selectOptimalProxy method

Proxy? selectOptimalProxy(
  1. String url,
  2. List<Proxy> availableProxies,
  3. String? lastErrorMessage
)

Gets the optimal proxy for the given URL and error pattern

Implementation

Proxy? selectOptimalProxy(
  String url,
  List<Proxy> availableProxies,
  String? lastErrorMessage,
) {
  if (availableProxies.isEmpty) return null;

  // If we have an error message, try to select a proxy that might work better
  if (lastErrorMessage != null) {
    final lowerError = lastErrorMessage.toLowerCase();

    // For connection issues, prefer proxies with different IPs
    if (lowerError.contains('connection closed') ||
        lowerError.contains('connection reset') ||
        lowerError.contains('timeout')) {
      // Try to find a proxy with a different IP class
      final lastProxy = availableProxies.last;
      final differentClassProxies = availableProxies.where(
        (p) => !p.ip.startsWith(lastProxy.ip.split('.').first),
      );

      if (differentClassProxies.isNotEmpty) {
        return differentClassProxies.first;
      }
    }

    // For SSL issues, prefer proxies with different IPs
    if (lowerError.contains('ssl') || lowerError.contains('certificate')) {
      // Try to find a different proxy
      if (availableProxies.length > 1) {
        return availableProxies[1]; // Return the second proxy in the list
      }
    }
  }

  // Default to the first available proxy
  return availableProxies.first;
}