From f6ccd58deee788f19183500cb51d8fdc8aebce7b Mon Sep 17 00:00:00 2001 From: yousseefs Date: Tue, 29 Oct 2024 18:43:31 +0000 Subject: [PATCH 01/20] some fixs --- prisma/mysql-schema.prisma | 1 + prisma/postgresql-schema.prisma | 1 + .../whatsapp/whatsapp.baileys.service.ts | 22 ++++++++++++++----- 3 files changed, 18 insertions(+), 6 deletions(-) diff --git a/prisma/mysql-schema.prisma b/prisma/mysql-schema.prisma index ff968882..8ce2f79b 100644 --- a/prisma/mysql-schema.prisma +++ b/prisma/mysql-schema.prisma @@ -127,6 +127,7 @@ model Chat { unreadMessages Int @default(0) @@index([instanceId]) @@index([remoteJid]) + @@unique([instanceId, remoteJid]) } model Contact { diff --git a/prisma/postgresql-schema.prisma b/prisma/postgresql-schema.prisma index 011de9a0..eaff59e5 100644 --- a/prisma/postgresql-schema.prisma +++ b/prisma/postgresql-schema.prisma @@ -127,6 +127,7 @@ model Chat { unreadMessages Int @default(0) @@index([instanceId]) @@index([remoteJid]) + @@unique([remoteJid, instanceId]) } model Contact { diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index 185910bd..54d6b26a 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -1085,9 +1085,14 @@ export class BaileysStartupService extends ChannelStartupService { this.sendDataWebhook(Events.CHATS_UPSERT, [chatToInsert]); if (this.configService.get('DATABASE').SAVE_DATA.CHATS) { - await this.prismaRepository.chat.create({ - data: chatToInsert, - }); + try { + await this.prismaRepository.chat.create({ + data: chatToInsert, + }); + } + catch(error){ + console.log(`Chat insert record ignored: ${chatToInsert.remoteJid} - ${chatToInsert.instanceId}`); + } } } @@ -1420,9 +1425,14 @@ export class BaileysStartupService extends ChannelStartupService { this.sendDataWebhook(Events.CHATS_UPSERT, [chatToInsert]); if (this.configService.get('DATABASE').SAVE_DATA.CHATS) { - await this.prismaRepository.chat.create({ - data: chatToInsert, - }); + try { + await this.prismaRepository.chat.create({ + data: chatToInsert, + }); + } + catch(error){ + console.log(`Chat insert record ignored: ${chatToInsert.remoteJid} - ${chatToInsert.instanceId}`); + } } } } From 0e5f9e3b77654078c5c0e2c87234931854fc5640 Mon Sep 17 00:00:00 2001 From: Adriel Santos Araujo <47580872+adriel12319@users.noreply.github.com> Date: Thu, 31 Oct 2024 22:52:45 -0300 Subject: [PATCH 02/20] Update getConversationMessage.ts --- src/utils/getConversationMessage.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/getConversationMessage.ts b/src/utils/getConversationMessage.ts index c1d93f58..fe3bed3f 100644 --- a/src/utils/getConversationMessage.ts +++ b/src/utils/getConversationMessage.ts @@ -17,7 +17,7 @@ const getTypeMessage = (msg: any) => { msg?.message?.viewOnceMessageV2?.message?.audioMessage?.url, listResponseMessage: msg?.message?.listResponseMessage?.title, responseRowId: msg?.message?.listResponseMessage?.singleSelectReply?.selectedRowId, - templateButtonReplyMessage: msg?.message?.templateButtonReplyMessage?.selectedId, + templateButtonReplyMessage: msg?.message?.templateButtonReplyMessage?.selectedId || buttonsResponseMessage: msg?.message?.buttonsResponseMessage?.selectedButtonId, // Medias audioMessage: msg?.message?.speechToText ? msg?.message?.speechToText From 8f86c9d758abe2e503bb05a16abf04b361f6330d Mon Sep 17 00:00:00 2001 From: Adriel Santos Araujo <47580872+adriel12319@users.noreply.github.com> Date: Thu, 31 Oct 2024 23:19:17 -0300 Subject: [PATCH 03/20] Update getConversationMessage.ts --- src/utils/getConversationMessage.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/getConversationMessage.ts b/src/utils/getConversationMessage.ts index fe3bed3f..eb4e56cf 100644 --- a/src/utils/getConversationMessage.ts +++ b/src/utils/getConversationMessage.ts @@ -17,7 +17,7 @@ const getTypeMessage = (msg: any) => { msg?.message?.viewOnceMessageV2?.message?.audioMessage?.url, listResponseMessage: msg?.message?.listResponseMessage?.title, responseRowId: msg?.message?.listResponseMessage?.singleSelectReply?.selectedRowId, - templateButtonReplyMessage: msg?.message?.templateButtonReplyMessage?.selectedId || buttonsResponseMessage: msg?.message?.buttonsResponseMessage?.selectedButtonId, + templateButtonReplyMessage: msg?.message?.templateButtonReplyMessage?.selectedId || msg?.message?.buttonsResponseMessage?.selectedButtonId, // Medias audioMessage: msg?.message?.speechToText ? msg?.message?.speechToText From 6591a67ab66336d7a04a32b846b8acbfbe02ab82 Mon Sep 17 00:00:00 2001 From: Davidson Gomes Date: Sat, 2 Nov 2024 08:12:30 -0300 Subject: [PATCH 04/20] feat: sh local install --- local_install.sh | 150 ++++++++++++++++++++++++++++++ src/api/routes/instance.router.ts | 1 + 2 files changed, 151 insertions(+) create mode 100755 local_install.sh diff --git a/local_install.sh b/local_install.sh new file mode 100755 index 00000000..529a2c4b --- /dev/null +++ b/local_install.sh @@ -0,0 +1,150 @@ +#!/bin/bash + +# Definir cores para melhor legibilidade +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' # No Color + +# Função para log +log() { + echo -e "${GREEN}[INFO]${NC} $1" +} +log_error() { + echo -e "${RED}[ERROR]${NC} $1" +} +log_warning() { + echo -e "${YELLOW}[WARNING]${NC} $1" +} + +# Verificar se está rodando como root +if [ "$(id -u)" = "0" ]; then + log_error "Este script não deve ser executado como root" + exit 1 +fi + +# Verificar sistema operacional +OS="$(uname -s)" +case "${OS}" in + Linux*) + if [ ! -x "$(command -v curl)" ]; then + log_warning "Curl não está instalado. Tentando instalar..." + if [ -x "$(command -v apt-get)" ]; then + sudo apt-get update && sudo apt-get install -y curl + elif [ -x "$(command -v yum)" ]; then + sudo yum install -y curl + else + log_error "Não foi possível instalar curl automaticamente. Por favor, instale manualmente." + exit 1 + fi + fi + ;; + Darwin*) + if [ ! -x "$(command -v curl)" ]; then + log_error "Curl não está instalado. Por favor, instale o Xcode Command Line Tools." + exit 1 + fi + ;; + *) + log_error "Sistema operacional não suportado: ${OS}" + exit 1 + ;; +esac + +# Verificar conexão com a internet antes de prosseguir +if ! ping -c 1 8.8.8.8 &> /dev/null; then + log_error "Sem conexão com a internet. Por favor, verifique sua conexão." + exit 1 +fi + +# Adicionar verificação de espaço em disco +REQUIRED_SPACE=1000000 # 1GB em KB +AVAILABLE_SPACE=$(df -k . | awk 'NR==2 {print $4}') +if [ $AVAILABLE_SPACE -lt $REQUIRED_SPACE ]; then + log_error "Espaço em disco insuficiente. Necessário pelo menos 1GB livre." + exit 1 +fi + +# Adicionar tratamento de erro para comandos npm +npm_install_with_retry() { + local max_attempts=3 + local attempt=1 + + while [ $attempt -le $max_attempts ]; do + log "Tentativa $attempt de $max_attempts para npm install" + if npm install; then + return 0 + fi + attempt=$((attempt + 1)) + [ $attempt -le $max_attempts ] && log_warning "Falha na instalação. Tentando novamente em 5 segundos..." && sleep 5 + done + + log_error "Falha ao executar npm install após $max_attempts tentativas" + return 1 +} + +# Adicionar timeout para comandos +execute_with_timeout() { + timeout 300 $@ || log_error "Comando excedeu o tempo limite de 5 minutos: $@" +} + +# Verificar se o NVM já está instalado +if [ -d "$HOME/.nvm" ]; then + log "NVM já está instalado." +else + log "Instalando NVM..." + curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash +fi + +# Carregar o NVM no ambiente atual +export NVM_DIR="$HOME/.nvm" +[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" +[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" + +# Verificar se a versão do Node.js já está instalada +if command -v node >/dev/null 2>&1 && [ "$(node -v)" = "v20.10.0" ]; then + log "Node.js v20.10.0 já está instalado." +else + log "Instalando Node.js v20.10.0..." + nvm install v20.10.0 +fi + +nvm use v20.10.0 + +# Verificar as versões instaladas +log "Verificando as versões instaladas:" +log "Node.js: $(node -v)" +log "npm: $(npm -v)" + +# Instala dependências do projeto +log "Instalando dependências do projeto..." +rm -rf node_modules +npm install + +# Deploy do banco de dados +log "Deploy do banco de dados..." +npm run db:generate +npm run db:deploy + +# Iniciar o projeto +log "Iniciando o projeto..." +if [ "$1" = "-dev" ]; then + npm run dev:server +else + npm run build + npm run start:prod +fi + +log "Instalação concluída com sucesso!" + +# Criar arquivo de log +LOGFILE="./installation_log_$(date +%Y%m%d_%H%M%S).log" +exec 1> >(tee -a "$LOGFILE") +exec 2>&1 + +# Adicionar trap para limpeza em caso de interrupção +cleanup() { + log "Limpando recursos temporários..." + # Adicione comandos de limpeza aqui +} +trap cleanup EXIT diff --git a/src/api/routes/instance.router.ts b/src/api/routes/instance.router.ts index 7b81368d..2bf7f967 100644 --- a/src/api/routes/instance.router.ts +++ b/src/api/routes/instance.router.ts @@ -12,6 +12,7 @@ export class InstanceRouter extends RouterBroker { super(); this.router .post('/create', ...guards, async (req, res) => { + console.log('create instance', req.body); const response = await this.dataValidate({ request: req, schema: instanceSchema, From fd1f08a41ebf48abdec7f65f59c3201768600ee2 Mon Sep 17 00:00:00 2001 From: Felipe Medeiros Date: Tue, 5 Nov 2024 17:16:41 -0300 Subject: [PATCH 05/20] feat: handle quoted messages in WhatsApp integration --- .../channel/whatsapp/whatsapp.baileys.service.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index 0afd5318..a01559e3 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -4259,6 +4259,19 @@ export class BaileysStartupService extends ChannelStartupService { delete messageRaw.message.documentWithCaptionMessage; } + const quotedMessage = messageRaw?.contextInfo?.quotedMessage; + if (quotedMessage) { + if (quotedMessage.extendedTextMessage) { + quotedMessage.conversation = quotedMessage.extendedTextMessage.text; + delete quotedMessage.extendedTextMessage; + } + + if (quotedMessage.documentWithCaptionMessage) { + quotedMessage.documentMessage = quotedMessage.documentWithCaptionMessage.message.documentMessage; + delete quotedMessage.documentWithCaptionMessage; + } + } + return messageRaw; } From 3d51b45e2b22504ac73a3ba4a9ebad4fb0ffc717 Mon Sep 17 00:00:00 2001 From: Richards0n Date: Fri, 8 Nov 2024 00:25:00 -0300 Subject: [PATCH 06/20] feat: format participant phone number in messages --- .../chatbot/chatwoot/services/chatwoot.service.ts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts b/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts index 503a5cc9..adcc9c3c 100644 --- a/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts +++ b/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts @@ -1970,11 +1970,16 @@ export class ChatwootService { if (body.key.remoteJid.includes('@g.us')) { const participantName = body.pushName; + const rawPhoneNumber = body.key.remoteJid.split('@')[0]; + const formattedPhoneNumber = `+${rawPhoneNumber.slice(0, 2)} (${rawPhoneNumber.slice( + 2, + 4, + )}) ${rawPhoneNumber.slice(4, 8)}-${rawPhoneNumber.slice(8)}`; let content: string; if (!body.key.fromMe) { - content = `**${participantName}:**\n\n${bodyMessage}`; + content = `**${formattedPhoneNumber} - ${participantName}:**\n\n${bodyMessage}`; } else { content = `${bodyMessage}`; } @@ -2099,11 +2104,16 @@ export class ChatwootService { if (body.key.remoteJid.includes('@g.us')) { const participantName = body.pushName; + const rawPhoneNumber = body.key.remoteJid.split('@')[0]; + const formattedPhoneNumber = `+${rawPhoneNumber.slice(0, 2)} (${rawPhoneNumber.slice( + 2, + 4, + )}) ${rawPhoneNumber.slice(4, 8)}-${rawPhoneNumber.slice(8)}`; let content: string; if (!body.key.fromMe) { - content = `**${participantName}**\n\n${bodyMessage}`; + content = `**${formattedPhoneNumber} - ${participantName}:**\n\n${bodyMessage}`; } else { content = `${bodyMessage}`; } From c8410bd146b90b921cf5616df521f455df8ad392 Mon Sep 17 00:00:00 2001 From: Rafael Souza Date: Fri, 8 Nov 2024 07:15:23 -0300 Subject: [PATCH 07/20] Fix Message.Status as String --- .../migration.sql | 232 ++++++++++++++++++ 1 file changed, 232 insertions(+) create mode 100644 prisma/mysql-migrations/20241108101333_fix_message_status_as_string/migration.sql diff --git a/prisma/mysql-migrations/20241108101333_fix_message_status_as_string/migration.sql b/prisma/mysql-migrations/20241108101333_fix_message_status_as_string/migration.sql new file mode 100644 index 00000000..ae17f418 --- /dev/null +++ b/prisma/mysql-migrations/20241108101333_fix_message_status_as_string/migration.sql @@ -0,0 +1,232 @@ +/* + Warnings: + + - You are about to alter the column `createdAt` on the `Chat` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Chat` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Chatwoot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Chatwoot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Contact` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Contact` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Dify` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Dify` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `DifySetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `DifySetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `EvolutionBot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `EvolutionBot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `EvolutionBotSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `EvolutionBotSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Flowise` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Flowise` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `FlowiseSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `FlowiseSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `disconnectionAt` on the `Instance` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Instance` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Instance` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `IntegrationSession` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `IntegrationSession` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `IsOnWhatsapp` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `IsOnWhatsapp` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Label` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Label` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Media` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `OpenaiBot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `OpenaiBot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `OpenaiCreds` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `OpenaiCreds` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `OpenaiSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `OpenaiSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Proxy` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Proxy` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Rabbitmq` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Rabbitmq` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Session` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Setting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Setting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Sqs` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Sqs` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Template` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Template` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Typebot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Typebot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `TypebotSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `TypebotSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Webhook` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Webhook` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Websocket` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Websocket` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + +*/ +-- AlterTable +ALTER TABLE `Chat` ADD COLUMN `unreadMessages` INTEGER NOT NULL DEFAULT 0, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `Chatwoot` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Contact` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `Dify` ADD COLUMN `splitMessages` BOOLEAN NULL DEFAULT false, + ADD COLUMN `timePerChar` INTEGER NULL DEFAULT 50, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `DifySetting` ADD COLUMN `splitMessages` BOOLEAN NULL DEFAULT false, + ADD COLUMN `timePerChar` INTEGER NULL DEFAULT 50, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `EvolutionBot` ADD COLUMN `splitMessages` BOOLEAN NULL DEFAULT false, + ADD COLUMN `timePerChar` INTEGER NULL DEFAULT 50, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `EvolutionBotSetting` ADD COLUMN `splitMessages` BOOLEAN NULL DEFAULT false, + ADD COLUMN `timePerChar` INTEGER NULL DEFAULT 50, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Flowise` ADD COLUMN `splitMessages` BOOLEAN NULL DEFAULT false, + ADD COLUMN `timePerChar` INTEGER NULL DEFAULT 50, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `FlowiseSetting` ADD COLUMN `splitMessages` BOOLEAN NULL DEFAULT false, + ADD COLUMN `timePerChar` INTEGER NULL DEFAULT 50, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Instance` MODIFY `disconnectionAt` TIMESTAMP NULL, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `IntegrationSession` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `IsOnWhatsapp` MODIFY `createdAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Label` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Media` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP; + +-- AlterTable +ALTER TABLE `Message` MODIFY `status` VARCHAR(30) NULL; + +-- AlterTable +ALTER TABLE `OpenaiBot` ADD COLUMN `splitMessages` BOOLEAN NULL DEFAULT false, + ADD COLUMN `timePerChar` INTEGER NULL DEFAULT 50, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `OpenaiCreds` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `OpenaiSetting` ADD COLUMN `splitMessages` BOOLEAN NULL DEFAULT false, + ADD COLUMN `timePerChar` INTEGER NULL DEFAULT 50, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Proxy` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Rabbitmq` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Session` MODIFY `createdAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP; + +-- AlterTable +ALTER TABLE `Setting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Sqs` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Template` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Typebot` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `TypebotSetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Webhook` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Websocket` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- CreateTable +CREATE TABLE `Pusher` ( + `id` VARCHAR(191) NOT NULL, + `enabled` BOOLEAN NOT NULL DEFAULT false, + `appId` VARCHAR(100) NOT NULL, + `key` VARCHAR(100) NOT NULL, + `secret` VARCHAR(100) NOT NULL, + `cluster` VARCHAR(100) NOT NULL, + `useTLS` BOOLEAN NOT NULL DEFAULT false, + `events` JSON NOT NULL, + `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NOT NULL, + `instanceId` VARCHAR(191) NOT NULL, + + UNIQUE INDEX `Pusher_instanceId_key`(`instanceId`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateIndex +CREATE INDEX `Chat_remoteJid_idx` ON `Chat`(`remoteJid`); + +-- CreateIndex +CREATE INDEX `Contact_remoteJid_idx` ON `Contact`(`remoteJid`); + +-- CreateIndex +CREATE INDEX `Setting_instanceId_idx` ON `Setting`(`instanceId`); + +-- CreateIndex +CREATE INDEX `Webhook_instanceId_idx` ON `Webhook`(`instanceId`); + +-- AddForeignKey +ALTER TABLE `Pusher` ADD CONSTRAINT `Pusher_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- RenameIndex +ALTER TABLE `Chat` RENAME INDEX `Chat_instanceId_fkey` TO `Chat_instanceId_idx`; + +-- RenameIndex +ALTER TABLE `Contact` RENAME INDEX `Contact_instanceId_fkey` TO `Contact_instanceId_idx`; + +-- RenameIndex +ALTER TABLE `Message` RENAME INDEX `Message_instanceId_fkey` TO `Message_instanceId_idx`; + +-- RenameIndex +ALTER TABLE `MessageUpdate` RENAME INDEX `MessageUpdate_instanceId_fkey` TO `MessageUpdate_instanceId_idx`; + +-- RenameIndex +ALTER TABLE `MessageUpdate` RENAME INDEX `MessageUpdate_messageId_fkey` TO `MessageUpdate_messageId_idx`; From 7ef8afa9b37c5f00b4c92352700f7eb289a3b7cd Mon Sep 17 00:00:00 2001 From: Richards0n Date: Mon, 11 Nov 2024 16:57:04 -0300 Subject: [PATCH 08/20] Refactor phone number formatting in ChatwootService to improve parsing logic --- .../chatwoot/services/chatwoot.service.ts | 30 ++++++++++++------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts b/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts index adcc9c3c..9b0c60bf 100644 --- a/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts +++ b/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts @@ -1970,11 +1970,16 @@ export class ChatwootService { if (body.key.remoteJid.includes('@g.us')) { const participantName = body.pushName; - const rawPhoneNumber = body.key.remoteJid.split('@')[0]; - const formattedPhoneNumber = `+${rawPhoneNumber.slice(0, 2)} (${rawPhoneNumber.slice( - 2, - 4, - )}) ${rawPhoneNumber.slice(4, 8)}-${rawPhoneNumber.slice(8)}`; + const rawPhoneNumber = body.key.participant.split('@')[0]; + const phoneMatch = rawPhoneNumber.match(/^(\d{2})(\d{2})(\d{4})(\d{4})$/); + + let formattedPhoneNumber: string; + + if (phoneMatch) { + formattedPhoneNumber = `+${phoneMatch[1]} (${phoneMatch[2]}) ${phoneMatch[3]}-${phoneMatch[4]}`; + } else { + formattedPhoneNumber = `+${rawPhoneNumber}`; + } let content: string; @@ -2104,11 +2109,16 @@ export class ChatwootService { if (body.key.remoteJid.includes('@g.us')) { const participantName = body.pushName; - const rawPhoneNumber = body.key.remoteJid.split('@')[0]; - const formattedPhoneNumber = `+${rawPhoneNumber.slice(0, 2)} (${rawPhoneNumber.slice( - 2, - 4, - )}) ${rawPhoneNumber.slice(4, 8)}-${rawPhoneNumber.slice(8)}`; + const rawPhoneNumber = body.key.participant.split('@')[0]; + const phoneMatch = rawPhoneNumber.match(/^(\d{2})(\d{2})(\d{4})(\d{4})$/); + + let formattedPhoneNumber: string; + + if (phoneMatch) { + formattedPhoneNumber = `+${phoneMatch[1]} (${phoneMatch[2]}) ${phoneMatch[3]}-${phoneMatch[4]}`; + } else { + formattedPhoneNumber = `+${rawPhoneNumber}`; + } let content: string; From 753f4ba141d1561d33f33df17aa3d5cdba105a90 Mon Sep 17 00:00:00 2001 From: Alexandre Prado Date: Thu, 14 Nov 2024 02:25:15 -0300 Subject: [PATCH 09/20] fix: chatbots send message text buffer --- src/api/integrations/chatbot/dify/services/dify.service.ts | 2 +- .../chatbot/evolutionBot/services/evolutionBot.service.ts | 4 ++-- .../integrations/chatbot/flowise/services/flowise.service.ts | 4 ++-- .../integrations/chatbot/openai/services/openai.service.ts | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/api/integrations/chatbot/dify/services/dify.service.ts b/src/api/integrations/chatbot/dify/services/dify.service.ts index 9f7b6127..c60782d7 100644 --- a/src/api/integrations/chatbot/dify/services/dify.service.ts +++ b/src/api/integrations/chatbot/dify/services/dify.service.ts @@ -428,8 +428,8 @@ export class DifyService { }, false, ); - textBuffer = ''; } + textBuffer = ''; } if (mediaType === 'audio') { diff --git a/src/api/integrations/chatbot/evolutionBot/services/evolutionBot.service.ts b/src/api/integrations/chatbot/evolutionBot/services/evolutionBot.service.ts index 3b8a8a4a..5275f9e1 100644 --- a/src/api/integrations/chatbot/evolutionBot/services/evolutionBot.service.ts +++ b/src/api/integrations/chatbot/evolutionBot/services/evolutionBot.service.ts @@ -190,8 +190,8 @@ export class EvolutionBotService { }, false, ); - textBuffer = ''; } + textBuffer = ''; } if (mediaType === 'audio') { @@ -274,8 +274,8 @@ export class EvolutionBotService { }, false, ); - textBuffer = ''; } + textBuffer = ''; } sendTelemetry('/message/sendText'); diff --git a/src/api/integrations/chatbot/flowise/services/flowise.service.ts b/src/api/integrations/chatbot/flowise/services/flowise.service.ts index d1ab4e2f..6e4cdbd5 100644 --- a/src/api/integrations/chatbot/flowise/services/flowise.service.ts +++ b/src/api/integrations/chatbot/flowise/services/flowise.service.ts @@ -189,8 +189,8 @@ export class FlowiseService { }, false, ); - textBuffer = ''; } + textBuffer = ''; } if (mediaType === 'audio') { @@ -273,8 +273,8 @@ export class FlowiseService { }, false, ); - textBuffer = ''; } + textBuffer = ''; } sendTelemetry('/message/sendText'); diff --git a/src/api/integrations/chatbot/openai/services/openai.service.ts b/src/api/integrations/chatbot/openai/services/openai.service.ts index 440e3941..16f4ce80 100644 --- a/src/api/integrations/chatbot/openai/services/openai.service.ts +++ b/src/api/integrations/chatbot/openai/services/openai.service.ts @@ -234,8 +234,8 @@ export class OpenaiService { }, false, ); - textBuffer = ''; } + textBuffer = ''; } if (mediaType === 'audio') { @@ -318,8 +318,8 @@ export class OpenaiService { }, false, ); - textBuffer = ''; } + textBuffer = ''; } sendTelemetry('/message/sendText'); From d87d7c07759254b818ae29267ced0a16e60c031c Mon Sep 17 00:00:00 2001 From: Alan Cezar Date: Thu, 14 Nov 2024 09:07:57 -0300 Subject: [PATCH 10/20] fixed image mime type --- src/api/integrations/channel/meta/whatsapp.business.service.ts | 2 +- 1 file changed, 1 insertion(+), 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 65c87961..1b1fada6 100644 --- a/src/api/integrations/channel/meta/whatsapp.business.service.ts +++ b/src/api/integrations/channel/meta/whatsapp.business.service.ts @@ -339,7 +339,7 @@ export class BusinessStartupService extends ChannelStartupService { ? 'audio' : 'video'; - const mimetype = result.headers['content-type']; + const mimetype = result.data?.mime_type || result.headers['content-type']; const contentDisposition = result.headers['content-disposition']; let fileName = `${message.messages[0].id}.${mimetype.split('/')[1]}`; From 59383d5944b923d93e7d09a2bb9717db4c962254 Mon Sep 17 00:00:00 2001 From: Alan Cezar Date: Thu, 14 Nov 2024 09:08:23 -0300 Subject: [PATCH 11/20] fixed remoteJid --- src/api/integrations/channel/meta/whatsapp.business.service.ts | 2 +- 1 file changed, 1 insertion(+), 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 1b1fada6..c847101a 100644 --- a/src/api/integrations/channel/meta/whatsapp.business.service.ts +++ b/src/api/integrations/channel/meta/whatsapp.business.service.ts @@ -352,7 +352,7 @@ export class BusinessStartupService extends ChannelStartupService { const size = result.headers['content-length'] || buffer.data.byteLength; - const fullName = join(`${this.instance.id}`, received.key.remoteJid, mediaType, fileName); + const fullName = join(`${this.instance.id}`, key.remoteJid, mediaType, fileName); await s3Service.uploadFile(fullName, buffer.data, size, { 'Content-Type': mimetype, From 5eaabfb1eb554b831aec30eab33bb37e8fc5d1d4 Mon Sep 17 00:00:00 2001 From: Alan Cezar Date: Thu, 14 Nov 2024 09:08:52 -0300 Subject: [PATCH 12/20] fixed messageId --- .../integrations/channel/meta/whatsapp.business.service.ts | 6 +++++- 1 file changed, 5 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 c847101a..db8b628a 100644 --- a/src/api/integrations/channel/meta/whatsapp.business.service.ts +++ b/src/api/integrations/channel/meta/whatsapp.business.service.ts @@ -358,9 +358,13 @@ export class BusinessStartupService extends ChannelStartupService { 'Content-Type': mimetype, }); + const createdMessage = await this.prismaRepository.message.create({ + data: messageRaw, + }); + await this.prismaRepository.media.create({ data: { - messageId: received.messages[0].id, + messageId: createdMessage.id, instanceId: this.instanceId, type: mediaType, fileName: fullName, From e7ed1446eec34bb857410bd844f05d1c4bf8756c Mon Sep 17 00:00:00 2001 From: Alan Cezar Date: Thu, 14 Nov 2024 09:09:27 -0300 Subject: [PATCH 13/20] saved base64 file in memory --- 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 db8b628a..e348786a 100644 --- a/src/api/integrations/channel/meta/whatsapp.business.service.ts +++ b/src/api/integrations/channel/meta/whatsapp.business.service.ts @@ -375,6 +375,7 @@ export class BusinessStartupService extends ChannelStartupService { const mediaUrl = await s3Service.getObjectUrl(fullName); messageRaw.message.mediaUrl = mediaUrl; + messageRaw.message.base64 = buffer.data.toString('base64'); } catch (error) { this.logger.error(['Error on upload file to minio', error?.message, error?.stack]); } From d797d8177ca5f36c10a8a5e60d868ea85a6d81cd Mon Sep 17 00:00:00 2001 From: Alan Cezar Date: Thu, 14 Nov 2024 09:10:11 -0300 Subject: [PATCH 14/20] added isMediaMessage method --- .../channel/meta/whatsapp.business.service.ts | 14 ++++++++------ 1 file changed, 8 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 e348786a..452c1415 100644 --- a/src/api/integrations/channel/meta/whatsapp.business.service.ts +++ b/src/api/integrations/channel/meta/whatsapp.business.service.ts @@ -70,6 +70,13 @@ export class BusinessStartupService extends ChannelStartupService { await this.closeClient(); } + private isMediaMessage(message: any) { + return message.document || + message.image || + message.audio || + message.video + } + private async post(message: any, params: string) { try { let urlServer = this.configService.get('WA_BUSINESS').URL; @@ -301,12 +308,7 @@ export class BusinessStartupService extends ChannelStartupService { remoteJid: this.phoneNumber, fromMe: received.messages[0].from === received.metadata.phone_number_id, }; - if ( - received?.messages[0].document || - received?.messages[0].image || - received?.messages[0].audio || - received?.messages[0].video - ) { + if (this.isMediaMessage(received?.messages[0])) { messageRaw = { key, pushName, From ef7574273c84c98aab1b1beec0c503a05db56aae Mon Sep 17 00:00:00 2001 From: Alan Cezar Date: Thu, 14 Nov 2024 09:11:21 -0300 Subject: [PATCH 15/20] message recorded for no media messages --- .../channel/meta/whatsapp.business.service.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/api/integrations/channel/meta/whatsapp.business.service.ts b/src/api/integrations/channel/meta/whatsapp.business.service.ts index 452c1415..c44cbb18 100644 --- a/src/api/integrations/channel/meta/whatsapp.business.service.ts +++ b/src/api/integrations/channel/meta/whatsapp.business.service.ts @@ -504,9 +504,11 @@ export class BusinessStartupService extends ChannelStartupService { } } - 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 }, From 99a533afc1103e274404e0da3544a015aa600bc6 Mon Sep 17 00:00:00 2001 From: Vitor Date: Thu, 14 Nov 2024 20:48:47 -0300 Subject: [PATCH 16/20] =?UTF-8?q?o=20chat=20est=C3=A1=20colocando=20a=20co?= =?UTF-8?q?nversa=20como=20pendente=20quando=20o=20cliente=20manda=20mensa?= =?UTF-8?q?gem,=20esse=20c=C3=B3digo=20visa=20corrigir=20isso.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../integrations/chatbot/chatwoot/services/chatwoot.service.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts b/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts index 503a5cc9..d71daae4 100644 --- a/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts +++ b/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts @@ -704,7 +704,7 @@ export class ChatwootService { conversation = contactConversations.payload.find((conversation) => conversation.inbox_id == filterInbox.id); this.logger.verbose(`Found conversation in reopenConversation mode: ${JSON.stringify(conversation)}`); - if (this.provider.conversationPending) { + if (this.provider.conversationPending && conversation.status !== 'open') { if (conversation) { await client.conversations.toggleStatus({ accountId: this.provider.accountId, From 1d5508736eb802884f22bb627f41c06b629f9045 Mon Sep 17 00:00:00 2001 From: Alan Cezar Date: Fri, 15 Nov 2024 17:57:38 -0300 Subject: [PATCH 17/20] =?UTF-8?q?corrigido=20o=20envio=20de=20=C3=A1udio?= =?UTF-8?q?=20para=20OpenAI?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../channel/meta/whatsapp.business.service.ts | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/api/integrations/channel/meta/whatsapp.business.service.ts b/src/api/integrations/channel/meta/whatsapp.business.service.ts index c44cbb18..921d0e6d 100644 --- a/src/api/integrations/channel/meta/whatsapp.business.service.ts +++ b/src/api/integrations/channel/meta/whatsapp.business.service.ts @@ -465,16 +465,23 @@ export class BusinessStartupService extends ChannelStartupService { }, }); + const audioMessage = received?.messages[0]?.audio; + if ( openAiDefaultSettings && openAiDefaultSettings.openaiCredsId && openAiDefaultSettings.speechToText && - received?.message?.audioMessage + audioMessage ) { messageRaw.message.speechToText = await this.openaiService.speechToText( openAiDefaultSettings.OpenaiCreds, - received, - this.client.updateMediaMessage, + { + message: { + mediaUrl: messageRaw.message.mediaUrl, + ...messageRaw, + } + }, + () => {}, ); } } From b7e15be418a2e8b984df6e68ea358685ec43e589 Mon Sep 17 00:00:00 2001 From: Lucas Tonon <105813423+lucastononro@users.noreply.github.com> Date: Sun, 17 Nov 2024 11:36:12 -0300 Subject: [PATCH 18/20] Update docker-compose and .env.example Error: Database URL: Environment variables loaded from .env Prisma schema loaded from prisma/postgresql-schema.prisma Datasource "db": PostgreSQL database "evolution", schema "public" at "localhost:5432" Error: P1001: Can't reach database server at localhost:5432 Fix: Update `docker-compose.yaml` and `.env.example` files to configure PostgreSQL service and connection URI. * **docker-compose.yaml** - Add `listen_addresses=*` command to the `postgres` service. - Add environment variables: `POSTGRES_USER=user`, `POSTGRES_PASSWORD=pass`, `POSTGRES_DB=evolution`, `POSTGRES_HOST_AUTH_METHOD=trust`. * **.env.example** - Update `DATABASE_CONNECTION_URI` to `postgresql://user:pass@postgres:5432/evolution?schema=public`. --- For more details, open the [Copilot Workspace session](https://copilot-workspace.githubnext.com/EvolutionAPI/evolution-api?shareId=XXXX-XXXX-XXXX-XXXX). --- .env.example | 2 +- docker-compose.yaml | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/.env.example b/.env.example index d6412fec..f5b7cde3 100644 --- a/.env.example +++ b/.env.example @@ -26,7 +26,7 @@ DEL_INSTANCE=false # Provider: postgresql | mysql DATABASE_PROVIDER=postgresql -DATABASE_CONNECTION_URI='postgresql://user:pass@localhost:5432/evolution?schema=public' +DATABASE_CONNECTION_URI='postgresql://user:pass@postgres:5432/evolution?schema=public' # Client name for the database connection # It is used to separate an API installation from another that uses the same database. DATABASE_CONNECTION_CLIENT_NAME=evolution_exchange diff --git a/docker-compose.yaml b/docker-compose.yaml index b286919c..9a60a9a9 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -34,12 +34,15 @@ services: image: postgres:15 networks: - evolution-net - command: ["postgres", "-c", "max_connections=1000"] + command: ["postgres", "-c", "max_connections=1000", "-c", "listen_addresses=*"] restart: always ports: - 5432:5432 environment: - - POSTGRES_PASSWORD=PASSWORD + - POSTGRES_USER=user + - POSTGRES_PASSWORD=pass + - POSTGRES_DB=evolution + - POSTGRES_HOST_AUTH_METHOD=trust volumes: - postgres_data:/var/lib/postgresql/data expose: From bfd8c08987be4aa38bfce5c52b4473e6c6438878 Mon Sep 17 00:00:00 2001 From: Richards0n Date: Mon, 18 Nov 2024 20:01:10 -0300 Subject: [PATCH 19/20] Add Windows support for database deployment and improve error handling in runWithProvider.js --- package.json | 3 ++- runWithProvider.js | 22 +++++++++++++++++----- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/package.json b/package.json index f7e77194..0ca3e5a7 100644 --- a/package.json +++ b/package.json @@ -13,6 +13,7 @@ "lint": "eslint --fix --ext .ts src", "db:generate": "node runWithProvider.js \"npx prisma generate --schema ./prisma/DATABASE_PROVIDER-schema.prisma\"", "db:deploy": "node runWithProvider.js \"rm -rf ./prisma/migrations && cp -r ./prisma/DATABASE_PROVIDER-migrations ./prisma/migrations && npx prisma migrate deploy --schema ./prisma/DATABASE_PROVIDER-schema.prisma\"", + "db:deploy:win": "node runWithProvider.js \"xcopy /E /I prisma\\DATABASE_PROVIDER-migrations prisma\\migrations && npx prisma migrate deploy --schema prisma\\DATABASE_PROVIDER-schema.prisma\"", "db:studio": "node runWithProvider.js \"npx prisma studio --schema ./prisma/DATABASE_PROVIDER-schema.prisma\"", "db:migrate:dev": "node runWithProvider.js \"rm -rf ./prisma/migrations && cp -r ./prisma/DATABASE_PROVIDER-migrations ./prisma/migrations && npx prisma migrate dev --schema ./prisma/DATABASE_PROVIDER-schema.prisma && cp -r ./prisma/migrations/* ./prisma/DATABASE_PROVIDER-migrations\"" }, @@ -115,4 +116,4 @@ "tsconfig-paths": "^4.2.0", "typescript": "^5.5.4" } -} +} \ No newline at end of file diff --git a/runWithProvider.js b/runWithProvider.js index a8275763..154538be 100644 --- a/runWithProvider.js +++ b/runWithProvider.js @@ -1,19 +1,31 @@ const dotenv = require('dotenv'); const { execSync } = require('child_process'); +const { existsSync } = require('fs'); + dotenv.config(); const { DATABASE_PROVIDER } = process.env; -const databaseProviderDefault = DATABASE_PROVIDER ?? "postgresql" +const databaseProviderDefault = DATABASE_PROVIDER ?? 'postgresql'; if (!DATABASE_PROVIDER) { - console.error(`DATABASE_PROVIDER is not set in the .env file, using default: ${databaseProviderDefault}`); - // process.exit(1); + console.warn(`DATABASE_PROVIDER is not set in the .env file, using default: ${databaseProviderDefault}`); } -const command = process.argv +let command = process.argv .slice(2) .join(' ') - .replace(/\DATABASE_PROVIDER/g, databaseProviderDefault); + .replace(/DATABASE_PROVIDER/g, databaseProviderDefault); + +if (command.includes('rmdir') && existsSync('prisma\\migrations')) { + try { + execSync('rmdir /S /Q prisma\\migrations', { stdio: 'inherit' }); + } catch (error) { + console.error(`Error removing directory: prisma\\migrations`); + process.exit(1); + } +} else if (command.includes('rmdir')) { + console.warn(`Directory 'prisma\\migrations' does not exist, skipping removal.`); +} try { execSync(command, { stdio: 'inherit' }); From 3582cd38fb2ca0f464625a6c57fdbb13d9f237d5 Mon Sep 17 00:00:00 2001 From: Richards0n Date: Mon, 18 Nov 2024 20:07:08 -0300 Subject: [PATCH 20/20] Add Windows support for database migration commands in package.json --- package.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 0ca3e5a7..c57c2e9e 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,8 @@ "db:deploy": "node runWithProvider.js \"rm -rf ./prisma/migrations && cp -r ./prisma/DATABASE_PROVIDER-migrations ./prisma/migrations && npx prisma migrate deploy --schema ./prisma/DATABASE_PROVIDER-schema.prisma\"", "db:deploy:win": "node runWithProvider.js \"xcopy /E /I prisma\\DATABASE_PROVIDER-migrations prisma\\migrations && npx prisma migrate deploy --schema prisma\\DATABASE_PROVIDER-schema.prisma\"", "db:studio": "node runWithProvider.js \"npx prisma studio --schema ./prisma/DATABASE_PROVIDER-schema.prisma\"", - "db:migrate:dev": "node runWithProvider.js \"rm -rf ./prisma/migrations && cp -r ./prisma/DATABASE_PROVIDER-migrations ./prisma/migrations && npx prisma migrate dev --schema ./prisma/DATABASE_PROVIDER-schema.prisma && cp -r ./prisma/migrations/* ./prisma/DATABASE_PROVIDER-migrations\"" + "db:migrate:dev": "node runWithProvider.js \"rm -rf ./prisma/migrations && cp -r ./prisma/DATABASE_PROVIDER-migrations ./prisma/migrations && npx prisma migrate dev --schema ./prisma/DATABASE_PROVIDER-schema.prisma && cp -r ./prisma/migrations/* ./prisma/DATABASE_PROVIDER-migrations\"", + "db:migrate:dev:win": "node runWithProvider.js \"xcopy /E /I prisma\\DATABASE_PROVIDER-migrations prisma\\migrations && npx prisma migrate dev --schema prisma\\DATABASE_PROVIDER-schema.prisma\"" }, "repository": { "type": "git",