All files / services EvolutionAPIService.js

0% Statements 0/135
0% Branches 0/44
0% Functions 0/17
0% Lines 0/135

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
/**
 * Evolution API Service
 * Handles communication with Evolution API
 * 
 * @module services/EvolutionAPIService
 */
 
const axios = require('axios');
const { logger } = require('../config/logger');
 
class EvolutionAPIService {
  constructor() {
    // Don't cache these values - always read from process.env
    logger.info('Evolution API Service initialized');
  }
 
  /**
   * Get axios client with current environment variables
   * @returns {Object} Axios instance
   */
  getClient() {
    const baseURL = process.env.EVOLUTION_API_URL || 'http://localhost:8080';
    const apiKey = process.env.EVOLUTION_API_KEY;
 
    return axios.create({
      baseURL: baseURL,
      headers: {
        'Content-Type': 'application/json',
        'apikey': apiKey
      },
      timeout: 30000
    });
  }
 
  /**
   * Create new instance
   * @param {string} instanceName - Unique instance name
   * @param {string} webhookUrl - Webhook URL for events
   * @param {Array} webhookEvents - Events to subscribe
   * @returns {Promise<Object>} Instance data
   */
  async createInstance(instanceName, webhookUrl, webhookEvents = []) {
    try {
      logger.info('Creating Evolution API instance', { instanceName, webhookUrl, webhookEvents });
 
      const client = this.getClient();
      
      // Log the request details
      logger.info('Evolution API request details', {
        baseURL: process.env.EVOLUTION_API_URL,
        hasApiKey: !!process.env.EVOLUTION_API_KEY,
        instanceName,
        webhookUrl
      });
      
      const response = await client.post('/instance/create', {
        instanceName,
        qrcode: true,
        integration: 'WHATSAPP-BAILEYS'
      });
 
      logger.info('Instance created successfully', { instanceName, data: response.data });
 
      // CRITICAL: Set webhook immediately after creation with webhookByEvents: true
      if (webhookUrl) {
        try {
          logger.info('Configuring webhook with webhookByEvents: true', { 
            instanceName, 
            webhookUrl,
            events: webhookEvents 
          });
          
          await this.setWebhook(instanceName, webhookUrl, webhookEvents);
          
          logger.info('✅ Webhook configured successfully with webhookByEvents: true', { instanceName });
        } catch (webhookError) {
          logger.error('❌ Failed to set webhook during instance creation', {
            instanceName,
            webhookUrl,
            error: webhookError.message,
            stack: webhookError.stack,
            response: webhookError.response?.data
          });
          // Don't throw - instance is still usable, but log prominently
          logger.warn('⚠️  Instance created but webhook configuration failed - manual configuration may be needed');
        }
      }
 
      return response.data;
    } catch (error) {
      logger.error('Error creating Evolution API instance', {
        instanceName,
        error: error.message,
        response: error.response?.data,
        status: error.response?.status,
        stack: error.stack
      });
      throw new Error(`Failed to create instance: ${error.response?.data?.message || error.message}`);
    }
  }
 
  /**
   * Set webhook for instance
   * @param {string} instanceName - Instance name
   * @param {string} webhookUrl - Webhook URL
   * @param {Array} events - Events to subscribe
   * @returns {Promise<Object>} Webhook data
   */
  async setWebhook(instanceName, webhookUrl, events = []) {
    try {
      logger.info('Setting webhook for instance', { instanceName, webhookUrl, events });
 
      const defaultEvents = [
        'QRCODE_UPDATED',
        'CONNECTION_UPDATE',
        'MESSAGES_UPSERT',
        'MESSAGES_UPDATE',
        'SEND_MESSAGE'
      ];
 
      const client = this.getClient();
      const response = await client.post(`/webhook/set/${instanceName}`, {
        webhook: {
          enabled: true,
          url: webhookUrl,
          webhookByEvents: true,  // CRÍTICO: deve ser true
          webhookBase64: false,
          events: events.length > 0 ? events : defaultEvents,
          headers: {
            'ngrok-skip-browser-warning': 'true'
          }
        }
      });
 
      logger.info('Webhook set successfully', { instanceName, response: response.data });
 
      return response.data;
    } catch (error) {
      logger.error('Error setting webhook', {
        instanceName,
        error: error.message,
        response: error.response?.data
      });
      throw new Error(`Failed to set webhook: ${error.response?.data?.message || error.message}`);
    }
  }
 
  /**
   * Get instance connection status
   * @param {string} instanceName - Instance name
   * @returns {Promise<Object>} Status data
   */
  async getInstanceStatus(instanceName) {
    try {
      logger.info('Getting instance status from Evolution API', { 
        instanceName,
        url: `/instance/connectionState/${instanceName}`,
        baseURL: process.env.EVOLUTION_API_URL
      });
      
      const client = this.getClient();
      const response = await client.get(`/instance/connectionState/${instanceName}`);
      
      logger.info('Instance status retrieved successfully', { 
        instanceName, 
        status: response.data,
        statusCode: response.status
      });
 
      return response.data;
    } catch (error) {
      logger.error('Error getting instance status from Evolution API', {
        instanceName,
        error: error.message,
        status: error.response?.status,
        statusText: error.response?.statusText,
        responseData: error.response?.data,
        url: error.config?.url,
        baseURL: error.config?.baseURL
      });
      throw new Error(`Failed to get status: ${error.response?.data?.message || error.message}`);
    }
  }
 
  /**
   * Connect instance (generate QR code)
   * @param {string} instanceName - Instance name
   * @returns {Promise<Object>} Connection data with QR code
   */
  async connectInstance(instanceName) {
    try {
      logger.info('Connecting instance via Evolution API', { 
        instanceName,
        url: `/instance/connect/${instanceName}`,
        baseURL: process.env.EVOLUTION_API_URL
      });
 
      const client = this.getClient();
      const response = await client.get(`/instance/connect/${instanceName}`);
 
      logger.info('Instance connection response', { 
        instanceName,
        hasData: !!response.data,
        dataKeys: response.data ? Object.keys(response.data) : [],
        status: response.status,
        fullData: response.data
      });
 
      return response.data;
    } catch (error) {
      logger.error('Error connecting instance via Evolution API', {
        instanceName,
        error: error.message,
        status: error.response?.status,
        statusText: error.response?.statusText,
        responseData: error.response?.data,
        url: error.config?.url,
        baseURL: error.config?.baseURL
      });
      throw new Error(`Failed to connect: ${error.response?.data?.message || error.message}`);
    }
  }
 
  /**
   * Disconnect instance
   * @param {string} instanceName - Instance name
   * @returns {Promise<Object>} Disconnect result
   */
  async disconnectInstance(instanceName) {
    try {
      logger.info('Disconnecting instance', { instanceName });
 
      const client = this.getClient();
      const response = await client.delete(`/instance/logout/${instanceName}`);
 
      logger.info('Instance disconnected', { instanceName });
 
      return response.data;
    } catch (error) {
      logger.error('Error disconnecting instance', {
        instanceName,
        error: error.message,
        response: error.response?.data
      });
      throw new Error(`Failed to disconnect: ${error.response?.data?.message || error.message}`);
    }
  }
 
  /**
   * Delete instance
   * @param {string} instanceName - Instance name
   * @returns {Promise<Object>} Delete result
   */
  async deleteInstance(instanceName) {
    try {
      logger.info('Deleting instance from Evolution API', { 
        instanceName,
        url: `/instance/delete/${instanceName}`,
        baseURL: process.env.EVOLUTION_API_URL
      });
 
      const client = this.getClient();
      const response = await client.delete(`/instance/delete/${instanceName}`);
 
      logger.info('Instance deleted from Evolution API successfully', { 
        instanceName,
        status: response.status,
        data: response.data
      });
 
      return response.data;
    } catch (error) {
      logger.error('Error deleting instance from Evolution API', {
        instanceName,
        error: error.message,
        status: error.response?.status,
        statusText: error.response?.statusText,
        responseData: error.response?.data,
        url: error.config?.url,
        baseURL: error.config?.baseURL
      });
      throw new Error(`Failed to delete: ${error.response?.data?.message || error.message}`);
    }
  }
 
  /**
   * Send text message
   * @param {string} instanceName - Instance name
   * @param {string} phoneNumber - Recipient phone number (can be remoteJid or just number)
   * @param {string} message - Message text
   * @returns {Promise<Object>} Send result
   */
  async sendTextMessage(instanceName, phoneNumber, message) {
    return this.sendMessage(instanceName, phoneNumber, message);
  }
 
  /**
   * Send message
   * @param {string} instanceName - Instance name
   * @param {string} phoneNumber - Recipient phone number
   * @param {string} message - Message text
   * @returns {Promise<Object>} Send result
   */
  async sendMessage(instanceName, phoneNumber, message) {
    try {
      logger.info('Sending message via Evolution API', { instanceName, phoneNumber });
 
      // Format phone number (remove + and @s.whatsapp.net if present)
      const formattedPhone = phoneNumber.replace(/^\+/, '').replace('@s.whatsapp.net', '').replace('@lid', '');
 
      const client = this.getClient();
      const response = await client.post(`/message/sendText/${instanceName}`, {
        number: formattedPhone,
        text: message
      });
 
      logger.info('Message sent successfully', { instanceName, phoneNumber });
 
      return response.data;
    } catch (error) {
      logger.error('Error sending message', {
        instanceName,
        phoneNumber,
        error: error.message,
        response: error.response?.data
      });
      throw new Error(`Failed to send message: ${error.response?.data?.message || error.message}`);
    }
  }
 
  /**
   * Send reaction to a message
   * @param {string} instanceName - Instance name
   * @param {Object} messageKey - Message key object from Evolution API
   * @param {string} emoji - Emoji to react with
   * @returns {Promise<Object>} Send result
   */
  async sendReaction(instanceName, messageKey, emoji) {
    try {
      logger.info('Sending reaction via Evolution API', { instanceName, emoji });
 
      const client = this.getClient();
      const response = await client.post(`/message/sendReaction/${instanceName}`, {
        key: messageKey,
        reaction: emoji
      });
 
      logger.info('Reaction sent successfully', { instanceName, emoji });
 
      return response.data;
    } catch (error) {
      logger.error('Error sending reaction', {
        instanceName,
        emoji,
        error: error.message,
        response: error.response?.data
      });
      throw new Error(`Failed to send reaction: ${error.response?.data?.message || error.message}`);
    }
  }
 
  /**
   * Send media message
   * @param {string} instanceName - Instance name
   * @param {string} phoneNumber - Recipient phone number
   * @param {string} mediaUrl - Media URL
   * @param {string} caption - Media caption
   * @param {string} mediaType - Media type (image, video, audio, document)
   * @returns {Promise<Object>} Send result
   */
  async sendMedia(instanceName, phoneNumber, mediaUrl, caption = '', mediaType = 'image') {
    try {
      logger.info('Sending media via Evolution API', { instanceName, phoneNumber, mediaType });
 
      // Format phone number
      const formattedPhone = phoneNumber.replace(/^\+/, '').replace('@s.whatsapp.net', '').replace('@lid', '');
 
      let endpoint = '/message/sendMedia';
      const payload = {
        number: formattedPhone,
        mediatype: mediaType,
        media: mediaUrl
      };
 
      if (caption) {
        payload.caption = caption;
      }
 
      const client = this.getClient();
      const response = await client.post(`${endpoint}/${instanceName}`, payload);
 
      logger.info('Media sent successfully', { instanceName, phoneNumber, mediaType });
 
      return response.data;
    } catch (error) {
      logger.error('Error sending media', {
        instanceName,
        phoneNumber,
        mediaType,
        error: error.message,
        response: error.response?.data
      });
      throw new Error(`Failed to send media: ${error.response?.data?.message || error.message}`);
    }
  }
 
  /**
   * Get QR code
   * @param {string} instanceName - Instance name
   * @returns {Promise<Object>} QR code data
   */
  async getQRCode(instanceName) {
    try {
      const client = this.getClient();
      
      logger.info('Requesting QR code from Evolution API', { 
        instanceName,
        url: `/instance/qrcode/${instanceName}`,
        baseURL: process.env.EVOLUTION_API_URL
      });
      
      const response = await client.get(`/instance/qrcode/${instanceName}`);
 
      logger.info('QR code response received', { 
        instanceName,
        hasData: !!response.data,
        dataKeys: response.data ? Object.keys(response.data) : [],
        fullData: response.data
      });
 
      return response.data;
    } catch (error) {
      logger.error('Error getting QR code from Evolution API', {
        instanceName,
        error: error.message,
        status: error.response?.status,
        statusText: error.response?.statusText,
        responseData: error.response?.data,
        url: error.config?.url,
        baseURL: error.config?.baseURL
      });
      throw new Error(`Failed to get QR code: ${error.response?.data?.message || error.message}`);
    }
  }
 
  /**
   * Restart instance
   * @param {string} instanceName - Instance name
   * @returns {Promise<Object>} Restart result
   */
  async restartInstance(instanceName) {
    try {
      logger.info('Restarting instance', { instanceName });
 
      const client = this.getClient();
      const response = await client.put(`/instance/restart/${instanceName}`);
 
      logger.info('Instance restarted', { instanceName });
 
      return response.data;
    } catch (error) {
      logger.error('Error restarting instance', {
        instanceName,
        error: error.message,
        response: error.response?.data
      });
      throw new Error(`Failed to restart: ${error.response?.data?.message || error.message}`);
    }
  }
 
  /**
   * Get instance info
   * @param {string} instanceName - Instance name
   * @returns {Promise<Object>} Instance info
   */
  async getInstanceInfo(instanceName) {
    try {
      logger.info('Getting instance info from Evolution API', { instanceName });
      
      const client = this.getClient();
      const response = await client.get(`/instance/fetchInstances/${instanceName}`);
 
      logger.info('Instance info retrieved', { 
        instanceName,
        hasProfilePic: !!response.data?.profilePicUrl,
        profileName: response.data?.profileName
      });
 
      return response.data;
    } catch (error) {
      logger.error('Error getting instance info', {
        instanceName,
        error: error.message,
        response: error.response?.data
      });
      throw new Error(`Failed to get instance info: ${error.response?.data?.message || error.message}`);
    }
  }
 
  /**
   * Get instance settings
   * @param {string} instanceName - Instance name
   * @returns {Promise<Object>} Instance settings
   */
  async getInstanceSettings(instanceName) {
    try {
      logger.info('Getting instance settings', { instanceName });
 
      const client = this.getClient();
      const response = await client.get(`/settings/find/${instanceName}`);
 
      logger.info('Instance settings retrieved', { instanceName, settings: response.data });
 
      return response.data;
    } catch (error) {
      logger.error('Error getting instance settings', {
        instanceName,
        error: error.message,
        response: error.response?.data
      });
      throw new Error(`Failed to get settings: ${error.response?.data?.message || error.message}`);
    }
  }
 
  /**
   * Set instance settings
   * @param {string} instanceName - Instance name
   * @param {Object} settings - Settings object
   * @returns {Promise<Object>} Updated settings
   */
  async setInstanceSettings(instanceName, settings) {
    try {
      logger.info('Setting instance settings', { instanceName, settings });
 
      const client = this.getClient();
      const response = await client.post(`/settings/set/${instanceName}`, settings);
 
      logger.info('Instance settings updated', { instanceName });
 
      return response.data;
    } catch (error) {
      logger.error('Error setting instance settings', {
        instanceName,
        error: error.message,
        response: error.response?.data
      });
      throw new Error(`Failed to set settings: ${error.response?.data?.message || error.message}`);
    }
  }
}
 
module.exports = new EvolutionAPIService();