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:
@@ -2,15 +2,16 @@ import 'dart:developer' as developer;
|
||||
|
||||
import 'package:audio_service/audio_service.dart';
|
||||
import 'package:just_audio/just_audio.dart';
|
||||
|
||||
import '../modelos/emisora.dart';
|
||||
import '../modelos/preset_ecualizador.dart';
|
||||
|
||||
/// Estado de reproducción expuesto al UI.
|
||||
enum EstadoReproduccion { detenido, cargando, reproduciendo, pausado, error }
|
||||
|
||||
// ─────────────────────────────────────────────────────────────
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Handler global — inicializado en main.dart con AudioService.init
|
||||
// ─────────────────────────────────────────────────────────────
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
PluriWaveAudioHandler? _handlerGlobal;
|
||||
|
||||
void registrarHandler(PluriWaveAudioHandler handler) {
|
||||
@@ -73,7 +74,7 @@ class ServicioAudio {
|
||||
bool get estaSonando => _handler.playbackState.value.playing;
|
||||
Future<void> dispose() async {}
|
||||
|
||||
// ── Ecualizador ──────────────────────────────────────────────────────────
|
||||
// ── Ecualizador ───────────────────────────────────────────────────────────
|
||||
AndroidEqualizer? get ecualizador => _handler.ecualizador;
|
||||
bool get ecualizadorDisponible => _handler.ecualizadorDisponible;
|
||||
PresetEcualizador get presetActual => _handler.presetActual;
|
||||
@@ -85,9 +86,9 @@ class ServicioAudio {
|
||||
_handler.setBanda(index, db);
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// AudioHandler
|
||||
// ─────────────────────────────────────────────────────────────
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
class PluriWaveAudioHandler extends BaseAudioHandler with SeekHandler {
|
||||
final AndroidEqualizer _eq = AndroidEqualizer();
|
||||
|
||||
@@ -132,9 +133,6 @@ class PluriWaveAudioHandler extends BaseAudioHandler with SeekHandler {
|
||||
playbackState.add(playbackState.value.copyWith(bufferedPosition: pos));
|
||||
});
|
||||
|
||||
// ── Escuchar errores de ExoPlayer ─────────────────────────────────────
|
||||
// Captura todos los PlaybackException: TYPE_SOURCE (HTTP cleartext,
|
||||
// certificado inválido, 404), TYPE_UNEXPECTED, timeout de conexión, etc.
|
||||
_player.playbackEventStream.listen(
|
||||
(_) {},
|
||||
onError: (Object error, StackTrace stackTrace) {
|
||||
@@ -143,8 +141,7 @@ class PluriWaveAudioHandler extends BaseAudioHandler with SeekHandler {
|
||||
);
|
||||
}
|
||||
|
||||
/// Gestiona cualquier error de reproducción de ExoPlayer de forma
|
||||
/// controlada: emite estado de error al UI y resetea la reproducción.
|
||||
/// Gestiona cualquier error de reproducción de ExoPlayer.
|
||||
void _gestionarErrorReproduccion(Object error) {
|
||||
String mensaje;
|
||||
String codigoLog;
|
||||
@@ -160,17 +157,17 @@ class PluriWaveAudioHandler extends BaseAudioHandler with SeekHandler {
|
||||
developer.log(
|
||||
'[PluriWave] Error reproducción: $codigoLog',
|
||||
name: 'ServicioAudio',
|
||||
level: 900, // warning
|
||||
level: 900,
|
||||
);
|
||||
|
||||
// Emitir estado de error al UI (incluye mensaje legible)
|
||||
playbackState.add(playbackState.value.copyWith(
|
||||
processingState: AudioProcessingState.error,
|
||||
playing: false,
|
||||
errorMessage: mensaje,
|
||||
));
|
||||
emisoraActual = null;
|
||||
mediaItem.add(null);
|
||||
|
||||
// Resetear el player a estado idle limpio (sin lanzar otra excepción)
|
||||
_player.stop().catchError((_) {});
|
||||
}
|
||||
|
||||
@@ -178,7 +175,6 @@ class PluriWaveAudioHandler extends BaseAudioHandler with SeekHandler {
|
||||
String _mensajeAmigable(PlayerException e) {
|
||||
final code = e.code;
|
||||
|
||||
// ERROR_CODE_IO_* — problemas de red/fuente
|
||||
if (code >= 2000 && code < 3000) {
|
||||
if (code == 2001) return 'Sin conexión a internet';
|
||||
if (code == 2002) return 'La URL de la radio no es válida';
|
||||
@@ -187,18 +183,14 @@ class PluriWaveAudioHandler extends BaseAudioHandler with SeekHandler {
|
||||
return 'No se puede conectar a la radio';
|
||||
}
|
||||
|
||||
// ERROR_CODE_PARSING_* — formato de stream no soportado
|
||||
if (code >= 3000 && code < 4000) {
|
||||
return 'Formato de stream no compatible';
|
||||
}
|
||||
|
||||
// ERROR_CODE_DECODING_* — error de decodificación
|
||||
if (code >= 4000 && code < 5000) {
|
||||
return 'Error al decodificar el stream de audio';
|
||||
}
|
||||
|
||||
// TYPE_SOURCE — error en la fuente (HTTP cleartext, cert, etc.)
|
||||
// En just_audio suele mapearse como code=-1 o message con "Cleartext"
|
||||
final msg = e.message ?? '';
|
||||
if (msg.contains('Cleartext') || msg.contains('cleartext')) {
|
||||
return 'Esta radio usa HTTP sin cifrar (no permitido)';
|
||||
@@ -227,12 +219,9 @@ class PluriWaveAudioHandler extends BaseAudioHandler with SeekHandler {
|
||||
await _player.stop();
|
||||
await _player.setUrl(mediaItem.id);
|
||||
await _player.play();
|
||||
// Habilitar ecualizador tras reproducir (necesita audio activo)
|
||||
emisoraActual = _emisoraDesdeMediaItem(mediaItem);
|
||||
await _activarEcualizador();
|
||||
} on PlayerException catch (e) {
|
||||
// El error ya llega por playbackEventStream.onError, pero también
|
||||
// lo capturamos aquí para asegurarnos de emitir el estado de error
|
||||
// y propagarlo como excepción (para que EstadoRadio muestre el mensaje).
|
||||
_gestionarErrorReproduccion(e);
|
||||
throw Exception(_mensajeAmigable(e));
|
||||
} on Exception catch (e) {
|
||||
@@ -246,6 +235,8 @@ class PluriWaveAudioHandler extends BaseAudioHandler with SeekHandler {
|
||||
playing: false,
|
||||
errorMessage: 'Error inesperado al reproducir',
|
||||
));
|
||||
emisoraActual = null;
|
||||
this.mediaItem.add(null);
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
@@ -318,4 +309,15 @@ class PluriWaveAudioHandler extends BaseAudioHandler with SeekHandler {
|
||||
await stop();
|
||||
await _player.dispose();
|
||||
}
|
||||
|
||||
Emisora _emisoraDesdeMediaItem(MediaItem mediaItem) {
|
||||
final uuid = mediaItem.extras?['uuid'] as String? ?? mediaItem.id;
|
||||
return Emisora(
|
||||
uuid: uuid,
|
||||
nombre: mediaItem.title,
|
||||
url: mediaItem.id,
|
||||
pais: (mediaItem.artist?.isNotEmpty ?? false) ? mediaItem.artist : null,
|
||||
favicon: mediaItem.artUri?.toString(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
104
lib/servicios/servicio_ecualizador.dart
Normal file
104
lib/servicios/servicio_ecualizador.dart
Normal file
@@ -0,0 +1,104 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../modelos/preset_ecualizador.dart';
|
||||
|
||||
class ConfiguracionEcualizador {
|
||||
const ConfiguracionEcualizador({
|
||||
required this.principal,
|
||||
required this.porEmisora,
|
||||
});
|
||||
|
||||
final PresetEcualizador principal;
|
||||
final Map<String, PresetEcualizador> porEmisora;
|
||||
}
|
||||
|
||||
class ServicioEcualizador {
|
||||
static const _keyPresetPrincipal = 'eq_preset_principal_v1';
|
||||
static const _keyPresetsPorEmisora = 'eq_presets_por_emisora_v1';
|
||||
|
||||
Future<ConfiguracionEcualizador> cargar() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final principal = _leerPresetPrincipal(prefs);
|
||||
final porEmisora = _leerPresetsPorEmisora(prefs);
|
||||
return ConfiguracionEcualizador(
|
||||
principal: principal,
|
||||
porEmisora: porEmisora,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> guardarPrincipal(PresetEcualizador preset) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_keyPresetPrincipal, jsonEncode(preset.toJson()));
|
||||
}
|
||||
|
||||
Future<void> guardarPorEmisora(String uuid, PresetEcualizador preset) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final mapa = _leerPresetsPorEmisora(prefs);
|
||||
mapa[uuid] = preset;
|
||||
await _guardarPresetsPorEmisora(prefs, mapa);
|
||||
}
|
||||
|
||||
Future<void> eliminarPorEmisora(String uuid) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final mapa = _leerPresetsPorEmisora(prefs);
|
||||
mapa.remove(uuid);
|
||||
await _guardarPresetsPorEmisora(prefs, mapa);
|
||||
}
|
||||
|
||||
Future<void> guardarConfiguracion(ConfiguracionEcualizador config) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(
|
||||
_keyPresetPrincipal,
|
||||
jsonEncode(config.principal.toJson()),
|
||||
);
|
||||
await _guardarPresetsPorEmisora(prefs, config.porEmisora);
|
||||
}
|
||||
|
||||
PresetEcualizador _leerPresetPrincipal(SharedPreferences prefs) {
|
||||
final raw = prefs.getString(_keyPresetPrincipal);
|
||||
if (raw == null || raw.isEmpty) {
|
||||
return PresetEcualizador.flat;
|
||||
}
|
||||
try {
|
||||
return PresetEcualizador.desdeJson(
|
||||
Map<String, dynamic>.from(jsonDecode(raw) as Map),
|
||||
);
|
||||
} catch (_) {
|
||||
return PresetEcualizador.flat;
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, PresetEcualizador> _leerPresetsPorEmisora(
|
||||
SharedPreferences prefs,
|
||||
) {
|
||||
final raw = prefs.getString(_keyPresetsPorEmisora);
|
||||
if (raw == null || raw.isEmpty) {
|
||||
return {};
|
||||
}
|
||||
try {
|
||||
final data = Map<String, dynamic>.from(jsonDecode(raw) as Map);
|
||||
return data.map(
|
||||
(uuid, preset) => MapEntry(
|
||||
uuid,
|
||||
PresetEcualizador.desdeJson(
|
||||
Map<String, dynamic>.from(preset as Map),
|
||||
),
|
||||
),
|
||||
);
|
||||
} catch (_) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _guardarPresetsPorEmisora(
|
||||
SharedPreferences prefs,
|
||||
Map<String, PresetEcualizador> mapa,
|
||||
) async {
|
||||
final serializado = mapa.map(
|
||||
(uuid, preset) => MapEntry(uuid, preset.toJson()),
|
||||
);
|
||||
await prefs.setString(_keyPresetsPorEmisora, jsonEncode(serializado));
|
||||
}
|
||||
}
|
||||
@@ -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