From eb456f6a880fe4de022fd6a680eb8307fdff7643 Mon Sep 17 00:00:00 2001 From: Jesus Date: Tue, 8 Oct 2024 08:08:33 +0200 Subject: [PATCH 1/5] Fix unreadMessages for fetchChats query --- src/api/services/channel.service.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/api/services/channel.service.ts b/src/api/services/channel.service.ts index 5d079b69..3fb7c4ef 100644 --- a/src/api/services/channel.service.ts +++ b/src/api/services/channel.service.ts @@ -624,7 +624,7 @@ export class ChannelStartupService { "Chat"."updatedAt", "Contact"."pushName", "Contact"."profilePicUrl", - "Contact"."unreadMessages" + "Chat"."unreadMessages" FROM "Chat" INNER JOIN "Message" ON "Chat"."remoteJid" = "Message"."key"->>'remoteJid' LEFT JOIN "Contact" ON "Chat"."remoteJid" = "Contact"."remoteJid" @@ -639,7 +639,7 @@ export class ChannelStartupService { "Chat"."updatedAt", "Contact"."pushName", "Contact"."profilePicUrl", - "Contact"."unreadMessages" + "Chat"."unreadMessages" ORDER BY "Chat"."updatedAt" DESC; `; From cada7be1e5ee28e89976b46c9ebed7e889790a29 Mon Sep 17 00:00:00 2001 From: Jesus Date: Tue, 8 Oct 2024 08:47:08 +0200 Subject: [PATCH 2/5] Add last_message to fetchChats query --- src/api/services/channel.service.ts | 99 ++++++++++++++++++++--------- 1 file changed, 69 insertions(+), 30 deletions(-) diff --git a/src/api/services/channel.service.ts b/src/api/services/channel.service.ts index 3fb7c4ef..8c19173e 100644 --- a/src/api/services/channel.service.ts +++ b/src/api/services/channel.service.ts @@ -14,6 +14,7 @@ import { Logger } from '@config/logger.config'; import { NotFoundException } from '@exceptions'; import { Contact, Message } from '@prisma/client'; import { WASocket } from 'baileys'; +import { isArray } from 'class-validator'; import EventEmitter2 from 'eventemitter2'; import { v4 } from 'uuid'; @@ -309,7 +310,9 @@ export class ChannelStartupService { return null; } - const ignoreJidsArray = Array.isArray(data.ignoreJids) ? data.ignoreJids.map((event) => String(event)) : []; + const ignoreJidsArray = Array.isArray(data.ignoreJids) + ? data.ignoreJids.map((event) => String(event)) + : []; return { enabled: data?.enabled, @@ -537,7 +540,9 @@ export class ChannelStartupService { keyFilters?.id ? { key: { path: ['id'], equals: keyFilters?.id } } : {}, keyFilters?.fromMe ? { key: { path: ['fromMe'], equals: keyFilters?.fromMe } } : {}, keyFilters?.remoteJid ? { key: { path: ['remoteJid'], equals: keyFilters?.remoteJid } } : {}, - keyFilters?.participants ? { key: { path: ['participants'], equals: keyFilters?.participants } } : {}, + keyFilters?.participants + ? { key: { path: ['participants'], equals: keyFilters?.participants } } + : {}, ], }, }); @@ -560,7 +565,9 @@ export class ChannelStartupService { keyFilters?.id ? { key: { path: ['id'], equals: keyFilters?.id } } : {}, keyFilters?.fromMe ? { key: { path: ['fromMe'], equals: keyFilters?.fromMe } } : {}, keyFilters?.remoteJid ? { key: { path: ['remoteJid'], equals: keyFilters?.remoteJid } } : {}, - keyFilters?.participants ? { key: { path: ['participants'], equals: keyFilters?.participants } } : {}, + keyFilters?.participants + ? { key: { path: ['participants'], equals: keyFilters?.participants } } + : {}, ], }, orderBy: { @@ -615,33 +622,65 @@ export class ChannelStartupService { : null; const result = await this.prismaRepository.$queryRaw` - SELECT - "Chat"."id", - "Chat"."remoteJid", - "Chat"."name", - "Chat"."labels", - "Chat"."createdAt", - "Chat"."updatedAt", - "Contact"."pushName", - "Contact"."profilePicUrl", - "Chat"."unreadMessages" - FROM "Chat" - INNER JOIN "Message" ON "Chat"."remoteJid" = "Message"."key"->>'remoteJid' - LEFT JOIN "Contact" ON "Chat"."remoteJid" = "Contact"."remoteJid" - WHERE "Chat"."instanceId" = ${this.instanceId} - ${remoteJid ? 'AND "Chat"."remoteJid" = ${remoteJid}' : ''} - GROUP BY - "Chat"."id", - "Chat"."remoteJid", - "Chat"."name", - "Chat"."labels", - "Chat"."createdAt", - "Chat"."updatedAt", - "Contact"."pushName", - "Contact"."profilePicUrl", - "Chat"."unreadMessages" - ORDER BY "Chat"."updatedAt" DESC; - `; + SELECT + "Chat"."id", + "Chat"."remoteJid", + "Chat"."name", + "Chat"."labels", + "Chat"."createdAt", + "Chat"."updatedAt", + "Contact"."pushName", + "Contact"."profilePicUrl", + (ARRAY_AGG("Message"."id" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_id, + (ARRAY_AGG("Message"."key" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_key, + (ARRAY_AGG("Message"."pushName" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_pushName, + (ARRAY_AGG("Message"."participant" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_participant, + (ARRAY_AGG("Message"."messageType" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_messageType, + (ARRAY_AGG("Message"."message" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_message, + (ARRAY_AGG("Message"."contextInfo" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_contextInfo, + (ARRAY_AGG("Message"."source" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_source, + (ARRAY_AGG("Message"."messageTimestamp" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_messageTimestamp, + (ARRAY_AGG("Message"."instanceId" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_instanceId, + (ARRAY_AGG("Message"."sessionId" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_sessionId, + (ARRAY_AGG("Message"."status" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_status + FROM "Chat" + LEFT JOIN "Message" ON "Message"."key"->>'remoteJid' = "Chat"."remoteJid" + LEFT JOIN "Contact" ON "Chat"."remoteJid" = "Contact"."remoteJid" + WHERE + "Chat"."instanceId" like ${this.instanceId} + ${remoteJid ? 'AND "Chat"."remoteJid" like ${remoteJid}' : ''} + GROUP BY + "Chat"."id", + "Chat"."remoteJid", + "Contact"."id" + ORDER BY "Chat"."updatedAt" DESC; + `.then((chats) => { + if (chats && isArray(chats) && chats.length > 0) { + return chats.map((chat) => { + return { + ...chat, + lastMessage: chat.last_message_id + ? { + id: chat.last_message_id, + key: chat.last_message_key, + pushName: chat.last_message_pushName, + participant: chat.last_message_participant, + messageType: chat.last_message_messageType, + message: chat.last_message_message, + contextInfo: chat.last_message_contextInfo, + source: chat.last_message_source, + messageTimestamp: chat.last_message_messageTimestamp, + instanceId: chat.last_message_instanceId, + sessionId: chat.last_message_sessionId, + status: chat.last_message_status, + } + : undefined, + }; + }); + } + + return []; + }); return result; } From c6ee463daedd0d55c53abf620a7787a097abb3ee Mon Sep 17 00:00:00 2001 From: Jesus Date: Tue, 8 Oct 2024 12:51:10 +0200 Subject: [PATCH 3/5] Improve update messages status --- .../whatsapp/whatsapp.baileys.service.ts | 72 ++++++++++++++----- 1 file changed, 55 insertions(+), 17 deletions(-) diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index d10fb748..0e0d38a5 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -666,7 +666,6 @@ export class BaileysStartupService extends ChannelStartupService { instanceId: this.instanceId, remoteJid: chat.id, name: chat.name, - unreadMessages: typeof chat.unreadCount === 'number' ? chat.unreadCount : 0, }, data: { remoteJid: chat.id }, }); @@ -1106,6 +1105,11 @@ export class BaileysStartupService extends ChannelStartupService { data: messageRaw, }); + if (received.key.fromMe === false && msg.status === status[3]) { + // is received not read message + await this.updateChatUnreadMessages(received.key.remoteJid); + } + if (isMedia) { if (this.configService.get('S3').ENABLE) { try { @@ -1237,7 +1241,7 @@ export class BaileysStartupService extends ChannelStartupService { }, 'messages.update': async (args: WAMessageUpdate[], settings: any) => { - const unreadChatToUpdate: Record = {}; // {remoteJid: readedMessages} + const readChatToUpdate: Record = {}; // remoteJid[] for await (const { key, update } of args) { if (settings?.groupsIgnore && key.remoteJid?.includes('@g.us')) { @@ -1309,13 +1313,28 @@ export class BaileysStartupService extends ChannelStartupService { return; } else if (update.status !== undefined && status[update.status] !== findMessage.status) { - if (!unreadChatToUpdate[key.remoteJid!]) { - unreadChatToUpdate[key.remoteJid!] = 0; + if (!key.fromMe && key.remoteJid) { + readChatToUpdate[key.remoteJid] = true; + + if (status[update.status] === status[4]) { + // Mark to read old messages + await this.prismaRepository.message.updateMany({ + where: { + AND: [ + { key: { path: ['remoteJid'], equals: key.remoteJid } }, + { key: { path: ['fromMe'], equals: false } }, + { messageTimestamp: { lt: findMessage.messageTimestamp } }, // Delivered messages + { + OR: [{ status: null }, { status: status[3] }], + }, + ], + }, + data: { status: status[4] }, + }); + } } - unreadChatToUpdate[key.remoteJid!]++; - - this.prismaRepository.message.update({ + await this.prismaRepository.message.update({ where: { id: findMessage.id }, data: { status: status[update.status] }, }); @@ -1341,16 +1360,7 @@ export class BaileysStartupService extends ChannelStartupService { } } - for await (const [remoteJid, unreadMessages] of Object.entries(unreadChatToUpdate)) { - const chat = await this.prismaRepository.chat.findFirst({ where: { remoteJid } }); - - if (chat) { - this.prismaRepository.chat.update({ - where: { id: chat.id }, - data: { unreadMessages: Math.max(0, chat.unreadMessages - unreadMessages) }, - }); - } - } + await Promise.all(Object.keys(readChatToUpdate).map((remoteJid) => this.updateChatUnreadMessages(remoteJid))); }, }; @@ -3708,6 +3718,10 @@ export class BaileysStartupService extends ChannelStartupService { source: getDevice(message.key.id), }; + if (!messageRaw.status && message.key.fromMe === false) { + messageRaw.status = status[3]; // DELIVERED MESSAGE + } + if (messageRaw.message.extendedTextMessage) { messageRaw.messageType = 'conversation'; messageRaw.message.conversation = messageRaw.message.extendedTextMessage.text; @@ -3735,4 +3749,28 @@ export class BaileysStartupService extends ChannelStartupService { task.start(); } } + + private async updateChatUnreadMessages(remoteJid: string): Promise { + const [chat, unreadMessages] = await Promise.all([ + this.prismaRepository.chat.findFirst({ where: { remoteJid } }), + this.prismaRepository.message.count({ + where: { + AND: [ + { key: { path: ['remoteJid'], equals: remoteJid } }, + { key: { path: ['fromMe'], equals: false } }, + { status: { equals: status[3] } }, + ], + }, + }), + ]); + + if (chat && chat.unreadMessages !== unreadMessages) { + await this.prismaRepository.chat.update({ + where: { id: chat.id }, + data: { unreadMessages }, + }); + } + + return unreadMessages; + } } From 73e732bf24f48ae66578d09b5a388569938a7a40 Mon Sep 17 00:00:00 2001 From: Jesus Date: Tue, 8 Oct 2024 12:51:34 +0200 Subject: [PATCH 4/5] Added last message to fetch chats --- src/api/services/channel.service.ts | 179 +++++++++++++++++----------- 1 file changed, 110 insertions(+), 69 deletions(-) diff --git a/src/api/services/channel.service.ts b/src/api/services/channel.service.ts index 8c19173e..708903b6 100644 --- a/src/api/services/channel.service.ts +++ b/src/api/services/channel.service.ts @@ -310,9 +310,7 @@ export class ChannelStartupService { return null; } - const ignoreJidsArray = Array.isArray(data.ignoreJids) - ? data.ignoreJids.map((event) => String(event)) - : []; + const ignoreJidsArray = Array.isArray(data.ignoreJids) ? data.ignoreJids.map((event) => String(event)) : []; return { enabled: data?.enabled, @@ -540,9 +538,7 @@ export class ChannelStartupService { keyFilters?.id ? { key: { path: ['id'], equals: keyFilters?.id } } : {}, keyFilters?.fromMe ? { key: { path: ['fromMe'], equals: keyFilters?.fromMe } } : {}, keyFilters?.remoteJid ? { key: { path: ['remoteJid'], equals: keyFilters?.remoteJid } } : {}, - keyFilters?.participants - ? { key: { path: ['participants'], equals: keyFilters?.participants } } - : {}, + keyFilters?.participants ? { key: { path: ['participants'], equals: keyFilters?.participants } } : {}, ], }, }); @@ -565,9 +561,7 @@ export class ChannelStartupService { keyFilters?.id ? { key: { path: ['id'], equals: keyFilters?.id } } : {}, keyFilters?.fromMe ? { key: { path: ['fromMe'], equals: keyFilters?.fromMe } } : {}, keyFilters?.remoteJid ? { key: { path: ['remoteJid'], equals: keyFilters?.remoteJid } } : {}, - keyFilters?.participants - ? { key: { path: ['participants'], equals: keyFilters?.participants } } - : {}, + keyFilters?.participants ? { key: { path: ['participants'], equals: keyFilters?.participants } } : {}, ], }, orderBy: { @@ -621,67 +615,114 @@ export class ChannelStartupService { : this.createJid(query.where?.remoteJid) : null; - const result = await this.prismaRepository.$queryRaw` - SELECT - "Chat"."id", - "Chat"."remoteJid", - "Chat"."name", - "Chat"."labels", - "Chat"."createdAt", - "Chat"."updatedAt", - "Contact"."pushName", - "Contact"."profilePicUrl", - (ARRAY_AGG("Message"."id" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_id, - (ARRAY_AGG("Message"."key" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_key, - (ARRAY_AGG("Message"."pushName" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_pushName, - (ARRAY_AGG("Message"."participant" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_participant, - (ARRAY_AGG("Message"."messageType" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_messageType, - (ARRAY_AGG("Message"."message" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_message, - (ARRAY_AGG("Message"."contextInfo" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_contextInfo, - (ARRAY_AGG("Message"."source" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_source, - (ARRAY_AGG("Message"."messageTimestamp" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_messageTimestamp, - (ARRAY_AGG("Message"."instanceId" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_instanceId, - (ARRAY_AGG("Message"."sessionId" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_sessionId, - (ARRAY_AGG("Message"."status" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_status - FROM "Chat" - LEFT JOIN "Message" ON "Message"."key"->>'remoteJid' = "Chat"."remoteJid" - LEFT JOIN "Contact" ON "Chat"."remoteJid" = "Contact"."remoteJid" - WHERE - "Chat"."instanceId" like ${this.instanceId} - ${remoteJid ? 'AND "Chat"."remoteJid" like ${remoteJid}' : ''} - GROUP BY - "Chat"."id", - "Chat"."remoteJid", - "Contact"."id" - ORDER BY "Chat"."updatedAt" DESC; - `.then((chats) => { - if (chats && isArray(chats) && chats.length > 0) { - return chats.map((chat) => { - return { - ...chat, - lastMessage: chat.last_message_id - ? { - id: chat.last_message_id, - key: chat.last_message_key, - pushName: chat.last_message_pushName, - participant: chat.last_message_participant, - messageType: chat.last_message_messageType, - message: chat.last_message_message, - contextInfo: chat.last_message_contextInfo, - source: chat.last_message_source, - messageTimestamp: chat.last_message_messageTimestamp, - instanceId: chat.last_message_instanceId, - sessionId: chat.last_message_sessionId, - status: chat.last_message_status, - } - : undefined, - }; - }); - } + let results = []; - return []; - }); + if (!remoteJid) { + results = await this.prismaRepository.$queryRaw` + SELECT + "Chat"."id", + "Chat"."remoteJid", + "Chat"."name", + "Chat"."labels", + "Chat"."createdAt", + "Chat"."updatedAt", + "Contact"."pushName", + "Contact"."profilePicUrl", + "Chat"."unreadMessages", + (ARRAY_AGG("Message"."id" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_id, + (ARRAY_AGG("Message"."key" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_key, + (ARRAY_AGG("Message"."pushName" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_pushName, + (ARRAY_AGG("Message"."participant" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_participant, + (ARRAY_AGG("Message"."messageType" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_messageType, + (ARRAY_AGG("Message"."message" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_message, + (ARRAY_AGG("Message"."contextInfo" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_contextInfo, + (ARRAY_AGG("Message"."source" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_source, + (ARRAY_AGG("Message"."messageTimestamp" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_messageTimestamp, + (ARRAY_AGG("Message"."instanceId" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_instanceId, + (ARRAY_AGG("Message"."sessionId" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_sessionId, + (ARRAY_AGG("Message"."status" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_status + FROM "Chat" + LEFT JOIN "Message" ON "Message"."key"->>'remoteJid' = "Chat"."remoteJid" + LEFT JOIN "Contact" ON "Chat"."remoteJid" = "Contact"."remoteJid" + WHERE + "Chat"."instanceId" = ${this.instanceId} + GROUP BY + "Chat"."id", + "Chat"."remoteJid", + "Contact"."id", + "Message"."messageTimestamp" + ORDER BY "Message"."messageTimestamp" DESC NULLS LAST, "Chat"."updatedAt" DESC; + `; + } else { + results = await this.prismaRepository.$queryRaw` + SELECT + "Chat"."id", + "Chat"."remoteJid", + "Chat"."name", + "Chat"."labels", + "Chat"."createdAt", + "Chat"."updatedAt", + "Contact"."pushName", + "Contact"."profilePicUrl", + "Chat"."unreadMessages", + (ARRAY_AGG("Message"."id" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_id, + (ARRAY_AGG("Message"."key" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_key, + (ARRAY_AGG("Message"."pushName" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_pushName, + (ARRAY_AGG("Message"."participant" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_participant, + (ARRAY_AGG("Message"."messageType" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_messageType, + (ARRAY_AGG("Message"."message" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_message, + (ARRAY_AGG("Message"."contextInfo" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_contextInfo, + (ARRAY_AGG("Message"."source" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_source, + (ARRAY_AGG("Message"."messageTimestamp" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_messageTimestamp, + (ARRAY_AGG("Message"."instanceId" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_instanceId, + (ARRAY_AGG("Message"."sessionId" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_sessionId, + (ARRAY_AGG("Message"."status" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_status + FROM "Chat" + LEFT JOIN "Message" ON "Message"."key"->>'remoteJid' = "Chat"."remoteJid" + LEFT JOIN "Contact" ON "Chat"."remoteJid" = "Contact"."remoteJid" + WHERE + "Chat"."instanceId" = ${this.instanceId} AND "Chat"."remoteJid" = ${remoteJid} + GROUP BY + "Chat"."id", + "Chat"."remoteJid", + "Contact"."id", + "Message"."messageTimestamp" + ORDER BY "Message"."messageTimestamp" DESC NULLS LAST, "Chat"."updatedAt" DESC; + `; + } - return result; + if (results && isArray(results) && results.length > 0) { + return results.map((chat) => { + return { + id: chat.id, + remoteJid: chat.remoteJid, + name: chat.name, + labels: chat.labels, + createdAt: chat.createdAt, + updatedAt: chat.updatedAt, + pushName: chat.pushName, + profilePicUrl: chat.profilePicUrl, + unreadMessages: chat.unreadMessages, + lastMessage: chat.last_message_id + ? { + id: chat.last_message_id, + key: chat.last_message_key, + pushName: chat.last_message_pushName, + participant: chat.last_message_participant, + messageType: chat.last_message_messageType, + message: chat.last_message_message, + contextInfo: chat.last_message_contextInfo, + source: chat.last_message_source, + messageTimestamp: chat.last_message_messageTimestamp, + instanceId: chat.last_message_instanceId, + sessionId: chat.last_message_sessionId, + status: chat.last_message_status, + } + : undefined, + }; + }); + } + + return []; } } From 394c091810b8691f7ed4bcb42f656fe17e58cc4f Mon Sep 17 00:00:00 2001 From: Jesus Date: Tue, 8 Oct 2024 17:15:53 +0200 Subject: [PATCH 5/5] Fix parse multiples messages updates and creates --- .../whatsapp/whatsapp.baileys.service.ts | 75 ++++++++++++------- 1 file changed, 47 insertions(+), 28 deletions(-) diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index 0e0d38a5..0e5198d3 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -983,8 +983,10 @@ export class BaileysStartupService extends ChannelStartupService { for (const received of messages) { if (received.message?.conversation || received.message?.extendedTextMessage?.text) { const text = received.message?.conversation || received.message?.extendedTextMessage?.text; + if (text == 'requestPlaceholder' && !requestId) { const messageId = await this.client.requestPlaceholderResend(received.key); + console.log('requested placeholder resync, id=', messageId); } else if (requestId) { console.log('Message received from phone, id=', requestId, received); @@ -1018,6 +1020,7 @@ export class BaileysStartupService extends ChannelStartupService { message: received, retry: 0, }); + continue; } @@ -1034,7 +1037,7 @@ export class BaileysStartupService extends ChannelStartupService { received.message?.pollUpdateMessage || !received?.message ) { - return; + continue; } if (Long.isLong(received.messageTimestamp)) { @@ -1042,7 +1045,7 @@ export class BaileysStartupService extends ChannelStartupService { } if (settings?.groupsIgnore && received.key.remoteJid.includes('@g.us')) { - return; + continue; } const messageRaw = this.prepareMessage(received); @@ -1105,9 +1108,15 @@ export class BaileysStartupService extends ChannelStartupService { data: messageRaw, }); - if (received.key.fromMe === false && msg.status === status[3]) { - // is received not read message - await this.updateChatUnreadMessages(received.key.remoteJid); + if (received.key.fromMe === false) { + if (msg.status === status[3]) { + this.logger.log(`Update not read messages ${received.key.remoteJid}`); + // is received not read message + await this.updateChatUnreadMessages(received.key.remoteJid); + } else if (msg.status === status[4]) { + this.logger.log(`Update readed messages ${received.key.remoteJid} - ${msg.messageTimestamp}`); + this.updateMessagesReadedByTimestamp(received.key.remoteJid, msg.messageTimestamp); + } } if (isMedia) { @@ -1122,11 +1131,8 @@ export class BaileysStartupService extends ChannelStartupService { ); const { buffer, mediaType, fileName, size } = media; - const mimetype = mime.getType(fileName).toString(); - const fullName = join(`${this.instance.id}`, received.key.remoteJid, mediaType, fileName); - await s3Service.uploadFile(fullName, buffer, size.fileLength?.low, { 'Content-Type': mimetype, }); @@ -1193,7 +1199,7 @@ export class BaileysStartupService extends ChannelStartupService { }; if (contactRaw.remoteJid === 'status@broadcast') { - return; + continue; } if (contact) { @@ -1214,7 +1220,7 @@ export class BaileysStartupService extends ChannelStartupService { update: contactRaw, }); - return; + continue; } this.sendDataWebhook(Events.CONTACTS_UPSERT, contactRaw); @@ -1241,11 +1247,11 @@ export class BaileysStartupService extends ChannelStartupService { }, 'messages.update': async (args: WAMessageUpdate[], settings: any) => { - const readChatToUpdate: Record = {}; // remoteJid[] + const readChatToUpdate: Record = {}; // {remoteJid: true} for await (const { key, update } of args) { if (settings?.groupsIgnore && key.remoteJid?.includes('@g.us')) { - return; + continue; } if (status[update.status] === 'READ' && key.fromMe) { @@ -1260,6 +1266,7 @@ export class BaileysStartupService extends ChannelStartupService { if (key.remoteJid !== 'status@broadcast') { let pollUpdates: any; + if (update.pollUpdates) { const pollCreation = await this.getMessage(key); @@ -1282,7 +1289,7 @@ export class BaileysStartupService extends ChannelStartupService { }); if (!findMessage) { - return; + continue; } if (update.message === null && update.status === undefined) { @@ -1311,26 +1318,14 @@ export class BaileysStartupService extends ChannelStartupService { ); } - return; + continue; } else if (update.status !== undefined && status[update.status] !== findMessage.status) { if (!key.fromMe && key.remoteJid) { readChatToUpdate[key.remoteJid] = true; if (status[update.status] === status[4]) { - // Mark to read old messages - await this.prismaRepository.message.updateMany({ - where: { - AND: [ - { key: { path: ['remoteJid'], equals: key.remoteJid } }, - { key: { path: ['fromMe'], equals: false } }, - { messageTimestamp: { lt: findMessage.messageTimestamp } }, // Delivered messages - { - OR: [{ status: null }, { status: status[3] }], - }, - ], - }, - data: { status: status[4] }, - }); + this.logger.log(`Update as read ${key.remoteJid} - ${findMessage.messageTimestamp}`); + this.updateMessagesReadedByTimestamp(key.remoteJid, findMessage.messageTimestamp); } } @@ -3750,6 +3745,30 @@ export class BaileysStartupService extends ChannelStartupService { } } + private async updateMessagesReadedByTimestamp(remoteJid: string, timestamp?: number): Promise { + if (timestamp === undefined || timestamp === null) return 0; + + const result = await this.prismaRepository.message.updateMany({ + where: { + AND: [ + { key: { path: ['remoteJid'], equals: remoteJid } }, + { key: { path: ['fromMe'], equals: false } }, + { messageTimestamp: { lte: timestamp } }, + { + OR: [{ status: null }, { status: status[3] }], + }, + ], + }, + data: { status: status[4] }, + }); + + if (result) { + return result.count; + } + + return 0; + } + private async updateChatUnreadMessages(remoteJid: string): Promise { const [chat, unreadMessages] = await Promise.all([ this.prismaRepository.chat.findFirst({ where: { remoteJid } }),