From 0f00d89809943a79152ed2812f9e7d4b95ecf647 Mon Sep 17 00:00:00 2001 From: kdeng00 Date: Sat, 26 Apr 2025 17:46:38 -0400 Subject: [PATCH 1/6] Added code --- src/callers/song.rs | 161 +++++++++++++++++++++++++++++++++++++++++++- src/main.rs | 4 ++ 2 files changed, 164 insertions(+), 1 deletion(-) diff --git a/src/callers/song.rs b/src/callers/song.rs index d914a55..8ff144c 100644 --- a/src/callers/song.rs +++ b/src/callers/song.rs @@ -122,10 +122,36 @@ mod song_queue { Err(_err) => Err(sqlx::Error::RowNotFound), } } + + pub async fn get_data(pool: &sqlx::PgPool, id: &uuid::Uuid) -> Result, sqlx::Error> { + let result = sqlx::query( + r#" + SELECT data FROM "songQueue" + WHERE id = $1; + "#, + ) + .bind(id) + .fetch_one(pool) + .await + .map_err(|e| { + eprintln!("Error inserting: {}", e); + }); + + match result { + Ok(row) => { + let data = row + .try_get("data") + .map_err(|_e| sqlx::Error::RowNotFound) + .unwrap(); + Ok(data) + } + Err(_err) => Err(sqlx::Error::RowNotFound), + } + } } pub mod endpoint { - use axum::{Json, http::StatusCode}; + use axum::{Json, http::StatusCode, response::IntoResponse}; use std::io::Write; use crate::callers::song::song_queue; @@ -197,4 +223,137 @@ pub mod endpoint { } } } + + /* + use axum::{ + response::{Response, IntoResponse}, + routing::get, + Router, + extract::Path, + http::{header, StatusCode, Uri}, +}; +use std::path::{Path, PathBuf}; +use tokio::fs::File; +use tokio_util::io::ReaderStream; +use mime_guess::from_path; +use uuid::Uuid; + +// Configuration constants +const MEDIA_DIRECTORY: &str = "./media"; +const ALLOWED_EXTENSION: &str = "flac"; +*/ + + pub async fn download_flac( + axum::Extension(pool): axum::Extension, + axum::extract::Path(id): axum::extract::Path) -> (StatusCode, axum::response::Response) { + pritnln!("Id: {:?}", id); + + match song_queue::get_data(&pool, &id).await { + Ok(data) => { + let by = axum::body::Bytes::from(data); + /* + match axum::response::Response::builder() + .status(StatusCode::OK) + .header( + axum::http::header::CONTENT_TYPE, + "audio/flac", + ) + .header( + axum::http::header::CONTENT_DISPOSITION, + format!("attachment; filename=\"{}.flac\"", id), + ) + .header(axum::http::header::CONTENT_LENGTH, by.len()) + .body(by) { + Ok(resp) => { + (StatusCode::OK, resp) + } + Err(err) => { + } + } + */ + let mut response = by.into_response(); + let headers = response.headers_mut(); + headers.insert( + axum::http::header::CONTENT_TYPE, + "audio/flac".parse().unwrap(), + ); + headers.insert( + axum::http::header::CONTENT_DISPOSITION, + format!("attachment; filename=\"{}.flac\"", id).parse().unwrap(), + ); + + (StatusCode::OK, response) + } + Err(_err) => { + (StatusCode::BAD_REQUEST, axum::response::Response::default()) + } + } + // Construct the file path + /* + let file_name = format!("{}.{}", id, ALLOWED_EXTENSION); + let file_path = PathBuf::from(MEDIA_DIRECTORY).join(&file_name); + + // Security check: prevent path traversal + if !file_path.starts_with(MEDIA_DIRECTORY) { + return Err(( + StatusCode::BAD_REQUEST, + "Invalid file path".to_string(), + )); + } + + // Get file metadata + let metadata = match tokio::fs::metadata(&file_path).await { + Ok(meta) => meta, + Err(err) if err.kind() == std::io::ErrorKind::NotFound => { + return Err(( + StatusCode::NOT_FOUND, + "File not found".to_string(), + )); + } + Err(err) => { + return Err(( + StatusCode::INTERNAL_SERVER_ERROR, + format!("Failed to read file: {}", err), + )); + } + }; + + // Verify this is a FLAC file (extension check) + if file_path.extension().map(|ext| ext != ALLOWED_EXTENSION).unwrap_or(true) { + return Err(( + StatusCode::BAD_REQUEST, + "Invalid file type".to_string(), + )); + } + + // Open the file + let file = match File::open(&file_path).await { + Ok(file) => file, + Err(err) => { + return Err(( + StatusCode::INTERNAL_SERVER_ERROR, + format!("Failed to open file: {}", err), + )); + } + }; + + // Create stream from file + let stream = ReaderStream::new(file); + + // Build response + axum::response::Response::builder() + .status(StatusCode::OK) + .header( + header::CONTENT_TYPE, + "audio/flac", // Specific MIME type for FLAC + ) + .header( + header::CONTENT_DISPOSITION, + format!("attachment; filename=\"{}\"", file_name), + ) + .header(header::CONTENT_LENGTH, metadata.len()) + .body(axum::body::Body::from_stream(stream)) + .unwrap()) + */ + } } diff --git a/src/main.rs b/src/main.rs index f3cc9e2..1075ae1 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::QUEUESONG, + get(crate::callers::song::endpoint::download_flac), + ) .route( crate::callers::endpoints::NEXTQUEUESONG, get(crate::callers::song::endpoint::fetch_queue_song), -- 2.47.3 From 9d8bfbf7c8e88cc58afae36cfb5d3622fbb6a437 Mon Sep 17 00:00:00 2001 From: kdeng00 Date: Sat, 26 Apr 2025 18:00:13 -0400 Subject: [PATCH 2/6] Got it working --- src/callers/mod.rs | 1 + src/callers/song.rs | 2 +- src/main.rs | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/callers/mod.rs b/src/callers/mod.rs index e6ff83a..aac314c 100644 --- a/src/callers/mod.rs +++ b/src/callers/mod.rs @@ -3,6 +3,7 @@ pub mod song; pub mod endpoints { pub const QUEUESONG: &str = "/api/v2/song/queue"; + pub const QUEUESONGDATA: &str = "/api/v2/song/queue/{id}"; pub const NEXTQUEUESONG: &str = "/api/v2/song/queue/next"; pub const QUEUEMETADATA: &str = "/api/v2/song/metadata/queue"; } diff --git a/src/callers/song.rs b/src/callers/song.rs index 8ff144c..81b3a28 100644 --- a/src/callers/song.rs +++ b/src/callers/song.rs @@ -246,7 +246,7 @@ const ALLOWED_EXTENSION: &str = "flac"; pub async fn download_flac( axum::Extension(pool): axum::Extension, axum::extract::Path(id): axum::extract::Path) -> (StatusCode, axum::response::Response) { - pritnln!("Id: {:?}", id); + println!("Id: {:?}", id); match song_queue::get_data(&pool, &id).await { Ok(data) => { diff --git a/src/main.rs b/src/main.rs index 1075ae1..09541e6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -70,7 +70,7 @@ pub mod init { post(crate::callers::song::endpoint::queue_song), ) .route( - crate::callers::endpoints::QUEUESONG, + crate::callers::endpoints::QUEUESONGDATA, get(crate::callers::song::endpoint::download_flac), ) .route( -- 2.47.3 From f806ac0eafbb65d209cc39cd22843d38b540b1f4 Mon Sep 17 00:00:00 2001 From: kdeng00 Date: Sat, 26 Apr 2025 18:27:22 -0400 Subject: [PATCH 3/6] Added test and refactored test code --- src/main.rs | 107 +++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 98 insertions(+), 9 deletions(-) diff --git a/src/main.rs b/src/main.rs index 09541e6..f19844e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -231,11 +231,41 @@ mod tests { app.clone().oneshot(req).await } + async fn fetch_queue_req(app: &axum::Router,) -> Result { + let fetch_req = axum::http::Request::builder() + .method(axum::http::Method::GET) + .uri(crate::callers::endpoints::NEXTQUEUESONG) + .header(axum::http::header::CONTENT_TYPE, "application/json") + .body(axum::body::Body::empty()) + .unwrap(); + app.clone().oneshot(fetch_req).await + } + + async fn fetch_queue_data_req(app: &axum::Router, id: &uuid::Uuid) -> Result { + let raw_uri = String::from(crate::callers::endpoints::QUEUESONGDATA); + let end_index = raw_uri.len() - 4; + let mut uri: String = (&raw_uri[..end_index]).to_string(); + uri += &id.to_string(); + let req = axum::http::Request::builder() + .method(axum::http::Method::GET) + .uri(uri) + .header(axum::http::header::CONTENT_TYPE, "audio/flac") + .body(axum::body::Body::empty()) + .unwrap(); + + app.clone().oneshot(req).await + } + + pub async fn resp_to_bytes(response: axum::response::Response) -> Result { + axum::body::to_bytes(response.into_body(), usize::MAX) + .await + } + pub async fn get_resp_data(response: axum::response::Response) -> Data where Data: for<'a> serde::Deserialize<'a>, { - let body = axum::body::to_bytes(response.into_body(), usize::MAX) + let body = resp_to_bytes(response) .await .unwrap(); serde_json::from_slice(&body).unwrap() @@ -303,14 +333,7 @@ mod tests { assert_eq!(false, resp.data.is_empty(), "Should not be empty"); assert_eq!(false, resp.data[0].is_nil(), "Should not be empty"); - let fetch_req = axum::http::Request::builder() - .method(axum::http::Method::GET) - .uri(crate::callers::endpoints::NEXTQUEUESONG) - .header(axum::http::header::CONTENT_TYPE, "application/json") - .body(axum::body::Body::empty()) - .unwrap(); - - match app.clone().oneshot(fetch_req).await { + match fetch_queue_req(&app).await { Ok(response) => { let resp = get_resp_data::< crate::callers::song::response::fetch_queue_song::Response, @@ -331,6 +354,72 @@ mod tests { let _ = db_mgr::drop_database(&tm_pool, &db_name).await; } + #[tokio::test] + async fn test_song_fetch_queue_data() { + 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 = init::app(pool).await; + + // Send request + match song_queue_req(&app).await { + Ok(response) => { + let resp = + get_resp_data::(response).await; + assert_eq!(false, resp.data.is_empty(), "Should not be empty"); + assert_eq!(false, resp.data[0].is_nil(), "Should not be empty"); + + match fetch_queue_req(&app).await { + Ok(response) => { + let resp = get_resp_data::< + crate::callers::song::response::fetch_queue_song::Response, + >(response) + .await; + assert_eq!(false, resp.data.is_empty(), "Should not be empty"); + let id = resp.data[0].id; + + match fetch_queue_data_req(&app, &id).await { + Ok(response) => { + // let _resp = get_resp_data::>(response).await; + match resp_to_bytes(response).await { + Ok(bytes) => { + assert_eq!(false, bytes.is_empty(), "Queued data should not be empty"); + } + Err(err) => { + assert!(false, "Error: {:?}", err); + } + } + } + Err(err) => { + assert!(false, "Error: {:?}", err); + } + } + } + Err(err) => { + assert!(false, "Error: {:?}", err); + } + } + } + Err(err) => { + assert!(false, "Error: {:?}", err); + } + }; + + 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(); -- 2.47.3 From 802dfcae827e8b608a7c0dd1ddd641adcf9d6bda Mon Sep 17 00:00:00 2001 From: kdeng00 Date: Sat, 26 Apr 2025 18:28:39 -0400 Subject: [PATCH 4/6] Removed comment --- src/main.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index f19844e..837d6bd 100644 --- a/src/main.rs +++ b/src/main.rs @@ -392,7 +392,6 @@ mod tests { match fetch_queue_data_req(&app, &id).await { Ok(response) => { - // let _resp = get_resp_data::>(response).await; match resp_to_bytes(response).await { Ok(bytes) => { assert_eq!(false, bytes.is_empty(), "Queued data should not be empty"); -- 2.47.3 From 8a017e346e858af4ff3e99f605dded80eff6b1f5 Mon Sep 17 00:00:00 2001 From: kdeng00 Date: Sat, 26 Apr 2025 18:29:55 -0400 Subject: [PATCH 5/6] Cleanup --- src/callers/song.rs | 106 -------------------------------------------- 1 file changed, 106 deletions(-) diff --git a/src/callers/song.rs b/src/callers/song.rs index 81b3a28..cc7ce36 100644 --- a/src/callers/song.rs +++ b/src/callers/song.rs @@ -224,25 +224,6 @@ pub mod endpoint { } } - /* - use axum::{ - response::{Response, IntoResponse}, - routing::get, - Router, - extract::Path, - http::{header, StatusCode, Uri}, -}; -use std::path::{Path, PathBuf}; -use tokio::fs::File; -use tokio_util::io::ReaderStream; -use mime_guess::from_path; -use uuid::Uuid; - -// Configuration constants -const MEDIA_DIRECTORY: &str = "./media"; -const ALLOWED_EXTENSION: &str = "flac"; -*/ - pub async fn download_flac( axum::Extension(pool): axum::Extension, axum::extract::Path(id): axum::extract::Path) -> (StatusCode, axum::response::Response) { @@ -251,26 +232,6 @@ const ALLOWED_EXTENSION: &str = "flac"; match song_queue::get_data(&pool, &id).await { Ok(data) => { let by = axum::body::Bytes::from(data); - /* - match axum::response::Response::builder() - .status(StatusCode::OK) - .header( - axum::http::header::CONTENT_TYPE, - "audio/flac", - ) - .header( - axum::http::header::CONTENT_DISPOSITION, - format!("attachment; filename=\"{}.flac\"", id), - ) - .header(axum::http::header::CONTENT_LENGTH, by.len()) - .body(by) { - Ok(resp) => { - (StatusCode::OK, resp) - } - Err(err) => { - } - } - */ let mut response = by.into_response(); let headers = response.headers_mut(); headers.insert( @@ -288,72 +249,5 @@ const ALLOWED_EXTENSION: &str = "flac"; (StatusCode::BAD_REQUEST, axum::response::Response::default()) } } - // Construct the file path - /* - let file_name = format!("{}.{}", id, ALLOWED_EXTENSION); - let file_path = PathBuf::from(MEDIA_DIRECTORY).join(&file_name); - - // Security check: prevent path traversal - if !file_path.starts_with(MEDIA_DIRECTORY) { - return Err(( - StatusCode::BAD_REQUEST, - "Invalid file path".to_string(), - )); - } - - // Get file metadata - let metadata = match tokio::fs::metadata(&file_path).await { - Ok(meta) => meta, - Err(err) if err.kind() == std::io::ErrorKind::NotFound => { - return Err(( - StatusCode::NOT_FOUND, - "File not found".to_string(), - )); - } - Err(err) => { - return Err(( - StatusCode::INTERNAL_SERVER_ERROR, - format!("Failed to read file: {}", err), - )); - } - }; - - // Verify this is a FLAC file (extension check) - if file_path.extension().map(|ext| ext != ALLOWED_EXTENSION).unwrap_or(true) { - return Err(( - StatusCode::BAD_REQUEST, - "Invalid file type".to_string(), - )); - } - - // Open the file - let file = match File::open(&file_path).await { - Ok(file) => file, - Err(err) => { - return Err(( - StatusCode::INTERNAL_SERVER_ERROR, - format!("Failed to open file: {}", err), - )); - } - }; - - // Create stream from file - let stream = ReaderStream::new(file); - - // Build response - axum::response::Response::builder() - .status(StatusCode::OK) - .header( - header::CONTENT_TYPE, - "audio/flac", // Specific MIME type for FLAC - ) - .header( - header::CONTENT_DISPOSITION, - format!("attachment; filename=\"{}\"", file_name), - ) - .header(header::CONTENT_LENGTH, metadata.len()) - .body(axum::body::Body::from_stream(stream)) - .unwrap()) - */ } } -- 2.47.3 From a8076ddcf4c94c71c0e559fe4d5fe44322b6bc51 Mon Sep 17 00:00:00 2001 From: kdeng00 Date: Sat, 26 Apr 2025 18:30:58 -0400 Subject: [PATCH 6/6] Code formatting --- src/callers/song.rs | 11 +++++----- src/main.rs | 52 +++++++++++++++++++++++++-------------------- 2 files changed, 35 insertions(+), 28 deletions(-) diff --git a/src/callers/song.rs b/src/callers/song.rs index cc7ce36..0f4872d 100644 --- a/src/callers/song.rs +++ b/src/callers/song.rs @@ -226,7 +226,8 @@ pub mod endpoint { pub async fn download_flac( axum::Extension(pool): axum::Extension, - axum::extract::Path(id): axum::extract::Path) -> (StatusCode, axum::response::Response) { + axum::extract::Path(id): axum::extract::Path, + ) -> (StatusCode, axum::response::Response) { println!("Id: {:?}", id); match song_queue::get_data(&pool, &id).await { @@ -240,14 +241,14 @@ pub mod endpoint { ); headers.insert( axum::http::header::CONTENT_DISPOSITION, - format!("attachment; filename=\"{}.flac\"", id).parse().unwrap(), + format!("attachment; filename=\"{}.flac\"", id) + .parse() + .unwrap(), ); (StatusCode::OK, response) } - Err(_err) => { - (StatusCode::BAD_REQUEST, axum::response::Response::default()) - } + Err(_err) => (StatusCode::BAD_REQUEST, axum::response::Response::default()), } } } diff --git a/src/main.rs b/src/main.rs index 837d6bd..5a12085 100644 --- a/src/main.rs +++ b/src/main.rs @@ -231,17 +231,22 @@ mod tests { app.clone().oneshot(req).await } - async fn fetch_queue_req(app: &axum::Router,) -> Result { - let fetch_req = axum::http::Request::builder() - .method(axum::http::Method::GET) - .uri(crate::callers::endpoints::NEXTQUEUESONG) - .header(axum::http::header::CONTENT_TYPE, "application/json") - .body(axum::body::Body::empty()) - .unwrap(); + async fn fetch_queue_req( + app: &axum::Router, + ) -> Result { + let fetch_req = axum::http::Request::builder() + .method(axum::http::Method::GET) + .uri(crate::callers::endpoints::NEXTQUEUESONG) + .header(axum::http::header::CONTENT_TYPE, "application/json") + .body(axum::body::Body::empty()) + .unwrap(); app.clone().oneshot(fetch_req).await } - async fn fetch_queue_data_req(app: &axum::Router, id: &uuid::Uuid) -> Result { + async fn fetch_queue_data_req( + app: &axum::Router, + id: &uuid::Uuid, + ) -> Result { let raw_uri = String::from(crate::callers::endpoints::QUEUESONGDATA); let end_index = raw_uri.len() - 4; let mut uri: String = (&raw_uri[..end_index]).to_string(); @@ -256,18 +261,17 @@ mod tests { app.clone().oneshot(req).await } - pub async fn resp_to_bytes(response: axum::response::Response) -> Result { - axum::body::to_bytes(response.into_body(), usize::MAX) - .await + pub async fn resp_to_bytes( + response: axum::response::Response, + ) -> Result { + axum::body::to_bytes(response.into_body(), usize::MAX).await } pub async fn get_resp_data(response: axum::response::Response) -> Data where Data: for<'a> serde::Deserialize<'a>, { - let body = resp_to_bytes(response) - .await - .unwrap(); + let body = resp_to_bytes(response).await.unwrap(); serde_json::from_slice(&body).unwrap() } @@ -391,16 +395,18 @@ mod tests { let id = resp.data[0].id; match fetch_queue_data_req(&app, &id).await { - Ok(response) => { - match resp_to_bytes(response).await { - Ok(bytes) => { - assert_eq!(false, bytes.is_empty(), "Queued data should not be empty"); - } - Err(err) => { - assert!(false, "Error: {:?}", err); - } + Ok(response) => match resp_to_bytes(response).await { + Ok(bytes) => { + assert_eq!( + false, + bytes.is_empty(), + "Queued data should not be empty" + ); } - } + Err(err) => { + assert!(false, "Error: {:?}", err); + } + }, Err(err) => { assert!(false, "Error: {:?}", err); } -- 2.47.3