Criação do monitoramento da sessão

pull/1/head
adriano 2022-06-28 21:34:43 -03:00
parent c5c13f2b34
commit 7fd739f812
6 changed files with 110 additions and 49 deletions

View File

@ -25,6 +25,7 @@
"dotenv": "^8.2.0", "dotenv": "^8.2.0",
"express": "^4.17.1", "express": "^4.17.1",
"express-async-errors": "^3.1.1", "express-async-errors": "^3.1.1",
"fast-folder-size": "^1.7.0",
"fs-extra": "^10.1.0", "fs-extra": "^10.1.0",
"http-graceful-shutdown": "^2.3.2", "http-graceful-shutdown": "^2.3.2",
"jsonwebtoken": "^8.5.1", "jsonwebtoken": "^8.5.1",

View File

@ -12,8 +12,9 @@ import ShowWhatsAppService from "../services/WhatsappService/ShowWhatsAppService
import UpdateWhatsAppService from "../services/WhatsappService/UpdateWhatsAppService"; import UpdateWhatsAppService from "../services/WhatsappService/UpdateWhatsAppService";
import AppError from "../errors/AppError"; import AppError from "../errors/AppError";
import path from 'path'; import path from 'path';
interface WhatsappData { interface WhatsappData {
name: string; name: string;
@ -25,8 +26,8 @@ interface WhatsappData {
} }
export const index = async (req: Request, res: Response): Promise<Response> => { export const index = async (req: Request, res: Response): Promise<Response> => {
const whatsapps = await ListWhatsAppsService(); const whatsapps = await ListWhatsAppsService();
return res.status(200).json(whatsapps); return res.status(200).json(whatsapps);
}; };
@ -43,7 +44,7 @@ export const store = async (req: Request, res: Response): Promise<Response> => {
if (req.user.profile !== "master") { if (req.user.profile !== "master") {
throw new AppError("ERR_NO_PERMISSION", 403); throw new AppError("ERR_NO_PERMISSION", 403);
} }
const { whatsapp, oldDefaultWhatsapp } = await CreateWhatsAppService({ const { whatsapp, oldDefaultWhatsapp } = await CreateWhatsAppService({
name, name,
status, status,
@ -75,7 +76,7 @@ export const show = async (req: Request, res: Response): Promise<Response> => {
const { whatsappId } = req.params; const { whatsappId } = req.params;
const whatsapp = await ShowWhatsAppService(whatsappId); const whatsapp = await ShowWhatsAppService(whatsappId);
return res.status(200).json(whatsapp); return res.status(200).json(whatsapp);
}; };
@ -114,14 +115,14 @@ export const remove = async (
if (req.user.profile !== "master") { if (req.user.profile !== "master") {
throw new AppError("ERR_NO_PERMISSION", 403); throw new AppError("ERR_NO_PERMISSION", 403);
} }
const { whatsappId } = req.params; const { whatsappId } = req.params;
await DeleteWhatsAppService(whatsappId); await DeleteWhatsAppService(whatsappId);
removeDir(path.join(process.cwd(),'.wwebjs_auth', `session-bd_${whatsappId}`)) removeDir(path.join(process.cwd(), '.wwebjs_auth', `session-bd_${whatsappId}`))
removeWbot(+whatsappId); removeWbot(+whatsappId);
console.log('Deleteou o whatsapp service com id = ', whatsappId) console.log('Deleteou o whatsapp service com id = ', whatsappId)
@ -130,7 +131,7 @@ export const remove = async (
io.emit("whatsapp", { io.emit("whatsapp", {
action: "delete", action: "delete",
whatsappId: +whatsappId whatsappId: +whatsappId
}); });
return res.status(200).json({ message: "Whatsapp deleted." }); return res.status(200).json({ message: "Whatsapp deleted." });
}; };

View File

@ -0,0 +1,23 @@
const fsPromises = require("fs/promises");
const fs = require('fs-extra')
// Delete a directory and its children
export const convertBytes = (bytes: number,) => {
const sizes = ["Bytes", "KB", "MB", "GB", "TB"]
if (bytes == 0) {
return "n/a"
}
const i = +(Math.floor(Math.log(bytes) / Math.log(1024)))
if (i == 0) {
return bytes + " " + sizes[i]
}
// return (bytes / Math.pow(1024, i)).toFixed(1) + " " + sizes[i]
return (bytes / Math.pow(1024, i)).toFixed(1)
}

View File

@ -1,70 +1,107 @@
import SetTicketMessagesAsRead from "../helpers/SetTicketMessagesAsRead"; import SetTicketMessagesAsRead from "../helpers/SetTicketMessagesAsRead";
import ShowTicketService from "../services/TicketServices/ShowTicketService"; import ShowTicketService from "../services/TicketServices/ShowTicketService";
import SendWhatsAppMessage from "../services/WbotServices/SendWhatsAppMessage"; import SendWhatsAppMessage from "../services/WbotServices/SendWhatsAppMessage";
import ListSchedulingNotifyService from "../services/SchedulingNotifyServices/ListSchedulingNotifyService";
import DeleteSchedulingNotifyService from "../services/SchedulingNotifyServices/DeleteSchedulingNotifyService";
import ListSchedulingNotifyService from "../services/SchedulingNotifyServices/ListSchedulingNotifyService";
let scheduler_monitor:any; import DeleteSchedulingNotifyService from "../services/SchedulingNotifyServices/DeleteSchedulingNotifyService";
import { getIO } from "../libs/socket";
import ListWhatsAppsService from "../services/WhatsappService/ListWhatsAppsService";
import path from "path";
import { convertBytes } from "./ConvertBytes";
const fastFolderSize = require('fast-folder-size')
const { promisify } = require('util')
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 day = date.getDate().toString().padStart(2, '0');
let month = (date.getMonth()+1).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 } = await ListSchedulingNotifyService({ searchParam: dateParm, pageNumber: "1" }); const { schedulingNotifies, count, hasMore } = await ListSchedulingNotifyService({ searchParam: dateParm, pageNumber: "1" });
// console.log('schedulingNotifies: ',schedulingNotifies)
if(schedulingNotifies && schedulingNotifies.length>0){ // console.log('schedulingNotifies: ',schedulingNotifies)
if (schedulingNotifies && schedulingNotifies.length > 0) {
const ticket = await ShowTicketService(schedulingNotifies[0].ticketId); const ticket = await ShowTicketService(schedulingNotifies[0].ticketId);
SetTicketMessagesAsRead(ticket); SetTicketMessagesAsRead(ticket);
await SendWhatsAppMessage({
body: schedulingNotifies[0].message, ticket
});
DeleteSchedulingNotifyService(schedulingNotifies[0].id)
}
const whatsapps = await ListWhatsAppsService();
whatsapps.forEach(async whats => {
console.log('whats id: ', whats.id)
const sourcePath = path.join(__dirname, `../../.wwebjs_auth/`, `session-bd_${whats.id}`)
const fastFolderSizeAsync = promisify(fastFolderSize)
let size = await fastFolderSizeAsync(sourcePath)
size = convertBytes(size)
await SendWhatsAppMessage({ console.log(size)
body: schedulingNotifies[0].message, ticket
}); // SESSION MONITORING
// const io = getIO();
DeleteSchedulingNotifyService(schedulingNotifies[0].id) // io.emit("whatsappSessionMonit", {
// action: "update",
} // whatsappSessionSize: {
// id: whats.id,
// sessionSize: size
// }
// });
});
} catch (error) { } catch (error) {
console.log('>>> SchedulingNotifiySendMessage.ts error: ', error) console.log('>>> SchedulingNotifiySendMessage.ts error: ', error)
stopSchedulingMonitor() stopSchedulingMonitor()
startSchedulingMonitor(timeInterval) startSchedulingMonitor(timeInterval)
} }
}; };
export const startSchedulingMonitor =async (mileseconds: number) => { export const startSchedulingMonitor = async (mileseconds: number) => {
timeInterval = mileseconds timeInterval = mileseconds
scheduler_monitor = setInterval(monitor, mileseconds) scheduler_monitor = setInterval(monitor, mileseconds)
} }
export const stopSchedulingMonitor =async ( ) => {
export const stopSchedulingMonitor = async () => {
clearInterval(scheduler_monitor) clearInterval(scheduler_monitor)
@ -73,4 +110,3 @@ export const stopSchedulingMonitor =async ( ) => {

View File

@ -157,7 +157,7 @@ const monitor = async () => {
if (countTest == 0) { if (countTest == 0) {
try { try {
// console.log(' Carregando usuárion no listUserId...') console.log(' Carregando usuárion no listUserId...')
listUserId = await ListUserParamiterService({ profile: 'user' }) listUserId = await ListUserParamiterService({ profile: 'user' })
} catch (error) { } catch (error) {

View File

@ -16,4 +16,4 @@ StartAllWhatsAppsSessions();
gracefulShutdown(server); gracefulShutdown(server);
startSchedulingMonitor(5000) startSchedulingMonitor(5000)
startWhoIsOnlineMonitor(2000) startWhoIsOnlineMonitor(4000)