refactor: update TypeScript build process and dependencies

- Changed the build command in package.json to use TypeScript compiler (tsc) with noEmit option.
- Added @swc/core and @swc/helpers as development dependencies for improved performance.

refactor: clean up WhatsApp Baileys service

- Removed unused properties and interfaces related to message keys.
- Simplified message handling logic by removing redundant checks and conditions.
- Updated message timestamp handling for consistency.
- Improved readability and maintainability by restructuring code and removing commented-out sections.

refactor: optimize Chatwoot service

- Streamlined database queries by reusing PostgreSQL client connection.
- Enhanced conversation creation logic with better cache handling.
- Removed unnecessary methods and improved existing ones for clarity.
- Updated message sending logic to handle file streams instead of buffers.

fix: improve translation loading mechanism

- Simplified translation file loading by removing environment variable checks.
- Ensured translations are loaded from a consistent path within the project structure.
This commit is contained in:
Willian Coqueiro
2025-10-12 15:03:48 +00:00
parent c041986e26
commit 4b043cb4b8
6 changed files with 943 additions and 2104 deletions

View File

@@ -152,13 +152,7 @@ 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;
@@ -1004,10 +998,6 @@ export class BaileysStartupService extends ChannelStartupService {
continue;
}
if (m.key.remoteJid?.includes('@lid') && (m.key as ExtendedIMessageKey).senderPn) {
m.key.remoteJid = (m.key as ExtendedIMessageKey).senderPn;
}
if (Long.isLong(m?.messageTimestamp)) {
m.messageTimestamp = m.messageTimestamp?.toNumber();
}
@@ -1069,16 +1059,7 @@ export class BaileysStartupService extends ChannelStartupService {
settings: any,
) => {
try {
// Garantir que localChatwoot está carregado antes de processar mensagens
if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED && !this.localChatwoot?.enabled) {
await this.loadChatwoot();
}
for (const received of messages) {
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) =>
[
@@ -1126,9 +1107,9 @@ export class BaileysStartupService extends ChannelStartupService {
await this.sendDataWebhook(Events.MESSAGES_EDITED, editedMessage);
const oldMessage = await this.getMessage(editedMessage.key, true);
if ((oldMessage as any)?.id) {
const editedMessageTimestamp = Long.isLong(editedMessage?.timestampMs)
? Math.floor(editedMessage.timestampMs.toNumber() / 1000)
: Math.floor((editedMessage.timestampMs as number) / 1000);
const editedMessageTimestamp = Long.isLong(received?.messageTimestamp)
? Math.floor(received?.messageTimestamp.toNumber())
: Math.floor(received?.messageTimestamp as number);
await this.prismaRepository.message.update({
where: { id: (oldMessage as any).id },
@@ -1367,10 +1348,6 @@ export class BaileysStartupService extends ChannelStartupService {
}
}
if (messageRaw.key.remoteJid?.includes('@lid') && messageRaw.key.remoteJidAlt) {
messageRaw.key.remoteJid = messageRaw.key.remoteJidAlt;
}
this.logger.log(messageRaw);
this.sendDataWebhook(Events.MESSAGES_UPSERT, messageRaw);
@@ -1446,25 +1423,18 @@ export class BaileysStartupService extends ChannelStartupService {
continue;
}
if (key.remoteJid?.includes('@lid') && key.remoteJidAlt) {
key.remoteJid = key.remoteJidAlt;
}
if (update.message !== null && update.status === undefined) continue;
const updateKey = `${this.instance.id}_${key.id}_${update.status}`;
const cached = await this.baileysCache.get(updateKey);
// Não ignorar mensagens deletadas (messageStubType === 1) mesmo que estejam em cache
const isDeletedMessage = update.messageStubType === 1;
if (cached && !isDeletedMessage) {
if (cached) {
this.logger.info(`Message duplicated ignored [avoid deadlock]: ${updateKey}`);
continue;
}
if (!isDeletedMessage) {
await this.baileysCache.set(updateKey, true, this.UPDATE_CACHE_TTL_SECONDS);
}
await this.baileysCache.set(updateKey, true, 30 * 60);
if (status[update.status] === 'READ' && key.fromMe) {
if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED && this.localChatwoot?.enabled) {
@@ -1494,8 +1464,8 @@ export class BaileysStartupService extends ChannelStartupService {
keyId: key.id,
remoteJid: key?.remoteJid,
fromMe: key.fromMe,
participant: key?.remoteJid,
status: status[update.status] ?? 'DELETED',
participant: key?.participant,
status: status[update.status],
pollUpdates,
instanceId: this.instanceId,
};
@@ -1568,22 +1538,8 @@ export class BaileysStartupService extends ChannelStartupService {
this.sendDataWebhook(Events.MESSAGES_UPDATE, message);
if (this.configService.get<Database>('DATABASE').SAVE_DATA.MESSAGE_UPDATE) {
// Verificar se a mensagem ainda existe antes de criar o update
const messageExists = await this.prismaRepository.message.findFirst({
where: {
instanceId: message.instanceId,
key: {
path: ['id'],
equals: message.keyId,
},
},
});
if (messageExists) {
await this.prismaRepository.messageUpdate.create({ data: message });
}
}
if (this.configService.get<Database>('DATABASE').SAVE_DATA.MESSAGE_UPDATE)
await this.prismaRepository.messageUpdate.create({ data: message });
const existingChat = await this.prismaRepository.chat.findFirst({
where: { instanceId: this.instanceId, remoteJid: message.remoteJid },
@@ -2193,7 +2149,20 @@ export class BaileysStartupService extends ChannelStartupService {
}
}
const linkPreview = options?.linkPreview != false ? undefined : false;
let linkPreview: boolean | undefined;
let conversationText: string | undefined;
if (typeof message === 'object' && 'conversation' in message && typeof message['conversation'] === 'string') {
conversationText = message['conversation'];
if (conversationText.includes('[linkPreview=false]')) {
message['conversation'] = conversationText.replace('[linkPreview=false]', '').trim();
linkPreview = false;
}
}
if (linkPreview === undefined) {
linkPreview = options?.linkPreview != false ? undefined : false;
}
let quoted: WAMessage;
@@ -3453,18 +3422,13 @@ export class BaileysStartupService extends ChannelStartupService {
}
const numberJid = numberVerified?.jid || user.jid;
// const lid =
// typeof numberVerified?.lid === 'string'
// ? numberVerified.lid
// : numberJid.includes('@lid')
// ? numberJid.split('@')[1]
// : undefined;
return new OnWhatsAppDto(
numberJid,
!!numberVerified?.exists,
user.number,
contacts.find((c) => c.remoteJid === numberJid)?.pushName,
// lid,
undefined,
);
}),
);
@@ -3616,7 +3580,7 @@ export class BaileysStartupService extends ChannelStartupService {
keyId: messageId,
remoteJid: response.key.remoteJid,
fromMe: response.key.fromMe,
participant: response.key?.remoteJid,
participant: response.key?.participant,
status: 'DELETED',
instanceId: this.instanceId,
};
@@ -4051,7 +4015,7 @@ export class BaileysStartupService extends ChannelStartupService {
keyId: messageId,
remoteJid: messageSent.key.remoteJid,
fromMe: messageSent.key.fromMe,
participant: messageSent.key?.remoteJid,
participant: messageSent.key?.participant,
status: 'EDITED',
instanceId: this.instanceId,
};
@@ -4647,9 +4611,7 @@ export class BaileysStartupService extends ChannelStartupService {
return response;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public async baileysAssertSessions(jids: string[], _force?: boolean) {
// Note: _force parameter kept for API compatibility but not used in Baileys 7.0.0-rc.5+
public async baileysAssertSessions(jids: string[]) {
const response = await this.client.assertSessions(jids);
return response;
@@ -4854,7 +4816,7 @@ export class BaileysStartupService extends ChannelStartupService {
{
OR: [
keyFilters?.remoteJid ? { key: { path: ['remoteJid'], equals: keyFilters?.remoteJid } } : {},
keyFilters?.senderPn ? { key: { path: ['senderPn'], equals: keyFilters?.senderPn } } : {},
keyFilters?.remoteJidAlt ? { key: { path: ['remoteJidAlt'], equals: keyFilters?.remoteJidAlt } } : {},
],
},
],
@@ -4884,7 +4846,7 @@ export class BaileysStartupService extends ChannelStartupService {
{
OR: [
keyFilters?.remoteJid ? { key: { path: ['remoteJid'], equals: keyFilters?.remoteJid } } : {},
keyFilters?.senderPn ? { key: { path: ['senderPn'], equals: keyFilters?.senderPn } } : {},
keyFilters?.remoteJidAlt ? { key: { path: ['remoteJidAlt'], equals: keyFilters?.remoteJidAlt } } : {},
],
},
],