Skip to content

Commit

Permalink
enhancement of setting messages as read
Browse files Browse the repository at this point in the history
  • Loading branch information
allgood committed Jul 5, 2024
1 parent 8b89fa5 commit 3686a1b
Showing 1 changed file with 39 additions and 18 deletions.
57 changes: 39 additions & 18 deletions backend/src/helpers/SetTicketMessagesAsRead.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { proto, WASocket } from "@whiskeysockets/baileys";
import { WASocket, proto } from "@whiskeysockets/baileys";
import { cacheLayer } from "../libs/cache";
import { getIO } from "../libs/socket";
import Message from "../models/Message";
Expand All @@ -10,36 +10,57 @@ const SetTicketMessagesAsRead = async (ticket: Ticket): Promise<void> => {
await ticket.update({ unreadMessages: 0 });
await cacheLayer.set(`contacts:${ticket.contactId}:unreads`, "0");
let companyId: number;

try {
const wbot = await GetTicketWbot(ticket);

const getJsonMessage = await Message.findAll({
const messages = await Message.findAll({
attributes: ["id", "companyId", "dataJson"],
where: {
ticketId: ticket.id,
fromMe: false,
read: false
},
order: [["createdAt", "DESC"]]
});
companyId = getJsonMessage[0]?.companyId;

getJsonMessage.map(async m => {
const message: proto.IWebMessageInfo = JSON.parse(m.dataJson);
if (message.key) {
await (wbot as WASocket).readMessages([message.key]);
}
});
if (messages.length === 0) return;

companyId = messages[0]?.companyId;

const messageKeys = messages
.map(m => {
const message: proto.IWebMessageInfo = JSON.parse(m.dataJson);
return message.key;
})
.filter(key => key !== undefined);

if (getJsonMessage.length > 0) {
const lastMessages: proto.IWebMessageInfo = JSON.parse(
getJsonMessage[0].dataJson
);
if (lastMessages?.key?.remoteJid && lastMessages.key.fromMe === false) {
await (wbot as WASocket).chatModify(
{ markRead: true, lastMessages: [lastMessages] },
`${lastMessages.key.remoteJid}`
// Process message keys in batches of 250
const batchSize = 250;
for (let i = 0; i < messageKeys.length; i += batchSize) {
const batch = messageKeys.slice(i, i + batchSize);
(wbot as WASocket).readMessages(batch).catch(err => {
logger.error(
{ error: err as Error },
`Could not mark messages as read. Err: ${err?.message}`
);
}
});
}

const lastMessage: proto.IWebMessageInfo = JSON.parse(messages[0].dataJson);
if (lastMessage?.key?.remoteJid && !lastMessage.key.fromMe) {
// Asynchronous chatModify call
(wbot as WASocket)
.chatModify(
{ markRead: true, lastMessages: [lastMessage] },
lastMessage.key.remoteJid
)
.catch(err => {
logger.error(
{ error: err as Error },
`Could not modify chat. Err: ${err?.message}`
);
});
}

await Message.update(
Expand Down

0 comments on commit 3686a1b

Please sign in to comment.