Implentação GC e pre envio apos conexao das sessões para contornar bug

pull/21/head
adriano 2022-12-31 03:12:26 -03:00
parent 963422a7a0
commit 7d5010d9a6
6 changed files with 110 additions and 84 deletions

View File

@ -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",

View File

@ -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}`);

View File

@ -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()

View File

@ -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<void> => {
export const StartAllWhatsAppsSessions = async (): Promise<void> => {
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<void> => {
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<void> => {
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
});
}
};

View File

@ -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);
}

View File

@ -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<void> => {
// TEST DEL MULTI SESSION
_clear_lst()
let index = lst.findIndex((x: any) => x.id == msg.id.id)