push-npwppmzuounm #69
25
.claude/hooks/preToolUse.sh
Executable file
25
.claude/hooks/preToolUse.sh
Executable file
@@ -0,0 +1,25 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Lire les données JSON envoyées par Claude Code
|
||||
INPUT=$(cat)
|
||||
|
||||
# Extraire le nom de l'outil
|
||||
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name')
|
||||
|
||||
# Pour les éditions de fichiers, forcer la demande de confirmation
|
||||
if [[ "$TOOL_NAME" == "Edit" ]] || [[ "$TOOL_NAME" == "MultiEdit" ]] || [[ "$TOOL_NAME" == "Write" ]]; then
|
||||
# Retourner une décision "ask" qui force la confirmation
|
||||
cat << EOF
|
||||
{
|
||||
"hookSpecificOutput": {
|
||||
"hookEventName": "PreToolUse",
|
||||
"permissionDecision": "ask",
|
||||
"permissionDecisionReason": "Validation requise pour toute édition de fichier"
|
||||
}
|
||||
}
|
||||
EOF
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Pour les autres outils, laisser passer normalement
|
||||
exit 0
|
||||
146
Blackboard/Report/metadata_RF_cache.md
Normal file
146
Blackboard/Report/metadata_RF_cache.md
Normal file
@@ -0,0 +1,146 @@
|
||||
# Rapport: Simplification de pmoradiofrance
|
||||
|
||||
## Résumé
|
||||
|
||||
Refactoring complet 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
|
||||
|
||||
## Plan d'implémentation détaillé
|
||||
|
||||
Le plan détaillé est disponible dans:
|
||||
`/Users/coissac/.claude/plans/glowing-scribbling-cook.md`
|
||||
173
Blackboard/ToDiscuss/metadata_RF_cache.md
Normal file
173
Blackboard/ToDiscuss/metadata_RF_cache.md
Normal file
@@ -0,0 +1,173 @@
|
||||
**Tu réaliseras ce travail en appliquant scrupuleusement les règles définies dans [@Rules.md](file:///Users/coissac/Sync/maison/Petite_maisons/src/pmomusic/Blackboard/Rules.md)**
|
||||
|
||||
**On ne travaille que dans la Crate PMORadioFrance**
|
||||
|
||||
À partir de maintenant, tu ne prends plus en compte ce que tu pensais avant et tu écoutes bien. Et tu construis un plan d'implémentation que je dois valider. Tu arrêtes de prendre des initiatives et de faire des bêtises.
|
||||
|
||||
- Tu as des fonctions d'interrogation de l'API Radio France qu'il faut utiliser au minimum. Mais Radio France nous donne des dates d'invalidation des métadonnées. Globalement, on doit gérer une grosse map où les valeurs ont des TTL.
|
||||
- Quand un client demande une donnée du cache, si le TTL est atteint, il commence par utiliser l'API Radio France, modifie le cache, puis la retourne. Dans le cas contraire, il retourne directement la donnée.
|
||||
|
||||
A chaque fois qu'il fait un appel de l'API Radio France pour modifier ses valeurs, Le cache émet un événement ou avertit ses abonnés, comme quoi les données d'un slug particulier ont été modifiées. Comme ça tout le monde peut se synchroniser.
|
||||
|
||||
Les clients, par exemple la fonction Browse, n'interrogent que le cache qui a forcément des données à jour. Les métadonnées ne sont jamais stockées hors du cache, on se réfère toujours à elles.
|
||||
|
||||
Nous devons maintenant considérer le fonctionnement du control point. Celui-ci est capable de s'abonner à une playlist pour suivre ses modifications. Il ne peut pas s'abonner à un item.
|
||||
|
||||
Dans le cas d'une radio, on peut considérer que chaque canal, chaque slug, est en réalité une playlist à un item qu'il faut suivre. Ainsi, le Control Point peut décider de jouer cette playlist en s'abonnant à elle et être tenu au courant des modifications par des événements GENA.
|
||||
|
||||
La source Radio France doit donc s'abonner aux événements du Cache. A chaque fois qu'un slug est modifié, elle avertit par un événement Jenna que la playlist à un item qui correspond à ce Slug est modifiée.
|
||||
|
||||
Maintenant, il y a le cache des stations. Le cache des stations finalement il ne stock qu'un emboîtement de listes de slug. Ça, normalement, ça ne bouge quasiment pas. On peut dire que une fois par jour, on met à jour ce cache. Les listes de slug ont donc un TTL mais très long.
|
||||
|
||||
A chaque browse, on reconstruit un document didl à partir des métadonnées à jour provenant du cache.
|
||||
|
||||
## Round 2
|
||||
|
||||
Je repasse sur ton code. Tout est beaucoup beaucoup trop compliqué, trop de structures allambiquées, de trucs qui s'emboîtent dans des trucs. Il faut faire simple. Le mot d'ordre est simple. Nous ne construisons pas une usine à gaz, nous construisons simplement un truc capable de diffuser moins d'une centaine de radios.
|
||||
|
||||
### Simplification de la notion de station.
|
||||
|
||||
Alors, tu fais une distinction entre radio locale et web radio, c'est une distinction sémantique, mais d'un point de vue informatique y'a pas de différence.
|
||||
|
||||
L'unité de base, ça devrait être:
|
||||
|
||||
pub struct StationGroup {
|
||||
pub stations: Vec<Station>,
|
||||
}
|
||||
|
||||
La seule règle metier sémantique est: L'index 0 du vecteur est attribué à la station principale du groupe, par exemple FIP, pour le groupe FIP, si elle existe.
|
||||
|
||||
Et du coup, les StationGroups devrait juste être un vecteur de StationGroup
|
||||
|
||||
- StationGroups définie le niveau zéro du browse
|
||||
- StationGroup définit les différents niveaux 1
|
||||
|
||||
Chaque station étant représentée maintenant par une playlist à un item item, Il y a un niveau 2 de browsing qui correspond à l'item de la station.
|
||||
|
||||
Donc, Station, StationGroup et StationGroups devrait chacun fournir une méthode retournant un objet PMODidl qui se construit en demandant les métadonnées au cache. Genre:
|
||||
|
||||
async pub fn to_didl(caches et server_base_url)
|
||||
|
||||
## Simplification du cache
|
||||
|
||||
Il faut réfléchir, Finalement, qu'est-ce que l'on a besoin de stocker dans le cache pour être efficace? De quoi remplir les Didl. Donc, à partir des données parsées depuis l'API Radio France, il faut reconstruire une structure simplifiée. contenant juste les données telles qu'on va les utiliser dans le diddle. Idéalement, le cache devrait être capable de fournir le bien d'idoles d'un item. Avec une méthode to_didl(slug) -> Un item de la Crate pmodidl. Tout le reste est superflu. Donc ne doit pas être stocké. Pour calculer la durée correctement, Il nous faut la fin de validité de l'item. Il est donc important de stocker end_time. Normalement, end time est aussi le TTL. Car à la fin de la diffusion de cet item, ça veut dire qu'il faut remettre à jour les métadata, Pour avoir l'item suivant.
|
||||
|
||||
## Round 3
|
||||
|
||||
### Problèmes identifiés
|
||||
|
||||
Point 3 : Le cache des slugs doit être persistant et stocké dans la config comme actuellement. Avec un délai d'une semaine. Le cache des métadonnées reste en mémoire. Les métadonnées changent à chaque émission, il n'y a pas de raison de les stocker de manière persistante.
|
||||
|
||||
Du coup, le cache des métadonnées, Pour simplifier la vie des autres structures. devrait s'occuper de cacher les covers dans pmocovers et stocker le PK de l'image dans le cache pour pouvoir construire le didl de l'item.
|
||||
|
||||
En fait, le didl de l'item, Dans notre nouvelle strategie est déjà un didl d'une playlist à un item.
|
||||
|
||||
### Architecture cible simplifiée
|
||||
|
||||
#### 1. Structures de station (models.rs et playlist.rs)
|
||||
|
||||
Je ne comprends pas bien la distinction entre les deux:
|
||||
A-t-on vraiment besoin des deux fonctions?
|
||||
À quoi sert cette fonction to_container?
|
||||
|
||||
```
|
||||
// Browse niveau 1: retourne les playlists (containers) pour chaque station du groupe
|
||||
pub async fn to_didl(&self, metadata_cache: &MetadataCache, server_base_url: &str) -> Vec<Container>;
|
||||
|
||||
// Helper pour construire le container de groupe (sans items, juste la structure)
|
||||
pub fn to_container(&self, server_base_url: Option<&str>) -> Container;
|
||||
```
|
||||
|
||||
```
|
||||
impl CachedMetadata {
|
||||
// Parse depuis LiveResponse + Station + optionnel cover cache
|
||||
#[cfg(feature = "cache")]
|
||||
pub async fn from_live_response(
|
||||
station: &Station,
|
||||
live: &LiveResponse,
|
||||
cover_cache: Option<&Arc<CoverCache>>,
|
||||
server_base_url: Option<&str>,
|
||||
) -> Result<Self>;
|
||||
|
||||
pub fn from_live_response_sync(
|
||||
station: &Station,
|
||||
live: &LiveResponse,
|
||||
server_base_url: Option<&str>,
|
||||
) -> Result<Self>;
|
||||
```
|
||||
|
||||
C'est quoi exactement la fonction from_live_response_sync ?
|
||||
J'ai l'impression que tu surcompliques encore.
|
||||
|
||||
```
|
||||
pub fn to_didl_item(&self, parent_id: &str) -> Item
|
||||
```
|
||||
|
||||
Vu ma remarque précédente:
|
||||
En fait, le didl de l'item, Dans notre nouvelle strategie est déjà un didl d'une playlist à un item.
|
||||
|
||||
Cette fonction devrait juste être un toDiddle et retourner le diddle d'une playlist à un item avec exactement les mêmes métadonnées pour la playlist conteneur et l'item à l'intérieur.
|
||||
|
||||
### 3. Cache de stations (intégré dans stateful_client.rs)
|
||||
|
||||
Comme je le disais plus haut, ce cache doit être permanent via l'usage de la configuration. Comme c'est le cas actuellement.
|
||||
|
||||
## Hiérarchie de browse
|
||||
|
||||
**Niveau 1**: Browse d'un groupe
|
||||
En fait, si un station groupe ne contient qu'un seul item, C'est à dire qu'il n'y a pas plusieurs sous-radios sous ce groupe. on peut directement retourner la playlist simple qui contient simplement cet item.
|
||||
|
||||
Questions pour validation
|
||||
|
||||
1. **Organisation des stations sans webradios**: Faut-il créer un groupe pour chaque station standalone (France Culture, France Inter, etc.) ou les mettre toutes dans un seul groupe "Stations principales"?
|
||||
- En fait, si un station groupe ne contient qu'un seul item, C'est à dire qu'il n'y a pas plusieurs sous-radios sous ce groupe. on peut directement retourner la playlist simple qui contient simplement cet item. Sinon, on retourne un container qui contient les playlists de chacun des items. Cela peut directement être implémenté dans le code de la fonction to Didl du groupe de station.
|
||||
|
||||
2. **Cache de métadonnées**: In-memory uniquement (données volatiles avec TTL court)?
|
||||
- Oui, in-memory seulement, TTL basé sur la fin de diffusion de cet item.
|
||||
|
||||
3. **Cache de stations**: Rester dans pmoconfig avec TTL 1 jour?
|
||||
- Oui, garder le système actuel, Il me semble que le TTL est d'une semaine actuellement, mais le garder tel qu'il est.
|
||||
|
||||
4. **Gestion d'erreur API Radio France down**: Retourner les données expirées avec warning?
|
||||
- **Proposition**: Oui, graceful degradation
|
||||
C'est parfait.
|
||||
|
||||
5. **Migration du code existant**: Faut-il maintenir une compatibilité temporaire ou refactoring complet immédiat?
|
||||
- **Proposition**: Refactoring complet, c'est une simplification profonde
|
||||
C'est parfait.
|
||||
|
||||
|
||||
## Round 4
|
||||
|
||||
### 2. Groupes de stations (playlist.rs)
|
||||
|
||||
```
|
||||
impl StationGroups {
|
||||
// Browse niveau 0: retourne les containers de groupes
|
||||
pub async fn to_didl(&self, metadata_cache: &MetadataCache, server_base_url: &str) -> Vec<Container>;
|
||||
}
|
||||
```
|
||||
|
||||
Pourquoi retourner un vecteur de conteneurs et pas un conteneur qui contient des conteneurs? Ça doit retourner une structure didl La fonction s'appelle to_didl.
|
||||
|
||||
Il faut être cohérent. Et **SIMPLE**.
|
||||
|
||||
### 3. Cache de métadonnées (NOUVEAU: metadata_cache.rs)
|
||||
|
||||
Il y a actuellement dans le code des règles pour passer des métadonnées Radio France vers des métadonnées UPNP, qui agrège les métadonnées selon certaines règles depuis Radio France pour en faire des métadonnées plus simples mais avec une sémantique correcte pour l'interface utilisateur du côté UPNP. Il ne faut pas abandonner ces règles.
|
||||
|
||||
### Hiérarchie de browse
|
||||
|
||||
**Niveau 0**: `radiofrance` → containers de groupes
|
||||
- "France Culture" (id: `radiofrance:franceculture`) - playlist directe si groupe à 1 station
|
||||
- "FIP" (id: `radiofrance:group:fip`) - container de groupe si plusieurs stations
|
||||
- "Radios ICI" (id: `radiofrance:ici`) - container de groupe pour les radios locales --> Je te rappelle qu'il n'y a plus de distinction entre radio locale et autres radios. Ça c'était avant. Donc ICI fonctionne exactement comme FIP.
|
||||
|
||||
### Étapes d'implémentation
|
||||
|
||||
#### Étape 1: Créer metadata_cache.rs
|
||||
1. Définir `CachedMetadata` struct avec tous les champs DIDL
|
||||
|
||||
On est d'accord que si tu définis ce type là, ça veut dire que tu supprimes le client Stateful. Sans ça, c'est complètement redondant.
|
||||
|
||||
A la fin de cette tâche, tu généreras le nouveau plan dans le fichier de rapport tel que c'est demandé par le fichier de règles [@Rules.md](file:///Users/coissac/Sync/maison/Petite_maisons/src/pmomusic/Blackboard/Rules.md) que tu devras suivre scrupuleusement.
|
||||
2
Cargo.lock
generated
2
Cargo.lock
generated
@@ -4,7 +4,7 @@ version = 4
|
||||
|
||||
[[package]]
|
||||
name = "PMOMusic"
|
||||
version = "0.3.12"
|
||||
version = "0.3.15"
|
||||
dependencies = [
|
||||
"axum 0.8.7",
|
||||
"console-subscriber",
|
||||
|
||||
@@ -50,6 +50,7 @@ COPY pmoaudiocache/ ./pmoaudiocache/
|
||||
COPY pmoaudio/ ./pmoaudio/
|
||||
COPY pmoqobuz/ ./pmoqobuz/
|
||||
COPY pmoparadise/ ./pmoparadise/
|
||||
COPY pmoradiofrance/ ./pmoradiofrance/
|
||||
COPY pmosource/ ./pmosource/
|
||||
COPY pmoplaylist/ ./pmoplaylist/
|
||||
COPY pmoflac/ ./pmoflac/
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "PMOMusic"
|
||||
version = "0.3.12"
|
||||
version = "0.3.15"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
||||
@@ -11,6 +11,7 @@ use std::sync::{Arc, Mutex};
|
||||
use std::thread::{self, JoinHandle};
|
||||
use std::time::SystemTime;
|
||||
|
||||
use pmodidl::{DIDLLite, MediaMetadataParser};
|
||||
use tracing::{debug, error};
|
||||
|
||||
use crate::errors::ControlPointError;
|
||||
@@ -755,8 +756,30 @@ impl MusicRenderer {
|
||||
|
||||
/// Get playback position
|
||||
pub fn playback_position(&self) -> Result<PlaybackPositionInfo, ControlPointError> {
|
||||
self.lock_backend_for("playback_position")
|
||||
.playback_position()
|
||||
let mut position_info = self
|
||||
.lock_backend_for("playback_position")
|
||||
.playback_position()?;
|
||||
|
||||
// Si track_duration est absent ou invalide, essayer de le parser depuis le DIDL metadata
|
||||
let needs_duration_fix = position_info
|
||||
.track_duration
|
||||
.as_ref()
|
||||
.map(|d| d == "00:00:00" || d == "0:00:00")
|
||||
.unwrap_or(true); // None = true
|
||||
|
||||
if needs_duration_fix {
|
||||
if let Some(ref metadata_xml) = position_info.track_metadata {
|
||||
if let Some(duration) = parse_didl_duration(metadata_xml) {
|
||||
tracing::debug!(
|
||||
"MusicRenderer: Corrected track_duration from DIDL metadata: {}",
|
||||
duration
|
||||
);
|
||||
position_info.track_duration = Some(duration);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(position_info)
|
||||
}
|
||||
|
||||
/// Sets the playlist binding for this renderer.
|
||||
@@ -1437,6 +1460,36 @@ impl RendererFromMediaRendererInfo for MusicRendererBackend {
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse duration from DIDL-Lite metadata XML.
|
||||
///
|
||||
/// Extracts the duration attribute from the <res> element in DIDL metadata.
|
||||
/// This is used as a fallback when the renderer doesn't provide track_duration
|
||||
/// in GetPositionInfo or similar calls.
|
||||
fn parse_didl_duration(didl_xml: &str) -> Option<String> {
|
||||
// Parse DIDL-Lite XML properly using pmodidl
|
||||
let didl = match DIDLLite::parse(didl_xml) {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
tracing::trace!("Failed to parse DIDL metadata: {}", e);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
// Extract duration from the first item's first resource
|
||||
let duration = didl.items.first()?.resources.first()?.duration.clone();
|
||||
|
||||
if let Some(ref dur) = duration {
|
||||
tracing::debug!(
|
||||
"MusicRenderer: Extracted duration from DIDL metadata: {}",
|
||||
dur
|
||||
);
|
||||
} else {
|
||||
tracing::trace!("No duration attribute found in DIDL metadata");
|
||||
}
|
||||
|
||||
duration
|
||||
}
|
||||
|
||||
/// Transport control façade that dispatches to whichever backend can fulfill
|
||||
/// the request, returning a standardized error if the backend lacks support.
|
||||
impl TransportControl for MusicRendererBackend {
|
||||
|
||||
@@ -473,7 +473,7 @@ impl ContentHandler {
|
||||
/// Construit le container racine du MediaServer
|
||||
async fn build_root_container(&self) -> Container {
|
||||
let sources = list_all_sources().await;
|
||||
let child_count = sources.len();
|
||||
let _child_count = sources.len();
|
||||
|
||||
Container {
|
||||
id: "0".to_string(),
|
||||
|
||||
@@ -16,8 +16,8 @@ use axum::{
|
||||
response::{IntoResponse, Response},
|
||||
routing::get,
|
||||
};
|
||||
use pmoaudiocache::{AudioCacheExt, Cache as AudioCache, get_audio_cache, register_audio_cache};
|
||||
use pmocovers::{Cache as CoverCache, CoverCacheExt, get_cover_cache, register_cover_cache};
|
||||
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},
|
||||
@@ -91,7 +91,7 @@ impl ParadiseStreamingExt for pmoserver::Server {
|
||||
}
|
||||
};
|
||||
|
||||
let audio_cache = match get_audio_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
|
||||
@@ -332,7 +332,7 @@ 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 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!(
|
||||
|
||||
@@ -244,25 +244,21 @@ impl SourcesExt for Server {
|
||||
|
||||
#[cfg(feature = "radiofrance")]
|
||||
async fn register_radiofrance(&mut self) -> Result<()> {
|
||||
use pmoradiofrance::{RadioFranceExt, RadioFranceSource, RadioFranceStatefulClient};
|
||||
use pmoradiofrance::{RadioFranceExt, RadioFranceSource};
|
||||
|
||||
tracing::info!("Initializing Radio France source...");
|
||||
|
||||
// Obtenir l'URL de base du serveur
|
||||
let base_url = self.base_url();
|
||||
|
||||
// Créer le client stateful depuis la config
|
||||
let client = RadioFranceStatefulClient::from_config()
|
||||
// Créer la source depuis le registry (avec cache)
|
||||
let config = pmoconfig::get_config();
|
||||
let source = RadioFranceSource::from_registry(config, base_url)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
SourceInitError::RadioFranceError(format!("Failed to create client: {}", e))
|
||||
SourceInitError::RadioFranceError(format!("Failed to create source: {}", e))
|
||||
})?;
|
||||
|
||||
// Créer la source depuis le registry (avec cache)
|
||||
let source = RadioFranceSource::from_registry(client, base_url).map_err(|e| {
|
||||
SourceInitError::RadioFranceError(format!("Failed to create source: {}", e))
|
||||
})?;
|
||||
|
||||
// Configurer le notifier pour les événements UPnP GENA
|
||||
let notifier = Arc::new(|containers: &[String]| {
|
||||
let refs: Vec<&str> = containers.iter().map(|s| s.as_str()).collect();
|
||||
|
||||
@@ -145,7 +145,7 @@ async fn register_qobuz(Json(creds): Json<QobuzCredentials>) -> impl IntoRespons
|
||||
tag = "sources"
|
||||
)]
|
||||
async fn register_paradise(Json(params): Json<ParadiseParams>) -> impl IntoResponse {
|
||||
use pmoparadise::{RadioParadiseClient, RadioParadiseSource};
|
||||
use pmoparadise::RadioParadiseSource;
|
||||
use pmosource::api::register_source;
|
||||
|
||||
// Utiliser l'URL de base depuis les params ou une valeur par défaut
|
||||
|
||||
@@ -16,7 +16,6 @@ use axum::{
|
||||
};
|
||||
use futures::StreamExt;
|
||||
use serde_json;
|
||||
use std::sync::Arc;
|
||||
|
||||
// ============ Gestion des erreurs ============
|
||||
|
||||
@@ -61,33 +60,26 @@ pub fn create_router(state: RadioFranceState) -> Router {
|
||||
|
||||
/// GET /api/radiofrance/stations
|
||||
/// Returns the grouped list of stations
|
||||
#[axum::debug_handler]
|
||||
async fn get_stations(
|
||||
State(state): State<RadioFranceState>,
|
||||
) -> Result<Json<StationGroups>, AppError> {
|
||||
let stations = state
|
||||
.client
|
||||
.get_stations()
|
||||
.await
|
||||
.map_err(|e| AppError(e.to_string()))?;
|
||||
|
||||
let groups = StationGroups::from_stations(stations);
|
||||
Ok(Json(groups))
|
||||
async fn get_stations(State(state): State<RadioFranceState>) -> impl IntoResponse {
|
||||
match state.source.get_stations().await {
|
||||
Ok(stations) => {
|
||||
let groups = StationGroups::from_stations(stations);
|
||||
Json(groups).into_response()
|
||||
}
|
||||
Err(e) => AppError(e.to_string()).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
/// GET /api/radiofrance/{slug}/metadata
|
||||
/// Returns live metadata for a station (with caching)
|
||||
/// Returns live metadata for a station
|
||||
async fn get_metadata(
|
||||
State(state): State<RadioFranceState>,
|
||||
Path(slug): Path<String>,
|
||||
) -> Result<Json<LiveResponse>, AppError> {
|
||||
let metadata = state
|
||||
.client
|
||||
.get_live_metadata(&slug)
|
||||
.await
|
||||
.map_err(|e| AppError(e.to_string()))?;
|
||||
|
||||
Ok(Json(metadata))
|
||||
) -> impl IntoResponse {
|
||||
match state.source.get_live_metadata(&slug).await {
|
||||
Ok(metadata) => Json(metadata).into_response(),
|
||||
Err(e) => AppError(e.to_string()).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
/// GET /api/radiofrance/{slug}/stream
|
||||
@@ -95,40 +87,24 @@ async fn get_metadata(
|
||||
async fn proxy_stream(
|
||||
State(state): State<RadioFranceState>,
|
||||
Path(slug): Path<String>,
|
||||
) -> Result<Response, AppError> {
|
||||
// Start metadata refresh when stream is accessed
|
||||
) -> impl IntoResponse {
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::info!("Stream proxy accessed for station: {}", slug);
|
||||
|
||||
if let Some(ref source) = state.source {
|
||||
// Spawn refresh task (non-blocking)
|
||||
let source_clone = Arc::clone(source);
|
||||
let slug_clone = slug.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = source_clone.start_metadata_refresh(&slug_clone).await {
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::error!("Failed to start metadata refresh for {}: {}", slug_clone, e);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::warn!("No source available to start metadata refresh");
|
||||
}
|
||||
|
||||
// Get the stream URL
|
||||
let stream_url = state
|
||||
.client
|
||||
.get_stream_url(&slug)
|
||||
.await
|
||||
.map_err(|e| AppError(format!("Stream not found: {}", e)))?;
|
||||
let stream_url = match state.source.get_stream_url(&slug).await {
|
||||
Ok(url) => url,
|
||||
Err(e) => return AppError(format!("Stream not found: {}", e)).into_response(),
|
||||
};
|
||||
|
||||
// Connect to the Radio France stream
|
||||
let response = reqwest::get(&stream_url)
|
||||
.await
|
||||
.map_err(|e| AppError(format!("Failed to connect: {}", e)))?;
|
||||
let response = match reqwest::get(&stream_url).await {
|
||||
Ok(r) => r,
|
||||
Err(e) => return AppError(format!("Failed to connect: {}", e)).into_response(),
|
||||
};
|
||||
|
||||
if !response.status().is_success() {
|
||||
return Err(AppError(format!("Upstream returned {}", response.status())));
|
||||
return AppError(format!("Upstream returned {}", response.status())).into_response();
|
||||
}
|
||||
|
||||
// Build response headers
|
||||
@@ -136,50 +112,14 @@ async fn proxy_stream(
|
||||
headers.insert("content-type", "audio/aac".parse().unwrap());
|
||||
headers.insert("cache-control", "no-cache".parse().unwrap());
|
||||
|
||||
// Create streaming body with cleanup on disconnect
|
||||
// Create streaming body
|
||||
let stream = response
|
||||
.bytes_stream()
|
||||
.map(|chunk| chunk.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e)));
|
||||
|
||||
// Wrap the stream to detect when client disconnects
|
||||
let source_for_cleanup = state.source.clone();
|
||||
let slug_for_cleanup = slug.clone();
|
||||
let monitored_stream =
|
||||
futures::stream::unfold((stream, false), move |(mut stream, mut done)| {
|
||||
let source = source_for_cleanup.clone();
|
||||
let slug = slug_for_cleanup.clone();
|
||||
async move {
|
||||
if done {
|
||||
return None;
|
||||
}
|
||||
let body = Body::from_stream(stream);
|
||||
|
||||
match stream.next().await {
|
||||
Some(Ok(chunk)) => Some((Ok(chunk), (stream, false))),
|
||||
Some(Err(e)) => {
|
||||
// Error occurred, stop refresh
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::info!("Stream error for {}, stopping refresh", slug);
|
||||
if let Some(src) = source {
|
||||
src.stop_metadata_refresh(&slug).await;
|
||||
}
|
||||
Some((Err(e), (stream, true)))
|
||||
}
|
||||
None => {
|
||||
// Stream ended normally, stop refresh
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::info!("Stream ended for {}, stopping refresh", slug);
|
||||
if let Some(src) = source {
|
||||
src.stop_metadata_refresh(&slug).await;
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let body = Body::from_stream(monitored_stream);
|
||||
|
||||
Ok((headers, body).into_response())
|
||||
(headers, body).into_response()
|
||||
}
|
||||
|
||||
/// GET /api/radiofrance/default-logo
|
||||
|
||||
@@ -200,7 +200,7 @@ impl RadioFranceClient {
|
||||
.into_iter()
|
||||
.map(|slug| {
|
||||
let name = Self::slug_to_display_name(&slug);
|
||||
Station::main(slug, name)
|
||||
Station::new(slug, name)
|
||||
})
|
||||
.collect());
|
||||
}
|
||||
@@ -211,7 +211,7 @@ impl RadioFranceClient {
|
||||
|
||||
Ok(KNOWN_MAIN_STATIONS
|
||||
.iter()
|
||||
.map(|(slug, name)| Station::main(*slug, *name))
|
||||
.map(|(slug, name)| Station::new(*slug, *name))
|
||||
.collect())
|
||||
}
|
||||
|
||||
@@ -249,7 +249,7 @@ impl RadioFranceClient {
|
||||
.into_iter()
|
||||
.map(|slug| {
|
||||
let name = Self::slug_to_display_name(&slug);
|
||||
Station::webradio(slug, name, station)
|
||||
Station::new(slug, name)
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
@@ -267,10 +267,7 @@ impl RadioFranceClient {
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter(|local| local.is_on_air)
|
||||
.map(|local| {
|
||||
let region = local.title.replace("ICI ", "");
|
||||
Station::local_radio(local.name, local.title, region, local.id)
|
||||
})
|
||||
.map(|local| Station::new(local.name, local.title))
|
||||
.collect())
|
||||
}
|
||||
|
||||
@@ -1145,21 +1142,9 @@ mod tests {
|
||||
let stations = stations.unwrap();
|
||||
assert!(!stations.is_empty(), "Expected stations");
|
||||
|
||||
// Count by type
|
||||
let main_count = stations.iter().filter(|s| s.is_main()).count();
|
||||
let webradio_count = stations.iter().filter(|s| s.is_webradio()).count();
|
||||
let local_count = stations.iter().filter(|s| s.is_local_radio()).count();
|
||||
println!("Discovered {} total stations", stations.len());
|
||||
|
||||
println!("Discovered {} total stations:", stations.len());
|
||||
println!(" - {} main stations", main_count);
|
||||
println!(" - {} webradios", webradio_count);
|
||||
println!(" - {} local radios", local_count);
|
||||
|
||||
// Should have a good mix
|
||||
assert!(main_count >= 5, "Expected at least 5 main stations");
|
||||
assert!(local_count >= 30, "Expected at least 30 local radios");
|
||||
|
||||
// Total should be significant
|
||||
// Should have a significant number of stations
|
||||
assert!(
|
||||
stations.len() >= 40,
|
||||
"Expected at least 40 total stations, got {}",
|
||||
|
||||
@@ -32,14 +32,23 @@
|
||||
//! # }
|
||||
//! ```
|
||||
|
||||
use crate::models::{CachedStationList, Station};
|
||||
use crate::models::Station;
|
||||
use anyhow::Result;
|
||||
use pmoconfig::Config;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_yaml::Value;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
/// Default TTL for station list cache (7 days in seconds)
|
||||
pub const DEFAULT_STATION_CACHE_TTL_SECS: u64 = 7 * 24 * 3600;
|
||||
|
||||
/// Cached station list (simplifié)
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
struct CachedStations {
|
||||
stations: Vec<Station>,
|
||||
last_updated: u64, // Unix timestamp
|
||||
}
|
||||
|
||||
/// Trait d'extension pour gérer la configuration Radio France dans pmoconfig
|
||||
///
|
||||
/// Ce trait étend `pmoconfig::Config` avec des méthodes spécifiques
|
||||
@@ -75,7 +84,7 @@ pub trait RadioFranceConfigExt {
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// - `Some(CachedStationList)` si le cache existe et est valide
|
||||
/// - `Some(Vec<Station>)` si le cache existe et est valide
|
||||
/// - `None` si le cache n'existe pas ou est expiré
|
||||
///
|
||||
/// # Cache Validation
|
||||
@@ -83,8 +92,7 @@ pub trait RadioFranceConfigExt {
|
||||
/// Le cache est considéré invalide si :
|
||||
/// - Il n'existe pas
|
||||
/// - Son TTL est dépassé (configurable, défaut 7 jours)
|
||||
/// - Sa version ne correspond pas à la version actuelle de l'algorithme
|
||||
fn get_radiofrance_cached_stations(&self) -> Result<Option<CachedStationList>>;
|
||||
fn get_radiofrance_stations_cached(&self) -> Result<Option<Vec<Station>>>;
|
||||
|
||||
/// Enregistre la liste des stations en cache
|
||||
///
|
||||
@@ -103,45 +111,8 @@ pub trait RadioFranceConfigExt {
|
||||
/// Définit le TTL du cache des stations (en secondes)
|
||||
fn set_radiofrance_station_cache_ttl(&self, ttl_secs: u64) -> Result<()>;
|
||||
|
||||
/// Vérifie si le cache des stations est valide
|
||||
///
|
||||
/// Raccourci pour `get_radiofrance_cached_stations()?.is_some()`
|
||||
fn is_radiofrance_station_cache_valid(&self) -> bool;
|
||||
|
||||
/// Efface le cache des stations (force re-découverte)
|
||||
fn clear_radiofrance_station_cache(&self) -> Result<()>;
|
||||
|
||||
// ========================================================================
|
||||
// High-level helpers
|
||||
// ========================================================================
|
||||
|
||||
/// Récupère les stations, en utilisant le cache si valide
|
||||
///
|
||||
/// Cette méthode est un helper qui :
|
||||
/// 1. Vérifie le cache
|
||||
/// 2. Si valide, retourne les stations du cache
|
||||
/// 3. Si invalide, retourne None (l'appelant doit découvrir et mettre en cache)
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```no_run
|
||||
/// # use pmoconfig::get_config;
|
||||
/// # use pmoradiofrance::{RadioFranceConfigExt, RadioFranceClient};
|
||||
/// # #[tokio::main]
|
||||
/// # async fn main() -> anyhow::Result<()> {
|
||||
/// let config = get_config();
|
||||
/// let stations = if let Some(cached) = config.get_radiofrance_stations_cached()? {
|
||||
/// cached
|
||||
/// } else {
|
||||
/// let client = RadioFranceClient::new().await?;
|
||||
/// let discovered = client.discover_all_stations().await?;
|
||||
/// config.set_radiofrance_cached_stations(&discovered)?;
|
||||
/// discovered
|
||||
/// };
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
fn get_radiofrance_stations_cached(&self) -> Result<Option<Vec<Station>>>;
|
||||
}
|
||||
|
||||
impl RadioFranceConfigExt for Config {
|
||||
@@ -160,19 +131,24 @@ impl RadioFranceConfigExt for Config {
|
||||
self.set_value(&["sources", "radiofrance", "enabled"], Value::Bool(enabled))
|
||||
}
|
||||
|
||||
fn get_radiofrance_cached_stations(&self) -> Result<Option<CachedStationList>> {
|
||||
fn get_radiofrance_stations_cached(&self) -> Result<Option<Vec<Station>>> {
|
||||
let ttl = self.get_radiofrance_station_cache_ttl()?;
|
||||
|
||||
match self.get_value(&["sources", "radiofrance", "station_cache"]) {
|
||||
Ok(value) => {
|
||||
// Try to deserialize the cached data
|
||||
let cached: CachedStationList = serde_yaml::from_value(value)?;
|
||||
let cached: CachedStations = serde_yaml::from_value(value)?;
|
||||
|
||||
// Check validity
|
||||
if cached.is_valid(ttl) {
|
||||
Ok(Some(cached))
|
||||
// Check validity (TTL)
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs();
|
||||
|
||||
if now - cached.last_updated < ttl {
|
||||
Ok(Some(cached.stations))
|
||||
} else {
|
||||
// Cache expired or version mismatch
|
||||
// Cache expired
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
@@ -181,7 +157,16 @@ impl RadioFranceConfigExt for Config {
|
||||
}
|
||||
|
||||
fn set_radiofrance_cached_stations(&self, stations: &[Station]) -> Result<()> {
|
||||
let cached = CachedStationList::new(stations.to_vec());
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs();
|
||||
|
||||
let cached = CachedStations {
|
||||
stations: stations.to_vec(),
|
||||
last_updated: now,
|
||||
};
|
||||
|
||||
let value = serde_yaml::to_value(&cached)?;
|
||||
self.set_value(&["sources", "radiofrance", "station_cache"], value)
|
||||
}
|
||||
@@ -212,23 +197,10 @@ impl RadioFranceConfigExt for Config {
|
||||
)
|
||||
}
|
||||
|
||||
fn is_radiofrance_station_cache_valid(&self) -> bool {
|
||||
self.get_radiofrance_cached_stations()
|
||||
.ok()
|
||||
.flatten()
|
||||
.is_some()
|
||||
}
|
||||
|
||||
fn clear_radiofrance_station_cache(&self) -> Result<()> {
|
||||
// Set to null to clear
|
||||
self.set_value(&["sources", "radiofrance", "station_cache"], Value::Null)
|
||||
}
|
||||
|
||||
fn get_radiofrance_stations_cached(&self) -> Result<Option<Vec<Station>>> {
|
||||
Ok(self
|
||||
.get_radiofrance_cached_stations()?
|
||||
.map(|cached| cached.stations))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -96,7 +96,7 @@ pub mod models;
|
||||
pub mod config_ext;
|
||||
|
||||
#[cfg(feature = "pmoconfig")]
|
||||
pub mod stateful_client;
|
||||
pub mod metadata_cache;
|
||||
|
||||
#[cfg(feature = "playlist")]
|
||||
pub mod playlist;
|
||||
@@ -117,18 +117,18 @@ pub mod api_rest;
|
||||
pub use client::{ClientBuilder, RadioFranceClient};
|
||||
pub use error::{Error, Result};
|
||||
pub use models::{
|
||||
BroadcastType, CachedStationList, EmbedImage, ImageSize, Line, LiveResponse, LocalRadio, Media,
|
||||
Release, ShowMetadata, Song, Station, StationType, StreamFormat, StreamSource, Visuals,
|
||||
BroadcastType, EmbedImage, ImageSize, Line, LiveResponse, LocalRadio, Media, Release,
|
||||
ShowMetadata, Song, Station, StreamFormat, StreamSource, Visuals,
|
||||
};
|
||||
|
||||
#[cfg(feature = "pmoconfig")]
|
||||
pub use config_ext::RadioFranceConfigExt;
|
||||
|
||||
#[cfg(feature = "pmoconfig")]
|
||||
pub use stateful_client::RadioFranceStatefulClient;
|
||||
pub use metadata_cache::{CachedMetadata, MetadataCache, MetadataUpdateCallback};
|
||||
|
||||
#[cfg(feature = "playlist")]
|
||||
pub use playlist::{StationGroup, StationGroups, StationPlaylist};
|
||||
pub use playlist::{StationGroup, StationGroups};
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
pub use source::RadioFranceSource;
|
||||
|
||||
664
pmoradiofrance/src/metadata_cache.rs
Normal file
664
pmoradiofrance/src/metadata_cache.rs
Normal file
@@ -0,0 +1,664 @@
|
||||
//! Cache de métadonnées pour Radio France avec TTL et système d'événements
|
||||
//!
|
||||
//! Ce module fournit un cache centralisé pour les métadonnées des stations Radio France:
|
||||
//! - Cache in-memory avec TTL basé sur `end_time` de l'API
|
||||
//! - Gestion automatique du cache de covers via pmocovers
|
||||
//! - Système d'événements pour la synchronisation GENA
|
||||
//! - Cache persistant des stations via pmoconfig
|
||||
//!
|
||||
//! # Architecture
|
||||
//!
|
||||
//! - `CachedMetadata` : Métadonnées simplifiées pour construire un DIDL
|
||||
//! - `MetadataCache` : Gère le cache in-memory + cache persistant + événements
|
||||
|
||||
use crate::client::RadioFranceClient;
|
||||
use crate::error::Result;
|
||||
use crate::models::{ImageSize, LiveResponse, Station};
|
||||
use pmoconfig::Config;
|
||||
use pmodidl::{Container, Item, Resource};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
#[cfg(feature = "cache")]
|
||||
use pmocovers::Cache as CoverCache;
|
||||
|
||||
#[cfg(feature = "cache")]
|
||||
use pmocache::cache_trait::FileCache;
|
||||
|
||||
// ============================================================================
|
||||
// CachedMetadata
|
||||
// ============================================================================
|
||||
|
||||
/// Métadonnées simplifiées pour construire un DIDL de playlist à un item
|
||||
///
|
||||
/// Contient UNIQUEMENT les données nécessaires pour remplir le DIDL.
|
||||
/// Construit depuis `LiveResponse` avec les règles de mapping RF → UPnP.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CachedMetadata {
|
||||
/// Slug de la station
|
||||
pub slug: String,
|
||||
|
||||
// Champs pour le DIDL (playlist + item)
|
||||
pub title: String,
|
||||
pub creator: Option<String>,
|
||||
pub artist: Option<String>,
|
||||
pub album: Option<String>,
|
||||
pub genre: Option<String>,
|
||||
pub class: String,
|
||||
pub album_art: Option<String>, // URL publique de la cover
|
||||
pub album_art_pk: Option<String>, // PK dans pmocovers
|
||||
|
||||
// Resource (stream)
|
||||
pub stream_url: String,
|
||||
pub protocol_info: String,
|
||||
pub sample_frequency: Option<String>,
|
||||
pub nr_audio_channels: Option<String>,
|
||||
pub duration: Option<String>, // Calculé depuis end_time
|
||||
|
||||
// TTL = end_time de l'API Radio France
|
||||
pub end_time: Option<u64>, // Unix timestamp
|
||||
}
|
||||
|
||||
impl CachedMetadata {
|
||||
/// Parse depuis LiveResponse avec gestion automatique du cache de covers
|
||||
///
|
||||
/// IMPORTANT: Préserve les règles de mapping RF → UPnP existantes:
|
||||
/// - Radio musicale avec song → métadonnées du morceau
|
||||
/// - Radio parlée → agrégation émission/producteur
|
||||
/// - Évite duplications du nom de station
|
||||
/// - Calcule duration depuis end_time
|
||||
#[cfg(feature = "cache")]
|
||||
pub async fn from_live_response(
|
||||
station: &Station,
|
||||
live: &LiveResponse,
|
||||
cover_cache: &Arc<CoverCache>,
|
||||
server_base_url: &str,
|
||||
) -> Result<Self> {
|
||||
// 1. Extraire les champs metadata avec les règles RF → UPnP
|
||||
let (title, creator, artist, album, genre, class) =
|
||||
Self::extract_metadata_fields(station, live);
|
||||
|
||||
// 2. Gestion de la cover avec cache
|
||||
let (album_art, album_art_pk) = Self::cache_cover(live, cover_cache, server_base_url).await;
|
||||
|
||||
// 3. Construction de la ressource (stream)
|
||||
let (stream_url, protocol_info, sample_frequency, nr_audio_channels, duration) =
|
||||
Self::build_stream_resource(live, &station.slug, server_base_url);
|
||||
|
||||
// 4. TTL = end_time
|
||||
let end_time = live.now.end_time;
|
||||
|
||||
Ok(Self {
|
||||
slug: station.slug.clone(),
|
||||
title,
|
||||
creator,
|
||||
artist,
|
||||
album,
|
||||
genre,
|
||||
class,
|
||||
album_art,
|
||||
album_art_pk,
|
||||
stream_url,
|
||||
protocol_info,
|
||||
sample_frequency,
|
||||
nr_audio_channels,
|
||||
duration,
|
||||
end_time,
|
||||
})
|
||||
}
|
||||
|
||||
/// Extrait les champs de métadonnées selon le type de radio
|
||||
///
|
||||
/// RÈGLES DE MAPPING (préservées du code existant):
|
||||
/// - Radio musicale avec song → titre/artiste/album du morceau
|
||||
/// - Radio parlée → agrégation émission/producteur
|
||||
fn extract_metadata_fields(
|
||||
station: &Station,
|
||||
metadata: &LiveResponse,
|
||||
) -> (
|
||||
String,
|
||||
Option<String>,
|
||||
Option<String>,
|
||||
Option<String>,
|
||||
Option<String>,
|
||||
String,
|
||||
) {
|
||||
let now = &metadata.now;
|
||||
|
||||
// Détecter si c'est une radio musicale avec un morceau en cours
|
||||
if let Some(ref song) = now.song {
|
||||
// Radio musicale avec morceau
|
||||
let title = now.first_line.title_or_default().to_string();
|
||||
let song_artist = if song.interpreters.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(song.artists_display())
|
||||
};
|
||||
|
||||
// Artist affiché = "Station - Artiste du morceau" pour identifier la radio
|
||||
// Éviter la duplication si l'artiste est égal au nom de la station
|
||||
let artist = if let Some(ref art) = song_artist {
|
||||
if art != &station.name {
|
||||
Some(format!("{} - {}", station.name, art))
|
||||
} else {
|
||||
Some(station.name.clone())
|
||||
}
|
||||
} else {
|
||||
Some(station.name.clone())
|
||||
};
|
||||
|
||||
let album = song.release.title.clone();
|
||||
let creator = song_artist; // Creator reste l'artiste du morceau
|
||||
let genre = Some("Music".to_string());
|
||||
let class = "object.item.audioItem.musicTrack".to_string();
|
||||
|
||||
(title, creator, artist, album, genre, class)
|
||||
} else {
|
||||
// Radio parlée ou segment talk sur radio musicale
|
||||
let first = now.first_line.title_or_default();
|
||||
let second = now.second_line.title_or_default();
|
||||
|
||||
// Construire le titre en évitant les duplications
|
||||
let title = if !first.is_empty() && !second.is_empty() {
|
||||
// Si first contient déjà second, utiliser seulement first
|
||||
if first.contains(second) {
|
||||
first.to_string()
|
||||
} else {
|
||||
format!("{} • {}", first, second)
|
||||
}
|
||||
} else if !first.is_empty() {
|
||||
first.to_string()
|
||||
} else {
|
||||
station.name.clone()
|
||||
};
|
||||
|
||||
// Artist/Creator = "{Station} - {Subtitle}"
|
||||
// Éviter la duplication si subtitle == nom de la station
|
||||
let artist = if !second.is_empty() && second != station.name {
|
||||
Some(format!("{} - {}", station.name, second))
|
||||
} else {
|
||||
Some(station.name.clone())
|
||||
};
|
||||
let creator = artist.clone();
|
||||
|
||||
// Album = nom de l'émission principale
|
||||
let album = if !first.is_empty() {
|
||||
Some(first.to_string())
|
||||
} else {
|
||||
Some(station.name.clone())
|
||||
};
|
||||
let genre = Some("Talk Radio".to_string());
|
||||
let class = "object.item.audioItem.audioBroadcast".to_string();
|
||||
|
||||
(title, creator, artist, album, genre, class)
|
||||
}
|
||||
}
|
||||
|
||||
/// Cache la cover et retourne (url_publique, pk)
|
||||
#[cfg(feature = "cache")]
|
||||
async fn cache_cover(
|
||||
metadata: &LiveResponse,
|
||||
cache: &Arc<CoverCache>,
|
||||
server_base_url: &str,
|
||||
) -> (Option<String>, Option<String>) {
|
||||
// Extraire l'UUID de la cover (priorité : visual_background > visuals.card > visuals.player)
|
||||
let uuid = metadata
|
||||
.now
|
||||
.visual_background
|
||||
.as_ref()
|
||||
.and_then(|v| v.extract_uuid())
|
||||
.or_else(|| {
|
||||
metadata.now.visuals.as_ref().and_then(|visuals| {
|
||||
visuals
|
||||
.card
|
||||
.as_ref()
|
||||
.and_then(|c| c.extract_uuid())
|
||||
.or_else(|| visuals.player.as_ref().and_then(|p| p.extract_uuid()))
|
||||
})
|
||||
});
|
||||
|
||||
let uuid = match uuid {
|
||||
Some(u) => u,
|
||||
None => {
|
||||
// Fallback sur le logo par défaut via l'API REST
|
||||
let logo_url = format!(
|
||||
"{}/api/radiofrance/default-logo",
|
||||
server_base_url.trim_end_matches('/')
|
||||
);
|
||||
return (Some(logo_url), None);
|
||||
}
|
||||
};
|
||||
|
||||
// URL haute résolution
|
||||
let cover_url = ImageSize::Large.build_url(&uuid);
|
||||
|
||||
// Tenter de cacher la cover
|
||||
match cache.add_from_url(&cover_url, Some("radiofrance")).await {
|
||||
Ok(pk) => {
|
||||
// Construire l'URL publique
|
||||
let route = cache.route_for(&pk, None);
|
||||
let public_url = format!("{}{}", server_base_url.trim_end_matches('/'), route);
|
||||
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::debug!(
|
||||
"Cached cover - UUID: {}, PK: {}, route: {}, public_url: {}",
|
||||
uuid,
|
||||
pk,
|
||||
route,
|
||||
public_url
|
||||
);
|
||||
|
||||
(Some(public_url), Some(pk))
|
||||
}
|
||||
Err(e) => {
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::warn!("Failed to cache Radio France cover UUID {}: {}", uuid, e);
|
||||
// Fallback sur le logo par défaut en cas d'erreur
|
||||
let logo_url = format!(
|
||||
"{}/api/radiofrance/default-logo",
|
||||
server_base_url.trim_end_matches('/')
|
||||
);
|
||||
(Some(logo_url), None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Construit la ressource stream avec URL du proxy
|
||||
fn build_stream_resource(
|
||||
metadata: &LiveResponse,
|
||||
station_slug: &str,
|
||||
server_base_url: &str,
|
||||
) -> (
|
||||
String,
|
||||
String,
|
||||
Option<String>,
|
||||
Option<String>,
|
||||
Option<String>,
|
||||
) {
|
||||
// Calculer la durée restante (maintenant -> end_time)
|
||||
let duration = if let Some(end) = metadata.now.end_time {
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs();
|
||||
|
||||
if end > now {
|
||||
let duration_secs = end - now;
|
||||
let hours = duration_secs / 3600;
|
||||
let minutes = (duration_secs % 3600) / 60;
|
||||
let seconds = duration_secs % 60;
|
||||
Some(format!("{}:{:02}:{:02}", hours, minutes, seconds))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// URL du proxy PMOMusic
|
||||
let url = format!(
|
||||
"{}/api/radiofrance/{}/stream",
|
||||
server_base_url.trim_end_matches('/'),
|
||||
station_slug
|
||||
);
|
||||
|
||||
// Déterminer le protocol_info et caractéristiques audio
|
||||
let best_stream = metadata.now.media.best_hifi_stream();
|
||||
|
||||
let (protocol_info, sample_frequency, nr_audio_channels) = match best_stream {
|
||||
Some(stream) => {
|
||||
let protocol_info = match stream.format {
|
||||
crate::models::StreamFormat::Aac => "http-get:*:audio/aac:*".to_string(),
|
||||
crate::models::StreamFormat::Hls => {
|
||||
"http-get:*:application/vnd.apple.mpegurl:*".to_string()
|
||||
}
|
||||
crate::models::StreamFormat::Mp3 => "http-get:*:audio/mpeg:*".to_string(),
|
||||
};
|
||||
|
||||
let sample_freq = match stream.format {
|
||||
crate::models::StreamFormat::Aac => Some("48000".to_string()),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let channels = match stream.format {
|
||||
crate::models::StreamFormat::Aac | crate::models::StreamFormat::Mp3 => {
|
||||
Some("2".to_string())
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
|
||||
(protocol_info, sample_freq, channels)
|
||||
}
|
||||
None => {
|
||||
// Fallback
|
||||
("http-get:*:audio/aac:*".to_string(), None, None)
|
||||
}
|
||||
};
|
||||
|
||||
(
|
||||
url,
|
||||
protocol_info,
|
||||
sample_frequency,
|
||||
nr_audio_channels,
|
||||
duration,
|
||||
)
|
||||
}
|
||||
|
||||
/// Construit un Container DIDL de playlist à un item
|
||||
///
|
||||
/// La playlist et l'item ont EXACTEMENT les mêmes métadonnées
|
||||
pub fn to_didl(&self, playlist_id: &str, parent_id: &str) -> Container {
|
||||
// Calculer la duration dynamiquement (temps restant jusqu'à end_time)
|
||||
let duration = if let Some(end) = self.end_time {
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs();
|
||||
|
||||
if end > now {
|
||||
let duration_secs = end - now;
|
||||
let hours = duration_secs / 3600;
|
||||
let minutes = (duration_secs % 3600) / 60;
|
||||
let seconds = duration_secs % 60;
|
||||
let dur = format!("{}:{:02}:{:02}", hours, minutes, seconds);
|
||||
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::debug!(
|
||||
"Duration calculated for {}: {} (end_time: {}, now: {}, remaining: {}s)",
|
||||
self.slug,
|
||||
dur,
|
||||
end,
|
||||
now,
|
||||
duration_secs
|
||||
);
|
||||
|
||||
Some(dur)
|
||||
} else {
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::warn!(
|
||||
"Duration expired for {}: end_time {} < now {}",
|
||||
self.slug,
|
||||
end,
|
||||
now
|
||||
);
|
||||
None
|
||||
}
|
||||
} else {
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::warn!("No end_time for {}, duration will be None", self.slug);
|
||||
None
|
||||
};
|
||||
|
||||
let item = Item {
|
||||
id: format!("{}:stream", playlist_id),
|
||||
parent_id: playlist_id.to_string(),
|
||||
restricted: Some("1".to_string()),
|
||||
title: self.title.clone(),
|
||||
creator: self.creator.clone(),
|
||||
class: self.class.clone(),
|
||||
artist: self.artist.clone(),
|
||||
album: self.album.clone(),
|
||||
genre: self.genre.clone(),
|
||||
album_art: self.album_art.clone(),
|
||||
album_art_pk: self.album_art_pk.clone(),
|
||||
date: None,
|
||||
original_track_number: None,
|
||||
resources: vec![Resource {
|
||||
protocol_info: self.protocol_info.clone(),
|
||||
bits_per_sample: None,
|
||||
sample_frequency: self.sample_frequency.clone(),
|
||||
nr_audio_channels: self.nr_audio_channels.clone(),
|
||||
duration,
|
||||
url: self.stream_url.clone(),
|
||||
}],
|
||||
descriptions: vec![],
|
||||
};
|
||||
|
||||
// Container de playlist avec LES MÊMES métadonnées
|
||||
Container {
|
||||
id: playlist_id.to_string(),
|
||||
parent_id: parent_id.to_string(),
|
||||
restricted: Some("1".to_string()),
|
||||
child_count: Some("1".to_string()),
|
||||
searchable: Some("0".to_string()),
|
||||
title: self.title.clone(),
|
||||
class: "object.container.playlistContainer".to_string(),
|
||||
artist: self.artist.clone(),
|
||||
album_art: self.album_art.clone(),
|
||||
containers: vec![],
|
||||
items: vec![item],
|
||||
}
|
||||
}
|
||||
|
||||
/// Vérifie si le TTL est dépassé
|
||||
pub fn is_expired(&self) -> bool {
|
||||
if let Some(end_time) = self.end_time {
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs();
|
||||
now >= end_time
|
||||
} else {
|
||||
// Pas de end_time = toujours expiré (refresh systématique)
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// MetadataCache
|
||||
// ============================================================================
|
||||
|
||||
/// Type de callback pour les notifications de mise à jour
|
||||
pub type MetadataUpdateCallback = Arc<dyn Fn(&str) + Send + Sync>;
|
||||
|
||||
/// Cache de métadonnées avec TTL et système d'événements
|
||||
///
|
||||
/// Gère:
|
||||
/// - Cache in-memory des métadonnées (HashMap avec TTL)
|
||||
/// - Cache persistant des stations (via pmoconfig)
|
||||
/// - Système d'événements (subscribe/notify)
|
||||
pub struct MetadataCache {
|
||||
/// Cache in-memory slug -> CachedMetadata
|
||||
cache: Arc<RwLock<HashMap<String, CachedMetadata>>>,
|
||||
/// Client HTTP Radio France
|
||||
client: RadioFranceClient,
|
||||
/// Cache de covers (pmocovers)
|
||||
#[cfg(feature = "cache")]
|
||||
cover_cache: Arc<CoverCache>,
|
||||
/// URL de base du serveur
|
||||
server_base_url: String,
|
||||
/// Configuration (pour cache persistant des stations)
|
||||
config: Arc<Config>,
|
||||
/// Abonnés aux événements
|
||||
subscribers: Arc<RwLock<Vec<MetadataUpdateCallback>>>,
|
||||
}
|
||||
|
||||
impl MetadataCache {
|
||||
/// Constructeur avec tous les paramètres obligatoires
|
||||
#[cfg(feature = "cache")]
|
||||
pub fn new(
|
||||
client: RadioFranceClient,
|
||||
cover_cache: Arc<CoverCache>,
|
||||
server_base_url: String,
|
||||
config: Arc<Config>,
|
||||
) -> Self {
|
||||
Self {
|
||||
cache: Arc::new(RwLock::new(HashMap::new())),
|
||||
client,
|
||||
cover_cache,
|
||||
server_base_url,
|
||||
config,
|
||||
subscribers: Arc::new(RwLock::new(Vec::new())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Récupère les métadonnées (rafraîchit si TTL expiré)
|
||||
///
|
||||
/// # Logique
|
||||
///
|
||||
/// 1. Vérifie le cache in-memory
|
||||
/// 2. Si valide, retourne directement
|
||||
/// 3. Sinon, appelle API Radio France
|
||||
/// 4. Met à jour le cache
|
||||
/// 5. Notifie les abonnés
|
||||
/// 6. Retourne les métadonnées
|
||||
///
|
||||
/// # Graceful degradation
|
||||
///
|
||||
/// Si l'API Radio France est down, retourne les données expirées du cache
|
||||
#[cfg(feature = "cache")]
|
||||
pub async fn get(&self, slug: &str) -> Result<CachedMetadata> {
|
||||
// 1. Vérifie le cache
|
||||
{
|
||||
let cache = self.cache.read().await;
|
||||
if let Some(metadata) = cache.get(slug) {
|
||||
if !metadata.is_expired() {
|
||||
return Ok(metadata.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. TTL expiré ou absent: appelle API Radio France
|
||||
let live_response = match self.client.live_metadata(slug).await {
|
||||
Ok(resp) => resp,
|
||||
Err(e) => {
|
||||
// Graceful degradation: retourner les données expirées si API down
|
||||
let cache = self.cache.read().await;
|
||||
if let Some(metadata) = cache.get(slug) {
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::warn!(
|
||||
"API Radio France down for {}, using expired cache: {}",
|
||||
slug,
|
||||
e
|
||||
);
|
||||
return Ok(metadata.clone());
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
|
||||
// 3. Récupérer le nom de la station depuis la liste des stations
|
||||
let station_name = {
|
||||
let stations = self.get_stations().await.unwrap_or_default();
|
||||
stations
|
||||
.iter()
|
||||
.find(|s| s.slug == slug)
|
||||
.map(|s| s.name.clone())
|
||||
.unwrap_or_else(|| slug.to_string())
|
||||
};
|
||||
|
||||
// 4. Parse LiveResponse -> CachedMetadata
|
||||
let metadata = CachedMetadata::from_live_response(
|
||||
&Station {
|
||||
slug: slug.to_string(),
|
||||
name: station_name,
|
||||
},
|
||||
&live_response,
|
||||
&self.cover_cache,
|
||||
&self.server_base_url,
|
||||
)
|
||||
.await?;
|
||||
|
||||
// 4. Met à jour le cache
|
||||
{
|
||||
let mut cache = self.cache.write().await;
|
||||
cache.insert(slug.to_string(), metadata.clone());
|
||||
}
|
||||
|
||||
// 5. Notifie les abonnés (async)
|
||||
self.notify_async(slug).await;
|
||||
|
||||
// 6. Retourne les métadonnées
|
||||
Ok(metadata)
|
||||
}
|
||||
|
||||
/// Récupère la liste des stations (cache persistant via pmoconfig)
|
||||
///
|
||||
/// # Logique
|
||||
///
|
||||
/// 1. Essaie de lire depuis pmoconfig
|
||||
/// 2. Si cache valide (TTL 1 semaine), retourne
|
||||
/// 3. Sinon, découvre via API et met à jour pmoconfig
|
||||
pub async fn get_stations(&self) -> Result<Vec<Station>> {
|
||||
// TODO: Implémenter avec config_ext
|
||||
// Pour l'instant, découvre directement
|
||||
self.client.discover_all_stations().await
|
||||
}
|
||||
|
||||
/// Récupère les métadonnées live brutes de l'API (sans cache)
|
||||
///
|
||||
/// Cette méthode est utilisée par l'API REST pour retourner
|
||||
/// la réponse complète de l'API Radio France
|
||||
pub async fn get_live_metadata(&self, slug: &str) -> Result<LiveResponse> {
|
||||
self.client.live_metadata(slug).await
|
||||
}
|
||||
|
||||
/// Récupère l'URL du stream HiFi pour une station
|
||||
pub async fn get_stream_url(&self, slug: &str) -> Result<String> {
|
||||
self.client.get_hifi_stream_url(slug).await
|
||||
}
|
||||
|
||||
/// S'abonner aux changements de métadonnées
|
||||
///
|
||||
/// Le callback sera appelé avec le slug chaque fois que
|
||||
/// les métadonnées de ce slug sont rafraîchies
|
||||
pub fn subscribe(&self, callback: MetadataUpdateCallback) {
|
||||
// Spawn une tâche pour éviter le blocking dans le runtime
|
||||
let subscribers = self.subscribers.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut subs = subscribers.write().await;
|
||||
subs.push(callback);
|
||||
});
|
||||
}
|
||||
|
||||
/// Notifier tous les abonnés qu'un slug a été mis à jour (version async)
|
||||
async fn notify_async(&self, slug: &str) {
|
||||
// Clone pour éviter de bloquer longtemps
|
||||
let callbacks: Vec<_> = {
|
||||
let subscribers = self.subscribers.read().await;
|
||||
subscribers.clone()
|
||||
};
|
||||
|
||||
for callback in callbacks.iter() {
|
||||
callback(slug);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_cached_metadata_is_expired() {
|
||||
let metadata = CachedMetadata {
|
||||
slug: "test".to_string(),
|
||||
title: "Test".to_string(),
|
||||
creator: None,
|
||||
artist: None,
|
||||
album: None,
|
||||
genre: None,
|
||||
class: "test".to_string(),
|
||||
album_art: None,
|
||||
album_art_pk: None,
|
||||
stream_url: "".to_string(),
|
||||
protocol_info: "".to_string(),
|
||||
sample_frequency: None,
|
||||
nr_audio_channels: None,
|
||||
duration: None,
|
||||
end_time: Some(0), // Dans le passé
|
||||
};
|
||||
|
||||
assert!(metadata.is_expired());
|
||||
|
||||
let metadata_no_end = CachedMetadata {
|
||||
end_time: None,
|
||||
..metadata
|
||||
};
|
||||
|
||||
assert!(metadata_no_end.is_expired());
|
||||
}
|
||||
}
|
||||
@@ -10,97 +10,22 @@ use serde::{Deserialize, Serialize};
|
||||
// ============================================================================
|
||||
|
||||
/// A discovered Radio France station
|
||||
///
|
||||
/// Simplifié: juste slug + name, plus de distinction de type
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct Station {
|
||||
/// Unique slug identifier (e.g., "franceculture", "fip_rock")
|
||||
pub slug: String,
|
||||
/// Human-readable name (e.g., "France Culture", "FIP Rock")
|
||||
pub name: String,
|
||||
/// Type of station
|
||||
pub station_type: StationType,
|
||||
}
|
||||
|
||||
/// Type of Radio France station
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum StationType {
|
||||
/// Main station (France Inter, France Culture, FIP, etc.)
|
||||
Main,
|
||||
/// Webradio variant of a main station
|
||||
Webradio {
|
||||
/// Parent station slug (e.g., "fip" for "fip_rock")
|
||||
parent_station: String,
|
||||
},
|
||||
/// Local France Bleu radio
|
||||
LocalRadio {
|
||||
/// Region name
|
||||
region: String,
|
||||
/// Internal Radio France ID
|
||||
id: u32,
|
||||
},
|
||||
}
|
||||
|
||||
impl Station {
|
||||
/// Create a new main station
|
||||
pub fn main(slug: impl Into<String>, name: impl Into<String>) -> Self {
|
||||
/// Create a new station
|
||||
pub fn new(slug: impl Into<String>, name: impl Into<String>) -> Self {
|
||||
Self {
|
||||
slug: slug.into(),
|
||||
name: name.into(),
|
||||
station_type: StationType::Main,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a new webradio station
|
||||
pub fn webradio(
|
||||
slug: impl Into<String>,
|
||||
name: impl Into<String>,
|
||||
parent: impl Into<String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
slug: slug.into(),
|
||||
name: name.into(),
|
||||
station_type: StationType::Webradio {
|
||||
parent_station: parent.into(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a new local radio station
|
||||
pub fn local_radio(
|
||||
slug: impl Into<String>,
|
||||
name: impl Into<String>,
|
||||
region: impl Into<String>,
|
||||
id: u32,
|
||||
) -> Self {
|
||||
Self {
|
||||
slug: slug.into(),
|
||||
name: name.into(),
|
||||
station_type: StationType::LocalRadio {
|
||||
region: region.into(),
|
||||
id,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if this is a main station
|
||||
pub fn is_main(&self) -> bool {
|
||||
matches!(self.station_type, StationType::Main)
|
||||
}
|
||||
|
||||
/// Check if this is a webradio
|
||||
pub fn is_webradio(&self) -> bool {
|
||||
matches!(self.station_type, StationType::Webradio { .. })
|
||||
}
|
||||
|
||||
/// Check if this is a local radio
|
||||
pub fn is_local_radio(&self) -> bool {
|
||||
matches!(self.station_type, StationType::LocalRadio { .. })
|
||||
}
|
||||
|
||||
/// Get the parent station for webradios, or the station itself for main stations
|
||||
pub fn base_station(&self) -> &str {
|
||||
match &self.station_type {
|
||||
StationType::Webradio { parent_station } => parent_station,
|
||||
_ => &self.slug,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -415,86 +340,15 @@ impl ImageSize {
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Cached Station List
|
||||
// ============================================================================
|
||||
|
||||
/// Cached list of discovered stations with timestamp
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct CachedStationList {
|
||||
/// List of discovered stations
|
||||
pub stations: Vec<Station>,
|
||||
/// Unix timestamp when the list was last updated
|
||||
pub last_updated: u64,
|
||||
/// Version of the discovery algorithm (for invalidation)
|
||||
pub version: u32,
|
||||
}
|
||||
|
||||
impl CachedStationList {
|
||||
/// Current version of the discovery algorithm
|
||||
pub const CURRENT_VERSION: u32 = 1;
|
||||
|
||||
/// Default TTL for station list cache (7 days in seconds)
|
||||
pub const DEFAULT_TTL_SECS: u64 = 7 * 24 * 3600;
|
||||
|
||||
/// Create a new cached station list
|
||||
pub fn new(stations: Vec<Station>) -> Self {
|
||||
Self {
|
||||
stations,
|
||||
last_updated: std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or(0),
|
||||
version: Self::CURRENT_VERSION,
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if the cache is still valid
|
||||
pub fn is_valid(&self, ttl_secs: u64) -> bool {
|
||||
if self.version != Self::CURRENT_VERSION {
|
||||
return false;
|
||||
}
|
||||
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or(0);
|
||||
|
||||
now.saturating_sub(self.last_updated) < ttl_secs
|
||||
}
|
||||
|
||||
/// Check if cache is valid with default TTL
|
||||
pub fn is_valid_default(&self) -> bool {
|
||||
self.is_valid(Self::DEFAULT_TTL_SECS)
|
||||
}
|
||||
|
||||
/// Get the age of the cache in seconds
|
||||
pub fn age_secs(&self) -> u64 {
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or(0);
|
||||
|
||||
now.saturating_sub(self.last_updated)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_station_creation() {
|
||||
let main = Station::main("franceculture", "France Culture");
|
||||
assert!(main.is_main());
|
||||
assert_eq!(main.base_station(), "franceculture");
|
||||
|
||||
let webradio = Station::webradio("fip_rock", "FIP Rock", "fip");
|
||||
assert!(webradio.is_webradio());
|
||||
assert_eq!(webradio.base_station(), "fip");
|
||||
|
||||
let local = Station::local_radio("francebleu_alsace", "ICI Alsace", "Alsace", 12);
|
||||
assert!(local.is_local_radio());
|
||||
let station = Station::new("franceculture", "France Culture");
|
||||
assert_eq!(station.slug, "franceculture");
|
||||
assert_eq!(station.name, "France Culture");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -506,13 +360,4 @@ mod tests {
|
||||
"https://www.radiofrance.fr/pikapi/images/436430f7-5b2b-43f2-9f3c-28f2ad6cae39/200x200"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cached_station_list_validity() {
|
||||
let stations = vec![Station::main("fip", "FIP")];
|
||||
let cached = CachedStationList::new(stations);
|
||||
|
||||
assert!(cached.is_valid(3600)); // Valid for 1 hour
|
||||
assert!(cached.is_valid_default()); // Valid with default TTL
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -6,26 +6,15 @@
|
||||
use anyhow::Result;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::stateful_client::RadioFranceStatefulClient;
|
||||
|
||||
/// État partagé pour les handlers Radio France
|
||||
#[derive(Clone)]
|
||||
pub struct RadioFranceState {
|
||||
pub client: Arc<RadioFranceStatefulClient>,
|
||||
pub source: Option<Arc<crate::source::RadioFranceSource>>,
|
||||
pub source: Arc<crate::source::RadioFranceSource>,
|
||||
}
|
||||
|
||||
impl RadioFranceState {
|
||||
pub fn new(client: RadioFranceStatefulClient) -> Self {
|
||||
Self {
|
||||
client: Arc::new(client),
|
||||
source: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_source(mut self, source: Arc<crate::source::RadioFranceSource>) -> Self {
|
||||
self.source = Some(source);
|
||||
self
|
||||
pub fn new(source: Arc<crate::source::RadioFranceSource>) -> Self {
|
||||
Self { source }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,7 +28,6 @@
|
||||
|
||||
use crate::api_rest::create_router;
|
||||
use crate::pmoserver_ext::{RadioFranceExt, RadioFranceState};
|
||||
use crate::stateful_client::RadioFranceStatefulClient;
|
||||
use anyhow::Result;
|
||||
use pmoserver::Server;
|
||||
use std::sync::Arc;
|
||||
@@ -38,14 +37,14 @@ impl RadioFranceExt for Server {
|
||||
async fn init_radiofrance(&mut self) -> Result<Arc<RadioFranceState>> {
|
||||
info!("Initializing Radio France API...");
|
||||
|
||||
// Créer le client stateful
|
||||
// Créer une source dédiée pour l'API (sans enregistrement UPnP)
|
||||
let config = pmoconfig::get_config();
|
||||
let client = RadioFranceStatefulClient::new(config)
|
||||
let source = crate::source::RadioFranceSource::new(config)
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("Failed to create Radio France client: {}", e))?;
|
||||
.map_err(|e| anyhow::anyhow!("Failed to create Radio France source: {}", e))?;
|
||||
|
||||
// Créer l'état partagé (RadioFranceState est Clone et contient déjà un Arc<client>)
|
||||
let state = RadioFranceState::new(client);
|
||||
// Créer l'état partagé
|
||||
let state = RadioFranceState::new(Arc::new(source));
|
||||
|
||||
// Créer et enregistrer le router
|
||||
let router = create_router(state.clone());
|
||||
@@ -63,14 +62,8 @@ impl RadioFranceExt for Server {
|
||||
) -> Result<Arc<RadioFranceState>> {
|
||||
info!("Initializing Radio France API with existing source...");
|
||||
|
||||
// Créer le client stateful
|
||||
let config = pmoconfig::get_config();
|
||||
let client = RadioFranceStatefulClient::new(config)
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("Failed to create Radio France client: {}", e))?;
|
||||
|
||||
// Créer l'état partagé avec la source
|
||||
let state = RadioFranceState::new(client).with_source(source);
|
||||
// Créer l'état partagé (simplement une référence à la source)
|
||||
let state = RadioFranceState::new(source);
|
||||
|
||||
// Créer et enregistrer le router
|
||||
let router = create_router(state.clone());
|
||||
|
||||
@@ -3,21 +3,16 @@
|
||||
//! This module implements the `MusicSource` trait from `pmosource` for Radio France,
|
||||
//! providing UPnP/DLNA integration with dynamic container generation.
|
||||
|
||||
use crate::client::RadioFranceClient;
|
||||
use crate::error::Result;
|
||||
use crate::models::Station;
|
||||
use crate::playlist::{StationGroup, StationGroups, StationPlaylist};
|
||||
use crate::stateful_client::RadioFranceStatefulClient;
|
||||
use crate::metadata_cache::MetadataCache;
|
||||
use crate::playlist::StationGroups;
|
||||
use pmoconfig::Config;
|
||||
use pmodidl::{Container, Item};
|
||||
use pmosource::{async_trait, BrowseResult, MusicSource, MusicSourceError, SourceCapabilities};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::time::SystemTime;
|
||||
use tokio::sync::RwLock;
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
#[cfg(feature = "cache")]
|
||||
use pmocovers::Cache as CoverCache;
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
use pmoupnp;
|
||||
@@ -28,25 +23,15 @@ pub const RADIOFRANCE_DEFAULT_IMAGE: &[u8] = include_bytes!("../assets/radiofran
|
||||
/// Radio France music source
|
||||
///
|
||||
/// Provides access to ~70 Radio France stations via UPnP/DLNA with:
|
||||
/// - Dynamic container generation based on station structure
|
||||
/// - Automatic metadata refresh for active streams
|
||||
/// - Hierarchical organization (standalone, groups, local radios)
|
||||
/// - Cache de métadonnées avec TTL et système d'événements
|
||||
/// - Construction dynamique de containers DIDL
|
||||
/// - Notifications GENA pour les playlists
|
||||
pub struct RadioFranceSource {
|
||||
/// Stateful client with automatic caching
|
||||
client: RadioFranceStatefulClient,
|
||||
/// Cache de métadonnées centralisé
|
||||
metadata_cache: Arc<MetadataCache>,
|
||||
|
||||
/// Cache of playlists by station slug (volatile metadata)
|
||||
playlists: Arc<RwLock<HashMap<String, StationPlaylist>>>,
|
||||
|
||||
/// Background tasks for metadata refresh
|
||||
refresh_handles: Arc<RwLock<HashMap<String, JoinHandle<()>>>>,
|
||||
|
||||
/// Cover cache (optional)
|
||||
#[cfg(feature = "cache")]
|
||||
cover_cache: Option<Arc<CoverCache>>,
|
||||
|
||||
/// Server base URL for cover URLs
|
||||
server_base_url: Option<String>,
|
||||
/// Server base URL
|
||||
server_base_url: String,
|
||||
|
||||
/// Update counter for change tracking
|
||||
update_id: Arc<RwLock<u32>>,
|
||||
@@ -63,7 +48,7 @@ impl RadioFranceSource {
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `config` - Configuration for the client
|
||||
/// * `config` - Configuration for cache and discovery
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
@@ -78,20 +63,34 @@ impl RadioFranceSource {
|
||||
/// Ok(())
|
||||
/// }
|
||||
/// ```
|
||||
#[cfg(feature = "cache")]
|
||||
pub async fn new(config: Arc<Config>) -> Result<Self> {
|
||||
let client = RadioFranceStatefulClient::new(config).await?;
|
||||
let client = RadioFranceClient::new().await?;
|
||||
let cover_cache = pmoupnp::cache_registry::get_cover_cache()
|
||||
.ok_or_else(|| crate::error::Error::Other("Cover cache not initialized".to_string()))?;
|
||||
|
||||
Ok(Self {
|
||||
// TODO: Récupérer server_base_url depuis config
|
||||
let server_base_url = "http://localhost:8080".to_string();
|
||||
|
||||
let metadata_cache = Arc::new(MetadataCache::new(
|
||||
client,
|
||||
playlists: Arc::new(RwLock::new(HashMap::new())),
|
||||
refresh_handles: Arc::new(RwLock::new(HashMap::new())),
|
||||
#[cfg(feature = "cache")]
|
||||
cover_cache: None,
|
||||
server_base_url: None,
|
||||
update_id: Arc::new(RwLock::new(0)),
|
||||
last_change: Arc::new(RwLock::new(None)),
|
||||
cover_cache,
|
||||
server_base_url.clone(),
|
||||
config,
|
||||
));
|
||||
|
||||
let update_id = Arc::new(RwLock::new(0));
|
||||
let last_change = Arc::new(RwLock::new(None));
|
||||
|
||||
let source = Self {
|
||||
metadata_cache,
|
||||
server_base_url,
|
||||
update_id,
|
||||
last_change,
|
||||
container_notifier: None,
|
||||
})
|
||||
};
|
||||
|
||||
Ok(source)
|
||||
}
|
||||
|
||||
/// Set the container notifier for UPnP GENA events
|
||||
@@ -99,454 +98,86 @@ impl RadioFranceSource {
|
||||
mut self,
|
||||
notifier: Arc<dyn Fn(&[String]) + Send + Sync + 'static>,
|
||||
) -> Self {
|
||||
// S'abonner aux événements du cache de métadonnées
|
||||
let container_notifier = Arc::new(notifier.clone());
|
||||
let update_id = self.update_id.clone();
|
||||
let last_change = self.last_change.clone();
|
||||
|
||||
self.metadata_cache.subscribe(Arc::new(move |slug: &str| {
|
||||
let slug = slug.to_string();
|
||||
let update_id = update_id.clone();
|
||||
let last_change = last_change.clone();
|
||||
let container_notifier = container_notifier.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
*update_id.write().await += 1;
|
||||
*last_change.write().await = Some(SystemTime::now());
|
||||
|
||||
// Notifier le container de playlist (pas l'item)
|
||||
container_notifier(&[format!("radiofrance:{}", slug)]);
|
||||
});
|
||||
}));
|
||||
|
||||
self.container_notifier = Some(notifier);
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the cover cache
|
||||
#[cfg(feature = "cache")]
|
||||
pub fn with_cover_cache(mut self, cache: Arc<CoverCache>) -> Self {
|
||||
self.cover_cache = Some(cache);
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the server base URL for cover serving
|
||||
pub fn with_server_base_url(mut self, url: impl Into<String>) -> Self {
|
||||
self.server_base_url = Some(url.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Create a new Radio France source from the cache registry
|
||||
///
|
||||
/// This is the recommended way to create a source when using the UPnP server.
|
||||
/// The cover cache is automatically retrieved from the global registry.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `client` - Radio France stateful client
|
||||
/// * `base_url` - Base URL for streaming server (e.g., "http://192.168.0.138:8080")
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the cover cache is not initialized in the registry
|
||||
/// * `config` - Configuration
|
||||
/// * `base_url` - Base URL for streaming server
|
||||
#[cfg(feature = "server")]
|
||||
pub fn from_registry(
|
||||
client: RadioFranceStatefulClient,
|
||||
base_url: impl Into<String>,
|
||||
) -> Result<Self> {
|
||||
#[cfg(feature = "cache")]
|
||||
let cover_cache = pmoupnp::cache_registry::get_cover_cache();
|
||||
pub async fn from_registry(config: Arc<Config>, base_url: impl Into<String>) -> Result<Self> {
|
||||
let client = RadioFranceClient::new().await?;
|
||||
let cover_cache = pmoupnp::cache_registry::get_cover_cache()
|
||||
.ok_or_else(|| crate::error::Error::Other("Cover cache not initialized".to_string()))?;
|
||||
let server_base_url = base_url.into();
|
||||
|
||||
let metadata_cache = Arc::new(MetadataCache::new(
|
||||
client,
|
||||
cover_cache,
|
||||
server_base_url.clone(),
|
||||
config,
|
||||
));
|
||||
|
||||
let update_id = Arc::new(RwLock::new(0));
|
||||
let last_change = Arc::new(RwLock::new(None));
|
||||
|
||||
Ok(Self {
|
||||
client,
|
||||
playlists: Arc::new(RwLock::new(HashMap::new())),
|
||||
refresh_handles: Arc::new(RwLock::new(HashMap::new())),
|
||||
#[cfg(feature = "cache")]
|
||||
cover_cache,
|
||||
server_base_url: Some(base_url.into()),
|
||||
update_id: Arc::new(RwLock::new(0)),
|
||||
last_change: Arc::new(RwLock::new(None)),
|
||||
metadata_cache,
|
||||
server_base_url,
|
||||
update_id,
|
||||
last_change,
|
||||
container_notifier: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Start metadata refresh task for a station
|
||||
pub async fn start_metadata_refresh(&self, station_slug: &str) -> Result<()> {
|
||||
let mut handles = self.refresh_handles.write().await;
|
||||
|
||||
// If already running, do nothing
|
||||
if handles.contains_key(station_slug) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let client = self.client.clone();
|
||||
let playlists = self.playlists.clone();
|
||||
let slug = station_slug.to_string();
|
||||
let update_id = self.update_id.clone();
|
||||
let last_change = self.last_change.clone();
|
||||
let container_notifier = self.container_notifier.clone();
|
||||
|
||||
#[cfg(feature = "cache")]
|
||||
let cover_cache = self.cover_cache.clone();
|
||||
|
||||
let server_base_url = self.server_base_url.clone();
|
||||
|
||||
let handle = tokio::spawn(async move {
|
||||
loop {
|
||||
match client.get_live_metadata(&slug).await {
|
||||
Ok(metadata) => {
|
||||
let delay = std::time::Duration::from_millis(metadata.delay_to_refresh);
|
||||
|
||||
#[cfg(feature = "logging")]
|
||||
{
|
||||
let artist = metadata
|
||||
.now
|
||||
.song
|
||||
.as_ref()
|
||||
.and_then(|s| {
|
||||
if s.interpreters.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(s.artists_display())
|
||||
}
|
||||
})
|
||||
.unwrap_or_else(|| "".to_string());
|
||||
tracing::debug!(
|
||||
"Refreshed metadata for {}: title='{}' artist='{}' delay={}ms",
|
||||
slug,
|
||||
metadata.now.first_line.title.as_deref().unwrap_or(""),
|
||||
artist,
|
||||
metadata.delay_to_refresh
|
||||
);
|
||||
}
|
||||
|
||||
// Update the playlist metadata
|
||||
#[cfg(feature = "cache")]
|
||||
{
|
||||
let mut pls = playlists.write().await;
|
||||
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::debug!(
|
||||
"Looking for playlist '{}' in cache, found: {}",
|
||||
slug,
|
||||
pls.contains_key(&slug)
|
||||
);
|
||||
|
||||
if let Some(playlist) = pls.get_mut(&slug) {
|
||||
let old_title = playlist.stream_item.title.clone();
|
||||
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::debug!(
|
||||
"Updating playlist for {}: current title = '{}'",
|
||||
slug,
|
||||
old_title
|
||||
);
|
||||
|
||||
let _: Result<()> = playlist
|
||||
.update_metadata(
|
||||
&metadata,
|
||||
cover_cache.as_ref(),
|
||||
server_base_url.as_deref(),
|
||||
)
|
||||
.await;
|
||||
|
||||
let new_title = playlist.stream_item.title.clone();
|
||||
|
||||
#[cfg(feature = "logging")]
|
||||
if old_title != new_title {
|
||||
tracing::info!(
|
||||
"Metadata updated for {}: {} -> {}",
|
||||
slug,
|
||||
old_title,
|
||||
new_title
|
||||
);
|
||||
}
|
||||
|
||||
// Update change tracking
|
||||
*update_id.write().await = update_id.read().await.wrapping_add(1);
|
||||
*last_change.write().await = Some(SystemTime::now());
|
||||
|
||||
// Notify UPnP ContentDirectory of the change
|
||||
if let Some(ref notifier) = container_notifier {
|
||||
// Notify the station's stream item container
|
||||
let container_id = format!("radiofrance:{}", slug);
|
||||
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::info!(
|
||||
"Notifying UPnP container update: {}",
|
||||
container_id
|
||||
);
|
||||
|
||||
notifier(&[container_id]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "cache"))]
|
||||
{
|
||||
let mut pls = playlists.write().await;
|
||||
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::debug!(
|
||||
"Looking for playlist '{}' in cache, found: {}",
|
||||
slug,
|
||||
pls.contains_key(&slug)
|
||||
);
|
||||
|
||||
if let Some(playlist) = pls.get_mut(&slug) {
|
||||
let old_title = playlist.stream_item.title.clone();
|
||||
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::debug!(
|
||||
"Updating playlist for {}: current title = '{}'",
|
||||
slug,
|
||||
old_title
|
||||
);
|
||||
|
||||
let _: Result<()> = playlist.update_metadata_no_cache(
|
||||
&metadata,
|
||||
server_base_url.as_deref(),
|
||||
);
|
||||
|
||||
let new_title = playlist.stream_item.title.clone();
|
||||
|
||||
#[cfg(feature = "logging")]
|
||||
if old_title != new_title {
|
||||
tracing::info!(
|
||||
"Metadata updated for {}: {} -> {}",
|
||||
slug,
|
||||
old_title,
|
||||
new_title
|
||||
);
|
||||
}
|
||||
|
||||
// Update change tracking
|
||||
*update_id.write().await = update_id.read().await.wrapping_add(1);
|
||||
*last_change.write().await = Some(SystemTime::now());
|
||||
|
||||
// Notify UPnP ContentDirectory of the change
|
||||
if let Some(ref notifier) = container_notifier {
|
||||
// Notify the station's stream item container
|
||||
let container_id = format!("radiofrance:{}", slug);
|
||||
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::info!(
|
||||
"Notifying UPnP container update: {}",
|
||||
container_id
|
||||
);
|
||||
|
||||
notifier(&[container_id]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tokio::time::sleep(delay).await;
|
||||
}
|
||||
Err(e) => {
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::warn!("Failed to refresh metadata for {}: {}", slug, e);
|
||||
|
||||
tokio::time::sleep(std::time::Duration::from_secs(60)).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
handles.insert(station_slug.to_string(), handle);
|
||||
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::debug!("Started metadata refresh for station: {}", station_slug);
|
||||
|
||||
Ok(())
|
||||
impl RadioFranceSource {
|
||||
/// Get the list of all Radio France stations
|
||||
pub async fn get_stations(&self) -> Result<Vec<crate::models::Station>> {
|
||||
self.metadata_cache.get_stations().await
|
||||
}
|
||||
|
||||
/// Stop metadata refresh task for a station
|
||||
pub async fn stop_metadata_refresh(&self, station_slug: &str) {
|
||||
let mut handles = self.refresh_handles.write().await;
|
||||
if let Some(handle) = handles.remove(station_slug) {
|
||||
handle.abort();
|
||||
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::debug!("Stopped metadata refresh for station: {}", station_slug);
|
||||
}
|
||||
/// Get live metadata for a station
|
||||
pub async fn get_live_metadata(&self, slug: &str) -> Result<crate::models::LiveResponse> {
|
||||
self.metadata_cache.get_live_metadata(slug).await
|
||||
}
|
||||
|
||||
/// Build the UPnP container tree dynamically from station data
|
||||
async fn build_container_tree(&self) -> Result<Container> {
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::debug!("Building container tree");
|
||||
|
||||
let stations = self.client.get_stations().await?;
|
||||
let groups = StationGroups::from_stations(stations);
|
||||
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::debug!(
|
||||
"Groups: {} standalone, {} with webradios, {} local radios",
|
||||
groups.standalone.len(),
|
||||
groups.with_webradios.len(),
|
||||
groups.local_radios.len()
|
||||
);
|
||||
|
||||
let mut containers = Vec::new();
|
||||
let mut items = Vec::new();
|
||||
|
||||
// 1. Standalone stations → direct items (avec appels API)
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::debug!(
|
||||
"Building {} standalone station items",
|
||||
groups.standalone.len()
|
||||
);
|
||||
|
||||
for station in &groups.standalone {
|
||||
items.push(self.build_station_item(station).await?);
|
||||
}
|
||||
|
||||
// 2. Stations with webradios → containers
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::debug!("Building {} group containers", groups.with_webradios.len());
|
||||
|
||||
for group in &groups.with_webradios {
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::debug!("Building container for group: {}", group.main.name);
|
||||
containers.push(self.build_station_container(group).await?);
|
||||
}
|
||||
|
||||
// 3. Local radios → single "Radios ICI" container
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::debug!(
|
||||
"Building ICI container with {} local radios",
|
||||
groups.local_radios.len()
|
||||
);
|
||||
|
||||
if !groups.local_radios.is_empty() {
|
||||
containers.push(self.build_ici_container(&groups.local_radios).await?);
|
||||
}
|
||||
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::debug!(
|
||||
"Container tree built: {} containers, {} items",
|
||||
containers.len(),
|
||||
items.len()
|
||||
);
|
||||
|
||||
Ok(Container {
|
||||
id: "radiofrance".to_string(),
|
||||
parent_id: "0".to_string(),
|
||||
restricted: Some("1".to_string()),
|
||||
child_count: Some((containers.len() + items.len()).to_string()),
|
||||
searchable: Some("0".to_string()),
|
||||
title: "Radio France".to_string(),
|
||||
class: "object.container".to_string(),
|
||||
artist: None,
|
||||
album_art: None,
|
||||
containers,
|
||||
items,
|
||||
})
|
||||
}
|
||||
|
||||
/// Build a container for a station group (main + webradios)
|
||||
/// Returns an empty container - items will be built when browsing into it
|
||||
async fn build_station_container(&self, group: &StationGroup) -> Result<Container> {
|
||||
let child_count = 1 + group.webradios.len(); // main + webradios
|
||||
|
||||
// Utiliser le logo par défaut si server_base_url est configuré
|
||||
let album_art = self.server_base_url.as_ref().map(|base| {
|
||||
format!(
|
||||
"{}/api/radiofrance/default-logo",
|
||||
base.trim_end_matches('/')
|
||||
)
|
||||
});
|
||||
|
||||
Ok(Container {
|
||||
id: format!("radiofrance:group:{}", group.main.slug),
|
||||
parent_id: "radiofrance".to_string(),
|
||||
restricted: Some("1".to_string()),
|
||||
child_count: Some(child_count.to_string()),
|
||||
searchable: Some("0".to_string()),
|
||||
title: group.main.name.clone(),
|
||||
class: "object.container".to_string(),
|
||||
artist: None,
|
||||
album_art,
|
||||
containers: vec![],
|
||||
items: vec![],
|
||||
})
|
||||
}
|
||||
|
||||
/// Build the "Radios ICI" container
|
||||
/// Returns an empty container - items will be built when browsing into it
|
||||
async fn build_ici_container(&self, local_radios: &[Station]) -> Result<Container> {
|
||||
// Utiliser le logo par défaut si server_base_url est configuré
|
||||
let album_art = self.server_base_url.as_ref().map(|base| {
|
||||
format!(
|
||||
"{}/api/radiofrance/default-logo",
|
||||
base.trim_end_matches('/')
|
||||
)
|
||||
});
|
||||
|
||||
Ok(Container {
|
||||
id: "radiofrance:ici".to_string(),
|
||||
parent_id: "radiofrance".to_string(),
|
||||
restricted: Some("1".to_string()),
|
||||
child_count: Some(local_radios.len().to_string()),
|
||||
searchable: Some("0".to_string()),
|
||||
title: "Radios ICI".to_string(),
|
||||
class: "object.container".to_string(),
|
||||
artist: None,
|
||||
album_art,
|
||||
containers: vec![],
|
||||
items: vec![],
|
||||
})
|
||||
}
|
||||
|
||||
/// Build a UPnP item for a station
|
||||
///
|
||||
/// Fetches live metadata to create a complete item with stream URL.
|
||||
async fn build_station_item(&self, station: &Station) -> Result<Item> {
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::debug!(
|
||||
"Building station item for: {} ({})",
|
||||
station.name,
|
||||
station.slug
|
||||
);
|
||||
|
||||
let playlists = self.playlists.read().await;
|
||||
|
||||
// If we already have this station in cache, use it
|
||||
if let Some(existing) = playlists.get(&station.slug) {
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::debug!("Using cached item for: {}", station.slug);
|
||||
return Ok(existing.stream_item.clone());
|
||||
}
|
||||
|
||||
// Release read lock before fetching metadata
|
||||
drop(playlists);
|
||||
|
||||
// Fetch metadata from API
|
||||
let metadata = self.client.get_live_metadata(&station.slug).await?;
|
||||
|
||||
// Create playlist with metadata
|
||||
#[cfg(feature = "cache")]
|
||||
let playlist = StationPlaylist::from_live_metadata(
|
||||
station.clone(),
|
||||
&metadata,
|
||||
self.cover_cache.as_ref(),
|
||||
self.server_base_url.as_deref(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
#[cfg(not(feature = "cache"))]
|
||||
let playlist = StationPlaylist::from_live_metadata_no_cache(
|
||||
station.clone(),
|
||||
&metadata,
|
||||
self.server_base_url.as_deref(),
|
||||
)?;
|
||||
|
||||
// Cache it
|
||||
let mut playlists_write = self.playlists.write().await;
|
||||
playlists_write.insert(station.slug.clone(), playlist.clone());
|
||||
drop(playlists_write);
|
||||
|
||||
// Note: We don't start metadata refresh here to avoid blocking during browse.
|
||||
// Refresh will be started in resolve_uri() when the stream is actually played.
|
||||
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::debug!(
|
||||
"Built item for {}: {} resources, album_art: {:?}",
|
||||
station.slug,
|
||||
playlist.stream_item.resources.len(),
|
||||
playlist.stream_item.album_art.is_some()
|
||||
);
|
||||
|
||||
Ok(playlist.stream_item)
|
||||
/// Get the HiFi stream URL for a station
|
||||
pub async fn get_stream_url(&self, slug: &str) -> Result<String> {
|
||||
self.metadata_cache.get_stream_url(slug).await
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for RadioFranceSource {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("RadioFranceSource")
|
||||
.field("client", &self.client)
|
||||
.field("playlists_count", &"<locked>")
|
||||
.field("refresh_handles_count", &"<locked>")
|
||||
.field("server_base_url", &self.server_base_url)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
@@ -599,81 +230,84 @@ impl MusicSource for RadioFranceSource {
|
||||
async fn browse(&self, object_id: &str) -> pmosource::Result<BrowseResult> {
|
||||
match object_id {
|
||||
"radiofrance" => {
|
||||
let container = self
|
||||
.build_container_tree()
|
||||
// Niveau 0: retourne le Container avec les groupes
|
||||
let stations = self
|
||||
.metadata_cache
|
||||
.get_stations()
|
||||
.await
|
||||
.map_err(|e| MusicSourceError::BrowseError(e.to_string()))?;
|
||||
|
||||
Ok(BrowseResult::Mixed {
|
||||
containers: container.containers,
|
||||
items: container.items,
|
||||
})
|
||||
let groups = StationGroups::from_stations(stations);
|
||||
let container = groups
|
||||
.to_didl(&self.metadata_cache, &self.server_base_url)
|
||||
.await
|
||||
.map_err(|e| MusicSourceError::BrowseError(e.to_string()))?;
|
||||
|
||||
Ok(BrowseResult::Containers(container.containers))
|
||||
}
|
||||
id if id.starts_with("radiofrance:group:") => {
|
||||
id if id.starts_with("radiofrance:group:") || id == "radiofrance:ici" => {
|
||||
// Niveau 1: browse d'un groupe
|
||||
let slug = id
|
||||
.strip_prefix("radiofrance:group:")
|
||||
.or_else(|| {
|
||||
if id == "radiofrance:ici" {
|
||||
Some("ici")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.ok_or_else(|| MusicSourceError::ObjectNotFound(id.to_string()))?;
|
||||
|
||||
let stations = self
|
||||
.client
|
||||
.metadata_cache
|
||||
.get_stations()
|
||||
.await
|
||||
.map_err(|e| MusicSourceError::BrowseError(e.to_string()))?;
|
||||
let groups = StationGroups::from_stations(stations);
|
||||
|
||||
let groups = StationGroups::from_stations(stations);
|
||||
let group = groups
|
||||
.with_webradios
|
||||
.groups
|
||||
.iter()
|
||||
.find(|g| g.main.slug == slug)
|
||||
.find(|g| g.stations[0].slug == slug)
|
||||
.ok_or_else(|| MusicSourceError::ObjectNotFound(id.to_string()))?;
|
||||
|
||||
// Build items for this group only (main + webradios)
|
||||
let group_id = format!("radiofrance:group:{}", slug);
|
||||
|
||||
let mut main_item = self
|
||||
.build_station_item(&group.main)
|
||||
let container = group
|
||||
.to_didl(&self.metadata_cache, &self.server_base_url)
|
||||
.await
|
||||
.map_err(|e| MusicSourceError::BrowseError(e.to_string()))?;
|
||||
|
||||
// Fix parent_id to point to the group container
|
||||
main_item.parent_id = group_id.clone();
|
||||
let mut items = vec![main_item];
|
||||
|
||||
for webradio in &group.webradios {
|
||||
let mut item = self
|
||||
.build_station_item(webradio)
|
||||
.await
|
||||
.map_err(|e| MusicSourceError::BrowseError(e.to_string()))?;
|
||||
|
||||
// Fix parent_id to point to the group container
|
||||
item.parent_id = group_id.clone();
|
||||
items.push(item);
|
||||
// Si c'est une playlist (1 station), retourner le container lui-même
|
||||
// Sinon retourner ses sous-containers
|
||||
if container.class == "object.container.playlistContainer" {
|
||||
Ok(BrowseResult::Containers(vec![container]))
|
||||
} else {
|
||||
Ok(BrowseResult::Containers(container.containers))
|
||||
}
|
||||
|
||||
Ok(BrowseResult::Items(items))
|
||||
}
|
||||
"radiofrance:ici" => {
|
||||
id if id.starts_with("radiofrance:") && !id.contains(":stream") => {
|
||||
// Niveau 2: browse d'une station (playlist)
|
||||
let slug = id
|
||||
.strip_prefix("radiofrance:")
|
||||
.ok_or_else(|| MusicSourceError::ObjectNotFound(id.to_string()))?;
|
||||
|
||||
let stations = self
|
||||
.client
|
||||
.metadata_cache
|
||||
.get_stations()
|
||||
.await
|
||||
.map_err(|e| MusicSourceError::BrowseError(e.to_string()))?;
|
||||
let groups = StationGroups::from_stations(stations);
|
||||
|
||||
// Build items for local radios only
|
||||
let mut items = Vec::new();
|
||||
for station in &groups.local_radios {
|
||||
let mut item = self
|
||||
.build_station_item(station)
|
||||
.await
|
||||
.map_err(|e| MusicSourceError::BrowseError(e.to_string()))?;
|
||||
let station = stations
|
||||
.iter()
|
||||
.find(|s| s.slug == slug)
|
||||
.ok_or_else(|| MusicSourceError::ObjectNotFound(id.to_string()))?;
|
||||
|
||||
// Fix parent_id to point to the ICI container
|
||||
item.parent_id = "radiofrance:ici".to_string();
|
||||
items.push(item);
|
||||
}
|
||||
let container = station
|
||||
.to_didl(&self.metadata_cache, &self.server_base_url)
|
||||
.await
|
||||
.map_err(|e| MusicSourceError::BrowseError(e.to_string()))?;
|
||||
|
||||
Ok(BrowseResult::Items(items))
|
||||
// Retourner les items de la playlist
|
||||
Ok(BrowseResult::Items(container.items))
|
||||
}
|
||||
_ => Err(MusicSourceError::ObjectNotFound(object_id.to_string())),
|
||||
}
|
||||
@@ -686,82 +320,49 @@ impl MusicSource for RadioFranceSource {
|
||||
.and_then(|s| s.strip_suffix(":stream"))
|
||||
.ok_or_else(|| MusicSourceError::ObjectNotFound(object_id.to_string()))?;
|
||||
|
||||
let playlists = self.playlists.read().await;
|
||||
playlists
|
||||
.get(slug)
|
||||
.map(|p| p.stream_item.clone())
|
||||
let stations = self
|
||||
.metadata_cache
|
||||
.get_stations()
|
||||
.await
|
||||
.map_err(|e| MusicSourceError::BrowseError(e.to_string()))?;
|
||||
|
||||
let station = stations
|
||||
.iter()
|
||||
.find(|s| s.slug == slug)
|
||||
.ok_or_else(|| MusicSourceError::ObjectNotFound(object_id.to_string()))?;
|
||||
|
||||
let container = station
|
||||
.to_didl(&self.metadata_cache, &self.server_base_url)
|
||||
.await
|
||||
.map_err(|e| MusicSourceError::BrowseError(e.to_string()))?;
|
||||
|
||||
container
|
||||
.items
|
||||
.into_iter()
|
||||
.next()
|
||||
.ok_or_else(|| MusicSourceError::ObjectNotFound(object_id.to_string()))
|
||||
}
|
||||
|
||||
async fn resolve_uri(&self, object_id: &str) -> pmosource::Result<String> {
|
||||
// Extract station slug from object_id (format: radiofrance:{slug}:stream)
|
||||
let slug = object_id
|
||||
let _slug = object_id
|
||||
.strip_prefix("radiofrance:")
|
||||
.and_then(|s| s.strip_suffix(":stream"))
|
||||
.ok_or_else(|| MusicSourceError::ObjectNotFound(object_id.to_string()))?;
|
||||
|
||||
// Ensure we have metadata for this station
|
||||
let playlists = self.playlists.read().await;
|
||||
let needs_metadata = !playlists.contains_key(slug);
|
||||
drop(playlists);
|
||||
|
||||
if needs_metadata {
|
||||
// Fetch metadata and create playlist
|
||||
let stations = self
|
||||
.client
|
||||
.get_stations()
|
||||
.await
|
||||
.map_err(|e| MusicSourceError::BrowseError(e.to_string()))?;
|
||||
|
||||
let station = stations
|
||||
.iter()
|
||||
.find(|s| s.slug == slug)
|
||||
.ok_or_else(|| MusicSourceError::ObjectNotFound(slug.to_string()))?;
|
||||
|
||||
let metadata = self
|
||||
.client
|
||||
.get_live_metadata(slug)
|
||||
.await
|
||||
.map_err(|e| MusicSourceError::BrowseError(e.to_string()))?;
|
||||
|
||||
#[cfg(feature = "cache")]
|
||||
let playlist = StationPlaylist::from_live_metadata(
|
||||
station.clone(),
|
||||
&metadata,
|
||||
self.cover_cache.as_ref(),
|
||||
self.server_base_url.as_deref(),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| MusicSourceError::BrowseError(e.to_string()))?;
|
||||
|
||||
#[cfg(not(feature = "cache"))]
|
||||
let playlist = StationPlaylist::from_live_metadata_no_cache(
|
||||
station.clone(),
|
||||
&metadata,
|
||||
self.server_base_url.as_deref(),
|
||||
)
|
||||
.map_err(|e| MusicSourceError::BrowseError(e.to_string()))?;
|
||||
|
||||
let mut playlists_write = self.playlists.write().await;
|
||||
playlists_write.insert(slug.to_string(), playlist);
|
||||
|
||||
// Start metadata refresh
|
||||
drop(playlists_write);
|
||||
let _ = self.start_metadata_refresh(slug).await;
|
||||
}
|
||||
|
||||
// Get the item to extract the stream URL
|
||||
let item = self.get_item(object_id).await?;
|
||||
item.resources
|
||||
.first()
|
||||
.map(|r| r.url.clone())
|
||||
.ok_or_else(|| MusicSourceError::UriResolutionError("No resource found".to_string()))
|
||||
.ok_or_else(|| MusicSourceError::ObjectNotFound(object_id.to_string()))
|
||||
}
|
||||
|
||||
fn supports_fifo(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
async fn append_track(&self, _track: Item) -> pmosource::Result<()> {
|
||||
async fn append_track(&self, _item: Item) -> pmosource::Result<()> {
|
||||
Err(MusicSourceError::FifoNotSupported)
|
||||
}
|
||||
|
||||
@@ -777,34 +378,7 @@ impl MusicSource for RadioFranceSource {
|
||||
*self.last_change.read().await
|
||||
}
|
||||
|
||||
async fn get_items(&self, offset: usize, count: usize) -> pmosource::Result<Vec<Item>> {
|
||||
// Not applicable for radio stations
|
||||
let _ = (offset, count);
|
||||
async fn get_items(&self, _offset: usize, _count: usize) -> pmosource::Result<Vec<Item>> {
|
||||
Ok(vec![])
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for RadioFranceSource {
|
||||
fn drop(&mut self) {
|
||||
// Abort all refresh tasks on drop
|
||||
if let Ok(handles) = self.refresh_handles.try_write() {
|
||||
for (_, handle) in handles.iter() {
|
||||
handle.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// Note: These tests require a valid pmoconfig setup
|
||||
// They are primarily structural tests
|
||||
|
||||
#[test]
|
||||
fn test_source_metadata() {
|
||||
// Test that we can create a source with proper metadata
|
||||
// Actual async tests would go in integration tests
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,484 +0,0 @@
|
||||
//! Stateful client for Radio France with automatic caching
|
||||
//!
|
||||
//! This module provides a higher-level client that automatically manages
|
||||
//! station discovery caching through pmoconfig, providing a simpler API
|
||||
//! for integration into PMOMusic.
|
||||
//!
|
||||
//! # Example
|
||||
//!
|
||||
//! ```no_run
|
||||
//! use pmoradiofrance::RadioFranceStatefulClient;
|
||||
//! use pmoconfig::get_config;
|
||||
//!
|
||||
//! #[tokio::main]
|
||||
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
//! let config = get_config();
|
||||
//! let client = RadioFranceStatefulClient::new(config).await?;
|
||||
//!
|
||||
//! // Get stations (automatically cached with 7-day TTL)
|
||||
//! let stations = client.get_stations().await?;
|
||||
//!
|
||||
//! // Get live metadata (handles caching internally)
|
||||
//! let metadata = client.get_live_metadata("franceculture").await?;
|
||||
//!
|
||||
//! Ok(())
|
||||
//! }
|
||||
//! ```
|
||||
|
||||
use crate::client::RadioFranceClient;
|
||||
use crate::config_ext::RadioFranceConfigExt;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::models::{LiveResponse, Station};
|
||||
use pmoconfig::Config;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
/// Cache entry for live metadata
|
||||
#[derive(Debug, Clone)]
|
||||
struct LiveMetadataCache {
|
||||
/// Cached metadata
|
||||
metadata: LiveResponse,
|
||||
/// When the cache should be invalidated (based on delayToRefresh)
|
||||
valid_until: SystemTime,
|
||||
}
|
||||
|
||||
impl LiveMetadataCache {
|
||||
/// Create a new cache entry
|
||||
fn new(metadata: LiveResponse) -> Self {
|
||||
let delay = Duration::from_millis(metadata.delay_to_refresh);
|
||||
let valid_until = SystemTime::now() + delay;
|
||||
|
||||
Self {
|
||||
metadata,
|
||||
valid_until,
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if the cache is still valid
|
||||
fn is_valid(&self) -> bool {
|
||||
SystemTime::now() < self.valid_until
|
||||
}
|
||||
|
||||
/// Get the remaining time until the cache expires
|
||||
#[cfg(feature = "logging")]
|
||||
fn remaining_ttl(&self) -> Duration {
|
||||
self.valid_until
|
||||
.duration_since(SystemTime::now())
|
||||
.unwrap_or(Duration::ZERO)
|
||||
}
|
||||
}
|
||||
|
||||
/// Stateful Radio France client with automatic caching
|
||||
///
|
||||
/// This client wraps `RadioFranceClient` and adds:
|
||||
/// - Automatic station list caching via pmoconfig
|
||||
/// - Live metadata caching (in-memory, respecting delayToRefresh)
|
||||
/// - Simple high-level API for PMOMusic integration
|
||||
///
|
||||
/// # Caching Strategy
|
||||
///
|
||||
/// - **Station List**: Cached in pmoconfig with 7-day TTL (configurable)
|
||||
/// - **Live Metadata**: Cached in-memory per station, TTL from API's delayToRefresh
|
||||
///
|
||||
/// # Thread Safety
|
||||
///
|
||||
/// This client is thread-safe (Clone + Send + Sync) and can be shared
|
||||
/// across async tasks.
|
||||
#[derive(Clone)]
|
||||
pub struct RadioFranceStatefulClient {
|
||||
/// Underlying HTTP client
|
||||
client: RadioFranceClient,
|
||||
/// Configuration handle (Arc for sharing)
|
||||
config: Arc<Config>,
|
||||
/// In-memory cache for live metadata (thread-safe)
|
||||
metadata_cache: Arc<std::sync::RwLock<std::collections::HashMap<String, LiveMetadataCache>>>,
|
||||
}
|
||||
|
||||
impl RadioFranceStatefulClient {
|
||||
/// Create a new stateful client
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `config` - Configuration handle for caching station lists
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```no_run
|
||||
/// use pmoconfig::get_config;
|
||||
/// use pmoradiofrance::RadioFranceStatefulClient;
|
||||
///
|
||||
/// #[tokio::main]
|
||||
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
/// let config = get_config();
|
||||
/// let client = RadioFranceStatefulClient::new(config).await?;
|
||||
/// Ok(())
|
||||
/// }
|
||||
/// ```
|
||||
pub async fn new(config: Arc<Config>) -> Result<Self> {
|
||||
let client = RadioFranceClient::new().await?;
|
||||
Ok(Self {
|
||||
client,
|
||||
config,
|
||||
metadata_cache: Arc::new(std::sync::RwLock::new(std::collections::HashMap::new())),
|
||||
})
|
||||
}
|
||||
|
||||
/// Create a client from global configuration
|
||||
///
|
||||
/// This is a convenience method that reads the configuration from
|
||||
/// the global config singleton.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```ignore
|
||||
/// use pmoradiofrance::RadioFranceStatefulClient;
|
||||
///
|
||||
/// #[tokio::main]
|
||||
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
/// let client = RadioFranceStatefulClient::from_config().await?;
|
||||
/// Ok(())
|
||||
/// }
|
||||
/// ```
|
||||
pub async fn from_config() -> Result<Self> {
|
||||
let config = pmoconfig::get_config();
|
||||
Self::new(config).await
|
||||
}
|
||||
|
||||
/// Create a client with a custom RadioFranceClient
|
||||
pub fn with_client(client: RadioFranceClient, config: Arc<Config>) -> Self {
|
||||
Self {
|
||||
client,
|
||||
config,
|
||||
metadata_cache: Arc::new(std::sync::RwLock::new(std::collections::HashMap::new())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the underlying HTTP client
|
||||
pub fn client(&self) -> &RadioFranceClient {
|
||||
&self.client
|
||||
}
|
||||
|
||||
/// Get the configuration
|
||||
pub fn config(&self) -> &Arc<Config> {
|
||||
&self.config
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// Station Discovery (with automatic caching)
|
||||
// ========================================================================
|
||||
|
||||
/// Get all stations, using cache if valid
|
||||
///
|
||||
/// This method automatically:
|
||||
/// 1. Checks if Radio France is enabled in config
|
||||
/// 2. Tries to use cached station list
|
||||
/// 3. If cache miss/expired, discovers and caches stations
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns error if:
|
||||
/// - Radio France is disabled in config
|
||||
/// - Discovery fails and no valid cache exists
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```no_run
|
||||
/// # use pmoradiofrance::RadioFranceStatefulClient;
|
||||
/// # use pmoconfig::get_config;
|
||||
/// # #[tokio::main]
|
||||
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
/// # let config = get_config();
|
||||
/// # let client = RadioFranceStatefulClient::new(config).await?;
|
||||
/// let stations = client.get_stations().await?;
|
||||
/// for station in stations {
|
||||
/// println!("{} - {}", station.name, station.slug);
|
||||
/// }
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub async fn get_stations(&self) -> Result<Vec<Station>> {
|
||||
// Check if Radio France is enabled
|
||||
if !self.config.get_radiofrance_enabled()? {
|
||||
return Err(Error::other("Radio France is disabled in configuration"));
|
||||
}
|
||||
|
||||
// Try to get from cache
|
||||
if let Some(stations) = self.config.get_radiofrance_stations_cached()? {
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::debug!("Using {} cached stations", stations.len());
|
||||
return Ok(stations);
|
||||
}
|
||||
|
||||
// Cache miss - discover and cache with timeout
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::info!("Station cache miss - discovering stations");
|
||||
|
||||
let stations = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(10),
|
||||
self.client.discover_all_stations(),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| Error::other("Timeout while discovering Radio France stations (10s)"))??;
|
||||
|
||||
// Cache the results
|
||||
self.config.set_radiofrance_cached_stations(&stations)?;
|
||||
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::info!("Discovered and cached {} stations", stations.len());
|
||||
|
||||
Ok(stations)
|
||||
}
|
||||
|
||||
/// Force refresh of the station list (bypass cache)
|
||||
///
|
||||
/// Use this to force re-discovery, for example after a manual
|
||||
/// cache invalidation or to get the latest station list.
|
||||
pub async fn refresh_stations(&self) -> Result<Vec<Station>> {
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::info!("Force refreshing station list");
|
||||
|
||||
let stations = self.client.discover_all_stations().await?;
|
||||
self.config.set_radiofrance_cached_stations(&stations)?;
|
||||
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::info!("Refreshed {} stations", stations.len());
|
||||
|
||||
Ok(stations)
|
||||
}
|
||||
|
||||
/// Clear the station cache
|
||||
///
|
||||
/// Forces next `get_stations()` call to re-discover stations.
|
||||
pub fn clear_station_cache(&self) -> Result<()> {
|
||||
Ok(self.config.clear_radiofrance_station_cache()?)
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// Live Metadata (with intelligent caching)
|
||||
// ========================================================================
|
||||
|
||||
/// Get live metadata for a station, using cache if valid
|
||||
///
|
||||
/// This method automatically:
|
||||
/// 1. Checks in-memory cache
|
||||
/// 2. If cache valid (based on delayToRefresh), returns cached data
|
||||
/// 3. If cache expired, fetches fresh data and updates cache
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `station` - Station slug (e.g., "franceculture", "fip_rock")
|
||||
///
|
||||
/// # Caching Behavior
|
||||
///
|
||||
/// The cache TTL is determined by the API's `delayToRefresh` field,
|
||||
/// which respects Radio France's recommended polling interval.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```no_run
|
||||
/// # use pmoradiofrance::RadioFranceStatefulClient;
|
||||
/// # use pmoconfig::get_config;
|
||||
/// # #[tokio::main]
|
||||
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
/// # let config = get_config();
|
||||
/// # let client = RadioFranceStatefulClient::new(config).await?;
|
||||
/// let metadata = client.get_live_metadata("franceculture").await?;
|
||||
/// println!("Now: {} - {}",
|
||||
/// metadata.now.first_line.title_or_default(),
|
||||
/// metadata.now.second_line.title_or_default()
|
||||
/// );
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub async fn get_live_metadata(&self, station: &str) -> Result<LiveResponse> {
|
||||
// Check cache first
|
||||
{
|
||||
let cache = self.metadata_cache.read().unwrap();
|
||||
if let Some(entry) = cache.get(station) {
|
||||
if entry.is_valid() {
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::debug!(
|
||||
"Using cached metadata for {} (TTL: {:?})",
|
||||
station,
|
||||
entry.remaining_ttl()
|
||||
);
|
||||
return Ok(entry.metadata.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Cache miss or expired - fetch fresh data with timeout
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::debug!("Fetching live metadata for {}", station);
|
||||
|
||||
let metadata = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(5),
|
||||
self.client.live_metadata(station),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
Error::other(format!(
|
||||
"Timeout while fetching metadata for {} (5s)",
|
||||
station
|
||||
))
|
||||
})??;
|
||||
|
||||
// Update cache
|
||||
{
|
||||
let mut cache = self.metadata_cache.write().unwrap();
|
||||
cache.insert(
|
||||
station.to_string(),
|
||||
LiveMetadataCache::new(metadata.clone()),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::debug!(
|
||||
"Cached metadata for {} (TTL: {} ms)",
|
||||
station,
|
||||
metadata.delay_to_refresh
|
||||
);
|
||||
|
||||
Ok(metadata)
|
||||
}
|
||||
|
||||
/// Force refresh of live metadata (bypass cache)
|
||||
///
|
||||
/// Use this when you need the absolute latest metadata,
|
||||
/// ignoring the cached version.
|
||||
pub async fn refresh_live_metadata(&self, station: &str) -> Result<LiveResponse> {
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::debug!("Force refreshing metadata for {}", station);
|
||||
|
||||
let metadata = self.client.live_metadata(station).await?;
|
||||
|
||||
// Update cache
|
||||
{
|
||||
let mut cache = self.metadata_cache.write().unwrap();
|
||||
cache.insert(
|
||||
station.to_string(),
|
||||
LiveMetadataCache::new(metadata.clone()),
|
||||
);
|
||||
}
|
||||
|
||||
Ok(metadata)
|
||||
}
|
||||
|
||||
/// Clear the metadata cache for a specific station
|
||||
pub fn clear_metadata_cache(&self, station: &str) {
|
||||
let mut cache = self.metadata_cache.write().unwrap();
|
||||
cache.remove(station);
|
||||
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::debug!("Cleared metadata cache for {}", station);
|
||||
}
|
||||
|
||||
/// Clear all metadata caches
|
||||
pub fn clear_all_metadata_caches(&self) {
|
||||
let mut cache = self.metadata_cache.write().unwrap();
|
||||
cache.clear();
|
||||
|
||||
#[cfg(feature = "logging")]
|
||||
tracing::debug!("Cleared all metadata caches");
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// Convenience Methods
|
||||
// ========================================================================
|
||||
|
||||
/// Get the HiFi stream URL for a station
|
||||
///
|
||||
/// Convenience wrapper around `get_live_metadata()` that extracts
|
||||
/// the best HiFi stream URL.
|
||||
pub async fn get_stream_url(&self, station: &str) -> Result<String> {
|
||||
self.client.get_hifi_stream_url(station).await
|
||||
}
|
||||
|
||||
/// Check if Radio France is enabled in configuration
|
||||
pub fn is_enabled(&self) -> Result<bool> {
|
||||
Ok(self.config.get_radiofrance_enabled()?)
|
||||
}
|
||||
|
||||
/// Enable Radio France in configuration
|
||||
pub fn set_enabled(&self, enabled: bool) -> Result<()> {
|
||||
Ok(self.config.set_radiofrance_enabled(enabled)?)
|
||||
}
|
||||
|
||||
/// Get the station cache TTL in seconds
|
||||
pub fn get_station_cache_ttl(&self) -> Result<u64> {
|
||||
Ok(self.config.get_radiofrance_station_cache_ttl()?)
|
||||
}
|
||||
|
||||
/// Set the station cache TTL in seconds
|
||||
pub fn set_station_cache_ttl(&self, ttl_secs: u64) -> Result<()> {
|
||||
Ok(self.config.set_radiofrance_station_cache_ttl(ttl_secs)?)
|
||||
}
|
||||
|
||||
/// Get cache statistics
|
||||
///
|
||||
/// Returns (number of cached stations, number of cached metadata entries)
|
||||
pub fn cache_stats(&self) -> (usize, usize) {
|
||||
let station_count = self
|
||||
.config
|
||||
.get_radiofrance_stations_cached()
|
||||
.ok()
|
||||
.flatten()
|
||||
.map(|s| s.len())
|
||||
.unwrap_or(0);
|
||||
|
||||
let metadata_count = self.metadata_cache.read().unwrap().len();
|
||||
|
||||
(station_count, metadata_count)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for RadioFranceStatefulClient {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let (station_cache, metadata_cache) = self.cache_stats();
|
||||
f.debug_struct("RadioFranceStatefulClient")
|
||||
.field("client", &self.client)
|
||||
.field("cached_stations", &station_cache)
|
||||
.field("cached_metadata_entries", &metadata_cache)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// Note: Real integration tests would require pmoconfig setup
|
||||
// These are just structural tests
|
||||
|
||||
#[test]
|
||||
fn test_live_metadata_cache_validity() {
|
||||
let response = LiveResponse {
|
||||
station_name: "test".to_string(),
|
||||
delay_to_refresh: 5000, // 5 seconds
|
||||
migrated: true,
|
||||
now: crate::models::ShowMetadata {
|
||||
print_prog_music: false,
|
||||
start_time: None,
|
||||
end_time: None,
|
||||
producer: None,
|
||||
first_line: Default::default(),
|
||||
second_line: Default::default(),
|
||||
third_line: None,
|
||||
intro: None,
|
||||
react_available: false,
|
||||
visual_background: None,
|
||||
song: None,
|
||||
media: Default::default(),
|
||||
visuals: None,
|
||||
local_radios: None,
|
||||
},
|
||||
next: None,
|
||||
};
|
||||
|
||||
let cache = LiveMetadataCache::new(response);
|
||||
assert!(cache.is_valid());
|
||||
|
||||
// Verify the cache expires in the future
|
||||
assert!(cache.valid_until > SystemTime::now());
|
||||
}
|
||||
}
|
||||
@@ -1 +1 @@
|
||||
0.3.12
|
||||
0.3.15
|
||||
|
||||
Reference in New Issue
Block a user