From c77650a7d6f7cb26b06e214fafc812e8c1c0c275 Mon Sep 17 00:00:00 2001 From: nestordavalos Date: Sat, 12 Oct 2024 14:08:46 -0300 Subject: [PATCH] Add voice-calls-baileys dependency and implement startConnection function --- package.json | 3 +- .../integrations/channel/whatsapp/wavoip.ts | 85 +++++++++++++++++++ .../whatsapp/whatsapp.baileys.service.ts | 7 ++ 3 files changed, 94 insertions(+), 1 deletion(-) create mode 100644 src/api/integrations/channel/whatsapp/wavoip.ts diff --git a/package.json b/package.json index 9946c585..da9e543b 100644 --- a/package.json +++ b/package.json @@ -89,7 +89,8 @@ "sharp": "^0.32.2", "socket.io": "^4.7.1", "tsup": "^8.2.4", - "uuid": "^9.0.0" + "uuid": "^9.0.0", + "voice-calls-baileys": "^1.0.5" }, "devDependencies": { "@types/compression": "^1.7.2", diff --git a/src/api/integrations/channel/whatsapp/wavoip.ts b/src/api/integrations/channel/whatsapp/wavoip.ts new file mode 100644 index 00000000..ecc638fc --- /dev/null +++ b/src/api/integrations/channel/whatsapp/wavoip.ts @@ -0,0 +1,85 @@ +import axios from 'axios'; +import { useVoiceCallsBaileys } from 'voice-calls-baileys'; + +// Define el tipo de respuesta esperada para mayor seguridad +interface ApiResponse { + type?: string; + data?: any; + message?: string; + result?: { + code?: string; + }; +} + +// Hace una solicitud a la API +async function makeRequest(token: string): Promise { + try { + const url = 'https://api.wavoip.com/devices/evolution'; + const payload = { + name: '', + token: token, + }; + + console.log(`Enviando solicitud a la API con el token: ${token}`); + const response = await axios.post(url, payload); + const data = response.data; + + if (data?.type === 'success') { + console.log('¡Solicitud exitosa!'); + return true; + } else if (data?.result?.code === 'ER_DUP_ENTRY') { + console.warn('La sesión ya existe, omitiendo creación...'); + return true; // Tratar como éxito ya que la sesión ya existe. + } else { + console.log('Respuesta no válida. Intentando de nuevo...', data); + return false; + } + } catch (error: any) { + const statusCode = error?.response?.status; + const errorMessage = error?.response?.data?.message || error?.message || error; + + if (statusCode === 500) { + console.error('Error 500: ', error?.response?.data || 'Error en el servidor.'); + } else { + console.error(`Error ${statusCode}:`, errorMessage); + } + return false; + } +} + +// Reintenta la solicitud hasta que tenga éxito o supere el límite de reintentos +async function retryRequest(token: string, maxRetries = 5): Promise { + let attempts = 0; + + while (attempts < maxRetries) { + console.log(`Intento ${attempts + 1} de ${maxRetries}`); + const success = await makeRequest(token); + + if (success) { + console.log('Conexión establecida exitosamente.'); + return; + } + + attempts++; + console.log('Esperando 1 segundo antes de volver a intentar...'); + await new Promise((resolve) => setTimeout(resolve, 1000)); // Espera 1 segundo antes de volver a intentar + } + + console.error('Límite de reintentos alcanzado. La solicitud ha fallado.'); +} + +// Inicia la conexión con el cliente y la instancia +export const startConnection = async (client: any, instance: { token: string }): Promise => { + const token = instance.token; + + if (!token) { + console.error('Token no recibido. No se puede iniciar la conexión.'); + return; + } + + console.log('Iniciando la conexión con el token:', token); + await retryRequest(token); + + console.log('Usando Voice Calls con Baileys...'); + useVoiceCallsBaileys(token, client, 'open', true); +}; diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index 19b20590..28750568 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -45,6 +45,7 @@ import { SendTextDto, StatusMessage, } from '@api/dto/sendMessage.dto'; +import { startConnection } from '@api/integrations/channel/whatsapp/wavoip'; import { chatwootImport } from '@api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper'; import * as s3Service from '@api/integrations/storage/s3/libs/minio.server'; import { ProviderFiles } from '@api/provider/sessions'; @@ -371,6 +372,12 @@ export class BaileysStartupService extends ChannelStartupService { } if (connection === 'open') { + try { + await startConnection(this.client, { token: this.token, ...this.instance }); + } catch (error) { + this.logger.error(error); + } + this.instance.wuid = this.client.user.id.replace(/:\d+/, ''); try { const profilePic = await this.profilePicture(this.instance.wuid);