chore: update Baileys dependency to version 7.0.0-rc.3 and improve message key handling in WhatsApp service
Some checks failed
Build Docker image / Build and Deploy (push) Has been cancelled

This commit is contained in:
Davidson Gomes
2025-09-15 16:21:33 -03:00
parent bfe7030fab
commit 486645fb08
7 changed files with 2855 additions and 1434 deletions

View File

@@ -151,6 +151,19 @@ import { v4 } from 'uuid';
import { BaileysMessageProcessor } from './baileysMessage.processor';
import { useVoiceCallsBaileys } from './voiceCalls/useVoiceCallsBaileys';
export interface ExtendedMessageKey extends WAMessageKey {
senderPn?: string;
previousRemoteJid?: string | null;
}
export interface ExtendedIMessageKey extends proto.IMessageKey {
senderPn?: string;
remoteJidAlt?: string;
participantAlt?: string;
server_id?: string;
isViewOnce?: boolean;
}
const groupMetadataCache = new CacheService(new CacheEngine(configService, 'groups').getEngine());
// Adicione a função getVideoDuration no início do arquivo
@@ -986,8 +999,8 @@ export class BaileysStartupService extends ChannelStartupService {
continue;
}
if (m.key.remoteJid?.includes('@lid') && m.key.remoteJidAlt) {
m.key.remoteJid = m.key.remoteJidAlt;
if (m.key.remoteJid?.includes('@lid') && (m.key as ExtendedIMessageKey).senderPn) {
m.key.remoteJid = (m.key as ExtendedIMessageKey).senderPn;
}
if (Long.isLong(m?.messageTimestamp)) {
@@ -1052,9 +1065,9 @@ export class BaileysStartupService extends ChannelStartupService {
) => {
try {
for (const received of messages) {
if (received.key.remoteJid?.includes('@lid') && received.key.remoteJidAlt) {
(received.key as { previousRemoteJid?: string | null }).previousRemoteJid = received.key.remoteJid;
received.key.remoteJid = received.key.remoteJidAlt;
if (received.key.remoteJid?.includes('@lid') && (received.key as ExtendedMessageKey).senderPn) {
(received.key as ExtendedMessageKey).previousRemoteJid = received.key.remoteJid;
received.key.remoteJid = (received.key as ExtendedMessageKey).senderPn;
}
if (
received?.messageStubParameters?.some?.((param) =>
@@ -4308,47 +4321,30 @@ export class BaileysStartupService extends ChannelStartupService {
throw new Error('Method not available in the Baileys service');
}
private sanitizeMessageContent(messageContent: any): any {
if (!messageContent) return messageContent;
private convertLongToNumber(obj: any): any {
if (obj === null || obj === undefined) {
return obj;
}
// Deep clone and sanitize to avoid modifying original
return JSON.parse(
JSON.stringify(messageContent, (key, value) => {
// Convert Long objects to numbers
if (Long.isLong(value)) {
return value.toNumber();
if (Long.isLong(obj)) {
return obj.toNumber();
}
if (Array.isArray(obj)) {
return obj.map((item) => this.convertLongToNumber(item));
}
if (typeof obj === 'object') {
const converted: any = {};
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
converted[key] = this.convertLongToNumber(obj[key]);
}
}
return converted;
}
// Convert Uint8Array to regular arrays
if (value instanceof Uint8Array) {
return Array.from(value);
}
// Remove functions and other non-serializable objects
if (typeof value === 'function') {
return undefined;
}
// Handle objects with toJSON method
if (value && typeof value === 'object' && typeof value.toJSON === 'function') {
return value.toJSON();
}
// Handle special objects that might not serialize properly
if (value && typeof value === 'object') {
// Check if it's a plain object or has prototype issues
try {
JSON.stringify(value);
return value;
} catch (e) {
// If it can't be stringified, return a safe representation
return '[Non-serializable object]';
}
}
return value;
}),
);
return obj;
}
private prepareMessage(message: proto.IWebMessageInfo): any {
@@ -4363,11 +4359,11 @@ export class BaileysStartupService extends ChannelStartupService {
? 'Você'
: message?.participant || (message.key?.participant ? message.key.participant.split('@')[0] : null)),
status: status[message.status],
message: this.sanitizeMessageContent({ ...message.message }),
contextInfo: this.sanitizeMessageContent(contentMsg?.contextInfo),
message: this.convertLongToNumber({ ...message.message }),
contextInfo: this.convertLongToNumber(contentMsg?.contextInfo),
messageType: contentType || 'unknown',
messageTimestamp: Long.isLong(message.messageTimestamp)
? (message.messageTimestamp as Long).toNumber()
? message.messageTimestamp.toNumber()
: (message.messageTimestamp as number),
instanceId: this.instanceId,
source: getDevice(message.key.id),

View File

@@ -1,5 +1,6 @@
import { InstanceDto } from '@api/dto/instance.dto';
import { Options, Quoted, SendAudioDto, SendMediaDto, SendTextDto } from '@api/dto/sendMessage.dto';
import { ExtendedMessageKey } from '@api/integrations/channel/whatsapp/whatsapp.baileys.service';
import { ChatwootDto } from '@api/integrations/chatbot/chatwoot/dto/chatwoot.dto';
import { postgresClient } from '@api/integrations/chatbot/chatwoot/libs/postgres.client';
import { chatwootImport } from '@api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper';
@@ -1284,12 +1285,7 @@ export class ChatwootService {
});
if (message) {
const key = message.key as {
id: string;
remoteJid: string;
fromMe: boolean;
participant: string;
};
const key = message.key as ExtendedMessageKey;
await waInstance?.client.sendMessage(key.remoteJid, { delete: key });
@@ -1487,12 +1483,7 @@ export class ChatwootService {
},
});
if (lastMessage && !lastMessage.chatwootIsRead) {
const key = lastMessage.key as {
id: string;
fromMe: boolean;
remoteJid: string;
participant?: string;
};
const key = lastMessage.key as ExtendedMessageKey;
waInstance?.markMessageAsRead({
readMessages: [
@@ -1550,12 +1541,7 @@ export class ChatwootService {
chatwootMessageIds: ChatwootMessage,
instance: InstanceDto,
) {
const key = message.key as {
id: string;
fromMe: boolean;
remoteJid: string;
participant?: string;
};
const key = message.key as ExtendedMessageKey;
if (!chatwootMessageIds.messageId || !key?.id) {
return;
@@ -1623,12 +1609,7 @@ export class ChatwootService {
},
});
const key = message?.key as {
id: string;
fromMe: boolean;
remoteJid: string;
participant?: string;
};
const key = message?.key as ExtendedMessageKey;
if (message && key?.id) {
return {
@@ -2258,12 +2239,13 @@ export class ChatwootService {
body?.editedMessage?.conversation || body?.editedMessage?.extendedTextMessage?.text
}\n\n_\`${i18next.t('cw.message.edited')}.\`_`;
const message = await this.getMessageByKeyId(instance, body?.key?.id);
const key = message.key as {
id: string;
fromMe: boolean;
remoteJid: string;
participant?: string;
};
if (!message) {
this.logger.warn('Message not found for edit event');
return;
}
const key = message.key as ExtendedMessageKey;
const messageType = key?.fromMe ? 'outgoing' : 'incoming';
@@ -2541,7 +2523,7 @@ export class ChatwootService {
const savedMessages = await this.prismaRepository.message.findMany({
where: {
Instance: { name: instance.instanceName },
messageTimestamp: { gte: dayjs().subtract(6, 'hours').unix() },
messageTimestamp: { gte: Number(dayjs().subtract(6, 'hours').unix()) },
AND: ids.map((id) => ({ key: { path: ['id'], not: id } })),
},
});

View File

@@ -29,6 +29,8 @@ export class WAMonitoringService {
Object.assign(this.db, configService.get<Database>('DATABASE'));
Object.assign(this.redis, configService.get<CacheConf>('CACHE'));
(this as any).providerSession = Object.freeze(configService.get<ProviderSession>('PROVIDER'));
}
private readonly db: Partial<Database> = {};
@@ -37,7 +39,7 @@ export class WAMonitoringService {
private readonly logger = new Logger('WAMonitoringService');
public readonly waInstances: Record<string, any> = {};
private readonly providerSession = Object.freeze(this.configService.get<ProviderSession>('PROVIDER'));
private readonly providerSession: ProviderSession;
public delInstanceTime(instance: string) {
const time = this.configService.get<DelInstance>('DEL_INSTANCE');