From d4b1af0b136e986ffed28fc4508574996a20164a Mon Sep 17 00:00:00 2001 From: Jonathan Mantovani Date: Fri, 1 Nov 2024 14:59:22 -0300 Subject: [PATCH 01/97] fix: getIdMedia and audioWhatsapp/ bug fix send media for meta --- src/api/abstract/abstract.router.ts | 4 ++ src/api/controllers/instance.controller.ts | 3 +- .../channel/meta/whatsapp.business.service.ts | 47 +++++++++---------- src/config/env.config.ts | 2 + 4 files changed, 31 insertions(+), 25 deletions(-) diff --git a/src/api/abstract/abstract.router.ts b/src/api/abstract/abstract.router.ts index e8449a8c..afa4b24e 100644 --- a/src/api/abstract/abstract.router.ts +++ b/src/api/abstract/abstract.router.ts @@ -41,6 +41,10 @@ export abstract class RouterBroker { Object.assign(instance, body); } + if (request.originalUrl.includes('/webhook/meta')) { + Object.assign(instance, body); + } + Object.assign(ref, body); const v = schema ? validate(ref, schema) : { valid: true, errors: [] }; diff --git a/src/api/controllers/instance.controller.ts b/src/api/controllers/instance.controller.ts index 1de011a9..c8665e3d 100644 --- a/src/api/controllers/instance.controller.ts +++ b/src/api/controllers/instance.controller.ts @@ -127,7 +127,8 @@ export class InstanceController { throw new BadRequestException('number is required'); } const urlServer = this.configService.get('SERVER').URL; - webhookWaBusiness = `${urlServer}/webhook/meta`; + const webHookTest = this.configService.get('WA_BUSINESS').WEBHOOK_TEST; + webhookWaBusiness = `${webHookTest ? webHookTest : urlServer}/webhook/meta`; accessTokenWaBusiness = this.configService.get('WA_BUSINESS').TOKEN_WEBHOOK; } diff --git a/src/api/integrations/channel/meta/whatsapp.business.service.ts b/src/api/integrations/channel/meta/whatsapp.business.service.ts index e6979a69..b517835d 100644 --- a/src/api/integrations/channel/meta/whatsapp.business.service.ts +++ b/src/api/integrations/channel/meta/whatsapp.business.service.ts @@ -811,26 +811,28 @@ export class BusinessStartupService extends ChannelStartupService { private async getIdMedia(mediaMessage: any) { const formData = new FormData(); - - const fileStream = createReadStream(mediaMessage.media); - - formData.append('file', fileStream, { filename: 'media', contentType: mediaMessage.mimetype }); - formData.append('typeFile', mediaMessage.mimetype); + const buffer = Buffer.from(mediaMessage.media, 'base64'); formData.append('messaging_product', 'whatsapp'); + formData.append('type', mediaMessage.mimetype); + formData.append('file', buffer, { filename: mediaMessage.fileName, contentType: mediaMessage.mimetype }); - // const fileBuffer = await fs.readFile(mediaMessage.media); + const headers = { "Content-Type": "multipart/form-data", Authorization: `Bearer ${this.token}` }; + let urlServer = this.configService.get('WA_BUSINESS').URL; + const version = this.configService.get('WA_BUSINESS').VERSION; - // const fileBlob = new Blob([fileBuffer], { type: mediaMessage.mimetype }); - // formData.append('file', fileBlob); - // formData.append('typeFile', mediaMessage.mimetype); - // formData.append('messaging_product', 'whatsapp'); - - const headers = { Authorization: `Bearer ${this.token}` }; - const res = await axios.post( - process.env.API_URL + '/' + process.env.VERSION + '/' + this.number + '/media', - formData, - { headers }, - ); + let res: any; + try { + res = await axios.post( + urlServer + '/' + version + '/' + this.number + '/media', + formData, + { headers }, + ); + + } catch (error) { + if (error.response) { + this.logger.info(JSON.stringify(error.response.data)); + } + } return res.data.id; } @@ -866,11 +868,11 @@ export class BusinessStartupService extends ChannelStartupService { prepareMedia.type = 'link'; } else { mimetype = mime.getType(mediaMessage.fileName); + prepareMedia.mimetype = mimetype; const id = await this.getIdMedia(prepareMedia); prepareMedia.id = id; prepareMedia.type = 'id'; } - prepareMedia.mimetype = mimetype; return prepareMedia; @@ -915,6 +917,7 @@ export class BusinessStartupService extends ChannelStartupService { prepareMedia.type = 'link'; } else { mimetype = mime.getType(prepareMedia.fileName); + prepareMedia.mimetype = mimetype; const id = await this.getIdMedia(prepareMedia); prepareMedia.id = id; prepareMedia.type = 'id'; @@ -928,12 +931,8 @@ export class BusinessStartupService extends ChannelStartupService { public async audioWhatsapp(data: SendAudioDto, file?: any) { const mediaData: SendAudioDto = { ...data }; - if (file?.buffer) { - mediaData.audio = file.buffer.toString('base64'); - } else { - console.error('File or buffer is undefined.'); - throw new Error('File or buffer is undefined.'); - } + const audioBuffer = Buffer.from(data.audio, 'base64'); + mediaData.audio = audioBuffer.toString('base64'); const message = await this.processAudio(mediaData.audio, data.number); diff --git a/src/config/env.config.ts b/src/config/env.config.ts index 6ef0453e..3229687d 100644 --- a/src/config/env.config.ts +++ b/src/config/env.config.ts @@ -113,6 +113,7 @@ export type WaBusiness = { URL: string; VERSION: string; LANGUAGE: string; + WEBHOOK_TEST: string; }; export type EventsWebhook = { @@ -321,6 +322,7 @@ export class ConfigService { URL: process.env.WA_BUSINESS_URL || 'https://graph.facebook.com', VERSION: process.env.WA_BUSINESS_VERSION || 'v18.0', LANGUAGE: process.env.WA_BUSINESS_LANGUAGE || 'en', + WEBHOOK_TEST: process.env.WA_BUSINESS_WEBHOOK_TEST || '' }, LOG: { LEVEL: From 6605c93c1f7f9114c8f5ff0fbc1eee398ace5300 Mon Sep 17 00:00:00 2001 From: Jonathan Mantovani Date: Fri, 1 Nov 2024 15:56:01 -0300 Subject: [PATCH 02/97] fix: status read in whatsapp business --- src/api/integrations/channel/meta/whatsapp.business.service.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/api/integrations/channel/meta/whatsapp.business.service.ts b/src/api/integrations/channel/meta/whatsapp.business.service.ts index b517835d..e3b00c37 100644 --- a/src/api/integrations/channel/meta/whatsapp.business.service.ts +++ b/src/api/integrations/channel/meta/whatsapp.business.service.ts @@ -450,6 +450,8 @@ export class BusinessStartupService extends ChannelStartupService { return; } + if (item.status === 'read' && key.fromMe) return; + if (item.message === null && item.status === undefined) { this.sendDataWebhook(Events.MESSAGES_DELETE, key); From d22dacca5880a4752c9246ac64e70b6a9e3b356d Mon Sep 17 00:00:00 2001 From: Jonathan Mantovani Date: Fri, 1 Nov 2024 16:05:59 -0300 Subject: [PATCH 03/97] fix: receive sticker in connection for meta --- src/api/integrations/channel/meta/whatsapp.business.service.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/api/integrations/channel/meta/whatsapp.business.service.ts b/src/api/integrations/channel/meta/whatsapp.business.service.ts index e3b00c37..e7f92540 100644 --- a/src/api/integrations/channel/meta/whatsapp.business.service.ts +++ b/src/api/integrations/channel/meta/whatsapp.business.service.ts @@ -294,7 +294,8 @@ export class BusinessStartupService extends ChannelStartupService { received?.messages[0].document || received?.messages[0].image || received?.messages[0].audio || - received?.messages[0].video + received?.messages[0].video || + received?.messages[0].sticker ) { messageRaw = { key, From 8a2199fc129c352c2816061bdad25d066b004044 Mon Sep 17 00:00:00 2001 From: Jonathan Mantovani Date: Fri, 1 Nov 2024 19:09:14 -0300 Subject: [PATCH 04/97] fix sending media in groups where the group number is greater than 23 digits --- src/api/services/channel.service.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/api/services/channel.service.ts b/src/api/services/channel.service.ts index ba9c9274..97602a2b 100644 --- a/src/api/services/channel.service.ts +++ b/src/api/services/channel.service.ts @@ -308,7 +308,7 @@ export class ChannelStartupService { .split(':')[0] .split('@')[0]; - if (number.includes('-') && number.length >= 24) { + if (number.includes('-') && number.length >= 23) { number = number.replace(/[^\d-]/g, ''); return `${number}@g.us`; } From 807914bcfa8b19bc8e41c0e127de9cfa39610654 Mon Sep 17 00:00:00 2001 From: Jonathan Mantovani Date: Fri, 1 Nov 2024 19:30:22 -0300 Subject: [PATCH 05/97] fix messages loss --- .../integrations/channel/whatsapp/whatsapp.baileys.service.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index 0986067c..ed4f157a 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -940,7 +940,7 @@ export class BaileysStartupService extends ChannelStartupService { update: contactRaw, }); - return; + continue; } this.sendDataWebhook(Events.CONTACTS_UPSERT, contactRaw); From fdd25e314c2c5a4b35b06434dd94dba5a01f13f6 Mon Sep 17 00:00:00 2001 From: Jonathan Mantovani Date: Fri, 1 Nov 2024 20:25:17 -0300 Subject: [PATCH 06/97] fix encrypted incoming messages --- .../channel/whatsapp/whatsapp.baileys.service.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index ed4f157a..a786a3a7 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -846,6 +846,18 @@ export class BaileysStartupService extends ChannelStartupService { message: received, retry: 0, }); + + const messageRaw = this.prepareMessage(received); + this.logger.verbose('Sending data ciphertext to webhook in event MESSAGES_UPSERT'); + this.sendDataWebhook(Events.MESSAGES_UPSERT, messageRaw); + + this.logger.verbose('Inserting ciphertext in database'); + if (this.configService.get('DATABASE').SAVE_DATA.NEW_MESSAGE) { + await this.prismaRepository.message.create({ + data: messageRaw, + }); + } + continue; } From 614e9f7a885a0e5b8a354e9589a2291bc265a420 Mon Sep 17 00:00:00 2001 From: Jonathan Mantovani Date: Fri, 1 Nov 2024 20:41:57 -0300 Subject: [PATCH 07/97] fix message edited by whatsApp web --- .../channel/whatsapp/whatsapp.baileys.service.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index a786a3a7..4c30e116 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -870,11 +870,15 @@ export class BaileysStartupService extends ChannelStartupService { if ( (type !== 'notify' && type !== 'append') || - received.message?.protocolMessage || received.message?.pollUpdateMessage || !received?.message ) { return; + } else if(received.message?.protocolMessage){ + if(!received.message?.protocolMessage?.editedMessage){ + this.logger.verbose('message rejected'); + return; + } } if (Long.isLong(received.messageTimestamp)) { From d425e22fa7e4d1430f1b01bcd84e8d2f1af7cebc Mon Sep 17 00:00:00 2001 From: Jonathan Mantovani Date: Mon, 4 Nov 2024 10:51:04 -0300 Subject: [PATCH 08/97] bug fix: message.map is not a function.. Only iterate over message.contacts --- src/api/integrations/channel/meta/whatsapp.business.service.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/api/integrations/channel/meta/whatsapp.business.service.ts b/src/api/integrations/channel/meta/whatsapp.business.service.ts index e7f92540..5ef82df8 100644 --- a/src/api/integrations/channel/meta/whatsapp.business.service.ts +++ b/src/api/integrations/channel/meta/whatsapp.business.service.ts @@ -233,9 +233,10 @@ export class BusinessStartupService extends ChannelStartupService { vcard: vcard(message.contacts[0]), }; } else { + const contactsArray = Array.isArray(message.contacts) ? message.contacts : []; content.contactsArrayMessage = { displayName: `${message.length} contacts`, - contacts: message.map((contact) => { + contacts: contactsArray.map((contact) => { return { displayName: contact.name.formatted_name, vcard: vcard(contact), From b5b2028fdc023c7727e57f7169b0d45daef3581a Mon Sep 17 00:00:00 2001 From: Jonathan Mantovani Date: Mon, 4 Nov 2024 14:54:06 -0300 Subject: [PATCH 09/97] fix: Enter WhatsApp version individually --- prisma/postgresql-schema.prisma | 1 + .../channel/whatsapp/whatsapp.baileys.service.ts | 14 +++++++++++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/prisma/postgresql-schema.prisma b/prisma/postgresql-schema.prisma index 857c4426..c35cac5d 100644 --- a/prisma/postgresql-schema.prisma +++ b/prisma/postgresql-schema.prisma @@ -72,6 +72,7 @@ model Instance { businessId String? @db.VarChar(100) token String? @db.VarChar(255) clientName String? @db.VarChar(100) + webVersion String? @db.VarChar(50) disconnectionReasonCode Int? @db.Integer disconnectionObject Json? @db.JsonB disconnectionAt DateTime? @db.Timestamp diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index 4c30e116..991ad65b 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -442,6 +442,18 @@ export class BaileysStartupService extends ChannelStartupService { log = `Baileys version: ${version}`; } + const integrationData = await this.prismaRepository.instance.findUnique({ + where: { id: this.instance.id }, + select: { + webVersion: true, + }, + }); + const webVersion = integrationData.webVersion + ? integrationData.webVersion.split('.').map(Number) + : version + + this.logger.info(`WhatsApp webVersion: ${webVersion}`); + this.logger.info(log); this.logger.info(`Group Ignore: ${this.localSettings.groupsIgnore}`); @@ -487,7 +499,7 @@ export class BaileysStartupService extends ChannelStartupService { const socketConfig: UserFacingSocketConfig = { ...options, - version, + version: webVersion, logger: P({ level: this.logBaileys }), printQRInTerminal: false, auth: { From 8f617707a77c00845cca7ef8b60d81b18faec456 Mon Sep 17 00:00:00 2001 From: Jonathan Mantovani Date: Tue, 5 Nov 2024 10:09:45 -0300 Subject: [PATCH 10/97] fix: removed create in database for messages cache --- .../whatsapp/whatsapp.baileys.service.ts | 27 +++++++++++-------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index 991ad65b..c79d960b 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -520,10 +520,10 @@ export class BaileysStartupService extends ChannelStartupService { emitOwnEvents: false, shouldIgnoreJid: (jid) => { const isGroupJid = this.localSettings.groupsIgnore && isJidGroup(jid); - const isBroadcast = !this.localSettings.readStatus && isJidBroadcast(jid); + //const isBroadcast = !this.localSettings.readStatus && isJidBroadcast(jid); const isNewsletter = isJidNewsletter(jid); - return isGroupJid || isBroadcast || isNewsletter; + return isGroupJid || isNewsletter; }, syncFullHistory: this.localSettings.syncFullHistory, cachedGroupMetadata: this.getGroupMetadataCache, @@ -828,6 +828,8 @@ export class BaileysStartupService extends ChannelStartupService { ) => { try { for (const received of messages) { + + console.log("MESSAGES DO UPSERT:: " + JSON.stringify(received)) // if (received.message?.conversation || received.message?.extendedTextMessage?.text) { // const text = received.message?.conversation || received.message?.extendedTextMessage?.text; // if (text == 'requestPlaceholder' && !requestId) { @@ -859,17 +861,20 @@ export class BaileysStartupService extends ChannelStartupService { retry: 0, }); - const messageRaw = this.prepareMessage(received); + const messageRaw = { + key: received.key, + pushName: received.pushName, + messageType: 'ciphertext', + message: {}, + messageTimestamp: received.messageTimestamp as number, + owner: this.instance.name, + instanceId: this.instanceId, + source: getDevice(received.key.id), + }; + this.logger.verbose('Sending data ciphertext to webhook in event MESSAGES_UPSERT'); this.sendDataWebhook(Events.MESSAGES_UPSERT, messageRaw); - this.logger.verbose('Inserting ciphertext in database'); - if (this.configService.get('DATABASE').SAVE_DATA.NEW_MESSAGE) { - await this.prismaRepository.message.create({ - data: messageRaw, - }); - } - continue; } @@ -3098,7 +3103,7 @@ export class BaileysStartupService extends ChannelStartupService { messageType: contentType || 'unknown', messageTimestamp: message.messageTimestamp as number, instanceId: this.instanceId, - source: getDevice(message.key.id), + source: getDevice(message.key.id), }; if (messageRaw.message.extendedTextMessage) { From cbe095a48cf4b8664aa5514f598dea2d455f3346 Mon Sep 17 00:00:00 2001 From: Jonathan Mantovani Date: Tue, 5 Nov 2024 10:39:10 -0300 Subject: [PATCH 11/97] fix: private groups --- .../integrations/channel/whatsapp/whatsapp.baileys.service.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index c79d960b..796f9273 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -2525,7 +2525,7 @@ export class BaileysStartupService extends ChannelStartupService { await this.client.updateStatusPrivacy(settings.status); await this.client.updateOnlinePrivacy(settings.online); await this.client.updateLastSeenPrivacy(settings.last); - await this.client.updateGroupsAddPrivacy(settings.groupadd); + await this.client.updateGroupsAddPrivacy(settings.groupadd === 'none' ? 'all' : settings.groupadd); this.reloadConnection(); From a9f1b5ac02c275e5183acd82f42818287374cde4 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Tue, 5 Nov 2024 14:08:40 -0300 Subject: [PATCH 12/97] Migration webVersion --- .../20241105170512_web_version/migration.sql | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 prisma/postgresql-migrations/20241105170512_web_version/migration.sql diff --git a/prisma/postgresql-migrations/20241105170512_web_version/migration.sql b/prisma/postgresql-migrations/20241105170512_web_version/migration.sql new file mode 100644 index 00000000..97fb5cb4 --- /dev/null +++ b/prisma/postgresql-migrations/20241105170512_web_version/migration.sql @@ -0,0 +1,2 @@ +-- AlterTable +ALTER TABLE "Instance" ADD COLUMN "webVersion" VARCHAR(50); From e153b75ed184c586166474eec6570d2c67f3560a Mon Sep 17 00:00:00 2001 From: Jonathan Mantovani Date: Tue, 5 Nov 2024 16:32:24 -0300 Subject: [PATCH 13/97] removed console.log --- .../integrations/channel/whatsapp/whatsapp.baileys.service.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index 796f9273..add64c20 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -829,7 +829,6 @@ export class BaileysStartupService extends ChannelStartupService { try { for (const received of messages) { - console.log("MESSAGES DO UPSERT:: " + JSON.stringify(received)) // if (received.message?.conversation || received.message?.extendedTextMessage?.text) { // const text = received.message?.conversation || received.message?.extendedTextMessage?.text; // if (text == 'requestPlaceholder' && !requestId) { From 7297e278a1937e71e512f93b05c4d287df64c0ab Mon Sep 17 00:00:00 2001 From: Jonathan Mantovani Date: Wed, 6 Nov 2024 10:59:47 -0300 Subject: [PATCH 14/97] fix: blocked for status broadcast --- .../channel/whatsapp/whatsapp.baileys.service.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index add64c20..8108e574 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -88,9 +88,9 @@ import makeWASocket, { getContentType, getDevice, GroupMetadata, - isJidBroadcast, isJidGroup, isJidNewsletter, + isJidStatusBroadcast, isJidUser, makeCacheableSignalKeyStore, MessageUpsertType, @@ -520,10 +520,10 @@ export class BaileysStartupService extends ChannelStartupService { emitOwnEvents: false, shouldIgnoreJid: (jid) => { const isGroupJid = this.localSettings.groupsIgnore && isJidGroup(jid); - //const isBroadcast = !this.localSettings.readStatus && isJidBroadcast(jid); + const isBroadcast = !this.localSettings.readStatus && isJidStatusBroadcast(jid); const isNewsletter = isJidNewsletter(jid); - return isGroupJid || isNewsletter; + return isGroupJid || isBroadcast || isNewsletter; }, syncFullHistory: this.localSettings.syncFullHistory, cachedGroupMetadata: this.getGroupMetadataCache, From 98064ccaebf4aa34ef46f4d53dfd7a047717f567 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Mon, 11 Nov 2024 18:10:52 -0300 Subject: [PATCH 15/97] =?UTF-8?q?Novo=20tratamento=20para=20m=C3=ADdias=20?= =?UTF-8?q?no=20webhook?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../whatsapp/whatsapp.baileys.service.ts | 47 ++++++++++++++++--- 1 file changed, 40 insertions(+), 7 deletions(-) diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index 8108e574..bd4cd591 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -907,13 +907,7 @@ export class BaileysStartupService extends ChannelStartupService { const messageRaw = this.prepareMessage(received); - const isMedia = - received?.message?.imageMessage || - received?.message?.videoMessage || - received?.message?.stickerMessage || - received?.message?.documentMessage || - received?.message?.documentWithCaptionMessage || - received?.message?.audioMessage; + const isMedia = this.isMedia(received.message); if (this.localSettings.readMessages && received.key.id !== 'status@broadcast') { await this.client.readMessages([received.key]); @@ -2504,6 +2498,45 @@ export class BaileysStartupService extends ChannelStartupService { } } + public isMedia = (message: proto.IMessage): boolean => { + type MediaTypes = 'audioMessage' | 'imageMessage' | 'videoMessage' | 'documentMessage' | 'stickerMessage'; + const mediaTypes: MediaTypes[] = [ + 'audioMessage', + 'imageMessage', + 'videoMessage', + 'documentMessage', + 'stickerMessage', + ]; + + for (const type of mediaTypes) { + if (message[type]) { + return true; + } + } + + const nestedPaths = [ + message.ephemeralMessage?.message, + message.ephemeralMessage?.message?.viewOnceMessage?.message, + message.ephemeralMessage?.message?.viewOnceMessageV2?.message, + message.viewOnceMessage?.message, + message.viewOnceMessageV2?.message, + message.extendedTextMessage?.contextInfo?.quotedMessage, + message.documentWithCaptionMessage?.message, + ]; + + for (const nested of nestedPaths) { + if (nested) { + for (const type of mediaTypes) { + if (nested[type]) { + return true; + } + } + } + } + + return false; + } + public async fetchPrivacySettings() { const privacy = await this.client.fetchPrivacySettings(); From 0e5572ff6455078ca73104ea4340fe170939ac29 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Wed, 13 Nov 2024 19:02:33 -0300 Subject: [PATCH 16/97] Corrige recebimento de mensagens citadas --- .../channel/whatsapp/whatsapp.baileys.service.ts | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index bd4cd591..d79dfc83 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -886,15 +886,11 @@ export class BaileysStartupService extends ChannelStartupService { if ( (type !== 'notify' && type !== 'append') || + received.message?.protocolMessage || received.message?.pollUpdateMessage || !received?.message ) { return; - } else if(received.message?.protocolMessage){ - if(!received.message?.protocolMessage?.editedMessage){ - this.logger.verbose('message rejected'); - return; - } } if (Long.isLong(received.messageTimestamp)) { @@ -2520,7 +2516,6 @@ export class BaileysStartupService extends ChannelStartupService { message.ephemeralMessage?.message?.viewOnceMessageV2?.message, message.viewOnceMessage?.message, message.viewOnceMessageV2?.message, - message.extendedTextMessage?.contextInfo?.quotedMessage, message.documentWithCaptionMessage?.message, ]; From 3d50534783d7074ce0ca189348fce633cd19958a Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Thu, 14 Nov 2024 11:38:21 -0300 Subject: [PATCH 17/97] Corrige resposta de status --- .../channel/whatsapp/whatsapp.baileys.service.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index d79dfc83..e44ce2b5 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -901,6 +901,20 @@ export class BaileysStartupService extends ChannelStartupService { return; } + // Resposta de texto em algum status + if (received.message?.extendedTextMessage?.contextInfo?.remoteJid === 'status@broadcast' && + received.message?.extendedTextMessage?.contextInfo?.quotedMessage + ) { + const caption = received.message.extendedTextMessage.text; + received.message = received.message.extendedTextMessage.contextInfo.quotedMessage; + if (received.message.imageMessage) { + received.message.imageMessage.caption = caption; + } + if (received.message.videoMessage) { + received.message.videoMessage.caption = caption; + } + } + const messageRaw = this.prepareMessage(received); const isMedia = this.isMedia(received.message); From bc2c96f23bb1a099a89f8851d6244d80486b39c7 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Fri, 29 Nov 2024 13:18:24 -0300 Subject: [PATCH 18/97] =?UTF-8?q?Altera=20vers=C3=A3o=20da=20baileys?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index e1475bec..77407902 100644 --- a/package.json +++ b/package.json @@ -53,7 +53,7 @@ "@sentry/node": "^8.28.0", "amqplib": "^0.10.3", "axios": "^1.6.5", - "baileys": "github:renatoiub/Baileys", + "baileys": "github:EvolutionAPI/Baileys", "class-validator": "^0.14.1", "compression": "^1.7.4", "cors": "^2.8.5", From dc300028d253f39f9bbacd8c3286c4b95d109a75 Mon Sep 17 00:00:00 2001 From: Jonathan Mantovani Date: Wed, 4 Dec 2024 15:03:12 -0300 Subject: [PATCH 19/97] fix: send audios with quoted messages --- src/api/controllers/sendMessage.controller.ts | 8 ++++++++ .../channel/whatsapp/whatsapp.baileys.service.ts | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/api/controllers/sendMessage.controller.ts b/src/api/controllers/sendMessage.controller.ts index ab110878..757c195f 100644 --- a/src/api/controllers/sendMessage.controller.ts +++ b/src/api/controllers/sendMessage.controller.ts @@ -47,6 +47,14 @@ export class SendMessageController { } public async sendWhatsAppAudio({ instanceName }: InstanceDto, data: SendAudioDto, file?: any) { + if (typeof data.quoted === 'string') { + try { + data.quoted = JSON.parse(data.quoted); + } catch (error) { + console.error('Failed to parse quoted field:', error); + throw new BadRequestException('Invalid quoted format'); + } + } if (file?.buffer || isURL(data.audio) || isBase64(data.audio)) { return await this.waMonitor.waInstances[instanceName].audioWhatsapp(data, file); } else { diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index e44ce2b5..671a4bbe 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -2085,7 +2085,7 @@ export class BaileysStartupService extends ChannelStartupService { ptt: true, mimetype: 'audio/ogg; codecs=opus', }, - { presence: 'recording', delay: data?.delay }, + { presence: 'recording', delay: data?.delay, quoted: data?.quoted }, ); } From d41cedf752fadc467fc295b2bfc3ecdf78dbacbf Mon Sep 17 00:00:00 2001 From: Lucas Mesquita Date: Sat, 14 Dec 2024 15:28:46 -0300 Subject: [PATCH 20/97] Fixa versao 3.20 do node js alpine no dockerfile --- Dockerfile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Dockerfile b/Dockerfile index 760265e9..b28a9c74 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM node:20-alpine AS builder +FROM node:20-alpine3.20 AS builder RUN apk add git wget curl bash @@ -21,7 +21,7 @@ RUN chmod +x ./Docker/scripts/* && dos2unix ./Docker/scripts/* && \ ./Docker/scripts/generate_database.sh && \ npm run build -FROM node:20-alpine AS final +FROM node:20-alpine3.20 AS final RUN apk add git wget curl bash From 114f87938d30885e4b667c334365323826be481c Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Tue, 17 Dec 2024 16:58:22 -0300 Subject: [PATCH 21/97] Inclui groupInfo no webhook --- .../whatsapp/whatsapp.baileys.service.ts | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index 671a4bbe..beebf2c9 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -852,6 +852,16 @@ export class BaileysStartupService extends ChannelStartupService { } } + let groupInfo; + const { remoteJid } = received.key; + if (isJidGroup(remoteJid)) { + const groupMetaData = await this.getGroupMetadataCache(remoteJid); + groupInfo = { + id: groupMetaData.id, + subject: groupMetaData.subject + } + } + if (received.messageStubParameters && received.messageStubParameters[0] === 'Message absent from node') { this.logger.info(`Recovering message lost messageId: ${received.key.id}`); @@ -869,6 +879,7 @@ export class BaileysStartupService extends ChannelStartupService { owner: this.instance.name, instanceId: this.instanceId, source: getDevice(received.key.id), + groupInfo }; this.logger.verbose('Sending data ciphertext to webhook in event MESSAGES_UPSERT'); @@ -947,6 +958,7 @@ export class BaileysStartupService extends ChannelStartupService { messageRaw.message.base64 = buffer ? buffer.toString('base64') : undefined; } + messageRaw.groupInfo = groupInfo; this.logger.log(messageRaw); this.sendDataWebhook(Events.MESSAGES_UPSERT, messageRaw); @@ -1675,6 +1687,17 @@ export class BaileysStartupService extends ChannelStartupService { messageRaw.message.base64 = buffer ? buffer.toString('base64') : undefined; } + let groupInfo; + const { remoteJid } = messageSent.key; + if (isJidGroup(remoteJid)) { + const groupMetaData = await this.getGroupMetadataCache(remoteJid); + groupInfo = { + id: groupMetaData.id, + subject: groupMetaData.subject + } + } + + messageRaw.groupInfo = groupInfo; this.logger.log(messageRaw); this.sendDataWebhook(Events.SEND_MESSAGE, messageRaw); From ec6612a936cc46f7588bd8304039424986525570 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Thu, 26 Dec 2024 16:43:34 -0300 Subject: [PATCH 22/97] =?UTF-8?q?Envio=20de=20m=C3=ADdias=20com=20mensagen?= =?UTF-8?q?s=20citadas?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/api/controllers/sendMessage.controller.ts | 8 -------- .../channel/whatsapp/whatsapp.baileys.service.ts | 15 +++++++++++++++ 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/src/api/controllers/sendMessage.controller.ts b/src/api/controllers/sendMessage.controller.ts index 757c195f..ab110878 100644 --- a/src/api/controllers/sendMessage.controller.ts +++ b/src/api/controllers/sendMessage.controller.ts @@ -47,14 +47,6 @@ export class SendMessageController { } public async sendWhatsAppAudio({ instanceName }: InstanceDto, data: SendAudioDto, file?: any) { - if (typeof data.quoted === 'string') { - try { - data.quoted = JSON.parse(data.quoted); - } catch (error) { - console.error('Failed to parse quoted field:', error); - throw new BadRequestException('Invalid quoted format'); - } - } if (file?.buffer || isURL(data.audio) || isBase64(data.audio)) { return await this.waMonitor.waInstances[instanceName].audioWhatsapp(data, file); } else { diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index beebf2c9..b144250d 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -33,6 +33,7 @@ import { ContactMessage, MediaMessage, Options, + Quoted, SendAudioDto, SendContactDto, SendLocationDto, @@ -2069,6 +2070,7 @@ export class BaileysStartupService extends ChannelStartupService { public async mediaMessage(data: SendMediaDto, file?: any) { const mediaData: SendMediaDto = { ...data }; + data.quoted = this.parseQuoted(data.quoted); if (file) mediaData.media = file.buffer.toString('base64'); @@ -2089,6 +2091,7 @@ export class BaileysStartupService extends ChannelStartupService { public async audioWhatsapp(data: SendAudioDto, file?: any) { const mediaData: SendAudioDto = { ...data }; + data.quoted = this.parseQuoted(data.quoted); if (file?.buffer) { mediaData.audio = file.buffer.toString('base64'); @@ -3154,6 +3157,18 @@ export class BaileysStartupService extends ChannelStartupService { throw new Error('Method not available in the Baileys service'); } + private parseQuoted = (quoted: Quoted) => { + if (typeof quoted === 'string') { + try { + return JSON.parse(quoted); + } catch (error) { + console.error('Failed to parse quoted field:', error); + throw new BadRequestException('Invalid quoted format'); + } + } + return quoted; + } + private prepareMessage(message: proto.IWebMessageInfo): any { const contentType = getContentType(message.message); const contentMsg = message?.message[contentType] as any; From 01492cb58cfea6bab23c0908d54f56207de8ae86 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Wed, 22 Jan 2025 14:59:50 -0300 Subject: [PATCH 23/97] =?UTF-8?q?Remove=20inser=C3=A7=C3=A3o=20de=20contac?= =?UTF-8?q?ts,=20chats=20e=20messages=20no=20evento=20messaging-history.se?= =?UTF-8?q?t?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../whatsapp/whatsapp.baileys.service.ts | 47 ------------------- 1 file changed, 47 deletions(-) diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index b144250d..0490b46e 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -745,36 +745,6 @@ export class BaileysStartupService extends ChannelStartupService { `recv ${chats.length} chats, ${contacts.length} contacts, ${messages.length} msgs (is latest: ${isLatest}, progress: ${progress}%), type: ${syncType}`, ); - const chatsRaw: { remoteJid: string; instanceId: string; name?: string }[] = []; - const chatsRepository = new Set( - ( - await this.prismaRepository.chat.findMany({ - where: { instanceId: this.instanceId }, - }) - ).map((chat) => chat.remoteJid), - ); - - for (const chat of chats) { - if (chatsRepository?.has(chat.id)) { - continue; - } - - chatsRaw.push({ - remoteJid: chat.id, - instanceId: this.instanceId, - name: chat.name, - }); - } - - this.sendDataWebhook(Events.CHATS_SET, chatsRaw); - - if (this.configService.get('DATABASE').SAVE_DATA.HISTORIC) { - await this.prismaRepository.chat.createMany({ - data: chatsRaw, - skipDuplicates: true, - }); - } - const messagesRaw: any[] = []; for (const m of messages) { @@ -788,25 +758,8 @@ export class BaileysStartupService extends ChannelStartupService { messagesRaw.push(this.prepareMessage(m)); } - this.sendDataWebhook(Events.MESSAGES_SET, [...messagesRaw]); - if (this.configService.get('DATABASE').SAVE_DATA.HISTORIC) { - await this.prismaRepository.message.createMany({ - data: messagesRaw, - skipDuplicates: true, - }); - } - - await this.contactHandle['contacts.upsert']( - contacts - .filter((c) => !!c.notify || !!c.name) - .map((c) => ({ - id: c.id, - name: c.name ?? c.notify, - })), - ); - contacts = undefined; messages = undefined; chats = undefined; From a85e3abc1f807d85835e67d1ec9c79b5b2b9ac42 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Wed, 22 Jan 2025 15:00:17 -0300 Subject: [PATCH 24/97] Remove telemetry --- src/api/routes/index.router.ts | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/api/routes/index.router.ts b/src/api/routes/index.router.ts index dbc28a4f..1e7160e8 100644 --- a/src/api/routes/index.router.ts +++ b/src/api/routes/index.router.ts @@ -1,6 +1,5 @@ import { authGuard } from '@api/guards/auth.guard'; import { instanceExistsGuard, instanceLoggedGuard } from '@api/guards/instance.guard'; -import Telemetry from '@api/guards/telemetry.guard'; import { ChannelRouter } from '@api/integrations/channel/channel.router'; import { EventRouter } from '@api/integrations/event/event.router'; import { configService } from '@config/env.config'; @@ -31,8 +30,6 @@ enum HttpStatus { const router: Router = Router(); const guards = [instanceExistsGuard, instanceLoggedGuard, authGuard['apikey']]; -const telemetry = new Telemetry(); - const packageJson = JSON.parse(fs.readFileSync('./package.json', 'utf8')); router.get('/assets/*', (req, res) => { @@ -50,8 +47,6 @@ router.get('/assets/*', (req, res) => { }); router - .use((req, res, next) => telemetry.collectTelemetry(req, res, next)) - .get('/', (req, res) => { res.status(HttpStatus.OK).json({ status: HttpStatus.OK, From 15fc87b51ffd402c5b1dc5e562e2bfb950ca1398 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Wed, 22 Jan 2025 15:09:00 -0300 Subject: [PATCH 25/97] =?UTF-8?q?Altera=20vers=C3=A3o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 77407902..42cdcb14 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api-lite", - "version": "2.1.2", + "version": "2.1.3", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", From b68b30f6ab0427461a5ea37dff8fde7ccdf17204 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Thu, 23 Jan 2025 15:26:19 -0300 Subject: [PATCH 26/97] =?UTF-8?q?Altera=20log,=20inclui=20op=C3=A7=C3=A3o?= =?UTF-8?q?=20de=20enviar=20buffer=20em=20m=C3=ADdias=20WABA=20e=20inclui?= =?UTF-8?q?=20filename=20no=20envio=20de=20m=C3=ADdia=20document=20em=20WA?= =?UTF-8?q?BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../channel/meta/whatsapp.business.service.ts | 16 +++++++++++----- .../channel/whatsapp/whatsapp.baileys.service.ts | 2 +- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/src/api/integrations/channel/meta/whatsapp.business.service.ts b/src/api/integrations/channel/meta/whatsapp.business.service.ts index 5ef82df8..b7d56de3 100644 --- a/src/api/integrations/channel/meta/whatsapp.business.service.ts +++ b/src/api/integrations/channel/meta/whatsapp.business.service.ts @@ -666,6 +666,7 @@ export class BusinessStartupService extends ChannelStartupService { [message['type']]: message['id'], preview_url: linkPreview, caption: message['caption'], + ...(message['mediaType'] === "document" && {filename: message.fileName}), }, }; quoted ? (content.context = { message_id: quoted.id }) : content; @@ -815,7 +816,7 @@ export class BusinessStartupService extends ChannelStartupService { private async getIdMedia(mediaMessage: any) { const formData = new FormData(); - const buffer = Buffer.from(mediaMessage.media, 'base64'); + const buffer = mediaMessage.media; formData.append('messaging_product', 'whatsapp'); formData.append('type', mediaMessage.mimetype); formData.append('file', buffer, { filename: mediaMessage.fileName, contentType: mediaMessage.mimetype }); @@ -886,7 +887,8 @@ export class BusinessStartupService extends ChannelStartupService { } } - public async mediaMessage(data: SendMediaDto) { + public async mediaMessage(data: SendMediaDto, file?: any) { + if (file) data.media = file.buffer; const message = await this.prepareMediaMessage(data); return await this.sendMessageWithTyping( @@ -910,7 +912,7 @@ export class BusinessStartupService extends ChannelStartupService { let mimetype: string; const prepareMedia: any = { - fileName: `${hash}.mp3`, + fileName: `${hash}.ogg`, mediaType: 'audio', media: audio, }; @@ -935,8 +937,12 @@ export class BusinessStartupService extends ChannelStartupService { public async audioWhatsapp(data: SendAudioDto, file?: any) { const mediaData: SendAudioDto = { ...data }; - const audioBuffer = Buffer.from(data.audio, 'base64'); - mediaData.audio = audioBuffer.toString('base64'); + if (file?.buffer) { + mediaData.audio = file.buffer; + } else { + console.error('File or buffer is undefined.'); + throw new Error('File or buffer is undefined.'); + } const message = await this.processAudio(mediaData.audio, data.number); diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index 0490b46e..e4ba4eae 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -1512,7 +1512,7 @@ export class BaileysStartupService extends ChannelStartupService { const sender = isWA.jid.toLowerCase(); - this.logger.verbose(`Sending message to ${sender}`); + this.logger.log(`Sending message to ${sender}`); try { if (options?.delay) { From d39c162dcbce204e7718f1bd8c12de9ea94c522d Mon Sep 17 00:00:00 2001 From: Lucas Mesquita Date: Thu, 23 Jan 2025 20:09:16 -0300 Subject: [PATCH 27/97] Corrige status --- package.json | 2 +- .../integrations/channel/whatsapp/whatsapp.baileys.service.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index 42cdcb14..148a17d9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api-lite", - "version": "2.1.3", + "version": "2.1.4", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index e4ba4eae..5c58e701 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -191,7 +191,7 @@ export class BaileysStartupService extends ChannelStartupService { public async getProfileStatus() { const status = await this.client.fetchStatus(this.instance.wuid); - return status?.status; + return status[0]?.status; } public get profilePictureUrl() { @@ -1288,7 +1288,7 @@ export class BaileysStartupService extends ChannelStartupService { try { return { wuid: jid, - status: (await this.client.fetchStatus(jid))?.status, + status: (await this.client.fetchStatus(jid))[0]?.status, }; } catch (error) { return { From d9839210681d0c7663cefce883b6124101c69153 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Mon, 27 Jan 2025 14:28:38 -0300 Subject: [PATCH 28/97] =?UTF-8?q?Comenta=20listeners=20n=C3=A3o=20utilizad?= =?UTF-8?q?os?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../whatsapp/whatsapp.baileys.service.ts | 74 ++++++++++--------- 1 file changed, 38 insertions(+), 36 deletions(-) diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index 1a60c579..5dc21c5d 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -706,6 +706,7 @@ export class BaileysStartupService extends ChannelStartupService { private readonly contactHandle = { 'contacts.upsert': async (contacts: Contact[]) => { + this.logger.info('contacts.upsert: ' + JSON.stringify(contacts)); try { const contactsRaw: any = contacts.map((contact) => ({ remoteJid: contact.id, @@ -771,6 +772,7 @@ export class BaileysStartupService extends ChannelStartupService { profilePicUrl?: string; instanceId: string; }[] = []; + this.logger.info('contacts.update: ' + JSON.stringify(contacts)); for await (const contact of contacts) { contactsRaw.push({ remoteJid: contact.id, @@ -1446,42 +1448,42 @@ export class BaileysStartupService extends ChannelStartupService { } } - if (events['chats.upsert']) { - const payload = events['chats.upsert']; - this.chatHandle['chats.upsert'](payload); - } - - if (events['chats.update']) { - const payload = events['chats.update']; - this.chatHandle['chats.update'](payload); - } - - if (events['chats.delete']) { - const payload = events['chats.delete']; - this.chatHandle['chats.delete'](payload); - } - - if (events['contacts.upsert']) { - const payload = events['contacts.upsert']; - this.contactHandle['contacts.upsert'](payload); - } - - if (events['contacts.update']) { - const payload = events['contacts.update']; - this.contactHandle['contacts.update'](payload); - } - - if (events[Events.LABELS_ASSOCIATION]) { - const payload = events[Events.LABELS_ASSOCIATION]; - this.labelHandle[Events.LABELS_ASSOCIATION](payload, database); - return; - } - - if (events[Events.LABELS_EDIT]) { - const payload = events[Events.LABELS_EDIT]; - this.labelHandle[Events.LABELS_EDIT](payload); - return; - } + // if (events['chats.upsert']) { + // const payload = events['chats.upsert']; + // this.chatHandle['chats.upsert'](payload); + // } + + // if (events['chats.update']) { + // const payload = events['chats.update']; + // this.chatHandle['chats.update'](payload); + // } + + // if (events['chats.delete']) { + // const payload = events['chats.delete']; + // this.chatHandle['chats.delete'](payload); + // } + + // if (events['contacts.upsert']) { + // const payload = events['contacts.upsert']; + // this.contactHandle['contacts.upsert'](payload); + // } + + // if (events['contacts.update']) { + // const payload = events['contacts.update']; + // this.contactHandle['contacts.update'](payload); + // } + + // if (events[Events.LABELS_ASSOCIATION]) { + // const payload = events[Events.LABELS_ASSOCIATION]; + // this.labelHandle[Events.LABELS_ASSOCIATION](payload, database); + // return; + // } + + // if (events[Events.LABELS_EDIT]) { + // const payload = events[Events.LABELS_EDIT]; + // this.labelHandle[Events.LABELS_EDIT](payload); + // return; + // } } }); } From 73594af79ba9f021a7fa192f29cfa793a48508b2 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Mon, 27 Jan 2025 14:32:23 -0300 Subject: [PATCH 29/97] Remove log --- .../integrations/channel/whatsapp/whatsapp.baileys.service.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index 5dc21c5d..bfe3452f 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -706,7 +706,6 @@ export class BaileysStartupService extends ChannelStartupService { private readonly contactHandle = { 'contacts.upsert': async (contacts: Contact[]) => { - this.logger.info('contacts.upsert: ' + JSON.stringify(contacts)); try { const contactsRaw: any = contacts.map((contact) => ({ remoteJid: contact.id, @@ -772,7 +771,6 @@ export class BaileysStartupService extends ChannelStartupService { profilePicUrl?: string; instanceId: string; }[] = []; - this.logger.info('contacts.update: ' + JSON.stringify(contacts)); for await (const contact of contacts) { contactsRaw.push({ remoteJid: contact.id, From 4c1427366b260d59d4e236436ca9590c5d4c602c Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Mon, 27 Jan 2025 14:36:14 -0300 Subject: [PATCH 30/97] =?UTF-8?q?Update=20vers=C3=A3o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 04ccf1ef..f9b8bf61 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.1", + "version": "2.2.2", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", From 998a4f07c9697041517a30d7336f6401d183776f Mon Sep 17 00:00:00 2001 From: Jonathan Mantovani Date: Tue, 28 Jan 2025 16:25:01 -0300 Subject: [PATCH 31/97] fix: use cache on the findGroupInfos endpoint --- src/api/controllers/group.controller.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/api/controllers/group.controller.ts b/src/api/controllers/group.controller.ts index ebe7c036..64eaa14b 100644 --- a/src/api/controllers/group.controller.ts +++ b/src/api/controllers/group.controller.ts @@ -35,7 +35,7 @@ export class GroupController { } public async findGroupInfo(instance: InstanceDto, groupJid: GroupJid) { - return await this.waMonitor.waInstances[instance.instanceName].findGroup(groupJid); + return await this.waMonitor.waInstances[instance.instanceName].getGroupMetadataCache(groupJid.groupJid); } public async fetchAllGroups(instance: InstanceDto, getPaticipants: GetParticipant) { From 9d546aa8f4799ff0a940b7e6839e5d8ed9d16bf2 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Tue, 28 Jan 2025 17:44:54 -0300 Subject: [PATCH 32/97] Inclui index remoteJid na tabela isOnWhatsapp --- .../migration.sql | 2 + prisma/postgresql-schema.prisma | 1 + .../whatsapp/whatsapp.baileys.service.ts | 67 +++++++++++-------- 3 files changed, 41 insertions(+), 29 deletions(-) create mode 100644 prisma/postgresql-migrations/20250128200807_added_index_remotejid_on_is_on_whatsapp_table/migration.sql diff --git a/prisma/postgresql-migrations/20250128200807_added_index_remotejid_on_is_on_whatsapp_table/migration.sql b/prisma/postgresql-migrations/20250128200807_added_index_remotejid_on_is_on_whatsapp_table/migration.sql new file mode 100644 index 00000000..ea4ddaa3 --- /dev/null +++ b/prisma/postgresql-migrations/20250128200807_added_index_remotejid_on_is_on_whatsapp_table/migration.sql @@ -0,0 +1,2 @@ +-- CreateIndex +CREATE INDEX "IsOnWhatsapp_remoteJid_idx" ON "IsOnWhatsapp"("remoteJid"); diff --git a/prisma/postgresql-schema.prisma b/prisma/postgresql-schema.prisma index 2f4f9adf..2f79ed9e 100644 --- a/prisma/postgresql-schema.prisma +++ b/prisma/postgresql-schema.prisma @@ -627,4 +627,5 @@ model IsOnWhatsapp { jidOptions String createdAt DateTime @default(now()) @db.Timestamp updatedAt DateTime @updatedAt @db.Timestamp + @@index([remoteJid]) } diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index bfe3452f..cc835e06 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -729,35 +729,35 @@ export class BaileysStartupService extends ChannelStartupService { } } - const updatedContacts = await Promise.all( - contacts.map(async (contact) => ({ - remoteJid: contact.id, - pushName: contact?.name || contact?.verifiedName || contact.id.split('@')[0], - profilePicUrl: (await this.profilePicture(contact.id)).profilePictureUrl, - instanceId: this.instanceId, - })), - ); - - if (updatedContacts.length > 0) { - const usersContacts = updatedContacts.filter((c) => c.remoteJid.includes('@s.whatsapp')); - if (usersContacts) { - await saveOnWhatsappCache(usersContacts.map((c) => ({ remoteJid: c.remoteJid }))); - } - - this.sendDataWebhook(Events.CONTACTS_UPDATE, updatedContacts); - await Promise.all( - updatedContacts.map(async (contact) => { - const update = this.prismaRepository.contact.updateMany({ - where: { remoteJid: contact.remoteJid, instanceId: this.instanceId }, - data: { - profilePicUrl: contact.profilePicUrl, - }, - }); - - return update; - }), - ); - } + // const updatedContacts = await Promise.all( + // contacts.map(async (contact) => ({ + // remoteJid: contact.id, + // pushName: contact?.name || contact?.verifiedName || contact.id.split('@')[0], + // profilePicUrl: (await this.profilePicture(contact.id)).profilePictureUrl, + // instanceId: this.instanceId, + // })), + // ); + + // if (updatedContacts.length > 0) { + // const usersContacts = updatedContacts.filter((c) => c.remoteJid.includes('@s.whatsapp')); + // if (usersContacts) { + // await saveOnWhatsappCache(usersContacts.map((c) => ({ remoteJid: c.remoteJid }))); + // } + + // this.sendDataWebhook(Events.CONTACTS_UPDATE, updatedContacts); + // await Promise.all( + // updatedContacts.map(async (contact) => { + // const update = this.prismaRepository.contact.updateMany({ + // where: { remoteJid: contact.remoteJid, instanceId: this.instanceId }, + // data: { + // profilePicUrl: contact.profilePicUrl, + // }, + // }); + + // return update; + // }), + // ); + // } } catch (error) { console.error(error); this.logger.error(`Error: ${error.message}`); @@ -837,6 +837,15 @@ export class BaileysStartupService extends ChannelStartupService { } this.sendDataWebhook(Events.MESSAGES_SET, [...messagesRaw]); + await this.contactHandle['contacts.upsert']( + contacts + .filter((c) => !!c.notify || !!c.name) + .map((c) => ({ + id: c.id, + name: c.name ?? c.notify, + })), + ); + contacts = undefined; messages = undefined; chats = undefined; From c56a0d3949d8ac29b1a6d0b8572d44ae30cdbe57 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Tue, 28 Jan 2025 17:49:25 -0300 Subject: [PATCH 33/97] =?UTF-8?q?Update=20da=20vers=C3=A3o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index f9b8bf61..fbdaece7 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.2", + "version": "2.2.3", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", From b0d0bc4ab3280a4647e912b7801956a386083247 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Wed, 29 Jan 2025 13:59:56 -0300 Subject: [PATCH 34/97] =?UTF-8?q?Comenta=20c=C3=B3digo=20desnecess=C3=A1ri?= =?UTF-8?q?o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 2 +- .../evolution/evolution.channel.service.ts | 56 +-- .../whatsapp/whatsapp.baileys.service.ts | 444 +++++++++--------- 3 files changed, 251 insertions(+), 251 deletions(-) diff --git a/package.json b/package.json index fbdaece7..3342b7d9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.3", + "version": "2.2.4", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", diff --git a/src/api/integrations/channel/evolution/evolution.channel.service.ts b/src/api/integrations/channel/evolution/evolution.channel.service.ts index 7662fa24..a0c436c0 100644 --- a/src/api/integrations/channel/evolution/evolution.channel.service.ts +++ b/src/api/integrations/channel/evolution/evolution.channel.service.ts @@ -179,34 +179,34 @@ export class EvolutionStartupService extends ChannelStartupService { this.sendDataWebhook(Events.CONTACTS_UPSERT, contactRaw); - const chat = await this.prismaRepository.chat.findFirst({ - where: { instanceId: this.instanceId, remoteJid: data.remoteJid }, - }); - - if (chat) { - const chatRaw: any = { - remoteJid: data.remoteJid, - instanceId: this.instanceId, - }; - - this.sendDataWebhook(Events.CHATS_UPDATE, chatRaw); - - await this.prismaRepository.chat.updateMany({ - where: { remoteJid: chat.remoteJid }, - data: chatRaw, - }); - } - - const chatRaw: any = { - remoteJid: data.remoteJid, - instanceId: this.instanceId, - }; - - this.sendDataWebhook(Events.CHATS_UPSERT, chatRaw); - - await this.prismaRepository.chat.create({ - data: chatRaw, - }); + // const chat = await this.prismaRepository.chat.findFirst({ + // where: { instanceId: this.instanceId, remoteJid: data.remoteJid }, + // }); + + // if (chat) { + // const chatRaw: any = { + // remoteJid: data.remoteJid, + // instanceId: this.instanceId, + // }; + + // this.sendDataWebhook(Events.CHATS_UPDATE, chatRaw); + + // await this.prismaRepository.chat.updateMany({ + // where: { remoteJid: chat.remoteJid }, + // data: chatRaw, + // }); + // } + + // const chatRaw: any = { + // remoteJid: data.remoteJid, + // instanceId: this.instanceId, + // }; + + // this.sendDataWebhook(Events.CHATS_UPSERT, chatRaw); + + // await this.prismaRepository.chat.create({ + // data: chatRaw, + // }); } protected async sendMessageWithTyping(number: string, message: any, options?: Options, file?: any) { diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index cc835e06..00976c41 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -951,29 +951,29 @@ export class BaileysStartupService extends ChannelStartupService { if (settings?.groupsIgnore && received.key.remoteJid.includes('@g.us')) { continue; } - const existingChat = await this.prismaRepository.chat.findFirst({ - where: { instanceId: this.instanceId, remoteJid: received.key.remoteJid }, - select: { id: true, name: true }, - }); - - if ( - existingChat && - received.pushName && - existingChat.name !== received.pushName && - received.pushName.trim().length > 0 - ) { - this.sendDataWebhook(Events.CHATS_UPSERT, [{ ...existingChat, name: received.pushName }]); - if (this.configService.get('DATABASE').SAVE_DATA.CHATS) { - try { - await this.prismaRepository.chat.update({ - where: { id: existingChat.id }, - data: { name: received.pushName }, - }); - } catch (error) { - console.log(`Chat insert record ignored: ${received.key.remoteJid} - ${this.instanceId}`); - } - } - } + // const existingChat = await this.prismaRepository.chat.findFirst({ + // where: { instanceId: this.instanceId, remoteJid: received.key.remoteJid }, + // select: { id: true, name: true }, + // }); + + // if ( + // existingChat && + // received.pushName && + // existingChat.name !== received.pushName && + // received.pushName.trim().length > 0 + // ) { + // this.sendDataWebhook(Events.CHATS_UPSERT, [{ ...existingChat, name: received.pushName }]); + // if (this.configService.get('DATABASE').SAVE_DATA.CHATS) { + // try { + // await this.prismaRepository.chat.update({ + // where: { id: existingChat.id }, + // data: { name: received.pushName }, + // }); + // } catch (error) { + // console.log(`Chat insert record ignored: ${received.key.remoteJid} - ${this.instanceId}`); + // } + // } + // } // Resposta de texto em algum status if (received.message?.extendedTextMessage?.contextInfo?.remoteJid === 'status@broadcast' && @@ -1006,64 +1006,64 @@ export class BaileysStartupService extends ChannelStartupService { data: messageRaw, }); - if (received.key.fromMe === false) { - if (msg.status === status[3]) { - this.logger.log(`Update not read messages ${received.key.remoteJid}`); - - await this.updateChatUnreadMessages(received.key.remoteJid); - } else if (msg.status === status[4]) { - this.logger.log(`Update readed messages ${received.key.remoteJid} - ${msg.messageTimestamp}`); - - await this.updateMessagesReadedByTimestamp(received.key.remoteJid, msg.messageTimestamp); - } - } else { - // is send message by me - this.logger.log(`Update readed messages ${received.key.remoteJid} - ${msg.messageTimestamp}`); - - await this.updateMessagesReadedByTimestamp(received.key.remoteJid, msg.messageTimestamp); - } - - if (isMedia) { - if (this.configService.get('S3').ENABLE) { - try { - const message: any = received; - const media = await this.getBase64FromMediaMessage( - { - message, - }, - true, - ); - - const { buffer, mediaType, fileName, size } = media; - const mimetype = mimeTypes.lookup(fileName).toString(); - const fullName = join(`${this.instance.id}`, received.key.remoteJid, mediaType, fileName); - await s3Service.uploadFile(fullName, buffer, size.fileLength?.low, { - 'Content-Type': mimetype, - }); - - await this.prismaRepository.media.create({ - data: { - messageId: msg.id, - instanceId: this.instanceId, - type: mediaType, - fileName: fullName, - mimetype, - }, - }); - - const mediaUrl = await s3Service.getObjectUrl(fullName); - - messageRaw.message.mediaUrl = mediaUrl; - - await this.prismaRepository.message.update({ - where: { id: msg.id }, - data: messageRaw, - }); - } catch (error) { - this.logger.error(['Error on upload file to minio', error?.message, error?.stack]); - } - } - } + // if (received.key.fromMe === false) { + // if (msg.status === status[3]) { + // this.logger.log(`Update not read messages ${received.key.remoteJid}`); + + // await this.updateChatUnreadMessages(received.key.remoteJid); + // } else if (msg.status === status[4]) { + // this.logger.log(`Update readed messages ${received.key.remoteJid} - ${msg.messageTimestamp}`); + + // await this.updateMessagesReadedByTimestamp(received.key.remoteJid, msg.messageTimestamp); + // } + // } else { + // // is send message by me + // this.logger.log(`Update readed messages ${received.key.remoteJid} - ${msg.messageTimestamp}`); + + // await this.updateMessagesReadedByTimestamp(received.key.remoteJid, msg.messageTimestamp); + // } + + // if (isMedia) { + // if (this.configService.get('S3').ENABLE) { + // try { + // const message: any = received; + // const media = await this.getBase64FromMediaMessage( + // { + // message, + // }, + // true, + // ); + + // const { buffer, mediaType, fileName, size } = media; + // const mimetype = mimeTypes.lookup(fileName).toString(); + // const fullName = join(`${this.instance.id}`, received.key.remoteJid, mediaType, fileName); + // await s3Service.uploadFile(fullName, buffer, size.fileLength?.low, { + // 'Content-Type': mimetype, + // }); + + // await this.prismaRepository.media.create({ + // data: { + // messageId: msg.id, + // instanceId: this.instanceId, + // type: mediaType, + // fileName: fullName, + // mimetype, + // }, + // }); + + // const mediaUrl = await s3Service.getObjectUrl(fullName); + + // messageRaw.message.mediaUrl = mediaUrl; + + // await this.prismaRepository.message.update({ + // where: { id: msg.id }, + // data: messageRaw, + // }); + // } catch (error) { + // this.logger.error(['Error on upload file to minio', error?.message, error?.stack]); + // } + // } + // } } if (this.localWebhook.enabled) { @@ -1145,7 +1145,7 @@ export class BaileysStartupService extends ChannelStartupService { 'messages.update': async (args: WAMessageUpdate[], settings: any) => { this.logger.log(`Update messages ${JSON.stringify(args, undefined, 2)}`); - const readChatToUpdate: Record = {}; // {remoteJid: true} + //const readChatToUpdate: Record = {}; // {remoteJid: true} for await (const { key, update } of args) { if (settings?.groupsIgnore && key.remoteJid?.includes('@g.us')) { @@ -1166,57 +1166,57 @@ export class BaileysStartupService extends ChannelStartupService { } } - const findMessage = await this.prismaRepository.message.findFirst({ - where: { - instanceId: this.instanceId, - key: { - path: ['id'], - equals: key.id, - }, - }, - }); - - if (!findMessage) { - continue; - } + // const findMessage = await this.prismaRepository.message.findFirst({ + // where: { + // instanceId: this.instanceId, + // key: { + // path: ['id'], + // equals: key.id, + // }, + // }, + // }); + + // if (!findMessage) { + // continue; + // } if (update.message === null && update.status === undefined) { this.sendDataWebhook(Events.MESSAGES_DELETE, key); - const message: any = { - messageId: findMessage.id, - keyId: key.id, - remoteJid: key.remoteJid, - fromMe: key.fromMe, - participant: key?.remoteJid, - status: 'DELETED', - instanceId: this.instanceId, - }; - - if (this.configService.get('DATABASE').SAVE_DATA.MESSAGE_UPDATE) - await this.prismaRepository.messageUpdate.create({ - data: message, - }); + // const message: any = { + // messageId: findMessage.id, + // keyId: key.id, + // remoteJid: key.remoteJid, + // fromMe: key.fromMe, + // participant: key?.remoteJid, + // status: 'DELETED', + // instanceId: this.instanceId, + // }; + + // if (this.configService.get('DATABASE').SAVE_DATA.MESSAGE_UPDATE) + // await this.prismaRepository.messageUpdate.create({ + // data: message, + // }); continue; - } else if (update.status !== undefined && status[update.status] !== findMessage.status) { - if (!key.fromMe && key.remoteJid) { - readChatToUpdate[key.remoteJid] = true; - - if (status[update.status] === status[4]) { - this.logger.log(`Update as read ${key.remoteJid} - ${findMessage.messageTimestamp}`); - this.updateMessagesReadedByTimestamp(key.remoteJid, findMessage.messageTimestamp); - } - } - - await this.prismaRepository.message.update({ - where: { id: findMessage.id }, - data: { status: status[update.status] }, - }); - } + } //else if (update.status !== undefined && status[update.status] !== findMessage.status) { + // if (!key.fromMe && key.remoteJid) { + // readChatToUpdate[key.remoteJid] = true; + + // if (status[update.status] === status[4]) { + // this.logger.log(`Update as read ${key.remoteJid} - ${findMessage.messageTimestamp}`); + // this.updateMessagesReadedByTimestamp(key.remoteJid, findMessage.messageTimestamp); + // } + // } + + // await this.prismaRepository.message.update({ + // where: { id: findMessage.id }, + // data: { status: status[update.status] }, + // }); + //} const message: any = { - messageId: findMessage.id, + messageId: key.id, keyId: key.id, remoteJid: key.remoteJid, fromMe: key.fromMe, @@ -1228,41 +1228,41 @@ export class BaileysStartupService extends ChannelStartupService { this.sendDataWebhook(Events.MESSAGES_UPDATE, message); - if (this.configService.get('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 }, - }); - - if (existingChat) { - const chatToInsert = { - remoteJid: message.remoteJid, - instanceId: this.instanceId, - name: message.pushName || '', - unreadMessages: 0, - }; - - this.sendDataWebhook(Events.CHATS_UPSERT, [chatToInsert]); - if (this.configService.get('DATABASE').SAVE_DATA.CHATS) { - try { - await this.prismaRepository.chat.update({ - where: { - id: existingChat.id, - }, - data: chatToInsert, - }); - } catch (error) { - console.log(`Chat insert record ignored: ${chatToInsert.remoteJid} - ${chatToInsert.instanceId}`); - } - } - } + // if (this.configService.get('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 }, + // }); + + // if (existingChat) { + // const chatToInsert = { + // remoteJid: message.remoteJid, + // instanceId: this.instanceId, + // name: message.pushName || '', + // unreadMessages: 0, + // }; + + // this.sendDataWebhook(Events.CHATS_UPSERT, [chatToInsert]); + // if (this.configService.get('DATABASE').SAVE_DATA.CHATS) { + // try { + // await this.prismaRepository.chat.update({ + // where: { + // id: existingChat.id, + // }, + // data: chatToInsert, + // }); + // } catch (error) { + // console.log(`Chat insert record ignored: ${chatToInsert.remoteJid} - ${chatToInsert.instanceId}`); + // } + // } + // } } } - await Promise.all(Object.keys(readChatToUpdate).map((remoteJid) => this.updateChatUnreadMessages(remoteJid))); + //await Promise.all(Object.keys(readChatToUpdate).map((remoteJid) => this.updateChatUnreadMessages(remoteJid))); }, }; @@ -1411,22 +1411,22 @@ export class BaileysStartupService extends ChannelStartupService { this.messageHandle['messages.update'](payload, settings); } - if (events['message-receipt.update']) { - const payload = events['message-receipt.update'] as MessageUserReceiptUpdate[]; - const remotesJidMap: Record = {}; + // if (events['message-receipt.update']) { + // const payload = events['message-receipt.update'] as MessageUserReceiptUpdate[]; + // const remotesJidMap: Record = {}; - for (const event of payload) { - if (typeof event.key.remoteJid === 'string' && typeof event.receipt.readTimestamp === 'number') { - remotesJidMap[event.key.remoteJid] = event.receipt.readTimestamp; - } - } + // for (const event of payload) { + // if (typeof event.key.remoteJid === 'string' && typeof event.receipt.readTimestamp === 'number') { + // remotesJidMap[event.key.remoteJid] = event.receipt.readTimestamp; + // } + // } - await Promise.all( - Object.keys(remotesJidMap).map(async (remoteJid) => - this.updateMessagesReadedByTimestamp(remoteJid, remotesJidMap[remoteJid]), - ), - ); - } + // await Promise.all( + // Object.keys(remotesJidMap).map(async (remoteJid) => + // this.updateMessagesReadedByTimestamp(remoteJid, remotesJidMap[remoteJid]), + // ), + // ); + // } if (events['presence.update']) { const payload = events['presence.update']; @@ -3805,57 +3805,57 @@ export class BaileysStartupService extends ChannelStartupService { return messageRaw; } - private async updateMessagesReadedByTimestamp(remoteJid: string, timestamp?: number): Promise { - if (timestamp === undefined || timestamp === null) return 0; - - const result = await this.prismaRepository.message.updateMany({ - where: { - AND: [ - { key: { path: ['remoteJid'], equals: remoteJid } }, - { key: { path: ['fromMe'], equals: false } }, - { messageTimestamp: { lte: timestamp } }, - { - OR: [{ status: null }, { status: status[3] }], - }, - ], - }, - data: { status: status[4] }, - }); - - if (result) { - if (result.count > 0) { - this.updateChatUnreadMessages(remoteJid); - } - - return result.count; - } - - return 0; - } - - private async updateChatUnreadMessages(remoteJid: string): Promise { - const [chat, unreadMessages] = await Promise.all([ - this.prismaRepository.chat.findFirst({ where: { remoteJid } }), - this.prismaRepository.message.count({ - where: { - AND: [ - { key: { path: ['remoteJid'], equals: remoteJid } }, - { key: { path: ['fromMe'], equals: false } }, - { status: { equals: status[3] } }, - ], - }, - }), - ]); - - if (chat && chat.unreadMessages !== unreadMessages) { - await this.prismaRepository.chat.update({ - where: { id: chat.id }, - data: { unreadMessages }, - }); - } - - return unreadMessages; - } + // private async updateMessagesReadedByTimestamp(remoteJid: string, timestamp?: number): Promise { + // if (timestamp === undefined || timestamp === null) return 0; + + // const result = await this.prismaRepository.message.updateMany({ + // where: { + // AND: [ + // { key: { path: ['remoteJid'], equals: remoteJid } }, + // { key: { path: ['fromMe'], equals: false } }, + // { messageTimestamp: { lte: timestamp } }, + // { + // OR: [{ status: null }, { status: status[3] }], + // }, + // ], + // }, + // data: { status: status[4] }, + // }); + + // if (result) { + // if (result.count > 0) { + // this.updateChatUnreadMessages(remoteJid); + // } + + // return result.count; + // } + + // return 0; + // } + + // private async updateChatUnreadMessages(remoteJid: string): Promise { + // const [chat, unreadMessages] = await Promise.all([ + // this.prismaRepository.chat.findFirst({ where: { remoteJid } }), + // this.prismaRepository.message.count({ + // where: { + // AND: [ + // { key: { path: ['remoteJid'], equals: remoteJid } }, + // { key: { path: ['fromMe'], equals: false } }, + // { status: { equals: status[3] } }, + // ], + // }, + // }), + // ]); + + // if (chat && chat.unreadMessages !== unreadMessages) { + // await this.prismaRepository.chat.update({ + // where: { id: chat.id }, + // data: { unreadMessages }, + // }); + // } + + // return unreadMessages; + // } private async addLabel(labelId: string, instanceId: string, chatId: string) { const id = cuid(); From 3fa1a5f3d2ee191d30bda2dca076d2f937c5fd03 Mon Sep 17 00:00:00 2001 From: Lucas Mesquita Date: Thu, 30 Jan 2025 18:06:02 -0300 Subject: [PATCH 35/97] Altera lib da baileys --- package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 3342b7d9..ac42d35d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.4", + "version": "2.2.5", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", @@ -57,7 +57,7 @@ "@sentry/node": "^8.47.0", "amqplib": "^0.10.5", "axios": "^1.7.9", - "baileys": "github:EvolutionAPI/Baileys", + "baileys": "github:WhiskeySockets/Baileys#master", "class-validator": "^0.14.1", "compression": "^1.7.5", "cors": "^2.8.5", From 2b1060c94ae7c7fb21be17117b84ff49a62f3017 Mon Sep 17 00:00:00 2001 From: Lucas Mesquita Date: Thu, 30 Jan 2025 19:40:14 -0300 Subject: [PATCH 36/97] Remove codigo call nao usado --- package.json | 2 +- .../channel/whatsapp/whatsapp.baileys.service.ts | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/package.json b/package.json index ac42d35d..be1f3cac 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.5", + "version": "2.2.6", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index 00976c41..f327617a 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -1589,10 +1589,10 @@ export class BaileysStartupService extends ChannelStartupService { const jid = createJid(number); try { - const call = await this.client.offerCall(jid, isVideo); - setTimeout(() => this.client.terminateCall(call.id, call.to), callDuration * 1000); + //const call = await this.client.offerCall(jid, isVideo); + //setTimeout(() => this.client.terminateCall(call.id, call.to), callDuration * 1000); - return call; + //return call; } catch (error) { return error; } From d642cdc03892a8d9d22d0c5cae76c84a4583197c Mon Sep 17 00:00:00 2001 From: Lucas Mesquita Date: Fri, 31 Jan 2025 16:04:21 -0300 Subject: [PATCH 37/97] Update version --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index be1f3cac..b8d29dba 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.6", + "version": "2.2.7", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", From b8fd74116faa1ae2e6f17cb62cdf810e296d87d6 Mon Sep 17 00:00:00 2001 From: Lucas Mesquita Date: Fri, 31 Jan 2025 20:25:50 -0300 Subject: [PATCH 38/97] Update baileys version --- package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index b8d29dba..933ed16d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.7", + "version": "2.2.8", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", @@ -57,7 +57,7 @@ "@sentry/node": "^8.47.0", "amqplib": "^0.10.5", "axios": "^1.7.9", - "baileys": "github:WhiskeySockets/Baileys#master", + "baileys": "6.7.12", "class-validator": "^0.14.1", "compression": "^1.7.5", "cors": "^2.8.5", From c0fd917bacc9ad848d36c58fe09817d5b6dbd614 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Sat, 1 Feb 2025 15:23:35 -0300 Subject: [PATCH 39/97] Remove uniqueItems from mentioned validation --- src/validate/message.schema.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/validate/message.schema.ts b/src/validate/message.schema.ts index d514c619..5ee6f752 100644 --- a/src/validate/message.schema.ts +++ b/src/validate/message.schema.ts @@ -81,7 +81,6 @@ export const textMessageSchema: JSONSchema7 = { mentioned: { type: 'array', minItems: 1, - uniqueItems: true, items: { type: 'string', pattern: '^\\d+', From 12d4c071c7d1bacd65c41cd8de4aac18333a2754 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Tue, 4 Feb 2025 11:45:49 -0300 Subject: [PATCH 40/97] Envio de contatos no webhook messages.set --- .../whatsapp/whatsapp.baileys.service.ts | 19 +++++++++---------- .../integrations/event/event.controller.ts | 1 + src/api/integrations/event/event.manager.ts | 2 ++ .../event/webhook/webhook.controller.ts | 2 ++ src/api/services/channel.service.ts | 3 ++- src/api/types/wa.types.ts | 10 ++++++++++ 6 files changed, 26 insertions(+), 11 deletions(-) diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index f327617a..a08a7378 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -835,16 +835,15 @@ export class BaileysStartupService extends ChannelStartupService { messagesRaw.push(this.prepareMessage(m)); } - this.sendDataWebhook(Events.MESSAGES_SET, [...messagesRaw]); - - await this.contactHandle['contacts.upsert']( - contacts - .filter((c) => !!c.notify || !!c.name) - .map((c) => ({ - id: c.id, - name: c.name ?? c.notify, - })), - ); + + const c = contacts + .filter((c) => !!c.notify || !!c.name) + .map((c) => ({ + id: c.id, + name: c.name ?? c.notify, + })); + + this.sendDataWebhook(Events.MESSAGES_SET, undefined, true, undefined, { contacts: c, messages: messagesRaw }); contacts = undefined; messages = undefined; diff --git a/src/api/integrations/event/event.controller.ts b/src/api/integrations/event/event.controller.ts index 2e6a2330..4117d580 100644 --- a/src/api/integrations/event/event.controller.ts +++ b/src/api/integrations/event/event.controller.ts @@ -14,6 +14,7 @@ export type EmitData = { apiKey?: string; local?: boolean; integration?: string[]; + historySetData?: wa.HistorySetData; }; export interface EventControllerInterface { diff --git a/src/api/integrations/event/event.manager.ts b/src/api/integrations/event/event.manager.ts index 9df96f9f..e9076c0f 100644 --- a/src/api/integrations/event/event.manager.ts +++ b/src/api/integrations/event/event.manager.ts @@ -5,6 +5,7 @@ import { WebhookController } from '@api/integrations/event/webhook/webhook.contr import { WebsocketController } from '@api/integrations/event/websocket/websocket.controller'; import { PrismaRepository } from '@api/repository/repository.service'; import { WAMonitoringService } from '@api/services/monitor.service'; +import { wa } from '@api/types/wa.types'; import { Server } from 'http'; export class EventManager { @@ -100,6 +101,7 @@ export class EventManager { apiKey?: string; local?: boolean; integration?: string[]; + historySetData?: wa.HistorySetData; }): Promise { await this.websocket.emit(eventData); await this.rabbitmq.emit(eventData); diff --git a/src/api/integrations/event/webhook/webhook.controller.ts b/src/api/integrations/event/webhook/webhook.controller.ts index ce709c3d..fb8ea5ed 100644 --- a/src/api/integrations/event/webhook/webhook.controller.ts +++ b/src/api/integrations/event/webhook/webhook.controller.ts @@ -65,6 +65,7 @@ export class WebhookController extends EventController implements EventControlle apiKey, local, integration, + historySetData }: EmitData): Promise { if (integration && !integration.includes('webhook')) { return; @@ -83,6 +84,7 @@ export class WebhookController extends EventController implements EventControlle event, instance: instanceName, data, + historySetData, destination: instance?.url || `${webhookConfig.GLOBAL.URL}/${transformedWe}`, date_time: dateTime, sender, diff --git a/src/api/services/channel.service.ts b/src/api/services/channel.service.ts index 29bed428..c9c59be2 100644 --- a/src/api/services/channel.service.ts +++ b/src/api/services/channel.service.ts @@ -257,7 +257,7 @@ export class ChannelStartupService { return data; } - public async sendDataWebhook(event: Events, data: T, local = true, integration?: string[]) { + public async sendDataWebhook(event: Events, data: T, local = true, integration?: string[], historySetData?: wa.HistorySetData) { const serverUrl = this.configService.get('SERVER').URL; const tzoffset = new Date().getTimezoneOffset() * 60000; //offset in milliseconds const localISOTime = new Date(Date.now() - tzoffset).toISOString(); @@ -278,6 +278,7 @@ export class ChannelStartupService { apiKey: expose && instanceApikey ? instanceApikey : null, local, integration, + historySetData }); } diff --git a/src/api/types/wa.types.ts b/src/api/types/wa.types.ts index 0aad0696..df649aad 100644 --- a/src/api/types/wa.types.ts +++ b/src/api/types/wa.types.ts @@ -130,6 +130,16 @@ export declare namespace wa { }; export type StatusMessage = 'ERROR' | 'PENDING' | 'SERVER_ACK' | 'DELIVERY_ACK' | 'READ' | 'DELETED' | 'PLAYED'; + + export type HistorySetData = { + contacts: HistorySetContact[]; + messages: any[]; + } + + export type HistorySetContact = { + id: string; + name: string; + } } export const TypeMediaMessage = [ From 340a19a60674ae7eebc17f9cc89888340a47d87c Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Tue, 4 Feb 2025 21:12:36 -0300 Subject: [PATCH 41/97] =?UTF-8?q?Update=20vers=C3=A3o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 933ed16d..006050cd 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.8", + "version": "2.2.9", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", From 6ed23007b9840d1521961b6769ccc77fd390e78f Mon Sep 17 00:00:00 2001 From: Jonathan Mantovani Date: Mon, 10 Feb 2025 09:47:01 -0300 Subject: [PATCH 42/97] fix: Send ack update event to campaign messages --- .../channel/meta/whatsapp.business.service.ts | 21 ++----------------- 1 file changed, 2 insertions(+), 19 deletions(-) diff --git a/src/api/integrations/channel/meta/whatsapp.business.service.ts b/src/api/integrations/channel/meta/whatsapp.business.service.ts index c5f719da..3642c6e3 100644 --- a/src/api/integrations/channel/meta/whatsapp.business.service.ts +++ b/src/api/integrations/channel/meta/whatsapp.business.service.ts @@ -505,19 +505,6 @@ export class BusinessStartupService extends ChannelStartupService { return; } if (key.remoteJid !== 'status@broadcast' && !key?.remoteJid?.match(/(:\d+)/)) { - const findMessage = await this.prismaRepository.message.findFirst({ - where: { - instanceId: this.instanceId, - key: { - path: ['id'], - equals: key.id, - }, - }, - }); - - if (!findMessage) { - return; - } if (item.status === 'read' && key.fromMe) return; @@ -525,7 +512,7 @@ export class BusinessStartupService extends ChannelStartupService { this.sendDataWebhook(Events.MESSAGES_DELETE, key); const message: any = { - messageId: findMessage.id, + messageId: item.id, keyId: key.id, remoteJid: key.remoteJid, fromMe: key.fromMe, @@ -542,7 +529,7 @@ export class BusinessStartupService extends ChannelStartupService { } const message: any = { - messageId: findMessage.id, + messageId: item.id, keyId: key.id, remoteJid: key.remoteJid, fromMe: key.fromMe, @@ -556,10 +543,6 @@ export class BusinessStartupService extends ChannelStartupService { await this.prismaRepository.messageUpdate.create({ data: message, }); - - if (findMessage.webhookUrl) { - await axios.post(findMessage.webhookUrl, message); - } } } } From e6b637adb1d199171f8383cc87b761b2f87bc022 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Mon, 10 Feb 2025 13:47:05 -0300 Subject: [PATCH 43/97] Update version --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 006050cd..efb3be27 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.9", + "version": "2.2.10", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", From 9e23c38f6986eb95d1bbe7f587d33274b0dfd17f Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Mon, 24 Feb 2025 23:25:08 -0300 Subject: [PATCH 44/97] Update baileys --- package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index efb3be27..c09f4ca7 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.10", + "version": "2.2.11", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", @@ -57,7 +57,7 @@ "@sentry/node": "^8.47.0", "amqplib": "^0.10.5", "axios": "^1.7.9", - "baileys": "6.7.12", + "baileys": "6.7.13", "class-validator": "^0.14.1", "compression": "^1.7.5", "cors": "^2.8.5", From f21f93e6120eca1345ab9d1209233c9715f0bc18 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Tue, 25 Feb 2025 13:33:55 -0300 Subject: [PATCH 45/97] Remove persistencia de messageUpdate no waba e remove persistencia de contatos na baileys --- package.json | 2 +- .../channel/meta/whatsapp.business.service.ts | 32 ++++++------ .../whatsapp/whatsapp.baileys.service.ts | 50 +++++++++---------- 3 files changed, 42 insertions(+), 42 deletions(-) diff --git a/package.json b/package.json index c09f4ca7..71437be2 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.11", + "version": "2.2.12", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", diff --git a/src/api/integrations/channel/meta/whatsapp.business.service.ts b/src/api/integrations/channel/meta/whatsapp.business.service.ts index 3642c6e3..68ed2c6a 100644 --- a/src/api/integrations/channel/meta/whatsapp.business.service.ts +++ b/src/api/integrations/channel/meta/whatsapp.business.service.ts @@ -511,19 +511,19 @@ export class BusinessStartupService extends ChannelStartupService { if (item.message === null && item.status === undefined) { this.sendDataWebhook(Events.MESSAGES_DELETE, key); - const message: any = { - messageId: item.id, - keyId: key.id, - remoteJid: key.remoteJid, - fromMe: key.fromMe, - participant: key?.remoteJid, - status: 'DELETED', - instanceId: this.instanceId, - }; - - await this.prismaRepository.messageUpdate.create({ - data: message, - }); + // const message: any = { + // messageId: item.id, + // keyId: key.id, + // remoteJid: key.remoteJid, + // fromMe: key.fromMe, + // participant: key?.remoteJid, + // status: 'DELETED', + // instanceId: this.instanceId, + // }; + + // await this.prismaRepository.messageUpdate.create({ + // data: message, + // }); return; } @@ -540,9 +540,9 @@ export class BusinessStartupService extends ChannelStartupService { this.sendDataWebhook(Events.MESSAGES_UPDATE, message); - await this.prismaRepository.messageUpdate.create({ - data: message, - }); + // await this.prismaRepository.messageUpdate.create({ + // data: message, + // }); } } } diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index a08a7378..c740050c 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -1090,9 +1090,9 @@ export class BaileysStartupService extends ChannelStartupService { this.sendDataWebhook(Events.MESSAGES_UPSERT, messageRaw); - const contact = await this.prismaRepository.contact.findFirst({ - where: { remoteJid: received.key.remoteJid, instanceId: this.instanceId }, - }); + // const contact = await this.prismaRepository.contact.findFirst({ + // where: { remoteJid: received.key.remoteJid, instanceId: this.instanceId }, + // }); const contactRaw: { remoteJid: string; pushName: string; profilePicUrl?: string; instanceId: string } = { remoteJid: received.key.remoteJid, @@ -1105,32 +1105,32 @@ export class BaileysStartupService extends ChannelStartupService { continue; } - if (contact) { - this.sendDataWebhook(Events.CONTACTS_UPDATE, contactRaw); + // if (contact) { + // this.sendDataWebhook(Events.CONTACTS_UPDATE, contactRaw); - if (this.configService.get('DATABASE').SAVE_DATA.CONTACTS) - await this.prismaRepository.contact.upsert({ - where: { remoteJid_instanceId: { remoteJid: contactRaw.remoteJid, instanceId: contactRaw.instanceId } }, - create: contactRaw, - update: contactRaw, - }); + // if (this.configService.get('DATABASE').SAVE_DATA.CONTACTS) + // await this.prismaRepository.contact.upsert({ + // where: { remoteJid_instanceId: { remoteJid: contactRaw.remoteJid, instanceId: contactRaw.instanceId } }, + // create: contactRaw, + // update: contactRaw, + // }); - continue; - } + // continue; + // } - this.sendDataWebhook(Events.CONTACTS_UPSERT, contactRaw); + // this.sendDataWebhook(Events.CONTACTS_UPSERT, contactRaw); - if (this.configService.get('DATABASE').SAVE_DATA.CONTACTS) - await this.prismaRepository.contact.upsert({ - where: { - remoteJid_instanceId: { - remoteJid: contactRaw.remoteJid, - instanceId: contactRaw.instanceId, - }, - }, - update: contactRaw, - create: contactRaw, - }); + // if (this.configService.get('DATABASE').SAVE_DATA.CONTACTS) + // await this.prismaRepository.contact.upsert({ + // where: { + // remoteJid_instanceId: { + // remoteJid: contactRaw.remoteJid, + // instanceId: contactRaw.instanceId, + // }, + // }, + // update: contactRaw, + // create: contactRaw, + // }); if (contactRaw.remoteJid.includes('@s.whatsapp')) { await saveOnWhatsappCache([{ remoteJid: contactRaw.remoteJid }]); From b1e8a3e4feda202fde5ceb3e2413ea591c07c761 Mon Sep 17 00:00:00 2001 From: Jonathan Mantovani Date: Thu, 27 Feb 2025 17:11:00 -0300 Subject: [PATCH 46/97] fix sending media in groups where the group number is greater than 23 digits --- src/utils/createJid.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/createJid.ts b/src/utils/createJid.ts index a680e821..3c83bf16 100644 --- a/src/utils/createJid.ts +++ b/src/utils/createJid.ts @@ -51,7 +51,7 @@ export function createJid(number: string): string { .split(':')[0] .split('@')[0]; - if (number.includes('-') && number.length >= 24) { + if (number.includes('-') && number.length >= 23) { number = number.replace(/[^\d-]/g, ''); return `${number}@g.us`; } From c6748f8a03edfbbf99e60a60ccae568330726d85 Mon Sep 17 00:00:00 2001 From: Jonathan Mantovani Date: Fri, 28 Feb 2025 10:40:53 -0300 Subject: [PATCH 47/97] fix message edited by whatsApp web --- .../channel/whatsapp/whatsapp.baileys.service.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index a08a7378..80f7778c 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -936,11 +936,15 @@ export class BaileysStartupService extends ChannelStartupService { if ( (type !== 'notify' && type !== 'append') || - received.message?.protocolMessage || received.message?.pollUpdateMessage || !received?.message ) { - continue; + return; + } else if(received.message?.protocolMessage){ + if(!received.message?.protocolMessage?.editedMessage){ + this.logger.verbose('message rejected'); + return; + } } if (Long.isLong(received.messageTimestamp)) { From 775a5047e1eb03e17fa1ee569a0871a91c450076 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Fri, 28 Feb 2025 17:03:28 -0300 Subject: [PATCH 48/97] Release --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 71437be2..ad0cfa49 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.12", + "version": "2.2.13", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", From be0bfa422b71ff03974e23845dbb018b38dd94a4 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Tue, 25 Mar 2025 09:55:39 -0300 Subject: [PATCH 49/97] Update baileys e altera userDevicesCache --- package.json | 4 ++-- .../channel/whatsapp/whatsapp.baileys.service.ts | 5 ++++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index ad0cfa49..1d8d497d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.13", + "version": "2.2.14", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", @@ -57,7 +57,7 @@ "@sentry/node": "^8.47.0", "amqplib": "^0.10.5", "axios": "^1.7.9", - "baileys": "6.7.13", + "baileys": "6.7.16", "class-validator": "^0.14.1", "compression": "^1.7.5", "cors": "^2.8.5", diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index 500a4f07..5a097f79 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -157,7 +157,10 @@ export class BaileysStartupService extends ChannelStartupService { private authStateProvider: AuthStateProvider; private readonly msgRetryCounterCache: CacheStore = new NodeCache(); - private readonly userDevicesCache: CacheStore = new NodeCache(); + private readonly userDevicesCache: CacheStore = new NodeCache({ + stdTTL: 5 * 60, // 5 minutes, + useClones: false + }); private endSession = false; private logBaileys = this.configService.get('LOG').BAILEYS; From 3c723aa67517661ba4432e197976b6f38da2dc55 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Tue, 25 Mar 2025 16:37:06 -0300 Subject: [PATCH 50/97] Remove getMessage para evitar mensagem de 'Aguardando mensagem...' --- package.json | 2 +- .../integrations/channel/whatsapp/whatsapp.baileys.service.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 1d8d497d..b1c7b980 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.14", + "version": "2.2.15", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index 5a097f79..41cfaf61 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -544,7 +544,7 @@ export class BaileysStartupService extends ChannelStartupService { }, msgRetryCounterCache: this.msgRetryCounterCache, generateHighQualityLinkPreview: true, - getMessage: async (key) => (await this.getMessage(key)) as Promise, + // getMessage: async (key) => (await this.getMessage(key)) as Promise, ...browserOptions, markOnlineOnConnect: this.localSettings.alwaysOnline, retryRequestDelayMs: 350, From 3ba25d506cda756fc7da2301c18f1b105dc57da7 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Sat, 29 Mar 2025 19:42:51 -0300 Subject: [PATCH 51/97] =?UTF-8?q?Ajusta=20edi=C3=A7=C3=A3o=20de=20mensagen?= =?UTF-8?q?s=20e=20remove=20codigo=20n=C3=A3o=20usado?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 2 +- .../whatsapp/whatsapp.baileys.service.ts | 27 ++++++++++--------- 2 files changed, 16 insertions(+), 13 deletions(-) diff --git a/package.json b/package.json index b1c7b980..a90f4785 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.15", + "version": "2.2.16", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index 41cfaf61..f17f0780 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -1159,18 +1159,18 @@ export class BaileysStartupService extends ChannelStartupService { } if (key.remoteJid !== 'status@broadcast') { - let pollUpdates: any; + // let pollUpdates: any; - if (update.pollUpdates) { - const pollCreation = await this.getMessage(key); + // if (update.pollUpdates) { + // const pollCreation = await this.getMessage(key); - if (pollCreation) { - pollUpdates = getAggregateVotesInPollMessage({ - message: pollCreation as proto.IMessage, - pollUpdates: update.pollUpdates, - }); - } - } + // if (pollCreation) { + // pollUpdates = getAggregateVotesInPollMessage({ + // message: pollCreation as proto.IMessage, + // pollUpdates: update.pollUpdates, + // }); + // } + // } // const findMessage = await this.prismaRepository.message.findFirst({ // where: { @@ -1228,7 +1228,7 @@ export class BaileysStartupService extends ChannelStartupService { fromMe: key.fromMe, participant: key?.remoteJid, status: status[update.status], - pollUpdates, + // pollUpdates, instanceId: this.instanceId, }; @@ -3349,7 +3349,10 @@ export class BaileysStartupService extends ChannelStartupService { public async updateMessage(data: UpdateMessageDto) { const jid = createJid(data.number); - const options = await this.formatUpdateMessage(data); + // const options = await this.formatUpdateMessage(data); + const options = { + text: data.text, + } if (!options) { this.logger.error('Message not compatible'); From 0460d72146c7aeee0739e59a91446211ce4710b8 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Thu, 3 Apr 2025 13:03:57 -0300 Subject: [PATCH 52/97] Remove insert de mensagens --- package.json | 2 +- .../channel/meta/whatsapp.business.service.ts | 40 +++++++++---------- 2 files changed, 21 insertions(+), 21 deletions(-) diff --git a/package.json b/package.json index a90f4785..f12d20b2 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.16", + "version": "2.2.17", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", diff --git a/src/api/integrations/channel/meta/whatsapp.business.service.ts b/src/api/integrations/channel/meta/whatsapp.business.service.ts index 68ed2c6a..3caefd38 100644 --- a/src/api/integrations/channel/meta/whatsapp.business.service.ts +++ b/src/api/integrations/channel/meta/whatsapp.business.service.ts @@ -355,19 +355,19 @@ export class BusinessStartupService extends ChannelStartupService { 'Content-Type': mimetype, }); - const createdMessage = await this.prismaRepository.message.create({ - data: messageRaw, - }); + // const createdMessage = await this.prismaRepository.message.create({ + // data: messageRaw, + // }); - await this.prismaRepository.media.create({ - data: { - messageId: createdMessage.id, - instanceId: this.instanceId, - type: mediaType, - fileName: fullName, - mimetype, - }, - }); + // await this.prismaRepository.media.create({ + // data: { + // messageId: createdMessage.id, + // instanceId: this.instanceId, + // type: mediaType, + // fileName: fullName, + // mimetype, + // }, + // }); const mediaUrl = await s3Service.getObjectUrl(fullName); @@ -450,11 +450,11 @@ export class BusinessStartupService extends ChannelStartupService { this.sendDataWebhook(Events.MESSAGES_UPSERT, messageRaw); - if (!this.isMediaMessage(received?.messages[0])) { - await this.prismaRepository.message.create({ - data: messageRaw, - }); - } + // if (!this.isMediaMessage(received?.messages[0])) { + // await this.prismaRepository.message.create({ + // data: messageRaw, + // }); + // } const contact = await this.prismaRepository.contact.findFirst({ where: { instanceId: this.instanceId, remoteJid: key.remoteJid }, @@ -834,9 +834,9 @@ export class BusinessStartupService extends ChannelStartupService { this.sendDataWebhook(Events.SEND_MESSAGE, messageRaw); - await this.prismaRepository.message.create({ - data: messageRaw, - }); + // await this.prismaRepository.message.create({ + // data: messageRaw, + // }); return messageRaw; } catch (error) { From aa1c6df955d7b142cafd42afbd00d09abfffe199 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Tue, 15 Apr 2025 11:49:45 -0300 Subject: [PATCH 53/97] Fork baileys --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index f12d20b2..ac18c511 100644 --- a/package.json +++ b/package.json @@ -57,7 +57,7 @@ "@sentry/node": "^8.47.0", "amqplib": "^0.10.5", "axios": "^1.7.9", - "baileys": "6.7.16", + "baileys": "github:lnmesquita1/Baileys#master-fix", "class-validator": "^0.14.1", "compression": "^1.7.5", "cors": "^2.8.5", From 2273fbd2a09cb88cad80bdefd30f4bbdd902fffe Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Tue, 15 Apr 2025 11:50:37 -0300 Subject: [PATCH 54/97] Update version --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index ac18c511..635a76bf 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.17", + "version": "2.2.18", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", From 970ded7e75c8eb7159a3074a8713352348ac6fd4 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Tue, 15 Apr 2025 12:12:28 -0300 Subject: [PATCH 55/97] KeepAlive undefined --- package.json | 2 +- .../integrations/channel/whatsapp/whatsapp.baileys.service.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 635a76bf..adce834c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.18", + "version": "2.2.19", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index f17f0780..16c8750b 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -551,7 +551,7 @@ export class BaileysStartupService extends ChannelStartupService { maxMsgRetryCount: 4, fireInitQueries: true, connectTimeoutMs: 30_000, - keepAliveIntervalMs: 30_000, + keepAliveIntervalMs: undefined, qrTimeout: 45_000, emitOwnEvents: false, shouldIgnoreJid: (jid) => { From 0113243174966188ab98b6eb820c7b6d7cce7145 Mon Sep 17 00:00:00 2001 From: Lucas Mesquita Date: Tue, 15 Apr 2025 16:51:09 -0300 Subject: [PATCH 56/97] Update node js no dockerfile --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index e4851b6b..c475def3 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM node:20-alpine3.20 AS builder +FROM node:23.11.0-alpine3.20 AS builder RUN apk update && \ apk add git wget curl bash openssl From 2b973a1169bcc050ecf1f14bb42402812fcc8144 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Tue, 15 Apr 2025 17:50:41 -0300 Subject: [PATCH 57/97] =?UTF-8?q?Codigo=20408=20para=20n=C3=A3o=20reconect?= =?UTF-8?q?ar?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 2 +- .../channel/whatsapp/whatsapp.baileys.service.ts | 8 +++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/package.json b/package.json index adce834c..0d743e2d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.19", + "version": "2.2.20", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index 16c8750b..54e6def2 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -307,7 +307,7 @@ export class BaileysStartupService extends ChannelStartupService { if (connection === 'close') { const statusCode = (lastDisconnect?.error as Boom)?.output?.statusCode; - const codesToNotReconnect = [DisconnectReason.loggedOut, DisconnectReason.forbidden, 402, 406]; + const codesToNotReconnect = [DisconnectReason.loggedOut, DisconnectReason.forbidden, 402, 406, 408]; const shouldReconnect = !codesToNotReconnect.includes(statusCode); if (shouldReconnect) { await this.connectToWhatsapp(this.phoneNumber); @@ -2803,7 +2803,8 @@ export class BaileysStartupService extends ChannelStartupService { (jid) => !cachedNumbers.some((cached) => cached.jidOptions.includes(jid)), ); - const verify = await this.client.onWhatsApp(...filteredNumbers); + // const verify = await this.client.onWhatsApp(...filteredNumbers); + const verify = [null]; const users: OnWhatsAppDto[] = await Promise.all( jids.users.map(async (user) => { let numberVerified: (typeof verify)[0] | null = null; @@ -2862,7 +2863,8 @@ export class BaileysStartupService extends ChannelStartupService { const numberJid = numberVerified?.jid || user.jid; return { - exists: !!numberVerified?.exists, + //exists: !!numberVerified?.exists, + exists: true, jid: numberJid, name: contacts.find((c) => c.remoteJid === numberJid)?.pushName, number: user.number, From 64efef6bc2d135ecbddd1ff7c339386295ff7efb Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Tue, 15 Apr 2025 19:04:33 -0300 Subject: [PATCH 58/97] keepAliveIntervalMs para 30_000 --- package.json | 2 +- .../integrations/channel/whatsapp/whatsapp.baileys.service.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 0d743e2d..4e847d6e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.20", + "version": "2.2.21", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index 54e6def2..ed5b506f 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -551,7 +551,7 @@ export class BaileysStartupService extends ChannelStartupService { maxMsgRetryCount: 4, fireInitQueries: true, connectTimeoutMs: 30_000, - keepAliveIntervalMs: undefined, + keepAliveIntervalMs: 30_000, qrTimeout: 45_000, emitOwnEvents: false, shouldIgnoreJid: (jid) => { From 582cd918eb37e46c0ab93ffbee1b285a477cbded Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Wed, 16 Apr 2025 09:42:56 -0300 Subject: [PATCH 59/97] =?UTF-8?q?Retorna=20vers=C3=A3o=20da=20baileys?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 4e847d6e..ae0f916e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.21", + "version": "2.2.22", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", @@ -57,7 +57,7 @@ "@sentry/node": "^8.47.0", "amqplib": "^0.10.5", "axios": "^1.7.9", - "baileys": "github:lnmesquita1/Baileys#master-fix", + "baileys": "6.7.16", "class-validator": "^0.14.1", "compression": "^1.7.5", "cors": "^2.8.5", From 85b41363b0ba552bd75b573f42d65d807d9a49b1 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Wed, 16 Apr 2025 09:52:28 -0300 Subject: [PATCH 60/97] Update dockerfile --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index c475def3..e4851b6b 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM node:23.11.0-alpine3.20 AS builder +FROM node:20-alpine3.20 AS builder RUN apk update && \ apk add git wget curl bash openssl From bec40b3c03f48a6206e542bec0f8f34178445a64 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Wed, 16 Apr 2025 11:17:33 -0300 Subject: [PATCH 61/97] =?UTF-8?q?Ajuste=20verifica=C3=A7=C3=A3o=20de=20num?= =?UTF-8?q?eros?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../channel/whatsapp/whatsapp.baileys.service.ts | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index ed5b506f..2746887f 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -2803,8 +2803,7 @@ export class BaileysStartupService extends ChannelStartupService { (jid) => !cachedNumbers.some((cached) => cached.jidOptions.includes(jid)), ); - // const verify = await this.client.onWhatsApp(...filteredNumbers); - const verify = [null]; + const verify = await this.client.onWhatsApp(...filteredNumbers); const users: OnWhatsAppDto[] = await Promise.all( jids.users.map(async (user) => { let numberVerified: (typeof verify)[0] | null = null; @@ -2863,8 +2862,7 @@ export class BaileysStartupService extends ChannelStartupService { const numberJid = numberVerified?.jid || user.jid; return { - //exists: !!numberVerified?.exists, - exists: true, + exists: !!numberVerified?.exists, jid: numberJid, name: contacts.find((c) => c.remoteJid === numberJid)?.pushName, number: user.number, From a9e27a04af6cf999eed5784b54f6cc109a20182a Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Wed, 16 Apr 2025 11:18:42 -0300 Subject: [PATCH 62/97] Update --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index ae0f916e..ede21e4d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.22", + "version": "2.2.23", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", From f4594eef14c91f0fde7af7a80f64e0b5025ac367 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Fri, 18 Apr 2025 17:06:54 -0300 Subject: [PATCH 63/97] =?UTF-8?q?Cria=20endpoint=20para=20fazer=20count=20?= =?UTF-8?q?da=20instancias=20e=20remove=20verifica=C3=A7=C3=A3o=20do=20sta?= =?UTF-8?q?tusCode=20408?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 2 +- src/api/controllers/instance.controller.ts | 6 ++++++ src/api/guards/auth.guard.ts | 4 ++-- src/api/guards/instance.guard.ts | 2 +- .../channel/whatsapp/whatsapp.baileys.service.ts | 2 +- src/api/routes/instance.router.ts | 10 ++++++++++ 6 files changed, 21 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index ede21e4d..dd2dffc9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.23", + "version": "2.2.24", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", diff --git a/src/api/controllers/instance.controller.ts b/src/api/controllers/instance.controller.ts index 76e7d37e..de9553b3 100644 --- a/src/api/controllers/instance.controller.ts +++ b/src/api/controllers/instance.controller.ts @@ -286,6 +286,12 @@ export class InstanceController { return this.waMonitor.instanceInfo(instanceNames); } + public async countInstances() { + const count = await this.prismaRepository.instance.count(); + + return count; + } + public async setPresence({ instanceName }: InstanceDto, data: SetPresenceDto) { return await this.waMonitor.waInstances[instanceName].setPresence(data); } diff --git a/src/api/guards/auth.guard.ts b/src/api/guards/auth.guard.ts index 9ad20b61..d4467464 100644 --- a/src/api/guards/auth.guard.ts +++ b/src/api/guards/auth.guard.ts @@ -20,7 +20,7 @@ async function apikey(req: Request, _: Response, next: NextFunction) { return next(); } - if ((req.originalUrl.includes('/instance/create') || req.originalUrl.includes('/instance/fetchInstances')) && !key) { + if ((req.originalUrl.includes('/instance/create') || req.originalUrl.includes('/instance/fetchInstances') || req.originalUrl.includes('/instance/countInstances')) && !key) { throw new ForbiddenException('Missing global api key', 'The global api key must be set'); } const param = req.params as unknown as InstanceDto; @@ -34,7 +34,7 @@ async function apikey(req: Request, _: Response, next: NextFunction) { return next(); } } else { - if (req.originalUrl.includes('/instance/fetchInstances') && db.SAVE_DATA.INSTANCE) { + if ((req.originalUrl.includes('/instance/fetchInstances') || req.originalUrl.includes('/instance/countInstances')) && db.SAVE_DATA.INSTANCE) { const instanceByKey = await prismaRepository.instance.findFirst({ where: { token: key }, }); diff --git a/src/api/guards/instance.guard.ts b/src/api/guards/instance.guard.ts index e692f362..7d4a4dec 100644 --- a/src/api/guards/instance.guard.ts +++ b/src/api/guards/instance.guard.ts @@ -23,7 +23,7 @@ async function getInstance(instanceName: string) { } export async function instanceExistsGuard(req: Request, _: Response, next: NextFunction) { - if (req.originalUrl.includes('/instance/create') || req.originalUrl.includes('/instance/fetchInstances')) { + if (req.originalUrl.includes('/instance/create') || req.originalUrl.includes('/instance/fetchInstances') || req.originalUrl.includes('/instance/countInstances')) { return next(); } diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index 2746887f..f17f0780 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -307,7 +307,7 @@ export class BaileysStartupService extends ChannelStartupService { if (connection === 'close') { const statusCode = (lastDisconnect?.error as Boom)?.output?.statusCode; - const codesToNotReconnect = [DisconnectReason.loggedOut, DisconnectReason.forbidden, 402, 406, 408]; + const codesToNotReconnect = [DisconnectReason.loggedOut, DisconnectReason.forbidden, 402, 406]; const shouldReconnect = !codesToNotReconnect.includes(statusCode); if (shouldReconnect) { await this.connectToWhatsapp(this.phoneNumber); diff --git a/src/api/routes/instance.router.ts b/src/api/routes/instance.router.ts index dd990c3b..19a3ae40 100644 --- a/src/api/routes/instance.router.ts +++ b/src/api/routes/instance.router.ts @@ -67,6 +67,16 @@ export class InstanceRouter extends RouterBroker { return res.status(HttpStatus.OK).json(response); }) + .get(this.routerPath('countInstances', false), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: null, + ClassRef: InstanceDto, + execute: () => instanceController.countInstances(), + }); + + return res.status(HttpStatus.OK).json(response); + }) .post(this.routerPath('setPresence'), ...guards, async (req, res) => { const response = await this.dataValidate({ request: req, From fbc933727141756239cd95c45ee39696bad25025 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Mon, 21 Apr 2025 20:35:49 -0300 Subject: [PATCH 64/97] Endpoint de instancia pelo nome --- src/api/controllers/instance.controller.ts | 22 +++++++++++++++++++++- src/api/guards/auth.guard.ts | 4 ++-- src/api/guards/instance.guard.ts | 2 +- src/api/routes/instance.router.ts | 10 ++++++++++ 4 files changed, 34 insertions(+), 4 deletions(-) diff --git a/src/api/controllers/instance.controller.ts b/src/api/controllers/instance.controller.ts index de9553b3..78c9239b 100644 --- a/src/api/controllers/instance.controller.ts +++ b/src/api/controllers/instance.controller.ts @@ -286,9 +286,29 @@ export class InstanceController { return this.waMonitor.instanceInfo(instanceNames); } + public async getInstanceByName({ instanceName }: InstanceDto) { + const instanceByName = await this.prismaRepository.instance.findFirst({ + where: { + name: instanceName, + }, + }); + + if (!instanceByName) { + return null; + } + + const response = { + id: instanceByName.id, + name: instanceByName.name, + ownerJid: instanceByName.ownerJid, + connectionStatus: instanceByName.connectionStatus, + profileName: instanceByName.profileName, + } + return response; + } + public async countInstances() { const count = await this.prismaRepository.instance.count(); - return count; } diff --git a/src/api/guards/auth.guard.ts b/src/api/guards/auth.guard.ts index d4467464..c890a9dd 100644 --- a/src/api/guards/auth.guard.ts +++ b/src/api/guards/auth.guard.ts @@ -20,7 +20,7 @@ async function apikey(req: Request, _: Response, next: NextFunction) { return next(); } - if ((req.originalUrl.includes('/instance/create') || req.originalUrl.includes('/instance/fetchInstances') || req.originalUrl.includes('/instance/countInstances')) && !key) { + if ((req.originalUrl.includes('/instance/create') || req.originalUrl.includes('/instance/fetchInstances') || req.originalUrl.includes('/instance/countInstances') || req.originalUrl.includes('/instance/instanceByName')) && !key) { throw new ForbiddenException('Missing global api key', 'The global api key must be set'); } const param = req.params as unknown as InstanceDto; @@ -34,7 +34,7 @@ async function apikey(req: Request, _: Response, next: NextFunction) { return next(); } } else { - if ((req.originalUrl.includes('/instance/fetchInstances') || req.originalUrl.includes('/instance/countInstances')) && db.SAVE_DATA.INSTANCE) { + if ((req.originalUrl.includes('/instance/fetchInstances') || req.originalUrl.includes('/instance/countInstances') || req.originalUrl.includes('/instance/instanceByName')) && db.SAVE_DATA.INSTANCE) { const instanceByKey = await prismaRepository.instance.findFirst({ where: { token: key }, }); diff --git a/src/api/guards/instance.guard.ts b/src/api/guards/instance.guard.ts index 7d4a4dec..32736cd8 100644 --- a/src/api/guards/instance.guard.ts +++ b/src/api/guards/instance.guard.ts @@ -23,7 +23,7 @@ async function getInstance(instanceName: string) { } export async function instanceExistsGuard(req: Request, _: Response, next: NextFunction) { - if (req.originalUrl.includes('/instance/create') || req.originalUrl.includes('/instance/fetchInstances') || req.originalUrl.includes('/instance/countInstances')) { + if (req.originalUrl.includes('/instance/create') || req.originalUrl.includes('/instance/fetchInstances') || req.originalUrl.includes('/instance/countInstances') || req.originalUrl.includes('/instance/instanceByName')) { return next(); } diff --git a/src/api/routes/instance.router.ts b/src/api/routes/instance.router.ts index 19a3ae40..bd62fac3 100644 --- a/src/api/routes/instance.router.ts +++ b/src/api/routes/instance.router.ts @@ -77,6 +77,16 @@ export class InstanceRouter extends RouterBroker { return res.status(HttpStatus.OK).json(response); }) + .get(this.routerPath('instanceByName', false), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: null, + ClassRef: InstanceDto, + execute: (instance) => instanceController.getInstanceByName(instance), + }); + + return res.status(HttpStatus.OK).json(response); + }) .post(this.routerPath('setPresence'), ...guards, async (req, res) => { const response = await this.dataValidate({ request: req, From d6d246b19081b7f7c8b5543432acf784b78c9a2e Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Mon, 21 Apr 2025 20:36:10 -0300 Subject: [PATCH 65/97] =?UTF-8?q?Update=20vers=C3=A3o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index dd2dffc9..ae532b2a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.24", + "version": "2.2.25", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", From d094595ec8f8497e49f20b58b23decc28f3f4fb0 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Tue, 22 Apr 2025 11:37:10 -0300 Subject: [PATCH 66/97] Baileys pierre --- package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index ae532b2a..b316312c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.25", + "version": "2.2.26", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", @@ -57,7 +57,7 @@ "@sentry/node": "^8.47.0", "amqplib": "^0.10.5", "axios": "^1.7.9", - "baileys": "6.7.16", + "baileys": "github:splitpierre/Baileys#master", "class-validator": "^0.14.1", "compression": "^1.7.5", "cors": "^2.8.5", From dff9c8abf72adf4efb2f5811b9aaeca780147f28 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Tue, 22 Apr 2025 14:21:07 -0300 Subject: [PATCH 67/97] Corrige delete de mensagens --- .../whatsapp/whatsapp.baileys.service.ts | 57 ++++++++----------- 1 file changed, 24 insertions(+), 33 deletions(-) diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index f17f0780..de0fcdc0 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -3007,40 +3007,31 @@ export class BaileysStartupService extends ChannelStartupService { if (response) { const messageId = response.message?.protocolMessage?.key?.id; if (messageId) { - const isLogicalDeleted = configService.get('DATABASE').DELETE_DATA.LOGICAL_MESSAGE_DELETE; - let message = await this.prismaRepository.message.findUnique({ - where: { id: messageId }, - }); - if (isLogicalDeleted) { - if (!message) return response; - const existingKey = typeof message?.key === 'object' && message.key !== null ? message.key : {}; - message = await this.prismaRepository.message.update({ - where: { id: messageId }, - data: { - key: { - ...existingKey, - deleted: true, - }, - }, - }); - } else { - await this.prismaRepository.message.deleteMany({ - where: { - id: messageId, - }, - }); - } + // const isLogicalDeleted = configService.get('DATABASE').DELETE_DATA.LOGICAL_MESSAGE_DELETE; + // let message = await this.prismaRepository.message.findUnique({ + // where: { id: messageId }, + // }); + // if (isLogicalDeleted) { + // if (!message) return response; + // const existingKey = typeof message?.key === 'object' && message.key !== null ? message.key : {}; + // message = await this.prismaRepository.message.update({ + // where: { id: messageId }, + // data: { + // key: { + // ...existingKey, + // deleted: true, + // }, + // }, + // }); + // } else { + // await this.prismaRepository.message.deleteMany({ + // where: { + // id: messageId, + // }, + // }); + // } this.sendDataWebhook(Events.MESSAGES_DELETE, { - id: message.id, - instanceId: message.instanceId, - key: message.key, - messageType: message.messageType, - status: message.status, - source: message.source, - messageTimestamp: message.messageTimestamp, - pushName: message.pushName, - participant: message.participant, - message: message.message, + id: messageId, }); } } From 917e60bd97ac3253174689e6eb2eaef3d8818a0a Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Mon, 28 Apr 2025 18:48:33 -0300 Subject: [PATCH 68/97] =?UTF-8?q?Endpoint=20de=20download=20de=20m=C3=ADdi?= =?UTF-8?q?as=20direto=20da=20baileys?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 2 +- .../channel/whatsapp/baileys.controller.ts | 6 ++++++ .../channel/whatsapp/baileys.router.ts | 10 ++++++++++ .../channel/whatsapp/whatsapp.baileys.service.ts | 14 ++++++++++++++ 4 files changed, 31 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index b316312c..851f8662 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.26", + "version": "2.2.27", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", diff --git a/src/api/integrations/channel/whatsapp/baileys.controller.ts b/src/api/integrations/channel/whatsapp/baileys.controller.ts index ee547338..7c5dd4ad 100644 --- a/src/api/integrations/channel/whatsapp/baileys.controller.ts +++ b/src/api/integrations/channel/whatsapp/baileys.controller.ts @@ -40,6 +40,12 @@ export class BaileysController { return instance.baileysGenerateMessageTag(); } + public async downloadMediaMessage({ instanceName }: InstanceDto, body: any) { + const instance = this.waMonitor.waInstances[instanceName]; + + return instance.baileysDownloadMediaMessage(body); + } + public async sendNode({ instanceName }: InstanceDto, body: any) { const instance = this.waMonitor.waInstances[instanceName]; diff --git a/src/api/integrations/channel/whatsapp/baileys.router.ts b/src/api/integrations/channel/whatsapp/baileys.router.ts index 04a1d565..72e6a8b6 100644 --- a/src/api/integrations/channel/whatsapp/baileys.router.ts +++ b/src/api/integrations/channel/whatsapp/baileys.router.ts @@ -69,6 +69,16 @@ export class BaileysRouter extends RouterBroker { res.status(HttpStatus.OK).json(response); }) + .post(this.routerPath('downloadMediaMessage'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => baileysController.downloadMediaMessage(instance, req.body), + }); + + res.status(HttpStatus.OK).json(response); + }) .post(this.routerPath('sendNode'), ...guards, async (req, res) => { const response = await this.dataValidate({ request: req, diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index de0fcdc0..c52c7275 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -3959,6 +3959,20 @@ export class BaileysStartupService extends ChannelStartupService { return response; } + public async baileysDownloadMediaMessage(message: proto.IWebMessageInfo) { + const buffer = await downloadMediaMessage( + message, + 'buffer', + {}, + { + logger: P({ level: 'error' }) as any, + reuploadRequest: this.client.updateMediaMessage, + }, + ); + + return buffer.toString('base64');; + } + public async baileysSignalRepositoryDecryptMessage(jid: string, type: 'pkmsg' | 'msg', ciphertext: string) { try { const ciphertextBuffer = Buffer.from(ciphertext, 'base64'); From 7b6438ae0dfb939e3193c6bfdde7f746a4a00711 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Wed, 30 Apr 2025 02:44:32 -0300 Subject: [PATCH 69/97] Compatibilidade webhook meta V1 --- src/api/integrations/channel/meta/meta.router.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/api/integrations/channel/meta/meta.router.ts b/src/api/integrations/channel/meta/meta.router.ts index b0fc43ce..7127d9af 100644 --- a/src/api/integrations/channel/meta/meta.router.ts +++ b/src/api/integrations/channel/meta/meta.router.ts @@ -16,6 +16,17 @@ export class MetaRouter extends RouterBroker { const { body } = req; const response = await metaController.receiveWebhook(body); + return res.status(200).json(response); + }) + .get(this.routerPath('webhook/whatsapp', false), async (req, res) => { + if (req.query['hub.verify_token'] === configService.get('WA_BUSINESS').TOKEN_WEBHOOK) + res.send(req.query['hub.challenge']); + else res.send('Error, wrong validation token'); + }) + .post(this.routerPath('webhook/whatsapp', false), async (req, res) => { + const { body } = req; + const response = await metaController.receiveWebhook(body); + return res.status(200).json(response); }); } From 183c88d18b31c25ae6955b9044596eb0a26c88c7 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Wed, 30 Apr 2025 02:46:07 -0300 Subject: [PATCH 70/97] =?UTF-8?q?Update=20vers=C3=A3o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 851f8662..fc1b1f74 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.27", + "version": "2.2.28", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", @@ -57,7 +57,7 @@ "@sentry/node": "^8.47.0", "amqplib": "^0.10.5", "axios": "^1.7.9", - "baileys": "github:splitpierre/Baileys#master", + "baileys": "file:../Baileys", "class-validator": "^0.14.1", "compression": "^1.7.5", "cors": "^2.8.5", From bd47e9b515a5ab6d000939e45a06d30993e84990 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Wed, 30 Apr 2025 02:53:08 -0300 Subject: [PATCH 71/97] Update lib --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index fc1b1f74..de308701 100644 --- a/package.json +++ b/package.json @@ -57,7 +57,7 @@ "@sentry/node": "^8.47.0", "amqplib": "^0.10.5", "axios": "^1.7.9", - "baileys": "file:../Baileys", + "baileys": "github:splitpierre/Baileys#master", "class-validator": "^0.14.1", "compression": "^1.7.5", "cors": "^2.8.5", From a62edbc4b9876d34e0d716be6309c32ed66afae6 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Fri, 2 May 2025 19:31:40 -0300 Subject: [PATCH 72/97] Update baileys --- package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index de308701..1ad1a918 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.28", + "version": "2.2.29", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", @@ -57,7 +57,7 @@ "@sentry/node": "^8.47.0", "amqplib": "^0.10.5", "axios": "^1.7.9", - "baileys": "github:splitpierre/Baileys#master", + "baileys": "github:WhiskeySockets/Baileys#master", "class-validator": "^0.14.1", "compression": "^1.7.5", "cors": "^2.8.5", From ab1d802da6578fb955922bf96331f598b81159f7 Mon Sep 17 00:00:00 2001 From: Jonathan Mantovani Date: Tue, 13 May 2025 12:35:58 -0300 Subject: [PATCH 73/97] Log para identificar erros em webhook meta --- src/api/integrations/channel/meta/meta.controller.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/api/integrations/channel/meta/meta.controller.ts b/src/api/integrations/channel/meta/meta.controller.ts index 558a22e9..538febb6 100644 --- a/src/api/integrations/channel/meta/meta.controller.ts +++ b/src/api/integrations/channel/meta/meta.controller.ts @@ -15,6 +15,7 @@ export class MetaController extends ChannelController implements ChannelControll integrationEnabled: boolean; public async receiveWebhook(data: any) { + this.logger.info("VALOR DE DATA META: " + JSON.stringify(data)) if (data.object === 'whatsapp_business_account') { if (data.entry[0]?.changes[0]?.field === 'message_template_status_update') { const template = await this.prismaRepository.template.findFirst({ From ce09753f15f76f4eab7bd2e792511d307c7d2ca0 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Tue, 13 May 2025 14:03:00 -0300 Subject: [PATCH 74/97] =?UTF-8?q?Update=20vers=C3=A3o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 1ad1a918..16c8a28a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.29", + "version": "2.2.30", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", From 497554e03f2199be918b73ad38de0db6ae125066 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Wed, 14 May 2025 19:40:56 -0300 Subject: [PATCH 75/97] Retorno de erros da meta via webhook --- src/api/integrations/channel/meta/whatsapp.business.service.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/api/integrations/channel/meta/whatsapp.business.service.ts b/src/api/integrations/channel/meta/whatsapp.business.service.ts index 3caefd38..ea3c4d14 100644 --- a/src/api/integrations/channel/meta/whatsapp.business.service.ts +++ b/src/api/integrations/channel/meta/whatsapp.business.service.ts @@ -535,6 +535,7 @@ export class BusinessStartupService extends ChannelStartupService { fromMe: key.fromMe, participant: key?.remoteJid, status: item.status.toUpperCase(), + errors: item.errors, instanceId: this.instanceId, }; From 412f60f301bf04aa2170c82131266117f00a1aba Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Mesquita Date: Wed, 14 May 2025 19:45:37 -0300 Subject: [PATCH 76/97] =?UTF-8?q?Update=20vers=C3=A3o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 2 +- .../whatsapp/whatsapp.baileys.service.ts | 48 ++++++++++++++++++- 2 files changed, 47 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index 16c8a28a..6865e31a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.30", + "version": "2.2.31", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index c52c7275..7ae3bd3f 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -595,7 +595,7 @@ export class BaileysStartupService extends ChannelStartupService { this.eventHandler(); this.client.ws.on('CB:call', (packet) => { - console.log('CB:call', packet); + // console.log('CB:call', packet); const payload = { event: 'CB:call', packet: packet, @@ -604,7 +604,7 @@ export class BaileysStartupService extends ChannelStartupService { }); this.client.ws.on('CB:ack,class:call', (packet) => { - console.log('CB:ack,class:call', packet); + // console.log('CB:ack,class:call', packet); const payload = { event: 'CB:ack,class:call', packet: packet, @@ -3761,6 +3761,50 @@ export class BaileysStartupService extends ChannelStartupService { const contentType = getContentType(message.message); const contentMsg = message?.message[contentType] as any; + // const teste = { + // messageContextInfo: { + // deviceListMetadata: { + // senderKeyHash: "01JLmXAKQXesWw==", + // senderTimestamp: "1745146541", + // recipientKeyHash: "MqF4zcbEFrI3lw==", + // recipientTimestamp: "1745572827" + // }, + // deviceListMetadataVersion: 2 + // }, + // ephemeralMessage: { + // message: { + // documentWithCaptionMessage: { + // message: { + // documentMessage: { + // url: "https://mmg.whatsapp.net/v/t62.7119-24/34722357_2213164112419645_2947918714698327654_n.enc?ccb=11-4&oh=01_Q5Aa1QGXkA2FdYMVuYn-mxcn4X3gyVqtOBWH22kp62HdG_P5Ug&oe=68331230&_nc_sid=5e03e0&mms3=true", + // mimetype: "application/pdf", + // title: "Pedido 124040.pdf", + // fileSha256: "CERdYOygRTw1fkxfJ2v7R3YbdfJadzxrzmTZ0Mal99U=", + // fileLength: "74798", + // pageCount: 1, + // mediaKey: "qpkol332m0Kc8Qe5/VQQ/a56bM8ZrDjbx2G9frFvbBE=", + // fileName: "Pedido 124040.pdf", + // fileEncSha256: "/z7vSGbT3QKAJ/HsjFm24BWiN4lH/75TwjFVMqbMA7k=", + // directPath: "/v/t62.7119-24/34722357_2213164112419645_2947918714698327654_n.enc?ccb=11-4&oh=01_Q5Aa1QGXkA2FdYMVuYn-mxcn4X3gyVqtOBWH22kp62HdG_P5Ug&oe=68331230&_nc_sid=5e03e0", + // mediaKeyTimestamp: "1745593130", + // jpegThumbnail: "/9j/4AAQSkZJRgABAQAAAQABAAD/4gHYSUNDX1BST0ZJTEUAAQEAAAHIAAAAAAQwAABtbnRyUkdCIFhZWiAH4AABAAEAAAAAAABhY3NwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAA9tYAAQAAAADTLQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAlkZXNjAAAA8AAAACRyWFlaAAABFAAAABRnWFlaAAABKAAAABRiWFlaAAABPAAAABR3dHB0AAABUAAAABRyVFJDAAABZAAAAChnVFJDAAABZAAAAChiVFJDAAABZAAAAChjcHJ0AAABjAAAADxtbHVjAAAAAAAAAAEAAAAMZW5VUwAAAAgAAAAcAHMAUgBHAEJYWVogAAAAAAAAb6IAADj1AAADkFhZWiAAAAAAAABimQAAt4UAABjaWFlaIAAAAAAAACSgAAAPhAAAts9YWVogAAAAAAAA9tYAAQAAAADTLXBhcmEAAAAAAAQAAAACZmYAAPKnAAANWQAAE9AAAApbAAAAAAAAAABtbHVjAAAAAAAAAAEAAAAMZW5VUwAAACAAAAAcAEcAbwBvAGcAbABlACAASQBuAGMALgAgADIAMAAxADb/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/2wBDAQMDAwQDBAgEBAgQCwkLEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBD/wAARCAAaABIDASIAAhEBAxEB/8QAGAABAQEBAQAAAAAAAAAAAAAAAAQIBQn/xAAkEAACAQUAAQQDAQAAAAAAAAABAgMABAUREiEGFSMkCCIyM//EABQBAQAAAAAAAAAAAAAAAAAAAAD/xAAUEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIRAxEAPwD1CsEyi3N4L6YSQCb63wBG4I6O2DnoAtyNqh/Q7DbDGPOZu/xmVxFlb2djLBlJJ7YPPdSxyC5WFpYkREhdWVljlLOzpwEGg5bQ6NhKs0DOslzIBNMnVxCYmBWRlIClV2o1pW1plCsCwPRrIB8EboJMXNk5cZaS5m0trXIPBG13BazvcQxTFR2kcrJG0iBtgOUQsACVXegqylApWMx689cHLQxn1nneD+RrYPn3GbXt3Mv09df4eB8X8eB4rZlApSlB/9k=", + // contextInfo: { + // forwardingScore: 1, + // isForwarded: true, + // expiration: 7776000, + // ephemeralSettingTimestamp: "1730124480", + // disappearingMode: { + // initiator: "CHANGED_IN_CHAT" + // } + // }, + // caption: "Pedido 124040.pdf" + // } + // } + // } + // } + // } + // } + const messageRaw = { key: message.key, pushName: message.pushName, From b2dc0da63b259579bf7a4dca7dae2ee49f1dba9e Mon Sep 17 00:00:00 2001 From: Lucas Mesquita Date: Wed, 28 May 2025 08:07:24 -0300 Subject: [PATCH 77/97] Update baileys --- package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 6865e31a..a30d204a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.31", + "version": "2.2.32", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", @@ -57,7 +57,7 @@ "@sentry/node": "^8.47.0", "amqplib": "^0.10.5", "axios": "^1.7.9", - "baileys": "github:WhiskeySockets/Baileys#master", + "baileys": "6.7.18", "class-validator": "^0.14.1", "compression": "^1.7.5", "cors": "^2.8.5", From f822ee5335d02472cd939d51dbe47dff87392831 Mon Sep 17 00:00:00 2001 From: Lucas Mesquita Date: Sat, 31 May 2025 17:12:11 -0300 Subject: [PATCH 78/97] Remove chamada do evento SEND_MESSAGE --- package.json | 2 +- .../integrations/channel/meta/whatsapp.business.service.ts | 2 +- .../channel/whatsapp/whatsapp.baileys.service.ts | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index a30d204a..51cc6089 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.32", + "version": "2.2.33", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", diff --git a/src/api/integrations/channel/meta/whatsapp.business.service.ts b/src/api/integrations/channel/meta/whatsapp.business.service.ts index ea3c4d14..ff7db190 100644 --- a/src/api/integrations/channel/meta/whatsapp.business.service.ts +++ b/src/api/integrations/channel/meta/whatsapp.business.service.ts @@ -833,7 +833,7 @@ export class BusinessStartupService extends ChannelStartupService { this.logger.log(messageRaw); - this.sendDataWebhook(Events.SEND_MESSAGE, messageRaw); + //this.sendDataWebhook(Events.SEND_MESSAGE, messageRaw); // await this.prismaRepository.message.create({ // data: messageRaw, diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index 7ae3bd3f..301171e5 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -475,7 +475,7 @@ export class BaileysStartupService extends ChannelStartupService { } else { const baileysVersion = await fetchLatestBaileysVersion(); version = baileysVersion.version; - log = `Baileys version: ${version}`; + log = `Latest Baileys version: ${version}`; } const integrationData = await this.prismaRepository.instance.findUnique({ @@ -488,7 +488,7 @@ export class BaileysStartupService extends ChannelStartupService { ? integrationData.webVersion.split('.').map(Number) : version - this.logger.info(`WhatsApp webVersion: ${webVersion}`); + this.logger.info(`Using WhatsApp webVersion: ${webVersion}`); this.logger.info(log); @@ -1984,7 +1984,7 @@ export class BaileysStartupService extends ChannelStartupService { messageRaw.groupInfo = groupInfo; this.logger.log(messageRaw); - this.sendDataWebhook(Events.SEND_MESSAGE, messageRaw); + // this.sendDataWebhook(Events.SEND_MESSAGE, messageRaw); return messageRaw; } catch (error) { From 7cc42a30c1b9ad4f405bb4dc2f7369222df23855 Mon Sep 17 00:00:00 2001 From: Jonathan Mantovani Date: Wed, 4 Jun 2025 22:10:35 -0300 Subject: [PATCH 79/97] =?UTF-8?q?Corrige=20parse=20de=20quoted=20e=20adici?= =?UTF-8?q?ona=20retorno=20de=20ID=20ap=C3=B3s=20upload=20de=20m=C3=ADdia?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../channel/meta/whatsapp.business.service.ts | 21 +++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/src/api/integrations/channel/meta/whatsapp.business.service.ts b/src/api/integrations/channel/meta/whatsapp.business.service.ts index ff7db190..cc7b6193 100644 --- a/src/api/integrations/channel/meta/whatsapp.business.service.ts +++ b/src/api/integrations/channel/meta/whatsapp.business.service.ts @@ -635,14 +635,22 @@ export class BusinessStartupService extends ChannelStartupService { let webhookUrl: any; const linkPreview = options?.linkPreview != false ? undefined : false; if (options?.quoted) { - const m = options?.quoted; - + let m = options.quoted; + + if (typeof m === "string") { + try { + m = JSON.parse(m); + } catch (error) { + console.error("Erro ao fazer parse do quoted:", error); + throw "Invalid quoted format"; + } + } const msg = m?.key; if (!msg) { - throw 'Message not found'; + throw "Message not found"; } - + quoted = msg; } if (options?.webhookUrl) { @@ -883,13 +891,14 @@ export class BusinessStartupService extends ChannelStartupService { formData, { headers }, ); - + this.logger.log(`Media uploaded successfully: ${res?.data}`); + + return res?.data?.id; } catch (error) { if (error.response) { this.logger.info(JSON.stringify(error.response.data)); } } - return res.data.id; } protected async prepareMediaMessage(mediaMessage: MediaMessage) { From 6b0a6ace199cbd0866fd5f16efef7b4adeb04f1d Mon Sep 17 00:00:00 2001 From: Lucas Mesquita Date: Fri, 6 Jun 2025 13:54:09 -0300 Subject: [PATCH 80/97] =?UTF-8?q?Update=20vers=C3=A3o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 2 +- src/api/integrations/channel/meta/meta.controller.ts | 2 +- .../integrations/channel/meta/whatsapp.business.service.ts | 5 ++--- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index 51cc6089..3b3221c3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.33", + "version": "2.2.34", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", diff --git a/src/api/integrations/channel/meta/meta.controller.ts b/src/api/integrations/channel/meta/meta.controller.ts index 538febb6..be2c9613 100644 --- a/src/api/integrations/channel/meta/meta.controller.ts +++ b/src/api/integrations/channel/meta/meta.controller.ts @@ -15,7 +15,7 @@ export class MetaController extends ChannelController implements ChannelControll integrationEnabled: boolean; public async receiveWebhook(data: any) { - this.logger.info("VALOR DE DATA META: " + JSON.stringify(data)) + this.logger.info('VALOR DE DATA META: ' + JSON.stringify(data)) if (data.object === 'whatsapp_business_account') { if (data.entry[0]?.changes[0]?.field === 'message_template_status_update') { const template = await this.prismaRepository.template.findFirst({ diff --git a/src/api/integrations/channel/meta/whatsapp.business.service.ts b/src/api/integrations/channel/meta/whatsapp.business.service.ts index cc7b6193..e92cb884 100644 --- a/src/api/integrations/channel/meta/whatsapp.business.service.ts +++ b/src/api/integrations/channel/meta/whatsapp.business.service.ts @@ -26,7 +26,6 @@ import axios from 'axios'; import { arrayUnique, isURL } from 'class-validator'; import EventEmitter2 from 'eventemitter2'; import FormData from 'form-data'; -import { createReadStream } from 'fs'; import mimeTypes from 'mime-types'; import { join } from 'path'; @@ -637,12 +636,12 @@ export class BusinessStartupService extends ChannelStartupService { if (options?.quoted) { let m = options.quoted; - if (typeof m === "string") { + if (typeof m === 'string') { try { m = JSON.parse(m); } catch (error) { console.error("Erro ao fazer parse do quoted:", error); - throw "Invalid quoted format"; + throw 'Invalid quoted format'; } } const msg = m?.key; From 4806b426808393f90779288feca2fe06c43a6d8f Mon Sep 17 00:00:00 2001 From: Lucas Mesquita Date: Fri, 6 Jun 2025 15:31:18 -0300 Subject: [PATCH 81/97] Receber location na api oficial --- .../channel/meta/whatsapp.business.service.ts | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/api/integrations/channel/meta/whatsapp.business.service.ts b/src/api/integrations/channel/meta/whatsapp.business.service.ts index e92cb884..482114c0 100644 --- a/src/api/integrations/channel/meta/whatsapp.business.service.ts +++ b/src/api/integrations/channel/meta/whatsapp.business.service.ts @@ -184,6 +184,20 @@ export class BusinessStartupService extends ChannelStartupService { return content; } + private messageLocationJson(received: any) { + const message = received.messages[0]; + let content: any = { + locationMessage: { + degreesLatitude: message.location.latitude, + degreesLongitude: message.location.longitude, + address: message.location.address, + name: message.location.name, + }, + }; + message.context ? (content = { ...content, contextInfo: { stanzaId: message.context.id } }) : content; + return content; + } + private messageTextJson(received: any) { let content: any; const message = received.messages[0]; @@ -432,6 +446,19 @@ export class BusinessStartupService extends ChannelStartupService { source: 'unknown', instanceId: this.instanceId, }; + } else if (received?.messages[0].location) { + messageRaw = { + key, + pushName, + message: { + ...this.messageLocationJson(received), + }, + contextInfo: this.messageLocationJson(received)?.contextInfo, + messageType: 'locationMessage', + messageTimestamp: parseInt(received.messages[0].timestamp) as number, + source: 'unknown', + instanceId: this.instanceId, + }; } else { messageRaw = { key, From 88ef1b77a2c1b6734fa8164a61fa6572a8e80603 Mon Sep 17 00:00:00 2001 From: Lucas Mesquita Date: Fri, 6 Jun 2025 15:31:48 -0300 Subject: [PATCH 82/97] =?UTF-8?q?Update=20vers=C3=A3o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 3b3221c3..5721c635 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.34", + "version": "2.2.35", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", From a34a17d760112a67a0da71bab29d99d81dfde524 Mon Sep 17 00:00:00 2001 From: Jonathan Mantovani Date: Tue, 17 Jun 2025 12:10:34 -0300 Subject: [PATCH 83/97] =?UTF-8?q?logs=20para=20identificar=20o=20valor=20d?= =?UTF-8?q?e=20contacts=20que=20est=C3=A1=20vindo=20da=20baileys?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../channel/whatsapp/whatsapp.baileys.service.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index 301171e5..06850047 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -710,6 +710,7 @@ export class BaileysStartupService extends ChannelStartupService { private readonly contactHandle = { 'contacts.upsert': async (contacts: Contact[]) => { try { + this.logger.info(`VALOR DE CONTACT EM contacts.upsert: ${contacts}`) const contactsRaw: any = contacts.map((contact) => ({ remoteJid: contact.id, pushName: contact?.name || contact?.verifiedName || contact.id.split('@')[0], @@ -825,6 +826,8 @@ export class BaileysStartupService extends ChannelStartupService { `recv ${chats.length} chats, ${contacts.length} contacts, ${messages.length} msgs (is latest: ${isLatest}, progress: ${progress}%), type: ${syncType}`, ); + this.logger.info(`VALOR DE CONTACTS EM HISTORY: ${JSON.stringify(contacts)}`) + const messagesRaw: any[] = []; for (const m of messages) { @@ -886,6 +889,8 @@ export class BaileysStartupService extends ChannelStartupService { // } // } + this.logger.info("VALOR DA MENSAGEM: " + JSON.stringify(received)) + if (received.message?.protocolMessage?.editedMessage || received.message?.editedMessage?.message) { const editedMessage = received.message?.protocolMessage || received.message?.editedMessage?.message?.protocolMessage; From 153cd791e9be7bb64cdac6163d776285d7286bc5 Mon Sep 17 00:00:00 2001 From: Jonathan Mantovani Date: Wed, 18 Jun 2025 13:40:09 -0300 Subject: [PATCH 84/97] Remove download midia meta --- .../integrations/channel/meta/whatsapp.business.service.ts | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/api/integrations/channel/meta/whatsapp.business.service.ts b/src/api/integrations/channel/meta/whatsapp.business.service.ts index 482114c0..7446fafb 100644 --- a/src/api/integrations/channel/meta/whatsapp.business.service.ts +++ b/src/api/integrations/channel/meta/whatsapp.business.service.ts @@ -389,10 +389,6 @@ export class BusinessStartupService extends ChannelStartupService { } catch (error) { this.logger.error(['Error on upload file to minio', error?.message, error?.stack]); } - } else { - const buffer = await this.downloadMediaMessage(received?.messages[0]); - - messageRaw.message.base64 = buffer.toString('base64'); } } else if (received?.messages[0].interactive) { messageRaw = { From 46db0a2d19304894723b1e795e9a4331cc46fe9d Mon Sep 17 00:00:00 2001 From: Lucas Mesquita Date: Wed, 18 Jun 2025 13:50:35 -0300 Subject: [PATCH 85/97] =?UTF-8?q?Update=20vers=C3=A3o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 5721c635..ae03c99c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.35", + "version": "2.2.36", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", From 520519c19463ea6c7df6cf50ed77b18a892a677b Mon Sep 17 00:00:00 2001 From: Jonathan Mantovani Date: Fri, 20 Jun 2025 14:51:18 -0300 Subject: [PATCH 86/97] fix: substitui contatos com remoteJid @lid por senderPn --- package.json | 2 +- .../whatsapp/whatsapp.baileys.service.ts | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 5721c635..c6335091 100644 --- a/package.json +++ b/package.json @@ -57,7 +57,7 @@ "@sentry/node": "^8.47.0", "amqplib": "^0.10.5", "axios": "^1.7.9", - "baileys": "6.7.18", + "baileys": "github:WhiskeySockets/Baileys#f8a538eee293c38387c08b2ea97b22d9b61c9d55", "class-validator": "^0.14.1", "compression": "^1.7.5", "cors": "^2.8.5", diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index 06850047..170f61fd 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -140,6 +140,11 @@ import { useVoiceCallsBaileys } from './voiceCalls/useVoiceCallsBaileys'; const groupMetadataCache = new CacheService(new CacheEngine(configService, 'groups').getEngine()); +interface IMessageKeyWithExtras extends proto.IMessageKey { + senderPn?: string | null; + senderLid?: string | null; +} + export class BaileysStartupService extends ChannelStartupService { constructor( public readonly configService: ConfigService, @@ -891,6 +896,10 @@ export class BaileysStartupService extends ChannelStartupService { this.logger.info("VALOR DA MENSAGEM: " + JSON.stringify(received)) + received.key.remoteJid = this.normalizeLidKey(received?.key); + + this.logger.info("NOVO VALOR JID " + JSON.stringify(received?.key)) + if (received.message?.protocolMessage?.editedMessage || received.message?.editedMessage?.message) { const editedMessage = received.message?.protocolMessage || received.message?.editedMessage?.message?.protocolMessage; @@ -4048,4 +4057,12 @@ export class BaileysStartupService extends ChannelStartupService { return response; } + + public normalizeLidKey(key: proto.IMessageKey): string | undefined { + const extendedKey = key as IMessageKeyWithExtras; + if (extendedKey.remoteJid?.includes('@lid') && extendedKey.senderLid) { + return extendedKey.senderLid; + } + return extendedKey.remoteJid; + } } From f41995cf4337cb58e23697863355a309bafca69b Mon Sep 17 00:00:00 2001 From: Jonathan Mantovani Date: Fri, 20 Jun 2025 14:56:18 -0300 Subject: [PATCH 87/97] =?UTF-8?q?alterado=20o=20a=20valida=C3=A7=C3=A3o=20?= =?UTF-8?q?de=20senderLid=20para=20senderPn?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../integrations/channel/whatsapp/whatsapp.baileys.service.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index 170f61fd..c56d6277 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -4060,8 +4060,8 @@ export class BaileysStartupService extends ChannelStartupService { public normalizeLidKey(key: proto.IMessageKey): string | undefined { const extendedKey = key as IMessageKeyWithExtras; - if (extendedKey.remoteJid?.includes('@lid') && extendedKey.senderLid) { - return extendedKey.senderLid; + if (extendedKey.remoteJid?.includes('@lid') && extendedKey.senderPn) { + return extendedKey.senderPn; } return extendedKey.remoteJid; } From 153f9ee64da4201a09498ff60532b53dbd770516 Mon Sep 17 00:00:00 2001 From: Lucas Mesquita Date: Sun, 22 Jun 2025 18:16:11 -0300 Subject: [PATCH 88/97] =?UTF-8?q?Update=20vers=C3=A3o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 2 +- .../integrations/channel/whatsapp/whatsapp.baileys.service.ts | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index 2d7f0b65..5d4c25cb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.36", + "version": "2.2.37", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index c56d6277..6dfaf650 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -898,8 +898,6 @@ export class BaileysStartupService extends ChannelStartupService { received.key.remoteJid = this.normalizeLidKey(received?.key); - this.logger.info("NOVO VALOR JID " + JSON.stringify(received?.key)) - if (received.message?.protocolMessage?.editedMessage || received.message?.editedMessage?.message) { const editedMessage = received.message?.protocolMessage || received.message?.editedMessage?.message?.protocolMessage; @@ -4061,6 +4059,7 @@ export class BaileysStartupService extends ChannelStartupService { public normalizeLidKey(key: proto.IMessageKey): string | undefined { const extendedKey = key as IMessageKeyWithExtras; if (extendedKey.remoteJid?.includes('@lid') && extendedKey.senderPn) { + this.logger.info("NOVO VALOR JID " + extendedKey.senderPn); return extendedKey.senderPn; } return extendedKey.remoteJid; From c9abe4de17cb9d9909b8cc3bf7e787de7b45d34c Mon Sep 17 00:00:00 2001 From: Lucas Mesquita Date: Sat, 28 Jun 2025 20:42:38 -0300 Subject: [PATCH 89/97] =?UTF-8?q?Update=20vers=C3=A3o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 5d4c25cb..3c348a90 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.37", + "version": "2.2.38", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", From 6e1847d0fae82baa46b69fd5cbf6f3d0ff6b77f7 Mon Sep 17 00:00:00 2001 From: Jonathan Mantovani Date: Fri, 11 Jul 2025 14:10:38 -0300 Subject: [PATCH 90/97] =?UTF-8?q?Altera=C3=A7=C3=A3o=20na=20coluna=20token?= =?UTF-8?q?=20para=20o=20tipo=20text=20na=20tabela=20instances?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- prisma/postgresql-schema.prisma | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/prisma/postgresql-schema.prisma b/prisma/postgresql-schema.prisma index 2f79ed9e..2425c625 100644 --- a/prisma/postgresql-schema.prisma +++ b/prisma/postgresql-schema.prisma @@ -70,7 +70,7 @@ model Instance { integration String? @db.VarChar(100) number String? @db.VarChar(100) businessId String? @db.VarChar(100) - token String? @db.VarChar(255) + token String? @db.Text clientName String? @db.VarChar(100) webVersion String? @db.VarChar(50) disconnectionReasonCode Int? @db.Integer From 9c401802ae949c46b6b582ffafaf15090e2d9eeb Mon Sep 17 00:00:00 2001 From: Lucas Mesquita Date: Fri, 11 Jul 2025 14:17:37 -0300 Subject: [PATCH 91/97] =?UTF-8?q?update=20vers=C3=A3o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 3c348a90..98873603 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.38", + "version": "2.2.39", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", From b5bffc9bec7df4092150a049a089953d848aa126 Mon Sep 17 00:00:00 2001 From: Lucas Mesquita Date: Fri, 11 Jul 2025 15:25:57 -0300 Subject: [PATCH 92/97] Incluir arquivo de migration --- .../20250711181706_change_token_to_text/migration.sql | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 prisma/postgresql-migrations/20250711181706_change_token_to_text/migration.sql diff --git a/prisma/postgresql-migrations/20250711181706_change_token_to_text/migration.sql b/prisma/postgresql-migrations/20250711181706_change_token_to_text/migration.sql new file mode 100644 index 00000000..16c4f7aa --- /dev/null +++ b/prisma/postgresql-migrations/20250711181706_change_token_to_text/migration.sql @@ -0,0 +1,2 @@ +-- AlterTable +ALTER TABLE "Instance" ALTER COLUMN "token" SET DATA TYPE TEXT; From c595bb42cb4c9e5a25709403e5c86081875cce58 Mon Sep 17 00:00:00 2001 From: Lucas Mesquita Date: Fri, 11 Jul 2025 15:26:52 -0300 Subject: [PATCH 93/97] =?UTF-8?q?Update=20vers=C3=A3o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 98873603..b4847cd2 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-api", - "version": "2.2.39", + "version": "2.2.40", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", From 1760b91c2e670fb7ed275c516db653e8e6e50c5a Mon Sep 17 00:00:00 2001 From: Jonathan Mantovani Date: Mon, 4 Aug 2025 11:47:15 -0300 Subject: [PATCH 94/97] =?UTF-8?q?Tratamentos=20de=20objetos=20com=20mensag?= =?UTF-8?q?ens=20de=20an=C3=BAncios=20na=20meta?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../channel/meta/whatsapp.business.service.ts | 30 +++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/src/api/integrations/channel/meta/whatsapp.business.service.ts b/src/api/integrations/channel/meta/whatsapp.business.service.ts index 7446fafb..3416ae3d 100644 --- a/src/api/integrations/channel/meta/whatsapp.business.service.ts +++ b/src/api/integrations/channel/meta/whatsapp.business.service.ts @@ -201,14 +201,40 @@ export class BusinessStartupService extends ChannelStartupService { private messageTextJson(received: any) { let content: any; const message = received.messages[0]; + const referral = message.referral; + + const externalAdReply = referral?.source_url + ? { + externalAdReply: { + sourceUrl: referral.source_url, + title: referral.headline, + thumbnailUrl: referral.thumbnail_url + } + } + : undefined; + if (message.from === received.metadata.phone_number_id) { content = { extendedTextMessage: { text: message.text.body }, }; - message.context ? (content = { ...content, contextInfo: { stanzaId: message.context.id } }) : content; + if (message.context?.id) { + content.contextInfo = { + stanzaId: message.context.id, + ...externalAdReply, + }; + } else if (externalAdReply) { + content.contextInfo = externalAdReply; + } } else { content = { conversation: message.text.body }; - message.context ? (content = { ...content, contextInfo: { stanzaId: message.context.id } }) : content; + if (message.context?.id) { + content.contextInfo = { + stanzaId: message.context.id, + ...externalAdReply, + }; + } else if (externalAdReply) { + content.contextInfo = externalAdReply; + } } return content; } From bf7afd7bbc9596af1efa952424e73c429ff174f9 Mon Sep 17 00:00:00 2001 From: Jonathan Mantovani Date: Wed, 6 Aug 2025 16:32:33 -0300 Subject: [PATCH 95/97] =?UTF-8?q?Ajuste=20no=20c=C3=B3digo=20para=20enviar?= =?UTF-8?q?=20objeto=20de=20erro?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../channel/meta/whatsapp.business.service.ts | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/src/api/integrations/channel/meta/whatsapp.business.service.ts b/src/api/integrations/channel/meta/whatsapp.business.service.ts index 3416ae3d..14a3f3b0 100644 --- a/src/api/integrations/channel/meta/whatsapp.business.service.ts +++ b/src/api/integrations/channel/meta/whatsapp.business.service.ts @@ -206,30 +206,30 @@ export class BusinessStartupService extends ChannelStartupService { const externalAdReply = referral?.source_url ? { externalAdReply: { - sourceUrl: referral.source_url, - title: referral.headline, - thumbnailUrl: referral.thumbnail_url + sourceUrl: referral?.source_url, + title: referral?.headline, + thumbnailUrl: referral?.thumbnail_url } } : undefined; if (message.from === received.metadata.phone_number_id) { content = { - extendedTextMessage: { text: message.text.body }, + extendedTextMessage: { text: message?.text?.body }, }; if (message.context?.id) { content.contextInfo = { - stanzaId: message.context.id, + stanzaId: message?.context?.id, ...externalAdReply, }; } else if (externalAdReply) { content.contextInfo = externalAdReply; } } else { - content = { conversation: message.text.body }; - if (message.context?.id) { + content = { conversation: message?.text?.body }; + if (message?.context?.id) { content.contextInfo = { - stanzaId: message.context.id, + stanzaId: message?.context?.id, ...externalAdReply, }; } else if (externalAdReply) { @@ -490,6 +490,7 @@ export class BusinessStartupService extends ChannelStartupService { messageType: this.renderMessageType(received.messages[0].type), messageTimestamp: parseInt(received.messages[0].timestamp) as number, source: 'unknown', + errors: received.messages[0].errors || [], instanceId: this.instanceId, }; } From dc691d88b36788d23bfbbbb64ccfe47c2fe9dc32 Mon Sep 17 00:00:00 2001 From: Jonathan Mantovani Date: Fri, 8 Aug 2025 17:12:39 -0300 Subject: [PATCH 96/97] =?UTF-8?q?Mensagens=20de=20grupos=20com=20erro=20de?= =?UTF-8?q?=20'No=20SenderKeyRecord=20found=20for=20decryption'=20agora=20?= =?UTF-8?q?ser=C3=A3o=20enviados=20o=20mediaType=20como=20ciphertext?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../integrations/channel/whatsapp/whatsapp.baileys.service.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index 6dfaf650..00dafbad 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -916,7 +916,9 @@ export class BaileysStartupService extends ChannelStartupService { } } - if (received.messageStubParameters && received.messageStubParameters[0] === 'Message absent from node') { + if (received.messageStubParameters && + (received.messageStubParameters[0] === 'Message absent from node' || + received.messageStubParameters[0] === 'No SenderKeyRecord found for decryption')) { this.logger.info(`Recovering message lost messageId: ${received.key.id}`); await this.baileysCache.set(received.key.id, { From 5f095b432af4003baeab8cd898519fb8ace3f3f3 Mon Sep 17 00:00:00 2001 From: Jonathan Mantovani Date: Mon, 11 Aug 2025 12:38:14 -0300 Subject: [PATCH 97/97] Separa erros tipo NoSenderKeyRecord de ciphertext --- .../whatsapp/whatsapp.baileys.service.ts | 23 ++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index 00dafbad..ded3cb89 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -916,9 +916,7 @@ export class BaileysStartupService extends ChannelStartupService { } } - if (received.messageStubParameters && - (received.messageStubParameters[0] === 'Message absent from node' || - received.messageStubParameters[0] === 'No SenderKeyRecord found for decryption')) { + if (received.messageStubParameters && received.messageStubParameters[0] === 'Message absent from node') { this.logger.info(`Recovering message lost messageId: ${received.key.id}`); await this.baileysCache.set(received.key.id, { @@ -944,6 +942,25 @@ export class BaileysStartupService extends ChannelStartupService { continue; } + if (received.messageStubParameters && received.messageStubParameters[0] === 'No SenderKeyRecord found for decryption') { + const messageRaw = { + key: received.key, + pushName: received.pushName, + messageType: 'NoSenderKeyRecord', + message: {}, + messageTimestamp: received.messageTimestamp as number, + owner: this.instance.name, + instanceId: this.instanceId, + source: getDevice(received.key.id), + groupInfo + }; + + this.logger.verbose('Sending data NoSenderKeyRecord to webhook in event MESSAGES_UPSERT'); + this.sendDataWebhook(Events.MESSAGES_UPSERT, messageRaw); + + continue; + } + const retryCache = (await this.baileysCache.get(received.key.id)) || null; if (retryCache) {