diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index 64d5388c..46dbce67 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -667,7 +667,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 }, }); @@ -985,8 +984,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); @@ -1020,6 +1021,7 @@ export class BaileysStartupService extends ChannelStartupService { message: received, retry: 0, }); + continue; } @@ -1036,7 +1038,7 @@ export class BaileysStartupService extends ChannelStartupService { received.message?.pollUpdateMessage || !received?.message ) { - return; + continue; } if (Long.isLong(received.messageTimestamp)) { @@ -1044,7 +1046,7 @@ export class BaileysStartupService extends ChannelStartupService { } if (settings?.groupsIgnore && received.key.remoteJid.includes('@g.us')) { - return; + continue; } const messageRaw = this.prepareMessage(received); @@ -1107,6 +1109,17 @@ export class BaileysStartupService extends ChannelStartupService { data: messageRaw, }); + 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) { if (this.configService.get('S3').ENABLE) { try { @@ -1119,11 +1132,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, }); @@ -1192,7 +1202,7 @@ export class BaileysStartupService extends ChannelStartupService { }; if (contactRaw.remoteJid === 'status@broadcast') { - return; + continue; } if (contact) { @@ -1213,7 +1223,7 @@ export class BaileysStartupService extends ChannelStartupService { update: contactRaw, }); - return; + continue; } this.sendDataWebhook(Events.CONTACTS_UPSERT, contactRaw); @@ -1240,11 +1250,11 @@ export class BaileysStartupService extends ChannelStartupService { }, 'messages.update': async (args: WAMessageUpdate[], settings: any) => { - const unreadChatToUpdate: Record = {}; // {remoteJid: readedMessages} + 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) { @@ -1259,6 +1269,7 @@ export class BaileysStartupService extends ChannelStartupService { if (key.remoteJid !== 'status@broadcast') { let pollUpdates: any; + if (update.pollUpdates) { const pollCreation = await this.getMessage(key); @@ -1281,7 +1292,7 @@ export class BaileysStartupService extends ChannelStartupService { }); if (!findMessage) { - return; + continue; } if (update.message === null && update.status === undefined) { @@ -1310,15 +1321,18 @@ export class BaileysStartupService extends ChannelStartupService { ); } - return; + continue; } 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]) { + this.logger.log(`Update as read ${key.remoteJid} - ${findMessage.messageTimestamp}`); + this.updateMessagesReadedByTimestamp(key.remoteJid, findMessage.messageTimestamp); + } } - unreadChatToUpdate[key.remoteJid!]++; - - this.prismaRepository.message.update({ + await this.prismaRepository.message.update({ where: { id: findMessage.id }, data: { status: status[update.status] }, }); @@ -1344,16 +1358,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))); }, }; @@ -3713,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; @@ -3740,4 +3749,52 @@ export class BaileysStartupService extends ChannelStartupService { task.start(); } } + + 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 } }), + 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; + } } diff --git a/src/api/services/channel.service.ts b/src/api/services/channel.service.ts index c96ba52d..d917f3a1 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'; @@ -627,35 +628,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", - "Contact"."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", - "Contact"."unreadMessages" - ORDER BY "Chat"."updatedAt" DESC; - `; + let results = []; - return result; + 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; + `; + } + + 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 []; } }