Skip to content

Commit 8fe310f

Browse files
committed
fix: Mark as read from me and groups
1 parent 5f34d9c commit 8fe310f

File tree

1 file changed

+108
-25
lines changed

1 file changed

+108
-25
lines changed

src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

Lines changed: 108 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,7 @@ import makeWASocket, {
9999
isJidUser,
100100
makeCacheableSignalKeyStore,
101101
MessageUpsertType,
102+
MessageUserReceiptUpdate,
102103
MiscMessageGenerationOptions,
103104
ParticipantAction,
104105
prepareWAMessageMedia,
@@ -582,7 +583,6 @@ export class BaileysStartupService extends ChannelStartupService {
582583
remoteJid: chat.id,
583584
instanceId: this.instanceId,
584585
name: chat.name,
585-
unreadMessages: chat.unreadCount !== undefined ? chat.unreadCount : 0,
586586
}));
587587

588588
this.sendDataWebhook(Events.CHATS_UPSERT, chatsToInsert);
@@ -884,15 +884,15 @@ export class BaileysStartupService extends ChannelStartupService {
884884
received.message?.pollUpdateMessage ||
885885
!received?.message
886886
) {
887-
return;
887+
continue;
888888
}
889889

890890
if (Long.isLong(received.messageTimestamp)) {
891891
received.messageTimestamp = received.messageTimestamp?.toNumber();
892892
}
893893

894894
if (settings?.groupsIgnore && received.key.remoteJid.includes('@g.us')) {
895-
return;
895+
continue;
896896
}
897897

898898
const messageRaw = this.prepareMessage(received);
@@ -914,9 +914,23 @@ export class BaileysStartupService extends ChannelStartupService {
914914
}
915915

916916
if (this.configService.get<Database>('DATABASE').SAVE_DATA.NEW_MESSAGE) {
917-
await this.prismaRepository.message.create({
917+
const msg = await this.prismaRepository.message.create({
918918
data: messageRaw,
919919
});
920+
921+
if (received.key.fromMe === false) {
922+
if (msg.status === status[3]) {
923+
this.logger.log(`Update not read messages ${received.key.remoteJid}`);
924+
await this.updateChatUnreadMessages(received.key.remoteJid);
925+
} else if (msg.status === status[4]) {
926+
this.logger.log(`Update readed messages ${received.key.remoteJid} - ${msg.messageTimestamp}`);
927+
await this.updateMessagesReadedByTimestamp(received.key.remoteJid, msg.messageTimestamp);
928+
}
929+
} else {
930+
this.logger.log(`Update readed messages ${received.key.remoteJid} - ${msg.messageTimestamp}`);
931+
932+
await this.updateMessagesReadedByTimestamp(received.key.remoteJid, msg.messageTimestamp);
933+
}
920934
}
921935

922936
if (this.localWebhook.enabled) {
@@ -962,7 +976,7 @@ export class BaileysStartupService extends ChannelStartupService {
962976
};
963977

964978
if (contactRaw.remoteJid === 'status@broadcast') {
965-
return;
979+
continue;
966980
}
967981

968982
if (contact) {
@@ -975,7 +989,7 @@ export class BaileysStartupService extends ChannelStartupService {
975989
update: contactRaw,
976990
});
977991

978-
return;
992+
continue;
979993
}
980994

981995
this.sendDataWebhook(Events.CONTACTS_UPSERT, contactRaw);
@@ -1002,11 +1016,13 @@ export class BaileysStartupService extends ChannelStartupService {
10021016
},
10031017

10041018
'messages.update': async (args: WAMessageUpdate[], settings: any) => {
1005-
const unreadChatToUpdate: Record<string, number> = {};
1019+
this.logger.log(`Update messages ${JSON.stringify(args, undefined, 2)}`);
1020+
1021+
const readChatToUpdate: Record<string, true> = {};
10061022

10071023
for await (const { key, update } of args) {
10081024
if (settings?.groupsIgnore && key.remoteJid?.includes('@g.us')) {
1009-
return;
1025+
continue;
10101026
}
10111027

10121028
if (key.remoteJid !== 'status@broadcast') {
@@ -1033,7 +1049,7 @@ export class BaileysStartupService extends ChannelStartupService {
10331049
});
10341050

10351051
if (!findMessage) {
1036-
return;
1052+
continue;
10371053
}
10381054

10391055
if (update.message === null && update.status === undefined) {
@@ -1054,15 +1070,18 @@ export class BaileysStartupService extends ChannelStartupService {
10541070
data: message,
10551071
});
10561072

1057-
return;
1073+
continue;
10581074
} else if (update.status !== undefined && status[update.status] !== findMessage.status) {
1059-
if (!unreadChatToUpdate[key.remoteJid!]) {
1060-
unreadChatToUpdate[key.remoteJid!] = 0;
1061-
}
1075+
if (!key.fromMe && key.remoteJid) {
1076+
readChatToUpdate[key.remoteJid] = true;
10621077

1063-
unreadChatToUpdate[key.remoteJid!]++;
1078+
if (status[update.status] === status[4]) {
1079+
this.logger.log(`Update as read ${key.remoteJid} - ${findMessage.messageTimestamp}`);
1080+
this.updateMessagesReadedByTimestamp(key.remoteJid, findMessage.messageTimestamp);
1081+
}
1082+
}
10641083

1065-
this.prismaRepository.message.update({
1084+
await this.prismaRepository.message.update({
10661085
where: { id: findMessage.id },
10671086
data: { status: status[update.status] },
10681087
});
@@ -1088,16 +1107,7 @@ export class BaileysStartupService extends ChannelStartupService {
10881107
}
10891108
}
10901109

1091-
for await (const [remoteJid, unreadMessages] of Object.entries(unreadChatToUpdate)) {
1092-
const chat = await this.prismaRepository.chat.findFirst({ where: { remoteJid } });
1093-
1094-
if (chat) {
1095-
this.prismaRepository.chat.update({
1096-
where: { id: chat.id },
1097-
data: { unreadMessages: Math.max(0, chat.unreadMessages - unreadMessages) },
1098-
});
1099-
}
1100-
}
1110+
await Promise.all(Object.keys(readChatToUpdate).map((remoteJid) => this.updateChatUnreadMessages(remoteJid)));
11011111
},
11021112
};
11031113

@@ -1253,6 +1263,23 @@ export class BaileysStartupService extends ChannelStartupService {
12531263
this.messageHandle['messages.update'](payload, settings);
12541264
}
12551265

1266+
if (events['message-receipt.update']) {
1267+
const payload = events['message-receipt.update'] as MessageUserReceiptUpdate[];
1268+
const remotesJidMap: Record<string, number> = {};
1269+
1270+
for (const event of payload) {
1271+
if (typeof event.key.remoteJid === 'string' && typeof event.receipt.readTimestamp === 'number') {
1272+
remotesJidMap[event.key.remoteJid] = event.receipt.readTimestamp;
1273+
}
1274+
}
1275+
1276+
await Promise.all(
1277+
Object.keys(remotesJidMap).map(async (remoteJid) =>
1278+
this.updateMessagesReadedByTimestamp(remoteJid, remotesJidMap[remoteJid]),
1279+
),
1280+
);
1281+
}
1282+
12561283
if (events['presence.update']) {
12571284
const payload = events['presence.update'];
12581285

@@ -3247,6 +3274,10 @@ export class BaileysStartupService extends ChannelStartupService {
32473274
source: getDevice(message.key.id),
32483275
};
32493276

3277+
if (!messageRaw.status && message.key.fromMe === false) {
3278+
messageRaw.status = status[3];
3279+
}
3280+
32503281
if (messageRaw.message.extendedTextMessage) {
32513282
messageRaw.messageType = 'conversation';
32523283
messageRaw.message.conversation = messageRaw.message.extendedTextMessage.text;
@@ -3261,4 +3292,56 @@ export class BaileysStartupService extends ChannelStartupService {
32613292

32623293
return messageRaw;
32633294
}
3295+
3296+
private async updateMessagesReadedByTimestamp(remoteJid: string, timestamp?: number): Promise<number> {
3297+
if (timestamp === undefined || timestamp === null) return 0;
3298+
3299+
const result = await this.prismaRepository.message.updateMany({
3300+
where: {
3301+
AND: [
3302+
{ key: { path: ['remoteJid'], equals: remoteJid } },
3303+
{ key: { path: ['fromMe'], equals: false } },
3304+
{ messageTimestamp: { lte: timestamp } },
3305+
{
3306+
OR: [{ status: null }, { status: status[3] }],
3307+
},
3308+
],
3309+
},
3310+
data: { status: status[4] },
3311+
});
3312+
3313+
if (result) {
3314+
if (result.count > 0) {
3315+
this.updateChatUnreadMessages(remoteJid);
3316+
}
3317+
3318+
return result.count;
3319+
}
3320+
3321+
return 0;
3322+
}
3323+
3324+
private async updateChatUnreadMessages(remoteJid: string): Promise<number> {
3325+
const [chat, unreadMessages] = await Promise.all([
3326+
this.prismaRepository.chat.findFirst({ where: { remoteJid } }),
3327+
this.prismaRepository.message.count({
3328+
where: {
3329+
AND: [
3330+
{ key: { path: ['remoteJid'], equals: remoteJid } },
3331+
{ key: { path: ['fromMe'], equals: false } },
3332+
{ status: { equals: status[3] } },
3333+
],
3334+
},
3335+
}),
3336+
]);
3337+
3338+
if (chat && chat.unreadMessages !== unreadMessages) {
3339+
await this.prismaRepository.chat.update({
3340+
where: { id: chat.id },
3341+
data: { unreadMessages },
3342+
});
3343+
}
3344+
3345+
return unreadMessages;
3346+
}
32643347
}

0 commit comments

Comments
 (0)