selectProxy method

  1. @override
Proxy selectProxy(
  1. List<Proxy> proxies
)
override

Selects a proxy from the given list

Implementation

@override
Proxy selectProxy(List<Proxy> proxies) {
  if (proxies.isEmpty) {
    throw Exception('No proxies available');
  }

  // Filter proxies by country if specified
  List<Proxy> filteredProxies = proxies;
  if (targetCountry != null && targetCountry!.isNotEmpty) {
    final countryProxies =
        proxies
            .where(
              (proxy) =>
                  proxy.country?.toLowerCase() ==
                  targetCountry!.toLowerCase(),
            )
            .toList();

    if (countryProxies.isNotEmpty) {
      filteredProxies = countryProxies;
    }
  }

  // Filter proxies by region if specified and preferSameRegion is true
  if (preferSameRegion && targetRegion != null && targetRegion!.isNotEmpty) {
    final regionProxies =
        filteredProxies
            .where(
              (proxy) =>
                  proxy.region?.toLowerCase() == targetRegion!.toLowerCase(),
            )
            .toList();

    if (regionProxies.isNotEmpty) {
      filteredProxies = regionProxies;
    }
  }

  // Filter proxies by latency if specified
  if (useLatencyBasedSelection && maxLatency != null && maxLatency! > 0) {
    final lowLatencyProxies =
        filteredProxies
            .where(
              (proxy) =>
                  proxy.latency != null && proxy.latency! <= maxLatency!,
            )
            .toList();

    if (lowLatencyProxies.isNotEmpty) {
      filteredProxies = lowLatencyProxies;
    }
  }

  // If no proxies match the criteria, use the original list
  if (filteredProxies.isEmpty) {
    filteredProxies = proxies;
  }

  // If using latency-based selection, select based on weighted latency
  if (useLatencyBasedSelection) {
    return _selectByLatency(filteredProxies);
  }

  // Otherwise, select randomly
  return filteredProxies[_random.nextInt(filteredProxies.length)];
}