Next queued song (#123)

* Added code to fetch next queue item

* Updated README

* Give it a go

* Minor docker compose change

* Added docker-compose defaults

* Code refactor

* Removed data from being fetched

* Added test

* Formatting
This commit was merged in pull request #123.
This commit is contained in:
KD
2025-04-26 16:11:46 -04:00
committed by GitHub
parent db7350b550
commit 5e3ca1861d
5 changed files with 172 additions and 4 deletions
+2
View File
@@ -12,4 +12,6 @@ docker compose build --ssh default api auth_api
``` ```
Bring it up Bring it up
```
docker compose up -d --force-recreate api auth_api docker compose up -d --force-recreate api auth_api
```
+4 -1
View File
@@ -3,7 +3,9 @@ version: '3.8' # Use a recent version
services: services:
# --- Web API --- # --- Web API ---
api: api:
build: . # Tells docker-compose to build the Dockerfile in the current directory build: # Tells docker-compose to build the Dockerfile in the current directory
context: .
ssh: ["default"] # Uses host's SSH agent
container_name: icarus # Optional: Give the container a specific name container_name: icarus # Optional: Give the container a specific name
ports: ports:
# Map host port 8000 to container port 3000 (adjust as needed) # Map host port 8000 to container port 3000 (adjust as needed)
@@ -22,6 +24,7 @@ services:
auth_api: auth_api:
build: build:
context: ../icarus_auth # IMPORTANT: Relative path to the local checkout of your web API repo (containing the Dockerfile) context: ../icarus_auth # IMPORTANT: Relative path to the local checkout of your web API repo (containing the Dockerfile)
ssh: ["default"] # Uses host's SSH agent
dockerfile: Dockerfile # Optional: Specify if your Dockerfile has a non-standard name dockerfile: Dockerfile # Optional: Specify if your Dockerfile has a non-standard name
container_name: auth_api container_name: auth_api
restart: unless-stopped restart: unless-stopped
+1
View File
@@ -3,5 +3,6 @@ pub mod song;
pub mod endpoints { pub mod endpoints {
pub const QUEUESONG: &str = "/api/v2/song/queue"; pub const QUEUESONG: &str = "/api/v2/song/queue";
pub const NEXTQUEUESONG: &str = "/api/v2/song/queue/next";
pub const QUEUEMETADATA: &str = "/api/v2/song/metadata/queue"; pub const QUEUEMETADATA: &str = "/api/v2/song/metadata/queue";
} }
+81 -1
View File
@@ -15,6 +15,16 @@ pub mod response {
pub message: String, pub message: String,
pub data: Vec<uuid::Uuid>, pub data: Vec<uuid::Uuid>,
} }
pub mod fetch_queue_song {
use serde::{Deserialize, Serialize};
#[derive(Default, Deserialize, Serialize)]
pub struct Response {
pub message: String,
pub data: Vec<crate::callers::song::song_queue::SongQueue>,
}
}
} }
mod song_queue { mod song_queue {
@@ -23,7 +33,7 @@ mod song_queue {
pub mod status { pub mod status {
pub const PENDING: &str = "pending"; pub const PENDING: &str = "pending";
// Will be used later on // Will be used later on
pub const _PROCESSING: &str = "processing"; pub const PROCESSING: &str = "processing";
pub const _DONE: &str = "done"; pub const _DONE: &str = "done";
} }
@@ -32,6 +42,13 @@ mod song_queue {
pub id: uuid::Uuid, pub id: uuid::Uuid,
} }
#[derive(Debug, serde::Deserialize, serde::Serialize, sqlx::FromRow)]
pub struct SongQueue {
pub id: uuid::Uuid,
pub filename: String,
pub status: String,
}
pub async fn insert( pub async fn insert(
pool: &sqlx::PgPool, pool: &sqlx::PgPool,
data: &Vec<u8>, data: &Vec<u8>,
@@ -63,6 +80,48 @@ mod song_queue {
Err(_err) => Err(sqlx::Error::RowNotFound), Err(_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#"
UPDATE "songQueue"
SET status = $1
WHERE id = (
SELECT id FROM "songQueue"
WHERE status = $2
ORDER BY id
FOR UPDATE SKIP LOCKED
LIMIT 1
)
RETURNING id, filename, status;
"#,
)
.bind(status::PROCESSING)
.bind(status::PENDING)
.fetch_one(pool)
.await
.map_err(|e| {
eprintln!("Error inserting: {}", e);
});
match result {
Ok(row) => Ok(SongQueue {
id: row
.try_get("id")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
filename: row
.try_get("filename")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
status: row
.try_get("status")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
}),
Err(_err) => Err(sqlx::Error::RowNotFound),
}
}
} }
pub mod endpoint { pub mod endpoint {
@@ -117,4 +176,25 @@ pub mod endpoint {
(StatusCode::OK, Json(response)) (StatusCode::OK, Json(response))
} }
pub async fn fetch_queue_song(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
) -> (
StatusCode,
Json<super::response::fetch_queue_song::Response>,
) {
let mut response = super::response::fetch_queue_song::Response::default();
match song_queue::get_most_recent_and_update(&pool).await {
Ok(item) => {
response.message = String::from("Successful");
response.data.push(item);
(StatusCode::OK, Json(response))
}
Err(err) => {
response.message = err.to_string();
(StatusCode::BAD_REQUEST, Json(response))
}
}
}
} }
+82
View File
@@ -69,6 +69,10 @@ pub mod init {
crate::callers::endpoints::QUEUESONG, crate::callers::endpoints::QUEUESONG,
post(crate::callers::song::endpoint::queue_song), post(crate::callers::song::endpoint::queue_song),
) )
.route(
crate::callers::endpoints::NEXTQUEUESONG,
get(crate::callers::song::endpoint::fetch_queue_song),
)
.route( .route(
crate::callers::endpoints::QUEUEMETADATA, crate::callers::endpoints::QUEUEMETADATA,
post(crate::callers::metadata::endpoint::queue_metadata), post(crate::callers::metadata::endpoint::queue_metadata),
@@ -250,6 +254,84 @@ mod tests {
let _ = db_mgr::drop_database(&tm_pool, &db_name).await; let _ = db_mgr::drop_database(&tm_pool, &db_name).await;
} }
#[tokio::test]
async fn test_song_fetch_queue_item() {
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 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 {
Ok(response) => {
let body = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
let resp: crate::callers::song::response::fetch_queue_song::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;
}
#[tokio::test] #[tokio::test]
async fn test_song_metadata_queue() { async fn test_song_metadata_queue() {
let tm_pool = db_mgr::get_pool().await.unwrap(); let tm_pool = db_mgr::get_pool().await.unwrap();