From 9914c6752c3c1455b23e9a2d4b12824b77c01b07 Mon Sep 17 00:00:00 2001 From: canove Date: Thu, 13 Aug 2020 20:29:41 -0300 Subject: [PATCH] feat: option to handle whatsapp session on app --- backend/src/app.js | 4 +- .../controllers/WhatsAppSessionController.js | 28 ++++++++- backend/src/libs/wbot.js | 22 ++++--- backend/src/routes/whatsapp.js | 6 ++ backend/src/services/wbotMonitor.js | 54 ++++++++++++----- frontend/src/components/Qrcode/index.js | 2 +- frontend/src/components/SessionInfo/index.js | 36 +++++++++-- frontend/src/pages/WhatsAuth/WhatsAuth.js | 60 +++++++++++-------- frontend/src/translate/languages/en.js | 4 ++ frontend/src/translate/languages/pt.js | 4 ++ 10 files changed, 160 insertions(+), 60 deletions(-) diff --git a/backend/src/app.js b/backend/src/app.js index 39a6d66..ad92af2 100644 --- a/backend/src/app.js +++ b/backend/src/app.js @@ -66,9 +66,9 @@ io.on("connection", socket => { wBot .init() - .then(() => { + .then(({ dbSession }) => { wbotMessageListener(); - wbotMonitor(); + wbotMonitor(dbSession); }) .catch(err => console.log(err)); diff --git a/backend/src/controllers/WhatsAppSessionController.js b/backend/src/controllers/WhatsAppSessionController.js index 717302a..643d330 100644 --- a/backend/src/controllers/WhatsAppSessionController.js +++ b/backend/src/controllers/WhatsAppSessionController.js @@ -1,8 +1,8 @@ const Whatsapp = require("../models/Whatsapp"); -// const { getIO } = require("../libs/socket"); -// const { getWbot, init } = require("../libs/wbot"); +const { getIO } = require("../libs/socket"); +const { getWbot } = require("../libs/wbot"); -exports.show = async (req, res, next) => { +exports.show = async (req, res) => { const { sessionId } = req.params; const dbSession = await Whatsapp.findByPk(sessionId); @@ -13,6 +13,28 @@ exports.show = async (req, res, next) => { return res.status(200).json(dbSession); }; +exports.delete = async (req, res) => { + const wbot = getWbot(); + const io = getIO(); + + const { sessionId } = req.params; + const dbSession = await Whatsapp.findByPk(sessionId); + + if (!dbSession) { + return res.status(200).json({ message: "Session not found" }); + } + + await dbSession.update({ session: "", status: "pending" }); + wbot.logout(); + + io.emit("session", { + action: "logout", + session: dbSession, + }); + + return res.status(200).json({ message: "session disconnected" }); +}; + // exports.getContacts = async (req, res, next) => { // const io = getIO(); // const wbot = getWbot(); diff --git a/backend/src/libs/wbot.js b/backend/src/libs/wbot.js index b620a4b..ff62ade 100644 --- a/backend/src/libs/wbot.js +++ b/backend/src/libs/wbot.js @@ -9,7 +9,12 @@ module.exports = { init: async () => { let sessionCfg; - const dbSession = await Whatsapp.findOne({ where: { id: 1 } }); + const [dbSession] = await Whatsapp.findOrCreate({ + where: { id: 1 }, + defaults: { + id: 1, + }, + }); if (dbSession && dbSession.session) { sessionCfg = JSON.parse(dbSession.session); } @@ -21,20 +26,21 @@ module.exports = { wbot.initialize(); wbot.on("qr", async qr => { qrCode.generate(qr, { small: true }); - await Whatsapp.upsert({ id: 1, qrcode: qr, status: "pending" }); - getIO().emit("qrcode", { + await dbSession.update({ id: 1, qrcode: qr, status: "disconnected" }); + getIO().emit("session", { action: "update", qr: qr, + session: dbSession, }); }); wbot.on("authenticated", async session => { console.log("AUTHENTICATED"); - await Whatsapp.upsert({ + await dbSession.update({ id: 1, session: JSON.stringify(session), status: "authenticated", }); - getIO().emit("whats_auth", { + getIO().emit("session", { action: "authentication", session: dbSession, }); @@ -45,8 +51,8 @@ module.exports = { }); wbot.on("ready", async () => { console.log("READY"); - await Whatsapp.update( - { status: "online", qrcode: "" }, + await dbSession.update( + { status: "CONNECTED", qrcode: "" }, { where: { id: 1 } } ); // const chats = await wbot.getChats(); // pega as mensagens nao lidas (recebidas quando o bot estava offline) @@ -62,7 +68,7 @@ module.exports = { // console.log(unreadMessages); wbot.sendPresenceAvailable(); }); - return wbot; + return { wbot, dbSession }; }, getWbot: () => { diff --git a/backend/src/routes/whatsapp.js b/backend/src/routes/whatsapp.js index ac8b232..7d27526 100644 --- a/backend/src/routes/whatsapp.js +++ b/backend/src/routes/whatsapp.js @@ -11,6 +11,12 @@ routes.get( WhatsAppSessionController.show ); +routes.delete( + "/whatsapp/session/:sessionId", + isAuth, + WhatsAppSessionController.delete +); + // fetch contacts in user cellphone, not in use // routes.get("/whatsapp/contacts", isAuth, WhatsappController.getContacts); diff --git a/backend/src/services/wbotMonitor.js b/backend/src/services/wbotMonitor.js index 7649a15..b8e4145 100644 --- a/backend/src/services/wbotMonitor.js +++ b/backend/src/services/wbotMonitor.js @@ -1,41 +1,67 @@ const Sentry = require("@sentry/node"); -const Whatsapp = require("../models/Whatsapp"); const wbotMessageListener = require("./wbotMessageListener"); const { getIO } = require("../libs/socket"); const { getWbot, init } = require("../libs/wbot"); -const wbotMonitor = () => { +const wbotMonitor = dbSession => { const io = getIO(); const wbot = getWbot(); try { - wbot.on("change_state", newState => { + wbot.on("change_state", async newState => { console.log("monitor", newState); - }); - - wbot.on("change_battery", async batteryInfo => { - // Battery percentage for attached device has changed - const { battery, plugged } = batteryInfo; try { - await Whatsapp.update({ battery, plugged }, { where: { id: 1 } }); + await dbSession.update({ status: newState }); } catch (err) { Sentry.captureException(err); console.log(err); } - console.log(`Battery: ${battery}% - Charging? ${plugged}`); //todo> save batery state to db + io.emit("session", { + action: "update", + session: dbSession, + }); }); - wbot.on("disconnected", reason => { - console.log("disconnected", reason); //todo> save connection status to DB + wbot.on("change_battery", async batteryInfo => { + const { battery, plugged } = batteryInfo; + console.log(`Battery: ${battery}% - Charging? ${plugged}`); + + try { + await dbSession.update({ battery, plugged }); + } catch (err) { + Sentry.captureException(err); + console.log(err); + } + + io.emit("session", { + action: "update", + session: dbSession, + }); + }); + + wbot.on("disconnected", async reason => { + console.log("disconnected", reason); + try { + await dbSession.update({ status: "disconnected" }); + } catch (err) { + Sentry.captureException(err); + console.log(err); + } + + io.emit("session", { + action: "logout", + session: dbSession, + }); + setTimeout( () => init() - .then(res => { + .then(({ dbSession }) => { wbotMessageListener(); - wbotMonitor(); + wbotMonitor(dbSession); }) .catch(err => { Sentry.captureException(err); diff --git a/frontend/src/components/Qrcode/index.js b/frontend/src/components/Qrcode/index.js index bee787c..c73daf1 100644 --- a/frontend/src/components/Qrcode/index.js +++ b/frontend/src/components/Qrcode/index.js @@ -10,7 +10,7 @@ const Qrcode = ({ qrCode }) => { {i18n.t("qrCode.message")} - + {qrCode ? : loading} ); }; diff --git a/frontend/src/components/SessionInfo/index.js b/frontend/src/components/SessionInfo/index.js index d7e2a38..97bad50 100644 --- a/frontend/src/components/SessionInfo/index.js +++ b/frontend/src/components/SessionInfo/index.js @@ -1,22 +1,46 @@ import React from "react"; import Typography from "@material-ui/core/Typography"; +import Button from "@material-ui/core/Button"; +import { format, parseISO } from "date-fns"; import { i18n } from "../../translate/i18n"; +import api from "../../services/api"; const SessionInfo = ({ session }) => { console.log(session); + + const handleDisconectSession = async () => { + try { + await api.delete("/whatsapp/session/1"); + } catch (err) { + console.log(err); + } + }; + return ( -
- - {`${i18n.t("sessionInfo.status")}${session.status}`} + <> + + {`${i18n.t("sessionInfo.status")} ${session.status}`} - + + {`${i18n.t("sessionInfo.updatedAt")}`}{" "} + {session.updatedAt && + format(parseISO(session.updatedAt), "dd/mm/yy HH:mm")} + + + {/* {`${i18n.t("sessionInfo.battery")}${session.battery}%`} {`${i18n.t("sessionInfo.charging")}${session.plugged} `} - -
+ */} + ); }; diff --git a/frontend/src/pages/WhatsAuth/WhatsAuth.js b/frontend/src/pages/WhatsAuth/WhatsAuth.js index c8ca9ef..d0fd435 100644 --- a/frontend/src/pages/WhatsAuth/WhatsAuth.js +++ b/frontend/src/pages/WhatsAuth/WhatsAuth.js @@ -5,7 +5,6 @@ import openSocket from "socket.io-client"; import { makeStyles } from "@material-ui/core/styles"; -import Grid from "@material-ui/core/Grid"; import Paper from "@material-ui/core/Paper"; import SessionInfo from "../../components/SessionInfo"; import Qrcode from "../../components/Qrcode"; @@ -13,19 +12,19 @@ import Qrcode from "../../components/Qrcode"; const useStyles = makeStyles(theme => ({ root: { display: "flex", + alignItems: "center", + justifyContent: "center", padding: theme.spacing(4), }, - content: { - flexGrow: 1, - overflow: "auto", - }, paper: { padding: theme.spacing(2), display: "flex", + width: 400, overflow: "auto", - alignItems: "center", flexDirection: "column", + alignItems: "center", + justifyContent: "center", }, fixedHeight: { height: 640, @@ -42,9 +41,9 @@ const WhatsAuth = () => { useEffect(() => { const fetchSession = async () => { try { - const res = await api.get("/whatsapp/session/1"); - setQrCode(res.data.qrcode); - setSession(res.data); + const { data } = await api.get("/whatsapp/session/1"); + setQrCode(data.qrcode); + setSession(data); } catch (err) { console.log(err); } @@ -52,16 +51,25 @@ const WhatsAuth = () => { fetchSession(); }, []); + console.log("session", session); + useEffect(() => { const socket = openSocket(process.env.REACT_APP_BACKEND_URL); - socket.on("qrcode", data => { + socket.on("session", data => { if (data.action === "update") { setQrCode(data.qr); + setSession(data.session); } }); - socket.on("whats_auth", data => { + socket.on("session", data => { + if (data.action === "update") { + setSession(data.session); + } + }); + + socket.on("session", data => { if (data.action === "authentication") { setQrCode(""); setSession(data.session); @@ -69,6 +77,12 @@ const WhatsAuth = () => { } }); + socket.on("session", data => { + if (data.action === "logout") { + setSession(data.session); + } + }); + return () => { socket.disconnect(); }; @@ -76,21 +90,15 @@ const WhatsAuth = () => { return (
- - {session.status === "pending" ? ( - - - - - - ) : ( - - - - - - )} - + {session && session.status === "disconnected" ? ( + + + + ) : ( + + + + )}
); }; diff --git a/frontend/src/translate/languages/en.js b/frontend/src/translate/languages/en.js index b361f5d..a665666 100644 --- a/frontend/src/translate/languages/en.js +++ b/frontend/src/translate/languages/en.js @@ -45,6 +45,10 @@ const messages = { status: "Status:", battery: "Battery:", charging: "Loading:", + updatedAt: "Updated at:", + buttons: { + disconnect: "Disconnect", + }, }, qrCode: { message: "Read QrCode to start the session", diff --git a/frontend/src/translate/languages/pt.js b/frontend/src/translate/languages/pt.js index 106f430..9b04624 100644 --- a/frontend/src/translate/languages/pt.js +++ b/frontend/src/translate/languages/pt.js @@ -45,6 +45,10 @@ const messages = { status: "Status: ", battery: "Bateria: ", charging: "Carregando: ", + updatedAt: "Atualizado em:", + buttons: { + disconnect: "Desconectar", + }, }, qrCode: { message: "Leia o QrCode para iniciar a sessão",