From 40e2e5e8a625f9dd9510d83df53dd0110d830650 Mon Sep 17 00:00:00 2001 From: canove Date: Sat, 5 Sep 2020 15:43:52 -0300 Subject: [PATCH] improvement: better names on wbot methods --- backend/src/app.js | 5 +- .../ImportPhoneContactsController.js | 2 +- .../controllers/WhatsAppSessionController.js | 56 +++++- backend/src/libs/wbot.js | 167 +++++++++--------- backend/src/router/routes/whatsapp.js | 8 + backend/src/services/wbotMessageListener.js | 2 +- backend/src/services/wbotMonitor.js | 4 +- frontend/src/pages/Connection/index.js | 8 + 8 files changed, 160 insertions(+), 92 deletions(-) diff --git a/backend/src/app.js b/backend/src/app.js index ba664b9..73e8dcd 100644 --- a/backend/src/app.js +++ b/backend/src/app.js @@ -7,7 +7,7 @@ const cors = require("cors"); const multer = require("multer"); const Sentry = require("@sentry/node"); -const wBot = require("./libs/wbot"); +const { initWbot } = require("./libs/wbot"); const wbotMessageListener = require("./services/wbotMessageListener"); const wbotMonitor = require("./services/wbotMonitor"); const Whatsapp = require("./models/Whatsapp"); @@ -61,8 +61,7 @@ const startWhatsAppSessions = async () => { if (whatsapps.length > 0) { whatsapps.forEach(dbSession => { - wBot - .init(dbSession) + initWbot(dbSession) .then(() => { wbotMessageListener(dbSession); wbotMonitor(dbSession); diff --git a/backend/src/controllers/ImportPhoneContactsController.js b/backend/src/controllers/ImportPhoneContactsController.js index 19b5537..c9b79b0 100644 --- a/backend/src/controllers/ImportPhoneContactsController.js +++ b/backend/src/controllers/ImportPhoneContactsController.js @@ -1,6 +1,6 @@ const Contact = require("../models/Contact"); const { getIO } = require("../libs/socket"); -const { getWbot, init } = require("../libs/wbot"); +const { getWbot, initWbot } = require("../libs/wbot"); exports.store = async (req, res, next) => { const io = getIO(); diff --git a/backend/src/controllers/WhatsAppSessionController.js b/backend/src/controllers/WhatsAppSessionController.js index 67c5f16..94937ca 100644 --- a/backend/src/controllers/WhatsAppSessionController.js +++ b/backend/src/controllers/WhatsAppSessionController.js @@ -1,6 +1,8 @@ const Whatsapp = require("../models/Whatsapp"); const { getIO } = require("../libs/socket"); -const { getWbot } = require("../libs/wbot"); +const { getWbot, initWbot, removeWbot } = require("../libs/wbot"); +const wbotMessageListener = require("../services/wbotMessageListener"); +const wbotMonitor = require("../services/wbotMonitor"); exports.index = async (req, res) => { const dbSession = await Whatsapp.findAll(); @@ -8,6 +10,29 @@ exports.index = async (req, res) => { return res.status(200).json(dbSession); }; +exports.store = async (req, res) => { + const io = getIO(); + const dbSession = await Whatsapp.create(req.body); + + if (!dbSession) { + return res.status(400).json({ error: "Cannot create whatsapp session." }); + } + + initWbot(dbSession) + .then(() => { + wbotMessageListener(dbSession); + wbotMonitor(dbSession); + }) + .catch(err => console.log(err)); + + io.emit("session", { + action: "update", + session: dbSession, + }); + + return res.status(200).json({ message: "Session created sucessfully." }); +}; + exports.show = async (req, res) => { const { sessionId } = req.params; const dbSession = await Whatsapp.findByPk(sessionId); @@ -20,6 +45,7 @@ exports.show = async (req, res) => { }; exports.update = async (req, res) => { + const io = getIO(); const { sessionId } = req.params; const dbSession = await Whatsapp.findByPk(sessionId); @@ -29,15 +55,37 @@ exports.update = async (req, res) => { } const wbot = getWbot(dbSession.id); - const io = getIO(); + wbot.logout(); await dbSession.update(req.body); - wbot.logout(); io.emit("session", { action: "update", session: dbSession, }); - return res.status(200).json({ message: "session disconnected" }); + return res.status(200).json({ message: "Session updated" }); +}; + +exports.delete = async (req, res) => { + const io = getIO(); + const { sessionId } = req.params; + + const dbSession = await Whatsapp.findByPk(sessionId); + + if (!dbSession) { + return res.status(404).json({ message: "Session not found" }); + } + + const wbot = getWbot(dbSession.id); + await dbSession.destroy(); + + removeWbot(dbSession.id); + + io.emit("session", { + action: "delete", + sessionId: dbSession.id, + }); + + return res.status(200).json({ message: "Session deleted." }); }; diff --git a/backend/src/libs/wbot.js b/backend/src/libs/wbot.js index 2651db5..39c76ba 100644 --- a/backend/src/libs/wbot.js +++ b/backend/src/libs/wbot.js @@ -6,90 +6,83 @@ const { getIO } = require("../libs/socket"); let sessions = []; module.exports = { - init: async dbSession => { - const io = getIO(); - const sessionName = dbSession.name; - let sessionCfg; + initWbot: async dbSession => { + try { + const io = getIO(); + const sessionName = dbSession.name; + let sessionCfg; - if (dbSession && dbSession.session) { - sessionCfg = JSON.parse(dbSession.session); + if (dbSession && dbSession.session) { + sessionCfg = JSON.parse(dbSession.session); + } + + const sessionIndex = sessions.findIndex(s => s.id === dbSession.id); + if (sessionIndex !== -1) { + sessions[sessionIndex].destroy(); + sessions.splice(sessionIndex, 1); + } + + const wbot = new Client({ + session: sessionCfg, + restartOnAuthFail: true, + }); + wbot.initialize(); + + wbot.on("qr", async qr => { + console.log("Session:", sessionName); + + qrCode.generate(qr, { small: true }); + + await dbSession.update({ id: 1, qrcode: qr, status: "qrcode" }); + + io.emit("session", { + action: "update", + session: dbSession, + }); + }); + + wbot.on("authenticated", async session => { + console.log("Session:", sessionName, "AUTHENTICATED"); + + await dbSession.update({ + session: JSON.stringify(session), + status: "authenticated", + }); + + io.emit("session", { + action: "update", + session: dbSession, + }); + }); + + wbot.on("auth_failure", async msg => { + console.error("Session:", sessionName, "AUTHENTICATION FAILURE", msg); + + await dbSession.update({ session: "" }); + }); + + wbot.on("ready", async () => { + console.log("Session:", sessionName, "READY"); + + await dbSession.update({ + status: "CONNECTED", + qrcode: "", + }); + + io.emit("session", { + action: "update", + session: dbSession, + }); + + wbot.sendPresenceAvailable(); + }); + + wbot.id = dbSession.id; + sessions.push(wbot); + } catch (err) { + console.log(err); } - const sessionIndex = sessions.findIndex(s => s.id === dbSession.id); - if (sessionIndex !== -1) { - sessions[sessionIndex].destroy(); - sessions.splice(sessionIndex, 1); - } - - const wbot = new Client({ - session: sessionCfg, - restartOnAuthFail: true, - }); - wbot.initialize(); - - wbot.on("qr", async qr => { - console.log("Session:", sessionName); - - qrCode.generate(qr, { small: true }); - - await dbSession.update({ id: 1, qrcode: qr, status: "qrcode" }); - - io.emit("session", { - action: "update", - session: dbSession, - }); - }); - - wbot.on("authenticated", async session => { - console.log("Session:", sessionName, "AUTHENTICATED"); - - await dbSession.update({ - session: JSON.stringify(session), - status: "authenticated", - }); - - io.emit("session", { - action: "update", - session: dbSession, - }); - }); - - wbot.on("auth_failure", async msg => { - console.error("Session:", sessionName, "AUTHENTICATION FAILURE", msg); - - await dbSession.update({ session: "" }); - }); - - wbot.on("ready", async () => { - console.log("Session:", sessionName, "READY"); - - await dbSession.update({ - status: "CONNECTED", - qrcode: "", - }); - - io.emit("session", { - action: "update", - session: dbSession, - }); - - // const chats = await wbot.getChats(); // pega as mensagens nao lidas (recebidas quando o bot estava offline) - // let unreadMessages; // todo > salvar isso no DB pra mostrar no frontend - // for (let chat of chats) { - // if (chat.unreadCount > 0) { - // unreadMessages = await chat.fetchMessages({ - // limit: chat.unreadCount, - // }); - // } - // } - - // console.log(unreadMessages); - wbot.sendPresenceAvailable(); - }); - - wbot.id = dbSession.id; - sessions.push(wbot); - return null; }, @@ -103,4 +96,16 @@ module.exports = { } return sessions[sessionIndex]; }, + + removeWbot: sessionId => { + try { + const sessionIndex = sessions.findIndex(s => s.id === sessionId); + if (sessionIndex !== -1) { + sessions[sessionIndex].destroy(); + sessions.splice(sessionIndex, 1); + } + } catch (err) { + console.log(err); + } + }, }; diff --git a/backend/src/router/routes/whatsapp.js b/backend/src/router/routes/whatsapp.js index 97f792c..5c6125f 100644 --- a/backend/src/router/routes/whatsapp.js +++ b/backend/src/router/routes/whatsapp.js @@ -7,6 +7,8 @@ const routes = express.Router(); routes.get("/whatsapp/session/", isAuth, WhatsAppSessionController.index); +routes.post("/whatsapp/session", isAuth, WhatsAppSessionController.store); + routes.get( "/whatsapp/session/:sessionId", isAuth, @@ -19,4 +21,10 @@ routes.put( WhatsAppSessionController.update ); +routes.delete( + "/whatsapp/session/:sessionId", + isAuth, + WhatsAppSessionController.delete +); + module.exports = routes; diff --git a/backend/src/services/wbotMessageListener.js b/backend/src/services/wbotMessageListener.js index cc5f013..9056caa 100644 --- a/backend/src/services/wbotMessageListener.js +++ b/backend/src/services/wbotMessageListener.js @@ -9,7 +9,7 @@ const Ticket = require("../models/Ticket"); const Message = require("../models/Message"); const { getIO } = require("../libs/socket"); -const { getWbot, init } = require("../libs/wbot"); +const { getWbot, initWbot } = require("../libs/wbot"); const verifyContact = async (msgContact, profilePicUrl) => { let contact = await Contact.findOne({ diff --git a/backend/src/services/wbotMonitor.js b/backend/src/services/wbotMonitor.js index e6715d8..3bd286d 100644 --- a/backend/src/services/wbotMonitor.js +++ b/backend/src/services/wbotMonitor.js @@ -3,7 +3,7 @@ const Sentry = require("@sentry/node"); const wbotMessageListener = require("./wbotMessageListener"); const { getIO } = require("../libs/socket"); -const { getWbot, init } = require("../libs/wbot"); +const { getWbot, initWbot } = require("../libs/wbot"); const wbotMonitor = dbSession => { const io = getIO(); @@ -61,7 +61,7 @@ const wbotMonitor = dbSession => { setTimeout( () => - init(dbSession) + initWbot(dbSession) .then(() => { wbotMessageListener(dbSession); wbotMonitor(dbSession); diff --git a/frontend/src/pages/Connection/index.js b/frontend/src/pages/Connection/index.js index c8946a9..e3eb62d 100644 --- a/frontend/src/pages/Connection/index.js +++ b/frontend/src/pages/Connection/index.js @@ -47,6 +47,8 @@ const reducer = (state, action) => { if (action.type === "DELETE_SESSION") { const sessionId = action.payload; + console.log("cai aqui", sessionId); + const sessionIndex = state.findIndex(s => s.id === sessionId); if (sessionIndex !== -1) { state.splice(sessionIndex, 1); @@ -123,6 +125,12 @@ const WhatsAuth = () => { } }); + socket.on("session", data => { + if (data.action === "delete") { + dispatch({ type: "DELETE_SESSION", payload: data.sessionId }); + } + }); + return () => { socket.disconnect(); };