feat: 破坏file/db相关接口

This commit is contained in:
手瓜一十雪 2024-07-22 14:09:37 +08:00
parent 087c76b394
commit 72d2d3f224
9 changed files with 142 additions and 148 deletions

View File

@ -474,4 +474,4 @@ class DBUtil extends DBUtilBase {
} }
export const dbUtil = new DBUtil(); // export const dbUtil = new DBUtil();

View File

@ -4,7 +4,6 @@ import crypto from 'crypto';
import util from 'util'; import util from 'util';
import path from 'node:path'; import path from 'node:path';
import { log, logError } from './log'; import { log, logError } from './log';
import { dbUtil } from '@/common/utils/db';
import * as fileType from 'file-type'; import * as fileType from 'file-type';
import { v4 as uuidv4 } from 'uuid'; import { v4 as uuidv4 } from 'uuid';
import { napCatCore } from '@/core'; import { napCatCore } from '@/core';
@ -251,13 +250,14 @@ export async function uri2local(uri: string, fileName: string | null = null): Pr
} else { } else {
filePath = pathname; filePath = pathname;
} }
} else { }
const cache = await dbUtil.getFileCacheByName(uri); else {
if (cache) { // const cache = await dbUtil.getFileCacheByName(uri);
filePath = cache.path; // if (cache) {
} else { // filePath = cache.path;
filePath = uri; // } else {
} // filePath = uri;
// }
} }
res.isLocal = true; res.isLocal = true;

View File

@ -17,7 +17,6 @@ import fs from 'node:fs';
import { appid, qqVersionConfigInfo } from '@/common/utils/QQBasicInfo'; import { appid, qqVersionConfigInfo } from '@/common/utils/QQBasicInfo';
import { hostname, systemVersion } from '@/common/utils/system'; import { hostname, systemVersion } from '@/common/utils/system';
import { genSessionConfig } from '@/core/sessionConfig'; import { genSessionConfig } from '@/core/sessionConfig';
import { dbUtil } from '@/common/utils/db';
import { sleep } from '@/common/utils/helper'; import { sleep } from '@/common/utils/helper';
import crypto from 'node:crypto'; import crypto from 'node:crypto';
import { rawFriends, friends, groupMembers, groups, selfInfo, stat } from '@/core/data'; import { rawFriends, friends, groupMembers, groups, selfInfo, stat } from '@/core/data';
@ -84,20 +83,21 @@ export class NapCatCore {
const dataPath = path.resolve(this.dataPath, './NapCat/data'); const dataPath = path.resolve(this.dataPath, './NapCat/data');
fs.mkdirSync(dataPath, { recursive: true }); fs.mkdirSync(dataPath, { recursive: true });
logDebug('本账号数据/缓存目录:', dataPath); logDebug('本账号数据/缓存目录:', dataPath);
dbUtil.init(path.resolve(dataPath, `./${arg.uin}-v2.db`)).then(() => { // dbUtil.init(path.resolve(dataPath, `./${arg.uin}-v2.db`)).then(() => {
this.initDataListener(); // this.initDataListener();
this.onLoginSuccessFuncList.map(cb => { // this.onLoginSuccessFuncList.map(cb => {
new Promise((resolve, reject) => { // new Promise((resolve, reject) => {
const result = cb(arg.uin, arg.uid); // const result = cb(arg.uin, arg.uid);
if (result instanceof Promise) { // if (result instanceof Promise) {
result.then(resolve).catch(reject); // result.then(resolve).catch(reject);
} // }
}).then(); // }).then();
}); // });
}).catch((e) => { // }).catch((e) => {
logError('数据库初始化失败', e); // logError('数据库初始化失败', e);
}); // });
// this.initDataListener(); // this.initDataListener();
}).catch((e) => { }).catch((e) => {
logError('initSession failed', e); logError('initSession failed', e);
throw new Error(`启动失败: ${JSON.stringify(e)}`); throw new Error(`启动失败: ${JSON.stringify(e)}`);
@ -475,7 +475,7 @@ export class NapCatCore {
return loginList; return loginList;
} }
checkAdminEvent(groupCode: string, memberNew: GroupMember, memberOld: GroupMember | undefined ) : boolean { checkAdminEvent(groupCode: string, memberNew: GroupMember, memberOld: GroupMember | undefined ) : boolean {
if (memberNew.role !== memberOld.role) { if (memberNew.role !== memberOld?.role) {
log(`${groupCode} ${memberNew.nick} 角色变更为 ${memberNew.role === 3 ? '管理员' : '群员' }`); log(`${groupCode} ${memberNew.nick} 角色变更为 ${memberNew.role === 3 ? '管理员' : '群员' }`);
return true; return true;
} }

View File

@ -1,15 +1,15 @@
import BaseAction from '../BaseAction'; import BaseAction from '../BaseAction';
import fs from 'fs/promises'; import fs from 'fs/promises';
import { dbUtil } from '@/common/utils/db';
import { ob11Config } from '@/onebot11/config'; import { ob11Config } from '@/onebot11/config';
import { log, logDebug } from '@/common/utils/log'; import { log, logDebug } from '@/common/utils/log';
import { sleep } from '@/common/utils/helper'; import { sleep } from '@/common/utils/helper';
import { uri2local } from '@/common/utils/file'; import { uri2local } from '@/common/utils/file';
import { ActionName, BaseCheckResult } from '../types'; import { ActionName, BaseCheckResult } from '../types';
import { FileElement, RawMessage, VideoElement } from '@/core/entities'; import { FileElement, RawMessage, VideoElement } from '@/core/entities';
import { NTQQFileApi } from '@/core/apis'; import { NTQQFileApi, NTQQMsgApi } from '@/core/apis';
import { FromSchema, JSONSchema } from 'json-schema-to-ts'; import { FromSchema, JSONSchema } from 'json-schema-to-ts';
import Ajv from 'ajv'; import Ajv from 'ajv';
import { MessageUnique } from '@/common/utils/MessageUnique';
export interface GetFilePayload { export interface GetFilePayload {
file: string; // 文件名或者fileUuid file: string; // 文件名或者fileUuid
@ -45,69 +45,67 @@ export class GetFileBase extends BaseAction<GetFilePayload, GetFileResponse> {
return { id: element.elementId, element: element.fileElement }; return { id: element.elementId, element: element.fileElement };
} }
protected async _handle(payload: GetFilePayload): Promise<GetFileResponse> { protected async _handle(payload: GetFilePayload): Promise<GetFileResponse> {
let cache = await dbUtil.getFileCacheByName(payload.file); throw new Error('file not found');
if (!cache) { // let cache = await dbUtil.getFileCacheByName(payload.file);
cache = await dbUtil.getFileCacheByUuid(payload.file); // if (!cache) {
} // cache = await dbUtil.getFileCacheByUuid(payload.file);
if (!cache) {
throw new Error('file not found');
}
const { enableLocalFile2Url } = ob11Config;
try {
await fs.access(cache.path, fs.constants.F_OK);
} catch (e) {
logDebug('local file not found, start download...');
// if (cache.url) {
// const downloadResult = await uri2local(cache.url);
// if (downloadResult.success) {
// cache.path = downloadResult.path;
// dbUtil.updateFileCache(cache).then();
// } else {
// throw new Error('file download failed. ' + downloadResult.errMsg);
// }
// } else {
// // 没有url的可能是私聊文件或者群文件需要自己下载
// log('需要调用 NTQQ 下载文件api');
let msg = await dbUtil.getMsgByLongId(cache.msgId);
// log('文件 msg', msg);
if (msg) {
// 构建下载函数
const downloadPath = await NTQQFileApi.downloadMedia(msg.msgId, msg.chatType, msg.peerUid,
cache.elementId, '', '');
// await sleep(1000);
// log('download result', downloadPath);
msg = await dbUtil.getMsgByLongId(cache.msgId);
// log('下载完成后的msg', msg);
cache.path = downloadPath!;
dbUtil.updateFileCache(cache).then();
// log('下载完成后的msg', msg);
// }
}
}
// log('file found', cache);
const res: GetFileResponse = {
file: cache.path,
url: cache.url,
file_size: cache.size.toString(),
file_name: cache.name
};
if (enableLocalFile2Url) {
if (!cache.url) {
try {
res.base64 = await fs.readFile(cache.path, 'base64');
} catch (e) {
throw new Error('文件下载失败. ' + e);
}
}
}
// if (autoDeleteFile) {
// setTimeout(() => {
// fs.unlink(cache.filePath)
// }, autoDeleteFileSecond * 1000)
// } // }
return res; // if (!cache) {
// throw new Error('file not found');
// }
// const { enableLocalFile2Url } = ob11Config;
// try {
// await fs.access(cache.path, fs.constants.F_OK);
// } catch (e) {
// logDebug('local file not found, start download...');
// // if (cache.url) {
// // const downloadResult = await uri2local(cache.url);
// // if (downloadResult.success) {
// // cache.path = downloadResult.path;
// // dbUtil.updateFileCache(cache).then();
// // } else {
// // throw new Error('file download failed. ' + downloadResult.errMsg);
// // }
// // } else {
// // // 没有url的可能是私聊文件或者群文件需要自己下载
// // log('需要调用 NTQQ 下载文件api');
// let peer = MessageUnique.getPeerByMsgId(cache.msgId);
// let msg = await NTQQMsgApi.getMsgsByMsgId(peer?.Peer!,cache.msgId);
// // log('文件 msg', msg);
// if (msg) {
// // 构建下载函数
// const downloadPath = await NTQQFileApi.downloadMedia(msg.msgId, msg.chatType, msg.peerUid,
// cache.elementId, '', '');
// // await sleep(1000);
// // log('download result', downloadPath);
// let peer = MessageUnique.getPeerByMsgId(cache.msgId);
// msg = await NTQQMsgApi.getMsgsByMsgId(peer?.Peer!,cache.msgId);
// // log('下载完成后的msg', msg);
// cache.path = downloadPath!;
// dbUtil.updateFileCache(cache).then();
// // log('下载完成后的msg', msg);
// // }
// }
// }
// // log('file found', cache);
// const res: GetFileResponse = {
// file: cache.path,
// url: cache.url,
// file_size: cache.size.toString(),
// file_name: cache.name
// };
// if (enableLocalFile2Url) {
// if (!cache.url) {
// try {
// res.base64 = await fs.readFile(cache.path, 'base64');
// } catch (e) {
// throw new Error('文件下载失败. ' + e);
// }
// }
// }
//return res;
} }
} }

View File

@ -5,13 +5,13 @@ import {
Group, Group,
IdMusicSignPostData, IdMusicSignPostData,
NTQQFileApi, NTQQFileApi,
NTQQMsgApi,
SendArkElement, SendArkElement,
SendMessageElement, SendMessageElement,
SendMsgElementConstructor, SendMsgElementConstructor,
SignMusicWrapper SignMusicWrapper
} from '@/core'; } from '@/core';
import { getGroupMember } from '@/core/data'; import { getGroupMember } from '@/core/data';
import { dbUtil } from '@/common/utils/db';
import { logDebug, logError } from '@/common/utils/log'; import { logDebug, logError } from '@/common/utils/log';
import { uri2local } from '@/common/utils/file'; import { uri2local } from '@/common/utils/file';
import { ob11Config } from '@/onebot11/config'; import { ob11Config } from '@/onebot11/config';
@ -30,25 +30,25 @@ async function handleOb11FileLikeMessage(
) { ) {
let uri = file; let uri = file;
const cache = await dbUtil.getFileCacheByName(file); // const cache = await dbUtil.getFileCacheByName(file);
if (cache) { // if (cache) {
if (fs.existsSync(cache.path)) { // if (fs.existsSync(cache.path)) {
uri = 'file://' + cache.path; // uri = 'file://' + cache.path;
} else if (cache.url) { // } else if (cache.url) {
uri = cache.url; // uri = cache.url;
} else { // } else {
const fileMsgPeer = MessageUnique.getPeerByMsgId(cache.msgId); // const fileMsgPeer = MessageUnique.getPeerByMsgId(cache.msgId);
if (fileMsgPeer) { // if (fileMsgPeer) {
cache.path = await NTQQFileApi.downloadMedia( // cache.path = await NTQQFileApi.downloadMedia(
fileMsgPeer.MsgId, fileMsgPeer.Peer.chatType, fileMsgPeer.Peer.peerUid, // fileMsgPeer.MsgId, fileMsgPeer.Peer.chatType, fileMsgPeer.Peer.peerUid,
cache.elementId, '', '' // cache.elementId, '', ''
); // );
uri = 'file://' + cache.path; // uri = 'file://' + cache.path;
dbUtil.updateFileCache(cache); // dbUtil.updateFileCache(cache);
} // }
} // }
logDebug('找到文件缓存', uri); // logDebug('找到文件缓存', uri);
} // }
const { path, isLocal, fileName, errMsg } = (await uri2local(uri)); const { path, isLocal, fileName, errMsg } = (await uri2local(uri));
@ -87,7 +87,8 @@ const _handlers: {
}, },
[OB11MessageDataType.reply]: async ({ data: { id } }) => { [OB11MessageDataType.reply]: async ({ data: { id } }) => {
const replyMsg = await dbUtil.getMsgByShortId(parseInt(id)); const replyMsgM = MessageUnique.getMsgIdAndPeerByShortId(parseInt(id));
const replyMsg = (await NTQQMsgApi.getMsgsByMsgId(replyMsgM?.Peer!, [replyMsgM?.MsgId!])).msgList[0];
return replyMsg ? return replyMsg ?
SendMsgElementConstructor.reply(replyMsg.msgSeq, replyMsg.msgId, replyMsg.senderUin!, replyMsg.senderUin!) : SendMsgElementConstructor.reply(replyMsg.msgSeq, replyMsg.msgId, replyMsg.senderUin!, replyMsg.senderUin!) :
undefined; undefined;

View File

@ -4,7 +4,6 @@ import { selfInfo } from '@/core/data';
import createSendElements from '@/onebot11/action/msg/SendMsg/create-send-elements'; import createSendElements from '@/onebot11/action/msg/SendMsg/create-send-elements';
import { logDebug, logError } from '@/common/utils/log'; import { logDebug, logError } from '@/common/utils/log';
import { sleep } from '@/common/utils/helper'; import { sleep } from '@/common/utils/helper';
import fs from 'node:fs';
import { normalize, sendMsg } from '@/onebot11/action/msg/SendMsg/index'; import { normalize, sendMsg } from '@/onebot11/action/msg/SendMsg/index';
import { MessageUnique } from '@/common/utils/MessageUnique'; import { MessageUnique } from '@/common/utils/MessageUnique';

View File

@ -7,7 +7,6 @@ import {
ChatCacheListItemBasic, ChatCacheListItemBasic,
CacheFileType CacheFileType
} from '@/core/entities'; } from '@/core/entities';
import { dbUtil } from '@/common/utils/db';
import { NTQQFileApi, NTQQFileCacheApi } from '@/core/apis/file'; import { NTQQFileApi, NTQQFileCacheApi } from '@/core/apis/file';
import { logError } from '@/common/utils/log'; import { logError } from '@/common/utils/log';

View File

@ -42,7 +42,6 @@ import { ob11Config } from '@/onebot11/config';
import { deleteGroup, getGroupMember, groupMembers, selfInfo, tempGroupCodeMap } from '@/core/data'; import { deleteGroup, getGroupMember, groupMembers, selfInfo, tempGroupCodeMap } from '@/core/data';
import { NTQQFileApi, NTQQGroupApi, NTQQMsgApi, NTQQUserApi } from '@/core/apis'; import { NTQQFileApi, NTQQGroupApi, NTQQMsgApi, NTQQUserApi } from '@/core/apis';
import { OB11GroupMsgEmojiLikeEvent } from '@/onebot11/event/notice/OB11MsgEmojiLikeEvent'; import { OB11GroupMsgEmojiLikeEvent } from '@/onebot11/event/notice/OB11MsgEmojiLikeEvent';
import { napCatCore } from '@/core';
import { OB11FriendPokeEvent, OB11GroupPokeEvent } from './event/notice/OB11PokeEvent'; import { OB11FriendPokeEvent, OB11GroupPokeEvent } from './event/notice/OB11PokeEvent';
import { OB11BaseNoticeEvent } from './event/notice/OB11BaseNoticeEvent'; import { OB11BaseNoticeEvent } from './event/notice/OB11BaseNoticeEvent';
import { OB11GroupEssenceEvent } from './event/notice/OB11GroupEssenceEvent'; import { OB11GroupEssenceEvent } from './event/notice/OB11GroupEssenceEvent';
@ -178,17 +177,17 @@ export class OB11Constructor {
//console.log(message_data['data']['url']) //console.log(message_data['data']['url'])
// message_data["data"]["file_id"] = element.picElement.fileUuid // message_data["data"]["file_id"] = element.picElement.fileUuid
message_data['data']['file_size'] = element.picElement.fileSize; message_data['data']['file_size'] = element.picElement.fileSize;
dbUtil.addFileCache({ // dbUtil.addFileCache({
name: element.picElement.fileName, // name: element.picElement.fileName,
path: element.picElement.sourcePath, // path: element.picElement.sourcePath,
size: element.picElement.fileSize, // size: element.picElement.fileSize,
url: message_data['data']['url'], // url: message_data['data']['url'],
uuid: element.picElement.fileUuid || '', // uuid: element.picElement.fileUuid || '',
msgId: msg.msgId, // msgId: msg.msgId,
element: element.picElement, // element: element.picElement,
elementType: ElementType.PIC, // elementType: ElementType.PIC,
elementId: element.elementId // elementId: element.elementId
}).then(); // }).then();
// 不自动下载图片 // 不自动下载图片
} }
@ -203,17 +202,18 @@ export class OB11Constructor {
message_data['data']['file_id'] = videoOrFileElement.fileUuid; message_data['data']['file_id'] = videoOrFileElement.fileUuid;
message_data['data']['file_size'] = videoOrFileElement.fileSize; message_data['data']['file_size'] = videoOrFileElement.fileSize;
if (!element.videoElement) { if (!element.videoElement) {
dbUtil.addFileCache({ // dbUtil.addFileCache({
msgId: msg.msgId, // msgId: msg.msgId,
name: videoOrFileElement.fileName, // name: videoOrFileElement.fileName,
path: videoOrFileElement.filePath, // path: videoOrFileElement.filePath,
size: parseInt(videoOrFileElement.fileSize || '0'), // size: parseInt(videoOrFileElement.fileSize || '0'),
uuid: videoOrFileElement.fileUuid || '', // uuid: videoOrFileElement.fileUuid || '',
url: '', // url: '',
element: element.videoElement || element.fileElement, // element: element.videoElement || element.fileElement,
elementType: element.videoElement ? ElementType.VIDEO : ElementType.FILE, // elementType: element.videoElement ? ElementType.VIDEO : ElementType.FILE,
elementId: element.elementId // elementId: element.elementId
}).then(); // }).then();
// }
} }
} }
else if (element.pttElement) { else if (element.pttElement) {
@ -222,17 +222,17 @@ export class OB11Constructor {
message_data['data']['path'] = element.pttElement.filePath; message_data['data']['path'] = element.pttElement.filePath;
// message_data["data"]["file_id"] = element.pttElement.fileUuid // message_data["data"]["file_id"] = element.pttElement.fileUuid
message_data['data']['file_size'] = element.pttElement.fileSize; message_data['data']['file_size'] = element.pttElement.fileSize;
dbUtil.addFileCache({ // dbUtil.addFileCache({
name: element.pttElement.fileName, // name: element.pttElement.fileName,
path: element.pttElement.filePath, // path: element.pttElement.filePath,
size: parseInt(element.pttElement.fileSize) || 0, // size: parseInt(element.pttElement.fileSize) || 0,
url: '', // url: '',
uuid: element.pttElement.fileUuid || '', // uuid: element.pttElement.fileUuid || '',
msgId: msg.msgId, // msgId: msg.msgId,
element: element.pttElement, // element: element.pttElement,
elementType: ElementType.PTT, // elementType: ElementType.PTT,
elementId: element.elementId // elementId: element.elementId
}).then(); // }).then();
} }
else if (element.arkElement) { else if (element.arkElement) {

View File

@ -333,9 +333,6 @@ export class NapCatOnebot11 {
const { debug, reportSelfMessage } = ob11Config; const { debug, reportSelfMessage } = ob11Config;
for (const message of msgList) { for (const message of msgList) {
logDebug('收到新消息', message); logDebug('收到新消息', message);
// if (message.senderUin !== selfInfo.uin){
// message.msgShortId = await dbUtil.addMsg(message);
// }
OB11Constructor.message(message).then((msg) => { OB11Constructor.message(message).then((msg) => {
logDebug('收到消息: ', msg); logDebug('收到消息: ', msg);
if (debug) { if (debug) {