selectProxy method
Selects the next proxy from the given list
Implementation
@override
Proxy selectProxy(List<Proxy> proxies) {
if (proxies.isEmpty) {
throw ArgumentError('Proxy list cannot be empty');
}
// Group proxies by country
final proxiesByCountry = <String?, List<Proxy>>{};
final countryCodes = <String?>[];
for (final proxy in proxies) {
final countryCode = proxy.countryCode;
if (!proxiesByCountry.containsKey(countryCode)) {
proxiesByCountry[countryCode] = [];
countryCodes.add(countryCode);
}
proxiesByCountry[countryCode]!.add(proxy);
}
// Sort country codes for deterministic behavior
countryCodes.sort((a, b) {
if (a == null) return 1;
if (b == null) return -1;
return a.compareTo(b);
});
if (countryCodes.isEmpty) {
return proxies.first;
}
// Get the current country code
final countryIndex = _currentCountryIndex % countryCodes.length;
final countryCode = countryCodes[countryIndex];
// Get the proxies for the current country
final countryProxies = proxiesByCountry[countryCode] ?? [];
if (countryProxies.isEmpty) {
// Move to the next country
_currentCountryIndex = (_currentCountryIndex + 1) % countryCodes.length;
return selectProxy(proxies);
}
// Get the current proxy
final proxyIndex = _currentProxyIndex % countryProxies.length;
final proxy = countryProxies[proxyIndex];
// Move to the next proxy in the current country
_currentProxyIndex = (_currentProxyIndex + 1) % countryProxies.length;
// If we've gone through all proxies in the current country, move to the next country
if (_currentProxyIndex == 0) {
_currentCountryIndex = (_currentCountryIndex + 1) % countryCodes.length;
}
return proxy;
}