Skip to content
Merged
59 changes: 53 additions & 6 deletions src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getCollectionsDto } from '@api/dto/business.dto';

Check failure on line 1 in src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

View workflow job for this annotation

GitHub Actions / check-lint-and-build

Run autofix to sort these imports!
import { OfferCallDto } from '@api/dto/call.dto';
import {
ArchiveChatDto,
Expand Down Expand Up @@ -436,7 +436,7 @@
qrcodeTerminal.generate(qr, { small: true }, (qrcode) =>
this.logger.log(
`\n{ instance: ${this.instance.name} pairingCode: ${this.instance.qrcode.pairingCode}, qrcodeCount: ${this.instance.qrcode.count} }\n` +
qrcode,

Check failure on line 439 in src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

View workflow job for this annotation

GitHub Actions / check-lint-and-build

Insert `··`
),
);

Expand All @@ -462,16 +462,16 @@

const statusCode = (lastDisconnect?.error as Boom)?.output?.statusCode;
const codesToNotReconnect = [DisconnectReason.loggedOut, DisconnectReason.forbidden, 402, 406];
const shouldReconnect = !codesToNotReconnect.includes(statusCode);

Check failure on line 465 in src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

View workflow job for this annotation

GitHub Actions / check-lint-and-build

Delete `······`

this.logger.info({
message: 'Connection closed, evaluating reconnection',
statusCode,

Check failure on line 469 in src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

View workflow job for this annotation

GitHub Actions / check-lint-and-build

Delete `······`
shouldReconnect,
instanceName: this.instance.name,
});

if (shouldReconnect) {

Check failure on line 474 in src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

View workflow job for this annotation

GitHub Actions / check-lint-and-build

Delete `······`
// Add 3 second delay before reconnection to prevent rapid reconnection loops
this.logger.info('Reconnecting in 3 seconds...');
setTimeout(async () => {
Expand All @@ -488,7 +488,7 @@

await this.prismaRepository.instance.update({
where: { id: this.instanceId },
data: {

Check failure on line 491 in src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

View workflow job for this annotation

GitHub Actions / check-lint-and-build

Replace `⏎··········`Skipping·reconnection·for·status·code·${statusCode}·(code·is·in·codesToNotReconnect·list)`,⏎········` with ``Skipping·reconnection·for·status·code·${statusCode}·(code·is·in·codesToNotReconnect·list)``
connectionStatus: 'close',
disconnectionAt: new Date(),
disconnectionReasonCode: statusCode,
Expand Down Expand Up @@ -1017,14 +1017,29 @@
}

const contactsMap = new Map();
const contactsMapLidJid = new Map();

for (const contact of contacts) {
let jid = null;

if (contact?.id?.search('@lid') !== -1) {
if (contact.phoneNumber) {
jid = contact.phoneNumber;
}
}

if (!jid) {
jid = contact?.id;
}

if (contact.id && (contact.notify || contact.name)) {
contactsMap.set(contact.id, { name: contact.name ?? contact.notify, jid: contact.id });
contactsMap.set(contact.id, { name: contact.name ?? contact.notify, jid });
}

contactsMapLidJid.set(contact.id, { jid });
}

const chatsRaw: { remoteJid: string; instanceId: string; name?: string }[] = [];
const chatsRaw: { remoteJid: string; remoteLid: string; instanceId: string; name?: string }[] = [];
const chatsRepository = new Set(
(await this.prismaRepository.chat.findMany({ where: { instanceId: this.instanceId } })).map(
(chat) => chat.remoteJid,
Expand All @@ -1036,13 +1051,39 @@
continue;
}

chatsRaw.push({ remoteJid: chat.id, instanceId: this.instanceId, name: chat.name });
let remoteJid = null;
let remoteLid = null;

if (chat.id.search('@lid') !== -1) {
const contact = contactsMapLidJid.get(chat.id);

remoteLid = chat.id;

if (contact && contact.jid) {
remoteJid = contact.jid;
}
}

if (!remoteLid && chat.accountLid && chat.accountLid.search('@lid') !== -1) {
remoteLid = chat.accountLid;
}

if (!remoteJid) {
remoteJid = chat.id;
}

chatsRaw.push({ remoteJid, remoteLid, instanceId: this.instanceId, name: chat.name });
}

this.sendDataWebhook(Events.CHATS_SET, chatsRaw);

if (this.configService.get<Database>('DATABASE').SAVE_DATA.HISTORIC) {
await this.prismaRepository.chat.createMany({ data: chatsRaw, skipDuplicates: true });
const chatsToCreateMany = JSON.parse(JSON.stringify(chatsRaw)).map((chat) => {
delete chat.remoteLid;
return chat;
});

await this.prismaRepository.chat.createMany({ data: chatsToCreateMany, skipDuplicates: true });
}

const messagesRaw: any[] = [];
Expand Down Expand Up @@ -1072,10 +1113,10 @@

if (Long.isLong(m?.messageTimestamp)) {
m.messageTimestamp = m.messageTimestamp?.toNumber();
}

Check failure on line 1116 in src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

View workflow job for this annotation

GitHub Actions / check-lint-and-build

Insert `··`

Check failure on line 1117 in src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

View workflow job for this annotation

GitHub Actions / check-lint-and-build

Insert `··`
if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED) {

Check failure on line 1118 in src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

View workflow job for this annotation

GitHub Actions / check-lint-and-build

Replace `··············` with `················`
if (m.messageTimestamp <= timestampLimitToImport) {

Check failure on line 1119 in src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

View workflow job for this annotation

GitHub Actions / check-lint-and-build

Insert `··`
continue;
}
}
Expand Down Expand Up @@ -1526,8 +1567,14 @@
this.logger.verbose(messageRaw);

sendTelemetry(`received.message.${messageRaw.messageType ?? 'unknown'}`);
if ((messageRaw.key as any).remoteJid?.includes('@lid') && (messageRaw.key as any).remoteJidAlt) {
(messageRaw.key as any).remoteJid = (messageRaw.key as any).remoteJidAlt;

if (messageRaw.key.remoteJid?.includes('@lid') && messageRaw.key.remoteJidAlt) {
const lid = messageRaw.key.remoteJid;

messageRaw.key.remoteJid = messageRaw.key.remoteJidAlt;
messageRaw.key.remoteJidAlt = lid;

messageRaw.key.addressingMode = 'pn';
}
console.log(messageRaw);

Expand Down
Loading