From 74f38a82cf98641308858ac8bc067b14078171ad Mon Sep 17 00:00:00 2001 From: adriano Date: Wed, 16 Nov 2022 10:23:14 -0300 Subject: [PATCH] =?UTF-8?q?Implementa=C3=A7=C3=A3o=20de=20reestore=20autom?= =?UTF-8?q?atico=20para=20quando=20a=20sess=C3=A3o=20estiver=20conectada?= =?UTF-8?q?=20e=20n=C3=A3o=20envia=20mensagem?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/src/controllers/WhatsAppController.ts | 3 ++ .../controllers/WhatsAppSessionController.ts | 15 +++++- backend/src/helpers/RestartWhatsSession.ts | 8 +-- .../src/helpers/SetTicketMessagesAsRead.ts | 32 ++++++------ .../src/helpers/TrySendMessageMultiSession.ts | 49 ++++++++++++++++++ backend/src/libs/wbot.ts | 7 ++- .../WbotServices/SendWhatsAppMessage.ts | 50 +++++++++++++++++-- .../WbotServices/wbotMessageListener.ts | 36 ++++++------- 8 files changed, 152 insertions(+), 48 deletions(-) create mode 100644 backend/src/helpers/TrySendMessageMultiSession.ts diff --git a/backend/src/controllers/WhatsAppController.ts b/backend/src/controllers/WhatsAppController.ts index 253714d..504edfa 100644 --- a/backend/src/controllers/WhatsAppController.ts +++ b/backend/src/controllers/WhatsAppController.ts @@ -123,6 +123,9 @@ export const remove = async ( removeDir(path.join(process.cwd(), '.wwebjs_auth', `session-bd_${whatsappId}`)) + removeDir(path.join(process.cwd(), '.wwebjs_auth','sessions', `session-bd_${whatsappId}`)) + + removeWbot(+whatsappId); const io = getIO(); diff --git a/backend/src/controllers/WhatsAppSessionController.ts b/backend/src/controllers/WhatsAppSessionController.ts index 6cd2317..7f0392f 100644 --- a/backend/src/controllers/WhatsAppSessionController.ts +++ b/backend/src/controllers/WhatsAppSessionController.ts @@ -1,5 +1,5 @@ import { Request, Response } from "express"; -import { getWbot } from "../libs/wbot"; +import { getWbot, removeWbot } from "../libs/wbot"; import { removeDir } from "../helpers/DeleteDirectory"; import ShowWhatsAppService from "../services/WhatsappService/ShowWhatsAppService"; import { StartWhatsAppSession } from "../services/WbotServices/StartWhatsAppSession"; @@ -56,10 +56,21 @@ const remove = async (req: Request, res: Response): Promise => { const { whatsappId } = req.params; const whatsapp = await ShowWhatsAppService(whatsappId); - const wbot = getWbot(whatsapp.id); + const wbot = getWbot(whatsapp.id); await wbot.logout(); + + // TEST DEL + // removeWbot(+whatsapp.id) + + // await removeDir(path.join(process.cwd(), '.wwebjs_auth', 'sessions', `session-bd_${whatsappId}`)) + + // console.log('REMOVEU!!!!!!!!!!!!!!!!!!!!!') + + // + + return res.status(200).json({ message: "Session disconnected." }); }; diff --git a/backend/src/helpers/RestartWhatsSession.ts b/backend/src/helpers/RestartWhatsSession.ts index 1864152..a1feaf6 100644 --- a/backend/src/helpers/RestartWhatsSession.ts +++ b/backend/src/helpers/RestartWhatsSession.ts @@ -17,8 +17,8 @@ export const restartWhatsSession = async (whatsapp: Whatsapp, backupSession: boo const sourcePath = path.join(__dirname, `../../.wwebjs_auth/sessions/`, `session-bd_${whatsapp.id}`) const destPath = path.join(__dirname, `../../.wwebjs_auth/`, `session-bd_${whatsapp.id}`) - console.log('================sourcePath: ', sourcePath) - console.log('================destPath: ', destPath) + console.log('================> sourcePath: ', sourcePath) + console.log('================> destPath: ', destPath) removeWbot(whatsapp.id) @@ -34,6 +34,8 @@ export const restartWhatsSession = async (whatsapp: Whatsapp, backupSession: boo console.log('RESTARTING SESSION...') - await StartWhatsAppSession(whatsapp, backupSession); + // await StartWhatsAppSession(whatsapp, backupSession); + + setTimeout(() => StartWhatsAppSession(whatsapp, backupSession), 2000); } \ No newline at end of file diff --git a/backend/src/helpers/SetTicketMessagesAsRead.ts b/backend/src/helpers/SetTicketMessagesAsRead.ts index 326ca86..e880336 100644 --- a/backend/src/helpers/SetTicketMessagesAsRead.ts +++ b/backend/src/helpers/SetTicketMessagesAsRead.ts @@ -12,6 +12,7 @@ import { splitDateTime } from "./SplitDateTime"; import { format } from "date-fns"; import ptBR from 'date-fns/locale/pt-BR'; +import ListWhatsAppsNumber from "../services/WhatsappService/ListWhatsAppsNumber"; const SetTicketMessagesAsRead = async (ticket: Ticket): Promise => { await Message.update( @@ -26,39 +27,38 @@ const SetTicketMessagesAsRead = async (ticket: Ticket): Promise => { await ticket.update({ unreadMessages: 0 }); - try { + try { - const wbot = await GetTicketWbot(ticket); + const wbot = await GetTicketWbot(ticket); // test del // throw new Error('Throw makes it go boom!') // - + await wbot.sendSeen(`${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us`); } catch (err) { - logger.warn( - `Could not mark messages as read. Maybe whatsapp session disconnected? Err: ${err}` - ); - //Solução para contornar erro de sessão - if ((`${err}`).includes("Evaluation failed: r") && ticket.whatsappId) { + logger.warn(`Could not mark messages as read. Maybe whatsapp session disconnected? Err: ${err}`); + + //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`) - const dateToday = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR }))) - const whatsapp = await ShowWhatsAppService(ticket.whatsappId); + const whatsapp = await ShowWhatsAppService(ticket.whatsappId); + + if (whatsapp && whatsapp.status == 'CONNECTED') { - 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)=>{}); + + fs.writeFile(`${sourcePath}/${timestamp}_SetTicketMessagesAsRead.txt`, `Whatsapp id: ${whatsapp.id} \nDate: ${dateToday.fullDate} ${dateToday.fullTime} \nFile: SetTicketMessagesAsRead.ts \nError: ${err}`, (error) => { }); await restartWhatsSession(whatsapp) - + } } diff --git a/backend/src/helpers/TrySendMessageMultiSession.ts b/backend/src/helpers/TrySendMessageMultiSession.ts new file mode 100644 index 0000000..0a201ea --- /dev/null +++ b/backend/src/helpers/TrySendMessageMultiSession.ts @@ -0,0 +1,49 @@ + +import Ticket from "../models/Ticket"; +import ListWhatsAppsNumber from "../services/WhatsappService/ListWhatsAppsNumber"; +import GetTicketWbot from "./GetTicketWbot"; + +const sendMessageMultiSession = async (ticket: Ticket, body?: any, quotedMsgSerializedId?: any, sendSeen?: boolean) => { + + let sentMessage: any = '' + + const listWhatsapp: any = await ListWhatsAppsNumber(ticket.whatsappId, 'CONNECTED') + + if (listWhatsapp.length > 1) { + + for (let w = 0; w < listWhatsapp.length; w++) { + + if(listWhatsapp[w].id == ticket.whatsappId) continue + + try { + + console.log('CHANGE THE WHATSAPP SESSION ID: ', listWhatsapp[w].id) + + await ticket.update({ whatsappId: listWhatsapp[w].id }) + + const wbot = await GetTicketWbot(ticket); + + if (sendSeen) { + + await wbot.sendSeen(`${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us`); + + } + else if (body) { + + sentMessage = await wbot.sendMessage(`${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us`, body, { quotedMessageId: quotedMsgSerializedId, linkPreview: false }); + + } + + break + + } catch (error) { + console.log('Cannot send send the message using the whatsapp id: ', listWhatsapp[w].id, ' | error: ', error) + } + + } + } + + return sentMessage +}; + +export default sendMessageMultiSession; diff --git a/backend/src/libs/wbot.ts b/backend/src/libs/wbot.ts index c3f914e..58e0e54 100644 --- a/backend/src/libs/wbot.ts +++ b/backend/src/libs/wbot.ts @@ -160,7 +160,7 @@ export const initWbot = async (whatsapp: Whatsapp, backupSessionRestore: boolean - console.log(`>>>>>>>>>>>>>>>>>>>>>>>>>.. BACKUP SESSION whatsapp.id ${whatsapp.id} | backupSession: ${backupSession}`) + console.log(`>>>>>>>>>>>>>>>>>>>>>>>>> BACKUP SESSION whatsapp.id ${whatsapp.id} | backupSession: ${backupSession}`) const whatsIndex = backupSession.findIndex((id: number) => id === +whatsapp.id); @@ -192,7 +192,7 @@ export const initWbot = async (whatsapp: Whatsapp, backupSessionRestore: boolean console.log(` COPIOU backup whatsapp.id ---------------------------------->${whatsapp.id}`) - }, 55000); + }, 90000); console.log(' PASSOU NO TIMEOUT whatsapp.id: ',whatsapp.id) @@ -210,6 +210,9 @@ export const initWbot = async (whatsapp: Whatsapp, backupSessionRestore: boolean export const getWbot = (whatsappId: number): Session => { const sessionIndex = sessions.findIndex(s => s.id === whatsappId); + console.log('----------> sessionIndex: ', sessionIndex, ' | whatasappId: ', whatsappId) + console.log('----------> sessions: ',sessions.map(s => s.id)) + if (sessionIndex === -1) { throw new AppError("ERR_WAPP_NOT_INITIALIZED"); } diff --git a/backend/src/services/WbotServices/SendWhatsAppMessage.ts b/backend/src/services/WbotServices/SendWhatsAppMessage.ts index c274601..b787d44 100644 --- a/backend/src/services/WbotServices/SendWhatsAppMessage.ts +++ b/backend/src/services/WbotServices/SendWhatsAppMessage.ts @@ -16,6 +16,12 @@ import { deleteTicketsByContactsCache, updateTicketCacheByTicketId } from '../.. import ListWhatsAppsNumber from "../WhatsappService/ListWhatsAppsNumber"; import { getWbot } from "../../libs/wbot"; +import { json } from "sequelize/types"; + +import sendMessageMultiSession from "../../helpers/TrySendMessageMultiSession"; +import { restartWhatsSession } from "../../helpers/RestartWhatsSession"; + + interface Request { body: string; @@ -35,16 +41,17 @@ const SendWhatsAppMessage = async ({ } //TEST DEL - + // const whatsapp = await ShowWhatsAppService(33); // const wbot2 = getWbot(whatsapp.id); // await wbot2.logout(); - + // - let whatsapps:any + + let whatsapps: any const listWhatsapp = await ListWhatsAppsNumber(ticket.whatsappId, 'CONNECTED') @@ -64,7 +71,13 @@ const SendWhatsAppMessage = async ({ } - if (listWhatsapp.length == 0 || whatsapps !='CONNECTED') { + + + console.log('3 --------> ticket.whatsappId: ', ticket.whatsappId) + + + + if (listWhatsapp.length == 0 || (whatsapps && whatsapps.status != 'CONNECTED')) { whatsapps = await wbotByUserQueue(ticket.userId) @@ -87,6 +100,9 @@ const SendWhatsAppMessage = async ({ const wbot = await GetTicketWbot(ticket); + console.log('4 --------> ticket.whatsappId: ', ticket.whatsappId) + + try { const sentMessage = await wbot.sendMessage(`${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us`, body, { quotedMessageId: quotedMsgSerializedId, linkPreview: false }); @@ -96,6 +112,32 @@ const SendWhatsAppMessage = async ({ return sentMessage; } catch (err) { + + const whatsapp = await ShowWhatsAppService(ticket.whatsappId); + + if (whatsapp.status != 'RESTORING') { + + console.log('THE WHATSAAP ID: ', whatsapp.id, ' WILL BE RESTORED SOON!') + + await whatsapp.update({ + status: "RESTORING", + }); + setTimeout(() => restartWhatsSession(whatsapp, true), 90000); + } + + + + const sentMessage = await sendMessageMultiSession(ticket, body, quotedMsgSerializedId) + + if (sentMessage.length > 0) { + + 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"); } }; diff --git a/backend/src/services/WbotServices/wbotMessageListener.ts b/backend/src/services/WbotServices/wbotMessageListener.ts index 4c59268..9e09c02 100644 --- a/backend/src/services/WbotServices/wbotMessageListener.ts +++ b/backend/src/services/WbotServices/wbotMessageListener.ts @@ -369,30 +369,24 @@ const handleMessage = async ( wbot: Session ): Promise => { - // TEST DEL MULTI SESSION + // TEST DEL MULTI SESSION - if (!msg.id.fromMe) { + + let index = lst.findIndex((x: any) => x.id == msg.id.id) + + console.log('INDEX: ', index) + + if (index == -1) { + + lst.push({ id: msg.id.id }) + + } + else { + console.log('IGNORED ID: ', msg.id.id) + return } - // let index = lst.findIndex((x: any) => x.id == msg.id.id) - - // console.log('INDEX: ', index) - - // if (index == -1) { - - // lst.push({id: msg.id.id}) - - // } - // else{ - // console.log('IGNORED ID: ', msg.id.id) - // return - // } - - // console.log('PASSOU.................................FROM: ', msg.from.split("@")[0], ' | ID: ', msg.id.id) - - - - + console.log('PASSOU.................................FROM: ', msg.from.split("@")[0], ' | ID: ', msg.id.id) // const contact_message = await getLastId(`contact_message:5517988310949`)