Merge branch 'whats_session_out' into dialogflow_sessions_out

pull/20/head
adriano 2023-05-22 12:11:19 -03:00
commit be12d318fd
6 changed files with 88 additions and 72 deletions

0
TEST_SERVER1.7z 100644
View File

View File

@ -211,7 +211,8 @@ app.post('/api/session', async function (req, res) {
session_num = numbered_sessions.map((e) => parseInt((e.name.split('->')[e.name.split('->').length - 1]).trim().match(/\d+/)[0]))
console.log('session_num', session_num)
console.log('session_num', session_num)
}
let index = 1;

View File

@ -19,8 +19,8 @@ const express = require('express');
const FormData = require('form-data');
// const { MessageMedia } = require('./node_modules/whatsapp-web.js/src/structures');
let whatsappWebGlobalPath = path.join(process.env.NODE_PATH, 'whatsapp-web.js', '/src/structures');
whatsappWebGlobalPath = whatsappWebGlobalPath.replace(':','')
let whatsappWebGlobalPath = path.join(process.env.NODE_PATH, 'whatsapp-web.js', '/src/structures');
whatsappWebGlobalPath = whatsappWebGlobalPath.replace(':', '')
console.log('whatsappWebGlobalPath: ', whatsappWebGlobalPath)
console.log('process.env.NODE_PATH: ', process.env.NODE_PATH)
@ -176,20 +176,25 @@ client.on("qr", async qr => {
// omnihit.qrcode(process.env.MOBILEUID, process.env.MOBILENAME, qr);
// omnihit.monitor(process.env.MOBILEUID, process.env.MOBILENAME, "STARTUP");
asking_qrcode = true
asking_qrcode = true
await new Promise((resolve, reject) => {
dbcc.query("UPDATE Whatsapps SET qrcode = ?, status = ?, retries = ? where id = ?", [qr, 'qrcode', 0, process.env.WHATSAPP_ID],
dbcc.query("UPDATE Whatsapps SET qrcode = ?, status = ?, retries = ? where id = ?", [qr, 'qrcode', 0, process.env.WHATSAPP_ID],
function (err, result) {
if (err)
console.log("ERROR: " + err);
// else
// console.log('myslq result: ', result);
});
function (err, result) {
if (err) {
console.log("ERROR: " + err);
reject(err)
}
else {
resolve(result)
}
});
})
let url = process.env.CLIENT_URL + '/whatsapp/connection/qrcode'
try {
@ -271,15 +276,25 @@ client.on("ready", async () => {
dbcc.query("UPDATE Whatsapps SET qrcode = ?, status = ?, retries = ?, number = ? where id = ?", ["", 'CONNECTED', 0, client.info["wid"]["user"], process.env.WHATSAPP_ID],
await new Promise((resolve, reject) => {
dbcc.query("UPDATE Whatsapps SET qrcode = ?, status = ?, retries = ?, number = ? where id = ?", ["", 'CONNECTED', 0, client.info["wid"]["user"], process.env.WHATSAPP_ID],
function (err, result) {
if (err) {
console.log("ERROR: " + err);
reject(err)
}
else {
resolve(result)
}
});
})
function (err, result) {
if (err)
console.log("ERROR: " + err);
// else
// console.log('myslq result: ', result);
});
let url = process.env.CLIENT_URL + '/whatsapp/connection/qrcode'
@ -384,7 +399,7 @@ client.on("message_ack", async (msg, ack) => {
});
socketIo.on('send_message', async data => {
console.log('#')
console.log('--------------> send_message from number: ', mobileuid);
console.log('--------------> send_message to number: ', data.msg.number);
@ -400,7 +415,7 @@ socketIo.on('send_message', async data => {
socketIo.on('send_media', async data => {
console.log('#')
console.log('--------------> send_message from number: ', mobileuid);
console.log('--------------> send_message to number: ', data.msg.number);
@ -414,7 +429,7 @@ socketIo.on('send_media', async data => {
if (media && !media.filename)
media.filename = data.msg.media.filename
const sentMessage = await client.sendMessage(data.msg.number, media, { sendAudioAsVoice: data.msg.sendAudioAsVoice });
// const fullFilename = process.cwd() + process.env.MEDIA_DOWNLOAD_IN + data.msg.media.filename;
@ -683,16 +698,15 @@ const getWbotMessage = async (messageId, number, limit,) => {
}
async function whatsappMonitor(newState, omnihit_url, data) {
async function whatsappMonitor(newState, omnihit_url, data) {
dbcc.query("UPDATE Whatsapps SET status = ? where id = ?", [newState, process.env.WHATSAPP_ID],
function (err, result) {
if (err)
console.log("ERROR: " + err);
const whatsapp = await whatsappUpdateStatus(newState)
// else
// console.log('myslq result: ', result);
});
if (whatsapp && whatsapp.affectedRows) {
console.log('whatsapp status update affectedRows: ', whatsapp.affectedRows)
}
// console.log(' whatsappwhatsappwhatsappwhatsapp: ', whatsapp)
try {
@ -702,6 +716,23 @@ async function whatsappMonitor(newState, omnihit_url, data) {
}
}
async function whatsappUpdateStatus(newState) {
return await new Promise((resolve, reject) => {
dbcc.query("UPDATE Whatsapps SET status = ? where id = ?", [newState, process.env.WHATSAPP_ID],
function (err, result) {
if (err) {
console.log("ERROR: " + err);
reject(err);
}
else {
resolve(result);
}
});
});
}
async function handleMessage(msg) {
console.log('Entrou no message_create');
@ -709,7 +740,7 @@ async function handleMessage(msg) {
let msgContact = null;
let media = null;
if (msg.fromMe) {
if (msg.fromMe) {
msgContact = await client.getContactById(msg.to);
@ -740,7 +771,7 @@ async function handleMessage(msg) {
quotedMsg: quotedMsg ? quotedMsg.id.id : null,
media: media
};
socketIo.emit("message_create", data);
@ -868,6 +899,14 @@ async function monitor() {
console.log(`WHATSAPP_ID: ${process.env.WHATSAPP_ID} | CLIENT MOBILEUID: ${mobileuid} | NAME: ${process.env.MOBILENAME} | ENV MOBILEUID: ${process.env.MOBILEUID} | STATUS: ${stat}`)
if (stat && stat === 'CONNECTED') {
const result = await whatsappUpdateStatus('CONNECTED')
if (result)
console.log(`Update status to CONNECTED WHATSAPP_ID: ${process.env.WHATSAPP_ID} => result.affectedRows: ${result.affectedRows}`)
}
} catch (error) {
//new Date(new Date() + 'UTC')

View File

@ -107,6 +107,7 @@ export const store = async (req: Request, res: Response): Promise<Response> => {
number: Yup.string()
.required()
.matches(/^\d+$/, "Invalid number format. Only numbers is allowed.")
.matches(/^55\d+$/, "The number must start with 55.")
});
try {
@ -173,10 +174,9 @@ export const update = async (
const schema = Yup.object().shape({
name: Yup.string(),
number: Yup.string().matches(
/^\d+$/,
"Invalid number format. Only numbers is allowed."
)
number: Yup.string()
.matches(/^\d+$/,"Invalid number format. Only numbers is allowed.")
.matches(/^55\d+$/, "The number must start with 55.")
});
try {

View File

@ -14,9 +14,7 @@ export const wbotMonitorRemote = async (req: Request, res: Response): Promise<Re
const { action, whatsappId, reason } = req.body
console.log('-----------> ACTION: ', req.body['action'])
// let whatsapp = await ShowWhatsAppService(whatsappId)
console.log('-----------> ACTION: ', req.body['action'])
const whatsapp: any = await Whatsapp.findByPk(whatsappId, { raw: true })

View File

@ -946,7 +946,7 @@ const handleMessage = async (
if (index == -1) {
// console.log('-----------------> LST: ', lst)
// console.log('-----------------> LST: ', lst):q
lst.push({ id: msg.id.id })
@ -1019,6 +1019,12 @@ const handleMessage = async (
// const chat = await msg.getChat();
const chat = wbot.chat
// if(chat.isGroup){
// console.log('This message is from a Group and will be ignored!')
// return
// }
// console.log('----------> chat: ', JSON.parse(JSON.stringify(chat)))
// if (chat.isGroup) {
@ -1182,41 +1188,12 @@ const handleMessage = async (
} catch (err) {
Sentry.captureException(err);
logger.error(`Error handling whatsapp message: Err: ${err}`);
const whatsapp = await ShowWhatsAppService(wbot.id!);
//Solução para contornar erro de sessão
if ((`${err}`).includes("Evaluation failed: r")) {
const sourcePath = path.join(__dirname, `../../../.wwebjs_auth/sessions/log`)
let log = new Date(new Date() + 'UTC');
const dateToday = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR })))
if (whatsapp.status == 'CONNECTED') {
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)
}
}
else if (`${err}`.includes('[object Object]')) {
await _restore(whatsapp, 'auto_object_error')
}
logger.error(`Error handling whatsapp message: Err: ${err}`);
}
};
const handleMsgAck = async (msg_id: any, ack: any) => {
await new Promise(r => setTimeout(r, 500));
const io = getIO();
@ -1233,11 +1210,12 @@ const handleMsgAck = async (msg_id: any, ack: any) => {
]
});
if (!messageToUpdate) {
console.log(`Not found the MESSAGE ID ${msg_id}to change the ACK into the Message table`)
return;
}
await messageToUpdate.update({ ack });
// console.log('ACK messageToUpdate: ', JSON.parse(JSON.stringify(messageToUpdate)))
console.log('ACK messageToUpdate: ', JSON.parse(JSON.stringify(messageToUpdate)))
io.to(messageToUpdate.ticketId.toString()).emit("appMessage", {
action: "update",