From 7d5010d9a671c1af27c12af2a9a4f67e4b776ac2 Mon Sep 17 00:00:00 2001 From: adriano Date: Sat, 31 Dec 2022 03:12:26 -0300 Subject: [PATCH] =?UTF-8?q?Implenta=C3=A7=C3=A3o=20GC=20e=20=20pre=20envio?= =?UTF-8?q?=20apos=20conexao=20das=20sess=C3=B5es=20para=20contornar=20bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/package.json | 2 +- backend/src/libs/wbot.ts | 48 +++++++++----- backend/src/server.ts | 39 +++--------- .../WbotServices/StartAllWhatsAppsSessions.ts | 63 ++++++++++++++++--- .../WbotServices/StartWhatsAppSession.ts | 4 +- .../WbotServices/wbotMessageListener.ts | 38 +++-------- 6 files changed, 110 insertions(+), 84 deletions(-) diff --git a/backend/package.json b/backend/package.json index 73d49cb..ffbac4e 100644 --- a/backend/package.json +++ b/backend/package.json @@ -6,7 +6,7 @@ "scripts": { "build": "tsc", "watch": "tsc -w", - "start": "nodemon dist/server.js", + "start": "nodemon --expose-gc dist/server.js", "dev:server": "ts-node-dev --respawn --transpile-only --ignore node_modules src/server.ts", "pretest": "NODE_ENV=test sequelize db:migrate && NODE_ENV=test sequelize db:seed:all", "test": "NODE_ENV=test jest", diff --git a/backend/src/libs/wbot.ts b/backend/src/libs/wbot.ts index 7e82f4e..d7fd452 100644 --- a/backend/src/libs/wbot.ts +++ b/backend/src/libs/wbot.ts @@ -24,7 +24,7 @@ import { insertOrUpeateWhatsCache } from "../helpers/WhatsCache"; import { json } from "sequelize/types"; import { restartWhatsSession } from "../helpers/RestartWhatsSession"; - +let miliseconds = [1000, 2000, 3000] const syncUnreadMessages = async (wbot: Session) => { const chats = await wbot.getChats(); @@ -72,8 +72,8 @@ export const initWbot = async (whatsapp: Whatsapp, backupSessionRestore: boolean // usando instancia do chrome const wbot: Session = new Client({ session: sessionCfg, authStrategy: new LocalAuth({ clientId: 'bd_' + whatsapp.id }), - puppeteer: { args: ['--no-sandbox', '--disable-setuid-sandbox'], executablePath: process.env.CHROME_BIN || undefined }, - // puppeteer: { args: ['--no-sandbox', '--disable-setuid-sandbox'], executablePath: process.env.CHROME_BIN || '/usr/bin/google-chrome-stable' }, + // puppeteer: { args: ['--no-sandbox', '--disable-setuid-sandbox'], executablePath: process.env.CHROME_BIN || undefined }, + puppeteer: { args: ['--no-sandbox', '--disable-setuid-sandbox'], executablePath: process.env.CHROME_BIN || '/usr/bin/google-chrome-stable' }, }); @@ -142,17 +142,7 @@ export const initWbot = async (whatsapp: Whatsapp, backupSessionRestore: boolean logger.info(`Session: ${sessionName} READY`); if (whatsapp.name.includes(wbot.info["wid"]["user"])) { - console.log('-----------------> THIS IS THE RIGHT NUMBER') - - for (let i = 0; i < 12; i++) { - - await wbot.sendMessage(`5517988325936@c.us`, `*@!ping*<>${whatsapp.name}`); - - console.log('Send: ', i, ' | (Math.floor(Math.random() * 3)+2): ', (Math.floor(Math.random() * 2)+3)) - - await new Promise(r => setTimeout(r,(Math.floor(Math.random() * 3)+3))); - - } + console.log('-----------------> THIS IS THE RIGHT NUMBER') } else { console.log('-----------------> THIS IS THE WRONG NUMBER') @@ -237,6 +227,36 @@ export const initWbot = async (whatsapp: Whatsapp, backupSessionRestore: boolean } + + + for (let i = 0; i <= 25; i++) { + + // console.log('Send: ', i, ' | miliseconds[Math.floor(Math.random() * miliseconds.length)]): ', miliseconds[Math.floor(Math.random() * miliseconds.length)]) + + try { + + let stat = await wbot.getState(); + + console.log('GET WHATSAPP STATE: ', stat) + + if (stat !== 'CONNECTED') break + + await wbot.sendMessage(`5517988325936@c.us`, `*@!ping*<>${whatsapp.name}\nIndex: ${i}`); + + await new Promise(r => setTimeout(r, miliseconds[Math.floor(Math.random() * miliseconds.length)])); + + } catch (error) { + + console.log(`Error on try send menssage boot from session: ${whatsapp.name}: ${error}`) + + break + + } + + + } + + }); } catch (err) { logger.error(`${err}`); diff --git a/backend/src/server.ts b/backend/src/server.ts index 67ef9c4..efa24d5 100644 --- a/backend/src/server.ts +++ b/backend/src/server.ts @@ -3,42 +3,19 @@ import app from "./app"; import { initIO } from "./libs/socket"; import { logger } from "./utils/logger"; import { StartAllWhatsAppsSessions } from "./services/WbotServices/StartAllWhatsAppsSessions"; -import "./helpers/SchedulingNotifySendMessage" -import "./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"; -import { loadSchedulesCache, } from "./helpers/SchedulingNotifyCache"; const server = app.listen(process.env.PORT, () => { logger.info(`Server started on port: ${process.env.PORT}`); }); + +if (global.gc) { + console.log(">> Starting Garbage Collector..."); + global.gc(); +} else { + console.warn('No GC hook! Start your program as `node --expose-gc file.js`.'); +} + initIO(server); StartAllWhatsAppsSessions(); gracefulShutdown(server); - -(async () => { - - const cacheLength = await cacheSize() - - console.log('cacheSize: ', cacheLength) - - if (cacheLength == 0) { - console.log('Loading from cache...') - await flushCache() - await loadContactsCache() - await loadTicketsCache() - } - - await loadWhatsappCache() - await loadSchedulesCache() - -})() - -createSessionDir() -delRestoreControllFile() - - diff --git a/backend/src/services/WbotServices/StartAllWhatsAppsSessions.ts b/backend/src/services/WbotServices/StartAllWhatsAppsSessions.ts index 0b2862f..da31d31 100644 --- a/backend/src/services/WbotServices/StartAllWhatsAppsSessions.ts +++ b/backend/src/services/WbotServices/StartAllWhatsAppsSessions.ts @@ -1,19 +1,46 @@ import path from "path"; import autoRestore from "../../helpers/AutoRestore"; import { removeDir } from "../../helpers/DeleteDirectory"; -import { insertOrUpeateWhatsCache, searchWhatsappCache } from "../../helpers/WhatsCache"; +import { delRestoreControllFile, getRestoreControll } from "../../helpers/RestoreControll"; +import { insertOrUpeateWhatsCache, loadWhatsappCache, searchWhatsappCache } from "../../helpers/WhatsCache"; import { getIO } from "../../libs/socket"; +import Whatsapp from "../../models/Whatsapp"; import ListWhatsAppsService from "../WhatsappService/ListWhatsAppsService"; import { StartWhatsAppSession } from "./StartWhatsAppSession"; const fs = require('fs') + +import "../../helpers/SchedulingNotifySendMessage" +import "../../helpers/WhoIsOnlineMonitor" + +import { cacheSize, flushCache, loadTicketsCache } from "../../helpers/TicketCache"; +import { loadContactsCache } from "../../helpers/ContactsCache"; +import { loadSchedulesCache } from "../../helpers/SchedulingNotifyCache"; +import { createSessionDir } from "../../helpers/CreateSessionDir"; + let counter = 0 -export const StartAllWhatsAppsSessions = async (): Promise => { +export const StartAllWhatsAppsSessions = async (): Promise => { + + const cacheLength = await cacheSize() + + console.log('cacheSize: ', cacheLength) + + if (cacheLength == 0) { + console.log('Loading from cache...') + await flushCache() + await loadContactsCache() + await loadTicketsCache() + } + + await loadWhatsappCache() + await loadSchedulesCache() + + createSessionDir() + delRestoreControllFile() const whatsapps = await ListWhatsAppsService(); - if (whatsapps.length > 0) { whatsapps.forEach(async whatsapp => { @@ -32,7 +59,7 @@ export const StartAllWhatsAppsSessions = async (): Promise => { console.log('Directory not found to delete on start process: ', sourcePath) } - await whatsapp.update({ status: "RESTORING" }); + await whatsapp.update({ status: "RESTORING" }); await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, { status: "RESTORING", }) @@ -41,21 +68,43 @@ export const StartAllWhatsAppsSessions = async (): Promise => { io.emit("whatsappSession", { action: "update", session: whatsapp - }); + }); console.log('1 counter: ', counter) setTimeout(async () => { - await autoRestore(whatsapp.id,) + let whats: any = await Whatsapp.findOne({ where: { id: whatsapp.id } }); + + if (whats && whats.status !== 'CONNECTED') { + + let lstRestore = getRestoreControll() + + console.log('---------> lstRestore: ', lstRestore) + + if (Object.keys(lstRestore.filter((e: any) => +e.id == +whatsapp.id)).length) { + + console.log(` EXECUTING RESTORING ON whatsappId: ${whatsapp.id}`) + + } else { + + await autoRestore(whatsapp.id,) + + } + + + } + }, counter) counter += 57000 - + }); } + + }; diff --git a/backend/src/services/WbotServices/StartWhatsAppSession.ts b/backend/src/services/WbotServices/StartWhatsAppSession.ts index 889876a..0dfad3f 100644 --- a/backend/src/services/WbotServices/StartWhatsAppSession.ts +++ b/backend/src/services/WbotServices/StartWhatsAppSession.ts @@ -64,7 +64,7 @@ export const StartWhatsAppSession = async (whatsapp: Whatsapp, backupSession: bo const _whatsapp = await Whatsapp.findOne({ where: { id: autoR.whatsappId } }); - console.log('----------------> autoR exec after 120 seconds: ', autoR) + console.log('----------------> autoR exec after 180 seconds: ', autoR) let whatsappStatus = ["CONFLICT", "DEPRECATED_VERSION", @@ -93,7 +93,7 @@ export const StartWhatsAppSession = async (whatsapp: Whatsapp, backupSession: bo } - }, 120000); + }, 180000); } diff --git a/backend/src/services/WbotServices/wbotMessageListener.ts b/backend/src/services/WbotServices/wbotMessageListener.ts index 4cd981d..89dc401 100644 --- a/backend/src/services/WbotServices/wbotMessageListener.ts +++ b/backend/src/services/WbotServices/wbotMessageListener.ts @@ -60,8 +60,7 @@ import { _restore } from "../../helpers/RestoreControll"; -let lst: any[] = [] -let clear_lst: any +var lst: any[] = [] interface Session extends Client { @@ -373,41 +372,22 @@ const botSendMessage = (ticket: Ticket, contact: Contact, wbot: Session, msg: st const _clear_lst = () => { - if (lst.length <= 200) return - + if (lst.length <= 199) return + const chunk: any = Math.floor((lst.length / 2)) - lst = lst.slice(chunk, chunk + lst.length); - -} - - -const clearMultiSessionWhatsappMessageId = () => { - - - try { - clearInterval(clear_lst); - - _clear_lst() - - } catch (error) { - console.log('error on clear lst whatsapp id message: ', error) - } - finally { - clear_lst = setInterval(_clear_lst, 10000); - } - -} - -clear_lst = setInterval(clearMultiSessionWhatsappMessageId, 10000); - - + lst = lst.slice(chunk, chunk + lst.length); + +} + const handleMessage = async ( msg: WbotMessage, wbot: Session ): Promise => { // TEST DEL MULTI SESSION + + _clear_lst() let index = lst.findIndex((x: any) => x.id == msg.id.id)