From f823a99984a657b32d687a8dc5eeb9776106216a Mon Sep 17 00:00:00 2001 From: KD Date: Wed, 23 Apr 2025 20:50:07 -0400 Subject: [PATCH] Queue meta data (#121) * Added migrations Added new table to store metadata * Updated table * Added code for new endpoint * Updated module * Code formatting: * Added test code * Fixed test * Cleanup * Code refactor --- migrations/20250420185217_init_migration.sql | 12 +- src/callers/metadata.rs | 118 +++++++++++++++++++ src/callers/mod.rs | 2 + src/main.rs | 101 ++++++++++++++++ 4 files changed, 232 insertions(+), 1 deletion(-) create mode 100644 src/callers/metadata.rs diff --git a/migrations/20250420185217_init_migration.sql b/migrations/20250420185217_init_migration.sql index cb96059..57615c4 100644 --- a/migrations/20250420185217_init_migration.sql +++ b/migrations/20250420185217_init_migration.sql @@ -6,4 +6,14 @@ CREATE TABLE IF NOT EXISTS "songQueue" ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), filename TEXT NOT NULL, data BYTEA NOT NULL -); \ No newline at end of file +); + +CREATE TABLE IF NOT EXISTS "metadataQueue" ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + metadata jsonb NOT NULL, + created_at timestamp DEFAULT now(), + song_queue_id UUID NOT NULL +); + +-- Create an index for better query performance +CREATE INDEX metadata_queue_data_metadata ON "metadataQueue" USING gin (metadata); \ No newline at end of file diff --git a/src/callers/metadata.rs b/src/callers/metadata.rs new file mode 100644 index 0000000..c16546d --- /dev/null +++ b/src/callers/metadata.rs @@ -0,0 +1,118 @@ +pub mod request { + use serde::{Deserialize, Serialize}; + + #[derive(Default, Deserialize, Serialize)] + pub struct Request { + pub id: uuid::Uuid, + pub album: String, + pub album_artist: String, + pub artist: String, + pub disc: i32, + pub disc_count: i32, + pub duration: i64, + pub genre: String, + pub title: String, + pub track: i32, + pub track_count: i32, + pub year: i32, + } + + impl Request { + pub async fn to_json_value(&self) -> serde_json::Value { + serde_json::json!( + { + "id": &self.id, + "album": &self.album, + "album_artist": &self.album_artist, + "genre": &self.genre, + "year": &self.year, + "track_count": &self.track_count, + "disc_count": &self.disc_count, + "title": &self.title, + "artist": &self.artist, + "disc": &self.disc, + "track": &self.track, + "duration": &self.duration, + }) + } + } +} + +pub mod response { + use serde::{Deserialize, Serialize}; + + #[derive(Default, Deserialize, Serialize)] + pub struct Response { + pub message: String, + pub data: Vec, + } +} + +mod metadata_queue { + use sqlx::Row; + + #[derive(Debug, serde::Serialize, sqlx::FromRow)] + pub struct InsertedData { + pub id: uuid::Uuid, + } + + pub async fn insert( + pool: &sqlx::PgPool, + metadata: &serde_json::Value, + song_queue_id: &uuid::Uuid, + ) -> Result { + let result = sqlx::query( + r#" + INSERT INTO "metadataQueue" (metadata, song_queue_id) VALUES($1, $2) RETURNING id; + "#, + ) + .bind(metadata) + .bind(song_queue_id) + .fetch_one(pool) + .await + .map_err(|e| { + eprintln!("Error inserting: {}", e); + }); + + match result { + Ok(row) => { + let id: uuid::Uuid = row + .try_get("id") + .map_err(|_e| sqlx::Error::RowNotFound) + .unwrap(); + Ok(id) + } + Err(_err) => Err(sqlx::Error::RowNotFound), + } + } +} + +pub mod endpoint { + use axum::{Json, http::StatusCode}; + + pub async fn queue_metadata( + axum::Extension(pool): axum::Extension, + Json(payload): Json, + ) -> (StatusCode, Json) { + let mut results: Vec = Vec::new(); + let mut response = super::response::Response::default(); + let meta = payload.to_json_value().await; + match super::metadata_queue::insert(&pool, &meta, &payload.id).await { + Ok(id) => { + results.push(id); + response.data = results; + response.message = if response.data.is_empty() { + String::from("Error") + } else { + String::from("Success") + }; + + (StatusCode::OK, Json(response)) + } + Err(err) => { + response.message = err.to_string(); + (StatusCode::BAD_REQUEST, Json(response)) + } + } + } +} diff --git a/src/callers/mod.rs b/src/callers/mod.rs index 9ee3d1a..5abbb9f 100644 --- a/src/callers/mod.rs +++ b/src/callers/mod.rs @@ -1,5 +1,7 @@ +pub mod metadata; pub mod song; pub mod endpoints { pub const QUEUESONG: &str = "/api/v2/song/queue"; + pub const QUEUEMETADATA: &str = "/api/v2/song/metadata/queue"; } diff --git a/src/main.rs b/src/main.rs index 27dd3a4..aafcc52 100644 --- a/src/main.rs +++ b/src/main.rs @@ -69,6 +69,10 @@ pub mod init { crate::callers::endpoints::QUEUESONG, post(crate::callers::song::endpoint::queue_song), ) + .route( + crate::callers::endpoints::QUEUEMETADATA, + post(crate::callers::metadata::endpoint::queue_metadata), + ) } pub async fn app() -> axum::Router { @@ -245,4 +249,101 @@ mod tests { let _ = db_mgr::drop_database(&tm_pool, &db_name).await; } + + #[tokio::test] + async fn test_song_metadata_queue() { + let tm_pool = db_mgr::get_pool().await.unwrap(); + let db_name = db_mgr::generate_db_name().await; + + match db_mgr::create_database(&tm_pool, &db_name).await { + Ok(_) => { + println!("Success"); + } + Err(err) => { + assert!(false, "Error: {:?}", err); + } + } + + let pool = db_mgr::connect_to_db(&db_name).await.unwrap(); + db::migrations(&pool).await; + + let app = crate::init::routes() + .await + .layer(axum::Extension(pool)) + .layer(axum::extract::DefaultBodyLimit::max(1024 * 1024 * 1024)) + .layer(TimeoutLayer::new(Duration::from_secs(300))); + + // Create multipart form + let mut form = MultipartForm::default(); + let _ = form.add_file("flac", "tests/Machine_gun/track01.flac"); + + // Create request + let content_type = form.content_type(); + let body = MultipartBody::from(form); + let req = axum::http::Request::builder() + .method(axum::http::Method::POST) + .uri(crate::callers::endpoints::QUEUESONG) + .header(axum::http::header::CONTENT_TYPE, content_type) + .body(axum::body::Body::from_stream(body)) + .unwrap(); + + // Send request + match app.clone().oneshot(req).await { + Ok(response) => { + let body = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + println!("Body: {:?}", body); + let resp: crate::callers::song::response::Response = + serde_json::from_slice(&body).unwrap(); + assert_eq!(false, resp.data.is_empty(), "Should not be empty"); + assert_eq!(false, resp.data[0].is_nil(), "Should not be empty"); + let new_payload: serde_json::Value = serde_json::json!( + { + "id": resp.data[0], + "album" : "Machine Gun: The FillMore East First Show", + "album_artist" : "Jimi Hendrix", + "artist" : "Jimi Hendrix", + "disc" : 1, + "disc_count" : 1, + "duration" : 330, + "genre" : "Psychadelic Rock", + "title" : "Power of Soul", + "track" : 1, + "track_count" : 11, + "year" : 2016 + }); + + match app + .clone() + .oneshot( + axum::http::Request::builder() + .method(axum::http::Method::POST) + .uri(crate::callers::endpoints::QUEUEMETADATA) + .header(axum::http::header::CONTENT_TYPE, "application/json") + .body(axum::body::Body::from(new_payload.to_string())) + .unwrap(), + ) + .await + { + Ok(response) => { + let body = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + let resp: crate::callers::song::response::Response = + serde_json::from_slice(&body).unwrap(); + assert_eq!(false, resp.data.is_empty(), "Should not be empty"); + } + Err(err) => { + assert!(false, "Error: {:?}", err); + } + } + } + Err(err) => { + assert!(false, "Error: {:?}", err); + } + }; + + let _ = db_mgr::drop_database(&tm_pool, &db_name).await; + } }