diff --git a/src/api/integrations/channel/meta/whatsapp.business.service.ts b/src/api/integrations/channel/meta/whatsapp.business.service.ts index e5025d6d..bd6095e9 100644 --- a/src/api/integrations/channel/meta/whatsapp.business.service.ts +++ b/src/api/integrations/channel/meta/whatsapp.business.service.ts @@ -20,7 +20,7 @@ import { chatbotController } from '@api/server.module'; import { CacheService } from '@api/services/cache.service'; import { ChannelStartupService } from '@api/services/channel.service'; import { Events, wa } from '@api/types/wa.types'; -import { AudioConverter, Chatwoot, ConfigService, Database, Openai, S3, WaBusiness } from '@config/env.config'; +import { AudioConverter, ConfigService, Database, S3, WaBusiness } from '@config/env.config'; import { BadRequestException, InternalServerErrorException } from '@exceptions'; import { createJid } from '@utils/createJid'; import { status } from '@utils/renderStatus'; @@ -128,8 +128,6 @@ export class BusinessStartupService extends ChannelStartupService { const content = data.entry[0].changes[0].value; try { - this.loadChatwoot(); - this.eventHandler(content); this.phoneNumber = createJid(content.messages ? content.messages[0].from : content.statuses[0]?.recipient_id); @@ -516,38 +514,6 @@ export class BusinessStartupService extends ChannelStartupService { messageRaw.message.mediaUrl = mediaUrl; messageRaw.message.base64 = buffer.data.toString('base64'); - - // Processar OpenAI speech-to-text para áudio após o mediaUrl estar disponível - if (this.configService.get('OPENAI').ENABLED && mediaType === 'audio') { - const openAiDefaultSettings = await this.prismaRepository.openaiSetting.findFirst({ - where: { - instanceId: this.instanceId, - }, - include: { - OpenaiCreds: true, - }, - }); - - if ( - openAiDefaultSettings && - openAiDefaultSettings.openaiCredsId && - openAiDefaultSettings.speechToText - ) { - try { - messageRaw.message.speechToText = `[audio] ${await this.openaiService.speechToText( - openAiDefaultSettings.OpenaiCreds, - { - message: { - mediaUrl: messageRaw.message.mediaUrl, - ...messageRaw, - }, - }, - )}`; - } catch (speechError) { - this.logger.error(`Error processing speech-to-text: ${speechError}`); - } - } - } } } catch (error) { this.logger.error(['Error on upload file to minio', error?.message, error?.stack]); @@ -555,34 +521,6 @@ export class BusinessStartupService extends ChannelStartupService { } else { const buffer = await this.downloadMediaMessage(received?.messages[0]); messageRaw.message.base64 = buffer.toString('base64'); - - // Processar OpenAI speech-to-text para áudio mesmo sem S3 - if (this.configService.get('OPENAI').ENABLED && message.type === 'audio') { - const openAiDefaultSettings = await this.prismaRepository.openaiSetting.findFirst({ - where: { - instanceId: this.instanceId, - }, - include: { - OpenaiCreds: true, - }, - }); - - if (openAiDefaultSettings && openAiDefaultSettings.openaiCredsId && openAiDefaultSettings.speechToText) { - try { - messageRaw.message.speechToText = `[audio] ${await this.openaiService.speechToText( - openAiDefaultSettings.OpenaiCreds, - { - message: { - base64: messageRaw.message.base64, - ...messageRaw, - }, - }, - )}`; - } catch (speechError) { - this.logger.error(`Error processing speech-to-text: ${speechError}`); - } - } - } } } else if (received?.messages[0].interactive) { messageRaw = { @@ -666,20 +604,6 @@ export class BusinessStartupService extends ChannelStartupService { pushName: messageRaw.pushName, }); - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { - const chatwootSentMessage = await this.chatwootService.eventWhatsapp( - Events.MESSAGES_UPSERT, - { instanceName: this.instance.name, instanceId: this.instanceId }, - messageRaw, - ); - - if (chatwootSentMessage?.id) { - messageRaw.chatwootMessageId = chatwootSentMessage.id; - messageRaw.chatwootInboxId = chatwootSentMessage.id; - messageRaw.chatwootConversationId = chatwootSentMessage.id; - } - } - if (!this.isMediaMessage(message) && message.type !== 'sticker') { await this.prismaRepository.message.create({ data: messageRaw, @@ -711,14 +635,6 @@ export class BusinessStartupService extends ChannelStartupService { this.sendDataWebhook(Events.CONTACTS_UPDATE, contactRaw); - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { - await this.chatwootService.eventWhatsapp( - Events.CONTACTS_UPDATE, - { instanceName: this.instance.name, instanceId: this.instanceId }, - contactRaw, - ); - } - await this.prismaRepository.contact.updateMany({ where: { remoteJid: contact.remoteJid }, data: contactRaw, @@ -774,14 +690,6 @@ export class BusinessStartupService extends ChannelStartupService { data: message, }); - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { - this.chatwootService.eventWhatsapp( - Events.MESSAGES_DELETE, - { instanceName: this.instance.name, instanceId: this.instanceId }, - { key: key }, - ); - } - return; } @@ -1135,22 +1043,6 @@ export class BusinessStartupService extends ChannelStartupService { this.sendDataWebhook(Events.SEND_MESSAGE, messageRaw); - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled && !isIntegration) { - this.chatwootService.eventWhatsapp( - Events.SEND_MESSAGE, - { instanceName: this.instance.name, instanceId: this.instanceId }, - messageRaw, - ); - } - - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled && isIntegration) - await chatbotController.emit({ - instance: { instanceName: this.instance.name, instanceId: this.instanceId }, - remoteJid: messageRaw.key.remoteJid, - msg: messageRaw, - pushName: messageRaw.pushName, - }); - 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 7086818b..53b8cd6c 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -68,7 +68,6 @@ import { ConfigSessionPhone, Database, Log, - Openai, ProviderSession, QrCode, S3, @@ -310,14 +309,6 @@ export class BaileysStartupService extends ChannelStartupService { statusCode: DisconnectReason.badSession, }); - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { - this.chatwootService.eventWhatsapp( - Events.QRCODE_UPDATED, - { instanceName: this.instance.name, instanceId: this.instanceId }, - { message: 'QR code limit reached, please login again', statusCode: DisconnectReason.badSession }, - ); - } - this.sendDataWebhook(Events.CONNECTION_UPDATE, { instance: this.instance.name, state: 'refused', @@ -362,16 +353,6 @@ export class BaileysStartupService extends ChannelStartupService { this.sendDataWebhook(Events.QRCODE_UPDATED, { qrcode: { instance: this.instance.name, pairingCode: this.instance.qrcode.pairingCode, code: qr, base64 }, }); - - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { - this.chatwootService.eventWhatsapp( - Events.QRCODE_UPDATED, - { instanceName: this.instance.name, instanceId: this.instanceId }, - { - qrcode: { instance: this.instance.name, pairingCode: this.instance.qrcode.pairingCode, code: qr, base64 }, - }, - ); - } }); qrcodeTerminal.generate(qr, { small: true }, (qrcode) => @@ -419,14 +400,6 @@ export class BaileysStartupService extends ChannelStartupService { }, }); - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { - this.chatwootService.eventWhatsapp( - Events.STATUS_INSTANCE, - { instanceName: this.instance.name, instanceId: this.instanceId }, - { instance: this.instance.name, status: 'closed' }, - ); - } - this.eventEmitter.emit('logout.instance', this.instance.name, 'inner'); this.client?.ws?.close(); this.client.end(new Error('Close connection')); @@ -468,15 +441,6 @@ export class BaileysStartupService extends ChannelStartupService { }, }); - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { - this.chatwootService.eventWhatsapp( - Events.CONNECTION_UPDATE, - { instanceName: this.instance.name, instanceId: this.instanceId }, - { instance: this.instance.name, status: 'open' }, - ); - this.syncChatwootLostMessages(); - } - this.sendDataWebhook(Events.CONNECTION_UPDATE, { instance: this.instance.name, wuid: this.instance.wuid, @@ -702,7 +666,6 @@ export class BaileysStartupService extends ChannelStartupService { public async connectToWhatsapp(number?: string): Promise { try { - this.loadChatwoot(); this.loadSettings(); this.loadWebhook(); this.loadProxy(); @@ -802,22 +765,6 @@ export class BaileysStartupService extends ChannelStartupService { } } - if ( - this.configService.get('CHATWOOT').ENABLED && - this.localChatwoot?.enabled && - this.localChatwoot.importContacts && - contactsRaw.length - ) { - this.chatwootService.addHistoryContacts( - { instanceName: this.instance.name, instanceId: this.instance.id }, - contactsRaw, - ); - chatwootImport.importHistoryContacts( - { instanceName: this.instance.name, instanceId: this.instance.id }, - this.localChatwoot, - ); - } - const updatedContacts = await Promise.all( contacts.map(async (contact) => ({ remoteJid: contact.id, @@ -841,24 +788,6 @@ export class BaileysStartupService extends ChannelStartupService { data: { profilePicUrl: contact.profilePicUrl }, }); - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { - const instance = { instanceName: this.instance.name, instanceId: this.instance.id }; - - const findParticipant = await this.chatwootService.findContact( - instance, - contact.remoteJid.split('@')[0], - ); - - if (!findParticipant) { - return; - } - - this.chatwootService.updateContact(instance, findParticipant.id, { - name: contact.pushName, - avatar_url: contact.profilePicUrl, - }); - } - return update; }), ); @@ -922,23 +851,6 @@ export class BaileysStartupService extends ChannelStartupService { const instance: InstanceDto = { instanceName: this.instance.name }; - let timestampLimitToImport = null; - - if (this.configService.get('CHATWOOT').ENABLED) { - const daysLimitToImport = this.localChatwoot?.enabled ? this.localChatwoot.daysLimitImportMessages : 1000; - - const date = new Date(); - timestampLimitToImport = new Date(date.setDate(date.getDate() - daysLimitToImport)).getTime() / 1000; - - const maxBatchTimestamp = Math.max(...messages.map((message) => message.messageTimestamp as number)); - - const processBatch = maxBatchTimestamp >= timestampLimitToImport; - - if (!processBatch) { - return; - } - } - const contactsMap = new Map(); for (const contact of contacts) { @@ -971,23 +883,18 @@ export class BaileysStartupService extends ChannelStartupService { const messagesRaw: any[] = []; const messagesRepository: Set = new Set( - chatwootImport.getRepositoryMessagesCache(instance) ?? - ( - await this.prismaRepository.message.findMany({ - select: { key: true }, - where: { instanceId: this.instanceId }, - }) - ).map((message) => { - const key = message.key as { id: string }; + ( + await this.prismaRepository.message.findMany({ + select: { key: true }, + where: { instanceId: this.instanceId }, + }) + ).map((message) => { + const key = message.key as { id: string }; - return key.id; - }), + return key.id; + }), ); - if (chatwootImport.getRepositoryMessagesCache(instance) === null) { - chatwootImport.setRepositoryMessagesCache(instance, messagesRepository); - } - for (const m of messages) { if (!m.message || !m.key || !m.messageTimestamp) { continue; @@ -997,12 +904,6 @@ export class BaileysStartupService extends ChannelStartupService { m.messageTimestamp = m.messageTimestamp?.toNumber(); } - if (this.configService.get('CHATWOOT').ENABLED) { - if (m.messageTimestamp <= timestampLimitToImport) { - continue; - } - } - if (messagesRepository?.has(m.key.id)) { continue; } @@ -1025,18 +926,6 @@ export class BaileysStartupService extends ChannelStartupService { await this.prismaRepository.message.createMany({ data: messagesRaw, skipDuplicates: true }); } - if ( - this.configService.get('CHATWOOT').ENABLED && - this.localChatwoot?.enabled && - this.localChatwoot.importMessages && - messagesRaw.length > 0 - ) { - this.chatwootService.addHistoryMessages( - instance, - messagesRaw.filter((msg) => !chatwootImport.isIgnorePhoneNumber(msg.key?.remoteJid)), - ); - } - await this.contactHandle['contacts.upsert']( contacts.filter((c) => !!c.notify || !!c.name).map((c) => ({ id: c.id, name: c.name ?? c.notify })), ); @@ -1092,13 +981,6 @@ export class BaileysStartupService extends ChannelStartupService { received?.message?.protocolMessage || received?.message?.editedMessage?.message?.protocolMessage; if (editedMessage) { - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) - this.chatwootService.eventWhatsapp( - 'messages.edit', - { instanceName: this.instance.name, instanceId: this.instance.id }, - editedMessage, - ); - await this.sendDataWebhook(Events.MESSAGES_EDITED, editedMessage); const oldMessage = await this.getMessage(editedMessage.key, true); if ((oldMessage as any)?.id) { @@ -1201,35 +1083,6 @@ export class BaileysStartupService extends ChannelStartupService { await this.client.readMessages([received.key]); } - if ( - this.configService.get('CHATWOOT').ENABLED && - this.localChatwoot?.enabled && - !received.key.id.includes('@broadcast') - ) { - const chatwootSentMessage = await this.chatwootService.eventWhatsapp( - Events.MESSAGES_UPSERT, - { instanceName: this.instance.name, instanceId: this.instanceId }, - messageRaw, - ); - - if (chatwootSentMessage?.id) { - messageRaw.chatwootMessageId = chatwootSentMessage.id; - messageRaw.chatwootInboxId = chatwootSentMessage.inbox_id; - messageRaw.chatwootConversationId = chatwootSentMessage.conversation_id; - } - } - - if (this.configService.get('OPENAI').ENABLED && received?.message?.audioMessage) { - const openAiDefaultSettings = await this.prismaRepository.openaiSetting.findFirst({ - where: { instanceId: this.instanceId }, - include: { OpenaiCreds: true }, - }); - - if (openAiDefaultSettings && openAiDefaultSettings.openaiCredsId && openAiDefaultSettings.speechToText) { - messageRaw.message.speechToText = `[audio] ${await this.openaiService.speechToText(received, this)}`; - } - } - if (this.configService.get('DATABASE').SAVE_DATA.NEW_MESSAGE) { const msg = await this.prismaRepository.message.create({ data: messageRaw }); @@ -1390,14 +1243,6 @@ export class BaileysStartupService extends ChannelStartupService { if (contact) { this.sendDataWebhook(Events.CONTACTS_UPDATE, contactRaw); - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { - await this.chatwootService.eventWhatsapp( - Events.CONTACTS_UPDATE, - { instanceName: this.instance.name, instanceId: this.instanceId }, - contactRaw, - ); - } - if (this.configService.get('DATABASE').SAVE_DATA.CONTACTS) await this.prismaRepository.contact.upsert({ where: { remoteJid_instanceId: { remoteJid: contactRaw.remoteJid, instanceId: contactRaw.instanceId } }, @@ -1445,16 +1290,6 @@ export class BaileysStartupService extends ChannelStartupService { await this.baileysCache.set(updateKey, true, 30 * 60); - if (status[update.status] === 'READ' && key.fromMe) { - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { - this.chatwootService.eventWhatsapp( - 'messages.read', - { instanceName: this.instance.name, instanceId: this.instanceId }, - { key: key }, - ); - } - } - if (key.remoteJid !== 'status@broadcast' && key.id !== undefined) { let pollUpdates: any; @@ -1504,14 +1339,6 @@ export class BaileysStartupService extends ChannelStartupService { if (this.configService.get('DATABASE').SAVE_DATA.MESSAGE_UPDATE) await this.prismaRepository.messageUpdate.create({ data: message }); - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { - this.chatwootService.eventWhatsapp( - Events.MESSAGES_DELETE, - { instanceName: this.instance.name, instanceId: this.instanceId }, - { key: key }, - ); - } - continue; } @@ -1852,23 +1679,6 @@ export class BaileysStartupService extends ChannelStartupService { private historySyncNotification(msg: proto.Message.IHistorySyncNotification) { const instance: InstanceDto = { instanceName: this.instance.name }; - if ( - this.configService.get('CHATWOOT').ENABLED && - this.localChatwoot?.enabled && - this.localChatwoot.importMessages && - this.isSyncNotificationFromUsedSyncType(msg) - ) { - if (msg.chunkOrder === 1) { - this.chatwootService.startImportHistoryMessages(instance); - } - - if (msg.progress === 100) { - setTimeout(() => { - this.chatwootService.importHistoryMessages(instance); - }, 10000); - } - } - return true; } @@ -2273,25 +2083,6 @@ export class BaileysStartupService extends ChannelStartupService { const isVideo = messageSent?.message?.videoMessage; - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled && !isIntegration) { - this.chatwootService.eventWhatsapp( - Events.SEND_MESSAGE, - { instanceName: this.instance.name, instanceId: this.instanceId }, - messageRaw, - ); - } - - if (this.configService.get('OPENAI').ENABLED && messageRaw?.message?.audioMessage) { - const openAiDefaultSettings = await this.prismaRepository.openaiSetting.findFirst({ - where: { instanceId: this.instanceId }, - include: { OpenaiCreds: true }, - }); - - if (openAiDefaultSettings && openAiDefaultSettings.openaiCredsId && openAiDefaultSettings.speechToText) { - messageRaw.message.speechToText = `[audio] ${await this.openaiService.speechToText(messageRaw, this)}`; - } - } - if (this.configService.get('DATABASE').SAVE_DATA.NEW_MESSAGE) { const msg = await this.prismaRepository.message.create({ data: messageRaw }); @@ -2376,16 +2167,6 @@ export class BaileysStartupService extends ChannelStartupService { this.sendDataWebhook(Events.SEND_MESSAGE, messageRaw); - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled && isIntegration) { - await chatbotController.emit({ - instance: { instanceName: this.instance.name, instanceId: this.instanceId }, - remoteJid: messageRaw.key.remoteJid, - msg: messageRaw, - pushName: messageRaw.pushName, - isIntegration, - }); - } - return messageRaw; } catch (error) { this.logger.error(error); @@ -4017,12 +3798,6 @@ export class BaileysStartupService extends ChannelStartupService { if (editedMessage) { this.sendDataWebhook(Events.SEND_MESSAGE_UPDATE, editedMessage); - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) - this.chatwootService.eventWhatsapp( - 'send.message.update', - { instanceName: this.instance.name, instanceId: this.instance.id }, - editedMessage, - ); const messageId = messageSent.message?.protocolMessage?.key?.id; if (messageId && this.configService.get('DATABASE').SAVE_DATA.NEW_MESSAGE) { @@ -4534,34 +4309,6 @@ export class BaileysStartupService extends ChannelStartupService { return messageRaw; } - private async syncChatwootLostMessages() { - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { - const chatwootConfig = await this.findChatwoot(); - const prepare = (message: any) => this.prepareMessage(message); - this.chatwootService.syncLostMessages({ instanceName: this.instance.name }, chatwootConfig, prepare); - - // Generate ID for this cron task and store in cache - const cronId = cuid(); - const cronKey = `chatwoot:syncLostMessages`; - await this.chatwootService.getCache()?.hSet(cronKey, this.instance.name, cronId); - - const task = cron.schedule('0,30 * * * *', async () => { - // Check ID before executing (only if cache is available) - const cache = this.chatwootService.getCache(); - if (cache) { - const storedId = await cache.hGet(cronKey, this.instance.name); - if (storedId && storedId !== cronId) { - this.logger.info(`Stopping syncChatwootLostMessages cron - ID mismatch: ${cronId} vs ${storedId}`); - task.stop(); - return; - } - } - this.chatwootService.syncLostMessages({ instanceName: this.instance.name }, chatwootConfig, prepare); - }); - task.start(); - } - } - private async updateMessagesReadedByTimestamp(remoteJid: string, timestamp?: number): Promise { if (timestamp === undefined || timestamp === null) return 0;