From 73cb08a55746c5847ad412a1ef9ed76ef7558910 Mon Sep 17 00:00:00 2001 From: canove Date: Mon, 26 Oct 2020 19:55:07 -0300 Subject: [PATCH] feat: added routes to handle whatsapp session --- backend/src/controllers/WhatsAppController.ts | 11 ++--- .../controllers/WhatsAppSessionController.ts | 45 +++++++++---------- ...20201026215410-add-retries-to-whatsapps.ts | 15 +++++++ backend/src/libs/wbot.ts | 27 ++++++++++- backend/src/models/Whatsapp.ts | 3 ++ backend/src/routes/index.ts | 3 ++ backend/src/routes/whatsappSessionRoutes.ts | 30 ++++++------- backend/src/server.ts | 4 +- .../WbotServices/StartAllWhatsAppsSessions.ts | 11 +++++ .../WbotServices/StartWhatsAppSession.ts | 16 +++++++ .../WbotServices/StartWhatsAppSessions.ts | 19 -------- .../src/services/WbotServices/wbotMonitor.ts | 26 ++--------- .../WhatsappService/ShowWhatsAppService.ts | 4 +- 13 files changed, 118 insertions(+), 96 deletions(-) create mode 100644 backend/src/database/migrations/20201026215410-add-retries-to-whatsapps.ts create mode 100644 backend/src/services/WbotServices/StartAllWhatsAppsSessions.ts create mode 100644 backend/src/services/WbotServices/StartWhatsAppSession.ts delete mode 100644 backend/src/services/WbotServices/StartWhatsAppSessions.ts diff --git a/backend/src/controllers/WhatsAppController.ts b/backend/src/controllers/WhatsAppController.ts index 8838f2b..f08cbf5 100644 --- a/backend/src/controllers/WhatsAppController.ts +++ b/backend/src/controllers/WhatsAppController.ts @@ -1,6 +1,7 @@ import { Request, Response } from "express"; import { getIO } from "../libs/socket"; -import { initWbot, removeWbot } from "../libs/wbot"; +import { removeWbot } from "../libs/wbot"; +import { StartWhatsAppSession } from "../services/WbotServices/StartWhatsAppSession"; import wbotMessageListener from "../services/WbotServices/wbotMessageListener"; import wbotMonitor from "../services/WbotServices/wbotMonitor"; @@ -31,13 +32,7 @@ export const store = async (req: Request, res: Response): Promise => { isDefault }); - try { - const wbot = await initWbot(whatsapp); - wbotMessageListener(wbot); - wbotMonitor(wbot, whatsapp); - } catch (err) { - console.log(err); - } + StartWhatsAppSession(whatsapp); const io = getIO(); io.emit("whatsapp", { diff --git a/backend/src/controllers/WhatsAppSessionController.ts b/backend/src/controllers/WhatsAppSessionController.ts index 38f5416..46d3b6a 100644 --- a/backend/src/controllers/WhatsAppSessionController.ts +++ b/backend/src/controllers/WhatsAppSessionController.ts @@ -1,32 +1,29 @@ -// const Whatsapp = require("../models/Whatsapp"); -// const { getIO } = require("../libs/socket"); -// const { getWbot, initWbot, removeWbot } = require("../libs/wbot"); -// const wbotMessageListener = require("../services/wbotMessageListener"); -// const wbotMonitor = require("../services/wbotMonitor"); +import { Request, Response } from "express"; +// import Whatsapp from "../models/Whatsapp"; +// import { getIO } from "../libs/socket"; +import { getWbot } from "../libs/wbot"; +import ShowWhatsAppService from "../services/WhatsappService/ShowWhatsAppService"; +import { StartWhatsAppSession } from "../services/WbotServices/StartWhatsAppSession"; +// import wbotMonitor from "../services/wbotMonitor"; -// exports.show = async (req, res) => { -// const { whatsappId } = req.params; -// const dbSession = await Whatsapp.findByPk(whatsappId); +const store = async (req: Request, res: Response): Promise => { + const { whatsappId } = req.params; + const whatsapp = await ShowWhatsAppService(whatsappId); -// if (!dbSession) { -// return res.status(200).json({ message: "Session not found" }); -// } + StartWhatsAppSession(whatsapp); -// return res.status(200).json(dbSession); -// }; + return res.status(200).json({ message: "Starting session." }); +}; -// exports.delete = async (req, res) => { -// const { whatsappId } = req.params; +const remove = async (req: Request, res: Response): Promise => { + const { whatsappId } = req.params; + const whatsapp = await ShowWhatsAppService(whatsappId); -// const dbSession = await Whatsapp.findByPk(whatsappId); + const wbot = getWbot(whatsapp.id); -// if (!dbSession) { -// return res.status(404).json({ message: "Session not found" }); -// } + wbot.logout(); -// const wbot = getWbot(dbSession.id); + return res.status(200).json({ message: "Session disconnected." }); +}; -// wbot.logout(); - -// return res.status(200).json({ message: "Session disconnected." }); -// }; +export default { store, remove }; diff --git a/backend/src/database/migrations/20201026215410-add-retries-to-whatsapps.ts b/backend/src/database/migrations/20201026215410-add-retries-to-whatsapps.ts new file mode 100644 index 0000000..57b1450 --- /dev/null +++ b/backend/src/database/migrations/20201026215410-add-retries-to-whatsapps.ts @@ -0,0 +1,15 @@ +import { QueryInterface, DataTypes } from "sequelize"; + +module.exports = { + up: (queryInterface: QueryInterface) => { + return queryInterface.addColumn("Whatsapps", "retries", { + type: DataTypes.INTEGER, + defaultValue: 0, + allowNull: false + }); + }, + + down: (queryInterface: QueryInterface) => { + return queryInterface.removeColumn("Whatsapps", "retries"); + } +}; diff --git a/backend/src/libs/wbot.ts b/backend/src/libs/wbot.ts index 3f7f75a..25a145a 100644 --- a/backend/src/libs/wbot.ts +++ b/backend/src/libs/wbot.ts @@ -3,6 +3,7 @@ import { Client } from "whatsapp-web.js"; import { getIO } from "./socket"; import Whatsapp from "../models/Whatsapp"; import AppError from "../errors/AppError"; +import { StartWhatsAppSession } from "../services/WbotServices/StartWhatsAppSession"; interface Session extends Client { id?: number; @@ -37,6 +38,7 @@ export const initWbot = async (whatsapp: Whatsapp): Promise => { console.log("Session:", sessionName); qrCode.generate(qr, { small: true }); await whatsapp.update({ qrcode: qr, status: "qrcode" }); + io.emit("whatsappSession", { action: "update", session: whatsapp @@ -49,6 +51,7 @@ export const initWbot = async (whatsapp: Whatsapp): Promise => { session: JSON.stringify(session), status: "authenticated" }); + io.emit("whatsappSession", { action: "update", session: whatsapp @@ -57,20 +60,40 @@ export const initWbot = async (whatsapp: Whatsapp): Promise => { wbot.on("auth_failure", async msg => { console.error("Session:", sessionName, "AUTHENTICATION FAILURE", msg); - await whatsapp.update({ status: "OFFLINE" }); + + if (whatsapp.retries > 2) { + await whatsapp.update({ session: "", retries: 0 }); + } + + const retry = whatsapp.retries; + await whatsapp.update({ + status: "DISCONNECTED", + retries: retry + 1 + }); + + io.emit("whatsappSession", { + action: "update", + session: whatsapp + }); + + StartWhatsAppSession(whatsapp); reject(new Error("Error starting whatsapp session.")); }); wbot.on("ready", async () => { console.log("Session:", sessionName, "READY"); + await whatsapp.update({ status: "CONNECTED", - qrcode: "" + qrcode: "", + retries: 0 }); + io.emit("whatsappSession", { action: "update", session: whatsapp }); + wbot.sendPresenceAvailable(); wbot.id = whatsapp.id; sessions.push(wbot); diff --git a/backend/src/models/Whatsapp.ts b/backend/src/models/Whatsapp.ts index 6ba684e..099b0db 100644 --- a/backend/src/models/Whatsapp.ts +++ b/backend/src/models/Whatsapp.ts @@ -41,6 +41,9 @@ class Whatsapp extends Model { @Column plugged: boolean; + @Column + retries: number; + @Default(false) @AllowNull @Column diff --git a/backend/src/routes/index.ts b/backend/src/routes/index.ts index 744300e..2abafa8 100644 --- a/backend/src/routes/index.ts +++ b/backend/src/routes/index.ts @@ -7,6 +7,7 @@ import contactRoutes from "./contactRoutes"; import ticketRoutes from "./ticketRoutes"; import whatsappRoutes from "./whatsappRoutes"; import messageRoutes from "./messageRoutes"; +import whatsappSessionRoutes from "./whatsappSessionRoutes"; const routes = Router(); @@ -17,5 +18,7 @@ routes.use(contactRoutes); routes.use(ticketRoutes); routes.use(whatsappRoutes); routes.use(messageRoutes); +routes.use(messageRoutes); +routes.use(whatsappSessionRoutes); export default routes; diff --git a/backend/src/routes/whatsappSessionRoutes.ts b/backend/src/routes/whatsappSessionRoutes.ts index ead10c2..fc94d73 100644 --- a/backend/src/routes/whatsappSessionRoutes.ts +++ b/backend/src/routes/whatsappSessionRoutes.ts @@ -1,20 +1,20 @@ -// const express = require("express"); -// const isAuth = require("../../middleware/is-auth"); +import { Router } from "express"; +import isAuth from "../middleware/isAuth"; -// const WhatsAppSessionController = require("../../controllers/WhatsAppSessionController"); +import WhatsAppSessionController from "../controllers/WhatsAppSessionController"; -// const routes = express.Router(); +const whatsappSessionRoutes = Router(); -// routes.get( -// "/whatsappsession/:whatsappId", -// isAuth, -// WhatsAppSessionController.show -// ); +whatsappSessionRoutes.post( + "/whatsappsession/:whatsappId", + isAuth, + WhatsAppSessionController.store +); -// routes.delete( -// "/whatsappsession/:whatsappId", -// isAuth, -// WhatsAppSessionController.delete -// ); +whatsappSessionRoutes.delete( + "/whatsappsession/:whatsappId", + isAuth, + WhatsAppSessionController.remove +); -// module.exports = routes; +export default whatsappSessionRoutes; diff --git a/backend/src/server.ts b/backend/src/server.ts index 53c4065..00d12ac 100644 --- a/backend/src/server.ts +++ b/backend/src/server.ts @@ -1,10 +1,10 @@ import app from "./app"; import { initIO } from "./libs/socket"; -import { StartWhatsAppSessions } from "./services/WbotServices/StartWhatsAppSessions"; +import { StartAllWhatsAppsSessions } from "./services/WbotServices/StartAllWhatsAppsSessions"; const server = app.listen(process.env.PORT, () => { console.log(`Server started on port: ${process.env.PORT}`); }); initIO(server); -StartWhatsAppSessions(); +StartAllWhatsAppsSessions(); diff --git a/backend/src/services/WbotServices/StartAllWhatsAppsSessions.ts b/backend/src/services/WbotServices/StartAllWhatsAppsSessions.ts new file mode 100644 index 0000000..a472f9f --- /dev/null +++ b/backend/src/services/WbotServices/StartAllWhatsAppsSessions.ts @@ -0,0 +1,11 @@ +import Whatsapp from "../../models/Whatsapp"; +import { StartWhatsAppSession } from "./StartWhatsAppSession"; + +export const StartAllWhatsAppsSessions = async (): Promise => { + const whatsapps = await Whatsapp.findAll(); + if (whatsapps.length > 0) { + whatsapps.forEach(whatsapp => { + StartWhatsAppSession(whatsapp); + }); + } +}; diff --git a/backend/src/services/WbotServices/StartWhatsAppSession.ts b/backend/src/services/WbotServices/StartWhatsAppSession.ts new file mode 100644 index 0000000..4ea8fcc --- /dev/null +++ b/backend/src/services/WbotServices/StartWhatsAppSession.ts @@ -0,0 +1,16 @@ +import { initWbot } from "../../libs/wbot"; +import Whatsapp from "../../models/Whatsapp"; +import wbotMessageListener from "./wbotMessageListener"; +import wbotMonitor from "./wbotMonitor"; + +export const StartWhatsAppSession = async ( + whatsapp: Whatsapp +): Promise => { + try { + const wbot = await initWbot(whatsapp); + wbotMessageListener(wbot); + wbotMonitor(wbot, whatsapp); + } catch (err) { + console.log(err); + } +}; diff --git a/backend/src/services/WbotServices/StartWhatsAppSessions.ts b/backend/src/services/WbotServices/StartWhatsAppSessions.ts deleted file mode 100644 index 306c95a..0000000 --- a/backend/src/services/WbotServices/StartWhatsAppSessions.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { initWbot } from "../../libs/wbot"; -import Whatsapp from "../../models/Whatsapp"; -import wbotMessageListener from "./wbotMessageListener"; -import wbotMonitor from "./wbotMonitor"; - -export const StartWhatsAppSessions = async (): Promise => { - const whatsapps = await Whatsapp.findAll(); - if (whatsapps.length > 0) { - whatsapps.forEach(async whatsapp => { - try { - const wbot = await initWbot(whatsapp); - wbotMessageListener(wbot); - wbotMonitor(wbot, whatsapp); - } catch (err) { - console.log(err); - } - }); - } -}; diff --git a/backend/src/services/WbotServices/wbotMonitor.ts b/backend/src/services/WbotServices/wbotMonitor.ts index 565861b..ce62117 100644 --- a/backend/src/services/WbotServices/wbotMonitor.ts +++ b/backend/src/services/WbotServices/wbotMonitor.ts @@ -1,11 +1,9 @@ import * as Sentry from "@sentry/node"; import { Client } from "whatsapp-web.js"; -import wbotMessageListener from "./wbotMessageListener"; - import { getIO } from "../../libs/socket"; -import { initWbot } from "../../libs/wbot"; import Whatsapp from "../../models/Whatsapp"; +import { StartWhatsAppSession } from "./StartWhatsAppSession"; interface Session extends Client { id?: number; @@ -56,7 +54,7 @@ const wbotMonitor = async ( wbot.on("disconnected", async reason => { console.log("Disconnected session:", sessionName, reason); try { - await whatsapp.update({ status: "disconnected" }); + await whatsapp.update({ status: "DISCONNECTED", session: "" }); } catch (err) { Sentry.captureException(err); console.log(err); @@ -67,26 +65,8 @@ const wbotMonitor = async ( session: whatsapp }); - // to be removed after adding buttons to rebuild session on frontend - - setTimeout( - () => - initWbot(whatsapp) - .then(() => { - wbotMessageListener(wbot); - wbotMonitor(wbot, whatsapp); - }) - .catch(err => { - Sentry.captureException(err); - console.log(err); - }), - 2000 - ); + setTimeout(() => StartWhatsAppSession(whatsapp), 2000); }); - - // setInterval(() => { - // wbot.resetState(); - // }, 20000); } catch (err) { Sentry.captureException(err); console.log(err); diff --git a/backend/src/services/WhatsappService/ShowWhatsAppService.ts b/backend/src/services/WhatsappService/ShowWhatsAppService.ts index f31bd7c..6a203a9 100644 --- a/backend/src/services/WhatsappService/ShowWhatsAppService.ts +++ b/backend/src/services/WhatsappService/ShowWhatsAppService.ts @@ -1,9 +1,7 @@ import Whatsapp from "../../models/Whatsapp"; import AppError from "../../errors/AppError"; -const ShowWhatsAppService = async ( - id: string | number -): Promise => { +const ShowWhatsAppService = async (id: string | number): Promise => { const whatsapp = await Whatsapp.findByPk(id); if (!whatsapp) {