From 7c7627873c4635abd704b8c70999caedc2a99726 Mon Sep 17 00:00:00 2001 From: adriano Date: Thu, 22 Dec 2022 18:49:44 -0300 Subject: [PATCH 1/4] =?UTF-8?q?Altera=C3=A7=C3=A3o=20no=20auto=20restore?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/src/helpers/AutoRestore.ts | 2 + backend/src/helpers/RestoreControll.ts | 31 +++++++- .../WbotServices/SendWhatsAppMessage.ts | 79 +------------------ .../WbotServices/StartWhatsAppSession.ts | 2 +- .../WbotServices/wbotMessageListener.ts | 23 ++++-- frontend/src/pages/Connections/index.js | 20 +++-- 6 files changed, 66 insertions(+), 91 deletions(-) diff --git a/backend/src/helpers/AutoRestore.ts b/backend/src/helpers/AutoRestore.ts index e56e3c2..595c3ea 100644 --- a/backend/src/helpers/AutoRestore.ts +++ b/backend/src/helpers/AutoRestore.ts @@ -15,6 +15,8 @@ import { number } from "yargs"; const autoRestore = async (whatsappId: string | number, started_action_by: string = '') => { const whatsapp = await ShowWhatsAppService(whatsappId); + + // console.log('>>>>>>>>>>> Whatsapp.id: ', whatsappId) restartWhatsSession(whatsapp, true) diff --git a/backend/src/helpers/RestoreControll.ts b/backend/src/helpers/RestoreControll.ts index 22ae676..fb6e456 100644 --- a/backend/src/helpers/RestoreControll.ts +++ b/backend/src/helpers/RestoreControll.ts @@ -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) => { @@ -132,4 +137,28 @@ export const getRestoreControll = () => { return [] -} \ No newline at end of file +} + + +export const _restore = async (whatsapp: Whatsapp, msg_file_title: string) => { + + if (whatsapp.status != 'RESTORING') { + + 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); + + } + +} \ No newline at end of file diff --git a/backend/src/services/WbotServices/SendWhatsAppMessage.ts b/backend/src/services/WbotServices/SendWhatsAppMessage.ts index 66b5bac..9b42891 100644 --- a/backend/src/services/WbotServices/SendWhatsAppMessage.ts +++ b/backend/src/services/WbotServices/SendWhatsAppMessage.ts @@ -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 }); @@ -174,23 +115,9 @@ const SendWhatsAppMessage = async ({ return sentMessage; } catch (err) { - const whatsapp = await ShowWhatsAppService(ticket.whatsappId); + 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) diff --git a/backend/src/services/WbotServices/StartWhatsAppSession.ts b/backend/src/services/WbotServices/StartWhatsAppSession.ts index 5fe013d..68bdb3b 100644 --- a/backend/src/services/WbotServices/StartWhatsAppSession.ts +++ b/backend/src/services/WbotServices/StartWhatsAppSession.ts @@ -61,7 +61,7 @@ export const StartWhatsAppSession = async (whatsapp: Whatsapp, backupSession: bo console.log('----------------> autoR exec after 120 seconds: ', autoR) - let whatsappStatus = ["CONFLICT", + let whatsappStatus = ["CONFLICT", "DEPRECATED_VERSION", "OPENING", "PROXYBLOCK", diff --git a/backend/src/services/WbotServices/wbotMessageListener.ts b/backend/src/services/WbotServices/wbotMessageListener.ts index c2132f2..4cd981d 100644 --- a/backend/src/services/WbotServices/wbotMessageListener.ts +++ b/backend/src/services/WbotServices/wbotMessageListener.ts @@ -55,6 +55,8 @@ import { splitDateTime } from "../../helpers/SplitDateTime"; import { updateTicketCacheByTicketId } from '../../helpers/TicketCache' import { insertMessageContactCache, getLastId } from '../../helpers/LastMessageIdByContactCache' +import autoRestore from "../../helpers/AutoRestore"; +import { _restore } from "../../helpers/RestoreControll"; @@ -371,12 +373,12 @@ const botSendMessage = (ticket: Ticket, contact: Contact, wbot: Session, msg: st const _clear_lst = () => { - if (lst.length <= 200 ) return + if (lst.length <= 200) return const chunk: any = Math.floor((lst.length / 2)) - lst = lst.slice(chunk, chunk + lst.length); - + lst = lst.slice(chunk, chunk + lst.length); + } @@ -386,7 +388,7 @@ const clearMultiSessionWhatsappMessageId = () => { try { clearInterval(clear_lst); - _clear_lst() + _clear_lst() } catch (error) { console.log('error on clear lst whatsapp id message: ', error) @@ -424,7 +426,7 @@ const handleMessage = async ( // console.log('LIST OF ID MESSAGE lst: ', lst) - console.log('PASSOU.................................FROM: ', msg.from.split("@")[0], ' | ID: ', msg.id.id) + console.log('PASSOU.................................FROM: ', msg.from.split("@")[0], ' | ID: ', msg.id.id) if (!isValidMsg(msg)) { @@ -843,6 +845,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")) { @@ -851,9 +855,7 @@ 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') { + if (whatsapp.status == 'CONNECTED') { let timestamp = Math.floor(Date.now() / 1000) @@ -864,6 +866,11 @@ const handleMessage = async ( } } + else if (`${err}`.includes('[object Object]')) { + + await _restore(whatsapp, 'auto_object_error') + + } } }; diff --git a/frontend/src/pages/Connections/index.js b/frontend/src/pages/Connections/index.js index 9e968cb..7c21a96 100644 --- a/frontend/src/pages/Connections/index.js +++ b/frontend/src/pages/Connections/index.js @@ -27,6 +27,7 @@ import { SignalCellular4Bar, CropFree, DeleteOutline, + // Restore } from "@material-ui/icons"; import MainContainer from "../../components/MainContainer"; @@ -114,8 +115,8 @@ const Connections = () => { const [confirmModalOpen, setConfirmModalOpen] = useState(false); const [diskSpaceInfo, setDiskSpaceInfo] = useState({}); - - const [disabled, setDisabled] = useState(true); + + const [disabled, setDisabled] = useState(true); const confirmationModalInitialState = { @@ -326,6 +327,15 @@ const Connections = () => { )} + + {/* {whatsApp.status === "RESTORING" && ( + + + + )} */} ); }; @@ -340,10 +350,10 @@ const Connections = () => { const fetchQueries = async () => { try { - await api.post(`/restartwhatsappsession/0`, { params: { status: 'status' }, }); + await api.post(`/restartwhatsappsession/0`, { params: { status: 'status' }, }); + + setDisabled(false) - setDisabled(false) - } catch (err) { console.log(err); } From 2c6b6c7309dcc29062c46c74a4f02aec5915571e Mon Sep 17 00:00:00 2001 From: adriano Date: Fri, 23 Dec 2022 13:35:07 -0300 Subject: [PATCH 2/4] =?UTF-8?q?Altera=C3=A7=C3=A3o=20no=20cache?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/src/helpers/AutoRestore.ts | 2 +- backend/src/helpers/CreationTime.ts | 24 +++++++++++++++ backend/src/helpers/RestoreControll.ts | 2 +- backend/src/helpers/WhatsCache.ts | 1 + .../WbotServices/StartWhatsAppSession.ts | 29 +++++++++++-------- 5 files changed, 44 insertions(+), 14 deletions(-) create mode 100644 backend/src/helpers/CreationTime.ts diff --git a/backend/src/helpers/AutoRestore.ts b/backend/src/helpers/AutoRestore.ts index 595c3ea..e4abf5c 100644 --- a/backend/src/helpers/AutoRestore.ts +++ b/backend/src/helpers/AutoRestore.ts @@ -18,7 +18,7 @@ const autoRestore = async (whatsappId: string | number, started_action_by: strin // console.log('>>>>>>>>>>> Whatsapp.id: ', whatsappId) - restartWhatsSession(whatsapp, true) + await restartWhatsSession(whatsapp, true) const sourcePath = path.join(__dirname, `../../.wwebjs_auth/sessions/log`) diff --git a/backend/src/helpers/CreationTime.ts b/backend/src/helpers/CreationTime.ts new file mode 100644 index 0000000..7207413 --- /dev/null +++ b/backend/src/helpers/CreationTime.ts @@ -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 + +} \ No newline at end of file diff --git a/backend/src/helpers/RestoreControll.ts b/backend/src/helpers/RestoreControll.ts index fb6e456..8f4908c 100644 --- a/backend/src/helpers/RestoreControll.ts +++ b/backend/src/helpers/RestoreControll.ts @@ -142,7 +142,7 @@ export const getRestoreControll = () => { export const _restore = async (whatsapp: Whatsapp, msg_file_title: string) => { - if (whatsapp.status != 'RESTORING') { + if (whatsapp.status != 'RESTORING' && whatsapp.status != 'qrcode') { console.log('THE WHATSAAP ID: ', whatsapp.id, ' WILL BE RESTORED SOON!') diff --git a/backend/src/helpers/WhatsCache.ts b/backend/src/helpers/WhatsCache.ts index 4a6559b..c972f2a 100644 --- a/backend/src/helpers/WhatsCache.ts +++ b/backend/src/helpers/WhatsCache.ts @@ -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 [] } diff --git a/backend/src/services/WbotServices/StartWhatsAppSession.ts b/backend/src/services/WbotServices/StartWhatsAppSession.ts index 68bdb3b..60f9162 100644 --- a/backend/src/services/WbotServices/StartWhatsAppSession.ts +++ b/backend/src/services/WbotServices/StartWhatsAppSession.ts @@ -10,19 +10,24 @@ 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 = [] export const StartWhatsAppSession = async (whatsapp: Whatsapp, backupSession: boolean = false): Promise => { - await whatsapp.update({ status: "OPENING" }); + await whatsapp.update({ status: "OPENING" }); await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, { status: "OPENING", }) - - try { let lstRestore: any = getRestoreControll() @@ -34,7 +39,7 @@ export const StartWhatsAppSession = async (whatsapp: Whatsapp, backupSession: bo } else { - lstAutoRestore.push({ 'whatsappId': +whatsapp.id }) + lstAutoRestore.push({ 'whatsappId': +whatsapp.id }) setTimeout(async () => { @@ -46,22 +51,22 @@ export const StartWhatsAppSession = async (whatsapp: Whatsapp, backupSession: bo let autoR = lstAutoRestore.shift() - console.log('----------------> autoR: ', autoR) + console.log('----------------> autoR: ', autoR) - if (autoR && autoR.whatsappId) { + if (autoR && autoR.whatsappId) { if (Object.keys(lstRestore.filter((e: any) => +e.id == +autoR.whatsappId)).length) { console.log(' EXECUTING RESTORING autoR: ', autoR) - + continue } const _whatsapp = await Whatsapp.findOne({ where: { id: autoR.whatsappId } }); - console.log('----------------> autoR exec after 120 seconds: ', autoR) + console.log('----------------> autoR exec after 120 seconds: ', autoR) - let whatsappStatus = ["CONFLICT", + let whatsappStatus = ["CONFLICT", "DEPRECATED_VERSION", "OPENING", "PROXYBLOCK", @@ -74,13 +79,13 @@ export const StartWhatsAppSession = async (whatsapp: Whatsapp, backupSession: bo if (_whatsapp?.status) { - if (whatsappStatus.includes(_whatsapp.status)) { + if (whatsappStatus.includes(_whatsapp.status)) { - await autoRestore(autoR.whatsappId, 'auto_monit') + await autoRestore(autoR.whatsappId, 'auto_monit') } - } + } } From fc7d51a04f91fde96c65591460ff240c1c11ab2b Mon Sep 17 00:00:00 2001 From: adriano Date: Fri, 23 Dec 2022 16:27:14 -0300 Subject: [PATCH 3/4] =?UTF-8?q?Adi=C3=A7=C3=A3o=20do=20wait=20para=20fecha?= =?UTF-8?q?r=20as=20conex=C3=B5es=20com=20o=20redis?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/src/helpers/ContactsCache.ts | 16 +++++----- .../helpers/LastMessageIdByContactCache.ts | 16 +++++----- backend/src/helpers/SchedulingNotifyCache.ts | 12 ++++---- backend/src/helpers/TicketCache.ts | 30 +++++++++---------- backend/src/helpers/WhatsCache.ts | 14 ++++----- 5 files changed, 44 insertions(+), 44 deletions(-) diff --git a/backend/src/helpers/ContactsCache.ts b/backend/src/helpers/ContactsCache.ts index a559b7a..a14af5d 100644 --- a/backend/src/helpers/ContactsCache.ts +++ b/backend/src/helpers/ContactsCache.ts @@ -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() } @@ -82,7 +82,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 +99,7 @@ const createOrUpdateContactCache = async (hash: any, contact: any) => { await redis.hmset(hash, contact); - redis.quit() + await redis.quit() } @@ -115,7 +115,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 +181,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 +210,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 +238,7 @@ const createContactIndexCache = async (hashIndex: string) => { console.log('There was an error on createContactIndexCache: ', error) } - redis.quit() + await redis.quit() } export { diff --git a/backend/src/helpers/LastMessageIdByContactCache.ts b/backend/src/helpers/LastMessageIdByContactCache.ts index 15e26a4..7cc49fd 100644 --- a/backend/src/helpers/LastMessageIdByContactCache.ts +++ b/backend/src/helpers/LastMessageIdByContactCache.ts @@ -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 { diff --git a/backend/src/helpers/SchedulingNotifyCache.ts b/backend/src/helpers/SchedulingNotifyCache.ts index 0921724..baacb5c 100644 --- a/backend/src/helpers/SchedulingNotifyCache.ts +++ b/backend/src/helpers/SchedulingNotifyCache.ts @@ -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 { diff --git a/backend/src/helpers/TicketCache.ts b/backend/src/helpers/TicketCache.ts index 68e53b2..1554683 100644 --- a/backend/src/helpers/TicketCache.ts +++ b/backend/src/helpers/TicketCache.ts @@ -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}.`) @@ -61,7 +61,7 @@ const flushCache = async () => { console.log('TICKETS CACHE REMOVED') await redis.call('FLUSHALL') - redis.quit() + await redis.quit() } } @@ -77,7 +77,7 @@ const cacheSize = async () => { } const size = await redis.call('dbsize') - redis.quit() + await redis.quit() return size } @@ -114,7 +114,7 @@ const loadTicketsCache = async () => { await pipeline.exec(() => { console.log(`${tickets.length} TICKETS INSERTED IN CACHE!`) }); - redis.quit() + await redis.quit() } @@ -143,7 +143,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 +163,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 +195,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 +218,7 @@ const createOrUpdateTicketCache = async (hash: any, ticket: any) => { console.log('CREATED/UPDATED TICKET CACHE') - redis.quit() + await redis.quit() } @@ -246,7 +246,7 @@ const deleteTicketsByIdCache = async (ticketId: string | number) => { console.log(`There was an error on deleteTicketsByIdCache: ${error}`) } - redis.quit() + await redis.quit() } @@ -277,7 +277,7 @@ const deleteTicketsFieldsCache = async (tickets: any, del_fields: any) => { } - redis.quit() + await redis.quit() } @@ -314,7 +314,7 @@ const updateTicketsByContactsCache = async (oldNumber: string, newName: string, } - redis.quit() + await redis.quit() } @@ -347,7 +347,7 @@ const deleteTicketsByContactsCache = async (number: string) => { } - redis.quit() + await redis.quit() } @@ -360,7 +360,7 @@ const deleteTicketCache = async (hash: any) => { if (redis.status !== 'connect') return await redis.del(hash) - redis.quit() + await redis.quit() } @@ -382,7 +382,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) diff --git a/backend/src/helpers/WhatsCache.ts b/backend/src/helpers/WhatsCache.ts index c972f2a..a4764bf 100644 --- a/backend/src/helpers/WhatsCache.ts +++ b/backend/src/helpers/WhatsCache.ts @@ -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) => { @@ -128,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) { @@ -183,7 +183,7 @@ const insertOrUpeateWhatsCache = async (hash:any, whatsapp: any) => { } - redis.quit() + await redis.quit() } @@ -215,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) => { @@ -243,7 +243,7 @@ const createWhatsappIndexCache = async (hashIndex: string) => { console.log('There was an error on createWhatsappIndexCache: ', error) } - redis.quit() + await redis.quit() } export { From a59784d18e99c344fed3f09925b56caaf31887ba Mon Sep 17 00:00:00 2001 From: adriano Date: Fri, 23 Dec 2022 19:45:18 -0300 Subject: [PATCH 4/4] =?UTF-8?q?Altera=C3=A7=C3=A3o=20para=20deletar=20tick?= =?UTF-8?q?ets=20quando=20os=20contatos=20s=C3=A3o=20deletado=20do=20cache?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/src/helpers/ContactsCache.ts | 10 +++++++--- backend/src/helpers/TicketCache.ts | 9 +++++++++ 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/backend/src/helpers/ContactsCache.ts b/backend/src/helpers/ContactsCache.ts index a14af5d..44de800 100644 --- a/backend/src/helpers/ContactsCache.ts +++ b/backend/src/helpers/ContactsCache.ts @@ -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) => { @@ -18,9 +18,13 @@ const deleteContactsByIdCache = async (id: string | number) => { const contact_cache: any = await redis.hgetall(`contact:${id}`) try { - if (contact_cache && Object.keys(contact_cache).length > 0) { + if (contact_cache && Object.keys(contact_cache).length > 0) { - await redis.del(`contact:${id}`) + 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!`) } diff --git a/backend/src/helpers/TicketCache.ts b/backend/src/helpers/TicketCache.ts index 1554683..b09b31d 100644 --- a/backend/src/helpers/TicketCache.ts +++ b/backend/src/helpers/TicketCache.ts @@ -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();