style&fix: lint & poke

This commit is contained in:
手瓜一十雪 2024-06-21 23:04:56 +08:00
parent e53c37adc9
commit 14822c9599
17 changed files with 169 additions and 170 deletions

View File

@ -1,53 +1,53 @@
import crypto from 'crypto';
class LimitedHashTable<K, V> {
private keyToValue: Map<K, V> = new Map();
private valueToKey: Map<V, K> = new Map();
private maxSize: number;
private KeyQueneList: K[] = [];
private ValueQueneList: V[] = [];
constructor(maxSize: number) {
this.maxSize = maxSize;
}
set(key: K, value: V): void {
this.keyToValue.set(key, value);
this.valueToKey.set(value, key);
if (this.KeyQueneList.length >= this.maxSize || this.ValueQueneList.length >= this.maxSize) {
this.KeyQueneList.shift();
this.ValueQueneList.shift();
}
private keyToValue: Map<K, V> = new Map();
private valueToKey: Map<V, K> = new Map();
private maxSize: number;
private KeyQueneList: K[] = [];
private ValueQueneList: V[] = [];
constructor(maxSize: number) {
this.maxSize = maxSize;
}
set(key: K, value: V): void {
this.keyToValue.set(key, value);
this.valueToKey.set(value, key);
if (this.KeyQueneList.length >= this.maxSize || this.ValueQueneList.length >= this.maxSize) {
this.KeyQueneList.shift();
this.ValueQueneList.shift();
}
}
getValue(key: K): V | undefined {
return this.keyToValue.get(key);
}
getValue(key: K): V | undefined {
return this.keyToValue.get(key);
}
getKey(value: V): K | undefined {
return this.valueToKey.get(value);
}
getKey(value: V): K | undefined {
return this.valueToKey.get(value);
}
delete(key: K): void {
const value = this.keyToValue.get(key);
if (value !== undefined) {
this.keyToValue.delete(key);
this.valueToKey.delete(value);
}
delete(key: K): void {
const value = this.keyToValue.get(key);
if (value !== undefined) {
this.keyToValue.delete(key);
this.valueToKey.delete(value);
}
}
}
class MessageUniqueWrapper {
private msgIdMap: LimitedHashTable<number, string> = new LimitedHashTable(1000);
createMsg(MsgId: string) {
let ShortId = parseInt(crypto.createHash('sha1').update('2345').digest('hex').slice(0, 8), 16);
this.msgIdMap.set(ShortId, MsgId);
return ShortId;
}
getMsgIdByShortId(ShortId: number) {
return this.msgIdMap.getValue(ShortId);
}
getShortIdByMsgId(MsgId: string) {
return this.msgIdMap.getKey(MsgId);
}
private msgIdMap: LimitedHashTable<number, string> = new LimitedHashTable(1000);
createMsg(MsgId: string) {
const ShortId = parseInt(crypto.createHash('sha1').update('2345').digest('hex').slice(0, 8), 16);
this.msgIdMap.set(ShortId, MsgId);
return ShortId;
}
getMsgIdByShortId(ShortId: number) {
return this.msgIdMap.getValue(ShortId);
}
getShortIdByMsgId(MsgId: string) {
return this.msgIdMap.getKey(MsgId);
}
}
export const MessageUnique = new MessageUniqueWrapper();

View File

@ -1,14 +1,14 @@
// 方案一 MiniApp发包方案
// 前置条件: 处于GUI环境 存在MiniApp
import { NTQQSystemApi } from "@/core";
import { NTQQSystemApi } from '@/core';
// 前排提示: 开发验证仅Win平台开展
export class MiniAppUtil {
static async RunMiniAppWithGUI() {
//process.env.ELECTRON_RUN_AS_NODE = undefined;//没用还是得自己用cpp之类的语言写个程序转发参数
return NTQQSystemApi.BootMiniApp(process.execPath, "miniapp://open/1007?url=https%3A%2F%2Fm.q.qq.com%2Fa%2Fs%2Fedd0a83d3b8afe233dfa07adaaf8033f%3Fscene%3D1007%26min_refer%3D10001");
}
static async RunMiniAppWithGUI() {
//process.env.ELECTRON_RUN_AS_NODE = undefined;//没用还是得自己用cpp之类的语言写个程序转发参数
return NTQQSystemApi.BootMiniApp(process.execPath, 'miniapp://open/1007?url=https%3A%2F%2Fm.q.qq.com%2Fa%2Fs%2Fedd0a83d3b8afe233dfa07adaaf8033f%3Fscene%3D1007%26min_refer%3D10001');
}
}
// 方案二 MiniApp发包方案 替代MiniApp方案
// 前置条件: 无

View File

@ -264,23 +264,23 @@ export function isEqual(obj1: any, obj2: any) {
}
export async function deleteOldFiles(directoryPath: string, daysThreshold: number) {
try {
const files = await fsPromise.readdir(directoryPath);
try {
const files = await fsPromise.readdir(directoryPath);
for (const file of files) {
const filePath = path.join(directoryPath, file);
const stats = await fsPromise.stat(filePath);
const lastModifiedTime = stats.mtimeMs;
const currentTime = Date.now();
const timeDifference = currentTime - lastModifiedTime;
const daysDifference = timeDifference / (1000 * 60 * 60 * 24);
for (const file of files) {
const filePath = path.join(directoryPath, file);
const stats = await fsPromise.stat(filePath);
const lastModifiedTime = stats.mtimeMs;
const currentTime = Date.now();
const timeDifference = currentTime - lastModifiedTime;
const daysDifference = timeDifference / (1000 * 60 * 60 * 24);
if (daysDifference > daysThreshold) {
await fsPromise.unlink(filePath); // Delete the file
//console.log(`Deleted: ${filePath}`);
}
}
} catch (error) {
//console.error('Error deleting files:', error);
if (daysDifference > daysThreshold) {
await fsPromise.unlink(filePath); // Delete the file
//console.log(`Deleted: ${filePath}`);
}
}
} catch (error) {
//console.error('Error deleting files:', error);
}
}

View File

@ -119,7 +119,7 @@ export class RequestUtil {
const formDataParts = [
`------${boundary}\r\n`,
`Content-Disposition: form-data; name="share_image"; filename="${filePath}"\r\n`,
`Content-Type: ` + type + `\r\n\r\n`
'Content-Type: ' + type + '\r\n\r\n'
];
const fileContent = readFileSync(filePath);
@ -157,11 +157,10 @@ export class RequestUtil {
});
res.on('end', () => {
try {
if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
const responseJson = JSON.parse(responseBody) as retType;
resolve(responseJson.result?.url!);
resolve(responseJson.result!.url!);
} else {
reject(new Error(`Unexpected status code: ${res.statusCode}`));
}

View File

@ -7,20 +7,20 @@ import { FromSchema, JSONSchema } from 'json-schema-to-ts';
import { selfInfo } from '@/core/data';
const SchemaData = {
type: 'object',
properties: {
rawData: { type: 'string' },
brief: { type: 'string' }
},
required: ['brief', 'rawData'],
type: 'object',
properties: {
rawData: { type: 'string' },
brief: { type: 'string' }
},
required: ['brief', 'rawData'],
} as const satisfies JSONSchema;
type Payload = FromSchema<typeof SchemaData>;
export class CreateCollection extends BaseAction<Payload, any> {
actionName = ActionName.CreateCollection;
PayloadSchema = SchemaData;
protected async _handle(payload: Payload) {
return await NTQQCollectionApi.createCollection(selfInfo.uin, selfInfo.uid, selfInfo.nick, payload.brief, payload.rawData);
}
actionName = ActionName.CreateCollection;
PayloadSchema = SchemaData;
protected async _handle(payload: Payload) {
return await NTQQCollectionApi.createCollection(selfInfo.uin, selfInfo.uid, selfInfo.nick, payload.brief, payload.rawData);
}
}

View File

@ -7,20 +7,20 @@ import { FromSchema, JSONSchema } from 'json-schema-to-ts';
import { selfInfo } from '@/core/data';
const SchemaData = {
type: 'object',
properties: {
category: { type: 'number' },
count: { type: 'number' }
},
required: ['category', 'count'],
type: 'object',
properties: {
category: { type: 'number' },
count: { type: 'number' }
},
required: ['category', 'count'],
} as const satisfies JSONSchema;
type Payload = FromSchema<typeof SchemaData>;
export class GetCollectionList extends BaseAction<Payload, any> {
actionName = ActionName.GetCollectionList;
PayloadSchema = SchemaData;
protected async _handle(payload: Payload) {
return await NTQQCollectionApi.getAllCollection(payload.category, payload.count);
}
actionName = ActionName.GetCollectionList;
PayloadSchema = SchemaData;
protected async _handle(payload: Payload) {
return await NTQQCollectionApi.getAllCollection(payload.category, payload.count);
}
}

View File

@ -5,20 +5,20 @@ import { NTQQUserApi } from '@/core/apis';
import { FromSchema, JSONSchema } from 'json-schema-to-ts';
const SchemaData = {
type: 'object',
properties: {
longNick: { type: 'string' },
},
required: [ 'longNick'],
type: 'object',
properties: {
longNick: { type: 'string' },
},
required: [ 'longNick'],
} as const satisfies JSONSchema;
type Payload = FromSchema<typeof SchemaData>;
export class SetLongNick extends BaseAction<Payload, any> {
actionName = ActionName.SetLongNick;
PayloadSchema = SchemaData;
protected async _handle(payload: Payload) {
let ret = await NTQQUserApi.setLongNick(payload.longNick)
return ret;
}
actionName = ActionName.SetLongNick;
PayloadSchema = SchemaData;
protected async _handle(payload: Payload) {
const ret = await NTQQUserApi.setLongNick(payload.longNick);
return ret;
}
}

View File

@ -5,28 +5,28 @@ import { NTQQUserApi } from '@/core/apis';
import { FromSchema, JSONSchema } from 'json-schema-to-ts';
const SchemaData = {
type: 'object',
properties: {
nick: { type: 'string' },
longNick: { type: 'string' },
sex: { type: 'number' }//传Sex值建议传0
},
required: ['nick', 'longNick', 'sex'],
type: 'object',
properties: {
nick: { type: 'string' },
longNick: { type: 'string' },
sex: { type: 'number' }//传Sex值建议传0
},
required: ['nick', 'longNick', 'sex'],
} as const satisfies JSONSchema;
type Payload = FromSchema<typeof SchemaData>;
export class SetSelfProfile extends BaseAction<Payload, any | null> {
actionName = ActionName.SetSelfProfile;
PayloadSchema = SchemaData;
protected async _handle(payload: Payload) {
let ret = await NTQQUserApi.modifySelfProfile({
nick: payload.nick,
longNick: payload.longNick,
sex: payload.sex,
birthday: { birthday_year: '', birthday_month: '', birthday_day: '' },
location: undefined
});
return ret;
}
actionName = ActionName.SetSelfProfile;
PayloadSchema = SchemaData;
protected async _handle(payload: Payload) {
const ret = await NTQQUserApi.modifySelfProfile({
nick: payload.nick,
longNick: payload.longNick,
sex: payload.sex,
birthday: { birthday_year: '', birthday_month: '', birthday_day: '' },
location: undefined
});
return ret;
}
}

View File

@ -5,41 +5,41 @@ import { BuddyCategoryType } from '@/core/entities/';
import { FromSchema, JSONSchema } from 'json-schema-to-ts';
const SchemaData = {
type: 'object',
properties: {
user_id: { type: 'string' },
group_id: { type: 'string' },
phoneNumber: { type: 'string' },
},
type: 'object',
properties: {
user_id: { type: 'string' },
group_id: { type: 'string' },
phoneNumber: { type: 'string' },
},
} as const satisfies JSONSchema;
type Payload = FromSchema<typeof SchemaData>;
export class sharePeer extends BaseAction<Payload, any> {
actionName = ActionName.SharePeer;
PayloadSchema = SchemaData;
protected async _handle(payload: Payload) {
if (payload.group_id) {
return await NTQQGroupApi.getGroupRecommendContactArkJson(payload.group_id);
} else if (payload.user_id) {
return await NTQQUserApi.getBuddyRecommendContactArkJson(payload.user_id, payload.phoneNumber || '');
}
actionName = ActionName.SharePeer;
PayloadSchema = SchemaData;
protected async _handle(payload: Payload) {
if (payload.group_id) {
return await NTQQGroupApi.getGroupRecommendContactArkJson(payload.group_id);
} else if (payload.user_id) {
return await NTQQUserApi.getBuddyRecommendContactArkJson(payload.user_id, payload.phoneNumber || '');
}
}
}
const SchemaDataGroupEx = {
type: 'object',
properties: {
group_id: { type: 'string' },
},
required: ['group_id']
type: 'object',
properties: {
group_id: { type: 'string' },
},
required: ['group_id']
} as const satisfies JSONSchema;
type PayloadGroupEx = FromSchema<typeof SchemaDataGroupEx>;
export class shareGroupEx extends BaseAction<PayloadGroupEx, any> {
actionName = ActionName.ShareGroupEx;
PayloadSchema = SchemaDataGroupEx;
protected async _handle(payload: PayloadGroupEx) {
return await NTQQGroupApi.getArkJsonGroupShare(payload.group_id);
}
actionName = ActionName.ShareGroupEx;
PayloadSchema = SchemaDataGroupEx;
protected async _handle(payload: PayloadGroupEx) {
return await NTQQGroupApi.getArkJsonGroupShare(payload.group_id);
}
}

View File

@ -21,10 +21,10 @@ export default class GoCQHTTPGetStrangerInfo extends BaseAction<Payload, OB11Use
protected async _handle(payload: Payload): Promise<OB11User> {
const user_id = payload.user_id.toString();
let extendData = await NTQQUserApi.getUserDetailInfoByUin(user_id);
let uid = (await NTQQUserApi.getUidByUin(user_id))!;
const extendData = await NTQQUserApi.getUserDetailInfoByUin(user_id);
const uid = (await NTQQUserApi.getUidByUin(user_id))!;
if (!uid || uid.indexOf('*') != -1) {
let ret = {
const ret = {
...extendData,
user_id: parseInt(extendData.info.uin) || 0,
nickname: extendData.info.nick,
@ -34,10 +34,10 @@ export default class GoCQHTTPGetStrangerInfo extends BaseAction<Payload, OB11Use
level: extendData.info.qqLevel && calcQQLevel(extendData.info.qqLevel) || 0,
login_days: 0,
uid: ''
}
};
return ret;
}
let data = { ...extendData, ...(await NTQQUserApi.getUserDetailInfo(uid)) };
const data = { ...extendData, ...(await NTQQUserApi.getUserDetailInfo(uid)) };
return OB11Constructor.stranger(data);
}
}

View File

@ -25,7 +25,7 @@ export default class SetGroupKick extends BaseAction<Payload, null> {
if (!member) {
throw `群成员${payload.user_id}不存在`;
}
let rejectReq = payload.reject_add_request?.toString() == 'true';
const rejectReq = payload.reject_add_request?.toString() == 'true';
await NTQQGroupApi.kickMember(payload.group_id.toString(), [member.uid], rejectReq);
return null;
}

View File

@ -134,7 +134,7 @@ const _handlers: {
const uri2LocalRes = await uri2local(thumb);
if (uri2LocalRes.success) thumb = uri2LocalRes.path;
}
let videoEle = await SendMsgElementConstructor.video(path, fileName, thumb);
const videoEle = await SendMsgElementConstructor.video(path, fileName, thumb);
//未测试
context.deleteAfterSentFiles.push(videoEle.videoElement.filePath);
return videoEle;

View File

@ -120,11 +120,11 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
return { valid: false, message: `${payload.group_id}不存在` };
}
if (payload.user_id && payload.message_type !== 'group') {
let uid = await NTQQUserApi.getUidByUin(payload.user_id)
let isBuddy = await NTQQFriendApi.isBuddy(uid!);
const uid = await NTQQUserApi.getUidByUin(payload.user_id);
const isBuddy = await NTQQFriendApi.isBuddy(uid!);
// 此处有问题
if (!isBuddy) {
//return { valid: false, message: '异常消息' };
//return { valid: false, message: '异常消息' };
}
}
return { valid: true };

View File

@ -90,8 +90,8 @@ export enum ActionName {
GetOnlineClient = 'get_online_clients',
OCRImage = 'ocr_image',
IOCRImage = '.ocr_image',
SetSelfProfile = "set_self_profile",
CreateCollection = "create_collection",
GetCollectionList = "get_collection_list",
SetLongNick = "set_self_longnick"
SetSelfProfile = 'set_self_profile',
CreateCollection = 'create_collection',
GetCollectionList = 'get_collection_list',
SetLongNick = 'set_self_longnick'
}

View File

@ -21,7 +21,7 @@ export default class SendLike extends BaseAction<Payload, null> {
//logDebug('点赞参数', payload);
try {
const qq = payload.user_id.toString();
let uid: string = await NTQQUserApi.getUidByUin(qq) || '';
const uid: string = await NTQQUserApi.getUidByUin(qq) || '';
const result = await NTQQUserApi.like(uid, parseInt(payload.times?.toString()) || 1);
//logDebug('点赞结果', result);
if (result.result !== 0) {

View File

@ -80,7 +80,7 @@ export class OB11Constructor {
}
else if (msg.chatType == ChatType.friend) {
resMsg.sub_type = 'friend';
let user = await NTQQUserApi.getUserDetailInfoByUin(msg.senderUin!);
const user = await NTQQUserApi.getUserDetailInfoByUin(msg.senderUin!);
resMsg.sender.nickname = user.info.nick;
}
else if (msg.chatType == ChatType.temp) {
@ -191,7 +191,7 @@ export class OB11Constructor {
else if (element.videoElement || element.fileElement) {
const videoOrFileElement = element.videoElement || element.fileElement;
const ob11MessageDataType = element.videoElement ? OB11MessageDataType.video : OB11MessageDataType.file;
let videoDownUrl = element.videoElement ? await NTQQFileApi.getVideoUrl(msg, element) : videoOrFileElement.filePath;
const videoDownUrl = element.videoElement ? await NTQQFileApi.getVideoUrl(msg, element) : videoOrFileElement.filePath;
message_data['type'] = ob11MessageDataType;
message_data['data']['file'] = videoOrFileElement.fileName;
message_data['data']['path'] = videoDownUrl;

View File

@ -37,7 +37,7 @@ import { Data as SysData } from '@/proto/SysMessage';
import { Data as DeviceData } from '@/proto/SysMessage.DeviceChange';
import { OB11FriendPokeEvent, OB11GroupPokeEvent } from './event/notice/OB11PokeEvent';
import { isEqual } from '@/common/utils/helper';
import { MiniAppUtil } from '@/common/utils/Packet'
import { MiniAppUtil } from '@/common/utils/Packet';
import { RequestUtil } from '@/common/utils/request';
//下面几个其实应该移进Core-Data 缓存实现 但是现在在这里方便
@ -115,9 +115,7 @@ export class NapCatOnebot11 {
// };
try {
// 生产环境会自己去掉
if (import.meta.env.MODE == 'development') {
logDebug(buf2hex(Buffer.from(protobufData)));
}
const hex = buf2hex(Buffer.from(protobufData));
const sysMsg = SysData.fromBinary(Buffer.from(protobufData));
const peeruin = sysMsg.header[0].peerNumber;
const peeruid = sysMsg.header[0].peerString;
@ -126,27 +124,29 @@ export class NapCatOnebot11 {
const subType1 = sysMsg.body[0].subType1;
let pokeEvent: OB11FriendPokeEvent | OB11GroupPokeEvent;
//console.log(peeruid);
if (MsgType == 528 && subType0 == 290) {
if (MsgType == 528 && subType0 == 290 && hex.length < 250 && hex.endsWith('04')) {
// 防止上报两次 私聊戳一戳
if (PokeCache.has(peeruid)) {
PokeCache.delete(peeruid);
} else {
PokeCache.set(peeruid, false);
log('[私聊] 用户 ', peeruin, ' 对你戳一戳');
pokeEvent = new OB11FriendPokeEvent(peeruin);
postOB11Event(pokeEvent);
}
PokeCache.set(peeruid, false);
setTimeout(() => {
PokeCache.delete(peeruid);
}, 1000);
}
if (MsgType == 732 && subType0 == 20) {
if (MsgType == 732 && subType0 == 20 && hex.length < 150 && hex.endsWith('04')) {
// 防止上报两次 群聊戳一戳
if (PokeCache.has(peeruid)) {
PokeCache.delete(peeruid);
} else {
PokeCache.set(peeruid, false);
log('[群聊] 群组 ', peeruin, ' 戳一戳');
pokeEvent = new OB11GroupPokeEvent(peeruin);
postOB11Event(pokeEvent);
}
PokeCache.set(peeruid, false);
setTimeout(() => {
PokeCache.delete(peeruid);
}, 1000);
}
if (MsgType == 528 && subType0 == 349) {
const sysDeviceMsg = DeviceData.fromBinary(Buffer.from(protobufData));
@ -475,7 +475,7 @@ export class NapCatOnebot11 {
logDebug('收到邀请我加群通知');
const groupInviteEvent = new OB11GroupRequestEvent();
groupInviteEvent.group_id = parseInt(notify.group.groupCode);
let user_id = (await NTQQUserApi.getUinByUid(notify.user2.uid)) || '';
const user_id = (await NTQQUserApi.getUinByUid(notify.user2.uid)) || '';
groupInviteEvent.user_id = parseInt(user_id);
groupInviteEvent.sub_type = 'invite';
groupInviteEvent.flag = flag;
@ -531,7 +531,7 @@ export class NapCatOnebot11 {
} catch (e) {
logDebug('获取加好友者QQ号失败', e);
}
friendRequestEvent.flag = req.friendUid + "|" + req.reqTime;
friendRequestEvent.flag = req.friendUid + '|' + req.reqTime;
friendRequestEvent.comment = req.extWords;
postOB11Event(friendRequestEvent);
}