feat: Add code to enable sending of information via socket to application monitoring dashboard

pull/22/head
adriano 2024-02-09 09:35:19 -03:00
parent c444012963
commit 051e1b3b2a
3 changed files with 210 additions and 211 deletions

View File

@ -4,50 +4,72 @@ import ShowWhatsAppService from "../services/WhatsappService/ShowWhatsAppService
import { logger } from "../utils/logger"; import { logger } from "../utils/logger";
import * as Sentry from "@sentry/node"; import * as Sentry from "@sentry/node";
import Whatsapp from "../models/Whatsapp"; import Whatsapp from "../models/Whatsapp";
import omnihitDashboardSession from "../helpers/OmnhitDashboardSession";
// type IndexQuery = { // type IndexQuery = {
// centro_custo: string; // centro_custo: string;
// }; // };
export const wbotMonitorRemote = async (req: Request, res: Response): Promise<Response> => { export const wbotMonitorRemote = async (
req: Request,
res: Response
): Promise<Response> => {
const { action, whatsappId, reason } = req.body;
const { action, whatsappId, reason } = req.body console.log(
"action: ",
action,
" | whatsappId: ",
whatsappId,
" | reason: ",
reason
);
console.log('action: ', action, ' | whatsappId: ', whatsappId, ' | reason: ', reason) console.log("-----------> ACTION: ", req.body["action"]);
console.log('-----------> ACTION: ', req.body['action']) const whatsapp: any = await Whatsapp.findByPk(whatsappId, { raw: true });
const whatsapp: any = await Whatsapp.findByPk(whatsappId, { raw: true })
if (whatsapp) { if (whatsapp) {
if (action === 'disconnected') { if (action === "disconnected") {
logger.info(`Disconnected session: ${whatsapp.name}, reason: ${reason}`); logger.info(`Disconnected session: ${whatsapp.name}, reason: ${reason}`);
} }
let data: any = {};
data.whatsapp = { ...whatsapp, DB: process.env.DB_NAME };
data.action = "update";
await omnihitDashboardSession(data);
const io = getIO(); const io = getIO();
io.emit("whatsappSession", { io.emit("whatsappSession", {
action: "update", action: "update",
session: whatsapp session: whatsapp
}); });
} }
return res.status(200).json({ "message": "Ok" }); return res.status(200).json({ message: "Ok" });
}; };
export const wbotMonitorQrcodeRemote = async (
req: Request,
res: Response
): Promise<Response> => {
const { whatsappId } = req.body;
console.log(
"-----------> QRCODE MONITOR whatsappId: ",
req.body["whatsappId"]
);
const whatsapp: any = await Whatsapp.findByPk(whatsappId, { raw: true });
export const wbotMonitorQrcodeRemote = async (req: Request, res: Response): Promise<Response> => {
const { whatsappId } = req.body
console.log('-----------> QRCODE MONITOR whatsappId: ', req.body['whatsappId'])
const whatsapp: any = await Whatsapp.findByPk(whatsappId, { raw: true })
// let whatsapp = await ShowWhatsAppService(whatsappId) // let whatsapp = await ShowWhatsAppService(whatsappId)
if (whatsapp) {
let data: any = {};
data.whatsapp = { ...whatsapp, DB: process.env.DB_NAME };
data.action = "update";
await omnihitDashboardSession(data);
}
if (whatsapp) { if (whatsapp) {
const io = getIO(); const io = getIO();
io.emit("whatsappSession", { io.emit("whatsappSession", {
@ -56,16 +78,22 @@ export const wbotMonitorQrcodeRemote = async (req: Request, res: Response): Prom
}); });
} }
return res.status(200).json({ "message": "Ok" }); return res.status(200).json({ message: "Ok" });
}; };
export const wbotMonitorQrcodeNumberRead = async (
req: Request,
res: Response
): Promise<Response> => {
const { number } = req.body;
console.log("-----------> number read: ", number);
export const wbotMonitorQrcodeNumberRead = async (req: Request, res: Response): Promise<Response> => { const msg = `Numero lido: ${number} \nEssa sessão de whatsapp foi desconectada porque o numero que esta descrito no nome dessa sessão não corresponde ao numero lido!`;
let data: any = {};
const { number } = req.body data.msg = msg;
data.action = "error";
console.log('-----------> number read: ', number) await omnihitDashboardSession(data);
const io = getIO(); const io = getIO();
io.emit("whatsappSession", { io.emit("whatsappSession", {
@ -73,9 +101,5 @@ export const wbotMonitorQrcodeNumberRead = async (req: Request, res: Response):
msg: `Numero lido: ${number} \nEssa sessão de whatsapp foi desconectada porque o numero que esta descrito no nome dessa sessão não corresponde ao numero lido!` msg: `Numero lido: ${number} \nEssa sessão de whatsapp foi desconectada porque o numero que esta descrito no nome dessa sessão não corresponde ao numero lido!`
}); });
return res.status(200).json({ "message": "Ok" }); return res.status(200).json({ message: "Ok" });
}; };

View File

@ -0,0 +1,24 @@
import axios from "axios";
async function omnihitDashboardSession(data: any) {
// console.log('DATA: ', data)
try {
await axios.post(
`${process.env.URL_DASHBOARD_SESSIONS}/api/v1/omnihit/monitor`,
data,
{
headers: {
Authorization: `Bearer ${process.env.TOKEN_DASHBOARD_SESSIONS}`
}
}
);
} catch (error) {
console.log(
`Post request error to ${process.env.URL_DASHBOARD_SESSIONS}/api/v1/omnihit/monitor`
);
}
}
export default omnihitDashboardSession;

View File

@ -13,85 +13,84 @@ import SchedulingNotify from "../models/SchedulingNotify";
import Ticket from "../models/Ticket"; import Ticket from "../models/Ticket";
import User from "../models/User"; import User from "../models/User";
import { Sequelize, Op } from "sequelize"; import { Sequelize, Op } from "sequelize";
import omnihitDashboardSession from "./OmnhitDashboardSession";
const fastFolderSize = require("fast-folder-size");
const fastFolderSize = require('fast-folder-size') const { promisify } = require("util");
const { promisify } = require('util') const fs = require("fs");
const fs = require('fs')
const { exec } = require("child_process"); const { exec } = require("child_process");
let _fifo: any let _fifo: any;
let scheduler_monitor: any; let scheduler_monitor: any;
let timeInterval = 5 let timeInterval = 5;
const monitor = async () => { const monitor = async () => {
let date = new Date();
let date = new Date() let day = date.getDate().toString().padStart(2, "0");
let month = (date.getMonth() + 1).toString().padStart(2, "0");
let day = date.getDate().toString().padStart(2, '0');
let month = (date.getMonth() + 1).toString().padStart(2, '0');
let year = date.getFullYear(); let year = date.getFullYear();
let hour = date.getHours() let hour = date.getHours();
let minute = date.getMinutes() let minute = date.getMinutes();
let fullDate = `${year}-${month}-${day}`; let fullDate = `${year}-${month}-${day}`;
let dateParm = `${fullDate} ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}:00` let dateParm = `${fullDate} ${hour.toString().padStart(2, "0")}:${minute
.toString()
.padStart(2, "0")}:00`;
//console.log(dateParm); //console.log(dateParm);
try { try {
const { schedulingNotifies, count, hasMore } =
const { schedulingNotifies, count, hasMore } = await ListSchedulingNotifyService({ searchParam: dateParm, pageNumber: "1" }); await ListSchedulingNotifyService({
searchParam: dateParm,
pageNumber: "1"
});
if (schedulingNotifies && schedulingNotifies.length > 0) { if (schedulingNotifies && schedulingNotifies.length > 0) {
for (let i = 0; i < schedulingNotifies.length; i++) { for (let i = 0; i < schedulingNotifies.length; i++) {
const ticket: any = await ShowTicketService(
const ticket: any = await ShowTicketService(+schedulingNotifies[i].ticketId); +schedulingNotifies[i].ticketId
);
let _ticket = await Ticket.findOne({ let _ticket = await Ticket.findOne({
where: { where: {
contactId: ticket.contactId, contactId: ticket.contactId,
status: { [Op.in]: ['open', 'pending'] } status: { [Op.in]: ["open", "pending"] }
} }
}) });
await deleteScheduleByTicketIdCache(schedulingNotifies[i].ticketId) await deleteScheduleByTicketIdCache(schedulingNotifies[i].ticketId);
await DeleteSchedulingNotifyService(schedulingNotifies[i].id) await DeleteSchedulingNotifyService(schedulingNotifies[i].id);
if (_ticket) continue if (_ticket) continue;
if (ticket.dataValues.status == 'closed') { if (ticket.dataValues.status == "closed") {
await ticket.update({ status: 'open' }) await ticket.update({ status: "open" });
} }
const userId: number = ticket.getDataValue('userId'); const userId: number = ticket.getDataValue("userId");
let userN = ''; let userN = "";
if(userId){ if (userId) {
const useer = await User.findByPk(userId); const useer = await User.findByPk(userId);
if(useer){ if (useer) {
const userName: string = useer.getDataValue('name'); const userName: string = useer.getDataValue("name");
userN = `*${userName}:* \n`; userN = `*${userName}:* \n`;
} }
} }
await new Promise(f => setTimeout(f, 3000)); await new Promise(f => setTimeout(f, 3000));
await SendWhatsAppMessage({ await SendWhatsAppMessage({
body: userN+schedulingNotifies[i].message, ticket body: userN + schedulingNotifies[i].message,
ticket
}); });
} }
} }
exec("df -h /", (error: any, stdout: any, stderr: any) => { exec("df -h /", (error: any, stdout: any, stderr: any) => {
if (error) { if (error) {
console.log(`exec error: ${error.message}`); console.log(`exec error: ${error.message}`);
return; return;
@ -101,8 +100,8 @@ const monitor = async () => {
return; return;
} }
stdout = stdout.split(/\r?\n/) stdout = stdout.split(/\r?\n/);
stdout = stdout[1].trim().split(/\s+/) stdout = stdout[1].trim().split(/\s+/);
// DISK SPACE MONITORING // DISK SPACE MONITORING
const io = getIO(); const io = getIO();
@ -116,84 +115,36 @@ const monitor = async () => {
} }
}); });
let data: any = {};
data.diskSpace = {
DB: process.env.DB_NAME,
size: stdout[1],
used: stdout[2],
available: stdout[3],
use: stdout[4]
};
data.action = "update";
omnihitDashboardSession(data);
}); });
// WHATS SESSION SIZE MONITORING
// const whatsapps = await ListWhatsAppsService();
// whatsapps.forEach(async whats => {
// const sourcePath = path.join(__dirname, `../../.wwebjs_auth/`, `session-bd_${whats.id}`)
// if (fs.existsSync(sourcePath)) {
// try {
// const fastFolderSizeAsync = promisify(fastFolderSize)
// let size = await fastFolderSizeAsync(sourcePath)
// size = convertBytes(size)
// // SESSION MONITORING
// const io = getIO();
// io.emit("whatsappSessionMonit", {
// action: "update",
// whatsappSessionSize: {
// id: whats.id,
// sessionSize: size
// }
// });
// }
// catch (err) {
// console.log('An error occurred while get info from the directory: ', err);
// }
// }
// else {
// // console.log('Directory not found to get size info: ', sourcePath)
// }
// });
} catch (error) { } catch (error) {
console.log('>>> SchedulingNotifiySendMessage.ts error: ', error) console.log(">>> SchedulingNotifiySendMessage.ts error: ", error);
} }
}; };
const SchedulingNotifySendMessage = async () => { const SchedulingNotifySendMessage = async () => {
try { try {
clearInterval(_fifo); clearInterval(_fifo);
await monitor() await monitor();
} catch (error) { } catch (error) {
console.log('error on SchedulingNotifySendMessage: ', error) console.log("error on SchedulingNotifySendMessage: ", error);
} } finally {
finally {
_fifo = setInterval(SchedulingNotifySendMessage, 5000); _fifo = setInterval(SchedulingNotifySendMessage, 5000);
} }
} };
_fifo = setInterval(SchedulingNotifySendMessage, 5000); _fifo = setInterval(SchedulingNotifySendMessage, 5000);
module.exports = SchedulingNotifySendMessage;
module.exports = SchedulingNotifySendMessage