feat: new connections page to handle multiple whats

This commit is contained in:
canove
2020-09-05 14:41:55 -03:00
parent 8786c7ca5e
commit b8ff993e6f
9 changed files with 335 additions and 119 deletions

View File

@@ -2,6 +2,12 @@ const Whatsapp = require("../models/Whatsapp");
const { getIO } = require("../libs/socket");
const { getWbot } = require("../libs/wbot");
exports.index = async (req, res) => {
const dbSession = await Whatsapp.findAll();
return res.status(200).json(dbSession);
};
exports.show = async (req, res) => {
const { sessionId } = req.params;
const dbSession = await Whatsapp.findByPk(sessionId);
@@ -13,33 +19,25 @@ exports.show = async (req, res) => {
return res.status(200).json(dbSession);
};
exports.delete = async (req, res) => {
const wbot = getWbot();
const io = getIO();
exports.update = async (req, res) => {
const { sessionId } = req.params;
const dbSession = await Whatsapp.findByPk(sessionId);
if (!dbSession) {
return res.status(404).json({ message: "Session not found" });
}
await dbSession.update({ session: "", status: "pending" });
const wbot = getWbot(dbSession.id);
const io = getIO();
await dbSession.update(req.body);
wbot.logout();
io.emit("session", {
action: "logout",
action: "update",
session: dbSession,
});
return res.status(200).json({ message: "session disconnected" });
};
// exports.getContacts = async (req, res, next) => {
// const io = getIO();
// const wbot = getWbot();
// const phoneContacts = await wbot.getContacts();
// return res.status(200).json(phoneContacts);
// };

View File

@@ -7,6 +7,7 @@ let sessions = [];
module.exports = {
init: async dbSession => {
const io = getIO();
const sessionName = dbSession.name;
let sessionCfg;
@@ -14,43 +15,64 @@ module.exports = {
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: "disconnected" });
getIO().emit("session", {
await dbSession.update({ id: 1, qrcode: qr, status: "qrcode" });
io.emit("session", {
action: "update",
qr: qr,
session: dbSession,
});
});
wbot.on("authenticated", async session => {
console.log("Session:", sessionName, "AUTHENTICATED");
await dbSession.update({
session: JSON.stringify(session),
status: "authenticated",
});
getIO().emit("session", {
action: "authentication",
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) {
@@ -62,16 +84,19 @@ module.exports = {
// }
// console.log(unreadMessages);
// wbot.sendPresenceAvailable();
wbot.sendPresenceAvailable();
});
wbot.name = sessionName;
wbot.id = dbSession.id;
sessions.push(wbot);
return null;
},
getWbot: sessionName => {
const sessionIndex = sessions.findIndex(s => s.name === sessionName);
getWbot: sessionId => {
console.log(sessionId);
console.log(sessions.map(session => session.id));
const sessionIndex = sessions.findIndex(s => s.id === sessionId);
if (sessionIndex === -1) {
throw new Error("This Wbot session is not initialized");

View File

@@ -5,19 +5,18 @@ const WhatsAppSessionController = require("../../controllers/WhatsAppSessionCont
const routes = express.Router();
routes.get("/whatsapp/session/", isAuth, WhatsAppSessionController.index);
routes.get(
"/whatsapp/session/:sessionId",
isAuth,
WhatsAppSessionController.show
);
routes.delete(
routes.put(
"/whatsapp/session/:sessionId",
isAuth,
WhatsAppSessionController.delete
WhatsAppSessionController.update
);
// fetch contacts in user cellphone, not in use
// routes.get("/whatsapp/contacts", isAuth, WhatsappController.getContacts);
module.exports = routes;

View File

@@ -133,7 +133,7 @@ const handleMessage = async (msg, ticket, contact) => {
};
const wbotMessageListener = dbSession => {
const wbot = getWbot(dbSession.name);
const wbot = getWbot(dbSession.id);
const io = getIO();
wbot.on("message_create", async msg => {

View File

@@ -7,11 +7,12 @@ const { getWbot, init } = require("../libs/wbot");
const wbotMonitor = dbSession => {
const io = getIO();
const wbot = getWbot(dbSession.name);
const sessionName = dbSession.name;
const wbot = getWbot(dbSession.id);
try {
wbot.on("change_state", async newState => {
console.log("monitor", newState);
console.log("Monitor session:", sessionName, newState);
try {
await dbSession.update({ status: newState });
} catch (err) {
@@ -27,7 +28,9 @@ const wbotMonitor = dbSession => {
wbot.on("change_battery", async batteryInfo => {
const { battery, plugged } = batteryInfo;
console.log(`Battery: ${battery}% - Charging? ${plugged}`);
console.log(
`Battery session: ${sessionName} ${battery}% - Charging? ${plugged}`
);
try {
await dbSession.update({ battery, plugged });
@@ -43,7 +46,7 @@ const wbotMonitor = dbSession => {
});
wbot.on("disconnected", async reason => {
console.log("disconnected", reason);
console.log("Disconnected session:", sessionName, reason);
try {
await dbSession.update({ status: "disconnected" });
} catch (err) {
@@ -52,7 +55,7 @@ const wbotMonitor = dbSession => {
}
io.emit("session", {
action: "logout",
action: "update",
session: dbSession,
});
@@ -60,7 +63,7 @@ const wbotMonitor = dbSession => {
() =>
init(dbSession)
.then(() => {
wbotMessageListener();
wbotMessageListener(dbSession);
wbotMonitor(dbSession);
})
.catch(err => {