Q2TG/src/models/ForwardPairs.ts

81 lines
2.7 KiB
TypeScript
Raw Permalink Normal View History

2023-06-30 11:26:45 +00:00
import { Friend, Group } from 'icqq';
import TelegramChat from '../client/TelegramChat';
import OicqClient from '../client/OicqClient';
import Telegram from '../client/Telegram';
import db from './db';
2022-02-26 10:15:40 +00:00
import { Entity } from 'telegram/define';
import { BigInteger } from 'big-integer';
import { Pair } from './Pair';
2022-03-27 11:35:57 +00:00
import { getLogger, Logger } from 'log4js';
import Instance from './Instance';
export default class ForwardPairs {
private pairs: Pair[] = [];
2022-03-27 11:35:57 +00:00
private readonly log: Logger;
private constructor(private readonly instanceId: number) {
2022-03-27 11:35:57 +00:00
this.log = getLogger(`ForwardPairs - ${instanceId}`);
}
// 在 forwardController 创建时初始化
private async init(oicq: OicqClient, tgBot: Telegram, tgUser: Telegram) {
const dbValues = await db.forwardPair.findMany({
where: { instanceId: this.instanceId },
});
for (const i of dbValues) {
2022-03-27 11:35:57 +00:00
try {
const qq = oicq.getChat(Number(i.qqRoomId));
const tg = await tgBot.getChat(Number(i.tgChatId));
const tgUserChat = await tgUser.getChat(Number(i.tgChatId));
if (qq && tg && tgUserChat) {
this.pairs.push(new Pair(qq, tg, tgUserChat, i.id, i.flags));
2022-03-27 11:35:57 +00:00
}
}
catch (e) {
this.log.warn(`初始化遇到问题QQ: ${i.qqRoomId} TG: ${i.tgChatId}`);
}
}
}
public static async load(instanceId: number, oicq: OicqClient, tgBot: Telegram, tgUser: Telegram) {
const instance = new this(instanceId);
await instance.init(oicq, tgBot, tgUser);
return instance;
}
public async add(qq: Friend | Group, tg: TelegramChat, tgUser: TelegramChat) {
const dbEntry = await db.forwardPair.create({
data: {
qqRoomId: qq instanceof Friend ? qq.user_id : -qq.group_id,
tgChatId: Number(tg.id),
instanceId: this.instanceId,
},
});
this.pairs.push(new Pair(qq, tg, tgUser, dbEntry.id, dbEntry.flags));
return dbEntry;
}
2022-03-08 06:38:40 +00:00
public async remove(pair: Pair) {
this.pairs.splice(this.pairs.indexOf(pair), 1);
await db.forwardPair.delete({
where: { id: pair.dbId },
});
}
public find(target: Friend | Group | TelegramChat | Entity | number | BigInteger) {
2022-03-06 15:32:31 +00:00
if (!target) return null;
if (target instanceof Friend) {
return this.pairs.find(e => e.qq instanceof Friend && e.qq.user_id === target.user_id);
}
else if (target instanceof Group) {
return this.pairs.find(e => e.qq instanceof Group && e.qq.group_id === target.group_id);
}
else if (typeof target === 'number' || 'eq' in target) {
return this.pairs.find(e => e.qqRoomId === target || e.tg.id.eq(target));
}
else {
return this.pairs.find(e => e.tg.id.eq(target.id));
}
}
}