Updating song from queue (#132)

* Added endpoint - no code - for updating the song from the queue

* Added endpoint to update song from queue

* Endpoint is now available

* Fixed endoint uri

* Added tempfile crate for tests

* Test is working

* Test is operational

* Code formatting

* Code cleanup
This commit was merged in pull request #132.
This commit is contained in:
KD
2025-05-22 16:18:12 -04:00
committed by GitHub
parent b2a4faec76
commit d4c025511d
4 changed files with 208 additions and 1 deletions
+1
View File
@@ -25,3 +25,4 @@ icarus_models = { git = "ssh://git@git.kundeng.us/phoenix/icarus_models.git", ta
[dev-dependencies]
common-multipart-rfc7578 = { version = "0.7.0" }
url = { version = "2.5.4" }
tempfile = { version = "3.19.1" }
+1
View File
@@ -5,6 +5,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 QUEUESONGUPDATE: &str = "/api/v2/song/queue/{id}";
pub const NEXTQUEUESONG: &str = "/api/v2/song/queue/next";
pub const QUEUEMETADATA: &str = "/api/v2/song/metadata/queue";
pub const QUEUECOVERART: &str = "/api/v2/coverart/queue";
+76
View File
@@ -47,6 +47,14 @@ pub mod response {
pub data: Vec<ChangedStatus>,
}
}
pub mod update_song_queue {
#[derive(Default, serde::Deserialize, serde::Serialize)]
pub struct Response {
pub message: String,
pub data: Vec<Vec<u8>>,
}
}
}
pub mod status {
@@ -106,6 +114,33 @@ mod song_queue {
}
}
pub async fn update(
pool: &sqlx::PgPool,
data: &Vec<u8>,
id: &uuid::Uuid,
) -> Result<Vec<u8>, sqlx::Error> {
let result = sqlx::query(
r#"
UPDATE "songQueue" SET data = $1 WHERE id = $2 RETURNING data;
"#,
)
.bind(data)
.bind(id)
.fetch_one(pool)
.await
.map_err(|e| {
eprintln!("Error inserting: {:?}", e);
});
match result {
Ok(row) => Ok(row
.try_get("data")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap()),
Err(_) => Err(sqlx::Error::RowNotFound),
}
}
pub async fn get_most_recent_and_update(pool: &sqlx::PgPool) -> Result<SongQueue, sqlx::Error> {
let result = sqlx::query(
r#"
@@ -380,4 +415,45 @@ pub mod endpoint {
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
}
pub async fn update_song_queue(
axum::extract::Path(id): axum::extract::Path<uuid::Uuid>,
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
mut multipart: axum::extract::Multipart,
) -> (
axum::http::StatusCode,
axum::Json<super::response::update_song_queue::Response>,
) {
let mut response = super::response::update_song_queue::Response::default();
if let Some(field) = multipart.next_field().await.unwrap() {
let name = field.name().unwrap().to_string();
let file_name = field.file_name().unwrap().to_string();
let content_type = field.content_type().unwrap().to_string();
let data = field.bytes().await.unwrap();
println!(
"Received file '{}' (name = '{}', content-type = '{}', size = {})",
file_name,
name,
content_type,
data.len()
);
let raw_data: Vec<u8> = data.to_vec();
match song_queue::update(&pool, &raw_data, &id).await {
Ok(queued_data) => {
response.data.push(queued_data);
(axum::http::StatusCode::OK, axum::Json(response))
}
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
}
} else {
response.message = String::from("No data provided");
(axum::http::StatusCode::NOT_FOUND, axum::Json(response))
}
}
}
+130 -1
View File
@@ -81,6 +81,10 @@ pub mod init {
crate::callers::endpoints::NEXTQUEUESONG,
get(crate::callers::song::endpoint::fetch_queue_song),
)
.route(
crate::callers::endpoints::QUEUESONGUPDATE,
patch(crate::callers::song::endpoint::update_song_queue),
)
.route(
crate::callers::endpoints::QUEUEMETADATA,
post(crate::callers::metadata::endpoint::queue_metadata),
@@ -142,10 +146,12 @@ pub async fn root() -> &'static str {
mod tests {
use crate::db;
use std::io::Write;
use std::usize;
use common_multipart_rfc7578::client::multipart::{
Body as MultipartBody, Form as MultipartForm,
};
use std::usize;
use tower::ServiceExt;
mod db_mgr {
@@ -1070,4 +1076,127 @@ mod tests {
let _ = db_mgr::drop_database(&tm_pool, &db_name).await;
}
#[tokio::test]
async fn test_update_song_from_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 = init::app(pool).await;
// Send request
match song_queue_req(&app).await {
Ok(response) => {
let resp =
get_resp_data::<crate::callers::song::response::Response>(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) => match resp_to_bytes(response).await {
Ok(bytes) => {
assert_eq!(
false,
bytes.is_empty(),
"Queued data should not be empty"
);
let temp_file = tempfile::tempdir()
.expect("Could not create test directory");
let test_dir = String::from(temp_file.path().to_str().unwrap());
let new_file = format!("{}/new_file.flac", test_dir);
let mut file = std::fs::File::create(&new_file).unwrap();
file.write_all(&bytes).unwrap();
let mut form = MultipartForm::default();
let _ = form.add_file("flac", new_file);
// Create request
let content_type = form.content_type();
let body = MultipartBody::from(form);
let raw_uri =
String::from(crate::callers::endpoints::QUEUESONGUPDATE);
let end_index = raw_uri.len() - 5;
let uri = format!(
"{}/{}",
(&raw_uri[..end_index]).to_string(),
id.to_string()
);
match app
.clone()
.oneshot(
axum::http::Request::builder()
.method(axum::http::Method::PATCH)
.uri(uri)
.header(
axum::http::header::CONTENT_TYPE,
content_type,
)
.body(axum::body::Body::from_stream(body))
.unwrap(),
)
.await
{
Ok(response) => {
let resp = get_resp_data::<
crate::callers::song::response::update_song_queue::Response,
>(response)
.await;
assert_eq!(
false,
resp.data.is_empty(),
"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);
}
}
}
Err(err) => {
assert!(false, "Error: {:?}", err);
}
};
let _ = db_mgr::drop_database(&tm_pool, &db_name).await;
}
}