Team Ai
Apppublic

oex2003/evolution-api

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
proxy.controller.ts69 linesDownload Raw Back to controllers
1import { InstanceDto } from '@api/dto/instance.dto';2import { ProxyDto } from '@api/dto/proxy.dto';3import { WAMonitoringService } from '@api/services/monitor.service';4import { ProxyService } from '@api/services/proxy.service';5import { Logger } from '@config/logger.config';6import { BadRequestException, NotFoundException } from '@exceptions';7import { makeProxyAgent } from '@utils/makeProxyAgent';8import axios from 'axios';9 10const logger = new Logger('ProxyController');11 12export class ProxyController {13  constructor(14    private readonly proxyService: ProxyService,15    private readonly waMonitor: WAMonitoringService,16  ) {}17 18  public async createProxy(instance: InstanceDto, data: ProxyDto) {19    if (!this.waMonitor.waInstances[instance.instanceName]) {20      throw new NotFoundException(`The "${instance.instanceName}" instance does not exist`);21    }22 23    if (!data?.enabled) {24      data.host = '';25      data.port = '';26      data.protocol = '';27      data.username = '';28      data.password = '';29    }30 31    if (data.host) {32      const testProxy = await this.testProxy(data);33      if (!testProxy) {34        throw new BadRequestException('Invalid proxy');35      }36    }37 38    return this.proxyService.create(instance, data);39  }40 41  public async findProxy(instance: InstanceDto) {42    if (!this.waMonitor.waInstances[instance.instanceName]) {43      throw new NotFoundException(`The "${instance.instanceName}" instance does not exist`);44    }45 46    return this.proxyService.find(instance);47  }48 49  public async testProxy(proxy: ProxyDto) {50    try {51      const serverIp = await axios.get('https://icanhazip.com/');52      const response = await axios.get('https://icanhazip.com/', {53        httpsAgent: makeProxyAgent(proxy),54      });55 56      return response?.data !== serverIp?.data;57    } catch (error) {58      if (axios.isAxiosError(error) && error.response?.data) {59        logger.error('testProxy error: ' + error.response.data);60      } else if (axios.isAxiosError(error)) {61        logger.error('testProxy error: ');62      } else {63        logger.error('testProxy error: ');64      }65      return false;66    }67  }68}69