mirror of
https://github.com/LLOneBot/LLOneBot.git
synced 2024-11-22 01:56:33 +00:00
Compare commits
102 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
911841401a | ||
![]() |
4c6bd3df0b | ||
![]() |
c5932bcd98 | ||
![]() |
3abc9f2ae0 | ||
![]() |
e716c28e9a | ||
![]() |
9209ae766c | ||
![]() |
af8cf1882c | ||
![]() |
d93193c7fd | ||
![]() |
8a2245e2ec | ||
![]() |
1e144a1377 | ||
![]() |
8a44086419 | ||
![]() |
133719f96a | ||
![]() |
75c92a68bd | ||
![]() |
90820cf74d | ||
![]() |
f149594e23 | ||
![]() |
60e0c9e4ba | ||
![]() |
1a6739ffab | ||
![]() |
d8e31985af | ||
![]() |
c313fcd491 | ||
![]() |
f42727c8ad | ||
![]() |
17d9c48e68 | ||
![]() |
54179cb686 | ||
![]() |
c9a5ee69cf | ||
![]() |
e348103e84 | ||
![]() |
fccb0852aa | ||
![]() |
b3ea8fbc0c | ||
![]() |
ee483dd0cc | ||
![]() |
ed681b8adf | ||
![]() |
dcd4533eb3 | ||
![]() |
178c32053b | ||
![]() |
49ba276f5d | ||
![]() |
2bfe9e236b | ||
![]() |
05fd258afd | ||
![]() |
3b3098e017 | ||
![]() |
ddf9eed3a5 | ||
![]() |
712f0a8256 | ||
![]() |
a93220f9d2 | ||
![]() |
253cee7458 | ||
![]() |
82f9a4c63f | ||
![]() |
de6c8a5558 | ||
![]() |
c75337b8cb | ||
![]() |
2b796e33fe | ||
![]() |
175307d980 | ||
![]() |
993f8a9e8f | ||
![]() |
0130b8f6f7 | ||
![]() |
ba482d492f | ||
![]() |
6e71cd6064 | ||
![]() |
83dc1abd4a | ||
![]() |
4cabb9696e | ||
![]() |
75883e9cae | ||
![]() |
eeadaa12e9 | ||
![]() |
192736c8be | ||
![]() |
586fbb6518 | ||
![]() |
0a42e2df5b | ||
![]() |
97a637f0c6 | ||
![]() |
3f10b7a002 | ||
![]() |
f638e48260 | ||
![]() |
354ee389bc | ||
![]() |
7188946d7a | ||
![]() |
53055e9eab | ||
![]() |
7bdb84b11b | ||
![]() |
c906bcf7ea | ||
![]() |
cdc82562a3 | ||
![]() |
c34ce8ce0c | ||
![]() |
d1c94754ee | ||
![]() |
2626555c51 | ||
![]() |
5ff6ceec6d | ||
![]() |
17af156451 | ||
![]() |
c3c9e74832 | ||
![]() |
0480208738 | ||
![]() |
62eefbdb69 | ||
![]() |
566537cbe3 | ||
![]() |
ed831ae4cd | ||
![]() |
501031b39b | ||
![]() |
7bfb3f2003 | ||
![]() |
ba8ed36c6a | ||
![]() |
55d046b4f9 | ||
![]() |
ac417cedd3 | ||
![]() |
ade509f26d | ||
![]() |
a66c1a9779 | ||
![]() |
239cf18887 | ||
![]() |
936554cca2 | ||
![]() |
e1d47f55bf | ||
![]() |
cc8e8f108b | ||
![]() |
e6d36dc6c3 | ||
![]() |
66ca936148 | ||
![]() |
5088112864 | ||
![]() |
91075e192b | ||
![]() |
11108bc13f | ||
![]() |
3ec1134204 | ||
![]() |
de41dab846 | ||
![]() |
ededfe0f8c | ||
![]() |
6548876c74 | ||
![]() |
839fd7f1ab | ||
![]() |
2f9cd8ba19 | ||
![]() |
85d648622d | ||
![]() |
f08c816286 | ||
![]() |
6c267044f0 | ||
![]() |
b548fd3f0e | ||
![]() |
f110c2d3df | ||
![]() |
f521873ba7 | ||
![]() |
afe0ff89a7 |
177
README.md
177
README.md
@@ -1,174 +1,25 @@
|
|||||||
|
|
||||||
# LLOneBot API
|
# LLOneBot API
|
||||||
LiteLoaderQQNT的OneBot11协议插件
|
LiteLoaderQQNT插件,使你的NTQQ支持OneBot11协议进行QQ机器人开发
|
||||||
|
|
||||||
TG群:<https://t.me/+nLZEnpne-pQ1OWFl>
|
TG群:<https://t.me/+nLZEnpne-pQ1OWFl>
|
||||||
|
|
||||||
*注意:本文档对应的是 LiteLoader 1.0.0及以上版本,如果你使用的是旧版本请切换到本项目v1分支查看文档*
|
|
||||||
|
|
||||||
*V3之后不再需要LLAPI*
|
|
||||||
|
|
||||||
## 安装方法
|
## 安装方法
|
||||||
|
|
||||||
### 通用手动安装方法
|
见 <https://llonebot.github.io/zh-CN/guide/getting-started>
|
||||||
|
|
||||||
1.安装[LiteLoaderQQNT](https://liteloaderqqnt.github.io/guide/install.html)
|
## 设置界面
|
||||||
|
|
||||||
2.安装本项目插件[LLOneBot](https://github.com/linyuchen/LiteLoaderQQNT-OneBotApi/releases/), 注意本插件2.0以下的版本不支持LiteLoader 1.0.0及以上版本
|
<img src="./doc/image/setting.png" width="500px" alt="图片名称"/>
|
||||||
|
|
||||||
*关于插件的安装方法: 下载后解压复制到插件目录*
|
## HTTP 调用示例
|
||||||
|
|
||||||
*插件目录:`LiteLoaderQQNT/plugins`*
|
|
||||||
|
|
||||||
安装后的目录结构如下
|
|
||||||
```
|
|
||||||
├── plugins
|
|
||||||
│ ├── LLOneBot
|
|
||||||
│ │ └── main/
|
|
||||||
│ │ └── preload/
|
|
||||||
│ │ └── renderer/
|
|
||||||
│ │ └── manifest.json
|
|
||||||
│ │ └── node_modules/...
|
|
||||||
```
|
|
||||||
|
|
||||||
### Linux 容器化快速安装
|
|
||||||
|
|
||||||
执行以下任意脚本,按照提示设置NoVnc密码,即可运行,脚本问题与异常参考 [llonebot-docker](https://github.com/MliKiowa/llonebot-docker) 项目。
|
|
||||||
|
|
||||||
```bash
|
|
||||||
curl https://cdn.jsdelivr.net/gh/LLOneBot/llonebot-docker/fastboot.sh -o fastboot.sh & chmod +x fastboot.sh & sudo sh fastboot.sh
|
|
||||||
```
|
|
||||||
```bash
|
|
||||||
wget -O fastboot.sh https://cdn.jsdelivr.net/gh/LLOneBot/llonebot-docker/fastboot.sh & chmod +x fastboot.sh & sudo sh fastboot.sh
|
|
||||||
```
|
|
||||||
|
|
||||||
### 使用termux安装
|
|
||||||
|
|
||||||
具体安装过程与教程,参考 [llonebot-termux](https://github.com/LLOneBot/llonebot-termux) 项目。
|
|
||||||
|
|
||||||
## 支持的功能
|
|
||||||
|
|
||||||
目前支持的协议
|
|
||||||
- [x] http调用api
|
|
||||||
- [x] http事件上报,不支持快捷回复等快捷操作
|
|
||||||
- [x] 正向websocket
|
|
||||||
- [x] 反向websocket
|
|
||||||
|
|
||||||
主要功能:
|
|
||||||
- [x] 发送好友消息
|
|
||||||
- [x] 发送群消息
|
|
||||||
- [x] 获取好友列表
|
|
||||||
- [x] 获取群列表
|
|
||||||
- [x] 获取群成员列表
|
|
||||||
- [x] 撤回消息
|
|
||||||
- [x] 处理添加好友请求
|
|
||||||
- [x] 处理加群请求
|
|
||||||
- [x] 退群
|
|
||||||
- [x] 上报好友消息
|
|
||||||
- [x] 上报添加好友请求
|
|
||||||
- [x] 上报群消息
|
|
||||||
- [x] 上报好友、群消息撤回
|
|
||||||
- [x] 上报加群请求
|
|
||||||
- [x] 上报群员人数变动(尚不支持识别群员人数变动原因)
|
|
||||||
- [x] 设置群管理员
|
|
||||||
- [x] 群禁言/全体禁言
|
|
||||||
- [x] 群踢人
|
|
||||||
- [x] 群改群成员名片
|
|
||||||
- [x] 修改群名
|
|
||||||
|
|
||||||
消息格式支持:
|
|
||||||
- [x] cq码
|
|
||||||
- [x] 文字
|
|
||||||
- [x] 表情
|
|
||||||
- [x] 图片
|
|
||||||
- [x] 引用消息
|
|
||||||
- [x] @群成员
|
|
||||||
- [x] 语音(支持mp3、wav等多种音频格式直接发送)
|
|
||||||
- [x] json消息(只上报)
|
|
||||||
- [x] 转发消息记录(目前只能发不能收)
|
|
||||||
- [x] 视频(上报时暂时只有个空的file)
|
|
||||||
- [x] 文件(上报时暂时只有个空的file), type为file, data为{file: uri}, 发送时uri支持http://, file://, base64://
|
|
||||||
```
|
|
||||||
{
|
|
||||||
"type": "file",
|
|
||||||
"data": {
|
|
||||||
"file": "file:///D:/1.txt"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
- [ ] 发送音乐卡片
|
|
||||||
- [ ] 红包(没有计划支持)
|
|
||||||
- [ ] xml (没有计划支持)
|
|
||||||
|
|
||||||
## 示例
|
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
## 一些坑
|
## 支持的 api 和功能详情
|
||||||
|
|
||||||
<details>
|
见 <https://llonebot.github.io/zh-CN/develop/api>
|
||||||
<summary>下载了插件但是没有看到在NTQQ中生效</summary>
|
|
||||||
<br/>
|
|
||||||
检查是否下载的是插件release的版本,如果是源码的话需要自行编译。依然不生效请查阅<a href="https://liteloaderqqnt.github.io/guide/plugins.html">LiteLoaderQQNT的文档</a>
|
|
||||||
</details>
|
|
||||||
<br/>
|
|
||||||
|
|
||||||
<details>
|
|
||||||
<summary>调用接口报404</summary>
|
|
||||||
<br/>
|
|
||||||
目前没有支持全部的onebot规范接口,请检查是否调用了不支持的接口
|
|
||||||
-
|
|
||||||
</details>
|
|
||||||
<br/>
|
|
||||||
|
|
||||||
<details>
|
|
||||||
<summary>发送不了图片和语音</summary>
|
|
||||||
<br/>
|
|
||||||
检查当前操作用户是否有LiteLoaderQQNT/data/LLOneBot的写入权限,如Windows把QQ上安装到C盘有可能会出现无权限导致发送失败
|
|
||||||
</details>
|
|
||||||
<br/>
|
|
||||||
|
|
||||||
<details>
|
|
||||||
<summary>QQ变得很卡</summary>
|
|
||||||
<br/>
|
|
||||||
这是你的群特别多导致的,因为启动后会批量获取群成员列表,获取完之后就正常了
|
|
||||||
</details>
|
|
||||||
<br/>
|
|
||||||
|
|
||||||
## 支持的onebot v11 api:
|
|
||||||
- [x] get_login_info
|
|
||||||
- [x] send_msg
|
|
||||||
- [x] send_group_msg
|
|
||||||
- [x] send_private_msg
|
|
||||||
- [x] delete_msg
|
|
||||||
- [x] get_group_list
|
|
||||||
- [x] get_group_info
|
|
||||||
- [x] get_group_member_list
|
|
||||||
- [x] get_group_member_info
|
|
||||||
- [x] get_friend_list
|
|
||||||
- [x] set_friend_add_request
|
|
||||||
- [x] get_msg
|
|
||||||
- [x] send_like
|
|
||||||
- [x] set_group_add_request
|
|
||||||
- [x] set_group_leave
|
|
||||||
- [x] set_group_kick
|
|
||||||
- [x] set_group_ban
|
|
||||||
- [x] set_group_whole_ban
|
|
||||||
- [x] set_group_kick
|
|
||||||
- [x] set_group_admin
|
|
||||||
- [x] set_group_card
|
|
||||||
- [x] set_group_name
|
|
||||||
- [x] get_version_info
|
|
||||||
- [x] get_status
|
|
||||||
- [x] can_send_image
|
|
||||||
- [x] can_send_record
|
|
||||||
- [x] get_image
|
|
||||||
- [x] get_record
|
|
||||||
|
|
||||||
### 支持的go-cqhtp api:
|
|
||||||
- [x] send_private_forward_msg
|
|
||||||
- [x] send_group_forward_msg
|
|
||||||
- [x] get_stranger_info
|
|
||||||
|
|
||||||
## TODO
|
## TODO
|
||||||
- [x] 重构摆脱LLAPI,目前调用LLAPI只能在renderer进程调用,需重构成在main进程调用
|
- [x] 重构摆脱LLAPI,目前调用LLAPI只能在renderer进程调用,需重构成在main进程调用
|
||||||
@@ -178,14 +29,24 @@ wget -O fastboot.sh https://cdn.jsdelivr.net/gh/LLOneBot/llonebot-docker/fastboo
|
|||||||
- [x] 群管理功能,禁言、踢人,改群名片等
|
- [x] 群管理功能,禁言、踢人,改群名片等
|
||||||
- [x] 视频消息
|
- [x] 视频消息
|
||||||
- [x] 文件消息
|
- [x] 文件消息
|
||||||
- [ ] 音乐卡片
|
- [x] 群禁言事件上报
|
||||||
|
- [x] 优化加群成功事件上报
|
||||||
|
- [x] 清理缓存api
|
||||||
- [ ] 无头模式
|
- [ ] 无头模式
|
||||||
|
- [ ] 框架对接文档
|
||||||
|
|
||||||
## onebot11文档
|
## onebot11文档
|
||||||
<https://11.onebot.dev/>
|
<https://11.onebot.dev/>
|
||||||
|
|
||||||
|
## Stargazers over time
|
||||||
|
[](https://starchart.cc/LLOneBot/LLOneBot)
|
||||||
|
|
||||||
|
|
||||||
## 鸣谢
|
## 鸣谢
|
||||||
* [LiteLoaderQQNT](https://liteloaderqqnt.github.io/guide/install.html)
|
* [LiteLoaderQQNT](https://liteloaderqqnt.github.io/guide/install.html)
|
||||||
* [LLAPI](https://github.com/Night-stars-1/LiteLoaderQQNT-Plugin-LLAPI)
|
* [LLAPI](https://github.com/Night-stars-1/LiteLoaderQQNT-Plugin-LLAPI)
|
||||||
* chronocat
|
* [chronocat](https://github.com/chrononeko/chronocat/)
|
||||||
* [koishi-plugin-adapter-onebot](https://github.com/koishijs/koishi-plugin-adapter-onebot)
|
* [koishi-plugin-adapter-onebot](https://github.com/koishijs/koishi-plugin-adapter-onebot)
|
||||||
|
|
||||||
|
## 友链
|
||||||
|
* [Lagrange.Core](https://github.com/LagrangeDev/Lagrange.Core) 一款用C#实现的NTQQ纯协议跨平台QQ机器人框架
|
||||||
|
BIN
doc/image/setting.png
Normal file
BIN
doc/image/setting.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 64 KiB |
@@ -6,7 +6,7 @@ const external = ["silk-wasm", "ws",
|
|||||||
"module-error", "catering", "node-gyp-build"];
|
"module-error", "catering", "node-gyp-build"];
|
||||||
|
|
||||||
function genCpModule(module: string) {
|
function genCpModule(module: string) {
|
||||||
return { src: `./node_modules/${module}`, dest: `dist/node_modules/${module}`, flatten: false }
|
return {src: `./node_modules/${module}`, dest: `dist/node_modules/${module}`, flatten: false}
|
||||||
}
|
}
|
||||||
|
|
||||||
let config = {
|
let config = {
|
||||||
@@ -16,19 +16,25 @@ let config = {
|
|||||||
emptyOutDir: true,
|
emptyOutDir: true,
|
||||||
lib: {
|
lib: {
|
||||||
formats: ["cjs"],
|
formats: ["cjs"],
|
||||||
entry: { "main": "src/main/main.ts" },
|
entry: {"main": "src/main/main.ts"},
|
||||||
},
|
},
|
||||||
rollupOptions: {
|
rollupOptions: {
|
||||||
external,
|
external,
|
||||||
input: "src/main/main.ts",
|
input: "src/main/main.ts",
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
resolve:{
|
resolve: {
|
||||||
alias: {
|
alias: {
|
||||||
'./lib-cov/fluent-ffmpeg': './lib/fluent-ffmpeg'
|
'./lib-cov/fluent-ffmpeg': './lib/fluent-ffmpeg'
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
plugins: [cp({ targets: [...external.map(genCpModule), { src: './manifest.json', dest: 'dist' }] })]
|
plugins: [cp({
|
||||||
|
targets: [
|
||||||
|
...external.map(genCpModule),
|
||||||
|
{src: './manifest.json', dest: 'dist'}, {src: './icon.jpg', dest: 'dist'},
|
||||||
|
{src: './src/ntqqapi/external/ccpoke/poke-win32-x64.node', dest: 'dist/main/ccpoke/'},
|
||||||
|
]
|
||||||
|
})]
|
||||||
},
|
},
|
||||||
preload: {
|
preload: {
|
||||||
// vite config options
|
// vite config options
|
||||||
@@ -37,15 +43,14 @@ let config = {
|
|||||||
emptyOutDir: true,
|
emptyOutDir: true,
|
||||||
lib: {
|
lib: {
|
||||||
formats: ["cjs"],
|
formats: ["cjs"],
|
||||||
entry: { "preload": "src/preload.ts" },
|
entry: {"preload": "src/preload.ts"},
|
||||||
},
|
},
|
||||||
rollupOptions: {
|
rollupOptions: {
|
||||||
// external: externalAll,
|
// external: externalAll,
|
||||||
input: "src/preload.ts",
|
input: "src/preload.ts",
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
resolve:{
|
resolve: {}
|
||||||
}
|
|
||||||
},
|
},
|
||||||
renderer: {
|
renderer: {
|
||||||
// vite config options
|
// vite config options
|
||||||
@@ -54,15 +59,14 @@ let config = {
|
|||||||
emptyOutDir: true,
|
emptyOutDir: true,
|
||||||
lib: {
|
lib: {
|
||||||
formats: ["es"],
|
formats: ["es"],
|
||||||
entry: { "renderer": "src/renderer/index.ts" },
|
entry: {"renderer": "src/renderer/index.ts"},
|
||||||
},
|
},
|
||||||
rollupOptions: {
|
rollupOptions: {
|
||||||
// external: externalAll,
|
// external: externalAll,
|
||||||
input: "src/renderer/index.ts",
|
input: "src/renderer/index.ts",
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
resolve:{
|
resolve: {}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -1,11 +1,11 @@
|
|||||||
{
|
{
|
||||||
"manifest_version": 4,
|
"manifest_version": 4,
|
||||||
"type": "extension",
|
"type": "extension",
|
||||||
"name": "LLOneBot v3.13.0",
|
"name": "LLOneBot v3.16.1",
|
||||||
"slug": "LLOneBot",
|
"slug": "LLOneBot",
|
||||||
"description": "LiteLoaderQQNT的OneBotApi",
|
"description": "LiteLoaderQQNT的OneBotApi,不支持商店在线更新",
|
||||||
"version": "3.13.0",
|
"version": "3.16.1",
|
||||||
"thumbnail": "./icon.png",
|
"icon": "./icon.jpg",
|
||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
"name": "linyuchen",
|
"name": "linyuchen",
|
||||||
|
207
package-lock.json
generated
207
package-lock.json
generated
@@ -13,6 +13,7 @@
|
|||||||
"file-type": "^19.0.0",
|
"file-type": "^19.0.0",
|
||||||
"fluent-ffmpeg": "^2.1.2",
|
"fluent-ffmpeg": "^2.1.2",
|
||||||
"level": "^8.0.1",
|
"level": "^8.0.1",
|
||||||
|
"node-stream-zip": "^1.15.0",
|
||||||
"silk-wasm": "^3.2.3",
|
"silk-wasm": "^3.2.3",
|
||||||
"utf-8-validate": "^6.0.3",
|
"utf-8-validate": "^6.0.3",
|
||||||
"uuid": "^9.0.1",
|
"uuid": "^9.0.1",
|
||||||
@@ -986,16 +987,6 @@
|
|||||||
"url": "https://opencollective.com/eslint"
|
"url": "https://opencollective.com/eslint"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@eslint/eslintrc/node_modules/brace-expansion": {
|
|
||||||
"version": "1.1.11",
|
|
||||||
"resolved": "https://mirrors.cloud.tencent.com/npm/brace-expansion/-/brace-expansion-1.1.11.tgz",
|
|
||||||
"integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
|
|
||||||
"dev": true,
|
|
||||||
"dependencies": {
|
|
||||||
"balanced-match": "^1.0.0",
|
|
||||||
"concat-map": "0.0.1"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@eslint/eslintrc/node_modules/globals": {
|
"node_modules/@eslint/eslintrc/node_modules/globals": {
|
||||||
"version": "13.24.0",
|
"version": "13.24.0",
|
||||||
"resolved": "https://mirrors.cloud.tencent.com/npm/globals/-/globals-13.24.0.tgz",
|
"resolved": "https://mirrors.cloud.tencent.com/npm/globals/-/globals-13.24.0.tgz",
|
||||||
@@ -1011,18 +1002,6 @@
|
|||||||
"url": "https://github.com/sponsors/sindresorhus"
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@eslint/eslintrc/node_modules/minimatch": {
|
|
||||||
"version": "3.1.2",
|
|
||||||
"resolved": "https://mirrors.cloud.tencent.com/npm/minimatch/-/minimatch-3.1.2.tgz",
|
|
||||||
"integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
|
|
||||||
"dev": true,
|
|
||||||
"dependencies": {
|
|
||||||
"brace-expansion": "^1.1.7"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": "*"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@eslint/eslintrc/node_modules/type-fest": {
|
"node_modules/@eslint/eslintrc/node_modules/type-fest": {
|
||||||
"version": "0.20.2",
|
"version": "0.20.2",
|
||||||
"resolved": "https://mirrors.cloud.tencent.com/npm/type-fest/-/type-fest-0.20.2.tgz",
|
"resolved": "https://mirrors.cloud.tencent.com/npm/type-fest/-/type-fest-0.20.2.tgz",
|
||||||
@@ -1058,28 +1037,6 @@
|
|||||||
"node": ">=10.10.0"
|
"node": ">=10.10.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@humanwhocodes/config-array/node_modules/brace-expansion": {
|
|
||||||
"version": "1.1.11",
|
|
||||||
"resolved": "https://mirrors.cloud.tencent.com/npm/brace-expansion/-/brace-expansion-1.1.11.tgz",
|
|
||||||
"integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
|
|
||||||
"dev": true,
|
|
||||||
"dependencies": {
|
|
||||||
"balanced-match": "^1.0.0",
|
|
||||||
"concat-map": "0.0.1"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@humanwhocodes/config-array/node_modules/minimatch": {
|
|
||||||
"version": "3.1.2",
|
|
||||||
"resolved": "https://mirrors.cloud.tencent.com/npm/minimatch/-/minimatch-3.1.2.tgz",
|
|
||||||
"integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
|
|
||||||
"dev": true,
|
|
||||||
"dependencies": {
|
|
||||||
"brace-expansion": "^1.1.7"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": "*"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@humanwhocodes/module-importer": {
|
"node_modules/@humanwhocodes/module-importer": {
|
||||||
"version": "1.0.1",
|
"version": "1.0.1",
|
||||||
"resolved": "https://mirrors.cloud.tencent.com/npm/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz",
|
"resolved": "https://mirrors.cloud.tencent.com/npm/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz",
|
||||||
@@ -3225,16 +3182,6 @@
|
|||||||
"eslint": "^2 || ^3 || ^4 || ^5 || ^6 || ^7.2.0 || ^8"
|
"eslint": "^2 || ^3 || ^4 || ^5 || ^6 || ^7.2.0 || ^8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/eslint-plugin-import/node_modules/brace-expansion": {
|
|
||||||
"version": "1.1.11",
|
|
||||||
"resolved": "https://mirrors.cloud.tencent.com/npm/brace-expansion/-/brace-expansion-1.1.11.tgz",
|
|
||||||
"integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
|
|
||||||
"dev": true,
|
|
||||||
"dependencies": {
|
|
||||||
"balanced-match": "^1.0.0",
|
|
||||||
"concat-map": "0.0.1"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/eslint-plugin-import/node_modules/debug": {
|
"node_modules/eslint-plugin-import/node_modules/debug": {
|
||||||
"version": "3.2.7",
|
"version": "3.2.7",
|
||||||
"resolved": "https://mirrors.cloud.tencent.com/npm/debug/-/debug-3.2.7.tgz",
|
"resolved": "https://mirrors.cloud.tencent.com/npm/debug/-/debug-3.2.7.tgz",
|
||||||
@@ -3256,18 +3203,6 @@
|
|||||||
"node": ">=0.10.0"
|
"node": ">=0.10.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/eslint-plugin-import/node_modules/minimatch": {
|
|
||||||
"version": "3.1.2",
|
|
||||||
"resolved": "https://mirrors.cloud.tencent.com/npm/minimatch/-/minimatch-3.1.2.tgz",
|
|
||||||
"integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
|
|
||||||
"dev": true,
|
|
||||||
"dependencies": {
|
|
||||||
"brace-expansion": "^1.1.7"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": "*"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/eslint-plugin-n": {
|
"node_modules/eslint-plugin-n": {
|
||||||
"version": "16.6.2",
|
"version": "16.6.2",
|
||||||
"resolved": "https://mirrors.cloud.tencent.com/npm/eslint-plugin-n/-/eslint-plugin-n-16.6.2.tgz",
|
"resolved": "https://mirrors.cloud.tencent.com/npm/eslint-plugin-n/-/eslint-plugin-n-16.6.2.tgz",
|
||||||
@@ -3296,16 +3231,6 @@
|
|||||||
"eslint": ">=7.0.0"
|
"eslint": ">=7.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/eslint-plugin-n/node_modules/brace-expansion": {
|
|
||||||
"version": "1.1.11",
|
|
||||||
"resolved": "https://mirrors.cloud.tencent.com/npm/brace-expansion/-/brace-expansion-1.1.11.tgz",
|
|
||||||
"integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
|
|
||||||
"dev": true,
|
|
||||||
"dependencies": {
|
|
||||||
"balanced-match": "^1.0.0",
|
|
||||||
"concat-map": "0.0.1"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/eslint-plugin-n/node_modules/globals": {
|
"node_modules/eslint-plugin-n/node_modules/globals": {
|
||||||
"version": "13.24.0",
|
"version": "13.24.0",
|
||||||
"resolved": "https://mirrors.cloud.tencent.com/npm/globals/-/globals-13.24.0.tgz",
|
"resolved": "https://mirrors.cloud.tencent.com/npm/globals/-/globals-13.24.0.tgz",
|
||||||
@@ -3321,18 +3246,6 @@
|
|||||||
"url": "https://github.com/sponsors/sindresorhus"
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/eslint-plugin-n/node_modules/minimatch": {
|
|
||||||
"version": "3.1.2",
|
|
||||||
"resolved": "https://mirrors.cloud.tencent.com/npm/minimatch/-/minimatch-3.1.2.tgz",
|
|
||||||
"integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
|
|
||||||
"dev": true,
|
|
||||||
"dependencies": {
|
|
||||||
"brace-expansion": "^1.1.7"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": "*"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/eslint-plugin-n/node_modules/semver": {
|
"node_modules/eslint-plugin-n/node_modules/semver": {
|
||||||
"version": "7.6.0",
|
"version": "7.6.0",
|
||||||
"resolved": "https://mirrors.cloud.tencent.com/npm/semver/-/semver-7.6.0.tgz",
|
"resolved": "https://mirrors.cloud.tencent.com/npm/semver/-/semver-7.6.0.tgz",
|
||||||
@@ -3384,16 +3297,6 @@
|
|||||||
"url": "https://opencollective.com/eslint"
|
"url": "https://opencollective.com/eslint"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/eslint/node_modules/brace-expansion": {
|
|
||||||
"version": "1.1.11",
|
|
||||||
"resolved": "https://mirrors.cloud.tencent.com/npm/brace-expansion/-/brace-expansion-1.1.11.tgz",
|
|
||||||
"integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
|
|
||||||
"dev": true,
|
|
||||||
"dependencies": {
|
|
||||||
"balanced-match": "^1.0.0",
|
|
||||||
"concat-map": "0.0.1"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/eslint/node_modules/eslint-scope": {
|
"node_modules/eslint/node_modules/eslint-scope": {
|
||||||
"version": "7.2.2",
|
"version": "7.2.2",
|
||||||
"resolved": "https://mirrors.cloud.tencent.com/npm/eslint-scope/-/eslint-scope-7.2.2.tgz",
|
"resolved": "https://mirrors.cloud.tencent.com/npm/eslint-scope/-/eslint-scope-7.2.2.tgz",
|
||||||
@@ -3477,18 +3380,6 @@
|
|||||||
"url": "https://github.com/sponsors/sindresorhus"
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/eslint/node_modules/minimatch": {
|
|
||||||
"version": "3.1.2",
|
|
||||||
"resolved": "https://mirrors.cloud.tencent.com/npm/minimatch/-/minimatch-3.1.2.tgz",
|
|
||||||
"integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
|
|
||||||
"dev": true,
|
|
||||||
"dependencies": {
|
|
||||||
"brace-expansion": "^1.1.7"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": "*"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/eslint/node_modules/p-limit": {
|
"node_modules/eslint/node_modules/p-limit": {
|
||||||
"version": "3.1.0",
|
"version": "3.1.0",
|
||||||
"resolved": "https://mirrors.cloud.tencent.com/npm/p-limit/-/p-limit-3.1.0.tgz",
|
"resolved": "https://mirrors.cloud.tencent.com/npm/p-limit/-/p-limit-3.1.0.tgz",
|
||||||
@@ -4012,6 +3903,26 @@
|
|||||||
"url": "https://github.com/privatenumber/get-tsconfig?sponsor=1"
|
"url": "https://github.com/privatenumber/get-tsconfig?sponsor=1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/glob": {
|
||||||
|
"version": "7.2.3",
|
||||||
|
"resolved": "https://mirrors.cloud.tencent.com/npm/glob/-/glob-7.2.3.tgz",
|
||||||
|
"integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==",
|
||||||
|
"dev": true,
|
||||||
|
"dependencies": {
|
||||||
|
"fs.realpath": "^1.0.0",
|
||||||
|
"inflight": "^1.0.4",
|
||||||
|
"inherits": "2",
|
||||||
|
"minimatch": "^3.1.1",
|
||||||
|
"once": "^1.3.0",
|
||||||
|
"path-is-absolute": "^1.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "*"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/isaacs"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/glob-parent": {
|
"node_modules/glob-parent": {
|
||||||
"version": "5.1.2",
|
"version": "5.1.2",
|
||||||
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",
|
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",
|
||||||
@@ -4922,6 +4833,28 @@
|
|||||||
"node": ">=4"
|
"node": ">=4"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/minimatch": {
|
||||||
|
"version": "3.1.2",
|
||||||
|
"resolved": "https://mirrors.cloud.tencent.com/npm/minimatch/-/minimatch-3.1.2.tgz",
|
||||||
|
"integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
|
||||||
|
"dev": true,
|
||||||
|
"dependencies": {
|
||||||
|
"brace-expansion": "^1.1.7"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/minimatch/node_modules/brace-expansion": {
|
||||||
|
"version": "1.1.11",
|
||||||
|
"resolved": "https://mirrors.cloud.tencent.com/npm/brace-expansion/-/brace-expansion-1.1.11.tgz",
|
||||||
|
"integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
|
||||||
|
"dev": true,
|
||||||
|
"dependencies": {
|
||||||
|
"balanced-match": "^1.0.0",
|
||||||
|
"concat-map": "0.0.1"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/minimist": {
|
"node_modules/minimist": {
|
||||||
"version": "1.2.8",
|
"version": "1.2.8",
|
||||||
"resolved": "https://mirrors.cloud.tencent.com/npm/minimist/-/minimist-1.2.8.tgz",
|
"resolved": "https://mirrors.cloud.tencent.com/npm/minimist/-/minimist-1.2.8.tgz",
|
||||||
@@ -4998,6 +4931,18 @@
|
|||||||
"integrity": "sha512-y10wOWt8yZpqXmOgRo77WaHEmhYQYGNA6y421PKsKYWEK8aW+cqAphborZDhqfyKrbZEN92CN1X2KbafY2s7Yw==",
|
"integrity": "sha512-y10wOWt8yZpqXmOgRo77WaHEmhYQYGNA6y421PKsKYWEK8aW+cqAphborZDhqfyKrbZEN92CN1X2KbafY2s7Yw==",
|
||||||
"dev": true
|
"dev": true
|
||||||
},
|
},
|
||||||
|
"node_modules/node-stream-zip": {
|
||||||
|
"version": "1.15.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/node-stream-zip/-/node-stream-zip-1.15.0.tgz",
|
||||||
|
"integrity": "sha512-LN4fydt9TqhZhThkZIVQnF9cwjU3qmUH9h78Mx/K7d3VvfRqqwthLwJEUOEL0QPZ0XQmNN7be5Ggit5+4dq3Bw==",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.12.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/antelle"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/normalize-url": {
|
"node_modules/normalize-url": {
|
||||||
"version": "6.1.0",
|
"version": "6.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-6.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-6.1.0.tgz",
|
||||||
@@ -5509,48 +5454,6 @@
|
|||||||
"url": "https://github.com/sponsors/isaacs"
|
"url": "https://github.com/sponsors/isaacs"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/rimraf/node_modules/brace-expansion": {
|
|
||||||
"version": "1.1.11",
|
|
||||||
"resolved": "https://mirrors.cloud.tencent.com/npm/brace-expansion/-/brace-expansion-1.1.11.tgz",
|
|
||||||
"integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
|
|
||||||
"dev": true,
|
|
||||||
"dependencies": {
|
|
||||||
"balanced-match": "^1.0.0",
|
|
||||||
"concat-map": "0.0.1"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/rimraf/node_modules/glob": {
|
|
||||||
"version": "7.2.3",
|
|
||||||
"resolved": "https://mirrors.cloud.tencent.com/npm/glob/-/glob-7.2.3.tgz",
|
|
||||||
"integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==",
|
|
||||||
"dev": true,
|
|
||||||
"dependencies": {
|
|
||||||
"fs.realpath": "^1.0.0",
|
|
||||||
"inflight": "^1.0.4",
|
|
||||||
"inherits": "2",
|
|
||||||
"minimatch": "^3.1.1",
|
|
||||||
"once": "^1.3.0",
|
|
||||||
"path-is-absolute": "^1.0.0"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": "*"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"url": "https://github.com/sponsors/isaacs"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/rimraf/node_modules/minimatch": {
|
|
||||||
"version": "3.1.2",
|
|
||||||
"resolved": "https://mirrors.cloud.tencent.com/npm/minimatch/-/minimatch-3.1.2.tgz",
|
|
||||||
"integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
|
|
||||||
"dev": true,
|
|
||||||
"dependencies": {
|
|
||||||
"brace-expansion": "^1.1.7"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": "*"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/roarr": {
|
"node_modules/roarr": {
|
||||||
"version": "2.15.4",
|
"version": "2.15.4",
|
||||||
"resolved": "https://registry.npmjs.org/roarr/-/roarr-2.15.4.tgz",
|
"resolved": "https://registry.npmjs.org/roarr/-/roarr-2.15.4.tgz",
|
||||||
|
@@ -9,7 +9,7 @@
|
|||||||
"build-mac": "npm run build && npm run deploy-mac",
|
"build-mac": "npm run build && npm run deploy-mac",
|
||||||
"deploy-mac": "cp -r dist/* ~/Library/Containers/com.tencent.qq/Data/LiteLoaderQQNT/plugins/LLOneBot/",
|
"deploy-mac": "cp -r dist/* ~/Library/Containers/com.tencent.qq/Data/LiteLoaderQQNT/plugins/LLOneBot/",
|
||||||
"build-win": "npm run build && npm run deploy-win",
|
"build-win": "npm run build && npm run deploy-win",
|
||||||
"deploy-win": "cmd /c \"xcopy /S /Y dist\\* %USERPROFILE%\\documents\\LiteLoaderQQNT\\plugins\\LLOneBot\\\""
|
"deploy-win": "cmd /c \"xcopy /C /S /Y dist\\* %USERPROFILE%\\documents\\LiteLoaderQQNT\\plugins\\LLOneBot\\\""
|
||||||
},
|
},
|
||||||
"author": "",
|
"author": "",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
@@ -18,6 +18,7 @@
|
|||||||
"file-type": "^19.0.0",
|
"file-type": "^19.0.0",
|
||||||
"fluent-ffmpeg": "^2.1.2",
|
"fluent-ffmpeg": "^2.1.2",
|
||||||
"level": "^8.0.1",
|
"level": "^8.0.1",
|
||||||
|
"node-stream-zip": "^1.15.0",
|
||||||
"silk-wasm": "^3.2.3",
|
"silk-wasm": "^3.2.3",
|
||||||
"utf-8-validate": "^6.0.3",
|
"utf-8-validate": "^6.0.3",
|
||||||
"uuid": "^9.0.1",
|
"uuid": "^9.0.1",
|
||||||
|
17
scripts/test/test_db.ts
Normal file
17
scripts/test/test_db.ts
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
import {Level} from "level"
|
||||||
|
|
||||||
|
const db = new Level(process.env["level_db_path"], {valueEncoding: 'json'});
|
||||||
|
|
||||||
|
async function getGroupNotify() {
|
||||||
|
let keys = await db.keys().all();
|
||||||
|
let result = []
|
||||||
|
for (const key of keys) {
|
||||||
|
// console.log(key)
|
||||||
|
if (key.startsWith("group_notify_")) {
|
||||||
|
result.push(key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
getGroupNotify().then(console.log)
|
@@ -2,4 +2,6 @@ export const CHANNEL_GET_CONFIG = 'llonebot_get_config'
|
|||||||
export const CHANNEL_SET_CONFIG = 'llonebot_set_config'
|
export const CHANNEL_SET_CONFIG = 'llonebot_set_config'
|
||||||
export const CHANNEL_LOG = 'llonebot_log'
|
export const CHANNEL_LOG = 'llonebot_log'
|
||||||
export const CHANNEL_ERROR = 'llonebot_error'
|
export const CHANNEL_ERROR = 'llonebot_error'
|
||||||
|
export const CHANNEL_UPDATE = 'llonebot_update'
|
||||||
|
export const CHANNEL_CHECKVERSION = 'llonebot_checkversion'
|
||||||
export const CHANNEL_SELECT_FILE = 'llonebot_select_ffmpeg'
|
export const CHANNEL_SELECT_FILE = 'llonebot_select_ffmpeg'
|
||||||
|
@@ -1,9 +1,15 @@
|
|||||||
import fs from "fs";
|
import fs from "fs";
|
||||||
import {Config, OB11Config} from './types';
|
import {Config, OB11Config} from './types';
|
||||||
import {mergeNewProperties} from "./utils";
|
|
||||||
|
import {mergeNewProperties} from "./utils/helper";
|
||||||
|
import path from "node:path";
|
||||||
|
import {selfInfo} from "./data";
|
||||||
|
import {DATA_DIR} from "./utils";
|
||||||
|
|
||||||
export const HOOK_LOG = false;
|
export const HOOK_LOG = false;
|
||||||
|
|
||||||
|
export const ALLOW_SEND_TEMP_MSG = false;
|
||||||
|
|
||||||
export class ConfigUtil {
|
export class ConfigUtil {
|
||||||
private readonly configPath: string;
|
private readonly configPath: string;
|
||||||
private config: Config | null = null;
|
private config: Config | null = null;
|
||||||
@@ -42,6 +48,7 @@ export class ConfigUtil {
|
|||||||
reportSelfMessage: false,
|
reportSelfMessage: false,
|
||||||
autoDeleteFile: false,
|
autoDeleteFile: false,
|
||||||
autoDeleteFileSecond: 60,
|
autoDeleteFileSecond: 60,
|
||||||
|
enablePoke: false
|
||||||
};
|
};
|
||||||
|
|
||||||
if (!fs.existsSync(this.configPath)) {
|
if (!fs.existsSync(this.configPath)) {
|
||||||
@@ -82,3 +89,8 @@ export class ConfigUtil {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function getConfigUtil() {
|
||||||
|
const configFilePath = path.join(DATA_DIR, `config_${selfInfo.uin}.json`)
|
||||||
|
return new ConfigUtil(configFilePath)
|
||||||
|
}
|
@@ -1,16 +1,14 @@
|
|||||||
import {NTQQApi} from '../ntqqapi/ntcall'
|
|
||||||
import {
|
import {
|
||||||
type Friend,
|
type Friend,
|
||||||
type FriendRequest,
|
type FriendRequest,
|
||||||
type Group,
|
type Group,
|
||||||
type GroupMember,
|
type GroupMember,
|
||||||
type GroupNotify,
|
|
||||||
type RawMessage,
|
|
||||||
type SelfInfo
|
type SelfInfo
|
||||||
} from '../ntqqapi/types'
|
} from '../ntqqapi/types'
|
||||||
import {type FileCache, type LLOneBotError} from './types'
|
import {type FileCache, type LLOneBotError} from './types'
|
||||||
import {dbUtil} from "./db";
|
import {NTQQGroupApi} from "../ntqqapi/api/group";
|
||||||
import {raw} from "express";
|
import {log} from "./utils/log";
|
||||||
|
import {isNumeric} from "./utils/helper";
|
||||||
|
|
||||||
export const selfInfo: SelfInfo = {
|
export const selfInfo: SelfInfo = {
|
||||||
uid: '',
|
uid: '',
|
||||||
@@ -20,61 +18,63 @@ export const selfInfo: SelfInfo = {
|
|||||||
}
|
}
|
||||||
export let groups: Group[] = []
|
export let groups: Group[] = []
|
||||||
export let friends: Friend[] = []
|
export let friends: Friend[] = []
|
||||||
export let groupNotifies: Map<string, GroupNotify> = new Map<string, GroupNotify>()
|
|
||||||
export let friendRequests: Map<number, FriendRequest> = new Map<number, FriendRequest>()
|
export let friendRequests: Map<number, FriendRequest> = new Map<number, FriendRequest>()
|
||||||
export const llonebotError: LLOneBotError = {
|
export const llonebotError: LLOneBotError = {
|
||||||
ffmpegError: '',
|
ffmpegError: '',
|
||||||
otherError: ''
|
otherError: ''
|
||||||
}
|
}
|
||||||
|
|
||||||
export const fileCache = new Map<string, FileCache>()
|
|
||||||
|
|
||||||
|
export async function getFriend(uinOrUid: string): Promise<Friend | undefined> {
|
||||||
export async function getHistoryMsgByShortId(shortId: number) {
|
let filterKey = isNumeric(uinOrUid) ? "uin" : "uid"
|
||||||
// log("getHistoryMsgByShortId", shortId, Object.values(msgHistory).map(m=>m.msgShortId))
|
let filterValue = uinOrUid
|
||||||
return await dbUtil.getMsgByShortId(shortId);
|
let friend = friends.find(friend => friend[filterKey] === filterValue.toString())
|
||||||
}
|
// if (!friend) {
|
||||||
|
// try {
|
||||||
export async function getFriend(qq: string): Promise<Friend | undefined> {
|
// friends = (await NTQQApi.getFriends(true))
|
||||||
let friend = friends.find(friend => friend.uin === qq)
|
// friend = friends.find(friend => friend[filterKey] === filterValue.toString())
|
||||||
if (!friend){
|
// } catch (e) {
|
||||||
friends = (await NTQQApi.getFriends(true))
|
// // log("刷新好友列表失败", e.stack.toString())
|
||||||
friend = friends.find(friend => friend.uin === qq)
|
// }
|
||||||
}
|
// }
|
||||||
return friend
|
return friend
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getGroup(qq: string): Promise<Group | undefined> {
|
export async function getGroup(qq: string): Promise<Group | undefined> {
|
||||||
let group = groups.find(group => group.groupCode === qq)
|
let group = groups.find(group => group.groupCode === qq.toString())
|
||||||
if (!group){
|
if (!group) {
|
||||||
const _groups = await NTQQApi.getGroups(true);
|
try {
|
||||||
group = _groups.find(group => group.groupCode === qq)
|
const _groups = await NTQQGroupApi.getGroups(true);
|
||||||
if (group){
|
group = _groups.find(group => group.groupCode === qq.toString())
|
||||||
groups.push(group)
|
if (group) {
|
||||||
|
groups.push(group)
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
return group
|
return group
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getGroupMember(groupQQ: string | number, memberQQ: string | number, memberUid: string = null) {
|
export async function getGroupMember(groupQQ: string | number, memberUinOrUid: string | number) {
|
||||||
groupQQ = groupQQ.toString()
|
groupQQ = groupQQ.toString()
|
||||||
if (memberQQ) {
|
memberUinOrUid = memberUinOrUid.toString()
|
||||||
memberQQ = memberQQ.toString()
|
|
||||||
}
|
|
||||||
const group = await getGroup(groupQQ)
|
const group = await getGroup(groupQQ)
|
||||||
if (group) {
|
if (group) {
|
||||||
let filterFunc: (member: GroupMember) => boolean
|
const filterKey = isNumeric(memberUinOrUid) ? "uin" : "uid"
|
||||||
if (memberQQ) {
|
const filterValue = memberUinOrUid
|
||||||
filterFunc = member => member.uin === memberQQ
|
let filterFunc: (member: GroupMember) => boolean = member => member[filterKey] === filterValue
|
||||||
} else if (memberUid) {
|
|
||||||
filterFunc = member => member.uid === memberUid
|
|
||||||
}
|
|
||||||
let member = group.members?.find(filterFunc)
|
let member = group.members?.find(filterFunc)
|
||||||
if (!member) {
|
if (!member) {
|
||||||
const _members = await NTQQApi.getGroupMembers(groupQQ)
|
try {
|
||||||
if (_members.length > 0) {
|
const _members = await NTQQGroupApi.getGroupMembers(groupQQ)
|
||||||
group.members = _members
|
if (_members.length > 0) {
|
||||||
|
group.members = _members
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
// log("刷新群成员列表失败", e.stack.toString())
|
||||||
}
|
}
|
||||||
|
|
||||||
member = group.members?.find(filterFunc)
|
member = group.members?.find(filterFunc)
|
||||||
}
|
}
|
||||||
return member
|
return member
|
||||||
@@ -85,7 +85,7 @@ export async function getGroupMember(groupQQ: string | number, memberQQ: string
|
|||||||
export async function refreshGroupMembers(groupQQ: string) {
|
export async function refreshGroupMembers(groupQQ: string) {
|
||||||
const group = groups.find(group => group.groupCode === groupQQ)
|
const group = groups.find(group => group.groupCode === groupQQ)
|
||||||
if (group) {
|
if (group) {
|
||||||
group.members = await NTQQApi.getGroupMembers(groupQQ)
|
group.members = await NTQQGroupApi.getGroupMembers(groupQQ)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
261
src/common/db.ts
261
src/common/db.ts
@@ -1,22 +1,29 @@
|
|||||||
// import {DATA_DIR} from "./utils";
|
|
||||||
import {Level} from "level";
|
import {Level} from "level";
|
||||||
import {RawMessage} from "../ntqqapi/types";
|
import {type GroupNotify, RawMessage} from "../ntqqapi/types";
|
||||||
import {DATA_DIR} from "./utils";
|
import {DATA_DIR} from "./utils";
|
||||||
import {selfInfo} from "./data";
|
import {selfInfo} from "./data";
|
||||||
|
import {FileCache} from "./types";
|
||||||
|
import {log} from "./utils/log";
|
||||||
|
|
||||||
|
type ReceiveTempUinMap = Record<string, string>;
|
||||||
|
|
||||||
class DBUtil {
|
class DBUtil {
|
||||||
private readonly DB_KEY_PREFIX_MSG_ID = "msg_id_";
|
public readonly DB_KEY_PREFIX_MSG_ID = "msg_id_";
|
||||||
private readonly DB_KEY_PREFIX_MSG_SHORT_ID = "msg_short_id_";
|
public readonly DB_KEY_PREFIX_MSG_SHORT_ID = "msg_short_id_";
|
||||||
private readonly DB_KEY_PREFIX_MSG_SEQ_ID = "msg_seq_id_";
|
public readonly DB_KEY_PREFIX_MSG_SEQ_ID = "msg_seq_id_";
|
||||||
private db: Level;
|
public readonly DB_KEY_PREFIX_FILE = "file_";
|
||||||
private cache: Record<string, RawMessage> = {} // <msg_id_ | msg_short_id_ | msg_seq_id_><id>: RawMessage
|
public readonly DB_KEY_PREFIX_GROUP_NOTIFY = "group_notify_";
|
||||||
|
private readonly DB_KEY_RECEIVED_TEMP_UIN_MAP = "received_temp_uin_map";
|
||||||
|
public db: Level;
|
||||||
|
public cache: Record<string, RawMessage | string | FileCache | GroupNotify | ReceiveTempUinMap> = {} // <msg_id_ | msg_short_id_ | msg_seq_id_><id>: RawMessage
|
||||||
|
private currentShortId: number;
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* 数据库结构
|
* 数据库结构
|
||||||
* msg_id_101231230999: {} // 长id: RawMessage
|
* msg_id_101231230999: {} // 长id: RawMessage
|
||||||
* msg_short_id_1: 101231230999 // 短id: 长id
|
* msg_short_id_1: 101231230999 // 短id: 长id
|
||||||
* msg_seq_id_1: 101231230999 // 序列id: 长id
|
* msg_seq_id_1: 101231230999 // 序列id: 长id
|
||||||
|
* file_7827DBAFJFW2323.png: {} // 文件名: FileCache
|
||||||
* */
|
* */
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
@@ -24,9 +31,9 @@ class DBUtil {
|
|||||||
new Promise((resolve, reject) => {
|
new Promise((resolve, reject) => {
|
||||||
const initDB = () => {
|
const initDB = () => {
|
||||||
initCount++;
|
initCount++;
|
||||||
if (initCount > 50) {
|
// if (initCount > 50) {
|
||||||
return reject("init db fail")
|
// return reject("init db fail")
|
||||||
}
|
// }
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (!selfInfo.uin) {
|
if (!selfInfo.uin) {
|
||||||
@@ -38,110 +45,232 @@ class DBUtil {
|
|||||||
console.log("llonebot init db success")
|
console.log("llonebot init db success")
|
||||||
resolve(null)
|
resolve(null)
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// console.log("init db fail", e.stack.toString())
|
console.log("init db fail", e.stack.toString())
|
||||||
setTimeout(initDB, 300);
|
setTimeout(initDB, 300);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
initDB();
|
initDB();
|
||||||
}).then()
|
}).then()
|
||||||
|
|
||||||
|
const expiredMilliSecond = 1000 * 60 * 60;
|
||||||
|
|
||||||
setInterval(() => {
|
setInterval(() => {
|
||||||
this.cache = {}
|
// this.cache = {}
|
||||||
}, 1000 * 60 * 10)
|
// 清理时间较久的缓存
|
||||||
|
const now = Date.now()
|
||||||
|
for (let key in this.cache) {
|
||||||
|
let message: RawMessage = this.cache[key] as RawMessage;
|
||||||
|
if (message?.msgTime){
|
||||||
|
if ((now - (parseInt(message.msgTime) * 1000)) > expiredMilliSecond) {
|
||||||
|
delete this.cache[key]
|
||||||
|
// log("clear cache", key, message.msgTime);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, expiredMilliSecond)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async getReceivedTempUinMap(): Promise<ReceiveTempUinMap> {
|
||||||
|
try{
|
||||||
|
this.cache[this.DB_KEY_RECEIVED_TEMP_UIN_MAP] = JSON.parse(await this.db.get(this.DB_KEY_RECEIVED_TEMP_UIN_MAP));
|
||||||
|
}catch (e) {
|
||||||
|
}
|
||||||
|
return (this.cache[this.DB_KEY_RECEIVED_TEMP_UIN_MAP] || {}) as ReceiveTempUinMap;
|
||||||
|
}
|
||||||
|
public setReceivedTempUinMap(data: ReceiveTempUinMap) {
|
||||||
|
this.cache[this.DB_KEY_RECEIVED_TEMP_UIN_MAP] = data;
|
||||||
|
this.db.put(this.DB_KEY_RECEIVED_TEMP_UIN_MAP, JSON.stringify(data)).then();
|
||||||
|
}
|
||||||
private addCache(msg: RawMessage) {
|
private addCache(msg: RawMessage) {
|
||||||
const longIdKey = this.DB_KEY_PREFIX_MSG_ID + msg.msgId
|
const longIdKey = this.DB_KEY_PREFIX_MSG_ID + msg.msgId
|
||||||
const shortIdKey = this.DB_KEY_PREFIX_MSG_SHORT_ID + msg.msgShortId
|
const shortIdKey = this.DB_KEY_PREFIX_MSG_SHORT_ID + msg.msgShortId
|
||||||
const seqIdKey = this.DB_KEY_PREFIX_MSG_SEQ_ID + msg.msgSeq
|
const seqIdKey = this.DB_KEY_PREFIX_MSG_SEQ_ID + msg.msgSeq
|
||||||
this.cache[longIdKey] = this.cache[shortIdKey] = this.cache[seqIdKey] = msg
|
this.cache[longIdKey] = this.cache[shortIdKey] = msg
|
||||||
|
}
|
||||||
|
|
||||||
|
public clearCache() {
|
||||||
|
this.cache = {}
|
||||||
}
|
}
|
||||||
|
|
||||||
async getMsgByShortId(shortMsgId: number): Promise<RawMessage> {
|
async getMsgByShortId(shortMsgId: number): Promise<RawMessage> {
|
||||||
const shortMsgIdKey = this.DB_KEY_PREFIX_MSG_SHORT_ID + shortMsgId;
|
const shortMsgIdKey = this.DB_KEY_PREFIX_MSG_SHORT_ID + shortMsgId;
|
||||||
if (this.cache[shortMsgIdKey]) {
|
if (this.cache[shortMsgIdKey]) {
|
||||||
return this.cache[shortMsgIdKey]
|
// log("getMsgByShortId cache", shortMsgIdKey, this.cache[shortMsgIdKey])
|
||||||
|
return this.cache[shortMsgIdKey] as RawMessage
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const longId = await this.db.get(shortMsgIdKey);
|
||||||
|
const msg = await this.getMsgByLongId(longId)
|
||||||
|
this.addCache(msg)
|
||||||
|
return msg
|
||||||
|
} catch (e) {
|
||||||
|
log("getMsgByShortId db error", e.stack.toString())
|
||||||
}
|
}
|
||||||
const longId = await this.db.get(shortMsgIdKey);
|
|
||||||
const msg = await this.getMsgByLongId(longId)
|
|
||||||
this.addCache(msg)
|
|
||||||
return msg
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async getMsgByLongId(longId: string): Promise<RawMessage> {
|
async getMsgByLongId(longId: string): Promise<RawMessage> {
|
||||||
const longIdKey = this.DB_KEY_PREFIX_MSG_ID + longId;
|
const longIdKey = this.DB_KEY_PREFIX_MSG_ID + longId;
|
||||||
if (this.cache[longIdKey]) {
|
if (this.cache[longIdKey]) {
|
||||||
return this.cache[longIdKey]
|
return this.cache[longIdKey] as RawMessage
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const data = await this.db.get(longIdKey)
|
||||||
|
const msg = JSON.parse(data)
|
||||||
|
this.addCache(msg)
|
||||||
|
return msg
|
||||||
|
} catch (e) {
|
||||||
|
// log("getMsgByLongId db error", e.stack.toString())
|
||||||
}
|
}
|
||||||
const data = await this.db.get(longIdKey)
|
|
||||||
const msg = JSON.parse(data)
|
|
||||||
this.addCache(msg)
|
|
||||||
return msg
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async getMsgBySeqId(seqId: string): Promise<RawMessage> {
|
async getMsgBySeqId(seqId: string): Promise<RawMessage> {
|
||||||
const seqIdKey = this.DB_KEY_PREFIX_MSG_SEQ_ID + seqId;
|
const seqIdKey = this.DB_KEY_PREFIX_MSG_SEQ_ID + seqId;
|
||||||
if (this.cache[seqIdKey]) {
|
if (this.cache[seqIdKey]) {
|
||||||
return this.cache[seqIdKey]
|
return this.cache[seqIdKey] as RawMessage
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const longId = await this.db.get(seqIdKey);
|
||||||
|
const msg = await this.getMsgByLongId(longId)
|
||||||
|
this.addCache(msg)
|
||||||
|
return msg
|
||||||
|
} catch (e) {
|
||||||
|
log("getMsgBySeqId db error", e.stack.toString())
|
||||||
}
|
}
|
||||||
const longId = await this.db.get(seqIdKey);
|
|
||||||
const msg = await this.getMsgByLongId(longId)
|
|
||||||
this.addCache(msg)
|
|
||||||
return msg
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async addMsg(msg: RawMessage) {
|
async addMsg(msg: RawMessage) {
|
||||||
// 有则更新,无则添加
|
// 有则更新,无则添加
|
||||||
|
// log("addMsg", msg.msgId, msg.msgSeq, msg.msgShortId);
|
||||||
const longIdKey = this.DB_KEY_PREFIX_MSG_ID + msg.msgId
|
const longIdKey = this.DB_KEY_PREFIX_MSG_ID + msg.msgId
|
||||||
let existMsg = this.cache[longIdKey]
|
let existMsg = this.cache[longIdKey] as RawMessage
|
||||||
if (!existMsg){
|
|
||||||
try {
|
|
||||||
existMsg = await this.getMsgByLongId(msg.msgId)
|
|
||||||
}catch (e) {
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (existMsg){
|
|
||||||
this.updateMsg(msg).then()
|
|
||||||
return existMsg.msgShortId
|
|
||||||
}
|
|
||||||
|
|
||||||
const shortMsgId = await this.genMsgShortId();
|
|
||||||
const shortIdKey = this.DB_KEY_PREFIX_MSG_SHORT_ID + shortMsgId;
|
|
||||||
const seqIdKey = this.DB_KEY_PREFIX_MSG_SEQ_ID + msg.msgSeq;
|
|
||||||
await this.db.put(shortIdKey, msg.msgId);
|
|
||||||
msg.msgShortId = shortMsgId;
|
|
||||||
await this.db.put(longIdKey, JSON.stringify(msg));
|
|
||||||
await this.db.put(seqIdKey, msg.msgId);
|
|
||||||
this.cache[seqIdKey] = this.cache[shortIdKey] = this.cache[longIdKey] = msg;
|
|
||||||
return shortMsgId
|
|
||||||
}
|
|
||||||
|
|
||||||
async updateMsg(msg: RawMessage) {
|
|
||||||
const longIdKey = this.DB_KEY_PREFIX_MSG_ID + msg.msgId
|
|
||||||
let existMsg = this.cache[longIdKey]
|
|
||||||
if (!existMsg) {
|
if (!existMsg) {
|
||||||
try {
|
try {
|
||||||
existMsg = await this.getMsgByLongId(msg.msgId)
|
existMsg = await this.getMsgByLongId(msg.msgId)
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return
|
// log("addMsg getMsgByLongId error", e.stack.toString())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (existMsg) {
|
||||||
|
// log("消息已存在", existMsg.msgSeq, existMsg.msgShortId, existMsg.msgId)
|
||||||
|
this.updateMsg(msg).then()
|
||||||
|
return existMsg.msgShortId
|
||||||
|
}
|
||||||
|
this.addCache(msg);
|
||||||
|
|
||||||
|
const shortMsgId = await this.genMsgShortId();
|
||||||
|
const shortIdKey = this.DB_KEY_PREFIX_MSG_SHORT_ID + shortMsgId;
|
||||||
|
const seqIdKey = this.DB_KEY_PREFIX_MSG_SEQ_ID + msg.msgSeq;
|
||||||
|
msg.msgShortId = shortMsgId;
|
||||||
|
// log("新增消息记录", msg.msgId)
|
||||||
|
this.db.put(shortIdKey, msg.msgId).then().catch();
|
||||||
|
this.db.put(longIdKey, JSON.stringify(msg)).then().catch();
|
||||||
|
try {
|
||||||
|
await this.db.get(seqIdKey)
|
||||||
|
} catch (e) {
|
||||||
|
// log("新的seqId", seqIdKey)
|
||||||
|
this.db.put(seqIdKey, msg.msgId).then().catch();
|
||||||
|
}
|
||||||
|
if (!this.cache[seqIdKey]) {
|
||||||
|
this.cache[seqIdKey] = msg;
|
||||||
|
}
|
||||||
|
return shortMsgId
|
||||||
|
// log(`消息入库 ${seqIdKey}: ${msg.msgId}, ${shortMsgId}: ${msg.msgId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateMsg(msg: RawMessage) {
|
||||||
|
const longIdKey = this.DB_KEY_PREFIX_MSG_ID + msg.msgId
|
||||||
|
let existMsg = this.cache[longIdKey] as RawMessage
|
||||||
|
if (!existMsg) {
|
||||||
|
try {
|
||||||
|
existMsg = await this.getMsgByLongId(msg.msgId)
|
||||||
|
} catch (e) {
|
||||||
|
existMsg = msg
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Object.assign(existMsg, msg)
|
Object.assign(existMsg, msg)
|
||||||
await this.db.put(longIdKey, JSON.stringify(existMsg));
|
this.db.put(longIdKey, JSON.stringify(existMsg)).then().catch();
|
||||||
|
const shortIdKey = this.DB_KEY_PREFIX_MSG_SHORT_ID + existMsg.msgShortId;
|
||||||
|
const seqIdKey = this.DB_KEY_PREFIX_MSG_SEQ_ID + msg.msgSeq;
|
||||||
|
if (!this.cache[seqIdKey]) {
|
||||||
|
this.cache[seqIdKey] = existMsg;
|
||||||
|
}
|
||||||
|
this.db.put(shortIdKey, msg.msgId).then().catch();
|
||||||
|
try {
|
||||||
|
await this.db.get(seqIdKey)
|
||||||
|
} catch (e) {
|
||||||
|
this.db.put(seqIdKey, msg.msgId).then().catch();
|
||||||
|
// log("更新seqId error", e.stack, seqIdKey);
|
||||||
|
}
|
||||||
|
// log("更新消息", existMsg.msgSeq, existMsg.msgShortId, existMsg.msgId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private async genMsgShortId(): Promise<number> {
|
private async genMsgShortId(): Promise<number> {
|
||||||
let shortId = -2147483640
|
|
||||||
const key = "msg_current_short_id";
|
const key = "msg_current_short_id";
|
||||||
try {
|
if (this.currentShortId === undefined) {
|
||||||
let id: string = await this.db.get(key);
|
try {
|
||||||
shortId = parseInt(id);
|
let id: string = await this.db.get(key);
|
||||||
} catch (e) {
|
this.currentShortId = parseInt(id);
|
||||||
|
} catch (e) {
|
||||||
|
this.currentShortId = -2147483640
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.currentShortId++;
|
||||||
|
this.db.put(key, this.currentShortId.toString()).then().catch();
|
||||||
|
return this.currentShortId;
|
||||||
|
}
|
||||||
|
|
||||||
|
async addFileCache(fileName: string, data: FileCache) {
|
||||||
|
const key = this.DB_KEY_PREFIX_FILE + fileName;
|
||||||
|
if (this.cache[key]) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
let cacheDBData = {...data}
|
||||||
|
delete cacheDBData['downloadFunc']
|
||||||
|
this.cache[fileName] = data;
|
||||||
|
try {
|
||||||
|
await this.db.put(key, JSON.stringify(cacheDBData));
|
||||||
|
} catch (e) {
|
||||||
|
log("addFileCache db error", e.stack.toString())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async getFileCache(fileName: string): Promise<FileCache | undefined> {
|
||||||
|
const key = this.DB_KEY_PREFIX_FILE + fileName;
|
||||||
|
if (this.cache[key]) {
|
||||||
|
return this.cache[key] as FileCache
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
let data = await this.db.get(key);
|
||||||
|
return JSON.parse(data);
|
||||||
|
} catch (e) {
|
||||||
|
// log("getFileCache db error", e.stack.toString())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async addGroupNotify(notify: GroupNotify) {
|
||||||
|
const key = this.DB_KEY_PREFIX_GROUP_NOTIFY + notify.seq;
|
||||||
|
let existNotify = this.cache[key] as GroupNotify
|
||||||
|
if (existNotify) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
this.cache[key] = notify;
|
||||||
|
this.db.put(key, JSON.stringify(notify)).then().catch();
|
||||||
|
}
|
||||||
|
|
||||||
|
async getGroupNotify(seq: string): Promise<GroupNotify | undefined> {
|
||||||
|
const key = this.DB_KEY_PREFIX_GROUP_NOTIFY + seq;
|
||||||
|
if (this.cache[key]) {
|
||||||
|
return this.cache[key] as GroupNotify
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
let data = await this.db.get(key);
|
||||||
|
return JSON.parse(data);
|
||||||
|
} catch (e) {
|
||||||
|
// log("getGroupNotify db error", e.stack.toString())
|
||||||
}
|
}
|
||||||
shortId++;
|
|
||||||
await this.db.put(key, shortId.toString());
|
|
||||||
return shortId;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -1,6 +1,7 @@
|
|||||||
import express, {Express, json, Request, Response} from "express";
|
import express, {Express, json, Request, Response} from "express";
|
||||||
import {getConfigUtil, log} from "../utils";
|
|
||||||
import http from "http";
|
import http from "http";
|
||||||
|
import {log} from "../utils/log";
|
||||||
|
import {getConfigUtil} from "../config";
|
||||||
|
|
||||||
type RegisterHandler = (res: Response, payload: any) => Promise<any>
|
type RegisterHandler = (res: Response, payload: any) => Promise<any>
|
||||||
|
|
||||||
@@ -11,8 +12,21 @@ export abstract class HttpServerBase {
|
|||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
this.expressAPP = express();
|
this.expressAPP = express();
|
||||||
this.expressAPP.use(express.urlencoded({extended: true, limit: "500mb"}));
|
this.expressAPP.use(express.urlencoded({extended: true, limit: "5000mb"}));
|
||||||
this.expressAPP.use(json({limit: "500mb"}));
|
this.expressAPP.use((req, res, next) => {
|
||||||
|
// 兼容处理没有带content-type的请求
|
||||||
|
// log("req.headers['content-type']", req.headers['content-type'])
|
||||||
|
req.headers['content-type'] = 'application/json';
|
||||||
|
const originalJson = express.json({limit: "5000mb"});
|
||||||
|
// 调用原始的express.json()处理器
|
||||||
|
originalJson(req, res, (err) => {
|
||||||
|
if (err) {
|
||||||
|
log("Error parsing JSON:", err);
|
||||||
|
return res.status(400).send("Invalid JSON");
|
||||||
|
}
|
||||||
|
next();
|
||||||
|
});
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
authorize(req: Request, res: Response, next: () => void) {
|
authorize(req: Request, res: Response, next: () => void) {
|
||||||
|
@@ -1,7 +1,8 @@
|
|||||||
import {WebSocket, WebSocketServer} from "ws";
|
import {WebSocket, WebSocketServer} from "ws";
|
||||||
import {getConfigUtil, log} from "../utils";
|
|
||||||
import urlParse from "url";
|
import urlParse from "url";
|
||||||
import {IncomingMessage} from "node:http";
|
import {IncomingMessage} from "node:http";
|
||||||
|
import {log} from "../utils/log";
|
||||||
|
import {getConfigUtil} from "../config";
|
||||||
|
|
||||||
class WebsocketClientBase {
|
class WebsocketClientBase {
|
||||||
private wsClient: WebSocket
|
private wsClient: WebSocket
|
||||||
|
@@ -9,7 +9,10 @@ export interface OB11Config {
|
|||||||
enableWsReverse?: boolean
|
enableWsReverse?: boolean
|
||||||
messagePostFormat?: 'array' | 'string'
|
messagePostFormat?: 'array' | 'string'
|
||||||
}
|
}
|
||||||
|
export interface CheckVersion {
|
||||||
|
result: boolean,
|
||||||
|
version: string
|
||||||
|
}
|
||||||
export interface Config {
|
export interface Config {
|
||||||
ob11: OB11Config
|
ob11: OB11Config
|
||||||
token?: string
|
token?: string
|
||||||
@@ -21,6 +24,7 @@ export interface Config {
|
|||||||
autoDeleteFile?: boolean
|
autoDeleteFile?: boolean
|
||||||
autoDeleteFileSecond?: number
|
autoDeleteFileSecond?: number
|
||||||
ffmpeg?: string // ffmpeg路径
|
ffmpeg?: string // ffmpeg路径
|
||||||
|
enablePoke?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface LLOneBotError {
|
export interface LLOneBotError {
|
||||||
|
@@ -1,64 +1,13 @@
|
|||||||
import * as path from "node:path";
|
import fs from "fs";
|
||||||
import {selfInfo} from "./data";
|
import crypto from "crypto";
|
||||||
import {ConfigUtil} from "./config";
|
import ffmpeg from "fluent-ffmpeg";
|
||||||
import util from "util";
|
import util from "util";
|
||||||
import {encode, getDuration, isWav} from "silk-wasm";
|
import {encode, getDuration, isWav} from "silk-wasm";
|
||||||
import fs from 'fs';
|
import path from "node:path";
|
||||||
import {v4 as uuidv4} from "uuid";
|
import {v4 as uuidv4} from "uuid";
|
||||||
import ffmpeg from "fluent-ffmpeg"
|
import {DATA_DIR} from "./index";
|
||||||
|
import {log} from "./log";
|
||||||
export const DATA_DIR = global.LiteLoader.plugins["LLOneBot"].path.data;
|
import {getConfigUtil} from "../config";
|
||||||
|
|
||||||
export function getConfigUtil() {
|
|
||||||
const configFilePath = path.join(DATA_DIR, `config_${selfInfo.uin}.json`)
|
|
||||||
return new ConfigUtil(configFilePath)
|
|
||||||
}
|
|
||||||
|
|
||||||
function truncateString(obj: any, maxLength = 500) {
|
|
||||||
if (obj !== null && typeof obj === 'object') {
|
|
||||||
Object.keys(obj).forEach(key => {
|
|
||||||
if (typeof obj[key] === 'string') {
|
|
||||||
// 如果是字符串且超过指定长度,则截断
|
|
||||||
if (obj[key].length > maxLength) {
|
|
||||||
obj[key] = obj[key].substring(0, maxLength) + '...';
|
|
||||||
}
|
|
||||||
} else if (typeof obj[key] === 'object') {
|
|
||||||
// 如果是对象或数组,则递归调用
|
|
||||||
truncateString(obj[key], maxLength);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return obj;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function log(...msg: any[]) {
|
|
||||||
if (!getConfigUtil().getConfig().log) {
|
|
||||||
return //console.log(...msg);
|
|
||||||
}
|
|
||||||
let currentDateTime = new Date().toLocaleString();
|
|
||||||
const date = new Date();
|
|
||||||
const year = date.getFullYear();
|
|
||||||
const month = date.getMonth() + 1;
|
|
||||||
const day = date.getDate();
|
|
||||||
const currentDate = `${year}-${month}-${day}`;
|
|
||||||
const userInfo = selfInfo.uin ? `${selfInfo.nick}(${selfInfo.uin})` : ""
|
|
||||||
let logMsg = "";
|
|
||||||
for (let msgItem of msg) {
|
|
||||||
// 判断是否是对象
|
|
||||||
if (typeof msgItem === "object") {
|
|
||||||
let obj = JSON.parse(JSON.stringify(msgItem));
|
|
||||||
logMsg += JSON.stringify(truncateString(obj)) + " ";
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
logMsg += msgItem + " ";
|
|
||||||
}
|
|
||||||
logMsg = `${currentDateTime} ${userInfo}: ${logMsg}\n\n`
|
|
||||||
// sendLog(...msg);
|
|
||||||
// console.log(msg)
|
|
||||||
fs.appendFile(path.join(DATA_DIR, `llonebot-${currentDate}.log`), logMsg, (err: any) => {
|
|
||||||
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
export function isGIF(path: string) {
|
export function isGIF(path: string) {
|
||||||
const buffer = Buffer.alloc(4);
|
const buffer = Buffer.alloc(4);
|
||||||
@@ -68,11 +17,6 @@ export function isGIF(path: string) {
|
|||||||
return buffer.toString() === 'GIF8'
|
return buffer.toString() === 'GIF8'
|
||||||
}
|
}
|
||||||
|
|
||||||
export function sleep(ms: number): Promise<void> {
|
|
||||||
return new Promise(resolve => setTimeout(resolve, ms));
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// 定义一个异步函数来检查文件是否存在
|
// 定义一个异步函数来检查文件是否存在
|
||||||
export function checkFileReceived(path: string, timeout: number = 3000): Promise<void> {
|
export function checkFileReceived(path: string, timeout: number = 3000): Promise<void> {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
@@ -118,25 +62,6 @@ export async function file2base64(path: string) {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// 在保证老对象已有的属性不变化的情况下将新对象的属性复制到老对象
|
|
||||||
export function mergeNewProperties(newObj: any, oldObj: any) {
|
|
||||||
Object.keys(newObj).forEach(key => {
|
|
||||||
// 如果老对象不存在当前属性,则直接复制
|
|
||||||
if (!oldObj.hasOwnProperty(key)) {
|
|
||||||
oldObj[key] = newObj[key];
|
|
||||||
} else {
|
|
||||||
// 如果老对象和新对象的当前属性都是对象,则递归合并
|
|
||||||
if (typeof oldObj[key] === 'object' && typeof newObj[key] === 'object') {
|
|
||||||
mergeNewProperties(newObj[key], oldObj[key]);
|
|
||||||
} else if (typeof oldObj[key] === 'object' || typeof newObj[key] === 'object') {
|
|
||||||
// 属性冲突,有一方不是对象,直接覆盖
|
|
||||||
oldObj[key] = newObj[key];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function checkFfmpeg(newPath: string = null): Promise<boolean> {
|
export function checkFfmpeg(newPath: string = null): Promise<boolean> {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
if (newPath) {
|
if (newPath) {
|
||||||
@@ -205,7 +130,7 @@ export async function encodeSilk(filePath: string) {
|
|||||||
if (ffmpegPath) {
|
if (ffmpegPath) {
|
||||||
ffmpeg.setFfmpegPath(ffmpegPath);
|
ffmpeg.setFfmpegPath(ffmpegPath);
|
||||||
}
|
}
|
||||||
ffmpeg(filePath).toFormat("wav").on('end', function () {
|
ffmpeg(filePath).toFormat("wav").audioChannels(2).on('end', function () {
|
||||||
log('wav转换完成');
|
log('wav转换完成');
|
||||||
})
|
})
|
||||||
.on('error', function (err) {
|
.on('error', function (err) {
|
||||||
@@ -220,6 +145,7 @@ export async function encodeSilk(filePath: string) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
// const sampleRate = await getAudioSampleRate(filePath) || 0;
|
// const sampleRate = await getAudioSampleRate(filePath) || 0;
|
||||||
|
// log("音频采样率", sampleRate)
|
||||||
const pcm = fs.readFileSync(filePath);
|
const pcm = fs.readFileSync(filePath);
|
||||||
const silk = await encode(pcm, 0);
|
const silk = await encode(pcm, 0);
|
||||||
fs.writeFileSync(pttPath, silk.data);
|
fs.writeFileSync(pttPath, silk.data);
|
||||||
@@ -234,9 +160,9 @@ export async function encodeSilk(filePath: string) {
|
|||||||
} else {
|
} else {
|
||||||
const pcm = fs.readFileSync(filePath);
|
const pcm = fs.readFileSync(filePath);
|
||||||
let duration = 0;
|
let duration = 0;
|
||||||
try{
|
try {
|
||||||
duration = getDuration(pcm);
|
duration = getDuration(pcm);
|
||||||
}catch (e) {
|
} catch (e) {
|
||||||
log("获取语音文件时长失败", filePath, e.stack)
|
log("获取语音文件时长失败", filePath, e.stack)
|
||||||
duration = fs.statSync(filePath).size / 1024 / 3 // 每3kb大约1s
|
duration = fs.statSync(filePath).size / 1024 / 3 // 每3kb大约1s
|
||||||
duration = Math.floor(duration)
|
duration = Math.floor(duration)
|
||||||
@@ -256,6 +182,82 @@ export async function encodeSilk(filePath: string) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function isNull(value: any) {
|
export async function getVideoInfo(filePath: string) {
|
||||||
return value === undefined || value === null;
|
const size = fs.statSync(filePath).size;
|
||||||
|
return new Promise<{
|
||||||
|
width: number,
|
||||||
|
height: number,
|
||||||
|
time: number,
|
||||||
|
format: string,
|
||||||
|
size: number,
|
||||||
|
filePath: string
|
||||||
|
}>((resolve, reject) => {
|
||||||
|
ffmpeg(filePath).ffprobe((err, metadata) => {
|
||||||
|
if (err) {
|
||||||
|
reject(err);
|
||||||
|
} else {
|
||||||
|
const videoStream = metadata.streams.find(s => s.codec_type === 'video');
|
||||||
|
if (videoStream) {
|
||||||
|
console.log(`视频尺寸: ${videoStream.width}x${videoStream.height}`);
|
||||||
|
} else {
|
||||||
|
console.log('未找到视频流信息。');
|
||||||
|
}
|
||||||
|
resolve({
|
||||||
|
width: videoStream.width, height: videoStream.height,
|
||||||
|
time: parseInt(videoStream.duration),
|
||||||
|
format: metadata.format.format_name,
|
||||||
|
size,
|
||||||
|
filePath
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function encodeMp4(filePath: string) {
|
||||||
|
let videoInfo = await getVideoInfo(filePath);
|
||||||
|
log("视频信息", videoInfo)
|
||||||
|
if (videoInfo.format.indexOf("mp4") === -1) {
|
||||||
|
log("视频需要转换为MP4格式", filePath)
|
||||||
|
// 转成mp4
|
||||||
|
const newPath: string = await new Promise<string>((resolve, reject) => {
|
||||||
|
const newPath = filePath + ".mp4"
|
||||||
|
ffmpeg(filePath)
|
||||||
|
.toFormat('mp4')
|
||||||
|
.on('error', (err) => {
|
||||||
|
reject(`转换视频格式失败: ${err.message}`);
|
||||||
|
})
|
||||||
|
.on('end', () => {
|
||||||
|
log('视频转换为MP4格式完成');
|
||||||
|
resolve(newPath); // 返回转换后的文件路径
|
||||||
|
})
|
||||||
|
.save(newPath);
|
||||||
|
});
|
||||||
|
return await getVideoInfo(newPath)
|
||||||
|
}
|
||||||
|
return videoInfo
|
||||||
|
}
|
||||||
|
|
||||||
|
export function calculateFileMD5(filePath: string): Promise<string> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
// 创建一个流式读取器
|
||||||
|
const stream = fs.createReadStream(filePath);
|
||||||
|
const hash = crypto.createHash('md5');
|
||||||
|
|
||||||
|
stream.on('data', (data: Buffer) => {
|
||||||
|
// 当读取到数据时,更新哈希对象的状态
|
||||||
|
hash.update(data);
|
||||||
|
});
|
||||||
|
|
||||||
|
stream.on('end', () => {
|
||||||
|
// 文件读取完成,计算哈希
|
||||||
|
const md5 = hash.digest('hex');
|
||||||
|
resolve(md5);
|
||||||
|
});
|
||||||
|
|
||||||
|
stream.on('error', (err: Error) => {
|
||||||
|
// 处理可能的读取错误
|
||||||
|
reject(err);
|
||||||
|
});
|
||||||
|
});
|
||||||
}
|
}
|
46
src/common/utils/helper.ts
Normal file
46
src/common/utils/helper.ts
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
export function truncateString(obj: any, maxLength = 500) {
|
||||||
|
if (obj !== null && typeof obj === 'object') {
|
||||||
|
Object.keys(obj).forEach(key => {
|
||||||
|
if (typeof obj[key] === 'string') {
|
||||||
|
// 如果是字符串且超过指定长度,则截断
|
||||||
|
if (obj[key].length > maxLength) {
|
||||||
|
obj[key] = obj[key].substring(0, maxLength) + '...';
|
||||||
|
}
|
||||||
|
} else if (typeof obj[key] === 'object') {
|
||||||
|
// 如果是对象或数组,则递归调用
|
||||||
|
truncateString(obj[key], maxLength);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return obj;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isNumeric(str: string) {
|
||||||
|
return /^\d+$/.test(str);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sleep(ms: number): Promise<void> {
|
||||||
|
return new Promise(resolve => setTimeout(resolve, ms));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 在保证老对象已有的属性不变化的情况下将新对象的属性复制到老对象
|
||||||
|
export function mergeNewProperties(newObj: any, oldObj: any) {
|
||||||
|
Object.keys(newObj).forEach(key => {
|
||||||
|
// 如果老对象不存在当前属性,则直接复制
|
||||||
|
if (!oldObj.hasOwnProperty(key)) {
|
||||||
|
oldObj[key] = newObj[key];
|
||||||
|
} else {
|
||||||
|
// 如果老对象和新对象的当前属性都是对象,则递归合并
|
||||||
|
if (typeof oldObj[key] === 'object' && typeof newObj[key] === 'object') {
|
||||||
|
mergeNewProperties(newObj[key], oldObj[key]);
|
||||||
|
} else if (typeof oldObj[key] === 'object' || typeof newObj[key] === 'object') {
|
||||||
|
// 属性冲突,有一方不是对象,直接覆盖
|
||||||
|
oldObj[key] = newObj[key];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isNull(value: any) {
|
||||||
|
return value === undefined || value === null;
|
||||||
|
}
|
10
src/common/utils/index.ts
Normal file
10
src/common/utils/index.ts
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
export * from './file'
|
||||||
|
export * from './helper'
|
||||||
|
export * from './log'
|
||||||
|
export * from './qqlevel'
|
||||||
|
export * from './qqpkg'
|
||||||
|
export * from './update'
|
||||||
|
export const DATA_DIR = global.LiteLoader.plugins["LLOneBot"].path.data;
|
||||||
|
|
||||||
|
|
||||||
|
|
34
src/common/utils/log.ts
Normal file
34
src/common/utils/log.ts
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
import {selfInfo} from "../data";
|
||||||
|
import fs from "fs";
|
||||||
|
import path from "node:path";
|
||||||
|
import {DATA_DIR, truncateString} from "./index";
|
||||||
|
import {getConfigUtil} from "../config";
|
||||||
|
|
||||||
|
export function log(...msg: any[]) {
|
||||||
|
if (!getConfigUtil().getConfig().log) {
|
||||||
|
return //console.log(...msg);
|
||||||
|
}
|
||||||
|
let currentDateTime = new Date().toLocaleString();
|
||||||
|
const date = new Date();
|
||||||
|
const year = date.getFullYear();
|
||||||
|
const month = date.getMonth() + 1;
|
||||||
|
const day = date.getDate();
|
||||||
|
const currentDate = `${year}-${month}-${day}`;
|
||||||
|
const userInfo = selfInfo.uin ? `${selfInfo.nick}(${selfInfo.uin})` : ""
|
||||||
|
let logMsg = "";
|
||||||
|
for (let msgItem of msg) {
|
||||||
|
// 判断是否是对象
|
||||||
|
if (typeof msgItem === "object") {
|
||||||
|
let obj = JSON.parse(JSON.stringify(msgItem));
|
||||||
|
logMsg += JSON.stringify(truncateString(obj)) + " ";
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
logMsg += msgItem + " ";
|
||||||
|
}
|
||||||
|
logMsg = `${currentDateTime} ${userInfo}: ${logMsg}\n\n`
|
||||||
|
// sendLog(...msg);
|
||||||
|
// console.log(msg)
|
||||||
|
fs.appendFile(path.join(DATA_DIR, `llonebot-${currentDate}.log`), logMsg, (err: any) => {
|
||||||
|
|
||||||
|
})
|
||||||
|
}
|
7
src/common/utils/qqlevel.ts
Normal file
7
src/common/utils/qqlevel.ts
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
// QQ等级换算
|
||||||
|
import {QQLevel} from "../../ntqqapi/types";
|
||||||
|
|
||||||
|
export function calcQQLevel(level: QQLevel) {
|
||||||
|
const {crownNum, sunNum, moonNum, starNum} = level
|
||||||
|
return crownNum * 64 + sunNum * 16 + moonNum * 4 + starNum
|
||||||
|
}
|
10
src/common/utils/qqpkg.ts
Normal file
10
src/common/utils/qqpkg.ts
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import path from "path";
|
||||||
|
|
||||||
|
type QQPkgInfo = {
|
||||||
|
version: string;
|
||||||
|
buildVersion: string;
|
||||||
|
platform: string;
|
||||||
|
eleArch: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const qqPkgInfo: QQPkgInfo = require(path.join(process.resourcesPath, "app/package.json"))
|
62
src/common/utils/update.ts
Normal file
62
src/common/utils/update.ts
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
import {version} from "../../version";
|
||||||
|
import https from "node:https";
|
||||||
|
|
||||||
|
export async function checkVersion() {
|
||||||
|
const latestVersionText = await getRemoteVersion();
|
||||||
|
const latestVersion = latestVersionText.split(".");
|
||||||
|
const currentVersion = version.split(".");
|
||||||
|
for (let k in [0, 1, 2]) {
|
||||||
|
if (latestVersion[k] > currentVersion[k]) {
|
||||||
|
return { result: false, version: latestVersionText };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { result: true, version: version };
|
||||||
|
}
|
||||||
|
export async function updateLLOneBot() {
|
||||||
|
let mirrorGithubList = ["https://mirror.ghproxy.com"];
|
||||||
|
const latestVersion = await getRemoteVersion();
|
||||||
|
if (latestVersion && latestVersion != "") {
|
||||||
|
const downloadUrl = "https://github.com/LLOneBot/LLOneBot/releases/download/v" + latestVersion + "/LLOneBot.zip";
|
||||||
|
const realUrl = mirrorGithubList[0] + downloadUrl;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
export async function getRemoteVersion() {
|
||||||
|
let mirrorGithubList = ["https://521github.com"];
|
||||||
|
let Version = "";
|
||||||
|
for (let i = 0; i < mirrorGithubList.length; i++) {
|
||||||
|
let mirrorGithub = mirrorGithubList[i];
|
||||||
|
let tVersion = await getRemoteVersionByMirror(mirrorGithub);
|
||||||
|
if (tVersion && tVersion != "") {
|
||||||
|
Version = tVersion;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Version;
|
||||||
|
}
|
||||||
|
export async function getRemoteVersionByMirror(mirrorGithub: string) {
|
||||||
|
let releasePage = "error";
|
||||||
|
let reqPromise = async function (): Promise<string> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
https.get(mirrorGithub + "/LLOneBot/LLOneBot/releases", res => {
|
||||||
|
let list = [];
|
||||||
|
res.on('data', chunk => {
|
||||||
|
list.push(chunk);
|
||||||
|
});
|
||||||
|
res.on('end', () => {
|
||||||
|
resolve(Buffer.concat(list).toString());
|
||||||
|
});
|
||||||
|
}).on('error', err => {
|
||||||
|
reject();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
releasePage = await reqPromise();
|
||||||
|
if (releasePage === "error") return "";
|
||||||
|
return releasePage.match(new RegExp('(?<=(tag/v)).*?(?=("))'))[0];
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
return "";
|
||||||
|
|
||||||
|
}
|
197
src/main/main.ts
197
src/main/main.ts
@@ -7,41 +7,44 @@ import {
|
|||||||
CHANNEL_ERROR,
|
CHANNEL_ERROR,
|
||||||
CHANNEL_GET_CONFIG,
|
CHANNEL_GET_CONFIG,
|
||||||
CHANNEL_LOG,
|
CHANNEL_LOG,
|
||||||
|
CHANNEL_CHECKVERSION,
|
||||||
CHANNEL_SELECT_FILE,
|
CHANNEL_SELECT_FILE,
|
||||||
CHANNEL_SET_CONFIG,
|
CHANNEL_SET_CONFIG,
|
||||||
|
CHANNEL_UPDATE,
|
||||||
} from "../common/channels";
|
} from "../common/channels";
|
||||||
import {ob11WebsocketServer} from "../onebot11/server/ws/WebsocketServer";
|
import {ob11WebsocketServer} from "../onebot11/server/ws/WebsocketServer";
|
||||||
import {checkFfmpeg, DATA_DIR, getConfigUtil, log} from "../common/utils";
|
import {DATA_DIR} from "../common/utils";
|
||||||
import {
|
import {
|
||||||
friendRequests,
|
friendRequests,
|
||||||
|
getFriend,
|
||||||
getGroup,
|
getGroup,
|
||||||
getGroupMember,
|
getGroupMember,
|
||||||
groupNotifies,
|
llonebotError,
|
||||||
llonebotError, refreshGroupMembers,
|
refreshGroupMembers,
|
||||||
selfInfo
|
selfInfo, uidMaps
|
||||||
} from "../common/data";
|
} from "../common/data";
|
||||||
import {hookNTQQApiCall, hookNTQQApiReceive, ReceiveCmd, registerReceiveHook} from "../ntqqapi/hook";
|
import {hookNTQQApiCall, hookNTQQApiReceive, ReceiveCmdS, registerReceiveHook} from "../ntqqapi/hook";
|
||||||
import {OB11Constructor} from "../onebot11/constructor";
|
import {OB11Constructor} from "../onebot11/constructor";
|
||||||
import {NTQQApi} from "../ntqqapi/ntcall";
|
import {ChatType, FriendRequestNotify, GroupNotifies, GroupNotifyTypes, RawMessage} from "../ntqqapi/types";
|
||||||
import {
|
|
||||||
ChatType,
|
|
||||||
FriendRequestNotify,
|
|
||||||
GroupMember,
|
|
||||||
GroupNotifies,
|
|
||||||
GroupNotifyTypes,
|
|
||||||
RawMessage
|
|
||||||
} from "../ntqqapi/types";
|
|
||||||
import {ob11HTTPServer} from "../onebot11/server/http";
|
import {ob11HTTPServer} from "../onebot11/server/http";
|
||||||
import {OB11FriendRecallNoticeEvent} from "../onebot11/event/notice/OB11FriendRecallNoticeEvent";
|
import {OB11FriendRecallNoticeEvent} from "../onebot11/event/notice/OB11FriendRecallNoticeEvent";
|
||||||
import {OB11GroupRecallNoticeEvent} from "../onebot11/event/notice/OB11GroupRecallNoticeEvent";
|
import {OB11GroupRecallNoticeEvent} from "../onebot11/event/notice/OB11GroupRecallNoticeEvent";
|
||||||
import {postOB11Event} from "../onebot11/server/postOB11Event";
|
import {postOB11Event} from "../onebot11/server/postOB11Event";
|
||||||
import {ob11ReverseWebsockets} from "../onebot11/server/ws/ReverseWebsocket";
|
import {ob11ReverseWebsockets} from "../onebot11/server/ws/ReverseWebsocket";
|
||||||
import {OB11GroupAdminNoticeEvent} from "../onebot11/event/notice/OB11GroupAdminNoticeEvent";
|
import {OB11GroupAdminNoticeEvent} from "../onebot11/event/notice/OB11GroupAdminNoticeEvent";
|
||||||
import {OB11GroupDecreaseEvent} from "../onebot11/event/notice/OB11GroupDecreaseEvent";
|
|
||||||
import {OB11GroupRequestEvent} from "../onebot11/event/request/OB11GroupRequest";
|
import {OB11GroupRequestEvent} from "../onebot11/event/request/OB11GroupRequest";
|
||||||
import {OB11FriendRequestEvent} from "../onebot11/event/request/OB11FriendRequest";
|
import {OB11FriendRequestEvent} from "../onebot11/event/request/OB11FriendRequest";
|
||||||
import * as path from "node:path";
|
import * as path from "node:path";
|
||||||
import {dbUtil} from "../common/db";
|
import {dbUtil} from "../common/db";
|
||||||
|
import {setConfig} from "./setConfig";
|
||||||
|
import {NTQQUserApi} from "../ntqqapi/api/user";
|
||||||
|
import {NTQQGroupApi} from "../ntqqapi/api/group";
|
||||||
|
import {registerPokeHandler} from "../ntqqapi/external/ccpoke";
|
||||||
|
import {OB11FriendPokeEvent, OB11GroupPokeEvent} from "../onebot11/event/notice/OB11PokeEvent";
|
||||||
|
import {checkVersion, updateLLOneBot} from "../common/utils/update";
|
||||||
|
import {checkFfmpeg} from "../common/utils/file";
|
||||||
|
import {log} from "../common/utils/log";
|
||||||
|
import {getConfigUtil} from "../common/config";
|
||||||
|
|
||||||
|
|
||||||
let running = false;
|
let running = false;
|
||||||
@@ -50,7 +53,12 @@ let running = false;
|
|||||||
// 加载插件时触发
|
// 加载插件时触发
|
||||||
function onLoad() {
|
function onLoad() {
|
||||||
log("llonebot main onLoad");
|
log("llonebot main onLoad");
|
||||||
|
ipcMain.handle(CHANNEL_CHECKVERSION, async (event, arg) => {
|
||||||
|
return checkVersion();
|
||||||
|
});
|
||||||
|
ipcMain.handle(CHANNEL_UPDATE, async (event, arg) => {
|
||||||
|
return updateLLOneBot();
|
||||||
|
});
|
||||||
ipcMain.handle(CHANNEL_SELECT_FILE, async (event, arg) => {
|
ipcMain.handle(CHANNEL_SELECT_FILE, async (event, arg) => {
|
||||||
const selectPath = new Promise<string>((resolve, reject) => {
|
const selectPath = new Promise<string>((resolve, reject) => {
|
||||||
dialog
|
dialog
|
||||||
@@ -91,61 +99,8 @@ function onLoad() {
|
|||||||
const config = getConfigUtil().getConfig()
|
const config = getConfigUtil().getConfig()
|
||||||
return config;
|
return config;
|
||||||
})
|
})
|
||||||
ipcMain.on(CHANNEL_SET_CONFIG, (event, arg: Config) => {
|
ipcMain.on(CHANNEL_SET_CONFIG, (event, config: Config) => {
|
||||||
let oldConfig = getConfigUtil().getConfig();
|
setConfig(config).then();
|
||||||
getConfigUtil().setConfig(arg)
|
|
||||||
if (arg.ob11.httpPort != oldConfig.ob11.httpPort && arg.ob11.enableHttp) {
|
|
||||||
ob11HTTPServer.restart(arg.ob11.httpPort);
|
|
||||||
}
|
|
||||||
// 判断是否启用或关闭HTTP服务
|
|
||||||
if (!arg.ob11.enableHttp) {
|
|
||||||
ob11HTTPServer.stop();
|
|
||||||
} else {
|
|
||||||
ob11HTTPServer.start(arg.ob11.httpPort);
|
|
||||||
}
|
|
||||||
// 正向ws端口变化,重启服务
|
|
||||||
if (arg.ob11.wsPort != oldConfig.ob11.wsPort) {
|
|
||||||
ob11WebsocketServer.restart(arg.ob11.wsPort);
|
|
||||||
}
|
|
||||||
// 判断是否启用或关闭正向ws
|
|
||||||
if (arg.ob11.enableWs != oldConfig.ob11.enableWs) {
|
|
||||||
if (arg.ob11.enableWs) {
|
|
||||||
ob11WebsocketServer.start(arg.ob11.wsPort);
|
|
||||||
} else {
|
|
||||||
ob11WebsocketServer.stop();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// 判断是否启用或关闭反向ws
|
|
||||||
if (arg.ob11.enableWsReverse != oldConfig.ob11.enableWsReverse) {
|
|
||||||
if (arg.ob11.enableWsReverse) {
|
|
||||||
ob11ReverseWebsockets.start();
|
|
||||||
} else {
|
|
||||||
ob11ReverseWebsockets.stop();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (arg.ob11.enableWsReverse) {
|
|
||||||
// 判断反向ws地址有变化
|
|
||||||
if (arg.ob11.wsHosts.length != oldConfig.ob11.wsHosts.length) {
|
|
||||||
ob11ReverseWebsockets.restart();
|
|
||||||
} else {
|
|
||||||
for (const newHost of arg.ob11.wsHosts) {
|
|
||||||
if (!oldConfig.ob11.wsHosts.includes(newHost)) {
|
|
||||||
ob11ReverseWebsockets.restart();
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 检查ffmpeg
|
|
||||||
if (arg.ffmpeg) {
|
|
||||||
checkFfmpeg(arg.ffmpeg).then(success => {
|
|
||||||
if (success) {
|
|
||||||
llonebotError.ffmpegError = ''
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
})
|
})
|
||||||
|
|
||||||
ipcMain.on(CHANNEL_LOG, (event, arg) => {
|
ipcMain.on(CHANNEL_LOG, (event, arg) => {
|
||||||
@@ -155,35 +110,65 @@ function onLoad() {
|
|||||||
async function postReceiveMsg(msgList: RawMessage[]) {
|
async function postReceiveMsg(msgList: RawMessage[]) {
|
||||||
const {debug, reportSelfMessage} = getConfigUtil().getConfig();
|
const {debug, reportSelfMessage} = getConfigUtil().getConfig();
|
||||||
for (let message of msgList) {
|
for (let message of msgList) {
|
||||||
// log("收到新消息", message)
|
|
||||||
message.msgShortId = await dbUtil.addMsg(message)
|
// log("收到新消息", message.msgId, message.msgSeq)
|
||||||
|
// if (message.senderUin !== selfInfo.uin){
|
||||||
|
message.msgShortId = await dbUtil.addMsg(message);
|
||||||
|
// }
|
||||||
|
|
||||||
OB11Constructor.message(message).then((msg) => {
|
OB11Constructor.message(message).then((msg) => {
|
||||||
if (debug) {
|
if (debug) {
|
||||||
msg.raw = message;
|
msg.raw = message;
|
||||||
|
} else {
|
||||||
|
if (msg.message.length === 0) {
|
||||||
|
return
|
||||||
|
}
|
||||||
}
|
}
|
||||||
const isSelfMsg = msg.user_id.toString() == selfInfo.uin
|
const isSelfMsg = msg.user_id.toString() == selfInfo.uin
|
||||||
if (isSelfMsg && !reportSelfMessage) {
|
if (isSelfMsg && !reportSelfMessage) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if (isSelfMsg) {
|
||||||
|
msg.target_id = parseInt(message.peerUin);
|
||||||
|
}
|
||||||
postOB11Event(msg);
|
postOB11Event(msg);
|
||||||
// log("post msg", msg)
|
// log("post msg", msg)
|
||||||
}).catch(e => log("constructMessage error: ", e.stack.toString()));
|
}).catch(e => log("constructMessage error: ", e.stack.toString()));
|
||||||
|
OB11Constructor.GroupEvent(message).then(groupEvent => {
|
||||||
|
if (groupEvent) {
|
||||||
|
// log("post group event", groupEvent);
|
||||||
|
postOB11Event(groupEvent);
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function startReceiveHook() {
|
async function startReceiveHook() {
|
||||||
registerReceiveHook<{ msgList: Array<RawMessage> }>(ReceiveCmd.NEW_MSG, async (payload) => {
|
if (getConfigUtil().getConfig().enablePoke) {
|
||||||
|
registerPokeHandler((id, isGroup) => {
|
||||||
|
log(`收到戳一戳消息了!是否群聊:${isGroup},id:${id}`)
|
||||||
|
let pokeEvent: OB11FriendPokeEvent | OB11GroupPokeEvent;
|
||||||
|
if (isGroup) {
|
||||||
|
pokeEvent = new OB11GroupPokeEvent(parseInt(id));
|
||||||
|
} else {
|
||||||
|
pokeEvent = new OB11FriendPokeEvent(parseInt(id));
|
||||||
|
}
|
||||||
|
postOB11Event(pokeEvent);
|
||||||
|
})
|
||||||
|
}
|
||||||
|
registerReceiveHook<{
|
||||||
|
msgList: Array<RawMessage>
|
||||||
|
}>([ReceiveCmdS.NEW_MSG, ReceiveCmdS.NEW_ACTIVE_MSG], async (payload) => {
|
||||||
try {
|
try {
|
||||||
await postReceiveMsg(payload.msgList);
|
await postReceiveMsg(payload.msgList);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
log("report message error: ", e.toString());
|
log("report message error: ", e.stack.toString());
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
registerReceiveHook<{ msgList: Array<RawMessage> }>(ReceiveCmd.UPDATE_MSG, async (payload) => {
|
registerReceiveHook<{ msgList: Array<RawMessage> }>([ReceiveCmdS.UPDATE_MSG], async (payload) => {
|
||||||
for (const message of payload.msgList) {
|
for (const message of payload.msgList) {
|
||||||
// log("message update", message.sendStatus, message)
|
// log("message update", message.sendStatus, message.msgId, message.msgSeq)
|
||||||
if (message.recallTime != "0") {
|
if (message.recallTime != "0") { //todo: 这个判断方法不太好,应该使用灰色消息元素来判断
|
||||||
// 撤回消息上报
|
// 撤回消息上报
|
||||||
const oriMessage = await dbUtil.getMsgByLongId(message.msgId)
|
const oriMessage = await dbUtil.getMsgByLongId(message.msgId)
|
||||||
if (!oriMessage) {
|
if (!oriMessage) {
|
||||||
@@ -198,7 +183,7 @@ function onLoad() {
|
|||||||
let operatorId = message.senderUin
|
let operatorId = message.senderUin
|
||||||
for (const element of message.elements) {
|
for (const element of message.elements) {
|
||||||
const operatorUid = element.grayTipElement?.revokeElement.operatorUid
|
const operatorUid = element.grayTipElement?.revokeElement.operatorUid
|
||||||
const operator = await getGroupMember(message.peerUin, null, operatorUid)
|
const operator = await getGroupMember(message.peerUin, operatorUid)
|
||||||
operatorId = operator.uin
|
operatorId = operator.uin
|
||||||
}
|
}
|
||||||
const groupRecallEvent = new OB11GroupRecallNoticeEvent(
|
const groupRecallEvent = new OB11GroupRecallNoticeEvent(
|
||||||
@@ -213,10 +198,10 @@ function onLoad() {
|
|||||||
// 不让入库覆盖原来消息,不然就获取不到撤回的消息内容了
|
// 不让入库覆盖原来消息,不然就获取不到撤回的消息内容了
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
dbUtil.addMsg(message).then();
|
dbUtil.updateMsg(message).then();
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
registerReceiveHook<{ msgRecord: RawMessage }>(ReceiveCmd.SELF_SEND_MSG, async (payload) => {
|
registerReceiveHook<{ msgRecord: RawMessage }>(ReceiveCmdS.SELF_SEND_MSG, async (payload) => {
|
||||||
const {reportSelfMessage} = getConfigUtil().getConfig();
|
const {reportSelfMessage} = getConfigUtil().getConfig();
|
||||||
if (!reportSelfMessage) {
|
if (!reportSelfMessage) {
|
||||||
return
|
return
|
||||||
@@ -232,12 +217,12 @@ function onLoad() {
|
|||||||
"doubt": boolean,
|
"doubt": boolean,
|
||||||
"oldestUnreadSeq": string,
|
"oldestUnreadSeq": string,
|
||||||
"unreadCount": number
|
"unreadCount": number
|
||||||
}>(ReceiveCmd.UNREAD_GROUP_NOTIFY, async (payload) => {
|
}>(ReceiveCmdS.UNREAD_GROUP_NOTIFY, async (payload) => {
|
||||||
if (payload.unreadCount) {
|
if (payload.unreadCount) {
|
||||||
// log("开始获取群通知详情")
|
// log("开始获取群通知详情")
|
||||||
let notify: GroupNotifies;
|
let notify: GroupNotifies;
|
||||||
try {
|
try {
|
||||||
notify = await NTQQApi.getGroupNotifies();
|
notify = await NTQQGroupApi.getGroupNotifies();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// log("获取群通知详情失败", e);
|
// log("获取群通知详情失败", e);
|
||||||
return
|
return
|
||||||
@@ -249,25 +234,23 @@ function onLoad() {
|
|||||||
for (const notify of notifies) {
|
for (const notify of notifies) {
|
||||||
try {
|
try {
|
||||||
notify.time = Date.now();
|
notify.time = Date.now();
|
||||||
const notifyTime = parseInt(notify.seq) / 1000
|
// const notifyTime = parseInt(notify.seq) / 1000
|
||||||
// log(`加群通知时间${notifyTime}`, `LLOneBot启动时间${startTime}`);
|
// log(`加群通知时间${notifyTime}`, `LLOneBot启动时间${startTime}`);
|
||||||
// if (notifyTime < startTime) {
|
// if (notifyTime < startTime) {
|
||||||
// continue;
|
// continue;
|
||||||
// }
|
// }
|
||||||
let existNotify = groupNotifies[notify.seq];
|
let existNotify = await dbUtil.getGroupNotify(notify.seq);
|
||||||
if (existNotify) {
|
if (existNotify) {
|
||||||
if (Date.now() - existNotify.time < 3000) {
|
continue
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
log("收到群通知", notify);
|
log("收到群通知", notify);
|
||||||
groupNotifies[notify.seq] = notify;
|
await dbUtil.addGroupNotify(notify);
|
||||||
// let member2: GroupMember;
|
// let member2: GroupMember;
|
||||||
// if (notify.user2.uid) {
|
// if (notify.user2.uid) {
|
||||||
// member2 = await getGroupMember(notify.group.groupCode, null, notify.user2.uid);
|
// member2 = await getGroupMember(notify.group.groupCode, null, notify.user2.uid);
|
||||||
// }
|
// }
|
||||||
if ([GroupNotifyTypes.ADMIN_SET, GroupNotifyTypes.ADMIN_UNSET].includes(notify.type)) {
|
if ([GroupNotifyTypes.ADMIN_SET, GroupNotifyTypes.ADMIN_UNSET].includes(notify.type)) {
|
||||||
const member1 = await getGroupMember(notify.group.groupCode, null, notify.user1.uid);
|
const member1 = await getGroupMember(notify.group.groupCode, notify.user1.uid);
|
||||||
log("有管理员变动通知");
|
log("有管理员变动通知");
|
||||||
refreshGroupMembers(notify.group.groupCode).then()
|
refreshGroupMembers(notify.group.groupCode).then()
|
||||||
let groupAdminNoticeEvent = new OB11GroupAdminNoticeEvent()
|
let groupAdminNoticeEvent = new OB11GroupAdminNoticeEvent()
|
||||||
@@ -282,9 +265,9 @@ function onLoad() {
|
|||||||
log("获取群通知的成员信息失败", notify, getGroup(notify.group.groupCode));
|
log("获取群通知的成员信息失败", notify, getGroup(notify.group.groupCode));
|
||||||
}
|
}
|
||||||
} else if (notify.type == GroupNotifyTypes.MEMBER_EXIT) {
|
} else if (notify.type == GroupNotifyTypes.MEMBER_EXIT) {
|
||||||
log("有成员退出通知");
|
// log("有成员退出通知");
|
||||||
const member1 = await getGroupMember(notify.group.groupCode, null, notify.user1.uid);
|
// const member1 = await getGroupMember(notify.group.groupCode, null, notify.user1.uid);
|
||||||
let groupDecreaseEvent = new OB11GroupDecreaseEvent(parseInt(notify.group.groupCode), parseInt(member1.uin))
|
// let groupDecreaseEvent = new OB11GroupDecreaseEvent(parseInt(notify.group.groupCode), parseInt(member1.uin))
|
||||||
// postEvent(groupDecreaseEvent, true);
|
// postEvent(groupDecreaseEvent, true);
|
||||||
} else if ([GroupNotifyTypes.JOIN_REQUEST].includes(notify.type)) {
|
} else if ([GroupNotifyTypes.JOIN_REQUEST].includes(notify.type)) {
|
||||||
log("有加群请求");
|
log("有加群请求");
|
||||||
@@ -292,7 +275,7 @@ function onLoad() {
|
|||||||
groupRequestEvent.group_id = parseInt(notify.group.groupCode);
|
groupRequestEvent.group_id = parseInt(notify.group.groupCode);
|
||||||
let requestQQ = ""
|
let requestQQ = ""
|
||||||
try {
|
try {
|
||||||
requestQQ = (await NTQQApi.getUserDetailInfo(notify.user1.uid)).uin;
|
requestQQ = (await NTQQUserApi.getUserDetailInfo(notify.user1.uid)).uin;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
log("获取加群人QQ号失败", e)
|
log("获取加群人QQ号失败", e)
|
||||||
}
|
}
|
||||||
@@ -305,7 +288,10 @@ function onLoad() {
|
|||||||
log("收到邀请我加群通知")
|
log("收到邀请我加群通知")
|
||||||
let groupInviteEvent = new OB11GroupRequestEvent();
|
let groupInviteEvent = new OB11GroupRequestEvent();
|
||||||
groupInviteEvent.group_id = parseInt(notify.group.groupCode);
|
groupInviteEvent.group_id = parseInt(notify.group.groupCode);
|
||||||
let user_id = (await NTQQApi.getUserDetailInfo(notify.user2.uid))?.uin
|
let user_id = (await getFriend(notify.user2.uid))?.uin
|
||||||
|
if (!user_id) {
|
||||||
|
user_id = (await NTQQUserApi.getUserDetailInfo(notify.user2.uid))?.uin
|
||||||
|
}
|
||||||
groupInviteEvent.user_id = parseInt(user_id);
|
groupInviteEvent.user_id = parseInt(user_id);
|
||||||
groupInviteEvent.sub_type = "invite";
|
groupInviteEvent.sub_type = "invite";
|
||||||
groupInviteEvent.flag = notify.seq;
|
groupInviteEvent.flag = notify.seq;
|
||||||
@@ -321,14 +307,14 @@ function onLoad() {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
registerReceiveHook<FriendRequestNotify>(ReceiveCmd.FRIEND_REQUEST, async (payload) => {
|
registerReceiveHook<FriendRequestNotify>(ReceiveCmdS.FRIEND_REQUEST, async (payload) => {
|
||||||
for (const req of payload.data.buddyReqs) {
|
for (const req of payload.data.buddyReqs) {
|
||||||
if (req.isUnread && !friendRequests[req.sourceId] && (parseInt(req.reqTime) > startTime / 1000)) {
|
if (req.isUnread && !friendRequests[req.sourceId] && (parseInt(req.reqTime) > startTime / 1000)) {
|
||||||
friendRequests[req.sourceId] = req;
|
friendRequests[req.sourceId] = req;
|
||||||
log("有新的好友请求", req);
|
log("有新的好友请求", req);
|
||||||
let friendRequestEvent = new OB11FriendRequestEvent();
|
let friendRequestEvent = new OB11FriendRequestEvent();
|
||||||
try {
|
try {
|
||||||
let requester = await NTQQApi.getUserDetailInfo(req.friendUid)
|
let requester = await NTQQUserApi.getUserDetailInfo(req.friendUid)
|
||||||
friendRequestEvent.user_id = parseInt(requester.uin);
|
friendRequestEvent.user_id = parseInt(requester.uin);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
log("获取加好友者QQ号失败", e);
|
log("获取加好友者QQ号失败", e);
|
||||||
@@ -344,9 +330,16 @@ function onLoad() {
|
|||||||
let startTime = 0;
|
let startTime = 0;
|
||||||
|
|
||||||
async function start() {
|
async function start() {
|
||||||
|
log("llonebot pid", process.pid)
|
||||||
|
|
||||||
startTime = Date.now();
|
startTime = Date.now();
|
||||||
|
dbUtil.getReceivedTempUinMap().then(m=>{
|
||||||
|
for (const [key, value] of Object.entries(m)) {
|
||||||
|
uidMaps[value] = key;
|
||||||
|
}
|
||||||
|
})
|
||||||
startReceiveHook().then();
|
startReceiveHook().then();
|
||||||
NTQQApi.getGroups(true).then()
|
NTQQGroupApi.getGroups(true).then()
|
||||||
const config = getConfigUtil().getConfig()
|
const config = getConfigUtil().getConfig()
|
||||||
// 检查ffmpeg
|
// 检查ffmpeg
|
||||||
checkFfmpeg(config.ffmpeg).then(exist => {
|
checkFfmpeg(config.ffmpeg).then(exist => {
|
||||||
@@ -375,7 +368,7 @@ function onLoad() {
|
|||||||
const init = async () => {
|
const init = async () => {
|
||||||
try {
|
try {
|
||||||
log("start get self info")
|
log("start get self info")
|
||||||
const _ = await NTQQApi.getSelfInfo();
|
const _ = await NTQQUserApi.getSelfInfo();
|
||||||
log("get self info api result:", _);
|
log("get self info api result:", _);
|
||||||
Object.assign(selfInfo, _);
|
Object.assign(selfInfo, _);
|
||||||
selfInfo.nick = selfInfo.uin;
|
selfInfo.nick = selfInfo.uin;
|
||||||
@@ -385,7 +378,7 @@ function onLoad() {
|
|||||||
log("self info", selfInfo);
|
log("self info", selfInfo);
|
||||||
if (selfInfo.uin) {
|
if (selfInfo.uin) {
|
||||||
try {
|
try {
|
||||||
const userInfo = (await NTQQApi.getUserDetailInfo(selfInfo.uid));
|
const userInfo = (await NTQQUserApi.getUserDetailInfo(selfInfo.uid));
|
||||||
log("self info", userInfo);
|
log("self info", userInfo);
|
||||||
if (userInfo) {
|
if (userInfo) {
|
||||||
selfInfo.nick = userInfo.nick;
|
selfInfo.nick = userInfo.nick;
|
||||||
@@ -410,6 +403,10 @@ function onLoad() {
|
|||||||
|
|
||||||
// 创建窗口时触发
|
// 创建窗口时触发
|
||||||
function onBrowserWindowCreated(window: BrowserWindow) {
|
function onBrowserWindowCreated(window: BrowserWindow) {
|
||||||
|
if (selfInfo.uid) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log("window create", window.webContents.getURL().toString())
|
||||||
try {
|
try {
|
||||||
hookNTQQApiCall(window);
|
hookNTQQApiCall(window);
|
||||||
hookNTQQApiReceive(window);
|
hookNTQQApiReceive(window);
|
||||||
|
64
src/main/setConfig.ts
Normal file
64
src/main/setConfig.ts
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
import {Config} from "../common/types";
|
||||||
|
import {ob11HTTPServer} from "../onebot11/server/http";
|
||||||
|
import {ob11WebsocketServer} from "../onebot11/server/ws/WebsocketServer";
|
||||||
|
import {ob11ReverseWebsockets} from "../onebot11/server/ws/ReverseWebsocket";
|
||||||
|
import {llonebotError} from "../common/data";
|
||||||
|
import {checkFfmpeg} from "../common/utils/file";
|
||||||
|
import {getConfigUtil} from "../common/config";
|
||||||
|
|
||||||
|
export async function setConfig(config: Config) {
|
||||||
|
let oldConfig = getConfigUtil().getConfig();
|
||||||
|
getConfigUtil().setConfig(config)
|
||||||
|
if (config.ob11.httpPort != oldConfig.ob11.httpPort && config.ob11.enableHttp) {
|
||||||
|
ob11HTTPServer.restart(config.ob11.httpPort);
|
||||||
|
}
|
||||||
|
// 判断是否启用或关闭HTTP服务
|
||||||
|
if (!config.ob11.enableHttp) {
|
||||||
|
ob11HTTPServer.stop();
|
||||||
|
} else {
|
||||||
|
ob11HTTPServer.start(config.ob11.httpPort);
|
||||||
|
}
|
||||||
|
// 正向ws端口变化,重启服务
|
||||||
|
if (config.ob11.wsPort != oldConfig.ob11.wsPort) {
|
||||||
|
ob11WebsocketServer.restart(config.ob11.wsPort);
|
||||||
|
}
|
||||||
|
// 判断是否启用或关闭正向ws
|
||||||
|
if (config.ob11.enableWs != oldConfig.ob11.enableWs) {
|
||||||
|
if (config.ob11.enableWs) {
|
||||||
|
ob11WebsocketServer.start(config.ob11.wsPort);
|
||||||
|
} else {
|
||||||
|
ob11WebsocketServer.stop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 判断是否启用或关闭反向ws
|
||||||
|
if (config.ob11.enableWsReverse != oldConfig.ob11.enableWsReverse) {
|
||||||
|
if (config.ob11.enableWsReverse) {
|
||||||
|
ob11ReverseWebsockets.start();
|
||||||
|
} else {
|
||||||
|
ob11ReverseWebsockets.stop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (config.ob11.enableWsReverse) {
|
||||||
|
// 判断反向ws地址有变化
|
||||||
|
if (config.ob11.wsHosts.length != oldConfig.ob11.wsHosts.length) {
|
||||||
|
ob11ReverseWebsockets.restart();
|
||||||
|
} else {
|
||||||
|
for (const newHost of config.ob11.wsHosts) {
|
||||||
|
if (!oldConfig.ob11.wsHosts.includes(newHost)) {
|
||||||
|
ob11ReverseWebsockets.restart();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查ffmpeg
|
||||||
|
if (config.ffmpeg) {
|
||||||
|
checkFfmpeg(config.ffmpeg).then(success => {
|
||||||
|
if (success) {
|
||||||
|
llonebotError.ffmpegError = ''
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
217
src/ntqqapi/api/file.ts
Normal file
217
src/ntqqapi/api/file.ts
Normal file
@@ -0,0 +1,217 @@
|
|||||||
|
import {callNTQQApi, GeneralCallResult, NTQQApiClass, NTQQApiMethod} from "../ntcall";
|
||||||
|
import {
|
||||||
|
CacheFileList,
|
||||||
|
CacheFileListItem,
|
||||||
|
CacheFileType,
|
||||||
|
CacheScanResult,
|
||||||
|
ChatCacheList, ChatCacheListItemBasic,
|
||||||
|
ChatType,
|
||||||
|
ElementType
|
||||||
|
} from "../types";
|
||||||
|
import path from "path";
|
||||||
|
import fs from "fs";
|
||||||
|
import {ReceiveCmdS} from "../hook";
|
||||||
|
import {log} from "../../common/utils/log";
|
||||||
|
|
||||||
|
export class NTQQFileApi{
|
||||||
|
static async getFileType(filePath: string) {
|
||||||
|
return await callNTQQApi<{ ext: string }>({
|
||||||
|
className: NTQQApiClass.FS_API, methodName: NTQQApiMethod.FILE_TYPE, args: [filePath]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
static async getFileMd5(filePath: string) {
|
||||||
|
return await callNTQQApi<string>({
|
||||||
|
className: NTQQApiClass.FS_API,
|
||||||
|
methodName: NTQQApiMethod.FILE_MD5,
|
||||||
|
args: [filePath]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
static async copyFile(filePath: string, destPath: string) {
|
||||||
|
return await callNTQQApi<string>({
|
||||||
|
className: NTQQApiClass.FS_API,
|
||||||
|
methodName: NTQQApiMethod.FILE_COPY,
|
||||||
|
args: [{
|
||||||
|
fromPath: filePath,
|
||||||
|
toPath: destPath
|
||||||
|
}]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
static async getFileSize(filePath: string) {
|
||||||
|
return await callNTQQApi<number>({
|
||||||
|
className: NTQQApiClass.FS_API, methodName: NTQQApiMethod.FILE_SIZE, args: [filePath]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
// 上传文件到QQ的文件夹
|
||||||
|
static async uploadFile(filePath: string, elementType: ElementType = ElementType.PIC) {
|
||||||
|
const md5 = await NTQQFileApi.getFileMd5(filePath);
|
||||||
|
let ext = (await NTQQFileApi.getFileType(filePath))?.ext
|
||||||
|
if (ext) {
|
||||||
|
ext = "." + ext
|
||||||
|
} else {
|
||||||
|
ext = ""
|
||||||
|
}
|
||||||
|
let fileName = `${path.basename(filePath)}`;
|
||||||
|
if (fileName.indexOf(".") === -1) {
|
||||||
|
fileName += ext;
|
||||||
|
}
|
||||||
|
const mediaPath = await callNTQQApi<string>({
|
||||||
|
methodName: NTQQApiMethod.MEDIA_FILE_PATH,
|
||||||
|
args: [{
|
||||||
|
path_info: {
|
||||||
|
md5HexStr: md5,
|
||||||
|
fileName: fileName,
|
||||||
|
elementType: elementType,
|
||||||
|
elementSubType: 0,
|
||||||
|
thumbSize: 0,
|
||||||
|
needCreate: true,
|
||||||
|
downloadType: 1,
|
||||||
|
file_uuid: ""
|
||||||
|
}
|
||||||
|
}]
|
||||||
|
})
|
||||||
|
log("media path", mediaPath)
|
||||||
|
await NTQQFileApi.copyFile(filePath, mediaPath);
|
||||||
|
const fileSize = await NTQQFileApi.getFileSize(filePath);
|
||||||
|
return {
|
||||||
|
md5,
|
||||||
|
fileName,
|
||||||
|
path: mediaPath,
|
||||||
|
fileSize
|
||||||
|
}
|
||||||
|
}
|
||||||
|
static async downloadMedia(msgId: string, chatType: ChatType, peerUid: string, elementId: string, thumbPath: string, sourcePath: string) {
|
||||||
|
// 用于下载收到的消息中的图片等
|
||||||
|
if (fs.existsSync(sourcePath)) {
|
||||||
|
return sourcePath
|
||||||
|
}
|
||||||
|
const apiParams = [
|
||||||
|
{
|
||||||
|
getReq: {
|
||||||
|
msgId: msgId,
|
||||||
|
chatType: chatType,
|
||||||
|
peerUid: peerUid,
|
||||||
|
elementId: elementId,
|
||||||
|
thumbSize: 0,
|
||||||
|
downloadType: 1,
|
||||||
|
filePath: thumbPath,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
undefined,
|
||||||
|
]
|
||||||
|
// log("需要下载media", sourcePath);
|
||||||
|
await callNTQQApi({
|
||||||
|
methodName: NTQQApiMethod.DOWNLOAD_MEDIA,
|
||||||
|
args: apiParams,
|
||||||
|
cbCmd: ReceiveCmdS.MEDIA_DOWNLOAD_COMPLETE,
|
||||||
|
cmdCB: (payload: { notifyInfo: { filePath: string } }) => {
|
||||||
|
// log("media 下载完成判断", payload.notifyInfo.filePath, sourcePath);
|
||||||
|
return payload.notifyInfo.filePath == sourcePath;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return sourcePath
|
||||||
|
}
|
||||||
|
static async getImageSize(filePath: string) {
|
||||||
|
return await callNTQQApi<{ width: number, height: number }>({
|
||||||
|
className: NTQQApiClass.FS_API, methodName: NTQQApiMethod.IMAGE_SIZE, args: [filePath]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
export class NTQQFileCacheApi{
|
||||||
|
static async setCacheSilentScan(isSilent: boolean = true) {
|
||||||
|
return await callNTQQApi<GeneralCallResult>({
|
||||||
|
methodName: NTQQApiMethod.CACHE_SET_SILENCE,
|
||||||
|
args: [{
|
||||||
|
isSilent
|
||||||
|
}, null]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
static getCacheSessionPathList() {
|
||||||
|
return callNTQQApi<{
|
||||||
|
key: string,
|
||||||
|
value: string
|
||||||
|
}[]>({
|
||||||
|
className: NTQQApiClass.OS_API,
|
||||||
|
methodName: NTQQApiMethod.CACHE_PATH_SESSION,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
static clearCache(cacheKeys: Array<string> = ['tmp', 'hotUpdate']) {
|
||||||
|
return callNTQQApi<any>({ // TODO: 目前还不知道真正的返回值是什么
|
||||||
|
methodName: NTQQApiMethod.CACHE_CLEAR,
|
||||||
|
args: [{
|
||||||
|
keys: cacheKeys
|
||||||
|
}, null]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
static addCacheScannedPaths(pathMap: object = {}) {
|
||||||
|
return callNTQQApi<GeneralCallResult>({
|
||||||
|
methodName: NTQQApiMethod.CACHE_ADD_SCANNED_PATH,
|
||||||
|
args: [{
|
||||||
|
pathMap: {...pathMap},
|
||||||
|
}, null]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
static scanCache() {
|
||||||
|
callNTQQApi<GeneralCallResult>({
|
||||||
|
methodName: ReceiveCmdS.CACHE_SCAN_FINISH,
|
||||||
|
classNameIsRegister: true,
|
||||||
|
}).then();
|
||||||
|
return callNTQQApi<CacheScanResult>({
|
||||||
|
methodName: NTQQApiMethod.CACHE_SCAN,
|
||||||
|
args: [null, null],
|
||||||
|
timeoutSecond: 300,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
static getHotUpdateCachePath() {
|
||||||
|
return callNTQQApi<string>({
|
||||||
|
className: NTQQApiClass.HOTUPDATE_API,
|
||||||
|
methodName: NTQQApiMethod.CACHE_PATH_HOT_UPDATE
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
static getDesktopTmpPath() {
|
||||||
|
return callNTQQApi<string>({
|
||||||
|
className: NTQQApiClass.BUSINESS_API,
|
||||||
|
methodName: NTQQApiMethod.CACHE_PATH_DESKTOP_TEMP
|
||||||
|
});
|
||||||
|
}
|
||||||
|
static getChatCacheList(type: ChatType, pageSize: number = 1000, pageIndex: number = 0) {
|
||||||
|
return new Promise<ChatCacheList>((res, rej) => {
|
||||||
|
callNTQQApi<ChatCacheList>({
|
||||||
|
methodName: NTQQApiMethod.CACHE_CHAT_GET,
|
||||||
|
args: [{
|
||||||
|
chatType: type,
|
||||||
|
pageSize,
|
||||||
|
order: 1,
|
||||||
|
pageIndex
|
||||||
|
}, null]
|
||||||
|
}).then(list => res(list))
|
||||||
|
.catch(e => rej(e));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
static getFileCacheInfo(fileType: CacheFileType, pageSize: number = 1000, lastRecord?: CacheFileListItem) {
|
||||||
|
const _lastRecord = lastRecord ? lastRecord : {fileType: fileType};
|
||||||
|
|
||||||
|
return callNTQQApi<CacheFileList>({
|
||||||
|
methodName: NTQQApiMethod.CACHE_FILE_GET,
|
||||||
|
args: [{
|
||||||
|
fileType: fileType,
|
||||||
|
restart: true,
|
||||||
|
pageSize: pageSize,
|
||||||
|
order: 1,
|
||||||
|
lastRecord: _lastRecord,
|
||||||
|
}, null]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
static async clearChatCache(chats: ChatCacheListItemBasic[] = [], fileKeys: string[] = []) {
|
||||||
|
return await callNTQQApi<GeneralCallResult>({
|
||||||
|
methodName: NTQQApiMethod.CACHE_CHAT_CLEAR,
|
||||||
|
args: [{
|
||||||
|
chats,
|
||||||
|
fileKeys
|
||||||
|
}, null]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
61
src/ntqqapi/api/friend.ts
Normal file
61
src/ntqqapi/api/friend.ts
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
import {Friend, FriendRequest} from "../types";
|
||||||
|
import {ReceiveCmdS} from "../hook";
|
||||||
|
import {callNTQQApi, GeneralCallResult, NTQQApiMethod} from "../ntcall";
|
||||||
|
import {friendRequests} from "../../common/data";
|
||||||
|
|
||||||
|
export class NTQQFriendApi{
|
||||||
|
static async getFriends(forced = false) {
|
||||||
|
const data = await callNTQQApi<{
|
||||||
|
data: {
|
||||||
|
categoryId: number,
|
||||||
|
categroyName: string,
|
||||||
|
categroyMbCount: number,
|
||||||
|
buddyList: Friend[]
|
||||||
|
}[]
|
||||||
|
}>(
|
||||||
|
{
|
||||||
|
methodName: NTQQApiMethod.FRIENDS,
|
||||||
|
args: [{force_update: forced}, undefined],
|
||||||
|
cbCmd: ReceiveCmdS.FRIENDS
|
||||||
|
})
|
||||||
|
let _friends: Friend[] = [];
|
||||||
|
for (const fData of data.data) {
|
||||||
|
_friends.push(...fData.buddyList)
|
||||||
|
}
|
||||||
|
return _friends
|
||||||
|
}
|
||||||
|
static async likeFriend(uid: string, count = 1) {
|
||||||
|
return await callNTQQApi<GeneralCallResult>({
|
||||||
|
methodName: NTQQApiMethod.LIKE_FRIEND,
|
||||||
|
args: [{
|
||||||
|
doLikeUserInfo: {
|
||||||
|
friendUid: uid,
|
||||||
|
sourceId: 71,
|
||||||
|
doLikeCount: count,
|
||||||
|
doLikeTollCount: 0
|
||||||
|
}
|
||||||
|
}, null]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
static async handleFriendRequest(sourceId: number, accept: boolean,) {
|
||||||
|
const request: FriendRequest = friendRequests[sourceId]
|
||||||
|
if (!request) {
|
||||||
|
throw `sourceId ${sourceId}, 对应的好友请求不存在`
|
||||||
|
}
|
||||||
|
const result = await callNTQQApi<GeneralCallResult>({
|
||||||
|
methodName: NTQQApiMethod.HANDLE_FRIEND_REQUEST,
|
||||||
|
args: [
|
||||||
|
{
|
||||||
|
"approvalInfo": {
|
||||||
|
"friendUid": request.friendUid,
|
||||||
|
"reqTime": request.reqTime,
|
||||||
|
accept
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
})
|
||||||
|
delete friendRequests[sourceId];
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
223
src/ntqqapi/api/group.ts
Normal file
223
src/ntqqapi/api/group.ts
Normal file
@@ -0,0 +1,223 @@
|
|||||||
|
import {ReceiveCmdS} from "../hook";
|
||||||
|
import {Group, GroupMember, GroupMemberRole, GroupNotifies, GroupNotify, GroupRequestOperateTypes} from "../types";
|
||||||
|
import {callNTQQApi, GeneralCallResult, NTQQApiClass, NTQQApiMethod} from "../ntcall";
|
||||||
|
import {uidMaps} from "../../common/data";
|
||||||
|
import {BrowserWindow} from "electron";
|
||||||
|
import {dbUtil} from "../../common/db";
|
||||||
|
import {log} from "../../common/utils/log";
|
||||||
|
|
||||||
|
export class NTQQGroupApi{
|
||||||
|
static async getGroups(forced = false) {
|
||||||
|
let cbCmd = ReceiveCmdS.GROUPS
|
||||||
|
if (process.platform != "win32") {
|
||||||
|
cbCmd = ReceiveCmdS.GROUPS_UNIX
|
||||||
|
}
|
||||||
|
const result = await callNTQQApi<{
|
||||||
|
updateType: number,
|
||||||
|
groupList: Group[]
|
||||||
|
}>({methodName: NTQQApiMethod.GROUPS, args: [{force_update: forced}, undefined], cbCmd})
|
||||||
|
return result.groupList
|
||||||
|
}
|
||||||
|
static async getGroupMembers(groupQQ: string, num = 3000): Promise<GroupMember[]> {
|
||||||
|
const sceneId = await callNTQQApi({
|
||||||
|
methodName: NTQQApiMethod.GROUP_MEMBER_SCENE,
|
||||||
|
args: [{
|
||||||
|
groupCode: groupQQ,
|
||||||
|
scene: "groupMemberList_MainWindow"
|
||||||
|
}]
|
||||||
|
})
|
||||||
|
// log("get group member sceneId", sceneId);
|
||||||
|
try {
|
||||||
|
const result = await callNTQQApi<{
|
||||||
|
result: { infos: any }
|
||||||
|
}>({
|
||||||
|
methodName: NTQQApiMethod.GROUP_MEMBERS,
|
||||||
|
args: [{
|
||||||
|
sceneId: sceneId,
|
||||||
|
num: num
|
||||||
|
},
|
||||||
|
null
|
||||||
|
]
|
||||||
|
})
|
||||||
|
// log("members info", typeof result.result.infos, Object.keys(result.result.infos))
|
||||||
|
const values = result.result.infos.values()
|
||||||
|
|
||||||
|
const members: GroupMember[] = Array.from(values)
|
||||||
|
for (const member of members) {
|
||||||
|
uidMaps[member.uid] = member.uin;
|
||||||
|
}
|
||||||
|
// log(uidMaps);
|
||||||
|
// log("members info", values);
|
||||||
|
log(`get group ${groupQQ} members success`)
|
||||||
|
return members
|
||||||
|
} catch (e) {
|
||||||
|
log(`get group ${groupQQ} members failed`, e)
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
static async getGroupNotifies() {
|
||||||
|
// 获取管理员变更
|
||||||
|
// 加群通知,退出通知,需要管理员权限
|
||||||
|
callNTQQApi<GeneralCallResult>({
|
||||||
|
methodName: ReceiveCmdS.GROUP_NOTIFY,
|
||||||
|
classNameIsRegister: true,
|
||||||
|
}).then()
|
||||||
|
return await callNTQQApi<GroupNotifies>({
|
||||||
|
methodName: NTQQApiMethod.GET_GROUP_NOTICE,
|
||||||
|
cbCmd: ReceiveCmdS.GROUP_NOTIFY,
|
||||||
|
afterFirstCmd: false,
|
||||||
|
args: [
|
||||||
|
{"doubt": false, "startSeq": "", "number": 14},
|
||||||
|
null
|
||||||
|
]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
static async getGroupIgnoreNotifies() {
|
||||||
|
await NTQQGroupApi.getGroupNotifies();
|
||||||
|
const result = callNTQQApi<GroupNotifies>({
|
||||||
|
className: NTQQApiClass.WINDOW_API,
|
||||||
|
methodName: NTQQApiMethod.OPEN_EXTRA_WINDOW,
|
||||||
|
cbCmd: ReceiveCmdS.GROUP_NOTIFY,
|
||||||
|
afterFirstCmd: false,
|
||||||
|
args: [
|
||||||
|
"GroupNotifyFilterWindow"
|
||||||
|
]
|
||||||
|
})
|
||||||
|
// 关闭窗口
|
||||||
|
setTimeout(() => {
|
||||||
|
for (const w of BrowserWindow.getAllWindows()) {
|
||||||
|
// log("close window", w.webContents.getURL())
|
||||||
|
if (w.webContents.getURL().indexOf("#/notify-filter/") != -1) {
|
||||||
|
w.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, 2000);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
static async handleGroupRequest(seq: string, operateType: GroupRequestOperateTypes, reason?: string) {
|
||||||
|
const notify: GroupNotify = await dbUtil.getGroupNotify(seq)
|
||||||
|
if (!notify) {
|
||||||
|
throw `${seq}对应的加群通知不存在`
|
||||||
|
}
|
||||||
|
// delete groupNotifies[seq];
|
||||||
|
return await callNTQQApi<GeneralCallResult>({
|
||||||
|
methodName: NTQQApiMethod.HANDLE_GROUP_REQUEST,
|
||||||
|
args: [
|
||||||
|
{
|
||||||
|
"doubt": false,
|
||||||
|
"operateMsg": {
|
||||||
|
"operateType": operateType, // 2 拒绝
|
||||||
|
"targetMsg": {
|
||||||
|
"seq": seq, // 通知序列号
|
||||||
|
"type": notify.type,
|
||||||
|
"groupCode": notify.group.groupCode,
|
||||||
|
"postscript": reason
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
null
|
||||||
|
]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
static async quitGroup(groupQQ: string) {
|
||||||
|
await callNTQQApi<GeneralCallResult>({
|
||||||
|
methodName: NTQQApiMethod.QUIT_GROUP,
|
||||||
|
args: [
|
||||||
|
{"groupCode": groupQQ},
|
||||||
|
null
|
||||||
|
]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
static async kickMember(groupQQ: string, kickUids: string[], refuseForever: boolean = false, kickReason: string = '') {
|
||||||
|
return await callNTQQApi<GeneralCallResult>(
|
||||||
|
{
|
||||||
|
methodName: NTQQApiMethod.KICK_MEMBER,
|
||||||
|
args: [
|
||||||
|
{
|
||||||
|
groupCode: groupQQ,
|
||||||
|
kickUids,
|
||||||
|
refuseForever,
|
||||||
|
kickReason,
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
static async banMember(groupQQ: string, memList: Array<{ uid: string, timeStamp: number }>) {
|
||||||
|
// timeStamp为秒数, 0为解除禁言
|
||||||
|
return await callNTQQApi<GeneralCallResult>(
|
||||||
|
{
|
||||||
|
methodName: NTQQApiMethod.MUTE_MEMBER,
|
||||||
|
args: [
|
||||||
|
{
|
||||||
|
groupCode: groupQQ,
|
||||||
|
memList,
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
static async banGroup(groupQQ: string, shutUp: boolean) {
|
||||||
|
return await callNTQQApi<GeneralCallResult>({
|
||||||
|
methodName: NTQQApiMethod.MUTE_GROUP,
|
||||||
|
args: [
|
||||||
|
{
|
||||||
|
groupCode: groupQQ,
|
||||||
|
shutUp
|
||||||
|
}, null
|
||||||
|
]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
static async setMemberCard(groupQQ: string, memberUid: string, cardName: string) {
|
||||||
|
return await callNTQQApi<GeneralCallResult>({
|
||||||
|
methodName: NTQQApiMethod.SET_MEMBER_CARD,
|
||||||
|
args: [
|
||||||
|
{
|
||||||
|
groupCode: groupQQ,
|
||||||
|
uid: memberUid,
|
||||||
|
cardName
|
||||||
|
}, null
|
||||||
|
]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
static async setMemberRole(groupQQ: string, memberUid: string, role: GroupMemberRole) {
|
||||||
|
return await callNTQQApi<GeneralCallResult>({
|
||||||
|
methodName: NTQQApiMethod.SET_MEMBER_ROLE,
|
||||||
|
args: [
|
||||||
|
{
|
||||||
|
groupCode: groupQQ,
|
||||||
|
uid: memberUid,
|
||||||
|
role
|
||||||
|
}, null
|
||||||
|
]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
static async setGroupName(groupQQ: string, groupName: string) {
|
||||||
|
return await callNTQQApi<GeneralCallResult>({
|
||||||
|
methodName: NTQQApiMethod.SET_GROUP_NAME,
|
||||||
|
args: [
|
||||||
|
{
|
||||||
|
groupCode: groupQQ,
|
||||||
|
groupName
|
||||||
|
}, null
|
||||||
|
]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// 头衔不可用
|
||||||
|
static async setGroupTitle(groupQQ: string, uid: string, title: string) {
|
||||||
|
return await callNTQQApi<GeneralCallResult>({
|
||||||
|
methodName: NTQQApiMethod.SET_GROUP_TITLE,
|
||||||
|
args: [
|
||||||
|
{
|
||||||
|
groupCode: groupQQ,
|
||||||
|
uid,
|
||||||
|
title
|
||||||
|
}, null
|
||||||
|
]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
static publishGroupBulletin(groupQQ: string, title: string, content: string) {
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
188
src/ntqqapi/api/msg.ts
Normal file
188
src/ntqqapi/api/msg.ts
Normal file
@@ -0,0 +1,188 @@
|
|||||||
|
import {callNTQQApi, GeneralCallResult, NTQQApiMethod} from "../ntcall";
|
||||||
|
import {ChatType, RawMessage, SendMessageElement} from "../types";
|
||||||
|
import {dbUtil} from "../../common/db";
|
||||||
|
import {selfInfo} from "../../common/data";
|
||||||
|
import {ReceiveCmdS, registerReceiveHook} from "../hook";
|
||||||
|
import {log} from "../../common/utils/log";
|
||||||
|
import {sleep} from "../../common/utils/helper";
|
||||||
|
|
||||||
|
export let sendMessagePool: Record<string, ((sendSuccessMsg: RawMessage) => void) | null> = {}// peerUid: callbackFunnc
|
||||||
|
|
||||||
|
export interface Peer {
|
||||||
|
chatType: ChatType
|
||||||
|
peerUid: string // 如果是群聊uid为群号,私聊uid就是加密的字符串
|
||||||
|
guildId?: ""
|
||||||
|
}
|
||||||
|
|
||||||
|
export class NTQQMsgApi {
|
||||||
|
static async activateGroupChat(groupCode: string) {
|
||||||
|
// await this.fetchRecentContact();
|
||||||
|
// await sleep(500);
|
||||||
|
return await callNTQQApi<GeneralCallResult>({
|
||||||
|
methodName: NTQQApiMethod.ADD_ACTIVE_CHAT,
|
||||||
|
args: [{peer:{peerUid: groupCode, chatType: ChatType.group}, cnt: 20}, null]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
static async fetchRecentContact(){
|
||||||
|
await callNTQQApi({
|
||||||
|
methodName: NTQQApiMethod.RECENT_CONTACT,
|
||||||
|
args: [
|
||||||
|
{
|
||||||
|
fetchParam: {
|
||||||
|
anchorPointContact: {
|
||||||
|
contactId: '',
|
||||||
|
sortField: '',
|
||||||
|
pos: 0,
|
||||||
|
},
|
||||||
|
relativeMoveCount: 0,
|
||||||
|
listType: 2, // 1普通消息,2群助手内的消息
|
||||||
|
count: 200,
|
||||||
|
fetchOld: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
static async recallMsg(peer: Peer, msgIds: string[]) {
|
||||||
|
return await callNTQQApi({
|
||||||
|
methodName: NTQQApiMethod.RECALL_MSG,
|
||||||
|
args: [{
|
||||||
|
peer,
|
||||||
|
msgIds
|
||||||
|
}, null]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
static async sendMsg(peer: Peer, msgElements: SendMessageElement[],
|
||||||
|
waitComplete = true, timeout = 10000) {
|
||||||
|
const peerUid = peer.peerUid
|
||||||
|
|
||||||
|
// 等待上一个相同的peer发送完
|
||||||
|
let checkLastSendUsingTime = 0;
|
||||||
|
const waitLastSend = async () => {
|
||||||
|
if (checkLastSendUsingTime > timeout) {
|
||||||
|
throw ("发送超时")
|
||||||
|
}
|
||||||
|
let lastSending = sendMessagePool[peer.peerUid]
|
||||||
|
if (lastSending) {
|
||||||
|
// log("有正在发送的消息,等待中...")
|
||||||
|
await sleep(500);
|
||||||
|
checkLastSendUsingTime += 500;
|
||||||
|
return await waitLastSend();
|
||||||
|
} else {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await waitLastSend();
|
||||||
|
|
||||||
|
let sentMessage: RawMessage = null;
|
||||||
|
sendMessagePool[peerUid] = async (rawMessage: RawMessage) => {
|
||||||
|
delete sendMessagePool[peerUid];
|
||||||
|
sentMessage = rawMessage;
|
||||||
|
}
|
||||||
|
|
||||||
|
let checkSendCompleteUsingTime = 0;
|
||||||
|
const checkSendComplete = async (): Promise<RawMessage> => {
|
||||||
|
if (sentMessage) {
|
||||||
|
if (waitComplete) {
|
||||||
|
if ((await dbUtil.getMsgByLongId(sentMessage.msgId)).sendStatus == 2) {
|
||||||
|
return sentMessage
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return sentMessage
|
||||||
|
}
|
||||||
|
// log(`给${peerUid}发送消息成功`)
|
||||||
|
}
|
||||||
|
checkSendCompleteUsingTime += 500
|
||||||
|
if (checkSendCompleteUsingTime > timeout) {
|
||||||
|
throw ('发送超时')
|
||||||
|
}
|
||||||
|
await sleep(500)
|
||||||
|
return await checkSendComplete()
|
||||||
|
}
|
||||||
|
|
||||||
|
callNTQQApi({
|
||||||
|
methodName: NTQQApiMethod.SEND_MSG,
|
||||||
|
args: [{
|
||||||
|
msgId: "0",
|
||||||
|
peer, msgElements,
|
||||||
|
msgAttributeInfos: new Map(),
|
||||||
|
}, null]
|
||||||
|
}).then()
|
||||||
|
return await checkSendComplete()
|
||||||
|
}
|
||||||
|
|
||||||
|
static async forwardMsg(srcPeer: Peer, destPeer: Peer, msgIds: string[]) {
|
||||||
|
return await callNTQQApi<GeneralCallResult>({
|
||||||
|
methodName: NTQQApiMethod.FORWARD_MSG,
|
||||||
|
args: [
|
||||||
|
{
|
||||||
|
msgIds: msgIds,
|
||||||
|
srcContact: srcPeer,
|
||||||
|
dstContacts: [
|
||||||
|
destPeer
|
||||||
|
],
|
||||||
|
commentElements: [],
|
||||||
|
msgAttributeInfos: new Map()
|
||||||
|
},
|
||||||
|
null,
|
||||||
|
]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
static async multiForwardMsg(srcPeer: Peer, destPeer: Peer, msgIds: string[]) {
|
||||||
|
const msgInfos = msgIds.map(id => {
|
||||||
|
return {msgId: id, senderShowName: selfInfo.nick}
|
||||||
|
})
|
||||||
|
const apiArgs = [
|
||||||
|
{
|
||||||
|
msgInfos,
|
||||||
|
srcContact: srcPeer,
|
||||||
|
dstContact: destPeer,
|
||||||
|
commentElements: [],
|
||||||
|
msgAttributeInfos: new Map()
|
||||||
|
},
|
||||||
|
null,
|
||||||
|
]
|
||||||
|
return await new Promise<RawMessage>((resolve, reject) => {
|
||||||
|
let complete = false
|
||||||
|
setTimeout(() => {
|
||||||
|
if (!complete) {
|
||||||
|
reject("转发消息超时");
|
||||||
|
}
|
||||||
|
}, 5000)
|
||||||
|
registerReceiveHook(ReceiveCmdS.SELF_SEND_MSG, async (payload: { msgRecord: RawMessage }) => {
|
||||||
|
const msg = payload.msgRecord
|
||||||
|
// 需要判断它是转发的消息,并且识别到是当前转发的这一条
|
||||||
|
const arkElement = msg.elements.find(ele => ele.arkElement)
|
||||||
|
if (!arkElement) {
|
||||||
|
// log("收到的不是转发消息")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const forwardData: any = JSON.parse(arkElement.arkElement.bytesData)
|
||||||
|
if (forwardData.app != 'com.tencent.multimsg') {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (msg.peerUid == destPeer.peerUid && msg.senderUid == selfInfo.uid) {
|
||||||
|
complete = true
|
||||||
|
await dbUtil.addMsg(msg)
|
||||||
|
resolve(msg)
|
||||||
|
log('转发消息成功:', payload)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
callNTQQApi<GeneralCallResult>({
|
||||||
|
methodName: NTQQApiMethod.MULTI_FORWARD_MSG,
|
||||||
|
args: apiArgs
|
||||||
|
}).then(result => {
|
||||||
|
log("转发消息结果:", result, apiArgs)
|
||||||
|
if (result.result !== 0) {
|
||||||
|
complete = true;
|
||||||
|
reject("转发消息失败," + JSON.stringify(result));
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
57
src/ntqqapi/api/user.ts
Normal file
57
src/ntqqapi/api/user.ts
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
import {callNTQQApi, GeneralCallResult, NTQQApiClass, NTQQApiMethod} from "../ntcall";
|
||||||
|
import {SelfInfo, User} from "../types";
|
||||||
|
import {ReceiveCmdS} from "../hook";
|
||||||
|
import {uidMaps} from "../../common/data";
|
||||||
|
|
||||||
|
|
||||||
|
export class NTQQUserApi{
|
||||||
|
static async setQQAvatar(filePath: string) {
|
||||||
|
return await callNTQQApi<GeneralCallResult>({
|
||||||
|
methodName: NTQQApiMethod.SET_QQ_AVATAR,
|
||||||
|
args: [{
|
||||||
|
path:filePath
|
||||||
|
}, null],
|
||||||
|
timeoutSecond: 10 // 10秒不一定够
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
static async getSelfInfo() {
|
||||||
|
return await callNTQQApi<SelfInfo>({
|
||||||
|
className: NTQQApiClass.GLOBAL_DATA,
|
||||||
|
methodName: NTQQApiMethod.SELF_INFO, timeoutSecond: 2
|
||||||
|
})
|
||||||
|
}
|
||||||
|
static async getUserInfo(uid: string) {
|
||||||
|
const result = await callNTQQApi<{ profiles: Map<string, User> }>({
|
||||||
|
methodName: NTQQApiMethod.USER_INFO,
|
||||||
|
args: [{force: true, uids: [uid]}, undefined],
|
||||||
|
cbCmd: ReceiveCmdS.USER_INFO
|
||||||
|
})
|
||||||
|
return result.profiles.get(uid)
|
||||||
|
}
|
||||||
|
static async getUserDetailInfo(uid: string) {
|
||||||
|
const result = await callNTQQApi<{ info: User }>({
|
||||||
|
methodName: NTQQApiMethod.USER_DETAIL_INFO,
|
||||||
|
cbCmd: ReceiveCmdS.USER_DETAIL_INFO,
|
||||||
|
afterFirstCmd: false,
|
||||||
|
cmdCB: (payload) => {
|
||||||
|
const success = payload.info.uid == uid
|
||||||
|
// log("get user detail info", success, uid, payload)
|
||||||
|
return success
|
||||||
|
},
|
||||||
|
args: [
|
||||||
|
{
|
||||||
|
uid
|
||||||
|
},
|
||||||
|
null
|
||||||
|
]
|
||||||
|
})
|
||||||
|
const info = result.info
|
||||||
|
if (info?.uin) {
|
||||||
|
uidMaps[info.uid] = info.uin
|
||||||
|
}
|
||||||
|
return info
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
@@ -1,16 +1,22 @@
|
|||||||
import {
|
import {
|
||||||
AtType,
|
AtType,
|
||||||
ElementType, PicType, SendArkElement,
|
ElementType,
|
||||||
|
PicType,
|
||||||
|
SendArkElement,
|
||||||
SendFaceElement,
|
SendFaceElement,
|
||||||
SendFileElement,
|
SendFileElement,
|
||||||
SendPicElement,
|
SendPicElement,
|
||||||
SendPttElement,
|
SendPttElement,
|
||||||
SendReplyElement,
|
SendReplyElement,
|
||||||
SendTextElement
|
SendTextElement,
|
||||||
|
SendVideoElement
|
||||||
} from "./types";
|
} from "./types";
|
||||||
import {NTQQApi} from "./ntcall";
|
import {promises as fs} from "node:fs";
|
||||||
import {encodeSilk, isGIF} from "../common/utils";
|
import ffmpeg from "fluent-ffmpeg"
|
||||||
import * as fs from "node:fs";
|
import {NTQQFileApi} from "./api/file";
|
||||||
|
import {calculateFileMD5, encodeSilk, getVideoInfo, isGIF} from "../common/utils/file";
|
||||||
|
import {log} from "../common/utils/log";
|
||||||
|
import {sleep} from "../common/utils/helper";
|
||||||
|
|
||||||
|
|
||||||
export class SendMsgElementConstructor {
|
export class SendMsgElementConstructor {
|
||||||
@@ -55,9 +61,12 @@ export class SendMsgElementConstructor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static async pic(picPath: string): Promise<SendPicElement> {
|
static async pic(picPath: string, summary: string = ""): Promise<SendPicElement> {
|
||||||
const {md5, fileName, path, fileSize} = await NTQQApi.uploadFile(picPath, ElementType.PIC);
|
const {md5, fileName, path, fileSize} = await NTQQFileApi.uploadFile(picPath, ElementType.PIC);
|
||||||
const imageSize = await NTQQApi.getImageSize(picPath);
|
if (fileSize === 0) {
|
||||||
|
throw "文件异常,大小为0";
|
||||||
|
}
|
||||||
|
const imageSize = await NTQQFileApi.getImageSize(picPath);
|
||||||
const picElement = {
|
const picElement = {
|
||||||
md5HexStr: md5,
|
md5HexStr: md5,
|
||||||
fileSize: fileSize,
|
fileSize: fileSize,
|
||||||
@@ -71,7 +80,7 @@ export class SendMsgElementConstructor {
|
|||||||
fileUuid: "",
|
fileUuid: "",
|
||||||
fileSubId: "",
|
fileSubId: "",
|
||||||
thumbFileSize: 0,
|
thumbFileSize: 0,
|
||||||
summary: "",
|
summary,
|
||||||
};
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -81,14 +90,11 @@ export class SendMsgElementConstructor {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
static async file(filePath: string, showPreview: boolean = false, fileName: string = ""): Promise<SendFileElement> {
|
static async file(filePath: string, fileName: string = ""): Promise<SendFileElement> {
|
||||||
let picHeight = 0;
|
const {md5, fileName: _fileName, path, fileSize} = await NTQQFileApi.uploadFile(filePath, ElementType.FILE);
|
||||||
let picWidth = 0;
|
if (fileSize === 0) {
|
||||||
if (showPreview) {
|
throw "文件异常,大小为0";
|
||||||
picHeight = 1024;
|
|
||||||
picWidth = 768;
|
|
||||||
}
|
}
|
||||||
const {md5, fileName: _fileName, path, fileSize} = await NTQQApi.uploadFile(filePath, ElementType.FILE);
|
|
||||||
let element: SendFileElement = {
|
let element: SendFileElement = {
|
||||||
elementType: ElementType.FILE,
|
elementType: ElementType.FILE,
|
||||||
elementId: "",
|
elementId: "",
|
||||||
@@ -96,25 +102,89 @@ export class SendMsgElementConstructor {
|
|||||||
fileName: fileName || _fileName,
|
fileName: fileName || _fileName,
|
||||||
"filePath": path,
|
"filePath": path,
|
||||||
"fileSize": (fileSize).toString(),
|
"fileSize": (fileSize).toString(),
|
||||||
picHeight,
|
|
||||||
picWidth
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return element;
|
return element;
|
||||||
}
|
}
|
||||||
|
|
||||||
static video(filePath: string): Promise<SendFileElement> {
|
static async video(filePath: string, fileName: string = ""): Promise<SendVideoElement> {
|
||||||
return SendMsgElementConstructor.file(filePath, true);
|
let {fileName: _fileName, path, fileSize, md5} = await NTQQFileApi.uploadFile(filePath, ElementType.VIDEO);
|
||||||
|
if (fileSize === 0) {
|
||||||
|
throw "文件异常,大小为0";
|
||||||
|
}
|
||||||
|
// const videoInfo = await encodeMp4(path);
|
||||||
|
// path = videoInfo.filePath
|
||||||
|
// md5 = videoInfo.md5;
|
||||||
|
// fileSize = videoInfo.size;
|
||||||
|
// log("上传视频", md5, path, fileSize, fileName || _fileName)
|
||||||
|
const pathLib = require("path");
|
||||||
|
let thumb = path.replace(`${pathLib.sep}Ori${pathLib.sep}`, `${pathLib.sep}Thumb${pathLib.sep}`)
|
||||||
|
thumb = pathLib.dirname(thumb)
|
||||||
|
// log("thumb 目录", thumb)
|
||||||
|
const videoInfo = await getVideoInfo(path);
|
||||||
|
log("视频信息", videoInfo)
|
||||||
|
const createThumb = new Promise<string>((resolve, reject) => {
|
||||||
|
const thumbFileName = `${md5}_0.png`
|
||||||
|
ffmpeg(filePath)
|
||||||
|
.on("end", () => {
|
||||||
|
})
|
||||||
|
.on("error", (err) => {
|
||||||
|
reject(err);
|
||||||
|
})
|
||||||
|
.screenshots({
|
||||||
|
timestamps: [0],
|
||||||
|
filename: thumbFileName,
|
||||||
|
folder: thumb,
|
||||||
|
size: videoInfo.width + "x" + videoInfo.height
|
||||||
|
}).on("end", () => {
|
||||||
|
resolve(pathLib.join(thumb, thumbFileName));
|
||||||
|
});
|
||||||
|
})
|
||||||
|
let thumbPath = new Map()
|
||||||
|
const _thumbPath = await createThumb;
|
||||||
|
const thumbSize = (await fs.stat(_thumbPath)).size;
|
||||||
|
// log("生成缩略图", _thumbPath)
|
||||||
|
thumbPath.set(0, _thumbPath)
|
||||||
|
const thumbMd5 = await calculateFileMD5(_thumbPath);
|
||||||
|
let element: SendVideoElement = {
|
||||||
|
elementType: ElementType.VIDEO,
|
||||||
|
elementId: "",
|
||||||
|
videoElement: {
|
||||||
|
fileName: fileName || _fileName,
|
||||||
|
filePath: path,
|
||||||
|
videoMd5: md5,
|
||||||
|
thumbMd5,
|
||||||
|
fileTime: videoInfo.time,
|
||||||
|
thumbPath: thumbPath,
|
||||||
|
thumbSize,
|
||||||
|
thumbWidth: videoInfo.width,
|
||||||
|
thumbHeight: videoInfo.height,
|
||||||
|
fileSize: "" + fileSize,
|
||||||
|
// fileUuid: "",
|
||||||
|
// transferStatus: 0,
|
||||||
|
// progress: 0,
|
||||||
|
// invalidState: 0,
|
||||||
|
// fileSubId: "",
|
||||||
|
// fileBizId: null,
|
||||||
|
// originVideoMd5: "",
|
||||||
|
// fileFormat: 2,
|
||||||
|
// import_rich_media_context: null,
|
||||||
|
// sourceVideoCodecFormat: 2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return element;
|
||||||
}
|
}
|
||||||
|
|
||||||
static async ptt(pttPath: string): Promise<SendPttElement> {
|
static async ptt(pttPath: string): Promise<SendPttElement> {
|
||||||
const {converted, path: silkPath, duration} = await encodeSilk(pttPath);
|
const {converted, path: silkPath, duration} = await encodeSilk(pttPath);
|
||||||
// log("生成语音", silkPath, duration);
|
// log("生成语音", silkPath, duration);
|
||||||
const {md5, fileName, path, fileSize} = await NTQQApi.uploadFile(silkPath, ElementType.PTT);
|
const {md5, fileName, path, fileSize} = await NTQQFileApi.uploadFile(silkPath, ElementType.PTT);
|
||||||
|
if (fileSize === 0) {
|
||||||
|
throw "文件异常,大小为0";
|
||||||
|
}
|
||||||
if (converted) {
|
if (converted) {
|
||||||
fs.unlink(silkPath, () => {
|
fs.unlink(silkPath).then();
|
||||||
});
|
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
elementType: ElementType.PTT,
|
elementType: ElementType.PTT,
|
||||||
|
28
src/ntqqapi/external/ccpoke/index.ts
vendored
Normal file
28
src/ntqqapi/external/ccpoke/index.ts
vendored
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import {log} from "../../../common/utils/log";
|
||||||
|
|
||||||
|
let pokeEngine: any = null
|
||||||
|
|
||||||
|
type PokeHandler = (id: string, isGroup: boolean)=>void
|
||||||
|
|
||||||
|
let pokeRecords: Record<string, number> = {}
|
||||||
|
export function registerPokeHandler(handler: PokeHandler){
|
||||||
|
if(!pokeEngine){
|
||||||
|
try {
|
||||||
|
pokeEngine = require("./ccpoke/poke-win32-x64.node")
|
||||||
|
pokeEngine.performHooks();
|
||||||
|
}catch (e) {
|
||||||
|
log("戳一戳引擎加载失败", e)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pokeEngine.setHandlerForPokeHook((id: string, isGroup: boolean)=>{
|
||||||
|
let existTime = pokeRecords[id]
|
||||||
|
if (existTime){
|
||||||
|
if (Date.now() - existTime < 1500){
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pokeRecords[id] = Date.now()
|
||||||
|
handler(id, isGroup);
|
||||||
|
})
|
||||||
|
}
|
BIN
src/ntqqapi/external/ccpoke/poke-win32-x64.node
vendored
Normal file
BIN
src/ntqqapi/external/ccpoke/poke-win32-x64.node
vendored
Normal file
Binary file not shown.
@@ -1,72 +1,86 @@
|
|||||||
import {type BrowserWindow} from 'electron'
|
import {BrowserWindow} from 'electron';
|
||||||
import {getConfigUtil, log, sleep} from '../common/utils'
|
import {NTQQApiClass} from "./ntcall";
|
||||||
import {NTQQApi, type NTQQApiClass, sendMessagePool} from './ntcall'
|
import {NTQQMsgApi, sendMessagePool} from "./api/msg"
|
||||||
import {type Group, type RawMessage, type User} from './types'
|
import {ChatType, Group, RawMessage, User} from "./types";
|
||||||
import {friends, groups, selfInfo, tempGroupCodeMap} from '../common/data'
|
import {friends, groups, selfInfo, tempGroupCodeMap, uidMaps} from "../common/data";
|
||||||
import {OB11GroupDecreaseEvent} from '../onebot11/event/notice/OB11GroupDecreaseEvent'
|
import {OB11GroupDecreaseEvent} from "../onebot11/event/notice/OB11GroupDecreaseEvent";
|
||||||
import {OB11GroupIncreaseEvent} from '../onebot11/event/notice/OB11GroupIncreaseEvent'
|
import {v4 as uuidv4} from "uuid"
|
||||||
import {v4 as uuidv4} from 'uuid'
|
import {postOB11Event} from "../onebot11/server/postOB11Event";
|
||||||
import {postOB11Event} from '../onebot11/server/postOB11Event'
|
import {getConfigUtil, HOOK_LOG} from "../common/config";
|
||||||
import {HOOK_LOG} from '../common/config'
|
import fs from "fs";
|
||||||
import fs from 'fs'
|
|
||||||
import {dbUtil} from "../common/db";
|
import {dbUtil} from "../common/db";
|
||||||
|
import {NTQQGroupApi} from "./api/group";
|
||||||
|
import {log} from "../common/utils/log";
|
||||||
|
import {sleep} from "../common/utils/helper";
|
||||||
|
|
||||||
export const hookApiCallbacks: Record<string, (apiReturn: any) => void> = {}
|
export let hookApiCallbacks: Record<string, (apiReturn: any) => void> = {}
|
||||||
|
|
||||||
export enum ReceiveCmd {
|
export let ReceiveCmdS = {
|
||||||
UPDATE_MSG = 'nodeIKernelMsgListener/onMsgInfoListUpdate',
|
UPDATE_MSG: "nodeIKernelMsgListener/onMsgInfoListUpdate",
|
||||||
NEW_MSG = 'nodeIKernelMsgListener/onRecvMsg',
|
UPDATE_ACTIVE_MSG: "nodeIKernelMsgListener/onActiveMsgInfoUpdate",
|
||||||
SELF_SEND_MSG = 'nodeIKernelMsgListener/onAddSendMsg',
|
NEW_MSG: `nodeIKernelMsgListener/onRecvMsg`,
|
||||||
USER_INFO = 'nodeIKernelProfileListener/onProfileSimpleChanged',
|
NEW_ACTIVE_MSG: `nodeIKernelMsgListener/onRecvActiveMsg`,
|
||||||
USER_DETAIL_INFO = 'nodeIKernelProfileListener/onProfileDetailInfoChanged',
|
SELF_SEND_MSG: "nodeIKernelMsgListener/onAddSendMsg",
|
||||||
GROUPS = 'nodeIKernelGroupListener/onGroupListUpdate',
|
USER_INFO: "nodeIKernelProfileListener/onProfileSimpleChanged",
|
||||||
GROUPS_UNIX = 'onGroupListUpdate',
|
USER_DETAIL_INFO: "nodeIKernelProfileListener/onProfileDetailInfoChanged",
|
||||||
FRIENDS = 'onBuddyListChange',
|
GROUPS: "nodeIKernelGroupListener/onGroupListUpdate",
|
||||||
MEDIA_DOWNLOAD_COMPLETE = 'nodeIKernelMsgListener/onRichMediaDownloadComplete',
|
GROUPS_UNIX: "onGroupListUpdate",
|
||||||
UNREAD_GROUP_NOTIFY = 'nodeIKernelGroupListener/onGroupNotifiesUnreadCountUpdated',
|
FRIENDS: "onBuddyListChange",
|
||||||
GROUP_NOTIFY = 'nodeIKernelGroupListener/onGroupSingleScreenNotifies',
|
MEDIA_DOWNLOAD_COMPLETE: "nodeIKernelMsgListener/onRichMediaDownloadComplete",
|
||||||
FRIEND_REQUEST = 'nodeIKernelBuddyListener/onBuddyReqChange',
|
UNREAD_GROUP_NOTIFY: "nodeIKernelGroupListener/onGroupNotifiesUnreadCountUpdated",
|
||||||
SELF_STATUS = 'nodeIKernelProfileListener/onSelfStatusChanged',
|
GROUP_NOTIFY: "nodeIKernelGroupListener/onGroupSingleScreenNotifies",
|
||||||
|
FRIEND_REQUEST: "nodeIKernelBuddyListener/onBuddyReqChange",
|
||||||
|
SELF_STATUS: 'nodeIKernelProfileListener/onSelfStatusChanged',
|
||||||
|
CACHE_SCAN_FINISH: "nodeIKernelStorageCleanListener/onFinishScan",
|
||||||
|
MEDIA_UPLOAD_COMPLETE: "nodeIKernelMsgListener/onRichMediaUploadComplete",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type ReceiveCmd = typeof ReceiveCmdS[keyof typeof ReceiveCmdS]
|
||||||
|
|
||||||
interface NTQQApiReturnData<PayloadType = unknown> extends Array<any> {
|
interface NTQQApiReturnData<PayloadType = unknown> extends Array<any> {
|
||||||
0: {
|
0: {
|
||||||
'type': 'request'
|
"type": "request",
|
||||||
'eventName': NTQQApiClass
|
"eventName": NTQQApiClass,
|
||||||
'callbackId'?: string
|
"callbackId"?: string
|
||||||
}
|
},
|
||||||
1:
|
1:
|
||||||
Array<{
|
{
|
||||||
cmdName: ReceiveCmd
|
cmdName: ReceiveCmd,
|
||||||
cmdType: 'event'
|
cmdType: "event",
|
||||||
payload: PayloadType
|
payload: PayloadType
|
||||||
}>
|
}[]
|
||||||
}
|
}
|
||||||
|
|
||||||
const receiveHooks: Array<{
|
let receiveHooks: Array<{
|
||||||
method: ReceiveCmd
|
method: ReceiveCmd[],
|
||||||
hookFunc: ((payload: any) => void | Promise<void>)
|
hookFunc: ((payload: any) => void | Promise<void>)
|
||||||
id: string
|
id: string
|
||||||
}> = []
|
}> = []
|
||||||
|
|
||||||
export function hookNTQQApiReceive(window: BrowserWindow) {
|
export function hookNTQQApiReceive(window: BrowserWindow) {
|
||||||
const originalSend = window.webContents.send
|
const originalSend = window.webContents.send;
|
||||||
const patchSend = (channel: string, ...args: NTQQApiReturnData) => {
|
const patchSend = (channel: string, ...args: NTQQApiReturnData) => {
|
||||||
HOOK_LOG && log(`received ntqq api message: ${channel}`, JSON.stringify(args))
|
try {
|
||||||
|
if (!args[0]?.eventName?.startsWith("ns-LoggerApi")) {
|
||||||
|
HOOK_LOG && log(`received ntqq api message: ${channel}`, JSON.stringify(args))
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
|
||||||
|
}
|
||||||
if (args?.[1] instanceof Array) {
|
if (args?.[1] instanceof Array) {
|
||||||
for (const receiveData of args?.[1]) {
|
for (let receiveData of args?.[1]) {
|
||||||
const ntQQApiMethodName = receiveData.cmdName
|
const ntQQApiMethodName = receiveData.cmdName;
|
||||||
// log(`received ntqq api message: ${channel} ${ntQQApiMethodName}`, JSON.stringify(receiveData))
|
// log(`received ntqq api message: ${channel} ${ntQQApiMethodName}`, JSON.stringify(receiveData))
|
||||||
for (const hook of receiveHooks) {
|
for (let hook of receiveHooks) {
|
||||||
if (hook.method === ntQQApiMethodName) {
|
if (hook.method.includes(ntQQApiMethodName)) {
|
||||||
new Promise((resolve, reject) => {
|
new Promise((resolve, reject) => {
|
||||||
try {
|
try {
|
||||||
const _ = hook.hookFunc(receiveData.payload)
|
let _ = hook.hookFunc(receiveData.payload)
|
||||||
if (hook.hookFunc.constructor.name === 'AsyncFunction') {
|
if (hook.hookFunc.constructor.name === "AsyncFunction") {
|
||||||
(_ as Promise<void>).then()
|
(_ as Promise<void>).then()
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
log('hook error', e, receiveData.payload)
|
log("hook error", e, receiveData.payload)
|
||||||
}
|
}
|
||||||
}).then()
|
}).then()
|
||||||
}
|
}
|
||||||
@@ -75,68 +89,89 @@ export function hookNTQQApiReceive(window: BrowserWindow) {
|
|||||||
}
|
}
|
||||||
if (args[0]?.callbackId) {
|
if (args[0]?.callbackId) {
|
||||||
// log("hookApiCallback", hookApiCallbacks, args)
|
// log("hookApiCallback", hookApiCallbacks, args)
|
||||||
const callbackId = args[0].callbackId
|
const callbackId = args[0].callbackId;
|
||||||
if (hookApiCallbacks[callbackId]) {
|
if (hookApiCallbacks[callbackId]) {
|
||||||
// log("callback found")
|
// log("callback found")
|
||||||
new Promise((resolve, reject) => {
|
new Promise((resolve, reject) => {
|
||||||
hookApiCallbacks[callbackId](args[1])
|
hookApiCallbacks[callbackId](args[1]);
|
||||||
}).then()
|
}).then()
|
||||||
delete hookApiCallbacks[callbackId]
|
delete hookApiCallbacks[callbackId];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return originalSend.call(window.webContents, channel, ...args)
|
return originalSend.call(window.webContents, channel, ...args);
|
||||||
}
|
}
|
||||||
window.webContents.send = patchSend
|
window.webContents.send = patchSend;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function hookNTQQApiCall(window: BrowserWindow) {
|
export function hookNTQQApiCall(window: BrowserWindow) {
|
||||||
// 监听调用NTQQApi
|
// 监听调用NTQQApi
|
||||||
const webContents = window.webContents as any
|
let webContents = window.webContents as any;
|
||||||
const ipc_message_proxy = webContents._events['-ipc-message']?.[0] || webContents._events['-ipc-message']
|
const ipc_message_proxy = webContents._events["-ipc-message"]?.[0] || webContents._events["-ipc-message"];
|
||||||
|
|
||||||
const proxyIpcMsg = new Proxy(ipc_message_proxy, {
|
const proxyIpcMsg = new Proxy(ipc_message_proxy, {
|
||||||
apply(target, thisArg, args) {
|
apply(target, thisArg, args) {
|
||||||
HOOK_LOG && log('call NTQQ api', thisArg, args)
|
try {
|
||||||
return target.apply(thisArg, args)
|
if (args[3][1][0] !== "info") {
|
||||||
}
|
HOOK_LOG && log("call NTQQ api", thisArg, args);
|
||||||
})
|
}
|
||||||
if (webContents._events['-ipc-message']?.[0]) {
|
} catch (e) {
|
||||||
webContents._events['-ipc-message'][0] = proxyIpcMsg
|
|
||||||
|
}
|
||||||
|
return target.apply(thisArg, args);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (webContents._events["-ipc-message"]?.[0]) {
|
||||||
|
webContents._events["-ipc-message"][0] = proxyIpcMsg;
|
||||||
} else {
|
} else {
|
||||||
webContents._events['-ipc-message'] = proxyIpcMsg
|
webContents._events["-ipc-message"] = proxyIpcMsg;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function registerReceiveHook<PayloadType>(method: ReceiveCmd, hookFunc: (payload: PayloadType) => void): string {
|
export function registerReceiveHook<PayloadType>(method: ReceiveCmd | ReceiveCmd[], hookFunc: (payload: PayloadType) => void): string {
|
||||||
const id = uuidv4()
|
const id = uuidv4()
|
||||||
|
if (!Array.isArray(method)) {
|
||||||
|
method = [method]
|
||||||
|
}
|
||||||
receiveHooks.push({
|
receiveHooks.push({
|
||||||
method,
|
method,
|
||||||
hookFunc,
|
hookFunc,
|
||||||
id
|
id
|
||||||
})
|
})
|
||||||
return id
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function removeReceiveHook(id: string) {
|
export function removeReceiveHook(id: string) {
|
||||||
const index = receiveHooks.findIndex(h => h.id === id)
|
const index = receiveHooks.findIndex(h => h.id === id)
|
||||||
receiveHooks.splice(index, 1)
|
receiveHooks.splice(index, 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let activatedGroups: string[] = [];
|
||||||
async function updateGroups(_groups: Group[], needUpdate: boolean = true) {
|
async function updateGroups(_groups: Group[], needUpdate: boolean = true) {
|
||||||
for (const group of _groups) {
|
for (let group of _groups) {
|
||||||
let existGroup = groups.find(g => g.groupCode == group.groupCode)
|
// log("update group", group)
|
||||||
|
if (!activatedGroups.includes(group.groupCode)) {
|
||||||
|
NTQQMsgApi.activateGroupChat(group.groupCode).then((r) => {
|
||||||
|
activatedGroups.push(group.groupCode);
|
||||||
|
// log(`激活群聊天窗口${group.groupName}(${group.groupCode})`, r)
|
||||||
|
// if (r.result !== 0) {
|
||||||
|
// setTimeout(() => NTQQMsgApi.activateGroupChat(group.groupCode).then(r => log(`再次激活群聊天窗口${group.groupName}(${group.groupCode})`, r)), 500);
|
||||||
|
// }else {
|
||||||
|
// }
|
||||||
|
}).catch(log)
|
||||||
|
}
|
||||||
|
let existGroup = groups.find(g => g.groupCode == group.groupCode);
|
||||||
if (existGroup) {
|
if (existGroup) {
|
||||||
Object.assign(existGroup, group)
|
Object.assign(existGroup, group);
|
||||||
} else {
|
} else {
|
||||||
groups.push(group)
|
groups.push(group);
|
||||||
existGroup = group
|
existGroup = group;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (needUpdate) {
|
if (needUpdate) {
|
||||||
const members = await NTQQApi.getGroupMembers(group.groupCode)
|
const members = await NTQQGroupApi.getGroupMembers(group.groupCode);
|
||||||
|
|
||||||
if (members) {
|
if (members) {
|
||||||
existGroup.members = members
|
existGroup.members = members;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -144,83 +179,68 @@ async function updateGroups(_groups: Group[], needUpdate: boolean = true) {
|
|||||||
|
|
||||||
async function processGroupEvent(payload) {
|
async function processGroupEvent(payload) {
|
||||||
try {
|
try {
|
||||||
const newGroupList = payload.groupList
|
const newGroupList = payload.groupList;
|
||||||
for (const group of newGroupList) {
|
for (const group of newGroupList) {
|
||||||
const existGroup = groups.find(g => g.groupCode == group.groupCode)
|
let existGroup = groups.find(g => g.groupCode == group.groupCode);
|
||||||
if (existGroup) {
|
if (existGroup) {
|
||||||
if (existGroup.memberCount > group.memberCount) {
|
if (existGroup.memberCount > group.memberCount) {
|
||||||
const oldMembers = existGroup.members
|
const oldMembers = existGroup.members;
|
||||||
|
|
||||||
await sleep(200) // 如果请求QQ API的速度过快,通常无法正确拉取到最新的群信息,因此这里人为引入一个延时
|
await sleep(200); // 如果请求QQ API的速度过快,通常无法正确拉取到最新的群信息,因此这里人为引入一个延时
|
||||||
const newMembers = await NTQQApi.getGroupMembers(group.groupCode)
|
const newMembers = await NTQQGroupApi.getGroupMembers(group.groupCode);
|
||||||
|
|
||||||
group.members = newMembers
|
group.members = newMembers;
|
||||||
const newMembersSet = new Set<string>() // 建立索引降低时间复杂度
|
const newMembersSet = new Set<string>(); // 建立索引降低时间复杂度
|
||||||
|
|
||||||
for (const member of newMembers) {
|
for (const member of newMembers) {
|
||||||
newMembersSet.add(member.uin)
|
newMembersSet.add(member.uin);
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const member of oldMembers) {
|
for (const member of oldMembers) {
|
||||||
if (!newMembersSet.has(member.uin)) {
|
if (!newMembersSet.has(member.uin)) {
|
||||||
postOB11Event(new OB11GroupDecreaseEvent(group.groupCode, parseInt(member.uin)))
|
postOB11Event(new OB11GroupDecreaseEvent(group.groupCode, parseInt(member.uin)));
|
||||||
break
|
break;
|
||||||
}
|
|
||||||
}
|
|
||||||
} else if (existGroup.memberCount < group.memberCount) {
|
|
||||||
const oldMembers = existGroup.members
|
|
||||||
const oldMembersSet = new Set<string>()
|
|
||||||
for (const member of oldMembers) {
|
|
||||||
oldMembersSet.add(member.uin)
|
|
||||||
}
|
|
||||||
|
|
||||||
await sleep(200)
|
|
||||||
const newMembers = await NTQQApi.getGroupMembers(group.groupCode)
|
|
||||||
|
|
||||||
group.members = newMembers
|
|
||||||
for (const member of newMembers) {
|
|
||||||
if (!oldMembersSet.has(member.uin)) {
|
|
||||||
postOB11Event(new OB11GroupIncreaseEvent(group.groupCode, parseInt(member.uin)))
|
|
||||||
break
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
updateGroups(newGroupList, false).then()
|
updateGroups(newGroupList, false).then();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
updateGroups(payload.groupList).then()
|
updateGroups(payload.groupList).then();
|
||||||
console.log(e)
|
console.log(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
registerReceiveHook<{ groupList: Group[], updateType: number }>(ReceiveCmd.GROUPS, (payload) => {
|
// 群列表变动
|
||||||
|
registerReceiveHook<{ groupList: Group[], updateType: number }>(ReceiveCmdS.GROUPS, (payload) => {
|
||||||
if (payload.updateType != 2) {
|
if (payload.updateType != 2) {
|
||||||
updateGroups(payload.groupList).then()
|
updateGroups(payload.groupList).then();
|
||||||
} else {
|
} else {
|
||||||
if (process.platform == 'win32') {
|
if (process.platform == "win32") {
|
||||||
processGroupEvent(payload).then()
|
processGroupEvent(payload).then();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
registerReceiveHook<{ groupList: Group[], updateType: number }>(ReceiveCmd.GROUPS_UNIX, (payload) => {
|
registerReceiveHook<{ groupList: Group[], updateType: number }>(ReceiveCmdS.GROUPS_UNIX, (payload) => {
|
||||||
if (payload.updateType != 2) {
|
if (payload.updateType != 2) {
|
||||||
updateGroups(payload.groupList).then()
|
updateGroups(payload.groupList).then();
|
||||||
} else {
|
} else {
|
||||||
if (process.platform != 'win32') {
|
if (process.platform != "win32") {
|
||||||
processGroupEvent(payload).then()
|
processGroupEvent(payload).then();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// 好友列表变动
|
||||||
registerReceiveHook<{
|
registerReceiveHook<{
|
||||||
data: Array<{ categoryId: number, categroyName: string, categroyMbCount: number, buddyList: User[] }>
|
data: { categoryId: number, categroyName: string, categroyMbCount: number, buddyList: User[] }[]
|
||||||
}>(ReceiveCmd.FRIENDS, payload => {
|
}>(ReceiveCmdS.FRIENDS, payload => {
|
||||||
for (const fData of payload.data) {
|
for (const fData of payload.data) {
|
||||||
const _friends = fData.buddyList
|
const _friends = fData.buddyList;
|
||||||
for (const friend of _friends) {
|
for (let friend of _friends) {
|
||||||
const existFriend = friends.find(f => f.uin == friend.uin)
|
let existFriend = friends.find(f => f.uin == friend.uin)
|
||||||
if (!existFriend) {
|
if (!existFriend) {
|
||||||
friends.push(friend)
|
friends.push(friend)
|
||||||
} else {
|
} else {
|
||||||
@@ -230,54 +250,81 @@ registerReceiveHook<{
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
registerReceiveHook<{ msgList: RawMessage[] }>(ReceiveCmd.NEW_MSG, (payload) => {
|
registerReceiveHook<{ msgList: Array<RawMessage> }>([ReceiveCmdS.NEW_MSG, ReceiveCmdS.NEW_ACTIVE_MSG], (payload) => {
|
||||||
const {autoDeleteFile, autoDeleteFileSecond} = getConfigUtil().getConfig()
|
// 保存一下uid
|
||||||
for (const message of payload.msgList) {
|
for (const message of payload.msgList) {
|
||||||
// log("收到新消息,push到历史记录", message)
|
const uid = message.senderUid;
|
||||||
dbUtil.addMsg(message).then()
|
const uin = message.senderUin;
|
||||||
// 清理文件
|
if (uid && uin) {
|
||||||
if (!autoDeleteFile) {
|
if (message.chatType === ChatType.temp){
|
||||||
continue
|
dbUtil.getReceivedTempUinMap().then(receivedTempUinMap=>{
|
||||||
|
if (!receivedTempUinMap[uin]){
|
||||||
|
receivedTempUinMap[uin] = uid;
|
||||||
|
dbUtil.setReceivedTempUinMap(receivedTempUinMap)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
uidMaps[uid] = uin;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// 自动清理新消息文件
|
||||||
|
const {autoDeleteFile} = getConfigUtil().getConfig();
|
||||||
|
if (!autoDeleteFile) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for (const message of payload.msgList) {
|
||||||
|
// log("收到新消息,push到历史记录", message.msgId)
|
||||||
|
// dbUtil.addMsg(message).then()
|
||||||
|
// 清理文件
|
||||||
|
|
||||||
for (const msgElement of message.elements) {
|
for (const msgElement of message.elements) {
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
const picPath = msgElement.picElement?.sourcePath
|
const picPath = msgElement.picElement?.sourcePath
|
||||||
|
const picThumbPath = [...msgElement.picElement?.thumbPath.values()]
|
||||||
const pttPath = msgElement.pttElement?.filePath
|
const pttPath = msgElement.pttElement?.filePath
|
||||||
const pathList = [picPath, pttPath]
|
const filePath = msgElement.fileElement?.filePath
|
||||||
|
const videoPath = msgElement.videoElement?.filePath
|
||||||
|
const videoThumbPath: string[] = [...msgElement.videoElement?.thumbPath.values()]
|
||||||
|
const pathList = [picPath, ...picThumbPath, pttPath, filePath, videoPath, ...videoThumbPath]
|
||||||
if (msgElement.picElement) {
|
if (msgElement.picElement) {
|
||||||
pathList.push(...Object.values(msgElement.picElement.thumbPath))
|
pathList.push(...Object.values(msgElement.picElement.thumbPath))
|
||||||
}
|
}
|
||||||
const aioOpGrayTipElement = msgElement.grayTipElement?.aioOpGrayTipElement
|
const aioOpGrayTipElement = msgElement.grayTipElement?.aioOpGrayTipElement
|
||||||
if (aioOpGrayTipElement){
|
if (aioOpGrayTipElement) {
|
||||||
tempGroupCodeMap[aioOpGrayTipElement.peerUid] = aioOpGrayTipElement.fromGrpCodeOfTmpChat;
|
tempGroupCodeMap[aioOpGrayTipElement.peerUid] = aioOpGrayTipElement.fromGrpCodeOfTmpChat;
|
||||||
}
|
}
|
||||||
|
|
||||||
// log("需要清理的文件", pathList);
|
// log("需要清理的文件", pathList);
|
||||||
for (const path of pathList) {
|
for (const path of pathList) {
|
||||||
if (path) {
|
if (path) {
|
||||||
fs.unlink(picPath, () => {
|
fs.unlink(picPath, () => {
|
||||||
log('删除文件成功', path)
|
log("删除文件成功", path)
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, autoDeleteFileSecond * 1000)
|
}, getConfigUtil().getConfig().autoDeleteFileSecond * 1000)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
registerReceiveHook<{ msgRecord: RawMessage }>(ReceiveCmd.SELF_SEND_MSG, ({msgRecord}) => {
|
registerReceiveHook<{ msgRecord: RawMessage }>(ReceiveCmdS.SELF_SEND_MSG, ({msgRecord}) => {
|
||||||
const message = msgRecord
|
const message = msgRecord;
|
||||||
const peerUid = message.peerUid
|
const peerUid = message.peerUid;
|
||||||
// log("收到自己发送成功的消息", Object.keys(sendMessagePool), message);
|
// log("收到自己发送成功的消息", Object.keys(sendMessagePool), message);
|
||||||
|
// log("收到自己发送成功的消息", message.msgId, message.msgSeq);
|
||||||
|
dbUtil.addMsg(message).then()
|
||||||
const sendCallback = sendMessagePool[peerUid]
|
const sendCallback = sendMessagePool[peerUid]
|
||||||
if (sendCallback) {
|
if (sendCallback) {
|
||||||
try {
|
try {
|
||||||
sendCallback(message)
|
sendCallback(message);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
log('receive self msg error', e.stack)
|
log("receive self msg error", e.stack)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
registerReceiveHook<{ info: { status: number } }>(ReceiveCmd.SELF_STATUS, (info) => {
|
registerReceiveHook<{ info: { status: number } }>(ReceiveCmdS.SELF_STATUS, (info) => {
|
||||||
selfInfo.online = info.info.status !== 20
|
selfInfo.online = info.info.status !== 20
|
||||||
})
|
})
|
||||||
|
@@ -1,123 +1,111 @@
|
|||||||
import {ipcMain} from 'electron'
|
import {ipcMain} from "electron";
|
||||||
import {hookApiCallbacks, ReceiveCmd, registerReceiveHook, removeReceiveHook} from './hook'
|
import {hookApiCallbacks, ReceiveCmd, registerReceiveHook, removeReceiveHook} from "./hook";
|
||||||
import {log, sleep} from '../common/utils'
|
|
||||||
import {
|
|
||||||
type ChatType,
|
|
||||||
ElementType,
|
|
||||||
type Friend,
|
|
||||||
type FriendRequest,
|
|
||||||
type Group, GroupMember,
|
|
||||||
type GroupMemberRole,
|
|
||||||
type GroupNotifies,
|
|
||||||
type GroupNotify,
|
|
||||||
type GroupRequestOperateTypes,
|
|
||||||
type RawMessage,
|
|
||||||
type SelfInfo,
|
|
||||||
type SendMessageElement,
|
|
||||||
type User
|
|
||||||
} from './types'
|
|
||||||
import * as fs from 'node:fs'
|
|
||||||
import {friendRequests, groupNotifies, selfInfo} from '../common/data'
|
|
||||||
import {v4 as uuidv4} from 'uuid'
|
|
||||||
import path from 'path'
|
|
||||||
import {dbUtil} from "../common/db";
|
|
||||||
|
|
||||||
interface IPCReceiveEvent {
|
import {v4 as uuidv4} from "uuid"
|
||||||
eventName: string
|
import {log} from "../common/utils/log";
|
||||||
callbackId: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export type IPCReceiveDetail = [
|
|
||||||
{
|
|
||||||
cmdName: NTQQApiMethod
|
|
||||||
payload: unknown
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
export enum NTQQApiClass {
|
export enum NTQQApiClass {
|
||||||
NT_API = 'ns-ntApi',
|
NT_API = "ns-ntApi",
|
||||||
FS_API = 'ns-FsApi',
|
FS_API = "ns-FsApi",
|
||||||
GLOBAL_DATA = 'ns-GlobalDataApi'
|
OS_API = "ns-OsApi",
|
||||||
|
WINDOW_API = "ns-WindowApi",
|
||||||
|
HOTUPDATE_API = "ns-HotUpdateApi",
|
||||||
|
BUSINESS_API = "ns-BusinessApi",
|
||||||
|
GLOBAL_DATA = "ns-GlobalDataApi"
|
||||||
}
|
}
|
||||||
|
|
||||||
export enum NTQQApiMethod {
|
export enum NTQQApiMethod {
|
||||||
LIKE_FRIEND = 'nodeIKernelProfileLikeService/setBuddyProfileLike',
|
RECENT_CONTACT = "nodeIKernelRecentContactService/fetchAndSubscribeABatchOfRecentContact",
|
||||||
SELF_INFO = 'fetchAuthData',
|
ADD_ACTIVE_CHAT = "nodeIKernelMsgService/getAioFirstViewLatestMsgsAndAddActiveChat", // 激活群助手内的聊天窗口,这样才能收到消息
|
||||||
FRIENDS = 'nodeIKernelBuddyService/getBuddyList',
|
ADD_ACTIVE_CHAT_2 = "nodeIKernelMsgService/getMsgsIncludeSelfAndAddActiveChat",
|
||||||
GROUPS = 'nodeIKernelGroupService/getGroupList',
|
LIKE_FRIEND = "nodeIKernelProfileLikeService/setBuddyProfileLike",
|
||||||
GROUP_MEMBER_SCENE = 'nodeIKernelGroupService/createMemberListScene',
|
SELF_INFO = "fetchAuthData",
|
||||||
GROUP_MEMBERS = 'nodeIKernelGroupService/getNextMemberList',
|
FRIENDS = "nodeIKernelBuddyService/getBuddyList",
|
||||||
USER_INFO = 'nodeIKernelProfileService/getUserSimpleInfo',
|
GROUPS = "nodeIKernelGroupService/getGroupList",
|
||||||
USER_DETAIL_INFO = 'nodeIKernelProfileService/getUserDetailInfo',
|
GROUP_MEMBER_SCENE = "nodeIKernelGroupService/createMemberListScene",
|
||||||
FILE_TYPE = 'getFileType',
|
GROUP_MEMBERS = "nodeIKernelGroupService/getNextMemberList",
|
||||||
FILE_MD5 = 'getFileMd5',
|
USER_INFO = "nodeIKernelProfileService/getUserSimpleInfo",
|
||||||
FILE_COPY = 'copyFile',
|
USER_DETAIL_INFO = "nodeIKernelProfileService/getUserDetailInfo",
|
||||||
IMAGE_SIZE = 'getImageSizeFromPath',
|
FILE_TYPE = "getFileType",
|
||||||
FILE_SIZE = 'getFileSize',
|
FILE_MD5 = "getFileMd5",
|
||||||
MEDIA_FILE_PATH = 'nodeIKernelMsgService/getRichMediaFilePathForGuild',
|
FILE_COPY = "copyFile",
|
||||||
RECALL_MSG = 'nodeIKernelMsgService/recallMsg',
|
IMAGE_SIZE = "getImageSizeFromPath",
|
||||||
SEND_MSG = 'nodeIKernelMsgService/sendMsg',
|
FILE_SIZE = "getFileSize",
|
||||||
DOWNLOAD_MEDIA = 'nodeIKernelMsgService/downloadRichMedia',
|
MEDIA_FILE_PATH = "nodeIKernelMsgService/getRichMediaFilePathForGuild",
|
||||||
FORWARD_MSG = "nodeIKernelMsgService/forwardMsgWithComment", // 逐条转发
|
RECALL_MSG = "nodeIKernelMsgService/recallMsg",
|
||||||
MULTI_FORWARD_MSG = 'nodeIKernelMsgService/multiForwardMsgWithComment', // 合并转发
|
SEND_MSG = "nodeIKernelMsgService/sendMsg",
|
||||||
GET_GROUP_NOTICE = 'nodeIKernelGroupService/getSingleScreenNotifies',
|
DOWNLOAD_MEDIA = "nodeIKernelMsgService/downloadRichMedia",
|
||||||
HANDLE_GROUP_REQUEST = 'nodeIKernelGroupService/operateSysNotify',
|
FORWARD_MSG = "nodeIKernelMsgService/forwardMsgWithComment",
|
||||||
QUIT_GROUP = 'nodeIKernelGroupService/quitGroup',
|
MULTI_FORWARD_MSG = "nodeIKernelMsgService/multiForwardMsgWithComment", // 合并转发
|
||||||
|
GET_GROUP_NOTICE = "nodeIKernelGroupService/getSingleScreenNotifies",
|
||||||
|
HANDLE_GROUP_REQUEST = "nodeIKernelGroupService/operateSysNotify",
|
||||||
|
QUIT_GROUP = "nodeIKernelGroupService/quitGroup",
|
||||||
// READ_FRIEND_REQUEST = "nodeIKernelBuddyListener/onDoubtBuddyReqUnreadNumChange"
|
// READ_FRIEND_REQUEST = "nodeIKernelBuddyListener/onDoubtBuddyReqUnreadNumChange"
|
||||||
HANDLE_FRIEND_REQUEST = 'nodeIKernelBuddyService/approvalFriendRequest',
|
HANDLE_FRIEND_REQUEST = "nodeIKernelBuddyService/approvalFriendRequest",
|
||||||
KICK_MEMBER = 'nodeIKernelGroupService/kickMember',
|
KICK_MEMBER = "nodeIKernelGroupService/kickMember",
|
||||||
MUTE_MEMBER = 'nodeIKernelGroupService/setMemberShutUp',
|
MUTE_MEMBER = "nodeIKernelGroupService/setMemberShutUp",
|
||||||
MUTE_GROUP = 'nodeIKernelGroupService/setGroupShutUp',
|
MUTE_GROUP = "nodeIKernelGroupService/setGroupShutUp",
|
||||||
SET_MEMBER_CARD = 'nodeIKernelGroupService/modifyMemberCardName',
|
SET_MEMBER_CARD = "nodeIKernelGroupService/modifyMemberCardName",
|
||||||
SET_MEMBER_ROLE = 'nodeIKernelGroupService/modifyMemberRole',
|
SET_MEMBER_ROLE = "nodeIKernelGroupService/modifyMemberRole",
|
||||||
PUBLISH_GROUP_BULLETIN = 'nodeIKernelGroupService/publishGroupBulletinBulletin',
|
PUBLISH_GROUP_BULLETIN = "nodeIKernelGroupService/publishGroupBulletinBulletin",
|
||||||
SET_GROUP_NAME = 'nodeIKernelGroupService/modifyGroupName',
|
SET_GROUP_NAME = "nodeIKernelGroupService/modifyGroupName",
|
||||||
|
SET_GROUP_TITLE = "nodeIKernelGroupService/modifyMemberSpecialTitle",
|
||||||
|
|
||||||
|
CACHE_SET_SILENCE = 'nodeIKernelStorageCleanService/setSilentScan',
|
||||||
|
CACHE_ADD_SCANNED_PATH = 'nodeIKernelStorageCleanService/addCacheScanedPaths',
|
||||||
|
CACHE_PATH_HOT_UPDATE = 'getHotUpdateCachePath',
|
||||||
|
CACHE_PATH_DESKTOP_TEMP = 'getDesktopTmpPath',
|
||||||
|
CACHE_PATH_SESSION = 'getCleanableAppSessionPathList',
|
||||||
|
CACHE_SCAN = 'nodeIKernelStorageCleanService/scanCache',
|
||||||
|
CACHE_CLEAR = 'nodeIKernelStorageCleanService/clearCacheDataByKeys',
|
||||||
|
|
||||||
|
CACHE_CHAT_GET = 'nodeIKernelStorageCleanService/getChatCacheInfo',
|
||||||
|
CACHE_FILE_GET = 'nodeIKernelStorageCleanService/getFileCacheInfo',
|
||||||
|
CACHE_CHAT_CLEAR = 'nodeIKernelStorageCleanService/clearChatCacheInfo',
|
||||||
|
|
||||||
|
OPEN_EXTRA_WINDOW = 'openExternalWindow',
|
||||||
|
|
||||||
|
SET_QQ_AVATAR = 'nodeIKernelProfileService/setHeader'
|
||||||
}
|
}
|
||||||
|
|
||||||
enum NTQQApiChannel {
|
enum NTQQApiChannel {
|
||||||
IPC_UP_2 = 'IPC_UP_2',
|
IPC_UP_2 = "IPC_UP_2",
|
||||||
IPC_UP_3 = 'IPC_UP_3',
|
IPC_UP_3 = "IPC_UP_3",
|
||||||
IPC_UP_1 = 'IPC_UP_1',
|
IPC_UP_1 = "IPC_UP_1",
|
||||||
}
|
|
||||||
|
|
||||||
export interface Peer {
|
|
||||||
chatType: ChatType
|
|
||||||
peerUid: string // 如果是群聊uid为群号,私聊uid就是加密的字符串
|
|
||||||
guildId?: ''
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface NTQQApiParams {
|
interface NTQQApiParams {
|
||||||
methodName: NTQQApiMethod | string
|
methodName: NTQQApiMethod | string,
|
||||||
className?: NTQQApiClass
|
className?: NTQQApiClass,
|
||||||
channel?: NTQQApiChannel
|
channel?: NTQQApiChannel,
|
||||||
classNameIsRegister?: boolean
|
classNameIsRegister?: boolean
|
||||||
args?: unknown[]
|
args?: unknown[],
|
||||||
cbCmd?: ReceiveCmd | null
|
cbCmd?: ReceiveCmd | null,
|
||||||
cmdCB?: (payload: any) => boolean
|
cmdCB?: (payload: any) => boolean;
|
||||||
afterFirstCmd?: boolean // 是否在methodName调用完之后再去hook cbCmd
|
afterFirstCmd?: boolean, // 是否在methodName调用完之后再去hook cbCmd
|
||||||
timeoutSecond?: number
|
timeoutSecond?: number,
|
||||||
}
|
}
|
||||||
|
|
||||||
async function callNTQQApi<ReturnType>(params: NTQQApiParams) {
|
export function callNTQQApi<ReturnType>(params: NTQQApiParams) {
|
||||||
let {
|
let {
|
||||||
className, methodName, channel, args,
|
className, methodName, channel, args,
|
||||||
cbCmd, timeoutSecond: timeout,
|
cbCmd, timeoutSecond: timeout,
|
||||||
classNameIsRegister, cmdCB, afterFirstCmd
|
classNameIsRegister, cmdCB, afterFirstCmd
|
||||||
} = params
|
} = params;
|
||||||
className = className ?? NTQQApiClass.NT_API
|
className = className ?? NTQQApiClass.NT_API;
|
||||||
channel = channel ?? NTQQApiChannel.IPC_UP_2
|
channel = channel ?? NTQQApiChannel.IPC_UP_2;
|
||||||
args = args ?? []
|
args = args ?? [];
|
||||||
timeout = timeout ?? 5
|
timeout = timeout ?? 5;
|
||||||
afterFirstCmd = afterFirstCmd ?? true
|
afterFirstCmd = afterFirstCmd ?? true;
|
||||||
const uuid = uuidv4()
|
const uuid = uuidv4();
|
||||||
// log("callNTQQApi", channel, className, methodName, args, uuid)
|
// log("callNTQQApi", channel, className, methodName, args, uuid)
|
||||||
return await new Promise((resolve: (data: ReturnType) => void, reject) => {
|
return new Promise((resolve: (data: ReturnType) => void, reject) => {
|
||||||
// log("callNTQQApiPromise", channel, className, methodName, args, uuid)
|
// log("callNTQQApiPromise", channel, className, methodName, args, uuid)
|
||||||
const _timeout = timeout * 1000
|
const _timeout = timeout * 1000
|
||||||
let success = false
|
let success = false
|
||||||
let eventName = className + '-' + channel[channel.length - 1]
|
let eventName = className + "-" + channel[channel.length - 1];
|
||||||
if (classNameIsRegister) {
|
if (classNameIsRegister) {
|
||||||
eventName += '-register'
|
eventName += "-register";
|
||||||
}
|
}
|
||||||
const apiArgs = [methodName, ...args]
|
const apiArgs = [methodName, ...args]
|
||||||
if (!cbCmd) {
|
if (!cbCmd) {
|
||||||
@@ -125,40 +113,40 @@ async function callNTQQApi<ReturnType>(params: NTQQApiParams) {
|
|||||||
hookApiCallbacks[uuid] = (r: ReturnType) => {
|
hookApiCallbacks[uuid] = (r: ReturnType) => {
|
||||||
success = true
|
success = true
|
||||||
resolve(r)
|
resolve(r)
|
||||||
}
|
};
|
||||||
} else {
|
} else {
|
||||||
// 这里的callback比较特殊,QQ后端先返回是否调用成功,再返回一条结果数据
|
// 这里的callback比较特殊,QQ后端先返回是否调用成功,再返回一条结果数据
|
||||||
const secondCallback = () => {
|
const secondCallback = () => {
|
||||||
const hookId = registerReceiveHook<ReturnType>(cbCmd, (payload) => {
|
const hookId = registerReceiveHook<ReturnType>(cbCmd, (payload) => {
|
||||||
// log(methodName, "second callback", cbCmd, payload, cmdCB);
|
// log(methodName, "second callback", cbCmd, payload, cmdCB);
|
||||||
if (cmdCB) {
|
if (!!cmdCB) {
|
||||||
if (cmdCB(payload)) {
|
if (cmdCB(payload)) {
|
||||||
removeReceiveHook(hookId)
|
removeReceiveHook(hookId);
|
||||||
success = true
|
success = true
|
||||||
resolve(payload)
|
resolve(payload);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
removeReceiveHook(hookId)
|
removeReceiveHook(hookId);
|
||||||
success = true
|
success = true
|
||||||
resolve(payload)
|
resolve(payload);
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
!afterFirstCmd && secondCallback()
|
!afterFirstCmd && secondCallback();
|
||||||
hookApiCallbacks[uuid] = (result: GeneralCallResult) => {
|
hookApiCallbacks[uuid] = (result: GeneralCallResult) => {
|
||||||
log(`${methodName} callback`, result)
|
log(`${methodName} callback`, result)
|
||||||
if (result?.result == 0 || result === undefined) {
|
if (result?.result == 0 || result === undefined) {
|
||||||
afterFirstCmd && secondCallback()
|
afterFirstCmd && secondCallback();
|
||||||
} else {
|
} else {
|
||||||
success = true
|
success = true
|
||||||
reject(`ntqq api call failed, ${result.errMsg}`)
|
reject(`ntqq api call failed, ${result.errMsg}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
// log("ntqq api timeout", success, channel, className, methodName)
|
// log("ntqq api timeout", success, channel, className, methodName)
|
||||||
if (!success) {
|
if (!success) {
|
||||||
log(`ntqq api timeout ${channel}, ${eventName}, ${methodName}`, apiArgs)
|
log(`ntqq api timeout ${channel}, ${eventName}, ${methodName}`, apiArgs);
|
||||||
reject(`ntqq api timeout ${channel}, ${eventName}, ${methodName}, ${apiArgs}`)
|
reject(`ntqq api timeout ${channel}, ${eventName}, ${methodName}, ${apiArgs}`)
|
||||||
}
|
}
|
||||||
}, _timeout)
|
}, _timeout)
|
||||||
@@ -172,544 +160,22 @@ async function callNTQQApi<ReturnType>(params: NTQQApiParams) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
export const sendMessagePool: Record<string, ((sendSuccessMsg: RawMessage) => void) | null> = {}// peerUid: callbackFunnc
|
|
||||||
|
|
||||||
interface GeneralCallResult {
|
export interface GeneralCallResult {
|
||||||
result: number // 0: success
|
result: number, // 0: success
|
||||||
errMsg: string
|
errMsg: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export class NTQQApi {
|
export class NTQQApi {
|
||||||
// static likeFriend = defineNTQQApi<void>(NTQQApiChannel.IPC_UP_2, NTQQApiClass.NT_API, NTQQApiMethod.LIKE_FRIEND)
|
static async call(className: NTQQApiClass, cmdName: string, args: any[],) {
|
||||||
static async likeFriend(uid: string, count = 1) {
|
|
||||||
return await callNTQQApi<GeneralCallResult>({
|
return await callNTQQApi<GeneralCallResult>({
|
||||||
methodName: NTQQApiMethod.LIKE_FRIEND,
|
className,
|
||||||
args: [{
|
methodName: cmdName,
|
||||||
doLikeUserInfo: {
|
|
||||||
friendUid: uid,
|
|
||||||
sourceId: 71,
|
|
||||||
doLikeCount: count,
|
|
||||||
doLikeTollCount: 0
|
|
||||||
}
|
|
||||||
}, null]
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
static async getSelfInfo() {
|
|
||||||
return await callNTQQApi<SelfInfo>({
|
|
||||||
className: NTQQApiClass.GLOBAL_DATA,
|
|
||||||
// channel: NTQQApiChannel.IPC_UP_3,
|
|
||||||
methodName: NTQQApiMethod.SELF_INFO,
|
|
||||||
timeoutSecond: 2
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
static async getUserInfo(uid: string) {
|
|
||||||
const result = await callNTQQApi<{ profiles: Map<string, User> }>({
|
|
||||||
methodName: NTQQApiMethod.USER_INFO,
|
|
||||||
args: [{force: true, uids: [uid]}, undefined],
|
|
||||||
cbCmd: ReceiveCmd.USER_INFO
|
|
||||||
})
|
|
||||||
return result.profiles.get(uid)
|
|
||||||
}
|
|
||||||
|
|
||||||
static async getUserDetailInfo(uid: string) {
|
|
||||||
const result = await callNTQQApi<{ info: User }>({
|
|
||||||
methodName: NTQQApiMethod.USER_DETAIL_INFO,
|
|
||||||
cbCmd: ReceiveCmd.USER_DETAIL_INFO,
|
|
||||||
afterFirstCmd: false,
|
|
||||||
cmdCB: (payload) => {
|
|
||||||
const success = payload.info.uid == uid
|
|
||||||
// log("get user detail info", success, uid, payload)
|
|
||||||
return success
|
|
||||||
},
|
|
||||||
args: [
|
args: [
|
||||||
{
|
...args,
|
||||||
uid
|
|
||||||
},
|
|
||||||
null
|
|
||||||
]
|
|
||||||
})
|
|
||||||
return result.info
|
|
||||||
}
|
|
||||||
|
|
||||||
static async getFriends(forced = false) {
|
|
||||||
const data = await callNTQQApi<{
|
|
||||||
data: Array<{
|
|
||||||
categoryId: number
|
|
||||||
categroyName: string
|
|
||||||
categroyMbCount: number
|
|
||||||
buddyList: Friend[]
|
|
||||||
}>
|
|
||||||
}>(
|
|
||||||
{
|
|
||||||
methodName: NTQQApiMethod.FRIENDS,
|
|
||||||
args: [{force_update: forced}, undefined],
|
|
||||||
cbCmd: ReceiveCmd.FRIENDS
|
|
||||||
})
|
|
||||||
const _friends: Friend[] = []
|
|
||||||
for (const fData of data.data) {
|
|
||||||
_friends.push(...fData.buddyList)
|
|
||||||
}
|
|
||||||
return _friends
|
|
||||||
}
|
|
||||||
|
|
||||||
static async getGroups(forced = false) {
|
|
||||||
let cbCmd = ReceiveCmd.GROUPS
|
|
||||||
if (process.platform != 'win32') {
|
|
||||||
cbCmd = ReceiveCmd.GROUPS_UNIX
|
|
||||||
}
|
|
||||||
const result = await callNTQQApi<{
|
|
||||||
updateType: number
|
|
||||||
groupList: Group[]
|
|
||||||
}>({methodName: NTQQApiMethod.GROUPS, args: [{force_update: forced}, undefined], cbCmd})
|
|
||||||
return result.groupList
|
|
||||||
}
|
|
||||||
|
|
||||||
static async getGroupMembers(groupQQ: string, num = 3000): Promise<GroupMember[]> {
|
|
||||||
const sceneId = await callNTQQApi({
|
|
||||||
methodName: NTQQApiMethod.GROUP_MEMBER_SCENE,
|
|
||||||
args: [{
|
|
||||||
groupCode: groupQQ,
|
|
||||||
scene: 'groupMemberList_MainWindow'
|
|
||||||
}]
|
|
||||||
})
|
|
||||||
// log("get group member sceneId", sceneId);
|
|
||||||
try {
|
|
||||||
const result = await callNTQQApi<{
|
|
||||||
result: { infos: any }
|
|
||||||
}>({
|
|
||||||
methodName: NTQQApiMethod.GROUP_MEMBERS,
|
|
||||||
args: [{
|
|
||||||
sceneId,
|
|
||||||
num
|
|
||||||
},
|
|
||||||
null
|
|
||||||
]
|
|
||||||
})
|
|
||||||
// log("members info", typeof result.result.infos, Object.keys(result.result.infos))
|
|
||||||
const values = result.result.infos.values()
|
|
||||||
|
|
||||||
const members: GroupMember[] = Array.from(values)
|
|
||||||
for (const member of members) {
|
|
||||||
// uidMaps[member.uid] = member.uin;
|
|
||||||
}
|
|
||||||
// log(uidMaps);
|
|
||||||
// log("members info", values);
|
|
||||||
log(`get group ${groupQQ} members success`)
|
|
||||||
return members
|
|
||||||
} catch (e) {
|
|
||||||
log(`get group ${groupQQ} members failed`, e)
|
|
||||||
return []
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static async getFileType(filePath: string) {
|
|
||||||
return await callNTQQApi<{ ext: string }>({
|
|
||||||
className: NTQQApiClass.FS_API, methodName: NTQQApiMethod.FILE_TYPE, args: [filePath]
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
static async getFileMd5(filePath: string) {
|
|
||||||
return await callNTQQApi<string>({
|
|
||||||
className: NTQQApiClass.FS_API,
|
|
||||||
methodName: NTQQApiMethod.FILE_MD5,
|
|
||||||
args: [filePath]
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
static async copyFile(filePath: string, destPath: string) {
|
|
||||||
return await callNTQQApi<string>({
|
|
||||||
className: NTQQApiClass.FS_API,
|
|
||||||
methodName: NTQQApiMethod.FILE_COPY,
|
|
||||||
args: [{
|
|
||||||
fromPath: filePath,
|
|
||||||
toPath: destPath
|
|
||||||
}]
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
static async getImageSize(filePath: string) {
|
|
||||||
return await callNTQQApi<{ width: number, height: number }>({
|
|
||||||
className: NTQQApiClass.FS_API, methodName: NTQQApiMethod.IMAGE_SIZE, args: [filePath]
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
static async getFileSize(filePath: string) {
|
|
||||||
return await callNTQQApi<number>({
|
|
||||||
className: NTQQApiClass.FS_API, methodName: NTQQApiMethod.FILE_SIZE, args: [filePath]
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// 上传文件到QQ的文件夹
|
|
||||||
static async uploadFile(filePath: string, elementType: ElementType = ElementType.PIC) {
|
|
||||||
const md5 = await NTQQApi.getFileMd5(filePath)
|
|
||||||
let ext = (await NTQQApi.getFileType(filePath))?.ext
|
|
||||||
if (ext) {
|
|
||||||
ext = '.' + ext
|
|
||||||
} else {
|
|
||||||
ext = ''
|
|
||||||
}
|
|
||||||
let fileName = `${path.basename(filePath)}`
|
|
||||||
if (!fileName.includes('.')) {
|
|
||||||
fileName += ext
|
|
||||||
}
|
|
||||||
const mediaPath = await callNTQQApi<string>({
|
|
||||||
methodName: NTQQApiMethod.MEDIA_FILE_PATH,
|
|
||||||
args: [{
|
|
||||||
path_info: {
|
|
||||||
md5HexStr: md5,
|
|
||||||
fileName,
|
|
||||||
elementType,
|
|
||||||
elementSubType: 0,
|
|
||||||
thumbSize: 0,
|
|
||||||
needCreate: true,
|
|
||||||
downloadType: 1,
|
|
||||||
file_uuid: ''
|
|
||||||
}
|
|
||||||
}]
|
|
||||||
})
|
|
||||||
log('media path', mediaPath)
|
|
||||||
await NTQQApi.copyFile(filePath, mediaPath)
|
|
||||||
const fileSize = await NTQQApi.getFileSize(filePath)
|
|
||||||
return {
|
|
||||||
md5,
|
|
||||||
fileName,
|
|
||||||
path: mediaPath,
|
|
||||||
fileSize
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static async downloadMedia(msgId: string, chatType: ChatType, peerUid: string, elementId: string, thumbPath: string, sourcePath: string) {
|
|
||||||
// 用于下载收到的消息中的图片等
|
|
||||||
if (fs.existsSync(sourcePath)) {
|
|
||||||
return sourcePath
|
|
||||||
}
|
|
||||||
const apiParams = [
|
|
||||||
{
|
|
||||||
getReq: {
|
|
||||||
msgId,
|
|
||||||
chatType,
|
|
||||||
peerUid,
|
|
||||||
elementId,
|
|
||||||
thumbSize: 0,
|
|
||||||
downloadType: 1,
|
|
||||||
filePath: thumbPath
|
|
||||||
}
|
|
||||||
},
|
|
||||||
undefined
|
|
||||||
]
|
|
||||||
// log("需要下载media", sourcePath);
|
|
||||||
await callNTQQApi({
|
|
||||||
methodName: NTQQApiMethod.DOWNLOAD_MEDIA,
|
|
||||||
args: apiParams,
|
|
||||||
cbCmd: ReceiveCmd.MEDIA_DOWNLOAD_COMPLETE,
|
|
||||||
cmdCB: (payload: { notifyInfo: { filePath: string } }) => {
|
|
||||||
// log("media 下载完成判断", payload.notifyInfo.filePath, sourcePath);
|
|
||||||
return payload.notifyInfo.filePath == sourcePath
|
|
||||||
}
|
|
||||||
})
|
|
||||||
return sourcePath
|
|
||||||
}
|
|
||||||
|
|
||||||
static async recallMsg(peer: Peer, msgIds: string[]) {
|
|
||||||
return await callNTQQApi({
|
|
||||||
methodName: NTQQApiMethod.RECALL_MSG,
|
|
||||||
args: [{
|
|
||||||
peer,
|
|
||||||
msgIds
|
|
||||||
}, null]
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
static async sendMsg(peer: Peer, msgElements: SendMessageElement[], waitComplete = false, timeout = 10000) {
|
|
||||||
const peerUid = peer.peerUid
|
|
||||||
|
|
||||||
// 等待上一个相同的peer发送完
|
|
||||||
let checkLastSendUsingTime = 0
|
|
||||||
const waitLastSend = async () => {
|
|
||||||
if (checkLastSendUsingTime > timeout) {
|
|
||||||
throw ('发送超时')
|
|
||||||
}
|
|
||||||
const lastSending = sendMessagePool[peer.peerUid]
|
|
||||||
if (lastSending) {
|
|
||||||
// log("有正在发送的消息,等待中...")
|
|
||||||
await sleep(500)
|
|
||||||
checkLastSendUsingTime += 500
|
|
||||||
return await waitLastSend()
|
|
||||||
} else {
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
await waitLastSend()
|
|
||||||
|
|
||||||
let sentMessage: RawMessage = null
|
|
||||||
sendMessagePool[peerUid] = async (rawMessage: RawMessage) => {
|
|
||||||
delete sendMessagePool[peerUid]
|
|
||||||
sentMessage = rawMessage
|
|
||||||
}
|
|
||||||
|
|
||||||
let checkSendCompleteUsingTime = 0
|
|
||||||
const checkSendComplete = async (): Promise<RawMessage> => {
|
|
||||||
if (sentMessage) {
|
|
||||||
if (waitComplete) {
|
|
||||||
if ((await dbUtil.getMsgByLongId(sentMessage.msgId)).sendStatus == 2) {
|
|
||||||
return sentMessage
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else{
|
|
||||||
return sentMessage
|
|
||||||
}
|
|
||||||
// log(`给${peerUid}发送消息成功`)
|
|
||||||
}
|
|
||||||
checkSendCompleteUsingTime += 500
|
|
||||||
if (checkSendCompleteUsingTime > timeout) {
|
|
||||||
throw ('发送超时')
|
|
||||||
}
|
|
||||||
await sleep(500)
|
|
||||||
return await checkSendComplete()
|
|
||||||
}
|
|
||||||
|
|
||||||
callNTQQApi({
|
|
||||||
methodName: NTQQApiMethod.SEND_MSG,
|
|
||||||
args: [{
|
|
||||||
msgId: '0',
|
|
||||||
peer,
|
|
||||||
msgElements,
|
|
||||||
msgAttributeInfos: new Map()
|
|
||||||
}, null]
|
|
||||||
}).then()
|
|
||||||
return await checkSendComplete()
|
|
||||||
}
|
|
||||||
|
|
||||||
static async forwardMsg(srcPeer: Peer, destPeer: Peer, msgIds: string[]) {
|
|
||||||
return await callNTQQApi<GeneralCallResult>({
|
|
||||||
methodName: NTQQApiMethod.FORWARD_MSG,
|
|
||||||
args:[
|
|
||||||
{
|
|
||||||
msgIds: msgIds,
|
|
||||||
srcContact: srcPeer,
|
|
||||||
dstContacts: [
|
|
||||||
destPeer
|
|
||||||
],
|
|
||||||
commentElements: [],
|
|
||||||
msgAttributeInfos: new Map()
|
|
||||||
},
|
|
||||||
null,
|
|
||||||
]
|
|
||||||
})
|
|
||||||
|
|
||||||
}
|
|
||||||
static async multiForwardMsg(srcPeer: Peer, destPeer: Peer, msgIds: string[]) {
|
|
||||||
const msgInfos = msgIds.map(id => {
|
|
||||||
return {msgId: id, senderShowName: selfInfo.nick}
|
|
||||||
})
|
|
||||||
const apiArgs = [
|
|
||||||
{
|
|
||||||
msgInfos,
|
|
||||||
srcContact: srcPeer,
|
|
||||||
dstContact: destPeer,
|
|
||||||
commentElements: [],
|
|
||||||
msgAttributeInfos: new Map()
|
|
||||||
},
|
|
||||||
null
|
|
||||||
]
|
|
||||||
return await new Promise<RawMessage>((resolve, reject) => {
|
|
||||||
let complete = false
|
|
||||||
setTimeout(() => {
|
|
||||||
if (!complete) {
|
|
||||||
reject('转发消息超时')
|
|
||||||
}
|
|
||||||
}, 5000)
|
|
||||||
registerReceiveHook(ReceiveCmd.SELF_SEND_MSG, async (payload: { msgRecord: RawMessage }) => {
|
|
||||||
const msg = payload.msgRecord
|
|
||||||
// 需要判断它是转发的消息,并且识别到是当前转发的这一条
|
|
||||||
const arkElement = msg.elements.find(ele => ele.arkElement)
|
|
||||||
if (!arkElement) {
|
|
||||||
// log("收到的不是转发消息")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
const forwardData: any = JSON.parse(arkElement.arkElement.bytesData)
|
|
||||||
if (forwardData.app != 'com.tencent.multimsg') {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (msg.peerUid == destPeer.peerUid && msg.senderUid == selfInfo.uid) {
|
|
||||||
complete = true
|
|
||||||
await dbUtil.addMsg(msg)
|
|
||||||
resolve(msg)
|
|
||||||
log('转发消息成功:', payload)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
callNTQQApi<GeneralCallResult>({
|
|
||||||
methodName: NTQQApiMethod.MULTI_FORWARD_MSG,
|
|
||||||
args: apiArgs
|
|
||||||
}).then(result => {
|
|
||||||
log('转发消息结果:', result, apiArgs)
|
|
||||||
if (result.result !== 0) {
|
|
||||||
complete = true
|
|
||||||
reject('转发消息失败,' + JSON.stringify(result))
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
static async getGroupNotifies() {
|
|
||||||
// 获取管理员变更
|
|
||||||
// 加群通知,退出通知,需要管理员权限
|
|
||||||
callNTQQApi<GeneralCallResult>({
|
|
||||||
methodName: ReceiveCmd.GROUP_NOTIFY,
|
|
||||||
classNameIsRegister: true
|
|
||||||
}).then()
|
|
||||||
return await callNTQQApi<GroupNotifies>({
|
|
||||||
methodName: NTQQApiMethod.GET_GROUP_NOTICE,
|
|
||||||
cbCmd: ReceiveCmd.GROUP_NOTIFY,
|
|
||||||
afterFirstCmd: false,
|
|
||||||
args: [
|
|
||||||
{doubt: false, startSeq: '', number: 14},
|
|
||||||
null
|
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
static async handleGroupRequest(seq: string, operateType: GroupRequestOperateTypes, reason?: string) {
|
}
|
||||||
const notify: GroupNotify = groupNotifies[seq]
|
|
||||||
if (!notify) {
|
|
||||||
throw `${seq}对应的加群通知不存在`
|
|
||||||
}
|
|
||||||
delete groupNotifies[seq]
|
|
||||||
return await callNTQQApi<GeneralCallResult>({
|
|
||||||
methodName: NTQQApiMethod.HANDLE_GROUP_REQUEST,
|
|
||||||
args: [
|
|
||||||
{
|
|
||||||
doubt: false,
|
|
||||||
operateMsg: {
|
|
||||||
operateType, // 2 拒绝
|
|
||||||
targetMsg: {
|
|
||||||
seq, // 通知序列号
|
|
||||||
type: notify.type,
|
|
||||||
groupCode: notify.group.groupCode,
|
|
||||||
postscript: reason
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
null
|
|
||||||
]
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
static async quitGroup(groupQQ: string) {
|
|
||||||
await callNTQQApi<GeneralCallResult>({
|
|
||||||
methodName: NTQQApiMethod.QUIT_GROUP,
|
|
||||||
args: [
|
|
||||||
{groupCode: groupQQ},
|
|
||||||
null
|
|
||||||
]
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
static async handleFriendRequest(sourceId: number, accept: boolean) {
|
|
||||||
const request: FriendRequest = friendRequests[sourceId]
|
|
||||||
if (!request) {
|
|
||||||
throw `sourceId ${sourceId}, 对应的好友请求不存在`
|
|
||||||
}
|
|
||||||
const result = await callNTQQApi<GeneralCallResult>({
|
|
||||||
methodName: NTQQApiMethod.HANDLE_FRIEND_REQUEST,
|
|
||||||
args: [
|
|
||||||
{
|
|
||||||
approvalInfo: {
|
|
||||||
friendUid: request.friendUid,
|
|
||||||
reqTime: request.reqTime,
|
|
||||||
accept
|
|
||||||
}
|
|
||||||
}
|
|
||||||
]
|
|
||||||
})
|
|
||||||
delete friendRequests[sourceId]
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
static async kickMember(groupQQ: string, kickUids: string[], refuseForever: boolean = false, kickReason: string = '') {
|
|
||||||
return await callNTQQApi<GeneralCallResult>(
|
|
||||||
{
|
|
||||||
methodName: NTQQApiMethod.KICK_MEMBER,
|
|
||||||
args: [
|
|
||||||
{
|
|
||||||
groupCode: groupQQ,
|
|
||||||
kickUids,
|
|
||||||
refuseForever,
|
|
||||||
kickReason
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
static async banMember(groupQQ: string, memList: Array<{ uid: string, timeStamp: number }>) {
|
|
||||||
// timeStamp为秒数, 0为解除禁言
|
|
||||||
return await callNTQQApi<GeneralCallResult>(
|
|
||||||
{
|
|
||||||
methodName: NTQQApiMethod.MUTE_MEMBER,
|
|
||||||
args: [
|
|
||||||
{
|
|
||||||
groupCode: groupQQ,
|
|
||||||
memList
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
static async banGroup(groupQQ: string, shutUp: boolean) {
|
|
||||||
return await callNTQQApi<GeneralCallResult>({
|
|
||||||
methodName: NTQQApiMethod.MUTE_GROUP,
|
|
||||||
args: [
|
|
||||||
{
|
|
||||||
groupCode: groupQQ,
|
|
||||||
shutUp
|
|
||||||
}, null
|
|
||||||
]
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
static async setMemberCard(groupQQ: string, memberUid: string, cardName: string) {
|
|
||||||
return await callNTQQApi<GeneralCallResult>({
|
|
||||||
methodName: NTQQApiMethod.SET_MEMBER_CARD,
|
|
||||||
args: [
|
|
||||||
{
|
|
||||||
groupCode: groupQQ,
|
|
||||||
uid: memberUid,
|
|
||||||
cardName
|
|
||||||
}, null
|
|
||||||
]
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
static async setMemberRole(groupQQ: string, memberUid: string, role: GroupMemberRole) {
|
|
||||||
return await callNTQQApi<GeneralCallResult>({
|
|
||||||
methodName: NTQQApiMethod.SET_MEMBER_ROLE,
|
|
||||||
args: [
|
|
||||||
{
|
|
||||||
groupCode: groupQQ,
|
|
||||||
uid: memberUid,
|
|
||||||
role
|
|
||||||
}, null
|
|
||||||
]
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
static async setGroupName(groupQQ: string, groupName: string) {
|
|
||||||
return await callNTQQApi<GeneralCallResult>({
|
|
||||||
methodName: NTQQApiMethod.SET_GROUP_NAME,
|
|
||||||
args: [
|
|
||||||
{
|
|
||||||
groupCode: groupQQ,
|
|
||||||
groupName
|
|
||||||
}, null
|
|
||||||
]
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
static publishGroupBulletin(groupQQ: string, title: string, content: string) {
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
65
src/ntqqapi/types/cache.ts
Normal file
65
src/ntqqapi/types/cache.ts
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
import {ChatType} from "./msg";
|
||||||
|
|
||||||
|
export interface CacheScanResult {
|
||||||
|
result: number,
|
||||||
|
size: [ // 单位为字节
|
||||||
|
string, // 系统总存储空间
|
||||||
|
string, // 系统可用存储空间
|
||||||
|
string, // 系统已用存储空间
|
||||||
|
string, // QQ总大小
|
||||||
|
string, // 「聊天与文件」大小
|
||||||
|
string, // 未知
|
||||||
|
string, // 「缓存数据」大小
|
||||||
|
string, // 「其他数据」大小
|
||||||
|
string, // 未知
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ChatCacheList {
|
||||||
|
pageCount: number,
|
||||||
|
infos: ChatCacheListItem[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ChatCacheListItem {
|
||||||
|
chatType: ChatType,
|
||||||
|
basicChatCacheInfo: ChatCacheListItemBasic,
|
||||||
|
guildChatCacheInfo: unknown[] // TODO: 没用过频道所以不知道这里边的详细内容
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ChatCacheListItemBasic {
|
||||||
|
chatSize: string,
|
||||||
|
chatTime: string,
|
||||||
|
uid: string,
|
||||||
|
uin: string,
|
||||||
|
remarkName: string,
|
||||||
|
nickName: string,
|
||||||
|
chatType?: ChatType,
|
||||||
|
isChecked?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum CacheFileType {
|
||||||
|
IMAGE = 0,
|
||||||
|
VIDEO = 1,
|
||||||
|
AUDIO = 2,
|
||||||
|
DOCUMENT = 3,
|
||||||
|
OTHER = 4,
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CacheFileList {
|
||||||
|
infos: CacheFileListItem[],
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CacheFileListItem {
|
||||||
|
fileSize: string,
|
||||||
|
fileTime: string,
|
||||||
|
fileKey: string,
|
||||||
|
elementId: string,
|
||||||
|
elementIdStr: string,
|
||||||
|
fileType: CacheFileType,
|
||||||
|
path: string,
|
||||||
|
fileName: string,
|
||||||
|
senderId: string,
|
||||||
|
previewPath: string,
|
||||||
|
senderName: string,
|
||||||
|
isChecked?: boolean,
|
||||||
|
}
|
55
src/ntqqapi/types/group.ts
Normal file
55
src/ntqqapi/types/group.ts
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
import {QQLevel, Sex} from "./user";
|
||||||
|
|
||||||
|
export interface Group {
|
||||||
|
groupCode: string,
|
||||||
|
maxMember: number,
|
||||||
|
memberCount: number,
|
||||||
|
groupName: string,
|
||||||
|
groupStatus: 0,
|
||||||
|
memberRole: 2,
|
||||||
|
isTop: boolean,
|
||||||
|
toppedTimestamp: "0",
|
||||||
|
privilegeFlag: number, //65760
|
||||||
|
isConf: boolean,
|
||||||
|
hasModifyConfGroupFace: boolean,
|
||||||
|
hasModifyConfGroupName: boolean,
|
||||||
|
remarkName: string,
|
||||||
|
hasMemo: boolean,
|
||||||
|
groupShutupExpireTime: string, //"0",
|
||||||
|
personShutupExpireTime: string, //"0",
|
||||||
|
discussToGroupUin: string, //"0",
|
||||||
|
discussToGroupMaxMsgSeq: number,
|
||||||
|
discussToGroupTime: number,
|
||||||
|
groupFlagExt: number, //1073938496,
|
||||||
|
authGroupType: number, //0,
|
||||||
|
groupCreditLevel: number, //0,
|
||||||
|
groupFlagExt3: number, //0,
|
||||||
|
groupOwnerId: {
|
||||||
|
"memberUin": string, //"0",
|
||||||
|
"memberUid": string, //"u_fbf8N7aeuZEnUiJAbQ9R8Q"
|
||||||
|
},
|
||||||
|
members: GroupMember[] // 原始数据是没有这个的,为了方便自己加了这个字段
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum GroupMemberRole {
|
||||||
|
normal = 2,
|
||||||
|
admin = 3,
|
||||||
|
owner = 4
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GroupMember {
|
||||||
|
avatarPath: string;
|
||||||
|
cardName: string;
|
||||||
|
cardType: number;
|
||||||
|
isDelete: boolean;
|
||||||
|
nick: string;
|
||||||
|
qid: string;
|
||||||
|
remark: string;
|
||||||
|
role: GroupMemberRole; // 群主:4, 管理员:3,群员:2
|
||||||
|
shutUpTime: number; // 禁言时间,单位是什么暂时不清楚
|
||||||
|
uid: string; // 加密的字符串
|
||||||
|
uin: string; // QQ号
|
||||||
|
isRobot: boolean;
|
||||||
|
sex?: Sex
|
||||||
|
qqLevel?: QQLevel
|
||||||
|
}
|
7
src/ntqqapi/types/index.ts
Normal file
7
src/ntqqapi/types/index.ts
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
|
||||||
|
export * from './user';
|
||||||
|
export * from './group';
|
||||||
|
export * from './msg';
|
||||||
|
export * from './notify';
|
||||||
|
export * from './cache';
|
||||||
|
|
@@ -1,76 +1,11 @@
|
|||||||
export interface User {
|
import {GroupMemberRole} from "./group";
|
||||||
uid: string; // 加密的字符串
|
|
||||||
uin: string; // QQ号
|
|
||||||
nick: string;
|
|
||||||
avatarUrl?: string;
|
|
||||||
longNick?: string; // 签名
|
|
||||||
remark?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface SelfInfo extends User {
|
|
||||||
online?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface Friend extends User {
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface Group {
|
|
||||||
groupCode: string,
|
|
||||||
maxMember: number,
|
|
||||||
memberCount: number,
|
|
||||||
groupName: string,
|
|
||||||
groupStatus: 0,
|
|
||||||
memberRole: 2,
|
|
||||||
isTop: boolean,
|
|
||||||
toppedTimestamp: "0",
|
|
||||||
privilegeFlag: number, //65760
|
|
||||||
isConf: boolean,
|
|
||||||
hasModifyConfGroupFace: boolean,
|
|
||||||
hasModifyConfGroupName: boolean,
|
|
||||||
remarkName: string,
|
|
||||||
hasMemo: boolean,
|
|
||||||
groupShutupExpireTime: string, //"0",
|
|
||||||
personShutupExpireTime: string, //"0",
|
|
||||||
discussToGroupUin: string, //"0",
|
|
||||||
discussToGroupMaxMsgSeq: number,
|
|
||||||
discussToGroupTime: number,
|
|
||||||
groupFlagExt: number, //1073938496,
|
|
||||||
authGroupType: number, //0,
|
|
||||||
groupCreditLevel: number, //0,
|
|
||||||
groupFlagExt3: number, //0,
|
|
||||||
groupOwnerId: {
|
|
||||||
"memberUin": string, //"0",
|
|
||||||
"memberUid": string, //"u_fbf8N7aeuZEnUiJAbQ9R8Q"
|
|
||||||
},
|
|
||||||
members: GroupMember[] // 原始数据是没有这个的,为了方便自己加了这个字段
|
|
||||||
}
|
|
||||||
|
|
||||||
export enum GroupMemberRole {
|
|
||||||
normal = 2,
|
|
||||||
admin = 3,
|
|
||||||
owner = 4
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface GroupMember {
|
|
||||||
avatarPath: string;
|
|
||||||
cardName: string;
|
|
||||||
cardType: number;
|
|
||||||
isDelete: boolean;
|
|
||||||
nick: string;
|
|
||||||
qid: string;
|
|
||||||
remark: string;
|
|
||||||
role: GroupMemberRole; // 群主:4, 管理员:3,群员:2
|
|
||||||
shutUpTime: number; // 禁言时间,单位是什么暂时不清楚
|
|
||||||
uid: string; // 加密的字符串
|
|
||||||
uin: string; // QQ号
|
|
||||||
isRobot: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export enum ElementType {
|
export enum ElementType {
|
||||||
TEXT = 1,
|
TEXT = 1,
|
||||||
PIC = 2,
|
PIC = 2,
|
||||||
FILE = 3,
|
FILE = 3,
|
||||||
PTT = 4,
|
PTT = 4,
|
||||||
|
VIDEO = 5,
|
||||||
FACE = 6,
|
FACE = 6,
|
||||||
REPLY = 7,
|
REPLY = 7,
|
||||||
ARK = 10,
|
ARK = 10,
|
||||||
@@ -112,6 +47,7 @@ export enum PicType {
|
|||||||
gif = 2000,
|
gif = 2000,
|
||||||
jpg = 1000
|
jpg = 1000
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SendPicElement {
|
export interface SendPicElement {
|
||||||
elementType: ElementType.PIC,
|
elementType: ElementType.PIC,
|
||||||
elementId: "",
|
elementId: "",
|
||||||
@@ -166,11 +102,17 @@ export interface FileElement {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface SendFileElement {
|
export interface SendFileElement {
|
||||||
elementType: ElementType.FILE,
|
elementType: ElementType.FILE
|
||||||
elementId: "",
|
elementId: "",
|
||||||
fileElement: FileElement
|
fileElement: FileElement
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface SendVideoElement {
|
||||||
|
elementType: ElementType.VIDEO
|
||||||
|
elementId: "",
|
||||||
|
videoElement: VideoElement
|
||||||
|
}
|
||||||
|
|
||||||
export interface SendArkElement {
|
export interface SendArkElement {
|
||||||
elementType: ElementType.ARK,
|
elementType: ElementType.ARK,
|
||||||
elementId: "",
|
elementId: "",
|
||||||
@@ -179,7 +121,7 @@ export interface SendArkElement {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export type SendMessageElement = SendTextElement | SendPttElement |
|
export type SendMessageElement = SendTextElement | SendPttElement |
|
||||||
SendPicElement | SendReplyElement | SendFaceElement | SendFileElement | SendArkElement
|
SendPicElement | SendReplyElement | SendFaceElement | SendFileElement | SendVideoElement | SendArkElement
|
||||||
|
|
||||||
export enum AtType {
|
export enum AtType {
|
||||||
notAt = 0,
|
notAt = 0,
|
||||||
@@ -218,8 +160,8 @@ export interface PttElement {
|
|||||||
|
|
||||||
export interface ArkElement {
|
export interface ArkElement {
|
||||||
bytesData: string;
|
bytesData: string;
|
||||||
linkInfo:null,
|
linkInfo: null,
|
||||||
subElementType:null
|
subElementType: null
|
||||||
}
|
}
|
||||||
|
|
||||||
export const IMAGE_HTTP_HOST = "https://gchat.qpic.cn"
|
export const IMAGE_HTTP_HOST = "https://gchat.qpic.cn"
|
||||||
@@ -233,9 +175,15 @@ export interface PicElement {
|
|||||||
fileSize: number;
|
fileSize: number;
|
||||||
fileName: string;
|
fileName: string;
|
||||||
fileUuid: string;
|
fileUuid: string;
|
||||||
|
md5HexStr?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum GrayTipElementSubType {
|
||||||
|
INVITE_NEW_MEMBER = 12,
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface GrayTipElement {
|
export interface GrayTipElement {
|
||||||
|
subElementType: GrayTipElementSubType;
|
||||||
revokeElement: {
|
revokeElement: {
|
||||||
operatorRole: string;
|
operatorRole: string;
|
||||||
operatorUid: string;
|
operatorUid: string;
|
||||||
@@ -244,7 +192,11 @@ export interface GrayTipElement {
|
|||||||
operatorMemRemark?: string;
|
operatorMemRemark?: string;
|
||||||
wording: string; // 自定义的撤回提示语
|
wording: string; // 自定义的撤回提示语
|
||||||
}
|
}
|
||||||
aioOpGrayTipElement: TipAioOpGrayTipElement
|
aioOpGrayTipElement: TipAioOpGrayTipElement,
|
||||||
|
groupElement: TipGroupElement,
|
||||||
|
xmlElement: {
|
||||||
|
content: string;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface FaceElement {
|
export interface FaceElement {
|
||||||
@@ -255,34 +207,78 @@ export interface FaceElement {
|
|||||||
export interface VideoElement {
|
export interface VideoElement {
|
||||||
"filePath": string,
|
"filePath": string,
|
||||||
"fileName": string,
|
"fileName": string,
|
||||||
"videoMd5": string,
|
"videoMd5"?: string,
|
||||||
"thumbMd5": string
|
"thumbMd5"?: string
|
||||||
"fileTime": 87, // second
|
"fileTime"?: number, // second
|
||||||
"thumbSize": 314235, // byte
|
"thumbSize"?: number, // byte
|
||||||
"fileFormat": 2, // 2表示mp4?
|
"fileFormat"?: number, // 2表示mp4?
|
||||||
"fileSize": string, // byte
|
"fileSize"?: string, // byte
|
||||||
"thumbWidth": number,
|
"thumbWidth"?: number,
|
||||||
"thumbHeight": number,
|
"thumbHeight"?: number,
|
||||||
"busiType": 0, // 未知
|
"busiType"?: 0, // 未知
|
||||||
"subBusiType": 0, // 未知
|
"subBusiType"?: 0, // 未知
|
||||||
"thumbPath": Map<number, any>,
|
"thumbPath"?: Map<number, any>,
|
||||||
"transferStatus": 0, // 未知
|
"transferStatus"?: 0, // 未知
|
||||||
"progress": 0, // 下载进度?
|
"progress"?: 0, // 下载进度?
|
||||||
"invalidState": 0, // 未知
|
"invalidState"?: 0, // 未知
|
||||||
"fileUuid": string, // 可以用于下载链接?
|
"fileUuid"?: string, // 可以用于下载链接?
|
||||||
"fileSubId": "",
|
"fileSubId"?: "",
|
||||||
"fileBizId": null,
|
"fileBizId"?: null,
|
||||||
"originVideoMd5": "",
|
"originVideoMd5"?: "",
|
||||||
"import_rich_media_context": null,
|
"import_rich_media_context"?: null,
|
||||||
"sourceVideoCodecFormat": 0
|
"sourceVideoCodecFormat"?: number
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface TipAioOpGrayTipElement{
|
export interface TipAioOpGrayTipElement { // 这是什么提示来着?
|
||||||
operateType: number,
|
operateType: number,
|
||||||
peerUid: string,
|
peerUid: string,
|
||||||
fromGrpCodeOfTmpChat: string,
|
fromGrpCodeOfTmpChat: string,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export enum TipGroupElementType {
|
||||||
|
memberIncrease = 1,
|
||||||
|
ban = 8
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TipGroupElement {
|
||||||
|
"type": TipGroupElementType, // 1是表示有人加入群, 自己加入群也会收到这个
|
||||||
|
"role": 0, // 暂时不知
|
||||||
|
"groupName": string, // 暂时获取不到
|
||||||
|
"memberUid": string,
|
||||||
|
"memberNick": string,
|
||||||
|
"memberRemark": string,
|
||||||
|
"adminUid": string, // 同意加群的管理员uid
|
||||||
|
"adminNick": string,
|
||||||
|
"adminRemark": string,
|
||||||
|
"createGroup": null,
|
||||||
|
"memberAdd"?: {
|
||||||
|
"showType": 1,
|
||||||
|
"otherAdd": null,
|
||||||
|
"otherAddByOtherQRCode": null,
|
||||||
|
"otherAddByYourQRCode": null,
|
||||||
|
"youAddByOtherQRCode": null,
|
||||||
|
"otherInviteOther": null,
|
||||||
|
"otherInviteYou": null,
|
||||||
|
"youInviteOther": null
|
||||||
|
},
|
||||||
|
"shutUp"?: {
|
||||||
|
"curTime": string,
|
||||||
|
"duration": string, // 禁言时间,秒
|
||||||
|
"admin": {
|
||||||
|
"uid": string,
|
||||||
|
"card": string,
|
||||||
|
"name": string,
|
||||||
|
"role": GroupMemberRole
|
||||||
|
},
|
||||||
|
"member": {
|
||||||
|
"uid": string
|
||||||
|
"card": string,
|
||||||
|
"name": string,
|
||||||
|
"role": GroupMemberRole
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
export interface RawMessage {
|
export interface RawMessage {
|
||||||
msgId: string;
|
msgId: string;
|
||||||
@@ -321,61 +317,4 @@ export interface RawMessage {
|
|||||||
videoElement: VideoElement;
|
videoElement: VideoElement;
|
||||||
fileElement: FileElement;
|
fileElement: FileElement;
|
||||||
}[];
|
}[];
|
||||||
}
|
|
||||||
|
|
||||||
export enum GroupNotifyTypes {
|
|
||||||
INVITE_ME = 1,
|
|
||||||
INVITED_JOIN = 4, // 有人接受了邀请入群
|
|
||||||
JOIN_REQUEST = 7,
|
|
||||||
ADMIN_SET = 8,
|
|
||||||
ADMIN_UNSET = 12,
|
|
||||||
MEMBER_EXIT = 11, // 主动退出?
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface GroupNotifies {
|
|
||||||
doubt: boolean,
|
|
||||||
nextStartSeq: string,
|
|
||||||
notifies: GroupNotify[],
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface GroupNotify {
|
|
||||||
time: number; // 自己添加的字段,时间戳,毫秒, 用于判断收到短时间内收到重复的notify
|
|
||||||
seq: string, // 转成数字,再除以1000应该就是时间戳?
|
|
||||||
type: GroupNotifyTypes,
|
|
||||||
status: 0, // 未知
|
|
||||||
group: { groupCode: string, groupName: string },
|
|
||||||
user1: { uid: string, nickName: string }, // 被设置管理员的人
|
|
||||||
user2: { uid: string, nickName: string }, // 操作者
|
|
||||||
actionUser: { uid: string, nickName: string }, //未知
|
|
||||||
actionTime: string,
|
|
||||||
invitationExt: {
|
|
||||||
srcType: number, // 0?未知
|
|
||||||
groupCode: string, waitStatus: number
|
|
||||||
},
|
|
||||||
postscript: string, // 加群用户填写的验证信息
|
|
||||||
repeatSeqs: [],
|
|
||||||
warningTips: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export enum GroupRequestOperateTypes {
|
|
||||||
approve = 1,
|
|
||||||
reject = 2
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface FriendRequest {
|
|
||||||
friendUid: string,
|
|
||||||
reqTime: string, // 时间戳,秒
|
|
||||||
extWords: string, // 申请人填写的验证消息
|
|
||||||
isUnread: boolean,
|
|
||||||
friendNick: string,
|
|
||||||
sourceId: number,
|
|
||||||
groupCode: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface FriendRequestNotify {
|
|
||||||
data: {
|
|
||||||
unreadNums: number,
|
|
||||||
buddyReqs: FriendRequest[]
|
|
||||||
}
|
|
||||||
}
|
}
|
64
src/ntqqapi/types/notify.ts
Normal file
64
src/ntqqapi/types/notify.ts
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
|
||||||
|
export enum GroupNotifyTypes {
|
||||||
|
INVITE_ME = 1,
|
||||||
|
INVITED_JOIN = 4, // 有人接受了邀请入群
|
||||||
|
JOIN_REQUEST = 7,
|
||||||
|
ADMIN_SET = 8,
|
||||||
|
ADMIN_UNSET = 12,
|
||||||
|
MEMBER_EXIT = 11, // 主动退出?
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GroupNotifies {
|
||||||
|
doubt: boolean,
|
||||||
|
nextStartSeq: string,
|
||||||
|
notifies: GroupNotify[],
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum GroupNotifyStatus {
|
||||||
|
IGNORE = 0,
|
||||||
|
WAIT_HANDLE = 1,
|
||||||
|
APPROVE = 2,
|
||||||
|
REJECT = 3
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GroupNotify {
|
||||||
|
time: number; // 自己添加的字段,时间戳,毫秒, 用于判断收到短时间内收到重复的notify
|
||||||
|
seq: string, // 唯一标识符,转成数字再除以1000应该就是时间戳?
|
||||||
|
type: GroupNotifyTypes,
|
||||||
|
status: GroupNotifyStatus, // 0是已忽略?,1是未处理,2是已同意
|
||||||
|
group: { groupCode: string, groupName: string },
|
||||||
|
user1: { uid: string, nickName: string }, // 被设置管理员的人
|
||||||
|
user2: { uid: string, nickName: string }, // 操作者
|
||||||
|
actionUser: { uid: string, nickName: string }, //未知
|
||||||
|
actionTime: string,
|
||||||
|
invitationExt: {
|
||||||
|
srcType: number, // 0?未知
|
||||||
|
groupCode: string, waitStatus: number
|
||||||
|
},
|
||||||
|
postscript: string, // 加群用户填写的验证信息
|
||||||
|
repeatSeqs: [],
|
||||||
|
warningTips: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum GroupRequestOperateTypes {
|
||||||
|
approve = 1,
|
||||||
|
reject = 2
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FriendRequest {
|
||||||
|
friendUid: string,
|
||||||
|
reqTime: string, // 时间戳,秒
|
||||||
|
extWords: string, // 申请人填写的验证消息
|
||||||
|
isUnread: boolean,
|
||||||
|
friendNick: string,
|
||||||
|
sourceId: number,
|
||||||
|
groupCode: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FriendRequestNotify {
|
||||||
|
data: {
|
||||||
|
unreadNums: number,
|
||||||
|
buddyReqs: FriendRequest[]
|
||||||
|
}
|
||||||
|
}
|
28
src/ntqqapi/types/user.ts
Normal file
28
src/ntqqapi/types/user.ts
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
export enum Sex {
|
||||||
|
male = 0,
|
||||||
|
female = 2,
|
||||||
|
unknown = 255,
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface QQLevel {
|
||||||
|
"crownNum": number,
|
||||||
|
"sunNum": number,
|
||||||
|
"moonNum": number,
|
||||||
|
"starNum": number
|
||||||
|
}
|
||||||
|
export interface User {
|
||||||
|
uid: string; // 加密的字符串
|
||||||
|
uin: string; // QQ号
|
||||||
|
nick: string;
|
||||||
|
avatarUrl?: string;
|
||||||
|
longNick?: string; // 签名
|
||||||
|
remark?: string;
|
||||||
|
sex?: Sex;
|
||||||
|
"qqLevel"?: QQLevel
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SelfInfo extends User {
|
||||||
|
online?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Friend extends User {}
|
@@ -1,7 +1,8 @@
|
|||||||
import {ActionName, BaseCheckResult} from "./types"
|
import {ActionName, BaseCheckResult} from "./types"
|
||||||
import {OB11Response} from "./utils"
|
import {OB11Response} from "./utils"
|
||||||
import {OB11Return} from "../types";
|
import {OB11Return} from "../types";
|
||||||
import {log} from "../../common/utils";
|
|
||||||
|
import {log} from "../../common/utils/log";
|
||||||
|
|
||||||
class BaseAction<PayloadType, ReturnDataType> {
|
class BaseAction<PayloadType, ReturnDataType> {
|
||||||
actionName: ActionName
|
actionName: ActionName
|
||||||
@@ -21,8 +22,8 @@ class BaseAction<PayloadType, ReturnDataType> {
|
|||||||
const resData = await this._handle(payload);
|
const resData = await this._handle(payload);
|
||||||
return OB11Response.ok(resData);
|
return OB11Response.ok(resData);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
log("发送错误", e.stack)
|
log("发生错误", e)
|
||||||
return OB11Response.error(e.toString(), 200);
|
return OB11Response.error(e?.toString() || e?.stack?.toString() || "未知错误,可能操作超时", 200);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -35,8 +36,8 @@ class BaseAction<PayloadType, ReturnDataType> {
|
|||||||
const resData = await this._handle(payload)
|
const resData = await this._handle(payload)
|
||||||
return OB11Response.ok(resData, echo);
|
return OB11Response.ok(resData, echo);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
log("发生错误", e.stack.toString())
|
log("发生错误", e)
|
||||||
return OB11Response.error(e.toString(), 1200, echo)
|
return OB11Response.error(e.stack?.toString() || e.toString(), 1200, echo)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
105
src/onebot11/action/CleanCache.ts
Normal file
105
src/onebot11/action/CleanCache.ts
Normal file
@@ -0,0 +1,105 @@
|
|||||||
|
import BaseAction from "./BaseAction";
|
||||||
|
import {ActionName} from "./types";
|
||||||
|
import fs from "fs";
|
||||||
|
import Path from "path";
|
||||||
|
import {
|
||||||
|
ChatType,
|
||||||
|
ChatCacheListItemBasic,
|
||||||
|
CacheFileType
|
||||||
|
} from '../../ntqqapi/types';
|
||||||
|
import {dbUtil} from "../../common/db";
|
||||||
|
import {NTQQFileApi, NTQQFileCacheApi} from "../../ntqqapi/api/file";
|
||||||
|
|
||||||
|
export default class CleanCache extends BaseAction<void, void> {
|
||||||
|
actionName = ActionName.CleanCache
|
||||||
|
|
||||||
|
protected _handle(): Promise<void> {
|
||||||
|
return new Promise<void>(async (res, rej) => {
|
||||||
|
try {
|
||||||
|
// dbUtil.clearCache();
|
||||||
|
const cacheFilePaths: string[] = [];
|
||||||
|
|
||||||
|
await NTQQFileCacheApi.setCacheSilentScan(false);
|
||||||
|
|
||||||
|
cacheFilePaths.push((await NTQQFileCacheApi.getHotUpdateCachePath()));
|
||||||
|
cacheFilePaths.push((await NTQQFileCacheApi.getDesktopTmpPath()));
|
||||||
|
(await NTQQFileCacheApi.getCacheSessionPathList()).forEach(e => cacheFilePaths.push(e.value));
|
||||||
|
|
||||||
|
// await NTQQApi.addCacheScannedPaths(); // XXX: 调用就崩溃,原因目前还未知
|
||||||
|
const cacheScanResult = await NTQQFileCacheApi.scanCache();
|
||||||
|
const cacheSize = parseInt(cacheScanResult.size[6]);
|
||||||
|
|
||||||
|
if (cacheScanResult.result !== 0) {
|
||||||
|
throw('Something went wrong while scanning cache. Code: ' + cacheScanResult.result);
|
||||||
|
}
|
||||||
|
|
||||||
|
await NTQQFileCacheApi.setCacheSilentScan(true);
|
||||||
|
if (cacheSize > 0 && cacheFilePaths.length > 2) { // 存在缓存文件且大小不为 0 时执行清理动作
|
||||||
|
// await NTQQApi.clearCache([ 'tmp', 'hotUpdate', ...cacheScanResult ]) // XXX: 也是调用就崩溃,调用 fs 删除得了
|
||||||
|
deleteCachePath(cacheFilePaths);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取聊天记录列表
|
||||||
|
// NOTE: 以防有人不需要删除聊天记录,暂时先注释掉,日后加个开关
|
||||||
|
// const privateChatCache = await getCacheList(ChatType.friend); // 私聊消息
|
||||||
|
// const groupChatCache = await getCacheList(ChatType.group); // 群聊消息
|
||||||
|
// const chatCacheList = [ ...privateChatCache, ...groupChatCache ];
|
||||||
|
const chatCacheList: ChatCacheListItemBasic[] = [];
|
||||||
|
|
||||||
|
// 获取聊天缓存文件列表
|
||||||
|
const cacheFileList: string[] = [];
|
||||||
|
|
||||||
|
for (const name in CacheFileType) {
|
||||||
|
if (!isNaN(parseInt(name))) continue;
|
||||||
|
|
||||||
|
const fileTypeAny: any = CacheFileType[name];
|
||||||
|
const fileType: CacheFileType = fileTypeAny;
|
||||||
|
|
||||||
|
cacheFileList.push(...(await NTQQFileCacheApi.getFileCacheInfo(fileType)).infos.map(file => file.fileKey));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 一并清除
|
||||||
|
await NTQQFileCacheApi.clearChatCache(chatCacheList, cacheFileList);
|
||||||
|
res();
|
||||||
|
} catch(e) {
|
||||||
|
console.error('清理缓存时发生了错误');
|
||||||
|
rej(e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function deleteCachePath(pathList: string[]) {
|
||||||
|
const emptyPath = (path: string) => {
|
||||||
|
if (!fs.existsSync(path)) return;
|
||||||
|
const files = fs.readdirSync(path);
|
||||||
|
files.forEach(file => {
|
||||||
|
const filePath = Path.resolve(path, file);
|
||||||
|
const stats = fs.statSync(filePath);
|
||||||
|
if (stats.isDirectory()) emptyPath(filePath);
|
||||||
|
else fs.unlinkSync(filePath);
|
||||||
|
});
|
||||||
|
fs.rmdirSync(path);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const path of pathList) {
|
||||||
|
emptyPath(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function getCacheList(type: ChatType) { // NOTE: 做这个方法主要是因为目前还不支持针对频道消息的清理
|
||||||
|
return new Promise<Array<ChatCacheListItemBasic>>((res, rej) => {
|
||||||
|
NTQQFileCacheApi.getChatCacheList(type, 1000, 0)
|
||||||
|
.then(data => {
|
||||||
|
const list = data.infos.filter(e => e.chatType === type && parseInt(e.basicChatCacheInfo.chatSize) > 0);
|
||||||
|
const result = list.map(e => {
|
||||||
|
const result = { ...e.basicChatCacheInfo };
|
||||||
|
result.chatType = type;
|
||||||
|
result.isChecked = true;
|
||||||
|
return result;
|
||||||
|
});
|
||||||
|
res(result);
|
||||||
|
})
|
||||||
|
.catch(e => rej(e));
|
||||||
|
});
|
||||||
|
}
|
@@ -1,7 +1,8 @@
|
|||||||
import BaseAction from "./BaseAction";
|
import BaseAction from "./BaseAction";
|
||||||
import {NTQQApi} from "../../ntqqapi/ntcall";
|
import {NTQQApi} from "../../ntqqapi/ntcall";
|
||||||
import {ActionName} from "./types";
|
import {ActionName} from "./types";
|
||||||
import {log} from "../../common/utils";
|
|
||||||
|
import {log} from "../../common/utils/log";
|
||||||
|
|
||||||
interface Payload {
|
interface Payload {
|
||||||
method: string,
|
method: string,
|
||||||
|
@@ -1,7 +1,7 @@
|
|||||||
import {ActionName} from "./types";
|
import {ActionName} from "./types";
|
||||||
import BaseAction from "./BaseAction";
|
import BaseAction from "./BaseAction";
|
||||||
import {NTQQApi} from "../../ntqqapi/ntcall";
|
|
||||||
import {dbUtil} from "../../common/db";
|
import {dbUtil} from "../../common/db";
|
||||||
|
import {NTQQMsgApi} from "../../ntqqapi/api/msg";
|
||||||
|
|
||||||
interface Payload {
|
interface Payload {
|
||||||
message_id: number
|
message_id: number
|
||||||
@@ -12,7 +12,7 @@ class DeleteMsg extends BaseAction<Payload, void> {
|
|||||||
|
|
||||||
protected async _handle(payload: Payload) {
|
protected async _handle(payload: Payload) {
|
||||||
let msg = await dbUtil.getMsgByShortId(payload.message_id)
|
let msg = await dbUtil.getMsgByShortId(payload.message_id)
|
||||||
await NTQQApi.recallMsg({
|
await NTQQMsgApi.recallMsg({
|
||||||
chatType: msg.chatType,
|
chatType: msg.chatType,
|
||||||
peerUid: msg.peerUid
|
peerUid: msg.peerUid
|
||||||
}, [msg.msgId])
|
}, [msg.msgId])
|
||||||
|
@@ -1,7 +1,7 @@
|
|||||||
import BaseAction from "./BaseAction";
|
import BaseAction from "./BaseAction";
|
||||||
import {fileCache} from "../../common/data";
|
|
||||||
import {getConfigUtil} from "../../common/utils";
|
|
||||||
import fs from "fs/promises";
|
import fs from "fs/promises";
|
||||||
|
import {dbUtil} from "../../common/db";
|
||||||
|
import {getConfigUtil} from "../../common/config";
|
||||||
|
|
||||||
export interface GetFilePayload {
|
export interface GetFilePayload {
|
||||||
file: string // 文件名
|
file: string // 文件名
|
||||||
@@ -18,7 +18,7 @@ export interface GetFileResponse {
|
|||||||
|
|
||||||
export class GetFileBase extends BaseAction<GetFilePayload, GetFileResponse> {
|
export class GetFileBase extends BaseAction<GetFilePayload, GetFileResponse> {
|
||||||
protected async _handle(payload: GetFilePayload): Promise<GetFileResponse> {
|
protected async _handle(payload: GetFilePayload): Promise<GetFileResponse> {
|
||||||
const cache = fileCache.get(payload.file)
|
const cache = await dbUtil.getFileCache(payload.file)
|
||||||
const {autoDeleteFile, enableLocalFile2Url, autoDeleteFileSecond} = getConfigUtil().getConfig()
|
const {autoDeleteFile, enableLocalFile2Url, autoDeleteFileSecond} = getConfigUtil().getConfig()
|
||||||
if (!cache) {
|
if (!cache) {
|
||||||
throw new Error('file not found')
|
throw new Error('file not found')
|
||||||
|
@@ -3,6 +3,9 @@ import {getGroupMember} from "../../common/data";
|
|||||||
import {OB11Constructor} from "../constructor";
|
import {OB11Constructor} from "../constructor";
|
||||||
import BaseAction from "./BaseAction";
|
import BaseAction from "./BaseAction";
|
||||||
import {ActionName} from "./types";
|
import {ActionName} from "./types";
|
||||||
|
import {NTQQUserApi} from "../../ntqqapi/api/user";
|
||||||
|
import {log} from "../../common/utils/log";
|
||||||
|
import {isNull} from "../../common/utils/helper";
|
||||||
|
|
||||||
|
|
||||||
export interface PayloadType {
|
export interface PayloadType {
|
||||||
@@ -16,6 +19,12 @@ class GetGroupMemberInfo extends BaseAction<PayloadType, OB11GroupMember> {
|
|||||||
protected async _handle(payload: PayloadType) {
|
protected async _handle(payload: PayloadType) {
|
||||||
const member = await getGroupMember(payload.group_id.toString(), payload.user_id.toString())
|
const member = await getGroupMember(payload.group_id.toString(), payload.user_id.toString())
|
||||||
if (member) {
|
if (member) {
|
||||||
|
if (isNull(member.sex)){
|
||||||
|
log("获取群成员详细信息")
|
||||||
|
let info = (await NTQQUserApi.getUserDetailInfo(member.uid))
|
||||||
|
log("群成员详细信息结果", info)
|
||||||
|
Object.assign(member, info);
|
||||||
|
}
|
||||||
return OB11Constructor.groupMember(payload.group_id.toString(), member)
|
return OB11Constructor.groupMember(payload.group_id.toString(), member)
|
||||||
} else {
|
} else {
|
||||||
throw (`群成员${payload.user_id}不存在`)
|
throw (`群成员${payload.user_id}不存在`)
|
||||||
|
@@ -1,9 +1,9 @@
|
|||||||
import {OB11GroupMember} from '../types';
|
import {OB11GroupMember} from '../types';
|
||||||
import {getGroup} from "../../common/data";
|
import {getGroup} from "../../common/data";
|
||||||
import {NTQQApi} from "../../ntqqapi/ntcall";
|
|
||||||
import {OB11Constructor} from "../constructor";
|
import {OB11Constructor} from "../constructor";
|
||||||
import BaseAction from "./BaseAction";
|
import BaseAction from "./BaseAction";
|
||||||
import {ActionName} from "./types";
|
import {ActionName} from "./types";
|
||||||
|
import {NTQQGroupApi} from "../../ntqqapi/api/group";
|
||||||
|
|
||||||
export interface PayloadType {
|
export interface PayloadType {
|
||||||
group_id: number
|
group_id: number
|
||||||
@@ -17,7 +17,7 @@ class GetGroupMemberList extends BaseAction<PayloadType, OB11GroupMember[]> {
|
|||||||
const group = await getGroup(payload.group_id.toString());
|
const group = await getGroup(payload.group_id.toString());
|
||||||
if (group) {
|
if (group) {
|
||||||
if (!group.members?.length) {
|
if (!group.members?.length) {
|
||||||
group.members = await NTQQApi.getGroupMembers(payload.group_id.toString())
|
group.members = await NTQQGroupApi.getGroupMembers(payload.group_id.toString())
|
||||||
}
|
}
|
||||||
return OB11Constructor.groupMembers(group);
|
return OB11Constructor.groupMembers(group);
|
||||||
} else {
|
} else {
|
||||||
|
@@ -19,13 +19,14 @@ class GetMsg extends BaseAction<PayloadType, OB11Message> {
|
|||||||
if (!payload.message_id) {
|
if (!payload.message_id) {
|
||||||
throw ("参数message_id不能为空")
|
throw ("参数message_id不能为空")
|
||||||
}
|
}
|
||||||
const msg = await dbUtil.getMsgByShortId(payload.message_id)
|
let msg = await dbUtil.getMsgByShortId(payload.message_id)
|
||||||
if (msg) {
|
if(!msg) {
|
||||||
const msgData = await OB11Constructor.message(msg);
|
msg = await dbUtil.getMsgByLongId(payload.message_id.toString())
|
||||||
return msgData
|
}
|
||||||
} else {
|
if (!msg){
|
||||||
throw ("消息不存在")
|
throw ("消息不存在")
|
||||||
}
|
}
|
||||||
|
return await OB11Constructor.message(msg)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -1,9 +1,18 @@
|
|||||||
import SendMsg from "./SendMsg";
|
import SendMsg from "./SendMsg";
|
||||||
import {ActionName} from "./types";
|
import {ActionName, BaseCheckResult} from "./types";
|
||||||
|
import {OB11PostSendMsg} from "../types";
|
||||||
|
|
||||||
|
import {log} from "../../common/utils/log";
|
||||||
|
|
||||||
|
|
||||||
class SendGroupMsg extends SendMsg {
|
class SendGroupMsg extends SendMsg {
|
||||||
actionName = ActionName.SendGroupMsg
|
actionName = ActionName.SendGroupMsg
|
||||||
|
|
||||||
|
protected async check(payload: OB11PostSendMsg): Promise<BaseCheckResult> {
|
||||||
|
delete payload.user_id;
|
||||||
|
payload.message_type = "group"
|
||||||
|
return super.check(payload);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default SendGroupMsg
|
export default SendGroupMsg
|
@@ -1,7 +1,8 @@
|
|||||||
import BaseAction from "./BaseAction";
|
import BaseAction from "./BaseAction";
|
||||||
import {getFriend} from "../../common/data";
|
import {getFriend, getUidByUin, uidMaps} from "../../common/data";
|
||||||
import {NTQQApi} from "../../ntqqapi/ntcall";
|
|
||||||
import {ActionName} from "./types";
|
import {ActionName} from "./types";
|
||||||
|
import {NTQQFriendApi} from "../../ntqqapi/api/friend";
|
||||||
|
import {log} from "../../common/utils/log";
|
||||||
|
|
||||||
interface Payload {
|
interface Payload {
|
||||||
user_id: number,
|
user_id: number,
|
||||||
@@ -12,13 +13,17 @@ export default class SendLike extends BaseAction<Payload, null> {
|
|||||||
actionName = ActionName.SendLike
|
actionName = ActionName.SendLike
|
||||||
|
|
||||||
protected async _handle(payload: Payload): Promise<null> {
|
protected async _handle(payload: Payload): Promise<null> {
|
||||||
const qq = payload.user_id.toString();
|
log("点赞参数", payload)
|
||||||
const friend = await getFriend(qq)
|
|
||||||
if (!friend) {
|
|
||||||
throw (`点赞失败,${qq}不是好友`)
|
|
||||||
}
|
|
||||||
try {
|
try {
|
||||||
let result = await NTQQApi.likeFriend(friend.uid, parseInt(payload.times.toString()) || 1);
|
const qq = payload.user_id.toString();
|
||||||
|
const friend = await getFriend(qq)
|
||||||
|
let uid: string;
|
||||||
|
if (!friend) {
|
||||||
|
uid = getUidByUin(qq)
|
||||||
|
} else {
|
||||||
|
uid = friend.uid
|
||||||
|
}
|
||||||
|
let result = await NTQQFriendApi.likeFriend(uid, parseInt(payload.times?.toString()) || 1);
|
||||||
if (result.result !== 0) {
|
if (result.result !== 0) {
|
||||||
throw result.errMsg
|
throw result.errMsg
|
||||||
}
|
}
|
||||||
|
@@ -1,5 +1,20 @@
|
|||||||
import {AtType, ChatType, Group, RawMessage, SendArkElement, SendMessageElement} from "../../ntqqapi/types";
|
import {
|
||||||
import {friends, getGroup, getGroupMember, getUidByUin, selfInfo,} from "../../common/data";
|
AtType,
|
||||||
|
ChatType,
|
||||||
|
ElementType,
|
||||||
|
Group,
|
||||||
|
RawMessage,
|
||||||
|
SendArkElement,
|
||||||
|
SendMessageElement
|
||||||
|
} from "../../ntqqapi/types";
|
||||||
|
import {
|
||||||
|
friends,
|
||||||
|
getFriend,
|
||||||
|
getGroup,
|
||||||
|
getGroupMember,
|
||||||
|
getUidByUin,
|
||||||
|
selfInfo,
|
||||||
|
} from "../../common/data";
|
||||||
import {
|
import {
|
||||||
OB11MessageCustomMusic,
|
OB11MessageCustomMusic,
|
||||||
OB11MessageData,
|
OB11MessageData,
|
||||||
@@ -8,15 +23,18 @@ import {
|
|||||||
OB11MessageNode,
|
OB11MessageNode,
|
||||||
OB11PostSendMsg
|
OB11PostSendMsg
|
||||||
} from '../types';
|
} from '../types';
|
||||||
import {NTQQApi, Peer} from "../../ntqqapi/ntcall";
|
import {Peer} from "../../ntqqapi/api/msg";
|
||||||
import {SendMsgElementConstructor} from "../../ntqqapi/constructor";
|
import {SendMsgElementConstructor} from "../../ntqqapi/constructor";
|
||||||
import {uri2local} from "../utils";
|
import {uri2local} from "../utils";
|
||||||
import BaseAction from "./BaseAction";
|
import BaseAction from "./BaseAction";
|
||||||
import {ActionName, BaseCheckResult} from "./types";
|
import {ActionName, BaseCheckResult} from "./types";
|
||||||
import * as fs from "node:fs";
|
import * as fs from "node:fs";
|
||||||
import {log} from "../../common/utils";
|
|
||||||
import {decodeCQCode} from "../cqcode";
|
import {decodeCQCode} from "../cqcode";
|
||||||
import {dbUtil} from "../../common/db";
|
import {dbUtil} from "../../common/db";
|
||||||
|
import {ALLOW_SEND_TEMP_MSG} from "../../common/config";
|
||||||
|
import {NTQQMsgApi} from "../../ntqqapi/api/msg";
|
||||||
|
import {log} from "../../common/utils/log";
|
||||||
|
import {sleep} from "../../common/utils/helper";
|
||||||
|
|
||||||
function checkSendMessage(sendMsgList: OB11MessageData[]) {
|
function checkSendMessage(sendMsgList: OB11MessageData[]) {
|
||||||
function checkUri(uri: string): boolean {
|
function checkUri(uri: string): boolean {
|
||||||
@@ -69,27 +87,43 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
|
|||||||
message: "转发消息不能和普通消息混在一起发送,转发需要保证message只有type为node的元素"
|
message: "转发消息不能和普通消息混在一起发送,转发需要保证message只有type为node的元素"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (payload.group_id && !(await getGroup(payload.group_id))) {
|
||||||
|
return {
|
||||||
|
valid: false,
|
||||||
|
message: `群${payload.group_id}不存在`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (payload.user_id && payload.message_type !== "group") {
|
||||||
|
if (!(await getFriend(payload.user_id))) {
|
||||||
|
if (!ALLOW_SEND_TEMP_MSG && !(await dbUtil.getReceivedTempUinMap())[payload.user_id.toString()]) {
|
||||||
|
return {
|
||||||
|
valid: false,
|
||||||
|
message: `不能发送临时消息`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
valid: true,
|
valid: true,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected async _handle(payload: OB11PostSendMsg) {
|
protected async _handle(payload: OB11PostSendMsg) {
|
||||||
|
|
||||||
const peer: Peer = {
|
const peer: Peer = {
|
||||||
chatType: ChatType.friend,
|
chatType: ChatType.friend,
|
||||||
peerUid: ""
|
peerUid: ""
|
||||||
}
|
}
|
||||||
|
let isTempMsg = false;
|
||||||
let group: Group | undefined = undefined;
|
let group: Group | undefined = undefined;
|
||||||
if (payload?.group_id) {
|
const genGroupPeer = async () => {
|
||||||
group = await getGroup(payload.group_id.toString())
|
group = await getGroup(payload.group_id.toString())
|
||||||
if (!group) {
|
|
||||||
throw (`群${payload.group_id}不存在`)
|
|
||||||
}
|
|
||||||
peer.chatType = ChatType.group
|
peer.chatType = ChatType.group
|
||||||
// peer.name = group.name
|
// peer.name = group.name
|
||||||
peer.peerUid = group.groupCode
|
peer.peerUid = group.groupCode
|
||||||
} else if (payload?.user_id) {
|
}
|
||||||
|
|
||||||
|
const genFriendPeer = () => {
|
||||||
const friend = friends.find(f => f.uin == payload.user_id.toString())
|
const friend = friends.find(f => f.uin == payload.user_id.toString())
|
||||||
if (friend) {
|
if (friend) {
|
||||||
// peer.name = friend.nickName
|
// peer.name = friend.nickName
|
||||||
@@ -101,9 +135,20 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
|
|||||||
throw (`找不到私聊对象${payload.user_id}`)
|
throw (`找不到私聊对象${payload.user_id}`)
|
||||||
}
|
}
|
||||||
// peer.name = tempUser.nickName
|
// peer.name = tempUser.nickName
|
||||||
|
isTempMsg = true;
|
||||||
peer.peerUid = tempUserUid;
|
peer.peerUid = tempUserUid;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (payload?.group_id && payload.message_type === "group") {
|
||||||
|
await genGroupPeer()
|
||||||
|
|
||||||
|
} else if (payload?.user_id) {
|
||||||
|
genFriendPeer()
|
||||||
|
} else if (payload.group_id) {
|
||||||
|
await genGroupPeer()
|
||||||
|
} else {
|
||||||
|
throw ("发送消息参数错误, 请指定group_id或user_id")
|
||||||
|
}
|
||||||
const messages = this.convertMessage2List(payload.message);
|
const messages = this.convertMessage2List(payload.message);
|
||||||
if (this.getSpecialMsgNum(payload, OB11MessageDataType.node)) {
|
if (this.getSpecialMsgNum(payload, OB11MessageDataType.node)) {
|
||||||
try {
|
try {
|
||||||
@@ -129,12 +174,10 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
|
|||||||
}
|
}
|
||||||
// log("send msg:", peer, sendElements)
|
// log("send msg:", peer, sendElements)
|
||||||
const {sendElements, deleteAfterSentFiles} = await this.createSendElements(messages, group)
|
const {sendElements, deleteAfterSentFiles} = await this.createSendElements(messages, group)
|
||||||
try {
|
const returnMsg = await this.send(peer, sendElements, deleteAfterSentFiles)
|
||||||
const returnMsg = await this.send(peer, sendElements, deleteAfterSentFiles)
|
deleteAfterSentFiles.map(f => fs.unlink(f, () => {
|
||||||
return {message_id: returnMsg.msgShortId}
|
}));
|
||||||
} catch (e) {
|
return {message_id: returnMsg.msgShortId}
|
||||||
throw (e.toString())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected convertMessage2List(message: OB11MessageMixType) {
|
protected convertMessage2List(message: OB11MessageMixType) {
|
||||||
@@ -159,22 +202,58 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
|
|||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async cloneMsg(msg: RawMessage): Promise<RawMessage> {
|
||||||
|
log("克隆的目标消息", msg)
|
||||||
|
let sendElements: SendMessageElement[] = [];
|
||||||
|
for (const ele of msg.elements) {
|
||||||
|
sendElements.push(ele as SendMessageElement)
|
||||||
|
// Object.keys(ele).forEach((eleKey) => {
|
||||||
|
// if (eleKey.endsWith("Element")) {
|
||||||
|
// }
|
||||||
|
|
||||||
|
}
|
||||||
|
if (sendElements.length === 0) {
|
||||||
|
log("需要clone的消息无法解析,将会忽略掉", msg)
|
||||||
|
}
|
||||||
|
log("克隆消息", sendElements)
|
||||||
|
try {
|
||||||
|
const nodeMsg = await NTQQMsgApi.sendMsg({
|
||||||
|
chatType: ChatType.friend,
|
||||||
|
peerUid: selfInfo.uid
|
||||||
|
}, sendElements, true);
|
||||||
|
await sleep(500);
|
||||||
|
return nodeMsg
|
||||||
|
} catch (e) {
|
||||||
|
log(e, "克隆转发消息失败,将忽略本条消息", msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
// 返回一个合并转发的消息id
|
// 返回一个合并转发的消息id
|
||||||
private async handleForwardNode(destPeer: Peer, messageNodes: OB11MessageNode[], group: Group | undefined) {
|
private async handleForwardNode(destPeer: Peer, messageNodes: OB11MessageNode[], group: Group | undefined) {
|
||||||
const selfPeer: Peer = {
|
|
||||||
|
const selfPeer = {
|
||||||
chatType: ChatType.friend,
|
chatType: ChatType.friend,
|
||||||
peerUid: selfInfo.uid
|
peerUid: selfInfo.uid
|
||||||
}
|
}
|
||||||
let selfNodeMsgList: RawMessage[] = [];
|
let nodeMsgIds: string[] = []
|
||||||
let originalNodeMsgList: RawMessage[] = [];
|
// 先判断一遍是不是id和自定义混用
|
||||||
|
let needClone = messageNodes.filter(node => node.data.id).length && messageNodes.filter(node => !node.data.id).length
|
||||||
for (const messageNode of messageNodes) {
|
for (const messageNode of messageNodes) {
|
||||||
// 一个node表示一个人的消息
|
// 一个node表示一个人的消息
|
||||||
let nodeId = messageNode.data.id;
|
let nodeId = messageNode.data.id;
|
||||||
// 有nodeId表示一个子转发消息卡片
|
// 有nodeId表示一个子转发消息卡片
|
||||||
if (nodeId) {
|
if (nodeId) {
|
||||||
let nodeMsg = await dbUtil.getMsgByShortId(parseInt(nodeId));
|
let nodeMsg = await dbUtil.getMsgByShortId(parseInt(nodeId));
|
||||||
if (nodeMsg) {
|
if (!needClone) {
|
||||||
originalNodeMsgList.push(nodeMsg);
|
nodeMsgIds.push(nodeMsg.msgId)
|
||||||
|
} else {
|
||||||
|
if (nodeMsg.peerUid !== selfInfo.uid) {
|
||||||
|
const cloneMsg = await this.cloneMsg(nodeMsg)
|
||||||
|
if (cloneMsg) {
|
||||||
|
nodeMsgIds.push(cloneMsg.msgId)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// 自定义的消息
|
// 自定义的消息
|
||||||
@@ -185,58 +264,82 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
|
|||||||
deleteAfterSentFiles
|
deleteAfterSentFiles
|
||||||
} = await this.createSendElements(this.convertMessage2List(messageNode.data.content), group);
|
} = await this.createSendElements(this.convertMessage2List(messageNode.data.content), group);
|
||||||
log("开始生成转发节点", sendElements);
|
log("开始生成转发节点", sendElements);
|
||||||
const nodeMsg = await this.send(selfPeer, sendElements, deleteAfterSentFiles, true);
|
let sendElementsSplit: SendMessageElement[][] = []
|
||||||
selfNodeMsgList.push(nodeMsg);
|
let splitIndex = 0;
|
||||||
log("转发节点生成成功", nodeMsg.msgId);
|
for (const ele of sendElements) {
|
||||||
|
if (!sendElementsSplit[splitIndex]) {
|
||||||
|
sendElementsSplit[splitIndex] = []
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ele.elementType === ElementType.FILE || ele.elementType === ElementType.VIDEO) {
|
||||||
|
if (sendElementsSplit[splitIndex].length > 0) {
|
||||||
|
splitIndex++;
|
||||||
|
}
|
||||||
|
sendElementsSplit[splitIndex] = [ele]
|
||||||
|
splitIndex++;
|
||||||
|
} else {
|
||||||
|
sendElementsSplit[splitIndex].push(ele)
|
||||||
|
}
|
||||||
|
log(sendElementsSplit)
|
||||||
|
}
|
||||||
|
// log("分割后的转发节点", sendElementsSplit)
|
||||||
|
for (const eles of sendElementsSplit) {
|
||||||
|
const nodeMsg = await this.send(selfPeer, eles, [], true);
|
||||||
|
nodeMsgIds.push(nodeMsg.msgId)
|
||||||
|
await sleep(500);
|
||||||
|
log("转发节点生成成功", nodeMsg.msgId);
|
||||||
|
}
|
||||||
|
deleteAfterSentFiles.map(f => fs.unlink(f, () => {
|
||||||
|
}));
|
||||||
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
log("生效转发消息节点失败", e)
|
log("生成转发消息节点失败", e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let nodeIds: string[] = []
|
// 检查srcPeer是否一致,不一致则需要克隆成自己的消息, 让所有srcPeer都变成自己的,使其保持一致才能够转发
|
||||||
// 检查是否需要克隆直接引用消息id的节点
|
let nodeMsgArray: Array<RawMessage> = []
|
||||||
|
let srcPeer: Peer = null;
|
||||||
let needSendSelf = false;
|
let needSendSelf = false;
|
||||||
if (selfNodeMsgList.length) {
|
for (const [index, msgId] of nodeMsgIds.entries()) {
|
||||||
needSendSelf = true
|
const nodeMsg = await dbUtil.getMsgByLongId(msgId)
|
||||||
} else {
|
if (nodeMsg) {
|
||||||
needSendSelf = !originalNodeMsgList.every((msg, index) => msg.peerUid === originalNodeMsgList[0].peerUid && msg.recallTime.length < 2)
|
nodeMsgArray.push(nodeMsg)
|
||||||
|
if (!srcPeer) {
|
||||||
|
srcPeer = {chatType: nodeMsg.chatType, peerUid: nodeMsg.peerUid}
|
||||||
|
} else if (srcPeer.peerUid !== nodeMsg.peerUid) {
|
||||||
|
needSendSelf = true
|
||||||
|
srcPeer = selfPeer
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
log("nodeMsgArray", nodeMsgArray);
|
||||||
|
nodeMsgIds = nodeMsgArray.map(msg => msg.msgId);
|
||||||
if (needSendSelf) {
|
if (needSendSelf) {
|
||||||
nodeIds = selfNodeMsgList.map(msg => msg.msgId);
|
log("需要克隆转发消息");
|
||||||
for (const originalNodeMsg of originalNodeMsgList) {
|
for (const [index, msg] of nodeMsgArray.entries()) {
|
||||||
if (originalNodeMsg.peerUid === selfInfo.uid && originalNodeMsg.recallTime.length < 2) {
|
if (msg.peerUid !== selfInfo.uid) {
|
||||||
nodeIds.push(originalNodeMsg.msgId)
|
const cloneMsg = await this.cloneMsg(msg)
|
||||||
} else { // 需要进行克隆
|
if (cloneMsg) {
|
||||||
let sendElements: SendMessageElement[] = []
|
nodeMsgIds[index] = cloneMsg.msgId
|
||||||
Object.keys(originalNodeMsg.elements).forEach((eleKey) => {
|
|
||||||
if (eleKey !== "elementId") {
|
|
||||||
sendElements.push(originalNodeMsg.elements[eleKey])
|
|
||||||
}
|
|
||||||
})
|
|
||||||
try {
|
|
||||||
const nodeMsg = await NTQQApi.sendMsg(selfPeer, sendElements, true);
|
|
||||||
nodeIds.push(nodeMsg.msgId)
|
|
||||||
log("克隆转发消息成功")
|
|
||||||
} catch (e) {
|
|
||||||
log("克隆转发消息失败", e)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
nodeIds = originalNodeMsgList.map(msg => msg.msgId)
|
|
||||||
}
|
|
||||||
|
|
||||||
let srcPeer = selfPeer;
|
|
||||||
if (!needSendSelf) {
|
|
||||||
srcPeer = {
|
|
||||||
chatType: originalNodeMsgList[0].chatType === ChatType.group ? ChatType.group : ChatType.friend,
|
|
||||||
peerUid: originalNodeMsgList[0].peerUid
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
// elements之间用换行符分隔
|
||||||
|
// let _sendForwardElements: SendMessageElement[] = []
|
||||||
|
// for(let i = 0; i < sendForwardElements.length; i++){
|
||||||
|
// _sendForwardElements.push(sendForwardElements[i])
|
||||||
|
// _sendForwardElements.push(SendMsgElementConstructor.text("\n\n"))
|
||||||
|
// }
|
||||||
|
// const nodeMsg = await NTQQApi.sendMsg(selfPeer, _sendForwardElements, true);
|
||||||
|
// nodeIds.push(nodeMsg.msgId)
|
||||||
|
// await sleep(500);
|
||||||
// 开发转发
|
// 开发转发
|
||||||
try {
|
try {
|
||||||
return await NTQQApi.multiForwardMsg(srcPeer, destPeer, nodeIds)
|
log("开发转发", nodeMsgIds)
|
||||||
|
return await NTQQMsgApi.multiForwardMsg(srcPeer, destPeer, nodeMsgIds)
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
log("forward failed", e)
|
log("forward failed", e)
|
||||||
return null;
|
return null;
|
||||||
@@ -259,6 +362,9 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
|
|||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case OB11MessageDataType.at: {
|
case OB11MessageDataType.at: {
|
||||||
|
if (!group) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
let atQQ = sendMsg.data?.qq;
|
let atQQ = sendMsg.data?.qq;
|
||||||
if (atQQ) {
|
if (atQQ) {
|
||||||
atQQ = atQQ.toString()
|
atQQ = atQQ.toString()
|
||||||
@@ -296,25 +402,39 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
|
|||||||
case OB11MessageDataType.file:
|
case OB11MessageDataType.file:
|
||||||
case OB11MessageDataType.video:
|
case OB11MessageDataType.video:
|
||||||
case OB11MessageDataType.voice: {
|
case OB11MessageDataType.voice: {
|
||||||
const file = sendMsg.data?.file
|
let file = sendMsg.data?.file
|
||||||
const payloadFileName = sendMsg.data?.name
|
const payloadFileName = sendMsg.data?.name
|
||||||
if (file) {
|
if (file) {
|
||||||
const {path, isLocal, fileName} = (await uri2local(file))
|
const cache = await dbUtil.getFileCache(file)
|
||||||
|
if (cache) {
|
||||||
|
if (fs.existsSync(cache.filePath)) {
|
||||||
|
file = "file://" + cache.filePath
|
||||||
|
} else if (cache.downloadFunc) {
|
||||||
|
await cache.downloadFunc()
|
||||||
|
file = cache.filePath;
|
||||||
|
} else if (cache.url) {
|
||||||
|
file = cache.url
|
||||||
|
}
|
||||||
|
log("找到文件缓存", file);
|
||||||
|
}
|
||||||
|
const {path, isLocal, fileName, errMsg} = (await uri2local(file))
|
||||||
|
if (errMsg) {
|
||||||
|
throw errMsg
|
||||||
|
}
|
||||||
if (path) {
|
if (path) {
|
||||||
if (!isLocal) { // 只删除http和base64转过来的文件
|
if (!isLocal) { // 只删除http和base64转过来的文件
|
||||||
deleteAfterSentFiles.push(path)
|
deleteAfterSentFiles.push(path)
|
||||||
}
|
}
|
||||||
const constructorMap = {
|
|
||||||
[OB11MessageDataType.image]: SendMsgElementConstructor.pic,
|
|
||||||
[OB11MessageDataType.voice]: SendMsgElementConstructor.ptt,
|
|
||||||
[OB11MessageDataType.video]: SendMsgElementConstructor.video,
|
|
||||||
[OB11MessageDataType.file]: SendMsgElementConstructor.file,
|
|
||||||
}
|
|
||||||
if (sendMsg.type === OB11MessageDataType.file) {
|
if (sendMsg.type === OB11MessageDataType.file) {
|
||||||
log("发送文件", path, payloadFileName || fileName)
|
log("发送文件", path, payloadFileName || fileName)
|
||||||
sendElements.push(await SendMsgElementConstructor.file(path, false, payloadFileName || fileName));
|
sendElements.push(await SendMsgElementConstructor.file(path, payloadFileName || fileName));
|
||||||
} else {
|
} else if (sendMsg.type === OB11MessageDataType.video) {
|
||||||
sendElements.push(await constructorMap[sendMsg.type](path));
|
log("发送视频", path, payloadFileName || fileName)
|
||||||
|
sendElements.push(await SendMsgElementConstructor.video(path, payloadFileName || fileName));
|
||||||
|
} else if (sendMsg.type === OB11MessageDataType.voice) {
|
||||||
|
sendElements.push(await SendMsgElementConstructor.ptt(path));
|
||||||
|
}else if (sendMsg.type === OB11MessageDataType.image) {
|
||||||
|
sendElements.push(await SendMsgElementConstructor.pic(path, sendMsg.data.summary || ""));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -330,13 +450,13 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async send(peer: Peer, sendElements: SendMessageElement[], deleteAfterSentFiles: string[], waitComplete = false) {
|
private async send(peer: Peer, sendElements: SendMessageElement[], deleteAfterSentFiles: string[], waitComplete = true) {
|
||||||
if (!sendElements.length) {
|
if (!sendElements.length) {
|
||||||
throw ("消息体无法解析")
|
throw ("消息体无法解析")
|
||||||
}
|
}
|
||||||
const returnMsg = await NTQQApi.sendMsg(peer, sendElements, waitComplete, 20000);
|
const returnMsg = await NTQQMsgApi.sendMsg(peer, sendElements, waitComplete, 20000);
|
||||||
log("消息发送结果", returnMsg)
|
log("消息发送结果", returnMsg)
|
||||||
await dbUtil.addMsg(returnMsg)
|
returnMsg.msgShortId = await dbUtil.addMsg(returnMsg)
|
||||||
deleteAfterSentFiles.map(f => fs.unlink(f, () => {
|
deleteAfterSentFiles.map(f => fs.unlink(f, () => {
|
||||||
}))
|
}))
|
||||||
return returnMsg
|
return returnMsg
|
||||||
|
@@ -1,8 +1,14 @@
|
|||||||
import SendMsg from "./SendMsg";
|
import SendMsg from "./SendMsg";
|
||||||
import {ActionName} from "./types";
|
import {ActionName, BaseCheckResult} from "./types";
|
||||||
|
import {OB11PostSendMsg} from "../types";
|
||||||
|
|
||||||
class SendPrivateMsg extends SendMsg {
|
class SendPrivateMsg extends SendMsg {
|
||||||
actionName = ActionName.SendPrivateMsg
|
actionName = ActionName.SendPrivateMsg
|
||||||
|
|
||||||
|
protected async check(payload: OB11PostSendMsg): Promise<BaseCheckResult> {
|
||||||
|
payload.message_type = "private"
|
||||||
|
return super.check(payload);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default SendPrivateMsg
|
export default SendPrivateMsg
|
@@ -1,6 +1,6 @@
|
|||||||
import BaseAction from "./BaseAction";
|
import BaseAction from "./BaseAction";
|
||||||
import {NTQQApi} from "../../ntqqapi/ntcall";
|
|
||||||
import {ActionName} from "./types";
|
import {ActionName} from "./types";
|
||||||
|
import {NTQQFriendApi} from "../../ntqqapi/api/friend";
|
||||||
|
|
||||||
interface Payload {
|
interface Payload {
|
||||||
flag: string,
|
flag: string,
|
||||||
@@ -12,7 +12,7 @@ export default class SetFriendAddRequest extends BaseAction<Payload, null> {
|
|||||||
actionName = ActionName.SetFriendAddRequest;
|
actionName = ActionName.SetFriendAddRequest;
|
||||||
|
|
||||||
protected async _handle(payload: Payload): Promise<null> {
|
protected async _handle(payload: Payload): Promise<null> {
|
||||||
await NTQQApi.handleFriendRequest(parseInt(payload.flag), payload.approve)
|
await NTQQFriendApi.handleFriendRequest(parseInt(payload.flag), payload.approve)
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
@@ -1,8 +1,7 @@
|
|||||||
import BaseAction from "./BaseAction";
|
import BaseAction from "./BaseAction";
|
||||||
import {groupNotifies} from "../../common/data";
|
import {GroupRequestOperateTypes} from "../../ntqqapi/types";
|
||||||
import {GroupNotify, GroupRequestOperateTypes} from "../../ntqqapi/types";
|
|
||||||
import {NTQQApi} from "../../ntqqapi/ntcall";
|
|
||||||
import {ActionName} from "./types";
|
import {ActionName} from "./types";
|
||||||
|
import {NTQQGroupApi} from "../../ntqqapi/api/group";
|
||||||
|
|
||||||
interface Payload {
|
interface Payload {
|
||||||
flag: string,
|
flag: string,
|
||||||
@@ -17,15 +16,10 @@ export default class SetGroupAddRequest extends BaseAction<Payload, null> {
|
|||||||
|
|
||||||
protected async _handle(payload: Payload): Promise<null> {
|
protected async _handle(payload: Payload): Promise<null> {
|
||||||
const seq = payload.flag.toString();
|
const seq = payload.flag.toString();
|
||||||
const notify: GroupNotify = groupNotifies[seq]
|
await NTQQGroupApi.handleGroupRequest(seq,
|
||||||
try {
|
payload.approve ? GroupRequestOperateTypes.approve : GroupRequestOperateTypes.reject,
|
||||||
await NTQQApi.handleGroupRequest(seq,
|
payload.reason
|
||||||
payload.approve ? GroupRequestOperateTypes.approve : GroupRequestOperateTypes.reject,
|
)
|
||||||
payload.reason
|
|
||||||
)
|
|
||||||
} catch (e) {
|
|
||||||
throw e
|
|
||||||
}
|
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
}
|
}
|
@@ -1,8 +1,8 @@
|
|||||||
import BaseAction from "./BaseAction";
|
import BaseAction from "./BaseAction";
|
||||||
import {NTQQApi} from "../../ntqqapi/ntcall";
|
|
||||||
import {getGroupMember} from "../../common/data";
|
import {getGroupMember} from "../../common/data";
|
||||||
import {GroupMemberRole} from "../../ntqqapi/types";
|
import {GroupMemberRole} from "../../ntqqapi/types";
|
||||||
import {ActionName} from "./types";
|
import {ActionName} from "./types";
|
||||||
|
import {NTQQGroupApi} from "../../ntqqapi/api/group";
|
||||||
|
|
||||||
interface Payload {
|
interface Payload {
|
||||||
group_id: number,
|
group_id: number,
|
||||||
@@ -18,7 +18,7 @@ export default class SetGroupAdmin extends BaseAction<Payload, null> {
|
|||||||
if (!member) {
|
if (!member) {
|
||||||
throw `群成员${payload.user_id}不存在`
|
throw `群成员${payload.user_id}不存在`
|
||||||
}
|
}
|
||||||
await NTQQApi.setMemberRole(payload.group_id.toString(), member.uid, payload.enable ? GroupMemberRole.admin : GroupMemberRole.normal)
|
await NTQQGroupApi.setMemberRole(payload.group_id.toString(), member.uid, payload.enable ? GroupMemberRole.admin : GroupMemberRole.normal)
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
}
|
}
|
@@ -1,7 +1,7 @@
|
|||||||
import BaseAction from "./BaseAction";
|
import BaseAction from "./BaseAction";
|
||||||
import {NTQQApi} from "../../ntqqapi/ntcall";
|
|
||||||
import {getGroupMember} from "../../common/data";
|
import {getGroupMember} from "../../common/data";
|
||||||
import {ActionName} from "./types";
|
import {ActionName} from "./types";
|
||||||
|
import {NTQQGroupApi} from "../../ntqqapi/api/group";
|
||||||
|
|
||||||
interface Payload {
|
interface Payload {
|
||||||
group_id: number,
|
group_id: number,
|
||||||
@@ -17,7 +17,7 @@ export default class SetGroupBan extends BaseAction<Payload, null> {
|
|||||||
if (!member) {
|
if (!member) {
|
||||||
throw `群成员${payload.user_id}不存在`
|
throw `群成员${payload.user_id}不存在`
|
||||||
}
|
}
|
||||||
await NTQQApi.banMember(payload.group_id.toString(),
|
await NTQQGroupApi.banMember(payload.group_id.toString(),
|
||||||
[{uid: member.uid, timeStamp: parseInt(payload.duration.toString())}])
|
[{uid: member.uid, timeStamp: parseInt(payload.duration.toString())}])
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
@@ -1,7 +1,7 @@
|
|||||||
import BaseAction from "./BaseAction";
|
import BaseAction from "./BaseAction";
|
||||||
import {NTQQApi} from "../../ntqqapi/ntcall";
|
|
||||||
import {getGroupMember} from "../../common/data";
|
import {getGroupMember} from "../../common/data";
|
||||||
import {ActionName} from "./types";
|
import {ActionName} from "./types";
|
||||||
|
import {NTQQGroupApi} from "../../ntqqapi/api/group";
|
||||||
|
|
||||||
interface Payload {
|
interface Payload {
|
||||||
group_id: number,
|
group_id: number,
|
||||||
@@ -17,7 +17,7 @@ export default class SetGroupCard extends BaseAction<Payload, null> {
|
|||||||
if (!member) {
|
if (!member) {
|
||||||
throw `群成员${payload.user_id}不存在`
|
throw `群成员${payload.user_id}不存在`
|
||||||
}
|
}
|
||||||
await NTQQApi.setMemberCard(payload.group_id.toString(), member.uid, payload.card || "")
|
await NTQQGroupApi.setMemberCard(payload.group_id.toString(), member.uid, payload.card || "")
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
}
|
}
|
@@ -1,7 +1,7 @@
|
|||||||
import BaseAction from "./BaseAction";
|
import BaseAction from "./BaseAction";
|
||||||
import {NTQQApi} from "../../ntqqapi/ntcall";
|
|
||||||
import {getGroupMember} from "../../common/data";
|
import {getGroupMember} from "../../common/data";
|
||||||
import {ActionName} from "./types";
|
import {ActionName} from "./types";
|
||||||
|
import {NTQQGroupApi} from "../../ntqqapi/api/group";
|
||||||
|
|
||||||
interface Payload {
|
interface Payload {
|
||||||
group_id: number,
|
group_id: number,
|
||||||
@@ -17,7 +17,7 @@ export default class SetGroupKick extends BaseAction<Payload, null> {
|
|||||||
if (!member) {
|
if (!member) {
|
||||||
throw `群成员${payload.user_id}不存在`
|
throw `群成员${payload.user_id}不存在`
|
||||||
}
|
}
|
||||||
await NTQQApi.kickMember(payload.group_id.toString(), [member.uid], !!payload.reject_add_request);
|
await NTQQGroupApi.kickMember(payload.group_id.toString(), [member.uid], !!payload.reject_add_request);
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
}
|
}
|
@@ -1,7 +1,7 @@
|
|||||||
import BaseAction from "./BaseAction";
|
import BaseAction from "./BaseAction";
|
||||||
import {NTQQApi} from "../../ntqqapi/ntcall";
|
|
||||||
import {log} from "../../common/utils";
|
|
||||||
import {ActionName} from "./types";
|
import {ActionName} from "./types";
|
||||||
|
import {NTQQGroupApi} from "../../ntqqapi/api/group";
|
||||||
|
import {log} from "../../common/utils/log";
|
||||||
|
|
||||||
interface Payload {
|
interface Payload {
|
||||||
group_id: number,
|
group_id: number,
|
||||||
@@ -13,7 +13,7 @@ export default class SetGroupLeave extends BaseAction<Payload, any> {
|
|||||||
|
|
||||||
protected async _handle(payload: Payload): Promise<any> {
|
protected async _handle(payload: Payload): Promise<any> {
|
||||||
try {
|
try {
|
||||||
await NTQQApi.quitGroup(payload.group_id.toString())
|
await NTQQGroupApi.quitGroup(payload.group_id.toString())
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
log("退群失败", e)
|
log("退群失败", e)
|
||||||
throw e
|
throw e
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
import BaseAction from "./BaseAction";
|
import BaseAction from "./BaseAction";
|
||||||
import {NTQQApi} from "../../ntqqapi/ntcall";
|
|
||||||
import {ActionName} from "./types";
|
import {ActionName} from "./types";
|
||||||
|
import {NTQQGroupApi} from "../../ntqqapi/api/group";
|
||||||
|
|
||||||
interface Payload {
|
interface Payload {
|
||||||
group_id: number,
|
group_id: number,
|
||||||
@@ -12,7 +12,7 @@ export default class SetGroupName extends BaseAction<Payload, null> {
|
|||||||
|
|
||||||
protected async _handle(payload: Payload): Promise<null> {
|
protected async _handle(payload: Payload): Promise<null> {
|
||||||
|
|
||||||
await NTQQApi.setGroupName(payload.group_id.toString(), payload.group_name)
|
await NTQQGroupApi.setGroupName(payload.group_id.toString(), payload.group_name)
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
}
|
}
|
@@ -1,6 +1,6 @@
|
|||||||
import BaseAction from "./BaseAction";
|
import BaseAction from "./BaseAction";
|
||||||
import {NTQQApi} from "../../ntqqapi/ntcall";
|
|
||||||
import {ActionName} from "./types";
|
import {ActionName} from "./types";
|
||||||
|
import {NTQQGroupApi} from "../../ntqqapi/api/group";
|
||||||
|
|
||||||
interface Payload {
|
interface Payload {
|
||||||
group_id: number,
|
group_id: number,
|
||||||
@@ -12,7 +12,7 @@ export default class SetGroupWholeBan extends BaseAction<Payload, null> {
|
|||||||
|
|
||||||
protected async _handle(payload: Payload): Promise<null> {
|
protected async _handle(payload: Payload): Promise<null> {
|
||||||
|
|
||||||
await NTQQApi.banGroup(payload.group_id.toString(), !!payload.enable)
|
await NTQQGroupApi.banGroup(payload.group_id.toString(), !!payload.enable)
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
}
|
}
|
37
src/onebot11/action/go-cqhttp/UploadGroupFile.ts
Normal file
37
src/onebot11/action/go-cqhttp/UploadGroupFile.ts
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import BaseAction from "../BaseAction";
|
||||||
|
import {getGroup} from "../../../common/data";
|
||||||
|
import {ActionName} from "../types";
|
||||||
|
import {SendMsgElementConstructor} from "../../../ntqqapi/constructor";
|
||||||
|
import {ChatType, SendFileElement} from "../../../ntqqapi/types";
|
||||||
|
import {uri2local} from "../../utils";
|
||||||
|
import fs from "fs";
|
||||||
|
import {NTQQMsgApi} from "../../../ntqqapi/api/msg";
|
||||||
|
|
||||||
|
interface Payload{
|
||||||
|
group_id: number
|
||||||
|
file: string
|
||||||
|
name: string
|
||||||
|
folder: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export default class GoCQHTTPUploadGroupFile extends BaseAction<Payload, null> {
|
||||||
|
actionName = ActionName.GoCQHTTP_UploadGroupFile
|
||||||
|
|
||||||
|
protected async _handle(payload: Payload): Promise<null> {
|
||||||
|
const group = await getGroup(payload.group_id.toString());
|
||||||
|
if (!group){
|
||||||
|
throw new Error(`群组${payload.group_id}不存在`)
|
||||||
|
}
|
||||||
|
let file = payload.file;
|
||||||
|
if (fs.existsSync(file)){
|
||||||
|
file = `file://${file}`
|
||||||
|
}
|
||||||
|
const downloadResult = await uri2local(file);
|
||||||
|
if (downloadResult.errMsg){
|
||||||
|
throw new Error(downloadResult.errMsg)
|
||||||
|
}
|
||||||
|
let sendFileEle: SendFileElement = await SendMsgElementConstructor.file(downloadResult.path, payload.name);
|
||||||
|
await NTQQMsgApi.sendMsg({chatType: ChatType.group, peerUid: group.groupCode}, [sendFileEle]);
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
@@ -31,9 +31,19 @@ import SetGroupCard from "./SetGroupCard";
|
|||||||
import GetImage from "./GetImage";
|
import GetImage from "./GetImage";
|
||||||
import GetRecord from "./GetRecord";
|
import GetRecord from "./GetRecord";
|
||||||
import GoCQHTTPMarkMsgAsRead from "./MarkMsgAsRead";
|
import GoCQHTTPMarkMsgAsRead from "./MarkMsgAsRead";
|
||||||
|
import CleanCache from "./CleanCache";
|
||||||
|
import GoCQHTTPUploadGroupFile from "./go-cqhttp/UploadGroupFile";
|
||||||
|
import {GetConfigAction, SetConfigAction} from "./llonebot/Config";
|
||||||
|
import GetGroupAddRequest from "./llonebot/GetGroupAddRequest";
|
||||||
|
import SetQQAvatar from './llonebot/SetQQAvatar'
|
||||||
|
|
||||||
export const actionHandlers = [
|
export const actionHandlers = [
|
||||||
new Debug(),
|
new Debug(),
|
||||||
|
new GetConfigAction(),
|
||||||
|
new SetConfigAction(),
|
||||||
|
new GetGroupAddRequest(),
|
||||||
|
new SetQQAvatar(),
|
||||||
|
// onebot11
|
||||||
new SendLike(),
|
new SendLike(),
|
||||||
new GetMsg(),
|
new GetMsg(),
|
||||||
new GetLoginInfo(),
|
new GetLoginInfo(),
|
||||||
@@ -56,6 +66,7 @@ export const actionHandlers = [
|
|||||||
new SetGroupCard(),
|
new SetGroupCard(),
|
||||||
new GetImage(),
|
new GetImage(),
|
||||||
new GetRecord(),
|
new GetRecord(),
|
||||||
|
new CleanCache(),
|
||||||
|
|
||||||
//以下为go-cqhttp api
|
//以下为go-cqhttp api
|
||||||
new GoCQHTTPSendGroupForwardMsg(),
|
new GoCQHTTPSendGroupForwardMsg(),
|
||||||
@@ -63,6 +74,7 @@ export const actionHandlers = [
|
|||||||
new GoCQHTTPGetStrangerInfo(),
|
new GoCQHTTPGetStrangerInfo(),
|
||||||
new GetGuildList(),
|
new GetGuildList(),
|
||||||
new GoCQHTTPMarkMsgAsRead(),
|
new GoCQHTTPMarkMsgAsRead(),
|
||||||
|
new GoCQHTTPUploadGroupFile(),
|
||||||
|
|
||||||
]
|
]
|
||||||
|
|
||||||
|
20
src/onebot11/action/llonebot/Config.ts
Normal file
20
src/onebot11/action/llonebot/Config.ts
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
import BaseAction from "../BaseAction";
|
||||||
|
import {Config} from "../../../common/types";
|
||||||
|
import {ActionName} from "../types";
|
||||||
|
import {setConfig} from "../../../main/setConfig";
|
||||||
|
import {getConfigUtil} from "../../../common/config";
|
||||||
|
|
||||||
|
|
||||||
|
export class GetConfigAction extends BaseAction<null, Config> {
|
||||||
|
actionName = ActionName.GetConfig
|
||||||
|
protected async _handle(payload: null): Promise<Config> {
|
||||||
|
return getConfigUtil().getConfig()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class SetConfigAction extends BaseAction<Config, void> {
|
||||||
|
actionName = ActionName.SetConfig
|
||||||
|
protected async _handle(payload: Config): Promise<void> {
|
||||||
|
setConfig(payload).then();
|
||||||
|
}
|
||||||
|
}
|
33
src/onebot11/action/llonebot/GetGroupAddRequest.ts
Normal file
33
src/onebot11/action/llonebot/GetGroupAddRequest.ts
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
import {GroupNotify, GroupNotifyStatus} from "../../../ntqqapi/types";
|
||||||
|
import BaseAction from "../BaseAction";
|
||||||
|
import {ActionName} from "../types";
|
||||||
|
import {uidMaps} from "../../../common/data";
|
||||||
|
import {NTQQUserApi} from "../../../ntqqapi/api/user";
|
||||||
|
import {NTQQGroupApi} from "../../../ntqqapi/api/group";
|
||||||
|
import {log} from "../../../common/utils/log";
|
||||||
|
|
||||||
|
interface OB11GroupRequestNotify {
|
||||||
|
group_id: number,
|
||||||
|
user_id: number,
|
||||||
|
flag: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export default class GetGroupAddRequest extends BaseAction<null, OB11GroupRequestNotify[]> {
|
||||||
|
actionName = ActionName.GetGroupIgnoreAddRequest
|
||||||
|
|
||||||
|
protected async _handle(payload: null): Promise<OB11GroupRequestNotify[]> {
|
||||||
|
const data = await NTQQGroupApi.getGroupIgnoreNotifies()
|
||||||
|
log(data);
|
||||||
|
let notifies: GroupNotify[] = data.notifies.filter(notify => notify.status === GroupNotifyStatus.WAIT_HANDLE);
|
||||||
|
let returnData: OB11GroupRequestNotify[] = []
|
||||||
|
for (const notify of notifies) {
|
||||||
|
const uin = uidMaps[notify.user1.uid] || (await NTQQUserApi.getUserDetailInfo(notify.user1.uid))?.uin
|
||||||
|
returnData.push({
|
||||||
|
group_id: parseInt(notify.group.groupCode),
|
||||||
|
user_id: parseInt(uin),
|
||||||
|
flag: notify.seq
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return returnData;
|
||||||
|
}
|
||||||
|
}
|
44
src/onebot11/action/llonebot/SetQQAvatar.ts
Normal file
44
src/onebot11/action/llonebot/SetQQAvatar.ts
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
import BaseAction from "../BaseAction";
|
||||||
|
import {ActionName} from "../types";
|
||||||
|
import { uri2local } from "../../utils";
|
||||||
|
import * as fs from "node:fs";
|
||||||
|
import {NTQQUserApi} from "../../../ntqqapi/api/user";
|
||||||
|
import {checkFileReceived} from "../../../common/utils/file";
|
||||||
|
// import { log } from "../../../common/utils";
|
||||||
|
|
||||||
|
interface Payload {
|
||||||
|
file: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export default class SetAvatar extends BaseAction<Payload, null> {
|
||||||
|
actionName = ActionName.SetQQAvatar
|
||||||
|
|
||||||
|
protected async _handle(payload: Payload): Promise<null> {
|
||||||
|
const {path, isLocal, errMsg} = (await uri2local(payload.file))
|
||||||
|
if (errMsg){
|
||||||
|
throw `头像${payload.file}设置失败,file字段可能格式不正确`
|
||||||
|
}
|
||||||
|
if (path) {
|
||||||
|
await checkFileReceived(path, 5000); // 文件不存在QQ会崩溃,需要提前判断
|
||||||
|
const ret = await NTQQUserApi.setQQAvatar(path)
|
||||||
|
if (!isLocal){
|
||||||
|
fs.unlink(path, () => {})
|
||||||
|
}
|
||||||
|
if (!ret) {
|
||||||
|
throw `头像${payload.file}设置失败,api无返回`
|
||||||
|
}
|
||||||
|
// log(`头像设置返回:${JSON.stringify(ret)}`)
|
||||||
|
if (ret['result'] == 1004022) {
|
||||||
|
throw `头像${payload.file}设置失败,文件可能不是图片格式`
|
||||||
|
} else if(ret['result'] != 0) {
|
||||||
|
throw `头像${payload.file}设置失败,未知的错误,${ret['result']}:${ret['errMsg']}`
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (!isLocal){
|
||||||
|
fs.unlink(path, () => {})
|
||||||
|
}
|
||||||
|
throw `头像${payload.file}设置失败,无法获取头像,文件可能不存在`
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
@@ -14,6 +14,10 @@ export interface InvalidCheckResult {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export enum ActionName {
|
export enum ActionName {
|
||||||
|
GetGroupIgnoreAddRequest = "get_group_ignore_add_request",
|
||||||
|
SetQQAvatar = "set_qq_avatar",
|
||||||
|
GetConfig = "get_config",
|
||||||
|
SetConfig = "set_config",
|
||||||
Debug = "llonebot_debug",
|
Debug = "llonebot_debug",
|
||||||
SendLike = "send_like",
|
SendLike = "send_like",
|
||||||
GetLoginInfo = "get_login_info",
|
GetLoginInfo = "get_login_info",
|
||||||
@@ -42,10 +46,12 @@ export enum ActionName {
|
|||||||
SetGroupName = "set_group_name",
|
SetGroupName = "set_group_name",
|
||||||
GetImage = "get_image",
|
GetImage = "get_image",
|
||||||
GetRecord = "get_record",
|
GetRecord = "get_record",
|
||||||
|
CleanCache = "clean_cache",
|
||||||
// 以下为go-cqhttp api
|
// 以下为go-cqhttp api
|
||||||
GoCQHTTP_SendGroupForwardMsg = "send_group_forward_msg",
|
GoCQHTTP_SendGroupForwardMsg = "send_group_forward_msg",
|
||||||
GoCQHTTP_SendPrivateForwardMsg = "send_private_forward_msg",
|
GoCQHTTP_SendPrivateForwardMsg = "send_private_forward_msg",
|
||||||
GoCQHTTP_GetStrangerInfo = "get_stranger_info",
|
GoCQHTTP_GetStrangerInfo = "get_stranger_info",
|
||||||
GetGuildList = "get_guild_list",
|
GetGuildList = "get_guild_list",
|
||||||
GoCQHTTP_MarkMsgAsRead = "mark_msg_as_read",
|
GoCQHTTP_MarkMsgAsRead = "mark_msg_as_read",
|
||||||
|
GoCQHTTP_UploadGroupFile = "upload_group_file",
|
||||||
}
|
}
|
@@ -1,5 +1,6 @@
|
|||||||
import {OB11Return} from '../types';
|
import {OB11Return} from '../types';
|
||||||
import {isNull} from '../../common/utils';
|
|
||||||
|
import {isNull} from "../../common/utils/helper";
|
||||||
|
|
||||||
export class OB11Response {
|
export class OB11Response {
|
||||||
static res<T>(data: T, status: string, retcode: number, message: string = ""): OB11Return<T> {
|
static res<T>(data: T, status: string, retcode: number, message: string = ""): OB11Return<T> {
|
||||||
|
@@ -8,13 +8,32 @@ import {
|
|||||||
OB11User,
|
OB11User,
|
||||||
OB11UserSex
|
OB11UserSex
|
||||||
} from "./types";
|
} from "./types";
|
||||||
import {AtType, ChatType, Group, GroupMember, IMAGE_HTTP_HOST, RawMessage, SelfInfo, User} from '../ntqqapi/types';
|
import {
|
||||||
import {fileCache, getFriend, getGroupMember, selfInfo, tempGroupCodeMap} from '../common/data';
|
AtType,
|
||||||
import {getConfigUtil, log} from "../common/utils";
|
ChatType,
|
||||||
import {NTQQApi} from "../ntqqapi/ntcall";
|
GrayTipElementSubType,
|
||||||
|
Group,
|
||||||
|
GroupMember,
|
||||||
|
IMAGE_HTTP_HOST,
|
||||||
|
RawMessage,
|
||||||
|
SelfInfo, Sex,
|
||||||
|
TipGroupElementType,
|
||||||
|
User
|
||||||
|
} from '../ntqqapi/types';
|
||||||
|
import {getFriend, getGroupMember, selfInfo, tempGroupCodeMap} from '../common/data';
|
||||||
import {EventType} from "./event/OB11BaseEvent";
|
import {EventType} from "./event/OB11BaseEvent";
|
||||||
import {encodeCQCode} from "./cqcode";
|
import {encodeCQCode} from "./cqcode";
|
||||||
import {dbUtil} from "../common/db";
|
import {dbUtil} from "../common/db";
|
||||||
|
import {OB11GroupIncreaseEvent} from "./event/notice/OB11GroupIncreaseEvent";
|
||||||
|
import {OB11GroupBanEvent} from "./event/notice/OB11GroupBanEvent";
|
||||||
|
import {OB11GroupUploadNoticeEvent} from "./event/notice/OB11GroupUploadNoticeEvent";
|
||||||
|
import {OB11GroupNoticeEvent} from "./event/notice/OB11GroupNoticeEvent";
|
||||||
|
import {NTQQUserApi} from "../ntqqapi/api/user";
|
||||||
|
import {NTQQFileApi} from "../ntqqapi/api/file";
|
||||||
|
import {calcQQLevel} from "../common/utils/qqlevel";
|
||||||
|
import {log} from "../common/utils/log";
|
||||||
|
import {sleep} from "../common/utils/helper";
|
||||||
|
import {getConfigUtil} from "../common/config";
|
||||||
|
|
||||||
|
|
||||||
export class OB11Constructor {
|
export class OB11Constructor {
|
||||||
@@ -27,7 +46,7 @@ export class OB11Constructor {
|
|||||||
user_id: parseInt(msg.senderUin),
|
user_id: parseInt(msg.senderUin),
|
||||||
time: parseInt(msg.msgTime) || Date.now(),
|
time: parseInt(msg.msgTime) || Date.now(),
|
||||||
message_id: msg.msgShortId,
|
message_id: msg.msgShortId,
|
||||||
real_id: msg.msgId,
|
real_id: msg.msgShortId,
|
||||||
message_type: msg.chatType == ChatType.group ? "group" : "private",
|
message_type: msg.chatType == ChatType.group ? "group" : "private",
|
||||||
sender: {
|
sender: {
|
||||||
user_id: parseInt(msg.senderUin),
|
user_id: parseInt(msg.senderUin),
|
||||||
@@ -77,7 +96,7 @@ export class OB11Constructor {
|
|||||||
let atUid = element.textElement.atNtUid
|
let atUid = element.textElement.atNtUid
|
||||||
let atQQ = element.textElement.atUid
|
let atQQ = element.textElement.atUid
|
||||||
if (!atQQ || atQQ === "0") {
|
if (!atQQ || atQQ === "0") {
|
||||||
const atMember = await getGroupMember(msg.peerUin, null, atUid)
|
const atMember = await getGroupMember(msg.peerUin, atUid)
|
||||||
if (atMember) {
|
if (atMember) {
|
||||||
atQQ = atMember.uin
|
atQQ = atMember.uin
|
||||||
}
|
}
|
||||||
@@ -96,30 +115,43 @@ export class OB11Constructor {
|
|||||||
message_data["data"]["text"] = text
|
message_data["data"]["text"] = text
|
||||||
} else if (element.replyElement) {
|
} else if (element.replyElement) {
|
||||||
message_data["type"] = "reply"
|
message_data["type"] = "reply"
|
||||||
const replyMsg = await dbUtil.getMsgBySeqId(element.replyElement.replayMsgSeq)
|
// log("收到回复消息", element.replyElement.replayMsgSeq)
|
||||||
if (replyMsg) {
|
try {
|
||||||
message_data["data"]["id"] = replyMsg.msgShortId.toString()
|
const replyMsg = await dbUtil.getMsgBySeqId(element.replyElement.replayMsgSeq)
|
||||||
} else {
|
// log("找到回复消息", replyMsg.msgShortId, replyMsg.msgId)
|
||||||
continue
|
if (replyMsg) {
|
||||||
|
message_data["data"]["id"] = replyMsg.msgShortId.toString()
|
||||||
|
} else {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
log("获取不到引用的消息", e.stack, element.replyElement.replayMsgSeq)
|
||||||
}
|
}
|
||||||
|
|
||||||
} else if (element.picElement) {
|
} else if (element.picElement) {
|
||||||
message_data["type"] = "image"
|
message_data["type"] = "image"
|
||||||
// message_data["data"]["file"] = element.picElement.sourcePath
|
// message_data["data"]["file"] = element.picElement.sourcePath
|
||||||
message_data["data"]["file"] = element.picElement.fileName
|
message_data["data"]["file"] = element.picElement.fileName
|
||||||
// message_data["data"]["path"] = element.picElement.sourcePath
|
// message_data["data"]["path"] = element.picElement.sourcePath
|
||||||
message_data["data"]["url"] = IMAGE_HTTP_HOST + element.picElement.originImageUrl
|
const url = element.picElement.originImageUrl
|
||||||
|
const fileMd5 = element.picElement.md5HexStr
|
||||||
|
if (url) {
|
||||||
|
message_data["data"]["url"] = IMAGE_HTTP_HOST + url
|
||||||
|
} else if (fileMd5 && element.picElement.fileUuid.indexOf("_") === -1) { // fileuuid有下划线的是Linux发送的,这个url是另外的格式,目前尚未得知如何组装
|
||||||
|
message_data["data"]["url"] = `${IMAGE_HTTP_HOST}/gchatpic_new/0/0-0-${fileMd5.toUpperCase()}/0`
|
||||||
|
}
|
||||||
// message_data["data"]["file_id"] = element.picElement.fileUuid
|
// message_data["data"]["file_id"] = element.picElement.fileUuid
|
||||||
message_data["data"]["file_size"] = element.picElement.fileSize
|
message_data["data"]["file_size"] = element.picElement.fileSize
|
||||||
fileCache.set(element.picElement.fileName, {
|
dbUtil.addFileCache(element.picElement.fileName, {
|
||||||
fileName: element.picElement.fileName,
|
fileName: element.picElement.fileName,
|
||||||
filePath: element.picElement.sourcePath,
|
filePath: element.picElement.sourcePath,
|
||||||
fileSize: element.picElement.fileSize.toString(),
|
fileSize: element.picElement.fileSize.toString(),
|
||||||
url: IMAGE_HTTP_HOST + element.picElement.originImageUrl,
|
url: message_data["data"]["url"],
|
||||||
downloadFunc: async () => {
|
downloadFunc: async () => {
|
||||||
await NTQQApi.downloadMedia(msg.msgId, msg.chatType, msg.peerUid,
|
await NTQQFileApi.downloadMedia(msg.msgId, msg.chatType, msg.peerUid,
|
||||||
element.elementId, element.picElement.thumbPath.get(0), element.picElement.sourcePath)
|
element.elementId, element.picElement.thumbPath?.get(0) || "", element.picElement.sourcePath)
|
||||||
}
|
}
|
||||||
})
|
}).then()
|
||||||
// 不在自动下载图片
|
// 不在自动下载图片
|
||||||
|
|
||||||
} else if (element.videoElement) {
|
} else if (element.videoElement) {
|
||||||
@@ -128,15 +160,15 @@ export class OB11Constructor {
|
|||||||
message_data["data"]["path"] = element.videoElement.filePath
|
message_data["data"]["path"] = element.videoElement.filePath
|
||||||
// message_data["data"]["file_id"] = element.videoElement.fileUuid
|
// message_data["data"]["file_id"] = element.videoElement.fileUuid
|
||||||
message_data["data"]["file_size"] = element.videoElement.fileSize
|
message_data["data"]["file_size"] = element.videoElement.fileSize
|
||||||
fileCache.set(element.videoElement.fileName, {
|
dbUtil.addFileCache(element.videoElement.fileName, {
|
||||||
fileName: element.videoElement.fileName,
|
fileName: element.videoElement.fileName,
|
||||||
filePath: element.videoElement.filePath,
|
filePath: element.videoElement.filePath,
|
||||||
fileSize: element.videoElement.fileSize,
|
fileSize: element.videoElement.fileSize,
|
||||||
downloadFunc: async () => {
|
downloadFunc: async () => {
|
||||||
await NTQQApi.downloadMedia(msg.msgId, msg.chatType, msg.peerUid,
|
await NTQQFileApi.downloadMedia(msg.msgId, msg.chatType, msg.peerUid,
|
||||||
element.elementId, element.videoElement.thumbPath.get(0), element.videoElement.filePath)
|
element.elementId, element.videoElement.thumbPath.get(0), element.videoElement.filePath)
|
||||||
}
|
}
|
||||||
})
|
}).then()
|
||||||
// 怎么拿到url呢
|
// 怎么拿到url呢
|
||||||
} else if (element.fileElement) {
|
} else if (element.fileElement) {
|
||||||
message_data["type"] = OB11MessageDataType.file;
|
message_data["type"] = OB11MessageDataType.file;
|
||||||
@@ -144,15 +176,15 @@ export class OB11Constructor {
|
|||||||
// message_data["data"]["path"] = element.fileElement.filePath
|
// message_data["data"]["path"] = element.fileElement.filePath
|
||||||
// message_data["data"]["file_id"] = element.fileElement.fileUuid
|
// message_data["data"]["file_id"] = element.fileElement.fileUuid
|
||||||
message_data["data"]["file_size"] = element.fileElement.fileSize
|
message_data["data"]["file_size"] = element.fileElement.fileSize
|
||||||
fileCache.set(element.fileElement.fileName, {
|
dbUtil.addFileCache(element.fileElement.fileName, {
|
||||||
fileName: element.fileElement.fileName,
|
fileName: element.fileElement.fileName,
|
||||||
filePath: element.fileElement.filePath,
|
filePath: element.fileElement.filePath,
|
||||||
fileSize: element.fileElement.fileSize,
|
fileSize: element.fileElement.fileSize,
|
||||||
downloadFunc: async () => {
|
downloadFunc: async () => {
|
||||||
await NTQQApi.downloadMedia(msg.msgId, msg.chatType, msg.peerUid,
|
await NTQQFileApi.downloadMedia(msg.msgId, msg.chatType, msg.peerUid,
|
||||||
element.elementId, null, element.fileElement.filePath)
|
element.elementId, null, element.fileElement.filePath)
|
||||||
}
|
}
|
||||||
})
|
}).then()
|
||||||
// 怎么拿到url呢
|
// 怎么拿到url呢
|
||||||
} else if (element.pttElement) {
|
} else if (element.pttElement) {
|
||||||
message_data["type"] = OB11MessageDataType.voice;
|
message_data["type"] = OB11MessageDataType.voice;
|
||||||
@@ -160,11 +192,11 @@ export class OB11Constructor {
|
|||||||
message_data["data"]["path"] = element.pttElement.filePath
|
message_data["data"]["path"] = element.pttElement.filePath
|
||||||
// message_data["data"]["file_id"] = element.pttElement.fileUuid
|
// message_data["data"]["file_id"] = element.pttElement.fileUuid
|
||||||
message_data["data"]["file_size"] = element.pttElement.fileSize
|
message_data["data"]["file_size"] = element.pttElement.fileSize
|
||||||
fileCache.set(element.pttElement.fileName, {
|
dbUtil.addFileCache(element.pttElement.fileName, {
|
||||||
fileName: element.pttElement.fileName,
|
fileName: element.pttElement.fileName,
|
||||||
filePath: element.pttElement.filePath,
|
filePath: element.pttElement.filePath,
|
||||||
fileSize: element.pttElement.fileSize,
|
fileSize: element.pttElement.fileSize,
|
||||||
})
|
}).then()
|
||||||
|
|
||||||
// log("收到语音消息", msg)
|
// log("收到语音消息", msg)
|
||||||
// window.LLAPI.Ptt2Text(message.raw.msgId, message.peer, messages).then(text => {
|
// window.LLAPI.Ptt2Text(message.raw.msgId, message.peer, messages).then(text => {
|
||||||
@@ -179,30 +211,6 @@ export class OB11Constructor {
|
|||||||
message_data["type"] = OB11MessageDataType.face;
|
message_data["type"] = OB11MessageDataType.face;
|
||||||
message_data["data"]["id"] = element.faceElement.faceIndex.toString();
|
message_data["data"]["id"] = element.faceElement.faceIndex.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
// if (message_data.data.file) {
|
|
||||||
// let filePath: string = message_data.data.file;
|
|
||||||
// if (!enableLocalFile2Url) {
|
|
||||||
// message_data.data.file = "file://" + filePath
|
|
||||||
// } else { // 不使用本地路径
|
|
||||||
// const ignoreTypes = [OB11MessageDataType.file, OB11MessageDataType.video]
|
|
||||||
// if (!ignoreTypes.includes(message_data.type)) {
|
|
||||||
// if (message_data.data.url && !message_data.data.url.startsWith(IMAGE_HTTP_HOST + "/download")) {
|
|
||||||
// message_data.data.file = message_data.data.url
|
|
||||||
// } else {
|
|
||||||
// let { err, data } = await file2base64(filePath);
|
|
||||||
// if (err) {
|
|
||||||
// log("文件转base64失败", filePath, err)
|
|
||||||
// } else {
|
|
||||||
// message_data.data.file = "base64://" + data
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// } else {
|
|
||||||
// message_data.data.file = "file://" + filePath
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
if (message_data.type !== "unknown" && message_data.data) {
|
if (message_data.type !== "unknown" && message_data.data) {
|
||||||
const cqCode = encodeCQCode(message_data);
|
const cqCode = encodeCQCode(message_data);
|
||||||
if (messagePostFormat === 'string') {
|
if (messagePostFormat === 'string') {
|
||||||
@@ -216,6 +224,83 @@ export class OB11Constructor {
|
|||||||
return resMsg;
|
return resMsg;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static async GroupEvent(msg: RawMessage): Promise<OB11GroupNoticeEvent> {
|
||||||
|
if (msg.chatType !== ChatType.group) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// log("group msg", msg);
|
||||||
|
for (let element of msg.elements) {
|
||||||
|
const grayTipElement = element.grayTipElement
|
||||||
|
const groupElement = grayTipElement?.groupElement
|
||||||
|
if (groupElement) {
|
||||||
|
// log("收到群提示消息", groupElement)
|
||||||
|
if (groupElement.type == TipGroupElementType.memberIncrease) {
|
||||||
|
log("收到群成员增加消息", groupElement)
|
||||||
|
await sleep(1000);
|
||||||
|
const member = await getGroupMember(msg.peerUid, groupElement.memberUid);
|
||||||
|
let memberUin = member?.uin;
|
||||||
|
if (!memberUin) {
|
||||||
|
memberUin = (await NTQQUserApi.getUserDetailInfo(groupElement.memberUid)).uin
|
||||||
|
}
|
||||||
|
// log("获取新群成员QQ", memberUin)
|
||||||
|
const adminMember = await getGroupMember(msg.peerUid, groupElement.adminUid);
|
||||||
|
// log("获取同意新成员入群的管理员", adminMember)
|
||||||
|
if (memberUin) {
|
||||||
|
const operatorUin = adminMember?.uin || memberUin
|
||||||
|
let event = new OB11GroupIncreaseEvent(parseInt(msg.peerUid), parseInt(memberUin), parseInt(operatorUin));
|
||||||
|
// log("构造群增加事件", event)
|
||||||
|
return event;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (groupElement.type === TipGroupElementType.ban) {
|
||||||
|
log("收到群群员禁言提示", groupElement)
|
||||||
|
const memberUid = groupElement.shutUp.member.uid
|
||||||
|
const adminUid = groupElement.shutUp.admin.uid
|
||||||
|
let memberUin: string = ""
|
||||||
|
let duration = parseInt(groupElement.shutUp.duration)
|
||||||
|
let sub_type: "ban" | "lift_ban" = duration > 0 ? "ban" : "lift_ban"
|
||||||
|
if (memberUid){
|
||||||
|
memberUin = (await getGroupMember(msg.peerUid, memberUid))?.uin || (await NTQQUserApi.getUserDetailInfo(memberUid))?.uin
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
memberUin = "0"; // 0表示全员禁言
|
||||||
|
if (duration > 0) {
|
||||||
|
duration = -1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const adminUin = (await getGroupMember(msg.peerUid, adminUid))?.uin || (await NTQQUserApi.getUserDetailInfo(adminUid))?.uin
|
||||||
|
if (memberUin && adminUin) {
|
||||||
|
return new OB11GroupBanEvent(parseInt(msg.peerUid), parseInt(memberUin), parseInt(adminUin), duration, sub_type);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (element.fileElement){
|
||||||
|
return new OB11GroupUploadNoticeEvent(parseInt(msg.peerUid), parseInt(msg.senderUin), {id: element.fileElement.fileUuid, name: element.fileElement.fileName, size: parseInt(element.fileElement.fileSize)})
|
||||||
|
}
|
||||||
|
|
||||||
|
if (grayTipElement) {
|
||||||
|
if (grayTipElement.subElementType == GrayTipElementSubType.INVITE_NEW_MEMBER){
|
||||||
|
log("收到新人被邀请进群消息", grayTipElement)
|
||||||
|
const xmlElement = grayTipElement.xmlElement
|
||||||
|
if (xmlElement?.content){
|
||||||
|
const regex = /jp="(\d+)"/g;
|
||||||
|
|
||||||
|
let matches = [];
|
||||||
|
let match = null
|
||||||
|
|
||||||
|
while ((match = regex.exec(xmlElement.content)) !== null) {
|
||||||
|
matches.push(match[1]);
|
||||||
|
}
|
||||||
|
if (matches.length === 2){
|
||||||
|
const [inviter, invitee] = matches;
|
||||||
|
return new OB11GroupIncreaseEvent(parseInt(msg.peerUid), parseInt(invitee), parseInt(inviter), "invite");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
static friend(friend: User): OB11User {
|
static friend(friend: User): OB11User {
|
||||||
return {
|
return {
|
||||||
user_id: parseInt(friend.uin),
|
user_id: parseInt(friend.uin),
|
||||||
@@ -244,16 +329,25 @@ export class OB11Constructor {
|
|||||||
}[role]
|
}[role]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static sex(sex: Sex): OB11UserSex{
|
||||||
|
const sexMap = {
|
||||||
|
[Sex.male]: OB11UserSex.male,
|
||||||
|
[Sex.female]: OB11UserSex.female,
|
||||||
|
[Sex.unknown]: OB11UserSex.unknown
|
||||||
|
}
|
||||||
|
return sexMap[sex] || OB11UserSex.unknown
|
||||||
|
}
|
||||||
static groupMember(group_id: string, member: GroupMember): OB11GroupMember {
|
static groupMember(group_id: string, member: GroupMember): OB11GroupMember {
|
||||||
return {
|
return {
|
||||||
group_id: parseInt(group_id),
|
group_id: parseInt(group_id),
|
||||||
user_id: parseInt(member.uin),
|
user_id: parseInt(member.uin),
|
||||||
nickname: member.nick,
|
nickname: member.nick,
|
||||||
card: member.cardName,
|
card: member.cardName,
|
||||||
sex: OB11UserSex.unknown,
|
sex: OB11Constructor.sex(member.sex),
|
||||||
age: 0,
|
age: 0,
|
||||||
area: "",
|
area: "",
|
||||||
level: 0,
|
level: 0,
|
||||||
|
qq_level: member.qqLevel && calcQQLevel(member.qqLevel) || 0,
|
||||||
join_time: 0, // 暂时没法获取
|
join_time: 0, // 暂时没法获取
|
||||||
last_sent_time: 0, // 暂时没法获取
|
last_sent_time: 0, // 暂时没法获取
|
||||||
title_expire_time: 0,
|
title_expire_time: 0,
|
||||||
|
@@ -46,15 +46,22 @@ export function decodeCQCode(source: string): OB11MessageData[] {
|
|||||||
|
|
||||||
|
|
||||||
export function encodeCQCode(data: OB11MessageData) {
|
export function encodeCQCode(data: OB11MessageData) {
|
||||||
const CQCodeEscape = (text: string) => {
|
const CQCodeEscapeText = (text: string) => {
|
||||||
return text.replace(/\[/g, '[')
|
return text.replace(/\&/g, '&')
|
||||||
|
.replace(/\[/g, '[')
|
||||||
|
.replace(/\]/g, ']')
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
const CQCodeEscape = (text: string) => {
|
||||||
|
return text.replace(/\&/g, '&')
|
||||||
|
.replace(/\[/g, '[')
|
||||||
.replace(/\]/g, ']')
|
.replace(/\]/g, ']')
|
||||||
.replace(/\&/g, '&')
|
|
||||||
.replace(/,/g, ',');
|
.replace(/,/g, ',');
|
||||||
};
|
};
|
||||||
|
|
||||||
if (data.type === 'text') {
|
if (data.type === 'text') {
|
||||||
return CQCodeEscape(data.data.text);
|
return CQCodeEscapeText(data.data.text);
|
||||||
}
|
}
|
||||||
|
|
||||||
let result = '[CQ:' + data.type;
|
let result = '[CQ:' + data.type;
|
||||||
@@ -68,4 +75,4 @@ export function encodeCQCode(data: OB11MessageData) {
|
|||||||
|
|
||||||
// const result = parseCQCode("[CQ:at,qq=114514]早上好啊[CQ:image,file=http://baidu.com/1.jpg,type=show,id=40004]")
|
// const result = parseCQCode("[CQ:at,qq=114514]早上好啊[CQ:image,file=http://baidu.com/1.jpg,type=show,id=40004]")
|
||||||
// const result = parseCQCode("好好好")
|
// const result = parseCQCode("好好好")
|
||||||
// console.log(JSON.stringify(result))
|
// console.log(JSON.stringify(result))
|
||||||
|
17
src/onebot11/event/notice/OB11GroupBanEvent.ts
Normal file
17
src/onebot11/event/notice/OB11GroupBanEvent.ts
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
import {OB11GroupNoticeEvent} from "./OB11GroupNoticeEvent";
|
||||||
|
|
||||||
|
export class OB11GroupBanEvent extends OB11GroupNoticeEvent {
|
||||||
|
notice_type = "group_ban";
|
||||||
|
operator_id: number;
|
||||||
|
duration: number;
|
||||||
|
sub_type: "ban" | "lift_ban";
|
||||||
|
|
||||||
|
constructor(groupId: number, userId: number, operatorId: number, duration: number, sub_type: "ban" | "lift_ban") {
|
||||||
|
super();
|
||||||
|
this.group_id = groupId;
|
||||||
|
this.operator_id = operatorId;
|
||||||
|
this.user_id = userId;
|
||||||
|
this.duration = duration;
|
||||||
|
this.sub_type = sub_type;
|
||||||
|
}
|
||||||
|
}
|
@@ -1,14 +1,15 @@
|
|||||||
import {OB11GroupNoticeEvent} from "./OB11GroupNoticeEvent";
|
import {OB11GroupNoticeEvent} from "./OB11GroupNoticeEvent";
|
||||||
|
|
||||||
|
type GroupIncreaseSubType = "approve" | "invite";
|
||||||
export class OB11GroupIncreaseEvent extends OB11GroupNoticeEvent {
|
export class OB11GroupIncreaseEvent extends OB11GroupNoticeEvent {
|
||||||
notice_type = "group_increase";
|
notice_type = "group_increase";
|
||||||
sub_type = "approve"; // TODO: 实现其他几种子类型的识别 ("approve" | "invite")
|
|
||||||
operator_id: number;
|
operator_id: number;
|
||||||
|
sub_type: GroupIncreaseSubType;
|
||||||
constructor(groupId: number, userId: number) {
|
constructor(groupId: number, userId: number, operatorId: number, subType: GroupIncreaseSubType = "approve") {
|
||||||
super();
|
super();
|
||||||
this.group_id = groupId;
|
this.group_id = groupId;
|
||||||
this.operator_id = userId; // 实际上不应该这么实现,但是现在还没有办法识别用户是被邀请的,还是主动加入的
|
this.operator_id = operatorId;
|
||||||
this.user_id = userId;
|
this.user_id = userId;
|
||||||
|
this.sub_type = subType
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
19
src/onebot11/event/notice/OB11GroupUploadNoticeEvent.ts
Normal file
19
src/onebot11/event/notice/OB11GroupUploadNoticeEvent.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import {OB11GroupNoticeEvent} from "./OB11GroupNoticeEvent";
|
||||||
|
|
||||||
|
export interface GroupUploadFile{
|
||||||
|
id: string,
|
||||||
|
name: string,
|
||||||
|
size: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export class OB11GroupUploadNoticeEvent extends OB11GroupNoticeEvent {
|
||||||
|
notice_type = "group_upload"
|
||||||
|
file: GroupUploadFile
|
||||||
|
|
||||||
|
constructor(groupId: number, userId: number, file: GroupUploadFile) {
|
||||||
|
super();
|
||||||
|
this.group_id = groupId;
|
||||||
|
this.user_id = userId;
|
||||||
|
this.file = file
|
||||||
|
}
|
||||||
|
}
|
31
src/onebot11/event/notice/OB11PokeEvent.ts
Normal file
31
src/onebot11/event/notice/OB11PokeEvent.ts
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
import {OB11BaseNoticeEvent} from "./OB11BaseNoticeEvent";
|
||||||
|
import {selfInfo} from "../../../common/data";
|
||||||
|
import {OB11BaseEvent} from "../OB11BaseEvent";
|
||||||
|
|
||||||
|
class OB11PokeEvent extends OB11BaseNoticeEvent{
|
||||||
|
notice_type = "notify"
|
||||||
|
sub_type = "poke"
|
||||||
|
target_id = parseInt(selfInfo.uin)
|
||||||
|
user_id: number
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
export class OB11FriendPokeEvent extends OB11PokeEvent{
|
||||||
|
sender_id: number
|
||||||
|
constructor(user_id: number) {
|
||||||
|
super();
|
||||||
|
this.user_id = user_id;
|
||||||
|
this.sender_id = user_id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class OB11GroupPokeEvent extends OB11PokeEvent{
|
||||||
|
group_id: number
|
||||||
|
|
||||||
|
constructor(group_id: number, user_id: number=0) {
|
||||||
|
super();
|
||||||
|
this.group_id = group_id;
|
||||||
|
this.target_id = user_id;
|
||||||
|
this.user_id = user_id;
|
||||||
|
}
|
||||||
|
}
|
@@ -1,8 +1,8 @@
|
|||||||
import {Response} from "express";
|
import {Response} from "express";
|
||||||
import {getConfigUtil} from "../../common/utils";
|
|
||||||
import {OB11Response} from "../action/utils";
|
import {OB11Response} from "../action/utils";
|
||||||
import {HttpServerBase} from "../../common/server/http";
|
import {HttpServerBase} from "../../common/server/http";
|
||||||
import {actionHandlers} from "../action";
|
import {actionHandlers} from "../action";
|
||||||
|
import {getConfigUtil} from "../../common/config";
|
||||||
|
|
||||||
class OB11HTTPServer extends HttpServerBase {
|
class OB11HTTPServer extends HttpServerBase {
|
||||||
name = "OneBot V11 server"
|
name = "OneBot V11 server"
|
||||||
@@ -20,8 +20,10 @@ class OB11HTTPServer extends HttpServerBase {
|
|||||||
|
|
||||||
export const ob11HTTPServer = new OB11HTTPServer();
|
export const ob11HTTPServer = new OB11HTTPServer();
|
||||||
|
|
||||||
for (const action of actionHandlers) {
|
setTimeout(() => {
|
||||||
for (const method of ["post", "get"]) {
|
for (const action of actionHandlers) {
|
||||||
ob11HTTPServer.registerRouter(method, action.actionName, (res, payload) => action.handle(payload))
|
for (const method of ["post", "get"]) {
|
||||||
|
ob11HTTPServer.registerRouter(method, action.actionName, (res, payload) => action.handle(payload))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}, 0)
|
@@ -1,10 +1,11 @@
|
|||||||
import {getConfigUtil, log} from "../../common/utils";
|
|
||||||
import {OB11Message} from "../types";
|
import {OB11Message} from "../types";
|
||||||
import {selfInfo} from "../../common/data";
|
import {selfInfo} from "../../common/data";
|
||||||
import {OB11BaseMetaEvent} from "../event/meta/OB11BaseMetaEvent";
|
import {OB11BaseMetaEvent} from "../event/meta/OB11BaseMetaEvent";
|
||||||
import {OB11BaseNoticeEvent} from "../event/notice/OB11BaseNoticeEvent";
|
import {OB11BaseNoticeEvent} from "../event/notice/OB11BaseNoticeEvent";
|
||||||
import {WebSocket as WebSocketClass} from "ws";
|
import {WebSocket as WebSocketClass} from "ws";
|
||||||
import {wsReply} from "./ws/reply";
|
import {wsReply} from "./ws/reply";
|
||||||
|
import {log} from "../../common/utils/log";
|
||||||
|
import {getConfigUtil} from "../../common/config";
|
||||||
|
|
||||||
export type PostEventType = OB11Message | OB11BaseMetaEvent | OB11BaseNoticeEvent
|
export type PostEventType = OB11Message | OB11BaseMetaEvent | OB11BaseNoticeEvent
|
||||||
|
|
||||||
|
@@ -1,6 +1,3 @@
|
|||||||
import {getConfigUtil, log} from "../../../common/utils";
|
|
||||||
|
|
||||||
|
|
||||||
import {selfInfo} from "../../../common/data";
|
import {selfInfo} from "../../../common/data";
|
||||||
import {LifeCycleSubType, OB11LifeCycleEvent} from "../../event/meta/OB11LifeCycleEvent";
|
import {LifeCycleSubType, OB11LifeCycleEvent} from "../../event/meta/OB11LifeCycleEvent";
|
||||||
import {ActionName} from "../../action/types";
|
import {ActionName} from "../../action/types";
|
||||||
@@ -11,6 +8,8 @@ import {postWsEvent, registerWsEventSender, unregisterWsEventSender} from "../po
|
|||||||
import {wsReply} from "./reply";
|
import {wsReply} from "./reply";
|
||||||
import {WebSocket as WebSocketClass} from "ws";
|
import {WebSocket as WebSocketClass} from "ws";
|
||||||
import {OB11HeartbeatEvent} from "../../event/meta/OB11HeartbeatEvent";
|
import {OB11HeartbeatEvent} from "../../event/meta/OB11HeartbeatEvent";
|
||||||
|
import {log} from "../../../common/utils/log";
|
||||||
|
import {getConfigUtil} from "../../../common/config";
|
||||||
|
|
||||||
export let rwsList: ReverseWebsocket[] = [];
|
export let rwsList: ReverseWebsocket[] = [];
|
||||||
|
|
||||||
|
@@ -1,5 +1,4 @@
|
|||||||
import {WebSocket} from "ws";
|
import {WebSocket} from "ws";
|
||||||
import {getConfigUtil, log} from "../../../common/utils";
|
|
||||||
import {actionMap} from "../../action";
|
import {actionMap} from "../../action";
|
||||||
import {OB11Response} from "../../action/utils";
|
import {OB11Response} from "../../action/utils";
|
||||||
import {postWsEvent, registerWsEventSender, unregisterWsEventSender} from "../postOB11Event";
|
import {postWsEvent, registerWsEventSender, unregisterWsEventSender} from "../postOB11Event";
|
||||||
@@ -11,6 +10,8 @@ import {WebsocketServerBase} from "../../../common/server/websocket";
|
|||||||
import {IncomingMessage} from "node:http";
|
import {IncomingMessage} from "node:http";
|
||||||
import {wsReply} from "./reply";
|
import {wsReply} from "./reply";
|
||||||
import {selfInfo} from "../../../common/data";
|
import {selfInfo} from "../../../common/data";
|
||||||
|
import {log} from "../../../common/utils/log";
|
||||||
|
import {getConfigUtil} from "../../../common/config";
|
||||||
|
|
||||||
let heartbeatRunning = false;
|
let heartbeatRunning = false;
|
||||||
|
|
||||||
@@ -28,7 +29,7 @@ class OB11WebsocketServer extends WebsocketServerBase {
|
|||||||
let handleResult = await action.websocketHandle(params, echo);
|
let handleResult = await action.websocketHandle(params, echo);
|
||||||
wsReply(wsClient, handleResult)
|
wsReply(wsClient, handleResult)
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
wsReply(wsClient, OB11Response.error(`api处理出错:${e}`, 1200, echo))
|
wsReply(wsClient, OB11Response.error(`api处理出错:${e.stack}`, 1200, echo))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -1,7 +1,8 @@
|
|||||||
import {WebSocket as WebSocketClass} from "ws";
|
import {WebSocket as WebSocketClass} from "ws";
|
||||||
import {OB11Response} from "../../action/utils";
|
import {OB11Response} from "../../action/utils";
|
||||||
import {PostEventType} from "../postOB11Event";
|
import {PostEventType} from "../postOB11Event";
|
||||||
import {isNull, log} from "../../../common/utils";
|
import {log} from "../../../common/utils/log";
|
||||||
|
import {isNull} from "../../../common/utils/helper";
|
||||||
|
|
||||||
export function wsReply(wsClient: WebSocketClass, data: OB11Response | PostEventType) {
|
export function wsReply(wsClient: WebSocketClass, data: OB11Response | PostEventType) {
|
||||||
try {
|
try {
|
||||||
|
@@ -29,6 +29,7 @@ export interface OB11GroupMember {
|
|||||||
join_time?: number
|
join_time?: number
|
||||||
last_sent_time?: number
|
last_sent_time?: number
|
||||||
level?: number
|
level?: number
|
||||||
|
qq_level?: number
|
||||||
role?: OB11GroupMemberRole
|
role?: OB11GroupMemberRole
|
||||||
title?: string
|
title?: string
|
||||||
area?: string
|
area?: string
|
||||||
@@ -64,10 +65,11 @@ export enum OB11MessageType {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface OB11Message {
|
export interface OB11Message {
|
||||||
|
target_id?: number; // 自己发送的消息才有此字段
|
||||||
self_id?: number,
|
self_id?: number,
|
||||||
time: number,
|
time: number,
|
||||||
message_id: number,
|
message_id: number,
|
||||||
real_id: string,
|
real_id: number,
|
||||||
user_id: number,
|
user_id: number,
|
||||||
group_id?: number,
|
group_id?: number,
|
||||||
message_type: "private" | "group",
|
message_type: "private" | "group",
|
||||||
@@ -121,6 +123,9 @@ interface OB11MessageFileBase {
|
|||||||
|
|
||||||
export interface OB11MessageImage extends OB11MessageFileBase {
|
export interface OB11MessageImage extends OB11MessageFileBase {
|
||||||
type: OB11MessageDataType.image
|
type: OB11MessageDataType.image
|
||||||
|
data: OB11MessageFileBase['data'] & {
|
||||||
|
summary ? : string; // 图片摘要
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface OB11MessageRecord extends OB11MessageFileBase {
|
export interface OB11MessageRecord extends OB11MessageFileBase {
|
||||||
|
@@ -1,17 +1,23 @@
|
|||||||
import {DATA_DIR, isGIF, log} from "../common/utils";
|
import {DATA_DIR} from "../common/utils";
|
||||||
import {v4 as uuidv4} from "uuid";
|
import {v4 as uuidv4} from "uuid";
|
||||||
import * as path from 'node:path';
|
import * as path from 'node:path';
|
||||||
import {fileCache} from "../common/data";
|
|
||||||
import * as fileType from 'file-type';
|
import * as fileType from 'file-type';
|
||||||
|
import {dbUtil} from "../common/db";
|
||||||
|
import {isGIF} from "../common/utils/file";
|
||||||
|
import {log} from "../common/utils/log";
|
||||||
|
|
||||||
const fs = require("fs").promises;
|
const fs = require("fs").promises;
|
||||||
|
|
||||||
export async function uri2local(uri: string, fileName: string = null) {
|
type Uri2LocalRes = {
|
||||||
if (!fileName) {
|
success: boolean,
|
||||||
fileName = uuidv4();
|
errMsg: string,
|
||||||
}
|
fileName: string,
|
||||||
let filePath = path.join(DATA_DIR, fileName)
|
ext: string,
|
||||||
let url = new URL(uri);
|
path: string,
|
||||||
|
isLocal: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function uri2local(uri: string, fileName: string = null) : Promise<Uri2LocalRes>{
|
||||||
let res = {
|
let res = {
|
||||||
success: false,
|
success: false,
|
||||||
errMsg: "",
|
errMsg: "",
|
||||||
@@ -20,6 +26,19 @@ export async function uri2local(uri: string, fileName: string = null) {
|
|||||||
path: "",
|
path: "",
|
||||||
isLocal: false
|
isLocal: false
|
||||||
}
|
}
|
||||||
|
if (!fileName) {
|
||||||
|
fileName = uuidv4();
|
||||||
|
}
|
||||||
|
let filePath = path.join(DATA_DIR, fileName)
|
||||||
|
let url = null;
|
||||||
|
try{
|
||||||
|
url = new URL(uri);
|
||||||
|
}catch (e) {
|
||||||
|
res.errMsg = `uri ${uri} 解析失败,` + e.toString() + ` 可能${uri}不存在`
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
|
// log("uri protocol", url.protocol, uri);
|
||||||
if (url.protocol == "base64:") {
|
if (url.protocol == "base64:") {
|
||||||
// base64转成文件
|
// base64转成文件
|
||||||
let base64Data = uri.split("base64://")[1]
|
let base64Data = uri.split("base64://")[1]
|
||||||
@@ -33,7 +52,13 @@ export async function uri2local(uri: string, fileName: string = null) {
|
|||||||
}
|
}
|
||||||
} else if (url.protocol == "http:" || url.protocol == "https:") {
|
} else if (url.protocol == "http:" || url.protocol == "https:") {
|
||||||
// 下载文件
|
// 下载文件
|
||||||
let fetchRes = await fetch(url)
|
let fetchRes: Response;
|
||||||
|
try{
|
||||||
|
fetchRes = await fetch(url)
|
||||||
|
}catch (e) {
|
||||||
|
res.errMsg = `${url}下载失败`
|
||||||
|
return res
|
||||||
|
}
|
||||||
if (!fetchRes.ok) {
|
if (!fetchRes.ok) {
|
||||||
res.errMsg = `${url}下载失败,` + fetchRes.statusText
|
res.errMsg = `${url}下载失败,` + fetchRes.statusText
|
||||||
return res
|
return res
|
||||||
@@ -46,7 +71,7 @@ export async function uri2local(uri: string, fileName: string = null) {
|
|||||||
fileName = pathInfo.name
|
fileName = pathInfo.name
|
||||||
if (pathInfo.ext){
|
if (pathInfo.ext){
|
||||||
fileName += pathInfo.ext
|
fileName += pathInfo.ext
|
||||||
res.ext = pathInfo.ext
|
// res.ext = pathInfo.ext
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
res.fileName = fileName
|
res.fileName = fileName
|
||||||
@@ -67,7 +92,7 @@ export async function uri2local(uri: string, fileName: string = null) {
|
|||||||
filePath = pathname
|
filePath = pathname
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
const cache = fileCache.get(uri)
|
const cache = await dbUtil.getFileCache(uri);
|
||||||
if (cache) {
|
if (cache) {
|
||||||
filePath = cache.filePath
|
filePath = cache.filePath
|
||||||
} else {
|
} else {
|
||||||
|
@@ -1,12 +1,14 @@
|
|||||||
// Electron 主进程 与 渲染进程 交互的桥梁
|
// Electron 主进程 与 渲染进程 交互的桥梁
|
||||||
|
|
||||||
import {Config, LLOneBotError} from "./common/types";
|
import {CheckVersion, Config, LLOneBotError} from "./common/types";
|
||||||
import {
|
import {
|
||||||
CHANNEL_ERROR,
|
CHANNEL_ERROR,
|
||||||
CHANNEL_GET_CONFIG,
|
CHANNEL_GET_CONFIG,
|
||||||
CHANNEL_LOG,
|
CHANNEL_LOG,
|
||||||
|
CHANNEL_CHECKVERSION,
|
||||||
CHANNEL_SELECT_FILE,
|
CHANNEL_SELECT_FILE,
|
||||||
CHANNEL_SET_CONFIG,
|
CHANNEL_SET_CONFIG,
|
||||||
|
CHANNEL_UPDATE,
|
||||||
} from "./common/channels";
|
} from "./common/channels";
|
||||||
|
|
||||||
const {contextBridge} = require("electron");
|
const {contextBridge} = require("electron");
|
||||||
@@ -16,6 +18,12 @@ const llonebot = {
|
|||||||
log: (data: any) => {
|
log: (data: any) => {
|
||||||
ipcRenderer.send(CHANNEL_LOG, data);
|
ipcRenderer.send(CHANNEL_LOG, data);
|
||||||
},
|
},
|
||||||
|
checkVersion:async (): Promise<CheckVersion> => {
|
||||||
|
return ipcRenderer.invoke(CHANNEL_CHECKVERSION);
|
||||||
|
},
|
||||||
|
updateLLOneBot:async (): Promise<boolean> => {
|
||||||
|
return ipcRenderer.invoke(CHANNEL_UPDATE);
|
||||||
|
},
|
||||||
setConfig: (config: Config) => {
|
setConfig: (config: Config) => {
|
||||||
ipcRenderer.send(CHANNEL_SET_CONFIG, config);
|
ipcRenderer.send(CHANNEL_SET_CONFIG, config);
|
||||||
},
|
},
|
||||||
|
@@ -90,8 +90,8 @@ async function onSettingWindowCreated(view: Element) {
|
|||||||
], 'ob11.messagePostFormat', config.ob11.messagePostFormat),
|
], 'ob11.messagePostFormat', config.ob11.messagePostFormat),
|
||||||
),
|
),
|
||||||
SettingItem(
|
SettingItem(
|
||||||
'ffmpeg 路径', `<span id="config-ffmpeg-path-text">${!isEmpty(config.ffmpeg) ? config.ffmpeg : '未指定'}</span>`,
|
'ffmpeg 路径,发送语音、视频需要,同时保证ffprobe和ffmpeg在一起', ` <a href="javascript:LiteLoader.api.openExternal(\'https://llonebot.github.io/zh-CN/guide/ffmpeg\');">下载地址</a> <span id="config-ffmpeg-path-text">, 路径:${!isEmpty(config.ffmpeg) ? config.ffmpeg : '未指定'}</span>`,
|
||||||
SettingButton('选择', 'config-ffmpeg-select'),
|
SettingButton('选择ffmpeg', 'config-ffmpeg-select'),
|
||||||
),
|
),
|
||||||
SettingItem(
|
SettingItem(
|
||||||
'', null,
|
'', null,
|
||||||
@@ -99,6 +99,11 @@ async function onSettingWindowCreated(view: Element) {
|
|||||||
)
|
)
|
||||||
]),
|
]),
|
||||||
SettingList([
|
SettingList([
|
||||||
|
SettingItem(
|
||||||
|
'接收戳一戳消息, 暂时只支持Windows版的LLOneBot',
|
||||||
|
`重启QQ后生效,如果导致QQ崩溃请勿开启此项`,
|
||||||
|
SettingSwitch('enablePoke', config.enablePoke),
|
||||||
|
),
|
||||||
SettingItem(
|
SettingItem(
|
||||||
'使用 Base64 编码获取文件',
|
'使用 Base64 编码获取文件',
|
||||||
'开启后,调用 /get_image、/get_record 时,获取不到 url 时添加一个 Base64 字段',
|
'开启后,调用 /get_image、/get_record 时,获取不到 url 时添加一个 Base64 字段',
|
||||||
@@ -138,9 +143,14 @@ async function onSettingWindowCreated(view: Element) {
|
|||||||
]),
|
]),
|
||||||
SettingList([
|
SettingList([
|
||||||
SettingItem(
|
SettingItem(
|
||||||
'GitHub',
|
'GitHub 仓库',
|
||||||
`https://github.com/LLOneBot/LLOneBot`,
|
`https://github.com/LLOneBot/LLOneBot`,
|
||||||
SettingButton('点个Star', 'open-github'),
|
SettingButton('点个星星', 'open-github'),
|
||||||
|
),
|
||||||
|
SettingItem(
|
||||||
|
'LLOneBot 文档',
|
||||||
|
`https://llonebot.github.io/`,
|
||||||
|
SettingButton('看看文档', 'open-docs'),
|
||||||
),
|
),
|
||||||
SettingItem(
|
SettingItem(
|
||||||
'Telegram 群',
|
'Telegram 群',
|
||||||
@@ -166,18 +176,20 @@ async function onSettingWindowCreated(view: Element) {
|
|||||||
doc.querySelector('#open-qq-group').addEventListener('click', () => {
|
doc.querySelector('#open-qq-group').addEventListener('click', () => {
|
||||||
window.LiteLoader.api.openExternal('https://qm.qq.com/q/bDnHRG38aI')
|
window.LiteLoader.api.openExternal('https://qm.qq.com/q/bDnHRG38aI')
|
||||||
})
|
})
|
||||||
|
doc.querySelector('#open-docs').addEventListener('click', () => {
|
||||||
|
window.LiteLoader.api.openExternal('https://llonebot.github.io/')
|
||||||
|
})
|
||||||
// 生成反向地址列表
|
// 生成反向地址列表
|
||||||
const buildHostListItem = (type: string, host: string, index: number) => {
|
const buildHostListItem = (type: string, host: string, index: number, inputAttrs: any={}) => {
|
||||||
const dom = {
|
const dom = {
|
||||||
container: document.createElement('setting-item'),
|
container: document.createElement('setting-item'),
|
||||||
input: document.createElement('input'),
|
input: document.createElement('input'),
|
||||||
inputContainer: document.createElement('div'),
|
inputContainer: document.createElement('div'),
|
||||||
deleteBtn: document.createElement('setting-button'),
|
deleteBtn: document.createElement('setting-button'),
|
||||||
};
|
};
|
||||||
|
|
||||||
dom.container.classList.add('setting-host-list-item');
|
dom.container.classList.add('setting-host-list-item');
|
||||||
dom.container.dataset.direction = 'row';
|
dom.container.dataset.direction = 'row';
|
||||||
|
Object.assign(dom.input, inputAttrs);
|
||||||
dom.input.classList.add('q-input__inner');
|
dom.input.classList.add('q-input__inner');
|
||||||
dom.input.type = 'url';
|
dom.input.type = 'url';
|
||||||
dom.input.value = host;
|
dom.input.value = host;
|
||||||
@@ -200,18 +212,18 @@ async function onSettingWindowCreated(view: Element) {
|
|||||||
|
|
||||||
return dom.container;
|
return dom.container;
|
||||||
};
|
};
|
||||||
const buildHostList = (hosts: string[], type: string) => {
|
const buildHostList = (hosts: string[], type: string, inputAttr: any={}) => {
|
||||||
const result: HTMLElement[] = [];
|
const result: HTMLElement[] = [];
|
||||||
|
|
||||||
hosts.forEach((host, index) => {
|
hosts.forEach((host, index) => {
|
||||||
result.push(buildHostListItem(type, host, index));
|
result.push(buildHostListItem(type, host, index, inputAttr));
|
||||||
});
|
});
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
};
|
};
|
||||||
const addReverseHost = (type: string, doc: Document = document) => {
|
const addReverseHost = (type: string, doc: Document = document, inputAttr: any={}) => {
|
||||||
const hostContainerDom = doc.body.querySelector(`#config-ob11-${type}-list`);
|
const hostContainerDom = doc.body.querySelector(`#config-ob11-${type}-list`);
|
||||||
hostContainerDom.appendChild(buildHostListItem(type, '', ob11Config[type].length));
|
hostContainerDom.appendChild(buildHostListItem(type, '', ob11Config[type].length, inputAttr));
|
||||||
ob11Config[type].push('');
|
ob11Config[type].push('');
|
||||||
};
|
};
|
||||||
const initReverseHost = (type: string, doc: Document = document) => {
|
const initReverseHost = (type: string, doc: Document = document) => {
|
||||||
@@ -224,8 +236,8 @@ async function onSettingWindowCreated(view: Element) {
|
|||||||
initReverseHost('httpHosts', doc);
|
initReverseHost('httpHosts', doc);
|
||||||
initReverseHost('wsHosts', doc);
|
initReverseHost('wsHosts', doc);
|
||||||
|
|
||||||
doc.querySelector('#config-ob11-httpHosts-add').addEventListener('click', () => addReverseHost('httpHosts'));
|
doc.querySelector('#config-ob11-httpHosts-add').addEventListener('click', () => addReverseHost('httpHosts', document, {'placeholder': '如:http://127.0.0.1:5140/onebot' }));
|
||||||
doc.querySelector('#config-ob11-wsHosts-add').addEventListener('click', () => addReverseHost('wsHosts'));
|
doc.querySelector('#config-ob11-wsHosts-add').addEventListener('click', () => addReverseHost('wsHosts', document, {'placeholder': '如:ws://127.0.0.1:5140/onebot' }));
|
||||||
|
|
||||||
doc.querySelector('#config-ffmpeg-select').addEventListener('click', () => {
|
doc.querySelector('#config-ffmpeg-select').addEventListener('click', () => {
|
||||||
window.llonebot.selectFile()
|
window.llonebot.selectFile()
|
||||||
|
@@ -1 +1 @@
|
|||||||
export const version = "3.13.0"
|
export const version = "3.16.1"
|
Reference in New Issue
Block a user