feat: option to handle whatsapp session on app

This commit is contained in:
canove
2020-08-13 20:29:41 -03:00
parent cdc4411f70
commit 9914c6752c
10 changed files with 160 additions and 60 deletions

View File

@@ -66,9 +66,9 @@ io.on("connection", socket => {
wBot wBot
.init() .init()
.then(() => { .then(({ dbSession }) => {
wbotMessageListener(); wbotMessageListener();
wbotMonitor(); wbotMonitor(dbSession);
}) })
.catch(err => console.log(err)); .catch(err => console.log(err));

View File

@@ -1,8 +1,8 @@
const Whatsapp = require("../models/Whatsapp"); const Whatsapp = require("../models/Whatsapp");
// const { getIO } = require("../libs/socket"); const { getIO } = require("../libs/socket");
// const { getWbot, init } = require("../libs/wbot"); const { getWbot } = require("../libs/wbot");
exports.show = async (req, res, next) => { exports.show = async (req, res) => {
const { sessionId } = req.params; const { sessionId } = req.params;
const dbSession = await Whatsapp.findByPk(sessionId); const dbSession = await Whatsapp.findByPk(sessionId);
@@ -13,6 +13,28 @@ exports.show = async (req, res, next) => {
return res.status(200).json(dbSession); 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) => { // exports.getContacts = async (req, res, next) => {
// const io = getIO(); // const io = getIO();
// const wbot = getWbot(); // const wbot = getWbot();

View File

@@ -9,7 +9,12 @@ module.exports = {
init: async () => { init: async () => {
let sessionCfg; 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) { if (dbSession && dbSession.session) {
sessionCfg = JSON.parse(dbSession.session); sessionCfg = JSON.parse(dbSession.session);
} }
@@ -21,20 +26,21 @@ module.exports = {
wbot.initialize(); wbot.initialize();
wbot.on("qr", async qr => { wbot.on("qr", async qr => {
qrCode.generate(qr, { small: true }); qrCode.generate(qr, { small: true });
await Whatsapp.upsert({ id: 1, qrcode: qr, status: "pending" }); await dbSession.update({ id: 1, qrcode: qr, status: "disconnected" });
getIO().emit("qrcode", { getIO().emit("session", {
action: "update", action: "update",
qr: qr, qr: qr,
session: dbSession,
}); });
}); });
wbot.on("authenticated", async session => { wbot.on("authenticated", async session => {
console.log("AUTHENTICATED"); console.log("AUTHENTICATED");
await Whatsapp.upsert({ await dbSession.update({
id: 1, id: 1,
session: JSON.stringify(session), session: JSON.stringify(session),
status: "authenticated", status: "authenticated",
}); });
getIO().emit("whats_auth", { getIO().emit("session", {
action: "authentication", action: "authentication",
session: dbSession, session: dbSession,
}); });
@@ -45,8 +51,8 @@ module.exports = {
}); });
wbot.on("ready", async () => { wbot.on("ready", async () => {
console.log("READY"); console.log("READY");
await Whatsapp.update( await dbSession.update(
{ status: "online", qrcode: "" }, { status: "CONNECTED", qrcode: "" },
{ where: { id: 1 } } { where: { id: 1 } }
); );
// const chats = await wbot.getChats(); // pega as mensagens nao lidas (recebidas quando o bot estava offline) // 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); // console.log(unreadMessages);
wbot.sendPresenceAvailable(); wbot.sendPresenceAvailable();
}); });
return wbot; return { wbot, dbSession };
}, },
getWbot: () => { getWbot: () => {

View File

@@ -11,6 +11,12 @@ routes.get(
WhatsAppSessionController.show WhatsAppSessionController.show
); );
routes.delete(
"/whatsapp/session/:sessionId",
isAuth,
WhatsAppSessionController.delete
);
// fetch contacts in user cellphone, not in use // fetch contacts in user cellphone, not in use
// routes.get("/whatsapp/contacts", isAuth, WhatsappController.getContacts); // routes.get("/whatsapp/contacts", isAuth, WhatsappController.getContacts);

View File

@@ -1,41 +1,67 @@
const Sentry = require("@sentry/node"); const Sentry = require("@sentry/node");
const Whatsapp = require("../models/Whatsapp");
const wbotMessageListener = require("./wbotMessageListener"); const wbotMessageListener = require("./wbotMessageListener");
const { getIO } = require("../libs/socket"); const { getIO } = require("../libs/socket");
const { getWbot, init } = require("../libs/wbot"); const { getWbot, init } = require("../libs/wbot");
const wbotMonitor = () => { const wbotMonitor = dbSession => {
const io = getIO(); const io = getIO();
const wbot = getWbot(); const wbot = getWbot();
try { try {
wbot.on("change_state", newState => { wbot.on("change_state", async newState => {
console.log("monitor", newState); console.log("monitor", newState);
});
wbot.on("change_battery", async batteryInfo => {
// Battery percentage for attached device has changed
const { battery, plugged } = batteryInfo;
try { try {
await Whatsapp.update({ battery, plugged }, { where: { id: 1 } }); await dbSession.update({ status: newState });
} catch (err) { } catch (err) {
Sentry.captureException(err); Sentry.captureException(err);
console.log(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 => { wbot.on("change_battery", async batteryInfo => {
console.log("disconnected", reason); //todo> save connection status to DB 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( setTimeout(
() => () =>
init() init()
.then(res => { .then(({ dbSession }) => {
wbotMessageListener(); wbotMessageListener();
wbotMonitor(); wbotMonitor(dbSession);
}) })
.catch(err => { .catch(err => {
Sentry.captureException(err); Sentry.captureException(err);

View File

@@ -10,7 +10,7 @@ const Qrcode = ({ qrCode }) => {
<Typography color="primary" gutterBottom> <Typography color="primary" gutterBottom>
{i18n.t("qrCode.message")} {i18n.t("qrCode.message")}
</Typography> </Typography>
<QRCode value={qrCode} size={256} /> {qrCode ? <QRCode value={qrCode} size={256} /> : <span>loading</span>}
</div> </div>
); );
}; };

View File

@@ -1,22 +1,46 @@
import React from "react"; import React from "react";
import Typography from "@material-ui/core/Typography"; 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 { i18n } from "../../translate/i18n";
import api from "../../services/api";
const SessionInfo = ({ session }) => { const SessionInfo = ({ session }) => {
console.log(session); console.log(session);
const handleDisconectSession = async () => {
try {
await api.delete("/whatsapp/session/1");
} catch (err) {
console.log(err);
}
};
return ( return (
<div> <>
<Typography component="h2" variant="h6" color="primary" gutterBottom> <Typography variant="h6" color="primary">
{`${i18n.t("sessionInfo.status")}${session.status}`} {`${i18n.t("sessionInfo.status")} ${session.status}`}
</Typography> </Typography>
<Typography component="p" variant="h6"> <Typography variant="body2" gutterBottom>
{`${i18n.t("sessionInfo.updatedAt")}`}{" "}
{session.updatedAt &&
format(parseISO(session.updatedAt), "dd/mm/yy HH:mm")}
</Typography>
<Button
color="primary"
variant="contained"
onClick={handleDisconectSession}
>
{`${i18n.t("sessionInfo.buttons.disconnect")}`}
</Button>
{/* <Typography component="p" variant="h6">
{`${i18n.t("sessionInfo.battery")}${session.battery}%`} {`${i18n.t("sessionInfo.battery")}${session.battery}%`}
</Typography> </Typography>
<Typography color="textSecondary"> <Typography color="textSecondary">
{`${i18n.t("sessionInfo.charging")}${session.plugged} `} {`${i18n.t("sessionInfo.charging")}${session.plugged} `}
</Typography> </Typography> */}
</div> </>
); );
}; };

View File

@@ -5,7 +5,6 @@ import openSocket from "socket.io-client";
import { makeStyles } from "@material-ui/core/styles"; import { makeStyles } from "@material-ui/core/styles";
import Grid from "@material-ui/core/Grid";
import Paper from "@material-ui/core/Paper"; import Paper from "@material-ui/core/Paper";
import SessionInfo from "../../components/SessionInfo"; import SessionInfo from "../../components/SessionInfo";
import Qrcode from "../../components/Qrcode"; import Qrcode from "../../components/Qrcode";
@@ -13,19 +12,19 @@ import Qrcode from "../../components/Qrcode";
const useStyles = makeStyles(theme => ({ const useStyles = makeStyles(theme => ({
root: { root: {
display: "flex", display: "flex",
alignItems: "center",
justifyContent: "center",
padding: theme.spacing(4), padding: theme.spacing(4),
}, },
content: {
flexGrow: 1,
overflow: "auto",
},
paper: { paper: {
padding: theme.spacing(2), padding: theme.spacing(2),
display: "flex", display: "flex",
width: 400,
overflow: "auto", overflow: "auto",
alignItems: "center",
flexDirection: "column", flexDirection: "column",
alignItems: "center",
justifyContent: "center",
}, },
fixedHeight: { fixedHeight: {
height: 640, height: 640,
@@ -42,9 +41,9 @@ const WhatsAuth = () => {
useEffect(() => { useEffect(() => {
const fetchSession = async () => { const fetchSession = async () => {
try { try {
const res = await api.get("/whatsapp/session/1"); const { data } = await api.get("/whatsapp/session/1");
setQrCode(res.data.qrcode); setQrCode(data.qrcode);
setSession(res.data); setSession(data);
} catch (err) { } catch (err) {
console.log(err); console.log(err);
} }
@@ -52,16 +51,25 @@ const WhatsAuth = () => {
fetchSession(); fetchSession();
}, []); }, []);
console.log("session", session);
useEffect(() => { useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL); const socket = openSocket(process.env.REACT_APP_BACKEND_URL);
socket.on("qrcode", data => { socket.on("session", data => {
if (data.action === "update") { if (data.action === "update") {
setQrCode(data.qr); 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") { if (data.action === "authentication") {
setQrCode(""); setQrCode("");
setSession(data.session); setSession(data.session);
@@ -69,6 +77,12 @@ const WhatsAuth = () => {
} }
}); });
socket.on("session", data => {
if (data.action === "logout") {
setSession(data.session);
}
});
return () => { return () => {
socket.disconnect(); socket.disconnect();
}; };
@@ -76,21 +90,15 @@ const WhatsAuth = () => {
return ( return (
<div className={classes.root}> <div className={classes.root}>
<Grid container spacing={3}> {session && session.status === "disconnected" ? (
{session.status === "pending" ? ( <Paper className={classes.paper}>
<Grid item xs={12}> <Qrcode qrCode={qrCode} />
<Paper className={classes.paper}> </Paper>
<Qrcode qrCode={qrCode} /> ) : (
</Paper> <Paper className={classes.paper}>
</Grid> <SessionInfo session={session} />
) : ( </Paper>
<Grid item xs={12}> )}
<Paper className={classes.paper}>
<SessionInfo session={session} />
</Paper>
</Grid>
)}
</Grid>
</div> </div>
); );
}; };

View File

@@ -45,6 +45,10 @@ const messages = {
status: "Status:", status: "Status:",
battery: "Battery:", battery: "Battery:",
charging: "Loading:", charging: "Loading:",
updatedAt: "Updated at:",
buttons: {
disconnect: "Disconnect",
},
}, },
qrCode: { qrCode: {
message: "Read QrCode to start the session", message: "Read QrCode to start the session",

View File

@@ -45,6 +45,10 @@ const messages = {
status: "Status: ", status: "Status: ",
battery: "Bateria: ", battery: "Bateria: ",
charging: "Carregando: ", charging: "Carregando: ",
updatedAt: "Atualizado em:",
buttons: {
disconnect: "Desconectar",
},
}, },
qrCode: { qrCode: {
message: "Leia o QrCode para iniciar a sessão", message: "Leia o QrCode para iniciar a sessão",