Conclusão do recurso de multi-sessoes

pull/21/head
adriano 2022-12-14 09:29:42 -03:00
parent 1ef86354f8
commit 464182d53b
10 changed files with 396 additions and 57 deletions

View File

@ -11,9 +11,12 @@ import path from 'path';
import { getIO } from "../libs/socket";
import { stat } from "fs";
let lstRestore: any = []
import { setRestoreControll, getRestoreControll, shifRestoreControll } from "../helpers/RestoreControll";
// import { WWebJsw } from "../../WWebJS/session-bd_40"
import autoRestore from "../helpers/AutoRestore";
// let lstRestore: any = []
const store = async (req: Request, res: Response): Promise<Response> => {
const { whatsappId } = req.params;
@ -47,9 +50,11 @@ const restart = async (req: Request, res: Response): Promise<Response> => {
const io = getIO();
if (Object.keys(req.body).length > 0) {
if (Object.keys(req.body).length > 0) {
for (let i = 0; i < lstRestore.length; i++) {
let lstRestore: any = getRestoreControll()
for (let i = 0; i < lstRestore.length; i++) {
io.emit("whatsappSession", {
action: "update",
@ -60,32 +65,10 @@ const restart = async (req: Request, res: Response): Promise<Response> => {
return res.status(200).json({});
}
const whatsapp = await ShowWhatsAppService(whatsappId);
}
restartWhatsSession(whatsapp, true)
await autoRestore(whatsappId, 'human')
lstRestore.push({ 'id': +whatsappId, 'disabled': true })
io.emit("whatsappSession", {
action: "update",
session: { 'id': +whatsappId, 'disabled': true }
});
setTimeout(() => {
let whatsapp = lstRestore.shift();
whatsapp.disabled = false
io.emit("whatsappSession", {
action: "update",
session: whatsapp
});
}, 25000);
return res.status(200).json({ message: "Starting session." });
};

View File

@ -0,0 +1,69 @@
import ShowWhatsAppService from "../services/WhatsappService/ShowWhatsAppService";
import { restartWhatsSession } from "./RestartWhatsSession";
import { getRestoreControll, setRestoreControll, shifRestoreControll } from "./RestoreControll";
const fsPromises = require("fs/promises");
const fs = require('fs')
import { getIO } from "../libs/socket";
import path from "path";
import { splitDateTime } from "./SplitDateTime";
import { format } from "date-fns";
import ptBR from 'date-fns/locale/pt-BR';
import { number } from "yargs";
const autoRestore = async (whatsappId: string | number, started_action_by: string = '') => {
const whatsapp = await ShowWhatsAppService(whatsappId);
restartWhatsSession(whatsapp, true)
const sourcePath = path.join(__dirname, `../../.wwebjs_auth/sessions/log`)
if (fs.existsSync(sourcePath)) {
let log = new Date(new Date() + 'UTC');
const dateToday = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR })))
let timestamp = Math.floor(Date.now() / 1000)
let number: any = whatsapp.number
if (!number) {
number = ''
}
fs.writeFileSync(`${sourcePath}/${timestamp}_restore_${number}_triggered_by_${started_action_by}_id_${whatsappId}.txt`, `Whatsapp id: ${whatsapp.id} \nDate: ${dateToday.fullDate} ${dateToday.fullTime}`, (error: any) => { console.log(error) });
}
setRestoreControll({ 'id': +whatsappId, 'disabled': true })
let lstRestore: any = getRestoreControll()
const io = getIO();
io.emit("whatsappSession", {
action: "update",
session: { 'id': +whatsappId, 'disabled': true }
});
setTimeout(() => {
let whatsapp = shifRestoreControll();
whatsapp.disabled = false
io.emit("whatsappSession", {
action: "update",
session: whatsapp
});
}, 25000);
}
export default autoRestore;

View File

@ -0,0 +1,72 @@
import os from 'os';
import dir from 'path';
import fs from 'fs';
import path from 'path';
// Delete a directory and its children
export const createSessionDir = () => {
console.log('process.cwd(): ', process.cwd())
const wwebjsAuthPath = dir.join(process.cwd(), '.wwebjs_auth');
const sessionPath = dir.join(process.cwd(), '.wwebjs_auth', 'sessions');
const sessionLogPath = dir.join(process.cwd(), '.wwebjs_auth', 'sessions','log');
fs.access(wwebjsAuthPath, (error) => {
// To check if the given directory
// already exists or not
if (error) {
// If current directory does not exist
// then create it
fs.mkdir(wwebjsAuthPath, (error) => {
if (error) {
console.log(error);
} else {
console.log(`wwebjs_auth Directory created successfully !!!`);
}
});
} else {
console.log("wwebjs_auth Directory already exists !!");
}
});
fs.access(sessionPath, (error) => {
// To check if the given directory
// already exists or not
if (error) {
// If current directory does not exist
// then create it
fs.mkdir(sessionPath, (error) => {
if (error) {
console.log(error);
} else {
console.log(`sessions Directory created successfully !!!`);
}
});
} else {
console.log("sessions Directory already exists !!");
}
});
fs.access(sessionLogPath, (error) => {
// To check if the given directory
// already exists or not
if (error) {
// If current directory does not exist
// then create it
fs.mkdir(sessionLogPath, (error) => {
if (error) {
console.log(error);
} else {
console.log(`log Directory created successfully !!!`);
}
});
} else {
console.log("log Directory already exists !!");
}
});
}

View File

@ -0,0 +1,135 @@
import os from 'os';
import dir from 'path';
import fs from 'fs';
export const setRestoreControll = (obj: object) => {
const restoreInfoFile = dir.join(os.tmpdir(), `restoreInfo.json`);
try {
if (fs.existsSync(restoreInfoFile)) {
if (Array.isArray(obj)) {
fs.writeFileSync(restoreInfoFile, JSON.stringify(obj), "utf8");
}
else {
const restoreInfo = fs.readFileSync(restoreInfoFile, { encoding: 'utf8', flag: 'r' });
let lstRestore: any = JSON.parse(restoreInfo)
lstRestore.push(obj)
fs.writeFileSync(restoreInfoFile, JSON.stringify(lstRestore), "utf8");
}
} else {
console.log('restoreInfo.json file not found! It will be created.');
if (Array.isArray(obj)) {
fs.writeFileSync(restoreInfoFile, JSON.stringify(obj), "utf8");
}
else {
fs.writeFileSync(restoreInfoFile, JSON.stringify([obj]), "utf8");
}
}
} catch (error) {
console.log('There was an error on try to read the restoreInfo.json file: ', error)
}
}
export const shifRestoreControll = () => {
const restoreInfoFile = dir.join(os.tmpdir(), `restoreInfo.json`);
try {
if (fs.existsSync(restoreInfoFile)) {
const restoreInfo = fs.readFileSync(restoreInfoFile, { encoding: 'utf8', flag: 'r' });
let lstRestore: any = JSON.parse(restoreInfo)
let whatsapp: any = lstRestore.shift()
fs.writeFileSync(restoreInfoFile, JSON.stringify(lstRestore), "utf8");
return whatsapp
}
} catch (error) {
console.log('There was an error on try to read the restoreInfo.json file: ', error)
}
return {}
}
export const delRestoreControllFile = () => {
const restoreInfoFile = dir.join(os.tmpdir(), `restoreInfo.json`);
try {
if (fs.existsSync(restoreInfoFile)) {
fs.unlinkSync(restoreInfoFile)
} else {
console.log('restoreInfo.json file not found!');
}
} catch (error) {
console.log('There was an error on try delete the restoreInfo.json file: ', error)
}
}
export const getRestoreControll = () => {
const restoreInfoFile = dir.join(os.tmpdir(), `restoreInfo.json`);
try {
if (fs.existsSync(restoreInfoFile)) {
const restoreInfo = fs.readFileSync(restoreInfoFile, { encoding: 'utf8', flag: 'r' });
let lstRestore: any = JSON.parse(restoreInfo)
return lstRestore
} else {
console.log('restoreInfo.json file not found!');
}
} catch (error) {
console.log('There was an error on try to read the restoreInfo.json file: ', error)
}
return []
}

View File

@ -44,7 +44,7 @@ const SetTicketMessagesAsRead = async (ticket: Ticket): Promise<void> => {
//Solução para contornar erro de sessão
if ((`${err}`).includes("Evaluation failed: r") && ticket.whatsappId) {
const sourcePath = path.join(__dirname, `../../.wwebjs_auth/sessions`)
const sourcePath = path.join(__dirname, `../../.wwebjs_auth/sessions/log`)
const dateToday = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR })))
@ -52,12 +52,11 @@ const SetTicketMessagesAsRead = async (ticket: Ticket): Promise<void> => {
if (whatsapp && whatsapp.status == 'CONNECTED') {
let timestamp = Math.floor(Date.now() / 1000)
fs.writeFile(`${sourcePath}/${timestamp}_SetTicketMessagesAsRead.txt`, `Whatsapp id: ${whatsapp.id} \nDate: ${dateToday.fullDate} ${dateToday.fullTime} \nFile: SetTicketMessagesAsRead.ts \nError: ${err}`, (error) => { });
await restartWhatsSession(whatsapp)
// await restartWhatsSession(whatsapp)
}

View File

@ -120,7 +120,7 @@ async function searchWhatsappCache(id: string, status: string) {
return []
}
console.log('NUMBER_CACHED: ', number_cache)
// console.log('NUMBER_CACHED: ', number_cache)
// @x:foo @y:bar

View File

@ -10,6 +10,8 @@ import { startWhoIsOnlineMonitor } from "./helpers/WhoIsOnlineMonitor"
import { loadTicketsCache, flushCache, cacheSize } from './helpers/TicketCache'
import { loadContactsCache } from './helpers/ContactsCache'
import { loadWhatsappCache } from './helpers/WhatsCache'
import { delRestoreControllFile } from "./helpers/RestoreControll";
import { createSessionDir } from "./helpers/CreateSessionDir";
const server = app.listen(process.env.PORT, () => {
logger.info(`Server started on port: ${process.env.PORT}`);
@ -32,9 +34,11 @@ gracefulShutdown(server);
await loadTicketsCache()
await loadWhatsappCache()
}
})()
createSessionDir()
delRestoreControllFile()
startSchedulingMonitor(5000)
startWhoIsOnlineMonitor(3000)

View File

@ -22,6 +22,7 @@ import sendMessageMultiSession from "../../helpers/TrySendMessageMultiSession";
import { restartWhatsSession } from "../../helpers/RestartWhatsSession";
import { insertOrUpeateWhatsCache, searchWhatsappCache } from "../../helpers/WhatsCache";
import GetDefaultWhatsApp from "../../helpers/GetDefaultWhatsApp";
import autoRestore from "../../helpers/AutoRestore";
@ -51,17 +52,17 @@ const SendWhatsAppMessage = async ({
let whatsapps: any
//TEST DEL
// const defaultWhatsapp = await GetDefaultWhatsApp();
// console.log('DEFAULT WHATSAPP: ', JSON.parse(JSON.stringify(defaultWhatsapp)))
let listWhatsapp = null
listWhatsapp = await searchWhatsappCache(`${ticket.whatsappId}`, 'CONNECTED')
if(!listWhatsapp){
if (!listWhatsapp) {
listWhatsapp = await ListWhatsAppsNumber(ticket.whatsappId, 'CONNECTED')
}
@ -73,15 +74,15 @@ const SendWhatsAppMessage = async ({
console.log('entrou --------------------->')
const _whatsapp = listWhatsapp[Math.floor(Math.random() * listWhatsapp.length)];
const _whatsapp = listWhatsapp[Math.floor(Math.random() * listWhatsapp.length)];
await ticket.update({ whatsappId: +_whatsapp.id });
}
}
console.log('1 --------> ticket.whatsappId: ', ticket.whatsappId)
console.log('1 --------> ticket.whatsappId: ', ticket.whatsappId)
if (listWhatsapp.length == 0) {
if (listWhatsapp.length == 0) {
whatsapps = await wbotByUserQueue(ticket.userId)
@ -102,13 +103,13 @@ const SendWhatsAppMessage = async ({
}
//
//
// const listWhatsapp = await ListWhatsAppsNumber(ticket.whatsappId, 'CONNECTED')
// if (listWhatsapp.length > 1) {
@ -186,11 +187,10 @@ const SendWhatsAppMessage = async ({
status: "RESTORING",
})
setTimeout(() => restartWhatsSession(whatsapp, true), 90000);
// setTimeout(() => restartWhatsSession(whatsapp, true), 90000);
setTimeout(async () => await autoRestore(whatsapp.id, 'auto_send_message'), 95000);
}
const sentMessage = await sendMessageMultiSession(ticket, body, quotedMsgSerializedId)
if (sentMessage.length > 0) {

View File

@ -6,15 +6,96 @@ import wbotMonitor from "./wbotMonitor";
import { logger } from "../../utils/logger";
import { insertOrUpeateWhatsCache } from "../../helpers/WhatsCache";
export const StartWhatsAppSession = async (whatsapp: Whatsapp, backupSession: boolean = false): Promise<void> => {
await whatsapp.update({ status: "OPENING" });
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 = []
export const StartWhatsAppSession = async (whatsapp: Whatsapp, backupSession: boolean = false): Promise<void> => {
await whatsapp.update({ status: "OPENING" });
console.log('kkkkkkkkkkkkkxxxxxxxxxxxxxxxxxx')
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('kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk: ', 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(' ACONTECENDO RESTORING autoR: ', autoR)
continue
}
const _whatsapp = await Whatsapp.findOne({ where: { id: autoR.whatsappId } });
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')
}
}
}
}
}, 20000);
}
} catch (error) {
console.log('There was an error on try execute AUTO-RESTORE: ', error)
}
const io = getIO();
io.emit("whatsappSession", {
action: "update",

View File

@ -879,24 +879,20 @@ const handleMessage = async (
//Solução para contornar erro de sessão
if ((`${err}`).includes("Evaluation failed: r")) {
const sourcePath = path.join(__dirname, `../../../.wwebjs_auth/sessions`)
const sourcePath = path.join(__dirname, `../../../.wwebjs_auth/sessions/log`)
let log = new Date(new Date() + 'UTC');
const dateToday = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR })))
const whatsapp = await ShowWhatsAppService(wbot.id!);
if (whatsapp.status == 'CONNECTED') {
if (whatsapp.status == 'CONNECTED') {
let timestamp = Math.floor(Date.now() / 1000)
fs.writeFile(`${sourcePath}/${timestamp}_wbotMessageListener.txt`, `Whatsapp id: ${whatsapp.id} \nDate: ${dateToday.fullDate} ${dateToday.fullTime} \nFile: wbotMessageListener.ts \nError: ${err}`, (error) => { });
await restartWhatsSession(whatsapp)
// await restartWhatsSession(whatsapp)
}