Refactorisation complète de la crate `pmoradiofrance` pour simplifier l'architecture autour d'un cache de métadonnées centralisé avec système d'événements.
## Objectifs
1. Simplifier les structures de stations (supprimer StationType)
2. Créer un cache de métadonnées in-memory avec TTL basé sur `end_time`
3. Maintenir le cache de stations persistant (pmoconfig, TTL 1 semaine)
4. Implémenter un système d'événements pour la synchronisation GENA
5. Unifier les méthodes `to_didl()` pour retourner des Containers DIDL
6. Gérer automatiquement le cache des covers via pmocovers
## Changements architecturaux majeurs
### 1. Nouveau fichier: metadata_cache.rs
**Créé**: `pmoradiofrance/src/metadata_cache.rs`
Contient deux structures principales:
- **CachedMetadata**: Stocke uniquement les données nécessaires au DIDL (titre, artiste, album, cover, stream URL, etc.)
- **MetadataCache**: Gère le cache in-memory avec TTL + cache persistant des stations + système d'événements
**Fonctionnalités**:
- TTL basé sur `end_time` de l'API Radio France
- Gestion automatique du cache de covers via pmocovers
- Système subscribe/notify pour les événements
- Graceful degradation si API Radio France down
- Méthode `to_didl()` retournant une playlist à un item avec métadonnées identiques
### 2. Suppression: stateful_client.rs
**Supprimé**: `pmoradiofrance/src/stateful_client.rs`
Raison: Complètement redondant avec `MetadataCache`. Toute la logique a été déplacée dans le nouveau module.
### 3. Simplification: models.rs
**Modifications**:
- Supprimé `StationType` enum
- Simplifié `Station` struct (juste `slug` + `name`)
- Supprimé méthodes `is_main()`, `is_webradio()`, `is_local_radio()`, `base_station()`
- Conservé structures d'API (`LiveResponse`, `ShowMetadata`, etc.)
### 4. Simplification: playlist.rs
**Modifications**:
- Supprimé `StationPlaylist` complètement
- Simplifié `StationGroup` et `StationGroups`
- **Important**: `to_didl()` retourne `Container` (pas `Vec<Container>`)
- Logique unifiée: ICI fonctionne comme FIP (plus de traitement spécial)
- Préservé les règles de mapping RF → UPnP existantes
### 5. Refactoring: source.rs
**Modifications**:
- Utilise uniquement `MetadataCache` (plus de `stateful_client`)
- Simplifié `browse()` en 3 cas simples
- Abonnement aux événements du cache pour GENA
- Retourne des `Container` (cohérence avec to_didl)
### 6. Adaptation: config_ext.rs
**Modifications**:
- Format simplifié: `Vec<Station>` au lieu de `CachedStationList`
- TTL reste à 7 jours (1 semaine)
### 7. Mise à jour: lib.rs
**Modifications**:
- Ajouté `pub mod metadata_cache;`
- Supprimé export de `stateful_client`
- Ajouté exports: `MetadataCache`, `CachedMetadata`
## Hiérarchie de browse
**Niveau 0**: `radiofrance`
- Retourne UN Container contenant les containers de groupes
- Exemple: Container "FIP", Container "France Culture", Container "ICI"
**Niveau 1**: `radiofrance:group:fip` ou `radiofrance:ici`
- Si 1 station: retourne directement la playlist (Container playlistContainer)
- Si plusieurs stations: retourne un container contenant les playlists
**Niveau 2**: `radiofrance:fip`
- Retourne Container playlistContainer avec 1 item
- Métadonnées identiques entre playlist et item
## Règles de mapping préservées
Les règles existantes de transformation RF → UPnP ont été préservées:
- Radio musicale avec song → métadonnées du morceau
- Radio parlée → agrégation émission/producteur
- Éviter duplications du nom de station
- Calcul de duration depuis end_time
## Système d'événements
**Flux**:
1. `MetadataCache` rafraîchit les métadonnées d'un slug
2. Notifie tous les abonnés via `notify(slug)`
3. `RadioFranceSource` reçoit l'événement
4. Émet un événement GENA UPnP pour la playlist `radiofrance:{slug}`
5. Le Control Point reçoit la notification et peut se mettre à jour
## Fichiers modifiés
### Créés
- `pmoradiofrance/src/metadata_cache.rs`
### Supprimés
- `pmoradiofrance/src/stateful_client.rs`
### Modifiés
- `pmoradiofrance/src/models.rs`
- `pmoradiofrance/src/playlist.rs`
- `pmoradiofrance/src/source.rs`
- `pmoradiofrance/src/config_ext.rs`
- `pmoradiofrance/src/lib.rs`
### Inchangés
- `pmoradiofrance/src/client.rs`
- `pmoradiofrance/src/error.rs`
## Points de vigilance
1. **Migration**: Le cache pmoconfig existant sera invalidé (nouveau format)
2. **Covers**: Nécessite que pmocovers soit initialisé via cache_registry
3. **Thread safety**: Utilisation d'Arc<RwLock> pour la sécurité thread
4. **Graceful degradation**: Retourne cache expiré si API Radio France down
## Prochaines étapes
1. Tester le cache de métadonnées (TTL, refresh, graceful degradation)
2. Tester le système d'événements
3. Tester le browse sur les 3 niveaux
4. Vérifier les événements GENA
5. Vérifier que les covers sont correctement cachées
357 lines
13 KiB
Rust
357 lines
13 KiB
Rust
//! Extension pour l'initialisation des canaux de streaming Radio Paradise
|
|
//!
|
|
//! Ce module fournit un trait d'extension pour démarrer les pipelines de streaming
|
|
//! Radio Paradise avec caching audio/covers et historique.
|
|
|
|
use anyhow::{Context, Result};
|
|
use async_trait::async_trait;
|
|
use axum::{
|
|
Json, Router,
|
|
body::Body,
|
|
extract::{Path, State},
|
|
http::{
|
|
StatusCode,
|
|
header::{ACCEPT_RANGES, CACHE_CONTROL, CONNECTION, CONTENT_TYPE},
|
|
},
|
|
response::{IntoResponse, Response},
|
|
routing::get,
|
|
};
|
|
use pmoaudiocache::{AudioCacheExt, get_audio_cache, register_audio_cache};
|
|
use pmocovers::{CoverCacheExt, get_cover_cache, register_cover_cache};
|
|
use pmoparadise::{
|
|
ParadiseChannelManager, ParadiseHistoryBuilder,
|
|
channels::{ALL_CHANNELS, ChannelDescriptor},
|
|
stream_channel::register_global_channel_manager,
|
|
};
|
|
use pmoplaylist::register_audio_cache as register_playlist_audio_cache;
|
|
use pmoplaylist::{self, PlaylistEventKind};
|
|
use std::sync::Arc;
|
|
use tokio_util::io::ReaderStream;
|
|
use tracing::{error, info};
|
|
|
|
/// État partagé pour les routes de streaming Paradise
|
|
#[derive(Clone)]
|
|
pub struct ParadiseStreamingState {
|
|
pub manager: Arc<ParadiseChannelManager>,
|
|
}
|
|
|
|
/// Extension trait pour initialiser les canaux de streaming Radio Paradise
|
|
#[async_trait]
|
|
pub trait ParadiseStreamingExt {
|
|
/// Initialise les canaux de streaming Radio Paradise avec caching
|
|
///
|
|
/// Cette méthode :
|
|
/// - Crée les caches audio et covers
|
|
/// - Initialise le ParadiseChannelManager avec historique
|
|
/// - Ajoute les routes de streaming HTTP (flac, ogg, history, metadata)
|
|
///
|
|
/// # Routes créées
|
|
///
|
|
/// Pour chaque canal (main, mellow, rock, eclectic) :
|
|
/// - `/radioparadise/stream/{slug}/flac` - Stream FLAC live
|
|
/// - `/radioparadise/stream/{slug}/ogg` - Stream OGG live
|
|
/// - `/radioparadise/stream/{slug}/historic/{client_id}/flac` - Historique FLAC
|
|
/// - `/radioparadise/stream/{slug}/historic/{client_id}/ogg` - Historique OGG
|
|
/// - `/radioparadise/metadata/{slug}` - Métadonnées en temps réel
|
|
///
|
|
/// # Exemples
|
|
///
|
|
/// ```ignore
|
|
/// use pmomediaserver::ParadiseStreamingExt;
|
|
///
|
|
/// server.init_paradise_streaming().await?;
|
|
/// ```
|
|
async fn init_paradise_streaming(&mut self) -> Result<Arc<ParadiseChannelManager>>;
|
|
}
|
|
|
|
#[async_trait]
|
|
impl ParadiseStreamingExt for pmoserver::Server {
|
|
async fn init_paradise_streaming(&mut self) -> Result<Arc<ParadiseChannelManager>> {
|
|
info!("🎵 Initializing Radio Paradise streaming channels...");
|
|
// Sentinel log pour vérifier qu'on exécute bien cette version du binaire
|
|
tracing::warn!(
|
|
"🔍 Rien de neuf: entering init_paradise_streaming with caches+history setup"
|
|
);
|
|
|
|
// Récupérer ou initialiser les caches singletons
|
|
info!("📦 Getting cache singletons...");
|
|
let cover_cache = match get_cover_cache() {
|
|
Some(cache) => {
|
|
info!(" ✅ Using existing cover cache singleton");
|
|
cache
|
|
}
|
|
None => {
|
|
info!(" 📦 Initializing new cover cache singleton");
|
|
let cache = self
|
|
.init_cover_cache_configured()
|
|
.await
|
|
.context("Failed to initialize cover cache")?;
|
|
register_cover_cache(cache.clone());
|
|
cache
|
|
}
|
|
};
|
|
|
|
let _audio_cache = match get_audio_cache() {
|
|
Some(cache) => {
|
|
info!(" ✅ Using existing audio cache singleton");
|
|
// S'assurer qu'il est aussi enregistré dans le playlist manager
|
|
register_playlist_audio_cache(cache.clone());
|
|
cache
|
|
}
|
|
None => {
|
|
info!(" 📦 Initializing new audio cache singleton");
|
|
let cache = self
|
|
.init_audio_cache_configured()
|
|
.await
|
|
.context("Failed to initialize audio cache")?;
|
|
register_audio_cache(cache.clone());
|
|
register_playlist_audio_cache(cache.clone());
|
|
cache
|
|
}
|
|
};
|
|
|
|
// Créer le builder d'historique
|
|
let mut history_builder = ParadiseHistoryBuilder::default();
|
|
history_builder.playlist_prefix = "radio-paradise-history".into();
|
|
history_builder.playlist_title_prefix = Some("Radio Paradise History".into());
|
|
history_builder.max_history_tracks = Some(500);
|
|
history_builder.collection_prefix = Some("radioparadise".into());
|
|
history_builder.replay_max_lead_seconds = 1.0;
|
|
|
|
// Créer le manager de canaux
|
|
let base_url = Some(self.base_url());
|
|
info!(
|
|
"📡 Creating ParadiseChannelManager (base_url={:?})...",
|
|
base_url
|
|
);
|
|
// Si la création bloque (réseau RP lent), on coupe après 30s pour ne pas empêcher le serveur de démarrer.
|
|
let manager = match tokio::time::timeout(
|
|
std::time::Duration::from_secs(30),
|
|
ParadiseChannelManager::with_defaults_with_cover_cache(
|
|
Some(cover_cache.clone()),
|
|
Some(history_builder),
|
|
base_url,
|
|
),
|
|
)
|
|
.await
|
|
{
|
|
Ok(Ok(mgr)) => {
|
|
info!("✅ ParadiseChannelManager created");
|
|
Arc::new(mgr)
|
|
}
|
|
Ok(Err(e)) => {
|
|
tracing::warn!("⚠️ Failed to create ParadiseChannelManager: {}", e);
|
|
return Err(e).context("Failed to create ParadiseChannelManager");
|
|
}
|
|
Err(_) => {
|
|
let msg = "Timeout creating ParadiseChannelManager after 30s";
|
|
tracing::warn!("⚠️ {}", msg);
|
|
return Err(anyhow::anyhow!(msg));
|
|
}
|
|
};
|
|
|
|
register_global_channel_manager(manager.clone());
|
|
spawn_playlist_event_handler(manager.clone());
|
|
|
|
let state = Arc::new(ParadiseStreamingState {
|
|
manager: manager.clone(),
|
|
});
|
|
|
|
// Ajouter les routes pour chaque canal
|
|
info!("🌐 Registering streaming routes...");
|
|
for descriptor in ALL_CHANNELS.iter() {
|
|
let slug = descriptor.slug;
|
|
let channel_id = descriptor.id;
|
|
|
|
// Route FLAC live
|
|
let flac_path = format!("/radioparadise/stream/{}/flac", slug);
|
|
self.add_handler_with_state(
|
|
&flac_path,
|
|
move |State(state): State<Arc<ParadiseStreamingState>>| {
|
|
let manager = state.manager.clone();
|
|
async move { stream_flac(manager, channel_id).await }
|
|
},
|
|
state.clone(),
|
|
)
|
|
.await;
|
|
|
|
// Route OGG live
|
|
let ogg_path = format!("/radioparadise/stream/{}/ogg", slug);
|
|
self.add_handler_with_state(
|
|
&ogg_path,
|
|
move |State(state): State<Arc<ParadiseStreamingState>>| {
|
|
let manager = state.manager.clone();
|
|
async move { stream_ogg(manager, channel_id).await }
|
|
},
|
|
state.clone(),
|
|
)
|
|
.await;
|
|
|
|
// Routes historique
|
|
let history_path = format!("/radioparadise/stream/{}/historic", slug);
|
|
let history_router = Router::new()
|
|
.route(
|
|
"/{client_id}/flac",
|
|
get({
|
|
let manager = manager.clone();
|
|
move |Path(client_id): Path<String>| {
|
|
let manager = manager.clone();
|
|
async move { stream_history_flac(manager, channel_id, client_id).await }
|
|
}
|
|
}),
|
|
)
|
|
.route(
|
|
"/{client_id}/ogg",
|
|
get({
|
|
let manager = manager.clone();
|
|
move |Path(client_id): Path<String>| {
|
|
let manager = manager.clone();
|
|
async move { stream_history_ogg(manager, channel_id, client_id).await }
|
|
}
|
|
}),
|
|
);
|
|
|
|
self.add_router(&history_path, history_router).await;
|
|
|
|
// Route métadonnées
|
|
let meta_path = format!("/radioparadise/metadata/{}", slug);
|
|
self.add_handler_with_state(
|
|
&meta_path,
|
|
move |State(state): State<Arc<ParadiseStreamingState>>| {
|
|
let manager = state.manager.clone();
|
|
async move { get_metadata(manager, channel_id).await }
|
|
},
|
|
state.clone(),
|
|
)
|
|
.await;
|
|
|
|
info!(
|
|
" ✅ {} - /radioparadise/stream/{}/{{flac,ogg}}",
|
|
descriptor.display_name, slug
|
|
);
|
|
}
|
|
|
|
info!("✅ Radio Paradise streaming channels initialized");
|
|
|
|
Ok(manager)
|
|
}
|
|
}
|
|
|
|
// ============================================================================
|
|
// Handlers de streaming
|
|
// ============================================================================
|
|
|
|
async fn stream_flac(
|
|
manager: Arc<ParadiseChannelManager>,
|
|
channel_id: u8,
|
|
) -> Result<Response, StatusCode> {
|
|
let channel = manager.get(channel_id).ok_or(StatusCode::NOT_FOUND)?;
|
|
let stream = channel.subscribe_flac();
|
|
Ok(Response::builder()
|
|
.status(StatusCode::OK)
|
|
.header(CONTENT_TYPE, "audio/flac")
|
|
.header(CACHE_CONTROL, "no-store, no-transform")
|
|
.header(CONNECTION, "keep-alive")
|
|
.header(ACCEPT_RANGES, "none")
|
|
.body(Body::from_stream(ReaderStream::new(stream)))
|
|
.unwrap())
|
|
}
|
|
|
|
async fn stream_ogg(
|
|
manager: Arc<ParadiseChannelManager>,
|
|
channel_id: u8,
|
|
) -> Result<Response, StatusCode> {
|
|
let channel = manager.get(channel_id).ok_or(StatusCode::NOT_FOUND)?;
|
|
let stream = channel.subscribe_ogg();
|
|
Ok(Response::builder()
|
|
.status(StatusCode::OK)
|
|
.header(CONTENT_TYPE, "application/ogg")
|
|
.header(CACHE_CONTROL, "no-store, no-transform")
|
|
.header(CONNECTION, "keep-alive")
|
|
.header(ACCEPT_RANGES, "none")
|
|
.body(Body::from_stream(ReaderStream::new(stream)))
|
|
.unwrap())
|
|
}
|
|
|
|
async fn get_metadata(
|
|
manager: Arc<ParadiseChannelManager>,
|
|
channel_id: u8,
|
|
) -> Result<impl IntoResponse, StatusCode> {
|
|
let channel = manager.get(channel_id).ok_or(StatusCode::NOT_FOUND)?;
|
|
let metadata = channel.metadata().await;
|
|
Ok(Json(metadata))
|
|
}
|
|
|
|
async fn stream_history_flac(
|
|
manager: Arc<ParadiseChannelManager>,
|
|
channel_id: u8,
|
|
client_id: String,
|
|
) -> Result<Response, StatusCode> {
|
|
let channel = manager.get(channel_id).ok_or(StatusCode::NOT_FOUND)?;
|
|
let stream = channel.stream_history_flac(&client_id).await.map_err(|e| {
|
|
error!(
|
|
"Failed to start historical FLAC stream for channel {} (client_id={}): {}",
|
|
channel_id, client_id, e
|
|
);
|
|
StatusCode::INTERNAL_SERVER_ERROR
|
|
})?;
|
|
Ok(Response::builder()
|
|
.status(StatusCode::OK)
|
|
.header(CONTENT_TYPE, "audio/flac")
|
|
.header(CACHE_CONTROL, "no-store, no-transform")
|
|
.header(CONNECTION, "keep-alive")
|
|
.header(ACCEPT_RANGES, "none")
|
|
.body(Body::from_stream(ReaderStream::new(stream)))
|
|
.unwrap())
|
|
}
|
|
|
|
async fn stream_history_ogg(
|
|
manager: Arc<ParadiseChannelManager>,
|
|
channel_id: u8,
|
|
client_id: String,
|
|
) -> Result<Response, StatusCode> {
|
|
let channel = manager.get(channel_id).ok_or(StatusCode::NOT_FOUND)?;
|
|
let stream = channel.stream_history_ogg(&client_id).await.map_err(|e| {
|
|
error!(
|
|
"Failed to start historical OGG stream for channel {} (client_id={}): {}",
|
|
channel_id, client_id, e
|
|
);
|
|
StatusCode::INTERNAL_SERVER_ERROR
|
|
})?;
|
|
Ok(Response::builder()
|
|
.status(StatusCode::OK)
|
|
.header(CONTENT_TYPE, "application/ogg")
|
|
.header(CACHE_CONTROL, "no-store, no-transform")
|
|
.header(CONNECTION, "keep-alive")
|
|
.header(ACCEPT_RANGES, "none")
|
|
.body(Body::from_stream(ReaderStream::new(stream)))
|
|
.unwrap())
|
|
}
|
|
|
|
fn spawn_playlist_event_handler(manager: Arc<ParadiseChannelManager>) {
|
|
tokio::spawn(async move {
|
|
let mut rx = pmoplaylist::subscribe_events();
|
|
while let Ok(envelope) = rx.recv().await {
|
|
if let PlaylistEventKind::TrackPlayed { cache_pk: _, .. } = envelope.event.kind {
|
|
if let Some(descriptor) = channel_from_live_playlist(&envelope.event.playlist_id) {
|
|
if let Err(e) = manager.prefetch_until_horizon(descriptor.id).await {
|
|
tracing::warn!(
|
|
"Failed to prefetch for channel {}: {}",
|
|
descriptor.display_name,
|
|
e
|
|
);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
fn channel_from_live_playlist(playlist_id: &str) -> Option<&'static ChannelDescriptor> {
|
|
const PREFIX: &str = "radio-paradise-live-";
|
|
let slug = playlist_id.strip_prefix(PREFIX)?;
|
|
ALL_CHANNELS
|
|
.iter()
|
|
.find(|descriptor| descriptor.slug == slug)
|
|
}
|