Correção do restore

pull/3/head
adriano 2022-07-12 09:37:34 -03:00
parent bb04db9708
commit 5444baafc3
7 changed files with 453 additions and 424 deletions

View File

@ -0,0 +1 @@
Whatsapp id: 33 | Fri Jul 08 2022 15:02:50 GMT-0300 (Brasilia Standard Time)

View File

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

View File

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

View File

@ -19,9 +19,9 @@ const SetTicketMessagesAsRead = async (ticket: Ticket): Promise<void> => {
try { try {
const wbot = await GetTicketWbot(ticket); const wbot = await GetTicketWbot(ticket);
await wbot.sendSeen(
`${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us` await wbot.sendSeen(`${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us`);
);
} catch (err) { } catch (err) {
logger.warn( logger.warn(
`Could not mark messages as read. Maybe whatsapp session disconnected? Err: ${err}` `Could not mark messages as read. Maybe whatsapp session disconnected? Err: ${err}`

View File

@ -10,6 +10,7 @@ const fs = require('fs')
import { copyFolder } from "../helpers/CopyFolder"; import { copyFolder } from "../helpers/CopyFolder";
import path from "path"; import path from "path";
import { number } from "yup"; import { number } from "yup";
import { removeDir } from "../helpers/DeleteDirectory";
interface Session extends Client { interface Session extends Client {
id?: number; 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) => { return new Promise((resolve, reject) => {
try { try {
@ -63,23 +64,6 @@ export const initWbot = async (whatsapp: Whatsapp): Promise<Session> => {
puppeteer: { args: ['--no-sandbox', '--disable-setuid-sandbox'], executablePath: process.env.CHROME_BIN || undefined }, 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(); wbot.initialize();
@ -173,9 +157,12 @@ export const initWbot = async (whatsapp: Whatsapp): Promise<Session> => {
console.log(' whatsIndex: ', whatsIndex) console.log(' whatsIndex: ', whatsIndex)
if (whatsIndex !== -1) { if (whatsIndex !== -1 || backupSessionRestore) {
if (whatsIndex !== -1) {
backupSession.splice(whatsIndex, 1); backupSession.splice(whatsIndex, 1);
}
setTimeout(async () => { setTimeout(async () => {
@ -183,6 +170,9 @@ export const initWbot = async (whatsapp: Whatsapp): Promise<Session> => {
const destPath = path.join(__dirname, `../../.wwebjs_auth/sessions`, `session-bd_${whatsapp.id}`) const destPath = path.join(__dirname, `../../.wwebjs_auth/sessions`, `session-bd_${whatsapp.id}`)
if (fs.existsSync(path.join(__dirname, `../../.wwebjs_auth/sessions`))) { if (fs.existsSync(path.join(__dirname, `../../.wwebjs_auth/sessions`))) {
await removeDir(destPath)
// copy the good session for backup dir // copy the good session for backup dir
copyFolder(sourcePath, destPath) copyFolder(sourcePath, destPath)
} }
@ -193,9 +183,9 @@ export const initWbot = async (whatsapp: Whatsapp): Promise<Session> => {
console.log(` COPIOU backup whatsapp.id ---------------------------------->${whatsapp.id}`) 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 wbotMonitor from "./wbotMonitor";
import { logger } from "../../utils/logger"; 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" }); await whatsapp.update({ status: "OPENING" });
const io = getIO(); const io = getIO();
@ -15,7 +15,7 @@ export const StartWhatsAppSession = async (whatsapp: Whatsapp): Promise<void> =>
}); });
try { try {
const wbot = await initWbot(whatsapp); const wbot = await initWbot(whatsapp, backupSession);
wbotMessageListener(wbot); wbotMessageListener(wbot);
wbotMonitor(wbot, whatsapp); wbotMonitor(wbot, whatsapp);
} catch (err) { } catch (err) {

View File

@ -44,6 +44,7 @@ import data_ura from './ura'
import msg_client_transfer from './ura_msg_transfer' import msg_client_transfer from './ura_msg_transfer'
import final_message from "./ura_final_message"; import final_message from "./ura_final_message";
import SendWhatsAppMessage from "./SendWhatsAppMessage"; import SendWhatsAppMessage from "./SendWhatsAppMessage";
import Whatsapp from "../../models/Whatsapp";
// //
@ -353,6 +354,8 @@ const handleMessage = async (
return; return;
} }
try { try {
let msgContact: WbotContact; let msgContact: WbotContact;
let groupContact: Contact | undefined; let groupContact: Contact | undefined;
@ -741,6 +744,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 // test del
// console.log('WBOT.id: ',wbot.id) // console.log('WBOT.id: ',wbot.id)
@ -767,6 +781,30 @@ const handleMessage = async (
Sentry.captureException(err); Sentry.captureException(err);
logger.error(`Error handling whatsapp message: Err: ${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 whatsapp = await ShowWhatsAppService(wbot.id!);
if (whatsapp.status == 'CONNECTED') {
console.log('ENTROU NO RESTORE...')
let timestamp = Math.floor(Date.now() / 1000)
fs.writeFile(`${sourcePath}/${timestamp}.txt`, `Whatsapp id: ${whatsapp.id} | ${log}`, (error)=>{});
await restartWhatsSession(whatsapp)
console.log('...PASSOU O RESTORE')
}
}
} }
}; };