Skip to content

Commit a1cc504

Browse files
Merge pull request #1449 from gomessguii/feature/enhance-message-fetching
feat(whatsapp): enhance message fetching and processing logic
2 parents 0fd2e04 + 401b035 commit a1cc504

File tree

1 file changed

+140
-22
lines changed

1 file changed

+140
-22
lines changed

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

Lines changed: 140 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ import {
5555
import { chatwootImport } from '@api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper';
5656
import * as s3Service from '@api/integrations/storage/s3/libs/minio.server';
5757
import { ProviderFiles } from '@api/provider/sessions';
58-
import { PrismaRepository } from '@api/repository/repository.service';
58+
import { PrismaRepository, Query } from '@api/repository/repository.service';
5959
import { chatbotController, waMonitor } from '@api/server.module';
6060
import { CacheService } from '@api/services/cache.service';
6161
import { ChannelStartupService } from '@api/services/channel.service';
@@ -78,7 +78,7 @@ import { BadRequestException, InternalServerErrorException, NotFoundException }
7878
import ffmpegPath from '@ffmpeg-installer/ffmpeg';
7979
import { Boom } from '@hapi/boom';
8080
import { createId as cuid } from '@paralleldrive/cuid2';
81-
import { Instance } from '@prisma/client';
81+
import { Instance, Message } from '@prisma/client';
8282
import { createJid } from '@utils/createJid';
8383
import { makeProxyAgent } from '@utils/makeProxyAgent';
8484
import { getOnWhatsappCache, saveOnWhatsappCache } from '@utils/onWhatsappCache';
@@ -664,6 +664,10 @@ export class BaileysStartupService extends ChannelStartupService {
664664
qrTimeout: 45_000,
665665
emitOwnEvents: false,
666666
shouldIgnoreJid: (jid) => {
667+
if (this.localSettings.syncFullHistory && isJidGroup(jid)) {
668+
return false;
669+
}
670+
667671
const isGroupJid = this.localSettings.groupsIgnore && isJidGroup(jid);
668672
const isBroadcast = !this.localSettings.readStatus && isJidBroadcast(jid);
669673
const isNewsletter = isJidNewsletter(jid);
@@ -991,6 +995,17 @@ export class BaileysStartupService extends ChannelStartupService {
991995
}
992996
}
993997

998+
const contactsMap = new Map();
999+
1000+
for (const contact of contacts) {
1001+
if (contact.id && (contact.notify || contact.name)) {
1002+
contactsMap.set(contact.id, {
1003+
name: contact.name ?? contact.notify,
1004+
jid: contact.id,
1005+
});
1006+
}
1007+
}
1008+
9941009
const chatsRaw: { remoteJid: string; instanceId: string; name?: string }[] = [];
9951010
const chatsRepository = new Set(
9961011
(
@@ -1062,6 +1077,15 @@ export class BaileysStartupService extends ChannelStartupService {
10621077
continue;
10631078
}
10641079

1080+
if (!m.pushName && !m.key.fromMe) {
1081+
const participantJid = m.participant || m.key.participant || m.key.remoteJid;
1082+
if (participantJid && contactsMap.has(participantJid)) {
1083+
m.pushName = contactsMap.get(participantJid).name;
1084+
} else if (participantJid) {
1085+
m.pushName = participantJid.split('@')[0];
1086+
}
1087+
}
1088+
10651089
messagesRaw.push(this.prepareMessage(m));
10661090
}
10671091

@@ -1173,25 +1197,6 @@ export class BaileysStartupService extends ChannelStartupService {
11731197
}
11741198
}
11751199

1176-
// if (received.messageStubParameters && received.messageStubParameters[0] === 'Message absent from node') {
1177-
// this.logger.info(`Recovering message lost messageId: ${received.key.id}`);
1178-
1179-
// await this.baileysCache.set(received.key.id, {
1180-
// message: received,
1181-
// retry: 0,
1182-
// });
1183-
1184-
// continue;
1185-
// }
1186-
1187-
// const retryCache = (await this.baileysCache.get(received.key.id)) || null;
1188-
1189-
// if (retryCache) {
1190-
// this.logger.info('Recovered message lost');
1191-
// await this.baileysCache.delete(received.key.id);
1192-
// }
1193-
1194-
// Cache to avoid duplicate messages
11951200
const messageKey = `${this.instance.id}_${received.key.id}`;
11961201
const cached = await this.baileysCache.get(messageKey);
11971202

@@ -1218,6 +1223,7 @@ export class BaileysStartupService extends ChannelStartupService {
12181223
if (settings?.groupsIgnore && received.key.remoteJid.includes('@g.us')) {
12191224
continue;
12201225
}
1226+
12211227
const existingChat = await this.prismaRepository.chat.findFirst({
12221228
where: { instanceId: this.instanceId, remoteJid: received.key.remoteJid },
12231229
select: { id: true, name: true },
@@ -4481,7 +4487,11 @@ export class BaileysStartupService extends ChannelStartupService {
44814487

44824488
const messageRaw = {
44834489
key: message.key,
4484-
pushName: message.pushName,
4490+
pushName:
4491+
message.pushName ||
4492+
(message.key.fromMe
4493+
? 'Você'
4494+
: message?.participant || (message.key?.participant ? message.key.participant.split('@')[0] : null)),
44854495
status: status[message.status],
44864496
message: { ...message.message },
44874497
contextInfo: contentMsg?.contextInfo,
@@ -4849,4 +4859,112 @@ export class BaileysStartupService extends ChannelStartupService {
48494859
throw new InternalServerErrorException('Error getCatalog', error.toString());
48504860
}
48514861
}
4862+
4863+
public async fetchMessages(query: Query<Message>) {
4864+
const keyFilters = query?.where?.key as {
4865+
id?: string;
4866+
fromMe?: boolean;
4867+
remoteJid?: string;
4868+
participants?: string;
4869+
};
4870+
4871+
const timestampFilter = {};
4872+
if (query?.where?.messageTimestamp) {
4873+
if (query.where.messageTimestamp['gte'] && query.where.messageTimestamp['lte']) {
4874+
timestampFilter['messageTimestamp'] = {
4875+
gte: Math.floor(new Date(query.where.messageTimestamp['gte']).getTime() / 1000),
4876+
lte: Math.floor(new Date(query.where.messageTimestamp['lte']).getTime() / 1000),
4877+
};
4878+
}
4879+
}
4880+
4881+
const count = await this.prismaRepository.message.count({
4882+
where: {
4883+
instanceId: this.instanceId,
4884+
id: query?.where?.id,
4885+
source: query?.where?.source,
4886+
messageType: query?.where?.messageType,
4887+
...timestampFilter,
4888+
AND: [
4889+
keyFilters?.id ? { key: { path: ['id'], equals: keyFilters?.id } } : {},
4890+
keyFilters?.fromMe ? { key: { path: ['fromMe'], equals: keyFilters?.fromMe } } : {},
4891+
keyFilters?.remoteJid ? { key: { path: ['remoteJid'], equals: keyFilters?.remoteJid } } : {},
4892+
keyFilters?.participants ? { key: { path: ['participants'], equals: keyFilters?.participants } } : {},
4893+
],
4894+
},
4895+
});
4896+
4897+
if (!query?.offset) {
4898+
query.offset = 50;
4899+
}
4900+
4901+
if (!query?.page) {
4902+
query.page = 1;
4903+
}
4904+
4905+
const messages = await this.prismaRepository.message.findMany({
4906+
where: {
4907+
instanceId: this.instanceId,
4908+
id: query?.where?.id,
4909+
source: query?.where?.source,
4910+
messageType: query?.where?.messageType,
4911+
...timestampFilter,
4912+
AND: [
4913+
keyFilters?.id ? { key: { path: ['id'], equals: keyFilters?.id } } : {},
4914+
keyFilters?.fromMe ? { key: { path: ['fromMe'], equals: keyFilters?.fromMe } } : {},
4915+
keyFilters?.remoteJid ? { key: { path: ['remoteJid'], equals: keyFilters?.remoteJid } } : {},
4916+
keyFilters?.participants ? { key: { path: ['participants'], equals: keyFilters?.participants } } : {},
4917+
],
4918+
},
4919+
orderBy: {
4920+
messageTimestamp: 'desc',
4921+
},
4922+
skip: query.offset * (query?.page === 1 ? 0 : (query?.page as number) - 1),
4923+
take: query.offset,
4924+
select: {
4925+
id: true,
4926+
key: true,
4927+
pushName: true,
4928+
messageType: true,
4929+
message: true,
4930+
messageTimestamp: true,
4931+
instanceId: true,
4932+
source: true,
4933+
contextInfo: true,
4934+
MessageUpdate: {
4935+
select: {
4936+
status: true,
4937+
},
4938+
},
4939+
},
4940+
});
4941+
4942+
const formattedMessages = messages.map((message) => {
4943+
const messageKey = message.key as { fromMe: boolean; remoteJid: string; id: string; participant?: string };
4944+
4945+
if (!message.pushName) {
4946+
if (messageKey.fromMe) {
4947+
message.pushName = 'Você';
4948+
} else if (message.contextInfo) {
4949+
const contextInfo = message.contextInfo as { participant?: string };
4950+
if (contextInfo.participant) {
4951+
message.pushName = contextInfo.participant.split('@')[0];
4952+
} else if (messageKey.participant) {
4953+
message.pushName = messageKey.participant.split('@')[0];
4954+
}
4955+
}
4956+
}
4957+
4958+
return message;
4959+
});
4960+
4961+
return {
4962+
messages: {
4963+
total: count,
4964+
pages: Math.ceil(count / query.offset),
4965+
currentPage: query.page,
4966+
records: formattedMessages,
4967+
},
4968+
};
4969+
}
48524970
}

0 commit comments

Comments
 (0)