Merge branch 'dual_session_test' into dialogflow

pull/20/head
adriano 2022-12-23 20:19:43 -03:00
commit 1b603a7216
12 changed files with 166 additions and 148 deletions

View File

@ -16,7 +16,9 @@ const autoRestore = async (whatsappId: string | number, started_action_by: strin
const whatsapp = await ShowWhatsAppService(whatsappId);
restartWhatsSession(whatsapp, true)
// console.log('>>>>>>>>>>> Whatsapp.id: ', whatsappId)
await restartWhatsSession(whatsapp, true)
const sourcePath = path.join(__dirname, `../../.wwebjs_auth/sessions/log`)

View File

@ -4,7 +4,7 @@ import { type } from 'os'
const unflatten = require('flat').unflatten
var flatten = require('flat')
import ListContactsServiceCache from "../services/ContactServices/ListContactsServiceCache"
import { redisConn } from './TicketCache'
import { deleteTicketsByContactsCache, redisConn } from './TicketCache'
const deleteContactsByIdCache = async (id: string | number) => {
@ -20,6 +20,10 @@ const deleteContactsByIdCache = async (id: string | number) => {
try {
if (contact_cache && Object.keys(contact_cache).length > 0) {
console.log('contact_cache["number"]: ',contact_cache['number'])
await deleteTicketsByContactsCache(contact_cache['number'])
await redis.del(`contact:${id}`)
console.log(`Contacts cache number ${contact_cache['number']} deleted!`)
@ -31,7 +35,7 @@ const deleteContactsByIdCache = async (id: string | number) => {
console.log(`There was an error on deleteContactsByIdCache: ${error}`)
}
redis.quit()
await redis.quit()
}
const updateContactCache = async (hash: any, json_object: any) => {
@ -52,7 +56,7 @@ const updateContactCache = async (hash: any, json_object: any) => {
await pipeline.exec(() => { console.log("Key/value inserted/updated") });
redis.quit()
await redis.quit()
}
@ -82,7 +86,7 @@ const updateContactCacheById = async (id: string | number, update_fields: object
console.log(`There was an error on updateContactCacheById: ${error}`)
}
redis.quit()
await redis.quit()
}
const createOrUpdateContactCache = async (hash: any, contact: any) => {
@ -99,7 +103,7 @@ const createOrUpdateContactCache = async (hash: any, contact: any) => {
await redis.hmset(hash, contact);
redis.quit()
await redis.quit()
}
@ -115,7 +119,7 @@ async function searchContactCache(search: string, offset: number, limit: number)
search = escapeCharCache(search)
const response: any = await redis.call('FT.SEARCH', 'idx_contact', `(@escaped_name:*${search}*)|(@number:*${search}*)`, 'LIMIT', offset, limit, 'SORTBY', 'escaped_name', 'ASC')
redis.quit()
await redis.quit()
if (response.length === 1) {
@ -181,7 +185,7 @@ const insertContactsCache = async (contacts: any) => {
await pipeline.exec(() => { console.log(`${contacts.length} CONTACTS INSERTED IN CACHE!`) });
redis.quit()
await redis.quit()
}
const loadContactsCache = async () => {
@ -210,7 +214,7 @@ const loadContactsCache = async () => {
await pipeline.exec(() => { console.log(`${contacts.length} CONTACTS INSERTED IN CACHE!`) });
redis.quit()
await redis.quit()
}
const createContactIndexCache = async (hashIndex: string) => {
@ -238,7 +242,7 @@ const createContactIndexCache = async (hashIndex: string) => {
console.log('There was an error on createContactIndexCache: ', error)
}
redis.quit()
await redis.quit()
}
export {

View File

@ -0,0 +1,24 @@
// require fs module
const fs = require("fs");
// Delete a directory and its children
export const creationTime = (sourcePath: string) => {
if (fs.existsSync(sourcePath)) {
try {
const { birthtime } = fs.statSync(sourcePath)
return birthtime
} catch (error) {
console.log(`There was an error on trying get de file/directory creation info from ${sourcePath}: `, error)
}
}
return
}

View File

@ -31,7 +31,7 @@ const deleteContactsByIdCache = async (id: string | number) => {
console.log(`There was an error on deleteContactsByIdCache: ${error}`)
}
redis.quit()
await redis.quit()
}
const updateContactCache = async (hash: any, json_object: any) => {
@ -52,7 +52,7 @@ const updateContactCache = async (hash: any, json_object: any) => {
await pipeline.exec(() => { console.log("Key/value inserted/updated") });
redis.quit()
await redis.quit()
}
@ -84,7 +84,7 @@ const updateContactCacheById = async (id: string | number, update_fields: object
console.log(`There was an error on updateContactCacheById: ${error}`)
}
redis.quit()
await redis.quit()
}
const createOrUpdateContactCache = async (hash: any, contact: any) => {
@ -101,7 +101,7 @@ const createOrUpdateContactCache = async (hash: any, contact: any) => {
await redis.hmset(hash, contact);
redis.quit()
await redis.quit()
}
@ -117,7 +117,7 @@ async function searchContactCache(search: string, offset: number, limit: number)
search = escapeCharCache(search)
const response: any = await redis.call('FT.SEARCH', 'idx_contact_message', `(@escaped_name:*${search}*)|(@number:*${search}*)`, 'LIMIT', offset, limit, 'SORTBY', 'escaped_name', 'ASC')
redis.quit()
await redis.quit()
if (response.length === 1) {
@ -188,7 +188,7 @@ const insertMessageContactCache = async (hash: any, contact_message: any) => {
console.log('CREATED/UPDATED CONTACT MESSAGE')
redis.quit()
await redis.quit()
}
@ -218,7 +218,7 @@ const loadContactsCache = async () => {
await pipeline.exec(() => { console.log(`${contacts.length} CONTACTS INSERTED IN CACHE!`) });
redis.quit()
await redis.quit()
}
const createContactMessageIndexCache = async (hashIndex: string) => {
@ -246,7 +246,7 @@ const createContactMessageIndexCache = async (hashIndex: string) => {
console.log('There was an error on contact_message: ', error)
}
redis.quit()
await redis.quit()
}
export {

View File

@ -2,6 +2,11 @@
import os from 'os';
import dir from 'path';
import fs from 'fs';
import ShowWhatsAppService from '../services/WhatsappService/ShowWhatsAppService';
import { insertOrUpeateWhatsCache } from './WhatsCache';
import autoRestore from './AutoRestore';
import Whatsapp from '../models/Whatsapp';
import { getIO } from '../libs/socket';
export const setRestoreControll = (obj: object) => {
@ -133,3 +138,27 @@ export const getRestoreControll = () => {
return []
}
export const _restore = async (whatsapp: Whatsapp, msg_file_title: string) => {
if (whatsapp.status != 'RESTORING' && whatsapp.status != 'qrcode') {
console.log('THE WHATSAAP ID: ', whatsapp.id, ' WILL BE RESTORED SOON!')
await whatsapp.update({ status: "RESTORING", });
const io = getIO();
io.emit("whatsappSession", {
action: "update",
session: whatsapp
});
await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, { status: "RESTORING", })
setTimeout(async () => await autoRestore(whatsapp.id, msg_file_title), 95000);
}
}

View File

@ -38,7 +38,7 @@ const deleteScheduleByTicketIdCache = async (ticketId: string | number) => {
console.log(`There was an error on deleteScheduleByTicketIdCache: ${error}`)
}
redis.quit()
await redis.quit()
}
@ -63,7 +63,7 @@ const updateScheduleCacheByTicketId = async (scheduleNotify: any) => {
await pipeline.exec(() => { console.log("schedule Key/value inserted/updated") });
redis.quit()
await redis.quit()
}
@ -96,7 +96,7 @@ const createSchedulingNotifyCache = async (scheduleNotify: any) => {
console.log(`${scheduleNotify.length} SCHEDULE NOTIFY INSERTED IN CACHE!`)
redis.quit()
await redis.quit()
}
@ -112,7 +112,7 @@ async function searchScheduleCache(date: string, hour: number | string, minute:
date = escapeCharCache(date).trim()
const response: any = await redis.call('FT.SEARCH', 'idx_schedule', `(@date_escaped:${date}) (@hour:${hour}) (@minute:${minute})`)
redis.quit()
await redis.quit()
if (response.length === 1) {
@ -173,7 +173,7 @@ const loadSchedulesCache = async () => {
await pipeline.exec(() => { console.log(`${schedules.length} SCHEDULES NOTIFY INSERTED IN CACHE!`) });
redis.quit()
await redis.quit()
// let test = await searchScheduleCache('2022-12-16', '18', '30')
@ -207,7 +207,7 @@ const createScheduleIndexCache = async (hashIndex: string) => {
console.log('There was an error on createScheduleIndexCache: ', error)
}
redis.quit()
await redis.quit()
}
export {

View File

@ -20,11 +20,11 @@ const redisConn = async () => {
const conn = () => new Promise((resolve, reject) => {
redis.on('error', (err) => {
redis.on('error', async (err) => {
if (err.code === 'ECONNREFUSED') {
console.error(`Redis connection error: ${err}.`)
redis.quit()
await redis.quit()
}
else {
console.error(`Redis encountered an error: ${err.message}.`)
@ -36,9 +36,18 @@ const redisConn = async () => {
redis.on('connect', () => {
// console.log('CacheStore - Connection status: connected');
resolve(redis);
})
redis.on('end', () => {
// console.log('CacheStore - Connection status: disconnected');
});
redis.on('reconnecting', () => {
// console.log('CacheStore - Connection status: reconnecting');
});
});
return await conn();
@ -61,7 +70,7 @@ const flushCache = async () => {
console.log('TICKETS CACHE REMOVED')
await redis.call('FLUSHALL')
redis.quit()
await redis.quit()
}
}
@ -77,7 +86,7 @@ const cacheSize = async () => {
}
const size = await redis.call('dbsize')
redis.quit()
await redis.quit()
return size
}
@ -114,7 +123,7 @@ const loadTicketsCache = async () => {
await pipeline.exec(() => { console.log(`${tickets.length} TICKETS INSERTED IN CACHE!`) });
redis.quit()
await redis.quit()
}
@ -143,7 +152,7 @@ const createTicketIndexCache = async (hashIndex: string) => {
console.log('There was an error on createTicketIndexCache: ', error)
}
redis.quit()
await redis.quit()
}
const updateTicketCache = async (hash: any, json_object: any) => {
@ -163,7 +172,7 @@ const updateTicketCache = async (hash: any, json_object: any) => {
await pipeline.exec(() => { console.log("updateTicketCache Key/value inserted/updated") });
redis.quit()
await redis.quit()
}
@ -195,7 +204,7 @@ const updateTicketCacheByTicketId = async (ticketId: string | number, update_fie
console.log(`There was an error on updateTicketCacheByTicketId: ${error}`)
}
redis.quit()
await redis.quit()
}
@ -218,7 +227,7 @@ const createOrUpdateTicketCache = async (hash: any, ticket: any) => {
console.log('CREATED/UPDATED TICKET CACHE')
redis.quit()
await redis.quit()
}
@ -246,7 +255,7 @@ const deleteTicketsByIdCache = async (ticketId: string | number) => {
console.log(`There was an error on deleteTicketsByIdCache: ${error}`)
}
redis.quit()
await redis.quit()
}
@ -277,7 +286,7 @@ const deleteTicketsFieldsCache = async (tickets: any, del_fields: any) => {
}
redis.quit()
await redis.quit()
}
@ -314,7 +323,7 @@ const updateTicketsByContactsCache = async (oldNumber: string, newName: string,
}
redis.quit()
await redis.quit()
}
@ -347,7 +356,7 @@ const deleteTicketsByContactsCache = async (number: string) => {
}
redis.quit()
await redis.quit()
}
@ -360,7 +369,7 @@ const deleteTicketCache = async (hash: any) => {
if (redis.status !== 'connect') return
await redis.del(hash)
redis.quit()
await redis.quit()
}
@ -382,7 +391,7 @@ async function searchTicketCache(search: string, offset?: number, limit?: number
else {
response = await redis.call('FT.SEARCH', 'idx_ticket', `(@escaped_name:*${search}*)|(@contact_number:*${search}*)`)
}
redis.quit()
await redis.quit()
// console.log('response: ', response)

View File

@ -32,7 +32,7 @@ const deleteWhatsappCache = async (hash:any) => {
console.log(`There was an error on deleteWhatsappCache: ${error}`)
}
redis.quit()
await redis.quit()
}
const updateWhatsappCache = async (hash: any, json_object: any) => {
@ -53,7 +53,7 @@ const updateWhatsappCache = async (hash: any, json_object: any) => {
await pipeline.exec(() => { console.log("whatsapp Key/value inserted/updated") });
redis.quit()
await redis.quit()
}
@ -83,7 +83,7 @@ const updateWhatsappCacheById = async (hash:any, update_fields: object | any) =>
console.log(`There was an error on updateWhatsappCacheById: ${error}`)
}
redis.quit()
await redis.quit()
}
// const createOrUpdateContactCache = async (hash: any, contact: any) => {
@ -117,6 +117,7 @@ async function searchWhatsappCache(id: string, status: string) {
const number_cache: any = await redis.hgetall(`whatsapp:${id}`)
if(Object.entries(number_cache).length == 0){
redis.quit()
return []
}
@ -127,7 +128,7 @@ async function searchWhatsappCache(id: string, status: string) {
const response: any = await redis.call('FT.SEARCH', 'idx_whatsapp', `(@status:*${status}*) (@number:*${number_cache.number}*)`, 'SORTBY', 'status', 'ASC')
redis.quit()
await redis.quit()
if (response.length === 1) {
@ -182,7 +183,7 @@ const insertOrUpeateWhatsCache = async (hash:any, whatsapp: any) => {
}
redis.quit()
await redis.quit()
}
@ -214,7 +215,7 @@ const loadWhatsappCache = async () => {
await pipeline.exec(() => { console.log(`${whatsapps.length} WHATSAPPS INSERTED IN CACHE!`) });
redis.quit()
await redis.quit()
}
const createWhatsappIndexCache = async (hashIndex: string) => {
@ -242,7 +243,7 @@ const createWhatsappIndexCache = async (hashIndex: string) => {
console.log('There was an error on createWhatsappIndexCache: ', error)
}
redis.quit()
await redis.quit()
}
export {

View File

@ -23,6 +23,7 @@ import { restartWhatsSession } from "../../helpers/RestartWhatsSession";
import { insertOrUpeateWhatsCache, searchWhatsappCache } from "../../helpers/WhatsCache";
import GetDefaultWhatsApp from "../../helpers/GetDefaultWhatsApp";
import autoRestore from "../../helpers/AutoRestore";
import { _restore } from "../../helpers/RestoreControll";
@ -54,11 +55,6 @@ const SendWhatsAppMessage = async ({
let whatsapps: any
//TEST DEL
// const defaultWhatsapp = await GetDefaultWhatsApp();
// console.log('DEFAULT WHATSAPP: ', JSON.parse(JSON.stringify(defaultWhatsapp)))
let listWhatsapp = null
listWhatsapp = await searchWhatsappCache(`${ticket.whatsappId}`, 'CONNECTED')
@ -67,9 +63,6 @@ const SendWhatsAppMessage = async ({
listWhatsapp = await ListWhatsAppsNumber(ticket.whatsappId, 'CONNECTED')
}
// console.log('---')
// console.log('listWhatsapp search: ', listWhatsapp)
// console.log('---')
if (listWhatsapp.length > 1) {
@ -104,64 +97,12 @@ const SendWhatsAppMessage = async ({
}
//
// const listWhatsapp = await ListWhatsAppsNumber(ticket.whatsappId, 'CONNECTED')
// if (listWhatsapp.length > 1) {
// const _whatsapp = listWhatsapp[Math.floor(Math.random() * listWhatsapp.length)];
// await ticket.update({ whatsappId: _whatsapp.id });
// }
// else {
// whatsapps = await Whatsapp.findOne({
// where: { id: ticket.whatsappId },
// attributes: ['status']
// })
// }
// console.log('1 --------> ticket.whatsappId: ', ticket.whatsappId)
// if (listWhatsapp.length == 0 || (whatsapps && whatsapps.status != 'CONNECTED')) {
// whatsapps = await wbotByUserQueue(ticket.userId)
// if (whatsapps.length > 0) {
// if (whatsapps.length > 1) {
// await ticket.update({ whatsappId: whatsapps[+WhatsIndex(whatsapps)].id });
// }
// else {
// await ticket.update({ whatsappId: whatsapps[0].id });
// }
// }
// }
const wbot = await GetTicketWbot(ticket);
console.log('2 --------> send from whatsapp ticket.whatsappId: ', ticket.whatsappId)
try {
console.time
const sentMessage = await wbot.sendMessage(`${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us`, body, { quotedMessageId: quotedMsgSerializedId, linkPreview: false });
@ -176,21 +117,7 @@ const SendWhatsAppMessage = async ({
const whatsapp = await ShowWhatsAppService(ticket.whatsappId);
if (whatsapp.status != 'RESTORING') {
console.log('THE WHATSAAP ID: ', whatsapp.id, ' WILL BE RESTORED SOON!')
await whatsapp.update({
status: "RESTORING",
});
await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, {
status: "RESTORING",
})
// setTimeout(() => restartWhatsSession(whatsapp, true), 90000);
setTimeout(async () => await autoRestore(whatsapp.id, 'auto_send_message'), 95000);
}
await _restore(whatsapp, 'auto_send_message')
const sentMessage = await sendMessageMultiSession(ticket, body, quotedMsgSerializedId)

View File

@ -10,7 +10,14 @@ import { getRestoreControll, setRestoreControll, shifRestoreControll } from "../
import ShowWhatsAppService from "../WhatsappService/ShowWhatsAppService";
import { restartWhatsSession } from "../../helpers/RestartWhatsSession";
import dir from 'path';
import autoRestore from "../../helpers/AutoRestore";
import { creationTime } from "../../helpers/CreationTime";
import { splitDateTime } from "../../helpers/SplitDateTime";
import { format } from "date-fns";
import ptBR from 'date-fns/locale/pt-BR';
let lstAutoRestore: any = []
@ -21,8 +28,6 @@ export const StartWhatsAppSession = async (whatsapp: Whatsapp, backupSession: bo
status: "OPENING",
})
try {
let lstRestore: any = getRestoreControll()

View File

@ -65,6 +65,8 @@ import endPointQuery from "../../helpers/EndpointQuery";
import { Console } from "console";
import ShowContactCustomFieldService from "../ContactServices/ShowContactCustomFieldsService";
import { insertMessageContactCache, getLastId } from '../../helpers/LastMessageIdByContactCache'
import autoRestore from "../../helpers/AutoRestore";
import { _restore } from "../../helpers/RestoreControll";
@ -1054,6 +1056,8 @@ const handleMessage = async (
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")) {
@ -1062,8 +1066,6 @@ const handleMessage = async (
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') {
@ -1077,6 +1079,11 @@ const handleMessage = async (
}
}
else if (`${err}`.includes('[object Object]')) {
await _restore(whatsapp, 'auto_object_error')
}
}
};

View File

@ -27,6 +27,7 @@ import {
SignalCellular4Bar,
CropFree,
DeleteOutline,
// Restore
} from "@material-ui/icons";
import MainContainer from "../../components/MainContainer";
@ -326,6 +327,15 @@ const Connections = () => {
<SignalCellularConnectedNoInternet2Bar color="secondary" />
</CustomToolTip>
)}
{/* {whatsApp.status === "RESTORING" && (
<CustomToolTip
title={i18n.t("connections.toolTips.disconnected.title")}
content={i18n.t("connections.toolTips.disconnected.content")}
>
<Restore color="secondary" />
</CustomToolTip>
)} */}
</div>
);
};