Add http server with mpmc communication for mpris player
This commit is contained in:
63
src/http_server.rs
Normal file
63
src/http_server.rs
Normal file
@@ -0,0 +1,63 @@
|
||||
use axum::{
|
||||
extract::{Path, State},
|
||||
http::StatusCode,
|
||||
response::{IntoResponse, Response},
|
||||
routing::get,
|
||||
Router,
|
||||
};
|
||||
use tokio::sync::broadcast::Sender;
|
||||
|
||||
use crate::database::Database;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct SharedState {
|
||||
database: Database,
|
||||
mpris_sender: Sender<(String, String)>,
|
||||
}
|
||||
|
||||
pub async fn http_serve(database: &Database, mpris_producer: Sender<(String, String)>) {
|
||||
let database = database.clone();
|
||||
let shared_state = SharedState {
|
||||
database,
|
||||
mpris_sender: mpris_producer,
|
||||
};
|
||||
|
||||
let app = Router::new()
|
||||
.route("/", get(root))
|
||||
.route("/{length}", get(add_rating))
|
||||
.with_state(shared_state);
|
||||
|
||||
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
}
|
||||
|
||||
async fn root() -> impl IntoResponse {
|
||||
(StatusCode::OK, "Use /{user_id}/{rating}")
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
println!("mpris error: {e}");
|
||||
(StatusCode::BAD_REQUEST, e.to_string()).into_response()
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user