mirror of
https://github.com/LLOneBot/LLOneBot.git
synced 2024-11-22 01:56:33 +00:00
Compare commits
32 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
54179cb686 | ||
![]() |
c9a5ee69cf | ||
![]() |
e348103e84 | ||
![]() |
fccb0852aa | ||
![]() |
b3ea8fbc0c | ||
![]() |
ee483dd0cc | ||
![]() |
ed681b8adf | ||
![]() |
dcd4533eb3 | ||
![]() |
178c32053b | ||
![]() |
49ba276f5d | ||
![]() |
2bfe9e236b | ||
![]() |
05fd258afd | ||
![]() |
3b3098e017 | ||
![]() |
ddf9eed3a5 | ||
![]() |
712f0a8256 | ||
![]() |
a93220f9d2 | ||
![]() |
253cee7458 | ||
![]() |
82f9a4c63f | ||
![]() |
de6c8a5558 | ||
![]() |
c75337b8cb | ||
![]() |
2b796e33fe | ||
![]() |
175307d980 | ||
![]() |
993f8a9e8f | ||
![]() |
0130b8f6f7 | ||
![]() |
ba482d492f | ||
![]() |
6e71cd6064 | ||
![]() |
83dc1abd4a | ||
![]() |
4cabb9696e | ||
![]() |
75883e9cae | ||
![]() |
eeadaa12e9 | ||
![]() |
192736c8be | ||
![]() |
586fbb6518 |
15
README.md
15
README.md
@@ -29,17 +29,24 @@ TG群:<https://t.me/+nLZEnpne-pQ1OWFl>
|
||||
- [x] 群管理功能,禁言、踢人,改群名片等
|
||||
- [x] 视频消息
|
||||
- [x] 文件消息
|
||||
- [x] 群禁言事件上报
|
||||
- [x] 优化加群成功事件上报
|
||||
- [x] 清理缓存api
|
||||
- [ ] 无头模式
|
||||
- [ ] 群禁言事件上报
|
||||
- [ ] 优化加群成功事件上报
|
||||
- [ ] 清理缓存api
|
||||
- [ ] 框架对接文档
|
||||
|
||||
## onebot11文档
|
||||
<https://11.onebot.dev/>
|
||||
|
||||
## Stargazers over time
|
||||
[](https://starchart.cc/LLOneBot/LLOneBot)
|
||||
|
||||
|
||||
## 鸣谢
|
||||
* [LiteLoaderQQNT](https://liteloaderqqnt.github.io/guide/install.html)
|
||||
* [LLAPI](https://github.com/Night-stars-1/LiteLoaderQQNT-Plugin-LLAPI)
|
||||
* chronocat
|
||||
* [chronocat](https://github.com/chrononeko/chronocat/)
|
||||
* [koishi-plugin-adapter-onebot](https://github.com/koishijs/koishi-plugin-adapter-onebot)
|
||||
|
||||
## 友链
|
||||
* [Lagrange.Core](https://github.com/LagrangeDev/Lagrange.Core) 一款用C#实现的NTQQ纯协议跨平台QQ机器人框架
|
||||
|
@@ -28,7 +28,9 @@ let config = {
|
||||
'./lib-cov/fluent-ffmpeg': './lib/fluent-ffmpeg'
|
||||
},
|
||||
},
|
||||
plugins: [cp({ targets: [...external.map(genCpModule), { src: './manifest.json', dest: 'dist' }] })]
|
||||
plugins: [cp({ targets: [...external.map(genCpModule),
|
||||
{ src: './manifest.json', dest: 'dist' }, {src: './icon.jpg', dest: 'dist' }]
|
||||
})]
|
||||
},
|
||||
preload: {
|
||||
// vite config options
|
||||
|
@@ -1,11 +1,11 @@
|
||||
{
|
||||
"manifest_version": 4,
|
||||
"type": "extension",
|
||||
"name": "LLOneBot v3.13.10",
|
||||
"name": "LLOneBot v3.15.1",
|
||||
"slug": "LLOneBot",
|
||||
"description": "LiteLoaderQQNT的OneBotApi",
|
||||
"version": "3.13.10",
|
||||
"thumbnail": "./icon.png",
|
||||
"description": "LiteLoaderQQNT的OneBotApi,不支持商店在线更新",
|
||||
"version": "3.15.1",
|
||||
"icon": "./icon.jpg",
|
||||
"authors": [
|
||||
{
|
||||
"name": "linyuchen",
|
||||
|
@@ -9,7 +9,7 @@
|
||||
"build-mac": "npm run build && npm run deploy-mac",
|
||||
"deploy-mac": "cp -r dist/* ~/Library/Containers/com.tencent.qq/Data/LiteLoaderQQNT/plugins/LLOneBot/",
|
||||
"build-win": "npm run build && npm run deploy-win",
|
||||
"deploy-win": "cmd /c \"xcopy /S /Y dist\\* %USERPROFILE%\\documents\\LiteLoaderQQNT\\plugins\\LLOneBot\\\""
|
||||
"deploy-win": "cmd /c \"xcopy /C /S /Y dist\\* %USERPROFILE%\\documents\\LiteLoaderQQNT\\plugins\\LLOneBot\\\""
|
||||
},
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
|
17
scripts/test/test_db.ts
Normal file
17
scripts/test/test_db.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import {Level} from "level"
|
||||
|
||||
const db = new Level(process.env["level_db_path"], {valueEncoding: 'json'});
|
||||
|
||||
async function getGroupNotify() {
|
||||
let keys = await db.keys().all();
|
||||
let result = []
|
||||
for (const key of keys) {
|
||||
// console.log(key)
|
||||
if (key.startsWith("group_notify_")) {
|
||||
result.push(key)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
getGroupNotify().then(console.log)
|
@@ -11,7 +11,7 @@ import {
|
||||
import {type FileCache, type LLOneBotError} from './types'
|
||||
import {dbUtil} from "./db";
|
||||
import {raw} from "express";
|
||||
import {log} from "./utils";
|
||||
import {isNumeric, log} from "./utils";
|
||||
|
||||
export const selfInfo: SelfInfo = {
|
||||
uid: '',
|
||||
@@ -21,7 +21,6 @@ export const selfInfo: SelfInfo = {
|
||||
}
|
||||
export let groups: Group[] = []
|
||||
export let friends: Friend[] = []
|
||||
export let groupNotifies: Map<string, GroupNotify> = new Map<string, GroupNotify>()
|
||||
export let friendRequests: Map<number, FriendRequest> = new Map<number, FriendRequest>()
|
||||
export const llonebotError: LLOneBotError = {
|
||||
ffmpegError: '',
|
||||
@@ -29,9 +28,9 @@ export const llonebotError: LLOneBotError = {
|
||||
}
|
||||
|
||||
|
||||
export async function getFriend(qq: string, uid: string = ""): Promise<Friend | undefined> {
|
||||
let filterKey = uid ? "uid" : "uin"
|
||||
let filterValue = uid ? uid : qq
|
||||
export async function getFriend(uinOrUid: string): Promise<Friend | undefined> {
|
||||
let filterKey = isNumeric(uinOrUid) ? "uin" : "uid"
|
||||
let filterValue = uinOrUid
|
||||
let friend = friends.find(friend => friend[filterKey] === filterValue.toString())
|
||||
// if (!friend) {
|
||||
// try {
|
||||
@@ -60,15 +59,13 @@ export async function getGroup(qq: string): Promise<Group | undefined> {
|
||||
return group
|
||||
}
|
||||
|
||||
export async function getGroupMember(groupQQ: string | number, memberQQ: string | number, memberUid: string = null) {
|
||||
export async function getGroupMember(groupQQ: string | number, memberUinOrUid: string | number) {
|
||||
groupQQ = groupQQ.toString()
|
||||
if (memberQQ) {
|
||||
memberQQ = memberQQ.toString()
|
||||
}
|
||||
memberUinOrUid = memberUinOrUid.toString()
|
||||
const group = await getGroup(groupQQ)
|
||||
if (group) {
|
||||
const filterKey = memberQQ ? "uin" : "uid"
|
||||
const filterValue = memberQQ ? memberQQ : memberUid
|
||||
const filterKey = isNumeric(memberUinOrUid) ? "uin" : "uid"
|
||||
const filterValue = memberUinOrUid
|
||||
let filterFunc: (member: GroupMember) => boolean = member => member[filterKey] === filterValue
|
||||
let member = group.members?.find(filterFunc)
|
||||
if (!member) {
|
||||
|
137
src/common/db.ts
137
src/common/db.ts
@@ -1,17 +1,18 @@
|
||||
import {Level} from "level";
|
||||
import {RawMessage} from "../ntqqapi/types";
|
||||
import {type GroupNotify, RawMessage} from "../ntqqapi/types";
|
||||
import {DATA_DIR, log} from "./utils";
|
||||
import {selfInfo} from "./data";
|
||||
import {FileCache} from "./types";
|
||||
|
||||
|
||||
class DBUtil {
|
||||
private readonly DB_KEY_PREFIX_MSG_ID = "msg_id_";
|
||||
private readonly DB_KEY_PREFIX_MSG_SHORT_ID = "msg_short_id_";
|
||||
private readonly DB_KEY_PREFIX_MSG_SEQ_ID = "msg_seq_id_";
|
||||
private readonly DB_KEY_PREFIX_FILE = "file_";
|
||||
private db: Level;
|
||||
public cache: Record<string, RawMessage | string | FileCache> = {} // <msg_id_ | msg_short_id_ | msg_seq_id_><id>: RawMessage
|
||||
public readonly DB_KEY_PREFIX_MSG_ID = "msg_id_";
|
||||
public readonly DB_KEY_PREFIX_MSG_SHORT_ID = "msg_short_id_";
|
||||
public readonly DB_KEY_PREFIX_MSG_SEQ_ID = "msg_seq_id_";
|
||||
public readonly DB_KEY_PREFIX_FILE = "file_";
|
||||
public readonly DB_KEY_PREFIX_GROUP_NOTIFY = "group_notify_";
|
||||
public db: Level;
|
||||
public cache: Record<string, RawMessage | string | FileCache | GroupNotify> = {} // <msg_id_ | msg_short_id_ | msg_seq_id_><id>: RawMessage
|
||||
private currentShortId: number;
|
||||
|
||||
/*
|
||||
@@ -47,9 +48,23 @@ class DBUtil {
|
||||
}
|
||||
initDB();
|
||||
}).then()
|
||||
|
||||
const expiredMilliSecond = 1000 * 60 * 60;
|
||||
|
||||
setInterval(() => {
|
||||
this.cache = {}
|
||||
}, 1000 * 60 * 10)
|
||||
// this.cache = {}
|
||||
// 清理时间较久的缓存
|
||||
const now = Date.now()
|
||||
for (let key in this.cache) {
|
||||
let message: RawMessage = this.cache[key] as RawMessage;
|
||||
if (message?.msgTime){
|
||||
if ((now - (parseInt(message.msgTime) * 1000)) > expiredMilliSecond) {
|
||||
delete this.cache[key]
|
||||
// log("clear cache", key, message.msgTime);
|
||||
}
|
||||
}
|
||||
}
|
||||
}, expiredMilliSecond)
|
||||
}
|
||||
|
||||
private addCache(msg: RawMessage) {
|
||||
@@ -59,15 +74,24 @@ class DBUtil {
|
||||
this.cache[longIdKey] = this.cache[shortIdKey] = msg
|
||||
}
|
||||
|
||||
public clearCache() {
|
||||
this.cache = {}
|
||||
}
|
||||
|
||||
async getMsgByShortId(shortMsgId: number): Promise<RawMessage> {
|
||||
const shortMsgIdKey = this.DB_KEY_PREFIX_MSG_SHORT_ID + shortMsgId;
|
||||
if (this.cache[shortMsgIdKey]) {
|
||||
// log("getMsgByShortId cache", shortMsgIdKey, this.cache[shortMsgIdKey])
|
||||
return this.cache[shortMsgIdKey] as RawMessage
|
||||
}
|
||||
const longId = await this.db.get(shortMsgIdKey);
|
||||
const msg = await this.getMsgByLongId(longId)
|
||||
this.addCache(msg)
|
||||
return msg
|
||||
try {
|
||||
const longId = await this.db.get(shortMsgIdKey);
|
||||
const msg = await this.getMsgByLongId(longId)
|
||||
this.addCache(msg)
|
||||
return msg
|
||||
} catch (e) {
|
||||
log("getMsgByShortId db error", e.stack.toString())
|
||||
}
|
||||
}
|
||||
|
||||
async getMsgByLongId(longId: string): Promise<RawMessage> {
|
||||
@@ -75,10 +99,14 @@ class DBUtil {
|
||||
if (this.cache[longIdKey]) {
|
||||
return this.cache[longIdKey] as RawMessage
|
||||
}
|
||||
const data = await this.db.get(longIdKey)
|
||||
const msg = JSON.parse(data)
|
||||
this.addCache(msg)
|
||||
return msg
|
||||
try {
|
||||
const data = await this.db.get(longIdKey)
|
||||
const msg = JSON.parse(data)
|
||||
this.addCache(msg)
|
||||
return msg
|
||||
} catch (e) {
|
||||
// log("getMsgByLongId db error", e.stack.toString())
|
||||
}
|
||||
}
|
||||
|
||||
async getMsgBySeqId(seqId: string): Promise<RawMessage> {
|
||||
@@ -86,10 +114,14 @@ class DBUtil {
|
||||
if (this.cache[seqIdKey]) {
|
||||
return this.cache[seqIdKey] as RawMessage
|
||||
}
|
||||
const longId = await this.db.get(seqIdKey);
|
||||
const msg = await this.getMsgByLongId(longId)
|
||||
this.addCache(msg)
|
||||
return msg
|
||||
try {
|
||||
const longId = await this.db.get(seqIdKey);
|
||||
const msg = await this.getMsgByLongId(longId)
|
||||
this.addCache(msg)
|
||||
return msg
|
||||
} catch (e) {
|
||||
log("getMsgBySeqId db error", e.stack.toString())
|
||||
}
|
||||
}
|
||||
|
||||
async addMsg(msg: RawMessage) {
|
||||
@@ -110,28 +142,25 @@ class DBUtil {
|
||||
return existMsg.msgShortId
|
||||
}
|
||||
this.addCache(msg);
|
||||
// log("新增消息记录", msg.msgId)
|
||||
|
||||
const shortMsgId = await this.genMsgShortId();
|
||||
const shortIdKey = this.DB_KEY_PREFIX_MSG_SHORT_ID + shortMsgId;
|
||||
const seqIdKey = this.DB_KEY_PREFIX_MSG_SEQ_ID + msg.msgSeq;
|
||||
msg.msgShortId = shortMsgId;
|
||||
// log("新增消息记录", msg.msgId)
|
||||
this.db.put(shortIdKey, msg.msgId).then().catch();
|
||||
this.db.put(longIdKey, JSON.stringify(msg)).then().catch();
|
||||
try {
|
||||
this.db.put(shortIdKey, msg.msgId).then();
|
||||
this.db.put(longIdKey, JSON.stringify(msg)).then();
|
||||
try {
|
||||
await this.db.get(seqIdKey)
|
||||
} catch (e) {
|
||||
// log("新的seqId", seqIdKey)
|
||||
this.db.put(seqIdKey, msg.msgId).then();
|
||||
}
|
||||
if (!this.cache[seqIdKey]) {
|
||||
this.cache[seqIdKey] = msg;
|
||||
}
|
||||
// log(`消息入库 ${seqIdKey}: ${msg.msgId}, ${shortMsgId}: ${msg.msgId}`);
|
||||
await this.db.get(seqIdKey)
|
||||
} catch (e) {
|
||||
// log("addMsg db error", e.stack.toString());
|
||||
// log("新的seqId", seqIdKey)
|
||||
this.db.put(seqIdKey, msg.msgId).then().catch();
|
||||
}
|
||||
if (!this.cache[seqIdKey]) {
|
||||
this.cache[seqIdKey] = msg;
|
||||
}
|
||||
return shortMsgId
|
||||
// log(`消息入库 ${seqIdKey}: ${msg.msgId}, ${shortMsgId}: ${msg.msgId}`);
|
||||
}
|
||||
|
||||
async updateMsg(msg: RawMessage) {
|
||||
@@ -146,17 +175,17 @@ class DBUtil {
|
||||
}
|
||||
|
||||
Object.assign(existMsg, msg)
|
||||
this.db.put(longIdKey, JSON.stringify(existMsg)).then();
|
||||
this.db.put(longIdKey, JSON.stringify(existMsg)).then().catch();
|
||||
const shortIdKey = this.DB_KEY_PREFIX_MSG_SHORT_ID + existMsg.msgShortId;
|
||||
const seqIdKey = this.DB_KEY_PREFIX_MSG_SEQ_ID + msg.msgSeq;
|
||||
if (!this.cache[seqIdKey]) {
|
||||
this.cache[seqIdKey] = existMsg;
|
||||
}
|
||||
this.db.put(shortIdKey, msg.msgId).then();
|
||||
this.db.put(shortIdKey, msg.msgId).then().catch();
|
||||
try {
|
||||
await this.db.get(seqIdKey)
|
||||
} catch (e) {
|
||||
this.db.put(seqIdKey, msg.msgId).then();
|
||||
this.db.put(seqIdKey, msg.msgId).then().catch();
|
||||
// log("更新seqId error", e.stack, seqIdKey);
|
||||
}
|
||||
// log("更新消息", existMsg.msgSeq, existMsg.msgShortId, existMsg.msgId);
|
||||
@@ -175,7 +204,7 @@ class DBUtil {
|
||||
}
|
||||
|
||||
this.currentShortId++;
|
||||
await this.db.put(key, this.currentShortId.toString());
|
||||
this.db.put(key, this.currentShortId.toString()).then().catch();
|
||||
return this.currentShortId;
|
||||
}
|
||||
|
||||
@@ -187,7 +216,11 @@ class DBUtil {
|
||||
let cacheDBData = {...data}
|
||||
delete cacheDBData['downloadFunc']
|
||||
this.cache[fileName] = data;
|
||||
await this.db.put(key, JSON.stringify(cacheDBData));
|
||||
try {
|
||||
await this.db.put(key, JSON.stringify(cacheDBData));
|
||||
} catch (e) {
|
||||
log("addFileCache db error", e.stack.toString())
|
||||
}
|
||||
}
|
||||
|
||||
async getFileCache(fileName: string): Promise<FileCache | undefined> {
|
||||
@@ -196,11 +229,33 @@ class DBUtil {
|
||||
return this.cache[key] as FileCache
|
||||
}
|
||||
try {
|
||||
|
||||
let data = await this.db.get(key);
|
||||
return JSON.parse(data);
|
||||
} catch (e) {
|
||||
// log("getFileCache db error", e.stack.toString())
|
||||
}
|
||||
}
|
||||
|
||||
async addGroupNotify(notify: GroupNotify) {
|
||||
const key = this.DB_KEY_PREFIX_GROUP_NOTIFY + notify.seq;
|
||||
let existNotify = this.cache[key] as GroupNotify
|
||||
if (existNotify) {
|
||||
return
|
||||
}
|
||||
this.cache[key] = notify;
|
||||
this.db.put(key, JSON.stringify(notify)).then().catch();
|
||||
}
|
||||
|
||||
async getGroupNotify(seq: string): Promise<GroupNotify | undefined> {
|
||||
const key = this.DB_KEY_PREFIX_GROUP_NOTIFY + seq;
|
||||
if (this.cache[key]) {
|
||||
return this.cache[key] as GroupNotify
|
||||
}
|
||||
try {
|
||||
let data = await this.db.get(key);
|
||||
return JSON.parse(data);
|
||||
} catch (e) {
|
||||
// log("getGroupNotify db error", e.stack.toString())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -11,8 +11,21 @@ export abstract class HttpServerBase {
|
||||
|
||||
constructor() {
|
||||
this.expressAPP = express();
|
||||
this.expressAPP.use(express.urlencoded({extended: true, limit: "500mb"}));
|
||||
this.expressAPP.use(json({limit: "500mb"}));
|
||||
this.expressAPP.use(express.urlencoded({extended: true, limit: "5000mb"}));
|
||||
this.expressAPP.use((req, res, next) => {
|
||||
// 兼容处理没有带content-type的请求
|
||||
// log("req.headers['content-type']", req.headers['content-type'])
|
||||
req.headers['content-type'] = 'application/json';
|
||||
const originalJson = express.json({limit: "5000mb"});
|
||||
// 调用原始的express.json()处理器
|
||||
originalJson(req, res, (err) => {
|
||||
if (err) {
|
||||
log("Error parsing JSON:", err);
|
||||
return res.status(400).send("Invalid JSON");
|
||||
}
|
||||
next();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
authorize(req: Request, res: Response, next: () => void) {
|
||||
|
@@ -4,6 +4,7 @@ import {ConfigUtil} from "./config";
|
||||
import util from "util";
|
||||
import {encode, getDuration, isWav} from "silk-wasm";
|
||||
import fs from 'fs';
|
||||
import * as crypto from 'crypto';
|
||||
import {v4 as uuidv4} from "uuid";
|
||||
import ffmpeg from "fluent-ffmpeg"
|
||||
|
||||
@@ -31,6 +32,11 @@ function truncateString(obj: any, maxLength = 500) {
|
||||
return obj;
|
||||
}
|
||||
|
||||
export function isNumeric(str: string) {
|
||||
return /^\d+$/.test(str);
|
||||
}
|
||||
|
||||
|
||||
export function log(...msg: any[]) {
|
||||
if (!getConfigUtil().getConfig().log) {
|
||||
return //console.log(...msg);
|
||||
@@ -205,7 +211,7 @@ export async function encodeSilk(filePath: string) {
|
||||
if (ffmpegPath) {
|
||||
ffmpeg.setFfmpegPath(ffmpegPath);
|
||||
}
|
||||
ffmpeg(filePath).toFormat("wav").on('end', function () {
|
||||
ffmpeg(filePath).toFormat("wav").audioChannels(2).on('end', function () {
|
||||
log('wav转换完成');
|
||||
})
|
||||
.on('error', function (err) {
|
||||
@@ -220,11 +226,11 @@ export async function encodeSilk(filePath: string) {
|
||||
})
|
||||
}
|
||||
// const sampleRate = await getAudioSampleRate(filePath) || 0;
|
||||
// log("音频采样率", sampleRate)
|
||||
const pcm = fs.readFileSync(filePath);
|
||||
const silk = await encode(pcm, 0);
|
||||
fs.writeFileSync(pttPath, silk.data);
|
||||
fs.unlink(wavPath, (err) => {
|
||||
});
|
||||
fs.unlink(wavPath, (err) => { });
|
||||
log(`语音文件${filePath}转换成功!`, pttPath)
|
||||
return {
|
||||
converted: true,
|
||||
@@ -234,9 +240,9 @@ export async function encodeSilk(filePath: string) {
|
||||
} else {
|
||||
const pcm = fs.readFileSync(filePath);
|
||||
let duration = 0;
|
||||
try{
|
||||
try {
|
||||
duration = getDuration(pcm);
|
||||
}catch (e) {
|
||||
} catch (e) {
|
||||
log("获取语音文件时长失败", filePath, e.stack)
|
||||
duration = fs.statSync(filePath).size / 1024 / 3 // 每3kb大约1s
|
||||
duration = Math.floor(duration)
|
||||
@@ -256,6 +262,81 @@ export async function encodeSilk(filePath: string) {
|
||||
}
|
||||
}
|
||||
|
||||
export async function getVideoInfo(filePath: string) {
|
||||
const size = fs.statSync(filePath).size;
|
||||
return new Promise<{ width: number, height: number, time: number, format: string, size: number, filePath: string }>((resolve, reject) => {
|
||||
ffmpeg(filePath).ffprobe( (err, metadata) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
} else {
|
||||
const videoStream = metadata.streams.find(s => s.codec_type === 'video');
|
||||
if (videoStream) {
|
||||
console.log(`视频尺寸: ${videoStream.width}x${videoStream.height}`);
|
||||
} else {
|
||||
console.log('未找到视频流信息。');
|
||||
}
|
||||
resolve({
|
||||
width: videoStream.width, height: videoStream.height,
|
||||
time: parseInt(videoStream.duration),
|
||||
format: metadata.format.format_name,
|
||||
size,
|
||||
filePath
|
||||
});
|
||||
}
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
export async function encodeMp4(filePath: string) {
|
||||
let videoInfo = await getVideoInfo(filePath);
|
||||
log("视频信息", videoInfo)
|
||||
if (videoInfo.format.indexOf("mp4") === -1) {
|
||||
log("视频需要转换为MP4格式", filePath)
|
||||
// 转成mp4
|
||||
const newPath: string = await new Promise<string>((resolve, reject) => {
|
||||
const newPath = filePath + ".mp4"
|
||||
ffmpeg(filePath)
|
||||
.toFormat('mp4')
|
||||
.on('error', (err) => {
|
||||
reject(`转换视频格式失败: ${err.message}`);
|
||||
})
|
||||
.on('end', () => {
|
||||
log('视频转换为MP4格式完成');
|
||||
resolve(newPath); // 返回转换后的文件路径
|
||||
})
|
||||
.save(newPath);
|
||||
});
|
||||
return await getVideoInfo(newPath)
|
||||
}
|
||||
return videoInfo
|
||||
}
|
||||
|
||||
export function isNull(value: any) {
|
||||
return value === undefined || value === null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export function calculateFileMD5(filePath: string): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
// 创建一个流式读取器
|
||||
const stream = fs.createReadStream(filePath);
|
||||
const hash = crypto.createHash('md5');
|
||||
|
||||
stream.on('data', (data: Buffer) => {
|
||||
// 当读取到数据时,更新哈希对象的状态
|
||||
hash.update(data);
|
||||
});
|
||||
|
||||
stream.on('end', () => {
|
||||
// 文件读取完成,计算哈希
|
||||
const md5 = hash.digest('hex');
|
||||
resolve(md5);
|
||||
});
|
||||
|
||||
stream.on('error', (err: Error) => {
|
||||
// 处理可能的读取错误
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
109
src/main/main.ts
109
src/main/main.ts
@@ -13,35 +13,29 @@ import {
|
||||
import {ob11WebsocketServer} from "../onebot11/server/ws/WebsocketServer";
|
||||
import {checkFfmpeg, DATA_DIR, getConfigUtil, log} from "../common/utils";
|
||||
import {
|
||||
friendRequests, getFriend,
|
||||
friendRequests,
|
||||
getFriend,
|
||||
getGroup,
|
||||
getGroupMember,
|
||||
groupNotifies,
|
||||
llonebotError, refreshGroupMembers,
|
||||
llonebotError,
|
||||
refreshGroupMembers,
|
||||
selfInfo
|
||||
} from "../common/data";
|
||||
import {hookNTQQApiCall, hookNTQQApiReceive, ReceiveCmd, registerReceiveHook} from "../ntqqapi/hook";
|
||||
import {OB11Constructor} from "../onebot11/constructor";
|
||||
import {NTQQApi} from "../ntqqapi/ntcall";
|
||||
import {
|
||||
ChatType,
|
||||
FriendRequestNotify,
|
||||
GroupMember,
|
||||
GroupNotifies,
|
||||
GroupNotifyTypes,
|
||||
RawMessage
|
||||
} from "../ntqqapi/types";
|
||||
import {ChatType, FriendRequestNotify, GroupNotifies, GroupNotifyTypes, RawMessage} from "../ntqqapi/types";
|
||||
import {ob11HTTPServer} from "../onebot11/server/http";
|
||||
import {OB11FriendRecallNoticeEvent} from "../onebot11/event/notice/OB11FriendRecallNoticeEvent";
|
||||
import {OB11GroupRecallNoticeEvent} from "../onebot11/event/notice/OB11GroupRecallNoticeEvent";
|
||||
import {postOB11Event} from "../onebot11/server/postOB11Event";
|
||||
import {ob11ReverseWebsockets} from "../onebot11/server/ws/ReverseWebsocket";
|
||||
import {OB11GroupAdminNoticeEvent} from "../onebot11/event/notice/OB11GroupAdminNoticeEvent";
|
||||
import {OB11GroupDecreaseEvent} from "../onebot11/event/notice/OB11GroupDecreaseEvent";
|
||||
import {OB11GroupRequestEvent} from "../onebot11/event/request/OB11GroupRequest";
|
||||
import {OB11FriendRequestEvent} from "../onebot11/event/request/OB11FriendRequest";
|
||||
import * as path from "node:path";
|
||||
import {dbUtil} from "../common/db";
|
||||
import {setConfig} from "./setConfig";
|
||||
|
||||
|
||||
let running = false;
|
||||
@@ -91,61 +85,8 @@ function onLoad() {
|
||||
const config = getConfigUtil().getConfig()
|
||||
return config;
|
||||
})
|
||||
ipcMain.on(CHANNEL_SET_CONFIG, (event, arg: Config) => {
|
||||
let oldConfig = getConfigUtil().getConfig();
|
||||
getConfigUtil().setConfig(arg)
|
||||
if (arg.ob11.httpPort != oldConfig.ob11.httpPort && arg.ob11.enableHttp) {
|
||||
ob11HTTPServer.restart(arg.ob11.httpPort);
|
||||
}
|
||||
// 判断是否启用或关闭HTTP服务
|
||||
if (!arg.ob11.enableHttp) {
|
||||
ob11HTTPServer.stop();
|
||||
} else {
|
||||
ob11HTTPServer.start(arg.ob11.httpPort);
|
||||
}
|
||||
// 正向ws端口变化,重启服务
|
||||
if (arg.ob11.wsPort != oldConfig.ob11.wsPort) {
|
||||
ob11WebsocketServer.restart(arg.ob11.wsPort);
|
||||
}
|
||||
// 判断是否启用或关闭正向ws
|
||||
if (arg.ob11.enableWs != oldConfig.ob11.enableWs) {
|
||||
if (arg.ob11.enableWs) {
|
||||
ob11WebsocketServer.start(arg.ob11.wsPort);
|
||||
} else {
|
||||
ob11WebsocketServer.stop();
|
||||
}
|
||||
}
|
||||
// 判断是否启用或关闭反向ws
|
||||
if (arg.ob11.enableWsReverse != oldConfig.ob11.enableWsReverse) {
|
||||
if (arg.ob11.enableWsReverse) {
|
||||
ob11ReverseWebsockets.start();
|
||||
} else {
|
||||
ob11ReverseWebsockets.stop();
|
||||
}
|
||||
}
|
||||
if (arg.ob11.enableWsReverse) {
|
||||
// 判断反向ws地址有变化
|
||||
if (arg.ob11.wsHosts.length != oldConfig.ob11.wsHosts.length) {
|
||||
ob11ReverseWebsockets.restart();
|
||||
} else {
|
||||
for (const newHost of arg.ob11.wsHosts) {
|
||||
if (!oldConfig.ob11.wsHosts.includes(newHost)) {
|
||||
ob11ReverseWebsockets.restart();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 检查ffmpeg
|
||||
if (arg.ffmpeg) {
|
||||
checkFfmpeg(arg.ffmpeg).then(success => {
|
||||
if (success) {
|
||||
llonebotError.ffmpegError = ''
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
ipcMain.on(CHANNEL_SET_CONFIG, (event, config: Config) => {
|
||||
setConfig(config).then();
|
||||
})
|
||||
|
||||
ipcMain.on(CHANNEL_LOG, (event, arg) => {
|
||||
@@ -155,9 +96,10 @@ function onLoad() {
|
||||
async function postReceiveMsg(msgList: RawMessage[]) {
|
||||
const {debug, reportSelfMessage} = getConfigUtil().getConfig();
|
||||
for (let message of msgList) {
|
||||
|
||||
// log("收到新消息", message.msgId, message.msgSeq)
|
||||
// if (message.senderUin !== selfInfo.uin){
|
||||
message.msgShortId = await dbUtil.addMsg(message);
|
||||
message.msgShortId = await dbUtil.addMsg(message);
|
||||
// }
|
||||
|
||||
OB11Constructor.message(message).then((msg) => {
|
||||
@@ -171,6 +113,12 @@ function onLoad() {
|
||||
postOB11Event(msg);
|
||||
// log("post msg", msg)
|
||||
}).catch(e => log("constructMessage error: ", e.stack.toString()));
|
||||
OB11Constructor.GroupEvent(message).then(groupEvent => {
|
||||
if (groupEvent) {
|
||||
// log("post group event", groupEvent);
|
||||
postOB11Event(groupEvent);
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -185,7 +133,7 @@ function onLoad() {
|
||||
registerReceiveHook<{ msgList: Array<RawMessage> }>(ReceiveCmd.UPDATE_MSG, async (payload) => {
|
||||
for (const message of payload.msgList) {
|
||||
// log("message update", message.sendStatus, message.msgId, message.msgSeq)
|
||||
if (message.recallTime != "0") {
|
||||
if (message.recallTime != "0") { //todo: 这个判断方法不太好,应该使用灰色消息元素来判断
|
||||
// 撤回消息上报
|
||||
const oriMessage = await dbUtil.getMsgByLongId(message.msgId)
|
||||
if (!oriMessage) {
|
||||
@@ -200,7 +148,7 @@ function onLoad() {
|
||||
let operatorId = message.senderUin
|
||||
for (const element of message.elements) {
|
||||
const operatorUid = element.grayTipElement?.revokeElement.operatorUid
|
||||
const operator = await getGroupMember(message.peerUin, null, operatorUid)
|
||||
const operator = await getGroupMember(message.peerUin, operatorUid)
|
||||
operatorId = operator.uin
|
||||
}
|
||||
const groupRecallEvent = new OB11GroupRecallNoticeEvent(
|
||||
@@ -251,25 +199,23 @@ function onLoad() {
|
||||
for (const notify of notifies) {
|
||||
try {
|
||||
notify.time = Date.now();
|
||||
const notifyTime = parseInt(notify.seq) / 1000
|
||||
// const notifyTime = parseInt(notify.seq) / 1000
|
||||
// log(`加群通知时间${notifyTime}`, `LLOneBot启动时间${startTime}`);
|
||||
// if (notifyTime < startTime) {
|
||||
// continue;
|
||||
// }
|
||||
let existNotify = groupNotifies[notify.seq];
|
||||
let existNotify = await dbUtil.getGroupNotify(notify.seq);
|
||||
if (existNotify) {
|
||||
if (Date.now() - existNotify.time < 3000) {
|
||||
continue
|
||||
}
|
||||
continue
|
||||
}
|
||||
log("收到群通知", notify);
|
||||
groupNotifies[notify.seq] = notify;
|
||||
await dbUtil.addGroupNotify(notify);
|
||||
// let member2: GroupMember;
|
||||
// if (notify.user2.uid) {
|
||||
// member2 = await getGroupMember(notify.group.groupCode, null, notify.user2.uid);
|
||||
// }
|
||||
if ([GroupNotifyTypes.ADMIN_SET, GroupNotifyTypes.ADMIN_UNSET].includes(notify.type)) {
|
||||
const member1 = await getGroupMember(notify.group.groupCode, null, notify.user1.uid);
|
||||
const member1 = await getGroupMember(notify.group.groupCode, notify.user1.uid);
|
||||
log("有管理员变动通知");
|
||||
refreshGroupMembers(notify.group.groupCode).then()
|
||||
let groupAdminNoticeEvent = new OB11GroupAdminNoticeEvent()
|
||||
@@ -307,8 +253,8 @@ function onLoad() {
|
||||
log("收到邀请我加群通知")
|
||||
let groupInviteEvent = new OB11GroupRequestEvent();
|
||||
groupInviteEvent.group_id = parseInt(notify.group.groupCode);
|
||||
let user_id = (await getFriend("", notify.user2.uid))?.uin
|
||||
if (!user_id){
|
||||
let user_id = (await getFriend(notify.user2.uid))?.uin
|
||||
if (!user_id) {
|
||||
user_id = (await NTQQApi.getUserDetailInfo(notify.user2.uid))?.uin
|
||||
}
|
||||
groupInviteEvent.user_id = parseInt(user_id);
|
||||
@@ -349,6 +295,7 @@ function onLoad() {
|
||||
let startTime = 0;
|
||||
|
||||
async function start() {
|
||||
log("llonebot pid", process.pid)
|
||||
startTime = Date.now();
|
||||
startReceiveHook().then();
|
||||
NTQQApi.getGroups(true).then()
|
||||
@@ -415,6 +362,10 @@ function onLoad() {
|
||||
|
||||
// 创建窗口时触发
|
||||
function onBrowserWindowCreated(window: BrowserWindow) {
|
||||
if (selfInfo.uid) {
|
||||
return
|
||||
}
|
||||
log("window create", window.webContents.getURL().toString())
|
||||
try {
|
||||
hookNTQQApiCall(window);
|
||||
hookNTQQApiReceive(window);
|
||||
|
63
src/main/setConfig.ts
Normal file
63
src/main/setConfig.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import {Config} from "../common/types";
|
||||
import {checkFfmpeg, getConfigUtil} from "../common/utils";
|
||||
import {ob11HTTPServer} from "../onebot11/server/http";
|
||||
import {ob11WebsocketServer} from "../onebot11/server/ws/WebsocketServer";
|
||||
import {ob11ReverseWebsockets} from "../onebot11/server/ws/ReverseWebsocket";
|
||||
import {llonebotError} from "../common/data";
|
||||
|
||||
export async function setConfig(config: Config) {
|
||||
let oldConfig = getConfigUtil().getConfig();
|
||||
getConfigUtil().setConfig(config)
|
||||
if (config.ob11.httpPort != oldConfig.ob11.httpPort && config.ob11.enableHttp) {
|
||||
ob11HTTPServer.restart(config.ob11.httpPort);
|
||||
}
|
||||
// 判断是否启用或关闭HTTP服务
|
||||
if (!config.ob11.enableHttp) {
|
||||
ob11HTTPServer.stop();
|
||||
} else {
|
||||
ob11HTTPServer.start(config.ob11.httpPort);
|
||||
}
|
||||
// 正向ws端口变化,重启服务
|
||||
if (config.ob11.wsPort != oldConfig.ob11.wsPort) {
|
||||
ob11WebsocketServer.restart(config.ob11.wsPort);
|
||||
}
|
||||
// 判断是否启用或关闭正向ws
|
||||
if (config.ob11.enableWs != oldConfig.ob11.enableWs) {
|
||||
if (config.ob11.enableWs) {
|
||||
ob11WebsocketServer.start(config.ob11.wsPort);
|
||||
} else {
|
||||
ob11WebsocketServer.stop();
|
||||
}
|
||||
}
|
||||
// 判断是否启用或关闭反向ws
|
||||
if (config.ob11.enableWsReverse != oldConfig.ob11.enableWsReverse) {
|
||||
if (config.ob11.enableWsReverse) {
|
||||
ob11ReverseWebsockets.start();
|
||||
} else {
|
||||
ob11ReverseWebsockets.stop();
|
||||
}
|
||||
}
|
||||
if (config.ob11.enableWsReverse) {
|
||||
// 判断反向ws地址有变化
|
||||
if (config.ob11.wsHosts.length != oldConfig.ob11.wsHosts.length) {
|
||||
ob11ReverseWebsockets.restart();
|
||||
} else {
|
||||
for (const newHost of config.ob11.wsHosts) {
|
||||
if (!oldConfig.ob11.wsHosts.includes(newHost)) {
|
||||
ob11ReverseWebsockets.restart();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 检查ffmpeg
|
||||
if (config.ffmpeg) {
|
||||
checkFfmpeg(config.ffmpeg).then(success => {
|
||||
if (success) {
|
||||
llonebotError.ffmpegError = ''
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
}
|
@@ -1,16 +1,20 @@
|
||||
import {
|
||||
AtType,
|
||||
ElementType, PicType, SendArkElement,
|
||||
ElementType,
|
||||
PicType,
|
||||
SendArkElement,
|
||||
SendFaceElement,
|
||||
SendFileElement,
|
||||
SendPicElement,
|
||||
SendPttElement,
|
||||
SendReplyElement,
|
||||
SendTextElement
|
||||
SendTextElement,
|
||||
SendVideoElement
|
||||
} from "./types";
|
||||
import {NTQQApi} from "./ntcall";
|
||||
import {encodeSilk, isGIF} from "../common/utils";
|
||||
import * as fs from "node:fs";
|
||||
import {calculateFileMD5, encodeSilk, getVideoInfo, isGIF, log, sleep} from "../common/utils";
|
||||
import {promises as fs} from "node:fs";
|
||||
import ffmpeg from "fluent-ffmpeg"
|
||||
|
||||
|
||||
export class SendMsgElementConstructor {
|
||||
@@ -57,7 +61,7 @@ export class SendMsgElementConstructor {
|
||||
|
||||
static async pic(picPath: string): Promise<SendPicElement> {
|
||||
const {md5, fileName, path, fileSize} = await NTQQApi.uploadFile(picPath, ElementType.PIC);
|
||||
if (fileSize === 0){
|
||||
if (fileSize === 0) {
|
||||
throw "文件异常,大小为0";
|
||||
}
|
||||
const imageSize = await NTQQApi.getImageSize(picPath);
|
||||
@@ -84,15 +88,9 @@ export class SendMsgElementConstructor {
|
||||
};
|
||||
}
|
||||
|
||||
static async file(filePath: string, showPreview: boolean = false, fileName: string = ""): Promise<SendFileElement> {
|
||||
let picHeight = 0;
|
||||
let picWidth = 0;
|
||||
if (showPreview) {
|
||||
picHeight = 1024;
|
||||
picWidth = 768;
|
||||
}
|
||||
static async file(filePath: string, fileName: string = ""): Promise<SendFileElement> {
|
||||
const {md5, fileName: _fileName, path, fileSize} = await NTQQApi.uploadFile(filePath, ElementType.FILE);
|
||||
if (fileSize === 0){
|
||||
if (fileSize === 0) {
|
||||
throw "文件异常,大小为0";
|
||||
}
|
||||
let element: SendFileElement = {
|
||||
@@ -102,28 +100,89 @@ export class SendMsgElementConstructor {
|
||||
fileName: fileName || _fileName,
|
||||
"filePath": path,
|
||||
"fileSize": (fileSize).toString(),
|
||||
picHeight,
|
||||
picWidth
|
||||
}
|
||||
}
|
||||
|
||||
return element;
|
||||
}
|
||||
|
||||
static video(filePath: string, fileName: string=""): Promise<SendFileElement> {
|
||||
return SendMsgElementConstructor.file(filePath, true, fileName);
|
||||
static async video(filePath: string, fileName: string = ""): Promise<SendVideoElement> {
|
||||
let {fileName: _fileName, path, fileSize, md5} = await NTQQApi.uploadFile(filePath, ElementType.VIDEO);
|
||||
if (fileSize === 0) {
|
||||
throw "文件异常,大小为0";
|
||||
}
|
||||
// const videoInfo = await encodeMp4(path);
|
||||
// path = videoInfo.filePath
|
||||
// md5 = videoInfo.md5;
|
||||
// fileSize = videoInfo.size;
|
||||
// log("上传视频", md5, path, fileSize, fileName || _fileName)
|
||||
const pathLib = require("path");
|
||||
let thumb = path.replace(`${pathLib.sep}Ori${pathLib.sep}`, `${pathLib.sep}Thumb${pathLib.sep}`)
|
||||
thumb = pathLib.dirname(thumb)
|
||||
// log("thumb 目录", thumb)
|
||||
const videoInfo = await getVideoInfo(path);
|
||||
log("视频信息", videoInfo)
|
||||
const createThumb = new Promise<string>((resolve, reject) => {
|
||||
const thumbFileName = `${md5}_0.png`
|
||||
ffmpeg(filePath)
|
||||
.on("end", () => {
|
||||
})
|
||||
.on("error", (err) => {
|
||||
reject(err);
|
||||
})
|
||||
.screenshots({
|
||||
timestamps: [0],
|
||||
filename: thumbFileName,
|
||||
folder: thumb,
|
||||
size: videoInfo.width + "x" + videoInfo.height
|
||||
}).on("end", () => {
|
||||
resolve(pathLib.join(thumb, thumbFileName));
|
||||
});
|
||||
})
|
||||
let thumbPath = new Map()
|
||||
const _thumbPath = await createThumb;
|
||||
const thumbSize = (await fs.stat(_thumbPath)).size;
|
||||
// log("生成缩略图", _thumbPath)
|
||||
thumbPath.set(0, _thumbPath)
|
||||
const thumbMd5 = await calculateFileMD5(_thumbPath);
|
||||
let element: SendVideoElement = {
|
||||
elementType: ElementType.VIDEO,
|
||||
elementId: "",
|
||||
videoElement: {
|
||||
fileName: fileName || _fileName,
|
||||
filePath: path,
|
||||
videoMd5: md5,
|
||||
thumbMd5,
|
||||
fileTime: videoInfo.time,
|
||||
thumbPath: thumbPath,
|
||||
thumbSize,
|
||||
thumbWidth: videoInfo.width,
|
||||
thumbHeight: videoInfo.height,
|
||||
fileSize: "" + fileSize,
|
||||
// fileUuid: "",
|
||||
// transferStatus: 0,
|
||||
// progress: 0,
|
||||
// invalidState: 0,
|
||||
// fileSubId: "",
|
||||
// fileBizId: null,
|
||||
// originVideoMd5: "",
|
||||
// fileFormat: 2,
|
||||
// import_rich_media_context: null,
|
||||
// sourceVideoCodecFormat: 2
|
||||
}
|
||||
}
|
||||
return element;
|
||||
}
|
||||
|
||||
static async ptt(pttPath: string): Promise<SendPttElement> {
|
||||
const {converted, path: silkPath, duration} = await encodeSilk(pttPath);
|
||||
// log("生成语音", silkPath, duration);
|
||||
const {md5, fileName, path, fileSize} = await NTQQApi.uploadFile(silkPath, ElementType.PTT);
|
||||
if (fileSize === 0){
|
||||
if (fileSize === 0) {
|
||||
throw "文件异常,大小为0";
|
||||
}
|
||||
if (converted) {
|
||||
fs.unlink(silkPath, () => {
|
||||
});
|
||||
fs.unlink(silkPath).then();
|
||||
}
|
||||
return {
|
||||
elementType: ElementType.PTT,
|
||||
|
@@ -28,6 +28,7 @@ export enum ReceiveCmd {
|
||||
FRIEND_REQUEST = "nodeIKernelBuddyListener/onBuddyReqChange",
|
||||
SELF_STATUS = 'nodeIKernelProfileListener/onSelfStatusChanged',
|
||||
CACHE_SCAN_FINISH = "nodeIKernelStorageCleanListener/onFinishScan",
|
||||
MEDIA_UPLOAD_COMPLETE = "nodeIKernelMsgListener/onRichMediaUploadComplete",
|
||||
}
|
||||
|
||||
interface NTQQApiReturnData<PayloadType = unknown> extends Array<any> {
|
||||
@@ -168,24 +169,6 @@ async function processGroupEvent(payload) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
} else if (existGroup.memberCount < group.memberCount) {
|
||||
const oldMembers = existGroup.members;
|
||||
const oldMembersSet = new Set<string>();
|
||||
for (const member of oldMembers) {
|
||||
oldMembersSet.add(member.uin);
|
||||
}
|
||||
|
||||
await sleep(200);
|
||||
const newMembers = await NTQQApi.getGroupMembers(group.groupCode);
|
||||
|
||||
group.members = newMembers;
|
||||
for (const member of newMembers) {
|
||||
if (!oldMembersSet.has(member.uin)) {
|
||||
postOB11Event(new OB11GroupIncreaseEvent(group.groupCode, parseInt(member.uin)));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -197,6 +180,7 @@ async function processGroupEvent(payload) {
|
||||
}
|
||||
}
|
||||
|
||||
// 群列表变动
|
||||
registerReceiveHook<{ groupList: Group[], updateType: number }>(ReceiveCmd.GROUPS, (payload) => {
|
||||
if (payload.updateType != 2) {
|
||||
updateGroups(payload.groupList).then();
|
||||
@@ -216,6 +200,7 @@ registerReceiveHook<{ groupList: Group[], updateType: number }>(ReceiveCmd.GROUP
|
||||
}
|
||||
})
|
||||
|
||||
// 好友列表变动
|
||||
registerReceiveHook<{
|
||||
data: { categoryId: number, categroyName: string, categroyMbCount: number, buddyList: User[] }[]
|
||||
}>(ReceiveCmd.FRIENDS, payload => {
|
||||
@@ -232,20 +217,26 @@ registerReceiveHook<{
|
||||
}
|
||||
})
|
||||
|
||||
// 新消息
|
||||
registerReceiveHook<{ msgList: Array<RawMessage> }>(ReceiveCmd.NEW_MSG, (payload) => {
|
||||
const {autoDeleteFile} = getConfigUtil().getConfig();
|
||||
if (!autoDeleteFile) {
|
||||
return
|
||||
}
|
||||
for (const message of payload.msgList) {
|
||||
// log("收到新消息,push到历史记录", message.msgId)
|
||||
// dbUtil.addMsg(message).then()
|
||||
// 清理文件
|
||||
if (!autoDeleteFile) {
|
||||
continue
|
||||
}
|
||||
|
||||
for (const msgElement of message.elements) {
|
||||
setTimeout(() => {
|
||||
const picPath = msgElement.picElement?.sourcePath
|
||||
const picThumbPath = [...msgElement.picElement?.thumbPath.values()]
|
||||
const pttPath = msgElement.pttElement?.filePath
|
||||
const pathList = [picPath, pttPath]
|
||||
const filePath = msgElement.fileElement?.filePath
|
||||
const videoPath = msgElement.videoElement?.filePath
|
||||
const videoThumbPath: string[] = [...msgElement.videoElement?.thumbPath.values()]
|
||||
const pathList = [picPath, ...picThumbPath, pttPath, filePath, videoPath, ...videoThumbPath]
|
||||
if (msgElement.picElement) {
|
||||
pathList.push(...Object.values(msgElement.picElement.thumbPath))
|
||||
}
|
||||
@@ -253,6 +244,7 @@ registerReceiveHook<{ msgList: Array<RawMessage> }>(ReceiveCmd.NEW_MSG, (payload
|
||||
if (aioOpGrayTipElement){
|
||||
tempGroupCodeMap[aioOpGrayTipElement.peerUid] = aioOpGrayTipElement.fromGrpCodeOfTmpChat;
|
||||
}
|
||||
|
||||
// log("需要清理的文件", pathList);
|
||||
for (const path of pathList) {
|
||||
if (path) {
|
||||
@@ -261,7 +253,7 @@ registerReceiveHook<{ msgList: Array<RawMessage> }>(ReceiveCmd.NEW_MSG, (payload
|
||||
});
|
||||
}
|
||||
}
|
||||
}, 60 * 1000)
|
||||
}, getConfigUtil().getConfig().autoDeleteFileSecond * 1000)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
@@ -1,4 +1,4 @@
|
||||
import {ipcMain} from "electron";
|
||||
import {BrowserWindow, ipcMain} from "electron";
|
||||
import {hookApiCallbacks, ReceiveCmd, registerReceiveHook, removeReceiveHook} from "./hook";
|
||||
import {log, sleep} from "../common/utils";
|
||||
import {
|
||||
@@ -21,7 +21,7 @@ import {
|
||||
CacheFileList, CacheFileListItem, CacheFileType,
|
||||
} from "./types";
|
||||
import * as fs from "fs";
|
||||
import {friendRequests, groupNotifies, selfInfo, uidMaps} from "../common/data";
|
||||
import {friendRequests, selfInfo, uidMaps} from "../common/data";
|
||||
import {v4 as uuidv4} from "uuid"
|
||||
import path from "path";
|
||||
import {dbUtil} from "../common/db";
|
||||
@@ -42,12 +42,14 @@ export enum NTQQApiClass {
|
||||
NT_API = "ns-ntApi",
|
||||
FS_API = "ns-FsApi",
|
||||
OS_API = "ns-OsApi",
|
||||
WINDOW_API = "ns-WindowApi",
|
||||
HOTUPDATE_API = "ns-HotUpdateApi",
|
||||
BUSINESS_API = "ns-BusinessApi",
|
||||
GLOBAL_DATA = "ns-GlobalDataApi"
|
||||
}
|
||||
|
||||
export enum NTQQApiMethod {
|
||||
SET_HEADER = "nodeIKernelProfileService/setHeader",
|
||||
LIKE_FRIEND = "nodeIKernelProfileLikeService/setBuddyProfileLike",
|
||||
SELF_INFO = "fetchAuthData",
|
||||
FRIENDS = "nodeIKernelBuddyService/getBuddyList",
|
||||
@@ -79,6 +81,7 @@ export enum NTQQApiMethod {
|
||||
SET_MEMBER_ROLE = "nodeIKernelGroupService/modifyMemberRole",
|
||||
PUBLISH_GROUP_BULLETIN = "nodeIKernelGroupService/publishGroupBulletinBulletin",
|
||||
SET_GROUP_NAME = "nodeIKernelGroupService/modifyGroupName",
|
||||
SET_GROUP_TITLE = "nodeIKernelGroupService/modifyMemberSpecialTitle",
|
||||
|
||||
CACHE_SET_SILENCE = 'nodeIKernelStorageCleanService/setSilentScan',
|
||||
CACHE_ADD_SCANNED_PATH = 'nodeIKernelStorageCleanService/addCacheScanedPaths',
|
||||
@@ -91,6 +94,10 @@ export enum NTQQApiMethod {
|
||||
CACHE_CHAT_GET = 'nodeIKernelStorageCleanService/getChatCacheInfo',
|
||||
CACHE_FILE_GET = 'nodeIKernelStorageCleanService/getFileCacheInfo',
|
||||
CACHE_CHAT_CLEAR = 'nodeIKernelStorageCleanService/clearChatCacheInfo',
|
||||
|
||||
OPEN_EXTRA_WINDOW = 'openExternalWindow',
|
||||
|
||||
SET_QQ_AVATAR = 'nodeIKernelProfileService/setHeader'
|
||||
}
|
||||
|
||||
enum NTQQApiChannel {
|
||||
@@ -201,7 +208,13 @@ interface GeneralCallResult {
|
||||
|
||||
|
||||
export class NTQQApi {
|
||||
// static likeFriend = defineNTQQApi<void>(NTQQApiChannel.IPC_UP_2, NTQQApiClass.NT_API, NTQQApiMethod.LIKE_FRIEND)
|
||||
static async setHeader(path: string) {
|
||||
return await callNTQQApi<GeneralCallResult>({
|
||||
methodName: NTQQApiMethod.SET_HEADER,
|
||||
args: [path]
|
||||
})
|
||||
}
|
||||
|
||||
static async likeFriend(uid: string, count = 1) {
|
||||
return await callNTQQApi<GeneralCallResult>({
|
||||
methodName: NTQQApiMethod.LIKE_FRIEND,
|
||||
@@ -249,7 +262,11 @@ export class NTQQApi {
|
||||
null
|
||||
]
|
||||
})
|
||||
return result.info
|
||||
const info = result.info
|
||||
if (info?.uin) {
|
||||
uidMaps[info.uid] = info.uin
|
||||
}
|
||||
return info
|
||||
}
|
||||
|
||||
static async getFriends(forced = false) {
|
||||
@@ -475,8 +492,7 @@ export class NTQQApi {
|
||||
if ((await dbUtil.getMsgByLongId(sentMessage.msgId)).sendStatus == 2) {
|
||||
return sentMessage
|
||||
}
|
||||
}
|
||||
else{
|
||||
} else {
|
||||
return sentMessage
|
||||
}
|
||||
// log(`给${peerUid}发送消息成功`)
|
||||
@@ -503,7 +519,7 @@ export class NTQQApi {
|
||||
static async forwardMsg(srcPeer: Peer, destPeer: Peer, msgIds: string[]) {
|
||||
return await callNTQQApi<GeneralCallResult>({
|
||||
methodName: NTQQApiMethod.FORWARD_MSG,
|
||||
args:[
|
||||
args: [
|
||||
{
|
||||
msgIds: msgIds,
|
||||
srcContact: srcPeer,
|
||||
@@ -518,6 +534,7 @@ export class NTQQApi {
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
static async multiForwardMsg(srcPeer: Peer, destPeer: Peer, msgIds: string[]) {
|
||||
const msgInfos = msgIds.map(id => {
|
||||
return {msgId: id, senderShowName: selfInfo.nick}
|
||||
@@ -589,12 +606,35 @@ export class NTQQApi {
|
||||
});
|
||||
}
|
||||
|
||||
static async getGroupIgnoreNotifies() {
|
||||
await NTQQApi.getGroupNotifies();
|
||||
const result = callNTQQApi<GroupNotifies>({
|
||||
className: NTQQApiClass.WINDOW_API,
|
||||
methodName: NTQQApiMethod.OPEN_EXTRA_WINDOW,
|
||||
cbCmd: ReceiveCmd.GROUP_NOTIFY,
|
||||
afterFirstCmd: false,
|
||||
args: [
|
||||
"GroupNotifyFilterWindow"
|
||||
]
|
||||
})
|
||||
// 关闭窗口
|
||||
setTimeout(() => {
|
||||
for (const w of BrowserWindow.getAllWindows()) {
|
||||
// log("close window", w.webContents.getURL())
|
||||
if (w.webContents.getURL().indexOf("#/notify-filter/") != -1) {
|
||||
w.close();
|
||||
}
|
||||
}
|
||||
}, 2000);
|
||||
return result;
|
||||
}
|
||||
|
||||
static async handleGroupRequest(seq: string, operateType: GroupRequestOperateTypes, reason?: string) {
|
||||
const notify: GroupNotify = groupNotifies[seq];
|
||||
const notify: GroupNotify = await dbUtil.getGroupNotify(seq)
|
||||
if (!notify) {
|
||||
throw `${seq}对应的加群通知不存在`
|
||||
}
|
||||
delete groupNotifies[seq];
|
||||
// delete groupNotifies[seq];
|
||||
return await callNTQQApi<GeneralCallResult>({
|
||||
methodName: NTQQApiMethod.HANDLE_GROUP_REQUEST,
|
||||
args: [
|
||||
@@ -727,6 +767,29 @@ export class NTQQApi {
|
||||
})
|
||||
}
|
||||
|
||||
static async call(className: NTQQApiClass, cmdName: string, args: any[],) {
|
||||
return await callNTQQApi<GeneralCallResult>({
|
||||
className,
|
||||
methodName: cmdName,
|
||||
args: [
|
||||
...args,
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
static async setGroupTitle(groupQQ: string, uid: string, title: string) {
|
||||
return await callNTQQApi<GeneralCallResult>({
|
||||
methodName: NTQQApiMethod.SET_GROUP_TITLE,
|
||||
args: [
|
||||
{
|
||||
groupCode: groupQQ,
|
||||
uid,
|
||||
title
|
||||
}, null
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
static publishGroupBulletin(groupQQ: string, title: string, content: string) {
|
||||
|
||||
}
|
||||
@@ -785,7 +848,7 @@ export class NTQQApi {
|
||||
});
|
||||
}
|
||||
|
||||
static clearCache(cacheKeys: Array<string> = [ 'tmp', 'hotUpdate' ]) {
|
||||
static clearCache(cacheKeys: Array<string> = ['tmp', 'hotUpdate']) {
|
||||
return callNTQQApi<any>({ // TODO: 目前还不知道真正的返回值是什么
|
||||
methodName: NTQQApiMethod.CACHE_CLEAR,
|
||||
args: [{
|
||||
@@ -805,12 +868,12 @@ export class NTQQApi {
|
||||
pageIndex
|
||||
}, null]
|
||||
}).then(list => res(list))
|
||||
.catch(e => rej(e));
|
||||
.catch(e => rej(e));
|
||||
});
|
||||
}
|
||||
|
||||
static getFileCacheInfo(fileType: CacheFileType, pageSize: number = 1000, lastRecord?: CacheFileListItem) {
|
||||
const _lastRecord = lastRecord ? lastRecord : { fileType: fileType };
|
||||
const _lastRecord = lastRecord ? lastRecord : {fileType: fileType};
|
||||
|
||||
return callNTQQApi<CacheFileList>({
|
||||
methodName: NTQQApiMethod.CACHE_FILE_GET,
|
||||
@@ -833,4 +896,14 @@ export class NTQQApi {
|
||||
}, null]
|
||||
});
|
||||
}
|
||||
|
||||
static async setQQAvatar(filePath: string) {
|
||||
return await callNTQQApi<GeneralCallResult>({
|
||||
methodName: NTQQApiMethod.SET_QQ_AVATAR,
|
||||
args: [{
|
||||
path:filePath
|
||||
}, null],
|
||||
timeoutSecond: 10 // 10秒不一定够
|
||||
});
|
||||
}
|
||||
}
|
@@ -71,6 +71,7 @@ export enum ElementType {
|
||||
PIC = 2,
|
||||
FILE = 3,
|
||||
PTT = 4,
|
||||
VIDEO = 5,
|
||||
FACE = 6,
|
||||
REPLY = 7,
|
||||
ARK = 10,
|
||||
@@ -112,6 +113,7 @@ export enum PicType {
|
||||
gif = 2000,
|
||||
jpg = 1000
|
||||
}
|
||||
|
||||
export interface SendPicElement {
|
||||
elementType: ElementType.PIC,
|
||||
elementId: "",
|
||||
@@ -166,11 +168,16 @@ export interface FileElement {
|
||||
}
|
||||
|
||||
export interface SendFileElement {
|
||||
elementType: ElementType.FILE,
|
||||
elementType: ElementType.FILE
|
||||
elementId: "",
|
||||
fileElement: FileElement
|
||||
}
|
||||
|
||||
export interface SendVideoElement {
|
||||
elementType: ElementType.VIDEO
|
||||
elementId: "",
|
||||
videoElement: VideoElement
|
||||
}
|
||||
export interface SendArkElement {
|
||||
elementType: ElementType.ARK,
|
||||
elementId: "",
|
||||
@@ -179,7 +186,7 @@ export interface SendArkElement {
|
||||
}
|
||||
|
||||
export type SendMessageElement = SendTextElement | SendPttElement |
|
||||
SendPicElement | SendReplyElement | SendFaceElement | SendFileElement | SendArkElement
|
||||
SendPicElement | SendReplyElement | SendFaceElement | SendFileElement | SendVideoElement | SendArkElement
|
||||
|
||||
export enum AtType {
|
||||
notAt = 0,
|
||||
@@ -218,8 +225,8 @@ export interface PttElement {
|
||||
|
||||
export interface ArkElement {
|
||||
bytesData: string;
|
||||
linkInfo:null,
|
||||
subElementType:null
|
||||
linkInfo: null,
|
||||
subElementType: null
|
||||
}
|
||||
|
||||
export const IMAGE_HTTP_HOST = "https://gchat.qpic.cn"
|
||||
@@ -245,7 +252,8 @@ export interface GrayTipElement {
|
||||
operatorMemRemark?: string;
|
||||
wording: string; // 自定义的撤回提示语
|
||||
}
|
||||
aioOpGrayTipElement: TipAioOpGrayTipElement
|
||||
aioOpGrayTipElement: TipAioOpGrayTipElement,
|
||||
groupElement: TipGroupElement
|
||||
}
|
||||
|
||||
export interface FaceElement {
|
||||
@@ -256,37 +264,42 @@ export interface FaceElement {
|
||||
export interface VideoElement {
|
||||
"filePath": string,
|
||||
"fileName": string,
|
||||
"videoMd5": string,
|
||||
"thumbMd5": string
|
||||
"fileTime": 87, // second
|
||||
"thumbSize": 314235, // byte
|
||||
"fileFormat": 2, // 2表示mp4?
|
||||
"fileSize": string, // byte
|
||||
"thumbWidth": number,
|
||||
"thumbHeight": number,
|
||||
"busiType": 0, // 未知
|
||||
"subBusiType": 0, // 未知
|
||||
"thumbPath": Map<number, any>,
|
||||
"transferStatus": 0, // 未知
|
||||
"progress": 0, // 下载进度?
|
||||
"invalidState": 0, // 未知
|
||||
"fileUuid": string, // 可以用于下载链接?
|
||||
"fileSubId": "",
|
||||
"fileBizId": null,
|
||||
"originVideoMd5": "",
|
||||
"import_rich_media_context": null,
|
||||
"sourceVideoCodecFormat": 0
|
||||
"videoMd5"?: string,
|
||||
"thumbMd5"?: string
|
||||
"fileTime"?: number, // second
|
||||
"thumbSize"?: number, // byte
|
||||
"fileFormat"?: number, // 2表示mp4?
|
||||
"fileSize"?: string, // byte
|
||||
"thumbWidth"?: number,
|
||||
"thumbHeight"?: number,
|
||||
"busiType"?: 0, // 未知
|
||||
"subBusiType"?: 0, // 未知
|
||||
"thumbPath"?: Map<number, any>,
|
||||
"transferStatus"?: 0, // 未知
|
||||
"progress"?: 0, // 下载进度?
|
||||
"invalidState"?: 0, // 未知
|
||||
"fileUuid"?: string, // 可以用于下载链接?
|
||||
"fileSubId"?: "",
|
||||
"fileBizId"?: null,
|
||||
"originVideoMd5"?: "",
|
||||
"import_rich_media_context"?: null,
|
||||
"sourceVideoCodecFormat"?: number
|
||||
}
|
||||
|
||||
export interface TipAioOpGrayTipElement{
|
||||
export interface TipAioOpGrayTipElement { // 这是什么提示来着?
|
||||
operateType: number,
|
||||
peerUid: string,
|
||||
fromGrpCodeOfTmpChat: string,
|
||||
}
|
||||
|
||||
export enum TipGroupElementType {
|
||||
memberIncrease = 1,
|
||||
ban = 8
|
||||
}
|
||||
|
||||
export interface TipGroupElement {
|
||||
"type": 1, // 1是表示有人加入群, 自己加入群也会收到这个
|
||||
"role": 0,
|
||||
"type": TipGroupElementType, // 1是表示有人加入群, 自己加入群也会收到这个
|
||||
"role": 0, // 暂时不知
|
||||
"groupName": string, // 暂时获取不到
|
||||
"memberUid": string,
|
||||
"memberNick": string,
|
||||
@@ -295,7 +308,7 @@ export interface TipGroupElement {
|
||||
"adminNick": string,
|
||||
"adminRemark": string,
|
||||
"createGroup": null,
|
||||
"memberAdd": {
|
||||
"memberAdd"?: {
|
||||
"showType": 1,
|
||||
"otherAdd": null,
|
||||
"otherAddByOtherQRCode": null,
|
||||
@@ -305,7 +318,22 @@ export interface TipGroupElement {
|
||||
"otherInviteYou": null,
|
||||
"youInviteOther": null
|
||||
},
|
||||
"shutUp": null
|
||||
"shutUp"?: {
|
||||
"curTime": string,
|
||||
"duration": string, // 禁言时间,秒
|
||||
"admin": {
|
||||
"uid": string,
|
||||
"card": string,
|
||||
"name": string,
|
||||
"role": GroupMemberRole
|
||||
},
|
||||
"member": {
|
||||
"uid": string
|
||||
"card": string,
|
||||
"name": string,
|
||||
"role": GroupMemberRole
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -364,11 +392,17 @@ export interface GroupNotifies {
|
||||
notifies: GroupNotify[],
|
||||
}
|
||||
|
||||
export enum GroupNotifyStatus {
|
||||
IGNORE = 0,
|
||||
WAIT_HANDLE = 1,
|
||||
APPROVE = 2,
|
||||
REJECT = 3
|
||||
}
|
||||
export interface GroupNotify {
|
||||
time: number; // 自己添加的字段,时间戳,毫秒, 用于判断收到短时间内收到重复的notify
|
||||
seq: string, // 转成数字,再除以1000应该就是时间戳?
|
||||
seq: string, // 唯一标识符,转成数字再除以1000应该就是时间戳?
|
||||
type: GroupNotifyTypes,
|
||||
status: 0, // 未知
|
||||
status: GroupNotifyStatus, // 0是已忽略?,1是未处理,2是已同意
|
||||
group: { groupCode: string, groupName: string },
|
||||
user1: { uid: string, nickName: string }, // 被设置管理员的人
|
||||
user2: { uid: string, nickName: string }, // 操作者
|
||||
|
@@ -22,7 +22,7 @@ class BaseAction<PayloadType, ReturnDataType> {
|
||||
return OB11Response.ok(resData);
|
||||
} catch (e) {
|
||||
log("发生错误", e)
|
||||
return OB11Response.error(e.toString(), 200);
|
||||
return OB11Response.error(e?.toString() || e?.stack?.toString() || "未知错误,可能操作超时", 200);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ class BaseAction<PayloadType, ReturnDataType> {
|
||||
return OB11Response.ok(resData, echo);
|
||||
} catch (e) {
|
||||
log("发生错误", e)
|
||||
return OB11Response.error(e.toString(), 1200, echo)
|
||||
return OB11Response.error(e.stack?.toString() || e.toString(), 1200, echo)
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -8,6 +8,7 @@ import {
|
||||
ChatCacheListItemBasic,
|
||||
CacheFileType
|
||||
} from '../../ntqqapi/types';
|
||||
import {dbUtil} from "../../common/db";
|
||||
|
||||
export default class CleanCache extends BaseAction<void, void> {
|
||||
actionName = ActionName.CleanCache
|
||||
@@ -15,6 +16,7 @@ export default class CleanCache extends BaseAction<void, void> {
|
||||
protected _handle(): Promise<void> {
|
||||
return new Promise<void>(async (res, rej) => {
|
||||
try {
|
||||
// dbUtil.clearCache();
|
||||
const cacheFilePaths: string[] = [];
|
||||
|
||||
await NTQQApi.setCacheSilentScan(false);
|
||||
|
@@ -19,12 +19,14 @@ class GetMsg extends BaseAction<PayloadType, OB11Message> {
|
||||
if (!payload.message_id) {
|
||||
throw ("参数message_id不能为空")
|
||||
}
|
||||
const msg = await dbUtil.getMsgByShortId(payload.message_id)
|
||||
if (msg) {
|
||||
return await OB11Constructor.message(msg)
|
||||
} else {
|
||||
let msg = await dbUtil.getMsgByShortId(payload.message_id)
|
||||
if(!msg) {
|
||||
msg = await dbUtil.getMsgByLongId(payload.message_id.toString())
|
||||
}
|
||||
if (!msg){
|
||||
throw ("消息不存在")
|
||||
}
|
||||
return await OB11Constructor.message(msg)
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -1,4 +1,12 @@
|
||||
import {AtType, ChatType, Group, RawMessage, SendArkElement, SendMessageElement} from "../../ntqqapi/types";
|
||||
import {
|
||||
AtType,
|
||||
ChatType,
|
||||
ElementType,
|
||||
Group,
|
||||
RawMessage,
|
||||
SendArkElement,
|
||||
SendMessageElement
|
||||
} from "../../ntqqapi/types";
|
||||
import {friends, getFriend, getGroup, getGroupMember, getUidByUin, selfInfo,} from "../../common/data";
|
||||
import {
|
||||
OB11MessageCustomMusic,
|
||||
@@ -18,7 +26,6 @@ import {log, sleep} from "../../common/utils";
|
||||
import {decodeCQCode} from "../cqcode";
|
||||
import {dbUtil} from "../../common/db";
|
||||
import {ALLOW_SEND_TEMP_MSG} from "../../common/config";
|
||||
import {FileCache} from "../../common/types";
|
||||
|
||||
function checkSendMessage(sendMsgList: OB11MessageData[]) {
|
||||
function checkUri(uri: string): boolean {
|
||||
@@ -93,6 +100,7 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
|
||||
}
|
||||
|
||||
protected async _handle(payload: OB11PostSendMsg) {
|
||||
|
||||
const peer: Peer = {
|
||||
chatType: ChatType.friend,
|
||||
peerUid: ""
|
||||
@@ -157,14 +165,10 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
|
||||
}
|
||||
// log("send msg:", peer, sendElements)
|
||||
const {sendElements, deleteAfterSentFiles} = await this.createSendElements(messages, group)
|
||||
try {
|
||||
const returnMsg = await this.send(peer, sendElements, deleteAfterSentFiles)
|
||||
deleteAfterSentFiles.map(f => fs.unlink(f, () => {}));
|
||||
return {message_id: returnMsg.msgShortId}
|
||||
} catch (e) {
|
||||
log("发送消息失败", e.stack.toString())
|
||||
throw (e.toString())
|
||||
}
|
||||
const returnMsg = await this.send(peer, sendElements, deleteAfterSentFiles)
|
||||
deleteAfterSentFiles.map(f => fs.unlink(f, () => {
|
||||
}));
|
||||
return {message_id: returnMsg.msgShortId}
|
||||
}
|
||||
|
||||
protected convertMessage2List(message: OB11MessageMixType) {
|
||||
@@ -189,23 +193,58 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
|
||||
return 0
|
||||
}
|
||||
|
||||
private async cloneMsg(msg: RawMessage): Promise<RawMessage> {
|
||||
log("克隆的目标消息", msg)
|
||||
let sendElements: SendMessageElement[] = [];
|
||||
for (const ele of msg.elements) {
|
||||
sendElements.push(ele as SendMessageElement)
|
||||
// Object.keys(ele).forEach((eleKey) => {
|
||||
// if (eleKey.endsWith("Element")) {
|
||||
// }
|
||||
|
||||
}
|
||||
if (sendElements.length === 0) {
|
||||
log("需要clone的消息无法解析,将会忽略掉", msg)
|
||||
}
|
||||
log("克隆消息", sendElements)
|
||||
try {
|
||||
const nodeMsg = await NTQQApi.sendMsg({
|
||||
chatType: ChatType.friend,
|
||||
peerUid: selfInfo.uid
|
||||
}, sendElements, true);
|
||||
await sleep(500);
|
||||
return nodeMsg
|
||||
} catch (e) {
|
||||
log(e, "克隆转发消息失败,将忽略本条消息", msg);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// 返回一个合并转发的消息id
|
||||
private async handleForwardNode(destPeer: Peer, messageNodes: OB11MessageNode[], group: Group | undefined) {
|
||||
const selfPeer: Peer = {
|
||||
|
||||
const selfPeer = {
|
||||
chatType: ChatType.friend,
|
||||
peerUid: selfInfo.uid
|
||||
}
|
||||
let selfNodeMsgList: RawMessage[] = []; // 自己给自己发的消息
|
||||
let originalNodeMsgList: RawMessage[] = [];
|
||||
let sendForwardElements: SendMessageElement[] = []
|
||||
let nodeMsgIds: string[] = []
|
||||
// 先判断一遍是不是id和自定义混用
|
||||
let needClone = messageNodes.filter(node => node.data.id).length && messageNodes.filter(node => !node.data.id).length
|
||||
for (const messageNode of messageNodes) {
|
||||
// 一个node表示一个人的消息
|
||||
let nodeId = messageNode.data.id;
|
||||
// 有nodeId表示一个子转发消息卡片
|
||||
if (nodeId) {
|
||||
let nodeMsg = await dbUtil.getMsgByShortId(parseInt(nodeId));
|
||||
if (nodeMsg) {
|
||||
originalNodeMsgList.push(nodeMsg);
|
||||
if (!needClone) {
|
||||
nodeMsgIds.push(nodeMsg.msgId)
|
||||
} else {
|
||||
if (nodeMsg.peerUid !== selfInfo.uid) {
|
||||
const cloneMsg = await this.cloneMsg(nodeMsg)
|
||||
if (cloneMsg) {
|
||||
nodeMsgIds.push(cloneMsg.msgId)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 自定义的消息
|
||||
@@ -216,57 +255,68 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
|
||||
deleteAfterSentFiles
|
||||
} = await this.createSendElements(this.convertMessage2List(messageNode.data.content), group);
|
||||
log("开始生成转发节点", sendElements);
|
||||
sendForwardElements.push(...sendElements);
|
||||
const nodeMsg = await this.send(selfPeer, sendElements, deleteAfterSentFiles, true);
|
||||
selfNodeMsgList.push(nodeMsg);
|
||||
log("转发节点生成成功", nodeMsg.msgId);
|
||||
await sleep(500);
|
||||
let sendElementsSplit: SendMessageElement[][] = []
|
||||
let splitIndex = 0;
|
||||
for (const ele of sendElements) {
|
||||
if (!sendElementsSplit[splitIndex]) {
|
||||
sendElementsSplit[splitIndex] = []
|
||||
}
|
||||
|
||||
if (ele.elementType === ElementType.FILE || ele.elementType === ElementType.VIDEO) {
|
||||
if (sendElementsSplit[splitIndex].length > 0) {
|
||||
splitIndex++;
|
||||
}
|
||||
sendElementsSplit[splitIndex] = [ele]
|
||||
splitIndex++;
|
||||
} else {
|
||||
sendElementsSplit[splitIndex].push(ele)
|
||||
}
|
||||
log(sendElementsSplit)
|
||||
}
|
||||
// log("分割后的转发节点", sendElementsSplit)
|
||||
for (const eles of sendElementsSplit) {
|
||||
const nodeMsg = await this.send(selfPeer, eles, [], true);
|
||||
nodeMsgIds.push(nodeMsg.msgId)
|
||||
await sleep(500);
|
||||
log("转发节点生成成功", nodeMsg.msgId);
|
||||
}
|
||||
deleteAfterSentFiles.map(f => fs.unlink(f, () => {
|
||||
}));
|
||||
|
||||
} catch (e) {
|
||||
log("生效转发消息节点失败", e)
|
||||
log("生成转发消息节点失败", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let nodeIds: string[] = []
|
||||
// 检查是否需要克隆直接引用消息id的节点
|
||||
// 检查srcPeer是否一致,不一致则需要克隆成自己的消息, 让所有srcPeer都变成自己的,使其保持一致才能够转发
|
||||
let nodeMsgArray: Array<RawMessage> = []
|
||||
let srcPeer: Peer = null;
|
||||
let needSendSelf = false;
|
||||
if (sendForwardElements.length) {
|
||||
needSendSelf = true
|
||||
} else {
|
||||
needSendSelf = !originalNodeMsgList.every((msg, index) => msg.peerUid === originalNodeMsgList[0].peerUid && msg.recallTime.length < 2)
|
||||
for (const [index, msgId] of nodeMsgIds.entries()) {
|
||||
const nodeMsg = await dbUtil.getMsgByLongId(msgId)
|
||||
if (nodeMsg) {
|
||||
nodeMsgArray.push(nodeMsg)
|
||||
if (!srcPeer) {
|
||||
srcPeer = {chatType: nodeMsg.chatType, peerUid: nodeMsg.peerUid}
|
||||
} else if (srcPeer.peerUid !== nodeMsg.peerUid) {
|
||||
needSendSelf = true
|
||||
srcPeer = selfPeer
|
||||
}
|
||||
}
|
||||
}
|
||||
log("nodeMsgArray", nodeMsgArray);
|
||||
nodeMsgIds = nodeMsgArray.map(msg => msg.msgId);
|
||||
if (needSendSelf) {
|
||||
nodeIds = selfNodeMsgList.map(msg => msg.msgId);
|
||||
let sendElements: SendMessageElement[] = [];
|
||||
for (const originalNodeMsg of originalNodeMsgList) {
|
||||
if (originalNodeMsg.peerUid === selfInfo.uid && originalNodeMsg.recallTime.length < 2) {
|
||||
nodeIds.push(originalNodeMsg.msgId)
|
||||
} else { // 需要进行克隆
|
||||
Object.keys(originalNodeMsg.elements).forEach((eleKey) => {
|
||||
if (eleKey !== "elementId") {
|
||||
sendForwardElements.push(originalNodeMsg.elements[eleKey])
|
||||
sendElements.push(originalNodeMsg.elements[eleKey])
|
||||
}
|
||||
})
|
||||
try {
|
||||
const nodeMsg = await NTQQApi.sendMsg(selfPeer, sendElements, true);
|
||||
nodeIds.push(nodeMsg.msgId)
|
||||
log("克隆转发消息到节点")
|
||||
} catch (e) {
|
||||
log("克隆转发消息失败", e)
|
||||
log("需要克隆转发消息");
|
||||
for (const [index, msg] of nodeMsgArray.entries()) {
|
||||
if (msg.peerUid !== selfInfo.uid) {
|
||||
const cloneMsg = await this.cloneMsg(msg)
|
||||
if (cloneMsg) {
|
||||
nodeMsgIds[index] = cloneMsg.msgId
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
nodeIds = originalNodeMsgList.map(msg => msg.msgId)
|
||||
}
|
||||
|
||||
let srcPeer = selfPeer;
|
||||
if (!needSendSelf) {
|
||||
srcPeer = {
|
||||
chatType: originalNodeMsgList[0].chatType === ChatType.group ? ChatType.group : ChatType.friend,
|
||||
peerUid: originalNodeMsgList[0].peerUid
|
||||
}
|
||||
}
|
||||
// elements之间用换行符分隔
|
||||
// let _sendForwardElements: SendMessageElement[] = []
|
||||
@@ -279,7 +329,8 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
|
||||
// await sleep(500);
|
||||
// 开发转发
|
||||
try {
|
||||
return await NTQQApi.multiForwardMsg(srcPeer, destPeer, nodeIds)
|
||||
log("开发转发", nodeMsgIds)
|
||||
return await NTQQApi.multiForwardMsg(srcPeer, destPeer, nodeMsgIds)
|
||||
} catch (e) {
|
||||
log("forward failed", e)
|
||||
return null;
|
||||
@@ -302,7 +353,7 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
|
||||
}
|
||||
break;
|
||||
case OB11MessageDataType.at: {
|
||||
if (!group){
|
||||
if (!group) {
|
||||
continue
|
||||
}
|
||||
let atQQ = sendMsg.data?.qq;
|
||||
@@ -346,18 +397,19 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
|
||||
const payloadFileName = sendMsg.data?.name
|
||||
if (file) {
|
||||
const cache = await dbUtil.getFileCache(file)
|
||||
if (cache){
|
||||
if (fs.existsSync(cache.filePath)){
|
||||
if (cache) {
|
||||
if (fs.existsSync(cache.filePath)) {
|
||||
file = "file://" + cache.filePath
|
||||
}
|
||||
else if (cache.downloadFunc){
|
||||
} else if (cache.downloadFunc) {
|
||||
await cache.downloadFunc()
|
||||
file = cache.filePath;
|
||||
log("找到文件缓存", file);
|
||||
} else if (cache.url) {
|
||||
file = cache.url
|
||||
}
|
||||
log("找到文件缓存", file);
|
||||
}
|
||||
const {path, isLocal, fileName, errMsg} = (await uri2local(file))
|
||||
if (errMsg){
|
||||
if (errMsg) {
|
||||
throw errMsg
|
||||
}
|
||||
if (path) {
|
||||
@@ -372,7 +424,7 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
|
||||
}
|
||||
if (sendMsg.type === OB11MessageDataType.file) {
|
||||
log("发送文件", path, payloadFileName || fileName)
|
||||
sendElements.push(await SendMsgElementConstructor.file(path, false, payloadFileName || fileName));
|
||||
sendElements.push(await SendMsgElementConstructor.file(path, payloadFileName || fileName));
|
||||
} else if (sendMsg.type === OB11MessageDataType.video) {
|
||||
log("发送视频", path, payloadFileName || fileName)
|
||||
sendElements.push(await SendMsgElementConstructor.video(path, payloadFileName || fileName));
|
||||
|
@@ -1,6 +1,5 @@
|
||||
import BaseAction from "./BaseAction";
|
||||
import {groupNotifies} from "../../common/data";
|
||||
import {GroupNotify, GroupRequestOperateTypes} from "../../ntqqapi/types";
|
||||
import {GroupRequestOperateTypes} from "../../ntqqapi/types";
|
||||
import {NTQQApi} from "../../ntqqapi/ntcall";
|
||||
import {ActionName} from "./types";
|
||||
|
||||
@@ -17,15 +16,10 @@ export default class SetGroupAddRequest extends BaseAction<Payload, null> {
|
||||
|
||||
protected async _handle(payload: Payload): Promise<null> {
|
||||
const seq = payload.flag.toString();
|
||||
const notify: GroupNotify = groupNotifies[seq]
|
||||
try {
|
||||
await NTQQApi.handleGroupRequest(seq,
|
||||
payload.approve ? GroupRequestOperateTypes.approve : GroupRequestOperateTypes.reject,
|
||||
payload.reason
|
||||
)
|
||||
} catch (e) {
|
||||
throw e
|
||||
}
|
||||
await NTQQApi.handleGroupRequest(seq,
|
||||
payload.approve ? GroupRequestOperateTypes.approve : GroupRequestOperateTypes.reject,
|
||||
payload.reason
|
||||
)
|
||||
return null
|
||||
}
|
||||
}
|
37
src/onebot11/action/go-cqhttp/UploadGroupFile.ts
Normal file
37
src/onebot11/action/go-cqhttp/UploadGroupFile.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import BaseAction from "../BaseAction";
|
||||
import {getGroup} from "../../../common/data";
|
||||
import {ActionName} from "../types";
|
||||
import {SendMsgElementConstructor} from "../../../ntqqapi/constructor";
|
||||
import {ChatType, SendFileElement} from "../../../ntqqapi/types";
|
||||
import {NTQQApi} from "../../../ntqqapi/ntcall";
|
||||
import {uri2local} from "../../utils";
|
||||
import fs from "fs";
|
||||
|
||||
interface Payload{
|
||||
group_id: number
|
||||
file: string
|
||||
name: string
|
||||
folder: string
|
||||
}
|
||||
|
||||
export default class GoCQHTTPUploadGroupFile extends BaseAction<Payload, null> {
|
||||
actionName = ActionName.GoCQHTTP_UploadGroupFile
|
||||
|
||||
protected async _handle(payload: Payload): Promise<null> {
|
||||
const group = await getGroup(payload.group_id.toString());
|
||||
if (!group){
|
||||
throw new Error(`群组${payload.group_id}不存在`)
|
||||
}
|
||||
let file = payload.file;
|
||||
if (fs.existsSync(file)){
|
||||
file = `file://${file}`
|
||||
}
|
||||
const downloadResult = await uri2local(file);
|
||||
if (downloadResult.errMsg){
|
||||
throw new Error(downloadResult.errMsg)
|
||||
}
|
||||
let sendFileEle: SendFileElement = await SendMsgElementConstructor.file(downloadResult.path, payload.name);
|
||||
await NTQQApi.sendMsg({chatType: ChatType.group, peerUid: group.groupCode}, [sendFileEle]);
|
||||
return null
|
||||
}
|
||||
}
|
@@ -32,9 +32,18 @@ import GetImage from "./GetImage";
|
||||
import GetRecord from "./GetRecord";
|
||||
import GoCQHTTPMarkMsgAsRead from "./MarkMsgAsRead";
|
||||
import CleanCache from "./CleanCache";
|
||||
import GoCQHTTPUploadGroupFile from "./go-cqhttp/UploadGroupFile";
|
||||
import {GetConfigAction, SetConfigAction} from "./llonebot/Config";
|
||||
import GetGroupAddRequest from "./llonebot/GetGroupAddRequest";
|
||||
import SetQQAvatar from './llonebot/SetQQAvatar'
|
||||
|
||||
export const actionHandlers = [
|
||||
new Debug(),
|
||||
new GetConfigAction(),
|
||||
new SetConfigAction(),
|
||||
new GetGroupAddRequest(),
|
||||
new SetQQAvatar(),
|
||||
// onebot11
|
||||
new SendLike(),
|
||||
new GetMsg(),
|
||||
new GetLoginInfo(),
|
||||
@@ -65,6 +74,7 @@ export const actionHandlers = [
|
||||
new GoCQHTTPGetStrangerInfo(),
|
||||
new GetGuildList(),
|
||||
new GoCQHTTPMarkMsgAsRead(),
|
||||
new GoCQHTTPUploadGroupFile(),
|
||||
|
||||
]
|
||||
|
||||
|
20
src/onebot11/action/llonebot/Config.ts
Normal file
20
src/onebot11/action/llonebot/Config.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import BaseAction from "../BaseAction";
|
||||
import {Config} from "../../../common/types";
|
||||
import {getConfigUtil} from "../../../common/utils";
|
||||
import {ActionName} from "../types";
|
||||
import {setConfig} from "../../../main/setConfig";
|
||||
|
||||
|
||||
export class GetConfigAction extends BaseAction<null, Config> {
|
||||
actionName = ActionName.GetConfig
|
||||
protected async _handle(payload: null): Promise<Config> {
|
||||
return getConfigUtil().getConfig()
|
||||
}
|
||||
}
|
||||
|
||||
export class SetConfigAction extends BaseAction<Config, void> {
|
||||
actionName = ActionName.SetConfig
|
||||
protected async _handle(payload: Config): Promise<void> {
|
||||
setConfig(payload).then();
|
||||
}
|
||||
}
|
32
src/onebot11/action/llonebot/GetGroupAddRequest.ts
Normal file
32
src/onebot11/action/llonebot/GetGroupAddRequest.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import {GroupNotify, GroupNotifyStatus} from "../../../ntqqapi/types";
|
||||
import BaseAction from "../BaseAction";
|
||||
import {ActionName} from "../types";
|
||||
import {NTQQApi} from "../../../ntqqapi/ntcall";
|
||||
import {uidMaps} from "../../../common/data";
|
||||
import {log} from "../../../common/utils";
|
||||
|
||||
interface OB11GroupRequestNotify {
|
||||
group_id: number,
|
||||
user_id: number,
|
||||
flag: string
|
||||
}
|
||||
|
||||
export default class GetGroupAddRequest extends BaseAction<null, OB11GroupRequestNotify[]> {
|
||||
actionName = ActionName.GetGroupIgnoreAddRequest
|
||||
|
||||
protected async _handle(payload: null): Promise<OB11GroupRequestNotify[]> {
|
||||
const data = await NTQQApi.getGroupIgnoreNotifies()
|
||||
log(data);
|
||||
let notifies: GroupNotify[] = data.notifies.filter(notify => notify.status === GroupNotifyStatus.WAIT_HANDLE);
|
||||
let returnData: OB11GroupRequestNotify[] = []
|
||||
for (const notify of notifies) {
|
||||
const uin = uidMaps[notify.user1.uid] || (await NTQQApi.getUserDetailInfo(notify.user1.uid))?.uin
|
||||
returnData.push({
|
||||
group_id: parseInt(notify.group.groupCode),
|
||||
user_id: parseInt(uin),
|
||||
flag: notify.seq
|
||||
})
|
||||
}
|
||||
return returnData;
|
||||
}
|
||||
}
|
44
src/onebot11/action/llonebot/SetQQAvatar.ts
Normal file
44
src/onebot11/action/llonebot/SetQQAvatar.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import BaseAction from "../BaseAction";
|
||||
import {NTQQApi} from "../../../ntqqapi/ntcall";
|
||||
import {ActionName} from "../types";
|
||||
import { uri2local } from "../../utils";
|
||||
import * as fs from "node:fs";
|
||||
import { checkFileReceived } from "../../../common/utils";
|
||||
// import { log } from "../../../common/utils";
|
||||
|
||||
interface Payload {
|
||||
file: string
|
||||
}
|
||||
|
||||
export default class SetAvatar extends BaseAction<Payload, null> {
|
||||
actionName = ActionName.SetQQAvatar
|
||||
|
||||
protected async _handle(payload: Payload): Promise<null> {
|
||||
const {path, isLocal, errMsg} = (await uri2local(payload.file))
|
||||
if (errMsg){
|
||||
throw `头像${payload.file}设置失败,file字段可能格式不正确`
|
||||
}
|
||||
if (path) {
|
||||
await checkFileReceived(path, 5000); // 文件不存在QQ会崩溃,需要提前判断
|
||||
const ret = await NTQQApi.setQQAvatar(path)
|
||||
if (!isLocal){
|
||||
fs.unlink(path, () => {})
|
||||
}
|
||||
if (!ret) {
|
||||
throw `头像${payload.file}设置失败,api无返回`
|
||||
}
|
||||
// log(`头像设置返回:${JSON.stringify(ret)}`)
|
||||
if (ret['result'] == 1004022) {
|
||||
throw `头像${payload.file}设置失败,文件可能不是图片格式`
|
||||
} else if(ret['result'] != 0) {
|
||||
throw `头像${payload.file}设置失败,未知的错误,${ret['result']}:${ret['errMsg']}`
|
||||
}
|
||||
} else {
|
||||
if (!isLocal){
|
||||
fs.unlink(path, () => {})
|
||||
}
|
||||
throw `头像${payload.file}设置失败,无法获取头像,文件可能不存在`
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
@@ -14,6 +14,10 @@ export interface InvalidCheckResult {
|
||||
}
|
||||
|
||||
export enum ActionName {
|
||||
GetGroupIgnoreAddRequest = "get_group_ignore_add_request",
|
||||
SetQQAvatar = "set_qq_avatar",
|
||||
GetConfig = "get_config",
|
||||
SetConfig = "set_config",
|
||||
Debug = "llonebot_debug",
|
||||
SendLike = "send_like",
|
||||
GetLoginInfo = "get_login_info",
|
||||
@@ -49,4 +53,5 @@ export enum ActionName {
|
||||
GoCQHTTP_GetStrangerInfo = "get_stranger_info",
|
||||
GetGuildList = "get_guild_list",
|
||||
GoCQHTTP_MarkMsgAsRead = "mark_msg_as_read",
|
||||
GoCQHTTP_UploadGroupFile = "upload_group_file",
|
||||
}
|
@@ -8,13 +8,27 @@ import {
|
||||
OB11User,
|
||||
OB11UserSex
|
||||
} from "./types";
|
||||
import {AtType, ChatType, Group, GroupMember, IMAGE_HTTP_HOST, RawMessage, SelfInfo, User} from '../ntqqapi/types';
|
||||
import {getFriend, getGroupMember, selfInfo, tempGroupCodeMap} from '../common/data';
|
||||
import {getConfigUtil, log} from "../common/utils";
|
||||
import {
|
||||
AtType,
|
||||
ChatType,
|
||||
Group,
|
||||
GroupMember,
|
||||
IMAGE_HTTP_HOST,
|
||||
RawMessage,
|
||||
SelfInfo,
|
||||
TipGroupElementType,
|
||||
User
|
||||
} from '../ntqqapi/types';
|
||||
import {getFriend, getGroup, getGroupMember, selfInfo, tempGroupCodeMap} from '../common/data';
|
||||
import {getConfigUtil, log, sleep} from "../common/utils";
|
||||
import {NTQQApi} from "../ntqqapi/ntcall";
|
||||
import {EventType} from "./event/OB11BaseEvent";
|
||||
import {encodeCQCode} from "./cqcode";
|
||||
import {dbUtil} from "../common/db";
|
||||
import {OB11GroupIncreaseEvent} from "./event/notice/OB11GroupIncreaseEvent";
|
||||
import {OB11GroupBanEvent} from "./event/notice/OB11GroupBanEvent";
|
||||
import {OB11GroupUploadNoticeEvent} from "./event/notice/OB11GroupUploadNoticeEvent";
|
||||
import {OB11GroupNoticeEvent} from "./event/notice/OB11GroupNoticeEvent";
|
||||
|
||||
|
||||
export class OB11Constructor {
|
||||
@@ -77,7 +91,7 @@ export class OB11Constructor {
|
||||
let atUid = element.textElement.atNtUid
|
||||
let atQQ = element.textElement.atUid
|
||||
if (!atQQ || atQQ === "0") {
|
||||
const atMember = await getGroupMember(msg.peerUin, null, atUid)
|
||||
const atMember = await getGroupMember(msg.peerUin, atUid)
|
||||
if (atMember) {
|
||||
atQQ = atMember.uin
|
||||
}
|
||||
@@ -97,7 +111,7 @@ export class OB11Constructor {
|
||||
} else if (element.replyElement) {
|
||||
message_data["type"] = "reply"
|
||||
// log("收到回复消息", element.replyElement.replayMsgSeq)
|
||||
try{
|
||||
try {
|
||||
const replyMsg = await dbUtil.getMsgBySeqId(element.replyElement.replayMsgSeq)
|
||||
// log("找到回复消息", replyMsg.msgShortId, replyMsg.msgId)
|
||||
if (replyMsg) {
|
||||
@@ -105,7 +119,7 @@ export class OB11Constructor {
|
||||
} else {
|
||||
continue
|
||||
}
|
||||
}catch (e) {
|
||||
} catch (e) {
|
||||
log("获取不到引用的消息", e.stack, element.replyElement.replayMsgSeq)
|
||||
}
|
||||
|
||||
@@ -116,10 +130,9 @@ export class OB11Constructor {
|
||||
// message_data["data"]["path"] = element.picElement.sourcePath
|
||||
const url = element.picElement.originImageUrl
|
||||
const fileMd5 = element.picElement.md5HexStr
|
||||
if (url){
|
||||
if (url) {
|
||||
message_data["data"]["url"] = IMAGE_HTTP_HOST + url
|
||||
}
|
||||
else if (fileMd5 && element.picElement.fileUuid.indexOf("_") === -1){ // fileuuid有下划线的是Linux发送的,这个url是另外的格式,目前尚未得知如何组装
|
||||
} else if (fileMd5 && element.picElement.fileUuid.indexOf("_") === -1) { // fileuuid有下划线的是Linux发送的,这个url是另外的格式,目前尚未得知如何组装
|
||||
message_data["data"]["url"] = `${IMAGE_HTTP_HOST}/gchatpic_new/0/0-0-${fileMd5.toUpperCase()}/0`
|
||||
}
|
||||
// message_data["data"]["file_id"] = element.picElement.fileUuid
|
||||
@@ -193,7 +206,10 @@ export class OB11Constructor {
|
||||
message_data["type"] = OB11MessageDataType.face;
|
||||
message_data["data"]["id"] = element.faceElement.faceIndex.toString();
|
||||
}
|
||||
|
||||
// todo: 解析入群grayTipElement
|
||||
else if (element.grayTipElement?.aioOpGrayTipElement) {
|
||||
log("收到 group gray tip 消息", element.grayTipElement.aioOpGrayTipElement)
|
||||
}
|
||||
// if (message_data.data.file) {
|
||||
// let filePath: string = message_data.data.file;
|
||||
// if (!enableLocalFile2Url) {
|
||||
@@ -230,6 +246,60 @@ export class OB11Constructor {
|
||||
return resMsg;
|
||||
}
|
||||
|
||||
static async GroupEvent(msg: RawMessage): Promise<OB11GroupNoticeEvent> {
|
||||
if (msg.chatType !== ChatType.group) {
|
||||
return;
|
||||
}
|
||||
for (let element of msg.elements) {
|
||||
const groupElement = element.grayTipElement?.groupElement
|
||||
if (groupElement) {
|
||||
// log("收到群提示消息", groupElement)
|
||||
if (groupElement.type == TipGroupElementType.memberIncrease) {
|
||||
log("收到群成员增加消息", groupElement)
|
||||
await sleep(1000);
|
||||
const member = await getGroupMember(msg.peerUid, groupElement.memberUid);
|
||||
let memberUin = member?.uin;
|
||||
if (!memberUin) {
|
||||
memberUin = (await NTQQApi.getUserDetailInfo(groupElement.memberUid)).uin
|
||||
}
|
||||
// log("获取新群成员QQ", memberUin)
|
||||
const adminMember = await getGroupMember(msg.peerUid, groupElement.adminUid);
|
||||
// log("获取同意新成员入群的管理员", adminMember)
|
||||
if (memberUin) {
|
||||
const operatorUin = adminMember?.uin || memberUin
|
||||
let event = new OB11GroupIncreaseEvent(parseInt(msg.peerUid), parseInt(memberUin), parseInt(operatorUin));
|
||||
// log("构造群增加事件", event)
|
||||
return event;
|
||||
}
|
||||
}
|
||||
else if (groupElement.type === TipGroupElementType.ban) {
|
||||
log("收到群群员禁言提示", groupElement)
|
||||
const memberUid = groupElement.shutUp.member.uid
|
||||
const adminUid = groupElement.shutUp.admin.uid
|
||||
let memberUin: string = ""
|
||||
let duration = parseInt(groupElement.shutUp.duration)
|
||||
let sub_type: "ban" | "lift_ban" = duration > 0 ? "ban" : "lift_ban"
|
||||
if (memberUid){
|
||||
memberUin = (await getGroupMember(msg.peerUid, memberUid))?.uin || (await NTQQApi.getUserDetailInfo(memberUid))?.uin
|
||||
}
|
||||
else {
|
||||
memberUin = "0"; // 0表示全员禁言
|
||||
if (duration > 0) {
|
||||
duration = -1
|
||||
}
|
||||
}
|
||||
const adminUin = (await getGroupMember(msg.peerUid, adminUid))?.uin || (await NTQQApi.getUserDetailInfo(adminUid))?.uin
|
||||
if (memberUin && adminUin) {
|
||||
return new OB11GroupBanEvent(parseInt(msg.peerUid), parseInt(memberUin), parseInt(adminUin), duration, sub_type);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (element.fileElement){
|
||||
return new OB11GroupUploadNoticeEvent(parseInt(msg.peerUid), parseInt(msg.senderUin), {id: element.fileElement.fileName, name: element.fileElement.fileName, size: parseInt(element.fileElement.fileSize)})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static friend(friend: User): OB11User {
|
||||
return {
|
||||
user_id: parseInt(friend.uin),
|
||||
|
17
src/onebot11/event/notice/OB11GroupBanEvent.ts
Normal file
17
src/onebot11/event/notice/OB11GroupBanEvent.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import {OB11GroupNoticeEvent} from "./OB11GroupNoticeEvent";
|
||||
|
||||
export class OB11GroupBanEvent extends OB11GroupNoticeEvent {
|
||||
notice_type = "group_ban";
|
||||
operator_id: number;
|
||||
duration: number;
|
||||
sub_type: "ban" | "lift_ban";
|
||||
|
||||
constructor(groupId: number, userId: number, operatorId: number, duration: number, sub_type: "ban" | "lift_ban") {
|
||||
super();
|
||||
this.group_id = groupId;
|
||||
this.operator_id = operatorId;
|
||||
this.user_id = userId;
|
||||
this.duration = duration;
|
||||
this.sub_type = sub_type;
|
||||
}
|
||||
}
|
@@ -5,10 +5,10 @@ export class OB11GroupIncreaseEvent extends OB11GroupNoticeEvent {
|
||||
sub_type = "approve"; // TODO: 实现其他几种子类型的识别 ("approve" | "invite")
|
||||
operator_id: number;
|
||||
|
||||
constructor(groupId: number, userId: number) {
|
||||
constructor(groupId: number, userId: number, operatorId: number) {
|
||||
super();
|
||||
this.group_id = groupId;
|
||||
this.operator_id = userId; // 实际上不应该这么实现,但是现在还没有办法识别用户是被邀请的,还是主动加入的
|
||||
this.operator_id = operatorId;
|
||||
this.user_id = userId;
|
||||
}
|
||||
}
|
||||
|
19
src/onebot11/event/notice/OB11GroupUploadNoticeEvent.ts
Normal file
19
src/onebot11/event/notice/OB11GroupUploadNoticeEvent.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import {OB11GroupNoticeEvent} from "./OB11GroupNoticeEvent";
|
||||
|
||||
export interface GroupUploadFile{
|
||||
id: string,
|
||||
name: string,
|
||||
size: number
|
||||
}
|
||||
|
||||
export class OB11GroupUploadNoticeEvent extends OB11GroupNoticeEvent {
|
||||
notice_type = "group_upload"
|
||||
file: GroupUploadFile
|
||||
|
||||
constructor(groupId: number, userId: number, file: GroupUploadFile) {
|
||||
super();
|
||||
this.group_id = groupId;
|
||||
this.user_id = userId;
|
||||
this.file = file
|
||||
}
|
||||
}
|
@@ -20,8 +20,10 @@ class OB11HTTPServer extends HttpServerBase {
|
||||
|
||||
export const ob11HTTPServer = new OB11HTTPServer();
|
||||
|
||||
for (const action of actionHandlers) {
|
||||
for (const method of ["post", "get"]) {
|
||||
ob11HTTPServer.registerRouter(method, action.actionName, (res, payload) => action.handle(payload))
|
||||
setTimeout(() => {
|
||||
for (const action of actionHandlers) {
|
||||
for (const method of ["post", "get"]) {
|
||||
ob11HTTPServer.registerRouter(method, action.actionName, (res, payload) => action.handle(payload))
|
||||
}
|
||||
}
|
||||
}
|
||||
}, 0)
|
@@ -6,12 +6,16 @@ import {dbUtil} from "../common/db";
|
||||
|
||||
const fs = require("fs").promises;
|
||||
|
||||
export async function uri2local(uri: string, fileName: string = null) {
|
||||
if (!fileName) {
|
||||
fileName = uuidv4();
|
||||
}
|
||||
let filePath = path.join(DATA_DIR, fileName)
|
||||
let url = new URL(uri);
|
||||
type Uri2LocalRes = {
|
||||
success: boolean,
|
||||
errMsg: string,
|
||||
fileName: string,
|
||||
ext: string,
|
||||
path: string,
|
||||
isLocal: boolean
|
||||
}
|
||||
|
||||
export async function uri2local(uri: string, fileName: string = null) : Promise<Uri2LocalRes>{
|
||||
let res = {
|
||||
success: false,
|
||||
errMsg: "",
|
||||
@@ -20,6 +24,19 @@ export async function uri2local(uri: string, fileName: string = null) {
|
||||
path: "",
|
||||
isLocal: false
|
||||
}
|
||||
if (!fileName) {
|
||||
fileName = uuidv4();
|
||||
}
|
||||
let filePath = path.join(DATA_DIR, fileName)
|
||||
let url = null;
|
||||
try{
|
||||
url = new URL(uri);
|
||||
}catch (e) {
|
||||
res.errMsg = `uri ${uri} 解析失败,` + e.toString() + ` 可能${uri}不存在`
|
||||
return res
|
||||
}
|
||||
|
||||
// log("uri protocol", url.protocol, uri);
|
||||
if (url.protocol == "base64:") {
|
||||
// base64转成文件
|
||||
let base64Data = uri.split("base64://")[1]
|
||||
|
@@ -90,7 +90,7 @@ async function onSettingWindowCreated(view: Element) {
|
||||
], 'ob11.messagePostFormat', config.ob11.messagePostFormat),
|
||||
),
|
||||
SettingItem(
|
||||
'ffmpeg 路径', `<span id="config-ffmpeg-path-text">${!isEmpty(config.ffmpeg) ? config.ffmpeg : '未指定'}</span>`,
|
||||
'ffmpeg 路径, 发送语音、视频需要,同时保证ffprobe和ffmpeg在一起', `<span id="config-ffmpeg-path-text">${!isEmpty(config.ffmpeg) ? config.ffmpeg : '未指定'}</span>`,
|
||||
SettingButton('选择', 'config-ffmpeg-select'),
|
||||
),
|
||||
SettingItem(
|
||||
@@ -138,7 +138,7 @@ async function onSettingWindowCreated(view: Element) {
|
||||
]),
|
||||
SettingList([
|
||||
SettingItem(
|
||||
'GitHub',
|
||||
'GitHub和文档',
|
||||
`https://github.com/LLOneBot/LLOneBot`,
|
||||
SettingButton('点个Star', 'open-github'),
|
||||
),
|
||||
@@ -167,17 +167,16 @@ async function onSettingWindowCreated(view: Element) {
|
||||
window.LiteLoader.api.openExternal('https://qm.qq.com/q/bDnHRG38aI')
|
||||
})
|
||||
// 生成反向地址列表
|
||||
const buildHostListItem = (type: string, host: string, index: number) => {
|
||||
const buildHostListItem = (type: string, host: string, index: number, inputAttrs: any={}) => {
|
||||
const dom = {
|
||||
container: document.createElement('setting-item'),
|
||||
input: document.createElement('input'),
|
||||
inputContainer: document.createElement('div'),
|
||||
deleteBtn: document.createElement('setting-button'),
|
||||
};
|
||||
|
||||
dom.container.classList.add('setting-host-list-item');
|
||||
dom.container.dataset.direction = 'row';
|
||||
|
||||
Object.assign(dom.input, inputAttrs);
|
||||
dom.input.classList.add('q-input__inner');
|
||||
dom.input.type = 'url';
|
||||
dom.input.value = host;
|
||||
@@ -200,18 +199,18 @@ async function onSettingWindowCreated(view: Element) {
|
||||
|
||||
return dom.container;
|
||||
};
|
||||
const buildHostList = (hosts: string[], type: string) => {
|
||||
const buildHostList = (hosts: string[], type: string, inputAttr: any={}) => {
|
||||
const result: HTMLElement[] = [];
|
||||
|
||||
hosts.forEach((host, index) => {
|
||||
result.push(buildHostListItem(type, host, index));
|
||||
result.push(buildHostListItem(type, host, index, inputAttr));
|
||||
});
|
||||
|
||||
return result;
|
||||
};
|
||||
const addReverseHost = (type: string, doc: Document = document) => {
|
||||
const addReverseHost = (type: string, doc: Document = document, inputAttr: any={}) => {
|
||||
const hostContainerDom = doc.body.querySelector(`#config-ob11-${type}-list`);
|
||||
hostContainerDom.appendChild(buildHostListItem(type, '', ob11Config[type].length));
|
||||
hostContainerDom.appendChild(buildHostListItem(type, '', ob11Config[type].length, inputAttr));
|
||||
ob11Config[type].push('');
|
||||
};
|
||||
const initReverseHost = (type: string, doc: Document = document) => {
|
||||
@@ -224,8 +223,8 @@ async function onSettingWindowCreated(view: Element) {
|
||||
initReverseHost('httpHosts', doc);
|
||||
initReverseHost('wsHosts', doc);
|
||||
|
||||
doc.querySelector('#config-ob11-httpHosts-add').addEventListener('click', () => addReverseHost('httpHosts'));
|
||||
doc.querySelector('#config-ob11-wsHosts-add').addEventListener('click', () => addReverseHost('wsHosts'));
|
||||
doc.querySelector('#config-ob11-httpHosts-add').addEventListener('click', () => addReverseHost('httpHosts', document, {'placeholder': '如:http://127.0.0.1:5140/onebot' }));
|
||||
doc.querySelector('#config-ob11-wsHosts-add').addEventListener('click', () => addReverseHost('wsHosts', document, {'placeholder': '如:ws://127.0.0.1:5140/onebot' }));
|
||||
|
||||
doc.querySelector('#config-ffmpeg-select').addEventListener('click', () => {
|
||||
window.llonebot.selectFile()
|
||||
|
@@ -1 +1 @@
|
||||
export const version = "3.13.10"
|
||||
export const version = "3.15.1"
|
Reference in New Issue
Block a user