Merge pull request #1 from AdrianoRobson/frontend

Frontend
pull/2/head
Renato Di Giacomo 2022-07-20 12:16:50 -03:00 committed by GitHub
commit 390772eb91
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 542 additions and 437 deletions

View File

@ -37,9 +37,6 @@ export const index = async (req: Request, res: Response): Promise<Response> => {
export const store = async (req: Request, res: Response): Promise<Response> => {
const { ticketId } = req.params;
const { body, quotedMsg }: MessageData = req.body;
const medias = req.files as Express.Multer.File[];

View File

@ -44,7 +44,7 @@ const restart = async (req: Request, res: Response): Promise<Response> => {
const whatsapp = await ShowWhatsAppService(whatsappId);
await restartWhatsSession(whatsapp)
restartWhatsSession(whatsapp, true)
return res.status(200).json({ message: "Starting session." });
};

View File

@ -10,7 +10,7 @@ const fsPromises = require("fs/promises");
const fs = require('fs')
// Restart session
export const restartWhatsSession = async (whatsapp: Whatsapp) => {
export const restartWhatsSession = async (whatsapp: Whatsapp, backupSession: boolean = false) => {
console.log('RESTARTING THE whatsapp.id: ', whatsapp.id)
@ -34,6 +34,6 @@ export const restartWhatsSession = async (whatsapp: Whatsapp) => {
console.log('RESTARTING SESSION...')
await StartWhatsAppSession(whatsapp);
await StartWhatsAppSession(whatsapp, backupSession);
}

View File

@ -1,8 +1,17 @@
import path from "path";
import { getIO } from "../libs/socket";
import Message from "../models/Message";
import Ticket from "../models/Ticket";
import ShowWhatsAppService from "../services/WhatsappService/ShowWhatsAppService";
import { logger } from "../utils/logger";
import GetTicketWbot from "./GetTicketWbot";
import fs from 'fs';
import { restartWhatsSession } from "./RestartWhatsSession";
import { Session } from "@sentry/types";
import { splitDateTime } from "./SplitDateTime";
import { format } from "date-fns";
import ptBR from 'date-fns/locale/pt-BR';
const SetTicketMessagesAsRead = async (ticket: Ticket): Promise<void> => {
await Message.update(
@ -18,14 +27,43 @@ const SetTicketMessagesAsRead = async (ticket: Ticket): Promise<void> => {
await ticket.update({ unreadMessages: 0 });
try {
const wbot = await GetTicketWbot(ticket);
await wbot.sendSeen(
`${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us`
);
// test del
// throw new Error('Throw makes it go boom!')
//
await wbot.sendSeen(`${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us`);
} catch (err) {
logger.warn(
`Could not mark messages as read. Maybe whatsapp session disconnected? Err: ${err}`
);
//Solução para contornar erro de sessão
if ((`${err}`).includes("Evaluation failed: r") && ticket.whatsappId) {
const sourcePath = path.join(__dirname,`../../.wwebjs_auth/sessions`)
const dateToday = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR })))
const whatsapp = await ShowWhatsAppService(ticket.whatsappId);
if (whatsapp && whatsapp.status == 'CONNECTED') {
console.log('SetTicketMessagesAsRead.ts - ENTROU NO RESTORE...')
let timestamp = Math.floor(Date.now() / 1000)
fs.writeFile(`${sourcePath}/${timestamp}_SetTicketMessagesAsRead.txt`, `Whatsapp id: ${whatsapp.id} \nDate: ${dateToday.fullDate} ${dateToday.fullTime} \nFile: SetTicketMessagesAsRead.ts \nError: ${err}`, (error)=>{});
await restartWhatsSession(whatsapp)
console.log('...PASSOU O RESTORE - SetTicketMessagesAsRead.ts ')
}
}
}
const io = getIO();

View File

@ -10,6 +10,7 @@ const fs = require('fs')
import { copyFolder } from "../helpers/CopyFolder";
import path from "path";
import { number } from "yup";
import { removeDir } from "../helpers/DeleteDirectory";
interface Session extends Client {
id?: number;
@ -43,7 +44,7 @@ const syncUnreadMessages = async (wbot: Session) => {
}
};
export const initWbot = async (whatsapp: Whatsapp): Promise<Session> => {
export const initWbot = async (whatsapp: Whatsapp, backupSessionRestore: boolean = false): Promise<Session> => {
return new Promise((resolve, reject) => {
try {
const io = getIO();
@ -59,23 +60,6 @@ export const initWbot = async (whatsapp: Whatsapp): Promise<Session> => {
puppeteer: { args: ['--no-sandbox', '--disable-setuid-sandbox'], executablePath: process.env.CHROME_BIN || undefined },
});
//OPÇÃO DEFAULT NAO MD
// const wbot: Session = new Client({session: sessionCfg,
// puppeteer: {executablePath: process.env.CHROME_BIN || undefined
// }
// });
//OPÇÃO MD ANTIGO COM ERRO
// const io = getIO();
// const sessionName = whatsapp.name;
// const SESSION_FILE_PATH = './session.json'
// let sessionCfg
// if(fs.existsSync(SESSION_FILE_PATH)){
// sessionCfg = require(SESSION_FILE_PATH)
// }
// const wbot: Session = new Client({ puppeteer: { headless: true }, clientId: 'bd_'+whatsapp.id})
wbot.initialize();
@ -169,9 +153,13 @@ export const initWbot = async (whatsapp: Whatsapp): Promise<Session> => {
console.log(' whatsIndex: ', whatsIndex)
if (whatsIndex !== -1) {
if (whatsIndex !== -1 || backupSessionRestore) {
if (whatsIndex !== -1) {
backupSession.splice(whatsIndex, 1);
}
setTimeout(async () => {
@ -179,6 +167,9 @@ export const initWbot = async (whatsapp: Whatsapp): Promise<Session> => {
const destPath = path.join(__dirname, `../../.wwebjs_auth/sessions`, `session-bd_${whatsapp.id}`)
if (fs.existsSync(path.join(__dirname, `../../.wwebjs_auth/sessions`))) {
await removeDir(destPath)
// copy the good session for backup dir
copyFolder(sourcePath, destPath)
}
@ -189,9 +180,9 @@ export const initWbot = async (whatsapp: Whatsapp): Promise<Session> => {
console.log(` COPIOU backup whatsapp.id ---------------------------------->${whatsapp.id}`)
}, 30000);
}, 55000);
console.log(' PASSOU NO TIMEOUT!')
console.log(' PASSOU NO TIMEOUT whatsapp.id: ',whatsapp.id)
}

View File

@ -5,7 +5,7 @@ import { getIO } from "../../libs/socket";
import wbotMonitor from "./wbotMonitor";
import { logger } from "../../utils/logger";
export const StartWhatsAppSession = async (whatsapp: Whatsapp): Promise<void> => {
export const StartWhatsAppSession = async (whatsapp: Whatsapp, backupSession: boolean = false): Promise<void> => {
await whatsapp.update({ status: "OPENING" });
const io = getIO();
@ -15,7 +15,7 @@ export const StartWhatsAppSession = async (whatsapp: Whatsapp): Promise<void> =>
});
try {
const wbot = await initWbot(whatsapp);
const wbot = await initWbot(whatsapp, backupSession);
wbotMessageListener(wbot);
wbotMonitor(wbot, whatsapp);
} catch (err) {

View File

@ -7,6 +7,9 @@ import { copyFolder } from "../../helpers/CopyFolder";
import { removeDir } from "../../helpers/DeleteDirectory";
import path from 'path';
import { format } from "date-fns";
import ptBR from 'date-fns/locale/pt-BR';
import {
Contact as WbotContact,
Message as WbotMessage,
@ -44,6 +47,8 @@ import data_ura from './ura'
import msg_client_transfer from './ura_msg_transfer'
import final_message from "./ura_final_message";
import SendWhatsAppMessage from "./SendWhatsAppMessage";
import Whatsapp from "../../models/Whatsapp";
import { splitDateTime } from "../../helpers/SplitDateTime";
//
@ -353,6 +358,8 @@ const handleMessage = async (
return;
}
try {
let msgContact: WbotContact;
let groupContact: Contact | undefined;
@ -741,6 +748,17 @@ const handleMessage = async (
//
// test del
// if (msg.body.trim() == 'broken') {
// throw new Error('Throw makes it go boom!')
// }
// console.log('>>>>>>>>>>>> whatsapp.status: ', whatsapp.status)
//
// test del
// console.log('WBOT.id: ',wbot.id)
@ -767,6 +785,32 @@ const handleMessage = async (
Sentry.captureException(err);
logger.error(`Error handling whatsapp message: Err: ${err}`);
//Solução para contornar erro de sessão
if ((`${err}`).includes("Evaluation failed: r")) {
const sourcePath = path.join(__dirname,`../../../.wwebjs_auth/sessions`)
let log = new Date(new Date() + 'UTC');
const dateToday = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR })))
const whatsapp = await ShowWhatsAppService(wbot.id!);
if (whatsapp.status == 'CONNECTED') {
console.log('wbotMessageListener.ts - ENTROU NO RESTORE...')
let timestamp = Math.floor(Date.now() / 1000)
fs.writeFile(`${sourcePath}/${timestamp}_wbotMessageListener.txt`, `Whatsapp id: ${whatsapp.id} \nDate: ${dateToday.fullDate} ${dateToday.fullTime} \nFile: wbotMessageListener.ts \nError: ${err}`, (error)=>{});
await restartWhatsSession(whatsapp)
console.log('...PASSOU O RESTORE - wbotMessageListener.ts ')
}
}
}
};

View File

@ -283,7 +283,7 @@ const reducer = (state, action) => {
state[messageIndex] = newMessage;
} else {
state.push(newMessage);
console.log(' TESTANDO NOVA MENSAGEM: ', newMessage)
// console.log(' TESTANDO NOVA MENSAGEM: ', newMessage)
}
return [...state];
@ -365,7 +365,7 @@ const MessagesList = ({ ticketId, isGroup }) => {
if (data.action === "create") {
dispatch({ type: "ADD_MESSAGE", payload: data.message });
console.log('* NOVA MENSAGEM CAP: ', data.message)
// console.log('* NOVA MENSAGEM CAP: ', data.message)
scrollToBottom();
}

View File

@ -61,7 +61,7 @@ const NotificationsPopOver = () => {
const { handleLogout } = useContext(AuthContext);
const [lastRef] = useState(+history.location.pathname.split("/")[2])
// const [lastRef] = useState(+history.location.pathname.split("/")[2])
// console.log('ticketIdRef: ',ticketIdRef, ' | lastRef: ',lastRef)
@ -168,12 +168,16 @@ const NotificationsPopOver = () => {
});
socket.on("appMessage", data => {
// console.log('******************* DATA: ', data)
if (
data.action === "create" &&
!data.message.read &&
(data.ticket.userId === user?.id || !data.ticket.userId)
) {
// console.log('entrou.............')
setNotifications(prevState => {
@ -195,6 +199,7 @@ const NotificationsPopOver = () => {
});
const shouldNotNotificate = (data.message.ticketId === ticketIdRef.current && document.visibilityState === "visible") ||
(data.ticket.userId && data.ticket.userId !== user?.id) ||
data.ticket.isGroup || !data.ticket.userId;
@ -203,7 +208,6 @@ const NotificationsPopOver = () => {
//console.log('PASSOU!!!!!!!')
handleNotifications(data);
}
});

View File

@ -221,6 +221,14 @@ const TicketListItem = ({ ticket }) => {
badge: classes.badgeStyle,
}}
/>
{/* <Badge
className={classes.newMessagesCount}
badgeContent={ticket.unreadMessages}
classes={{
badge: classes.badgeStyle,
}}
/> */}
</span>
}
/>

View File

@ -77,6 +77,9 @@ const reducer = (state, action) => {
newTickets.forEach(ticket => {
// console.log('* ticket.unreadMessages: ',ticket.unreadMessages)
const ticketIndex = state.findIndex(t => t.id === ticket.id);
if (ticketIndex !== -1) {
state[ticketIndex] = ticket;
@ -105,6 +108,8 @@ const reducer = (state, action) => {
if (action.type === "UPDATE_TICKET") {
const ticket = action.payload;
// console.log('++++++++++++ UPDATE_TICKET: ',ticket)
const ticketIndex = state.findIndex(t => t.id === ticket.id);
if (ticketIndex !== -1) {
state[ticketIndex] = ticket;
@ -116,12 +121,26 @@ const reducer = (state, action) => {
}
if (action.type === "UPDATE_TICKET_UNREAD_MESSAGES") {
const ticket = action.payload;
const message = action.payload.message
const ticket = action.payload.ticket;
const ticketIndex = state.findIndex(t => t.id === ticket.id);
if (ticketIndex !== -1) {
// console.log('>>>>>> ticketIndex: ', ticketIndex)
// console.log('&&&&&&& UPDATE_TICKET_UNREAD_MESSAGES ticket: ',ticket, ' |\n MESSAGE: ', message)
if(!message.fromMe){
ticket.unreadMessages +=1
}
state[ticketIndex] = ticket;
state.unshift(state.splice(ticketIndex, 1)[0]);
} else {
state.unshift(ticket);
}
@ -227,9 +246,13 @@ const TicketsList = (props) => {
socket.on("appMessage", data => {
if (data.action === "create" && shouldUpdateTicket(data.ticket)) {
// console.log('((((((((((((((((((( DATA.MESSAGE: ', data.message)
dispatch({
type: "UPDATE_TICKET_UNREAD_MESSAGES",
payload: data.ticket,
// payload: data.ticket,
payload: data,
});
}
});