projeto-hit/backend/src/services/WbotServices/StartWhatsAppSession.ts

117 lines
2.8 KiB
TypeScript
Raw Normal View History

import { initWbot } from "../../libs/wbot";
import Whatsapp from "../../models/Whatsapp";
import { wbotMessageListener } from "./wbotMessageListener";
import { getIO } from "../../libs/socket";
import wbotMonitor from "./wbotMonitor";
import { logger } from "../../utils/logger";
2022-11-17 14:40:37 +00:00
import { insertOrUpeateWhatsCache } from "../../helpers/WhatsCache";
2022-12-14 12:29:42 +00:00
import { getRestoreControll, setRestoreControll, shifRestoreControll } from "../../helpers/RestoreControll";
import ShowWhatsAppService from "../WhatsappService/ShowWhatsAppService";
import { restartWhatsSession } from "../../helpers/RestartWhatsSession";
import autoRestore from "../../helpers/AutoRestore";
let lstAutoRestore: any = []
2022-07-12 12:37:34 +00:00
export const StartWhatsAppSession = async (whatsapp: Whatsapp, backupSession: boolean = false): Promise<void> => {
2022-12-14 12:29:42 +00:00
await whatsapp.update({ status: "OPENING" });
2022-12-12 16:02:18 +00:00
2022-11-17 14:40:37 +00:00
await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, {
status: "OPENING",
})
2022-12-14 12:29:42 +00:00
try {
let lstRestore: any = getRestoreControll()
if (Object.keys(lstRestore.filter((e: any) => +e.id == +whatsapp.id)).length) {
2022-12-15 17:44:02 +00:00
console.log('Restore executed by human whatasappId: ', whatsapp.id)
2022-12-14 12:29:42 +00:00
}
else {
lstAutoRestore.push({ 'whatsappId': +whatsapp.id })
setTimeout(async () => {
lstRestore = getRestoreControll()
let count = lstAutoRestore.length
for (let i = 0; i < count; i++) {
let autoR = lstAutoRestore.shift()
console.log('----------------> autoR: ', autoR)
if (autoR && autoR.whatsappId) {
if (Object.keys(lstRestore.filter((e: any) => +e.id == +autoR.whatsappId)).length) {
console.log(' EXECUTING RESTORING autoR: ', autoR)
2022-12-14 12:29:42 +00:00
continue
}
const _whatsapp = await Whatsapp.findOne({ where: { id: autoR.whatsappId } });
console.log('----------------> autoR exec after 120 seconds: ', autoR)
2022-12-22 21:49:44 +00:00
let whatsappStatus = ["CONFLICT",
"DEPRECATED_VERSION",
"OPENING",
"PROXYBLOCK",
"SMB_TOS_BLOCK",
"TIMEOUT",
"TOS_BLOCK",
"UNLAUNCHED",
"UNPAIRED",
2022-12-14 12:29:42 +00:00
"UNPAIRED_IDLE"]
if (_whatsapp?.status) {
if (whatsappStatus.includes(_whatsapp.status)) {
await autoRestore(autoR.whatsappId, 'auto_monit')
}
}
}
}
}, 120000);
2022-12-14 12:29:42 +00:00
}
} catch (error) {
console.log('There was an error on try execute AUTO-RESTORE: ', error)
}
const io = getIO();
io.emit("whatsappSession", {
action: "update",
session: whatsapp
});
try {
2022-07-12 12:37:34 +00:00
const wbot = await initWbot(whatsapp, backupSession);
wbotMessageListener(wbot);
wbotMonitor(wbot, whatsapp);
} catch (err) {
logger.error(`${err}`);
}
};