Ajount d'un viewer radio paradise

This commit is contained in:
2025-10-19 01:01:33 +02:00
parent 032b55a6f1
commit 7a8562fe8e
11 changed files with 972 additions and 7 deletions

2
Cargo.lock generated
View File

@@ -2375,6 +2375,7 @@ name = "pmoparadise"
version = "0.1.0"
dependencies = [
"anyhow",
"axum",
"bytes",
"claxon",
"futures",
@@ -2396,6 +2397,7 @@ dependencies = [
"tracing",
"tracing-subscriber",
"url",
"utoipa",
"uuid",
"wiremock",
]

View File

@@ -7,14 +7,13 @@ edition = "2024"
pmoconfig = { path = "../pmoconfig" }
pmoupnp = { path = "../pmoupnp"}
pmomediarenderer = { path = "../pmomediarenderer" }
pmomediaserver = { path = "../pmomediaserver", features = ["qobuz", "paradise", "api"] }
pmomediaserver = { path = "../pmomediaserver", features = ["qobuz", "paradise", "paradise-api", "api"] }
pmosource = { path = "../pmosource", features = ["server"] }
pmoserver = { path = "../pmoserver" }
pmocovers = { path = "../pmocovers", features = ["pmoserver"] }
pmoaudiocache = { path = "../pmoaudiocache", features = ["pmoserver"]}
pmoapp = { path = "../pmoapp", features = ["pmoserver"] }
tokio = { version = "1.35", features = ["rt-multi-thread", "macros", "sync", "time","signal"] }
tracing = "0.1.41"
tracing-subscriber = "0.3.20"

View File

@@ -35,7 +35,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// tracing::warn!("⚠️ Failed to register Qobuz: {}", e);
// }
// Enregistrer Radio Paradise
// Enregistrer Radio Paradise (inclut l'initialisation de l'API)
if let Err(e) = server.register_paradise().await {
tracing::warn!("⚠️ Failed to register Radio Paradise: {}", e);
}

View File

@@ -15,6 +15,9 @@
<router-link to="/covers-cache" @click="showDebugMenu = false">🎨 Cover Cache</router-link>
<router-link to="/audio-cache" @click="showDebugMenu = false">🎵 Audio Cache</router-link>
<router-link to="/api-dashboard" @click="showDebugMenu = false">🚀 API Dashboard</router-link>
<div class="submenu-divider">Sources</div>
<router-link to="/radio-paradise" @click="showDebugMenu = false">📻 Radio Paradise</router-link>
</div>
</div>
</nav>
@@ -32,7 +35,7 @@ const showDebugMenu = ref(false)
const route = useRoute()
const isDebugRoute = computed(() => {
return ['/logs', '/upnp', '/covers-cache', '/audio-cache', '/api-dashboard'].includes(route.path)
return ['/logs', '/upnp', '/covers-cache', '/audio-cache', '/api-dashboard', '/radio-paradise'].includes(route.path)
})
</script>
@@ -154,6 +157,17 @@ const isDebugRoute = computed(() => {
font-weight: bold;
}
.submenu-divider {
padding: 0.5rem 1rem;
margin-top: 0.5rem;
border-top: 1px solid #555;
color: #999;
font-size: 0.85em;
font-weight: bold;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.main-content {
flex: 1;
width: 100%;

View File

@@ -0,0 +1,516 @@
<template>
<div class="radio-paradise-explorer">
<div class="header">
<h2>Radio Paradise Explorer</h2>
<div class="controls">
<button @click="refreshNowPlaying" :disabled="loading" class="btn-primary">
<span v-if="loading"></span>
<span v-else>🔄</span>
Refresh
</button>
<select v-model="selectedChannel" @change="changeChannel" class="channel-select">
<option v-for="channel in channels" :key="channel.id" :value="channel.id">
{{ channel.name }}
</option>
</select>
</div>
</div>
<div v-if="error" class="error-message">
{{ error }}
</div>
<!-- Now Playing Section -->
<div v-if="nowPlaying" class="now-playing-section">
<h3>🎵 Now Playing</h3>
<div v-if="nowPlaying.current_song" class="current-song">
<div v-if="nowPlaying.current_song.cover_url" class="cover-art">
<img :src="nowPlaying.current_song.cover_url" :alt="`${nowPlaying.current_song.album} cover`">
</div>
<div class="song-details">
<div class="artist">{{ nowPlaying.current_song.artist }}</div>
<div class="title">{{ nowPlaying.current_song.title }}</div>
<div class="album">{{ nowPlaying.current_song.album }}</div>
<div class="metadata">
<span v-if="nowPlaying.current_song.year" class="year">{{ nowPlaying.current_song.year }}</span>
<span class="duration">{{ formatDuration(nowPlaying.current_song.duration_ms) }}</span>
<span v-if="nowPlaying.current_song.rating" class="rating"> {{ nowPlaying.current_song.rating.toFixed(1) }}</span>
</div>
</div>
</div>
</div>
<!-- Block Info -->
<div v-if="nowPlaying" class="block-info">
<h3>📦 Block Info</h3>
<div class="block-details">
<div class="info-row">
<span class="label">Event ID:</span>
<span class="value">{{ nowPlaying.event }}</span>
</div>
<div class="info-row">
<span class="label">Next Event:</span>
<span class="value">{{ nowPlaying.end_event }}</span>
</div>
<div class="info-row">
<span class="label">Block Length:</span>
<span class="value">{{ formatDuration(nowPlaying.block_length_ms) }}</span>
</div>
<div class="info-row">
<span class="label">Songs in Block:</span>
<span class="value">{{ nowPlaying.songs.length }}</span>
</div>
<div class="info-row">
<span class="label">Stream URL:</span>
<a :href="nowPlaying.stream_url" target="_blank" class="stream-link">{{ nowPlaying.stream_url }}</a>
</div>
</div>
</div>
<!-- Songs List -->
<div v-if="nowPlaying && nowPlaying.songs" class="songs-section">
<h3>🎼 Songs in Current Block</h3>
<div class="songs-list">
<div
v-for="song in nowPlaying.songs"
:key="song.index"
:class="['song-item', { 'current': song.index === nowPlaying.current_song_index }]"
>
<div class="song-number">{{ song.index + 1 }}</div>
<div v-if="song.cover_url" class="song-cover-mini">
<img :src="song.cover_url" :alt="`${song.album} cover`">
</div>
<div class="song-info">
<div class="song-title">{{ song.title }}</div>
<div class="song-artist">{{ song.artist }}</div>
<div class="song-album">{{ song.album }}</div>
</div>
<div class="song-meta">
<div class="song-year" v-if="song.year">{{ song.year }}</div>
<div class="song-duration">{{ formatDuration(song.duration_ms) }}</div>
<div class="song-elapsed">@{{ formatDuration(song.elapsed_ms) }}</div>
<div v-if="song.rating" class="song-rating"> {{ song.rating.toFixed(1) }}</div>
</div>
</div>
</div>
</div>
<!-- Available Channels -->
<div class="channels-section">
<h3>📻 Available Channels</h3>
<div class="channels-grid">
<div
v-for="channel in channels"
:key="channel.id"
:class="['channel-card', { 'active': channel.id === selectedChannel }]"
@click="selectChannel(channel.id)"
>
<div class="channel-name">{{ channel.name }}</div>
<div class="channel-description">{{ channel.description }}</div>
</div>
</div>
</div>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
const API_BASE = '/api/radioparadise'
const loading = ref(false)
const error = ref(null)
const nowPlaying = ref(null)
const channels = ref([])
const selectedChannel = ref(0)
// Format duration from milliseconds to MM:SS
function formatDuration(ms) {
const seconds = Math.floor(ms / 1000)
const minutes = Math.floor(seconds / 60)
const remainingSeconds = seconds % 60
return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
}
// Fetch now playing info
async function refreshNowPlaying() {
loading.value = true
error.value = null
try {
const response = await fetch(`${API_BASE}/now-playing`)
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`)
}
nowPlaying.value = await response.json()
} catch (e) {
error.value = `Failed to fetch now playing: ${e.message}`
console.error('Error fetching now playing:', e)
} finally {
loading.value = false
}
}
// Fetch available channels
async function fetchChannels() {
try {
const response = await fetch(`${API_BASE}/channels`)
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`)
}
channels.value = await response.json()
} catch (e) {
error.value = `Failed to fetch channels: ${e.message}`
console.error('Error fetching channels:', e)
}
}
// Select a channel
function selectChannel(channelId) {
selectedChannel.value = channelId
// For now, just highlight it - we could implement channel switching
// when the API supports it
}
// Change channel (placeholder for future implementation)
function changeChannel() {
console.log('Channel changed to:', selectedChannel.value)
// TODO: Implement channel switching in the API
}
// Initialize on mount
onMounted(async () => {
await fetchChannels()
await refreshNowPlaying()
// Auto-refresh every 30 seconds
setInterval(() => {
if (!loading.value) {
refreshNowPlaying()
}
}, 30000)
})
</script>
<style scoped>
.radio-paradise-explorer {
padding: 20px;
max-width: 1200px;
margin: 0 auto;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
padding-bottom: 10px;
border-bottom: 2px solid #333;
}
.header h2 {
margin: 0;
color: #00d4ff;
}
.controls {
display: flex;
gap: 10px;
align-items: center;
}
.btn-primary {
background: #00d4ff;
color: #000;
border: none;
padding: 8px 16px;
border-radius: 4px;
cursor: pointer;
font-weight: bold;
transition: background 0.3s;
}
.btn-primary:hover:not(:disabled) {
background: #00a8cc;
}
.btn-primary:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.channel-select {
padding: 8px 12px;
border-radius: 4px;
border: 1px solid #333;
background: #1a1a1a;
color: #fff;
cursor: pointer;
}
.error-message {
background: #ff4444;
color: white;
padding: 12px;
border-radius: 4px;
margin-bottom: 20px;
}
/* Now Playing Section */
.now-playing-section {
background: linear-gradient(135deg, #1a1a1a 0%, #2a2a2a 100%);
border-radius: 8px;
padding: 20px;
margin-bottom: 20px;
border: 1px solid #333;
}
.now-playing-section h3 {
margin-top: 0;
color: #00d4ff;
}
.current-song {
display: flex;
gap: 20px;
align-items: flex-start;
}
.cover-art {
flex-shrink: 0;
}
.cover-art img {
width: 200px;
height: 200px;
object-fit: cover;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.5);
}
.song-details {
flex: 1;
}
.artist {
font-size: 1.8em;
font-weight: bold;
color: #00d4ff;
margin-bottom: 8px;
}
.title {
font-size: 1.4em;
margin-bottom: 8px;
color: #fff;
}
.album {
font-size: 1.1em;
color: #999;
margin-bottom: 12px;
}
.metadata {
display: flex;
gap: 15px;
font-size: 0.9em;
color: #666;
}
.metadata span {
padding: 4px 8px;
background: #333;
border-radius: 4px;
}
/* Block Info */
.block-info {
background: #1a1a1a;
border-radius: 8px;
padding: 20px;
margin-bottom: 20px;
border: 1px solid #333;
}
.block-info h3 {
margin-top: 0;
color: #00d4ff;
}
.block-details {
display: flex;
flex-direction: column;
gap: 10px;
}
.info-row {
display: flex;
justify-content: space-between;
padding: 8px 0;
border-bottom: 1px solid #333;
}
.info-row:last-child {
border-bottom: none;
}
.label {
font-weight: bold;
color: #999;
}
.value {
color: #fff;
}
.stream-link {
color: #00d4ff;
text-decoration: none;
word-break: break-all;
}
.stream-link:hover {
text-decoration: underline;
}
/* Songs List */
.songs-section {
background: #1a1a1a;
border-radius: 8px;
padding: 20px;
margin-bottom: 20px;
border: 1px solid #333;
}
.songs-section h3 {
margin-top: 0;
color: #00d4ff;
}
.songs-list {
display: flex;
flex-direction: column;
gap: 8px;
}
.song-item {
display: flex;
gap: 12px;
padding: 12px;
background: #2a2a2a;
border-radius: 4px;
align-items: center;
transition: background 0.3s;
}
.song-item:hover {
background: #333;
}
.song-item.current {
background: #003d4d;
border-left: 4px solid #00d4ff;
}
.song-number {
font-weight: bold;
color: #666;
min-width: 30px;
text-align: center;
}
.song-cover-mini img {
width: 50px;
height: 50px;
object-fit: cover;
border-radius: 4px;
}
.song-info {
flex: 1;
min-width: 0;
}
.song-title {
font-weight: bold;
color: #fff;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.song-artist {
color: #00d4ff;
font-size: 0.9em;
}
.song-album {
color: #999;
font-size: 0.85em;
}
.song-meta {
display: flex;
gap: 10px;
font-size: 0.85em;
color: #666;
align-items: center;
}
.song-meta > div {
padding: 2px 6px;
background: #1a1a1a;
border-radius: 3px;
}
/* Channels Section */
.channels-section {
background: #1a1a1a;
border-radius: 8px;
padding: 20px;
border: 1px solid #333;
}
.channels-section h3 {
margin-top: 0;
color: #00d4ff;
}
.channels-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 15px;
}
.channel-card {
background: #2a2a2a;
padding: 15px;
border-radius: 8px;
cursor: pointer;
transition: all 0.3s;
border: 2px solid transparent;
}
.channel-card:hover {
background: #333;
transform: translateY(-2px);
}
.channel-card.active {
border-color: #00d4ff;
background: #003d4d;
}
.channel-name {
font-weight: bold;
color: #00d4ff;
margin-bottom: 8px;
font-size: 1.1em;
}
.channel-description {
color: #999;
font-size: 0.9em;
}
</style>

View File

@@ -5,6 +5,7 @@ import CoverCacheManager from "../components/CoverCacheManager.vue";
import AudioCacheManager from "../components/AudioCacheManager.vue";
import UpnpExplorer from "../components/UpnpExplorer.vue";
import APIDashboard from "../components/APIDashboard.vue";
import RadioParadiseExplorer from "../components/RadioParadiseExplorer.vue";
const routes = [
{ path: "/", name: "home", component: HelloWorld },
@@ -13,6 +14,7 @@ const routes = [
{ path: "/audio-cache", name: "audio-cache", component: AudioCacheManager },
{ path: "/upnp", name: "upnp", component: UpnpExplorer },
{ path: "/api-dashboard", name: "api-dashboard", component: APIDashboard },
{ path: "/radio-paradise", name: "radio-paradise", component: RadioParadiseExplorer },
];
const router = createRouter({

View File

@@ -34,3 +34,5 @@ api = ["dep:axum", "dep:utoipa", "pmosource/server"]
qobuz = ["api", "dep:pmoqobuz", "dep:pmoconfig", "pmoqobuz/server"]
# Feature pour activer le support Radio Paradise
paradise = ["api", "dep:pmoparadise", "pmoparadise/server"]
# Feature pour activer l'API REST de Radio Paradise (en plus de la source UPnP)
paradise-api = ["paradise", "pmoparadise/pmoserver"]

View File

@@ -165,7 +165,7 @@ impl SourcesExt for Server {
#[cfg(feature = "paradise")]
async fn register_paradise(&mut self) -> Result<()> {
use pmoparadise::{RadioParadiseClient, RadioParadiseSource};
use pmoparadise::{RadioParadiseClient, RadioParadiseSource, RadioParadiseExt};
tracing::info!("Initializing Radio Paradise source...");
@@ -184,6 +184,17 @@ impl SourcesExt for Server {
tracing::info!("✅ Radio Paradise source registered successfully");
// Initialiser l'API REST Radio Paradise
#[cfg(feature = "paradise-api")]
{
tracing::info!("📻 Initializing Radio Paradise API...");
if let Err(e) = self.init_radioparadise().await {
tracing::warn!("⚠️ Failed to initialize Radio Paradise API: {}", e);
} else {
tracing::info!("✅ Radio Paradise API initialized");
}
}
Ok(())
}
}

View File

@@ -55,14 +55,20 @@ pmoplaylist = { path = "../pmoplaylist" }
pmocovers = { path = "../pmocovers" }
pmoaudiocache = { path = "../pmoaudiocache" }
# OpenAPI/Swagger support (pour pmoserver extension)
utoipa = { version = "5.4.0", optional = true }
axum = { version = "0.8.4", optional = true }
[features]
default = ["metadata-only"]
# Mode métadonnées seules (pas de décodage FLAC)
metadata-only = []
# Active le décodage FLAC par-track
per-track = ["dep:claxon", "dep:hound", "dep:tempfile"]
# Active le media server UPnP
mediaserver = ["dep:pmoupnp", "dep:pmoserver", "dep:pmodidl", "dep:uuid"]
# Active l'API REST pmoserver
pmoserver = ["dep:pmoserver", "dep:utoipa", "dep:axum"]
# Active le media server UPnP (includes pmoserver)
mediaserver = ["dep:pmoupnp", "dep:pmodidl", "dep:uuid", "pmoserver"]
# Feature pour activer le support serveur (cache registry)
server = ["pmosource/server"]
# Feature cache (deprecated - toujours actif maintenant)

View File

@@ -255,6 +255,9 @@ pub mod track;
#[cfg(feature = "mediaserver")]
pub mod mediaserver;
#[cfg(feature = "pmoserver")]
pub mod pmoserver_ext;
// Re-exports for convenience
pub use client::{ClientBuilder, RadioParadiseClient};
pub use error::{Error, Result};
@@ -268,6 +271,9 @@ pub use track::{TrackMetadata, TrackStream};
#[cfg(feature = "mediaserver")]
pub use mediaserver::{RadioParadiseMediaServer, MediaServerBuilder};
#[cfg(feature = "pmoserver")]
pub use pmoserver_ext::{RadioParadiseExt, RadioParadiseState, RadioParadiseApiDoc, create_api_router};
// Version information
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

View File

@@ -0,0 +1,407 @@
//! Extension pmoserver pour Radio Paradise
//!
//! Ce module fournit un trait d'extension pour ajouter facilement l'API Radio Paradise
//! à un serveur pmoserver.
use crate::{RadioParadiseClient, Block, NowPlaying};
use axum::{
extract::{Path, State},
http::StatusCode,
routing::get,
Json, Router,
};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tokio::sync::RwLock;
use utoipa::{OpenApi, ToSchema};
/// État partagé pour l'API Radio Paradise
#[derive(Clone)]
pub struct RadioParadiseState {
client: Arc<RwLock<RadioParadiseClient>>,
}
impl RadioParadiseState {
pub async fn new() -> anyhow::Result<Self> {
let client = RadioParadiseClient::new()
.await
.map_err(|e| anyhow::anyhow!("Failed to create RadioParadise client: {}", e))?;
Ok(Self {
client: Arc::new(RwLock::new(client)),
})
}
}
/// Information sur un canal Radio Paradise
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct ChannelInfo {
/// ID du canal (0-3)
pub id: u8,
/// Nom du canal
pub name: String,
/// Description
pub description: String,
}
/// Réponse avec informations étendues sur le morceau en cours
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct NowPlayingResponse {
/// Event ID du block actuel
pub event: u64,
/// Event ID du prochain block
pub end_event: u64,
/// URL de streaming du block
pub stream_url: String,
/// Durée totale du block en ms
pub block_length_ms: u64,
/// Index du morceau actuel
pub current_song_index: Option<usize>,
/// Morceau actuel
pub current_song: Option<SongInfo>,
/// Tous les morceaux du block
pub songs: Vec<SongInfo>,
}
/// Information sur un morceau
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct SongInfo {
/// Index dans le block
pub index: usize,
/// Artiste
pub artist: String,
/// Titre
pub title: String,
/// Album
pub album: String,
/// Année
pub year: Option<u32>,
/// Temps écoulé depuis le début du block (ms)
pub elapsed_ms: u64,
/// Durée du morceau (ms)
pub duration_ms: u64,
/// URL de la pochette
pub cover_url: Option<String>,
/// Note (0-10)
pub rating: Option<f32>,
}
/// Réponse pour un block
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct BlockResponse {
/// Event ID du block
pub event: u64,
/// Event ID du prochain block
pub end_event: u64,
/// URL de streaming
pub url: String,
/// Durée totale (ms)
pub length_ms: u64,
/// Morceaux du block
pub songs: Vec<SongInfo>,
}
impl From<Block> for BlockResponse {
fn from(block: Block) -> Self {
let songs = block
.songs_ordered()
.into_iter()
.map(|(index, song)| SongInfo {
index,
artist: song.artist.clone(),
title: song.title.clone(),
album: song.album.clone(),
year: song.year,
elapsed_ms: song.elapsed,
duration_ms: song.duration,
cover_url: song.cover.as_ref().and_then(|c| block.cover_url(c)),
rating: song.rating,
})
.collect();
Self {
event: block.event,
end_event: block.end_event,
url: block.url,
length_ms: block.length,
songs,
}
}
}
impl From<NowPlaying> for NowPlayingResponse {
fn from(np: NowPlaying) -> Self {
let songs: Vec<SongInfo> = np
.block
.songs_ordered()
.into_iter()
.map(|(index, song)| SongInfo {
index,
artist: song.artist.clone(),
title: song.title.clone(),
album: song.album.clone(),
year: song.year,
elapsed_ms: song.elapsed,
duration_ms: song.duration,
cover_url: song.cover.as_ref().and_then(|c| np.block.cover_url(c)),
rating: song.rating,
})
.collect();
let current_song = np.current_song.as_ref().and_then(|song| {
let index = np.current_song_index?;
Some(SongInfo {
index,
artist: song.artist.clone(),
title: song.title.clone(),
album: song.album.clone(),
year: song.year,
elapsed_ms: song.elapsed,
duration_ms: song.duration,
cover_url: song.cover.as_ref().and_then(|c| np.block.cover_url(c)),
rating: song.rating,
})
});
Self {
event: np.block.event,
end_event: np.block.end_event,
stream_url: np.block.url,
block_length_ms: np.block.length,
current_song_index: np.current_song_index,
current_song,
songs,
}
}
}
/// GET /now-playing - Récupère le morceau en cours
#[utoipa::path(
get,
path = "/now-playing",
responses(
(status = 200, description = "Morceau en cours", body = NowPlayingResponse),
(status = 500, description = "Erreur serveur")
),
tag = "Radio Paradise"
)]
async fn get_now_playing(
State(state): State<RadioParadiseState>,
) -> Result<Json<NowPlayingResponse>, StatusCode> {
let client = state.client.read().await;
let now_playing = client
.now_playing()
.await
.map_err(|e| {
tracing::error!("Failed to fetch now playing from Radio Paradise: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
Ok(Json(now_playing.into()))
}
/// GET /block/current - Récupère le block actuel
#[utoipa::path(
get,
path = "/block/current",
responses(
(status = 200, description = "Block actuel", body = BlockResponse),
(status = 500, description = "Erreur serveur")
),
tag = "Radio Paradise"
)]
async fn get_current_block(
State(state): State<RadioParadiseState>,
) -> Result<Json<BlockResponse>, StatusCode> {
let client = state.client.read().await;
let block = client
.get_block(None)
.await
.map_err(|e| {
tracing::error!("Failed to fetch current block from Radio Paradise: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
Ok(Json(block.into()))
}
/// GET /block/{event_id} - Récupère un block spécifique
#[utoipa::path(
get,
path = "/block/{event_id}",
params(
("event_id" = u64, Path, description = "Event ID du block")
),
responses(
(status = 200, description = "Block demandé", body = BlockResponse),
(status = 500, description = "Erreur serveur")
),
tag = "Radio Paradise"
)]
async fn get_block_by_id(
State(state): State<RadioParadiseState>,
Path(event_id): Path<u64>,
) -> Result<Json<BlockResponse>, StatusCode> {
let client = state.client.read().await;
let block = client
.get_block(Some(event_id))
.await
.map_err(|e| {
tracing::error!("Failed to fetch block {} from Radio Paradise: {}", event_id, e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
Ok(Json(block.into()))
}
/// GET /channels - Liste les canaux disponibles
#[utoipa::path(
get,
path = "/channels",
responses(
(status = 200, description = "Liste des canaux", body = Vec<ChannelInfo>)
),
tag = "Radio Paradise"
)]
async fn get_channels() -> Json<Vec<ChannelInfo>> {
let channels = vec![
ChannelInfo {
id: 0,
name: "Main Mix".to_string(),
description: "Eclectic mix of rock, world, electronica, and more".to_string(),
},
ChannelInfo {
id: 1,
name: "Mellow Mix".to_string(),
description: "Mellower, less aggressive music".to_string(),
},
ChannelInfo {
id: 2,
name: "Rock Mix".to_string(),
description: "Heavier, more guitar-driven music".to_string(),
},
ChannelInfo {
id: 3,
name: "World/Etc Mix".to_string(),
description: "Global beats and world music".to_string(),
},
];
Json(channels)
}
/// Information sur un bitrate
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct BitrateInfo {
/// ID du bitrate (0-4)
pub id: u8,
/// Nom/description
pub name: String,
}
/// GET /bitrates - Liste les bitrates disponibles
#[utoipa::path(
get,
path = "/bitrates",
responses(
(status = 200, description = "Liste des bitrates disponibles", body = Vec<BitrateInfo>)
),
tag = "Radio Paradise"
)]
async fn get_bitrates() -> Json<Vec<BitrateInfo>> {
let bitrates = vec![
BitrateInfo {
id: 0,
name: "MP3 128 kbps".to_string(),
},
BitrateInfo {
id: 1,
name: "AAC 64 kbps".to_string(),
},
BitrateInfo {
id: 2,
name: "AAC 128 kbps".to_string(),
},
BitrateInfo {
id: 3,
name: "AAC 320 kbps".to_string(),
},
BitrateInfo {
id: 4,
name: "FLAC Lossless".to_string(),
},
];
Json(bitrates)
}
/// Documentation OpenAPI pour l'API Radio Paradise
#[derive(OpenApi)]
#[openapi(
info(
title = "Radio Paradise API",
version = "1.0.0",
description = "API REST pour accéder aux métadonnées et streams de Radio Paradise"
),
paths(
get_now_playing,
get_current_block,
get_block_by_id,
get_channels,
get_bitrates
),
components(schemas(
NowPlayingResponse,
BlockResponse,
SongInfo,
ChannelInfo,
BitrateInfo
)),
tags(
(name = "Radio Paradise", description = "Endpoints pour Radio Paradise streaming")
)
)]
pub struct RadioParadiseApiDoc;
/// Crée le router pour l'API Radio Paradise
pub fn create_api_router(state: RadioParadiseState) -> Router {
Router::new()
.route("/now-playing", get(get_now_playing))
.route("/block/current", get(get_current_block))
.route("/block/{event_id}", get(get_block_by_id))
.route("/channels", get(get_channels))
.route("/bitrates", get(get_bitrates))
.with_state(state)
}
/// Trait d'extension pour pmoserver::Server
///
/// Permet d'initialiser Radio Paradise avec routes HTTP complètes
#[cfg(feature = "pmoserver")]
pub trait RadioParadiseExt {
/// Initialise l'API Radio Paradise
///
/// # Routes créées
///
/// - API: `/api/radioparadise/*`
/// - Swagger: `/swagger-ui/radioparadise`
async fn init_radioparadise(&mut self) -> anyhow::Result<RadioParadiseState>;
}
#[cfg(feature = "pmoserver")]
impl RadioParadiseExt for pmoserver::Server {
async fn init_radioparadise(&mut self) -> anyhow::Result<RadioParadiseState> {
let state = RadioParadiseState::new().await?;
// Créer le router API
let api_router = create_api_router(state.clone());
// L'enregistrer avec OpenAPI
self.add_openapi(
api_router,
RadioParadiseApiDoc::openapi(),
"radioparadise"
).await;
Ok(state)
}
}