Add tokio watch channel to update mpris player state
This commit is contained in:
@@ -5,7 +5,7 @@ use axum::{
|
||||
routing::get,
|
||||
Router,
|
||||
};
|
||||
use tokio::sync::broadcast::Sender;
|
||||
use tokio::sync::watch::Sender;
|
||||
|
||||
use crate::database::Database;
|
||||
|
||||
@@ -24,7 +24,7 @@ pub async fn http_serve(database: &Database, mpris_producer: Sender<(String, Str
|
||||
|
||||
let app = Router::new()
|
||||
.route("/", get(root))
|
||||
.route("/{length}", get(add_rating))
|
||||
.route("/{user_id}/{rating}", get(add_rating))
|
||||
.with_state(shared_state);
|
||||
|
||||
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
|
||||
@@ -39,24 +39,19 @@ async fn add_rating(
|
||||
Path((user_id, rating)): Path<(i64, i64)>,
|
||||
State(shared): State<SharedState>,
|
||||
) -> Response {
|
||||
// Get the current interpret and track from the broadcast channel
|
||||
match shared.mpris_sender.subscribe().recv().await {
|
||||
Ok((interpret, track)) => {
|
||||
// write to db
|
||||
match shared
|
||||
.database
|
||||
.user_add_rating(user_id, &interpret, &track, rating)
|
||||
.await
|
||||
{
|
||||
Ok(_) => (StatusCode::OK, "Done.").into_response(),
|
||||
Err(e) => {
|
||||
println!("HTTP error: {e}");
|
||||
(StatusCode::BAD_REQUEST, e.to_string()).into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut mpris_rx = shared.mpris_sender.subscribe();
|
||||
|
||||
// Get the current interpret and track from the watch channel
|
||||
let (interpret, track) = (*mpris_rx.borrow_and_update()).clone();
|
||||
|
||||
match shared
|
||||
.database
|
||||
.user_add_rating(user_id, &interpret, &track, rating)
|
||||
.await
|
||||
{
|
||||
Ok(_) => (StatusCode::OK, "Done.").into_response(),
|
||||
Err(e) => {
|
||||
println!("mpris error: {e}");
|
||||
println!("HTTP error: {e}");
|
||||
(StatusCode::BAD_REQUEST, e.to_string()).into_response()
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user