From 330299726d89f96d8e606d220b8a5113e83738c5 Mon Sep 17 00:00:00 2001 From: adriano Date: Sun, 11 Dec 2022 04:47:32 -0300 Subject: [PATCH] =?UTF-8?q?Finaliza=C3=A7=C3=A3o=20de=20implementa=C3=A7?= =?UTF-8?q?=C3=A3o=20do=20controle=20do=20bot=C3=A3o=20restore?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/WhatsAppSessionController.ts | 63 +++++++++--- .../src/helpers/TrySendMessageMultiSession.ts | 2 +- backend/src/helpers/WhatsCache.ts | 26 ++--- backend/src/libs/wbot.ts | 26 ++++- backend/src/routes/whatsappSessionRoutes.ts | 1 + .../WbotServices/SendWhatsAppMessage.ts | 95 ++++++++++++++----- .../WbotServices/wbotMessageListener.ts | 4 +- .../WhatsappService/UpdateWhatsAppService.ts | 16 +++- frontend/src/components/QrcodeModal/index.js | 21 +++- frontend/src/hooks/useWhatsApps/index.js | 53 ++++++++--- frontend/src/pages/Connections/index.js | 95 ++++++++++++------- frontend/src/translate/languages/en.js | 2 + frontend/src/translate/languages/es.js | 3 + frontend/src/translate/languages/pt.js | 4 + 14 files changed, 311 insertions(+), 100 deletions(-) diff --git a/backend/src/controllers/WhatsAppSessionController.ts b/backend/src/controllers/WhatsAppSessionController.ts index 7f0392f..e1fbeaa 100644 --- a/backend/src/controllers/WhatsAppSessionController.ts +++ b/backend/src/controllers/WhatsAppSessionController.ts @@ -7,7 +7,11 @@ import UpdateWhatsAppService from "../services/WhatsappService/UpdateWhatsAppSer import { restartWhatsSession } from "../helpers/RestartWhatsSession"; -import path from 'path'; +import path from 'path'; +import { getIO } from "../libs/socket"; +import { stat } from "fs"; + +let lstRestore: any = [] // import { WWebJsw } from "../../WWebJS/session-bd_40" @@ -36,17 +40,52 @@ const update = async (req: Request, res: Response): Promise => { + const restart = async (req: Request, res: Response): Promise => { - + const { whatsappId } = req.params; - console.log('FROM REQUEST WHATSAPP ID: ', whatsappId) + const io = getIO(); + if (Object.keys(req.body).length > 0) { + + for (let i = 0; i < lstRestore.length; i++) { + + io.emit("whatsappSession", { + action: "update", + session: { 'id': +lstRestore[i].id, 'disabled': true } + }); + + } + + return res.status(200).json({}); + + } + const whatsapp = await ShowWhatsAppService(whatsappId); restartWhatsSession(whatsapp, true) - //restartWhatsSession(whatsapp) + 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." }); }; @@ -56,20 +95,20 @@ 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) + // TEST DEL + // removeWbot(+whatsapp.id) - // await removeDir(path.join(process.cwd(), '.wwebjs_auth', 'sessions', `session-bd_${whatsappId}`)) + // await removeDir(path.join(process.cwd(), '.wwebjs_auth', 'sessions', `session-bd_${whatsappId}`)) + + // console.log('REMOVEU!!!!!!!!!!!!!!!!!!!!!') + + // - // console.log('REMOVEU!!!!!!!!!!!!!!!!!!!!!') - - // - return res.status(200).json({ message: "Session disconnected." }); }; diff --git a/backend/src/helpers/TrySendMessageMultiSession.ts b/backend/src/helpers/TrySendMessageMultiSession.ts index 0a201ea..ecc0069 100644 --- a/backend/src/helpers/TrySendMessageMultiSession.ts +++ b/backend/src/helpers/TrySendMessageMultiSession.ts @@ -9,7 +9,7 @@ const sendMessageMultiSession = async (ticket: Ticket, body?: any, quotedMsgSeri const listWhatsapp: any = await ListWhatsAppsNumber(ticket.whatsappId, 'CONNECTED') - if (listWhatsapp.length > 1) { + if (listWhatsapp.length > 0) { for (let w = 0; w < listWhatsapp.length; w++) { diff --git a/backend/src/helpers/WhatsCache.ts b/backend/src/helpers/WhatsCache.ts index 45ed77e..0811ea6 100644 --- a/backend/src/helpers/WhatsCache.ts +++ b/backend/src/helpers/WhatsCache.ts @@ -113,18 +113,20 @@ async function searchWhatsappCache(id: string, status: string) { if (redis.status !== 'connect') return null + + const number_cache: any = await redis.hgetall(`whatsapp:${id}`) + + if(Object.entries(number_cache).length == 0){ + return [] + } + + console.log('NUMBER_CACHED: ', number_cache) + // @x:foo @y:bar - // const response: any = await redis.call('FT.SEARCH', 'idx_whatsapp', `(@status:*${status}*) (@number:*${number}*)`, 'SORTBY', 'status', 'ASC') - - // const response: any = await redis.call('FT.SEARCH', 'idx_whatsapp', `(@id:*${id}*))`) - - const response: any = [] - - const number_cache: any = await redis.hgetall(`whatsapp:${14}`) - - console.log('NUMBER CACHED: ', number_cache) - + const response: any = await redis.call('FT.SEARCH', 'idx_whatsapp', `(@status:*${status}*) (@number:*${number_cache.number}*)`, 'SORTBY', 'status', 'ASC') + + redis.quit() @@ -175,7 +177,7 @@ const insertOrUpeateWhatsCache = async (hash:any, whatsapp: any) => { await redis.hmset(hash,JSON.parse(JSON.stringify(whatsapp))); - console.log(`${whatsapp.length} WHATSAPP INSERTED OR UPADTED IN CACHE!`) + console.log(`WHATSAPP ID ${whatsapp.id} INSERTED OR UPADTED IN CACHE!`) } @@ -232,7 +234,7 @@ const createWhatsappIndexCache = async (hashIndex: string) => { await redis.call('FT.DROPINDEX', hashIndex) } - const response = await redis.call('FT.CREATE', hashIndex, 'ON', 'HASH', 'PREFIX', '1', 'whatsapp:', 'SCHEMA','id', 'NUMERIC', 'SORTABLE', 'status', 'TEXT', 'SORTABLE', 'number', 'TEXT') + const response = await redis.call('FT.CREATE', hashIndex, 'ON', 'HASH', 'PREFIX', '1', 'whatsapp:', 'SCHEMA','id', 'NUMERIC', 'status', 'TEXT', 'SORTABLE', 'number', 'TEXT', 'SORTABLE') console.log('Whatsapp index created: ', response) diff --git a/backend/src/libs/wbot.ts b/backend/src/libs/wbot.ts index e666211..589804f 100644 --- a/backend/src/libs/wbot.ts +++ b/backend/src/libs/wbot.ts @@ -21,6 +21,8 @@ const sessions: Session[] = []; let backupSession: any[] = [] import { insertOrUpeateWhatsCache } from "../helpers/WhatsCache"; +import { json } from "sequelize/types"; +import { restartWhatsSession } from "../helpers/RestartWhatsSession"; @@ -138,8 +140,28 @@ export const initWbot = async (whatsapp: Whatsapp, backupSessionRestore: boolean wbot.on("ready", async () => { logger.info(`Session: ${sessionName} READY`); - console.log('>>>>>>>>>>>>>> ready wbot.ts MOBILE NUMBER: ', wbot.info["wid"]["user"]) - + // console.log('>>>>>>>>>>>>>> ready wbot.ts MOBILE NUMBER: ', wbot.info["wid"]["user"]) + // console.log('::::::: WHATSAPP INFO: ', JSON.parse(JSON.stringify(whatsapp))) + + if(whatsapp.name.includes(wbot.info["wid"]["user"])){ + console.log('-----------------> THIS IS THE RIGHT NUMBER') + } + else{ + console.log('-----------------> THIS IS THE WRONG NUMBER') + let read_number = wbot.info["wid"]["user"] + + await wbot.logout() + + io.emit("whatsappSession", { + action: "error", + msg: `Numero lido: ${read_number} \nEssa sessão de whatsapp foi desconectada porque o numero que esta descrito no nome dessa sessão não corresponde ao numero lido!` + }); + + // restartWhatsSession(whatsapp) + + return + } + await whatsapp.update({ status: "CONNECTED", diff --git a/backend/src/routes/whatsappSessionRoutes.ts b/backend/src/routes/whatsappSessionRoutes.ts index 8a325f2..90e551e 100644 --- a/backend/src/routes/whatsappSessionRoutes.ts +++ b/backend/src/routes/whatsappSessionRoutes.ts @@ -12,6 +12,7 @@ whatsappSessionRoutes.post( isAuth, WhatsAppSessionController.store ); + whatsappSessionRoutes.put( "/whatsappsession/:whatsappId", diff --git a/backend/src/services/WbotServices/SendWhatsAppMessage.ts b/backend/src/services/WbotServices/SendWhatsAppMessage.ts index 68d4877..3e29aaa 100644 --- a/backend/src/services/WbotServices/SendWhatsAppMessage.ts +++ b/backend/src/services/WbotServices/SendWhatsAppMessage.ts @@ -21,6 +21,7 @@ import { json } from "sequelize/types"; import sendMessageMultiSession from "../../helpers/TrySendMessageMultiSession"; import { restartWhatsSession } from "../../helpers/RestartWhatsSession"; import { insertOrUpeateWhatsCache, searchWhatsappCache } from "../../helpers/WhatsCache"; +import GetDefaultWhatsApp from "../../helpers/GetDefaultWhatsApp"; @@ -47,41 +48,40 @@ const SendWhatsAppMessage = async ({ await GetWbotMessage(ticket, quotedMsg.id); quotedMsgSerializedId = SerializeWbotMsgId(ticket, quotedMsg); } + + + let whatsapps: any //TEST DEL - let whats_number = await searchWhatsappCache(`${ticket.whatsappId}`) - console.log('---') - console.log('whats_number search: ', whats_number) - console.log('---') + // const defaultWhatsapp = await GetDefaultWhatsApp(); + // console.log('DEFAULT WHATSAPP: ', JSON.parse(JSON.stringify(defaultWhatsapp))) - let whatsapps: any + let listWhatsapp = null + + listWhatsapp = await searchWhatsappCache(`${ticket.whatsappId}`, 'CONNECTED') - const listWhatsapp = await ListWhatsAppsNumber(ticket.whatsappId, 'CONNECTED') + if(!listWhatsapp){ + listWhatsapp = await ListWhatsAppsNumber(ticket.whatsappId, 'CONNECTED') + } + + // console.log('---') + // console.log('listWhatsapp search: ', listWhatsapp) + // console.log('---') if (listWhatsapp.length > 1) { - const _whatsapp = listWhatsapp[Math.floor(Math.random() * listWhatsapp.length)]; + console.log('entrou --------------------->') - await ticket.update({ whatsappId: _whatsapp.id }); + const _whatsapp = listWhatsapp[Math.floor(Math.random() * listWhatsapp.length)]; - } - else { + await ticket.update({ whatsappId: +_whatsapp.id }); - whatsapps = await Whatsapp.findOne({ - where: { id: ticket.whatsappId }, - attributes: ['status'] - }) + } - } + console.log('1 --------> ticket.whatsappId: ', ticket.whatsappId) - - - console.log('1 --------> ticket.whatsappId: ', ticket.whatsappId) - - - - if (listWhatsapp.length == 0 || (whatsapps && whatsapps.status != 'CONNECTED')) { + if (listWhatsapp.length == 0) { whatsapps = await wbotByUserQueue(ticket.userId) @@ -102,6 +102,57 @@ const SendWhatsAppMessage = async ({ } + +// + + + + + + // const listWhatsapp = await ListWhatsAppsNumber(ticket.whatsappId, 'CONNECTED') + + // if (listWhatsapp.length > 1) { + + // const _whatsapp = listWhatsapp[Math.floor(Math.random() * listWhatsapp.length)]; + + // await ticket.update({ whatsappId: _whatsapp.id }); + + // } + // else { + + // whatsapps = await Whatsapp.findOne({ + // where: { id: ticket.whatsappId }, + // attributes: ['status'] + // }) + + // } + + + // console.log('1 --------> ticket.whatsappId: ', ticket.whatsappId) + + + + // if (listWhatsapp.length == 0 || (whatsapps && whatsapps.status != 'CONNECTED')) { + + // whatsapps = await wbotByUserQueue(ticket.userId) + + // if (whatsapps.length > 0) { + + // if (whatsapps.length > 1) { + + // await ticket.update({ whatsappId: whatsapps[+WhatsIndex(whatsapps)].id }); + + // } + // else { + + // await ticket.update({ whatsappId: whatsapps[0].id }); + + // } + + // } + + // } + const wbot = await GetTicketWbot(ticket); console.log('2 --------> send from whatsapp ticket.whatsappId: ', ticket.whatsappId) diff --git a/backend/src/services/WbotServices/wbotMessageListener.ts b/backend/src/services/WbotServices/wbotMessageListener.ts index 24470c1..0bfc460 100644 --- a/backend/src/services/WbotServices/wbotMessageListener.ts +++ b/backend/src/services/WbotServices/wbotMessageListener.ts @@ -365,9 +365,9 @@ const botSendMessage = (ticket: Ticket, contact: Contact, wbot: Session, msg: st const _clear_lst = () => { - console.log('LIST (lst.length) WHATSAPP MESSAGE ID MULTI SESSION: : ', lst.length) + console.log('WHATSAPP MESSAGE ID MULTI SESSION: ', lst.length) - if (lst.length < 800 ) return + if (lst.length < 200 ) return console.log('BEFORE lst SLICE: ', lst) diff --git a/backend/src/services/WhatsappService/UpdateWhatsAppService.ts b/backend/src/services/WhatsappService/UpdateWhatsAppService.ts index 2b4e850..6b4d3c6 100644 --- a/backend/src/services/WhatsappService/UpdateWhatsAppService.ts +++ b/backend/src/services/WhatsappService/UpdateWhatsAppService.ts @@ -6,6 +6,10 @@ import Whatsapp from "../../models/Whatsapp"; import ShowWhatsAppService from "./ShowWhatsAppService"; import AssociateWhatsappQueue from "./AssociateWhatsappQueue"; import { insertOrUpeateWhatsCache } from "../../helpers/WhatsCache"; +import { getWbot } from "../../libs/wbot"; +import { restartWhatsSession } from "../../helpers/RestartWhatsSession"; + + interface WhatsappData { name?: string; @@ -47,6 +51,8 @@ const UpdateWhatsAppService = async ({ queueIds = [] } = whatsappData; + + try { await schema.validate({ name, status, isDefault }); } catch (err) { @@ -68,8 +74,16 @@ const UpdateWhatsAppService = async ({ } } - const whatsapp = await ShowWhatsAppService(whatsappId); + const whatsapp = await ShowWhatsAppService(whatsappId); + // console.log('############## whatsapp: ', JSON.parse(JSON.stringify(whatsapp))) + + if(name && !name.includes(whatsapp.number) && whatsapp.status === 'CONNECTED'){ + + throw new AppError("ERR_WAPP_WRONG_SESSION_NAME"); + + } + await whatsapp.update({ name, status, diff --git a/frontend/src/components/QrcodeModal/index.js b/frontend/src/components/QrcodeModal/index.js index 78b75b6..dcca527 100644 --- a/frontend/src/components/QrcodeModal/index.js +++ b/frontend/src/components/QrcodeModal/index.js @@ -1,4 +1,4 @@ -import React, { useEffect, useState } from "react"; +import React, { useEffect, useState, useContext } from "react"; import QRCode from "qrcode.react"; import openSocket from "socket.io-client"; import toastError from "../../errors/toastError"; @@ -7,7 +7,12 @@ import { Dialog, DialogContent, Paper, Typography } from "@material-ui/core"; import { i18n } from "../../translate/i18n"; import api from "../../services/api"; +import { AuthContext } from "../../context/Auth/AuthContext"; + const QrcodeModal = ({ open, onClose, whatsAppId }) => { + + const { user } = useContext(AuthContext); + const [qrCode, setQrCode] = useState(""); useEffect(() => { @@ -36,12 +41,24 @@ const QrcodeModal = ({ open, onClose, whatsAppId }) => { if (data.action === "update" && data.session.qrcode === "") { onClose(); } + + if (data.action === "error") { + + console.log('user.profile: ', user.profile) + + if(user.profile === 'master'){ + + alert(data.msg) + + } + + } }); return () => { socket.disconnect(); }; - }, [whatsAppId, onClose]); + }, [whatsAppId, onClose, user.profile]); return ( diff --git a/frontend/src/hooks/useWhatsApps/index.js b/frontend/src/hooks/useWhatsApps/index.js index a0b51fd..1360ac1 100644 --- a/frontend/src/hooks/useWhatsApps/index.js +++ b/frontend/src/hooks/useWhatsApps/index.js @@ -2,6 +2,7 @@ import { useState, useEffect, useReducer } from "react"; import openSocket from "socket.io-client"; import toastError from "../../errors/toastError"; + import api from "../../services/api"; const reducer = (state, action) => { @@ -28,16 +29,39 @@ const reducer = (state, action) => { const whatsAppIndex = state.findIndex(s => s.id === whatsApp.id); if (whatsAppIndex !== -1) { - state[whatsAppIndex].status = whatsApp.status; - state[whatsAppIndex].updatedAt = whatsApp.updatedAt; - state[whatsAppIndex].qrcode = whatsApp.qrcode; - state[whatsAppIndex].retries = whatsApp.retries; + + if ('disabled' in whatsApp) { + state[whatsAppIndex].disabled = whatsApp.disabled + } + else { + state[whatsAppIndex].status = whatsApp.status; + state[whatsAppIndex].updatedAt = whatsApp.updatedAt; + state[whatsAppIndex].qrcode = whatsApp.qrcode; + state[whatsAppIndex].retries = whatsApp.retries; + } + + return [...state]; } else { return [...state]; } } + // if(action.type === "UPDATE_SESSION_RESTORE"){ + + // const whatsApp = action.payload; + + // console.log('------> whatsApp: ', whatsApp) + + // const whatsAppIndex = state.findIndex(s => s.id === whatsApp.id); + + // if (whatsAppIndex !== -1) { + // console.log('kkkkkkkkkkkkkkkkkkkkkkkkkk: ',whatsAppIndex) + + // return [...state]; + // } + // } + // if (action.type === "UPDATE_DISK_SPACE_MONIT") { // const whatsApp = action.payload; @@ -56,7 +80,7 @@ const reducer = (state, action) => { const whatsApp = action.payload; const whatsAppIndex = state.findIndex(s => s.id === whatsApp.id); - if (whatsAppIndex !== -1) { + if (whatsAppIndex !== -1) { state[whatsAppIndex].sessionSize = whatsApp.sessionSize; return [...state]; } else { @@ -84,6 +108,8 @@ const useWhatsApps = () => { const [whatsApps, dispatch] = useReducer(reducer, []); const [loading, setLoading] = useState(true); + + useEffect(() => { setLoading(true); const fetchSession = async () => { @@ -115,22 +141,21 @@ const useWhatsApps = () => { }); socket.on("whatsappSession", data => { - if (data.action === "update") { - + if (data.action === "update") { dispatch({ type: "UPDATE_SESSION", payload: data.session }); } - }); + else if (data.action === "update_restore") { + dispatch({ type: "UPDATE_SESSION_RESTORE", payload: data.session }); + } + }); socket.on("whatsappSessionMonit", data => { if (data.action === "update") { - - - dispatch({ type: "UPDATE_WHATSAPPS_SESSION_MONIT", payload: data.whatsappSessionSize }); } - }); - - + }); + + return () => { socket.disconnect(); diff --git a/frontend/src/pages/Connections/index.js b/frontend/src/pages/Connections/index.js index 2efc13d..9e968cb 100644 --- a/frontend/src/pages/Connections/index.js +++ b/frontend/src/pages/Connections/index.js @@ -114,8 +114,8 @@ const Connections = () => { const [confirmModalOpen, setConfirmModalOpen] = useState(false); const [diskSpaceInfo, setDiskSpaceInfo] = useState({}); - - + + const [disabled, setDisabled] = useState(true); const confirmationModalInitialState = { @@ -140,7 +140,9 @@ const Connections = () => { const handleRestartWhatsAppSession = async whatsAppId => { try { + await api.post(`/restartwhatsappsession/${whatsAppId}`); + } catch (err) { toastError(err); } @@ -329,6 +331,32 @@ const Connections = () => { }; + + + useEffect(() => { + + const delayDebounceFn = setTimeout(() => { + + const fetchQueries = async () => { + try { + + await api.post(`/restartwhatsappsession/0`, { params: { status: 'status' }, }); + + setDisabled(false) + + } catch (err) { + console.log(err); + } + }; + + fetchQueries(); + + }, 500); + return () => clearTimeout(delayDebounceFn); + + }, []); + + useEffect(() => { const socket = openSocket(process.env.REACT_APP_BACKEND_URL); @@ -407,37 +435,37 @@ const Connections = () => { perform="space-disk-info:show" yes={() => ( <> - - - - - Size - - - Used - - - Available - - - Use% - - - - - - - {diskSpaceInfo.size} - {diskSpaceInfo.used} - {diskSpaceInfo.available} - {diskSpaceInfo.use} - - -
-
- + + + + + Size + + + Used + + + Available + + + Use% + + + + + + + {diskSpaceInfo.size} + {diskSpaceInfo.used} + {diskSpaceInfo.available} + {diskSpaceInfo.use} + + +
+
+ )} - /> + /> @@ -533,9 +561,11 @@ const Connections = () => { role={user.profile} perform="connection-button:show" yes={() => ( + diff --git a/frontend/src/translate/languages/en.js b/frontend/src/translate/languages/en.js index 0391037..6484c5c 100644 --- a/frontend/src/translate/languages/en.js +++ b/frontend/src/translate/languages/en.js @@ -453,6 +453,8 @@ const messages = { "This color is already in use, pick another one.", ERR_WAPP_GREETING_REQUIRED: "Greeting message is required if there is more than one queue.", + ERR_WAPP_WRONG_SESSION_NAME: + "The number updated in the session name does not match the number read! To change the new number in the name disconnect the session!", }, }, }, diff --git a/frontend/src/translate/languages/es.js b/frontend/src/translate/languages/es.js index b4f7d5e..2e27e49 100644 --- a/frontend/src/translate/languages/es.js +++ b/frontend/src/translate/languages/es.js @@ -460,6 +460,9 @@ const messages = { "Este color ya está en uso, elija otro.", ERR_WAPP_GREETING_REQUIRED: "El mensaje de saludo es obligatorio cuando hay más de una cola.", + ERR_WAPP_WRONG_SESSION_NAME: + "¡El número actualizado en el nombre de la sesión no coincide con el número leído! Para cambiar el nuevo número en el nombre desconecte la sesión!", + }, }, }, diff --git a/frontend/src/translate/languages/pt.js b/frontend/src/translate/languages/pt.js index d3b7835..a92ab11 100644 --- a/frontend/src/translate/languages/pt.js +++ b/frontend/src/translate/languages/pt.js @@ -458,6 +458,10 @@ const messages = { "Esta cor já está em uso, escolha outra.", ERR_WAPP_GREETING_REQUIRED: "A mensagem de saudação é obrigatório quando há mais de uma fila.", + ERR_WAPP_WRONG_SESSION_NAME: + "O numero atualizado no nome da sessão não corresponde ao numero lido! Para alterar o novo numero no nome desconecte a sessão!", + + }, }, },