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

122 lines
3.0 KiB
TypeScript

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";
import { insertOrUpeateWhatsCache } from "../../helpers/WhatsCache";
import { getRestoreControll, setRestoreControll, shifRestoreControll } from "../../helpers/RestoreControll";
import ShowWhatsAppService from "../WhatsappService/ShowWhatsAppService";
import { restartWhatsSession } from "../../helpers/RestartWhatsSession";
import dir from 'path';
import autoRestore from "../../helpers/AutoRestore";
import { creationTime } from "../../helpers/CreationTime";
import { splitDateTime } from "../../helpers/SplitDateTime";
import { format } from "date-fns";
import ptBR from 'date-fns/locale/pt-BR';
let lstAutoRestore: any = []
export const StartWhatsAppSession = async (whatsapp: Whatsapp, backupSession: boolean = false): Promise<void> => {
await whatsapp.update({ status: "OPENING" });
await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, {
status: "OPENING",
})
try {
let lstRestore: any = getRestoreControll()
if (Object.keys(lstRestore.filter((e: any) => +e.id == +whatsapp.id)).length) {
console.log('Restore executed by human whatasappId: ', whatsapp.id)
}
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)
continue
}
const _whatsapp = await Whatsapp.findOne({ where: { id: autoR.whatsappId } });
console.log('----------------> autoR exec after 120 seconds: ', autoR)
let whatsappStatus = ["CONFLICT",
"DEPRECATED_VERSION",
"OPENING",
"PROXYBLOCK",
"SMB_TOS_BLOCK",
"TIMEOUT",
"TOS_BLOCK",
"UNLAUNCHED",
"UNPAIRED",
"UNPAIRED_IDLE"]
if (_whatsapp?.status) {
if (whatsappStatus.includes(_whatsapp.status)) {
await autoRestore(autoR.whatsappId, 'auto_monit')
}
}
}
}
}, 120000);
}
} 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 {
const wbot = await initWbot(whatsapp, backupSession);
wbotMessageListener(wbot);
wbotMonitor(wbot, whatsapp);
} catch (err) {
logger.error(`${err}`);
}
};