Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e5e6d50f2f | ||
|
|
7e59dbf79b | ||
|
|
28633f3c62 | ||
|
|
cf8e62d2ac | ||
|
|
457186419f | ||
|
|
9dfa31bdbc | ||
|
|
8dc4ff48f8 | ||
|
|
58c02d415f | ||
|
|
987ac09896 | ||
|
|
7d90820e19 | ||
|
|
ee8eb928b3 | ||
|
|
8f61b1486e | ||
|
|
44a29c6ee4 | ||
|
|
84021a19dc | ||
|
|
df0b79a87d | ||
|
|
dc26cc93ba | ||
|
|
985dfd4705 | ||
|
|
9dd46198cb | ||
|
|
7d647e0ed7 | ||
|
|
e93a17de78 | ||
|
|
de598242ab | ||
|
|
3d480fb018 | ||
|
|
5b253ea1d5 | ||
|
|
a61e0a253d | ||
|
|
056fff415c | ||
|
|
7c2923dd04 | ||
|
|
3258300539 | ||
|
|
f07f309c51 | ||
|
|
a5335687ec | ||
|
|
69ed8fc722 | ||
|
|
ac1ffc46d3 | ||
|
|
0b5087b410 | ||
|
|
043ce779e6 | ||
|
|
e9ae2ec751 | ||
|
|
69195ced93 | ||
|
|
a3a36718d6 | ||
|
|
d2a67cb560 | ||
|
|
d804a3b2e0 | ||
|
|
14e02bce3c | ||
|
|
d2c56d565b | ||
|
|
d508814dfa | ||
|
|
ac049e5cc1 | ||
|
|
cc27cd1f43 | ||
|
|
515bac4b3c | ||
|
|
6a2fd9e8f3 | ||
|
|
40c65c87bd | ||
|
|
ac39d04170 | ||
|
|
174150c5e1 | ||
|
|
56dc934106 | ||
|
|
28db1d1079 | ||
|
|
966855469d | ||
|
|
9374b8ac64 | ||
|
|
34ea2ce438 | ||
|
|
9dedcf93a8 | ||
|
|
0cc7ef2f30 | ||
|
|
d2097f77c8 | ||
|
|
46cbd29956 | ||
|
|
4fcaba2f3e | ||
|
|
4427ecd569 | ||
|
|
6d92a28e2b | ||
|
|
18f7d847ac | ||
|
|
d3092a1806 | ||
|
|
69c8960ea9 | ||
|
|
fc21d87a9b | ||
|
|
e036e70acc | ||
|
|
92cfaf24b8 | ||
|
|
15e4e261c5 | ||
|
|
7336352cd3 | ||
|
|
9b92f3825d | ||
|
|
74c727b9e3 | ||
|
|
a1f372bc9d | ||
|
|
b23607d51d | ||
|
|
a51bf60d9a | ||
|
|
003e8c2deb | ||
|
|
118bcbe83c | ||
|
|
0d63bf7415 | ||
|
|
f9252fb26d | ||
|
|
e821080ca8 | ||
|
|
b3749560c8 | ||
|
|
c3803e4ba8 | ||
|
|
f2840c7074 | ||
|
|
ad081e2149 | ||
|
|
0e4b881f76 | ||
|
|
90f26ca4f4 | ||
|
|
c4413dabb5 | ||
|
|
71be3ae2e1 | ||
|
|
3cfac51811 | ||
|
|
76c6ebc700 | ||
|
|
74b6fe97e5 | ||
|
|
4a0626f00b | ||
|
|
ba19cee07d | ||
|
|
624959f099 | ||
|
|
0110b71dd3 | ||
|
|
00ca582f1a | ||
|
|
bf932477dd | ||
|
|
f2b7ef0056 | ||
|
|
54c4641a0e | ||
|
|
5924346823 | ||
|
|
456086599c | ||
|
|
80ee12ecc2 | ||
|
|
acc5084647 | ||
|
|
afbec8ed44 | ||
|
|
a49e507e15 | ||
|
|
a52a9724cb | ||
|
|
245405d294 | ||
|
|
f53df5e313 | ||
|
|
c16064d7e3 | ||
|
|
98296fcec5 | ||
|
|
d8c72c2ebc | ||
|
|
8631453940 | ||
|
|
a4909ec9e5 | ||
|
|
4755a91cb3 | ||
|
|
c8f259ef4a | ||
|
|
cd9403f27a | ||
|
|
5724f490b4 | ||
|
|
99772851a7 | ||
|
|
9b4ff9c5e9 | ||
|
|
521808a6eb | ||
|
|
8d22868777 | ||
|
|
014b87c7ce | ||
|
|
80afa31f5c | ||
|
|
8356121518 | ||
|
|
58e8081420 | ||
|
|
f78431242c | ||
|
|
a38f7ea26e | ||
|
|
ff2b902cbd | ||
|
|
0238bcb280 | ||
|
|
c3675aef7c | ||
|
|
65636953e7 | ||
|
|
7e3e833f84 | ||
|
|
a24272b25a | ||
|
|
2638d13d11 | ||
|
|
ce78a3bbdf | ||
|
|
737b121dfe | ||
|
|
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 | ||
|
|
1565749105 | ||
|
|
e53a8a01b7 | ||
|
|
3afbcfaae5 | ||
|
|
d0085ec052 | ||
|
|
c3b328f91d | ||
|
|
7942c47808 | ||
|
|
46d93e715a | ||
|
|
a9027a8610 | ||
|
|
5853dc63ff | ||
|
|
ca14cb5437 | ||
|
|
a978d27f3a | ||
|
|
5a5b9d13d1 | ||
|
|
b62a6edd37 | ||
|
|
4d97f02fe9 | ||
|
|
c8dd520d65 | ||
|
|
8b313fe088 | ||
|
|
049ef2960c | ||
|
|
a0d584375a | ||
|
|
51c2fa285a | ||
|
|
c862a157db | ||
|
|
d708be4627 | ||
|
|
3791addb43 | ||
|
|
a40cbdc316 | ||
|
|
7e2ba60073 | ||
|
|
e3e364db63 | ||
|
|
4a51e3d686 | ||
|
|
84de00e6ac | ||
|
|
08d02c6303 | ||
|
|
e008920f39 | ||
|
|
99c74b4a66 | ||
|
|
92c6234b4f | ||
|
|
0d8e52ee77 | ||
|
|
0d84e3b99e |
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: 暂时只提建议
|
||||
@@ -0,0 +1,40 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 120" width="100%" height="100%" style="background-color: transparent;">
|
||||
<defs>
|
||||
<style>
|
||||
@import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@800&display=swap');
|
||||
|
||||
.title-font {
|
||||
font-family: 'Plus Jakarta Sans', sans-serif;
|
||||
font-size: 48px;
|
||||
font-weight: 800;
|
||||
letter-spacing: -0.02em;
|
||||
text-anchor: middle;
|
||||
}
|
||||
|
||||
.star-fx {
|
||||
animation: floatAnimation 4s ease-in-out infinite;
|
||||
}
|
||||
.star-top { transform-origin: 265px 25px; fill: #cec1e6; }
|
||||
.star-bottom { transform-origin: 45px 95px; animation-delay: 0.5s; fill: #fad6e6; }
|
||||
|
||||
@keyframes floatAnimation {
|
||||
0% { transform: translateY(0px) rotate(0deg); opacity: 0.9; }
|
||||
50% { transform: translateY(-8px) rotate(10deg); opacity: 1; }
|
||||
100% { transform: translateY(0px) rotate(0deg); opacity: 0.9; }
|
||||
}
|
||||
</style>
|
||||
</defs>
|
||||
|
||||
<g transform="translate(160, 75)">
|
||||
<text class="title-font" dx="2" dy="2">
|
||||
<tspan fill="#f9d5e7">Snow</tspan><tspan fill="#a5c9ff">Luma</tspan>
|
||||
</text>
|
||||
|
||||
<text class="title-font" dx="0" dy="0">
|
||||
<tspan fill="#a5c9ff">Snow</tspan><tspan fill="#cec1e6">Luma</tspan>
|
||||
</text>
|
||||
</g>
|
||||
|
||||
<path class="star-fx star-top" d="M265,13 L267.8,21.1 L276,24 L267.8,26.9 L265,35 L262.2,26.9 L254,24 L262.2,21.1 Z"/>
|
||||
<path class="star-fx star-bottom" d="M45,84 L47.1,90.2 L53.5,92.2 L47.1,94.2 L45,100 L42.9,94.2 L36.5,92.2 L42.9,90.2 Z"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.5 KiB |
@@ -0,0 +1,43 @@
|
||||
# Run the full workspace test suite on every pull request.
|
||||
#
|
||||
# The repo previously had no PR test gate, so broken tests could land on `dev`
|
||||
# unnoticed — and did (protocol's oidb-service rejection path, plus an external
|
||||
# contributor PR). This gates every PR on the whole suite.
|
||||
#
|
||||
# `pnpm -r --no-bail --if-present test` runs each package's `test` script
|
||||
# (skipping packages without one); --no-bail means one failing package still
|
||||
# reports the rest, and the run as a whole still fails if any package fails.
|
||||
name: CI
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# Cancel an in-flight run when the PR gets new commits.
|
||||
concurrency:
|
||||
group: ci-${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10.28.0
|
||||
run_install: false
|
||||
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Run all package tests
|
||||
run: pnpm -r --no-bail --if-present test
|
||||
@@ -15,7 +15,7 @@ jobs:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Delete old artifacts
|
||||
uses: actions/github-script@v7
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
let page = 1;
|
||||
@@ -44,16 +44,16 @@ jobs:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10.28.0
|
||||
run_install: false
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: 'pnpm'
|
||||
@@ -87,16 +87,16 @@ jobs:
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10.28.0
|
||||
run_install: false
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: 'pnpm'
|
||||
@@ -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
|
||||
@@ -137,7 +133,7 @@ jobs:
|
||||
# Single upload step — glob picks up both variants (.zip on Windows,
|
||||
# .tar.gz on Linux) for this matrix row.
|
||||
- name: Upload artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: SnowLuma-dev-${{ github.sha }}-${{ matrix.name }}
|
||||
path: SnowLuma-dev-${{ matrix.name }}*
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
name: Re-dispatch Docker Release
|
||||
|
||||
# Manual-only re-dispatcher for SnowLuma.Docker.Framework's docker-image.yml.
|
||||
#
|
||||
# The normal flow is automatic: release.yml's `dispatch-docker` job fires
|
||||
# after a tag-triggered release is published. This workflow exists for
|
||||
# rebuilding an existing release's Docker image without re-tagging — for
|
||||
# example after fixing the Dockerfile, rotating a Docker Hub credential,
|
||||
# or backfilling an older tag.
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
snowluma_tag:
|
||||
description: 'SnowLuma release tag to rebuild (e.g. v0.5.0)'
|
||||
required: true
|
||||
docker_image_override:
|
||||
description: 'Override Docker image name (defaults to vars.DOCKER_IMAGE)'
|
||||
required: false
|
||||
default: ''
|
||||
platforms_override:
|
||||
description: 'Override platforms (defaults to vars.DOCKER_PLATFORMS or linux/amd64,linux/arm64)'
|
||||
required: false
|
||||
default: ''
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
dispatch:
|
||||
runs-on: ubuntu-latest
|
||||
environment: SnowLuma
|
||||
steps:
|
||||
- name: Dispatch Docker rebuild
|
||||
uses: actions/github-script@v8
|
||||
env:
|
||||
RELEASE_REPOSITORY: ${{ vars.DOCKER_RELEASE_REPOSITORY }}
|
||||
DOCKER_IMAGE: ${{ vars.DOCKER_IMAGE }}
|
||||
DOCKER_PLATFORMS: ${{ vars.DOCKER_PLATFORMS }}
|
||||
DOCKER_WORKFLOW: ${{ vars.DOCKER_WORKFLOW }}
|
||||
DOCKER_REF: ${{ vars.DOCKER_REF }}
|
||||
SNOWLUMA_TAG: ${{ inputs.snowluma_tag }}
|
||||
IMAGE_OVERRIDE: ${{ inputs.docker_image_override }}
|
||||
PLATFORMS_OVERRIDE: ${{ inputs.platforms_override }}
|
||||
with:
|
||||
github-token: ${{ secrets.SNOWLUMA_TOKEN }}
|
||||
script: |
|
||||
const target = process.env.RELEASE_REPOSITORY;
|
||||
if (!target || !target.includes('/')) {
|
||||
throw new Error('Set SnowLuma environment variable DOCKER_RELEASE_REPOSITORY to owner/repo.');
|
||||
}
|
||||
|
||||
const tag = process.env.SNOWLUMA_TAG;
|
||||
if (!tag) throw new Error('snowluma_tag input is required.');
|
||||
|
||||
const [owner, repo] = target.split('/');
|
||||
const sourceRepo = context.repo.owner + '/' + context.repo.repo;
|
||||
const image = process.env.IMAGE_OVERRIDE || process.env.DOCKER_IMAGE || 'motricseven7/snowluma';
|
||||
const platforms = process.env.PLATFORMS_OVERRIDE || process.env.DOCKER_PLATFORMS || 'linux/amd64,linux/arm64';
|
||||
const workflowId = process.env.DOCKER_WORKFLOW || 'docker-image.yml';
|
||||
const ref = process.env.DOCKER_REF || 'main';
|
||||
|
||||
await github.rest.actions.createWorkflowDispatch({
|
||||
owner,
|
||||
repo,
|
||||
workflow_id: workflowId,
|
||||
ref,
|
||||
inputs: {
|
||||
image,
|
||||
tag,
|
||||
push: 'true',
|
||||
platforms,
|
||||
snowluma_tag: tag,
|
||||
snowluma_repository: sourceRepo,
|
||||
},
|
||||
});
|
||||
|
||||
core.info(`Re-dispatched ${workflowId}@${ref} on ${target} for SnowLuma release ${sourceRepo}@${tag} (image=${image}, platforms=${platforms}).`);
|
||||
@@ -0,0 +1,109 @@
|
||||
name: Publish MCP to npm
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- 'packages/mcp/**'
|
||||
# The action catalog is generated from @snowluma/onebot's specs, so an
|
||||
# action change must republish the MCP snapshot.
|
||||
- 'packages/onebot/**'
|
||||
- 'package.json'
|
||||
- 'pnpm-lock.yaml'
|
||||
- 'pnpm-workspace.yaml'
|
||||
- 'tsconfig.base.json'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
|
||||
concurrency:
|
||||
group: mcp-npm-publish-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
name: Build, test, and publish MCP
|
||||
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 MCP
|
||||
run: pnpm --filter @snowluma/mcp typecheck
|
||||
|
||||
- name: Test MCP (regenerates + validates the action catalog)
|
||||
run: pnpm --filter @snowluma/mcp test
|
||||
|
||||
- name: Build MCP
|
||||
run: pnpm --filter @snowluma/mcp build
|
||||
|
||||
- name: Check npm package version
|
||||
id: npm
|
||||
working-directory: packages/mcp
|
||||
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 MCP to npm
|
||||
if: steps.npm.outputs.already_published != 'true'
|
||||
working-directory: packages/mcp
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: npm publish --access public --provenance
|
||||
|
||||
- name: Summary
|
||||
shell: bash
|
||||
run: |
|
||||
{
|
||||
echo "## MCP 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,245 @@
|
||||
name: Promote Dev to Main
|
||||
on:
|
||||
push:
|
||||
branches: [dev]
|
||||
tags: ['chore.*']
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
auto_merge:
|
||||
description: Enable auto-merge on the resulting PR
|
||||
type: choice
|
||||
options: ['true', 'false']
|
||||
default: 'true'
|
||||
merge_method:
|
||||
description: Merge strategy when auto-merging
|
||||
type: choice
|
||||
options: ['merge', 'squash', 'rebase']
|
||||
default: 'merge'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: promote-dev-to-main
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
decide:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
run: ${{ steps.check.outputs.run }}
|
||||
auto_merge: ${{ steps.check.outputs.auto_merge }}
|
||||
merge_method: ${{ steps.check.outputs.merge_method }}
|
||||
reason: ${{ steps.check.outputs.reason }}
|
||||
steps:
|
||||
- name: Decide whether to promote
|
||||
id: check
|
||||
env:
|
||||
EVENT_NAME: ${{ github.event_name }}
|
||||
REF: ${{ github.ref }}
|
||||
REF_TYPE: ${{ github.ref_type }}
|
||||
HEAD_COMMIT_MSG: ${{ github.event.head_commit.message }}
|
||||
INPUT_AUTO_MERGE: ${{ inputs.auto_merge }}
|
||||
INPUT_MERGE_METHOD: ${{ inputs.merge_method }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
run='false'
|
||||
auto_merge='true'
|
||||
merge_method='merge'
|
||||
reason=''
|
||||
|
||||
case "${EVENT_NAME}" in
|
||||
workflow_dispatch)
|
||||
run='true'
|
||||
auto_merge="${INPUT_AUTO_MERGE:-true}"
|
||||
merge_method="${INPUT_MERGE_METHOD:-merge}"
|
||||
reason='Manual workflow_dispatch'
|
||||
;;
|
||||
push)
|
||||
if [ "${REF_TYPE}" = 'tag' ]; then
|
||||
run='true'
|
||||
merge_method='merge'
|
||||
reason="Tag push: ${REF}"
|
||||
elif [ "${REF}" = 'refs/heads/dev' ]; then
|
||||
msg="${HEAD_COMMIT_MSG:-}"
|
||||
if printf '%s' "${msg}" | grep -qiE '^\[merge\]|^chore\(release\):'; then
|
||||
run='true'
|
||||
merge_method='merge'
|
||||
reason='Commit message prefix on dev ([merge] or chore(release):)'
|
||||
else
|
||||
reason='Commit on dev without [merge] / chore(release): prefix'
|
||||
fi
|
||||
else
|
||||
reason="Push event on unhandled ref: ${REF}"
|
||||
fi
|
||||
;;
|
||||
*)
|
||||
reason="Unhandled event: ${EVENT_NAME}"
|
||||
;;
|
||||
esac
|
||||
|
||||
{
|
||||
echo "run=${run}"
|
||||
echo "auto_merge=${auto_merge}"
|
||||
echo "merge_method=${merge_method}"
|
||||
echo "reason=${reason}"
|
||||
} >> "${GITHUB_OUTPUT}"
|
||||
|
||||
{
|
||||
echo "## Promote decision"
|
||||
echo
|
||||
echo "| Key | Value |"
|
||||
echo "| --- | --- |"
|
||||
echo "| Event | \`${EVENT_NAME}\` |"
|
||||
echo "| Ref | \`${REF}\` |"
|
||||
echo "| Run | \`${run}\` |"
|
||||
echo "| Auto-merge | \`${auto_merge}\` |"
|
||||
echo "| Merge method | \`${merge_method}\` |"
|
||||
echo "| Reason | ${reason} |"
|
||||
} >> "${GITHUB_STEP_SUMMARY}"
|
||||
|
||||
promote:
|
||||
needs: decide
|
||||
if: needs.decide.outputs.run == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Validate GitHub App credentials
|
||||
env:
|
||||
APP_ID: ${{ secrets.SNOWLUMA_BOT_APP_ID }}
|
||||
PRIVATE_KEY: ${{ secrets.SNOWLUMA_BOT_PRIVATE_KEY }}
|
||||
run: |
|
||||
if [ -z "${APP_ID}" ] || [ -z "${PRIVATE_KEY}" ]; then
|
||||
echo 'Missing SNOWLUMA_BOT_APP_ID and/or SNOWLUMA_BOT_PRIVATE_KEY secrets.' >&2
|
||||
echo 'Configure the same GitHub App used by the nnphook native PR flow.' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Mint GitHub App installation token
|
||||
id: app-token
|
||||
uses: actions/create-github-app-token@v2
|
||||
with:
|
||||
app-id: ${{ secrets.SNOWLUMA_BOT_APP_ID }}
|
||||
private-key: ${{ secrets.SNOWLUMA_BOT_PRIVATE_KEY }}
|
||||
owner: ${{ github.repository_owner }}
|
||||
repositories: ${{ github.event.repository.name }}
|
||||
|
||||
- name: Resolve bot identity
|
||||
id: bot
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.app-token.outputs.token }}
|
||||
APP_SLUG: ${{ steps.app-token.outputs.app-slug }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
bot_login="${APP_SLUG}[bot]"
|
||||
bot_id="$(gh api "/users/${bot_login}" --jq .id)"
|
||||
bot_email="${bot_id}+${bot_login}@users.noreply.github.com"
|
||||
{
|
||||
echo "login=${bot_login}"
|
||||
echo "id=${bot_id}"
|
||||
echo "email=${bot_email}"
|
||||
} >> "${GITHUB_OUTPUT}"
|
||||
echo "Resolved bot: ${bot_login} <${bot_email}>"
|
||||
|
||||
- name: Checkout main
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: main
|
||||
fetch-depth: 0
|
||||
token: ${{ steps.app-token.outputs.token }}
|
||||
|
||||
- name: Compare dev to main
|
||||
id: diff
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git fetch origin dev:dev
|
||||
ahead="$(git rev-list --count main..dev)"
|
||||
behind="$(git rev-list --count dev..main)"
|
||||
dev_sha="$(git rev-parse dev)"
|
||||
dev_short="$(git rev-parse --short dev)"
|
||||
{
|
||||
echo "ahead=${ahead}"
|
||||
echo "behind=${behind}"
|
||||
echo "dev_sha=${dev_sha}"
|
||||
echo "dev_short=${dev_short}"
|
||||
} >> "${GITHUB_OUTPUT}"
|
||||
if [ "${ahead}" = '0' ]; then
|
||||
echo "skip=true" >> "${GITHUB_OUTPUT}"
|
||||
echo "::notice::dev has no commits ahead of main; nothing to promote."
|
||||
else
|
||||
echo "skip=false" >> "${GITHUB_OUTPUT}"
|
||||
echo "dev is ${ahead} ahead, ${behind} behind main."
|
||||
fi
|
||||
|
||||
- name: Ensure automation label exists
|
||||
if: steps.diff.outputs.skip != 'true'
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.app-token.outputs.token }}
|
||||
run: |
|
||||
gh label create automation --color 0E8A16 --description 'Automated bot PRs' 2>/dev/null || true
|
||||
|
||||
- name: Create or update Pull Request
|
||||
id: pr
|
||||
if: steps.diff.outputs.skip != 'true'
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.app-token.outputs.token }}
|
||||
DEV_SHA: ${{ steps.diff.outputs.dev_sha }}
|
||||
DEV_SHORT: ${{ steps.diff.outputs.dev_short }}
|
||||
AHEAD: ${{ steps.diff.outputs.ahead }}
|
||||
BEHIND: ${{ steps.diff.outputs.behind }}
|
||||
REASON: ${{ needs.decide.outputs.reason }}
|
||||
REF: ${{ github.ref }}
|
||||
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
title="chore: promote dev → main (${DEV_SHORT})"
|
||||
|
||||
{
|
||||
echo "Automated promotion of \`dev\` into \`main\`."
|
||||
echo
|
||||
echo "| Key | Value |"
|
||||
echo "| --- | --- |"
|
||||
echo "| Source | \`dev\` @ \`${DEV_SHA}\` |"
|
||||
echo "| Trigger ref | \`${REF}\` |"
|
||||
echo "| Trigger reason | ${REASON} |"
|
||||
echo "| Workflow run | ${RUN_URL} |"
|
||||
echo "| Ahead / Behind | ${AHEAD} / ${BEHIND} |"
|
||||
echo
|
||||
echo "Created by SnowLuma Bot."
|
||||
} > pr-body.md
|
||||
|
||||
existing="$(gh pr list --base main --head dev --state open --json number --jq '.[0].number' 2>/dev/null || true)"
|
||||
if [ -n "${existing}" ]; then
|
||||
gh pr edit "${existing}" --title "${title}" --body-file pr-body.md
|
||||
pr_number="${existing}"
|
||||
echo "Updated existing PR #${pr_number}"
|
||||
else
|
||||
url="$(gh pr create --base main --head dev --title "${title}" --body-file pr-body.md --label automation)"
|
||||
pr_number="${url##*/}"
|
||||
echo "Opened new PR #${pr_number} (${url})"
|
||||
fi
|
||||
|
||||
echo "number=${pr_number}" >> "${GITHUB_OUTPUT}"
|
||||
{
|
||||
echo "## Promote PR"
|
||||
echo
|
||||
echo "- Number: #${pr_number}"
|
||||
echo "- Source: \`dev@${DEV_SHORT}\`"
|
||||
echo "- Ahead/Behind: ${AHEAD}/${BEHIND}"
|
||||
} >> "${GITHUB_STEP_SUMMARY}"
|
||||
|
||||
- name: Enable auto-merge
|
||||
if: steps.diff.outputs.skip != 'true' && needs.decide.outputs.auto_merge == 'true'
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.app-token.outputs.token }}
|
||||
PR_NUMBER: ${{ steps.pr.outputs.number }}
|
||||
MERGE_METHOD: ${{ needs.decide.outputs.merge_method }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
method_flag='--merge'
|
||||
case "${MERGE_METHOD}" in
|
||||
squash) method_flag='--squash' ;;
|
||||
rebase) method_flag='--rebase' ;;
|
||||
*) method_flag='--merge' ;;
|
||||
esac
|
||||
gh pr merge "${PR_NUMBER}" --auto ${method_flag}
|
||||
echo "::notice::Auto-merge enabled on PR #${PR_NUMBER} with strategy: ${MERGE_METHOD}"
|
||||
@@ -26,18 +26,18 @@ jobs:
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10.28.0
|
||||
run_install: false
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: 'pnpm'
|
||||
@@ -76,7 +76,7 @@ jobs:
|
||||
tar -czf "SnowLuma-${{ github.ref_name }}-${{ matrix.name }}.tar.gz" -C dist .
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: release-${{ matrix.name }}
|
||||
path: SnowLuma-${{ github.ref_name }}-${{ matrix.name }}*
|
||||
@@ -88,12 +88,12 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout (for git log)
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Download all artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
path: artifacts
|
||||
|
||||
@@ -157,3 +157,58 @@ jobs:
|
||||
overwrite_files: true
|
||||
draft: false
|
||||
prerelease: ${{ contains(github.ref_name, '-') }}
|
||||
|
||||
# Triggers the Docker image build on SnowLuma.Docker.Framework once the
|
||||
# GitHub Release (and its per-arch tarballs) is published, so the Docker
|
||||
# workflow can pull the matching `SnowLuma-<tag>-linux-<arch>-lite.tar.gz`
|
||||
# asset and bake it into the container.
|
||||
#
|
||||
# Chained as a job dependency rather than via `on: release: published`
|
||||
# because workflows triggered by GITHUB_TOKEN cannot fire downstream
|
||||
# workflow events (GitHub anti-loop safeguard). Doing it as `needs: release`
|
||||
# keeps the dispatch under our PAT.
|
||||
dispatch-docker:
|
||||
needs: release
|
||||
runs-on: ubuntu-latest
|
||||
environment: SnowLuma
|
||||
steps:
|
||||
- name: Trigger Docker.Framework workflow_dispatch
|
||||
uses: actions/github-script@v8
|
||||
env:
|
||||
RELEASE_REPOSITORY: ${{ vars.DOCKER_RELEASE_REPOSITORY }}
|
||||
DOCKER_IMAGE: ${{ vars.DOCKER_IMAGE }}
|
||||
DOCKER_PLATFORMS: ${{ vars.DOCKER_PLATFORMS }}
|
||||
DOCKER_WORKFLOW: ${{ vars.DOCKER_WORKFLOW }}
|
||||
DOCKER_REF: ${{ vars.DOCKER_REF }}
|
||||
with:
|
||||
github-token: ${{ secrets.SNOWLUMA_TOKEN }}
|
||||
script: |
|
||||
const target = process.env.RELEASE_REPOSITORY;
|
||||
if (!target || !target.includes('/')) {
|
||||
throw new Error('Set SnowLuma environment variable DOCKER_RELEASE_REPOSITORY to owner/repo.');
|
||||
}
|
||||
|
||||
const [owner, repo] = target.split('/');
|
||||
const tag = context.ref.replace('refs/tags/', '');
|
||||
const sourceRepo = context.repo.owner + '/' + context.repo.repo;
|
||||
const image = process.env.DOCKER_IMAGE || 'motricseven7/snowluma';
|
||||
const platforms = process.env.DOCKER_PLATFORMS || 'linux/amd64,linux/arm64';
|
||||
const workflowId = process.env.DOCKER_WORKFLOW || 'docker-image.yml';
|
||||
const ref = process.env.DOCKER_REF || 'main';
|
||||
|
||||
await github.rest.actions.createWorkflowDispatch({
|
||||
owner,
|
||||
repo,
|
||||
workflow_id: workflowId,
|
||||
ref,
|
||||
inputs: {
|
||||
image,
|
||||
tag,
|
||||
push: 'true',
|
||||
platforms,
|
||||
snowluma_tag: tag,
|
||||
snowluma_repository: sourceRepo,
|
||||
},
|
||||
});
|
||||
|
||||
core.info(`Dispatched ${workflowId}@${ref} on ${target} for SnowLuma release ${sourceRepo}@${tag} (image=${image}, platforms=${platforms}).`);
|
||||
@@ -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}"
|
||||
@@ -7,6 +7,11 @@ node_modules/
|
||||
dist/
|
||||
**/dist/
|
||||
.vscode/
|
||||
.idea/
|
||||
|
||||
/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/)。
|
||||
+287
@@ -0,0 +1,287 @@
|
||||
# 贡献指南
|
||||
|
||||
欢迎!如果你正在阅读这份文档,多半是因为你想给 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`。
|
||||
- **`native/auto-update-*`** — 由 `SnowLuma Bot` 自动创建的原生产物更新分支(来自 `SnowLumaNative`,不需要手动维护)。
|
||||
|
||||
### 把 `dev` 合并到 `main`
|
||||
|
||||
工作流 `.github/workflows/promote-dev-to-main.yml` 会以 `SnowLuma Bot` 身份开 / 更新一个 `dev → main` 的 PR,并可选地自动合并。无论用哪种触发方式,工作流都会调用 `gh pr merge --auto`:**只有 `main` 分支保护中所有 required status checks(typecheck + 各架构 build)都通过后,机器人才会真正合并**。失败的工作流会卡住合并。
|
||||
|
||||
#### 1. 提交信息前缀(推荐日常使用)
|
||||
|
||||
向 `dev` push 一个提交,提交信息**以**以下任一前缀**开头**即触发(不区分大小写):
|
||||
|
||||
- `[merge]` — 例如 `[merge] fix: hotfix for OneBot mention`
|
||||
- `chore(release):` — 例如 `chore(release): v1.7.0`,符合 conventional commits 的发版习惯
|
||||
|
||||
> 是**前缀**匹配,不是任意位置。`fix: something [merge]` 不会触发,必须把 `[merge]` 写在最前面。
|
||||
|
||||
#### 2. 推送 `chore.*` 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 构建。
|
||||
|
||||
#### 3. 手动触发
|
||||
|
||||
打开仓库 Actions 页面 → `Promote Dev to Main` → `Run workflow`。可选输入:
|
||||
|
||||
- `auto_merge`:是否启用 auto-merge(默认 `true`)。
|
||||
- `merge_method`:`merge` / `squash` / `rebase`(默认 `merge`)。
|
||||
|
||||
### 启用 `main` 分支保护(必做)
|
||||
|
||||
仓库管理员需要在 GitHub 上为 `main` 配置规则集(Repository Rules)或经典分支保护,至少满足:
|
||||
|
||||
1. **Settings → Rules → Rulesets**(推荐)或 **Settings → Branches → Branch protection rules**。
|
||||
2. 选择 `main` 作为目标分支。
|
||||
3. 勾选:
|
||||
- **Restrict deletions** — 禁止删除 `main`。
|
||||
- **Require a pull request before merging** — 所有合并必须走 PR。
|
||||
- **Block force pushes** — 禁止强推。
|
||||
- **Require status checks to pass before merging(必勾)** — 把以下来自 `dev-build.yml` 的 check 全部加为 required:
|
||||
- `typecheck`
|
||||
- `build (win-x64)`
|
||||
- `build (linux-x64)`
|
||||
- `build (linux-arm64)`
|
||||
- **Require branches to be up to date before merging** — 保证 PR 合并前已 rebase 过最新 `main`。
|
||||
4. 在 **Bypass list / Allow specified actors to bypass** 中加入 `SnowLuma Bot` GitHub App。这样 `gh pr merge --auto` 才能在所有 required check 通过后由机器人自动完成合并;否则 PR 会一直卡在 auto-merge 等待人工 review。
|
||||
5. **不要**把任何用户加入 push 白名单,确保「禁止向 `main` 直接提交」的约束生效。第一次设置完后,连仓库管理员也只能通过 PR 改 `main`。
|
||||
|
||||
效果:任何对 `dev` 的推送都会先在 `dev-build.yml` 上跑 typecheck + 三个架构的 build;只有全部成功,promote 工作流的 `--auto` 合并才会真正发生。失败时 PR 会保留在 open 状态,修复后再次推到 `dev` 即可重新触发检查。
|
||||
|
||||
### 必需的 Secrets
|
||||
|
||||
`promote-dev-to-main.yml` 复用 `SnowLumaNative/build-native.yml` 同一个 GitHub App。请确认 SnowLuma 仓库(或 organization)级别已经配置:
|
||||
|
||||
- `SNOWLUMA_BOT_APP_ID` — 数字类型的 App ID。
|
||||
- `SNOWLUMA_BOT_PRIVATE_KEY` — 该 App 的 PEM 私钥。
|
||||
|
||||
App 必须在本仓库已安装,且授予 **Contents: Read+Write**、**Pull requests: Read+Write**。
|
||||
|
||||
### 本地工作流速查(维护者)
|
||||
|
||||
```bash
|
||||
# 把 dev 合入 main(三选一)
|
||||
|
||||
# 方式 A:commit-msg 前缀
|
||||
git commit -m "chore(release): v1.7.0" # 或 "[merge] fix: hotfix"
|
||||
git push # → 触发 promote-dev-to-main
|
||||
|
||||
# 方式 B:chore.* 合并 tag(与发布 tag 解耦)
|
||||
git tag chore.merge-20240509 # 或 chore.promote-v1.7.0 等
|
||||
git push origin chore.merge-20240509 # → 触发 promote-dev-to-main
|
||||
|
||||
# 方式 C:在 Actions 页面手动 Run workflow
|
||||
|
||||
# 合并完成后,发布版本(在 main 上打 v* tag)
|
||||
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,31 +1,50 @@
|
||||
# ❄️ SnowLuma
|
||||
> Next Remote Protocol Framework.
|
||||
<h1 align="center">
|
||||
<img src=".github/logo.svg" width="100%" alt="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="NPM" src="https://img.shields.io/npm/v/%40snowluma%2Fsdk?style=flat-square&label=sdk&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>
|
||||
|
||||
## 测试要求
|
||||
1. 外部库能正常加载
|
||||
<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>
|
||||
|
||||
2. 外部库能正常卸载
|
||||
---
|
||||
|
||||
3. 卸载时Pipe以及副作用被清除
|
||||
SnowLuma 是一个基于 TypeScript 的协议转换框架,旨在为 QQ 客户端提供 [OneBot v11](https://github.com/botuniverse/onebot-11) 标准接口,支持 WebSocket/HTTP 适配、多账号并行及 WebUI 管理。
|
||||
|
||||
4. 当Snowluma重启时可恢复所有Pipe管道
|
||||
## 特性
|
||||
|
||||
- **OneBot v11 兼容**:支持文本、音视频、Markdown、JSON 等消息格式。
|
||||
- **高性能架构**:TypeScript 全栈,基于 pnpm monorepo 管理,核心逻辑分离。
|
||||
- **现代化管理**:内置 WebUI 面板,支持实时日志、密码热更、多账号管理。
|
||||
- **多适配器支持**:WebSocket (Server/Client)、HTTP (Server/Post)。
|
||||
- **数据持久化**:使用 SQLite 存储好友、群组等关系数据。
|
||||
|
||||
## 快速开始
|
||||
|
||||
1. 从 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 下载最新发布包并解压。
|
||||
2. 运行 `./launcher.bat` (Windows) 或 `./launcher.sh` (Linux)。
|
||||
3. 访问 `http://localhost:5099` (初始账号 `admin`,密码见控制台输出)。
|
||||
|
||||
## 鸣谢
|
||||
[LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) - Proto
|
||||
|
||||
[NapCatQQ](https://github.com/NapNeko/NapCatQQ) - Scaner/Packet
|
||||
参考了 [LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) 的协议定义与 [NapCatQQ](https://github.com/NapNeko/NapCatQQ) 的实现思路。
|
||||
|
||||
## 辅助编程
|
||||
---
|
||||
|
||||
推荐 Opus4.6 + Gemini3.1pro 对本项目辅助开发
|
||||
<p align="center">
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/graphs/contributors"><img src="https://contrib.rocks/image?repo=SnowLuma/SnowLuma" /></a>
|
||||
</p>
|
||||
|
||||
本项目大量使用Ai技术。
|
||||
|
||||
## 加入我们
|
||||
[SnowLuma-QQ](https://qm.qq.com/q/g3UMLpWALe)
|
||||
|
||||
[SnowLuma-TG](https://t.me/napcatqq)
|
||||
@@ -0,0 +1,9 @@
|
||||
# V2.0.0 前计划
|
||||
- [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,105 @@
|
||||
import js from '@eslint/js';
|
||||
import reactHooks from 'eslint-plugin-react-hooks';
|
||||
import reactRefresh from 'eslint-plugin-react-refresh';
|
||||
import { defineConfig, globalIgnores } from 'eslint/config';
|
||||
import globals from 'globals';
|
||||
import tseslint from 'typescript-eslint';
|
||||
|
||||
const tsconfigRootDir = decodeURIComponent(new URL('.', import.meta.url).pathname).replace(/^\/(.:\/)/, '$1');
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores([
|
||||
'**/dist/**',
|
||||
'**/node_modules/**',
|
||||
'**/coverage/**',
|
||||
'**/.turbo/**',
|
||||
'**/.vite/**',
|
||||
'**/*.tsbuildinfo',
|
||||
'**/test/fixtures/**',
|
||||
'packages/runtime/native/**',
|
||||
]),
|
||||
{
|
||||
files: ['**/*.{js,mjs,cjs,ts,tsx}'],
|
||||
extends: [js.configs.recommended],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2023,
|
||||
sourceType: 'module',
|
||||
globals: {
|
||||
...globals.es2023,
|
||||
...globals.node,
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
'indent': ['error', 2, { SwitchCase: 1 }],
|
||||
'no-unused-vars': 'off',
|
||||
'no-useless-assignment': 'off',
|
||||
'prefer-const': 'off',
|
||||
'preserve-caught-error': 'off',
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [tseslint.configs.recommended],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
tsconfigRootDir,
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
'indent': ['error', 2, { SwitchCase: 1 }],
|
||||
'prefer-const': 'off',
|
||||
'@typescript-eslint/no-explicit-any': 'error',
|
||||
'@typescript-eslint/no-empty-object-type': 'off',
|
||||
'@typescript-eslint/no-this-alias': 'off',
|
||||
'@typescript-eslint/no-unused-vars': [
|
||||
'warn',
|
||||
{
|
||||
argsIgnorePattern: '^_',
|
||||
varsIgnorePattern: '^_',
|
||||
caughtErrorsIgnorePattern: '^_',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['**/tests/**/*.{ts,tsx}', '**/*.test.{ts,tsx}'],
|
||||
rules: {
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['**/bench/**/*.{ts,tsx}', 'packages/proton/test/**/*.{ts,tsx}'],
|
||||
rules: {
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
},
|
||||
},
|
||||
{
|
||||
// OIDB service layer is namespace-per-cmd by design — the
|
||||
// structural-typing contract (namespace IS the OidbCallSpec) and
|
||||
// the file:cmd 1:1 mapping are the whole point. Disable the
|
||||
// module-syntax preference here only.
|
||||
files: [
|
||||
'packages/protocol/src/oidb-services/**/*.ts',
|
||||
'packages/protocol/tests/oidb-services/**/*.ts',
|
||||
],
|
||||
rules: {
|
||||
'@typescript-eslint/no-namespace': 'off',
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['packages/webui/src/**/*.{ts,tsx}', 'packages/ui/src/**/*.{ts,tsx}'],
|
||||
extends: [reactHooks.configs.flat.recommended, reactRefresh.configs.vite],
|
||||
languageOptions: {
|
||||
globals: globals.browser,
|
||||
parserOptions: {
|
||||
tsconfigRootDir,
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
'indent': ['error', 2, { SwitchCase: 1 }],
|
||||
'prefer-const': 'off',
|
||||
'react-refresh/only-export-components': 'off',
|
||||
'react-hooks/set-state-in-effect': 'off',
|
||||
},
|
||||
},
|
||||
]);
|
||||
+24
-7
@@ -1,35 +1,52 @@
|
||||
{
|
||||
"name": "snowluma-monorepo",
|
||||
"version": "0.1.0",
|
||||
"version": "1.9.11",
|
||||
"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:mcp": "pnpm --filter @snowluma/mcp build",
|
||||
"build:all": "pnpm --filter @snowluma/core build:all && pnpm --filter @snowluma/sdk build && pnpm --filter @snowluma/mcp 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",
|
||||
"@vitest/coverage-istanbul": "4.1.4",
|
||||
"@vitest/coverage-v8": "^4.1.4",
|
||||
"cross-env": "^10.1.0",
|
||||
"typescript": "catalog:"
|
||||
"eslint": "^10.2.0",
|
||||
"eslint-plugin-react-hooks": "^7.0.1",
|
||||
"eslint-plugin-react-refresh": "^0.5.2",
|
||||
"globals": "^17.5.0",
|
||||
"jiti": "^2.6.1",
|
||||
"typescript": "catalog:",
|
||||
"typescript-eslint": "^8.58.2"
|
||||
},
|
||||
"pnpm": {
|
||||
"peerDependencyRules": {
|
||||
"allowedVersions": {
|
||||
"eslint-plugin-react-hooks>eslint": "10"
|
||||
}
|
||||
}
|
||||
},
|
||||
"onlyBuiltDependencies": [
|
||||
"better-sqlite3"
|
||||
]
|
||||
},
|
||||
"packageManager": "pnpm@10.28.0",
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
{
|
||||
"name": "@snowluma/bridge",
|
||||
"version": "1.9.11",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma bridge — QQ NT desktop client lifecycle: hook injection (via native addon), per-PID HookSession orchestration, pipe-watcher for process discovery, and the BridgeManagerSink interface that lets the hook layer call back into a UIN-keyed session router without depending on @snowluma/core. Consumed by the top-level app entry (which constructs the BridgeManager from @snowluma/core and injects it as the sink) and by the WebUI server (read-only HookProcessInfo views).",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"default": "./src/index.ts"
|
||||
},
|
||||
"./hook-manager": {
|
||||
"types": "./src/hook-manager.ts",
|
||||
"default": "./src/hook-manager.ts"
|
||||
},
|
||||
"./hook-session": {
|
||||
"types": "./src/hook-session.ts",
|
||||
"default": "./src/hook-session.ts"
|
||||
},
|
||||
"./hook-packet-client": {
|
||||
"types": "./src/hook-packet-client.ts",
|
||||
"default": "./src/hook-packet-client.ts"
|
||||
},
|
||||
"./injector": {
|
||||
"types": "./src/injector.ts",
|
||||
"default": "./src/injector.ts"
|
||||
},
|
||||
"./pipe-watcher": {
|
||||
"types": "./src/pipe-watcher.ts",
|
||||
"default": "./src/pipe-watcher.ts"
|
||||
},
|
||||
"./qq-hook-client": {
|
||||
"types": "./src/qq-hook-client.ts",
|
||||
"default": "./src/qq-hook-client.ts"
|
||||
},
|
||||
"./qq-port-probe": {
|
||||
"types": "./src/qq-port-probe.ts",
|
||||
"default": "./src/qq-port-probe.ts"
|
||||
},
|
||||
"./types": {
|
||||
"types": "./src/types.ts",
|
||||
"default": "./src/types.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"test": "vitest run",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@snowluma/common": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.12.2",
|
||||
"typescript": "catalog:",
|
||||
"vite": "catalog:",
|
||||
"vitest": "^4.1.4"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import type { PacketSender } from '@snowluma/common/packet-sender';
|
||||
import type { PacketInfo, PacketSink } from '@snowluma/common/protocol-types';
|
||||
import fs from 'fs';
|
||||
import { HookSession, type HookSessionDeps } from './hook-session';
|
||||
import {
|
||||
injectHookProcess,
|
||||
listHookProcesses,
|
||||
unloadHookProcess,
|
||||
type HookProcessBaseInfo,
|
||||
} from './injector';
|
||||
import { PipeWatcher } from './pipe-watcher';
|
||||
import { QqHookClient } from './qq-hook-client';
|
||||
import { probeQqLoginInfo, type QqPortLoginInfo } from './qq-port-probe';
|
||||
import type { HookProcessInfo } from './types';
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Sink that the hook layer calls back into when it observes a new login,
|
||||
* a parsed packet, or a PID disconnect. The concrete implementation lives
|
||||
* in @snowluma/core (`BridgeManager`), which is wired in by the top-level
|
||||
* app entry. Declaring it here keeps @snowluma/bridge free of any
|
||||
* dependency on @snowluma/core — the hook package is self-contained.
|
||||
*/
|
||||
export interface BridgeManagerSink {
|
||||
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void;
|
||||
onPacket(pkt: PacketInfo): void;
|
||||
onPidDisconnected(pid: number): void;
|
||||
}
|
||||
|
||||
export type HookManagerDeps = {
|
||||
bridgeManager: BridgeManagerSink;
|
||||
/** Sink for parsed packets from any live HookSession. Defaults to
|
||||
* `bridgeManager.onPacket` — every packet flows straight into the
|
||||
* per-UIN bridge dispatcher with no intermediate event emitter. */
|
||||
onPacket?: PacketSink;
|
||||
/** Native injector entrypoints. Defaults to the real native addon. */
|
||||
injector?: HookSessionDeps['injector'];
|
||||
/** Hook pipe-client factory. Defaults to `new QqHookClient(pid)`. */
|
||||
makeClient?: HookSessionDeps['makeClient'];
|
||||
/** Pre-built watcher. Defaults to a PipeWatcher wrapping the native listings. */
|
||||
pipeWatcher?: PipeWatcher;
|
||||
/** Polling interval for the default watcher. Ignored if `pipeWatcher` is provided. */
|
||||
watcherIntervalMs?: number;
|
||||
/** Native process lister used by `listProcesses()`. Defaults to the native addon. */
|
||||
listProcesses?: () => HookProcessBaseInfo[];
|
||||
/** When true, every newly-discovered QQ process is auto-injected (fires
|
||||
* `loadProcess(pid)` from the watcher's 'process-discovered' handler).
|
||||
* Failed loads are logged and leave the session in the 'error' state. */
|
||||
autoLoadOnDiscovery?: boolean;
|
||||
log?: Logger;
|
||||
};
|
||||
|
||||
/**
|
||||
* HookManager — thin orchestrator over a per-PID HookSession map and a
|
||||
* singleton PipeWatcher.
|
||||
*
|
||||
* Responsibilities:
|
||||
* - Route user commands (load/unload/refresh) to the matching session.
|
||||
* - Route watcher diff events to the matching session.
|
||||
* - Forward session events ('login' / 'disconnected') to BridgeManager.
|
||||
* - Retry stuck-in-connecting sessions on every watcher tick (so a
|
||||
* failed connect eventually recovers without a manual refresh).
|
||||
*
|
||||
* The native injector, native pipe-client, and native process/pipe
|
||||
* listings are all swappable dependencies so tests can run without a
|
||||
* real QQ.exe or a native addon.
|
||||
*/
|
||||
export class HookManager {
|
||||
private readonly bridgeManager: BridgeManagerSink;
|
||||
private readonly onPacket: PacketSink;
|
||||
private readonly injector: HookSessionDeps['injector'];
|
||||
private readonly makeClient: HookSessionDeps['makeClient'];
|
||||
private readonly pipeWatcher: PipeWatcher;
|
||||
private readonly ownsPipeWatcher: boolean;
|
||||
private readonly listProcessesNative: () => HookProcessBaseInfo[];
|
||||
private readonly autoLoadOnDiscovery: boolean;
|
||||
private readonly log: Logger;
|
||||
private readonly sessions = new Map<number, HookSession>();
|
||||
private readonly startPromise: Promise<void>;
|
||||
|
||||
private disposed = false;
|
||||
|
||||
constructor(deps: HookManagerDeps) {
|
||||
this.bridgeManager = deps.bridgeManager;
|
||||
this.onPacket = deps.onPacket ?? ((pkt) => deps.bridgeManager.onPacket(pkt));
|
||||
this.log = deps.log ?? createLogger('Hook');
|
||||
|
||||
this.injector = deps.injector ?? {
|
||||
inject: injectHookProcess,
|
||||
unload: (pid, handle) => {
|
||||
if (!handle) return;
|
||||
unloadHookProcess(pid, handle);
|
||||
},
|
||||
};
|
||||
this.makeClient = deps.makeClient ?? ((pid: number) => new QqHookClient(pid));
|
||||
this.listProcessesNative = deps.listProcesses ?? listHookProcesses;
|
||||
this.autoLoadOnDiscovery = deps.autoLoadOnDiscovery ?? false;
|
||||
|
||||
if (deps.pipeWatcher) {
|
||||
this.pipeWatcher = deps.pipeWatcher;
|
||||
this.ownsPipeWatcher = false;
|
||||
} else {
|
||||
this.pipeWatcher = new PipeWatcher({
|
||||
listProcesses: this.listProcessesNative,
|
||||
listLivePipes: () => QqHookClient.listLivePipes(),
|
||||
intervalMs: deps.watcherIntervalMs,
|
||||
log: this.log,
|
||||
});
|
||||
this.ownsPipeWatcher = true;
|
||||
}
|
||||
|
||||
this.bindWatcher();
|
||||
this.startPromise = this.pipeWatcher.start();
|
||||
}
|
||||
|
||||
// ─────────────── public API (unchanged from prior HookManager) ───────────────
|
||||
|
||||
async listProcesses(): Promise<HookProcessInfo[]> {
|
||||
await this.startPromise;
|
||||
let processes: HookProcessBaseInfo[];
|
||||
try {
|
||||
processes = this.listProcessesNative();
|
||||
} catch (error) {
|
||||
this.log.warn('listProcesses failed: %s', errMsg(error));
|
||||
processes = [];
|
||||
}
|
||||
const result: HookProcessInfo[] = [];
|
||||
for (const proc of processes) {
|
||||
const session = this.ensureSession(proc.pid);
|
||||
session.attachProcessInfo(proc);
|
||||
result.push(session.toInfo());
|
||||
}
|
||||
return result.sort((a, b) => a.pid - b.pid);
|
||||
}
|
||||
|
||||
async loadProcess(pid: number): Promise<HookProcessInfo> {
|
||||
this.assertValidPid(pid);
|
||||
await this.startPromise;
|
||||
const session = this.ensureSession(pid);
|
||||
const info = await session.load();
|
||||
// Pull the next tick forward so a freshly-injected pipe gets noticed
|
||||
// within the next event-loop turn instead of after the full interval.
|
||||
this.pipeWatcher.wake();
|
||||
return info;
|
||||
}
|
||||
|
||||
async unloadProcess(pid: number): Promise<HookProcessInfo> {
|
||||
this.assertValidPid(pid);
|
||||
await this.startPromise;
|
||||
const session = this.ensureSession(pid);
|
||||
return session.unload();
|
||||
}
|
||||
|
||||
async refreshProcess(pid: number): Promise<HookProcessInfo> {
|
||||
this.assertValidPid(pid);
|
||||
await this.startPromise;
|
||||
const session = this.ensureSession(pid);
|
||||
return session.refresh();
|
||||
}
|
||||
|
||||
async probeProcessLoginInfo(pid: number): Promise<QqPortLoginInfo | null> {
|
||||
this.assertValidPid(pid);
|
||||
return probeQqLoginInfo(pid);
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
if (this.disposed) return;
|
||||
this.disposed = true;
|
||||
for (const session of this.sessions.values()) {
|
||||
session.dispose();
|
||||
}
|
||||
this.sessions.clear();
|
||||
if (this.ownsPipeWatcher) {
|
||||
this.pipeWatcher.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────── wiring ───────────────
|
||||
|
||||
private bindWatcher(): void {
|
||||
this.pipeWatcher.on('process-discovered', (info: HookProcessBaseInfo) => {
|
||||
if (this.disposed) return;
|
||||
const session = this.ensureSession(info.pid);
|
||||
session.attachProcessInfo(info);
|
||||
// Headless/Docker deployments enable autoLoadOnDiscovery so QQ gets
|
||||
// injected without a human clicking "Load" in WebUI. Fire-and-forget:
|
||||
// failures are already captured inside loadInternal and surfaced via
|
||||
// the session's status field.
|
||||
if (this.autoLoadOnDiscovery && shouldAutoLoadPid(info.pid, this.log)) {
|
||||
void session.load().catch((err) => {
|
||||
this.log.warn('auto-load failed: PID=%d err=%s', info.pid, errMsg(err));
|
||||
});
|
||||
}
|
||||
});
|
||||
this.pipeWatcher.on('process-gone', (pid: number) => {
|
||||
if (this.disposed) return;
|
||||
const session = this.sessions.get(pid);
|
||||
if (session) session.notifyProcessGone();
|
||||
});
|
||||
this.pipeWatcher.on('pipe-up', (pid: number) => {
|
||||
if (this.disposed) return;
|
||||
const session = this.sessions.get(pid);
|
||||
if (session) session.onPipeUp();
|
||||
});
|
||||
this.pipeWatcher.on('pipe-down', (pid: number) => {
|
||||
if (this.disposed) return;
|
||||
const session = this.sessions.get(pid);
|
||||
if (session) session.onPipeDown();
|
||||
});
|
||||
// After every tick, retry sessions that are stuck in 'connecting' OR
|
||||
// 'disconnected' while the pipe is up. Mirrors the original
|
||||
// tickWatcher's per-tick reconcileConnect pass; onPipeUp is idempotent
|
||||
// so calling it for an already-connected session is harmless.
|
||||
//
|
||||
// The 'disconnected' branch matters on Windows: when the QQ-NT side of
|
||||
// the named pipe stays alive but the SnowLuma-side socket dies (read
|
||||
// EPIPE / idle-timeout / similar transient I/O fault), the watcher
|
||||
// sees the pipe as still-live (the OS-level pipe is still listed by
|
||||
// `listLivePipes`) so it never fires another `pipe-up`. Without
|
||||
// retrying 'disconnected' sessions here the session is stranded
|
||||
// forever — a real-world symptom users reported as "Windows running
|
||||
// for a while then stops" with logs `pipe error: read EPIPE` →
|
||||
// `session closed: UIN=…`.
|
||||
this.pipeWatcher.on('tick', () => {
|
||||
if (this.disposed) return;
|
||||
for (const session of this.sessions.values()) {
|
||||
if ((session.status === 'connecting' || session.status === 'disconnected')
|
||||
&& this.pipeWatcher.isPipeLive(session.pid)) {
|
||||
session.onPipeUp();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private ensureSession(pid: number): HookSession {
|
||||
let session = this.sessions.get(pid);
|
||||
if (session) return session;
|
||||
|
||||
session = new HookSession(pid, {
|
||||
injector: this.injector,
|
||||
makeClient: this.makeClient,
|
||||
pipeWatcher: this.pipeWatcher,
|
||||
onPacket: this.onPacket,
|
||||
log: this.log,
|
||||
});
|
||||
session.attachProcessInfo({ name: defaultProcessName() });
|
||||
|
||||
session.on('login', (uin: string, sender) => {
|
||||
this.bridgeManager.onHookLogin(pid, uin, sender);
|
||||
});
|
||||
session.on('disconnected', (wasLoggedIn: boolean) => {
|
||||
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid);
|
||||
});
|
||||
session.on('disposed', () => {
|
||||
this.sessions.delete(pid);
|
||||
});
|
||||
|
||||
this.sessions.set(pid, session);
|
||||
return session;
|
||||
}
|
||||
|
||||
private assertValidPid(pid: number): void {
|
||||
if (!Number.isInteger(pid) || pid <= 0) throw new Error('invalid pid');
|
||||
}
|
||||
}
|
||||
|
||||
function defaultProcessName(): string {
|
||||
return process.platform === 'win32' ? 'QQ.exe' : 'qq';
|
||||
}
|
||||
|
||||
function errMsg(value: unknown): string {
|
||||
return value instanceof Error ? value.message : String(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter for auto-load only. Returns false for Linux Electron child
|
||||
* processes (zygote/renderer/gpu/utility), which the native enumerator
|
||||
* mis-classifies as "main QQ" because their cmdline contains "qq" and
|
||||
* they transiently inherit wrapper.node via fork copy-on-write.
|
||||
*
|
||||
* Injecting into a zygote spawns the hook's resolver thread inside it;
|
||||
* every renderer Electron later forks then inherits that thread + the
|
||||
* partially-init'd hook state, which breaks QQ's IPC and login UI.
|
||||
*
|
||||
* Manual loadProcess() bypasses this gate — the operator is responsible
|
||||
* for picking the right PID from WebUI.
|
||||
*/
|
||||
export function shouldAutoLoadPid(pid: number, log: Logger): boolean {
|
||||
if (process.platform !== 'linux') return true;
|
||||
// Escape hatch: operators who explicitly want auto-load on every
|
||||
// enumerated PID can set this to opt out of the filter.
|
||||
if (process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL === '1') return true;
|
||||
|
||||
let cmdline: string;
|
||||
try {
|
||||
cmdline = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8');
|
||||
} catch {
|
||||
// Can't read cmdline (process gone, permission, etc.) — let the
|
||||
// existing load() path handle it; if the process is dead the load
|
||||
// will fail with a clear error.
|
||||
return true;
|
||||
}
|
||||
if (cmdline.includes('--type=')) {
|
||||
const type = (/--type=([^\0\s]+)/.exec(cmdline)?.[1]) ?? 'unknown';
|
||||
log.info('auto-load skip: PID=%d is an Electron child process (--type=%s)', pid, type);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
export type { HookProcessBaseInfo } from './injector';
|
||||
export type { QqPortLoginInfo } from './qq-port-probe';
|
||||
export type { HookProcessInfo, HookProcessStatus } from './types';
|
||||
+2
-2
@@ -1,8 +1,8 @@
|
||||
import type { PacketSender, SendPacketResult } from '../protocol/packet-sender';
|
||||
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import { QqHookClient, type QqHookSendReply } from './qq-hook-client';
|
||||
|
||||
export class HookPacketClient implements PacketSender {
|
||||
constructor(private readonly client: QqHookClient) {}
|
||||
constructor(private readonly client: QqHookClient) { }
|
||||
|
||||
async sendPacket(serviceCmd: string, body: Buffer, timeoutMs = 15000): Promise<SendPacketResult> {
|
||||
if (!this.client.isLoggedIn) {
|
||||
@@ -0,0 +1,439 @@
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import type { PacketSink } from '@snowluma/common/protocol-types';
|
||||
import { EventEmitter } from 'events';
|
||||
import { HookPacketClient } from './hook-packet-client';
|
||||
import type { HookInjectResult } from './injector';
|
||||
import type { QqHookClient, QqHookLoginState, QqHookPacket } from './qq-hook-client';
|
||||
import type { HookProcessInfo, HookProcessStatus } from './types';
|
||||
|
||||
export type HookSessionDeps = {
|
||||
injector: {
|
||||
inject: (pid: number) => HookInjectResult;
|
||||
unload: (pid: number, handle: HookInjectResult['handle']) => void;
|
||||
};
|
||||
makeClient: (pid: number) => QqHookClient;
|
||||
/** Sync fast-path check used by load() to skip re-injection when a
|
||||
* prior SnowLuma run left a working pipe behind. `tickNow` forces a
|
||||
* fresh poll — used after unload to dodge the up-to-1500ms cache
|
||||
* staleness that would otherwise false-flag a successful unload. */
|
||||
pipeWatcher: {
|
||||
isPipeLive: (pid: number) => boolean;
|
||||
tickNow?: () => Promise<void>;
|
||||
};
|
||||
/** Sink for parsed packets. Called with the BridgeManager-shaped
|
||||
* PacketInfo for every packet received while logged in. If omitted,
|
||||
* packets are dropped (useful in unit tests that don't care). */
|
||||
onPacket?: PacketSink;
|
||||
log?: Logger;
|
||||
};
|
||||
|
||||
/**
|
||||
* HookSession — owns the lifecycle of one QQ.exe process: injection,
|
||||
* pipe client, login state, and the public status field.
|
||||
*
|
||||
* Concurrency: every state-mutating method goes through a per-session
|
||||
* promise chain so user clicks (load/unload/refresh) and watcher-driven
|
||||
* events (onPipeUp/onPipeDown) never interleave.
|
||||
*
|
||||
* Communication: emits high-level events instead of calling BridgeManager
|
||||
* directly, so HookManager forwards them and tests can attach spies.
|
||||
*
|
||||
* Emitted events:
|
||||
* 'login' (uin, packetSender) — real-UIN login detected
|
||||
* 'disconnected' (wasLoggedIn) — connection dropped or torn down
|
||||
* 'status-changed' (status, error) — status field mutated
|
||||
* 'disposed' () — session stopped tracking this PID
|
||||
*/
|
||||
export class HookSession extends EventEmitter {
|
||||
readonly pid: number;
|
||||
|
||||
private readonly injector: HookSessionDeps['injector'];
|
||||
private readonly makeClient: HookSessionDeps['makeClient'];
|
||||
private readonly pipeWatcher: HookSessionDeps['pipeWatcher'];
|
||||
private readonly onPacket: PacketSink | null;
|
||||
private readonly log: Logger;
|
||||
|
||||
private _status: HookProcessStatus = 'available';
|
||||
private _error = '';
|
||||
private _uin = '0';
|
||||
private _method = '';
|
||||
private _name = '';
|
||||
private _path = '';
|
||||
|
||||
private injected = false;
|
||||
private connected = false;
|
||||
private loggedIn = false;
|
||||
private injectResult: HookInjectResult | null = null;
|
||||
private client: QqHookClient | null = null;
|
||||
private sender: HookPacketClient | null = null;
|
||||
private bound = false;
|
||||
private opChain: Promise<unknown> = Promise.resolve();
|
||||
private disposed = false;
|
||||
|
||||
constructor(pid: number, deps: HookSessionDeps) {
|
||||
super();
|
||||
this.pid = pid;
|
||||
this.injector = deps.injector;
|
||||
this.makeClient = deps.makeClient;
|
||||
this.pipeWatcher = deps.pipeWatcher;
|
||||
this.onPacket = deps.onPacket ?? null;
|
||||
this.log = deps.log ?? createLogger('HookSession');
|
||||
}
|
||||
|
||||
// ─────────────── readonly public surface ───────────────
|
||||
|
||||
get status(): HookProcessStatus { return this._status; }
|
||||
get error(): string { return this._error; }
|
||||
get uin(): string { return this._uin; }
|
||||
get method(): string { return this._method; }
|
||||
get isDisposed(): boolean { return this.disposed; }
|
||||
|
||||
attachProcessInfo(info: { name?: string; path?: string }): void {
|
||||
if (info.name) this._name = info.name;
|
||||
if (info.path) this._path = info.path;
|
||||
}
|
||||
|
||||
toInfo(): HookProcessInfo {
|
||||
return {
|
||||
pid: this.pid,
|
||||
name: this._name,
|
||||
path: this._path,
|
||||
injected: this.injected,
|
||||
connected: this.connected,
|
||||
loggedIn: this.loggedIn,
|
||||
uin: this._uin,
|
||||
status: this._status,
|
||||
error: this._error,
|
||||
method: this._method,
|
||||
};
|
||||
}
|
||||
|
||||
// ─────────────── user-facing commands ───────────────
|
||||
|
||||
load(): Promise<HookProcessInfo> {
|
||||
return this.serialize(() => this.loadInternal());
|
||||
}
|
||||
|
||||
unload(): Promise<HookProcessInfo> {
|
||||
return this.serialize(() => this.unloadInternal());
|
||||
}
|
||||
|
||||
refresh(): Promise<HookProcessInfo> {
|
||||
return this.serialize(() => this.refreshInternal());
|
||||
}
|
||||
|
||||
// ─────────────── watcher-driven events (called by manager) ───────────────
|
||||
|
||||
/** Pipe came up (or stayed up across a SnowLuma restart). Drives connect
|
||||
* attempts and adopts pre-existing hooks. Idempotent; safe to call on
|
||||
* every watcher tick where the pipe is live. */
|
||||
onPipeUp(): void {
|
||||
if (this.disposed) return;
|
||||
void this.serialize(async () => {
|
||||
if (this.disposed) return;
|
||||
// Adopt a DLL that survived a SnowLuma restart.
|
||||
if (!this.injected) {
|
||||
this.injected = true;
|
||||
if (!this._method) this._method = 'reconnect';
|
||||
}
|
||||
if (this.client?.isClosed) this.tearDownClient();
|
||||
if (!this.connected) {
|
||||
await this.attemptConnect();
|
||||
} else {
|
||||
this.setStatus(this.loggedIn ? 'online' : 'loaded', '');
|
||||
}
|
||||
}).catch(err => this.log.warn('onPipeUp failed: PID=%d err=%s', this.pid, errMsg(err)));
|
||||
}
|
||||
|
||||
onPipeDown(): void {
|
||||
if (this.disposed) return;
|
||||
void this.serialize(async () => {
|
||||
if (this.disposed) return;
|
||||
if (!this.connected) {
|
||||
// Nothing to tear down; just keep status visible.
|
||||
if (this.injected) this.setStatus('connecting', this._error);
|
||||
return;
|
||||
}
|
||||
const wasLoggedIn = this.loggedIn;
|
||||
this.tearDownClient();
|
||||
this.setStatus(
|
||||
this.injected ? (wasLoggedIn ? 'disconnected' : 'connecting') : 'available',
|
||||
'',
|
||||
);
|
||||
if (wasLoggedIn) this.emit('disconnected', true);
|
||||
}).catch(err => this.log.warn('onPipeDown failed: PID=%d err=%s', this.pid, errMsg(err)));
|
||||
}
|
||||
|
||||
/** Called by the manager when the watcher reports the QQ.exe process is
|
||||
* gone. Cleans up and signals the manager to remove this session. */
|
||||
notifyProcessGone(): void {
|
||||
if (this.disposed) return;
|
||||
void this.serialize(async () => {
|
||||
if (this.disposed) return;
|
||||
const wasLoggedIn = this.loggedIn;
|
||||
this.tearDownClient();
|
||||
this.injected = false;
|
||||
this.injectResult = null;
|
||||
this._method = '';
|
||||
this.setStatus('available', '');
|
||||
if (wasLoggedIn) this.emit('disconnected', true);
|
||||
this.disposed = true;
|
||||
this.emit('disposed');
|
||||
this.removeAllListeners();
|
||||
}).catch(err => this.log.warn('notifyProcessGone failed: PID=%d err=%s', this.pid, errMsg(err)));
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
if (this.disposed) return;
|
||||
this.disposed = true;
|
||||
this.tearDownClient();
|
||||
this.removeAllListeners();
|
||||
}
|
||||
|
||||
// ─────────────── per-session serialization ───────────────
|
||||
|
||||
private serialize<T>(op: () => Promise<T>): Promise<T> {
|
||||
const previous = this.opChain;
|
||||
let release!: () => void;
|
||||
const completion = new Promise<void>(resolve => { release = resolve; });
|
||||
this.opChain = previous.then(() => completion);
|
||||
return (async () => {
|
||||
try {
|
||||
await previous.catch(() => undefined);
|
||||
return await op();
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
// ─────────────── internal transitions ───────────────
|
||||
|
||||
private async loadInternal(): Promise<HookProcessInfo> {
|
||||
this._error = '';
|
||||
this.setStatus('loading', '');
|
||||
try {
|
||||
if (!this.injected) {
|
||||
// Fast path: a previous SnowLuma run may have left the hook DLL
|
||||
// resident in QQ.exe. If the watcher already sees a live pipe,
|
||||
// skip re-injection and let onPipeUp drive the reconnect.
|
||||
if (this.pipeWatcher.isPipeLive(this.pid)) {
|
||||
this.injected = true;
|
||||
this._method = this._method || 'reconnect';
|
||||
this.log.info('PID=%d already has SnowLuma pipe; will reconnect', this.pid);
|
||||
} else {
|
||||
this.injectResult = this.injector.inject(this.pid);
|
||||
this.injected = true;
|
||||
this._method = this.injectResult.method;
|
||||
}
|
||||
}
|
||||
this.setStatus(
|
||||
this.connected ? (this.loggedIn ? 'online' : 'loaded') : 'connecting',
|
||||
'',
|
||||
);
|
||||
} catch (error) {
|
||||
this._error = errMsg(error);
|
||||
this.setStatus('error', this._error);
|
||||
this.log.error('load failed: PID=%d err=%s', this.pid, this._error);
|
||||
}
|
||||
return this.toInfo();
|
||||
}
|
||||
|
||||
private async unloadInternal(): Promise<HookProcessInfo> {
|
||||
this._error = '';
|
||||
try {
|
||||
const wasLoggedIn = this.loggedIn;
|
||||
this.tearDownClient();
|
||||
if (wasLoggedIn) this.emit('disconnected', true);
|
||||
|
||||
const handle = this.injectResult?.handle;
|
||||
if (this.injected && handle) {
|
||||
this.injector.unload(this.pid, handle);
|
||||
this.log.info('SnowLuma unloaded from PID=%d', this.pid);
|
||||
}
|
||||
|
||||
this.injected = false;
|
||||
this.injectResult = null;
|
||||
this._method = '';
|
||||
this._uin = '0';
|
||||
|
||||
// Verify the unload took: if the pipe is still up the DLL is still
|
||||
// resident. The cached snapshot is up to 1500ms stale and we just
|
||||
// changed the world, so force a fresh poll first — otherwise even
|
||||
// a successful unload reads as "pipe still live" until the next
|
||||
// background tick runs and we'd report a spurious failure.
|
||||
await this.pipeWatcher.tickNow?.();
|
||||
if (this.pipeWatcher.isPipeLive(this.pid)) {
|
||||
this._error = 'DLL卸载失败:命名管道仍然存在,watcher将自动重连';
|
||||
this.setStatus('connecting', this._error);
|
||||
this.log.warn('unload verification failed: PID=%d pipe still up', this.pid);
|
||||
} else {
|
||||
this.setStatus('available', '');
|
||||
}
|
||||
} catch (error) {
|
||||
this._error = errMsg(error);
|
||||
this.setStatus('error', this._error);
|
||||
this.log.error('unload failed: PID=%d err=%s', this.pid, this._error);
|
||||
}
|
||||
return this.toInfo();
|
||||
}
|
||||
|
||||
private async refreshInternal(): Promise<HookProcessInfo> {
|
||||
this._error = '';
|
||||
try {
|
||||
const pipeUp = this.pipeWatcher.isPipeLive(this.pid);
|
||||
if (pipeUp) {
|
||||
// Adopt an unknown DLL the same way onPipeUp would.
|
||||
if (!this.injected) {
|
||||
this.injected = true;
|
||||
this._method = this._method || 'reconnect';
|
||||
}
|
||||
if (this.client?.isClosed) this.tearDownClient();
|
||||
if (!this.connected) {
|
||||
await this.attemptConnect();
|
||||
} else {
|
||||
this.setStatus(this.loggedIn ? 'online' : 'loaded', '');
|
||||
}
|
||||
} else {
|
||||
const wasLoggedIn = this.loggedIn;
|
||||
this.tearDownClient();
|
||||
this.setStatus(this.injected ? 'disconnected' : 'available', '');
|
||||
if (wasLoggedIn) this.emit('disconnected', true);
|
||||
}
|
||||
} catch (error) {
|
||||
this._error = errMsg(error);
|
||||
this.setStatus(this.injected ? 'disconnected' : 'error', this._error);
|
||||
this.log.warn('refresh failed: PID=%d err=%s', this.pid, this._error);
|
||||
}
|
||||
return this.toInfo();
|
||||
}
|
||||
|
||||
// ─────────────── client plumbing ───────────────
|
||||
|
||||
private async attemptConnect(): Promise<void> {
|
||||
if (this.connected) return;
|
||||
if (this.client?.isClosed) this.tearDownClient();
|
||||
if (!this.client) {
|
||||
this.client = this.makeClient(this.pid);
|
||||
this.sender = new HookPacketClient(this.client);
|
||||
this.bound = false;
|
||||
}
|
||||
if (!this.bound) {
|
||||
this.bindClient(this.client);
|
||||
this.bound = true;
|
||||
}
|
||||
|
||||
const client = this.client;
|
||||
try {
|
||||
await client.connectAll({ recv: true });
|
||||
this.connected = true;
|
||||
this.setStatus(client.isLoggedIn ? 'online' : 'loaded', '');
|
||||
const loginState = client.getLoginState();
|
||||
if (loginState.loggedIn) this.handleLoginState(loginState);
|
||||
this.log.info('pipe connected: PID=%d', this.pid);
|
||||
} catch (error) {
|
||||
this._error = errMsg(error);
|
||||
// Drop the client so the next attempt builds a fresh socket pair.
|
||||
this.tearDownClient();
|
||||
this.setStatus(this.injected ? 'connecting' : 'available', this._error);
|
||||
}
|
||||
}
|
||||
|
||||
private bindClient(client: QqHookClient): void {
|
||||
client.on('packet', packet => this.handlePacket(packet));
|
||||
client.on('loginState', state => this.handleLoginState(state));
|
||||
client.on('error', error => {
|
||||
const msg = errMsg(error);
|
||||
this._error = msg;
|
||||
this.log.warn('pipe error: PID=%d err=%s', this.pid, msg);
|
||||
});
|
||||
client.on('close', () => {
|
||||
if (this.disposed) return;
|
||||
// Only the currently-registered client should drive a reconcile;
|
||||
// listeners may fire for an already-replaced client.
|
||||
if (this.client !== client) return;
|
||||
void this.serialize(async () => {
|
||||
if (this.disposed) return;
|
||||
if (this.client !== client) return;
|
||||
const wasLoggedIn = this.loggedIn;
|
||||
this.tearDownClient();
|
||||
if (!this.injected) {
|
||||
this.setStatus('available', '');
|
||||
} else if (wasLoggedIn) {
|
||||
this.setStatus('disconnected', '');
|
||||
} else {
|
||||
this.setStatus('connecting', '');
|
||||
}
|
||||
if (wasLoggedIn) this.emit('disconnected', true);
|
||||
}).catch(err => this.log.warn('close reconcile failed: PID=%d err=%s', this.pid, errMsg(err)));
|
||||
});
|
||||
}
|
||||
|
||||
private tearDownClient(): void {
|
||||
const client = this.client;
|
||||
if (client) {
|
||||
client.removeAllListeners();
|
||||
try { client.close(); } catch { /* ignore */ }
|
||||
}
|
||||
this.client = null;
|
||||
this.sender = null;
|
||||
this.bound = false;
|
||||
this.connected = false;
|
||||
this.loggedIn = false;
|
||||
}
|
||||
|
||||
private handleLoginState(state: QqHookLoginState): void {
|
||||
const wasLoggedIn = this.loggedIn;
|
||||
const previousUin = this._uin;
|
||||
this._uin = state.uin || state.uinNumber.toString();
|
||||
this.loggedIn = state.loggedIn && isRealUin(this._uin);
|
||||
|
||||
if (this.loggedIn) {
|
||||
this.setStatus('online', '');
|
||||
} else if (this.connected) {
|
||||
this.setStatus('loaded', this._error);
|
||||
}
|
||||
|
||||
if (!this.loggedIn || !this.sender) return;
|
||||
if (wasLoggedIn && previousUin === this._uin) return;
|
||||
|
||||
this.emit('login', this._uin, this.sender);
|
||||
this.log.success('login detected: PID=%d UIN=%s', this.pid, this._uin);
|
||||
}
|
||||
|
||||
private handlePacket(packet: QqHookPacket): void {
|
||||
if (!this.loggedIn) return;
|
||||
const uin = packet.uin || this._uin;
|
||||
if (!isRealUin(uin)) return;
|
||||
if (!this.onPacket) return;
|
||||
// Re-shape the hook-client wire packet into BridgeManager's PacketInfo
|
||||
// shape. Used to live in the deleted NtqqHandler.onHookPacket; field
|
||||
// renaming was that module's entire purpose, so it lives at the source
|
||||
// now (no need for a single-listener event-emitter in between).
|
||||
this.onPacket({
|
||||
pid: this.pid,
|
||||
uin,
|
||||
serviceCmd: packet.cmd,
|
||||
seqId: packet.seq,
|
||||
retCode: packet.error,
|
||||
fromClient: false,
|
||||
body: Buffer.from(packet.body),
|
||||
});
|
||||
}
|
||||
|
||||
private setStatus(status: HookProcessStatus, error: string): void {
|
||||
if (this._status === status && this._error === error) return;
|
||||
this._status = status;
|
||||
this._error = error;
|
||||
this.emit('status-changed', status, error);
|
||||
}
|
||||
}
|
||||
|
||||
function isRealUin(uin: string): boolean {
|
||||
if (!uin || uin === '0') return false;
|
||||
return /^\d+$/.test(uin) && uin.length >= 5;
|
||||
}
|
||||
|
||||
function errMsg(value: unknown): string {
|
||||
return value instanceof Error ? value.message : String(value);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export {
|
||||
HookManager, type BridgeManagerSink, type HookManagerDeps, type HookProcessBaseInfo, type HookProcessInfo,
|
||||
type HookProcessStatus, type QqPortLoginInfo
|
||||
} from './hook-manager';
|
||||
|
||||
@@ -55,12 +55,13 @@ function defaultProcessName(): string {
|
||||
function nativeSearchDirs(): string[] {
|
||||
// Several layouts must be supported:
|
||||
// 1. Released zip (flattened dist/): __dirname=<extracted>/, native at <extracted>/native
|
||||
// 2. Repo bundled build (dist/index.mjs): __dirname=<root>/dist, native at <root>/dist/native
|
||||
// 3. Dev via tsx (packages/core/src/hook/injector.ts): __dirname=<root>/packages/core/src/hook
|
||||
// 2. Dev via tsx (packages/bridge/src/injector.ts): __dirname=<root>/packages/bridge/src
|
||||
// → walk up to <root>/packages and append runtime/native
|
||||
// Same offset works for `packages/bridge/dist/index.mjs` after build.
|
||||
// 3. cwd-based fallback when neither __dirname-relative path resolves.
|
||||
return [
|
||||
path.resolve(__dirname, 'native'),
|
||||
path.resolve(__dirname, '..', '..', '..', 'runtime', 'native'),
|
||||
path.resolve(__dirname, '..', '..', 'runtime', 'native'),
|
||||
path.resolve(process.cwd(), 'dist', 'native'),
|
||||
path.resolve(process.cwd(), 'packages', 'runtime', 'native'),
|
||||
];
|
||||
@@ -0,0 +1,208 @@
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import { EventEmitter } from 'events';
|
||||
import type { HookProcessBaseInfo } from './injector';
|
||||
|
||||
const DEFAULT_INTERVAL_MS = 1500;
|
||||
const MIN_INTERVAL_MS = 250;
|
||||
|
||||
export type PipeWatcherDeps = {
|
||||
/** Native: list QQ.exe processes currently running. */
|
||||
listProcesses: () => HookProcessBaseInfo[];
|
||||
/** Native: PIDs that currently have a live SnowLuma named pipe. */
|
||||
listLivePipes: () => Promise<Set<number>>;
|
||||
/** Polling interval in ms. Defaults to 1500, floored to 250. */
|
||||
intervalMs?: number;
|
||||
log?: Logger;
|
||||
};
|
||||
|
||||
/**
|
||||
* PipeWatcher — the only module that polls the OS for QQ.exe processes
|
||||
* and live SnowLuma named pipes. Subscribers consume diffs as events.
|
||||
*
|
||||
* Lifecycle: start() runs one tick synchronously, then schedules a poll
|
||||
* every `intervalMs`. tickNow() drains a single tick on demand. wake()
|
||||
* pulls the next scheduled tick forward to the next event-loop turn.
|
||||
*
|
||||
* Emitted events:
|
||||
* 'process-discovered' (info: HookProcessBaseInfo) — a QQ.exe appeared
|
||||
* 'process-gone' (pid: number) — a QQ.exe disappeared
|
||||
* 'pipe-up' (pid: number) — named pipe came up
|
||||
* 'pipe-down' (pid: number) — named pipe dropped
|
||||
* 'tick' () — fired after every poll
|
||||
*
|
||||
* Within a single tick the order is: process-discovered, pipe-up,
|
||||
* pipe-down, process-gone, tick. That ordering lets HookManager create
|
||||
* a session before it gets a pipe event and run disconnect logic before
|
||||
* dispose logic when QQ.exe is killed with a live pipe.
|
||||
*/
|
||||
export class PipeWatcher extends EventEmitter {
|
||||
private readonly listProcesses: PipeWatcherDeps['listProcesses'];
|
||||
private readonly listLivePipes: PipeWatcherDeps['listLivePipes'];
|
||||
private readonly intervalMs: number;
|
||||
private readonly log: Logger;
|
||||
|
||||
private livePipes = new Set<number>();
|
||||
private knownPids = new Set<number>();
|
||||
private timer: NodeJS.Timeout | null = null;
|
||||
private ticking = false;
|
||||
private pendingWake = false;
|
||||
private startPromise: Promise<void> | null = null;
|
||||
private stopped = false;
|
||||
|
||||
constructor(deps: PipeWatcherDeps) {
|
||||
super();
|
||||
this.listProcesses = deps.listProcesses;
|
||||
this.listLivePipes = deps.listLivePipes;
|
||||
this.intervalMs = Math.max(MIN_INTERVAL_MS, deps.intervalMs ?? DEFAULT_INTERVAL_MS);
|
||||
this.log = deps.log ?? createLogger('PipeWatcher');
|
||||
}
|
||||
|
||||
/** Was this PID's pipe live as of the last completed tick? */
|
||||
isPipeLive(pid: number): boolean {
|
||||
return this.livePipes.has(pid);
|
||||
}
|
||||
|
||||
/** Was this PID alive as of the last completed tick? */
|
||||
isProcessAlive(pid: number): boolean {
|
||||
return this.knownPids.has(pid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Run an initial tick (so isPipeLive/isProcessAlive return real data)
|
||||
* and begin the polling loop. Idempotent.
|
||||
*/
|
||||
start(): Promise<void> {
|
||||
if (this.startPromise) return this.startPromise;
|
||||
this.startPromise = (async () => {
|
||||
try {
|
||||
await this.tickOnce();
|
||||
} finally {
|
||||
this.scheduleNext(this.intervalMs);
|
||||
}
|
||||
})();
|
||||
return this.startPromise;
|
||||
}
|
||||
|
||||
/** Pull the next scheduled tick forward to the next event-loop turn. */
|
||||
wake(): void {
|
||||
if (this.stopped) return;
|
||||
this.scheduleNext(0);
|
||||
}
|
||||
|
||||
/** Force a single tick now. Resolves after diff events have been emitted. */
|
||||
tickNow(): Promise<void> {
|
||||
return this.tickOnce();
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.stopped = true;
|
||||
if (this.timer) {
|
||||
clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
}
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.stop();
|
||||
this.removeAllListeners();
|
||||
}
|
||||
|
||||
private scheduleNext(delayMs: number): void {
|
||||
if (this.stopped) return;
|
||||
if (this.timer) {
|
||||
clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
}
|
||||
this.timer = setTimeout(() => {
|
||||
this.timer = null;
|
||||
void this.tickAndReschedule();
|
||||
}, Math.max(0, delayMs));
|
||||
}
|
||||
|
||||
private async tickAndReschedule(): Promise<void> {
|
||||
try {
|
||||
await this.tickOnce();
|
||||
} finally {
|
||||
this.scheduleNext(this.intervalMs);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read processes + live pipes, emit diff events. If another tick is
|
||||
* already running, mark a follow-up tick so we don't lose a wake().
|
||||
*/
|
||||
private async tickOnce(): Promise<void> {
|
||||
if (this.ticking) {
|
||||
this.pendingWake = true;
|
||||
return;
|
||||
}
|
||||
this.ticking = true;
|
||||
try {
|
||||
let processes: HookProcessBaseInfo[];
|
||||
try {
|
||||
processes = this.listProcesses();
|
||||
} catch (error) {
|
||||
this.log.warn('listProcesses failed: %s', errMsg(error));
|
||||
processes = [];
|
||||
}
|
||||
let livePipes: Set<number>;
|
||||
try {
|
||||
livePipes = await this.listLivePipes();
|
||||
} catch (error) {
|
||||
this.log.warn('listLivePipes failed: %s', errMsg(error));
|
||||
livePipes = new Set();
|
||||
}
|
||||
|
||||
const newKnownPids = new Set<number>();
|
||||
for (const proc of processes) newKnownPids.add(proc.pid);
|
||||
|
||||
// 1. Newly discovered processes.
|
||||
for (const proc of processes) {
|
||||
if (!this.knownPids.has(proc.pid)) {
|
||||
this.emit('process-discovered', proc);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Pipes that came up. Ignore pipes for processes we don't know
|
||||
// about (would race against an out-of-order tick).
|
||||
const newLivePipes = new Set<number>();
|
||||
for (const pid of livePipes) {
|
||||
if (!newKnownPids.has(pid)) continue;
|
||||
newLivePipes.add(pid);
|
||||
if (!this.livePipes.has(pid)) {
|
||||
this.emit('pipe-up', pid);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Pipes that dropped. Emit pipe-down BEFORE process-gone so
|
||||
// subscribers can run disconnect logic before dispose logic.
|
||||
for (const pid of this.livePipes) {
|
||||
if (!newLivePipes.has(pid)) {
|
||||
this.emit('pipe-down', pid);
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Processes that disappeared.
|
||||
for (const pid of this.knownPids) {
|
||||
if (!newKnownPids.has(pid)) {
|
||||
this.emit('process-gone', pid);
|
||||
}
|
||||
}
|
||||
|
||||
this.knownPids = newKnownPids;
|
||||
this.livePipes = newLivePipes;
|
||||
this.emit('tick');
|
||||
} finally {
|
||||
this.ticking = false;
|
||||
if (this.pendingWake) {
|
||||
this.pendingWake = false;
|
||||
// Defer to break sync recursion if a listener calls wake().
|
||||
setImmediate(() => { void this.tickOnce(); });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function errMsg(value: unknown): string {
|
||||
return value instanceof Error ? value.message : String(value);
|
||||
}
|
||||
@@ -1,14 +1,15 @@
|
||||
import { EventEmitter } from 'events';
|
||||
import { promises as fs } from 'fs';
|
||||
import net from 'net';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { promises as fs } from 'fs';
|
||||
import { EventEmitter } from 'events';
|
||||
|
||||
export const PIPE_MAGIC = 0x31504851;
|
||||
export const PIPE_VERSION = 1;
|
||||
export const HEADER_SIZE = 40;
|
||||
export const DEFAULT_ACK_TIMEOUT_MS = 5000;
|
||||
export const DEFAULT_REPLY_TIMEOUT_MS = 30000;
|
||||
const DEFAULT_PIPE_PROBE_TIMEOUT_MS = 250;
|
||||
|
||||
export enum PipeOp {
|
||||
hello = 1,
|
||||
@@ -102,6 +103,63 @@ function mojoPipeName(pid: number, suffix: string): string {
|
||||
return path.join(linuxRuntimeDir(), `mojo.${pid}.${suffix}.sock`);
|
||||
}
|
||||
|
||||
type LinuxPipeProbe = (socketPath: string) => Promise<boolean>;
|
||||
|
||||
async function isConnectableUnixSocket(socketPath: string): Promise<boolean> {
|
||||
try {
|
||||
const stat = await fs.stat(socketPath);
|
||||
if (!stat.isSocket()) return false;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
|
||||
return new Promise<boolean>((resolve) => {
|
||||
let socket: net.Socket;
|
||||
try {
|
||||
socket = net.createConnection(socketPath);
|
||||
} catch {
|
||||
resolve(false);
|
||||
return;
|
||||
}
|
||||
let done = false;
|
||||
let timer: NodeJS.Timeout;
|
||||
const finish = (ok: boolean) => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
clearTimeout(timer);
|
||||
socket.removeAllListeners();
|
||||
socket.destroy();
|
||||
resolve(ok);
|
||||
};
|
||||
timer = setTimeout(() => finish(false), DEFAULT_PIPE_PROBE_TIMEOUT_MS);
|
||||
socket.once('connect', () => finish(true));
|
||||
socket.once('error', () => finish(false));
|
||||
});
|
||||
}
|
||||
|
||||
export async function listLiveLinuxPipePids(
|
||||
runtimeDir = linuxRuntimeDir(),
|
||||
probe: LinuxPipeProbe = isConnectableUnixSocket,
|
||||
): Promise<Set<number>> {
|
||||
const result = new Set<number>();
|
||||
let names: string[];
|
||||
try {
|
||||
names = await fs.readdir(runtimeDir);
|
||||
} catch {
|
||||
return result;
|
||||
}
|
||||
|
||||
await Promise.all(names.map(async (name) => {
|
||||
const m = /^mojo\.(\d+)\.control\.sock$/.exec(name);
|
||||
if (!m) return;
|
||||
const pid = Number(m[1]);
|
||||
if (!Number.isInteger(pid) || pid <= 0) return;
|
||||
if (await probe(path.join(runtimeDir, name))) result.add(pid);
|
||||
}));
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function toBuffer(body: Buffer | Uint8Array | string | null | undefined): Buffer {
|
||||
if (Buffer.isBuffer(body)) return body;
|
||||
if (body instanceof Uint8Array) return Buffer.from(body);
|
||||
@@ -177,7 +235,7 @@ function encodeFrame({
|
||||
class FrameReader {
|
||||
private buffer = Buffer.alloc(0);
|
||||
|
||||
constructor(private readonly onFrame: (frame: PipeFrame) => void) {}
|
||||
constructor(private readonly onFrame: (frame: PipeFrame) => void) { }
|
||||
|
||||
push(chunk: Buffer): void {
|
||||
this.buffer = Buffer.concat([this.buffer, chunk]);
|
||||
@@ -312,11 +370,7 @@ export class QqHookClient extends EventEmitter {
|
||||
if (m) result.add(Number(m[1]));
|
||||
}
|
||||
} else {
|
||||
const names = await fs.readdir(linuxRuntimeDir());
|
||||
for (const name of names) {
|
||||
const m = /^mojo\.(\d+)\.control\.sock$/.exec(name);
|
||||
if (m) result.add(Number(m[1]));
|
||||
}
|
||||
return await listLiveLinuxPipePids();
|
||||
}
|
||||
} catch {
|
||||
/* directory missing or inaccessible — treat as no live pipes */
|
||||
@@ -390,7 +444,18 @@ export class QqHookClient extends EventEmitter {
|
||||
}: QqHookSendOptions = {}): Promise<QqHookSendReply | { requestId: number }> {
|
||||
await this.connect();
|
||||
|
||||
const requestId = this.nextRequestId++ >>> 0;
|
||||
// Wrap inside uint32 explicitly. `nextRequestId++ >>> 0` would
|
||||
// misbehave once the integer exceeds Number.MAX_SAFE_INTEGER (the
|
||||
// postfix increment loses precision before the shift), letting two
|
||||
// distinct requests collide on the same id. Skip 0 because zero is
|
||||
// used as a sentinel by the wire protocol.
|
||||
let requestId = this.nextRequestId;
|
||||
while (this.pendingAcks.has(requestId) || this.pendingReplies.has(requestId)) {
|
||||
requestId = (requestId + 1) >>> 0;
|
||||
if (requestId === 0) requestId = 1;
|
||||
}
|
||||
this.nextRequestId = (requestId + 1) >>> 0;
|
||||
if (this.nextRequestId === 0) this.nextRequestId = 1;
|
||||
const payload = encodeFrame({
|
||||
op: PipeOp.sendRequest,
|
||||
requestId,
|
||||
@@ -400,6 +465,12 @@ export class QqHookClient extends EventEmitter {
|
||||
});
|
||||
|
||||
const ackDeferred = createDeferred<{ requestId: number; wantReply: boolean }>();
|
||||
// Always attach a handler so a rejection can never become "unhandled" (which
|
||||
// crashes Node). When the pipe closes, rejectControlPending() rejects every
|
||||
// pending deferred — but the reply is only `await`ed AFTER the ack, so if the
|
||||
// ack fails first the reply promise is rejected with NO awaiter. The real
|
||||
// `await` below still observes the value/rejection (a separate continuation).
|
||||
ackDeferred.promise.catch(() => { /* observed by the await, or harmless */ });
|
||||
this.pendingAcks.set(requestId, {
|
||||
resolve: ackDeferred.resolve,
|
||||
reject: ackDeferred.reject,
|
||||
@@ -409,6 +480,7 @@ export class QqHookClient extends EventEmitter {
|
||||
let replyDeferred: Deferred<QqHookSendReply> | null = null;
|
||||
if (wantReply) {
|
||||
replyDeferred = createDeferred<QqHookSendReply>();
|
||||
replyDeferred.promise.catch(() => { /* see note above — prevents unhandled rejection */ });
|
||||
this.pendingReplies.set(requestId, replyDeferred);
|
||||
}
|
||||
|
||||
@@ -448,7 +520,7 @@ export class QqHookClient extends EventEmitter {
|
||||
const workerCount = Math.max(1, Math.min(concurrency | 0, items.length || 1));
|
||||
|
||||
const worker = async () => {
|
||||
for (;;) {
|
||||
for (; ;) {
|
||||
const index = nextIndex;
|
||||
nextIndex += 1;
|
||||
if (index >= items.length) return;
|
||||
@@ -559,7 +631,7 @@ export class QqHookClient extends EventEmitter {
|
||||
else resolve();
|
||||
});
|
||||
}));
|
||||
this.controlWriteChain = writePromise.catch(() => {});
|
||||
this.controlWriteChain = writePromise.catch(() => { });
|
||||
return writePromise;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,282 @@
|
||||
import { exec } from 'child_process';
|
||||
import net from 'net';
|
||||
import https from 'https';
|
||||
import { promisify } from 'util';
|
||||
|
||||
const execAsync = promisify(exec);
|
||||
|
||||
const PORT_RANGE_START = 9210;
|
||||
const PORT_RANGE_END = 9219;
|
||||
const PROBE_TIMEOUT_MS = 1000;
|
||||
const CONNECTION_TIMEOUT_MS = 500;
|
||||
// QQ's Ptlogin quick-login ports plus its main process mean a single
|
||||
// logged-in client surfaces roughly this many processes. When no usable
|
||||
// probe port is found, a count BELOW this implies the target PID is still at
|
||||
// the login screen; AT/ABOVE it the environment is ambiguous (multiple or
|
||||
// unrelated `qq` processes), so we fall through to deep-link probing rather
|
||||
// than guess "logged out".
|
||||
const LOGGED_OUT_PROCESS_COUNT_MAX = 6;
|
||||
|
||||
export interface QqPortLoginInfo {
|
||||
port: number;
|
||||
uin: string;
|
||||
uid?: string;
|
||||
nickName?: string;
|
||||
loggedIn: boolean;
|
||||
}
|
||||
|
||||
interface JwtPayload {
|
||||
errCode: number;
|
||||
errMsg: string;
|
||||
port: number;
|
||||
uin?: string;
|
||||
uid?: string;
|
||||
nickName?: string;
|
||||
data?: {
|
||||
uin?: string;
|
||||
url?: string;
|
||||
};
|
||||
iat: number;
|
||||
}
|
||||
|
||||
function decodeJwt(token: string): JwtPayload | null {
|
||||
try {
|
||||
const parts = token.split('.');
|
||||
if (parts.length !== 3) return null;
|
||||
const payload = Buffer.from(parts[1], 'base64').toString('utf8');
|
||||
return JSON.parse(payload);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
async function probePort(port: number): Promise<QqPortLoginInfo | null> {
|
||||
return new Promise((resolve) => {
|
||||
const client = new net.Socket();
|
||||
const link = 'tencent://';
|
||||
const payload = `POST /tencent HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nConnection: close\r\nContent-Length: ${link.length}\r\n\r\n${link}`;
|
||||
|
||||
let responseData = '';
|
||||
let timer: NodeJS.Timeout;
|
||||
|
||||
const cleanup = () => {
|
||||
clearTimeout(timer);
|
||||
client.removeAllListeners();
|
||||
client.destroy();
|
||||
};
|
||||
|
||||
timer = setTimeout(() => {
|
||||
cleanup();
|
||||
resolve(null);
|
||||
}, PROBE_TIMEOUT_MS);
|
||||
|
||||
client.setTimeout(CONNECTION_TIMEOUT_MS);
|
||||
|
||||
client.connect(port, '127.0.0.1', () => {
|
||||
client.write(payload);
|
||||
});
|
||||
|
||||
client.on('data', (data) => {
|
||||
responseData += data.toString();
|
||||
});
|
||||
|
||||
client.on('close', () => {
|
||||
cleanup();
|
||||
const jwtMatch = responseData.match(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/);
|
||||
if (!jwtMatch) {
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const decoded = decodeJwt(jwtMatch[0]);
|
||||
if (!decoded || decoded.errCode !== 0) {
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const uin = decoded.uin || decoded.data?.uin || '';
|
||||
resolve({
|
||||
port,
|
||||
uin,
|
||||
uid: decoded.uid,
|
||||
nickName: decoded.nickName,
|
||||
loggedIn: uin.length > 0,
|
||||
});
|
||||
});
|
||||
|
||||
client.on('error', () => {
|
||||
cleanup();
|
||||
resolve(null);
|
||||
});
|
||||
|
||||
client.on('timeout', () => {
|
||||
cleanup();
|
||||
resolve(null);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/** One entry of the Ptlogin `pt_get_uins` JSONP array. Only the fields the
|
||||
* probe reads are modelled; QQ sends more but they're irrelevant here. */
|
||||
interface PtloginUin {
|
||||
uin?: string | number;
|
||||
account?: string | number;
|
||||
nickname?: string;
|
||||
}
|
||||
|
||||
async function fetchPtlogin(port: number): Promise<PtloginUin[]> {
|
||||
return new Promise((resolve) => {
|
||||
const url = `https://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`;
|
||||
|
||||
const req = https.get(
|
||||
url,
|
||||
{
|
||||
headers: {
|
||||
Host: 'localhost.ptlogin2.qq.com',
|
||||
Referer: 'https://xui.ptlogin2.qq.com/',
|
||||
Cookie: 'pt_local_token=0',
|
||||
},
|
||||
rejectUnauthorized: false, // 忽略本地自签证书报错
|
||||
timeout: CONNECTION_TIMEOUT_MS,
|
||||
},
|
||||
(res) => {
|
||||
let text = '';
|
||||
res.on('data', (chunk) => { text += chunk.toString(); });
|
||||
res.on('end', () => {
|
||||
try {
|
||||
// 100% 复刻 Python 切片逻辑:获取两个方括号中间的字符串,再包装成数组
|
||||
const inner = text.split('[')[1].split(']')[0];
|
||||
const data = JSON.parse('[' + inner + ']') as PtloginUin[];
|
||||
resolve(data);
|
||||
} catch {
|
||||
resolve([]);
|
||||
}
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
req.on('error', () => resolve([]));
|
||||
req.on('timeout', () => {
|
||||
req.destroy();
|
||||
resolve([]);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function tryPtloginMethod(port: number): Promise<QqPortLoginInfo | 'fallback'> {
|
||||
// 抽象的 QQNT
|
||||
const res1 = await fetchPtlogin(port);
|
||||
const res2 = await fetchPtlogin(port);
|
||||
|
||||
const target = res1.length < res2.length ? res1 : res2;
|
||||
|
||||
if (target.length === 1) {
|
||||
const account = target[0];
|
||||
return {
|
||||
port,
|
||||
uin: String(account.uin || account.account || ''),
|
||||
nickName: account.nickname || '',
|
||||
loggedIn: true,
|
||||
};
|
||||
}
|
||||
|
||||
// Any non-1 result — the 2+0 alternation, both-2, both-empty, etc. — is
|
||||
// inconclusive; hand off to the deep-link / process-count fallback.
|
||||
return 'fallback';
|
||||
}
|
||||
|
||||
|
||||
async function getQqProcessCount(): Promise<number> {
|
||||
try {
|
||||
if (process.platform === 'win32') {
|
||||
const { stdout } = await execAsync('tasklist /fi "imagename eq QQ.exe" /nh');
|
||||
return stdout.toLowerCase().split('\n').filter(line => line.includes('qq.exe')).length;
|
||||
} else {
|
||||
const { stdout } = await execAsync('pgrep -c qq');
|
||||
return parseInt(stdout.trim(), 10) || 0;
|
||||
}
|
||||
} catch {
|
||||
// On failure report the ambiguous threshold so we never falsely
|
||||
// conclude "logged out".
|
||||
return LOGGED_OUT_PROCESS_COUNT_MAX;
|
||||
}
|
||||
}
|
||||
|
||||
async function getProcessPorts(pid: number): Promise<number[]> {
|
||||
try {
|
||||
if (process.platform === 'win32') {
|
||||
const { stdout } = await execAsync(`netstat -ano | findstr ${pid}`);
|
||||
const ports = new Set<number>();
|
||||
const lines = stdout.split('\n');
|
||||
for (const line of lines) {
|
||||
const parts = line.trim().split(/\s+/);
|
||||
if (parts.length < 5) continue;
|
||||
const owningPid = parts[parts.length - 1];
|
||||
if (owningPid !== String(pid)) continue;
|
||||
|
||||
const localAddr = parts[1];
|
||||
const portMatch = localAddr.match(/:(\d+)$/);
|
||||
if (!portMatch) continue;
|
||||
ports.add(Number(portMatch[1]));
|
||||
}
|
||||
return Array.from(ports);
|
||||
} else {
|
||||
const { stdout } = await execAsync(`ss -tlnp | grep pid=${pid}`);
|
||||
const ports = new Set<number>();
|
||||
const lines = stdout.split('\n');
|
||||
for (const line of lines) {
|
||||
const match = line.match(/:(\d+)\s/);
|
||||
if (match) {
|
||||
ports.add(Number(match[1]));
|
||||
}
|
||||
}
|
||||
return Array.from(ports);
|
||||
}
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export async function probeQqLoginInfo(pid: number): Promise<QqPortLoginInfo | null> {
|
||||
const ports = await getProcessPorts(pid);
|
||||
|
||||
if (ports.length === 0) {
|
||||
const totalPids = await getQqProcessCount();
|
||||
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
|
||||
return { port: 0, uin: '', loggedIn: false };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const PT_PORTS = [4301, 4303, 4305, 4307, 4309];
|
||||
const matchedPtPorts = ports.filter(p => PT_PORTS.includes(p));
|
||||
|
||||
if (matchedPtPorts.length > 0) {
|
||||
for (const port of matchedPtPorts) {
|
||||
const ptResult = await tryPtloginMethod(port);
|
||||
if (ptResult !== 'fallback') {
|
||||
return ptResult;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const totalPids = await getQqProcessCount();
|
||||
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
|
||||
return {
|
||||
port: ports[0] || 0,
|
||||
uin: '',
|
||||
loggedIn: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const deepLinkPorts = ports.filter(p => p >= PORT_RANGE_START && p <= PORT_RANGE_END);
|
||||
for (const port of deepLinkPorts) {
|
||||
const info = await probePort(port);
|
||||
if (info) return info;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { HookProcessBaseInfo } from './injector';
|
||||
|
||||
export type HookProcessStatus =
|
||||
| 'available'
|
||||
| 'loading'
|
||||
| 'connecting'
|
||||
| 'loaded'
|
||||
| 'online'
|
||||
| 'error'
|
||||
| 'disconnected';
|
||||
|
||||
/** Public-facing snapshot of a per-PID HookSession. */
|
||||
export interface HookProcessInfo extends HookProcessBaseInfo {
|
||||
injected: boolean;
|
||||
connected: boolean;
|
||||
loggedIn: boolean;
|
||||
uin: string;
|
||||
status: HookProcessStatus;
|
||||
error: string;
|
||||
method: string;
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { EventEmitter } from 'events';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { HookManager, shouldAutoLoadPid } from '../src/hook-manager';
|
||||
import { PipeWatcher } from '../src/pipe-watcher';
|
||||
import type { ManualMapHandle } from '../src/injector';
|
||||
import type { BridgeManagerSink } from '../src/hook-manager';
|
||||
import type { QqHookClient } from '../src/qq-hook-client';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
|
||||
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
|
||||
const flush = () => new Promise<void>(r => setImmediate(r));
|
||||
|
||||
function makeManager(opts: {
|
||||
autoLoadOnDiscovery?: boolean;
|
||||
processes?: number[];
|
||||
}) {
|
||||
let pids = opts.processes ?? [];
|
||||
const live = new Set<number>();
|
||||
const inject = vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE }));
|
||||
const unload = vi.fn();
|
||||
const pipeWatcher = new PipeWatcher({
|
||||
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000, // disable internal timer; tests drive ticks manually
|
||||
});
|
||||
// FakeClient — never connected; just needs to satisfy EventEmitter +
|
||||
// a minimal subset of QqHookClient for HookSession.tearDownClient().
|
||||
const makeClient = vi.fn(() => {
|
||||
const c = new EventEmitter() as EventEmitter & Partial<QqHookClient>;
|
||||
(c as any).isClosed = false;
|
||||
(c as any).isLoggedIn = false;
|
||||
(c as any).getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
|
||||
(c as any).connectAll = async () => { throw new Error('test: never really connect'); };
|
||||
(c as any).close = () => { (c as any).isClosed = true; };
|
||||
return c as unknown as QqHookClient;
|
||||
});
|
||||
const bridgeManager = {
|
||||
onPacket: vi.fn(),
|
||||
onHookLogin: vi.fn(),
|
||||
onPidDisconnected: vi.fn(),
|
||||
} as unknown as BridgeManagerSink;
|
||||
const manager = new HookManager({
|
||||
bridgeManager,
|
||||
pipeWatcher,
|
||||
injector: { inject, unload },
|
||||
makeClient,
|
||||
autoLoadOnDiscovery: opts.autoLoadOnDiscovery,
|
||||
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||
});
|
||||
return {
|
||||
manager,
|
||||
inject,
|
||||
pipeWatcher,
|
||||
setProcesses: (next: number[]) => { pids = next; },
|
||||
};
|
||||
}
|
||||
|
||||
describe('HookManager.autoLoadOnDiscovery', () => {
|
||||
it('does NOT inject on process-discovered when flag is off', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: false, processes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
expect(ctx.inject).not.toHaveBeenCalled();
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('injects every newly-discovered PID when flag is on', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
// session.load() is queued via a per-session promise chain; flush twice
|
||||
// so the auto-load runs to completion before we assert.
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(1);
|
||||
expect(ctx.inject).toHaveBeenCalledWith(4242);
|
||||
|
||||
// A second PID appearing mid-flight should also trigger an inject.
|
||||
ctx.setProcesses([4242, 9999]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(2);
|
||||
expect(ctx.inject).toHaveBeenLastCalledWith(9999);
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('swallows inject errors so the watcher keeps running', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementationOnce(() => { throw new Error('ptrace denied'); });
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
// Second PID should still be auto-loaded — the failure on 4242 must
|
||||
// not leak out of the listener and break the watcher's emit loop.
|
||||
ctx.setProcesses([4242, 9999]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(2);
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
// `shouldAutoLoadPid` reads /proc/<pid>/cmdline directly, so we point
|
||||
// it at a temporary directory that mimics the procfs layout. This lets
|
||||
// the tests run on macOS / CI without a live Linux QQ process.
|
||||
describe('shouldAutoLoadPid', () => {
|
||||
let tmpProc: string;
|
||||
const originalReadFileSync = fs.readFileSync;
|
||||
const log = createLogger('test');
|
||||
const originalPlatform = process.platform;
|
||||
const originalAutoLoadAll = process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpProc = fs.mkdtempSync(path.join(os.tmpdir(), 'hookmgr-proc-'));
|
||||
Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });
|
||||
delete process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
|
||||
// Redirect readFileSync('/proc/<pid>/cmdline') to the tmp dir.
|
||||
(fs.readFileSync as unknown as typeof fs.readFileSync) = ((p: string, ...rest: unknown[]) => {
|
||||
const match = /^\/proc\/(\d+)\/cmdline$/.exec(p);
|
||||
if (match) {
|
||||
return originalReadFileSync(path.join(tmpProc, match[1], 'cmdline'), ...(rest as [BufferEncoding]));
|
||||
}
|
||||
return originalReadFileSync(p, ...(rest as [BufferEncoding]));
|
||||
}) as typeof fs.readFileSync;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
(fs.readFileSync as unknown as typeof fs.readFileSync) = originalReadFileSync;
|
||||
Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true });
|
||||
if (originalAutoLoadAll === undefined) delete process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
|
||||
else process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL = originalAutoLoadAll;
|
||||
fs.rmSync(tmpProc, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function writeCmdline(pid: number, args: string[]): void {
|
||||
const dir = path.join(tmpProc, String(pid));
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, 'cmdline'), args.join('\0') + '\0');
|
||||
}
|
||||
|
||||
it('allows the QQ main process (no --type=)', () => {
|
||||
writeCmdline(50, ['qq', '--no-sandbox']);
|
||||
expect(shouldAutoLoadPid(50, log)).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects Electron zygotes', () => {
|
||||
writeCmdline(59, ['/opt/QQ/qq', '--type=zygote', '--no-zygote-sandbox', '--no-sandbox']);
|
||||
expect(shouldAutoLoadPid(59, log)).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects renderer/gpu/utility children', () => {
|
||||
writeCmdline(70, ['/opt/QQ/qq', '--type=renderer']);
|
||||
writeCmdline(71, ['/opt/QQ/qq', '--type=gpu-process']);
|
||||
writeCmdline(72, ['/opt/QQ/qq', '--type=utility', '--utility-sub-type=network.mojom.NetworkService']);
|
||||
expect(shouldAutoLoadPid(70, log)).toBe(false);
|
||||
expect(shouldAutoLoadPid(71, log)).toBe(false);
|
||||
expect(shouldAutoLoadPid(72, log)).toBe(false);
|
||||
});
|
||||
|
||||
it('allows everything if SNOWLUMA_HOOK_AUTOLOAD_ALL=1 (escape hatch)', () => {
|
||||
writeCmdline(59, ['/opt/QQ/qq', '--type=zygote']);
|
||||
process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL = '1';
|
||||
expect(shouldAutoLoadPid(59, log)).toBe(true);
|
||||
});
|
||||
|
||||
it('allows on non-linux platforms (filter is a Linux-only workaround)', () => {
|
||||
Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
|
||||
// No cmdline file needed — we return true before touching procfs.
|
||||
expect(shouldAutoLoadPid(59, log)).toBe(true);
|
||||
});
|
||||
|
||||
it('allows when /proc is unreadable (dead PID, permission issue)', () => {
|
||||
expect(shouldAutoLoadPid(99999, log)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
// E2E for Docker "QQ never logs in + pipe keeps reconnecting" scenario.
|
||||
//
|
||||
// Drives the real PipeWatcher + HookManager through repeated same-PID
|
||||
// pipe up/down cycles via tickNow() and asserts the BridgeManager mock
|
||||
// is never touched (no login → no Bridge / OneBotInstance / Identity).
|
||||
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { EventEmitter } from 'events';
|
||||
import { HookManager } from '../src/hook-manager';
|
||||
import { PipeWatcher } from '../src/pipe-watcher';
|
||||
import type { ManualMapHandle } from '../src/injector';
|
||||
import type { BridgeManagerSink } from '../src/hook-manager';
|
||||
import type { QqHookClient } from '../src/qq-hook-client';
|
||||
|
||||
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
|
||||
const flush = () => new Promise<void>(r => setImmediate(r));
|
||||
|
||||
class FakeClient extends EventEmitter {
|
||||
isClosed = false;
|
||||
isLoggedIn = false;
|
||||
async connectAll(_opts: { recv: boolean }) {
|
||||
if (this.isClosed) throw new Error('client is closed');
|
||||
}
|
||||
getLoginState() { return { loggedIn: false, uin: '0', uinNumber: 0n }; }
|
||||
close() {
|
||||
if (this.isClosed) return;
|
||||
this.isClosed = true;
|
||||
this.emit('close');
|
||||
}
|
||||
}
|
||||
|
||||
describe('HookManager — Docker reconnect-without-login leak guard', () => {
|
||||
it('after N pipe up/down cycles: no Bridge calls, no client accumulation', async () => {
|
||||
const PID = 61;
|
||||
const liveSet = new Set<number>([PID]);
|
||||
const clients: FakeClient[] = [];
|
||||
|
||||
const pipeWatcher = new PipeWatcher({
|
||||
listProcesses: () => [{ pid: PID, name: 'qq', path: '' }],
|
||||
listLivePipes: async () => new Set(liveSet),
|
||||
intervalMs: 60_000, // manual ticks only
|
||||
});
|
||||
|
||||
const bridgeManager = {
|
||||
onPacket: vi.fn(),
|
||||
onHookLogin: vi.fn(),
|
||||
onPidDisconnected: vi.fn(),
|
||||
} as unknown as BridgeManagerSink;
|
||||
|
||||
const manager = new HookManager({
|
||||
bridgeManager,
|
||||
pipeWatcher,
|
||||
injector: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: () => {
|
||||
const c = new FakeClient();
|
||||
clients.push(c);
|
||||
return c as unknown as QqHookClient;
|
||||
},
|
||||
autoLoadOnDiscovery: true,
|
||||
listProcesses: () => [{ pid: PID, name: 'qq', path: '' }],
|
||||
});
|
||||
|
||||
// Initial discovery + first connect.
|
||||
await pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
// Drive 50 pipe up/down cycles with the QQ process staying alive but
|
||||
// the pipe (= QQ control socket) bouncing every "tick".
|
||||
const CYCLES = 50;
|
||||
for (let i = 0; i < CYCLES; i++) {
|
||||
liveSet.delete(PID);
|
||||
await pipeWatcher.tickNow();
|
||||
await flush();
|
||||
liveSet.add(PID);
|
||||
await pipeWatcher.tickNow();
|
||||
await flush();
|
||||
}
|
||||
|
||||
// The "QQ never logs in" hypothesis: BridgeManager should never have
|
||||
// been told about a login or a disconnect.
|
||||
expect(bridgeManager.onHookLogin).not.toHaveBeenCalled();
|
||||
expect(bridgeManager.onPidDisconnected).not.toHaveBeenCalled();
|
||||
expect(bridgeManager.onPacket).not.toHaveBeenCalled();
|
||||
|
||||
// Hook layer should hold at most one live client.
|
||||
const alive = clients.filter(c => !c.isClosed);
|
||||
expect(alive.length, `live clients after ${CYCLES} cycles: ${alive.length}`).toBeLessThanOrEqual(1);
|
||||
|
||||
// Total clients minted = roughly one per up cycle. Sanity bound:
|
||||
// we must have actually exercised the reconnect path.
|
||||
expect(clients.length).toBeGreaterThan(1);
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
// Regression test for the Docker "QQ-never-logs-in + pipe keeps reconnecting" leak hypothesis.
|
||||
//
|
||||
// User-reported pattern (Docker, idle login screen):
|
||||
// 02:41:23 [Hook] pipe connected: PID=61
|
||||
// 04:37:55 [Hook] pipe connected: PID=61 (same PID, ~2h later)
|
||||
// 04:40:44 [Hook] pipe connected: PID=61
|
||||
// 04:43:48 [Hook] pipe connected: PID=61 → eventual OOM-kill
|
||||
//
|
||||
// Hypothesis (H2): every onPipeDown → onPipeUp cycle leaks the prior
|
||||
// QqHookClient (listeners or socket-ref keeping it pinned in memory),
|
||||
// so repeated reconnect drives unbounded growth.
|
||||
//
|
||||
// This test drives N up/down cycles against a HookSession with a FakeClient
|
||||
// factory and asserts:
|
||||
// - at most one client is alive at any point
|
||||
// - every prior client's EventEmitter listener count drops to 0 after teardown
|
||||
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { EventEmitter } from 'events';
|
||||
import { HookSession } from '../src/hook-session';
|
||||
import type { ManualMapHandle } from '../src/injector';
|
||||
import type { QqHookClient } from '../src/qq-hook-client';
|
||||
|
||||
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
|
||||
|
||||
class FakeClient extends EventEmitter {
|
||||
isClosed = false;
|
||||
isLoggedIn = false;
|
||||
private loginState = { loggedIn: false, uin: '0', uinNumber: 0n };
|
||||
|
||||
async connectAll(_opts: { recv: boolean }): Promise<void> {
|
||||
if (this.isClosed) throw new Error('client is closed');
|
||||
}
|
||||
getLoginState() { return { ...this.loginState }; }
|
||||
close(): void {
|
||||
if (this.isClosed) return;
|
||||
this.isClosed = true;
|
||||
this.emit('close');
|
||||
}
|
||||
}
|
||||
|
||||
function totalListenerCount(emitter: EventEmitter): number {
|
||||
return emitter.eventNames().reduce((n, evt) => n + emitter.listenerCount(evt), 0);
|
||||
}
|
||||
|
||||
const flush = () => new Promise<void>(r => setImmediate(r));
|
||||
|
||||
describe('HookSession — pipe reconnect with QQ never logging in', () => {
|
||||
it('does not accumulate live FakeClient instances across N pipe up/down cycles', async () => {
|
||||
let pipeLive = true;
|
||||
const clients: FakeClient[] = [];
|
||||
const session = new HookSession(61, {
|
||||
injector: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: () => {
|
||||
const c = new FakeClient();
|
||||
clients.push(c);
|
||||
return c as unknown as QqHookClient;
|
||||
},
|
||||
pipeWatcher: { isPipeLive: () => pipeLive },
|
||||
});
|
||||
|
||||
await session.load();
|
||||
session.onPipeUp();
|
||||
await flush();
|
||||
|
||||
const CYCLES = 50;
|
||||
for (let i = 0; i < CYCLES; i++) {
|
||||
pipeLive = false;
|
||||
session.onPipeDown();
|
||||
await flush();
|
||||
pipeLive = true;
|
||||
session.onPipeUp();
|
||||
await flush();
|
||||
}
|
||||
|
||||
const alive = clients.filter(c => !c.isClosed);
|
||||
expect.soft(clients.length).toBeGreaterThan(1);
|
||||
expect(alive.length, `expected ≤1 live client after ${CYCLES} reconnects, got ${alive.length}`)
|
||||
.toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('drops all listeners from each torn-down client', async () => {
|
||||
let pipeLive = true;
|
||||
const clients: FakeClient[] = [];
|
||||
const session = new HookSession(61, {
|
||||
injector: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: () => {
|
||||
const c = new FakeClient();
|
||||
clients.push(c);
|
||||
return c as unknown as QqHookClient;
|
||||
},
|
||||
pipeWatcher: { isPipeLive: () => pipeLive },
|
||||
});
|
||||
|
||||
await session.load();
|
||||
session.onPipeUp();
|
||||
await flush();
|
||||
|
||||
const CYCLES = 20;
|
||||
for (let i = 0; i < CYCLES; i++) {
|
||||
pipeLive = false;
|
||||
session.onPipeDown();
|
||||
await flush();
|
||||
pipeLive = true;
|
||||
session.onPipeUp();
|
||||
await flush();
|
||||
}
|
||||
|
||||
// Every client except the current one should have 0 listeners attached.
|
||||
// (HookSession.tearDownClient does client.removeAllListeners().)
|
||||
for (let i = 0; i < clients.length - 1; i++) {
|
||||
const lc = totalListenerCount(clients[i]);
|
||||
expect(lc, `client #${i} of ${clients.length} still has ${lc} listeners after teardown`)
|
||||
.toBe(0);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,446 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { EventEmitter } from 'events';
|
||||
import { HookSession } from '../src/hook-session';
|
||||
import type { ManualMapHandle } from '../src/injector';
|
||||
import type { QqHookClient, QqHookPacket } from '../src/qq-hook-client';
|
||||
import type { PacketSink } from '@snowluma/common/protocol-types';
|
||||
|
||||
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
|
||||
|
||||
/** Minimal stand-in for QqHookClient. Tests drive login/packet/error/close
|
||||
* events directly via fire* helpers. connectAll succeeds unless told otherwise. */
|
||||
class FakeClient extends EventEmitter {
|
||||
isClosed = false;
|
||||
isLoggedIn = false;
|
||||
shouldFailConnect = false;
|
||||
private loginState = { loggedIn: false, uin: '0', uinNumber: 0n };
|
||||
|
||||
async connectAll(_opts: { recv: boolean }): Promise<void> {
|
||||
if (this.shouldFailConnect) throw new Error('connect failed');
|
||||
if (this.isClosed) throw new Error('client is closed');
|
||||
}
|
||||
getLoginState() { return { ...this.loginState }; }
|
||||
close(): void {
|
||||
if (this.isClosed) return;
|
||||
this.isClosed = true;
|
||||
this.emit('close');
|
||||
}
|
||||
|
||||
fireLogin(uin: string): void {
|
||||
this.isLoggedIn = true;
|
||||
this.loginState = { loggedIn: true, uin, uinNumber: BigInt(uin) };
|
||||
this.emit('loginState', { ...this.loginState });
|
||||
}
|
||||
|
||||
firePacket(packet: QqHookPacket): void {
|
||||
this.emit('packet', packet);
|
||||
}
|
||||
}
|
||||
|
||||
function makeSession(opts: {
|
||||
pid?: number;
|
||||
pipeLive?: boolean;
|
||||
clientFailsConnect?: boolean;
|
||||
onPacket?: PacketSink;
|
||||
} = {}) {
|
||||
const pid = opts.pid ?? 1234;
|
||||
let pipeLive = opts.pipeLive ?? false;
|
||||
const clients: FakeClient[] = [];
|
||||
const injector = {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
unload: vi.fn(),
|
||||
};
|
||||
|
||||
const session = new HookSession(pid, {
|
||||
injector,
|
||||
makeClient: () => {
|
||||
const c = new FakeClient();
|
||||
if (opts.clientFailsConnect) c.shouldFailConnect = true;
|
||||
clients.push(c);
|
||||
// Cast: FakeClient mirrors only the surface HookSession touches.
|
||||
return c as unknown as QqHookClient;
|
||||
},
|
||||
pipeWatcher: { isPipeLive: () => pipeLive },
|
||||
onPacket: opts.onPacket,
|
||||
});
|
||||
|
||||
return {
|
||||
session,
|
||||
injector,
|
||||
clients,
|
||||
currentClient: () => clients[clients.length - 1]!,
|
||||
setPipeLive: (v: boolean) => { pipeLive = v; },
|
||||
};
|
||||
}
|
||||
|
||||
const flush = () => new Promise<void>(r => setImmediate(r));
|
||||
|
||||
describe('HookSession — load', () => {
|
||||
it('with no live pipe: injects, status → connecting, method from inject result', async () => {
|
||||
const { session, injector } = makeSession({ pipeLive: false });
|
||||
const info = await session.load();
|
||||
|
||||
expect(injector.inject).toHaveBeenCalledOnce();
|
||||
expect(info.status).toBe('connecting');
|
||||
expect(info.method).toBe('loadModuleManual');
|
||||
expect(info.injected).toBe(true);
|
||||
});
|
||||
|
||||
it('fast-path: pipe already live → skip inject, method → "reconnect"', async () => {
|
||||
const { session, injector } = makeSession({ pipeLive: true });
|
||||
const info = await session.load();
|
||||
|
||||
expect(injector.inject).not.toHaveBeenCalled();
|
||||
expect(info.method).toBe('reconnect');
|
||||
expect(info.injected).toBe(true);
|
||||
expect(info.status).toBe('connecting');
|
||||
});
|
||||
|
||||
it('inject failure → status error, error message captured', async () => {
|
||||
const injector = {
|
||||
inject: vi.fn(() => { throw new Error('inject boom'); }),
|
||||
unload: vi.fn(),
|
||||
};
|
||||
const session = new HookSession(1234, {
|
||||
injector,
|
||||
makeClient: () => new FakeClient() as unknown as QqHookClient,
|
||||
pipeWatcher: { isPipeLive: () => false },
|
||||
});
|
||||
const info = await session.load();
|
||||
expect(info.status).toBe('error');
|
||||
expect(info.error).toBe('inject boom');
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookSession — pipe up/down → connect lifecycle', () => {
|
||||
it('onPipeUp after load: client connects → status loaded', async () => {
|
||||
const ctx = makeSession({ pipeLive: true });
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
|
||||
expect(ctx.session.status).toBe('loaded');
|
||||
expect(ctx.clients).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('emits "login" with (uin, sender) after client signals loggedIn', async () => {
|
||||
const ctx = makeSession({ pipeLive: true });
|
||||
const loginSpy = vi.fn();
|
||||
ctx.session.on('login', loginSpy);
|
||||
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
|
||||
expect(loginSpy).toHaveBeenCalledOnce();
|
||||
const [uin, sender] = loginSpy.mock.calls[0]!;
|
||||
expect(uin).toBe('10001');
|
||||
expect(typeof (sender as { sendPacket: unknown }).sendPacket).toBe('function');
|
||||
expect(ctx.session.status).toBe('online');
|
||||
expect(ctx.session.uin).toBe('10001');
|
||||
});
|
||||
|
||||
it('does not re-emit "login" on duplicate loginState with same uin', async () => {
|
||||
const ctx = makeSession({ pipeLive: true });
|
||||
const loginSpy = vi.fn();
|
||||
ctx.session.on('login', loginSpy);
|
||||
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
|
||||
expect(loginSpy).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('connect failure: stays in connecting, error message captured (will retry on next tick)', async () => {
|
||||
const ctx = makeSession({ pipeLive: true, clientFailsConnect: true });
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
|
||||
expect(ctx.session.status).toBe('connecting');
|
||||
expect(ctx.session.error).toBe('connect failed');
|
||||
});
|
||||
|
||||
it('onPipeDown while logged in: emits disconnected(true), status disconnected', async () => {
|
||||
const ctx = makeSession({ pipeLive: true });
|
||||
const discSpy = vi.fn();
|
||||
ctx.session.on('disconnected', discSpy);
|
||||
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
|
||||
ctx.session.onPipeDown();
|
||||
await flush();
|
||||
|
||||
expect(discSpy).toHaveBeenCalledWith(true);
|
||||
expect(ctx.session.status).toBe('disconnected');
|
||||
});
|
||||
|
||||
it('onPipeDown while connected-but-not-logged-in: emits disconnected(false), status connecting', async () => {
|
||||
const ctx = makeSession({ pipeLive: true });
|
||||
const discSpy = vi.fn();
|
||||
ctx.session.on('disconnected', discSpy);
|
||||
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
// No login fired — we're connected but not logged in.
|
||||
|
||||
ctx.session.onPipeDown();
|
||||
await flush();
|
||||
|
||||
// disconnected(false) is currently NOT emitted — disconnect events are
|
||||
// reserved for "we owe BridgeManager a disconnect notification". This
|
||||
// preserves the original behaviour.
|
||||
expect(discSpy).not.toHaveBeenCalled();
|
||||
expect(ctx.session.status).toBe('connecting');
|
||||
});
|
||||
|
||||
it('repeated pipe down → up cycles reach consistent state', async () => {
|
||||
const ctx = makeSession({ pipeLive: true });
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
expect(ctx.session.status).toBe('online');
|
||||
|
||||
ctx.session.onPipeDown();
|
||||
await flush();
|
||||
expect(ctx.session.status).toBe('disconnected');
|
||||
|
||||
// Pipe returns — session builds a fresh client.
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
expect(ctx.clients.length).toBeGreaterThan(1);
|
||||
expect(ctx.session.status).toBe('loaded');
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookSession — unload', () => {
|
||||
it('while logged in: emits disconnected(true), calls unload, status available', async () => {
|
||||
const ctx = makeSession({ pipeLive: false });
|
||||
await ctx.session.load();
|
||||
ctx.setPipeLive(true);
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
|
||||
const discSpy = vi.fn();
|
||||
ctx.session.on('disconnected', discSpy);
|
||||
ctx.setPipeLive(false); // unload verification will see the pipe gone
|
||||
|
||||
await ctx.session.unload();
|
||||
|
||||
expect(discSpy).toHaveBeenCalledWith(true);
|
||||
expect(ctx.injector.unload).toHaveBeenCalledOnce();
|
||||
expect(ctx.session.status).toBe('available');
|
||||
});
|
||||
|
||||
it('when pipe stays live after unload: status connecting with retry message', async () => {
|
||||
const ctx = makeSession({ pipeLive: false });
|
||||
await ctx.session.load();
|
||||
// Simulate the unload-failed scenario: pipe is still up after unload.
|
||||
ctx.setPipeLive(true);
|
||||
|
||||
const info = await ctx.session.unload();
|
||||
|
||||
expect(info.status).toBe('connecting');
|
||||
expect(info.error).toContain('命名管道仍然存在');
|
||||
});
|
||||
|
||||
it('forces a fresh tick before verifying so a stale snapshot does not false-flag a successful unload', async () => {
|
||||
// Reproduces the Windows-WebUI bug: PipeWatcher's cached snapshot is
|
||||
// up to 1500ms stale, so right after a successful native unload the
|
||||
// pre-fix code would read isPipeLive() == true and report failure
|
||||
// even though the DLL is gone. With the fix, tickNow() refreshes
|
||||
// the snapshot first and verification correctly sees the pipe down.
|
||||
const pid = 5555;
|
||||
let pipeLive = true; // initial cached state: pipe is live
|
||||
const tickNow = vi.fn(async () => { pipeLive = false; }); // OS poll says: gone now
|
||||
|
||||
const session = new HookSession(pid, {
|
||||
injector: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: () => new FakeClient() as unknown as QqHookClient,
|
||||
pipeWatcher: { isPipeLive: () => pipeLive, tickNow },
|
||||
});
|
||||
await session.load();
|
||||
pipeLive = true; // ensure the pre-check snapshot says "live"
|
||||
|
||||
const info = await session.unload();
|
||||
|
||||
expect(tickNow).toHaveBeenCalledOnce();
|
||||
expect(info.status).toBe('available');
|
||||
expect(info.error).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookSession — serialization', () => {
|
||||
it('user mashing load → unload → load runs in order, end state consistent', async () => {
|
||||
const ctx = makeSession({ pipeLive: false });
|
||||
|
||||
const p1 = ctx.session.load();
|
||||
const p2 = ctx.session.unload();
|
||||
const p3 = ctx.session.load();
|
||||
await Promise.all([p1, p2, p3]);
|
||||
|
||||
expect(ctx.injector.inject).toHaveBeenCalledTimes(2);
|
||||
expect(ctx.injector.unload).toHaveBeenCalledTimes(1);
|
||||
expect(ctx.session.status).toBe('connecting');
|
||||
});
|
||||
|
||||
it('onPipeUp queued behind in-flight load resolves correctly', async () => {
|
||||
const ctx = makeSession({ pipeLive: true });
|
||||
|
||||
const loadPromise = ctx.session.load();
|
||||
ctx.session.onPipeUp(); // queued behind load
|
||||
|
||||
await loadPromise;
|
||||
await flush();
|
||||
|
||||
expect(ctx.session.status).toBe('loaded');
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookSession — process gone', () => {
|
||||
it('emits disconnected(true) then disposed when killed while logged in', async () => {
|
||||
const ctx = makeSession({ pipeLive: true });
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
|
||||
const events: string[] = [];
|
||||
ctx.session.on('disconnected', () => events.push('disconnected'));
|
||||
ctx.session.on('disposed', () => events.push('disposed'));
|
||||
|
||||
ctx.session.notifyProcessGone();
|
||||
await flush();
|
||||
|
||||
expect(events).toEqual(['disconnected', 'disposed']);
|
||||
expect(ctx.session.isDisposed).toBe(true);
|
||||
});
|
||||
|
||||
it('emits only disposed when killed before login', async () => {
|
||||
const ctx = makeSession({ pipeLive: true });
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
|
||||
const events: string[] = [];
|
||||
ctx.session.on('disconnected', () => events.push('disconnected'));
|
||||
ctx.session.on('disposed', () => events.push('disposed'));
|
||||
|
||||
ctx.session.notifyProcessGone();
|
||||
await flush();
|
||||
|
||||
expect(events).toEqual(['disposed']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookSession — packet forwarding', () => {
|
||||
// These tests cover the field-rename + filter logic that used to live
|
||||
// inside the deleted NtqqHandler.onHookPacket. Inlining it here means
|
||||
// we can exercise the transformation with a plain vi.fn() sink, no
|
||||
// event-emitter machinery required.
|
||||
|
||||
it('forwards parsed packets to onPacket sink with PacketInfo shape', async () => {
|
||||
const onPacket = vi.fn();
|
||||
const ctx = makeSession({ pipeLive: true, onPacket });
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
|
||||
ctx.currentClient().firePacket({
|
||||
seq: 42,
|
||||
error: 0,
|
||||
cmd: 'trpc.msg.olpush.OlPushService.MsgPush',
|
||||
uin: '10001',
|
||||
body: Buffer.from([0x01, 0x02, 0x03]),
|
||||
});
|
||||
|
||||
expect(onPacket).toHaveBeenCalledOnce();
|
||||
const pkt = onPacket.mock.calls[0]![0];
|
||||
expect(pkt).toMatchObject({
|
||||
pid: 1234,
|
||||
uin: '10001',
|
||||
serviceCmd: 'trpc.msg.olpush.OlPushService.MsgPush',
|
||||
seqId: 42,
|
||||
retCode: 0,
|
||||
fromClient: false,
|
||||
});
|
||||
expect(Buffer.isBuffer(pkt.body)).toBe(true);
|
||||
expect([...pkt.body]).toEqual([1, 2, 3]);
|
||||
});
|
||||
|
||||
it('falls back to session uin when packet.uin is empty', async () => {
|
||||
const onPacket = vi.fn();
|
||||
const ctx = makeSession({ pipeLive: true, onPacket });
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
|
||||
ctx.currentClient().firePacket({
|
||||
seq: 1, error: 0, cmd: 'foo', uin: '', body: Buffer.alloc(0),
|
||||
});
|
||||
|
||||
expect(onPacket.mock.calls[0]![0].uin).toBe('10001');
|
||||
});
|
||||
|
||||
it('drops packets received before login', async () => {
|
||||
const onPacket = vi.fn();
|
||||
const ctx = makeSession({ pipeLive: true, onPacket });
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
// No login fired yet.
|
||||
|
||||
ctx.currentClient().firePacket({
|
||||
seq: 1, error: 0, cmd: 'foo', uin: '10001', body: Buffer.alloc(0),
|
||||
});
|
||||
|
||||
expect(onPacket).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('drops packets whose uin is non-real ("0" / too short / non-numeric)', async () => {
|
||||
const onPacket = vi.fn();
|
||||
const ctx = makeSession({ pipeLive: true, onPacket });
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
|
||||
// Packet uin '0' falls back to session uin '10001' — that one passes.
|
||||
// Force a bad uin via the packet AND null out session uin by simulating
|
||||
// a logout? Simpler: send a packet with uin '42' (numeric but <5 chars).
|
||||
ctx.currentClient().firePacket({
|
||||
seq: 1, error: 0, cmd: 'foo', uin: '42', body: Buffer.alloc(0),
|
||||
});
|
||||
|
||||
expect(onPacket).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('is a no-op when no onPacket sink is provided', async () => {
|
||||
const ctx = makeSession({ pipeLive: true }); // no onPacket
|
||||
await ctx.session.load();
|
||||
ctx.session.onPipeUp();
|
||||
await flush();
|
||||
ctx.currentClient().fireLogin('10001');
|
||||
|
||||
// Should not throw / crash.
|
||||
ctx.currentClient().firePacket({
|
||||
seq: 1, error: 0, cmd: 'foo', uin: '10001', body: Buffer.from([7]),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,195 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { PipeWatcher } from '../src/pipe-watcher';
|
||||
import type { HookProcessBaseInfo } from '../src/injector';
|
||||
|
||||
function setupWatcher(initial: { processes: HookProcessBaseInfo[]; live: Set<number> }) {
|
||||
let processes = initial.processes;
|
||||
let live = initial.live;
|
||||
const watcher = new PipeWatcher({
|
||||
listProcesses: () => processes,
|
||||
// Defensively copy so the watcher can't mutate the test's reference.
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000, // disable the internal timer; tests drive ticks manually
|
||||
});
|
||||
return {
|
||||
watcher,
|
||||
setProcesses: (p: HookProcessBaseInfo[]) => { processes = p; },
|
||||
setLive: (s: Set<number>) => { live = s; },
|
||||
};
|
||||
}
|
||||
|
||||
type EventRow = [string, unknown];
|
||||
|
||||
function captureEvents(watcher: PipeWatcher): EventRow[] {
|
||||
const events: EventRow[] = [];
|
||||
watcher.on('process-discovered', info => events.push(['discovered', (info as HookProcessBaseInfo).pid]));
|
||||
watcher.on('process-gone', pid => events.push(['gone', pid]));
|
||||
watcher.on('pipe-up', pid => events.push(['up', pid]));
|
||||
watcher.on('pipe-down', pid => events.push(['down', pid]));
|
||||
return events;
|
||||
}
|
||||
|
||||
describe('PipeWatcher', () => {
|
||||
it('start() emits process-discovered + pipe-up for live PIDs on first tick', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set([1234]),
|
||||
});
|
||||
const events = captureEvents(ctx.watcher);
|
||||
await ctx.watcher.start();
|
||||
|
||||
expect(events).toEqual([
|
||||
['discovered', 1234],
|
||||
['up', 1234],
|
||||
]);
|
||||
expect(ctx.watcher.isPipeLive(1234)).toBe(true);
|
||||
expect(ctx.watcher.isProcessAlive(1234)).toBe(true);
|
||||
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('pipe-down emitted when a previously-live pipe disappears', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set([1234]),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
ctx.setLive(new Set());
|
||||
await ctx.watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([['down', 1234]]);
|
||||
expect(ctx.watcher.isPipeLive(1234)).toBe(false);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('process-gone + pipe-down both emitted (pipe-down first) when QQ.exe is killed with a live pipe', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set([1234]),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
ctx.setProcesses([]);
|
||||
ctx.setLive(new Set());
|
||||
await ctx.watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([
|
||||
['down', 1234],
|
||||
['gone', 1234],
|
||||
]);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('ignores live pipes whose process is not running', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [],
|
||||
live: new Set([9999]),
|
||||
});
|
||||
const events = captureEvents(ctx.watcher);
|
||||
await ctx.watcher.start();
|
||||
|
||||
expect(events).toEqual([]);
|
||||
expect(ctx.watcher.isPipeLive(9999)).toBe(false);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('emits pipe-up again after a pipe-down → pipe-up cycle', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set(),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
ctx.setLive(new Set([1234]));
|
||||
await ctx.watcher.tickNow();
|
||||
expect(events).toEqual([['up', 1234]]);
|
||||
|
||||
ctx.setLive(new Set());
|
||||
await ctx.watcher.tickNow();
|
||||
expect(events).toEqual([['up', 1234], ['down', 1234]]);
|
||||
|
||||
ctx.setLive(new Set([1234]));
|
||||
await ctx.watcher.tickNow();
|
||||
expect(events).toEqual([['up', 1234], ['down', 1234], ['up', 1234]]);
|
||||
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('does not double-emit on idempotent ticks (no state change)', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set([1234]),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
await ctx.watcher.tickNow();
|
||||
await ctx.watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([]);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('emits "tick" after every poll', async () => {
|
||||
const ctx = setupWatcher({ processes: [], live: new Set() });
|
||||
let ticks = 0;
|
||||
ctx.watcher.on('tick', () => { ticks++; });
|
||||
|
||||
await ctx.watcher.start();
|
||||
expect(ticks).toBe(1);
|
||||
|
||||
await ctx.watcher.tickNow();
|
||||
expect(ticks).toBe(2);
|
||||
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('wake() pulls the next tick forward', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set(),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
// Wait on 'tick' rather than guessing how many event-loop turns
|
||||
// setTimeout(0) needs (it's clamped to ~1ms and races setImmediate).
|
||||
const nextTick = new Promise<void>(resolve => ctx.watcher.once('tick', () => resolve()));
|
||||
ctx.setLive(new Set([1234]));
|
||||
ctx.watcher.wake();
|
||||
await nextTick;
|
||||
|
||||
expect(events).toEqual([['up', 1234]]);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('survives a throwing listProcesses without crashing the watcher', async () => {
|
||||
let processes: HookProcessBaseInfo[] = [];
|
||||
let live = new Set<number>();
|
||||
let shouldThrow = true;
|
||||
const watcher = new PipeWatcher({
|
||||
listProcesses: () => {
|
||||
if (shouldThrow) throw new Error('boom');
|
||||
return processes;
|
||||
},
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000,
|
||||
});
|
||||
|
||||
await watcher.start();
|
||||
expect(watcher.isProcessAlive(1234)).toBe(false);
|
||||
|
||||
shouldThrow = false;
|
||||
processes = [{ pid: 1234, name: 'QQ.exe', path: '' }];
|
||||
live = new Set([1234]);
|
||||
const events = captureEvents(watcher);
|
||||
await watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([['discovered', 1234], ['up', 1234]]);
|
||||
watcher.stop();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
import net from 'net';
|
||||
import { mkdtemp, rm, writeFile } from 'fs/promises';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { listLiveLinuxPipePids, QqHookClient } from '../src/qq-hook-client';
|
||||
|
||||
let tmpDir: string | null = null;
|
||||
|
||||
async function makeRuntimeDir(): Promise<string> {
|
||||
tmpDir = await mkdtemp(path.join(os.tmpdir(), 'snowluma-hook-'));
|
||||
return tmpDir;
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
if (!tmpDir) return;
|
||||
await rm(tmpDir, { recursive: true, force: true });
|
||||
tmpDir = null;
|
||||
});
|
||||
|
||||
describe('listLiveLinuxPipePids', () => {
|
||||
it('ignores stale-looking control socket names when the probe rejects them', async () => {
|
||||
const runtimeDir = await makeRuntimeDir();
|
||||
await writeFile(path.join(runtimeDir, 'mojo.55.control.sock'), '');
|
||||
await writeFile(path.join(runtimeDir, 'mojo.55.recv.sock'), '');
|
||||
|
||||
const pids = await listLiveLinuxPipePids(runtimeDir, async () => false);
|
||||
|
||||
expect([...pids]).toEqual([]);
|
||||
});
|
||||
|
||||
it('returns only connectable control sockets', async () => {
|
||||
const runtimeDir = await makeRuntimeDir();
|
||||
await writeFile(path.join(runtimeDir, 'mojo.55.control.sock'), '');
|
||||
await writeFile(path.join(runtimeDir, 'mojo.56.control.sock'), '');
|
||||
await writeFile(path.join(runtimeDir, 'mojo.56.recv.sock'), '');
|
||||
await writeFile(path.join(runtimeDir, 'mojo.not-a-pid.control.sock'), '');
|
||||
|
||||
const probe = vi.fn(async (socketPath: string) => socketPath.endsWith('mojo.56.control.sock'));
|
||||
const pids = await listLiveLinuxPipePids(runtimeDir, probe);
|
||||
|
||||
expect([...pids]).toEqual([56]);
|
||||
expect(probe).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe.skipIf(process.platform === 'win32')('QqHookClient — pipe close mid-send', () => {
|
||||
// Regression: when the control pipe closes while a send() is awaiting its
|
||||
// ack, rejectControlPending() rejects BOTH the ack and reply deferreds. The
|
||||
// reply is only `await`ed after the ack, so if the ack rejects first the
|
||||
// reply promise is rejected with NO awaiter — an UNHANDLED rejection that
|
||||
// crashes the Node process (Docker: supervisor restarts it ~1s later; on
|
||||
// Windows it just dies → "connection pipe closed", bot down). The .catch()
|
||||
// guard on each deferred prevents it; without the guard this test trips the
|
||||
// unhandledRejection assertion below.
|
||||
it('does not raise an unhandled rejection', async () => {
|
||||
const dir = await mkdtemp(path.join(os.tmpdir(), 'snowluma-pipe-'));
|
||||
const prevRuntimeDir = process.env.SNOWLUMA_HOOK_RUNTIME_DIR;
|
||||
process.env.SNOWLUMA_HOOK_RUNTIME_DIR = dir;
|
||||
|
||||
const PID = 778899;
|
||||
const helloFrame = (): Buffer => {
|
||||
const h = Buffer.alloc(40);
|
||||
h.writeUInt32LE(0x31504851, 0); // PIPE_MAGIC
|
||||
h.writeUInt16LE(1, 4); // PIPE_VERSION
|
||||
h.writeUInt16LE(1, 6); // PipeOp.hello
|
||||
h.writeBigUInt64LE(BigInt(PID), 32); // value0 = pid
|
||||
return h;
|
||||
};
|
||||
|
||||
let controlConn: net.Socket | null = null;
|
||||
const controlServer = net.createServer((sock) => { controlConn = sock; sock.write(helloFrame()); });
|
||||
const recvServer = net.createServer((sock) => { sock.write(helloFrame()); });
|
||||
await new Promise<void>((r) => controlServer.listen(path.join(dir, `mojo.${PID}.control.sock`), () => r()));
|
||||
await new Promise<void>((r) => recvServer.listen(path.join(dir, `mojo.${PID}.recv.sock`), () => r()));
|
||||
|
||||
const unhandled: unknown[] = [];
|
||||
const onUnhandled = (reason: unknown): void => { unhandled.push(reason); };
|
||||
process.on('unhandledRejection', onUnhandled);
|
||||
|
||||
const client = new QqHookClient(PID);
|
||||
client.on('error', () => { /* socket reset on destroy — ignore */ });
|
||||
try {
|
||||
await client.connectAll({ recv: true });
|
||||
|
||||
// Start a reply-expecting send, let it reach the in-flight (awaiting-ack)
|
||||
// state, then have the "hook" drop the pipe before it answers.
|
||||
const sent = client.send('noop', null, { wantReply: true, ackTimeoutMs: 1000, replyTimeoutMs: 1000 })
|
||||
.then(() => 'resolved' as const, (e: unknown) => e);
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
controlConn?.destroy();
|
||||
|
||||
const outcome = await sent;
|
||||
await new Promise((r) => setTimeout(r, 50)); // let Node surface any unhandled rejection
|
||||
|
||||
expect(outcome).toBeInstanceOf(Error);
|
||||
expect(unhandled, `unhandled rejections leaked: ${unhandled.map(String).join(', ')}`).toHaveLength(0);
|
||||
} finally {
|
||||
process.off('unhandledRejection', onUnhandled);
|
||||
client.close();
|
||||
await new Promise<void>((r) => controlServer.close(() => r()));
|
||||
await new Promise<void>((r) => recvServer.close(() => r()));
|
||||
if (prevRuntimeDir === undefined) delete process.env.SNOWLUMA_HOOK_RUNTIME_DIR;
|
||||
else process.env.SNOWLUMA_HOOK_RUNTIME_DIR = prevRuntimeDir;
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node"],
|
||||
"noEmit": true
|
||||
},
|
||||
"include": [
|
||||
"src/**/*"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ['tests/**/*.test.ts'],
|
||||
environment: 'node',
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"name": "@snowluma/common",
|
||||
"version": "1.9.11",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/protocol, @snowluma/core, and @snowluma/onebot. Per-file subpath exports keep import sites unambiguous and let the bundler tree-shake aggressively (importing `@snowluma/common/hex` doesn't pull in `node:fs` from the logger transport).",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"default": "./src/index.ts"
|
||||
},
|
||||
"./logger": {
|
||||
"types": "./src/logger.ts",
|
||||
"default": "./src/logger.ts"
|
||||
},
|
||||
"./hex": {
|
||||
"types": "./src/hex.ts",
|
||||
"default": "./src/hex.ts"
|
||||
},
|
||||
"./json": {
|
||||
"types": "./src/json.ts",
|
||||
"default": "./src/json.ts"
|
||||
},
|
||||
"./log-file-transport": {
|
||||
"types": "./src/log-file-transport.ts",
|
||||
"default": "./src/log-file-transport.ts"
|
||||
},
|
||||
"./log-summary": {
|
||||
"types": "./src/log-summary.ts",
|
||||
"default": "./src/log-summary.ts"
|
||||
},
|
||||
"./packet-sender": {
|
||||
"types": "./src/packet-sender.ts",
|
||||
"default": "./src/packet-sender.ts"
|
||||
},
|
||||
"./protocol-types": {
|
||||
"types": "./src/protocol-types.ts",
|
||||
"default": "./src/protocol-types.ts"
|
||||
},
|
||||
"./runtime": {
|
||||
"types": "./src/runtime.ts",
|
||||
"default": "./src/runtime.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.12.2",
|
||||
"typescript": "catalog:"
|
||||
}
|
||||
}
|
||||
@@ -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,6 @@
|
||||
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,118 @@
|
||||
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(' ');
|
||||
}
|
||||
|
||||
const VERBOSE_STRING_MAX = 200;
|
||||
const VERBOSE_TOTAL_MAX = 1500;
|
||||
// Keys whose values must never be rendered — tokens, passwords, secrets.
|
||||
const REDACT_KEY = /^(.*[-_])?(token|password|passwd|secret|access[-_]?token)([-_].*)?$/i;
|
||||
|
||||
/**
|
||||
* Deep, debug-grade render of a params object for the `trace` level: shows the
|
||||
* full nested structure (message segments, nested objects) so a reproduction
|
||||
* is legible — unlike {@link summarizeParams}, which collapses nested values.
|
||||
*
|
||||
* Three guards keep it safe and bounded:
|
||||
* - per-string cap (long values like base64 image data become `"…<N B>"`),
|
||||
* - total output budget (so a giant payload can't flood the buffer),
|
||||
* - key-based redaction (token / password / secret → `"***"`).
|
||||
*/
|
||||
export function renderParamsVerbose(params: unknown): string {
|
||||
const seen = new WeakSet<object>();
|
||||
let budget = VERBOSE_TOTAL_MAX;
|
||||
|
||||
const walk = (value: unknown, key?: string): string => {
|
||||
if (budget <= 0) return '…';
|
||||
if (key !== undefined && REDACT_KEY.test(key)) return '"***"';
|
||||
if (value === null) return 'null';
|
||||
if (value === undefined) return 'undefined';
|
||||
|
||||
switch (typeof value) {
|
||||
case 'string': {
|
||||
const truncated =
|
||||
value.length > VERBOSE_STRING_MAX
|
||||
? `${value.slice(0, VERBOSE_STRING_MAX)}…<${value.length}B>`
|
||||
: value;
|
||||
const out = JSON.stringify(truncated);
|
||||
budget -= out.length;
|
||||
return out;
|
||||
}
|
||||
case 'number':
|
||||
case 'boolean':
|
||||
case 'bigint': {
|
||||
const out = String(value);
|
||||
budget -= out.length;
|
||||
return out;
|
||||
}
|
||||
case 'object': {
|
||||
if (seen.has(value as object)) return '"[circular]"';
|
||||
seen.add(value as object);
|
||||
const parts: string[] = [];
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) {
|
||||
if (budget <= 0) { parts.push('…'); break; }
|
||||
parts.push(walk(item));
|
||||
}
|
||||
return `[${parts.join(',')}]`;
|
||||
}
|
||||
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
|
||||
if (budget <= 0) { parts.push('…'); break; }
|
||||
parts.push(`${k}:${walk(v, k)}`);
|
||||
}
|
||||
return `{${parts.join(',')}}`;
|
||||
}
|
||||
default:
|
||||
return typeof value;
|
||||
}
|
||||
};
|
||||
|
||||
return walk(params);
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
import { format } from 'util';
|
||||
import { getFileTransport } from './log-file-transport';
|
||||
import { currentRequestId } from './request-context';
|
||||
|
||||
type LogLevel = 'trace' | '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;
|
||||
/** Correlation id, when emitted inside a `runWithRequestId(...)` scope. */
|
||||
req?: 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> = {
|
||||
trace: 5,
|
||||
debug: 10,
|
||||
info: 20,
|
||||
success: 25,
|
||||
warn: 30,
|
||||
error: 40,
|
||||
};
|
||||
|
||||
const LEVEL_LABEL: Record<LogLevel, string> = {
|
||||
trace: 'TRACE',
|
||||
debug: 'DEBUG',
|
||||
info: 'INFO',
|
||||
success: 'OK',
|
||||
warn: 'WARN',
|
||||
error: 'ERROR',
|
||||
};
|
||||
|
||||
const COLOR_CODE: Record<LogLevel, number> = {
|
||||
trace: 90,
|
||||
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;
|
||||
|
||||
/** Trace ring cap — env-tunable since trace is the high-volume stream. */
|
||||
function resolveTraceBufferMax(): number {
|
||||
const raw = Number.parseInt(process.env.SNOWLUMA_TRACE_BUFFER ?? '', 10);
|
||||
return Number.isFinite(raw) && raw >= 100 ? raw : 5000;
|
||||
}
|
||||
const TRACE_BUFFER_MAX = resolveTraceBufferMax();
|
||||
|
||||
/**
|
||||
* Fixed-capacity circular buffer. O(1) push + eviction (no array `.shift()`),
|
||||
* so the high-throughput trace stream never pays an O(n) shift per overflow.
|
||||
*/
|
||||
class RingBuffer<T> {
|
||||
private readonly buf: (T | undefined)[];
|
||||
private start = 0;
|
||||
private count = 0;
|
||||
constructor(private readonly cap: number) {
|
||||
this.buf = new Array<T | undefined>(cap);
|
||||
}
|
||||
push(item: T): void {
|
||||
const end = (this.start + this.count) % this.cap;
|
||||
this.buf[end] = item;
|
||||
if (this.count < this.cap) this.count += 1;
|
||||
else this.start = (this.start + 1) % this.cap; // full → overwrite oldest
|
||||
}
|
||||
/** Most recent `n` items, oldest→newest. */
|
||||
recent(n: number): T[] {
|
||||
const take = Math.max(0, Math.min(Math.trunc(n), this.count));
|
||||
const out: T[] = new Array<T>(take);
|
||||
const first = this.start + (this.count - take);
|
||||
for (let i = 0; i < take; i += 1) out[i] = this.buf[(first + i) % this.cap]!;
|
||||
return out;
|
||||
}
|
||||
toArray(): T[] {
|
||||
return this.recent(this.count);
|
||||
}
|
||||
get size(): number {
|
||||
return this.count;
|
||||
}
|
||||
}
|
||||
|
||||
const logRing = new RingBuffer<LogEntry>(MAX_LOG_ENTRIES);
|
||||
const traceRing = new RingBuffer<LogEntry>(TRACE_BUFFER_MAX);
|
||||
const logSubscribers = new Set<(entry: LogEntry) => void>();
|
||||
let nextLogId = 1;
|
||||
|
||||
function resolveMinLevel(): LogLevel {
|
||||
const raw = (process.env.SNOWLUMA_LOG_LEVEL ?? 'info').toLowerCase();
|
||||
if (raw === 'trace' || 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[] = ['trace', '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[], reqId?: number): 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);
|
||||
const reqTag = reqId !== undefined ? `[req#${reqId}]` : '';
|
||||
|
||||
if (!useColor()) {
|
||||
return `${ts} ${label} ${uinSlot} [${options.scope}] ${reqTag ? `${reqTag} ` : ''}${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}]`);
|
||||
const cReq = reqTag ? `${ansi(COLOR_DIM, reqTag)} ` : '';
|
||||
return `${cTs} ${cLabel} ${cUin} ${cScope} ${cReq}${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);
|
||||
|
||||
// `trace` never touches disk and is the high-volume full-chain stream. When
|
||||
// it won't reach the console/memory buffer either (level not dialed to
|
||||
// trace), bail BEFORE format/render AND before evaluating any lazy producer
|
||||
// — this is what keeps full-chain tracing ~free at the default level even
|
||||
// with hundreds of groups.
|
||||
if (level === 'trace' && !passesConsole) return;
|
||||
|
||||
// Lazy trace form: `log.trace(() => ['…', deepRender(x)])`. The producer
|
||||
// (and its expensive deep render) only runs now that trace is confirmed live.
|
||||
let realArgs = args;
|
||||
if (level === 'trace' && args.length === 1 && typeof args[0] === 'function') {
|
||||
realArgs = (args[0] as () => unknown[])();
|
||||
}
|
||||
|
||||
const reqId = currentRequestId();
|
||||
const message = format(...realArgs);
|
||||
const line = render(level, options, realArgs, reqId);
|
||||
const entry: LogEntry = {
|
||||
id: nextLogId++,
|
||||
time: new Date().toISOString(),
|
||||
level,
|
||||
scope: options.scope,
|
||||
...(options.uin !== undefined ? { uin: options.uin } : {}),
|
||||
...(reqId !== undefined ? { req: reqId } : {}),
|
||||
message,
|
||||
line,
|
||||
};
|
||||
|
||||
if (passesConsole) {
|
||||
// Trace gets its own ring so its volume never evicts the normal log buffer.
|
||||
(level === 'trace' ? traceRing : logRing).push(entry);
|
||||
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 sees debug-and-up for post-mortem value; `trace` is
|
||||
// memory / WebUI only (omitted here to avoid huge on-disk volume). ANSI
|
||||
// stripping happens inside the transport. UIN routes the line to its
|
||||
// per-account sub-file in addition to the shared one.
|
||||
if (level !== 'trace') 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.trunc(limit));
|
||||
// Merge the normal + trace rings by id (ids are monotonic, so id order is
|
||||
// chronological). The trace ring is empty unless trace level is/was active,
|
||||
// so the common case is just the normal ring with no sort.
|
||||
const merged = traceRing.size > 0
|
||||
? [...logRing.toArray(), ...traceRing.toArray()].sort((a, b) => a.id - b.id)
|
||||
: logRing.toArray();
|
||||
return merged.slice(-n);
|
||||
}
|
||||
|
||||
export function subscribeLogs(callback: (entry: LogEntry) => void): () => void {
|
||||
logSubscribers.add(callback);
|
||||
return () => {
|
||||
logSubscribers.delete(callback);
|
||||
};
|
||||
}
|
||||
|
||||
export interface Logger {
|
||||
/**
|
||||
* High-volume, memory-only diagnostic level (never written to disk). Pass a
|
||||
* lazy producer — `trace(() => ['msg %s', expensiveRender(x)])` — so the
|
||||
* arguments (and any costly rendering) are built only when trace is active.
|
||||
* A plain `trace('msg', x)` works too but evaluates its args eagerly.
|
||||
*/
|
||||
trace: (...args: unknown[]) => void;
|
||||
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 {
|
||||
trace: (...args: unknown[]) => emit('trace', opts, args),
|
||||
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 });
|
||||
}
|
||||
|
||||
// Request-correlation helpers live alongside the logger since `[req#N]`
|
||||
// stamping is a logging concern. Re-exported here so callers import the
|
||||
// whole logging surface from one place.
|
||||
export { nextRequestId, runWithRequestId, currentRequestId } from './request-context';
|
||||
File renamed without changes.
@@ -8,3 +8,4 @@ export interface PacketInfo {
|
||||
fromClient: boolean;
|
||||
body: Uint8Array;
|
||||
}
|
||||
export type PacketSink = (packet: PacketInfo) => void;
|
||||
@@ -0,0 +1,35 @@
|
||||
import { AsyncLocalStorage } from 'async_hooks';
|
||||
|
||||
interface RequestStore {
|
||||
id: number;
|
||||
}
|
||||
|
||||
const storage = new AsyncLocalStorage<RequestStore>();
|
||||
let counter = 0;
|
||||
|
||||
/**
|
||||
* Allocate the next per-process request id (monotonic). Wraps via uint32 so
|
||||
* it never overflows to a non-integer; `0` is skipped so "no id" stays
|
||||
* unambiguous.
|
||||
*/
|
||||
export function nextRequestId(): number {
|
||||
counter = (counter + 1) >>> 0;
|
||||
if (counter === 0) counter = 1;
|
||||
return counter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run `fn` with `id` bound as the ambient request id for the entire async
|
||||
* chain it spawns. Any logger call anywhere in that chain — across packages,
|
||||
* across awaits — picks it up via {@link currentRequestId} with no signature
|
||||
* threading. Used by the OneBot action handler to correlate a request's whole
|
||||
* journey (entry → outbound packets → exit) under one `[req#N]` tag.
|
||||
*/
|
||||
export function runWithRequestId<T>(id: number, fn: () => T): T {
|
||||
return storage.run({ id }, fn);
|
||||
}
|
||||
|
||||
/** The request id bound to the current async context, or undefined outside one. */
|
||||
export function currentRequestId(): number | undefined {
|
||||
return storage.getStore()?.id;
|
||||
}
|
||||
@@ -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.11",
|
||||
"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/protocol": "workspace:*",
|
||||
"@snowluma/proto-defs": "workspace:*",
|
||||
"@snowluma/proton": "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.21",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "catalog:",
|
||||
"vite": "catalog:",
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
import { FetchDownloadRkeys } from '@snowluma/protocol/oidb-services/contacts/fetch-download-rkeys';
|
||||
import { FetchFriendListPage } from '@snowluma/protocol/oidb-services/contacts/fetch-friend-list-page';
|
||||
import { FetchGroupList } from '@snowluma/protocol/oidb-services/contacts/fetch-group-list';
|
||||
import { FetchGroupMemberListPage } from '@snowluma/protocol/oidb-services/contacts/fetch-group-member-list-page';
|
||||
import { FetchGroupRequests } from '@snowluma/protocol/oidb-services/contacts/fetch-group-requests';
|
||||
import { FetchUserProfile } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile';
|
||||
import { FetchUserProfileByUid } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile-by-uid';
|
||||
import type {
|
||||
FriendInfo,
|
||||
GroupMemberInfo,
|
||||
GroupRequestInfo,
|
||||
QQGroupInfo,
|
||||
UserProfileInfo,
|
||||
} from '@snowluma/protocol/qq-info';
|
||||
import type { DownloadRKeyInfo } from '../bridge';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
// ─── Helpers (previously in bridge-contacts.ts) ───────────────────
|
||||
|
||||
type FriendPropertySource = {
|
||||
additional?: Array<{
|
||||
type?: number;
|
||||
layer1?: {
|
||||
properties?: Array<{
|
||||
code?: number;
|
||||
value?: string;
|
||||
}>;
|
||||
};
|
||||
}>;
|
||||
};
|
||||
|
||||
export function buildFriendProperties(raw: FriendPropertySource): Map<number, string> {
|
||||
const props = new Map<number, string>();
|
||||
for (const additional of raw.additional ?? []) {
|
||||
if ((additional.type ?? 0) !== 1 || !additional.layer1) continue;
|
||||
for (const property of additional.layer1.properties ?? []) {
|
||||
props.set(property.code ?? 0, property.value ?? '');
|
||||
}
|
||||
}
|
||||
return props;
|
||||
}
|
||||
|
||||
export function permissionToRole(permission: number): string {
|
||||
switch (permission) {
|
||||
case 1: return 'owner';
|
||||
case 2: return 'admin';
|
||||
default: return 'member';
|
||||
}
|
||||
}
|
||||
|
||||
const MEMBER_LIST_TTL_MS = 60_000;
|
||||
|
||||
export class ContactsApi {
|
||||
/**
|
||||
* Per-group inflight + last-fetch cache for `fetchGroupMemberList`.
|
||||
* Keyed by groupId, lives for the lifetime of the Bridge.
|
||||
*
|
||||
* Without this, a busy OneBot client (e.g. MaiBot calling
|
||||
* `get_group_member_info` once per inbound message) triggers one
|
||||
* OIDB 0xfe7_3 per chat message — sustained >1k/h, which trips
|
||||
* Tencent risk-control and gets the account banned for 7 days.
|
||||
*/
|
||||
private memberListInflight = new Map<number, Promise<GroupMemberInfo[]>>();
|
||||
private memberListLastFetch = new Map<number, { at: number; data: GroupMemberInfo[] }>();
|
||||
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
|
||||
async fetchFriendList(): Promise<FriendInfo[]> {
|
||||
const friends: FriendInfo[] = [];
|
||||
let nextUin: number | null = null;
|
||||
do {
|
||||
const resp = await FetchFriendListPage.invoke(this.ctx, { nextUin });
|
||||
for (const raw of resp.friends ?? []) {
|
||||
const props = buildFriendProperties(raw);
|
||||
friends.push({
|
||||
uin: raw.uin ?? 0,
|
||||
uid: raw.uid ?? '',
|
||||
nickname: props.get(20002) ?? String(raw.uin ?? 0),
|
||||
remark: props.get(103) ?? '',
|
||||
});
|
||||
}
|
||||
nextUin = resp.next?.uin ?? null;
|
||||
if (nextUin === 0) nextUin = null;
|
||||
} while (nextUin !== null);
|
||||
|
||||
this.ctx.identity.rememberFriends(friends);
|
||||
return friends;
|
||||
}
|
||||
|
||||
async fetchGroupList(): Promise<QQGroupInfo[]> {
|
||||
const resp = await FetchGroupList.invoke(this.ctx);
|
||||
const groups: QQGroupInfo[] = [];
|
||||
for (const raw of resp.groups ?? []) {
|
||||
groups.push({
|
||||
groupId: raw.groupUin ?? 0,
|
||||
groupName: raw.info?.groupName ?? '',
|
||||
remark: raw.customInfo?.remark ?? '',
|
||||
memberCount: raw.info?.memberCount ?? 0,
|
||||
memberMax: raw.info?.memberMax ?? 0,
|
||||
members: new Map(),
|
||||
});
|
||||
}
|
||||
this.ctx.identity.rememberGroups(groups);
|
||||
return groups;
|
||||
}
|
||||
|
||||
async fetchGroupMemberList(
|
||||
groupId: number,
|
||||
options: { force?: boolean } = {},
|
||||
): Promise<GroupMemberInfo[]> {
|
||||
const now = Date.now();
|
||||
const last = this.memberListLastFetch.get(groupId);
|
||||
if (!options.force && last && now - last.at < MEMBER_LIST_TTL_MS) {
|
||||
return last.data;
|
||||
}
|
||||
const inflight = this.memberListInflight.get(groupId);
|
||||
if (inflight) return inflight;
|
||||
const task = (async () => {
|
||||
try {
|
||||
const data = await this.fetchGroupMemberListUncached(groupId);
|
||||
this.memberListLastFetch.set(groupId, { at: Date.now(), data });
|
||||
return data;
|
||||
} finally {
|
||||
this.memberListInflight.delete(groupId);
|
||||
}
|
||||
})();
|
||||
this.memberListInflight.set(groupId, task);
|
||||
return task;
|
||||
}
|
||||
|
||||
private async fetchGroupMemberListUncached(groupId: number): Promise<GroupMemberInfo[]> {
|
||||
const members: GroupMemberInfo[] = [];
|
||||
let token = '';
|
||||
do {
|
||||
const resp = await FetchGroupMemberListPage.invoke(this.ctx, { groupId, token });
|
||||
for (const raw of resp.members ?? []) {
|
||||
members.push({
|
||||
uin: raw.uin?.uin ?? 0,
|
||||
uid: raw.uin?.uid ?? '',
|
||||
nickname: raw.memberName ?? '',
|
||||
card: raw.memberCard?.memberCard ?? '',
|
||||
role: permissionToRole(raw.permission ?? 0),
|
||||
level: raw.level?.level ?? 0,
|
||||
title: raw.specialTitle ?? '',
|
||||
joinTime: raw.joinTimestamp ?? 0,
|
||||
lastSentTime: raw.lastMsgTimestamp ?? 0,
|
||||
shutUpTime: raw.shutUpTimestamp ?? 0,
|
||||
});
|
||||
}
|
||||
token = resp.token ?? '';
|
||||
} while (token);
|
||||
|
||||
this.ctx.identity.rememberGroupMembers(groupId, members);
|
||||
return members;
|
||||
}
|
||||
|
||||
async fetchUserProfile(uin: number): Promise<UserProfileInfo> {
|
||||
const info = await FetchUserProfile.invoke(this.ctx, { uin });
|
||||
this.ctx.identity.rememberUserProfile(info);
|
||||
return info;
|
||||
}
|
||||
|
||||
/** Look up a user profile by UID (string form). Used for strangers
|
||||
* whose UIN we don't have yet — typically the requester on a
|
||||
* group join request push. Mirrors Lagrange's `FetchUserInfoEvent
|
||||
* .Create(targetUid)` path. */
|
||||
async fetchUserProfileByUid(uid: string): Promise<UserProfileInfo> {
|
||||
const info = await FetchUserProfileByUid.invoke(this.ctx, { uid });
|
||||
if (info.uin > 0) this.ctx.identity.rememberUserProfile(info);
|
||||
return info;
|
||||
}
|
||||
|
||||
async fetchGroupRequests(filtered = false): Promise<GroupRequestInfo[]> {
|
||||
const resp = await FetchGroupRequests.invoke(this.ctx, { filtered });
|
||||
const requests: GroupRequestInfo[] = [];
|
||||
for (const raw of resp.requests ?? []) {
|
||||
requests.push({
|
||||
groupId: raw.group?.groupUin ?? 0,
|
||||
groupName: raw.group?.groupName ?? '',
|
||||
targetUid: raw.target?.uid ?? '',
|
||||
targetUin: 0,
|
||||
targetName: raw.target?.name ?? '',
|
||||
invitorUid: raw.invitor?.uid ?? '',
|
||||
invitorUin: 0,
|
||||
invitorName: raw.invitor?.name ?? '',
|
||||
operatorUid: raw.operatorUser?.uid ?? '',
|
||||
operatorUin: 0,
|
||||
operatorName: raw.operatorUser?.name ?? '',
|
||||
sequence: Number(raw.sequence ?? 0),
|
||||
state: raw.state ?? 0,
|
||||
eventType: raw.eventType ?? 0,
|
||||
comment: raw.comment ?? '',
|
||||
filtered,
|
||||
});
|
||||
}
|
||||
this.ctx.identity.rememberGroupRequests(requests);
|
||||
return requests;
|
||||
}
|
||||
|
||||
async fetchDownloadRKeys(): Promise<DownloadRKeyInfo[]> {
|
||||
const resp = await FetchDownloadRkeys.invoke(this.ctx);
|
||||
|
||||
const result: DownloadRKeyInfo[] = [];
|
||||
for (const entry of resp.downloadRkey?.rkeys ?? []) {
|
||||
const rkey = entry.rkey ?? '';
|
||||
const type = entry.type ?? 0;
|
||||
if (rkey && type) {
|
||||
result.push({
|
||||
rkey,
|
||||
ttlSeconds: Number(entry.rkeyTtlSec ?? 0),
|
||||
storeId: entry.storeId ?? 0,
|
||||
createTime: entry.rkeyCreateTime ?? 0,
|
||||
type,
|
||||
});
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
import { FetchAiVoice } from '@snowluma/protocol/oidb-services/extras/fetch-ai-voice';
|
||||
import {
|
||||
FetchAiVoiceList,
|
||||
type AiVoiceCategory as NamespaceAiVoiceCategory,
|
||||
} from '@snowluma/protocol/oidb-services/extras/fetch-ai-voice-list';
|
||||
import { GetStrangerStatus, type StrangerStatus as NamespaceStrangerStatus } from '@snowluma/protocol/oidb-services/extras/get-stranger-status';
|
||||
import { GroupTodo } from '@snowluma/protocol/oidb-services/extras/group-todo';
|
||||
import type { PttTransReq, PttTransResp } from '@snowluma/proto-defs/ptt-trans';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import type { MediaIndexNode } from './shared';
|
||||
|
||||
/** Inputs for a voice-to-text request, gathered from the received `record`
|
||||
* element + its message meta. `uuid`/`md5Hex` come from the cached record;
|
||||
* the uins + scene from the message meta. */
|
||||
export interface PttTransInput {
|
||||
isGroup: boolean;
|
||||
msgId: number;
|
||||
senderUin: number;
|
||||
/** Receiver uin (c2c) or group uin (group). */
|
||||
peerUin: number;
|
||||
uuid: string;
|
||||
md5Hex: string;
|
||||
duration: number;
|
||||
size: number;
|
||||
format: number;
|
||||
/** Group ptt numeric file id (group only; optional). */
|
||||
fileId?: number;
|
||||
}
|
||||
|
||||
function hexToBytes(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;
|
||||
}
|
||||
|
||||
// ─────────────── public types (re-exported from bridge.ts as before) ───
|
||||
|
||||
export type StrangerStatus = NamespaceStrangerStatus;
|
||||
|
||||
export const AiVoiceChatType = {
|
||||
Unknown: 0,
|
||||
Sound: 1,
|
||||
Sing: 2,
|
||||
} as const;
|
||||
export type AiVoiceChatType = typeof AiVoiceChatType[keyof typeof AiVoiceChatType];
|
||||
|
||||
export type AiVoiceCategory = NamespaceAiVoiceCategory;
|
||||
export interface AiVoiceItem {
|
||||
voiceId: string;
|
||||
voiceDisplayName: string;
|
||||
voiceExampleUrl: string;
|
||||
}
|
||||
|
||||
export class ExtrasApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
|
||||
// ─────────────── Group todo (0xF90) ───────────────
|
||||
|
||||
setGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
|
||||
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'set' });
|
||||
}
|
||||
|
||||
completeGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
|
||||
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'complete' });
|
||||
}
|
||||
|
||||
cancelGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
|
||||
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'cancel' });
|
||||
}
|
||||
|
||||
// ─────────────── Stranger online/ext status (0xFE1_2) ───────────────
|
||||
|
||||
/**
|
||||
* Returns `null` on transport / decode failure rather than throwing,
|
||||
* so the OneBot action can produce a clean retcode without try/catch
|
||||
* gymnastics. Namespace throws on transport failure → swallow here.
|
||||
*/
|
||||
async getStrangerStatus(uin: number): Promise<StrangerStatus | null> {
|
||||
try {
|
||||
return await GetStrangerStatus.invoke(this.ctx, { uin });
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────── AI voice (0x929D / 0x929B) ───────────────
|
||||
|
||||
fetchAiVoiceList(groupId: number, chatType: AiVoiceChatType | number): Promise<AiVoiceCategory[]> {
|
||||
return FetchAiVoiceList.invoke(this.ctx, { groupId, chatType });
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger AI voice synthesis. Server may return an empty msgInfo while
|
||||
* the render is in-flight; we retry until a node materialises or the
|
||||
* cap is hit. napcat uses the same 30-retry budget.
|
||||
*
|
||||
* The returned MediaIndexNode plugs directly into
|
||||
* `apis.groupFile.getPttUrl`, which already handles every other
|
||||
* download-URL fetch in SnowLuma.
|
||||
*/
|
||||
async fetchAiVoice(
|
||||
groupId: number,
|
||||
voiceId: string,
|
||||
text: string,
|
||||
chatType: AiVoiceChatType | number,
|
||||
maxRetries = 30,
|
||||
): Promise<MediaIndexNode> {
|
||||
// Random 32-bit session id — server uses this to deduplicate polls.
|
||||
const sessionId = Math.floor(Math.random() * 0xFFFFFFFF) >>> 0;
|
||||
for (let i = 0; i < maxRetries; i++) {
|
||||
const node = await FetchAiVoice.invoke(this.ctx, { groupId, voiceId, text, chatType, sessionId });
|
||||
if (node) return node as MediaIndexNode;
|
||||
}
|
||||
throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`);
|
||||
}
|
||||
|
||||
// ─────────────── Voice-to-text (pttTrans.Trans{C2C,Group}PttReq) ───────────────
|
||||
|
||||
/**
|
||||
* Send ONE `pttTrans.Trans{C2C,Group}PttReq` to trigger transcription and
|
||||
* return the recognised text IF the response carries it inline (the
|
||||
* already-transcribed case). For a freshly-received voice the response is an
|
||||
* empty ack and the text is delivered later via the async Event 0x210
|
||||
* subType-61 push — callers should treat `''` as "pending" and wait for the
|
||||
* `ptt_trans_result` event (correlated by msgId). Live-verified end to end.
|
||||
*/
|
||||
async translatePttToText(input: PttTransInput): Promise<string> {
|
||||
const md5 = hexToBytes(input.md5Hex);
|
||||
const req: PttTransReq = input.isGroup
|
||||
? {
|
||||
type: 1,
|
||||
groupItem: {
|
||||
msgId: BigInt(input.msgId), senderUin: BigInt(input.senderUin), groupUin: BigInt(input.peerUin),
|
||||
fileId: input.fileId ?? 0, md5, duration: input.duration, size: input.size,
|
||||
format: input.format, uuid: input.uuid,
|
||||
},
|
||||
}
|
||||
: {
|
||||
type: 2,
|
||||
c2cItem: {
|
||||
msgId: BigInt(input.msgId), senderUin: BigInt(input.senderUin), receiverUin: BigInt(input.peerUin),
|
||||
uuid: input.uuid, duration: input.duration, size: input.size, format: input.format, md5,
|
||||
},
|
||||
};
|
||||
const cmd = input.isGroup ? 'pttTrans.TransGroupPttReq' : 'pttTrans.TransC2CPttReq';
|
||||
|
||||
const result = await this.ctx.sendRawPacket(cmd, protobuf_encode<PttTransReq>(req));
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'ptt translate request failed');
|
||||
}
|
||||
const resp = protobuf_decode<PttTransResp>(result.responseData);
|
||||
const item = input.isGroup ? resp?.groupResult : resp?.c2cResult;
|
||||
if (item?.errCode) throw new Error(`ptt translate failed: error=${item.errCode}`);
|
||||
return item?.text ?? ''; // '' = transcribing async; caller awaits the push
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,562 @@
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import type {
|
||||
LongMsgResult,
|
||||
RecvLongMsgReq,
|
||||
RecvLongMsgResp,
|
||||
SendLongMsgReq,
|
||||
SendLongMsgResp,
|
||||
} from '@snowluma/proto-defs/longmsg';
|
||||
import type { FileExtra, PushMsg, PushMsgBody } from '@snowluma/proto-defs/message';
|
||||
import { buildSendElems } from '@snowluma/protocol/element-builder';
|
||||
import type { ForwardNodePayload, MessageElement } from '@snowluma/protocol/events';
|
||||
import { parseMsgPush } from '@snowluma/protocol/msg-push';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { gunzipSync, gzipSync } from 'zlib';
|
||||
import type { Bridge } from '../bridge';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
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`.
|
||||
//
|
||||
// CRITICAL: the same uuid (`inner.uuid`) MUST be baked into the
|
||||
// outer's preview element as `forwardUuid` AND used as the
|
||||
// `actionCommand` for the outer's piggyback entry. That's the
|
||||
// alignment the QQ-NT receiver uses to find the inner layer
|
||||
// inside the outer's LongMsgResult without a second server fetch
|
||||
// — see `dev/NapCatQQ/.../SendMsg.ts:241-246` + the `uniseq` round-
|
||||
// trip in `dev/NapCatQQ/.../forward-msg-builder.ts:94`.
|
||||
const myInnerActions: ForwardInnerAction[] = [];
|
||||
const processedNodes: ForwardNodePayload[] = [];
|
||||
const isGroup = groupId !== undefined;
|
||||
for (const node of nodes) {
|
||||
if (node.innerForward && node.innerForward.length > 0) {
|
||||
const inner = await this.uploadRecursive(node.innerForward, groupId, userId);
|
||||
// NapCat piggybacks `{uuid: inner.uuid, packetMsg: inner.packetMsg}`
|
||||
// + the entire `inner.innerPacketMsg` array up to its caller. We
|
||||
// mirror that — `inner.uuid` indexes the inner level itself,
|
||||
// and `inner.innerActions` already contains deeper layers.
|
||||
myInnerActions.push({ uuid: inner.uuid, msgBody: inner.msgBody });
|
||||
myInnerActions.push(...inner.innerActions);
|
||||
// Replace the inner placeholder element with a forward preview
|
||||
// pointing at the inner res_id. `forwardUuid: inner.uuid`
|
||||
// baked into the LightApp JSON's `meta.detail.uniseq` is what
|
||||
// closes the loop with our piggyback action above.
|
||||
const previewElement: MessageElement = {
|
||||
type: 'forward',
|
||||
resId: inner.resId,
|
||||
forwardUuid: inner.uuid,
|
||||
forwardSource: deriveInnerSource(node.innerForward, isGroup),
|
||||
forwardSummary: `查看${node.innerForward.length}条转发消息`,
|
||||
forwardPrompt: '[聊天记录]',
|
||||
forwardNews: previewLinesFromNodes(node.innerForward),
|
||||
forwardTSum: node.innerForward.length,
|
||||
};
|
||||
processedNodes.push({
|
||||
userUin: node.userUin,
|
||||
nickname: node.nickname,
|
||||
elements: [previewElement],
|
||||
time: node.time,
|
||||
msgId: node.msgId,
|
||||
msgSeq: node.msgSeq,
|
||||
groupId: node.groupId,
|
||||
senderCard: node.senderCard,
|
||||
messageType: node.messageType,
|
||||
});
|
||||
} else {
|
||||
processedNodes.push(node);
|
||||
}
|
||||
}
|
||||
|
||||
// Encode this level's msgBody.
|
||||
const msgBody = await Promise.all(processedNodes.map(
|
||||
node => buildForwardPushBody(bridge, node, groupId, userUid),
|
||||
));
|
||||
|
||||
// Compose the action list: own MultiMsg + piggybacked inner actions.
|
||||
const longMsgResult = protobuf_encode<LongMsgResult>({
|
||||
action: [
|
||||
{ actionCommand: 'MultiMsg', actionData: { msgBody } },
|
||||
...myInnerActions.map(a => ({
|
||||
actionCommand: a.uuid,
|
||||
actionData: { msgBody: a.msgBody },
|
||||
})),
|
||||
],
|
||||
});
|
||||
|
||||
const selfUid = await resolveSelfUid(bridge);
|
||||
const info: SendLongMsgReq['info'] = {
|
||||
type: groupId ? 3 : 1,
|
||||
uid: { uid: groupId ? String(groupId) : selfUid },
|
||||
payload: gzipSync(Buffer.from(longMsgResult)),
|
||||
};
|
||||
if (groupId) info.groupUin = groupId;
|
||||
|
||||
const request = protobuf_encode<SendLongMsgReq>({
|
||||
info,
|
||||
settings: {
|
||||
field1: 4,
|
||||
field2: 1,
|
||||
field3: 7,
|
||||
field4: 0,
|
||||
},
|
||||
});
|
||||
|
||||
const result = await this.ctx.sendRawPacket('trpc.group.long_msg_interface.MsgService.SsoSendLongMsg', request);
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'upload forward message failed');
|
||||
}
|
||||
|
||||
const resp = protobuf_decode<SendLongMsgResp>(result.responseData);
|
||||
const resId = typeof resp?.result?.resId === 'string' ? resp.result.resId : '';
|
||||
if (!resId) {
|
||||
throw new Error('upload forward message response missing res_id');
|
||||
}
|
||||
|
||||
forwardResCache.set(resId, processedNodes.map(node => ({
|
||||
userUin: node.userUin,
|
||||
nickname: node.nickname,
|
||||
elements: [...node.elements],
|
||||
time: node.time,
|
||||
msgId: node.msgId,
|
||||
msgSeq: node.msgSeq,
|
||||
groupId: node.groupId ?? groupId,
|
||||
senderCard: node.senderCard,
|
||||
messageType: node.messageType ?? (groupId ? 'group' : 'private'),
|
||||
})));
|
||||
|
||||
return {
|
||||
resId,
|
||||
msgBody,
|
||||
// UUID generated here so the OUTER caller can use it as both
|
||||
// (1) the `actionCommand` for its piggyback entry carrying our
|
||||
// msgBody, and
|
||||
// (2) the `forwardUuid` baked into its forward-preview element
|
||||
// pointing at our resId.
|
||||
// Receivers walking the outer's LongMsgResult find the inner
|
||||
// layer by matching `uniseq` from (2) against `actionCommand`
|
||||
// from (1) — no separate fetch needed.
|
||||
uuid: randomUUID(),
|
||||
innerActions: myInnerActions,
|
||||
};
|
||||
}
|
||||
|
||||
async fetch(resId: string): Promise<ForwardNodePayload[]> {
|
||||
const bridge = 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 actions = Array.isArray(longMsg?.action) ? longMsg!.action! : [];
|
||||
const mainAction = actions.find(item => item?.actionCommand === 'MultiMsg');
|
||||
const msgBodyList = Array.isArray(mainAction?.actionData?.msgBody) ? mainAction!.actionData!.msgBody : [];
|
||||
|
||||
// Piggyback index: any non-`MultiMsg` action carries an inner
|
||||
// layer keyed by the uuid the sender baked into its forward
|
||||
// preview's `uniseq`. Build a lookup so we can resolve inner
|
||||
// forwards (via their uniseq → inner msgBody) without a second
|
||||
// server roundtrip — matches the sender-side piggyback emitted in
|
||||
// `uploadRecursive` above.
|
||||
const piggybackByUuid = new Map<string, PushMsgBody[]>();
|
||||
for (const action of actions) {
|
||||
const cmd = action?.actionCommand;
|
||||
if (!cmd || cmd === 'MultiMsg') continue;
|
||||
const body = Array.isArray(action.actionData?.msgBody) ? action.actionData.msgBody : [];
|
||||
piggybackByUuid.set(cmd, body);
|
||||
}
|
||||
|
||||
const nodes = this.decodeMsgBodiesToNodes(msgBodyList);
|
||||
|
||||
// Walk the decoded outer nodes for inner-forward previews
|
||||
// (`type: 'forward', forwardUuid: <uniseq>`). For each, pull the
|
||||
// matching piggyback body, decode it into inner nodes, and seed
|
||||
// the cache by the inner resId so a follow-up `fetch(innerResId)`
|
||||
// hits the cache instead of the wire.
|
||||
if (piggybackByUuid.size > 0) {
|
||||
this.consumePiggybacks(nodes, piggybackByUuid);
|
||||
}
|
||||
|
||||
if (nodes.length > 0) {
|
||||
forwardResCache.set(resId, cloneNodes(nodes));
|
||||
}
|
||||
return nodes;
|
||||
}
|
||||
|
||||
/** Walk a list of PushMsgBody, run each through the regular msg-push
|
||||
* pipeline, and shape the result into ForwardNodePayloads. Extracted
|
||||
* so both the outer + piggyback decode paths share one implementation. */
|
||||
private decodeMsgBodiesToNodes(msgBodyList: PushMsgBody[]): ForwardNodePayload[] {
|
||||
const out: ForwardNodePayload[] = [];
|
||||
for (const msgBody of msgBodyList) {
|
||||
const wrapped = protobuf_encode<PushMsg>({ message: msgBody });
|
||||
const pkt: PacketInfo = {
|
||||
pid: 0,
|
||||
uin: this.ctx.identity.uin,
|
||||
serviceCmd: 'trpc.msg.olpush.OlPushService.MsgPush',
|
||||
seqId: 0,
|
||||
retCode: 0,
|
||||
fromClient: false,
|
||||
body: wrapped,
|
||||
};
|
||||
const events = parseMsgPush(pkt, this.ctx.identity);
|
||||
const event = events.find(e =>
|
||||
e.kind === 'friend_message' || e.kind === 'group_message' || e.kind === 'temp_message');
|
||||
if (!event) continue;
|
||||
|
||||
if (event.kind === 'group_message') {
|
||||
out.push({
|
||||
userUin: event.senderUin,
|
||||
nickname: event.senderCard || event.senderNick,
|
||||
elements: event.elements,
|
||||
time: event.time,
|
||||
msgId: event.msgId,
|
||||
msgSeq: event.msgSeq,
|
||||
groupId: event.groupId,
|
||||
senderCard: event.senderCard,
|
||||
messageType: 'group',
|
||||
});
|
||||
} else if (event.kind === 'friend_message') {
|
||||
out.push({
|
||||
userUin: event.senderUin,
|
||||
nickname: event.senderNick,
|
||||
elements: event.elements,
|
||||
time: event.time,
|
||||
msgId: event.msgId,
|
||||
msgSeq: event.msgSeq,
|
||||
messageType: 'private',
|
||||
});
|
||||
} else {
|
||||
out.push({
|
||||
userUin: event.senderUin,
|
||||
nickname: event.senderNick,
|
||||
elements: event.elements,
|
||||
time: event.time,
|
||||
msgSeq: event.msgSeq,
|
||||
groupId: event.groupId,
|
||||
messageType: 'private',
|
||||
});
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Recursively resolve forward previews against the piggyback table.
|
||||
* For every `{type: 'forward', resId, forwardUuid}` element we find,
|
||||
* look up the uniseq in the piggyback map; if hit, decode the
|
||||
* inner msgBody and cache it by inner resId, then descend into that
|
||||
* inner layer to resolve deeper nestings carried in the SAME
|
||||
* piggyback set (NapCat hoists the entire tree's piggybacks onto
|
||||
* the outermost action list). */
|
||||
private consumePiggybacks(
|
||||
nodes: ForwardNodePayload[],
|
||||
piggybackByUuid: Map<string, PushMsgBody[]>,
|
||||
): void {
|
||||
const seen = new Set<string>();
|
||||
const visit = (chain: ForwardNodePayload[]): void => {
|
||||
for (const node of chain) {
|
||||
for (const elem of node.elements) {
|
||||
if (elem.type !== 'forward') continue;
|
||||
const uuid = elem.forwardUuid;
|
||||
const innerResId = elem.resId;
|
||||
if (!uuid || !innerResId || seen.has(uuid)) continue;
|
||||
const body = piggybackByUuid.get(uuid);
|
||||
if (!body) continue;
|
||||
seen.add(uuid);
|
||||
const innerNodes = this.decodeMsgBodiesToNodes(body);
|
||||
forwardResCache.set(innerResId, cloneNodes(innerNodes));
|
||||
visit(innerNodes);
|
||||
}
|
||||
}
|
||||
};
|
||||
visit(nodes);
|
||||
}
|
||||
}
|
||||
|
||||
function cloneNodes(nodes: ForwardNodePayload[]): ForwardNodePayload[] {
|
||||
return nodes.map(node => ({
|
||||
userUin: node.userUin,
|
||||
nickname: node.nickname,
|
||||
elements: [...node.elements],
|
||||
time: node.time,
|
||||
msgId: node.msgId,
|
||||
msgSeq: node.msgSeq,
|
||||
groupId: node.groupId,
|
||||
senderCard: node.senderCard,
|
||||
messageType: node.messageType,
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { DeleteFriend } from '@snowluma/protocol/oidb-services/friend/delete-friend';
|
||||
import { HandleFriendRequest } from '@snowluma/protocol/oidb-services/friend/handle-friend-request';
|
||||
import { SetFriendRemark } from '@snowluma/protocol/oidb-services/friend/set-friend-remark';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
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).
|
||||
*/
|
||||
handleRequest(uidOrFlag: string, approve: boolean): Promise<void> {
|
||||
return HandleFriendRequest.invoke(this.ctx, { uidOrFlag, approve });
|
||||
}
|
||||
|
||||
async delete(userId: number, block = false): Promise<void> {
|
||||
await DeleteFriend.invoke(this.ctx, { userId, block });
|
||||
|
||||
// Refresh friend cache after deletion so subsequent reads don't
|
||||
// surface a ghost entry. Best-effort: a transient OIDB hiccup here
|
||||
// shouldn't make the delete itself look failed.
|
||||
try { await this.ctx.apis.contacts.fetchFriendList(); } catch { /* ignore */ }
|
||||
}
|
||||
|
||||
setRemark(userId: number, remark: string): Promise<void> {
|
||||
return SetFriendRemark.invoke(this.ctx, { userId, remark });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { GetAtAllRemain } from '@snowluma/protocol/oidb-services/group-admin/get-at-all-remain';
|
||||
import { KickMember } from '@snowluma/protocol/oidb-services/group-admin/kick-member';
|
||||
import { KickMembers } from '@snowluma/protocol/oidb-services/group-admin/kick-members';
|
||||
import { LeaveGroup } from '@snowluma/protocol/oidb-services/group-admin/leave-group';
|
||||
import { MuteAll } from '@snowluma/protocol/oidb-services/group-admin/mute-all';
|
||||
import { MuteMember } from '@snowluma/protocol/oidb-services/group-admin/mute-member';
|
||||
import { SetAddOption } from '@snowluma/protocol/oidb-services/group-admin/set-add-option';
|
||||
import { SetAddRequest } from '@snowluma/protocol/oidb-services/group-admin/set-add-request';
|
||||
import { SetAdmin } from '@snowluma/protocol/oidb-services/group-admin/set-admin';
|
||||
import { SetGroupName } from '@snowluma/protocol/oidb-services/group-admin/set-group-name';
|
||||
import { SetGroupRemark } from '@snowluma/protocol/oidb-services/group-admin/set-group-remark';
|
||||
import { SetMemberCard } from '@snowluma/protocol/oidb-services/group-admin/set-member-card';
|
||||
import { SetSearch } from '@snowluma/protocol/oidb-services/group-admin/set-search';
|
||||
import { SetSpecialTitle } from '@snowluma/protocol/oidb-services/group-admin/set-special-title';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
export class GroupAdminApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
|
||||
muteMember(groupId: number, userId: number, duration: number): Promise<void> {
|
||||
return MuteMember.invoke(this.ctx, { groupId, userId, duration });
|
||||
}
|
||||
|
||||
muteAll(groupId: number, enable: boolean): Promise<void> {
|
||||
return MuteAll.invoke(this.ctx, { groupId, enable });
|
||||
}
|
||||
|
||||
setAddOption(groupId: number, addType: number): Promise<void> {
|
||||
return SetAddOption.invoke(this.ctx, { groupId, addType });
|
||||
}
|
||||
|
||||
setSearch(groupId: number): Promise<void> {
|
||||
return SetSearch.invoke(this.ctx, { groupId });
|
||||
}
|
||||
|
||||
setAddRequest(
|
||||
groupId: number, sequence: number, eventType: number,
|
||||
approve: boolean, reason = '', filtered = false,
|
||||
): Promise<void> {
|
||||
return SetAddRequest.invoke(this.ctx, { groupId, sequence, eventType, approve, reason, filtered });
|
||||
}
|
||||
|
||||
kickMember(groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> {
|
||||
return KickMember.invoke(this.ctx, { groupId, userId, reject, reason });
|
||||
}
|
||||
|
||||
kickMembers(groupId: number, userIds: number[], reject: boolean): Promise<void> {
|
||||
return KickMembers.invoke(this.ctx, { groupId, userIds, reject });
|
||||
}
|
||||
|
||||
leave(groupId: number): Promise<void> {
|
||||
return LeaveGroup.invoke(this.ctx, { groupId });
|
||||
}
|
||||
|
||||
setAdmin(groupId: number, userId: number, enable: boolean): Promise<void> {
|
||||
return SetAdmin.invoke(this.ctx, { groupId, userId, enable });
|
||||
}
|
||||
|
||||
setCard(groupId: number, userId: number, card: string): Promise<void> {
|
||||
return SetMemberCard.invoke(this.ctx, { groupId, userId, card });
|
||||
}
|
||||
|
||||
setName(groupId: number, name: string): Promise<void> {
|
||||
return SetGroupName.invoke(this.ctx, { groupId, name });
|
||||
}
|
||||
|
||||
setSpecialTitle(groupId: number, userId: number, title: string): Promise<void> {
|
||||
return SetSpecialTitle.invoke(this.ctx, { groupId, userId, title });
|
||||
}
|
||||
|
||||
/**
|
||||
* The bot's local-only label for a group. Lives here rather than
|
||||
* `FriendApi` because the semantic is "operate on a group" rather
|
||||
* than "operate on a contact list".
|
||||
*/
|
||||
setRemark(groupId: number, remark: string): Promise<void> {
|
||||
return SetGroupRemark.invoke(this.ctx, { groupId, remark });
|
||||
}
|
||||
|
||||
getAtAllRemain(groupId: number): Promise<{
|
||||
can_at_all: boolean;
|
||||
remain_at_all_count_for_group: number;
|
||||
remain_at_all_count_for_uin: number;
|
||||
}> {
|
||||
return GetAtAllRemain.invoke(this.ctx, { groupId });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
import type { JsonObject, JsonValue } from '@snowluma/common/json';
|
||||
import type {
|
||||
DeleteMediasRequest,
|
||||
DeleteMediasResponse,
|
||||
DoQunCommentRequest,
|
||||
DoQunCommentResponse,
|
||||
DoQunLikeRequest,
|
||||
DoQunLikeResponse,
|
||||
GetMediaListRequest,
|
||||
GetMediaListResponse,
|
||||
MediaInfo,
|
||||
} from '@snowluma/proto-defs/oidb-actions/group-album';
|
||||
import { getGroupAlbumList, uploadImageToGroupAlbum } from '@snowluma/protocol/web/group-album';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
|
||||
function convertBigIntToString(obj: unknown): JsonValue {
|
||||
if (obj === null || obj === undefined) return null;
|
||||
if (typeof obj === 'bigint') return obj.toString();
|
||||
if (Array.isArray(obj)) return obj.map(convertBigIntToString);
|
||||
if (typeof obj === 'object') {
|
||||
const result: JsonObject = {};
|
||||
for (const [key, value] of Object.entries(obj)) {
|
||||
result[key] = convertBigIntToString(value);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean') return obj;
|
||||
return null;
|
||||
}
|
||||
|
||||
export class GroupAlbumApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
|
||||
// 列出群相册(基于 qzone.qq.com 的 HTTP Cookie)。
|
||||
async list(groupId: number): Promise<GroupAlbumList> {
|
||||
const groupCode = groupId.toString();
|
||||
const uin = this.ctx.identity.uin;
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
const albumData = await getGroupAlbumList(cookieObject, groupCode, uin);
|
||||
return albumData?.album || [];
|
||||
}
|
||||
|
||||
// 上传图片到现有相册(HTTP 分片上传)。
|
||||
async upload(groupId: number, albumId: string, albumName: string, filePath: string): Promise<void> {
|
||||
const groupCode = groupId.toString();
|
||||
const uin = this.ctx.identity.uin;
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
await uploadImageToGroupAlbum(cookieObject, groupCode, albumId, albumName, filePath, uin);
|
||||
}
|
||||
|
||||
async getMediaList(groupId: number, albumId: string, attachInfo = ''): Promise<GroupAlbumMediaResult> {
|
||||
const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
|
||||
|
||||
const body = protobuf_encode<GetMediaListRequest>({
|
||||
field1: 0,
|
||||
field2: new Uint8Array(0),
|
||||
field3: new Uint8Array(0),
|
||||
reqInfo: {
|
||||
groupId: groupId.toString(),
|
||||
albumId,
|
||||
field3: 0,
|
||||
attachInfo,
|
||||
field5: '',
|
||||
},
|
||||
traceId,
|
||||
extMap: [{ key: 'fc-appid', value: '100' }],
|
||||
});
|
||||
|
||||
const result = await this.ctx.sendRawPacket(
|
||||
'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.GetMediaList',
|
||||
body,
|
||||
15000,
|
||||
);
|
||||
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'failed to get album media list');
|
||||
}
|
||||
|
||||
const resp = protobuf_decode<GetMediaListResponse>(result.responseData);
|
||||
|
||||
if (resp.field1 !== 0) {
|
||||
throw new Error(`fetch album media list error: retCode ${resp.field1 ?? 'unknown'}`);
|
||||
}
|
||||
|
||||
const data = resp.data ?? {};
|
||||
const mediaList = data.mediaList ?? [];
|
||||
const nextAttachInfo = data.nextAttachInfo ?? '';
|
||||
|
||||
return convertBigIntToString({ mediaList, nextAttachInfo }) as unknown as GroupAlbumMediaResult;
|
||||
}
|
||||
|
||||
async comment(groupId: number, albumId: string, lloc: string, content: string): Promise<GroupAlbumCommentResult> {
|
||||
const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
|
||||
const clientKey = Date.now().toString();
|
||||
const uin = this.ctx.identity.uin;
|
||||
|
||||
const body = protobuf_encode<DoQunCommentRequest>({
|
||||
field1: 8527,
|
||||
field2: new Uint8Array(0),
|
||||
field3: new Uint8Array(0),
|
||||
body: {
|
||||
groupId: groupId.toString(),
|
||||
field3: 2,
|
||||
reqBody: {
|
||||
field1: { field3: 0, field4: '' },
|
||||
field2: {
|
||||
field1: { uin },
|
||||
},
|
||||
field5: {
|
||||
field1: {
|
||||
field2: {
|
||||
field1: 0, field2: '',
|
||||
lloc,
|
||||
field4: '', field6: '', field7: 0, field8: 0, field9: 0, field14: 0, field15: 0, field17: 0,
|
||||
},
|
||||
},
|
||||
albumId,
|
||||
field5: 0,
|
||||
},
|
||||
},
|
||||
field5: {
|
||||
field2: { uin },
|
||||
field3: {
|
||||
field1: 0,
|
||||
field2: content,
|
||||
field3: '', field4: '', field5: 0, field6: '',
|
||||
},
|
||||
clientKey,
|
||||
},
|
||||
},
|
||||
traceId,
|
||||
extMap: [{ key: 'fc-appid', value: '100' }],
|
||||
});
|
||||
|
||||
const result = await this.ctx.sendRawPacket(
|
||||
'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunComment',
|
||||
body,
|
||||
15000,
|
||||
);
|
||||
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'failed to comment on album media');
|
||||
}
|
||||
|
||||
const resp = protobuf_decode<DoQunCommentResponse>(result.responseData);
|
||||
|
||||
const resCode = resp.field1;
|
||||
if (resCode !== 0 && resCode !== 8527 && !resp.comment) {
|
||||
throw new Error(`comment album media error: retCode ${resCode ?? 'unknown'}`);
|
||||
}
|
||||
|
||||
const commentData = resp.comment?.data ?? {};
|
||||
|
||||
return convertBigIntToString({
|
||||
id: commentData.id ?? '',
|
||||
user: { uin: commentData.user?.uin ?? '' },
|
||||
content: commentData.content ?? [],
|
||||
time: commentData.time ?? '0',
|
||||
clientKey: commentData.clientKey ?? '',
|
||||
}) as unknown as GroupAlbumCommentResult;
|
||||
}
|
||||
|
||||
async like(groupId: number, albumId: string, batchId: string, lloc: string | undefined, isLike: boolean): Promise<JsonValue> {
|
||||
const uin = this.ctx.identity.uin;
|
||||
const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
|
||||
|
||||
const type = isLike ? 2 : 1;
|
||||
const status = isLike ? 0 : 1;
|
||||
|
||||
let id = '';
|
||||
if (lloc) {
|
||||
id = `421_1_0_${groupId}|${albumId}|${batchId}^||^421_1_0_${groupId}|${albumId}|${lloc}^||^0`;
|
||||
} else {
|
||||
id = `421_1_0_${groupId}|${albumId}|${batchId}`;
|
||||
}
|
||||
|
||||
const body = protobuf_encode<DoQunLikeRequest>({
|
||||
field1: 5495,
|
||||
field2: 'h5_test',
|
||||
field3: 'h5_test',
|
||||
body: {
|
||||
type,
|
||||
like: { id, status },
|
||||
publish: {
|
||||
cellCommon: {
|
||||
time: BigInt(Date.now()),
|
||||
feedId: `422_0_${batchId}`,
|
||||
},
|
||||
cellUserInfo: {
|
||||
user: { uin },
|
||||
},
|
||||
cellMedia: {
|
||||
albumId,
|
||||
batchId: BigInt(batchId),
|
||||
},
|
||||
cellQunInfo: {
|
||||
qunId: groupId.toString(),
|
||||
},
|
||||
},
|
||||
clientKey,
|
||||
},
|
||||
extMap: [{ key: 'fc-appid', value: '100' }],
|
||||
});
|
||||
|
||||
const result = await this.ctx.sendRawPacket(
|
||||
'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunLike',
|
||||
body,
|
||||
15000,
|
||||
);
|
||||
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'failed to like album media');
|
||||
}
|
||||
|
||||
const resp = protobuf_decode<DoQunLikeResponse>(result.responseData);
|
||||
const resCode = resp.field1;
|
||||
|
||||
if (resCode !== 5495) {
|
||||
throw new Error(`like album media error: retCode ${resCode ?? 'unknown'}`);
|
||||
}
|
||||
|
||||
return convertBigIntToString(resp.body?.like ?? {});
|
||||
}
|
||||
|
||||
async delete(groupId: number, albumId: string, lloc: string): Promise<{ success: true }> {
|
||||
const uin = this.ctx.identity.uin;
|
||||
const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
|
||||
|
||||
const body = protobuf_encode<DeleteMediasRequest>({
|
||||
field1: 8694,
|
||||
field2: 'h5_test',
|
||||
field3: 'h5_test',
|
||||
body: {
|
||||
groupId: groupId.toString(),
|
||||
albumId,
|
||||
lloc,
|
||||
},
|
||||
traceId: clientKey,
|
||||
extMap: [{ key: 'fc-appid', value: '100' }],
|
||||
});
|
||||
|
||||
const result = await this.ctx.sendRawPacket(
|
||||
'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.DeleteMedias',
|
||||
body,
|
||||
15000,
|
||||
);
|
||||
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'failed to delete album media');
|
||||
}
|
||||
|
||||
const resp = protobuf_decode<DeleteMediasResponse>(result.responseData);
|
||||
const resCode = resp.field1;
|
||||
const errCode = resp.field2;
|
||||
const errMsg = resp.field3;
|
||||
|
||||
if (resCode !== 8694 || errCode) {
|
||||
throw new Error(`delete album media error [${errCode ?? 'unknown'}]: ${errMsg ?? 'unknown'}`);
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
}
|
||||
}
|
||||
export interface GroupAlbumMediaResult {
|
||||
mediaList: Array<JsonValue & Partial<MediaInfo>>;
|
||||
nextAttachInfo: string;
|
||||
}
|
||||
|
||||
export type GroupAlbumList = NonNullable<Awaited<ReturnType<typeof getGroupAlbumList>>>['album'];
|
||||
|
||||
export interface GroupAlbumCommentResult {
|
||||
id: string;
|
||||
user: { uin: string };
|
||||
content: Array<{ type: number; content: string }>;
|
||||
time: string;
|
||||
clientKey: string;
|
||||
}
|
||||
@@ -0,0 +1,644 @@
|
||||
import { toHexUpper } from '@snowluma/common/hex';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { FileUploadExt } from '@snowluma/proto-defs/highway';
|
||||
import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
|
||||
import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '@snowluma/protocol/highway/utils';
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import type { Bridge } from '../bridge';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
import { resolveSelfUid, toInt, type MediaIndexNode } from './shared';
|
||||
|
||||
import { CreateGroupFolder } from '@snowluma/protocol/oidb-services/group-file/create-group-folder';
|
||||
import { DeleteGroupFile } from '@snowluma/protocol/oidb-services/group-file/delete-group-file';
|
||||
import { DeleteGroupFolder } from '@snowluma/protocol/oidb-services/group-file/delete-group-folder';
|
||||
import { GetGroupFileCount } from '@snowluma/protocol/oidb-services/group-file/get-group-file-count';
|
||||
import { GetGroupFileUrl } from '@snowluma/protocol/oidb-services/group-file/get-group-file-url';
|
||||
import { GetGroupPttUrl } from '@snowluma/protocol/oidb-services/group-file/get-group-ptt-url';
|
||||
import { GetGroupVideoUrl } from '@snowluma/protocol/oidb-services/group-file/get-group-video-url';
|
||||
import { GetPrivateFileUrl } from '@snowluma/protocol/oidb-services/group-file/get-private-file-url';
|
||||
import { GetPrivatePttUrl } from '@snowluma/protocol/oidb-services/group-file/get-private-ptt-url';
|
||||
import { GetPrivateVideoUrl } from '@snowluma/protocol/oidb-services/group-file/get-private-video-url';
|
||||
import { ListGroupFilesPage } from '@snowluma/protocol/oidb-services/group-file/list-group-files-page';
|
||||
import { MoveGroupFile } from '@snowluma/protocol/oidb-services/group-file/move-group-file';
|
||||
import { PublishGroupFile } from '@snowluma/protocol/oidb-services/group-file/publish-group-file';
|
||||
import { RenameGroupFolder } from '@snowluma/protocol/oidb-services/group-file/rename-group-folder';
|
||||
import { UploadGroupFileRequest } from '@snowluma/protocol/oidb-services/group-file/upload-group-file-request';
|
||||
import { UploadPrivateFileRequest } from '@snowluma/protocol/oidb-services/group-file/upload-private-file-request';
|
||||
import { ensureRetCodeZero } from '@snowluma/protocol/oidb-services/shared';
|
||||
|
||||
const log = createLogger('GroupFile');
|
||||
|
||||
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
|
||||
|
||||
// ─────────────── public result types ───────────────
|
||||
|
||||
export interface GroupFileInfo {
|
||||
fileId: string;
|
||||
fileName: string;
|
||||
busId: number;
|
||||
fileSize: number;
|
||||
uploadTime: number;
|
||||
deadTime: number;
|
||||
modifyTime: number;
|
||||
downloadTimes: number;
|
||||
uploader: number;
|
||||
uploaderName: string;
|
||||
}
|
||||
|
||||
export interface GroupFolderInfo {
|
||||
folderId: string;
|
||||
folderName: string;
|
||||
createTime: number;
|
||||
creator: number;
|
||||
creatorName: string;
|
||||
totalFileCount: number;
|
||||
}
|
||||
|
||||
export interface GroupFilesResult {
|
||||
files: GroupFileInfo[];
|
||||
folders: GroupFolderInfo[];
|
||||
}
|
||||
|
||||
export interface UploadFileResult {
|
||||
fileId: string | null;
|
||||
fileHash?: string | null;
|
||||
}
|
||||
|
||||
// Re-export so callers don't have to dig into apis/shared.
|
||||
export type { MediaIndexNode } from './shared';
|
||||
|
||||
// ─────────────── file-specific helpers ───────────────
|
||||
|
||||
function normalizeDirectory(dir?: string): string {
|
||||
if (!dir || !dir.trim()) return '/';
|
||||
return dir;
|
||||
}
|
||||
|
||||
function bytesToHexUpper(data: unknown): string {
|
||||
if (!(data instanceof Uint8Array) || data.length === 0) return '';
|
||||
return toHexUpper(data);
|
||||
}
|
||||
|
||||
// Reverses acidify's `Int.toIpString()`: the 32-bit IP arrives
|
||||
// little-endian-packed (byte0 = first dotted octet) and we unpack it the
|
||||
// same way. Force-unsigned the shift to keep negative ints (high bit set)
|
||||
// rendering correctly — JS `>>` is arithmetic and would turn 0xFF000000
|
||||
// into a negative number.
|
||||
function int32ToIpv4Dotted(value: number): string {
|
||||
const b1 = value & 0xFF;
|
||||
const b2 = (value >>> 8) & 0xFF;
|
||||
const b3 = (value >>> 16) & 0xFF;
|
||||
const b4 = (value >>> 24) & 0xFF;
|
||||
return `${b1}.${b2}.${b3}.${b4}`;
|
||||
}
|
||||
|
||||
function normalizeUploadFileName(name: string, fallback: string): string {
|
||||
const trimmed = name.trim();
|
||||
if (trimmed) return trimmed;
|
||||
const safeFallback = fallback.trim();
|
||||
return safeFallback || 'file.bin';
|
||||
}
|
||||
|
||||
function md5First10MB(bytes: Uint8Array): Uint8Array {
|
||||
const limit = Math.min(bytes.length, 10 * 1024 * 1024);
|
||||
return computeMd5(bytes.subarray(0, limit));
|
||||
}
|
||||
|
||||
function buildGroupFileUploadExt(
|
||||
senderUin: number,
|
||||
groupId: number,
|
||||
fileName: string,
|
||||
fileSize: number,
|
||||
md5: Uint8Array,
|
||||
fileId: string,
|
||||
uploadKey: Uint8Array,
|
||||
checkKey: Uint8Array,
|
||||
uploadHost: string,
|
||||
uploadPort: number,
|
||||
): Uint8Array {
|
||||
return protobuf_encode<FileUploadExt>({
|
||||
unknown1: 100,
|
||||
unknown2: 1,
|
||||
entry: {
|
||||
busiBuff: {
|
||||
busId: 102,
|
||||
senderUin: BigInt(senderUin),
|
||||
receiverUin: BigInt(groupId),
|
||||
groupCode: BigInt(groupId),
|
||||
},
|
||||
fileEntry: {
|
||||
fileSize: BigInt(Math.max(0, fileSize)),
|
||||
md5,
|
||||
md5S2: md5,
|
||||
checkKey,
|
||||
fileId,
|
||||
uploadKey,
|
||||
},
|
||||
clientInfo: {
|
||||
clientType: 3,
|
||||
appId: '100',
|
||||
terminalType: 3,
|
||||
clientVer: '1.1.1',
|
||||
unknown: 4,
|
||||
},
|
||||
fileNameInfo: {
|
||||
fileName,
|
||||
},
|
||||
host: {
|
||||
hosts: [
|
||||
{
|
||||
url: {
|
||||
host: uploadHost,
|
||||
unknown: 1,
|
||||
},
|
||||
port: uploadPort,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
unknown200: 0,
|
||||
});
|
||||
}
|
||||
|
||||
function buildPrivateFileUploadExt(
|
||||
senderUin: number,
|
||||
fileName: string,
|
||||
fileSize: number,
|
||||
md5: Uint8Array,
|
||||
sha1: Uint8Array,
|
||||
fileId: string,
|
||||
uploadKey: Uint8Array,
|
||||
uploadHost: string,
|
||||
uploadPort: number,
|
||||
): Uint8Array {
|
||||
return protobuf_encode<FileUploadExt>({
|
||||
unknown1: 100,
|
||||
unknown2: 1,
|
||||
entry: {
|
||||
busiBuff: {
|
||||
busId: 102,
|
||||
senderUin: BigInt(senderUin),
|
||||
receiverUin: 0n,
|
||||
groupCode: 0n,
|
||||
},
|
||||
fileEntry: {
|
||||
fileSize: BigInt(Math.max(0, fileSize)),
|
||||
md5,
|
||||
md5S2: md5,
|
||||
checkKey: sha1,
|
||||
fileId,
|
||||
uploadKey,
|
||||
},
|
||||
clientInfo: {
|
||||
clientType: 3,
|
||||
appId: '100',
|
||||
terminalType: 3,
|
||||
clientVer: '1.1.1',
|
||||
unknown: 4,
|
||||
},
|
||||
fileNameInfo: {
|
||||
fileName,
|
||||
},
|
||||
host: {
|
||||
hosts: [
|
||||
{
|
||||
url: {
|
||||
host: uploadHost,
|
||||
unknown: 1,
|
||||
},
|
||||
port: uploadPort,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
unknown3: 0,
|
||||
unknown200: 1,
|
||||
});
|
||||
}
|
||||
|
||||
export class GroupFileApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
|
||||
// ─────────────── publish (group file → chat) ───────────────
|
||||
|
||||
publish(groupId: number, fileId: string): Promise<void> {
|
||||
if (!fileId) throw new Error('publish requires fileId');
|
||||
return PublishGroupFile.invoke(this.ctx, { groupId, fileId });
|
||||
}
|
||||
|
||||
// ─────────────── count ───────────────
|
||||
|
||||
getCount(groupId: number): Promise<{ fileCount: number; maxCount: number }> {
|
||||
return GetGroupFileCount.invoke(this.ctx, { groupId });
|
||||
}
|
||||
|
||||
// ─────────────── upload (3-stage: OIDB preflight → highway → publish) ───────────────
|
||||
|
||||
async upload(
|
||||
groupId: number,
|
||||
source: string,
|
||||
name = '',
|
||||
folderId = '/',
|
||||
uploadFile = true,
|
||||
): Promise<UploadFileResult> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
// Group/private files may legitimately be up to 4 GiB on QQ's wire,
|
||||
// so override the default 1 GiB cap with the protocol ceiling.
|
||||
const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES);
|
||||
if (!loaded.bytes.length) throw new Error('group file is empty');
|
||||
|
||||
const fileName = normalizeUploadFileName(name, loaded.fileName);
|
||||
const hashes = computeHashes(loaded.bytes);
|
||||
|
||||
const upload = await UploadGroupFileRequest.invoke(this.ctx, {
|
||||
groupId,
|
||||
fileName,
|
||||
folderId: normalizeDirectory(folderId),
|
||||
fileSize: loaded.bytes.length,
|
||||
fileSha1: hashes.sha1,
|
||||
fileMd5: hashes.md5,
|
||||
});
|
||||
ensureRetCodeZero('group file upload', upload.retCode, upload.retMsg, upload.clientWording);
|
||||
|
||||
const fileId = typeof upload.fileId === 'string' && upload.fileId ? upload.fileId : null;
|
||||
if (!fileId) throw new Error('group file upload response missing file_id');
|
||||
|
||||
// Remember the upload so a later `send_group_msg` carrying just the
|
||||
// file_id can route via `publish` without forcing the OneBot caller
|
||||
// to thread fileName/size/md5 separately. For groups the wire
|
||||
// publish (OIDB 0x6d9_4) only needs the file_id itself, so this is
|
||||
// mainly for log-line correctness; the c2c counterpart in
|
||||
// `uploadPrivate` is where the cache is actually load-bearing.
|
||||
this.ctx.rememberUploadedFile({
|
||||
fileId,
|
||||
scope: 'group',
|
||||
groupId,
|
||||
fileName,
|
||||
fileSize: loaded.bytes.length,
|
||||
fileMd5: hashes.md5,
|
||||
fileSha1: hashes.sha1,
|
||||
rememberedAt: Date.now(),
|
||||
});
|
||||
|
||||
if (!upload.boolFileExist && uploadFile) {
|
||||
const senderUin = toInt(this.ctx.identity.uin);
|
||||
if (senderUin <= 0) throw new Error('invalid self uin for group file upload');
|
||||
|
||||
const uploadHost = (typeof upload.uploadIp === 'string' && upload.uploadIp)
|
||||
|| (typeof upload.serverDns === 'string' && upload.serverDns)
|
||||
|| '';
|
||||
const uploadPort = toInt(upload.uploadPort);
|
||||
if (!uploadHost || uploadPort <= 0) {
|
||||
throw new Error('group file upload host is invalid');
|
||||
}
|
||||
|
||||
const ext = buildGroupFileUploadExt(
|
||||
senderUin,
|
||||
groupId,
|
||||
fileName,
|
||||
loaded.bytes.length,
|
||||
hashes.md5,
|
||||
fileId,
|
||||
upload.fileKey instanceof Uint8Array ? upload.fileKey : new Uint8Array(0),
|
||||
upload.checkKey instanceof Uint8Array ? upload.checkKey : new Uint8Array(0),
|
||||
uploadHost,
|
||||
uploadPort,
|
||||
);
|
||||
|
||||
const session = await fetchHighwaySession(bridge);
|
||||
await uploadHighwayHttp(bridge, session, 71, loaded.bytes, hashes.md5, ext);
|
||||
}
|
||||
|
||||
// Stage 3: file is on the server, now publish it as a chat message.
|
||||
//
|
||||
// Without this, OIDB 0x6D6_0 + highway PUT only stages the bytes —
|
||||
// the chat shows nothing. The publish step goes via a dedicated OIDB
|
||||
// call (0x6D9_4), NOT via `MessageSvc.PbSendMsg` with a transElem(24)
|
||||
// payload — the QQ-NT server rejects that with `result=79`. Mirrors
|
||||
// Lagrange.Core V2's `GroupSendFileService.cs`. Suppressed when the
|
||||
// caller opts out via `uploadFile=false` (treat that as "I only
|
||||
// wanted the slot allocated, hold the chat post"). Routes through
|
||||
// `this.publish` so tests can mock at the same Api boundary.
|
||||
if (uploadFile) {
|
||||
try {
|
||||
await this.publish(groupId, fileId);
|
||||
} catch (err) {
|
||||
// The bytes are already on the server and the fileId is valid —
|
||||
// fail loud but don't lose the upload result the action handler
|
||||
// committed to returning. Callers can still resolve the file by
|
||||
// id; they'll just have to re-publish it themselves.
|
||||
log.warn('group file uploaded (fileId=%s) but chat post failed: %s',
|
||||
fileId, err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
|
||||
return { fileId };
|
||||
}
|
||||
|
||||
async uploadPrivate(
|
||||
userId: number,
|
||||
source: string,
|
||||
name = '',
|
||||
uploadFile = true,
|
||||
): Promise<UploadFileResult> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES);
|
||||
if (!loaded.bytes.length) throw new Error('private file is empty');
|
||||
|
||||
const targetUid = await this.ctx.resolveUserUid(userId);
|
||||
let selfUid = this.ctx.identity.selfUid;
|
||||
if (!selfUid) {
|
||||
const selfUin = toInt(this.ctx.identity.uin);
|
||||
if (selfUin > 0) {
|
||||
selfUid = await this.ctx.resolveUserUid(selfUin);
|
||||
}
|
||||
}
|
||||
if (!selfUid) throw new Error('self uid is unavailable');
|
||||
|
||||
const senderUin = toInt(this.ctx.identity.uin);
|
||||
if (senderUin <= 0) throw new Error('invalid self uin for private file upload');
|
||||
|
||||
const fileName = normalizeUploadFileName(name, loaded.fileName);
|
||||
const hashes = computeHashes(loaded.bytes);
|
||||
|
||||
const upload = await UploadPrivateFileRequest.invoke(this.ctx, {
|
||||
senderUid: selfUid,
|
||||
receiverUid: targetUid,
|
||||
fileName,
|
||||
fileSize: loaded.bytes.length,
|
||||
fileSha1: hashes.sha1,
|
||||
fileMd5: hashes.md5,
|
||||
md510MCheckSum: md5First10MB(loaded.bytes),
|
||||
});
|
||||
ensureRetCodeZero('private file upload', upload.retCode, upload.retMsg, undefined);
|
||||
|
||||
const fileId = typeof upload.uuid === 'string' && upload.uuid ? upload.uuid : null;
|
||||
const fileHash = typeof upload.fileAddon === 'string' && upload.fileAddon ? upload.fileAddon : null;
|
||||
if (!fileId) throw new Error('private file upload response missing file_id');
|
||||
|
||||
// Cache the metadata so a later `send_private_msg` carrying just
|
||||
// `{type:'file', file_id}` can resurrect the full c2c-file packet
|
||||
// (NotOnlineFile { fileSize, fileMd5, fileName, fileHash }). Without
|
||||
// this the recipient sees a 0-byte file because the OneBot send path
|
||||
// has no way to recover those fields from the file_id alone.
|
||||
this.ctx.rememberUploadedFile({
|
||||
fileId,
|
||||
scope: 'private',
|
||||
userId,
|
||||
fileName,
|
||||
fileSize: loaded.bytes.length,
|
||||
fileMd5: hashes.md5,
|
||||
fileSha1: hashes.sha1,
|
||||
fileHash: fileHash ?? '',
|
||||
rememberedAt: Date.now(),
|
||||
});
|
||||
|
||||
if (!upload.boolFileExist && uploadFile) {
|
||||
// Host selection.
|
||||
//
|
||||
// Current QQ-NT server rollout has stopped populating the legacy
|
||||
// `uploadIp` (field 60) entirely. The host now arrives as the first
|
||||
// entry of `rtpMediaPlatformUploadAddress` (field 210, repeated
|
||||
// IPv4 message) — same place acidify reads it from since their
|
||||
// 2026-04 protobuf refactor. Each IPv4 has paired `inIP`/`inPort`
|
||||
// (LAN, same DC as the OIDB endpoint) and `outIP`/`outPort` (WAN);
|
||||
// acidify uses `inIP`/`inPort` exclusively and so do we, because
|
||||
// that's the address the highway PUT actually needs to reach.
|
||||
//
|
||||
// The 32-bit IPs are little-endian-packed (byte0 = first octet)
|
||||
// per acidify's `Int.toIpString()`. Cross-checked the byte order
|
||||
// by inspecting their highway flow — there's no separate htonl
|
||||
// step, so the integer is already in network-octet-first order.
|
||||
//
|
||||
// Older server versions still populate the legacy string fields
|
||||
// (uploadIp / uploadDomain / uploadIpList[0] / uploadHttpsDomain /
|
||||
// uploadDns), so we fall through to those after rtpMediaPlatform.
|
||||
// Pair an HTTPS-flavored host with `uploadHttpsPort` if that's
|
||||
// what we picked.
|
||||
const rtpFirst = (Array.isArray(upload.rtpMediaPlatformUploadAddress)
|
||||
&& upload.rtpMediaPlatformUploadAddress[0])
|
||||
? upload.rtpMediaPlatformUploadAddress[0] : null;
|
||||
const rtpInIP = rtpFirst && typeof rtpFirst.inIP === 'number' && rtpFirst.inIP !== 0
|
||||
? int32ToIpv4Dotted(rtpFirst.inIP) : '';
|
||||
const rtpInPort = rtpFirst && typeof rtpFirst.inPort === 'number'
|
||||
? rtpFirst.inPort : 0;
|
||||
const ipListFirst = (Array.isArray(upload.uploadIpList) && upload.uploadIpList[0])
|
||||
? upload.uploadIpList[0] : '';
|
||||
const uploadHost = (rtpInIP)
|
||||
|| (typeof upload.uploadIp === 'string' && upload.uploadIp)
|
||||
|| (typeof upload.uploadDomain === 'string' && upload.uploadDomain)
|
||||
|| (ipListFirst)
|
||||
|| (typeof upload.uploadHttpsDomain === 'string' && upload.uploadHttpsDomain)
|
||||
|| (typeof upload.uploadDns === 'string' && upload.uploadDns)
|
||||
|| '';
|
||||
const httpsHostUsed = !rtpInIP && !upload.uploadIp && !upload.uploadDomain && !ipListFirst
|
||||
&& typeof upload.uploadHttpsDomain === 'string' && !!upload.uploadHttpsDomain;
|
||||
const uploadPort = rtpInIP && rtpInPort > 0
|
||||
? rtpInPort
|
||||
: httpsHostUsed && toInt(upload.uploadHttpsPort) > 0
|
||||
? toInt(upload.uploadHttpsPort)
|
||||
: toInt(upload.uploadPort);
|
||||
if (!uploadHost || uploadPort <= 0) {
|
||||
const rtpDump = Array.isArray(upload.rtpMediaPlatformUploadAddress)
|
||||
? JSON.stringify(upload.rtpMediaPlatformUploadAddress.map((e) => ({
|
||||
outIP: e.outIP, outPort: e.outPort, inIP: e.inIP, inPort: e.inPort,
|
||||
iPType: e.iPType,
|
||||
})))
|
||||
: '[]';
|
||||
log.warn(
|
||||
'private file upload host missing — rtp=%s ip=%s domain=%s ipList=%s httpsDomain=%s dns=%s lanip=%s port=%s httpsPort=%s',
|
||||
rtpDump,
|
||||
upload.uploadIp ?? '', upload.uploadDomain ?? '',
|
||||
JSON.stringify(upload.uploadIpList ?? []),
|
||||
upload.uploadHttpsDomain ?? '', upload.uploadDns ?? '',
|
||||
upload.uploadLanip ?? '', upload.uploadPort ?? 0,
|
||||
upload.uploadHttpsPort ?? 0,
|
||||
);
|
||||
throw new Error('private file upload host is invalid');
|
||||
}
|
||||
|
||||
const ext = buildPrivateFileUploadExt(
|
||||
senderUin,
|
||||
fileName,
|
||||
loaded.bytes.length,
|
||||
hashes.md5,
|
||||
hashes.sha1,
|
||||
fileId,
|
||||
upload.mediaPlatformUploadKey instanceof Uint8Array
|
||||
? upload.mediaPlatformUploadKey
|
||||
: (upload.uploadKey instanceof Uint8Array ? upload.uploadKey : new Uint8Array(0)),
|
||||
uploadHost,
|
||||
uploadPort,
|
||||
);
|
||||
|
||||
const session = await fetchHighwaySession(bridge);
|
||||
await uploadHighwayHttp(bridge, session, 95, loaded.bytes, hashes.md5, ext);
|
||||
}
|
||||
|
||||
// Stage 3: publish the file as a c2c chat message. C2C files use
|
||||
// `RichText.notOnlineFile` (parallel to `elems`), so we go through
|
||||
// the dedicated `sendC2cFile` on MessageApi instead of `sendPrivate`
|
||||
// which only knows about elems[]. NapCat does the same atomic
|
||||
// upload+send dance — without it the file sits on the server and
|
||||
// the recipient sees nothing.
|
||||
if (uploadFile) {
|
||||
try {
|
||||
await this.ctx.apis.message.sendC2cFile(userId, targetUid, {
|
||||
fileId,
|
||||
fileName,
|
||||
fileSize: loaded.bytes.length,
|
||||
fileMd5: hashes.md5,
|
||||
fileHash: fileHash ?? '',
|
||||
});
|
||||
} catch (err) {
|
||||
log.warn('private file uploaded (fileId=%s) but chat post failed: %s',
|
||||
fileId, err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
|
||||
return { fileId, fileHash };
|
||||
}
|
||||
|
||||
// ─────────────── list (paginated loop) ───────────────
|
||||
|
||||
async list(groupId: number, folderId = '/'): Promise<GroupFilesResult> {
|
||||
const targetDirectory = normalizeDirectory(folderId);
|
||||
const files: GroupFileInfo[] = [];
|
||||
const folders: GroupFolderInfo[] = [];
|
||||
|
||||
const pageSize = 20;
|
||||
let startIndex = 0;
|
||||
for (let page = 0; page < 200; page++) {
|
||||
const list = await ListGroupFilesPage.invoke(this.ctx, {
|
||||
groupId, targetDirectory, startIndex, pageSize,
|
||||
});
|
||||
if (!list) break;
|
||||
ensureRetCodeZero('group file list', list.retCode, list.retMsg, list.clientWording);
|
||||
|
||||
for (const item of list.items ?? []) {
|
||||
const type = toInt(item?.type);
|
||||
if (type === 1 && item?.fileInfo) {
|
||||
const file = item.fileInfo;
|
||||
const uploader = toInt(file.uploaderUin);
|
||||
const cached = this.ctx.identity.findGroupMember(groupId, uploader);
|
||||
files.push({
|
||||
fileId: typeof file.fileId === 'string' ? file.fileId : '',
|
||||
fileName: typeof file.fileName === 'string' ? file.fileName : '',
|
||||
busId: toInt(file.busId),
|
||||
fileSize: toInt(file.fileSize),
|
||||
uploadTime: toInt(file.uploadedTime),
|
||||
deadTime: toInt(file.expireTime),
|
||||
modifyTime: toInt(file.modifiedTime),
|
||||
downloadTimes: toInt(file.downloadedTimes),
|
||||
uploader,
|
||||
uploaderName: (typeof file.uploaderName === 'string' && file.uploaderName)
|
||||
|| cached?.card
|
||||
|| cached?.nickname
|
||||
|| '',
|
||||
});
|
||||
} else if (type === 2 && item?.folderInfo) {
|
||||
const folder = item.folderInfo;
|
||||
const creator = toInt(folder.creatorUin);
|
||||
const cached = this.ctx.identity.findGroupMember(groupId, creator);
|
||||
folders.push({
|
||||
folderId: typeof folder.folderId === 'string' ? folder.folderId : '',
|
||||
folderName: typeof folder.folderName === 'string' ? folder.folderName : '',
|
||||
createTime: toInt(folder.createTime),
|
||||
creator,
|
||||
creatorName: (typeof folder.creatorName === 'string' && folder.creatorName)
|
||||
|| cached?.card
|
||||
|| cached?.nickname
|
||||
|| '',
|
||||
totalFileCount: toInt(folder.totalFileCount),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (list.isEnd) break;
|
||||
startIndex += pageSize;
|
||||
}
|
||||
|
||||
return { files, folders };
|
||||
}
|
||||
|
||||
// ─────────────── url fetch (group / private files) ───────────────
|
||||
|
||||
async getUrl(groupId: number, fileId: string, busId = 102): Promise<string> {
|
||||
const download = await GetGroupFileUrl.invoke(this.ctx, { groupId, fileId, busId });
|
||||
ensureRetCodeZero('group file url', download.retCode, download.retMsg, download.clientWording);
|
||||
|
||||
const dns = (typeof download.downloadDns === 'string' && download.downloadDns)
|
||||
|| (typeof download.downloadIp === 'string' && download.downloadIp)
|
||||
|| '';
|
||||
const hexUrl = bytesToHexUpper(download.downloadUrl);
|
||||
if (!dns || !hexUrl) {
|
||||
throw new Error('group file url response invalid');
|
||||
}
|
||||
|
||||
// Keep the same behavior as Lagrange: append file_id after ?fname=
|
||||
return `https://${dns}/ftn_handler/${hexUrl}/?fname=${fileId}`;
|
||||
}
|
||||
|
||||
async getPrivateUrl(userId: number, fileId: string, fileHash: string): Promise<string> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const selfUid = await resolveSelfUid(bridge);
|
||||
void userId;
|
||||
const result = await GetPrivateFileUrl.invoke(this.ctx, { selfUid, fileId, fileHash });
|
||||
|
||||
const server = typeof result?.server === 'string' ? result.server : '';
|
||||
const port = toInt(result?.port);
|
||||
const url = typeof result?.url === 'string' ? result.url : '';
|
||||
if (!server || !port || !url) {
|
||||
throw new Error('private file url response invalid');
|
||||
}
|
||||
return `http://${server}:${port}${url}&isthumb=0`;
|
||||
}
|
||||
|
||||
// ─────────────── delete / move ───────────────
|
||||
|
||||
delete(groupId: number, fileId: string): Promise<void> {
|
||||
return DeleteGroupFile.invoke(this.ctx, { groupId, fileId });
|
||||
}
|
||||
|
||||
move(groupId: number, fileId: string, parentDirectory: string, targetDirectory: string): Promise<void> {
|
||||
return MoveGroupFile.invoke(this.ctx, { groupId, fileId, parentDirectory, targetDirectory });
|
||||
}
|
||||
|
||||
// ─────────────── folders ───────────────
|
||||
|
||||
createFolder(groupId: number, name: string, parentId = '/'): Promise<void> {
|
||||
return CreateGroupFolder.invoke(this.ctx, {
|
||||
groupId, parentId: normalizeDirectory(parentId), folderName: name,
|
||||
});
|
||||
}
|
||||
|
||||
deleteFolder(groupId: number, folderId: string): Promise<void> {
|
||||
return DeleteGroupFolder.invoke(this.ctx, { groupId, folderId });
|
||||
}
|
||||
|
||||
renameFolder(groupId: number, folderId: string, newFolderName: string): Promise<void> {
|
||||
return RenameGroupFolder.invoke(this.ctx, { groupId, folderId, newFolderName });
|
||||
}
|
||||
|
||||
// ─────────────── rich-media URL by node ───────────────
|
||||
|
||||
getPttUrl(groupId: number, node: MediaIndexNode): Promise<string> {
|
||||
return GetGroupPttUrl.invoke(this.ctx, { groupId, node });
|
||||
}
|
||||
|
||||
async getPrivatePttUrl(node: MediaIndexNode): Promise<string> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const selfUid = await resolveSelfUid(bridge);
|
||||
return GetPrivatePttUrl.invoke(this.ctx, { selfUid, node });
|
||||
}
|
||||
|
||||
getVideoUrl(groupId: number, node: MediaIndexNode): Promise<string> {
|
||||
return GetGroupVideoUrl.invoke(this.ctx, { groupId, node });
|
||||
}
|
||||
|
||||
async getPrivateVideoUrl(node: MediaIndexNode): Promise<string> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const selfUid = await resolveSelfUid(bridge);
|
||||
return GetPrivateVideoUrl.invoke(this.ctx, { selfUid, node });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
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,68 @@
|
||||
// InteractionApi — facade over interactive-engagement OIDB cmds
|
||||
// (poke / like / reaction / essence / emoji-like-list). Every method
|
||||
// is a one-line forwarder to a self-contained namespace under
|
||||
// @snowluma/protocol/oidb-services. The facade exists purely to keep
|
||||
// the `bridge.apis.interaction.X(...)` ergonomic call style; all wire
|
||||
// work (envelope build / encode / send / decode) lives in the
|
||||
// namespace files.
|
||||
|
||||
import { SendLike } from '@snowluma/protocol/oidb-services/interaction/send-like';
|
||||
import { SendPoke } from '@snowluma/protocol/oidb-services/interaction/send-poke';
|
||||
import { SetEssence } from '@snowluma/protocol/oidb-services/interaction/set-essence';
|
||||
import { FetchReactionSummary } from '@snowluma/protocol/oidb-services/reaction/fetch-reaction-summary';
|
||||
import { GetEmojiLikes } from '@snowluma/protocol/oidb-services/reaction/get-emoji-likes';
|
||||
import { SetReaction } from '@snowluma/protocol/oidb-services/reaction/set-reaction';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
export class InteractionApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
|
||||
sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise<void> {
|
||||
return SendPoke.invoke(this.ctx, { isGroup, peerUin, targetUin });
|
||||
}
|
||||
|
||||
sendLike(userId: number, count: number): Promise<void> {
|
||||
return SendLike.invoke(this.ctx, { userId, count });
|
||||
}
|
||||
|
||||
setReaction(groupId: number, sequence: number, code: string, isSet: boolean): Promise<void> {
|
||||
return SetReaction.invoke(this.ctx, { groupId, sequence, code, isSet });
|
||||
}
|
||||
|
||||
setEssence(groupId: number, sequence: number, random: number, enable: boolean): Promise<void> {
|
||||
return SetEssence.invoke(this.ctx, { groupId, sequence, random, enable });
|
||||
}
|
||||
|
||||
/**
|
||||
* Legacy stub: see `GetEmojiLikes` namespace comment for why this
|
||||
* SSO path can never surface the user list. Real data lives in
|
||||
* ReactionStore on the OneBot side.
|
||||
*/
|
||||
async getEmojiLikes(
|
||||
groupId: number,
|
||||
sequence: number,
|
||||
emojiId: string,
|
||||
emojiType = 1,
|
||||
count = 10,
|
||||
cookie = '',
|
||||
): Promise<{ users: Array<{ uin: number }>; cookie: string; isLast: boolean }> {
|
||||
try {
|
||||
return await GetEmojiLikes.invoke(this.ctx, { groupId, sequence, emojiId, emojiType, count, cookie });
|
||||
} catch {
|
||||
return { users: [], cookie: '', isLast: true };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the per-emoji reaction summary on a group message via
|
||||
* 0x9084_1 — emoji_id + reactor count + last-reaction timestamp.
|
||||
* Cross-checked against the local ReactionStore cache for callers
|
||||
* that need to detect cache gaps.
|
||||
*/
|
||||
fetchReactionSummary(
|
||||
groupId: number,
|
||||
sequence: number,
|
||||
): Promise<Array<{ emojiId: string; emojiType: number; count: number; lastReactionTime: number }>> {
|
||||
return FetchReactionSummary.invoke(this.ctx, { groupId, sequence });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,459 @@
|
||||
import type {
|
||||
SendMessageRequest,
|
||||
SendMessageResponse,
|
||||
} from '@snowluma/proto-defs/action';
|
||||
import type { FileExtra } from '@snowluma/proto-defs/message';
|
||||
import type {
|
||||
C2CRecallRequest,
|
||||
GroupRecallRequest,
|
||||
SsoReadedReportReq,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { buildSendElems } from '@snowluma/protocol/element-builder';
|
||||
import type { MessageElement, QQEventVariant } from '@snowluma/protocol/events';
|
||||
import { fetchC2cMessageRange, fetchGroupMessageRange } from '@snowluma/protocol/msg-push';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
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';
|
||||
|
||||
type GroupMessage = Extract<QQEventVariant, { kind: 'group_message' }>;
|
||||
type FriendMessage = Extract<QQEventVariant, { kind: 'friend_message' }>;
|
||||
|
||||
// ── Group-history fetch guards (the server frequency-limits / kicks abusive
|
||||
// pulls, so keep each request small, bound the loop, and space the sends). ──
|
||||
const HISTORY_MAX_COUNT = 200; // hard cap on messages returned per call
|
||||
const HISTORY_CHUNK_SEQ = 30; // sequence span per server request (small packet)
|
||||
const HISTORY_MAX_REQUESTS = 12; // bound the walk-back loop
|
||||
const HISTORY_MIN_GAP_MS = 300; // minimum spacing between SsoGetGroupMsg sends
|
||||
|
||||
// Serialized throttle gate: chains so concurrent callers queue, and enforces
|
||||
// at least HISTORY_MIN_GAP_MS between actual sends (the first send isn't
|
||||
// penalized). Process-wide — shared across all groups AND accounts in this
|
||||
// process — so no client can make us flood the server regardless of fan-out.
|
||||
let historyLastSendAt = 0;
|
||||
let historyGate: Promise<void> = Promise.resolve();
|
||||
function throttleHistory(): Promise<void> {
|
||||
const run = historyGate.then(async () => {
|
||||
const wait = historyLastSendAt + HISTORY_MIN_GAP_MS - Date.now();
|
||||
if (wait > 0) await new Promise<void>((resolve) => setTimeout(resolve, wait));
|
||||
historyLastSendAt = Date.now();
|
||||
});
|
||||
historyGate = run.catch(() => undefined);
|
||||
return run;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared walk-back loop for group + c2c history: pull HISTORY_CHUNK_SEQ-wide
|
||||
* windows ending at `endSeq`, throttled, walking strictly backward (handling a
|
||||
* server-side short cap via the oldest sequence actually returned), dedup by
|
||||
* sequence, until `count` (capped) is gathered or the floor is reached. Returns
|
||||
* the newest `want` items oldest→newest.
|
||||
*/
|
||||
async function walkBackHistory<T extends { msgSeq: number }>(
|
||||
endSeq: number,
|
||||
count: number,
|
||||
fetchWindow: (startSeq: number, endSeq: number) => Promise<T[]>,
|
||||
): Promise<T[]> {
|
||||
if (!(endSeq > 0)) return [];
|
||||
const want = Math.min(Math.max(1, Math.trunc(count) || 0), HISTORY_MAX_COUNT);
|
||||
|
||||
const collected = new Map<number, T>(); // dedup by sequence
|
||||
let curEnd = endSeq;
|
||||
for (let i = 0; i < HISTORY_MAX_REQUESTS && collected.size < want && curEnd >= 1; i++) {
|
||||
const start = Math.max(1, curEnd - HISTORY_CHUNK_SEQ + 1);
|
||||
await throttleHistory();
|
||||
let batch: T[];
|
||||
try {
|
||||
batch = await fetchWindow(start, curEnd);
|
||||
} catch {
|
||||
break; // network/decode error — return whatever we have so far
|
||||
}
|
||||
if (batch.length > 0) {
|
||||
let minSeq = curEnd;
|
||||
for (const ev of batch) {
|
||||
collected.set(ev.msgSeq, ev);
|
||||
if (ev.msgSeq < minSeq) minSeq = ev.msgSeq;
|
||||
}
|
||||
curEnd = minSeq - 1; // strictly below the oldest returned (covers short caps)
|
||||
} else {
|
||||
curEnd = start - 1; // empty window (recalled/absent seqs) — skip past it
|
||||
}
|
||||
}
|
||||
const all = [...collected.values()].sort((a, b) => a.msgSeq - b.msgSeq);
|
||||
return all.slice(-want); // newest `want`, oldest→newest
|
||||
}
|
||||
|
||||
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,
|
||||
},
|
||||
},
|
||||
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,
|
||||
},
|
||||
},
|
||||
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');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch real group history from the server (`SsoGetGroupMsg`), ending at and
|
||||
* including `endSeq`, walking backward in small windows until `count`
|
||||
* messages are gathered or the floor is reached. Rate-limited + capped so a
|
||||
* hammering client can't make us flood the server (and get the account
|
||||
* kicked). Returns decoded `group_message` events oldest→newest.
|
||||
*/
|
||||
async getGroupHistory(groupUin: number, endSeq: number, count: number, selfUin = 0): Promise<GroupMessage[]> {
|
||||
if (!(groupUin > 0)) return [];
|
||||
return walkBackHistory(endSeq, count, (start, end) =>
|
||||
fetchGroupMessageRange(this.ctx, this.ctx.identity, selfUin, groupUin, start, end));
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch real private (c2c) history from the server (`SsoGetC2cMsg`), ending
|
||||
* at and including `endSeq`. Same rate-limit + data-volume guards as the
|
||||
* group variant (they share the throttle gate). `friendUid` is the
|
||||
* conversation peer's UID. Returns decoded `friend_message` events
|
||||
* oldest→newest.
|
||||
*/
|
||||
async getC2cHistory(friendUid: string, endSeq: number, count: number, selfUin = 0): Promise<FriendMessage[]> {
|
||||
if (!friendUid) return [];
|
||||
return walkBackHistory(endSeq, count, (start, end) =>
|
||||
fetchC2cMessageRange(this.ctx, this.ctx.identity, selfUin, friendUid, start, end));
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a single group message by its exact sequence — `SsoGetGroupMsg` over a
|
||||
* 1-wide `[seq, seq]` range, through the shared history throttle gate. Used to
|
||||
* back-fill a replied-to message the local store never saw. Returns the
|
||||
* matching `group_message`, or null if absent / on error.
|
||||
*/
|
||||
async getGroupMessageBySeq(groupUin: number, seq: number, selfUin = 0): Promise<GroupMessage | null> {
|
||||
if (!(groupUin > 0) || !(seq > 0)) return null;
|
||||
await throttleHistory();
|
||||
try {
|
||||
const batch = await fetchGroupMessageRange(this.ctx, this.ctx.identity, selfUin, groupUin, seq, seq);
|
||||
return batch.find((m) => m.msgSeq === seq) ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a single c2c message by its exact sequence — `SsoGetC2cMsg` over a
|
||||
* 1-wide `[seq, seq]` range, through the same throttle gate. `friendUid` is the
|
||||
* conversation peer. Returns the matching `friend_message`, or null.
|
||||
*/
|
||||
async getC2cMessageBySeq(friendUid: string, seq: number, selfUin = 0): Promise<FriendMessage | null> {
|
||||
if (!friendUid || !(seq > 0)) return null;
|
||||
await throttleHistory();
|
||||
try {
|
||||
const batch = await fetchC2cMessageRange(this.ctx, this.ctx.identity, selfUin, friendUid, seq, seq);
|
||||
return batch.find((m) => m.msgSeq === seq) ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import type { JsonObject, JsonValue } from '@snowluma/common/json';
|
||||
import type {
|
||||
MiniAppShareReq,
|
||||
MiniAppShareResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
// Migrated OIDB cmds — facade methods are one-line forwarders.
|
||||
import { ClickInlineKeyboardButton } from '@snowluma/protocol/oidb-services/misc/click-inline-keyboard-button';
|
||||
import { SendGroupSign } from '@snowluma/protocol/oidb-services/misc/send-group-sign';
|
||||
import { TranslateEnToZh } from '@snowluma/protocol/oidb-services/misc/translate-en-to-zh';
|
||||
import { RequestDbKey } from '@snowluma/protocol/oidb-services/misc/request-decrypt-key';
|
||||
|
||||
export class MiscApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
|
||||
translateEn2Zh(words: string[]): Promise<string[]> {
|
||||
return TranslateEnToZh.invoke(this.ctx, { words });
|
||||
}
|
||||
|
||||
async getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string): Promise<JsonObject> {
|
||||
let appid = '1109937557'; // default: bilibili
|
||||
let iconUrl = 'http://miniapp.gtimg.cn/public/appicon/51f90239b78a2e4994c11215f4c4ba15_200.jpg';
|
||||
|
||||
if (type === 'weibo') {
|
||||
appid = '1109224783';
|
||||
iconUrl = 'http://miniapp.gtimg.cn/public/appicon/35bbb44dc68e65194cfacfb206b8f1f7_200.jpg';
|
||||
} else if (type !== 'bili') {
|
||||
throw new Error(`unsupported type: ${type}, only support bili and weibo`);
|
||||
}
|
||||
|
||||
const request = protobuf_encode<MiniAppShareReq>({
|
||||
sdkVersion: 'V1_PC_MINISDK_99.99.99_1_APP_A',
|
||||
body: { appid, title, desc, picUrl, jumpUrl, iconUrl },
|
||||
});
|
||||
|
||||
const result = await this.ctx.sendRawPacket('LightAppSvc.mini_app_share.AdaptShareInfo', request);
|
||||
|
||||
if (!result.success || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'get mini app ark failed');
|
||||
}
|
||||
|
||||
const decoded = protobuf_decode<MiniAppShareResp>(result.responseData);
|
||||
const jsonStr = decoded?.body?.jsonStr;
|
||||
|
||||
if (!jsonStr) {
|
||||
throw new Error('mini app share json empty');
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(jsonStr) as Record<string, JsonObject | string | number | boolean | null>;
|
||||
|
||||
return {
|
||||
data: {
|
||||
ver: parsed.ver,
|
||||
prompt: parsed.prompt,
|
||||
config: parsed.config,
|
||||
app: parsed.appName,
|
||||
view: parsed.appView,
|
||||
meta: parsed.metaData,
|
||||
miniappShareOrigin: 3,
|
||||
miniappOpenRefer: '10002',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
clickInlineKeyboardButton(
|
||||
groupId: number,
|
||||
botAppid: number,
|
||||
buttonId: string,
|
||||
callbackData: string,
|
||||
msgSeq: number,
|
||||
): Promise<JsonValue> {
|
||||
return ClickInlineKeyboardButton.invoke(this.ctx, { groupId, botAppid, buttonId, callbackData, msgSeq });
|
||||
}
|
||||
|
||||
sendGroupSign(groupId: number): Promise<void> {
|
||||
return SendGroupSign.invoke(this.ctx, { groupId });
|
||||
}
|
||||
|
||||
async getDecryptKey(dbSalt: string): Promise<string> {
|
||||
const result = await RequestDbKey.invoke(this.ctx, { db_salt: dbSalt });
|
||||
if (!result.success) {
|
||||
throw new Error(result.errorMsg || `Failed to get decrypt key (code: ${result.errorCode})`);
|
||||
}
|
||||
if (!result.dbKey) {
|
||||
throw new Error('Decrypt key is empty');
|
||||
}
|
||||
return result.dbKey;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import type {
|
||||
FaceroamOpReq,
|
||||
FaceroamOpResp,
|
||||
GroupAvatarExtra,
|
||||
SetStatusReq,
|
||||
SetStatusResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
|
||||
import { computeHashes, loadBinarySource } from '@snowluma/protocol/highway/utils';
|
||||
import { GetLike, type LikeInfo } from '@snowluma/protocol/oidb-services/profile/get-like';
|
||||
import { GetUnidirectionalFriendList, type UnidirectionalFriendEntry } from '@snowluma/protocol/oidb-services/profile/get-unidirectional-friend-list';
|
||||
import { SetInputStatus } from '@snowluma/protocol/oidb-services/profile/set-input-status';
|
||||
import { SetProfile } from '@snowluma/protocol/oidb-services/profile/set-profile';
|
||||
import { SetSelfLongNick } from '@snowluma/protocol/oidb-services/profile/set-self-long-nick';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { Bridge } from '../bridge';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
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}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setProfile(nickname?: string, personalNote?: string): Promise<void> {
|
||||
return SetProfile.invoke(this.ctx, { nickname, personalNote });
|
||||
}
|
||||
|
||||
setSelfLongNick(longNick: string): Promise<void> {
|
||||
return SetSelfLongNick.invoke(this.ctx, { longNick });
|
||||
}
|
||||
|
||||
setInputStatus(userId: number, eventType: number): Promise<void> {
|
||||
return SetInputStatus.invoke(this.ctx, { userId, eventType });
|
||||
}
|
||||
|
||||
async setAvatar(source: string): Promise<void> {
|
||||
const bridge = 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 ───────────────
|
||||
|
||||
getLike(userId?: number, start = 0, limit = 10): Promise<LikeInfo> {
|
||||
return GetLike.invoke(this.ctx, { userId, start, limit });
|
||||
}
|
||||
|
||||
getUnidirectionalFriendList(): Promise<UnidirectionalFriendEntry[]> {
|
||||
return GetUnidirectionalFriendList.invoke(this.ctx);
|
||||
}
|
||||
|
||||
async fetchCustomFace(count = 10): Promise<string[]> {
|
||||
const req = {
|
||||
inner: { field1: 1, osVersion: '10.0.26200', qqVersion: '9.9.28-46928' },
|
||||
uin: BigInt(this.ctx.identity.uin),
|
||||
field3: 1,
|
||||
field6: 1,
|
||||
};
|
||||
const request = protobuf_encode<FaceroamOpReq>(req);
|
||||
const result = await this.ctx.sendRawPacket('Faceroam.OpReq', request);
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'fetch custom face failed');
|
||||
}
|
||||
const resp = protobuf_decode<FaceroamOpResp>(result.responseData);
|
||||
if (!resp || resp.retCode !== 0) {
|
||||
throw new Error(`fetch custom face error: ${resp?.message || 'unknown'}`);
|
||||
}
|
||||
const faceIds = resp.item?.faceIds || [];
|
||||
return faceIds.slice(0, count).map((id: string) => `https://p.qpic.cn/qq_expression/${this.ctx.identity.uin}/${id}/0`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import type { Bridge } from '../bridge';
|
||||
|
||||
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,333 @@
|
||||
import { loadBinarySource } from '@snowluma/protocol/highway/utils';
|
||||
import { ForceFetchClientKey, type ClientKeyInfo as NamespaceClientKeyInfo } from '@snowluma/protocol/oidb-services/web/force-fetch-client-key';
|
||||
import { GetPskey } from '@snowluma/protocol/oidb-services/web/get-pskey';
|
||||
import { getGroupEssenceMsg, getGroupEssenceMsgAll, type GroupEssenceMsgRet } from '@snowluma/protocol/web/group-essence';
|
||||
import { getHonorListWebAPI, WebHonorType, type WebHonorItem } from '@snowluma/protocol/web/group-honor';
|
||||
import {
|
||||
deleteGroupNotice as deleteGroupNoticeHttp,
|
||||
getGroupNoticeWebAPI,
|
||||
setGroupNoticeWebAPI,
|
||||
uploadGroupNoticeImage,
|
||||
type SetNoticeRetSuccess,
|
||||
} from '@snowluma/protocol/web/group-notice';
|
||||
import { RequestUtil } from '@snowluma/protocol/web/request-util';
|
||||
import type { Bridge } from '../bridge';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
|
||||
|
||||
export type ClientKeyInfo = NamespaceClientKeyInfo;
|
||||
|
||||
export interface WebHonorInfo {
|
||||
[key: string]: import('@snowluma/common/json').JsonValue;
|
||||
group_id: number;
|
||||
current_talkative: WebHonorItem | null;
|
||||
talkative_list: WebHonorItem[];
|
||||
performer_list: WebHonorItem[];
|
||||
legend_list: WebHonorItem[];
|
||||
emotion_list: WebHonorItem[];
|
||||
strong_newbie_list: WebHonorItem[];
|
||||
}
|
||||
|
||||
export interface WebNoticeInfo {
|
||||
[key: string]: import('@snowluma/common/json').JsonValue;
|
||||
notice_id: string;
|
||||
sender_id: number;
|
||||
publish_time: number;
|
||||
message: {
|
||||
text: string;
|
||||
image: Array<{ id: string; height: number; width: number }>;
|
||||
images: Array<{ id: string; height: number; width: number }>;
|
||||
};
|
||||
settings: import('@snowluma/common/json').JsonValue;
|
||||
read_num: number;
|
||||
}
|
||||
|
||||
// ─────────────── private helpers (cookie acquisition) ───────────────
|
||||
|
||||
function forceFetchClientKeyInner(bridge: Bridge): Promise<ClientKeyInfo> {
|
||||
return ForceFetchClientKey.invoke(bridge);
|
||||
}
|
||||
|
||||
function getPSkey(bridge: Bridge, domainList: string[]): Promise<{ domainPskeyMap: Map<string, string> }> {
|
||||
return GetPskey.invoke(bridge, { domainList });
|
||||
}
|
||||
|
||||
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<GroupEssenceMsgRet> {
|
||||
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<GroupEssenceMsgRet[]> {
|
||||
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<WebHonorInfo> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
|
||||
const honorInfo: WebHonorInfo = {
|
||||
group_id: groupId,
|
||||
current_talkative: null,
|
||||
talkative_list: [],
|
||||
performer_list: [],
|
||||
legend_list: [],
|
||||
emotion_list: [],
|
||||
strong_newbie_list: [],
|
||||
};
|
||||
|
||||
if (type === WebHonorType.TALKATIVE || type === WebHonorType.ALL) {
|
||||
const talkativeList = await getHonorListWebAPI(cookieObject, groupCode, 1);
|
||||
if (talkativeList.length > 0) {
|
||||
honorInfo.current_talkative = talkativeList[0];
|
||||
honorInfo.talkative_list = talkativeList;
|
||||
}
|
||||
}
|
||||
|
||||
if (type === WebHonorType.PERFORMER || type === WebHonorType.ALL) {
|
||||
honorInfo.performer_list = await getHonorListWebAPI(cookieObject, groupCode, 2);
|
||||
}
|
||||
|
||||
if (type === WebHonorType.LEGEND || type === WebHonorType.ALL) {
|
||||
honorInfo.legend_list = await getHonorListWebAPI(cookieObject, groupCode, 3);
|
||||
}
|
||||
|
||||
if (type === WebHonorType.EMOTION || type === WebHonorType.ALL) {
|
||||
honorInfo.emotion_list = await getHonorListWebAPI(cookieObject, groupCode, 6);
|
||||
}
|
||||
|
||||
return honorInfo;
|
||||
}
|
||||
|
||||
// ─────────────── group notice ───────────────
|
||||
|
||||
async sendNotice(
|
||||
groupId: number,
|
||||
content: string,
|
||||
options?: {
|
||||
image?: string; // local path, http URL, or undefined (text-only)
|
||||
pinned?: number;
|
||||
type?: number;
|
||||
confirm_required?: number;
|
||||
},
|
||||
): Promise<SetNoticeRetSuccess> {
|
||||
const bridge = 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) {
|
||||
// Route through loadBinarySource so the group-notice image download
|
||||
// gets the same browser-UA + Referer-retry hardening as every other
|
||||
// media fetch — and http/file/base64 source handling for free.
|
||||
const loaded = await loadBinarySource(options.image, 'group-notice image');
|
||||
const imageBuffer = Buffer.from(loaded.bytes);
|
||||
|
||||
const picInfo = await uploadGroupNoticeImage(cookieObject, imageBuffer);
|
||||
if (picInfo) {
|
||||
picId = picInfo.id;
|
||||
imgWidth = picInfo.width;
|
||||
imgHeight = picInfo.height;
|
||||
}
|
||||
}
|
||||
|
||||
const ret = await setGroupNoticeWebAPI(
|
||||
cookieObject,
|
||||
groupCode,
|
||||
content,
|
||||
options?.pinned ?? 0,
|
||||
options?.type ?? 1,
|
||||
1,
|
||||
1,
|
||||
options?.confirm_required ?? 1,
|
||||
picId,
|
||||
imgWidth,
|
||||
imgHeight,
|
||||
);
|
||||
|
||||
if (!ret || ret.ec !== 0) {
|
||||
throw new Error(`设置群公告失败: ${ret?.em || '未知错误(Cookie过期或权限不足)'}`);
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
async getNotice(groupId: number): Promise<WebNoticeInfo[]> {
|
||||
const bridge = 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: WebNoticeInfo[] = [];
|
||||
|
||||
if (ret.feeds) {
|
||||
for (const key in ret.feeds) {
|
||||
const feed = ret.feeds[key];
|
||||
if (!feed) continue;
|
||||
|
||||
const image = feed.msg?.pics?.map((pic) => ({
|
||||
id: pic.id,
|
||||
height: pic.h,
|
||||
width: pic.w,
|
||||
})) || [];
|
||||
|
||||
retNotices.push({
|
||||
notice_id: feed.fid,
|
||||
sender_id: feed.u,
|
||||
publish_time: feed.pubt,
|
||||
message: {
|
||||
text: feed.msg?.text || '',
|
||||
image,
|
||||
images: image,
|
||||
},
|
||||
settings: feed.settings,
|
||||
read_num: feed.read_num,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return retNotices;
|
||||
}
|
||||
|
||||
async deleteNotice(groupId: number, fid: string): Promise<boolean> {
|
||||
const bridge = 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,8 @@
|
||||
import type { BridgeContext as BaseBridgeContext } from '@snowluma/protocol/bridge-context';
|
||||
import type { ApiHub } from './apis';
|
||||
|
||||
export interface BridgeContext extends BaseBridgeContext {
|
||||
readonly apis: ApiHub;
|
||||
}
|
||||
export type { UploadedFileMeta } from '@snowluma/protocol/bridge-context';
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
import type { BridgeContext } from './bridge-context';
|
||||
|
||||
export interface BridgeInterface extends BridgeContext {
|
||||
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}`);
|
||||
}
|
||||
+143
-458
@@ -1,148 +1,87 @@
|
||||
// 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 { createLogger } from '@snowluma/common/logger';
|
||||
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import { MSG_PUSH_CMD, parseMsgPush } from '@snowluma/protocol/msg-push';
|
||||
import { IncomingPacketPipeline, type CmdParser } from '@snowluma/protocol/packet-pipeline';
|
||||
import { buildApiHub, type ApiHub } from './apis';
|
||||
import {
|
||||
SendMessageRequestSchema,
|
||||
SendMessageResponseSchema,
|
||||
} from './proto/action';
|
||||
|
||||
// Delegated modules
|
||||
import { resolveUserUid as resolveUserUid_ } from './bridge-oidb';
|
||||
import {
|
||||
fetchFriendList as fetchFriendList_,
|
||||
fetchGroupList as fetchGroupList_,
|
||||
fetchGroupMemberList as fetchGroupMemberList_,
|
||||
fetchUserProfile as fetchUserProfile_,
|
||||
fetchGroupRequests as fetchGroupRequests_,
|
||||
fetchDownloadRKeys as fetchDownloadRKeys_,
|
||||
} from './bridge-contacts';
|
||||
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_,
|
||||
setFriendRemark as setFriendRemark_,
|
||||
fetchGroupFileCount as fetchGroupFileCount_,
|
||||
} from './bridge-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[];
|
||||
|
||||
export interface SendMessageReceipt {
|
||||
messageId: number;
|
||||
sequence: number;
|
||||
clientSequence: number;
|
||||
random: number;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
export interface DownloadRKeyInfo {
|
||||
rkey: string;
|
||||
ttlSeconds: number;
|
||||
storeId: number;
|
||||
createTime: number;
|
||||
type: number;
|
||||
}
|
||||
AiVoiceChatType,
|
||||
type AiVoiceCategory,
|
||||
type StrangerStatus,
|
||||
} from './apis/extras';
|
||||
import type { BridgeInterface } from './bridge-interface';
|
||||
|
||||
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[]>();
|
||||
readonly events = new BridgeEventBus();
|
||||
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[] }>();
|
||||
|
||||
// Sequence and random generators for outgoing messages
|
||||
private static readonly UPLOADED_FILE_CACHE_MAX = 1024;
|
||||
private uploadedFileMeta_ = new Map<string, UploadedFileMeta>();
|
||||
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;
|
||||
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),
|
||||
resolveStrangerProfile: async (uid) => {
|
||||
try {
|
||||
const p = await this.apis.contacts.fetchUserProfileByUid(uid);
|
||||
if (p.uin <= 0) return null;
|
||||
return { uin: p.uin, nickname: p.nickname };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
resolveGroupJoinRequest: async (groupId, uid, subType) => {
|
||||
try {
|
||||
const requests = await this.apis.contacts.fetchGroupRequests();
|
||||
const match = requests.find(r => {
|
||||
if (r.groupId !== groupId) return false;
|
||||
return subType === 'invite' ? r.invitorUid === uid : r.targetUid === uid;
|
||||
});
|
||||
if (!match) return null;
|
||||
return { comment: match.comment, sequence: match.sequence };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
});
|
||||
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 ---
|
||||
|
||||
attachPid(pid: number): void {
|
||||
this.pids_.add(pid);
|
||||
}
|
||||
@@ -155,363 +94,109 @@ export class Bridge {
|
||||
for (const pid of this.pids_) return pid;
|
||||
return null;
|
||||
}
|
||||
|
||||
// --- 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;
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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);
|
||||
recallUploadedFile(fileId: string): UploadedFileMeta | undefined {
|
||||
if (!fileId) return undefined;
|
||||
return this.uploadedFileMeta_.get(fileId);
|
||||
}
|
||||
|
||||
// --- Sequence / random generators ---
|
||||
|
||||
private nextClientSequence(): number {
|
||||
nextClientSequence(): number {
|
||||
return ++this.clientSeq_;
|
||||
}
|
||||
|
||||
private nextMessageRandom(): number {
|
||||
nextMessageRandom(): number {
|
||||
this.msgRandom_ = (this.msgRandom_ + 0x9E3779B9) >>> 0;
|
||||
return this.msgRandom_ & 0x7FFFFFFF;
|
||||
}
|
||||
|
||||
// --- Send packet (raw) ---
|
||||
|
||||
async sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs = 15000): Promise<SendPacketResult> {
|
||||
if (!this.packetClient_) {
|
||||
log.warn('packet %s dropped: no packet sender attached', serviceCmd);
|
||||
return {
|
||||
success: false, gotResponse: false, errorCode: -1,
|
||||
errorMessage: 'no packet sender attached', responseData: null,
|
||||
};
|
||||
}
|
||||
return this.packetClient_.sendPacket(serviceCmd, Buffer.from(body), timeoutMs);
|
||||
const startedAt = Date.now();
|
||||
const result = await this.packetClient_.sendPacket(serviceCmd, Buffer.from(body), timeoutMs);
|
||||
const elapsed = Date.now() - startedAt;
|
||||
const respLen = result.responseData ? result.responseData.length : 0;
|
||||
if (!result.success || result.errorCode !== 0) {
|
||||
// QQ-side rejection or transport failure — the usual root cause when an
|
||||
// action misbehaves. Warn (persisted) with cmd + code so a user's log
|
||||
// shows exactly where the chain broke.
|
||||
log.warn('packet %s failed: code=%d gotResponse=%s %s (uin=%s, %dB, %dms)',
|
||||
serviceCmd, result.errorCode, result.gotResponse,
|
||||
result.errorMessage ?? '', this.identity.uin, body.length, elapsed);
|
||||
} else {
|
||||
// Happy path — memory-only trace so the full chain shows under the
|
||||
// request's [req#N] when debugging, without flooding disk.
|
||||
log.trace(() => [`packet ${serviceCmd} ok (${body.length}B⇄${respLen}B, ${elapsed}ms)`]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// --- 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,
|
||||
};
|
||||
}
|
||||
|
||||
// --- Delegated: OIDB helpers ---
|
||||
|
||||
async resolveUserUid(uin: number, groupId?: number): Promise<string> {
|
||||
return resolveUserUid_(this, uin, groupId);
|
||||
}
|
||||
|
||||
// --- Delegated: Contact / info queries ---
|
||||
|
||||
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 setFriendRemark(userId: number, remark: string): Promise<void> { return setFriendRemark_(this, userId, remark); }
|
||||
async fetchGroupFileCount(groupId: number): Promise<{ fileCount: number; maxCount: number }> { return fetchGroupFileCount_(this, groupId); }
|
||||
}
|
||||
|
||||
// --- 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;
|
||||
return this.identity.resolveUid(uin, groupId);
|
||||
}
|
||||
}
|
||||
export interface SendMessageReceipt {
|
||||
messageId: number;
|
||||
sequence: number;
|
||||
clientSequence: number;
|
||||
random: number;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
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;
|
||||
storeId: number;
|
||||
createTime: number;
|
||||
type: number;
|
||||
}
|
||||
|
||||
export interface ClientKeyInfo {
|
||||
clientKey: string;
|
||||
expireTime: string;
|
||||
keyIndex: string
|
||||
}
|
||||
export { AiVoiceChatType };
|
||||
export type { AiVoiceCategory, StrangerStatus };
|
||||
|
||||
@@ -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,216 +0,0 @@
|
||||
// Highway HTTP client: session fetch and chunked binary upload.
|
||||
// Port of src/bridge/src/highway_client.cpp
|
||||
|
||||
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';
|
||||
|
||||
const HIGHWAY_APP_ID = 1600001604;
|
||||
const HIGHWAY_BLOCK_SIZE = 1024 * 1024;
|
||||
|
||||
export const PRIVATE_IMAGE_CMD_ID = 1003;
|
||||
export const GROUP_IMAGE_CMD_ID = 1004;
|
||||
|
||||
export interface HighwaySession {
|
||||
sigSession: Uint8Array;
|
||||
sessionKey: Uint8Array;
|
||||
host: string;
|
||||
port: number;
|
||||
}
|
||||
|
||||
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({
|
||||
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);
|
||||
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');
|
||||
}
|
||||
|
||||
const session: HighwaySession = {
|
||||
sigSession: resp.httpConn.sigSession as Uint8Array,
|
||||
sessionKey: (resp.httpConn.sessionKey as Uint8Array) ?? new Uint8Array(0),
|
||||
host: 'htdata3.qq.com',
|
||||
port: 80,
|
||||
};
|
||||
|
||||
for (const si of resp.httpConn.serverInfos ?? []) {
|
||||
if ((si.serviceType ?? 0) !== 1 || !si.serverAddrs?.length) continue;
|
||||
for (const addr of si.serverAddrs) {
|
||||
const ip = addr.ip ?? 0;
|
||||
const port = addr.port ?? 0;
|
||||
if (ip && port) {
|
||||
session.host = ipv4ToString(ip);
|
||||
session.port = port;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`[Highway] session: ${session.host}:${session.port} sig=${(session.sigSession as Uint8Array).length}B`);
|
||||
return session;
|
||||
}
|
||||
|
||||
function makeHighwayHead(
|
||||
uin: string, commandId: number, fileSize: number, offset: number, length: number,
|
||||
chunkMd5: Uint8Array, fileMd5: Uint8Array, sigSession: Uint8Array, extend: Uint8Array,
|
||||
): Uint8Array {
|
||||
return protoEncode({
|
||||
msgBaseHead: {
|
||||
version: 1, uin, command: 'PicUp.DataUp', seq: 0, retryTimes: 0,
|
||||
appId: HIGHWAY_APP_ID, dataFlag: 16, commandId,
|
||||
},
|
||||
msgSegHead: {
|
||||
serviceId: 0, filesize: BigInt(fileSize), dataOffset: BigInt(offset), dataLength: length,
|
||||
retCode: 0, serviceTicket: sigSession, flag: 0, md5: chunkMd5, fileMd5, cacheAddr: 0, cachePort: 0,
|
||||
},
|
||||
bytesReqExtendInfo: extend,
|
||||
timestamp: 0n,
|
||||
msgLoginSigHead: { loginSigType: 8, appId: HIGHWAY_APP_ID },
|
||||
}, ReqDataHighwayHeadSchema);
|
||||
}
|
||||
|
||||
export function buildHighwayExtend(
|
||||
uKey: string, msgInfo: any, ipv4s: any[], sha1: Uint8Array,
|
||||
): Uint8Array {
|
||||
const msgInfoBody = msgInfo?.msgInfoBody ?? [];
|
||||
if (msgInfoBody.length === 0) throw new Error('upload response missing msg_info body');
|
||||
|
||||
const first = msgInfoBody[0];
|
||||
const networkIpv4s: any[] = [];
|
||||
for (const ipv4 of ipv4s ?? []) {
|
||||
const ip = ipv4.outIp ?? 0;
|
||||
const port = ipv4.outPort ?? 0;
|
||||
if (ip && port) {
|
||||
networkIpv4s.push({ domain: { isEnable: true, ip: ipv4ToString(ip) }, port });
|
||||
}
|
||||
}
|
||||
|
||||
return protoEncode({
|
||||
fileUuid: first?.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);
|
||||
}
|
||||
|
||||
// --- 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));
|
||||
socket.setTimeout(timeoutMs);
|
||||
socket.on('timeout', () => { socket.destroy(); reject(new Error('TCP connect timeout')); });
|
||||
socket.on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
function socketWrite(socket: net.Socket, data: Uint8Array): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
socket.write(data, (err) => err ? reject(err) : resolve());
|
||||
});
|
||||
}
|
||||
|
||||
function readHttpResponseBody(socket: net.Socket): Promise<Uint8Array> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunks: Buffer[] = [];
|
||||
let headerEnd = -1;
|
||||
let contentLength = 0;
|
||||
let totalNeeded = 0;
|
||||
|
||||
const checkComplete = () => {
|
||||
const buf = Buffer.concat(chunks);
|
||||
if (headerEnd < 0) {
|
||||
const idx = buf.indexOf('\r\n\r\n');
|
||||
if (idx >= 0) {
|
||||
headerEnd = idx + 4;
|
||||
const headerStr = buf.subarray(0, headerEnd).toString('ascii').toLowerCase();
|
||||
const clMatch = headerStr.match(/content-length:\s*(\d+)/);
|
||||
contentLength = clMatch ? parseInt(clMatch[1], 10) : 0;
|
||||
totalNeeded = headerEnd + contentLength;
|
||||
}
|
||||
}
|
||||
if (headerEnd >= 0 && buf.length >= totalNeeded) {
|
||||
socket.removeAllListeners('data');
|
||||
socket.removeAllListeners('error');
|
||||
resolve(new Uint8Array(buf.subarray(headerEnd, totalNeeded)));
|
||||
}
|
||||
};
|
||||
|
||||
socket.on('data', (chunk) => { chunks.push(chunk); checkComplete(); });
|
||||
socket.on('error', reject);
|
||||
socket.on('close', () => {
|
||||
const buf = Buffer.concat(chunks);
|
||||
if (headerEnd >= 0) resolve(new Uint8Array(buf.subarray(headerEnd)));
|
||||
else reject(new Error('connection closed before response'));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function httpPostFrame(
|
||||
socket: net.Socket, host: string, path: string, body: Uint8Array,
|
||||
): Promise<Uint8Array> {
|
||||
const header = `POST ${path} HTTP/1.1\r\nHost: ${host}\r\nConnection: keep-alive\r\nAccept-Encoding: identity\r\nUser-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2)\r\nContent-Length: ${body.length}\r\n\r\n`;
|
||||
await socketWrite(socket, Buffer.from(header, 'ascii'));
|
||||
if (body.length > 0) await socketWrite(socket, body);
|
||||
return readHttpResponseBody(socket);
|
||||
}
|
||||
|
||||
export async function uploadHighwayHttp(
|
||||
bridge: Bridge, session: HighwaySession, commandId: number,
|
||||
bytes: Uint8Array, fileMd5: Uint8Array, extend: Uint8Array,
|
||||
): Promise<void> {
|
||||
const pathStr = `/cgi-bin/httpconn?htcmd=0x6FF0087&uin=${bridge.qqInfo.uin}`;
|
||||
const socket = await tcpConnect(session.host, session.port);
|
||||
|
||||
try {
|
||||
let offset = 0;
|
||||
while (offset < bytes.length) {
|
||||
const chunkSize = Math.min(HIGHWAY_BLOCK_SIZE, bytes.length - offset);
|
||||
const chunk = bytes.subarray(offset, offset + chunkSize);
|
||||
const chunkMd5 = computeMd5(chunk);
|
||||
const head = makeHighwayHead(
|
||||
bridge.qqInfo.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);
|
||||
if (resp?.errorCode && resp.errorCode !== 0) {
|
||||
throw new Error(`highway upload error_code=${resp.errorCode}`);
|
||||
}
|
||||
offset += chunkSize;
|
||||
console.log(`[Highway] uploaded ${offset}/${bytes.length} bytes`);
|
||||
}
|
||||
} finally {
|
||||
socket.destroy();
|
||||
}
|
||||
}
|
||||
@@ -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,198 +0,0 @@
|
||||
// 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';
|
||||
|
||||
export interface LoadedBinary {
|
||||
bytes: Uint8Array;
|
||||
fileName: string;
|
||||
}
|
||||
|
||||
export interface ImageHashes {
|
||||
md5: Uint8Array;
|
||||
sha1: Uint8Array;
|
||||
md5Hex: string;
|
||||
sha1Hex: string;
|
||||
}
|
||||
|
||||
export interface ImageFormat {
|
||||
format: number; // 1000=jpg, 1001=png, 1002=webp, 1005=bmp, 2000=gif
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
// --- Binary source loading ---
|
||||
|
||||
export async function loadBinarySource(source: string, resourceName: string): Promise<LoadedBinary> {
|
||||
if (!source) throw new Error(`${resourceName} source is empty`);
|
||||
|
||||
if (source.startsWith('base64://')) {
|
||||
return { bytes: Buffer.from(source.slice(9), 'base64'), fileName: '' };
|
||||
}
|
||||
|
||||
if (source.startsWith('http://') || source.startsWith('https://')) {
|
||||
const resp = await fetch(source);
|
||||
if (!resp.ok) throw new Error(`HTTP download failed: ${resp.status}`);
|
||||
const bytes = new Uint8Array(await resp.arrayBuffer());
|
||||
const fileName = guessFileNameFromUrl(source);
|
||||
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 bytes = fs.readFileSync(filePath);
|
||||
const fileName = path.basename(filePath);
|
||||
return { bytes, fileName };
|
||||
}
|
||||
|
||||
function guessFileNameFromUrl(url: string): string {
|
||||
const queryPos = url.search(/[?#]/);
|
||||
const pathPart = queryPos >= 0 ? url.slice(0, queryPos) : url;
|
||||
const lastSlash = pathPart.lastIndexOf('/');
|
||||
return lastSlash >= 0 ? pathPart.slice(lastSlash + 1) : '';
|
||||
}
|
||||
|
||||
// --- Hashing ---
|
||||
|
||||
export function computeHashes(data: Uint8Array): ImageHashes {
|
||||
const md5 = createHash('md5').update(data).digest();
|
||||
const sha1 = createHash('sha1').update(data).digest();
|
||||
return {
|
||||
md5: new Uint8Array(md5),
|
||||
sha1: new Uint8Array(sha1),
|
||||
md5Hex: md5.toString('hex'),
|
||||
sha1Hex: sha1.toString('hex'),
|
||||
};
|
||||
}
|
||||
|
||||
export function computeMd5(data: Uint8Array): Uint8Array {
|
||||
return new Uint8Array(createHash('md5').update(data).digest());
|
||||
}
|
||||
|
||||
// --- Image format detection (port of C++ detect_image_format) ---
|
||||
|
||||
function readBE16(data: Uint8Array, offset: number): number {
|
||||
return (data[offset] << 8) | data[offset + 1];
|
||||
}
|
||||
|
||||
function readBE32(data: Uint8Array, offset: number): number {
|
||||
return ((data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3]) >>> 0;
|
||||
}
|
||||
|
||||
function readLE16(data: Uint8Array, offset: number): number {
|
||||
return data[offset] | (data[offset + 1] << 8);
|
||||
}
|
||||
|
||||
function readLE32(data: Uint8Array, offset: number): number {
|
||||
return (data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)) >>> 0;
|
||||
}
|
||||
|
||||
function readBE24(data: Uint8Array, offset: number): number {
|
||||
return (data[offset] << 16) | (data[offset + 1] << 8) | data[offset + 2];
|
||||
}
|
||||
|
||||
export function detectImageFormat(bytes: Uint8Array): ImageFormat {
|
||||
let width = 0;
|
||||
let height = 0;
|
||||
|
||||
// PNG
|
||||
if (bytes.length >= 24 &&
|
||||
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 };
|
||||
}
|
||||
|
||||
// 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) {
|
||||
width = readLE16(bytes, 6);
|
||||
height = readLE16(bytes, 8);
|
||||
return { format: 2000, width, height };
|
||||
}
|
||||
|
||||
// BMP
|
||||
if (bytes.length >= 26 && bytes[0] === 0x42 && bytes[1] === 0x4D) {
|
||||
width = readLE32(bytes, 18);
|
||||
height = readLE32(bytes, 22);
|
||||
return { format: 1005, width, height };
|
||||
}
|
||||
|
||||
// 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) {
|
||||
if (bytes[12] === 0x56 && bytes[13] === 0x50 && bytes[14] === 0x38 && bytes[15] === 0x20) {
|
||||
width = readLE16(bytes, 26);
|
||||
height = readLE16(bytes, 28);
|
||||
return { format: 1002, width, height };
|
||||
}
|
||||
if (bytes[12] === 0x56 && bytes[13] === 0x50 && bytes[14] === 0x38 && bytes[15] === 0x4C) {
|
||||
const bits = readLE32(bytes, 21);
|
||||
width = (bits & 0x3FFF) + 1;
|
||||
height = ((bits >> 14) & 0x3FFF) + 1;
|
||||
return { format: 1002, width, height };
|
||||
}
|
||||
if (bytes[12] === 0x56 && bytes[13] === 0x50 && bytes[14] === 0x38 && bytes[15] === 0x58) {
|
||||
width = readBE24(bytes, 24) + 1;
|
||||
height = readBE24(bytes, 27) + 1;
|
||||
return { format: 1002, width, height };
|
||||
}
|
||||
}
|
||||
|
||||
// JPEG
|
||||
if (bytes.length >= 4 && bytes[0] === 0xFF && bytes[1] === 0xD8) {
|
||||
let offset = 2;
|
||||
while (offset + 9 <= bytes.length) {
|
||||
if (bytes[offset] !== 0xFF) { offset++; continue; }
|
||||
const marker = bytes[offset + 1];
|
||||
if (marker === 0xD8 || marker === 0xD9) { offset += 2; continue; }
|
||||
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) {
|
||||
height = readBE16(bytes, offset + 5);
|
||||
width = readBE16(bytes, offset + 7);
|
||||
return { format: 1000, width, height };
|
||||
}
|
||||
offset += 2 + segLen;
|
||||
}
|
||||
return { format: 1000, width: 0, height: 0 };
|
||||
}
|
||||
|
||||
return { format: 1000, width: 0, height: 0 };
|
||||
}
|
||||
|
||||
// --- Highway frame packing/unpacking ---
|
||||
|
||||
export function packHighwayFrame(head: Uint8Array, body: Uint8Array): Uint8Array {
|
||||
const frame = new Uint8Array(9 + head.length + body.length + 1);
|
||||
frame[0] = 0x28;
|
||||
const dv = new DataView(frame.buffer, frame.byteOffset);
|
||||
dv.setUint32(1, head.length, false);
|
||||
dv.setUint32(5, body.length, false);
|
||||
frame.set(head, 9);
|
||||
frame.set(body, 9 + head.length);
|
||||
frame[frame.length - 1] = 0x29;
|
||||
return frame;
|
||||
}
|
||||
|
||||
export function unpackHighwayFrame(frame: Uint8Array): { head: Uint8Array; body: Uint8Array } {
|
||||
if (frame.length < 10 || frame[0] !== 0x28 || frame[frame.length - 1] !== 0x29) {
|
||||
throw new Error('invalid highway response frame');
|
||||
}
|
||||
const dv = new DataView(frame.buffer, frame.byteOffset);
|
||||
const headLen = dv.getUint32(1, false);
|
||||
const bodyLen = dv.getUint32(5, false);
|
||||
return {
|
||||
head: frame.subarray(9, 9 + headLen),
|
||||
body: frame.subarray(9 + headLen, 9 + headLen + bodyLen),
|
||||
};
|
||||
}
|
||||
@@ -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 { createLogger } from '@snowluma/common/logger';
|
||||
import type { PacketSender } from '@snowluma/common/packet-sender';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import { Bridge } from './bridge';
|
||||
import { QQInfo } from './qq-info';
|
||||
import type { PacketSender } from '../protocol/packet-sender';
|
||||
import { createLogger } from '../utils/logger';
|
||||
|
||||
export type SessionStartedCallback = (uin: string, qqInfo: QQInfo, bridge: Bridge) => void;
|
||||
export type SessionStartedCallback = (uin: string, bridge: Bridge) => void;
|
||||
export type SessionClosedCallback = (uin: string) => void;
|
||||
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,788 +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;
|
||||
@@ -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,75 +0,0 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
export interface RuntimeConfig {
|
||||
webuiPort?: number;
|
||||
}
|
||||
|
||||
const CONFIG_DIR = 'config';
|
||||
const RUNTIME_CONFIG_PATH = path.join(CONFIG_DIR, 'runtime.json');
|
||||
|
||||
const DEFAULT_RUNTIME_CONFIG: RuntimeConfig = {
|
||||
webuiPort: 5099,
|
||||
};
|
||||
|
||||
export function loadRuntimeConfig(): RuntimeConfig {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
|
||||
const loaded = tryLoadRuntimeConfig();
|
||||
if (!loaded) {
|
||||
saveRuntimeConfig(DEFAULT_RUNTIME_CONFIG);
|
||||
return { ...DEFAULT_RUNTIME_CONFIG };
|
||||
}
|
||||
|
||||
const normalized: RuntimeConfig = {
|
||||
webuiPort: normalizePort(loaded.webuiPort ?? 5099, 5099),
|
||||
};
|
||||
|
||||
if (
|
||||
normalized.webuiPort !== loaded.webuiPort
|
||||
) {
|
||||
saveRuntimeConfig(normalized);
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
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),
|
||||
};
|
||||
} 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 isObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
Vendored
+1
@@ -1 +1,2 @@
|
||||
declare const __BUILD_WEBUI__: boolean;
|
||||
declare const __APP_VERSION__: string;
|
||||
@@ -1,519 +0,0 @@
|
||||
import type { BridgeManager } from '../bridge/manager';
|
||||
import type { NtqqHandler } from '../protocol/ntqq-handler';
|
||||
import { createLogger } from '../utils/logger';
|
||||
import { HookPacketClient } from './hook-packet-client';
|
||||
import { injectHookProcess, listHookProcesses, unloadHookProcess, type HookInjectResult, type HookProcessBaseInfo } from './injector';
|
||||
import { QqHookClient, type QqHookLoginState, type QqHookPacket } from './qq-hook-client';
|
||||
|
||||
const log = createLogger('Hook');
|
||||
const DEFAULT_WATCHER_INTERVAL_MS = 1500;
|
||||
const MIN_WATCHER_INTERVAL_MS = 250;
|
||||
|
||||
export type HookProcessStatus =
|
||||
| 'available'
|
||||
| 'loading'
|
||||
| 'connecting'
|
||||
| 'loaded'
|
||||
| 'online'
|
||||
| 'error'
|
||||
| 'disconnected';
|
||||
|
||||
export interface HookProcessInfo extends HookProcessBaseInfo {
|
||||
injected: boolean;
|
||||
connected: boolean;
|
||||
loggedIn: boolean;
|
||||
uin: string;
|
||||
status: HookProcessStatus;
|
||||
error: string;
|
||||
method: string;
|
||||
}
|
||||
|
||||
interface HookProcessState extends HookProcessInfo {
|
||||
client: QqHookClient | null;
|
||||
sender: HookPacketClient | null;
|
||||
injectResult: HookInjectResult | null;
|
||||
bound: boolean;
|
||||
}
|
||||
|
||||
export interface HookManagerOptions {
|
||||
/** Background pipe-watcher polling interval. Lower = faster reconnect but
|
||||
* more frequent named-pipe directory listings. Defaults to 1500 ms. */
|
||||
watcherIntervalMs?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Manages SnowLuma hook injection and bridge connectivity for QQ.exe processes.
|
||||
*
|
||||
* Lifecycle: load -> inject DLL only (returns fast) -> background watcher
|
||||
* detects the named pipe coming up and connects -> on QQ login the bridge is
|
||||
* notified. The watcher also handles reconnect after a pipe drop and detects
|
||||
* hooks that survived a previous SnowLuma restart.
|
||||
*
|
||||
* Concurrency: every per-PID mutation (load / unload / refresh / connect /
|
||||
* close-handler / watcher reconcile) goes through a per-PID promise chain so
|
||||
* users can spam buttons without races.
|
||||
*/
|
||||
export class HookManager {
|
||||
private readonly states = new Map<number, HookProcessState>();
|
||||
private readonly opsByPid = new Map<number, Promise<unknown>>();
|
||||
private readonly watcherIntervalMs: number;
|
||||
private watcherTimer: NodeJS.Timeout | null = null;
|
||||
private watcherTicking = false;
|
||||
private disposed = false;
|
||||
|
||||
constructor(
|
||||
private readonly ntqq: NtqqHandler,
|
||||
private readonly bridgeManager: BridgeManager,
|
||||
options: HookManagerOptions = {},
|
||||
) {
|
||||
this.watcherIntervalMs = Math.max(
|
||||
MIN_WATCHER_INTERVAL_MS,
|
||||
options.watcherIntervalMs ?? DEFAULT_WATCHER_INTERVAL_MS,
|
||||
);
|
||||
// Boot the watcher on the next tick so callers can attach listeners first.
|
||||
this.scheduleWatcher(0);
|
||||
}
|
||||
|
||||
async listProcesses(): Promise<HookProcessInfo[]> {
|
||||
const processes = listHookProcesses();
|
||||
const seen = new Set<number>();
|
||||
for (const proc of processes) {
|
||||
seen.add(proc.pid);
|
||||
const state = this.ensureState(proc.pid);
|
||||
state.name = proc.name || state.name;
|
||||
state.path = proc.path || state.path;
|
||||
}
|
||||
const result: HookProcessInfo[] = [];
|
||||
for (const proc of processes) {
|
||||
result.push(this.toPublicInfo(this.ensureState(proc.pid)));
|
||||
}
|
||||
for (const state of this.states.values()) {
|
||||
if (!seen.has(state.pid) && (state.injected || state.client)) {
|
||||
result.push(this.toPublicInfo(state));
|
||||
}
|
||||
}
|
||||
return result.sort((a, b) => a.pid - b.pid);
|
||||
}
|
||||
|
||||
loadProcess(pid: number): Promise<HookProcessInfo> {
|
||||
if (!Number.isInteger(pid) || pid <= 0) throw new Error('invalid pid');
|
||||
return this.serialize(pid, () => this.loadProcessInternal(pid));
|
||||
}
|
||||
|
||||
unloadProcess(pid: number): Promise<HookProcessInfo> {
|
||||
if (!Number.isInteger(pid) || pid <= 0) throw new Error('invalid pid');
|
||||
return this.serialize(pid, () => this.unloadProcessInternal(pid));
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-probe the named pipe for `pid`, reconnect if it became available,
|
||||
* or tear down a stale connection if it disappeared. Safe to call at any
|
||||
* time; serialised against load/unload/watcher actions on the same PID.
|
||||
*/
|
||||
refreshProcess(pid: number): Promise<HookProcessInfo> {
|
||||
if (!Number.isInteger(pid) || pid <= 0) throw new Error('invalid pid');
|
||||
return this.serialize(pid, () => this.refreshProcessInternal(pid));
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.disposed = true;
|
||||
if (this.watcherTimer) {
|
||||
clearTimeout(this.watcherTimer);
|
||||
this.watcherTimer = null;
|
||||
}
|
||||
for (const state of this.states.values()) {
|
||||
this.tearDownClient(state);
|
||||
state.status = state.injected ? 'disconnected' : 'available';
|
||||
}
|
||||
}
|
||||
|
||||
// ───────────────────────── per-PID serialization ─────────────────────────
|
||||
|
||||
/**
|
||||
* Serialise an operation against a per-PID promise chain. Guarantees that
|
||||
* load / unload / refresh / watcher-driven connects for the same PID never
|
||||
* interleave even if the user mashes buttons.
|
||||
*/
|
||||
private async serialize<T>(pid: number, op: () => Promise<T>): Promise<T> {
|
||||
const previous = this.opsByPid.get(pid) ?? Promise.resolve();
|
||||
let release!: () => void;
|
||||
const completion = new Promise<void>(resolve => { release = resolve; });
|
||||
const chained = previous.then(() => completion);
|
||||
this.opsByPid.set(pid, chained);
|
||||
try {
|
||||
await previous.catch(() => undefined);
|
||||
return await op();
|
||||
} finally {
|
||||
release();
|
||||
// Drop the chain entry once nothing else is waiting on it.
|
||||
if (this.opsByPid.get(pid) === chained) this.opsByPid.delete(pid);
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────── load / unload ──────────────────────────────
|
||||
|
||||
private async loadProcessInternal(pid: number): Promise<HookProcessInfo> {
|
||||
const state = this.ensureState(pid);
|
||||
state.error = '';
|
||||
state.status = 'loading';
|
||||
|
||||
try {
|
||||
if (!state.injected) {
|
||||
// Fast path: a previous SnowLuma run may have left the hook DLL
|
||||
// resident in QQ.exe. If the control pipe is already listed we skip
|
||||
// re-injection and let the watcher reconnect instead.
|
||||
const livePipes = await QqHookClient.listLivePipes();
|
||||
if (livePipes.has(pid)) {
|
||||
state.injected = true;
|
||||
state.method = 'reconnect';
|
||||
log.info('PID=%d already has SnowLuma pipe; will reconnect via watcher', pid);
|
||||
} else {
|
||||
state.injectResult = injectHookProcess(pid);
|
||||
state.injected = true;
|
||||
state.method = state.injectResult.method;
|
||||
log.info('SnowLuma loaded into PID=%d via %s', pid, state.method);
|
||||
}
|
||||
}
|
||||
state.status = state.connected
|
||||
? (state.loggedIn ? 'online' : 'loaded')
|
||||
: 'connecting';
|
||||
} catch (error) {
|
||||
state.status = 'error';
|
||||
state.error = error instanceof Error ? error.message : String(error);
|
||||
log.error('load failed: PID=%d err=%s', pid, state.error);
|
||||
}
|
||||
|
||||
// Wake the watcher so it can pick up the freshly-injected pipe asap
|
||||
// instead of waiting up to one full interval.
|
||||
this.scheduleWatcher(0);
|
||||
return this.toPublicInfo(state);
|
||||
}
|
||||
|
||||
private async unloadProcessInternal(pid: number): Promise<HookProcessInfo> {
|
||||
const state = this.ensureState(pid);
|
||||
state.error = '';
|
||||
|
||||
try {
|
||||
const wasLoggedIn = state.loggedIn;
|
||||
this.tearDownClient(state);
|
||||
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid);
|
||||
|
||||
const handle = state.injectResult?.handle;
|
||||
if (state.injected && handle) {
|
||||
unloadHookProcess(pid, handle);
|
||||
log.info('SnowLuma unloaded from PID=%d via unloadModuleManual', pid);
|
||||
}
|
||||
|
||||
// Clear injection state first
|
||||
state.injected = false;
|
||||
state.injectResult = null;
|
||||
state.method = '';
|
||||
state.uin = '0';
|
||||
|
||||
// Verify unload succeeded by checking if pipe still exists
|
||||
const livePipes = await QqHookClient.listLivePipes();
|
||||
if (livePipes.has(pid)) {
|
||||
// Pipe still exists - unload failed, but let watcher handle reconnection
|
||||
state.error = 'DLL卸载失败:命名管道仍然存在,watcher将自动重连';
|
||||
state.status = 'connecting'; // Let watcher pick it up and reconnect
|
||||
log.warn('unload verification failed: PID=%d pipe still exists after unloadModuleManual, watcher will reconnect', pid);
|
||||
} else {
|
||||
// Successfully unloaded
|
||||
state.status = 'available';
|
||||
state.error = '';
|
||||
}
|
||||
} catch (error) {
|
||||
state.status = 'error';
|
||||
state.error = error instanceof Error ? error.message : String(error);
|
||||
log.error('unload failed: PID=%d err=%s', pid, state.error);
|
||||
}
|
||||
|
||||
return this.toPublicInfo(state);
|
||||
}
|
||||
|
||||
private async refreshProcessInternal(pid: number): Promise<HookProcessInfo> {
|
||||
const state = this.ensureState(pid);
|
||||
state.error = '';
|
||||
|
||||
try {
|
||||
const livePipes = await QqHookClient.listLivePipes();
|
||||
const pipeUp = livePipes.has(pid);
|
||||
|
||||
if (pipeUp) {
|
||||
// A live pipe means a SnowLuma DLL is resident — even if we did not
|
||||
// inject it ourselves (e.g. left over from a prior run).
|
||||
if (!state.injected) {
|
||||
state.injected = true;
|
||||
state.method = state.method || 'reconnect';
|
||||
}
|
||||
if (state.client?.isClosed) this.tearDownClient(state);
|
||||
if (!state.connected) {
|
||||
await this.attemptConnect(state);
|
||||
} else {
|
||||
state.status = state.loggedIn ? 'online' : 'loaded';
|
||||
}
|
||||
} else {
|
||||
// Pipe is gone; if we still hold a client, drop it and surface the
|
||||
// appropriate disconnected/available state to the UI.
|
||||
const wasLoggedIn = state.loggedIn;
|
||||
this.tearDownClient(state);
|
||||
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid);
|
||||
state.status = state.injected ? 'disconnected' : 'available';
|
||||
}
|
||||
} catch (error) {
|
||||
state.error = error instanceof Error ? error.message : String(error);
|
||||
state.status = state.injected ? 'disconnected' : 'error';
|
||||
log.warn('refresh failed: PID=%d err=%s', pid, state.error);
|
||||
}
|
||||
|
||||
return this.toPublicInfo(state);
|
||||
}
|
||||
|
||||
private ensureState(pid: number): HookProcessState {
|
||||
let state = this.states.get(pid);
|
||||
if (!state) {
|
||||
state = {
|
||||
pid,
|
||||
name: 'QQ.exe',
|
||||
path: '',
|
||||
injected: false,
|
||||
connected: false,
|
||||
loggedIn: false,
|
||||
uin: '0',
|
||||
status: 'available',
|
||||
error: '',
|
||||
method: '',
|
||||
client: null,
|
||||
sender: null,
|
||||
injectResult: null,
|
||||
bound: false,
|
||||
};
|
||||
this.states.set(pid, state);
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
// ───────────────────────────── pipe watcher ──────────────────────────────
|
||||
|
||||
private scheduleWatcher(delayMs: number): void {
|
||||
if (this.disposed) return;
|
||||
if (this.watcherTimer) {
|
||||
clearTimeout(this.watcherTimer);
|
||||
this.watcherTimer = null;
|
||||
}
|
||||
this.watcherTimer = setTimeout(() => {
|
||||
this.watcherTimer = null;
|
||||
void this.tickWatcher();
|
||||
}, Math.max(0, delayMs));
|
||||
}
|
||||
|
||||
private async tickWatcher(): Promise<void> {
|
||||
if (this.disposed) return;
|
||||
if (this.watcherTicking) {
|
||||
this.scheduleWatcher(this.watcherIntervalMs);
|
||||
return;
|
||||
}
|
||||
this.watcherTicking = true;
|
||||
try {
|
||||
const livePipes = await QqHookClient.listLivePipes();
|
||||
const processes = listHookProcesses();
|
||||
|
||||
// Refresh metadata + ensure a state entry exists for each known PID.
|
||||
for (const proc of processes) {
|
||||
const state = this.ensureState(proc.pid);
|
||||
state.name = proc.name || state.name;
|
||||
state.path = proc.path || state.path;
|
||||
}
|
||||
// Auto-detect hooks that survived a SnowLuma restart or failed unload.
|
||||
for (const pid of livePipes) {
|
||||
const state = this.ensureState(pid);
|
||||
if (!state.injected) {
|
||||
state.injected = true;
|
||||
state.method = state.method || 'reconnect';
|
||||
if (state.status === 'available') state.status = 'connecting';
|
||||
log.info('Detected pre-existing SnowLuma pipe in PID=%d', pid);
|
||||
}
|
||||
}
|
||||
|
||||
const runningSet = new Set(processes.map(p => p.pid));
|
||||
const tasks: Promise<unknown>[] = [];
|
||||
for (const state of [...this.states.values()]) {
|
||||
const alivePipe = livePipes.has(state.pid);
|
||||
const aliveProc = runningSet.has(state.pid);
|
||||
|
||||
// Reap stale state entries that have nothing left to do.
|
||||
if (!aliveProc && !alivePipe && !state.injected && !state.client) {
|
||||
this.states.delete(state.pid);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Pipe vanished but we still hold a client → schedule a teardown.
|
||||
if (state.connected && !alivePipe) {
|
||||
tasks.push(this.serialize(state.pid, async () => this.reconcileLostPipe(state.pid))
|
||||
.catch(err => log.warn('watcher teardown failed: PID=%d err=%s', state.pid, this.errMsg(err))));
|
||||
continue;
|
||||
}
|
||||
|
||||
// Injected & pipe up but not connected → schedule a connect.
|
||||
if (state.injected && !state.connected && alivePipe) {
|
||||
tasks.push(this.serialize(state.pid, async () => this.reconcileConnect(state.pid))
|
||||
.catch(err => log.warn('watcher connect failed: PID=%d err=%s', state.pid, this.errMsg(err))));
|
||||
continue;
|
||||
}
|
||||
|
||||
// Injected but pipe still pending → keep status visible to the UI.
|
||||
if (state.injected && !state.connected && !alivePipe) {
|
||||
if (state.status !== 'error' && state.status !== 'disconnected' && state.status !== 'loading') {
|
||||
state.status = 'connecting';
|
||||
}
|
||||
}
|
||||
}
|
||||
await Promise.all(tasks);
|
||||
} finally {
|
||||
this.watcherTicking = false;
|
||||
this.scheduleWatcher(this.watcherIntervalMs);
|
||||
}
|
||||
}
|
||||
|
||||
/** Re-check pipe and connect under the per-PID lock. */
|
||||
private async reconcileConnect(pid: number): Promise<void> {
|
||||
const state = this.states.get(pid);
|
||||
if (!state || !state.injected || state.connected) return;
|
||||
if (state.client?.isClosed) this.tearDownClient(state);
|
||||
const live = await QqHookClient.listLivePipes();
|
||||
if (!live.has(pid)) return;
|
||||
await this.attemptConnect(state);
|
||||
}
|
||||
|
||||
/** Tear down a client whose pipe disappeared. */
|
||||
private async reconcileLostPipe(pid: number): Promise<void> {
|
||||
const state = this.states.get(pid);
|
||||
if (!state || !state.connected) return;
|
||||
const live = await QqHookClient.listLivePipes();
|
||||
if (live.has(pid)) return;
|
||||
const wasLoggedIn = state.loggedIn;
|
||||
this.tearDownClient(state);
|
||||
state.status = state.injected ? (wasLoggedIn ? 'disconnected' : 'connecting') : 'available';
|
||||
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid);
|
||||
}
|
||||
|
||||
// ───────────────────────────── client plumbing ───────────────────────────
|
||||
|
||||
private async attemptConnect(state: HookProcessState): Promise<void> {
|
||||
if (state.connected) return;
|
||||
if (state.client?.isClosed) this.tearDownClient(state);
|
||||
if (!state.client) {
|
||||
state.client = new QqHookClient(state.pid);
|
||||
state.sender = new HookPacketClient(state.client);
|
||||
state.bound = false;
|
||||
}
|
||||
if (!state.bound) {
|
||||
this.bindClient(state, state.client);
|
||||
state.bound = true;
|
||||
}
|
||||
|
||||
const client = state.client;
|
||||
try {
|
||||
await client.connectAll({ recv: true });
|
||||
state.connected = true;
|
||||
state.status = client.isLoggedIn ? 'online' : 'loaded';
|
||||
state.error = '';
|
||||
const loginState = client.getLoginState();
|
||||
if (loginState.loggedIn) this.handleLoginState(state, loginState);
|
||||
log.info('pipe connected: PID=%d', state.pid);
|
||||
} catch (error) {
|
||||
state.error = this.errMsg(error);
|
||||
// Drop the client so the next attempt builds a fresh socket pair.
|
||||
this.tearDownClient(state);
|
||||
state.status = state.injected ? 'connecting' : 'available';
|
||||
}
|
||||
}
|
||||
|
||||
private bindClient(state: HookProcessState, client: QqHookClient): void {
|
||||
client.on('packet', packet => this.handlePacket(state, packet));
|
||||
client.on('loginState', loginState => this.handleLoginState(state, loginState));
|
||||
client.on('error', error => {
|
||||
const msg = this.errMsg(error);
|
||||
state.error = msg;
|
||||
log.warn('pipe error: PID=%d err=%s', state.pid, msg);
|
||||
});
|
||||
client.on('close', () => {
|
||||
if (this.disposed) return;
|
||||
// Only the client that is currently registered should drive a reconcile;
|
||||
// listeners may fire for an already-replaced client.
|
||||
if (state.client !== client) return;
|
||||
void this.serialize(state.pid, async () => {
|
||||
if (state.client !== client) return;
|
||||
const wasLoggedIn = state.loggedIn;
|
||||
this.tearDownClient(state);
|
||||
if (!state.injected) {
|
||||
state.status = 'available';
|
||||
} else if (wasLoggedIn) {
|
||||
state.status = 'disconnected';
|
||||
this.bridgeManager.onPidDisconnected(state.pid);
|
||||
} else {
|
||||
state.status = 'connecting';
|
||||
}
|
||||
}).catch(err => log.warn('close reconcile failed: PID=%d err=%s', state.pid, this.errMsg(err)));
|
||||
});
|
||||
}
|
||||
|
||||
/** Detach + close the current client and reset its associated fields. */
|
||||
private tearDownClient(state: HookProcessState): void {
|
||||
const client = state.client;
|
||||
if (client) {
|
||||
client.removeAllListeners();
|
||||
try { client.close(); } catch { /* ignore */ }
|
||||
}
|
||||
state.client = null;
|
||||
state.sender = null;
|
||||
state.bound = false;
|
||||
state.connected = false;
|
||||
state.loggedIn = false;
|
||||
}
|
||||
|
||||
private handleLoginState(state: HookProcessState, loginState: QqHookLoginState): void {
|
||||
const wasLoggedIn = state.loggedIn;
|
||||
const previousUin = state.uin;
|
||||
state.uin = loginState.uin || loginState.uinNumber.toString();
|
||||
state.loggedIn = loginState.loggedIn && isRealUin(state.uin);
|
||||
state.status = state.loggedIn ? 'online' : (state.connected ? 'loaded' : state.status);
|
||||
|
||||
if (!state.loggedIn || !state.sender) return;
|
||||
if (wasLoggedIn && previousUin === state.uin) return;
|
||||
|
||||
this.bridgeManager.onHookLogin(state.pid, state.uin, state.sender);
|
||||
log.success('login detected: PID=%d UIN=%s', state.pid, state.uin);
|
||||
}
|
||||
|
||||
private handlePacket(state: HookProcessState, packet: QqHookPacket): void {
|
||||
if (!state.loggedIn) return;
|
||||
const uin = packet.uin || state.uin;
|
||||
if (!isRealUin(uin)) return;
|
||||
this.ntqq.onHookPacket(state.pid, { ...packet, uin });
|
||||
}
|
||||
|
||||
private toPublicInfo(state: HookProcessState): HookProcessInfo {
|
||||
return {
|
||||
pid: state.pid,
|
||||
name: state.name,
|
||||
path: state.path,
|
||||
injected: state.injected,
|
||||
connected: state.connected,
|
||||
loggedIn: state.loggedIn,
|
||||
uin: state.uin,
|
||||
status: state.status,
|
||||
error: state.error,
|
||||
method: state.method,
|
||||
};
|
||||
}
|
||||
|
||||
private errMsg(value: unknown): string {
|
||||
return value instanceof Error ? value.message : String(value);
|
||||
}
|
||||
}
|
||||
|
||||
function isRealUin(uin: string): boolean {
|
||||
if (!uin || uin === '0') return false;
|
||||
return /^\d+$/.test(uin) && uin.length >= 5;
|
||||
}
|
||||
+45
-15
@@ -1,23 +1,39 @@
|
||||
import { NtqqHandler } from './protocol/ntqq-handler';
|
||||
import { HookManager } from '@snowluma/bridge';
|
||||
import { closeLogger, createLogger } from '@snowluma/common/logger';
|
||||
import { loadRuntimeConfig } from '@snowluma/common/runtime';
|
||||
import { OneBotManager } from '@snowluma/onebot/manager';
|
||||
import { BridgeManager } from './bridge/manager';
|
||||
import { OneBotManager } from './onebot/manager';
|
||||
import { loadRuntimeConfig } from './common/runtime';
|
||||
import { createLogger } from './utils/logger';
|
||||
import { HookManager } from './hook/hook-manager';
|
||||
|
||||
const runtimeConfig = loadRuntimeConfig();
|
||||
const log = createLogger('App');
|
||||
|
||||
// Last-resort process guards. This is a long-running daemon: a hooked QQ pipe
|
||||
// can drop at any moment, and a stray rejection on a detached callback (or a
|
||||
// throw that escapes one) must NOT take the whole process down — otherwise
|
||||
// Docker restarts it (dropping every session) and a bare Windows run just dies
|
||||
// ("connection pipe closed", bot offline). Log and keep serving; the bridge's
|
||||
// own watcher reconnects the dropped pipe. Targeted handlers still cover the
|
||||
// known paths (e.g. the hook-client send deferreds) — these only catch what
|
||||
// slips through, and surface its stack so the real source can be fixed.
|
||||
process.on('unhandledRejection', (reason) => {
|
||||
log.error('unhandledRejection (kept alive): %s',
|
||||
reason instanceof Error ? (reason.stack ?? reason.message) : String(reason));
|
||||
});
|
||||
process.on('uncaughtException', (error) => {
|
||||
log.error('uncaughtException (kept alive): %s', error.stack ?? error.message);
|
||||
});
|
||||
|
||||
async function main() {
|
||||
log.info('SnowLuma starting');
|
||||
|
||||
const ntqq = new NtqqHandler();
|
||||
const bridgeManager = new BridgeManager();
|
||||
const oneBotManager = new OneBotManager();
|
||||
const hookManager = new HookManager(ntqq, bridgeManager);
|
||||
const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad);
|
||||
const hookManager = new HookManager({ bridgeManager, autoLoadOnDiscovery });
|
||||
if (autoLoadOnDiscovery) {
|
||||
log.info('hook auto-load enabled: every discovered QQ process will be injected');
|
||||
}
|
||||
|
||||
// Bind bridge manager to NTQQ handler (receives all parsed packets)
|
||||
bridgeManager.bind(ntqq);
|
||||
oneBotManager.bind(bridgeManager);
|
||||
|
||||
if (
|
||||
@@ -25,7 +41,6 @@ async function main() {
|
||||
process.env.SNOWLUMA_DEV_WEBUI === '1'
|
||||
) {
|
||||
try {
|
||||
log.info('WebUI is enabled, starting...');
|
||||
const { initWebUI } = await import('./webui/server');
|
||||
await initWebUI(runtimeConfig.webuiPort || 5099, oneBotManager, hookManager);
|
||||
} catch (err) {
|
||||
@@ -33,16 +48,31 @@ async function main() {
|
||||
}
|
||||
}
|
||||
|
||||
// Graceful shutdown
|
||||
process.on('SIGINT', () => {
|
||||
log.warn('Shutting down...');
|
||||
// Graceful shutdown: dispose managers, await log flush, then exit.
|
||||
// SIGINT (Ctrl-C) and SIGTERM (Docker/systemd) take the same path.
|
||||
const shutdown = (signal: string) => async () => {
|
||||
log.warn(`Shutting down (${signal})...`);
|
||||
oneBotManager.dispose();
|
||||
hookManager.dispose();
|
||||
await closeLogger();
|
||||
process.exit(0);
|
||||
});
|
||||
};
|
||||
process.on('SIGINT', shutdown('SIGINT'));
|
||||
process.on('SIGTERM', shutdown('SIGTERM'));
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
function resolveAutoLoad(fromConfig: boolean | undefined): boolean {
|
||||
const envRaw = process.env.SNOWLUMA_HOOK_AUTOLOAD;
|
||||
if (typeof envRaw === 'string' && envRaw.trim()) {
|
||||
const v = envRaw.trim().toLowerCase();
|
||||
if (v === '1' || v === 'true' || v === 'yes' || v === 'on') return true;
|
||||
if (v === '0' || v === 'false' || v === 'no' || v === 'off') return false;
|
||||
}
|
||||
return fromConfig === true;
|
||||
}
|
||||
|
||||
main().catch(async (error) => {
|
||||
log.error(error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
await closeLogger();
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -1,601 +0,0 @@
|
||||
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||
import { asMessage, asNumber, asString, asBoolean } from '../api-handler';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
// --- Likes & Pokes ---
|
||||
|
||||
h.registerAction('send_like', async (params) => {
|
||||
const userId = asNumber(params.user_id);
|
||||
const times = asNumber(params.times) || 1;
|
||||
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
if (!ctx.sendLike) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.sendLike(userId, times);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('friend_poke', async (params) => {
|
||||
const userId = asNumber(params.user_id);
|
||||
const targetId = asNumber(params.target_id) || undefined;
|
||||
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
if (!ctx.sendFriendPoke) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.sendFriendPoke(userId, targetId);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('group_poke', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userId = asNumber(params.user_id);
|
||||
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
|
||||
if (!ctx.sendGroupPoke) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.sendGroupPoke(groupId, userId);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('send_poke', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userId = asNumber(params.user_id);
|
||||
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
if (groupId) {
|
||||
if (!ctx.sendGroupPoke) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.sendGroupPoke(groupId, userId);
|
||||
} else {
|
||||
if (!ctx.sendFriendPoke) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.sendFriendPoke(userId);
|
||||
}
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
// --- Essence ---
|
||||
|
||||
h.registerAction('set_essence_msg', async (params) => {
|
||||
const messageId = asNumber(params.message_id);
|
||||
if (!Number.isInteger(messageId) || messageId === 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
|
||||
}
|
||||
if (!ctx.setEssenceMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.setEssenceMsg(messageId);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('delete_essence_msg', async (params) => {
|
||||
const messageId = asNumber(params.message_id);
|
||||
if (!Number.isInteger(messageId) || messageId === 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
|
||||
}
|
||||
if (!ctx.deleteEssenceMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.deleteEssenceMsg(messageId);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('get_essence_msg_list', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
// Essence list fetch requires web ticket/cookie flow not wired yet.
|
||||
// Keep API-compatible output shape for callers.
|
||||
return okResponse([]);
|
||||
});
|
||||
|
||||
// --- Reactions ---
|
||||
|
||||
h.registerAction('set_group_reaction', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const messageId = asNumber(params.message_id);
|
||||
const code = asString(params.code);
|
||||
const isSet = asBoolean(params.is_set, true);
|
||||
|
||||
if (!Number.isInteger(messageId) || messageId === 0 || !code) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message_id and code are required');
|
||||
}
|
||||
|
||||
const meta = ctx.getMessageMeta(messageId);
|
||||
if (!meta || !meta.isGroup) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not a group message');
|
||||
}
|
||||
|
||||
if (groupId && groupId !== meta.targetId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id does not match message session');
|
||||
}
|
||||
|
||||
if (!ctx.setGroupReaction) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.setGroupReaction(meta.targetId, meta.sequence, code, isSet);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
// --- History ---
|
||||
|
||||
h.registerAction('get_group_msg_history', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const messageId = asNumber(params.message_id) || 0;
|
||||
const count = asNumber(params.count) || 20;
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
if (!ctx.getGroupMsgHistory) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
const messages = await ctx.getGroupMsgHistory(groupId, messageId, count);
|
||||
return okResponse({ messages });
|
||||
});
|
||||
|
||||
h.registerAction('get_friend_msg_history', async (params) => {
|
||||
const userId = asNumber(params.user_id);
|
||||
const messageId = asNumber(params.message_id) || 0;
|
||||
const count = asNumber(params.count) || 20;
|
||||
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
if (!ctx.getFriendMsgHistory) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
const messages = await ctx.getFriendMsgHistory(userId, messageId, count);
|
||||
return okResponse({ messages });
|
||||
});
|
||||
|
||||
h.registerAction('mark_msg_as_read', async () => {
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
// --- RKey ---
|
||||
|
||||
h.registerAction('get_rkey', async () => {
|
||||
if (ctx.getDownloadRKeys) {
|
||||
return okResponse(await ctx.getDownloadRKeys());
|
||||
}
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
});
|
||||
|
||||
// --- OCR stubs ---
|
||||
|
||||
h.registerAction('ocr_image', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('.ocr_image', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
// --- Group notice stubs ---
|
||||
|
||||
h.registerAction('_send_group_notice', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('_get_group_notice', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('_del_group_notice', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
// --- Forward messages ---
|
||||
|
||||
h.registerAction('upload_forward_msg', async (params) => {
|
||||
const messages = asMessage(params.messages ?? params.message);
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
|
||||
if (!ctx.sendForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
|
||||
const result = await ctx.sendForwardMsg(messages);
|
||||
const data: Record<string, unknown> = {
|
||||
res_id: result.forwardId,
|
||||
forward_id: result.forwardId,
|
||||
message_id: 0,
|
||||
};
|
||||
if (groupId > 0) data.group_id = groupId;
|
||||
return okResponse(data as any);
|
||||
});
|
||||
|
||||
h.registerAction('upload_foward_msg', async (params) => {
|
||||
const messages = asMessage(params.messages ?? params.message);
|
||||
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
|
||||
if (!ctx.sendForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
const result = await ctx.sendForwardMsg(messages);
|
||||
return okResponse({ res_id: result.forwardId, forward_id: result.forwardId, message_id: 0 });
|
||||
});
|
||||
|
||||
h.registerAction('send_forward_msg', async (params) => {
|
||||
const messageType = asString(params.message_type);
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userId = asNumber(params.user_id);
|
||||
const messages = asMessage(params.messages ?? params.message);
|
||||
|
||||
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
|
||||
|
||||
if ((messageType === 'group' || groupId > 0) && ctx.sendGroupForwardMsg) {
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
const result = await ctx.sendGroupForwardMsg(groupId, messages);
|
||||
return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId });
|
||||
}
|
||||
|
||||
if ((messageType === 'private' || userId > 0) && ctx.sendPrivateForwardMsg) {
|
||||
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
const result = await ctx.sendPrivateForwardMsg(userId, messages);
|
||||
return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId });
|
||||
}
|
||||
|
||||
if (!ctx.sendForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
const result = await ctx.sendForwardMsg(messages);
|
||||
return okResponse({ message_id: 0, res_id: result.forwardId, forward_id: result.forwardId });
|
||||
});
|
||||
|
||||
h.registerAction('send_group_forward_msg', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const messages = asMessage(params.messages ?? params.message);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
|
||||
if (!ctx.sendGroupForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
|
||||
const result = await ctx.sendGroupForwardMsg(groupId, messages);
|
||||
return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId });
|
||||
});
|
||||
|
||||
h.registerAction('send_private_forward_msg', async (params) => {
|
||||
const userId = asNumber(params.user_id);
|
||||
const messages = asMessage(params.messages ?? params.message);
|
||||
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
|
||||
if (!ctx.sendPrivateForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
|
||||
const result = await ctx.sendPrivateForwardMsg(userId, messages);
|
||||
return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId });
|
||||
});
|
||||
|
||||
h.registerAction('get_forward_msg', async (params) => {
|
||||
let id = asString(params.id);
|
||||
if (!id) {
|
||||
const rawMessageId = params.message_id;
|
||||
const numericMessageId = asNumber(rawMessageId);
|
||||
if (numericMessageId > 0) {
|
||||
const event = ctx.getMessage(numericMessageId);
|
||||
const segments = Array.isArray(event?.message) ? event.message : [];
|
||||
for (const seg of segments) {
|
||||
if (typeof seg !== 'object' || seg === null || Array.isArray(seg)) continue;
|
||||
const so = seg as Record<string, unknown>;
|
||||
if (String(so.type ?? '') !== 'forward') continue;
|
||||
const data = (typeof so.data === 'object' && so.data !== null && !Array.isArray(so.data))
|
||||
? so.data as Record<string, unknown>
|
||||
: null;
|
||||
const candidate = asString(data?.id) || asString(data?.res_id) || asString(data?.forward_id);
|
||||
if (candidate) {
|
||||
id = candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!id) {
|
||||
id = asString(rawMessageId);
|
||||
}
|
||||
}
|
||||
|
||||
if (!id) return failedResponse(RETCODE.BAD_REQUEST, 'id or message_id is required');
|
||||
if (!ctx.getForwardMsg) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
|
||||
const messages = await ctx.getForwardMsg(id);
|
||||
return okResponse({ messages });
|
||||
});
|
||||
|
||||
// --- Media ---
|
||||
|
||||
h.registerAction('get_image', async (params) => {
|
||||
const file = asString(params.file);
|
||||
if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required');
|
||||
const imageInfo = findMediaInStore('image', file, ctx);
|
||||
if (imageInfo) {
|
||||
return okResponse(imageInfo as unknown as import('../types').JsonValue);
|
||||
}
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'image not found in cache');
|
||||
});
|
||||
|
||||
h.registerAction('get_record', async (params) => {
|
||||
const file = asString(params.file);
|
||||
if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required');
|
||||
const recordInfo = findMediaInStore('record', file, ctx);
|
||||
if (recordInfo) {
|
||||
return okResponse(recordInfo as unknown as import('../types').JsonValue);
|
||||
}
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'record not found in cache');
|
||||
});
|
||||
|
||||
// --- Credentials ---
|
||||
|
||||
h.registerAction('get_cookies', async () => {
|
||||
return okResponse({ cookies: '' });
|
||||
});
|
||||
|
||||
h.registerAction('get_csrf_token', async () => {
|
||||
return okResponse({ token: 0 });
|
||||
});
|
||||
|
||||
h.registerAction('get_credentials', async () => {
|
||||
return okResponse({ cookies: '', csrf_token: 0 });
|
||||
});
|
||||
|
||||
// --- Utility ---
|
||||
|
||||
h.registerAction('set_restart', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not supported');
|
||||
});
|
||||
|
||||
h.registerAction('clean_cache', async () => {
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('.handle_quick_operation', async (params) => {
|
||||
const context = params.context as import('../types').JsonObject | undefined;
|
||||
const operation = params.operation as Record<string, unknown> | undefined;
|
||||
if (!context || !operation) return failedResponse(RETCODE.BAD_REQUEST, 'context and operation are required');
|
||||
const { executeQuickOperation } = await import('../http-post-transport');
|
||||
await executeQuickOperation(context, operation, h);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
// --- NapCat-compatible extended APIs ---
|
||||
|
||||
h.registerAction('set_friend_remark', async (params) => {
|
||||
const userId = asNumber(params.user_id);
|
||||
const remark = asString(params.remark) ?? '';
|
||||
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
if (!ctx.setFriendRemark) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.setFriendRemark(userId, remark);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_msg_emoji_like', async (params) => {
|
||||
const messageId = asNumber(params.message_id);
|
||||
const emojiId = asString(params.emoji_id);
|
||||
const set = asBoolean(params.set, true);
|
||||
if (!Number.isInteger(messageId) || messageId === 0 || !emojiId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message_id and emoji_id are required');
|
||||
}
|
||||
if (!ctx.setMsgEmojiLike) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.setMsgEmojiLike(messageId, emojiId, set);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('mark_private_msg_as_read', async () => {
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('mark_group_msg_as_read', async () => {
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('_mark_all_as_read', async () => {
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('get_group_file_system_info', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
if (ctx.getGroupFileCount) {
|
||||
const info = await ctx.getGroupFileCount(groupId);
|
||||
return okResponse({
|
||||
file_count: info.fileCount,
|
||||
limit_count: info.maxCount,
|
||||
used_space: 0,
|
||||
total_space: 10737418240,
|
||||
});
|
||||
}
|
||||
return okResponse({
|
||||
file_count: 0,
|
||||
limit_count: 10000,
|
||||
used_space: 0,
|
||||
total_space: 10737418240,
|
||||
});
|
||||
});
|
||||
|
||||
h.registerAction('check_url_safely', async () => {
|
||||
return okResponse({ level: 1 });
|
||||
});
|
||||
|
||||
h.registerAction('download_file', async (params) => {
|
||||
const url = asString(params.url);
|
||||
const base64 = asString(params.base64);
|
||||
const name = asString(params.name);
|
||||
if (!url && !base64) return failedResponse(RETCODE.BAD_REQUEST, 'url or base64 is required');
|
||||
|
||||
const fs = await import('fs');
|
||||
const pathMod = await import('path');
|
||||
const cryptoMod = await import('crypto');
|
||||
const tempDir = pathMod.join('data', 'downloads');
|
||||
if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true });
|
||||
|
||||
let filePath: string;
|
||||
if (base64) {
|
||||
const buf = Buffer.from(base64, 'base64');
|
||||
const fileName = name || cryptoMod.createHash('md5').update(buf).digest('hex');
|
||||
filePath = pathMod.join(tempDir, fileName);
|
||||
fs.writeFileSync(filePath, buf);
|
||||
} else {
|
||||
const response = await fetch(url!, {
|
||||
headers: parseDownloadHeaders(params.headers),
|
||||
});
|
||||
if (!response.ok) return failedResponse(RETCODE.ACTION_FAILED, `download failed: ${response.status}`);
|
||||
const buf = Buffer.from(await response.arrayBuffer());
|
||||
const fileName = name || cryptoMod.createHash('md5').update(buf).digest('hex');
|
||||
filePath = pathMod.join(tempDir, fileName);
|
||||
fs.writeFileSync(filePath, buf);
|
||||
}
|
||||
return okResponse({ file: pathMod.resolve(filePath) });
|
||||
});
|
||||
|
||||
h.registerAction('set_qq_profile', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('set_online_status', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('get_group_ignored_notifies', async () => {
|
||||
return okResponse([]);
|
||||
});
|
||||
|
||||
h.registerAction('get_group_shut_list', async () => {
|
||||
return okResponse([]);
|
||||
});
|
||||
|
||||
h.registerAction('forward_friend_single_msg', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('forward_group_single_msg', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('get_recent_contact', async () => {
|
||||
return okResponse([]);
|
||||
});
|
||||
|
||||
h.registerAction('get_profile_like', async () => {
|
||||
return okResponse({});
|
||||
});
|
||||
|
||||
h.registerAction('get_friends_with_category', async () => {
|
||||
if (ctx.getFriendList) {
|
||||
return okResponse(await ctx.getFriendList());
|
||||
}
|
||||
return okResponse([]);
|
||||
});
|
||||
|
||||
// --- Additional NapCat-compatible stubs ---
|
||||
|
||||
h.registerAction('get_online_clients', async () => {
|
||||
return okResponse({ clients: [] });
|
||||
});
|
||||
|
||||
h.registerAction('_get_model_show', async () => {
|
||||
return okResponse({ variants: [] });
|
||||
});
|
||||
|
||||
h.registerAction('_set_model_show', async () => {
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('.get_word_slices', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('get_group_at_all_remain', async () => {
|
||||
return okResponse({ can_at_all: false, remain_at_all_count_for_group: 0, remain_at_all_count_for_uin: 0 });
|
||||
});
|
||||
|
||||
h.registerAction('get_unidirectional_friend_list', async () => {
|
||||
return okResponse([]);
|
||||
});
|
||||
|
||||
h.registerAction('set_self_longnick', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('get_collection_list', async () => {
|
||||
return okResponse([]);
|
||||
});
|
||||
|
||||
h.registerAction('create_collection', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('set_qq_avatar', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('set_input_status', async () => {
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('translate_en2zh', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('get_clientkey', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('get_mini_app_ark', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('click_inline_keyboard_button', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('set_group_sign', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('send_group_sign', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('get_group_info_ex', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
if (ctx.getGroupInfo) {
|
||||
return okResponse(await ctx.getGroupInfo(groupId));
|
||||
}
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
});
|
||||
|
||||
h.registerAction('get_group_detail_info', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
if (ctx.getGroupInfo) {
|
||||
return okResponse(await ctx.getGroupInfo(groupId));
|
||||
}
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
});
|
||||
|
||||
h.registerAction('trans_group_file', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('rename_group_file', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('get_file', async (params) => {
|
||||
const fileId = asString(params.file_id) || asString(params.file);
|
||||
if (!fileId) return failedResponse(RETCODE.BAD_REQUEST, 'file_id is required');
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
|
||||
h.registerAction('.send_packet', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Search through cached message segments to find a media element (image/record)
|
||||
* that matches the given file identifier.
|
||||
*/
|
||||
function findMediaInStore(
|
||||
mediaType: 'image' | 'record',
|
||||
file: string,
|
||||
ctx: ApiActionContext,
|
||||
): Record<string, unknown> | null {
|
||||
// The file param can match a file id, a URL, or a filename stored in segments.
|
||||
// We don't have a reverse index, so this is best-effort from stored events.
|
||||
// Most callers will pass the `file` field from a received message segment.
|
||||
// Just return the info if we can look it up from any recent cached message.
|
||||
// This is a known limitation — full implementation would require a media cache.
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse download_file headers parameter into a Record.
|
||||
*/
|
||||
function parseDownloadHeaders(headers: unknown): Record<string, string> {
|
||||
const result: Record<string, string> = {};
|
||||
if (!headers) return result;
|
||||
const headerList: string[] = [];
|
||||
if (typeof headers === 'string') {
|
||||
headerList.push(...headers.split(/\r?\n/).filter(Boolean));
|
||||
} else if (Array.isArray(headers)) {
|
||||
for (const h of headers) {
|
||||
if (typeof h === 'string') headerList.push(h);
|
||||
}
|
||||
}
|
||||
for (const line of headerList) {
|
||||
const idx = line.indexOf('=');
|
||||
if (idx > 0) {
|
||||
result[line.substring(0, idx).trim()] = line.substring(idx + 1).trim();
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||
import { asNumber, asBoolean } from '../api-handler';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('get_friend_list', async () => {
|
||||
if (ctx.getFriendList) {
|
||||
return okResponse(await ctx.getFriendList());
|
||||
}
|
||||
return okResponse([]);
|
||||
});
|
||||
|
||||
h.registerAction('get_stranger_info', async (params) => {
|
||||
const userId = asNumber(params.user_id);
|
||||
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
if (ctx.getStrangerInfo) {
|
||||
const info = await ctx.getStrangerInfo(userId);
|
||||
return okResponse(info ?? { user_id: userId, nickname: '', sex: 'unknown', age: 0 });
|
||||
}
|
||||
return okResponse({ user_id: userId, nickname: '', sex: 'unknown', age: 0 });
|
||||
});
|
||||
|
||||
h.registerAction('delete_friend', async (params) => {
|
||||
const userId = asNumber(params.user_id);
|
||||
const block = asBoolean(params.block, false);
|
||||
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
if (!ctx.handleDeleteFriend) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.handleDeleteFriend(userId, block);
|
||||
return okResponse();
|
||||
});
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||
import { asNumber, asString, asBoolean } from '../api-handler';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('set_group_kick', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userId = asNumber(params.user_id);
|
||||
const reject = asBoolean(params.reject_add_request, false);
|
||||
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
|
||||
if (!ctx.setGroupKick) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.setGroupKick(groupId, userId, reject);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_ban', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userId = asNumber(params.user_id);
|
||||
const duration = asNumber(params.duration) || 1800;
|
||||
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
|
||||
if (!ctx.setGroupBan) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.setGroupBan(groupId, userId, duration);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_whole_ban', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const enable = asBoolean(params.enable, true);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
if (!ctx.setGroupWholeBan) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.setGroupWholeBan(groupId, enable);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_admin', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userId = asNumber(params.user_id);
|
||||
const enable = asBoolean(params.enable, true);
|
||||
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
|
||||
if (!ctx.setGroupAdmin) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.setGroupAdmin(groupId, userId, enable);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_card', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userId = asNumber(params.user_id);
|
||||
const card = asString(params.card);
|
||||
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
|
||||
if (!ctx.setGroupCard) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.setGroupCard(groupId, userId, card);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_name', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const name = asString(params.group_name);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
if (!ctx.setGroupName) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.setGroupName(groupId, name);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_leave', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
if (!ctx.setGroupLeave) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.setGroupLeave(groupId);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_special_title', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userId = asNumber(params.user_id);
|
||||
const title = asString(params.special_title);
|
||||
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
|
||||
if (!ctx.setGroupSpecialTitle) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.setGroupSpecialTitle(groupId, userId, title);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_anonymous', async () => {
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_anonymous_ban', async () => {
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_portrait', async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
});
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||
import { asBoolean, asNumber, asString } from '../api-handler';
|
||||
import { RETCODE, failedResponse } from '../types';
|
||||
import { okResponse } from '../types';
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('upload_group_file', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const file = asString(params.file);
|
||||
const name = asString(params.name);
|
||||
const folderId = asString(params.folder) || asString(params.folder_id) || '/';
|
||||
const uploadFile = asBoolean(params.upload_file, true);
|
||||
if (!groupId || !file) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file are required');
|
||||
if (!ctx.uploadGroupFile) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
const fileId = await ctx.uploadGroupFile(groupId, file, name, folderId, uploadFile);
|
||||
return okResponse({ file_id: fileId });
|
||||
});
|
||||
|
||||
h.registerAction('upload_private_file', async (params) => {
|
||||
const userId = asNumber(params.user_id);
|
||||
const file = asString(params.file);
|
||||
const name = asString(params.name);
|
||||
const uploadFile = asBoolean(params.upload_file, true);
|
||||
if (!userId || !file) return failedResponse(RETCODE.BAD_REQUEST, 'user_id and file are required');
|
||||
if (!ctx.uploadPrivateFile) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
const fileId = await ctx.uploadPrivateFile(userId, file, name, uploadFile);
|
||||
return okResponse({ file_id: fileId });
|
||||
});
|
||||
|
||||
h.registerAction('get_group_file_url', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const fileId = asString(params.file_id);
|
||||
const busId = asNumber(params.busid) || 102;
|
||||
if (!groupId || !fileId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file_id are required');
|
||||
}
|
||||
if (!ctx.getGroupFileUrl) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
return okResponse({ url: await ctx.getGroupFileUrl(groupId, fileId, busId) });
|
||||
});
|
||||
|
||||
h.registerAction('get_group_root_files', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
}
|
||||
if (!ctx.getGroupFiles) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
return okResponse(await ctx.getGroupFiles(groupId, '/'));
|
||||
});
|
||||
|
||||
h.registerAction('get_group_files_by_folder', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const folderId = asString(params.folder_id) || asString(params.folder) || '/';
|
||||
if (!groupId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
}
|
||||
if (!ctx.getGroupFiles) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
return okResponse(await ctx.getGroupFiles(groupId, folderId));
|
||||
});
|
||||
|
||||
h.registerAction('delete_group_file', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const fileId = asString(params.file_id);
|
||||
if (!groupId || !fileId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file_id are required');
|
||||
}
|
||||
if (!ctx.deleteGroupFile) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.deleteGroupFile(groupId, fileId);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('move_group_file', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const fileId = asString(params.file_id);
|
||||
const parentDirectory = asString(params.parent_directory);
|
||||
const targetDirectory = asString(params.target_directory);
|
||||
if (!groupId || !fileId || !parentDirectory || !targetDirectory) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, file_id, parent_directory and target_directory are required');
|
||||
}
|
||||
if (!ctx.moveGroupFile) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.moveGroupFile(groupId, fileId, parentDirectory, targetDirectory);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('create_group_file_folder', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const name = asString(params.name);
|
||||
const parentId = asString(params.parent_id) || '/';
|
||||
if (!groupId || !name) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and name are required');
|
||||
}
|
||||
if (!ctx.createGroupFileFolder) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.createGroupFileFolder(groupId, name, parentId);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('delete_group_file_folder', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const folderId = asString(params.folder_id);
|
||||
if (!groupId || !folderId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and folder_id are required');
|
||||
}
|
||||
if (!ctx.deleteGroupFileFolder) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.deleteGroupFileFolder(groupId, folderId);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('rename_group_file_folder', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const folderId = asString(params.folder_id);
|
||||
const newName = asString(params.new_folder_name) || asString(params.name);
|
||||
if (!groupId || !folderId || !newName) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, folder_id and new_folder_name are required');
|
||||
}
|
||||
if (!ctx.renameGroupFileFolder) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.renameGroupFileFolder(groupId, folderId, newName);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('get_private_file_url', async (params) => {
|
||||
const userId = asNumber(params.user_id);
|
||||
const fileId = asString(params.file_id);
|
||||
const fileHash = asString(params.file_hash);
|
||||
if (!userId || !fileId || !fileHash) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'user_id, file_id and file_hash are required');
|
||||
}
|
||||
if (!ctx.getPrivateFileUrl) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
return okResponse({ url: await ctx.getPrivateFileUrl(userId, fileId, fileHash) });
|
||||
});
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||
import { asNumber, asBoolean } from '../api-handler';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('get_group_list', async (params) => {
|
||||
const noCache = asBoolean(params.no_cache, false);
|
||||
if (ctx.getGroupList) {
|
||||
return okResponse(await ctx.getGroupList(noCache));
|
||||
}
|
||||
return okResponse([]);
|
||||
});
|
||||
|
||||
h.registerAction('get_group_info', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
const noCache = asBoolean(params.no_cache, false);
|
||||
if (ctx.getGroupInfo) {
|
||||
const info = await ctx.getGroupInfo(groupId, noCache);
|
||||
return okResponse(info ?? { group_id: groupId, group_name: '', member_count: 0, max_member_count: 0 });
|
||||
}
|
||||
return okResponse({ group_id: groupId, group_name: '', member_count: 0, max_member_count: 0 });
|
||||
});
|
||||
|
||||
h.registerAction('get_group_member_list', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
const noCache = asBoolean(params.no_cache, false);
|
||||
if (ctx.getGroupMemberList) {
|
||||
return okResponse(await ctx.getGroupMemberList(groupId, noCache));
|
||||
}
|
||||
return okResponse([]);
|
||||
});
|
||||
|
||||
h.registerAction('get_group_member_info', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userId = asNumber(params.user_id);
|
||||
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
|
||||
const noCache = asBoolean(params.no_cache, false);
|
||||
if (ctx.getGroupMemberInfo) {
|
||||
const info = await ctx.getGroupMemberInfo(groupId, userId, noCache);
|
||||
return okResponse(info ?? {
|
||||
group_id: groupId, user_id: userId, nickname: '', card: '',
|
||||
sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0,
|
||||
level: '0', role: 'member', title: '',
|
||||
});
|
||||
}
|
||||
return okResponse({
|
||||
group_id: groupId, user_id: userId, nickname: '', card: '',
|
||||
sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0,
|
||||
level: '0', role: 'member', title: '',
|
||||
});
|
||||
});
|
||||
|
||||
h.registerAction('get_group_honor_info', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
return okResponse({
|
||||
group_id: groupId, current_talkative: null, talkative_list: [],
|
||||
performer_list: [], legend_list: [], strong_newbie_list: [], emotion_list: [],
|
||||
});
|
||||
});
|
||||
|
||||
h.registerAction('get_group_system_msg', async () => {
|
||||
if (ctx.handleGetGroupSystemMsg) {
|
||||
return okResponse(await ctx.handleGetGroupSystemMsg());
|
||||
}
|
||||
return okResponse([]);
|
||||
});
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||
import { okResponse } from '../types';
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('get_login_info', async () => {
|
||||
const login = ctx.getLoginInfo();
|
||||
return okResponse({ user_id: login.userId, nickname: login.nickname });
|
||||
});
|
||||
|
||||
h.registerAction('get_status', async () => {
|
||||
const online = ctx.isOnline();
|
||||
return okResponse({ online, good: online });
|
||||
});
|
||||
|
||||
h.registerAction('get_version_info', async () => {
|
||||
return okResponse({
|
||||
app_name: 'SnowLuma',
|
||||
app_version: '0.1.0-node',
|
||||
protocol_version: 'v11',
|
||||
});
|
||||
});
|
||||
|
||||
h.registerAction('can_send_image', async () => {
|
||||
return okResponse({ yes: ctx.canSendImage?.() ?? false });
|
||||
});
|
||||
|
||||
h.registerAction('can_send_record', async () => {
|
||||
return okResponse({ yes: ctx.canSendRecord?.() ?? false });
|
||||
});
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
import type { JsonObject, JsonValue } from '../types';
|
||||
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||
import { asNumber, asString, asBoolean, asMessage } from '../api-handler';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('send_msg', async (params) => {
|
||||
const messageType = asString(params.message_type);
|
||||
const message = asMessage(params.message);
|
||||
const autoEscape = asBoolean(params.auto_escape, false);
|
||||
|
||||
if (message === undefined) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message is required');
|
||||
}
|
||||
|
||||
if (messageType === 'group' || params.group_id !== undefined) {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!Number.isInteger(groupId) || groupId <= 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
}
|
||||
if (!ctx.sendGroupMessage) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'send_group_msg is not implemented');
|
||||
}
|
||||
const result = await ctx.sendGroupMessage(groupId, message, autoEscape);
|
||||
return okResponse({ message_id: result.messageId });
|
||||
}
|
||||
|
||||
const userId = asNumber(params.user_id);
|
||||
if (!Number.isInteger(userId) || userId <= 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
}
|
||||
if (!ctx.sendPrivateMessage) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'send_private_msg is not implemented');
|
||||
}
|
||||
const result = await ctx.sendPrivateMessage(userId, message, autoEscape);
|
||||
return okResponse({ message_id: result.messageId });
|
||||
});
|
||||
|
||||
h.registerAction('send_private_msg', async (params) => {
|
||||
const userId = asNumber(params.user_id);
|
||||
const message = asMessage(params.message);
|
||||
const autoEscape = asBoolean(params.auto_escape, false);
|
||||
|
||||
if (!Number.isInteger(userId) || userId <= 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
}
|
||||
if (message === undefined) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message is required');
|
||||
}
|
||||
if (!ctx.sendPrivateMessage) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'send_private_msg is not implemented');
|
||||
}
|
||||
|
||||
const result = await ctx.sendPrivateMessage(userId, message, autoEscape);
|
||||
return okResponse({ message_id: result.messageId });
|
||||
});
|
||||
|
||||
h.registerAction('send_group_msg', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const message = asMessage(params.message);
|
||||
const autoEscape = asBoolean(params.auto_escape, false);
|
||||
|
||||
if (!Number.isInteger(groupId) || groupId <= 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
}
|
||||
if (message === undefined) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message is required');
|
||||
}
|
||||
if (!ctx.sendGroupMessage) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'send_group_msg is not implemented');
|
||||
}
|
||||
|
||||
const result = await ctx.sendGroupMessage(groupId, message, autoEscape);
|
||||
return okResponse({ message_id: result.messageId });
|
||||
});
|
||||
|
||||
h.registerAction('get_msg', async (params) => {
|
||||
const messageId = asNumber(params.message_id);
|
||||
if (!Number.isInteger(messageId) || messageId === 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
|
||||
}
|
||||
|
||||
const data = ctx.getMessage(messageId);
|
||||
if (!data) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
|
||||
}
|
||||
|
||||
const result: JsonObject = { ...data };
|
||||
delete result.post_type;
|
||||
delete result.self_id;
|
||||
result.real_id = (result.message_id ?? messageId) as JsonValue;
|
||||
return okResponse(result);
|
||||
});
|
||||
|
||||
h.registerAction('delete_msg', async (params) => {
|
||||
const messageId = asNumber(params.message_id);
|
||||
if (!Number.isInteger(messageId) || messageId === 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
|
||||
}
|
||||
if (!ctx.deleteMessage) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'delete_msg is not implemented');
|
||||
}
|
||||
|
||||
const meta = ctx.getMessageMeta(messageId);
|
||||
if (!meta) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not retractable');
|
||||
}
|
||||
|
||||
await ctx.deleteMessage(messageId, meta);
|
||||
return okResponse();
|
||||
});
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||
import { asString, asBoolean } from '../api-handler';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('set_friend_add_request', async (params) => {
|
||||
const flag = asString(params.flag);
|
||||
const approve = asBoolean(params.approve, true);
|
||||
if (!flag) return failedResponse(RETCODE.BAD_REQUEST, 'flag is required');
|
||||
if (!ctx.handleFriendRequest) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.handleFriendRequest(flag, approve);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_add_request', async (params) => {
|
||||
const flag = asString(params.flag);
|
||||
const subType = asString(params.sub_type, asString(params.type, 'add'));
|
||||
const approve = asBoolean(params.approve, true);
|
||||
const reason = asString(params.reason);
|
||||
if (!flag) return failedResponse(RETCODE.BAD_REQUEST, 'flag is required');
|
||||
if (!ctx.handleGroupRequest) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
await ctx.handleGroupRequest(flag, subType, approve, reason);
|
||||
return okResponse();
|
||||
});
|
||||
}
|
||||
@@ -1,519 +0,0 @@
|
||||
import type { MessageElement, QQEventVariant } from '../bridge/events';
|
||||
import type { JsonArray, JsonObject } from './types';
|
||||
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from './message-id';
|
||||
|
||||
export type ImageUrlResolver = (element: MessageElement, isGroup: boolean) => string;
|
||||
export type MediaUrlResolver = (element: MessageElement, isGroup: boolean, sessionId: number) => Promise<string>;
|
||||
export type MessageIdResolver = (isGroup: boolean, sessionId: number, sequence: number, eventName: string) => number;
|
||||
|
||||
export class EventConverter {
|
||||
private imageUrlResolver_: ImageUrlResolver | null = null;
|
||||
private mediaUrlResolver_: MediaUrlResolver | null = null;
|
||||
private messageIdResolver_: MessageIdResolver | null = null;
|
||||
|
||||
setImageUrlResolver(resolver: ImageUrlResolver): void {
|
||||
this.imageUrlResolver_ = resolver;
|
||||
}
|
||||
|
||||
setMediaUrlResolver(resolver: MediaUrlResolver): void {
|
||||
this.mediaUrlResolver_ = resolver;
|
||||
}
|
||||
|
||||
setMessageIdResolver(resolver: MessageIdResolver): void {
|
||||
this.messageIdResolver_ = resolver;
|
||||
}
|
||||
|
||||
async convert(instanceUin: string, event: QQEventVariant): Promise<JsonObject | null> {
|
||||
const selfId = parseSelfId(instanceUin);
|
||||
|
||||
switch (event.kind) {
|
||||
case 'friend_message':
|
||||
{
|
||||
const isSelf = event.senderUin === selfId;
|
||||
const postType = isSelf ? 'message_sent' : 'message';
|
||||
const messageId = this.resolveMessageId(false, event.senderUin, event.msgSeq, PRIVATE_MESSAGE_EVENT);
|
||||
const segments = await elementsToJson(event.elements, false, event.senderUin, this.imageUrlResolver_, this.mediaUrlResolver_, this.messageIdResolver_);
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: selfId,
|
||||
post_type: postType,
|
||||
message_type: 'private',
|
||||
sub_type: 'friend',
|
||||
message_id: messageId,
|
||||
message_seq: event.msgSeq,
|
||||
user_id: event.senderUin,
|
||||
message: segments,
|
||||
raw_message: segmentsToRawMessage(segments),
|
||||
font: 0,
|
||||
sender: {
|
||||
user_id: event.senderUin,
|
||||
nickname: event.senderNick,
|
||||
sex: 'unknown',
|
||||
age: 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case 'group_message':
|
||||
{
|
||||
const isSelf = event.senderUin === selfId;
|
||||
const postType = isSelf ? 'message_sent' : 'message';
|
||||
const messageId = this.resolveMessageId(true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT);
|
||||
const segments = await elementsToJson(event.elements, true, event.groupId, this.imageUrlResolver_, this.mediaUrlResolver_, this.messageIdResolver_);
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: selfId,
|
||||
post_type: postType,
|
||||
message_type: 'group',
|
||||
sub_type: 'normal',
|
||||
message_id: messageId,
|
||||
message_seq: event.msgSeq,
|
||||
group_id: event.groupId,
|
||||
user_id: event.senderUin,
|
||||
message: segments,
|
||||
raw_message: segmentsToRawMessage(segments),
|
||||
font: 0,
|
||||
sender: {
|
||||
user_id: event.senderUin,
|
||||
nickname: event.senderNick,
|
||||
card: event.senderCard,
|
||||
role: event.senderRole || 'member',
|
||||
sex: 'unknown',
|
||||
age: 0,
|
||||
},
|
||||
anonymous: null,
|
||||
};
|
||||
}
|
||||
|
||||
case 'temp_message':
|
||||
{
|
||||
const isSelf = event.senderUin === selfId;
|
||||
const postType = isSelf ? 'message_sent' : 'message';
|
||||
const messageId = this.resolveMessageId(false, event.senderUin, event.msgSeq, PRIVATE_MESSAGE_EVENT);
|
||||
const segments = await elementsToJson(event.elements, false, event.senderUin, this.imageUrlResolver_, this.mediaUrlResolver_, this.messageIdResolver_);
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: selfId,
|
||||
post_type: postType,
|
||||
message_type: 'private',
|
||||
sub_type: 'group',
|
||||
message_id: messageId,
|
||||
message_seq: event.msgSeq,
|
||||
user_id: event.senderUin,
|
||||
message: segments,
|
||||
raw_message: segmentsToRawMessage(segments),
|
||||
font: 0,
|
||||
sender: {
|
||||
user_id: event.senderUin,
|
||||
nickname: event.senderNick,
|
||||
sex: 'unknown',
|
||||
age: 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case 'group_member_join':
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: selfId,
|
||||
post_type: 'notice',
|
||||
notice_type: 'group_increase',
|
||||
sub_type: event.operatorUin === event.userUin ? 'approve' : 'invite',
|
||||
group_id: event.groupId,
|
||||
operator_id: event.operatorUin,
|
||||
user_id: event.userUin,
|
||||
};
|
||||
|
||||
case 'group_member_leave':
|
||||
{
|
||||
let subType: string;
|
||||
if (event.isKick) {
|
||||
subType = event.userUin === parseSelfId(instanceUin) ? 'kick_me' : 'kick';
|
||||
} else {
|
||||
subType = 'leave';
|
||||
}
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: selfId,
|
||||
post_type: 'notice',
|
||||
notice_type: 'group_decrease',
|
||||
sub_type: subType,
|
||||
group_id: event.groupId,
|
||||
operator_id: event.operatorUin,
|
||||
user_id: event.userUin,
|
||||
};
|
||||
}
|
||||
|
||||
case 'group_mute':
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: selfId,
|
||||
post_type: 'notice',
|
||||
notice_type: 'group_ban',
|
||||
sub_type: event.duration > 0 ? 'ban' : 'lift_ban',
|
||||
group_id: event.groupId,
|
||||
operator_id: event.operatorUin,
|
||||
user_id: event.userUin,
|
||||
duration: event.duration,
|
||||
};
|
||||
|
||||
case 'group_admin':
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: selfId,
|
||||
post_type: 'notice',
|
||||
notice_type: 'group_admin',
|
||||
sub_type: event.set ? 'set' : 'unset',
|
||||
group_id: event.groupId,
|
||||
user_id: event.userUin,
|
||||
};
|
||||
|
||||
case 'friend_recall':
|
||||
{
|
||||
const messageId = this.resolveMessageId(false, event.userUin, event.msgSeq, PRIVATE_MESSAGE_EVENT);
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: selfId,
|
||||
post_type: 'notice',
|
||||
notice_type: 'friend_recall',
|
||||
user_id: event.userUin,
|
||||
message_id: messageId,
|
||||
};
|
||||
}
|
||||
|
||||
case 'group_recall':
|
||||
{
|
||||
const messageId = this.resolveMessageId(true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT);
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: selfId,
|
||||
post_type: 'notice',
|
||||
notice_type: 'group_recall',
|
||||
group_id: event.groupId,
|
||||
operator_id: event.operatorUin,
|
||||
user_id: event.authorUin,
|
||||
message_id: messageId,
|
||||
};
|
||||
}
|
||||
|
||||
case 'friend_request':
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: selfId,
|
||||
post_type: 'request',
|
||||
request_type: 'friend',
|
||||
user_id: event.fromUin,
|
||||
comment: event.message,
|
||||
flag: event.flag,
|
||||
};
|
||||
|
||||
case 'group_invite':
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: selfId,
|
||||
post_type: 'request',
|
||||
request_type: 'group',
|
||||
sub_type: event.subType || 'invite',
|
||||
group_id: event.groupId,
|
||||
user_id: event.fromUin,
|
||||
comment: event.message,
|
||||
flag: event.flag,
|
||||
};
|
||||
|
||||
case 'friend_poke':
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: selfId,
|
||||
post_type: 'notice',
|
||||
notice_type: 'notify',
|
||||
sub_type: 'poke',
|
||||
user_id: event.userUin,
|
||||
target_id: event.targetUin,
|
||||
action: event.action,
|
||||
suffix: event.suffix,
|
||||
action_img_url: event.actionImgUrl,
|
||||
};
|
||||
|
||||
case 'group_poke':
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: selfId,
|
||||
post_type: 'notice',
|
||||
notice_type: 'notify',
|
||||
sub_type: 'poke',
|
||||
group_id: event.groupId,
|
||||
user_id: event.userUin,
|
||||
target_id: event.targetUin,
|
||||
action: event.action,
|
||||
suffix: event.suffix,
|
||||
action_img_url: event.actionImgUrl,
|
||||
};
|
||||
|
||||
case 'group_essence':
|
||||
{
|
||||
const messageId = this.resolveMessageId(true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT);
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: selfId,
|
||||
post_type: 'notice',
|
||||
notice_type: 'essence',
|
||||
sub_type: event.set ? 'add' : 'delete',
|
||||
group_id: event.groupId,
|
||||
user_id: event.senderUin,
|
||||
sender_id: event.senderUin,
|
||||
operator_id: event.operatorUin,
|
||||
message_id: messageId,
|
||||
message_seq: event.msgSeq,
|
||||
random: event.random,
|
||||
};
|
||||
}
|
||||
|
||||
case 'group_file_upload':
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: selfId,
|
||||
post_type: 'notice',
|
||||
notice_type: 'group_upload',
|
||||
group_id: event.groupId,
|
||||
user_id: event.userUin,
|
||||
file: {
|
||||
id: event.fileId,
|
||||
name: event.fileName,
|
||||
size: event.fileSize,
|
||||
busid: event.busId,
|
||||
},
|
||||
};
|
||||
|
||||
case 'friend_add':
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: selfId,
|
||||
post_type: 'notice',
|
||||
notice_type: 'friend_add',
|
||||
user_id: event.userUin,
|
||||
};
|
||||
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private resolveMessageId(isGroup: boolean, sessionId: number, sequence: number, eventName: string): number {
|
||||
if (this.messageIdResolver_) {
|
||||
const resolved = this.messageIdResolver_(isGroup, sessionId, sequence, eventName);
|
||||
if (Number.isInteger(resolved) && resolved !== 0) return resolved;
|
||||
}
|
||||
const seq = Math.trunc(sequence);
|
||||
return seq === 0 ? 0 : seq;
|
||||
}
|
||||
}
|
||||
|
||||
function parseSelfId(instanceUin: string): number {
|
||||
const parsed = Number.parseInt(instanceUin, 10);
|
||||
return Number.isNaN(parsed) ? 0 : parsed;
|
||||
}
|
||||
|
||||
async function elementsToJson(
|
||||
elements: MessageElement[],
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
resolver?: ImageUrlResolver | null,
|
||||
mediaResolver?: MediaUrlResolver | null,
|
||||
messageIdResolver?: MessageIdResolver | null,
|
||||
): Promise<JsonArray> {
|
||||
const result: JsonArray = [];
|
||||
for (const element of elements) {
|
||||
result.push(await elementToSegment(element, isGroup, sessionId, resolver, mediaResolver, messageIdResolver));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function elementsToOneBotSegments(
|
||||
elements: MessageElement[],
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
resolver?: ImageUrlResolver | null,
|
||||
mediaResolver?: MediaUrlResolver | null,
|
||||
messageIdResolver?: MessageIdResolver | null,
|
||||
): Promise<JsonArray> {
|
||||
return elementsToJson(elements, isGroup, sessionId, resolver, mediaResolver, messageIdResolver);
|
||||
}
|
||||
|
||||
async function elementToSegment(
|
||||
element: MessageElement,
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
resolver?: ImageUrlResolver | null,
|
||||
mediaResolver?: MediaUrlResolver | null,
|
||||
messageIdResolver?: MessageIdResolver | null,
|
||||
): Promise<JsonObject> {
|
||||
if (element.type === 'text') {
|
||||
return { type: 'text', data: { text: element.text ?? '' } };
|
||||
}
|
||||
|
||||
if (element.type === 'face') {
|
||||
return { type: 'face', data: { id: String(element.faceId ?? 0) } };
|
||||
}
|
||||
|
||||
if (element.type === 'image') {
|
||||
const url = resolver ? resolver(element, isGroup) : (element.imageUrl ?? '');
|
||||
return {
|
||||
type: 'image',
|
||||
data: {
|
||||
url,
|
||||
file: element.fileId ?? '',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (element.type === 'at') {
|
||||
const qq = (element.uid === 'all' || element.targetUin === 0)
|
||||
? 'all'
|
||||
: String(element.targetUin ?? 0);
|
||||
return { type: 'at', data: { qq } };
|
||||
}
|
||||
|
||||
if (element.type === 'reply') {
|
||||
const id = resolveReplyId(isGroup, sessionId, element.replySeq ?? 0, messageIdResolver);
|
||||
return { type: 'reply', data: { id: String(id) } };
|
||||
}
|
||||
|
||||
if (element.type === 'record') {
|
||||
const url = mediaResolver ? await mediaResolver(element, isGroup, sessionId) : (element.url ?? '');
|
||||
return {
|
||||
type: 'record',
|
||||
data: {
|
||||
file: element.fileName ?? element.fileId ?? '',
|
||||
url,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (element.type === 'video') {
|
||||
const url = mediaResolver ? await mediaResolver(element, isGroup, sessionId) : (element.url ?? '');
|
||||
return {
|
||||
type: 'video',
|
||||
data: {
|
||||
file: element.fileName ?? element.fileId ?? '',
|
||||
url,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (element.type === 'json') {
|
||||
return { type: 'json', data: { data: element.text ?? '' } };
|
||||
}
|
||||
|
||||
if (element.type === 'xml') {
|
||||
return {
|
||||
type: 'xml',
|
||||
data: {
|
||||
data: element.text ?? '',
|
||||
resid: element.subType ?? 35,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (element.type === 'file') {
|
||||
const url = mediaResolver ? await mediaResolver(element, isGroup, sessionId) : (element.url ?? '');
|
||||
return {
|
||||
type: 'file',
|
||||
data: {
|
||||
name: element.fileName ?? '',
|
||||
size: element.fileSize ?? 0,
|
||||
id: element.fileId ?? '',
|
||||
url,
|
||||
file_hash: element.fileHash ?? '',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (element.type === 'mface') {
|
||||
return {
|
||||
type: 'mface',
|
||||
data: {
|
||||
name: element.text ?? '',
|
||||
tab_id: element.faceId ?? 0,
|
||||
sub_type: element.subType ?? 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (element.type === 'poke') {
|
||||
return {
|
||||
type: 'poke',
|
||||
data: {
|
||||
type: element.subType ?? 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (!isGroup && element.type === 'at') {
|
||||
return { type: 'text', data: { text: element.text ?? '' } };
|
||||
}
|
||||
|
||||
return { type: element.type, data: {} };
|
||||
}
|
||||
|
||||
// --- CQ code raw_message generation (from already-resolved JSON segments) ---
|
||||
|
||||
function cqEscape(text: string): string {
|
||||
return text.replace(/&/g, '&').replace(/\[/g, '[').replace(/\]/g, ']').replace(/,/g, ',');
|
||||
}
|
||||
|
||||
function segmentsToRawMessage(segments: JsonArray): string {
|
||||
return segments.map(seg => segmentToCQ(seg as JsonObject)).join('');
|
||||
}
|
||||
|
||||
function segmentToCQ(seg: JsonObject): string {
|
||||
const type = String(seg.type ?? '');
|
||||
const data = (seg.data ?? {}) as Record<string, unknown>;
|
||||
switch (type) {
|
||||
case 'text':
|
||||
return cqEscape(String(data.text ?? ''));
|
||||
case 'face':
|
||||
return `[CQ:face,id=${data.id ?? 0}]`;
|
||||
case 'image':
|
||||
return `[CQ:image,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
|
||||
case 'at':
|
||||
return `[CQ:at,qq=${data.qq ?? ''}]`;
|
||||
case 'reply':
|
||||
return `[CQ:reply,id=${data.id ?? 0}]`;
|
||||
case 'record':
|
||||
return `[CQ:record,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
|
||||
case 'video':
|
||||
return `[CQ:video,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
|
||||
case 'json':
|
||||
return `[CQ:json,data=${cqEscape(String(data.data ?? ''))}]`;
|
||||
case 'xml':
|
||||
return `[CQ:xml,data=${cqEscape(String(data.data ?? ''))}]`;
|
||||
case 'forward':
|
||||
return `[CQ:forward,id=${cqEscape(String(data.id ?? ''))}]`;
|
||||
case 'mface':
|
||||
return `[CQ:mface,name=${cqEscape(String(data.name ?? ''))}]`;
|
||||
case 'poke':
|
||||
return `[CQ:poke,type=${data.type ?? 0}]`;
|
||||
case 'file':
|
||||
return `[CQ:file,name=${cqEscape(String(data.name ?? ''))},size=${data.size ?? 0},id=${cqEscape(String(data.id ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
|
||||
default:
|
||||
return `[CQ:${type}]`;
|
||||
}
|
||||
}
|
||||
|
||||
function resolveReplyId(
|
||||
isGroup: boolean,
|
||||
sessionId: number,
|
||||
sequence: number,
|
||||
resolver?: MessageIdResolver | null,
|
||||
): number {
|
||||
const seq = Math.trunc(sequence);
|
||||
if (seq === 0) return 0;
|
||||
|
||||
if (resolver) {
|
||||
const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT;
|
||||
const resolved = resolver(isGroup, sessionId, seq, eventName);
|
||||
if (Number.isInteger(resolved) && resolved !== 0) return resolved;
|
||||
}
|
||||
|
||||
return seq;
|
||||
}
|
||||
Loaded 100 of 640 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user