mirror of
https://github.com/R0m1k3/xtremflow.git
synced 2026-10-24 07:28:05 +02:00
fix(epg,ui): utiliser get_simple_data_table pour l'EPG et recaler la sidebar sur le thème
EPG — les trois chemins (backend /api/epg, XtreamService.getShortEpg et getShortEPG) n'utilisaient que get_epg et get_short_epg. Beaucoup de panneaux Xtream ne connaissent pas get_epg : ils répondent 200 avec le bloc d'authentification, sans epg_listings, ce qui produisait un guide vide indiscernable d'une chaîne sans programme. get_short_epg y renvoie epg_listings vide en permanence. - backend : get_simple_data_table en premier, get_short_epg en repli - client : bascule automatique et mémorisée vers le tableau complet dès qu'un panneau est muet sur l'action légère, pour ne pas doubler les requêtes sur chaque tuile de grille - dates dérivées des *_timestamp epoch et émises en ISO-8601 UTC : les champs texte sont dans le fuseau du panneau, sans indicateur de zone, et étaient relus comme de l'heure locale — le guide était décalé et les enregistrements planifiés depuis le guide l'étaient aussi - cache backend : la clé incluait seulement le channelId, deux playlists partageant un stream_id se servaient mutuellement leur guide UI — les deux halos d'ambiance du dashboard étaient restés de l'ancien thème : primary (#FFB68C) à 40 % posé sur le coin haut-gauche, donc pile derrière la sidebar, et info (#A3B8C4, bleu-gris) à 35 % dans une palette entièrement chaude. Ramenés à des braises ember à 8 % / 6 %. - fond via AppColors.backgroundGradient - onglet actif rempli en primaryContainer (surface) et non primary (teinte claire réservée au texte/icônes) - sidebar en niveau flottant : en niveau 1 son fond #181310 se confondait avec le haut du dégradé #1A1310 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
095eb2c1b0
commit
537312908a
4 files changed
+286
-114
No files matched your search
+71
-42
@@ -8,14 +8,26 @@ import '../models/playlist_config.dart';
|
|||||||
class EpgApi {
|
class EpgApi {
|
||||||
final Future<PlaylistConfig?> Function(Request) _getPlaylist;
|
final Future<PlaylistConfig?> Function(Request) _getPlaylist;
|
||||||
|
|
||||||
// Cache simple en mémoire : channelId → {data, expiresAt}
|
/// Cache mémoire : « dns|username|channelId » → {data, expiresAt}.
|
||||||
|
///
|
||||||
|
/// La clé inclut le compte : les `stream_id` sont propres à chaque panneau,
|
||||||
|
/// deux playlists distinctes peuvent parfaitement partager le même
|
||||||
|
/// identifiant et se servaient alors le guide l'une de l'autre.
|
||||||
final Map<String, _CacheEntry> _cache = {};
|
final Map<String, _CacheEntry> _cache = {};
|
||||||
|
|
||||||
EpgApi(this._getPlaylist);
|
EpgApi(this._getPlaylist);
|
||||||
|
|
||||||
Future<Response> handleGetEpg(Request request, String channelId) async {
|
Future<Response> handleGetEpg(Request request, String channelId) async {
|
||||||
// Vérifier le cache
|
final playlist = await _getPlaylist(request);
|
||||||
final cached = _cache[channelId];
|
if (playlist == null) {
|
||||||
|
return Response.forbidden(
|
||||||
|
json.encode({'error': 'Playlist non trouvée'}),
|
||||||
|
headers: {'Content-Type': 'application/json'},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
final cacheKey = '${playlist.dns}|${playlist.username}|$channelId';
|
||||||
|
final cached = _cache[cacheKey];
|
||||||
if (cached != null && DateTime.now().isBefore(cached.expiresAt)) {
|
if (cached != null && DateTime.now().isBefore(cached.expiresAt)) {
|
||||||
return Response.ok(
|
return Response.ok(
|
||||||
cached.data,
|
cached.data,
|
||||||
@@ -24,49 +36,45 @@ class EpgApi {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
final playlist = await _getPlaylist(request);
|
|
||||||
if (playlist == null) {
|
|
||||||
return Response.forbidden(
|
|
||||||
json.encode({'error': 'Playlist non trouvée'}),
|
|
||||||
headers: {'Content-Type': 'application/json'},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
final dns = playlist.dns;
|
final dns = playlist.dns;
|
||||||
// 1. Tenter d'abord l'EPG complet (48h)
|
|
||||||
var url =
|
|
||||||
'$dns/player_api.php?username=${playlist.username}&password=${playlist.password}'
|
|
||||||
'&action=get_epg&stream_id=$channelId&limit=48';
|
|
||||||
|
|
||||||
var response =
|
|
||||||
await http.get(Uri.parse(url)).timeout(const Duration(seconds: 60));
|
|
||||||
Map<String, dynamic> epgData = {
|
Map<String, dynamic> epgData = {
|
||||||
'channel_id': channelId,
|
'channel_id': channelId,
|
||||||
'programmes': [],
|
'programmes': [],
|
||||||
};
|
};
|
||||||
|
|
||||||
if (response.statusCode == 200) {
|
// Ordre d'essai des actions Xtream.
|
||||||
final raw = json.decode(response.body);
|
//
|
||||||
epgData = _transformEpgData(raw, channelId);
|
// `get_simple_data_table` d'abord : c'est la seule action réellement
|
||||||
}
|
// universelle. `get_epg` n'existe pas sur beaucoup de panneaux — au lieu
|
||||||
|
// d'une erreur, ils renvoient poliment le payload d'authentification,
|
||||||
|
// sans champ `epg_listings`, ce qui produisait un guide vide impossible
|
||||||
|
// à distinguer d'une chaîne sans programme.
|
||||||
|
const actions = [
|
||||||
|
'get_simple_data_table',
|
||||||
|
'get_short_epg',
|
||||||
|
];
|
||||||
|
|
||||||
// 2. Fallback EPG court si le complet est vide
|
for (final action in actions) {
|
||||||
if ((epgData['programmes'] as List).isEmpty) {
|
final url =
|
||||||
url =
|
|
||||||
'$dns/player_api.php?username=${playlist.username}&password=${playlist.password}'
|
'$dns/player_api.php?username=${playlist.username}&password=${playlist.password}'
|
||||||
'&action=get_short_epg&stream_id=$channelId';
|
'&action=$action&stream_id=$channelId';
|
||||||
response =
|
|
||||||
|
final response =
|
||||||
await http.get(Uri.parse(url)).timeout(const Duration(seconds: 60));
|
await http.get(Uri.parse(url)).timeout(const Duration(seconds: 60));
|
||||||
if (response.statusCode == 200) {
|
if (response.statusCode != 200) continue;
|
||||||
final raw = json.decode(response.body);
|
|
||||||
epgData = _transformEpgData(raw, channelId);
|
try {
|
||||||
|
epgData = transformEpgData(json.decode(response.body), channelId);
|
||||||
|
} catch (_) {
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
|
if ((epgData['programmes'] as List).isNotEmpty) break;
|
||||||
}
|
}
|
||||||
|
|
||||||
final jsonStr = json.encode(epgData);
|
final jsonStr = json.encode(epgData);
|
||||||
|
|
||||||
// Mettre en cache 30 minutes
|
// Mettre en cache 30 minutes
|
||||||
_cache[channelId] = _CacheEntry(
|
_cache[cacheKey] = _CacheEntry(
|
||||||
data: jsonStr,
|
data: jsonStr,
|
||||||
expiresAt: DateTime.now().add(const Duration(minutes: 30)),
|
expiresAt: DateTime.now().add(const Duration(minutes: 30)),
|
||||||
);
|
);
|
||||||
@@ -83,7 +91,9 @@ class EpgApi {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Map<String, dynamic> _transformEpgData(dynamic raw, String channelId) {
|
/// Normalise une réponse Xtream (`epg_listings`) vers le format servi au
|
||||||
|
/// client. Public pour être couvert par `bin/test/epg_api_test.dart`.
|
||||||
|
Map<String, dynamic> transformEpgData(dynamic raw, String channelId) {
|
||||||
try {
|
try {
|
||||||
List<dynamic> listings = [];
|
List<dynamic> listings = [];
|
||||||
|
|
||||||
@@ -94,16 +104,18 @@ class EpgApi {
|
|||||||
}
|
}
|
||||||
|
|
||||||
final programmes = listings.map((item) {
|
final programmes = listings.map((item) {
|
||||||
final startRaw = item['start'] as String? ?? '';
|
// Les champs texte `start`/`end` sont exprimés dans le fuseau du
|
||||||
final endRaw = item['stop'] as String? ?? item['end'] as String? ?? '';
|
// panneau (souvent Europe/Amsterdam), sans indicateur de zone : le
|
||||||
|
// client les relisait comme de l'heure locale et décalait tout le
|
||||||
// Normaliser les dates pour le frontend (Xtream format support)
|
// guide. Les `*_timestamp` sont de l'epoch UTC — on s'en sert dès
|
||||||
final start = startRaw.contains(' ') && !startRaw.contains('T')
|
// qu'ils sont présents et on émet de l'ISO-8601 UTC explicite.
|
||||||
? startRaw.replaceFirst(' ', 'T')
|
final start = _isoUtc(item['start_timestamp']) ??
|
||||||
: startRaw;
|
_normalizeDate(item['start'] as String? ?? '');
|
||||||
final end = endRaw.contains(' ') && !endRaw.contains('T')
|
final end = _isoUtc(item['stop_timestamp']) ??
|
||||||
? endRaw.replaceFirst(' ', 'T')
|
_isoUtc(item['end_timestamp']) ??
|
||||||
: endRaw;
|
_normalizeDate(
|
||||||
|
(item['stop'] as String?) ?? (item['end'] as String?) ?? '',
|
||||||
|
);
|
||||||
|
|
||||||
// Décoder le titre (base64 si nécessaire)
|
// Décoder le titre (base64 si nécessaire)
|
||||||
String title = item['title'] as String? ?? '';
|
String title = item['title'] as String? ?? '';
|
||||||
@@ -136,6 +148,23 @@ class EpgApi {
|
|||||||
return {'channel_id': channelId, 'programmes': [], 'error': e.toString()};
|
return {'channel_id': channelId, 'programmes': [], 'error': e.toString()};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Epoch (secondes, String ou int) → ISO-8601 UTC, ou `null` si absent.
|
||||||
|
static String? _isoUtc(dynamic timestamp) {
|
||||||
|
if (timestamp == null) return null;
|
||||||
|
final seconds = timestamp is int ? timestamp : int.tryParse('$timestamp');
|
||||||
|
if (seconds == null || seconds <= 0) return null;
|
||||||
|
return DateTime.fromMillisecondsSinceEpoch(seconds * 1000, isUtc: true)
|
||||||
|
.toIso8601String();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Repli : « YYYY-MM-DD HH:MM:SS » → « YYYY-MM-DDTHH:MM:SS ».
|
||||||
|
static String _normalizeDate(String raw) {
|
||||||
|
if (raw.contains(' ') && !raw.contains('T')) {
|
||||||
|
return raw.replaceFirst(' ', 'T');
|
||||||
|
}
|
||||||
|
return raw;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class _CacheEntry {
|
class _CacheEntry {
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
import 'package:test/test.dart';
|
||||||
|
import '../api/epg_api.dart';
|
||||||
|
|
||||||
|
/// Extrait réel d'une réponse `get_simple_data_table` (panneau Xtream) :
|
||||||
|
/// titres/descriptions en base64, horodatages epoch UTC doublés d'une chaîne
|
||||||
|
/// exprimée dans le fuseau du panneau — ici Europe/Amsterdam (UTC+2).
|
||||||
|
const _sampleListing = {
|
||||||
|
'epg_listings': [
|
||||||
|
{
|
||||||
|
'id': '336987829',
|
||||||
|
'epg_id': '104',
|
||||||
|
'title': 'Sm91cm5hbCBkZSAyMGg=', // "Journal de 20h"
|
||||||
|
'lang': '',
|
||||||
|
'start': '2026-08-11 20:00:00',
|
||||||
|
'end': '2026-08-11 20:35:00',
|
||||||
|
'description': 'TCdpbmZvIGR1IHNvaXI=', // "L'info du soir"
|
||||||
|
'channel_id': 'TF1.fr',
|
||||||
|
'start_timestamp': '1786471200', // 2026-08-11T18:00:00Z
|
||||||
|
'stop_timestamp': '1786473300', // 2026-08-11T18:35:00Z
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
final api = EpgApi((_) async => null);
|
||||||
|
|
||||||
|
group('transformEpgData', () {
|
||||||
|
test('convertit les horodatages epoch en ISO-8601 UTC', () {
|
||||||
|
final result = api.transformEpgData(_sampleListing, '845452');
|
||||||
|
final programme = (result['programmes'] as List).single as Map;
|
||||||
|
|
||||||
|
// Sans cette conversion, le client relisait « 2026-08-11T20:00:00 »
|
||||||
|
// comme de l'heure locale et décalait tout le guide de 2 h.
|
||||||
|
expect(programme['start'], '2026-08-11T18:00:00.000Z');
|
||||||
|
expect(programme['end'], '2026-08-11T18:35:00.000Z');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('décode les titres et descriptions base64', () {
|
||||||
|
final result = api.transformEpgData(_sampleListing, '845452');
|
||||||
|
final programme = (result['programmes'] as List).single as Map;
|
||||||
|
|
||||||
|
expect(programme['title'], 'Journal de 20h');
|
||||||
|
expect(programme['description'], "L'info du soir");
|
||||||
|
expect(programme['channel_id'], '845452');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('retombe sur les champs texte quand les epoch manquent', () {
|
||||||
|
final result = api.transformEpgData({
|
||||||
|
'epg_listings': [
|
||||||
|
{
|
||||||
|
'title': 'Sm91cm5hbCBkZSAyMGg=',
|
||||||
|
'start': '2026-08-11 20:00:00',
|
||||||
|
'stop': '2026-08-11 20:35:00',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}, '845452');
|
||||||
|
final programme = (result['programmes'] as List).single as Map;
|
||||||
|
|
||||||
|
expect(programme['start'], '2026-08-11T20:00:00');
|
||||||
|
expect(programme['end'], '2026-08-11T20:35:00');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rend une liste vide sur un payload sans epg_listings', () {
|
||||||
|
// Ce que renvoie un panneau qui ne connaît pas l'action demandée :
|
||||||
|
// un 200 contenant le bloc d'authentification.
|
||||||
|
final result = api.transformEpgData({
|
||||||
|
'user_info': {'auth': 1},
|
||||||
|
'server_info': {'url': 'tit.example'},
|
||||||
|
}, '845452');
|
||||||
|
|
||||||
|
expect(result['programmes'], isEmpty);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -46,24 +46,18 @@ class _DashboardScreenState extends ConsumerState<DashboardScreen> {
|
|||||||
body: Stack(
|
body: Stack(
|
||||||
fit: StackFit.expand,
|
fit: StackFit.expand,
|
||||||
children: [
|
children: [
|
||||||
// 1. Cinematic Deep Space Background - Premium Apple TV Style
|
// 1. Fond « salle de projection » — dégradé chaud du design system.
|
||||||
Positioned.fill(
|
Positioned.fill(
|
||||||
child: Container(
|
child: Container(
|
||||||
decoration: const BoxDecoration(
|
decoration: const BoxDecoration(
|
||||||
gradient: LinearGradient(
|
gradient: AppColors.backgroundGradient,
|
||||||
begin: Alignment.topCenter,
|
|
||||||
end: Alignment.bottomCenter,
|
|
||||||
colors: [
|
|
||||||
AppColors.surfaceContainerLowest, // Very dark top
|
|
||||||
AppColors.background, // Black bottom
|
|
||||||
AppColors.baseLevel0, // Slightly darker for depth
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|
||||||
// Ambient Glow Top-Left - Teal (Primary) - VISIBLE
|
// Faisceau du projecteur, en haut à gauche.
|
||||||
|
// Intensité volontairement basse (8 %) : au-delà, le halo délave la
|
||||||
|
// sidebar et les cartes en pêche et sort le rendu de la palette.
|
||||||
Positioned(
|
Positioned(
|
||||||
top: -300,
|
top: -300,
|
||||||
left: -300,
|
left: -300,
|
||||||
@@ -74,8 +68,8 @@ class _DashboardScreenState extends ConsumerState<DashboardScreen> {
|
|||||||
shape: BoxShape.circle,
|
shape: BoxShape.circle,
|
||||||
gradient: RadialGradient(
|
gradient: RadialGradient(
|
||||||
colors: [
|
colors: [
|
||||||
AppColors.primary.withOpacity(0.4),
|
AppColors.glowPrimary(0.08),
|
||||||
AppColors.primary.withOpacity(0.1),
|
AppColors.glowPrimary(0.03),
|
||||||
Colors.transparent,
|
Colors.transparent,
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
@@ -83,7 +77,9 @@ class _DashboardScreenState extends ConsumerState<DashboardScreen> {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|
||||||
// Ambient Glow Bottom-Right - Blue - VISIBLE
|
// Braise résiduelle en bas à droite. L'ancien halo utilisait
|
||||||
|
// `AppColors.info` (bleu-gris) : une teinte froide dans une palette
|
||||||
|
// entièrement chaude, d'où le rendu grisâtre.
|
||||||
Positioned(
|
Positioned(
|
||||||
bottom: -250,
|
bottom: -250,
|
||||||
right: -250,
|
right: -250,
|
||||||
@@ -94,8 +90,8 @@ class _DashboardScreenState extends ConsumerState<DashboardScreen> {
|
|||||||
shape: BoxShape.circle,
|
shape: BoxShape.circle,
|
||||||
gradient: RadialGradient(
|
gradient: RadialGradient(
|
||||||
colors: [
|
colors: [
|
||||||
AppColors.info.withOpacity(0.35),
|
AppColors.glowPrimary(0.06),
|
||||||
AppColors.info.withOpacity(0.1),
|
AppColors.glowPrimary(0.02),
|
||||||
Colors.transparent,
|
Colors.transparent,
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
@@ -124,9 +120,12 @@ class _DashboardScreenState extends ConsumerState<DashboardScreen> {
|
|||||||
top: 24,
|
top: 24,
|
||||||
bottom: 24,
|
bottom: 24,
|
||||||
width: 80,
|
width: 80,
|
||||||
child: GlassContainer.glass(
|
// Niveau « flottant » : le niveau 1 (#181310) se confondait avec
|
||||||
|
// le haut du dégradé de fond (#1A1310) — la barre n'existait plus
|
||||||
|
// que par sa bordure. Le niveau 2 apporte l'arête ember et
|
||||||
|
// l'ombre profonde qui la détachent vraiment.
|
||||||
|
child: GlassContainer.floating(
|
||||||
borderRadius: 24,
|
borderRadius: 24,
|
||||||
borderColor: AppColors.border,
|
|
||||||
child: Column(
|
child: Column(
|
||||||
mainAxisAlignment: MainAxisAlignment.center,
|
mainAxisAlignment: MainAxisAlignment.center,
|
||||||
children: [
|
children: [
|
||||||
@@ -141,7 +140,7 @@ class _DashboardScreenState extends ConsumerState<DashboardScreen> {
|
|||||||
borderRadius: BorderRadius.circular(12),
|
borderRadius: BorderRadius.circular(12),
|
||||||
boxShadow: [
|
boxShadow: [
|
||||||
BoxShadow(
|
BoxShadow(
|
||||||
color: AppColors.primary.withOpacity(0.4),
|
color: AppColors.glowPrimary(0.35),
|
||||||
blurRadius: 10,
|
blurRadius: 10,
|
||||||
offset: const Offset(0, 4),
|
offset: const Offset(0, 4),
|
||||||
),
|
),
|
||||||
@@ -149,7 +148,7 @@ class _DashboardScreenState extends ConsumerState<DashboardScreen> {
|
|||||||
),
|
),
|
||||||
child: const Icon(
|
child: const Icon(
|
||||||
Icons.play_arrow_rounded,
|
Icons.play_arrow_rounded,
|
||||||
color: AppColors.textPrimary,
|
color: AppColors.onPrimary,
|
||||||
size: 28,
|
size: 28,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -172,21 +171,26 @@ class _DashboardScreenState extends ConsumerState<DashboardScreen> {
|
|||||||
width: 48,
|
width: 48,
|
||||||
height: 48,
|
height: 48,
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
|
// Remplissage ember (`primaryContainer`) et non
|
||||||
|
// `primary` : cette dernière est la teinte claire
|
||||||
|
// réservée au texte/icône, pas aux surfaces.
|
||||||
color: isSelected
|
color: isSelected
|
||||||
? AppColors.primary.withOpacity(0.2)
|
? AppColors.primaryContainer
|
||||||
|
.withValues(alpha: 0.20)
|
||||||
: Colors.transparent,
|
: Colors.transparent,
|
||||||
borderRadius: BorderRadius.circular(16),
|
borderRadius: BorderRadius.circular(16),
|
||||||
border: isSelected
|
border: isSelected
|
||||||
? Border.all(
|
? Border.all(
|
||||||
color: AppColors.primary.withOpacity(0.5),
|
color: AppColors.primary
|
||||||
|
.withValues(alpha: 0.55),
|
||||||
)
|
)
|
||||||
: null,
|
: null,
|
||||||
),
|
),
|
||||||
child: Icon(
|
child: Icon(
|
||||||
_icons[index],
|
_icons[index],
|
||||||
color: isSelected
|
color: isSelected
|
||||||
? AppColors.textPrimary
|
? AppColors.primary
|
||||||
: AppColors.textSecondary,
|
: AppColors.textTertiary,
|
||||||
size: 24,
|
size: 24,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -203,10 +207,10 @@ class _DashboardScreenState extends ConsumerState<DashboardScreen> {
|
|||||||
onTap: () {},
|
onTap: () {},
|
||||||
borderRadius: 50,
|
borderRadius: 50,
|
||||||
scaleFactor: 1.1,
|
scaleFactor: 1.1,
|
||||||
child: CircleAvatar(
|
child: const CircleAvatar(
|
||||||
radius: 20,
|
radius: 20,
|
||||||
backgroundColor: AppColors.primary.withOpacity(0.1),
|
backgroundColor: AppColors.surfaceContainerHigh,
|
||||||
child: const Icon(
|
child: Icon(
|
||||||
Icons.person,
|
Icons.person,
|
||||||
color: AppColors.textSecondary,
|
color: AppColors.textSecondary,
|
||||||
size: 20,
|
size: 20,
|
||||||
|
|||||||
@@ -45,6 +45,18 @@ class XtreamService {
|
|||||||
/// quelques connexions parallèles, ce qui vide l'EPG de toute la grille.
|
/// quelques connexions parallèles, ce qui vide l'EPG de toute la grille.
|
||||||
/// On sérialise donc par petits paquets.
|
/// On sérialise donc par petits paquets.
|
||||||
static final _Semaphore _epgGate = _Semaphore(3);
|
static final _Semaphore _epgGate = _Semaphore(3);
|
||||||
|
|
||||||
|
/// Action EPG retenue pour ce panneau.
|
||||||
|
///
|
||||||
|
/// `get_short_epg` est la requête légère (2-3 programmes) mais une partie
|
||||||
|
/// des panneaux répond `{"epg_listings":[]}` en permanence ; seule
|
||||||
|
/// `get_simple_data_table` y renvoie le guide. On teste la première, et
|
||||||
|
/// dès qu'un panneau se révèle incapable de la servir on bascule
|
||||||
|
/// définitivement, pour ne pas payer deux requêtes par tuile de grille.
|
||||||
|
static const _epgActionShort = 'get_short_epg';
|
||||||
|
static const _epgActionTable = 'get_simple_data_table';
|
||||||
|
static String _epgAction = _epgActionShort;
|
||||||
|
|
||||||
late final Dio _dio;
|
late final Dio _dio;
|
||||||
late final CacheOptions _cacheOptions;
|
late final CacheOptions _cacheOptions;
|
||||||
|
|
||||||
@@ -662,6 +674,22 @@ class XtreamService {
|
|||||||
///
|
///
|
||||||
/// Returns "Now" and "Next" program info
|
/// Returns "Now" and "Next" program info
|
||||||
Future<List<EpgEntry>> getShortEpg(String streamId) async {
|
Future<List<EpgEntry>> getShortEpg(String streamId) async {
|
||||||
|
final listings = await _fetchEpgListings(streamId);
|
||||||
|
return listings.map(EpgEntry.fromJson).toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get short EPG as ShortEPG object (for EPGWidget)
|
||||||
|
Future<xm.ShortEPG> getShortEPG(String streamId) async {
|
||||||
|
final listings = await _fetchEpgListings(streamId);
|
||||||
|
if (listings.isEmpty) return const xm.ShortEPG();
|
||||||
|
return xm.ShortEPG.fromJson({'epg_listings': listings});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Récupère le guide d'une chaîne, normalisé et réduit à la fenêtre utile.
|
||||||
|
///
|
||||||
|
/// Bascule automatiquement de `get_short_epg` vers `get_simple_data_table`
|
||||||
|
/// quand le panneau ne sert pas la première : voir [_epgAction].
|
||||||
|
Future<List<Map<String, dynamic>>> _fetchEpgListings(String streamId) async {
|
||||||
if (_currentPlaylist == null) throw Exception('No playlist configured');
|
if (_currentPlaylist == null) throw Exception('No playlist configured');
|
||||||
|
|
||||||
if (isPlaybackLoading) {
|
if (isPlaybackLoading) {
|
||||||
@@ -670,10 +698,33 @@ class XtreamService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
await _epgGate.acquire();
|
await _epgGate.acquire();
|
||||||
|
try {
|
||||||
|
var listings = await _requestEpg(streamId, _epgAction);
|
||||||
|
|
||||||
|
// Panneau muet sur l'action légère : on retente avec le tableau complet
|
||||||
|
// et on mémorise le choix pour toutes les chaînes suivantes.
|
||||||
|
if (listings.isEmpty && _epgAction == _epgActionShort) {
|
||||||
|
listings = await _requestEpg(streamId, _epgActionTable);
|
||||||
|
if (listings.isNotEmpty) {
|
||||||
|
debugPrint(
|
||||||
|
'[XtreamService] EPG : $_epgActionShort vide sur ce panneau, '
|
||||||
|
'bascule définitive vers $_epgActionTable',
|
||||||
|
);
|
||||||
|
_epgAction = _epgActionTable;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return _normalizeListings(listings);
|
||||||
|
} finally {
|
||||||
|
_epgGate.release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<List<dynamic>> _requestEpg(String streamId, String action) async {
|
||||||
try {
|
try {
|
||||||
final response = await _apiGet(
|
final response = await _apiGet(
|
||||||
{
|
{
|
||||||
'action': 'get_short_epg',
|
'action': action,
|
||||||
'stream_id': streamId,
|
'stream_id': streamId,
|
||||||
},
|
},
|
||||||
options: Options(
|
options: Options(
|
||||||
@@ -693,7 +744,7 @@ class XtreamService {
|
|||||||
if (data is String) {
|
if (data is String) {
|
||||||
if (data.trim().isEmpty) {
|
if (data.trim().isEmpty) {
|
||||||
debugPrint('[XtreamService] EPG $streamId : réponse vide');
|
debugPrint('[XtreamService] EPG $streamId : réponse vide');
|
||||||
return [];
|
return const [];
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
data = json.decode(data);
|
data = json.decode(data);
|
||||||
@@ -703,76 +754,90 @@ class XtreamService {
|
|||||||
'(${response.headers.value('content-type')}) — '
|
'(${response.headers.value('content-type')}) — '
|
||||||
'${data.length > 120 ? '${data.substring(0, 120)}…' : data}',
|
'${data.length > 120 ? '${data.substring(0, 120)}…' : data}',
|
||||||
);
|
);
|
||||||
return [];
|
return const [];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (data == null) {
|
if (data == null) {
|
||||||
debugPrint('[XtreamService] EPG $streamId : corps nul');
|
debugPrint('[XtreamService] EPG $streamId : corps nul');
|
||||||
return [];
|
return const [];
|
||||||
}
|
}
|
||||||
|
|
||||||
if (data is! Map || data['epg_listings'] == null) {
|
if (data is! Map || data['epg_listings'] is! List) {
|
||||||
|
// Cas typique de `get_epg` / `get_short_epg` non supportés : le
|
||||||
|
// panneau répond 200 avec le payload d'authentification.
|
||||||
debugPrint(
|
debugPrint(
|
||||||
'[XtreamService] EPG $streamId : pas de champ epg_listings '
|
'[XtreamService] EPG $streamId ($action) : pas de champ '
|
||||||
'(clés: ${data is Map ? data.keys.toList() : data.runtimeType})',
|
'epg_listings (clés: '
|
||||||
|
'${data is Map ? data.keys.toList() : data.runtimeType})',
|
||||||
);
|
);
|
||||||
return [];
|
return const [];
|
||||||
}
|
}
|
||||||
|
|
||||||
final List<dynamic> epgData = data['epg_listings'] as List<dynamic>;
|
return data['epg_listings'] as List<dynamic>;
|
||||||
return epgData
|
|
||||||
.map((entry) => EpgEntry.fromJson(entry as Map<String, dynamic>))
|
|
||||||
.toList();
|
|
||||||
} on DioException catch (e) {
|
} on DioException catch (e) {
|
||||||
// L'EPG reste optionnel — mais avaler l'erreur en silence rendait toute
|
// L'EPG reste optionnel — mais avaler l'erreur en silence rendait toute
|
||||||
// panne indiscernable d'une grille réellement vide.
|
// panne indiscernable d'une grille réellement vide.
|
||||||
debugPrint(
|
debugPrint(
|
||||||
'[XtreamService] EPG $streamId en échec : '
|
'[XtreamService] EPG $streamId ($action) en échec : '
|
||||||
'HTTP ${e.response?.statusCode} ${e.type} — ${e.message}',
|
'HTTP ${e.response?.statusCode} ${e.type} — ${e.message}',
|
||||||
);
|
);
|
||||||
return [];
|
return const [];
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
debugPrint('[XtreamService] EPG $streamId en échec : $e');
|
debugPrint('[XtreamService] EPG $streamId ($action) en échec : $e');
|
||||||
return [];
|
return const [];
|
||||||
} finally {
|
|
||||||
_epgGate.release();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get short EPG as ShortEPG object (for EPGWidget)
|
/// Aligne les dates sur de l'ISO-8601 UTC et ne garde que la fenêtre utile.
|
||||||
Future<xm.ShortEPG> getShortEPG(String streamId) async {
|
///
|
||||||
if (_currentPlaylist == null) throw Exception('No playlist configured');
|
/// Deux raisons :
|
||||||
|
/// * `get_simple_data_table` renvoie plusieurs jours de programmes (~35 Ko
|
||||||
|
/// par chaîne). Les appelants prennent « le premier élément » comme
|
||||||
|
/// programme courant : sans coupe, ils afficheraient un programme
|
||||||
|
/// d'avant-hier.
|
||||||
|
/// * Les champs texte `start`/`end` sont dans le fuseau du panneau et sans
|
||||||
|
/// indicateur de zone ; seuls les `*_timestamp` (epoch UTC) sont fiables.
|
||||||
|
static List<Map<String, dynamic>> _normalizeListings(List<dynamic> raw) {
|
||||||
|
final now = DateTime.now();
|
||||||
|
final result = <Map<String, dynamic>>[];
|
||||||
|
|
||||||
if (isPlaybackLoading) {
|
for (final item in raw) {
|
||||||
debugPrint('[XtreamService] Throttling short EPG metadata for $streamId');
|
if (item is! Map) continue;
|
||||||
await Future.delayed(_throttleDelay);
|
final entry = Map<String, dynamic>.from(item);
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
final start = _epgDate(entry['start_timestamp'], entry['start']);
|
||||||
final response = await _apiGet(
|
final end = _epgDate(
|
||||||
{
|
entry['stop_timestamp'] ?? entry['end_timestamp'],
|
||||||
'action': 'get_short_epg',
|
entry['stop'] ?? entry['end'],
|
||||||
'stream_id': streamId,
|
|
||||||
},
|
|
||||||
options: Options(
|
|
||||||
extra: CacheOptions(
|
|
||||||
store: _cacheOptions.store,
|
|
||||||
policy: CachePolicy.request,
|
|
||||||
maxStale: const Duration(minutes: 5),
|
|
||||||
).toExtra(),
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
|
if (start == null || end == null) continue;
|
||||||
|
|
||||||
if (response.data == null) {
|
// Programme déjà terminé : sans intérêt pour un « en cours / à suivre ».
|
||||||
return const xm.ShortEPG();
|
if (end.isBefore(now)) continue;
|
||||||
}
|
|
||||||
|
|
||||||
return xm.ShortEPG.fromJson(response.data as Map<String, dynamic>);
|
entry['start'] = start.toIso8601String();
|
||||||
} catch (e) {
|
entry['end'] = end.toIso8601String();
|
||||||
// EPG is optional, don't throw on failure
|
entry['stop'] = entry['end'];
|
||||||
return const xm.ShortEPG();
|
result.add(entry);
|
||||||
|
|
||||||
|
if (result.length >= 8) break;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Epoch UTC prioritaire, repli sur la chaîne « YYYY-MM-DD HH:MM:SS ».
|
||||||
|
static DateTime? _epgDate(dynamic timestamp, dynamic text) {
|
||||||
|
final seconds = timestamp is int ? timestamp : int.tryParse('$timestamp');
|
||||||
|
if (seconds != null && seconds > 0) {
|
||||||
|
return DateTime.fromMillisecondsSinceEpoch(seconds * 1000, isUtc: true);
|
||||||
|
}
|
||||||
|
final str = text?.toString() ?? '';
|
||||||
|
if (str.isEmpty) return null;
|
||||||
|
return DateTime.tryParse(
|
||||||
|
str.contains(' ') && !str.contains('T') ? str.replaceFirst(' ', 'T') : str,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Dispose resources
|
/// Dispose resources
|
||||||
|
|||||||
Reference in new issue
Block a user