Remoção do recurso de multisessoes

pull/21/head
adriano 2023-01-01 20:40:00 -03:00
parent 7d5010d9a6
commit e68c0be622
12 changed files with 278 additions and 178 deletions

View File

@ -18,6 +18,7 @@
"@sentry/node": "^5.29.2",
"@types/pino": "^6.3.4",
"bcryptjs": "^2.4.3",
"check-internet-connected": "^2.0.6",
"cookie-parser": "^1.4.5",
"cors": "^2.8.5",
"date-fns": "^2.16.1",

View File

@ -0,0 +1,69 @@
const fsPromises = require("fs/promises");
const fs = require('fs')
const checkInternetConnected = require('check-internet-connected');
import ShowWhatsAppService from "../services/WhatsappService/ShowWhatsAppService";
import { Client } from "whatsapp-web.js";
import { splitDateTime } from "../helpers/SplitDateTime";
import { format } from "date-fns";
import ptBR from 'date-fns/locale/pt-BR';
import dir from 'path';
import { getIO } from "../libs/socket";
import { number } from "yup";
const internetConnection = async (whatasappId?: string | number) => {
checkInternetConnected().then((result: any) => {
console.log('Internet successfully connected to a server: ', result);//successfully connected to a server
}).catch((ex: any) => {
console.log('Intenet connection cannot connect to a server or error occurred: ', ex); // cannot connect to a server or error occurred.
});
const config = {
timeout: 5000, //timeout connecting to each server, each try
retries: 5,//number of retries to do before failing
domain: 'https://apple.com',//the domain to check DNS record of
}
let internet_status:any = null
try {
internet_status = await checkInternetConnected(config);
} catch (error) {
console.log('Erron when trying get internet connection info: ', error)
}
console.log('INTERNET STATUS: ', internet_status)
if (whatasappId && !internet_status) {
const dateToday = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR })))
let timestamp = Math.floor(Date.now() / 1000)
const sourcePath = dir.join(process.cwd(), '.wwebjs_auth', 'sessions', 'log');
fs.writeFileSync(`${sourcePath}/${timestamp}_internet_connection_lost.txt`, `Date: ${dateToday.fullDate} ${dateToday.fullTime}`, (error: any) => { console.log(error) });
let whats = await ShowWhatsAppService(whatasappId)
await whats.update({ status: "OPENING" });
const io = getIO();
io.emit("whatsappSession", {
action: "update",
session: whats
});
}
return internet_status
}
export default internetConnection;

View File

@ -5,6 +5,7 @@ import Whatsapp from "../models/Whatsapp";
import { StartWhatsAppSession } from "../services/WbotServices/StartWhatsAppSession";
import { copyFolder } from "./CopyFolder";
import { removeDir } from "./DeleteDirectory";
// import internetConnection from "./InternetConnection";
const fsPromises = require("fs/promises");
const fs = require('fs')
@ -22,19 +23,19 @@ export const restartWhatsSession = async (whatsapp: Whatsapp, backupSession: boo
removeWbot(whatsapp.id)
await removeDir(destPath)
await removeDir(destPath)
if (fs.existsSync(sourcePath)) {
if (fs.existsSync(sourcePath)) {
// copy the good session for restars the new session
copyFolder(sourcePath, destPath)
copyFolder(sourcePath, destPath)
}
else {
console.log('Directory not found to copy: ', sourcePath)
else {
console.log('Directory not found to copy: ', sourcePath)
}
console.log('RESTARTING SESSION...')
// await StartWhatsAppSession(whatsapp, backupSession);
// await StartWhatsAppSession(whatsapp, backupSession);
setTimeout(() => StartWhatsAppSession(whatsapp, backupSession), 2000);

View File

@ -3,7 +3,7 @@ import os from 'os';
import dir from 'path';
import fs from 'fs';
import ShowWhatsAppService from '../services/WhatsappService/ShowWhatsAppService';
import { insertOrUpeateWhatsCache } from './WhatsCache';
// import { insertOrUpeateWhatsCache } from './WhatsCache';
import autoRestore from './AutoRestore';
import Whatsapp from '../models/Whatsapp';
import { getIO } from '../libs/socket';
@ -155,7 +155,7 @@ export const _restore = async (whatsapp: Whatsapp, msg_file_title: string) => {
session: whatsapp
});
await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, { status: "RESTORING", })
// await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, { status: "RESTORING", })
setTimeout(async () => await autoRestore(whatsapp.id, msg_file_title), 95000);

View File

@ -247,9 +247,9 @@ const createWhatsappIndexCache = async (hashIndex: string) => {
}
export {
loadWhatsappCache,
searchWhatsappCache,
updateWhatsappCacheById,
insertOrUpeateWhatsCache,
deleteWhatsappCache
// loadWhatsappCache,
// searchWhatsappCache,
// updateWhatsappCacheById,
// insertOrUpeateWhatsCache,
// deleteWhatsappCache
}

View File

@ -20,7 +20,7 @@ const sessions: Session[] = [];
let backupSession: any[] = []
import { insertOrUpeateWhatsCache } from "../helpers/WhatsCache";
// import { insertOrUpeateWhatsCache } from "../helpers/WhatsCache";
import { json } from "sequelize/types";
import { restartWhatsSession } from "../helpers/RestartWhatsSession";
@ -91,7 +91,7 @@ export const initWbot = async (whatsapp: Whatsapp, backupSessionRestore: boolean
logger.info("Session:", sessionName);
qrCode.generate(qr, { small: true });
await whatsapp.update({ qrcode: qr, status: "qrcode", retries: 0 });
await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, { qrcode: qr, status: "qrcode", retries: 0 })
// await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, { qrcode: qr, status: "qrcode", retries: 0 })
const sessionIndex = sessions.findIndex(s => s.id === whatsapp.id);
if (sessionIndex === -1) {
@ -117,7 +117,7 @@ export const initWbot = async (whatsapp: Whatsapp, backupSessionRestore: boolean
if (whatsapp.retries > 1) {
await whatsapp.update({ session: "", retries: 0 });
await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, { session: "", retries: 0 })
// await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, { session: "", retries: 0 })
}
const retry = whatsapp.retries;
@ -125,10 +125,10 @@ export const initWbot = async (whatsapp: Whatsapp, backupSessionRestore: boolean
status: "DISCONNECTED",
retries: retry + 1
});
await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, {
status: "DISCONNECTED",
retries: retry + 1
})
// await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, {
// status: "DISCONNECTED",
// retries: retry + 1
// })
io.emit("whatsappSession", {
action: "update",
@ -165,7 +165,7 @@ export const initWbot = async (whatsapp: Whatsapp, backupSessionRestore: boolean
retries: 0,
number: wbot.info["wid"]["user"]
});
await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, whatsapp)
// await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, whatsapp)
io.emit("whatsappSession", {
action: "update",
@ -229,32 +229,32 @@ export const initWbot = async (whatsapp: Whatsapp, backupSessionRestore: boolean
for (let i = 0; i <= 25; i++) {
// 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)])
// // console.log('Send: ', i, ' | miliseconds[Math.floor(Math.random() * miliseconds.length)]): ', miliseconds[Math.floor(Math.random() * miliseconds.length)])
try {
// try {
let stat = await wbot.getState();
// let stat = await wbot.getState();
console.log('GET WHATSAPP STATE: ', stat)
// console.log('GET WHATSAPP STATE: ', stat)
if (stat !== 'CONNECTED') break
// if (stat !== 'CONNECTED') break
await wbot.sendMessage(`5517988325936@c.us`, `*@!ping*<>${whatsapp.name}\nIndex: ${i}`);
// await wbot.sendMessage(`5517988325936@c.us`, `*@!ping*<>${whatsapp.name}\nIndex: ${i}`);
await new Promise(r => setTimeout(r, miliseconds[Math.floor(Math.random() * miliseconds.length)]));
// await new Promise(r => setTimeout(r, miliseconds[Math.floor(Math.random() * miliseconds.length)]));
} catch (error) {
// } catch (error) {
console.log(`Error on try send menssage boot from session: ${whatsapp.name}: ${error}`)
// console.log(`Error on try send menssage boot from session: ${whatsapp.name}: ${error}`)
break
// break
}
// }
}
// }
});

View File

@ -20,7 +20,7 @@ import { json } from "sequelize/types";
import sendMessageMultiSession from "../../helpers/TrySendMessageMultiSession";
import { restartWhatsSession } from "../../helpers/RestartWhatsSession";
import { insertOrUpeateWhatsCache, searchWhatsappCache } from "../../helpers/WhatsCache";
// import { insertOrUpeateWhatsCache, searchWhatsappCache } from "../../helpers/WhatsCache";
import GetDefaultWhatsApp from "../../helpers/GetDefaultWhatsApp";
import autoRestore from "../../helpers/AutoRestore";
import { _restore } from "../../helpers/RestoreControll";
@ -53,33 +53,39 @@ const SendWhatsAppMessage = async ({
}
let whatsapps: any
// let whatsapps: any
let listWhatsapp = null
// let listWhatsapp = null
listWhatsapp = await searchWhatsappCache(`${ticket.whatsappId}`, 'CONNECTED')
// listWhatsapp = await searchWhatsappCache(`${ticket.whatsappId}`, 'CONNECTED')
if (!listWhatsapp) {
listWhatsapp = await ListWhatsAppsNumber(ticket.whatsappId, 'CONNECTED')
}
// if (!listWhatsapp) {
// listWhatsapp = await ListWhatsAppsNumber(ticket.whatsappId, 'CONNECTED')
// }
if (listWhatsapp.length > 1) {
// if (listWhatsapp.length > 1) {
console.log('entrou --------------------->')
// console.log('entrou --------------------->')
const _whatsapp = listWhatsapp[Math.floor(Math.random() * listWhatsapp.length)];
await ticket.update({ whatsappId: +_whatsapp.id });
// const _whatsapp = listWhatsapp[Math.floor(Math.random() * listWhatsapp.length)];
}
// await ticket.update({ whatsappId: +_whatsapp.id });
console.log('1 --------> ticket.whatsappId: ', ticket.whatsappId)
// }
if (listWhatsapp.length == 0) {
// console.log('1 --------> ticket.whatsappId: ', ticket.whatsappId)
whatsapps = await wbotByUserQueue(ticket.userId)
const whatsapp = await Whatsapp.findByPk(ticket.whatsappId);
// console.log('whatsapp.status: ', whatsapp?.status)
// if (listWhatsapp.length == 0) {
if (whatsapp && whatsapp.status != 'CONNECTED') {
let whatsapps = await wbotByUserQueue(ticket.userId)
// console.log('whatsapps whatsapps whatsapps: ', JSON.parse(JSON.stringify(whatsapps)))
if (whatsapps.length > 0) {
@ -116,19 +122,19 @@ const SendWhatsAppMessage = async ({
return sentMessage;
} catch (err) {
const whatsapp = await ShowWhatsAppService(ticket.whatsappId);
const whatsapp = await ShowWhatsAppService(ticket.whatsappId);
await _restore(whatsapp, 'auto_send_message')
await _restore(whatsapp, 'auto_send_message')
const sentMessage = await sendMessageMultiSession(ticket, body, quotedMsgSerializedId)
// const sentMessage = await sendMessageMultiSession(ticket, body, quotedMsgSerializedId)
if (sentMessage.length > 0) {
// if (sentMessage.length > 0) {
await ticket.update({ lastMessage: body });
await updateTicketCacheByTicketId(ticket.id, { lastMessage: body, updatedAt: new Date(ticket.updatedAt).toISOString() })
return sentMessage;
// await ticket.update({ lastMessage: body });
// await updateTicketCacheByTicketId(ticket.id, { lastMessage: body, updatedAt: new Date(ticket.updatedAt).toISOString() })
// return sentMessage;
}
// }
throw new AppError("ERR_SENDING_WAPP_MSG");

View File

@ -2,7 +2,7 @@ import path from "path";
import autoRestore from "../../helpers/AutoRestore";
import { removeDir } from "../../helpers/DeleteDirectory";
import { delRestoreControllFile, getRestoreControll } from "../../helpers/RestoreControll";
import { insertOrUpeateWhatsCache, loadWhatsappCache, searchWhatsappCache } from "../../helpers/WhatsCache";
// import { insertOrUpeateWhatsCache, loadWhatsappCache, searchWhatsappCache } from "../../helpers/WhatsCache";
import { getIO } from "../../libs/socket";
import Whatsapp from "../../models/Whatsapp";
import ListWhatsAppsService from "../WhatsappService/ListWhatsAppsService";
@ -33,7 +33,7 @@ export const StartAllWhatsAppsSessions = async (): Promise<void> => {
await loadTicketsCache()
}
await loadWhatsappCache()
// await loadWhatsappCache()
await loadSchedulesCache()
createSessionDir()
@ -60,9 +60,9 @@ export const StartAllWhatsAppsSessions = async (): Promise<void> => {
}
await whatsapp.update({ status: "RESTORING" });
await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, {
status: "RESTORING",
})
// await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, {
// status: "RESTORING",
// })
const io = getIO();
io.emit("whatsappSession", {

View File

@ -4,7 +4,7 @@ import { wbotMessageListener } from "./wbotMessageListener";
import { getIO } from "../../libs/socket";
import wbotMonitor from "./wbotMonitor";
import { logger } from "../../utils/logger";
import { insertOrUpeateWhatsCache } from "../../helpers/WhatsCache";
// import { insertOrUpeateWhatsCache } from "../../helpers/WhatsCache";
import { getRestoreControll, setRestoreControll, shifRestoreControll } from "../../helpers/RestoreControll";
import ShowWhatsAppService from "../WhatsappService/ShowWhatsAppService";
@ -18,91 +18,17 @@ import { splitDateTime } from "../../helpers/SplitDateTime";
import { format } from "date-fns";
import ptBR from 'date-fns/locale/pt-BR';
import path from "path";
const fs = require('fs')
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 180 seconds: ', autoR)
let whatsappStatus = ["CONFLICT",
"DEPRECATED_VERSION",
"OPENING",
"PAIRING",
"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')
}
}
}
}
}, 180000);
}
} catch (error) {
console.log('There was an error on try execute AUTO-RESTORE: ', error)
}
await whatsapp.update({ status: "OPENING" });
const io = getIO();
io.emit("whatsappSession", {

View File

@ -60,7 +60,7 @@ import { _restore } from "../../helpers/RestoreControll";
var lst: any[] = []
// var lst: any[] = []
interface Session extends Client {
@ -370,15 +370,15 @@ const botSendMessage = (ticket: Ticket, contact: Contact, wbot: Session, msg: st
}
const _clear_lst = () => {
// const _clear_lst = () => {
if (lst.length <= 199) return
// if (lst.length <= 199) return
const chunk: any = Math.floor((lst.length / 2))
// const chunk: any = Math.floor((lst.length / 2))
lst = lst.slice(chunk, chunk + lst.length);
// lst = lst.slice(chunk, chunk + lst.length);
}
// }
const handleMessage = async (
msg: WbotMessage,
@ -387,26 +387,26 @@ const handleMessage = async (
// TEST DEL MULTI SESSION
_clear_lst()
// _clear_lst()
let index = lst.findIndex((x: any) => x.id == msg.id.id)
// let index = lst.findIndex((x: any) => x.id == msg.id.id)
console.log('INDEX: ', index)
// console.log('INDEX: ', index)
if (index == -1) {
// if (index == -1) {
lst.push({ id: msg.id.id })
// lst.push({ id: msg.id.id })
}
else {
console.log('IGNORED ID: ', msg.id.id)
// }
// else {
// console.log('IGNORED ID: ', msg.id.id)
return
}
// return
// }
// console.log('LIST OF ID MESSAGE lst: ', lst)
// // console.log('LIST OF ID MESSAGE lst: ', lst)
console.log('PASSOU.................................FROM: ', msg.from.split("@")[0], ' | ID: ', msg.id.id)
// console.log('PASSOU.................................FROM: ', msg.from.split("@")[0], ' | ID: ', msg.id.id)
if (!isValidMsg(msg)) {

View File

@ -1,12 +1,34 @@
import * as Sentry from "@sentry/node";
import { Client } from "whatsapp-web.js";
import { insertOrUpeateWhatsCache } from "../../helpers/WhatsCache";
// import { insertOrUpeateWhatsCache } from "../../helpers/WhatsCache";
import { getIO } from "../../libs/socket";
import Whatsapp from "../../models/Whatsapp";
import { logger } from "../../utils/logger";
import { StartWhatsAppSession } from "./StartWhatsAppSession";
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';
import path from "path";
const fs = require('fs')
let lstAutoRestore: any = []
interface Session extends Client {
id?: number;
}
@ -22,11 +44,86 @@ const wbotMonitor = async (
wbot.on("change_state", async newState => {
logger.info(`Monitor session: ${sessionName}, ${newState}`);
// console.log('>>>>>>>>>>>>>> change_state wbotMonitor.ts MOBILE NUMBER: ', wbot.info["wid"]["user"])
console.log('>>>>>>>>>>>>>> change_state wbotMonitor.ts MOBILE NUMBER: ', wbot.info["wid"]["user"])
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 180 seconds: ', autoR)
let whatsappStatus = ["CONFLICT",
"DEPRECATED_VERSION",
"OPENING",
"PAIRING",
"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')
}
}
}
}
console.log('888888888888888888 ENTROU NO SET TIMEOUT -----------> ')
}, 180000);
}
} catch (error) {
console.log('There was an error on try execute AUTO-RESTORE: ', error)
}
try {
await whatsapp.update({ status: newState });
await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, { status: newState })
// await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, { status: newState })
} catch (err: any) {
Sentry.captureException(err);
logger.error(err);
@ -62,7 +159,7 @@ const wbotMonitor = async (
try {
await whatsapp.update({ status: "OPENING", session: "" });
await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, { status: "OPENING", session: "" })
// await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, { status: "OPENING", session: "" })
} catch (err: any) {
Sentry.captureException(err);
logger.error(err);

View File

@ -5,7 +5,7 @@ import AppError from "../../errors/AppError";
import Whatsapp from "../../models/Whatsapp";
import ShowWhatsAppService from "./ShowWhatsAppService";
import AssociateWhatsappQueue from "./AssociateWhatsappQueue";
import { insertOrUpeateWhatsCache } from "../../helpers/WhatsCache";
// import { insertOrUpeateWhatsCache } from "../../helpers/WhatsCache";
import { getWbot } from "../../libs/wbot";
import { restartWhatsSession } from "../../helpers/RestartWhatsSession";
@ -55,7 +55,7 @@ const UpdateWhatsAppService = async ({
try {
await schema.validate({ name, status, isDefault });
} catch (err) {
} catch (err: any) {
throw new AppError(err.message);
}
@ -93,14 +93,14 @@ const UpdateWhatsAppService = async ({
isDefault
});
await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, {
name,
status,
session,
greetingMessage,
farewellMessage,
isDefault
})
// await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, {
// name,
// status,
// session,
// greetingMessage,
// farewellMessage,
// isDefault
// })
await AssociateWhatsappQueue(whatsapp, queueIds);