feat(paises): add country browser and extract shared radio transport

Extracts ServicioRadio's transport loop (server discovery, host rotation,
bounded retries, User-Agent, timeout, status check, json.decode, sticky-host
bookkeeping) out of `_get` into a new `_getJson(path, params) ->
Future<List<dynamic>>` helper, moved as one block with no logic edits. `_get`
is reimplemented on top, still owning every station-specific concern:
`lastcheckok: '1'`, `Emisora.fromApi` + the empty-uuid/url filter, and the
`_compararCalidad` quality sort. `_getJson` is deliberately sort-agnostic and
filter-agnostic so a non-station endpoint can reuse the resilience behaviour
without inheriting station-only semantics.

Non-negotiable ordering followed per design ADR-4: new
test/servicios/servicio_radio_transporte_test.dart characterises all 8
existing station calls (7 via `_get` plus `registrarClick`, which builds its
own URI) against the UNMODIFIED `_get` first - green by construction -
pinning path, lastcheckok=1, hidebroken=true, a non-empty User-Agent, exact
order/reverse/limit/offset, and the exact returned UUID sequence from a
fixture with deliberately shuffled bitrate/clickcount/votes. That last
assertion is what makes the extraction safe: a sort that silently sank into
transport would pass every other check. Re-running the same file after the
extraction is byte-identical green. test/servicios/servicio_radio_test.dart
is untouched by this work unit - its passing unmodified is itself a signal
that transport wasn't disturbed.

The 6 pre-existing `order: bitrate` occurrences (obtenerPopulares,
buscarPorNombre, buscarPorPais, buscarPorIdioma, buscarPorTag, buscar) are
untouched - a deliberate server-side quality bias deciding which stations
return within `limit`, unrelated to and never to be confused with the
user-facing "Ordenar" control, which stays entirely client-side via the
existing OrdenEmisoras (Engram reference/radio-browser-sort-order).

Behaviour delta, accepted per ADR-4, not a regression: moving
`_servidorActual` bookkeeping into `_getJson` means a successful
`/json/countries` call now warms the sticky host for subsequent station
calls too - one shared warm mirror per instance, desirable, not per-call-type
state.

Adds the Paises browser over the verified `/json/countries` contract (Engram
reference/radio-browser-countries-endpoint): new lib/modelos/pais_radio.dart
(`PaisRadio.fromApi` parses `stationcount` via `int.tryParse` since the API
returns it as a JSON string, not an int - an `as int` cast would throw),
`obtenerPaises()` sends neither `lastcheckok` nor `order` (the screen sorts
client-side by name; the API's raw byte order isn't proper collation for any
locale this app ships), and inherits `hidebroken=true` from the unchanged
`_uri` (desirable here too, since the endpoint's own default is false).
`EstadoBusqueda` gains `paises`/`cargandoPaises`/`cargarPaises()` with an
in-memory cache guard so re-entering the screen never refetches.

New PantallaPaises (lib/pantallas/pantalla_paises.dart): a "Tus idiomas"
shortlist (one representative country per the app's 13 supported locales,
matched against the fetched list - the proposal/spec name this section but
don't specify its derivation) above the full alphabetical list, each entry
showing its parsed station count. Reachable from Buscar's discovery landing
state via a new entry row, added now rather than left dangling per this
file's own forward-reference comment (and the WU15/WU15b lesson: a
fully-tested but unreachable screen is a real defect, not a follow-up).

New ARB keys (en/es only, matching this change's established precedent):
countriesScreenTitle, countriesYourLanguagesTitle, countriesAllTitle,
radioCountriesError.

Tests: 631 -> 649 (2 skipped, unchanged). flutter analyze unchanged at 1
pre-existing info. grep confirms `countrycodes` appears nowhere in lib/.
This commit is contained in:
2026-07-29 09:36:31 +02:00
parent 9bd828139f
commit c6f16c81b5
27 changed files with 1087 additions and 46 deletions
+34
View File
@@ -6,6 +6,7 @@ import 'package:geolocator/geolocator.dart';
import '../l10n/gen/app_localizations.dart';
import '../modelos/emisora.dart';
import '../modelos/pais_radio.dart';
import '../servicios/servicio_radio.dart';
import 'orden_emisoras.dart';
@@ -50,6 +51,8 @@ class EstadoBusqueda extends ChangeNotifier {
String? _ultimoIdioma;
String? _ultimoTag;
int? _ultimoMinBitrate;
List<PaisRadio> _paises = [];
bool _cargandoPaises = false;
final _memoResultados = MemoLista<Emisora>();
final _memoCercanas = MemoLista<Emisora>();
@@ -68,6 +71,8 @@ class EstadoBusqueda extends ChangeNotifier {
bool get cargandoCercanas => _cargandoCercanas;
String? get paisCercanoDetectado => _paisCercanoDetectado;
String? get errorCercanas => _errorCercanas;
List<PaisRadio> get paises => _paises;
bool get cargandoPaises => _cargandoPaises;
/// Re-renders sorted views after the user changes the list ordering
/// (called by EstadoRadio, which owns that preference).
@@ -219,4 +224,33 @@ class EstadoBusqueda extends ChangeNotifier {
notifyListeners();
}
}
/// Fetches the Países browser's country list (WU7, `station-discovery-browse`
/// spec). In-memory cache guard: once populated, re-entering the screen
/// does not refetch — this is deliberately NOT time-based invalidation,
/// since the country/station-count universe changes on a scale of days,
/// not per app session.
///
/// Sorted once here (case-insensitive by name, same convention as
/// `ordenarEmisoras`'s `OrdenEmisoras.nombre` case) since the API orders by
/// raw byte order, not proper collation (design ADR-4).
Future<void> cargarPaises() async {
if (_paises.isNotEmpty || _cargandoPaises) return;
_cargandoPaises = true;
notifyListeners();
try {
// Defensive copy: `radio.obtenerPaises()` makes no growable/mutable
// guarantee about the list it returns (tests may hand back a `const`
// list) — sorting in place would throw on an unmodifiable list.
final ordenados = List<PaisRadio>.of(await radio.obtenerPaises())..sort(
(a, b) => a.nombre.toLowerCase().compareTo(b.nombre.toLowerCase()),
);
_paises = ordenados;
} catch (_) {
_alError?.call(_textos().radioCountriesError);
} finally {
_cargandoPaises = false;
notifyListeners();
}
}
}
+4
View File
@@ -309,6 +309,10 @@
"searchNoResultsSubtitle": "Try removing filters or typing another name to find an active station.",
"searchResultsCount": "{count, plural, =1{1 result} other{{count} results}}",
"searchClearFiltersAction": "{count, plural, =1{Clear filter} other{Clear {count} filters}}",
"countriesScreenTitle": "Countries",
"countriesYourLanguagesTitle": "Your languages",
"countriesAllTitle": "All countries",
"radioCountriesError": "We couldn't load the countries.",
"countrySpain": "Spain",
"countryUsa": "USA",
"countryMexico": "Mexico",
+4
View File
@@ -309,6 +309,10 @@
"searchNoResultsSubtitle": "Probá quitar filtros o escribir otro nombre para encontrar una señal activa.",
"searchResultsCount": "{count, plural, =1{1 resultado} other{{count} resultados}}",
"searchClearFiltersAction": "{count, plural, =1{Quitar el filtro} other{Quitar los {count} filtros}}",
"countriesScreenTitle": "Países",
"countriesYourLanguagesTitle": "Tus idiomas",
"countriesAllTitle": "Todos los países",
"radioCountriesError": "No pudimos cargar los países.",
"countrySpain": "España",
"countryUsa": "EE. UU.",
"countryMexico": "México",
+24
View File
@@ -1150,6 +1150,30 @@ abstract class AppLocalizations {
/// **'{count, plural, =1{Quitar el filtro} other{Quitar los {count} filtros}}'**
String searchClearFiltersAction(num count);
/// No description provided for @countriesScreenTitle.
///
/// In es, this message translates to:
/// **'Países'**
String get countriesScreenTitle;
/// No description provided for @countriesYourLanguagesTitle.
///
/// In es, this message translates to:
/// **'Tus idiomas'**
String get countriesYourLanguagesTitle;
/// No description provided for @countriesAllTitle.
///
/// In es, this message translates to:
/// **'Todos los países'**
String get countriesAllTitle;
/// No description provided for @radioCountriesError.
///
/// In es, this message translates to:
/// **'No pudimos cargar los países.'**
String get radioCountriesError;
/// No description provided for @countrySpain.
///
/// In es, this message translates to:
+12
View File
@@ -611,6 +611,18 @@ class AppLocalizationsAr extends AppLocalizations {
return '$_temp0';
}
@override
String get countriesScreenTitle => 'Países';
@override
String get countriesYourLanguagesTitle => 'Tus idiomas';
@override
String get countriesAllTitle => 'Todos los países';
@override
String get radioCountriesError => 'No pudimos cargar los países.';
@override
String get countrySpain => 'إسبانيا';
+12
View File
@@ -615,6 +615,18 @@ class AppLocalizationsBn extends AppLocalizations {
return '$_temp0';
}
@override
String get countriesScreenTitle => 'Países';
@override
String get countriesYourLanguagesTitle => 'Tus idiomas';
@override
String get countriesAllTitle => 'Todos los países';
@override
String get radioCountriesError => 'No pudimos cargar los países.';
@override
String get countrySpain => 'স্পেন';
+12
View File
@@ -618,6 +618,18 @@ class AppLocalizationsDe extends AppLocalizations {
return '$_temp0';
}
@override
String get countriesScreenTitle => 'Países';
@override
String get countriesYourLanguagesTitle => 'Tus idiomas';
@override
String get countriesAllTitle => 'Todos los países';
@override
String get radioCountriesError => 'No pudimos cargar los países.';
@override
String get countrySpain => 'Spanien';
+12
View File
@@ -612,6 +612,18 @@ class AppLocalizationsEn extends AppLocalizations {
return '$_temp0';
}
@override
String get countriesScreenTitle => 'Countries';
@override
String get countriesYourLanguagesTitle => 'Your languages';
@override
String get countriesAllTitle => 'All countries';
@override
String get radioCountriesError => 'We couldn\'t load the countries.';
@override
String get countrySpain => 'Spain';
+12
View File
@@ -616,6 +616,18 @@ class AppLocalizationsEs extends AppLocalizations {
return '$_temp0';
}
@override
String get countriesScreenTitle => 'Países';
@override
String get countriesYourLanguagesTitle => 'Tus idiomas';
@override
String get countriesAllTitle => 'Todos los países';
@override
String get radioCountriesError => 'No pudimos cargar los países.';
@override
String get countrySpain => 'España';
+12
View File
@@ -620,6 +620,18 @@ class AppLocalizationsFr extends AppLocalizations {
return '$_temp0';
}
@override
String get countriesScreenTitle => 'Países';
@override
String get countriesYourLanguagesTitle => 'Tus idiomas';
@override
String get countriesAllTitle => 'Todos los países';
@override
String get radioCountriesError => 'No pudimos cargar los países.';
@override
String get countrySpain => 'Espagne';
+12
View File
@@ -613,6 +613,18 @@ class AppLocalizationsHi extends AppLocalizations {
return '$_temp0';
}
@override
String get countriesScreenTitle => 'Países';
@override
String get countriesYourLanguagesTitle => 'Tus idiomas';
@override
String get countriesAllTitle => 'Todos los países';
@override
String get radioCountriesError => 'No pudimos cargar los países.';
@override
String get countrySpain => 'स्पेन';
+12
View File
@@ -614,6 +614,18 @@ class AppLocalizationsId extends AppLocalizations {
return '$_temp0';
}
@override
String get countriesScreenTitle => 'Países';
@override
String get countriesYourLanguagesTitle => 'Tus idiomas';
@override
String get countriesAllTitle => 'Todos los países';
@override
String get radioCountriesError => 'No pudimos cargar los países.';
@override
String get countrySpain => 'Spanyol';
+12
View File
@@ -616,6 +616,18 @@ class AppLocalizationsIt extends AppLocalizations {
return '$_temp0';
}
@override
String get countriesScreenTitle => 'Países';
@override
String get countriesYourLanguagesTitle => 'Tus idiomas';
@override
String get countriesAllTitle => 'Todos los países';
@override
String get radioCountriesError => 'No pudimos cargar los países.';
@override
String get countrySpain => 'Spagna';
+12
View File
@@ -593,6 +593,18 @@ class AppLocalizationsJa extends AppLocalizations {
return '$_temp0';
}
@override
String get countriesScreenTitle => 'Países';
@override
String get countriesYourLanguagesTitle => 'Tus idiomas';
@override
String get countriesAllTitle => 'Todos los países';
@override
String get radioCountriesError => 'No pudimos cargar los países.';
@override
String get countrySpain => 'スペイン';
+12
View File
@@ -615,6 +615,18 @@ class AppLocalizationsPt extends AppLocalizations {
return '$_temp0';
}
@override
String get countriesScreenTitle => 'Países';
@override
String get countriesYourLanguagesTitle => 'Tus idiomas';
@override
String get countriesAllTitle => 'Todos los países';
@override
String get radioCountriesError => 'No pudimos cargar los países.';
@override
String get countrySpain => 'Espanha';
+12
View File
@@ -616,6 +616,18 @@ class AppLocalizationsRu extends AppLocalizations {
return '$_temp0';
}
@override
String get countriesScreenTitle => 'Países';
@override
String get countriesYourLanguagesTitle => 'Tus idiomas';
@override
String get countriesAllTitle => 'Todos los países';
@override
String get radioCountriesError => 'No pudimos cargar los países.';
@override
String get countrySpain => 'Испания';
+12
View File
@@ -591,6 +591,18 @@ class AppLocalizationsZh extends AppLocalizations {
return '$_temp0';
}
@override
String get countriesScreenTitle => 'Países';
@override
String get countriesYourLanguagesTitle => 'Tus idiomas';
@override
String get countriesAllTitle => 'Todos los países';
@override
String get radioCountriesError => 'No pudimos cargar los países.';
@override
String get countrySpain => '西班牙';
+28
View File
@@ -0,0 +1,28 @@
/// Country entry from the Radio Browser `/json/countries` endpoint.
///
/// `stationcount` arrives as a JSON **string**, not a number — an `as int`
/// cast throws at runtime. This model always goes through `int.tryParse`
/// and defaults safely when a field is missing or malformed (Engram
/// `reference/radio-browser-countries-endpoint`, id 2500).
class PaisRadio {
const PaisRadio({
required this.nombre,
required this.codigoIso,
required this.numeroEmisoras,
});
/// `name` — country name as the API returns it (not translated).
final String nombre;
/// `iso_3166_1` — ISO 3166-1 alpha-2, normalized to uppercase.
final String codigoIso;
/// `stationcount`, parsed from its JSON string form.
final int numeroEmisoras;
factory PaisRadio.fromApi(Map<String, dynamic> json) => PaisRadio(
nombre: json['name'] as String? ?? '',
codigoIso: (json['iso_3166_1'] as String? ?? '').toUpperCase(),
numeroEmisoras: int.tryParse('${json['stationcount'] ?? ''}') ?? 0,
);
}
+63 -23
View File
@@ -11,8 +11,10 @@ import '../widgets/pluri_glass_surface.dart';
import '../widgets/pluri_icon.dart';
import '../widgets/pluri_layout.dart';
import '../widgets/pluri_premium_widgets.dart';
import '../widgets/pluri_push_scaffold.dart';
import 'package:pluriwave/widgets/tarjeta_emisora.dart';
import 'pantalla_paises.dart';
import 'reproducir_minimizado.dart';
const _paises = [
@@ -190,6 +192,7 @@ class _PantallaBuscarState extends State<PantallaBuscar> {
_seccionCercanas(context, theme, l10n),
_seccionTendencias(context, theme, l10n),
_chipGeneros(context, theme, l10n),
_seccionPaises(context, theme, l10n),
if (context.select<EstadoRadio, String?>((e) => e.error) != null)
_errorBanner(
context,
@@ -213,21 +216,15 @@ class _PantallaBuscarState extends State<PantallaBuscar> {
final l10n = AppLocalizations.of(context);
final pills = <Widget>[
if (_paisSeleccionado != null)
_pillFiltro(
_paisLabelSeleccionado(l10n) ?? _paisSeleccionado!,
() {
setState(() => _paisSeleccionado = null);
_buscar();
},
),
_pillFiltro(_paisLabelSeleccionado(l10n) ?? _paisSeleccionado!, () {
setState(() => _paisSeleccionado = null);
_buscar();
}),
if (_idiomaSeleccionado != null)
_pillFiltro(
_idiomaLabelSeleccionado(l10n) ?? _idiomaSeleccionado!,
() {
setState(() => _idiomaSeleccionado = null);
_buscar();
},
),
_pillFiltro(_idiomaLabelSeleccionado(l10n) ?? _idiomaSeleccionado!, () {
setState(() => _idiomaSeleccionado = null);
_buscar();
}),
if (_calidadMinima != null)
_pillFiltro('$_calidadMinima kbps', () {
setState(() => _calidadMinima = null);
@@ -249,7 +246,8 @@ class _PantallaBuscarState extends State<PantallaBuscar> {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (pills.isNotEmpty) Wrap(spacing: 8, runSpacing: 8, children: pills),
if (pills.isNotEmpty)
Wrap(spacing: 8, runSpacing: 8, children: pills),
if (pills.isNotEmpty && estado.resultados.isNotEmpty)
const SizedBox(height: 10),
if (!estado.cargando && estado.resultados.isNotEmpty)
@@ -438,9 +436,7 @@ class _PantallaBuscarState extends State<PantallaBuscar> {
selected: seleccionado == value,
visualDensity: VisualDensity.compact,
onSelected:
(_) => onChanged(
seleccionado == value ? null : value,
),
(_) => onChanged(seleccionado == value ? null : value),
),
],
),
@@ -486,9 +482,7 @@ class _PantallaBuscarState extends State<PantallaBuscar> {
selected: seleccionado == value,
visualDensity: VisualDensity.compact,
onSelected:
(_) => onChanged(
seleccionado == value ? null : value,
),
(_) => onChanged(seleccionado == value ? null : value),
),
],
),
@@ -527,7 +521,9 @@ class _PantallaBuscarState extends State<PantallaBuscar> {
child: PluriEmptyState(
glyph: PluriIconGlyph.search,
title:
sinFiltros ? l10n.searchEmptyTitle : l10n.searchNoResultsTitle,
sinFiltros
? l10n.searchEmptyTitle
: l10n.searchNoResultsTitle,
subtitle:
sinFiltros
? l10n.searchEmptySubtitle
@@ -803,6 +799,46 @@ class _PantallaBuscarState extends State<PantallaBuscar> {
);
}
/// WU7, `station-discovery-browse` spec: the "Países entry point" the
/// spec's landing-state scenario lists. Deferred from WU6 (this class's
/// own doc comment: `PantallaPaises` did not exist yet); added here now
/// that it does, alongside the screen it targets — an unreachable screen
/// would repeat the WU15/WU15b lesson (a fully-tested screen shipped with
/// no navigation path to it).
Widget _seccionPaises(
BuildContext context,
ThemeData theme,
AppLocalizations l10n,
) {
return Padding(
padding: const EdgeInsets.fromLTRB(
PluriLayout.horizontal,
8,
PluriLayout.horizontal,
0,
),
child: PluriGlassSurface(
padding: EdgeInsets.zero,
// `PluriGlassSurface` paints via `DecoratedBox`, not `Material` — a
// tappable `ListTile` needs its own `Material` ancestor or its ink
// splash silently fails to paint (Flutter's own debug assertion).
child: Material(
type: MaterialType.transparency,
child: ListTile(
leading: const Icon(Icons.public_rounded),
title: Text(l10n.countriesScreenTitle),
trailing: const Icon(Icons.chevron_right_rounded),
onTap:
() => PluriPushScaffold.push(
context,
(_) => const PantallaPaises(),
),
),
),
),
);
}
Widget _errorBanner(
BuildContext context,
String error,
@@ -892,7 +928,11 @@ class _PantallaBuscarState extends State<PantallaBuscar> {
(context, i) => TarjetaEmisora(
emisora: emisoras[i],
onTap: () => reproducirMinimizado(context, emisoras[i]),
).pluriFadeSlideIn(context, delay: Duration(milliseconds: i * 30), beginY: 0.1),
).pluriFadeSlideIn(
context,
delay: Duration(milliseconds: i * 30),
beginY: 0.1,
),
);
}
}
+161
View File
@@ -0,0 +1,161 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../estado/estado_busqueda.dart';
import '../l10n/gen/app_localizations.dart';
import '../modelos/pais_radio.dart';
import '../widgets/pluri_glass_surface.dart';
import '../widgets/pluri_layout.dart';
import '../widgets/pluri_push_scaffold.dart';
/// WU7, `station-discovery-browse` spec — "Países Browser Over the Verified
/// Countries Contract". Pure display over `EstadoBusqueda.cargarPaises()`
/// (in-memory cache guard, so re-entering this screen never re-fetches):
/// a "Tus idiomas" shortlist above the full alphabetical list, both with
/// live station counts already parsed from the API's `stationcount`
/// **string** field (`PaisRadio.fromApi`, Engram id 2500).
class PantallaPaises extends StatefulWidget {
const PantallaPaises({super.key});
@override
State<PantallaPaises> createState() => _PantallaPaisesState();
}
class _PantallaPaisesState extends State<PantallaPaises> {
/// One representative country per app-supported locale (the same 13
/// locales as `pantalla_ajustes_idioma.dart`'s `_idiomas` list). "Tus
/// idiomas" is named by the proposal/spec but its derivation is not
/// otherwise specified — this reuses the app's own existing language
/// identity rather than inventing a separate curated country list.
static const _paisPorIdioma = <String, String>{
'en': 'US',
'es': 'ES',
'zh': 'CN',
'hi': 'IN',
'ar': 'SA',
'pt': 'PT',
'fr': 'FR',
'ru': 'RU',
'de': 'DE',
'ja': 'JP',
'id': 'ID',
'bn': 'BD',
'it': 'IT',
};
@override
void initState() {
super.initState();
// `cargarPaises()` calls `notifyListeners()` before its first `await`
// (its loading-flag flip) — doing that synchronously inside `initState`
// would trigger "setState() or markNeedsBuild() called during build."
// Deferred to a post-frame callback, matching the established pattern
// for triggering a load from a screen's `initState`/`build`
// (`pantalla_alarmas.dart`'s `_favoritosSolicitados` guard).
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) context.read<EstadoBusqueda>().cargarPaises();
});
}
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context);
final estado = context.watch<EstadoBusqueda>();
return PluriPushScaffold(
title: l10n.countriesScreenTitle,
body:
estado.cargandoPaises && estado.paises.isEmpty
? const Center(child: CircularProgressIndicator())
: ListView(
padding: PluriLayout.pageContentPadding,
children: [
_seccionTusIdiomas(context, estado.paises, l10n),
const SizedBox(height: 16),
_seccionTodos(context, estado.paises, l10n),
],
),
);
}
Widget _seccionTusIdiomas(
BuildContext context,
List<PaisRadio> paises,
AppLocalizations l10n,
) {
final porCodigo = {for (final p in paises) p.codigoIso: p};
final destacados =
_paisPorIdioma.values
.map((codigo) => porCodigo[codigo])
.whereType<PaisRadio>()
.toList();
if (destacados.isEmpty) return const SizedBox.shrink();
final theme = Theme.of(context);
return PluriGlassSurface(
padding: const EdgeInsets.all(12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
l10n.countriesYourLanguagesTitle,
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w900,
),
),
const SizedBox(height: 8),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
for (final pais in destacados)
Chip(
label: Text(
'${pais.nombre} · ${l10n.stationsCount(pais.numeroEmisoras)}',
),
),
],
),
],
),
);
}
Widget _seccionTodos(
BuildContext context,
List<PaisRadio> paises,
AppLocalizations l10n,
) {
final theme = Theme.of(context);
return PluriGlassSurface(
padding: const EdgeInsets.all(12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
l10n.countriesAllTitle,
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w900,
),
),
const SizedBox(height: 4),
ListView.separated(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: paises.length,
separatorBuilder: (_, __) => const Divider(height: 1),
itemBuilder: (context, i) {
final pais = paises[i];
return ListTile(
contentPadding: EdgeInsets.zero,
title: Text(pais.nombre),
trailing: Text(l10n.stationsCount(pais.numeroEmisoras)),
);
},
),
],
),
);
}
}
+67 -14
View File
@@ -4,6 +4,7 @@ import 'package:http/http.dart' as http;
import 'package:package_info_plus/package_info_plus.dart';
import '../modelos/emisora.dart';
import '../modelos/pais_radio.dart';
/// Cliente para la Radio Browser API (https://api.radio-browser.info/).
///
@@ -157,7 +158,25 @@ class ServicioRadio {
return _descubrimientoEnCurso!;
}
Future<List<Emisora>> _get(String path, Map<String, String> params) async {
/// Transport ONLY: server discovery, host rotation, bounded retries,
/// User-Agent, timeout, status check, `json.decode`, sticky-host
/// bookkeeping. No filters, no models, no ordering — deliberately
/// sort-agnostic and filter-agnostic so non-station endpoints (e.g.
/// `/json/countries`, via [obtenerPaises]) can reuse this resilience
/// behaviour without inheriting station-only semantics such as
/// `lastcheckok` or bitrate ordering (design ADR-4).
///
/// Extracted verbatim from `_get` — no logic edits — so the 8 existing
/// station calls stay byte-identical
/// (`test/servicios/servicio_radio_transporte_test.dart`).
///
/// Named behaviour delta, accepted per ADR-4: `_servidorActual` is set here
/// on success/failure, so a successful `/json/countries` call now warms
/// the sticky host for subsequent station calls too.
Future<List<dynamic>> _getJson(
String path,
Map<String, String> params,
) async {
await _descubrirServidores();
Exception? ultimoError;
final indiceBase = _indiceServidorInicial();
@@ -165,14 +184,11 @@ class ServicioRadio {
for (int intento = 0; intento < totalIntentos; intento++) {
final servidor = _servidorPorIntento(indiceBase, intento);
final uri = _uri(servidor, path, {'lastcheckok': '1', ...params});
final uri = _uri(servidor, path, params);
try {
final resp = await _cliente
.get(
uri,
headers: {'User-Agent': await _resolverUserAgent()},
)
.get(uri, headers: {'User-Agent': await _resolverUserAgent()})
.timeout(_timeout);
if (resp.statusCode != 200) {
@@ -181,14 +197,7 @@ class ServicioRadio {
final lista = json.decode(resp.body) as List<dynamic>;
_servidorActual = servidor;
final emisoras =
lista
.cast<Map<String, dynamic>>()
.map(Emisora.fromApi)
.where((e) => e.uuid.isNotEmpty && e.url.isNotEmpty)
.toList();
emisoras.sort(_compararCalidad);
return emisoras;
return lista;
} on Exception catch (e) {
ultimoError = e;
_servidorActual = null;
@@ -203,6 +212,22 @@ class ServicioRadio {
throw ultimoError ?? Exception('Error desconocido al consultar la API');
}
/// Station layer over [_getJson]: adds the station-only `lastcheckok`
/// filter, maps to [Emisora], drops entries with an empty `uuid`/`url`,
/// and applies the quality sort. None of this belongs in transport — see
/// [_getJson]'s doc comment.
Future<List<Emisora>> _get(String path, Map<String, String> params) async {
final lista = await _getJson(path, {'lastcheckok': '1', ...params});
final emisoras =
lista
.cast<Map<String, dynamic>>()
.map(Emisora.fromApi)
.where((e) => e.uuid.isNotEmpty && e.url.isNotEmpty)
.toList();
emisoras.sort(_compararCalidad);
return emisoras;
}
/// Emisoras más votadas globalmente.
Future<List<Emisora>> obtenerPopulares({
int limit = 30,
@@ -301,6 +326,34 @@ class ServicioRadio {
});
}
/// Países disponibles vía `/json/countries` (station-discovery-browse
/// spec — "Países Browser Over the Verified Countries Contract").
///
/// Deliberately reuses [_getJson], never [_get]:
/// - **No `lastcheckok`.** That filter is station-only and meaningless on
/// a countries listing — sending it would be the whole bug this
/// extraction exists to avoid (Engram id 2500).
/// - **No `order` parameter.** Not because the endpoint default is
/// convenient, but because the screen sorts client-side by name anyway:
/// the API orders by raw byte order, which is not proper collation for
/// any locale this app ships (Engram id 2505's client-side-sort
/// reasoning applies here too).
/// - `hidebroken=true` is still applied (inherited from `_uri`, unchanged)
/// — the endpoint's own default is `false`, so this keeps dead stations
/// out of the per-country counts, which is desirable, not a station-only
/// concern.
///
/// The `.where(...)` guard mirrors `_get`'s own precedent of dropping
/// entries with empty required fields — not a claim about API behaviour.
Future<List<PaisRadio>> obtenerPaises() async {
final lista = await _getJson('/json/countries', const {});
return lista
.whereType<Map<String, dynamic>>()
.map(PaisRadio.fromApi)
.where((p) => p.nombre.isNotEmpty && p.codigoIso.length == 2)
.toList();
}
int _compararCalidad(Emisora a, Emisora b) {
final bitrateA = a.bitrate ?? 0;
final bitrateB = b.bitrate ?? 0;