feat: Implement startup retry mechanism for custom stations and equalizer persistence
- Added state management for startup retry and custom station handling in `EstadoRadio`. - Created tasks for implementing strict TDD with RED tests for HTTP failure retries and EQ persistence. - Developed verification report to ensure compliance with TDD practices. - Introduced fake services for testing, including `FakeServicioAudio`, `FakeServicioFavoritos`, and `FakeServicioRadio`. - Implemented widget tests for `PantallaInicio` and `PantallaFavoritos` to validate UI behavior with custom stations. - Enhanced `ServicioRadio` to support host rotation and retry logic for API calls. - Established a new configuration file to enforce project constraints and testing rules.
This commit is contained in:
@@ -1,35 +1,58 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
import '../modelos/emisora.dart';
|
||||
|
||||
/// Cliente para la Radio Browser API (https://api.radio-browser.info/).
|
||||
///
|
||||
/// Selecciona automáticamente un servidor disponible de entre los DNS
|
||||
/// resueltos para `all.api.radio-browser.info` y rota en caso de error.
|
||||
///
|
||||
/// ### Rate limiting
|
||||
/// La API no tiene límite documentado, pero por cortesía limitamos a
|
||||
/// peticiones con `?limit` explícito y no hacemos polling automático.
|
||||
/// Aplica reintentos acotados con rotación de host para tolerar fallos
|
||||
/// transitorios al iniciar.
|
||||
class ServicioRadio {
|
||||
static const _dnsHost = 'all.api.radio-browser.info';
|
||||
static const _timeout = Duration(seconds: 10);
|
||||
static const _timeoutPorDefecto = Duration(seconds: 10);
|
||||
static const _maxIntentosPorDefecto = 3;
|
||||
static const _retryDelayPorDefecto = Duration(milliseconds: 250);
|
||||
|
||||
// Servidores conocidos como fallback si el DNS falla
|
||||
// Servidores conocidos como fallback si el DNS falla.
|
||||
static const _servidoresFallback = [
|
||||
'de1.api.radio-browser.info',
|
||||
'nl1.api.radio-browser.info',
|
||||
'at1.api.radio-browser.info',
|
||||
];
|
||||
|
||||
ServicioRadio({
|
||||
http.Client? cliente,
|
||||
List<String>? servidores,
|
||||
int maxIntentos = _maxIntentosPorDefecto,
|
||||
Duration retryDelay = _retryDelayPorDefecto,
|
||||
Duration timeout = _timeoutPorDefecto,
|
||||
}) : _cliente = cliente ?? http.Client(),
|
||||
_servidores = (servidores == null || servidores.isEmpty)
|
||||
? List<String>.from(_servidoresFallback)
|
||||
: List<String>.from(servidores),
|
||||
_maxIntentos = maxIntentos < 1 ? 1 : maxIntentos,
|
||||
_retryDelay = retryDelay,
|
||||
_timeout = timeout;
|
||||
|
||||
final http.Client _cliente;
|
||||
final List<String> _servidores;
|
||||
final int _maxIntentos;
|
||||
final Duration _retryDelay;
|
||||
final Duration _timeout;
|
||||
|
||||
String? _servidorActual;
|
||||
|
||||
Future<String> _servidor() async {
|
||||
if (_servidorActual != null) return _servidorActual!;
|
||||
// Intentar DNS lookup simplificado — usamos fallback directamente
|
||||
final servidores = List<String>.from(_servidoresFallback)..shuffle(Random());
|
||||
_servidorActual = servidores.first;
|
||||
return _servidorActual!;
|
||||
int _indiceServidorInicial() {
|
||||
if (_servidorActual == null) {
|
||||
return 0;
|
||||
}
|
||||
final index = _servidores.indexOf(_servidorActual!);
|
||||
return index >= 0 ? index : 0;
|
||||
}
|
||||
|
||||
String _servidorPorIntento(int indiceBase, int intento) {
|
||||
final index = (indiceBase + intento) % _servidores.length;
|
||||
return _servidores[index];
|
||||
}
|
||||
|
||||
Uri _uri(String servidor, String path, Map<String, String> params) {
|
||||
@@ -40,31 +63,45 @@ class ServicioRadio {
|
||||
}
|
||||
|
||||
Future<List<Emisora>> _get(String path, Map<String, String> params) async {
|
||||
final servidor = await _servidor();
|
||||
// lastcheckok=1 filtra emisoras que la API verificó como funcionales
|
||||
final uri = _uri(servidor, path, {
|
||||
'lastcheckok': '1',
|
||||
...params,
|
||||
});
|
||||
try {
|
||||
final resp = await http.get(uri, headers: {
|
||||
'User-Agent': 'PluriWave/0.1.0 (es.freetimelab.pluriwave)',
|
||||
}).timeout(_timeout);
|
||||
Exception? ultimoError;
|
||||
final indiceBase = _indiceServidorInicial();
|
||||
final totalIntentos = _maxIntentos;
|
||||
|
||||
if (resp.statusCode != 200) {
|
||||
throw Exception('API error ${resp.statusCode}');
|
||||
for (int intento = 0; intento < totalIntentos; intento++) {
|
||||
final servidor = _servidorPorIntento(indiceBase, intento);
|
||||
final uri = _uri(servidor, path, {
|
||||
'lastcheckok': '1',
|
||||
...params,
|
||||
});
|
||||
|
||||
try {
|
||||
final resp = await _cliente.get(uri, headers: {
|
||||
'User-Agent': 'PluriWave/0.1.0 (es.freetimelab.pluriwave)',
|
||||
}).timeout(_timeout);
|
||||
|
||||
if (resp.statusCode != 200) {
|
||||
throw Exception('API error ${resp.statusCode}');
|
||||
}
|
||||
|
||||
final lista = json.decode(resp.body) as List<dynamic>;
|
||||
_servidorActual = servidor;
|
||||
return lista
|
||||
.cast<Map<String, dynamic>>()
|
||||
.map(Emisora.fromApi)
|
||||
.where((e) => e.uuid.isNotEmpty && e.url.isNotEmpty)
|
||||
.toList();
|
||||
} on Exception catch (e) {
|
||||
ultimoError = e;
|
||||
_servidorActual = null;
|
||||
|
||||
final ultimoIntento = intento == (totalIntentos - 1);
|
||||
if (!ultimoIntento && _retryDelay > Duration.zero) {
|
||||
await Future<void>.delayed(_retryDelay);
|
||||
}
|
||||
}
|
||||
final lista = json.decode(resp.body) as List<dynamic>;
|
||||
return lista
|
||||
.cast<Map<String, dynamic>>()
|
||||
.map(Emisora.fromApi)
|
||||
.where((e) => e.uuid.isNotEmpty && e.url.isNotEmpty)
|
||||
.toList();
|
||||
} catch (e) {
|
||||
// Rotar servidor en el siguiente intento
|
||||
_servidorActual = null;
|
||||
rethrow;
|
||||
}
|
||||
|
||||
throw ultimoError ?? Exception('Error desconocido al consultar la API');
|
||||
}
|
||||
|
||||
/// Emisoras más votadas globalmente.
|
||||
@@ -133,16 +170,17 @@ class ServicioRadio {
|
||||
});
|
||||
}
|
||||
|
||||
/// Registrar un click en la API (buenas prácticas de ciudadanía API).
|
||||
/// Registrar un click en la API (best effort).
|
||||
Future<void> registrarClick(String uuid) async {
|
||||
try {
|
||||
final servidor = await _servidor();
|
||||
await http.get(
|
||||
final servidor =
|
||||
_servidorActual ?? _servidorPorIntento(_indiceServidorInicial(), 0);
|
||||
await _cliente.get(
|
||||
Uri.https(servidor, '/json/url/$uuid'),
|
||||
headers: {'User-Agent': 'PluriWave/0.1.0 (es.freetimelab.pluriwave)'},
|
||||
).timeout(_timeout);
|
||||
} catch (_) {
|
||||
// No crítico — ignorar silenciosamente
|
||||
// No crítico, ignorar.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user