mirror of
https://github.com/NapNeko/NapCatQQ.git
synced 2025-07-19 12:03:37 +00:00
Compare commits
2 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
63902d440f | ||
![]() |
cea900ca2a |
16
README.md
16
README.md
@@ -1,9 +1,8 @@
|
|||||||
<img src="https://napneko.github.io/assets/newnewlogo.png" width = "305" height = "411" alt="NapCat" align=right />
|
|
||||||
<div align="center">
|
<div align="center">
|
||||||
|
|
||||||
# NapCat
|
# NapCat
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
_Modern protocol-side framework implemented based on NTQQ._
|
_Modern protocol-side framework implemented based on NTQQ._
|
||||||
|
|
||||||
@@ -41,18 +40,13 @@ _Modern protocol-side framework implemented based on NTQQ._
|
|||||||
| Docs | [](https://napneko.pages.dev/) | [](https://napcat.cyou/) | [](https://www.napcat.wiki) |
|
| Docs | [](https://napneko.pages.dev/) | [](https://napcat.cyou/) | [](https://www.napcat.wiki) |
|
||||||
|:-:|:-:|:-:|:-:|
|
|:-:|:-:|:-:|:-:|
|
||||||
|
|
||||||
| QQ Group | [](https://qm.qq.com/q/CMmPbGw0jA) | [](https://qm.qq.com/q/8zJMLjqy2Y) | [](https://qm.qq.com/q/HaRcfrHpUk) | [](https://qm.qq.com/q/I6LU87a0Yq) |
|
| Contact | [](https://qm.qq.com/q/I6LU87a0Yq) | [](https://qm.qq.com/q/HaRcfrHpUk) | [](https://t.me/MelodicMoonlight) |
|
||||||
|:-:|:-:|:-:|:-:|:-:|
|
|:-:|:-:|:-:|:-:|
|
||||||
|
|
||||||
| Telegram | [](https://t.me/MelodicMoonlight) |
|
|
||||||
|:-:|:-:|
|
|
||||||
|
|
||||||
## Thanks
|
## Thanks
|
||||||
|
|
||||||
+ [Lagrange](https://github.com/LagrangeDev/Lagrange.Core) 对本项目的大力支持 参考部分代码 已获授权
|
+ [Lagrange](https://github.com/LagrangeDev/Lagrange.Core) 对本项目的大力支持 参考部分代码 已获授权
|
||||||
|
|
||||||
+ [AstrBot](https://github.com/AstrBotDevs/AstrBot) 是完美适配本项目的LLM Bot框架 在此推荐一下
|
|
||||||
|
|
||||||
+ 不过最最重要的 还是需要感谢屏幕前的你哦~
|
+ 不过最最重要的 还是需要感谢屏幕前的你哦~
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -64,3 +58,7 @@ _Modern protocol-side framework implemented based on NTQQ._
|
|||||||
2. 项目其余逻辑代码采用[本仓库开源许可](./LICENSE).
|
2. 项目其余逻辑代码采用[本仓库开源许可](./LICENSE).
|
||||||
|
|
||||||
**本仓库仅用于提高易用性,实现消息推送类功能,此外,禁止任何项目未经仓库主作者授权基于 NapCat 代码开发。使用请遵守当地法律法规,由此造成的问题由使用者和提供违规使用教程者负责。**
|
**本仓库仅用于提高易用性,实现消息推送类功能,此外,禁止任何项目未经仓库主作者授权基于 NapCat 代码开发。使用请遵守当地法律法规,由此造成的问题由使用者和提供违规使用教程者负责。**
|
||||||
|
|
||||||
|
## Warnings
|
||||||
|
|
||||||
|
[某框架抄袭部分分析](https://napneko.github.io/other/about-copy)
|
||||||
|
BIN
external/LiteLoaderWrapper.zip
vendored
BIN
external/LiteLoaderWrapper.zip
vendored
Binary file not shown.
BIN
external/logo.png
vendored
BIN
external/logo.png
vendored
Binary file not shown.
Before Width: | Height: | Size: 250 KiB After Width: | Height: | Size: 204 KiB |
Binary file not shown.
@@ -1,9 +1,9 @@
|
|||||||
{
|
{
|
||||||
"name": "qq-chat",
|
"name": "qq-chat",
|
||||||
"version": "9.9.19-34740",
|
"version": "9.9.18-32869",
|
||||||
"verHash": "f31348f2",
|
"verHash": "e735296c",
|
||||||
"linuxVersion": "3.2.17-34740",
|
"linuxVersion": "3.2.16-32869",
|
||||||
"linuxVerHash": "5aa2d8d6",
|
"linuxVerHash": "4c192ba9",
|
||||||
"private": true,
|
"private": true,
|
||||||
"description": "QQ",
|
"description": "QQ",
|
||||||
"productName": "QQ",
|
"productName": "QQ",
|
||||||
@@ -16,8 +16,25 @@
|
|||||||
"bin": {
|
"bin": {
|
||||||
"qd": "externals/devtools/cli/index.js"
|
"qd": "externals/devtools/cli/index.js"
|
||||||
},
|
},
|
||||||
|
"appid": {
|
||||||
|
"win32": "537258389",
|
||||||
|
"darwin": "537258412",
|
||||||
|
"linux": "537258424"
|
||||||
|
},
|
||||||
"main": "./loadNapCat.js",
|
"main": "./loadNapCat.js",
|
||||||
"buildVersion": "34740",
|
"peerDependenciesMeta": {
|
||||||
|
"*": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"pnpm": {
|
||||||
|
"patchedDependencies": {
|
||||||
|
"@vue/runtime-dom@3.5.12": "patches/@vue__runtime-dom@3.5.12.patch",
|
||||||
|
"@swc/helpers@0.5.3": "patches/@swc__helpers@0.5.3.patch",
|
||||||
|
"vuex@4.1.0": "patches/vuex@4.1.0.patch"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"buildVersion": "32869",
|
||||||
"isPureShell": true,
|
"isPureShell": true,
|
||||||
"isByteCodeShell": true,
|
"isByteCodeShell": true,
|
||||||
"platform": "win32",
|
"platform": "win32",
|
||||||
|
@@ -4,7 +4,7 @@
|
|||||||
"name": "NapCatQQ",
|
"name": "NapCatQQ",
|
||||||
"slug": "NapCat.Framework",
|
"slug": "NapCat.Framework",
|
||||||
"description": "高性能的 OneBot 11 协议实现",
|
"description": "高性能的 OneBot 11 协议实现",
|
||||||
"version": "4.7.57",
|
"version": "4.7.43",
|
||||||
"icon": "./logo.png",
|
"icon": "./logo.png",
|
||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
|
@@ -2,7 +2,7 @@
|
|||||||
"name": "napcat",
|
"name": "napcat",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"version": "4.7.57",
|
"version": "4.7.43",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build:universal": "npm run build:webui && vite build --mode universal || exit 1",
|
"build:universal": "npm run build:webui && vite build --mode universal || exit 1",
|
||||||
"build:framework": "npm run build:webui && vite build --mode framework || exit 1",
|
"build:framework": "npm run build:webui && vite build --mode framework || exit 1",
|
||||||
@@ -41,7 +41,6 @@
|
|||||||
"ajv": "^8.13.0",
|
"ajv": "^8.13.0",
|
||||||
"async-mutex": "^0.5.0",
|
"async-mutex": "^0.5.0",
|
||||||
"commander": "^13.0.0",
|
"commander": "^13.0.0",
|
||||||
"cors": "^2.8.5",
|
|
||||||
"esbuild": "0.25.0",
|
"esbuild": "0.25.0",
|
||||||
"eslint": "^9.14.0",
|
"eslint": "^9.14.0",
|
||||||
"eslint-import-resolver-typescript": "^4.0.0",
|
"eslint-import-resolver-typescript": "^4.0.0",
|
||||||
@@ -63,7 +62,12 @@
|
|||||||
"compressing": "^1.10.1"
|
"compressing": "^1.10.1"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@ffmpeg.wasm/core-mt": "^0.13.2",
|
||||||
|
"cors": "^2.8.5",
|
||||||
|
"compressing": "^1.10.1",
|
||||||
"express": "^5.0.0",
|
"express": "^5.0.0",
|
||||||
|
"openai": "^4.85.1",
|
||||||
|
"piscina": "^4.7.0",
|
||||||
"silk-wasm": "^3.6.1",
|
"silk-wasm": "^3.6.1",
|
||||||
"ws": "^8.18.0"
|
"ws": "^8.18.0"
|
||||||
}
|
}
|
||||||
|
@@ -8,12 +8,11 @@ import { pipeline } from 'stream/promises';
|
|||||||
import { fileURLToPath } from 'url';
|
import { fileURLToPath } from 'url';
|
||||||
import { LogWrapper } from './log';
|
import { LogWrapper } from './log';
|
||||||
|
|
||||||
const downloadOri = "https://github.com/NapNeko/ffmpeg-build/releases/download/v1.0.0/ffmpeg-7.1.1-win64.zip"
|
const downloadOri = "https://github.com/BtbN/FFmpeg-Builds/releases/download/autobuild-2025-04-16-12-54/ffmpeg-n7.1.1-6-g48c0f071d4-win64-lgpl-7.1.zip"
|
||||||
const urls = [
|
const urls = [
|
||||||
"https://github.moeyy.xyz/" + downloadOri,
|
"https://github.moeyy.xyz/" + downloadOri,
|
||||||
"https://ghp.ci/" + downloadOri,
|
"https://ghp.ci/" + downloadOri,
|
||||||
"https://gh.api.99988866.xyz/" + downloadOri,
|
"https://gh.api.99988866.xyz/" + downloadOri,
|
||||||
"https://gh.api.99988866.xyz/" + downloadOri,
|
|
||||||
downloadOri
|
downloadOri
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -337,16 +336,9 @@ export async function downloadFFmpegIfNotExists(log: LogWrapper) {
|
|||||||
const ffprobe_exist = fs.existsSync(path.join(currentPath, 'ffmpeg', 'ffprobe.exe'));
|
const ffprobe_exist = fs.existsSync(path.join(currentPath, 'ffmpeg', 'ffprobe.exe'));
|
||||||
|
|
||||||
if (!ffmpeg_exist || !ffprobe_exist) {
|
if (!ffmpeg_exist || !ffprobe_exist) {
|
||||||
let url = await downloadFFmpeg(path.join(currentPath, 'ffmpeg'), path.join(currentPath, 'cache'), (percentage: number, message: string) => {
|
await downloadFFmpeg(path.join(currentPath, 'ffmpeg'), path.join(currentPath, 'cache'), (percentage: number, message: string) => {
|
||||||
log.log(`[FFmpeg] [Download] ${percentage}% - ${message}`);
|
log.log(`[FFmpeg] [Download] ${percentage}% - ${message}`);
|
||||||
});
|
});
|
||||||
if (!url) {
|
|
||||||
log.log('[FFmpeg] [Error] 下载FFmpeg失败');
|
|
||||||
return {
|
|
||||||
path: null,
|
|
||||||
reset: false
|
|
||||||
};
|
|
||||||
}
|
|
||||||
return {
|
return {
|
||||||
path: path.join(currentPath, 'ffmpeg'),
|
path: path.join(currentPath, 'ffmpeg'),
|
||||||
reset: true
|
reset: true
|
||||||
|
@@ -145,8 +145,8 @@ export enum FileUriType {
|
|||||||
|
|
||||||
export async function checkUriType(Uri: string) {
|
export async function checkUriType(Uri: string) {
|
||||||
const LocalFileRet = await solveProblem((uri: string) => {
|
const LocalFileRet = await solveProblem((uri: string) => {
|
||||||
if (fs.existsSync(path.normalize(uri))) {
|
if (fs.existsSync(uri)) {
|
||||||
return { Uri: path.normalize(uri), Type: FileUriType.Local };
|
return { Uri: uri, Type: FileUriType.Local };
|
||||||
}
|
}
|
||||||
return undefined;
|
return undefined;
|
||||||
}, Uri);
|
}, Uri);
|
||||||
|
@@ -1 +1 @@
|
|||||||
export const napCatVersion = '4.7.57';
|
export const napCatVersion = '4.7.43';
|
||||||
|
@@ -28,8 +28,6 @@ import { SendMessageContext } from '@/onebot/api';
|
|||||||
import { getFileTypeForSendType } from '../helper/msg';
|
import { getFileTypeForSendType } from '../helper/msg';
|
||||||
import { FFmpegService } from '@/common/ffmpeg';
|
import { FFmpegService } from '@/common/ffmpeg';
|
||||||
import { rkeyDataType } from '../types/file';
|
import { rkeyDataType } from '../types/file';
|
||||||
import { NapProtoMsg } from '@napneko/nap-proto-core';
|
|
||||||
import { FileId } from '../packet/transformer/proto/misc/fileid';
|
|
||||||
|
|
||||||
export class NTQQFileApi {
|
export class NTQQFileApi {
|
||||||
context: InstanceContext;
|
context: InstanceContext;
|
||||||
@@ -65,76 +63,6 @@ export class NTQQFileApi {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async getFileUrl(chatType: ChatType, peer: string, fileUUID?: string, file10MMd5?: string | undefined) {
|
|
||||||
if (this.core.apis.PacketApi.available) {
|
|
||||||
try {
|
|
||||||
if (chatType === ChatType.KCHATTYPEGROUP && fileUUID) {
|
|
||||||
return this.core.apis.PacketApi.pkt.operation.GetGroupFileUrl(+peer, fileUUID);
|
|
||||||
} else if (file10MMd5 && fileUUID) {
|
|
||||||
return this.core.apis.PacketApi.pkt.operation.GetPrivateFileUrl(peer, fileUUID, file10MMd5);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
this.context.logger.logError('获取文件URL失败', (error as Error).message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
throw new Error('fileUUID or file10MMd5 is undefined');
|
|
||||||
}
|
|
||||||
|
|
||||||
async getPttUrl(peer: string, fileUUID?: string) {
|
|
||||||
if (this.core.apis.PacketApi.available && fileUUID) {
|
|
||||||
let appid = new NapProtoMsg(FileId).decode(Buffer.from(fileUUID.replaceAll('-', '+').replaceAll('_', '/'), 'base64')).appid;
|
|
||||||
try {
|
|
||||||
if (appid && appid === 1403) {
|
|
||||||
return this.core.apis.PacketApi.pkt.operation.GetGroupPttUrl(+peer, {
|
|
||||||
fileUuid: fileUUID,
|
|
||||||
storeId: 1,
|
|
||||||
uploadTime: 0,
|
|
||||||
ttl: 0,
|
|
||||||
subType: 0,
|
|
||||||
});
|
|
||||||
} else if (fileUUID) {
|
|
||||||
return this.core.apis.PacketApi.pkt.operation.GetPttUrl(peer, {
|
|
||||||
fileUuid: fileUUID,
|
|
||||||
storeId: 1,
|
|
||||||
uploadTime: 0,
|
|
||||||
ttl: 0,
|
|
||||||
subType: 0,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
this.context.logger.logError('获取文件URL失败', (error as Error).message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
throw new Error('packet cant get ptt url');
|
|
||||||
}
|
|
||||||
|
|
||||||
async getVideoUrlPacket(peer: string, fileUUID?: string) {
|
|
||||||
if (this.core.apis.PacketApi.available && fileUUID) {
|
|
||||||
let appid = new NapProtoMsg(FileId).decode(Buffer.from(fileUUID.replaceAll('-', '+').replaceAll('_', '/'), 'base64')).appid;
|
|
||||||
try {
|
|
||||||
if (appid && appid === 1415) {
|
|
||||||
return this.core.apis.PacketApi.pkt.operation.GetGroupVideoUrl(+peer, {
|
|
||||||
fileUuid: fileUUID,
|
|
||||||
storeId: 1,
|
|
||||||
uploadTime: 0,
|
|
||||||
ttl: 0,
|
|
||||||
subType: 0,
|
|
||||||
});
|
|
||||||
} else if (fileUUID) {
|
|
||||||
return this.core.apis.PacketApi.pkt.operation.GetVideoUrl(peer, {
|
|
||||||
fileUuid: fileUUID,
|
|
||||||
storeId: 1,
|
|
||||||
uploadTime: 0,
|
|
||||||
ttl: 0,
|
|
||||||
subType: 0,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
this.context.logger.logError('获取文件URL失败', (error as Error).message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
throw new Error('packet cant get video url');
|
|
||||||
}
|
|
||||||
|
|
||||||
async copyFile(filePath: string, destPath: string) {
|
async copyFile(filePath: string, destPath: string) {
|
||||||
await this.core.util.copyFile(filePath, destPath);
|
await this.core.util.copyFile(filePath, destPath);
|
||||||
@@ -397,7 +325,6 @@ export class NTQQFileApi {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
return res.flat();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async downloadMedia(msgId: string, chatType: ChatType, peerUid: string, elementId: string, thumbPath: string, sourcePath: string, timeout = 1000 * 60 * 2, force: boolean = false) {
|
async downloadMedia(msgId: string, chatType: ChatType, peerUid: string, elementId: string, thumbPath: string, sourcePath: string, timeout = 1000 * 60 * 2, force: boolean = false) {
|
||||||
|
@@ -71,7 +71,6 @@ export class NTQQMsgApi {
|
|||||||
async queryMsgsWithFilterExWithSeq(peer: Peer, msgSeq: string) {
|
async queryMsgsWithFilterExWithSeq(peer: Peer, msgSeq: string) {
|
||||||
return await this.context.session.getMsgService().queryMsgsWithFilterEx('0', '0', msgSeq, {
|
return await this.context.session.getMsgService().queryMsgsWithFilterEx('0', '0', msgSeq, {
|
||||||
chatInfo: peer,
|
chatInfo: peer,
|
||||||
//searchFields: 3,
|
|
||||||
filterMsgType: [],
|
filterMsgType: [],
|
||||||
filterSendersUid: [],
|
filterSendersUid: [],
|
||||||
filterMsgToTime: '0',
|
filterMsgToTime: '0',
|
||||||
@@ -85,7 +84,6 @@ export class NTQQMsgApi {
|
|||||||
return await this.context.session.getMsgService().queryMsgsWithFilterEx('0', '0', msgSeq, {
|
return await this.context.session.getMsgService().queryMsgsWithFilterEx('0', '0', msgSeq, {
|
||||||
chatInfo: peer,
|
chatInfo: peer,
|
||||||
filterMsgType: [],
|
filterMsgType: [],
|
||||||
//searchFields: 3,
|
|
||||||
filterSendersUid: SendersUid,
|
filterSendersUid: SendersUid,
|
||||||
filterMsgToTime: MsgTime,
|
filterMsgToTime: MsgTime,
|
||||||
filterMsgFromTime: MsgTime,
|
filterMsgFromTime: MsgTime,
|
||||||
@@ -102,7 +100,6 @@ export class NTQQMsgApi {
|
|||||||
filterMsgToTime: '0',
|
filterMsgToTime: '0',
|
||||||
filterMsgFromTime: '0',
|
filterMsgFromTime: '0',
|
||||||
isReverseOrder: false,
|
isReverseOrder: false,
|
||||||
//searchFields: 3,
|
|
||||||
isIncludeCurrent: true,
|
isIncludeCurrent: true,
|
||||||
pageLimit: 1,
|
pageLimit: 1,
|
||||||
});
|
});
|
||||||
@@ -113,7 +110,6 @@ export class NTQQMsgApi {
|
|||||||
filterMsgType: [],
|
filterMsgType: [],
|
||||||
filterSendersUid: [],
|
filterSendersUid: [],
|
||||||
filterMsgToTime: '0',
|
filterMsgToTime: '0',
|
||||||
//searchFields: 3,
|
|
||||||
filterMsgFromTime: '0',
|
filterMsgFromTime: '0',
|
||||||
isReverseOrder: true,
|
isReverseOrder: true,
|
||||||
isIncludeCurrent: true,
|
isIncludeCurrent: true,
|
||||||
@@ -132,7 +128,6 @@ export class NTQQMsgApi {
|
|||||||
chatInfo: peer,//此处为Peer 为关键查询参数 没有啥也没有 by mlik iowa
|
chatInfo: peer,//此处为Peer 为关键查询参数 没有啥也没有 by mlik iowa
|
||||||
filterMsgType: [],
|
filterMsgType: [],
|
||||||
filterSendersUid: [],
|
filterSendersUid: [],
|
||||||
//searchFields: 3,
|
|
||||||
filterMsgToTime: filterMsgToTime,
|
filterMsgToTime: filterMsgToTime,
|
||||||
filterMsgFromTime: filterMsgFromTime,
|
filterMsgFromTime: filterMsgFromTime,
|
||||||
isReverseOrder: false,
|
isReverseOrder: false,
|
||||||
@@ -147,7 +142,6 @@ export class NTQQMsgApi {
|
|||||||
chatInfo: peer,
|
chatInfo: peer,
|
||||||
filterMsgType: [],
|
filterMsgType: [],
|
||||||
filterSendersUid: SendersUid,
|
filterSendersUid: SendersUid,
|
||||||
//searchFields: 3,
|
|
||||||
filterMsgToTime: '0',
|
filterMsgToTime: '0',
|
||||||
filterMsgFromTime: '0',
|
filterMsgFromTime: '0',
|
||||||
isReverseOrder: true,
|
isReverseOrder: true,
|
||||||
|
12
src/core/external/appid.json
vendored
12
src/core/external/appid.json
vendored
@@ -274,17 +274,5 @@
|
|||||||
"9.9.19-34606": {
|
"9.9.19-34606": {
|
||||||
"appid": 537282307,
|
"appid": 537282307,
|
||||||
"qua": "V1_WIN_NQ_9.9.19_34606_GW_B"
|
"qua": "V1_WIN_NQ_9.9.19_34606_GW_B"
|
||||||
},
|
|
||||||
"9.9.19-34740": {
|
|
||||||
"appid": 537290691,
|
|
||||||
"qua": "V1_WIN_NQ_9.9.19_34740_GW_B"
|
|
||||||
},
|
|
||||||
"3.2.17-34740": {
|
|
||||||
"appid": 537290727,
|
|
||||||
"qua": "V1_LNX_NQ_3.2.17_34740_GW_B"
|
|
||||||
},
|
|
||||||
"9.9.19-34958": {
|
|
||||||
"appid": 537290742,
|
|
||||||
"qua": "V1_WIN_NQ_9.9.19_34958_GW_B"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
16
src/core/external/offset.json
vendored
16
src/core/external/offset.json
vendored
@@ -350,21 +350,5 @@
|
|||||||
"3.2.17-34606-arm64": {
|
"3.2.17-34606-arm64": {
|
||||||
"send": "7711270",
|
"send": "7711270",
|
||||||
"recv": "7714BA0"
|
"recv": "7714BA0"
|
||||||
},
|
|
||||||
"9.9.19-34740-x64": {
|
|
||||||
"send": "3BDD8D0",
|
|
||||||
"recv": "3BE20D0"
|
|
||||||
},
|
|
||||||
"3.2.17-34740-x64": {
|
|
||||||
"send": "ADDF0A0",
|
|
||||||
"recv": "ADE2AC0"
|
|
||||||
},
|
|
||||||
"3.2.17-34740-arm64": {
|
|
||||||
"send": "7753BB8",
|
|
||||||
"recv": "77574E8"
|
|
||||||
},
|
|
||||||
"9.9.19-34958-x64": {
|
|
||||||
"send": "3BDD8D0",
|
|
||||||
"recv": "3BE20D0"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
@@ -3,43 +3,43 @@ import { BuddyCategoryType, FriendRequestNotify } from '@/core/types';
|
|||||||
export type OnBuddyChangeParams = BuddyCategoryType[];
|
export type OnBuddyChangeParams = BuddyCategoryType[];
|
||||||
|
|
||||||
export class NodeIKernelBuddyListener {
|
export class NodeIKernelBuddyListener {
|
||||||
onBuddyListChangedV2(_arg: unknown): any {
|
onBuddyListChangedV2(arg: unknown): any {
|
||||||
}
|
}
|
||||||
|
|
||||||
onAddBuddyNeedVerify(_arg: unknown): any {
|
onAddBuddyNeedVerify(arg: unknown): any {
|
||||||
}
|
}
|
||||||
|
|
||||||
onAddMeSettingChanged(_arg: unknown): any {
|
onAddMeSettingChanged(arg: unknown): any {
|
||||||
}
|
}
|
||||||
|
|
||||||
onAvatarUrlUpdated(_arg: unknown): any {
|
onAvatarUrlUpdated(arg: unknown): any {
|
||||||
}
|
}
|
||||||
|
|
||||||
onBlockChanged(_arg: unknown): any {
|
onBlockChanged(arg: unknown): any {
|
||||||
}
|
}
|
||||||
|
|
||||||
onBuddyDetailInfoChange(_arg: unknown): any {
|
onBuddyDetailInfoChange(arg: unknown): any {
|
||||||
}
|
}
|
||||||
|
|
||||||
onBuddyInfoChange(_arg: unknown): any {
|
onBuddyInfoChange(arg: unknown): any {
|
||||||
}
|
}
|
||||||
|
|
||||||
onBuddyListChange(_arg: OnBuddyChangeParams): any {
|
onBuddyListChange(arg: OnBuddyChangeParams): any {
|
||||||
}
|
}
|
||||||
|
|
||||||
onBuddyRemarkUpdated(_arg: unknown): any {
|
onBuddyRemarkUpdated(arg: unknown): any {
|
||||||
}
|
}
|
||||||
|
|
||||||
onBuddyReqChange(_arg: FriendRequestNotify): any {
|
onBuddyReqChange(arg: FriendRequestNotify): any {
|
||||||
}
|
}
|
||||||
|
|
||||||
onBuddyReqUnreadCntChange(_arg: unknown): any {
|
onBuddyReqUnreadCntChange(arg: unknown): any {
|
||||||
}
|
}
|
||||||
|
|
||||||
onCheckBuddySettingResult(_arg: unknown): any {
|
onCheckBuddySettingResult(arg: unknown): any {
|
||||||
}
|
}
|
||||||
|
|
||||||
onDelBatchBuddyInfos(_arg: unknown): any {
|
onDelBatchBuddyInfos(arg: unknown): any {
|
||||||
console.log('onDelBatchBuddyInfos not implemented', ...arguments);
|
console.log('onDelBatchBuddyInfos not implemented', ...arguments);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -66,12 +66,12 @@ export class NodeIKernelBuddyListener {
|
|||||||
onDoubtBuddyReqUnreadNumChange(_num: number): void | Promise<void> {
|
onDoubtBuddyReqUnreadNumChange(_num: number): void | Promise<void> {
|
||||||
}
|
}
|
||||||
|
|
||||||
onNickUpdated(_arg: unknown): any {
|
onNickUpdated(arg: unknown): any {
|
||||||
}
|
}
|
||||||
|
|
||||||
onSmartInfos(_arg: unknown): any {
|
onSmartInfos(arg: unknown): any {
|
||||||
}
|
}
|
||||||
|
|
||||||
onSpacePermissionInfos(_arg: unknown): any {
|
onSpacePermissionInfos(arg: unknown): any {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -6,14 +6,13 @@ import {
|
|||||||
PacketMsgFileElement,
|
PacketMsgFileElement,
|
||||||
PacketMsgPicElement,
|
PacketMsgPicElement,
|
||||||
PacketMsgPttElement,
|
PacketMsgPttElement,
|
||||||
PacketMsgReplyElement,
|
PacketMsgVideoElement
|
||||||
PacketMsgVideoElement,
|
|
||||||
} from '@/core/packet/message/element';
|
} from '@/core/packet/message/element';
|
||||||
import { ChatType, MsgSourceType, NTMsgType, RawMessage } from '@/core';
|
import { ChatType, MsgSourceType, NTMsgType, RawMessage } from '@/core';
|
||||||
import { MiniAppRawData, MiniAppReqParams } from '@/core/packet/entities/miniApp';
|
import { MiniAppRawData, MiniAppReqParams } from '@/core/packet/entities/miniApp';
|
||||||
import { AIVoiceChatType } from '@/core/packet/entities/aiChat';
|
import { AIVoiceChatType } from '@/core/packet/entities/aiChat';
|
||||||
import { NapProtoDecodeStructType, NapProtoEncodeStructType, NapProtoMsg } from '@napneko/nap-proto-core';
|
import { NapProtoDecodeStructType, NapProtoEncodeStructType, NapProtoMsg } from '@napneko/nap-proto-core';
|
||||||
import { IndexNode, LongMsgResult, MsgInfo, PushMsgBody } from '@/core/packet/transformer/proto';
|
import { IndexNode, LongMsgResult, MsgInfo } from '@/core/packet/transformer/proto';
|
||||||
import { OidbPacket } from '@/core/packet/transformer/base';
|
import { OidbPacket } from '@/core/packet/transformer/base';
|
||||||
import { ImageOcrResult } from '@/core/packet/entities/ocrResult';
|
import { ImageOcrResult } from '@/core/packet/entities/ocrResult';
|
||||||
import { gunzipSync } from 'zlib';
|
import { gunzipSync } from 'zlib';
|
||||||
@@ -77,9 +76,8 @@ export class PacketOperationContext {
|
|||||||
async UploadResources(msg: PacketMsg[], groupUin: number = 0) {
|
async UploadResources(msg: PacketMsg[], groupUin: number = 0) {
|
||||||
const chatType = groupUin ? ChatType.KCHATTYPEGROUP : ChatType.KCHATTYPEC2C;
|
const chatType = groupUin ? ChatType.KCHATTYPEGROUP : ChatType.KCHATTYPEC2C;
|
||||||
const peerUid = groupUin ? String(groupUin) : this.context.napcore.basicInfo.uid;
|
const peerUid = groupUin ? String(groupUin) : this.context.napcore.basicInfo.uid;
|
||||||
const reqList = msg.flatMap((m) =>
|
const reqList = msg.flatMap(m =>
|
||||||
m.msg
|
m.msg.map(e => {
|
||||||
.map((e) => {
|
|
||||||
if (e instanceof PacketMsgPicElement) {
|
if (e instanceof PacketMsgPicElement) {
|
||||||
return this.context.highway.uploadImage({ chatType, peerUid }, e);
|
return this.context.highway.uploadImage({ chatType, peerUid }, e);
|
||||||
} else if (e instanceof PacketMsgVideoElement) {
|
} else if (e instanceof PacketMsgVideoElement) {
|
||||||
@@ -90,11 +88,10 @@ export class PacketOperationContext {
|
|||||||
return this.context.highway.uploadFile({ chatType, peerUid }, e);
|
return this.context.highway.uploadFile({ chatType, peerUid }, e);
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
})
|
}).filter(Boolean)
|
||||||
.filter(Boolean)
|
|
||||||
);
|
);
|
||||||
const res = await Promise.allSettled(reqList);
|
const res = await Promise.allSettled(reqList);
|
||||||
this.context.logger.info(`上传资源${res.length}个,失败${res.filter((r) => r.status === 'rejected').length}个`);
|
this.context.logger.info(`上传资源${res.length}个,失败${res.filter(r => r.status === 'rejected').length}个`);
|
||||||
res.forEach((result, index) => {
|
res.forEach((result, index) => {
|
||||||
if (result.status === 'rejected') {
|
if (result.status === 'rejected') {
|
||||||
this.context.logger.error(`上传第${index + 1}个资源失败:${result.reason.stack}`);
|
this.context.logger.error(`上传第${index + 1}个资源失败:${result.reason.stack}`);
|
||||||
@@ -103,13 +100,10 @@ export class PacketOperationContext {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async UploadImage(img: PacketMsgPicElement) {
|
async UploadImage(img: PacketMsgPicElement) {
|
||||||
await this.context.highway.uploadImage(
|
await this.context.highway.uploadImage({
|
||||||
{
|
|
||||||
chatType: ChatType.KCHATTYPEC2C,
|
chatType: ChatType.KCHATTYPEC2C,
|
||||||
peerUid: this.context.napcore.basicInfo.uid,
|
peerUid: this.context.napcore.basicInfo.uid
|
||||||
},
|
}, img);
|
||||||
img
|
|
||||||
);
|
|
||||||
const index = img.msgInfo?.msgInfoBody?.at(0)?.index;
|
const index = img.msgInfo?.msgInfoBody?.at(0)?.index;
|
||||||
if (!index) {
|
if (!index) {
|
||||||
throw new Error('img.msgInfo?.msgInfoBody![0].index! is undefined');
|
throw new Error('img.msgInfo?.msgInfoBody![0].index! is undefined');
|
||||||
@@ -124,20 +118,6 @@ export class PacketOperationContext {
|
|||||||
return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
|
return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
async GetPttUrl(selfUid: string, node: NapProtoEncodeStructType<typeof IndexNode>) {
|
|
||||||
const req = trans.DownloadPtt.build(selfUid, node);
|
|
||||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
|
||||||
const res = trans.DownloadPtt.parse(resp);
|
|
||||||
return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
async GetVideoUrl(selfUid: string, node: NapProtoEncodeStructType<typeof IndexNode>) {
|
|
||||||
const req = trans.DownloadVideo.build(selfUid, node);
|
|
||||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
|
||||||
const res = trans.DownloadVideo.parse(resp);
|
|
||||||
return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
async GetGroupImageUrl(groupUin: number, node: NapProtoEncodeStructType<typeof IndexNode>) {
|
async GetGroupImageUrl(groupUin: number, node: NapProtoEncodeStructType<typeof IndexNode>) {
|
||||||
const req = trans.DownloadGroupImage.build(groupUin, node);
|
const req = trans.DownloadGroupImage.build(groupUin, node);
|
||||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||||
@@ -145,21 +125,6 @@ export class PacketOperationContext {
|
|||||||
return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
|
return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
async GetGroupPttUrl(groupUin: number, node: NapProtoEncodeStructType<typeof IndexNode>) {
|
|
||||||
const req = trans.DownloadGroupPtt.build(groupUin, node);
|
|
||||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
|
||||||
const res = trans.DownloadImage.parse(resp);
|
|
||||||
return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
async GetGroupVideoUrl(groupUin: number, node: NapProtoEncodeStructType<typeof IndexNode>) {
|
|
||||||
const req = trans.DownloadGroupVideo.build(groupUin, node);
|
|
||||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
|
||||||
const res = trans.DownloadImage.parse(resp);
|
|
||||||
return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
async ImageOCR(imgUrl: string) {
|
async ImageOCR(imgUrl: string) {
|
||||||
const req = trans.ImageOCR.build(imgUrl);
|
const req = trans.ImageOCR.build(imgUrl);
|
||||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||||
@@ -172,66 +137,24 @@ export class PacketOperationContext {
|
|||||||
coordinates: item.polygon.coordinates.map((c) => {
|
coordinates: item.polygon.coordinates.map((c) => {
|
||||||
return {
|
return {
|
||||||
x: c.x,
|
x: c.x,
|
||||||
y: c.y,
|
y: c.y
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
language: res.ocrRspBody.language,
|
language: res.ocrRspBody.language
|
||||||
} as ImageOcrResult;
|
} as ImageOcrResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async SendPreprocess(msg: PacketMsg[], groupUin: number = 0) {
|
|
||||||
const ps = msg.map((m) => {
|
|
||||||
return m.msg.map(async (e) => {
|
|
||||||
if (e instanceof PacketMsgReplyElement && !e.targetElems) {
|
|
||||||
this.context.logger.debug(`Cannot find reply element's targetElems, prepare to fetch it...`);
|
|
||||||
if (!e.targetPeer?.peerUid) {
|
|
||||||
this.context.logger.error(`targetPeer is undefined!`);
|
|
||||||
}
|
|
||||||
let targetMsg: NapProtoEncodeStructType<typeof PushMsgBody>[] | undefined;
|
|
||||||
if (e.isGroupReply) {
|
|
||||||
targetMsg = await this.FetchGroupMessage(+(e.targetPeer?.peerUid ?? 0), e.targetMessageSeq, e.targetMessageSeq);
|
|
||||||
} else {
|
|
||||||
targetMsg = await this.FetchC2CMessage(await this.context.napcore.basicInfo.uin2uid(e.targetUin), e.targetMessageSeq, e.targetMessageSeq);
|
|
||||||
}
|
|
||||||
e.targetElems = targetMsg.at(0)?.body?.richText?.elems;
|
|
||||||
e.targetSourceMsg = targetMsg.at(0);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}).flat();
|
|
||||||
await Promise.all(ps)
|
|
||||||
await this.UploadResources(msg, groupUin);
|
|
||||||
}
|
|
||||||
|
|
||||||
async FetchGroupMessage(groupUin: number, startSeq: number, endSeq: number): Promise<NapProtoDecodeStructType<typeof PushMsgBody>[]> {
|
|
||||||
const req = trans.FetchGroupMessage.build(groupUin, startSeq, endSeq);
|
|
||||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
|
||||||
const res = trans.FetchGroupMessage.parse(resp);
|
|
||||||
return res.body.messages
|
|
||||||
}
|
|
||||||
|
|
||||||
async FetchC2CMessage(targetUid: string, startSeq: number, endSeq: number): Promise<NapProtoDecodeStructType<typeof PushMsgBody>[]> {
|
|
||||||
const req = trans.FetchC2CMessage.build(targetUid, startSeq, endSeq);
|
|
||||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
|
||||||
const res = trans.FetchC2CMessage.parse(resp);
|
|
||||||
return res.messages
|
|
||||||
}
|
|
||||||
|
|
||||||
async UploadForwardMsg(msg: PacketMsg[], groupUin: number = 0) {
|
async UploadForwardMsg(msg: PacketMsg[], groupUin: number = 0) {
|
||||||
await this.SendPreprocess(msg, groupUin);
|
await this.UploadResources(msg, groupUin);
|
||||||
const req = trans.UploadForwardMsg.build(this.context.napcore.basicInfo.uid, msg, groupUin);
|
const req = trans.UploadForwardMsg.build(this.context.napcore.basicInfo.uid, msg, groupUin);
|
||||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||||
const res = trans.UploadForwardMsg.parse(resp);
|
const res = trans.UploadForwardMsg.parse(resp);
|
||||||
return res.result.resId;
|
return res.result.resId;
|
||||||
}
|
}
|
||||||
|
|
||||||
async MoveGroupFile(
|
async MoveGroupFile(groupUin: number, fileUUID: string, currentParentDirectory: string, targetParentDirectory: string) {
|
||||||
groupUin: number,
|
|
||||||
fileUUID: string,
|
|
||||||
currentParentDirectory: string,
|
|
||||||
targetParentDirectory: string
|
|
||||||
) {
|
|
||||||
const req = trans.MoveGroupFile.build(groupUin, fileUUID, currentParentDirectory, targetParentDirectory);
|
const req = trans.MoveGroupFile.build(groupUin, fileUUID, currentParentDirectory, targetParentDirectory);
|
||||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||||
const res = trans.MoveGroupFile.parse(resp);
|
const res = trans.MoveGroupFile.parse(resp);
|
||||||
@@ -251,7 +174,6 @@ export class PacketOperationContext {
|
|||||||
const res = trans.DownloadGroupFile.parse(resp);
|
const res = trans.DownloadGroupFile.parse(resp);
|
||||||
return `https://${res.download.downloadDns}/ftn_handler/${Buffer.from(res.download.downloadUrl).toString('hex')}/?fname=`;
|
return `https://${res.download.downloadDns}/ftn_handler/${Buffer.from(res.download.downloadUrl).toString('hex')}/?fname=`;
|
||||||
}
|
}
|
||||||
|
|
||||||
async GetPrivateFileUrl(self_id: string, fileUUID: string, md5: string) {
|
async GetPrivateFileUrl(self_id: string, fileUUID: string, md5: string) {
|
||||||
const req = trans.DownloadPrivateFile.build(self_id, fileUUID, md5);
|
const req = trans.DownloadPrivateFile.build(self_id, fileUUID, md5);
|
||||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||||
@@ -259,6 +181,13 @@ export class PacketOperationContext {
|
|||||||
return `http://${res.body?.result?.server}:${res.body?.result?.port}${res.body?.result?.url?.slice(8)}&isthumb=0`;
|
return `http://${res.body?.result?.server}:${res.body?.result?.port}${res.body?.result?.url?.slice(8)}&isthumb=0`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async GetGroupPttUrl(groupUin: number, node: NapProtoEncodeStructType<typeof IndexNode>) {
|
||||||
|
const req = trans.DownloadGroupPtt.build(groupUin, node);
|
||||||
|
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||||
|
const res = trans.DownloadGroupPtt.parse(resp);
|
||||||
|
return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
|
||||||
|
}
|
||||||
|
|
||||||
async GetMiniAppAdaptShareInfo(param: MiniAppReqParams) {
|
async GetMiniAppAdaptShareInfo(param: MiniAppReqParams) {
|
||||||
const req = trans.GetMiniAppAdaptShareInfo.build(param);
|
const req = trans.GetMiniAppAdaptShareInfo.build(param);
|
||||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||||
@@ -274,17 +203,12 @@ export class PacketOperationContext {
|
|||||||
return res.content.map((item) => {
|
return res.content.map((item) => {
|
||||||
return {
|
return {
|
||||||
category: item.category,
|
category: item.category,
|
||||||
voices: item.voices,
|
voices: item.voices
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async GetAiVoice(
|
async GetAiVoice(groupUin: number, voiceId: string, text: string, chatType: AIVoiceChatType): Promise<NapProtoDecodeStructType<typeof MsgInfo>> {
|
||||||
groupUin: number,
|
|
||||||
voiceId: string,
|
|
||||||
text: string,
|
|
||||||
chatType: AIVoiceChatType
|
|
||||||
): Promise<NapProtoDecodeStructType<typeof MsgInfo>> {
|
|
||||||
let reqTime = 0;
|
let reqTime = 0;
|
||||||
const reqMaxTime = 30;
|
const reqMaxTime = 30;
|
||||||
const sessionId = crypto.randomBytes(4).readUInt32BE(0);
|
const sessionId = crypto.randomBytes(4).readUInt32BE(0);
|
||||||
@@ -312,7 +236,6 @@ export class PacketOperationContext {
|
|||||||
if (!main?.actionData.msgBody) {
|
if (!main?.actionData.msgBody) {
|
||||||
throw new Error('msgBody is empty');
|
throw new Error('msgBody is empty');
|
||||||
}
|
}
|
||||||
this.context.logger.debug('rawChains ', inflate.toString('hex'));
|
|
||||||
|
|
||||||
const messagesPromises = main.actionData.msgBody.map(async (msg) => {
|
const messagesPromises = main.actionData.msgBody.map(async (msg) => {
|
||||||
if (!msg?.body?.richText?.elems) {
|
if (!msg?.body?.richText?.elems) {
|
||||||
@@ -328,12 +251,12 @@ export class PacketOperationContext {
|
|||||||
const groupUin = msg?.responseHead.grp?.groupUin ?? 0;
|
const groupUin = msg?.responseHead.grp?.groupUin ?? 0;
|
||||||
element.picElement = {
|
element.picElement = {
|
||||||
...element.picElement,
|
...element.picElement,
|
||||||
originImageUrl: await this.GetGroupImageUrl(groupUin, index!),
|
originImageUrl: await this.GetGroupImageUrl(groupUin, index!)
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
element.picElement = {
|
element.picElement = {
|
||||||
...element.picElement,
|
...element.picElement,
|
||||||
originImageUrl: await this.GetImageUrl(this.context.napcore.basicInfo.uid, index!),
|
originImageUrl: await this.GetImageUrl(this.context.napcore.basicInfo.uid, index!)
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
return element;
|
return element;
|
||||||
|
@@ -24,15 +24,12 @@ export class PacketMsgBuilder {
|
|||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
responseHead: {
|
responseHead: {
|
||||||
fromUin: node.senderUin,
|
|
||||||
type: 0,
|
|
||||||
sigMap: 0,
|
|
||||||
toUin: 0,
|
|
||||||
fromUid: '',
|
fromUid: '',
|
||||||
|
fromUin: node.senderUin,
|
||||||
|
toUid: node.groupId ? undefined : selfUid,
|
||||||
forward: node.groupId ? undefined : {
|
forward: node.groupId ? undefined : {
|
||||||
friendName: node.senderName,
|
friendName: node.senderName,
|
||||||
},
|
},
|
||||||
toUid: node.groupId ? undefined : selfUid,
|
|
||||||
grp: node.groupId ? {
|
grp: node.groupId ? {
|
||||||
groupUin: node.groupId,
|
groupUin: node.groupId,
|
||||||
memberName: node.senderName,
|
memberName: node.senderName,
|
||||||
@@ -43,13 +40,16 @@ export class PacketMsgBuilder {
|
|||||||
type: node.groupId ? 82 : 9,
|
type: node.groupId ? 82 : 9,
|
||||||
subType: node.groupId ? undefined : 4,
|
subType: node.groupId ? undefined : 4,
|
||||||
divSeq: node.groupId ? undefined : 4,
|
divSeq: node.groupId ? undefined : 4,
|
||||||
autoReply: 0,
|
msgId: crypto.randomBytes(4).readUInt32LE(0),
|
||||||
sequence: crypto.randomBytes(4).readUInt32LE(0),
|
sequence: crypto.randomBytes(4).readUInt32LE(0),
|
||||||
timeStamp: +node.time.toString().substring(0, 10),
|
timeStamp: +node.time.toString().substring(0, 10),
|
||||||
|
field7: BigInt(1),
|
||||||
|
field8: 0,
|
||||||
|
field9: 0,
|
||||||
forward: {
|
forward: {
|
||||||
field1: 0,
|
field1: 0,
|
||||||
field2: 0,
|
field2: 0,
|
||||||
field3: node.groupId ? 1 : 2,
|
field3: node.groupId ? 0 : 2,
|
||||||
unknownBase64: avatar,
|
unknownBase64: avatar,
|
||||||
avatar: avatar
|
avatar: avatar
|
||||||
}
|
}
|
||||||
|
@@ -10,7 +10,6 @@ import {
|
|||||||
MsgInfo,
|
MsgInfo,
|
||||||
NotOnlineImage,
|
NotOnlineImage,
|
||||||
OidbSvcTrpcTcp0XE37_800Response,
|
OidbSvcTrpcTcp0XE37_800Response,
|
||||||
PushMsgBody,
|
|
||||||
QBigFaceExtra,
|
QBigFaceExtra,
|
||||||
QSmallFaceExtra,
|
QSmallFaceExtra,
|
||||||
} from '@/core/packet/transformer/proto';
|
} from '@/core/packet/transformer/proto';
|
||||||
@@ -30,8 +29,7 @@ import {
|
|||||||
SendReplyElement,
|
SendReplyElement,
|
||||||
SendMultiForwardMsgElement,
|
SendMultiForwardMsgElement,
|
||||||
SendTextElement,
|
SendTextElement,
|
||||||
SendVideoElement,
|
SendVideoElement
|
||||||
Peer
|
|
||||||
} from '@/core';
|
} from '@/core';
|
||||||
import {ForwardMsgBuilder} from '@/common/forward-msg-builder';
|
import {ForwardMsgBuilder} from '@/common/forward-msg-builder';
|
||||||
import {PacketMsg, PacketSendMsgElement} from '@/core/packet/message/message';
|
import {PacketMsg, PacketSendMsgElement} from '@/core/packet/message/message';
|
||||||
@@ -148,40 +146,41 @@ export class PacketMsgAtElement extends PacketMsgTextElement {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class PacketMsgReplyElement extends IPacketMsgElement<SendReplyElement> {
|
export class PacketMsgReplyElement extends IPacketMsgElement<SendReplyElement> {
|
||||||
time: number;
|
messageId: bigint;
|
||||||
targetMessageId: bigint;
|
messageSeq: number;
|
||||||
targetMessageSeq: number;
|
messageClientSeq: number;
|
||||||
targetMessageClientSeq: number;
|
|
||||||
targetUin: number;
|
targetUin: number;
|
||||||
targetUid: string;
|
targetUid: string;
|
||||||
targetElems?: NapProtoEncodeStructType<typeof Elem>[];
|
time: number;
|
||||||
targetSourceMsg?: NapProtoEncodeStructType<typeof PushMsgBody>;
|
elems: PacketMsg[];
|
||||||
targetPeer?: Peer;
|
|
||||||
|
|
||||||
constructor(element: SendReplyElement) {
|
constructor(element: SendReplyElement) {
|
||||||
super(element);
|
super(element);
|
||||||
this.time = +(element.replyElement.replyMsgTime ?? Math.floor(Date.now() / 1000));
|
this.messageId = BigInt(element.replyElement.replayMsgId ?? 0);
|
||||||
this.targetMessageId = BigInt(element.replyElement.replayMsgId ?? 0);
|
this.messageSeq = +(element.replyElement.replayMsgSeq ?? 0);
|
||||||
this.targetMessageSeq = +(element.replyElement.replayMsgSeq ?? 0);
|
this.messageClientSeq = +(element.replyElement.replyMsgClientSeq ?? 0);
|
||||||
this.targetMessageClientSeq = +(element.replyElement.replyMsgClientSeq ?? 0);
|
|
||||||
this.targetUin = +(element.replyElement.senderUin ?? 0);
|
this.targetUin = +(element.replyElement.senderUin ?? 0);
|
||||||
this.targetUid = element.replyElement.senderUidStr ?? '';
|
this.targetUid = element.replyElement.senderUidStr ?? '';
|
||||||
this.targetPeer = element.replyElement._replyMsgPeer;
|
this.time = +(element.replyElement.replyMsgTime ?? 0);
|
||||||
|
this.elems = []; // TODO: in replyElement.sourceMsgTextElems
|
||||||
}
|
}
|
||||||
|
|
||||||
get isGroupReply(): boolean {
|
get isGroupReply(): boolean {
|
||||||
return this.targetMessageClientSeq === 0;
|
return this.messageClientSeq === 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
override buildElement(): NapProtoEncodeStructType<typeof Elem>[] {
|
override buildElement(): NapProtoEncodeStructType<typeof Elem>[] {
|
||||||
return [{
|
return [{
|
||||||
srcMsg: {
|
srcMsg: {
|
||||||
origSeqs: [this.isGroupReply ? this.targetMessageSeq : this.targetMessageClientSeq],
|
origSeqs: [this.isGroupReply ? this.messageClientSeq : this.messageSeq],
|
||||||
senderUin: BigInt(this.targetUin),
|
senderUin: BigInt(this.targetUin),
|
||||||
time: this.time,
|
time: this.time,
|
||||||
elems: this.targetElems ?? [],
|
elems: [], // TODO: in replyElement.sourceMsgTextElems
|
||||||
sourceMsg: new NapProtoMsg(PushMsgBody).encode(this.targetSourceMsg ?? {}),
|
pbReserve: {
|
||||||
toUin: BigInt(0),
|
messageId: this.messageId,
|
||||||
|
},
|
||||||
|
toUin: BigInt(this.targetUin),
|
||||||
|
type: 1,
|
||||||
}
|
}
|
||||||
}];
|
}];
|
||||||
}
|
}
|
||||||
|
@@ -1,50 +0,0 @@
|
|||||||
import * as proto from '@/core/packet/transformer/proto';
|
|
||||||
import { NapProtoEncodeStructType, NapProtoMsg } from '@napneko/nap-proto-core';
|
|
||||||
import { OidbPacket, PacketTransformer } from '@/core/packet/transformer/base';
|
|
||||||
import OidbBase from '@/core/packet/transformer/oidb/oidbBase';
|
|
||||||
import { IndexNode } from '@/core/packet/transformer/proto';
|
|
||||||
|
|
||||||
class DownloadGroupVideo extends PacketTransformer<typeof proto.NTV2RichMediaResp> {
|
|
||||||
constructor() {
|
|
||||||
super();
|
|
||||||
}
|
|
||||||
|
|
||||||
build(groupUin: number, node: NapProtoEncodeStructType<typeof IndexNode>): OidbPacket {
|
|
||||||
const body = new NapProtoMsg(proto.NTV2RichMediaReq).encode({
|
|
||||||
reqHead: {
|
|
||||||
common: {
|
|
||||||
requestId: 1,
|
|
||||||
command: 200
|
|
||||||
},
|
|
||||||
scene: {
|
|
||||||
requestType: 2,
|
|
||||||
businessType: 2,
|
|
||||||
sceneType: 2,
|
|
||||||
group: {
|
|
||||||
groupUin: groupUin
|
|
||||||
}
|
|
||||||
},
|
|
||||||
client: {
|
|
||||||
agentType: 2,
|
|
||||||
}
|
|
||||||
},
|
|
||||||
download: {
|
|
||||||
node: node,
|
|
||||||
download: {
|
|
||||||
video: {
|
|
||||||
busiType: 0,
|
|
||||||
sceneType: 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
return OidbBase.build(0x11EA, 200, body, true, false);
|
|
||||||
}
|
|
||||||
|
|
||||||
parse(data: Buffer) {
|
|
||||||
const oidbBody = OidbBase.parse(data).body;
|
|
||||||
return new NapProtoMsg(proto.NTV2RichMediaResp).decode(oidbBody);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export default new DownloadGroupVideo();
|
|
@@ -1,51 +0,0 @@
|
|||||||
import * as proto from '@/core/packet/transformer/proto';
|
|
||||||
import { NapProtoEncodeStructType, NapProtoMsg } from '@napneko/nap-proto-core';
|
|
||||||
import { OidbPacket, PacketTransformer } from '@/core/packet/transformer/base';
|
|
||||||
import OidbBase from '@/core/packet/transformer/oidb/oidbBase';
|
|
||||||
import { IndexNode } from '@/core/packet/transformer/proto';
|
|
||||||
|
|
||||||
class DownloadPtt extends PacketTransformer<typeof proto.NTV2RichMediaResp> {
|
|
||||||
constructor() {
|
|
||||||
super();
|
|
||||||
}
|
|
||||||
|
|
||||||
build(selfUid: string, node: NapProtoEncodeStructType<typeof IndexNode>): OidbPacket {
|
|
||||||
const body = new NapProtoMsg(proto.NTV2RichMediaReq).encode({
|
|
||||||
reqHead: {
|
|
||||||
common: {
|
|
||||||
requestId: 1,
|
|
||||||
command: 200
|
|
||||||
},
|
|
||||||
scene: {
|
|
||||||
requestType: 1,
|
|
||||||
businessType: 3,
|
|
||||||
sceneType: 1,
|
|
||||||
c2C: {
|
|
||||||
accountType: 2,
|
|
||||||
targetUid: selfUid
|
|
||||||
},
|
|
||||||
},
|
|
||||||
client: {
|
|
||||||
agentType: 2,
|
|
||||||
}
|
|
||||||
},
|
|
||||||
download: {
|
|
||||||
node: node,
|
|
||||||
download: {
|
|
||||||
video: {
|
|
||||||
busiType: 0,
|
|
||||||
sceneType: 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
return OidbBase.build(0x126D, 200, body, true, false);
|
|
||||||
}
|
|
||||||
|
|
||||||
parse(data: Buffer) {
|
|
||||||
const oidbBody = OidbBase.parse(data).body;
|
|
||||||
return new NapProtoMsg(proto.NTV2RichMediaResp).decode(oidbBody);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export default new DownloadPtt();
|
|
@@ -1,51 +0,0 @@
|
|||||||
import * as proto from '@/core/packet/transformer/proto';
|
|
||||||
import { NapProtoEncodeStructType, NapProtoMsg } from '@napneko/nap-proto-core';
|
|
||||||
import { OidbPacket, PacketTransformer } from '@/core/packet/transformer/base';
|
|
||||||
import OidbBase from '@/core/packet/transformer/oidb/oidbBase';
|
|
||||||
import { IndexNode } from '@/core/packet/transformer/proto';
|
|
||||||
|
|
||||||
class DownloadVideo extends PacketTransformer<typeof proto.NTV2RichMediaResp> {
|
|
||||||
constructor() {
|
|
||||||
super();
|
|
||||||
}
|
|
||||||
|
|
||||||
build(selfUid: string, node: NapProtoEncodeStructType<typeof IndexNode>): OidbPacket {
|
|
||||||
const body = new NapProtoMsg(proto.NTV2RichMediaReq).encode({
|
|
||||||
reqHead: {
|
|
||||||
common: {
|
|
||||||
requestId: 1,
|
|
||||||
command: 200
|
|
||||||
},
|
|
||||||
scene: {
|
|
||||||
requestType: 2,
|
|
||||||
businessType: 2,
|
|
||||||
sceneType: 1,
|
|
||||||
c2C: {
|
|
||||||
accountType: 2,
|
|
||||||
targetUid: selfUid
|
|
||||||
},
|
|
||||||
},
|
|
||||||
client: {
|
|
||||||
agentType: 2,
|
|
||||||
}
|
|
||||||
},
|
|
||||||
download: {
|
|
||||||
node: node,
|
|
||||||
download: {
|
|
||||||
video: {
|
|
||||||
busiType: 0,
|
|
||||||
sceneType: 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
return OidbBase.build(0x11E9, 200, body, true, false);
|
|
||||||
}
|
|
||||||
|
|
||||||
parse(data: Buffer) {
|
|
||||||
const oidbBody = OidbBase.parse(data).body;
|
|
||||||
return new NapProtoMsg(proto.NTV2RichMediaResp).decode(oidbBody);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export default new DownloadVideo();
|
|
@@ -13,6 +13,3 @@ export { default as UploadPrivatePtt } from './UploadPrivatePtt';
|
|||||||
export { default as UploadPrivateVideo } from './UploadPrivateVideo';
|
export { default as UploadPrivateVideo } from './UploadPrivateVideo';
|
||||||
export { default as DownloadImage } from './DownloadImage';
|
export { default as DownloadImage } from './DownloadImage';
|
||||||
export { default as DownloadGroupImage } from './DownloadGroupImage';
|
export { default as DownloadGroupImage } from './DownloadGroupImage';
|
||||||
export { default as DownloadVideo } from './DownloadVideo';
|
|
||||||
export { default as DownloadGroupVideo } from './DownloadGroupVideo';
|
|
||||||
export { default as DownloadPtt } from './DownloadPtt';
|
|
@@ -1,27 +0,0 @@
|
|||||||
import * as proto from '@/core/packet/transformer/proto';
|
|
||||||
import { NapProtoMsg } from '@napneko/nap-proto-core';
|
|
||||||
import { OidbPacket, PacketHexStrBuilder, PacketTransformer } from '@/core/packet/transformer/base';
|
|
||||||
|
|
||||||
class FetchC2CMessage extends PacketTransformer<typeof proto.SsoGetC2cMsgResponse> {
|
|
||||||
constructor() {
|
|
||||||
super();
|
|
||||||
}
|
|
||||||
|
|
||||||
build(targetUid: string, startSeq: number, endSeq: number): OidbPacket {
|
|
||||||
const req = new NapProtoMsg(proto.SsoGetC2cMsg).encode({
|
|
||||||
friendUid: targetUid,
|
|
||||||
startSequence: startSeq,
|
|
||||||
endSequence: endSeq,
|
|
||||||
});
|
|
||||||
return {
|
|
||||||
cmd: 'trpc.msg.register_proxy.RegisterProxy.SsoGetC2cMsg',
|
|
||||||
data: PacketHexStrBuilder(req)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
parse(data: Buffer) {
|
|
||||||
return new NapProtoMsg(proto.SsoGetC2cMsgResponse).decode(data);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export default new FetchC2CMessage();
|
|
@@ -1,30 +0,0 @@
|
|||||||
import * as proto from '@/core/packet/transformer/proto';
|
|
||||||
import { NapProtoMsg } from '@napneko/nap-proto-core';
|
|
||||||
import { OidbPacket, PacketHexStrBuilder, PacketTransformer } from '@/core/packet/transformer/base';
|
|
||||||
|
|
||||||
class FetchGroupMessage extends PacketTransformer<typeof proto.SsoGetGroupMsgResponse> {
|
|
||||||
constructor() {
|
|
||||||
super();
|
|
||||||
}
|
|
||||||
|
|
||||||
build(groupUin: number, startSeq: number, endSeq: number): OidbPacket {
|
|
||||||
const req = new NapProtoMsg(proto.SsoGetGroupMsg).encode({
|
|
||||||
info: {
|
|
||||||
groupUin: groupUin,
|
|
||||||
startSequence: startSeq,
|
|
||||||
endSequence: endSeq
|
|
||||||
},
|
|
||||||
direction: true
|
|
||||||
});
|
|
||||||
return {
|
|
||||||
cmd: 'trpc.msg.register_proxy.RegisterProxy.SsoGetGroupMsg',
|
|
||||||
data: PacketHexStrBuilder(req)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
parse(data: Buffer) {
|
|
||||||
return new NapProtoMsg(proto.SsoGetGroupMsgResponse).decode(data);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export default new FetchGroupMessage();
|
|
@@ -1,4 +1,2 @@
|
|||||||
export { default as UploadForwardMsg } from './UploadForwardMsg';
|
export { default as UploadForwardMsg } from './UploadForwardMsg';
|
||||||
export { default as FetchGroupMessage } from './FetchGroupMessage';
|
|
||||||
export { default as FetchC2CMessage } from './FetchC2CMessage';
|
|
||||||
export { default as DownloadForwardMsg } from './DownloadForwardMsg';
|
export { default as DownloadForwardMsg } from './DownloadForwardMsg';
|
@@ -13,15 +13,13 @@ import {
|
|||||||
export const ContentHead = {
|
export const ContentHead = {
|
||||||
type: ProtoField(1, ScalarType.UINT32),
|
type: ProtoField(1, ScalarType.UINT32),
|
||||||
subType: ProtoField(2, ScalarType.UINT32, true),
|
subType: ProtoField(2, ScalarType.UINT32, true),
|
||||||
c2cCmd: ProtoField(3, ScalarType.UINT32, true),
|
divSeq: ProtoField(3, ScalarType.UINT32, true),
|
||||||
ranDom: ProtoField(4, ScalarType.UINT32, true),
|
msgId: ProtoField(4, ScalarType.UINT32, true),
|
||||||
sequence: ProtoField(5, ScalarType.UINT32, true),
|
sequence: ProtoField(5, ScalarType.UINT32, true),
|
||||||
timeStamp: ProtoField(6, ScalarType.UINT32, true),
|
timeStamp: ProtoField(6, ScalarType.UINT32, true),
|
||||||
pkgNum: ProtoField(7, ScalarType.UINT64, true),
|
field7: ProtoField(7, ScalarType.UINT64, true),
|
||||||
pkgIndex: ProtoField(8, ScalarType.UINT32, true),
|
field8: ProtoField(8, ScalarType.UINT32, true),
|
||||||
divSeq: ProtoField(9, ScalarType.UINT32, true),
|
field9: ProtoField(9, ScalarType.UINT32, true),
|
||||||
autoReply: ProtoField(10, ScalarType.UINT32),
|
|
||||||
ntMsgSeq: ProtoField(10, ScalarType.UINT32, true),
|
|
||||||
newId: ProtoField(12, ScalarType.UINT64, true),
|
newId: ProtoField(12, ScalarType.UINT64, true),
|
||||||
forward: ProtoField(15, () => ForwardHead, true),
|
forward: ProtoField(15, () => ForwardHead, true),
|
||||||
};
|
};
|
||||||
|
@@ -1,6 +0,0 @@
|
|||||||
import { ProtoField, ScalarType } from '@napneko/nap-proto-core';
|
|
||||||
|
|
||||||
export const FileId = {
|
|
||||||
appid: ProtoField(4, ScalarType.UINT32, true),
|
|
||||||
ttl: ProtoField(10, ScalarType.UINT32, true),
|
|
||||||
};
|
|
@@ -249,7 +249,7 @@ export interface NodeIKernelGroupService {
|
|||||||
|
|
||||||
reqToJoinGroup(groupCode: string, arg: unknown): void;
|
reqToJoinGroup(groupCode: string, arg: unknown): void;
|
||||||
|
|
||||||
setGroupShutUp(groupCode: string, shutUp: boolean): Promise<GeneralCallResult>;
|
setGroupShutUp(groupCode: string, shutUp: boolean): void;
|
||||||
|
|
||||||
getGroupShutUpMemberList(groupCode: string): Promise<GeneralCallResult>;
|
getGroupShutUpMemberList(groupCode: string): Promise<GeneralCallResult>;
|
||||||
|
|
||||||
|
@@ -148,11 +148,10 @@ export interface NodeIKernelMsgService {
|
|||||||
msgList: RawMessage[]
|
msgList: RawMessage[]
|
||||||
}>;
|
}>;
|
||||||
|
|
||||||
// getMsgService/getMsgs { chatType: 2, peerUid: '975206796', privilegeFlag: 336068800 } 0 20 true
|
//@deprecated
|
||||||
getMsgs(peer: Peer & { privilegeFlag: number }, msgId: string, count: number, queryOrder: boolean): Promise<GeneralCallResult & {
|
getMsgs(peer: Peer, msgId: string, count: unknown, queryOrder: boolean): Promise<unknown>;
|
||||||
msgList: RawMessage[]
|
|
||||||
}>;
|
|
||||||
|
|
||||||
|
//@deprecated
|
||||||
getMsgsIncludeSelf(peer: Peer, msgId: string, count: number, queryOrder: boolean): Promise<GeneralCallResult & {
|
getMsgsIncludeSelf(peer: Peer, msgId: string, count: number, queryOrder: boolean): Promise<GeneralCallResult & {
|
||||||
msgList: RawMessage[]
|
msgList: RawMessage[]
|
||||||
}>;
|
}>;
|
||||||
|
@@ -1,15 +1,4 @@
|
|||||||
import {
|
import { ElementType, MessageElement, NTGrayTipElementSubTypeV2, PicSubType, PicType, TipAioOpGrayTipElement, TipGroupElement, NTVideoType, FaceType } from './msg';
|
||||||
ElementType,
|
|
||||||
MessageElement,
|
|
||||||
NTGrayTipElementSubTypeV2,
|
|
||||||
PicSubType,
|
|
||||||
PicType,
|
|
||||||
TipAioOpGrayTipElement,
|
|
||||||
TipGroupElement,
|
|
||||||
NTVideoType,
|
|
||||||
FaceType,
|
|
||||||
Peer
|
|
||||||
} from './msg';
|
|
||||||
|
|
||||||
type ElementFullBase = Omit<MessageElement, 'elementType' | 'elementId' | 'extBufForUI'>;
|
type ElementFullBase = Omit<MessageElement, 'elementType' | 'elementId' | 'extBufForUI'>;
|
||||||
|
|
||||||
@@ -224,9 +213,6 @@ export interface ReplyElement {
|
|||||||
senderUidStr?: string;
|
senderUidStr?: string;
|
||||||
replyMsgTime?: string;
|
replyMsgTime?: string;
|
||||||
replyMsgClientSeq?: string;
|
replyMsgClientSeq?: string;
|
||||||
// HACK: Attributes that were not originally available,
|
|
||||||
// but were added due to NTQQ and NapCat's internal implementation, are used to supplement NapCat
|
|
||||||
_replyMsgPeer?: Peer;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CalendarElement {
|
export interface CalendarElement {
|
||||||
|
@@ -501,15 +501,13 @@ export interface RawMessage {
|
|||||||
elements: MessageElement[];// 消息元素
|
elements: MessageElement[];// 消息元素
|
||||||
sourceType: MsgSourceType;// 消息来源类型
|
sourceType: MsgSourceType;// 消息来源类型
|
||||||
isOnlineMsg: boolean;// 是否为在线消息
|
isOnlineMsg: boolean;// 是否为在线消息
|
||||||
clientSeq?: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 查询消息参数接口
|
* 查询消息参数接口
|
||||||
*/
|
*/
|
||||||
export interface QueryMsgsParams {
|
export interface QueryMsgsParams {
|
||||||
chatInfo: Peer & { privilegeFlag?: number };
|
chatInfo: Peer;
|
||||||
//searchFields: number;
|
|
||||||
filterMsgType: Array<{ type: NTMsgType, subType: Array<number> }>;
|
filterMsgType: Array<{ type: NTMsgType, subType: Array<number> }>;
|
||||||
filterSendersUid: string[];
|
filterSendersUid: string[];
|
||||||
filterMsgFromTime: string;
|
filterMsgFromTime: string;
|
||||||
|
@@ -132,26 +132,18 @@ export enum BuddyReqType {
|
|||||||
KMEINITIATORWAITPEERCONFIRM = 13
|
KMEINITIATORWAITPEERCONFIRM = 13
|
||||||
}
|
}
|
||||||
|
|
||||||
// 其中 ? 代表新版本参数
|
|
||||||
export interface FriendRequest {
|
export interface FriendRequest {
|
||||||
|
isBuddy?: boolean;
|
||||||
isInitiator?: boolean;
|
isInitiator?: boolean;
|
||||||
isDecide: boolean;
|
isDecide: boolean;
|
||||||
friendUid: string;
|
friendUid: string;
|
||||||
reqType: BuddyReqType,
|
reqType: BuddyReqType,
|
||||||
reqTime: string; // 时间戳 秒
|
reqTime: string; // 时间戳 秒
|
||||||
flag?: number; // 0
|
|
||||||
preGroupingId?: number; // 0
|
|
||||||
commFriendNum?: number; // 共同好友数
|
|
||||||
extWords: string; // 申请人填写的验证消息
|
extWords: string; // 申请人填写的验证消息
|
||||||
isUnread: boolean;
|
isUnread: boolean;
|
||||||
isDoubt?: boolean; // 是否是可疑的好友请求
|
|
||||||
nameMore?: string;
|
|
||||||
friendNick: string;
|
friendNick: string;
|
||||||
sourceId: number;
|
sourceId: number;
|
||||||
groupCode: string;
|
groupCode: string
|
||||||
isBuddy?: boolean;
|
|
||||||
isAgreed?: boolean;
|
|
||||||
relation?: number;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface FriendRequestNotify {
|
export interface FriendRequestNotify {
|
||||||
|
@@ -15,10 +15,7 @@ export default class SetGroupWholeBan extends OneBotAction<Payload, null> {
|
|||||||
|
|
||||||
async _handle(payload: Payload): Promise<null> {
|
async _handle(payload: Payload): Promise<null> {
|
||||||
const enable = payload.enable?.toString() !== 'false';
|
const enable = payload.enable?.toString() !== 'false';
|
||||||
let res = await this.core.apis.GroupApi.banGroup(payload.group_id.toString(), enable);
|
await this.core.apis.GroupApi.banGroup(payload.group_id.toString(), enable);
|
||||||
if (res.result !== 0) {
|
|
||||||
throw new Error(`SetGroupWholeBan failed: ${res.errMsg} ${res.result}`);
|
|
||||||
}
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -174,11 +174,9 @@ export class SendMsgBase extends OneBotAction<OB11PostSendMsg, ReturnDataType> {
|
|||||||
nickname: string,
|
nickname: string,
|
||||||
}, dp: number = 0): Promise<{
|
}, dp: number = 0): Promise<{
|
||||||
finallySendElements: SendArkElement,
|
finallySendElements: SendArkElement,
|
||||||
res_id?: string,
|
res_id?: string
|
||||||
deleteAfterSentFiles: string[],
|
|
||||||
} | null> {
|
} | null> {
|
||||||
const packetMsg: PacketMsg[] = [];
|
const packetMsg: PacketMsg[] = [];
|
||||||
let delFiles: string[] = [];
|
|
||||||
for (const node of messageNodes) {
|
for (const node of messageNodes) {
|
||||||
if (dp >= 3) {
|
if (dp >= 3) {
|
||||||
this.core.context.logger.logWarn('转发消息深度超过3层,将停止解析!');
|
this.core.context.logger.logWarn('转发消息深度超过3层,将停止解析!');
|
||||||
@@ -194,11 +192,9 @@ export class SendMsgBase extends OneBotAction<OB11PostSendMsg, ReturnDataType> {
|
|||||||
nickname: (node.data.nickname || node.data.name) ?? parentMeta?.nickname ?? 'QQ用户',
|
nickname: (node.data.nickname || node.data.name) ?? parentMeta?.nickname ?? 'QQ用户',
|
||||||
}, dp + 1);
|
}, dp + 1);
|
||||||
sendElements = uploadReturnData?.finallySendElements ? [uploadReturnData.finallySendElements] : [];
|
sendElements = uploadReturnData?.finallySendElements ? [uploadReturnData.finallySendElements] : [];
|
||||||
delFiles.push(...(uploadReturnData?.deleteAfterSentFiles || []));
|
|
||||||
} else {
|
} else {
|
||||||
const sendElementsCreateReturn = await this.obContext.apis.MsgApi.createSendElements(OB11Data, msgPeer);
|
const sendElementsCreateReturn = await this.obContext.apis.MsgApi.createSendElements(OB11Data, msgPeer);
|
||||||
sendElements = sendElementsCreateReturn.sendElements;
|
sendElements = sendElementsCreateReturn.sendElements;
|
||||||
delFiles.push(...sendElementsCreateReturn.deleteAfterSentFiles);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const packetMsgElements: rawMsgWithSendMsg = {
|
const packetMsgElements: rawMsgWithSendMsg = {
|
||||||
@@ -222,8 +218,7 @@ export class SendMsgBase extends OneBotAction<OB11PostSendMsg, ReturnDataType> {
|
|||||||
const msg = (await this.core.apis.MsgApi.getMsgsByMsgId(nodeMsg.Peer, [nodeMsg.MsgId])).msgList[0];
|
const msg = (await this.core.apis.MsgApi.getMsgsByMsgId(nodeMsg.Peer, [nodeMsg.MsgId])).msgList[0];
|
||||||
this.core.context.logger.logDebug(`handleForwardedNodesPacket[PureRaw] 开始转换 ${stringifyWithBigInt(msg)}`);
|
this.core.context.logger.logDebug(`handleForwardedNodesPacket[PureRaw] 开始转换 ${stringifyWithBigInt(msg)}`);
|
||||||
if (msg) {
|
if (msg) {
|
||||||
let msgCache = await this.core.apis.FileApi.downloadRawMsgMedia([msg]);
|
await this.core.apis.FileApi.downloadRawMsgMedia([msg]);
|
||||||
delFiles.push(...msgCache);
|
|
||||||
const transformedMsg = this.core.apis.PacketApi.pkt.msgConverter.rawMsgToPacketMsg(msg, msgPeer);
|
const transformedMsg = this.core.apis.PacketApi.pkt.msgConverter.rawMsgToPacketMsg(msg, msgPeer);
|
||||||
this.core.context.logger.logDebug(`handleForwardedNodesPacket[PureRaw] 转换为 ${stringifyWithBigInt(transformedMsg)}`);
|
this.core.context.logger.logDebug(`handleForwardedNodesPacket[PureRaw] 转换为 ${stringifyWithBigInt(transformedMsg)}`);
|
||||||
packetMsg.push(transformedMsg);
|
packetMsg.push(transformedMsg);
|
||||||
@@ -239,7 +234,6 @@ export class SendMsgBase extends OneBotAction<OB11PostSendMsg, ReturnDataType> {
|
|||||||
const resid = await this.core.apis.PacketApi.pkt.operation.UploadForwardMsg(packetMsg, msgPeer.chatType === ChatType.KCHATTYPEGROUP ? +msgPeer.peerUid : 0);
|
const resid = await this.core.apis.PacketApi.pkt.operation.UploadForwardMsg(packetMsg, msgPeer.chatType === ChatType.KCHATTYPEGROUP ? +msgPeer.peerUid : 0);
|
||||||
const forwardJson = ForwardMsgBuilder.fromPacketMsg(resid, packetMsg, source, news, summary, prompt);
|
const forwardJson = ForwardMsgBuilder.fromPacketMsg(resid, packetMsg, source, news, summary, prompt);
|
||||||
return {
|
return {
|
||||||
deleteAfterSentFiles: delFiles,
|
|
||||||
finallySendElements: {
|
finallySendElements: {
|
||||||
elementType: ElementType.ARK,
|
elementType: ElementType.ARK,
|
||||||
elementId: '',
|
elementId: '',
|
||||||
@@ -261,7 +255,7 @@ export class SendMsgBase extends OneBotAction<OB11PostSendMsg, ReturnDataType> {
|
|||||||
const res_id = uploadReturnData?.res_id;
|
const res_id = uploadReturnData?.res_id;
|
||||||
const finallySendElements = uploadReturnData?.finallySendElements;
|
const finallySendElements = uploadReturnData?.finallySendElements;
|
||||||
if (!finallySendElements) throw Error('转发消息失败,生成节点为空');
|
if (!finallySendElements) throw Error('转发消息失败,生成节点为空');
|
||||||
const returnMsg = await this.obContext.apis.MsgApi.sendMsgWithOb11UniqueId(msgPeer, [finallySendElements], uploadReturnData.deleteAfterSentFiles || []).catch(() => undefined);
|
const returnMsg = await this.obContext.apis.MsgApi.sendMsgWithOb11UniqueId(msgPeer, [finallySendElements], []).catch(() => undefined);
|
||||||
return { message: returnMsg ?? null, res_id: res_id! };
|
return { message: returnMsg ?? null, res_id: res_id! };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -100,7 +100,7 @@ export class OneBotMsgApi {
|
|||||||
let qq: string = 'all';
|
let qq: string = 'all';
|
||||||
if (element.atType !== NTMsgAtType.ATTYPEALL) {
|
if (element.atType !== NTMsgAtType.ATTYPEALL) {
|
||||||
const { atNtUid, atUid } = element;
|
const { atNtUid, atUid } = element;
|
||||||
qq = !atUid || atUid === '0' ? await this.core.apis.UserApi.getUinByUidV2(atNtUid) : String(Number(atUid) >>> 0);
|
qq = !atUid || atUid === '0' ? await this.core.apis.UserApi.getUinByUidV2(atNtUid) : atUid;
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
type: OB11MessageDataType.at,
|
type: OB11MessageDataType.at,
|
||||||
@@ -150,31 +150,12 @@ export class OneBotMsgApi {
|
|||||||
};
|
};
|
||||||
FileNapCatOneBotUUID.encode(peer, msg.msgId, elementWrapper.elementId, element.fileUuid, element.fileUuid);
|
FileNapCatOneBotUUID.encode(peer, msg.msgId, elementWrapper.elementId, element.fileUuid, element.fileUuid);
|
||||||
FileNapCatOneBotUUID.encode(peer, msg.msgId, elementWrapper.elementId, element.fileUuid, element.fileName);
|
FileNapCatOneBotUUID.encode(peer, msg.msgId, elementWrapper.elementId, element.fileUuid, element.fileName);
|
||||||
if (this.core.apis.PacketApi.available) {
|
|
||||||
let url;
|
|
||||||
try {
|
|
||||||
url = await this.core.apis.FileApi.getFileUrl(msg.chatType, msg.peerUid, element.fileUuid, element.file10MMd5)
|
|
||||||
} catch (error) {
|
|
||||||
url = '';
|
|
||||||
}
|
|
||||||
if (url) {
|
|
||||||
return {
|
return {
|
||||||
type: OB11MessageDataType.file,
|
type: OB11MessageDataType.file,
|
||||||
data: {
|
data: {
|
||||||
file: element.fileName,
|
file: element.fileName,
|
||||||
file_id: element.fileUuid,
|
file_id: element.fileUuid,
|
||||||
file_size: element.fileSize,
|
file_size: element.fileSize,
|
||||||
url: url,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
type: OB11MessageDataType.file,
|
|
||||||
data: {
|
|
||||||
file: element.fileName,
|
|
||||||
file_id: element.fileUuid,
|
|
||||||
file_size: element.fileSize
|
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
@@ -244,13 +225,17 @@ export class OneBotMsgApi {
|
|||||||
},
|
},
|
||||||
|
|
||||||
replyElement: async (element, msg) => {
|
replyElement: async (element, msg) => {
|
||||||
|
const records = msg.records.find(msgRecord => msgRecord.msgId === element?.sourceMsgIdInRecords);
|
||||||
const peer = {
|
const peer = {
|
||||||
chatType: msg.chatType,
|
chatType: msg.chatType,
|
||||||
peerUid: msg.peerUid,
|
peerUid: msg.peerUid,
|
||||||
guildId: '',
|
guildId: '',
|
||||||
};
|
};
|
||||||
|
if (!records || !element.replyMsgTime || !element.senderUidStr) {
|
||||||
|
this.core.context.logger.logError('似乎是旧版客户端,获取不到引用的消息', element.replayMsgSeq);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
// 创建回复数据的通用方法
|
|
||||||
const createReplyData = (msgId: string): OB11MessageData => ({
|
const createReplyData = (msgId: string): OB11MessageData => ({
|
||||||
type: OB11MessageDataType.reply,
|
type: OB11MessageDataType.reply,
|
||||||
data: {
|
data: {
|
||||||
@@ -258,96 +243,48 @@ export class OneBotMsgApi {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// 查找记录
|
if (records.peerUin === '284840486' || records.peerUin === '1094950020') {
|
||||||
const records = msg.records.find(msgRecord => msgRecord.msgId === element?.sourceMsgIdInRecords);
|
|
||||||
|
|
||||||
// 特定账号的特殊处理
|
|
||||||
if (records && (records.peerUin === '284840486' || records.peerUin === '1094950020')) {
|
|
||||||
return createReplyData(records.msgId);
|
return createReplyData(records.msgId);
|
||||||
}
|
}
|
||||||
|
let replyMsgList = (await this.core.apis.MsgApi.queryMsgsWithFilterExWithSeqV2(peer, element.replayMsgSeq, records.msgTime, [element.senderUidStr])).msgList;
|
||||||
|
let replyMsg = replyMsgList.find(msg => msg.msgRandom === records.msgRandom);
|
||||||
|
|
||||||
// 获取消息的通用方法组
|
if (!replyMsg || records.msgRandom !== replyMsg.msgRandom) {
|
||||||
const tryFetchMethods = async (msgSeq: string, senderUid?: string, msgTime?: string, msgRandom?: string): Promise<RawMessage | undefined> => {
|
this.core.context.logger.logError(
|
||||||
try {
|
'筛选结果,筛选消息失败,将使用Fallback-1 Seq: ',
|
||||||
// 方法1:通过序号和时间筛选
|
|
||||||
if (senderUid && msgTime) {
|
|
||||||
const replyMsgList = (await this.core.apis.MsgApi.queryMsgsWithFilterExWithSeqV2(
|
|
||||||
peer, msgSeq, msgTime, [senderUid]
|
|
||||||
)).msgList;
|
|
||||||
|
|
||||||
const replyMsg = msgRandom
|
|
||||||
? replyMsgList.find(msg => msg.msgRandom === msgRandom)
|
|
||||||
: replyMsgList.find(msg => msg.msgSeq === msgSeq);
|
|
||||||
|
|
||||||
if (replyMsg) return replyMsg;
|
|
||||||
|
|
||||||
this.core.context.logger.logWarn(`方法1查询失败,序号: ${msgSeq}, 消息数: ${replyMsgList.length}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 方法2:直接通过序号获取
|
|
||||||
const replyMsgList = (await this.core.apis.MsgApi.getMsgsBySeqAndCount(
|
|
||||||
peer, msgSeq, 1, true, true
|
|
||||||
)).msgList;
|
|
||||||
|
|
||||||
const replyMsg = msgRandom
|
|
||||||
? replyMsgList.find(msg => msg.msgRandom === msgRandom)
|
|
||||||
: replyMsgList.find(msg => msg.msgSeq === msgSeq);
|
|
||||||
|
|
||||||
if (replyMsg) return replyMsg;
|
|
||||||
|
|
||||||
this.core.context.logger.logWarn(`方法2查询失败,序号: ${msgSeq}, 消息数: ${replyMsgList.length}`);
|
|
||||||
|
|
||||||
// 方法3:另一种筛选方式
|
|
||||||
if (senderUid) {
|
|
||||||
const replyMsgList = (await this.core.apis.MsgApi.queryMsgsWithFilterExWithSeqV3(
|
|
||||||
peer, msgSeq, [senderUid]
|
|
||||||
)).msgList;
|
|
||||||
|
|
||||||
const replyMsg = msgRandom
|
|
||||||
? replyMsgList.find(msg => msg.msgRandom === msgRandom)
|
|
||||||
: replyMsgList.find(msg => msg.msgSeq === msgSeq);
|
|
||||||
|
|
||||||
if (replyMsg) return replyMsg;
|
|
||||||
|
|
||||||
this.core.context.logger.logWarn(`方法3查询失败,序号: ${msgSeq}, 消息数: ${replyMsgList.length}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return undefined;
|
|
||||||
} catch (error) {
|
|
||||||
this.core.context.logger.logError('查询回复消息出错', error);
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// 有记录情况下,使用完整信息查询
|
|
||||||
if (records && element.replyMsgTime && element.senderUidStr) {
|
|
||||||
const replyMsg = await tryFetchMethods(
|
|
||||||
element.replayMsgSeq,
|
element.replayMsgSeq,
|
||||||
element.senderUidStr,
|
',消息长度:',
|
||||||
records.msgTime,
|
replyMsgList.length
|
||||||
records.msgRandom
|
|
||||||
);
|
);
|
||||||
|
replyMsgList = (await this.core.apis.MsgApi.getMsgsBySeqAndCount(peer, element.replayMsgSeq, 1, true, true)).msgList;
|
||||||
if (replyMsg) {
|
replyMsg = replyMsgList.find(msg => msg.msgRandom === records.msgRandom);
|
||||||
return createReplyData(replyMsg.msgId);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
this.core.context.logger.logError('所有查找方法均失败,获取不到带记录的引用消息', element.replayMsgSeq);
|
if (!replyMsg || records.msgRandom !== replyMsg.msgRandom) {
|
||||||
} else {
|
this.core.context.logger.logWarn(
|
||||||
// 旧版客户端或不完整记录的情况,也尝试使用相同流程
|
'筛选消息失败,将使用Fallback-2 Seq:',
|
||||||
this.core.context.logger.logWarn('似乎是旧版客户端,尝试仅通过序号获取引用消息', element.replayMsgSeq);
|
element.replayMsgSeq,
|
||||||
|
',消息长度:',
|
||||||
const replyMsg = await tryFetchMethods(element.replayMsgSeq);
|
replyMsgList.length
|
||||||
|
);
|
||||||
if (replyMsg) {
|
replyMsgList = (await this.core.apis.MsgApi.queryMsgsWithFilterExWithSeqV3(peer, element.replayMsgSeq, [element.senderUidStr])).msgList;
|
||||||
return createReplyData(replyMsg.msgId);
|
replyMsg = replyMsgList.find(msg => msg.msgRandom === records.msgRandom);
|
||||||
}
|
}
|
||||||
|
|
||||||
this.core.context.logger.logError('所有查找方法均失败,获取不到旧客户端的引用消息', element.replayMsgSeq);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
// 丢弃该消息段
|
||||||
|
if (!replyMsg || records.msgRandom !== replyMsg.msgRandom) {
|
||||||
|
this.core.context.logger.logError(
|
||||||
|
'最终筛选结果,筛选消息失败,获取不到引用的消息 Seq: ',
|
||||||
|
element.replayMsgSeq,
|
||||||
|
',消息长度:',
|
||||||
|
replyMsgList.length
|
||||||
|
);
|
||||||
return null;
|
return null;
|
||||||
|
}
|
||||||
|
return createReplyData(replyMsg.msgId);
|
||||||
},
|
},
|
||||||
|
|
||||||
videoElement: async (element, msg, elementWrapper) => {
|
videoElement: async (element, msg, elementWrapper) => {
|
||||||
const peer = {
|
const peer = {
|
||||||
chatType: msg.chatType,
|
chatType: msg.chatType,
|
||||||
@@ -394,18 +331,8 @@ export class OneBotMsgApi {
|
|||||||
|
|
||||||
//开始兜底
|
//开始兜底
|
||||||
if (!videoDownUrl) {
|
if (!videoDownUrl) {
|
||||||
if (this.core.apis.PacketApi.available) {
|
|
||||||
try {
|
|
||||||
videoDownUrl = await this.core.apis.FileApi.getVideoUrlPacket(msg.peerUid, element.fileUuid);
|
|
||||||
} catch (e) {
|
|
||||||
this.core.context.logger.logError('获取视频url失败', (e as Error).stack);
|
|
||||||
videoDownUrl = element.filePath;
|
videoDownUrl = element.filePath;
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
videoDownUrl = element.filePath;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
const fileCode = FileNapCatOneBotUUID.encode(peer, msg.msgId, elementWrapper.elementId, element.fileUuid, element.fileName);
|
const fileCode = FileNapCatOneBotUUID.encode(peer, msg.msgId, elementWrapper.elementId, element.fileUuid, element.fileName);
|
||||||
return {
|
return {
|
||||||
type: OB11MessageDataType.video,
|
type: OB11MessageDataType.video,
|
||||||
@@ -424,28 +351,6 @@ export class OneBotMsgApi {
|
|||||||
guildId: '',
|
guildId: '',
|
||||||
};
|
};
|
||||||
const fileCode = FileNapCatOneBotUUID.encode(peer, msg.msgId, elementWrapper.elementId, '', element.fileName);
|
const fileCode = FileNapCatOneBotUUID.encode(peer, msg.msgId, elementWrapper.elementId, '', element.fileName);
|
||||||
let pttUrl = '';
|
|
||||||
if (this.core.apis.PacketApi.available) {
|
|
||||||
try {
|
|
||||||
pttUrl = await this.core.apis.FileApi.getPttUrl(msg.peerUid, element.fileUuid);
|
|
||||||
} catch (e) {
|
|
||||||
this.core.context.logger.logError('获取语音url失败', (e as Error).stack);
|
|
||||||
pttUrl = element.filePath;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
pttUrl = element.filePath;
|
|
||||||
}
|
|
||||||
if (pttUrl) {
|
|
||||||
return {
|
|
||||||
type: OB11MessageDataType.voice,
|
|
||||||
data: {
|
|
||||||
file: fileCode,
|
|
||||||
path: element.filePath,
|
|
||||||
url: pttUrl,
|
|
||||||
file_size: element.fileSize,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return {
|
return {
|
||||||
type: OB11MessageDataType.voice,
|
type: OB11MessageDataType.voice,
|
||||||
data: {
|
data: {
|
||||||
@@ -562,8 +467,6 @@ export class OneBotMsgApi {
|
|||||||
replayMsgId: replyMsg.msgId, // raw.msgId
|
replayMsgId: replyMsg.msgId, // raw.msgId
|
||||||
senderUin: replyMsg.senderUin,
|
senderUin: replyMsg.senderUin,
|
||||||
senderUinStr: replyMsg.senderUin,
|
senderUinStr: replyMsg.senderUin,
|
||||||
replyMsgClientSeq: replyMsg.clientSeq,
|
|
||||||
_replyMsgPeer: replyMsgM.Peer
|
|
||||||
},
|
},
|
||||||
} :
|
} :
|
||||||
undefined;
|
undefined;
|
||||||
|
@@ -50,6 +50,7 @@ import {
|
|||||||
import { OB11Message } from './types';
|
import { OB11Message } from './types';
|
||||||
import { IOB11NetworkAdapter } from '@/onebot/network/adapter';
|
import { IOB11NetworkAdapter } from '@/onebot/network/adapter';
|
||||||
import { OB11HttpSSEServerAdapter } from './network/http-server-sse';
|
import { OB11HttpSSEServerAdapter } from './network/http-server-sse';
|
||||||
|
import { OB11PluginAdapter } from './network/plugin';
|
||||||
|
|
||||||
//OneBot实现类
|
//OneBot实现类
|
||||||
export class NapCatOneBot11Adapter {
|
export class NapCatOneBot11Adapter {
|
||||||
@@ -113,9 +114,9 @@ export class NapCatOneBot11Adapter {
|
|||||||
//创建NetWork服务
|
//创建NetWork服务
|
||||||
|
|
||||||
// 注册Plugin 如果需要基于NapCat进行快速开发
|
// 注册Plugin 如果需要基于NapCat进行快速开发
|
||||||
// this.networkManager.registerAdapter(
|
this.networkManager.registerAdapter(
|
||||||
// new OB11PluginAdapter('myPlugin', this.core, this,this.actions)
|
new OB11PluginAdapter('myPlugin', this.core, this,this.actions)
|
||||||
// );
|
);
|
||||||
for (const key of ob11Config.network.httpServers) {
|
for (const key of ob11Config.network.httpServers) {
|
||||||
if (key.enable) {
|
if (key.enable) {
|
||||||
this.networkManager.registerAdapter(
|
this.networkManager.registerAdapter(
|
||||||
@@ -334,7 +335,7 @@ export class NapCatOneBot11Adapter {
|
|||||||
for (let i = 0; i < reqs.unreadNums; i++) {
|
for (let i = 0; i < reqs.unreadNums; i++) {
|
||||||
const req = reqs.buddyReqs[i];
|
const req = reqs.buddyReqs[i];
|
||||||
if (!req) continue;
|
if (!req) continue;
|
||||||
if (!!req.isInitiator || (req.isDecide && req.reqType !== BuddyReqType.KMEINITIATORWAITPEERCONFIRM) || !req.isUnread) {
|
if (!!req.isInitiator || (req.isDecide && req.reqType !== BuddyReqType.KMEINITIATORWAITPEERCONFIRM)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
@@ -352,6 +353,7 @@ export class NapCatOneBot11Adapter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
this.context.session
|
this.context.session
|
||||||
.getBuddyService()
|
.getBuddyService()
|
||||||
.addKernelBuddyListener(proxiedListenerOf(buddyListener, this.context.logger));
|
.addKernelBuddyListener(proxiedListenerOf(buddyListener, this.context.logger));
|
||||||
|
@@ -1,5 +1,5 @@
|
|||||||
import { OB11EmitEventContent, OB11NetworkReloadType } from './index';
|
import { OB11EmitEventContent, OB11NetworkReloadType } from './index';
|
||||||
import { NapCatOneBot11Adapter, OB11Message } from '@/onebot';
|
import { NapCatOneBot11Adapter, OB11ArrayMessage, OB11Message } from '@/onebot';
|
||||||
import { NapCatCore } from '@/core';
|
import { NapCatCore } from '@/core';
|
||||||
import { PluginConfig } from '../config/config';
|
import { PluginConfig } from '../config/config';
|
||||||
import { plugin_onmessage } from '@/plugin';
|
import { plugin_onmessage } from '@/plugin';
|
||||||
@@ -22,7 +22,7 @@ export class OB11PluginAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
|||||||
|
|
||||||
onEvent<T extends OB11EmitEventContent>(event: T) {
|
onEvent<T extends OB11EmitEventContent>(event: T) {
|
||||||
if (event.post_type === 'message') {
|
if (event.post_type === 'message') {
|
||||||
plugin_onmessage(this.config.name, this.core, this.obContext, event as OB11Message, this.actions, this).then().catch();
|
plugin_onmessage(this.config.name, this.core, this.obContext, event as OB11ArrayMessage, this.actions, this).then().catch();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -39,11 +39,8 @@ export class OB11WebSocketServerAdapter extends IOB11NetworkAdapter<WebsocketSer
|
|||||||
wsClient.close();
|
wsClient.close();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// 鉴权 close 不会立刻销毁 当前返回可避免挂载message事件 close 并未立刻关闭 而是存在timer操作后关闭
|
//鉴权
|
||||||
// 引发高危漏洞
|
this.authorize(this.config.token, wsClient, wsReq);
|
||||||
if (!this.authorize(this.config.token, wsClient, wsReq)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const paramUrl = wsReq.url?.indexOf('?') !== -1 ? wsReq.url?.substring(0, wsReq.url?.indexOf('?')) : wsReq.url;
|
const paramUrl = wsReq.url?.indexOf('?') !== -1 ? wsReq.url?.substring(0, wsReq.url?.indexOf('?')) : wsReq.url;
|
||||||
const isApiConnect = paramUrl === '/api' || paramUrl === '/api/';
|
const isApiConnect = paramUrl === '/api' || paramUrl === '/api/';
|
||||||
if (!isApiConnect) {
|
if (!isApiConnect) {
|
||||||
@@ -148,16 +145,15 @@ export class OB11WebSocketServerAdapter extends IOB11NetworkAdapter<WebsocketSer
|
|||||||
}
|
}
|
||||||
|
|
||||||
private authorize(token: string | undefined, wsClient: WebSocket, wsReq: IncomingMessage) {
|
private authorize(token: string | undefined, wsClient: WebSocket, wsReq: IncomingMessage) {
|
||||||
if (!token || token.length == 0) return true;//客户端未设置密钥
|
if (!token || token.length == 0) return;//客户端未设置密钥
|
||||||
const QueryClientToken = urlParse.parse(wsReq?.url || '', true).query['access_token'];
|
const QueryClientToken = urlParse.parse(wsReq?.url || '', true).query['access_token'];
|
||||||
const HeaderClientToken = wsReq.headers.authorization?.split('Bearer ').pop() || '';
|
const HeaderClientToken = wsReq.headers.authorization?.split('Bearer ').pop() || '';
|
||||||
const ClientToken = typeof (QueryClientToken) === 'string' && QueryClientToken !== '' ? QueryClientToken : HeaderClientToken;
|
const ClientToken = typeof (QueryClientToken) === 'string' && QueryClientToken !== '' ? QueryClientToken : HeaderClientToken;
|
||||||
if (ClientToken === token) {
|
if (ClientToken === token) {
|
||||||
return true;
|
return;
|
||||||
}
|
}
|
||||||
wsClient.send(JSON.stringify(OB11Response.res(null, 'failed', 1403, 'token验证失败')));
|
wsClient.send(JSON.stringify(OB11Response.res(null, 'failed', 1403, 'token验证失败')));
|
||||||
wsClient.close();
|
wsClient.close();
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private checkStateAndReply<T>(data: T, wsClient: WebSocket) {
|
private checkStateAndReply<T>(data: T, wsClient: WebSocket) {
|
||||||
|
@@ -31,6 +31,10 @@ export interface OB11Message {
|
|||||||
post_type?: EventType;
|
post_type?: EventType;
|
||||||
raw?: RawMessage;
|
raw?: RawMessage;
|
||||||
}
|
}
|
||||||
|
export interface OB11ArrayMessage extends OB11Message {
|
||||||
|
message_format: 'array';
|
||||||
|
message: OB11MessageData[];
|
||||||
|
}
|
||||||
|
|
||||||
// 合并转发消息接口定义
|
// 合并转发消息接口定义
|
||||||
export interface OB11ForwardMessage extends OB11Message {
|
export interface OB11ForwardMessage extends OB11Message {
|
||||||
|
@@ -1,11 +1,217 @@
|
|||||||
import { NapCatOneBot11Adapter, OB11Message } from '@/onebot';
|
import { NapCatOneBot11Adapter, OB11ArrayMessage, OB11MessageDataType } from '@/onebot';
|
||||||
import { NapCatCore } from '@/core';
|
import { ChatType, NapCatCore, Peer, RawMessage } from '@/core';
|
||||||
import { ActionMap } from '@/onebot/action';
|
import { ActionMap } from '@/onebot/action';
|
||||||
import { OB11PluginAdapter } from '@/onebot/network/plugin';
|
import { OB11PluginAdapter } from '@/onebot/network/plugin';
|
||||||
|
import { OpenAI } from 'openai';
|
||||||
|
import { RequestUtil } from '@/common/request';
|
||||||
|
import { randomBytes } from 'node:crypto';
|
||||||
|
const client = new OpenAI({
|
||||||
|
apiKey: '',//必填多模态
|
||||||
|
baseURL: 'https://api.bili2233.work/v1'
|
||||||
|
});
|
||||||
|
|
||||||
export const plugin_onmessage = async (adapter: string, _core: NapCatCore, _obCtx: NapCatOneBot11Adapter, message: OB11Message, action: ActionMap, instance: OB11PluginAdapter) => {
|
async function handleMessageArray2String(messages: RawMessage[]): Promise<string[]> {
|
||||||
if (message.raw_message === 'ping') {
|
const result = [];
|
||||||
const ret = await action.get('send_group_msg')?.handle({ group_id: String(message.group_id), message: 'pong' }, adapter, instance.config);
|
let data = '';
|
||||||
console.log(ret);
|
for (let i = 0; i < messages.length; i++) {
|
||||||
|
try {
|
||||||
|
if (messages[i]) {
|
||||||
|
data += await handleMessage2String(messages[i]!) + '\n';
|
||||||
}
|
}
|
||||||
|
} catch {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if ((i + 1) % 1000 === 0 || i === messages.length - 1) {
|
||||||
|
result.push(data);
|
||||||
|
data = '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleMessage2String(message: RawMessage): Promise<string> {
|
||||||
|
let data = '';
|
||||||
|
for (let element of message.elements) {
|
||||||
|
if (element.textElement) {
|
||||||
|
data += element.textElement.content.replaceAll('->', '').replaceAll('<-', '');
|
||||||
|
}
|
||||||
|
if (element.replyElement) {
|
||||||
|
const records = message.records.find(msgRecord => msgRecord.msgId === element.replyElement?.sourceMsgIdInRecords);
|
||||||
|
if (records) {
|
||||||
|
data += '[Reply] 回应别人的消息 ->' + await handleMessage2String(records) + '<-';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (data.length === 0) throw new Error('消息为空');
|
||||||
|
return (message.sendMemberName || message.sendNickName) + ' 说: ->' + data + '<- ';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function generateChatCompletion(content_data: string): Promise<string> {
|
||||||
|
const chatCompletion = await client.chat.completions.create({
|
||||||
|
messages: [{ role: 'user', content: content_data }],
|
||||||
|
model: 'gemini-2.0-flash-thinking-exp'
|
||||||
|
});
|
||||||
|
console.log(chatCompletion);
|
||||||
|
return chatCompletion.choices[0]?.message.content || '';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function generateChatCompletionWithImg(content_data: string, url: string): Promise<string> {
|
||||||
|
const chatCompletion = await client.chat.completions.create({
|
||||||
|
messages: [
|
||||||
|
{
|
||||||
|
role: 'user', content: [
|
||||||
|
{
|
||||||
|
type: 'text',
|
||||||
|
text: content_data
|
||||||
|
}, {
|
||||||
|
type: 'image_url',
|
||||||
|
image_url: {
|
||||||
|
url: url
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
],
|
||||||
|
model: 'gemini-2.0-flash-thinking-exp'
|
||||||
|
});
|
||||||
|
return chatCompletion.choices[0]?.message.content || '';
|
||||||
|
}
|
||||||
|
|
||||||
|
export const plugin_onmessage = async (
|
||||||
|
adapter: string,
|
||||||
|
core: NapCatCore,
|
||||||
|
_obCtx: NapCatOneBot11Adapter,
|
||||||
|
message: OB11ArrayMessage,
|
||||||
|
action: ActionMap,
|
||||||
|
instance: OB11PluginAdapter
|
||||||
|
) => {
|
||||||
|
|
||||||
|
|
||||||
|
if (!message.message.find(m => m.type === 'text' && m.data.text.includes('#画像'))) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const user_id = message.message.find(m => m.type === 'at')?.data.qq ?? message.sender.user_id;
|
||||||
|
const user_uid = await core.apis.UserApi.getUidByUinV2(user_id.toString());
|
||||||
|
if (!user_uid) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const peer: Peer = { chatType: ChatType.KCHATTYPEGROUP, peerUid: message.group_id?.toString() ?? '' };
|
||||||
|
const msg = await core.apis.MsgApi.queryFirstMsgBySender(peer, [user_uid]);
|
||||||
|
if (msg.msgList.length < 1) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let msg_tag = '根据下面图片提取该图片的描述的描述,回应只用给出头像描述即可不要给出 好的 等等无关句子也不得提及该提示词,下面为图片内容。';
|
||||||
|
let avater_info = '头像仅供参考,Ta的头像描述: ' + await generateChatCompletionWithImg(msg_tag, `https://thirdqq.qlogo.cn/g?b=sdk&nk=${user_id}&s=100`);
|
||||||
|
console.log(`Final avater_info ret: ${avater_info}`)
|
||||||
|
const msg_string_all = await handleMessageArray2String(msg.msgList);
|
||||||
|
const user_info = await action.get('get_group_member_info')?.handle({ group_id: message.group_id?.toString()!, user_id: user_id }, adapter, instance.config);
|
||||||
|
|
||||||
|
if (msg_string_all.length > 1) {
|
||||||
|
const summaryPromises = msg_string_all.map(async (msg_string, i) => {
|
||||||
|
const content_data = `请根据下面聊天内容,分析 ${user_info?.data?.card || user_info?.data?.nickname} 的聊天风格分析其性格特点和一些有趣的信息和好笑的信息,为其建立用户画像,并加以幽默风趣的吐槽,下面是聊天内容,通过-><-字符区分结构。注意回复内容只用输出内容,不要提及此段话,注意一定不要使用markdown,请采用纯文本回复。附加提示信息:${avater_info} \n精选聊天记录: ${msg_string}`;
|
||||||
|
try {
|
||||||
|
const data = await generateChatCompletion(content_data);
|
||||||
|
if (data) {
|
||||||
|
msg_string_all[i] = '[总结(此消息过长Ai已压缩改为总结)] ->' + data + '<- ';
|
||||||
|
console.log(`Summary for part ${i + 1}: ${data}`);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
msg_string_all[i] = '';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
await action.get('send_group_msg')?.handle({
|
||||||
|
group_id: String(message.group_id),
|
||||||
|
message: [
|
||||||
|
{
|
||||||
|
type: OB11MessageDataType.reply,
|
||||||
|
data: {
|
||||||
|
id: message.message_id.toString()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: OB11MessageDataType.text,
|
||||||
|
data: {
|
||||||
|
text: `消息过长,共` + msg.msgList.length + `条消息,预计时间` + Math.round(10 * msg.msgList.length / 1000) + `秒,请稍等...`
|
||||||
|
}
|
||||||
|
}]
|
||||||
|
}, adapter, instance.config);
|
||||||
|
await Promise.all(summaryPromises);
|
||||||
|
}
|
||||||
|
|
||||||
|
const msg_string = msg_string_all.join('\n');
|
||||||
|
|
||||||
|
const content_data =
|
||||||
|
`请根据下面聊天内容,分析 ${user_info?.data?.card || user_info?.data?.nickname} 的聊天风格分析其性格特点和一些有趣的信息和好笑的信息,为其建立用户画像,并加以幽默风趣的吐槽,下面是聊天内容,通过-><-字符区分结构。注意回复内容只用输出内容,不要提及此段话,注意一定不要使用markdown,请采用纯文本回复。附加信息:${avater_info} \n精选聊天记录:${msg_string}`;
|
||||||
|
console.log(`Final content data: ${content_data}`);
|
||||||
|
const msg_ret = await generateChatCompletion(content_data);
|
||||||
|
console.log(`Final content ret: ${msg_ret}`)
|
||||||
|
let pic_tag = `请根据下面对该人物性格的分析,并虚构想象一个场景,生成如 (1 cute girl with (cat ear and cat tail:1.2) stands in the garden:1.1), (cute:1.35), (detailed beautiful eyes:1.3), (beautiful face:1.3), casual, silver hair, silver ear, (blue hair:0.8), (blue ear:0.8), long hair, coat, short skirt, hair blowing with the wind, (blue eye:1.2), flowers, (little girl:0.65), butterflys flying around 格式的文本用于描述人物,注意格式为英文加空格加逗号进行区分,请务必多的描述人物和想象和场景,至少50个描述Tag,风格是可爱动漫二次元风,注意一定要是人为主体描述,不要好的什么的回应,只用给出要求格式的文本,不需要 好的 的回应,也不要提及此段话,下面为该人物性格分析.附加信息:${avater_info}.下面是人物分析.\n${msg_ret}`;
|
||||||
|
let pic_tag_ret = await generateChatCompletion(pic_tag);
|
||||||
|
let pic = `https://thirdqq.qlogo.cn/g?b=sdk&nk=${user_id}&s=100`;
|
||||||
|
try {
|
||||||
|
let pic_generate = await RequestUtil.HttpGetJson<{ images?: Array<{ url: string }> }>
|
||||||
|
('https://api.siliconflow.cn/v1/images/generations', 'POST', {
|
||||||
|
"model": "stabilityai/stable-diffusion-xl-base-1.0",
|
||||||
|
"prompt": 'original, (masterpiece), (illustration), (extremely fine and beautiful), perfect detailed, photorealistic, (beautiful and clear background:1.25), (depth of field:0.7),' + pic_tag_ret,
|
||||||
|
"seed": randomBytes(4).readUInt32LE(0),
|
||||||
|
"negative_prompt": "(copyright name:1.5),logo,(watermark:1.5),character_watermark,lowres, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry, bad feet, ((cowboy)),(((pubic))), ((((pubic_hair))))sketch, duplicate, ugly, huge eyes, text, logo, monochrome, worst face, (bad and mutated hands:1.3), (worst quality:2.0), (low quality:2.0), (blurry:2.0), horror, geometry, bad_prompt, (bad hands), (missing fingers), multiple limbs, bad anatomy, (interlocked fingers:1.2), Ugly Fingers, (extra digit and hands and fingers and legs and arms:1.4), crown braid, ((2girl)), (deformed fingers:1.2), (long fingers:1.2),succubus wings,horn,succubus horn,succubus hairstyle, (bad-artist-anime), bad-artist, bad hand"
|
||||||
|
}, {
|
||||||
|
Authorization: 'Bearer ',//必填
|
||||||
|
'Content-Type': 'application/json'
|
||||||
|
});
|
||||||
|
if (pic_generate?.images?.[0]) {
|
||||||
|
pic = pic_generate?.images?.[0].url;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
|
||||||
|
}
|
||||||
|
await action.get('send_group_msg')?.handle({
|
||||||
|
group_id: String(message.group_id),
|
||||||
|
message: [{
|
||||||
|
type: OB11MessageDataType.node,
|
||||||
|
data: {
|
||||||
|
user_id: user_id,
|
||||||
|
nickname: user_info?.data?.card || user_info?.data?.nickname || '',
|
||||||
|
content: [
|
||||||
|
{
|
||||||
|
type: OB11MessageDataType.text,
|
||||||
|
data: { text: msg_ret }
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: OB11MessageDataType.node,
|
||||||
|
data: {
|
||||||
|
user_id: user_id,
|
||||||
|
nickname: user_info?.data?.card || user_info?.data?.nickname || '',
|
||||||
|
content: [
|
||||||
|
{
|
||||||
|
type: OB11MessageDataType.text,
|
||||||
|
data: { text: 'Tag: ' + pic_tag_ret }
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: OB11MessageDataType.node,
|
||||||
|
data: {
|
||||||
|
user_id: user_id,
|
||||||
|
nickname: user_info?.data?.card || user_info?.data?.nickname || '',
|
||||||
|
content: [
|
||||||
|
{
|
||||||
|
type: OB11MessageDataType.image,
|
||||||
|
data: {
|
||||||
|
file: pic
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}, adapter, instance.config);
|
||||||
|
|
||||||
};
|
};
|
@@ -1,7 +1,6 @@
|
|||||||
import { LogWrapper } from '@/common/log';
|
import { LogWrapper } from '@/common/log';
|
||||||
import * as net from 'net';
|
import * as net from 'net';
|
||||||
import * as process from 'process';
|
import * as process from 'process';
|
||||||
import { Writable } from 'stream';
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 连接到命名管道并重定向stdout
|
* 连接到命名管道并重定向stdout
|
||||||
@@ -12,6 +11,7 @@ import { Writable } from 'stream';
|
|||||||
export function connectToNamedPipe(logger: LogWrapper, timeoutMs: number = 5000): Promise<{ disconnect: () => void }> {
|
export function connectToNamedPipe(logger: LogWrapper, timeoutMs: number = 5000): Promise<{ disconnect: () => void }> {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
if (process.platform !== 'win32') {
|
if (process.platform !== 'win32') {
|
||||||
|
logger.log('只有Windows平台支持命名管道');
|
||||||
// 非Windows平台不reject,而是返回一个空的disconnect函数
|
// 非Windows平台不reject,而是返回一个空的disconnect函数
|
||||||
return resolve({ disconnect: () => { } });
|
return resolve({ disconnect: () => { } });
|
||||||
}
|
}
|
||||||
@@ -25,50 +25,12 @@ export function connectToNamedPipe(logger: LogWrapper, timeoutMs: number = 5000)
|
|||||||
}, timeoutMs);
|
}, timeoutMs);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const originalStdoutWrite = process.stdout.write.bind(process.stdout);
|
let originalStdoutWrite = process.stdout.write.bind(process.stdout);
|
||||||
const pipeSocket = net.connect(pipePath, () => {
|
const pipeSocket = net.connect(pipePath, () => {
|
||||||
// 清除超时
|
// 清除超时
|
||||||
clearTimeout(timeoutId);
|
clearTimeout(timeoutId);
|
||||||
|
|
||||||
// 优化网络性能设置
|
|
||||||
pipeSocket.setNoDelay(true); // 减少延迟
|
|
||||||
|
|
||||||
// 设置更高的高水位线,允许更多数据缓冲
|
|
||||||
|
|
||||||
logger.log(`[StdOut] 已重定向到命名管道: ${pipePath}`);
|
logger.log(`[StdOut] 已重定向到命名管道: ${pipePath}`);
|
||||||
|
|
||||||
// 创建拥有更优雅背压处理的 Writable 流
|
|
||||||
const pipeWritable = new Writable({
|
|
||||||
highWaterMark: 1024 * 64, // 64KB 高水位线
|
|
||||||
write(chunk, encoding, callback) {
|
|
||||||
if (!pipeSocket.writable) {
|
|
||||||
// 如果管道不可写,退回到原始stdout
|
|
||||||
logger.log('[StdOut] 管道不可写,回退到控制台输出');
|
|
||||||
return originalStdoutWrite(chunk, encoding, callback);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 尝试写入数据到管道
|
|
||||||
const canContinue = pipeSocket.write(chunk, encoding, () => {
|
|
||||||
// 数据已被发送或放入内部缓冲区
|
|
||||||
});
|
|
||||||
|
|
||||||
if (canContinue) {
|
|
||||||
// 如果返回true,表示可以继续写入更多数据
|
|
||||||
// 立即通知写入流可以继续
|
|
||||||
process.nextTick(callback);
|
|
||||||
} else {
|
|
||||||
// 如果返回false,表示内部缓冲区已满
|
|
||||||
// 等待drain事件再恢复写入
|
|
||||||
pipeSocket.once('drain', () => {
|
|
||||||
callback();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
// 明确返回true,表示写入已处理
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// 重定向stdout
|
|
||||||
process.stdout.write = (
|
process.stdout.write = (
|
||||||
chunk: any,
|
chunk: any,
|
||||||
encoding?: BufferEncoding | (() => void),
|
encoding?: BufferEncoding | (() => void),
|
||||||
@@ -78,11 +40,8 @@ export function connectToNamedPipe(logger: LogWrapper, timeoutMs: number = 5000)
|
|||||||
cb = encoding;
|
cb = encoding;
|
||||||
encoding = undefined;
|
encoding = undefined;
|
||||||
}
|
}
|
||||||
|
return pipeSocket.write(chunk, encoding as BufferEncoding, cb);
|
||||||
// 使用优化的writable流处理写入
|
|
||||||
return pipeWritable.write(chunk, encoding as BufferEncoding, cb as () => void);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// 提供断开连接的方法
|
// 提供断开连接的方法
|
||||||
const disconnect = () => {
|
const disconnect = () => {
|
||||||
process.stdout.write = originalStdoutWrite;
|
process.stdout.write = originalStdoutWrite;
|
||||||
@@ -94,7 +53,6 @@ export function connectToNamedPipe(logger: LogWrapper, timeoutMs: number = 5000)
|
|||||||
resolve({ disconnect });
|
resolve({ disconnect });
|
||||||
});
|
});
|
||||||
|
|
||||||
// 管道错误处理
|
|
||||||
pipeSocket.on('error', (err) => {
|
pipeSocket.on('error', (err) => {
|
||||||
clearTimeout(timeoutId);
|
clearTimeout(timeoutId);
|
||||||
process.stdout.write = originalStdoutWrite;
|
process.stdout.write = originalStdoutWrite;
|
||||||
@@ -102,18 +60,11 @@ export function connectToNamedPipe(logger: LogWrapper, timeoutMs: number = 5000)
|
|||||||
reject(err);
|
reject(err);
|
||||||
});
|
});
|
||||||
|
|
||||||
// 管道关闭处理
|
|
||||||
pipeSocket.on('end', () => {
|
pipeSocket.on('end', () => {
|
||||||
process.stdout.write = originalStdoutWrite;
|
process.stdout.write = originalStdoutWrite;
|
||||||
logger.log('命名管道连接已关闭');
|
logger.log('命名管道连接已关闭');
|
||||||
});
|
});
|
||||||
|
|
||||||
// 确保在连接意外关闭时恢复stdout
|
|
||||||
pipeSocket.on('close', () => {
|
|
||||||
process.stdout.write = originalStdoutWrite;
|
|
||||||
logger.log('命名管道连接已关闭');
|
|
||||||
});
|
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
clearTimeout(timeoutId);
|
clearTimeout(timeoutId);
|
||||||
logger.log(`尝试连接命名管道 ${pipePath} 时发生异常:`, error);
|
logger.log(`尝试连接命名管道 ${pipePath} 时发生异常:`, error);
|
||||||
|
@@ -7,7 +7,8 @@ import { builtinModules } from 'module';
|
|||||||
const external = [
|
const external = [
|
||||||
'silk-wasm',
|
'silk-wasm',
|
||||||
'ws',
|
'ws',
|
||||||
'express'
|
'express',
|
||||||
|
'openai'
|
||||||
];
|
];
|
||||||
const nodeModules = [...builtinModules, builtinModules.map((m) => `node:${m}`)].flat();
|
const nodeModules = [...builtinModules, builtinModules.map((m) => `node:${m}`)].flat();
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user