getNextProxy method

  1. @override
Proxy? getNextProxy()
override

Gets the next proxy from the internal list

Implementation

@override
Proxy? getNextProxy() {
  if (_proxies.isEmpty) {
    return null;
  }

  final now = DateTime.now().millisecondsSinceEpoch;

  // Try to find a suitable proxy
  for (int i = 0; i < _proxies.length; i++) {
    final index = (_currentIndex + i) % _proxies.length;
    final proxy = _proxies[index];
    final proxyKey = '${proxy.ip}:${proxy.port}';

    // Check if the proxy has too many consecutive failures
    final failures = _failureCount[proxyKey] ?? 0;
    if (failures >= maxConsecutiveFailures) {
      continue;
    }

    // Check if the proxy was used too recently
    final lastUsed = _lastUsedTime[proxyKey] ?? 0;
    if (now - lastUsed < minTimeBetweenUses) {
      continue;
    }

    // Update the current index and last used time
    _currentIndex = (index + 1) % _proxies.length;
    _lastUsedTime[proxyKey] = now;

    return proxy;
  }

  // If no suitable proxy was found, reset failure counts and try again
  if (_allProxiesHaveTooManyFailures()) {
    _failureCount.clear();
    return getNextProxy();
  }

  // If all proxies were used too recently, use the least recently used one
  final leastRecentlyUsed = _getLeastRecentlyUsedProxy();
  if (leastRecentlyUsed != null) {
    final proxyKey = '${leastRecentlyUsed.ip}:${leastRecentlyUsed.port}';
    _lastUsedTime[proxyKey] = now;
    return leastRecentlyUsed;
  }

  return null;
}