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

@ -212,6 +212,7 @@ 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])) 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; let index = 1;

View File

@ -178,17 +178,22 @@ client.on("qr", async qr => {
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) { function (err, result) {
if (err)
console.log("ERROR: " + err);
// else if (err) {
// console.log('myslq result: ', result); console.log("ERROR: " + err);
reject(err)
}
else {
resolve(result)
}
}); });
})
let url = process.env.CLIENT_URL + '/whatsapp/connection/qrcode' let url = process.env.CLIENT_URL + '/whatsapp/connection/qrcode'
@ -271,16 +276,26 @@ client.on("ready", async () => {
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], dbcc.query("UPDATE Whatsapps SET qrcode = ?, status = ?, retries = ?, number = ? where id = ?", ["", 'CONNECTED', 0, client.info["wid"]["user"], process.env.WHATSAPP_ID],
function (err, result) { function (err, result) {
if (err)
console.log("ERROR: " + err);
// else if (err) {
// console.log('myslq result: ', result); console.log("ERROR: " + err);
reject(err)
}
else {
resolve(result)
}
}); });
})
let url = process.env.CLIENT_URL + '/whatsapp/connection/qrcode' let url = process.env.CLIENT_URL + '/whatsapp/connection/qrcode'
try { try {
@ -685,14 +700,13 @@ 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], const whatsapp = await whatsappUpdateStatus(newState)
function (err, result) {
if (err)
console.log("ERROR: " + err);
// else if (whatsapp && whatsapp.affectedRows) {
// console.log('myslq result: ', result); console.log('whatsapp status update affectedRows: ', whatsapp.affectedRows)
}); }
// console.log(' whatsappwhatsappwhatsappwhatsapp: ', whatsapp)
try { 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) { async function handleMessage(msg) {
console.log('Entrou no message_create'); console.log('Entrou no message_create');
@ -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}`) 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) { } catch (error) {
//new Date(new Date() + 'UTC') //new Date(new Date() + 'UTC')

View File

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

View File

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

View File

@ -946,7 +946,7 @@ const handleMessage = async (
if (index == -1) { if (index == -1) {
// console.log('-----------------> LST: ', lst) // console.log('-----------------> LST: ', lst):q
lst.push({ id: msg.id.id }) lst.push({ id: msg.id.id })
@ -1019,6 +1019,12 @@ const handleMessage = async (
// const chat = await msg.getChat(); // const chat = await msg.getChat();
const chat = wbot.chat 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))) // console.log('----------> chat: ', JSON.parse(JSON.stringify(chat)))
// if (chat.isGroup) { // if (chat.isGroup) {
@ -1183,40 +1189,11 @@ const handleMessage = async (
} catch (err) { } catch (err) {
Sentry.captureException(err); Sentry.captureException(err);
logger.error(`Error handling whatsapp message: Err: ${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')
}
} }
}; };
const handleMsgAck = async (msg_id: any, ack: any) => { const handleMsgAck = async (msg_id: any, ack: any) => {
await new Promise(r => setTimeout(r, 500)); await new Promise(r => setTimeout(r, 500));
const io = getIO(); const io = getIO();
@ -1233,11 +1210,12 @@ const handleMsgAck = async (msg_id: any, ack: any) => {
] ]
}); });
if (!messageToUpdate) { if (!messageToUpdate) {
console.log(`Not found the MESSAGE ID ${msg_id}to change the ACK into the Message table`)
return; return;
} }
await messageToUpdate.update({ ack }); 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", { io.to(messageToUpdate.ticketId.toString()).emit("appMessage", {
action: "update", action: "update",