Skip to content

Commit 383805a

Browse files
committed
feat(whatsapp): enhance message fetching and processing logic
- Added a new method `fetchMessages` to retrieve messages based on various query parameters. - Improved handling of `pushName` for messages, ensuring proper assignment based on participant information. - Refactored user devices cache initialization for better readability. - Cleaned up commented-out code related to message recovery.
1 parent 6d63f2f commit 383805a

File tree

1 file changed

+144
-27
lines changed

1 file changed

+144
-27
lines changed

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

Lines changed: 144 additions & 27 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';
@@ -134,7 +134,6 @@ import { randomBytes } from 'crypto';
134134
import EventEmitter2 from 'eventemitter2';
135135
import ffmpeg from 'fluent-ffmpeg';
136136
import FormData from 'form-data';
137-
import { readFileSync } from 'fs';
138137
import Long from 'long';
139138
import mimeTypes from 'mime-types';
140139
import NodeCache from 'node-cache';
@@ -230,10 +229,10 @@ export class BaileysStartupService extends ChannelStartupService {
230229

231230
private authStateProvider: AuthStateProvider;
232231
private readonly msgRetryCounterCache: CacheStore = new NodeCache();
233-
private readonly userDevicesCache: CacheStore = new NodeCache({
234-
stdTTL: 300000,
235-
useClones: false
236-
});
232+
private readonly userDevicesCache: CacheStore = new NodeCache({
233+
stdTTL: 300000,
234+
useClones: false,
235+
});
237236
private endSession = false;
238237
private logBaileys = this.configService.get<Log>('LOG').BAILEYS;
239238

@@ -665,6 +664,10 @@ export class BaileysStartupService extends ChannelStartupService {
665664
qrTimeout: 45_000,
666665
emitOwnEvents: false,
667666
shouldIgnoreJid: (jid) => {
667+
if (this.localSettings.syncFullHistory && isJidGroup(jid)) {
668+
return false;
669+
}
670+
668671
const isGroupJid = this.localSettings.groupsIgnore && isJidGroup(jid);
669672
const isBroadcast = !this.localSettings.readStatus && isJidBroadcast(jid);
670673
const isNewsletter = isJidNewsletter(jid);
@@ -992,6 +995,17 @@ export class BaileysStartupService extends ChannelStartupService {
992995
}
993996
}
994997

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+
9951009
const chatsRaw: { remoteJid: string; instanceId: string; name?: string }[] = [];
9961010
const chatsRepository = new Set(
9971011
(
@@ -1063,6 +1077,15 @@ export class BaileysStartupService extends ChannelStartupService {
10631077
continue;
10641078
}
10651079

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+
10661089
messagesRaw.push(this.prepareMessage(m));
10671090
}
10681091

@@ -1174,25 +1197,6 @@ export class BaileysStartupService extends ChannelStartupService {
11741197
}
11751198
}
11761199

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

@@ -1219,6 +1223,7 @@ export class BaileysStartupService extends ChannelStartupService {
12191223
if (settings?.groupsIgnore && received.key.remoteJid.includes('@g.us')) {
12201224
continue;
12211225
}
1226+
12221227
const existingChat = await this.prismaRepository.chat.findFirst({
12231228
where: { instanceId: this.instanceId, remoteJid: received.key.remoteJid },
12241229
select: { id: true, name: true },
@@ -4482,7 +4487,11 @@ export class BaileysStartupService extends ChannelStartupService {
44824487

44834488
const messageRaw = {
44844489
key: message.key,
4485-
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)),
44864495
status: status[message.status],
44874496
message: { ...message.message },
44884497
contextInfo: contentMsg?.contextInfo,
@@ -4850,4 +4859,112 @@ export class BaileysStartupService extends ChannelStartupService {
48504859
throw new InternalServerErrorException('Error getCatalog', error.toString());
48514860
}
48524861
}
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+
}
48534970
}

0 commit comments

Comments
 (0)