Compare commits

..

5 Commits

Author SHA1 Message Date
KD ee400fe4eb Merge ecd5705272 into 34e292bea9 2025-07-23 01:49:47 +00:00
kdeng00 ecd5705272 Syntax change 2025-07-22 21:48:40 -04:00
kdeng00 226a475e75 File extension change 2025-07-22 21:46:18 -04:00
kdeng00 c8108cfb39 Temp change 2025-07-22 21:43:25 -04:00
kdeng00 3deb6983b0 Added release workflow 2025-07-22 21:41:26 -04:00
25 changed files with 37 additions and 1249 deletions
+2
View File
@@ -3,6 +3,8 @@ name: Release Tagging
on:
push:
branches: [ "v0.2" ]
pull_request:
branches: [ "v0.2" ]
jobs:
release:
+1 -1
View File
@@ -68,7 +68,7 @@ jobs:
env:
ROOT_DIRECTORY: "/tmp"
DATABASE_URL: "postgres://${{ secrets.POSTGRES_USER }}:${{ secrets.POSTGRES_PASSWORD }}@localhost:5432/${{ secrets.POSTGRES_DB }}"
run: cargo test --verbose --
run: cargo test --verbose
- name: Run clippy
run: cargo clippy -- -D warnings
-8
View File
@@ -1,8 +0,0 @@
{
"dev": {
"migrations": "./migrations"
},
"test": {
"migrations": "./test_migrations"
}
}
Generated
+3 -18
View File
@@ -630,16 +630,6 @@ dependencies = [
"hashbrown",
]
[[package]]
name = "hdrhistogram"
version = "7.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "765c9198f173dd59ce26ff9f95ef0aafd0a0fe01fb9d72841bc5066a4c06511d"
dependencies = [
"byteorder",
"num-traits",
]
[[package]]
name = "heck"
version = "0.5.0"
@@ -762,7 +752,7 @@ dependencies = [
[[package]]
name = "icarus"
version = "0.1.100"
version = "0.1.93"
dependencies = [
"axum",
"common-multipart-rfc7578",
@@ -770,7 +760,6 @@ dependencies = [
"icarus_envy",
"icarus_meta",
"icarus_models",
"mime_guess",
"serde",
"serde_json",
"sqlx",
@@ -804,8 +793,8 @@ dependencies = [
[[package]]
name = "icarus_models"
version = "0.5.1"
source = "git+ssh://git@git.kundeng.us/phoenix/icarus_models.git?tag=v0.5.1-devel-1c5de9dc26-111#1c5de9dc26099ac5f21e1dc7a1f7d0dbb892b34b"
version = "0.4.5"
source = "git+ssh://git@git.kundeng.us/phoenix/icarus_models.git?tag=v0.4.5-devel-655d05dabb-111#655d05dabbdadb9b28940564a1eb82470aa4f166"
dependencies = [
"rand 0.9.1",
"serde",
@@ -2136,13 +2125,9 @@ checksum = "d039ad9159c98b70ecfd540b2573b97f7f52c3e8d9f8ad57a24b916a536975f9"
dependencies = [
"futures-core",
"futures-util",
"hdrhistogram",
"indexmap",
"pin-project-lite",
"slab",
"sync_wrapper",
"tokio",
"tokio-util",
"tower-layer",
"tower-service",
"tracing",
+4 -5
View File
@@ -1,6 +1,6 @@
[package]
name = "icarus"
version = "0.1.100"
version = "0.1.93"
edition = "2024"
rust-version = "1.88"
@@ -8,18 +8,17 @@ rust-version = "1.88"
axum = { version = "0.8.4", features = ["multipart"] }
serde = { version = "1.0.219", features = ["derive"] }
serde_json = { version = "1.0.140" }
tower = { version = "0.5.2", features = ["full"] }
tower = { version = "0.5.2" }
tokio = { version = "1.45.1", features = ["full"] }
tokio-util = { version = "0.7.15", features = ["io"] }
tokio-util = { version = "0.7.15" }
tower-http = { version = "0.6.6", features = ["timeout"] }
tracing-subscriber = "0.3.19"
futures = { version = "0.3.31" }
mime_guess = { version = "2.0.5" }
uuid = { version = "1.17.0", features = ["v4", "serde"] }
sqlx = { version = "0.8.6", features = ["postgres", "runtime-tokio-native-tls", "time", "uuid"] }
time = { version = "0.3.41", features = ["formatting", "macros", "parsing", "serde"] }
icarus_meta = { git = "ssh://git@git.kundeng.us/phoenix/icarus_meta.git", tag = "v0.3.0-devel-f4b71de969-680" }
icarus_models = { git = "ssh://git@git.kundeng.us/phoenix/icarus_models.git", tag = "v0.5.1-devel-1c5de9dc26-111" }
icarus_models = { git = "ssh://git@git.kundeng.us/phoenix/icarus_models.git", tag = "v0.4.5-devel-655d05dabb-111" }
icarus_envy = { git = "ssh://git@git.kundeng.us/phoenix/icarus_envy.git", tag = "v0.3.0-devel-d73fba9899-006" }
[dev-dependencies]
-204
View File
@@ -45,13 +45,6 @@ pub mod request {
pub coverart_queue_id: uuid::Uuid,
}
}
pub mod get_coverart {
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct Params {
pub id: Option<uuid::Uuid>,
}
}
}
pub mod response {
@@ -106,14 +99,6 @@ pub mod response {
pub data: Vec<uuid::Uuid>,
}
}
pub mod get_coverart {
#[derive(Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct Response {
pub message: String,
pub data: Vec<icarus_models::coverart::CoverArt>,
}
}
}
pub mod db {
@@ -336,128 +321,6 @@ pub mod cov_db {
Err(_err) => Err(sqlx::Error::RowNotFound),
}
}
pub async fn get_coverart(
pool: &sqlx::PgPool,
id: &uuid::Uuid,
) -> Result<icarus_models::coverart::CoverArt, sqlx::Error> {
let result = sqlx::query(
r#"
SELECT id, title, path, song_id FROM "coverart" WHERE id = $1;
"#,
)
.bind(id)
.fetch_one(pool)
.await
.map_err(|e| {
eprintln!("Error querying data: {e:?}");
});
match result {
Ok(row) => Ok(icarus_models::coverart::CoverArt {
id: row
.try_get("id")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
title: row
.try_get("title")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
path: row
.try_get("path")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
data: Vec::new(),
song_id: row
.try_get("song_id")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
}),
Err(_) => Err(sqlx::Error::RowNotFound),
}
}
pub async fn get_coverart_with_song_id(
pool: &sqlx::PgPool,
song_id: &uuid::Uuid,
) -> Result<icarus_models::coverart::CoverArt, sqlx::Error> {
let result = sqlx::query(
r#"
SELECT id, title, path, song_id FROM "coverart" WHERE song_id = $1;
"#,
)
.bind(song_id)
.fetch_one(pool)
.await
.map_err(|e| {
eprintln!("Error querying data: {e:?}");
});
match result {
Ok(row) => Ok(icarus_models::coverart::CoverArt {
id: row
.try_get("id")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
title: row
.try_get("title")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
path: row
.try_get("path")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
data: Vec::new(),
song_id: row
.try_get("song_id")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
}),
Err(_) => Err(sqlx::Error::RowNotFound),
}
}
pub async fn delete_coverart(
pool: &sqlx::PgPool,
id: &uuid::Uuid,
) -> Result<icarus_models::coverart::CoverArt, sqlx::Error> {
let result = sqlx::query(
r#"
DELETE FROM "coverart"
WHERE id = $1
RETURNING id, title, path, song_id
"#,
)
.bind(id)
.fetch_one(pool)
.await
.map_err(|e| {
eprintln!("Error deleting data: {e:?}");
});
match result {
Ok(row) => Ok(icarus_models::coverart::CoverArt {
id: row
.try_get("id")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
title: row
.try_get("title")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
path: row
.try_get("path")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
song_id: row
.try_get("song_id")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
data: Vec::new(),
}),
Err(_err) => Err(sqlx::Error::RowNotFound),
}
}
}
pub mod endpoint {
@@ -644,10 +507,7 @@ pub mod endpoint {
match super::cov_db::create(&pool, &coverart, &song.id).await {
Ok(id) => {
// TODO: Populate song_id
coverart.id = id;
println!("Cover Art created");
response.message = String::from("Successful");
response.data.push(coverart);
@@ -700,68 +560,4 @@ pub mod endpoint {
}
}
}
pub async fn get_coverart(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::extract::Query(params): axum::extract::Query<super::request::get_coverart::Params>,
) -> (
axum::http::StatusCode,
axum::Json<super::response::get_coverart::Response>,
) {
let mut response = super::response::get_coverart::Response::default();
match params.id {
Some(id) => match super::cov_db::get_coverart(&pool, &id).await {
Ok(coverart) => {
response.data.push(coverart);
response.message = String::from(super::super::response::SUCCESSFUL);
(axum::http::StatusCode::OK, axum::Json(response))
}
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
},
None => {
response.message = String::from("Invalid parameters");
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
}
}
pub async fn download_coverart(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::extract::Path(id): axum::extract::Path<uuid::Uuid>,
) -> (axum::http::StatusCode, axum::response::Response) {
match super::cov_db::get_coverart(&pool, &id).await {
Ok(coverart) => match coverart.to_data() {
Ok(data) => {
let bytes = axum::body::Bytes::from(data);
let mut response = bytes.into_response();
let headers = response.headers_mut();
// TODO: Address hard coding
headers.insert(
axum::http::header::CONTENT_TYPE,
"audio/jpg".parse().unwrap(),
);
headers.insert(
axum::http::header::CONTENT_DISPOSITION,
format!("attachment; filename=\"{id}.jpg\"")
.parse()
.unwrap(),
);
(axum::http::StatusCode::OK, response)
}
Err(_err) => (
axum::http::StatusCode::NOT_FOUND,
axum::response::Response::default(),
),
},
Err(_err) => (
axum::http::StatusCode::NOT_FOUND,
axum::response::Response::default(),
),
}
}
}
-6
View File
@@ -16,13 +16,7 @@ pub mod endpoints {
pub const QUEUECOVERARTDATAWIPE: &str = "/api/v2/coverart/queue/data/wipe";
pub const CREATESONG: &str = "/api/v2/song";
pub const GETSONGS: &str = "/api/v2/song";
pub const STREAMSONG: &str = "/api/v2/song/stream/{id}";
pub const DOWNLOADSONG: &str = "/api/v2/song/download/{id}";
pub const DELETESONG: &str = "/api/v2/song/{id}";
pub const CREATECOVERART: &str = "/api/v2/coverart";
pub const GETCOVERART: &str = "/api/v2/coverart";
pub const DOWNLOADCOVERART: &str = "/api/v2/coverart/download/{id}";
}
pub mod response {
-336
View File
@@ -92,13 +92,6 @@ pub mod request {
pub user_id: uuid::Uuid,
}
}
pub mod get_songs {
#[derive(Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct Params {
pub id: Option<uuid::Uuid>,
}
}
}
pub mod response {
@@ -165,28 +158,6 @@ pub mod response {
pub data: Vec<uuid::Uuid>,
}
}
pub mod get_songs {
#[derive(Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct Response {
pub message: String,
pub data: Vec<icarus_models::song::Song>,
}
}
pub mod delete_song {
#[derive(Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct SongAndCoverArt {
pub song: icarus_models::song::Song,
pub coverart: icarus_models::coverart::CoverArt,
}
#[derive(Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct Response {
pub message: String,
pub data: Vec<SongAndCoverArt>,
}
}
}
// TODO: Might make a distinction between year and date in a song's tag at some point
@@ -350,105 +321,6 @@ pub mod song_db {
Err(_) => Err(sqlx::Error::RowNotFound),
}
}
pub async fn delete_song(
pool: &sqlx::PgPool,
id: &uuid::Uuid,
) -> Result<icarus_models::song::Song, sqlx::Error> {
let result = sqlx::query(
// icarus_models::song::Song,
r#"
DELETE FROM "song"
WHERE id = $1
RETURNING id, title, artist, album, album_artist, genre, year, disc, track, track_count, disc_count, duration, audio_type, date_created, filename, directory, user_id
"#,
)
.bind(id)
.fetch_one(pool)
.await
.map_err(|e| {
eprintln!("Error deleting data: {e:?}")
});
match result {
Ok(row) => {
let date_created_time: time::OffsetDateTime = row
.try_get("date_created")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap();
Ok(icarus_models::song::Song {
id: row
.try_get("id")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
title: row
.try_get("title")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
artist: row
.try_get("artist")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
album_artist: row
.try_get("album_artist")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
album: row
.try_get("album")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
genre: row
.try_get("genre")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
year: row
.try_get("year")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
track: row
.try_get("track")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
disc: row
.try_get("disc")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
track_count: row
.try_get("track_count")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
disc_count: row
.try_get("disc_count")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
duration: row
.try_get("duration")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
audio_type: row
.try_get("audio_type")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
filename: row
.try_get("filename")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
directory: row
.try_get("directory")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
date_created: date_created_time.to_string(),
user_id: row
.try_get("user_id")
.map_err(|_e| sqlx::Error::RowNotFound)
.unwrap(),
data: Vec::new(),
})
}
Err(_) => Err(sqlx::Error::RowNotFound),
}
}
}
mod song_queue {
@@ -858,7 +730,6 @@ pub mod endpoint {
}
}
// TODO: Rename
pub async fn download_flac(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::extract::Path(id): axum::extract::Path<uuid::Uuid>,
@@ -1097,211 +968,4 @@ pub mod endpoint {
}
}
}
pub async fn get_songs(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::extract::Query(params): axum::extract::Query<super::request::get_songs::Params>,
) -> (
axum::http::StatusCode,
Json<super::response::get_songs::Response>,
) {
let mut response = super::response::get_songs::Response::default();
match params.id {
Some(id) => match super::song_db::get_song(&pool, &id).await {
Ok(song) => {
response.message = String::from(super::super::response::SUCCESSFUL);
response.data.push(song);
(axum::http::StatusCode::OK, axum::Json(response))
}
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
},
None => {
response.message = String::from("Invalid parameters");
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
}
}
pub async fn stream_song(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::extract::Path(id): axum::extract::Path<uuid::Uuid>,
) -> impl IntoResponse {
match super::song_db::get_song(&pool, &id).await {
Ok(song) => {
let song_path = song.song_path().unwrap();
let path = std::path::Path::new(&song_path);
if !path.starts_with(&song.directory) || !path.exists() {
return Err((axum::http::StatusCode::NOT_FOUND, "File not found"));
}
let file = match tokio::fs::File::open(&path).await {
Ok(file) => file,
Err(_) => return Err((axum::http::StatusCode::NOT_FOUND, "File not found")),
};
let file_size = match file.metadata().await {
Ok(meta) => meta.len(),
Err(_) => {
return Err((
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
"Could not read file",
));
}
};
let mime = mime_guess::from_path(path).first_or_octet_stream();
let stream = tokio_util::io::ReaderStream::new(file);
let rep = axum::response::Response::builder()
.header("content-type", mime.to_string())
.header("accept-ranges", "bytes")
.header("content-length", file_size.to_string())
.body(axum::body::Body::from_stream(stream))
.unwrap();
Ok(rep)
}
Err(_err) => Err((
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
"Could not find file",
)),
}
}
pub async fn download_song(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::extract::Path(id): axum::extract::Path<uuid::Uuid>,
) -> (axum::http::StatusCode, axum::response::Response) {
match super::song_db::get_song(&pool, &id).await {
Ok(song) => match song.to_data() {
Ok(data) => {
let bytes = axum::body::Bytes::from(data);
let mut response = bytes.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=\"{id}.flac\"")
.parse()
.unwrap(),
);
(axum::http::StatusCode::OK, response)
}
Err(_err) => (
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::response::Response::default(),
),
},
Err(_err) => (
axum::http::StatusCode::NOT_FOUND,
axum::response::Response::default(),
),
}
}
pub async fn delete_song(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::extract::Path(id): axum::extract::Path<uuid::Uuid>,
) -> (
axum::http::StatusCode,
axum::Json<super::response::delete_song::Response>,
) {
let mut response = super::response::delete_song::Response::default();
match super::song_db::get_song(&pool, &id).await {
Ok(song) => {
match super::super::coverart::cov_db::get_coverart_with_song_id(&pool, &song.id)
.await
{
Ok(coverart) => {
let coverart_path = std::path::Path::new(&coverart.path);
if coverart_path.exists() {
match song.song_path() {
Ok(song_path) => {
match super::song_db::delete_song(&pool, &song.id).await {
Ok(deleted_song) => {
match super::super::coverart::cov_db::delete_coverart(
&pool,
&coverart.id,
)
.await
{
Ok(deleted_coverart) => {
match std::fs::remove_file(song_path) {
Ok(_) => match std::fs::remove_file(
&coverart.path,
) {
Ok(_) => {
response.message = String::from(super::super::response::SUCCESSFUL);
response.data.push(super::response::delete_song::SongAndCoverArt{ song: deleted_song, coverart: deleted_coverart });
(
axum::http::StatusCode::OK,
axum::Json(response),
)
}
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::INTERNAL_SERVER_ERROR, axum::Json(response))
}
},
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::INTERNAL_SERVER_ERROR, axum::Json(response))
}
}
}
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::INTERNAL_SERVER_ERROR, axum::Json(response))
}
}
}
Err(err) => {
response.message = err.to_string();
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response),
)
}
}
}
Err(err) => {
response.message = err.to_string();
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response),
)
}
}
} else {
response.message =
String::from("Could not locate coverart on the filesystem");
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response),
)
}
}
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::NOT_FOUND, axum::Json(response))
}
}
}
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::NOT_FOUND, axum::Json(response))
}
}
}
}
+27 -534
View File
@@ -44,7 +44,7 @@ async fn main() {
}
pub mod init {
use axum::routing::{delete, get, patch, post};
use axum::routing::{get, patch, post};
use std::time::Duration;
use tower_http::timeout::TimeoutLayer;
@@ -115,37 +115,12 @@ pub mod init {
crate::callers::endpoints::CREATECOVERART,
post(crate::callers::coverart::endpoint::create_coverart),
)
.route(
crate::callers::endpoints::GETSONGS,
get(crate::callers::song::endpoint::get_songs),
)
.route(
crate::callers::endpoints::GETCOVERART,
get(crate::callers::coverart::endpoint::get_coverart),
)
.route(
crate::callers::endpoints::DOWNLOADCOVERART,
get(crate::callers::coverart::endpoint::download_coverart),
)
.route(
crate::callers::endpoints::STREAMSONG,
get(crate::callers::song::endpoint::stream_song),
)
.route(
crate::callers::endpoints::DOWNLOADSONG,
get(crate::callers::song::endpoint::download_song),
)
.route(
crate::callers::endpoints::DELETESONG,
delete(crate::callers::song::endpoint::delete_song),
)
}
pub async fn app() -> axum::Router {
let pool = crate::db::create_pool()
.await
.expect("Failed to create pool");
// TODO: Look into handling this. Seems redundant to run migrations multiple times
crate::db::migrations(&pool).await;
routes()
@@ -252,15 +227,6 @@ mod tests {
Err("Error parsing".into())
}
}
pub async fn migrations(pool: &sqlx::PgPool) {
// Run migrations using the sqlx::migrate! macro
// Assumes your test migrations are in a ./test_migrations folder relative to Cargo.toml
sqlx::migrate!("./test_migrations")
.run(pool)
.await
.expect("Failed to run migrations");
}
}
mod init {
@@ -281,7 +247,7 @@ mod tests {
) -> Result<axum::response::Response, std::convert::Infallible> {
// Create multipart form
let mut form = MultipartForm::default();
let _ = form.add_file("flac", "tests/I/track01.flac");
let _ = form.add_file("flac", "tests/Machine_gun/track01.flac");
// Create request
let content_type = form.content_type();
@@ -365,7 +331,7 @@ mod tests {
app: &axum::Router,
) -> Result<axum::response::Response, std::convert::Infallible> {
let mut form = MultipartForm::default();
let _ = form.add_file("jpg", "tests/I/Coverart-1.jpg");
let _ = form.add_file("jpg", "tests/Machine_gun/160809_machinegun.jpg");
// Create request
let content_type = form.content_type();
@@ -441,7 +407,22 @@ mod tests {
song_queue_id: &uuid::Uuid,
user_id: &uuid::Uuid,
) -> Result<axum::response::Response, std::convert::Infallible> {
let payload = payload_data::create_song(song_queue_id, user_id).await;
let payload = serde_json::json!({
"title": "Power of Soul",
"artist": "Jimmi Hendrix",
"album_artist": "Jimmi Hendrix",
"album": "Machine Gun",
"genre": "Psychadelic Rock",
"date": "2016-01-01",
"track": 1,
"disc": 1,
"track_count": 11,
"disc_count": 1,
"duration": 330,
"audio_type": "flac",
"user_id": user_id,
"song_queue_id": song_queue_id
});
let req = axum::http::Request::builder()
.method(axum::http::Method::POST)
@@ -666,50 +647,23 @@ mod tests {
serde_json::from_slice(&body).unwrap()
}
pub async fn format_url_with_value(endpoint: &str, value: &uuid::Uuid) -> String {
let last = endpoint.len() - 5;
format!("{}/{value}", &endpoint[0..last])
}
// TODO: Change the name of the function to be more expressive and put into it's own module
pub mod payload_data {
pub async fn queue_metadata_payload_data(song_queue_id: &uuid::Uuid) -> serde_json::Value {
serde_json::json!(
{
"song_queue_id": song_queue_id,
"album" : "I",
"album_artist" : "Kuoth",
"artist" : "Kuoth",
"album" : "Machine Gun: The FillMore East First Show",
"album_artist" : "Jimi Hendrix",
"artist" : "Jimi Hendrix",
"disc" : 1,
"disc_count" : 1,
"duration" : 139,
"genre" : "Alternative Hip-Hop",
"title" : "Hypocrite Like The Rest",
"duration" : 330,
"genre" : "Psychadelic Rock",
"title" : "Power of Soul",
"track" : 1,
"track_count" : 9,
"year" : 2020
})
}
pub async fn create_song(
song_queue_id: &uuid::Uuid,
user_id: &uuid::Uuid,
) -> serde_json::Value {
serde_json::json!({
"title" : "Hypocrite Like The Rest",
"artist" : "Kuoth",
"album_artist": "Kuoth",
"album": "I",
"genre" : "Alternative Hip-Hop",
"date": "2020-01-01",
"track": 1,
"disc": 1,
"track_count": 9,
"disc_count": 1,
"duration": 139,
"audio_type": "flac",
"user_id": user_id,
"song_queue_id": song_queue_id
"track_count" : 11,
"year" : 2016
})
}
}
@@ -1838,465 +1792,4 @@ mod tests {
let _ = db_mgr::drop_database(&tm_pool, &db_name).await;
}
pub mod zzz_after_song_queue {
use futures::StreamExt;
use tower::ServiceExt;
#[tokio::test]
async fn test_get_songs() {
let tm_pool = super::db_mgr::get_pool().await.unwrap();
let db_name = super::db_mgr::generate_db_name().await;
match super::db_mgr::create_database(&tm_pool, &db_name).await {
Ok(_) => {
println!("Success");
}
Err(err) => {
assert!(false, "Error: {:?}", err);
}
}
let pool = super::db_mgr::connect_to_db(&db_name).await.unwrap();
super::db_mgr::migrations(&pool).await;
let app = super::init::app(pool).await;
let (id, _, _, _) = test_data::song_id().await.unwrap();
let uri = format!("{}?id={id}", crate::callers::endpoints::GETSONGS);
match app
.clone()
.oneshot(
axum::http::Request::builder()
.method(axum::http::Method::GET)
.uri(uri)
.header(axum::http::header::CONTENT_TYPE, "application/json")
.body(axum::body::Body::empty())
.unwrap(),
)
.await
{
Ok(response) => {
let resp = super::get_resp_data::<
crate::callers::song::response::get_songs::Response,
>(response)
.await;
assert_eq!(false, resp.data.is_empty(), "Should not be empty");
let song = resp.data[0].clone();
assert_eq!(id, song.id, "Id does not match {song:?}");
}
Err(err) => {
assert!(false, "Error: {err:?}");
}
}
let _ = super::db_mgr::drop_database(&tm_pool, &db_name).await;
}
#[tokio::test]
async fn test_get_coverart() {
let tm_pool = super::db_mgr::get_pool().await.unwrap();
let db_name = super::db_mgr::generate_db_name().await;
match super::db_mgr::create_database(&tm_pool, &db_name).await {
Ok(_) => {
println!("Success");
}
Err(err) => {
assert!(false, "Error: {:?}", err);
}
}
let pool = super::db_mgr::connect_to_db(&db_name).await.unwrap();
super::db_mgr::migrations(&pool).await;
let app = super::init::app(pool).await;
let id = test_data::coverart_id().await.unwrap();
let uri = format!("{}?id={id}", crate::callers::endpoints::GETCOVERART);
match app
.clone()
.oneshot(
axum::http::Request::builder()
.method(axum::http::Method::GET)
.uri(uri)
.header(axum::http::header::CONTENT_TYPE, "application/json")
.body(axum::body::Body::empty())
.unwrap(),
)
.await
{
Ok(response) => {
let resp = super::get_resp_data::<
crate::callers::coverart::response::get_coverart::Response,
>(response)
.await;
assert_eq!(false, resp.data.is_empty(), "Should not be empty");
let coverart = resp.data[0].clone();
assert_eq!(id, coverart.id, "Id does not match {coverart:?}");
}
Err(err) => {
assert!(false, "Error: {err:?}");
}
}
let _ = super::db_mgr::drop_database(&tm_pool, &db_name).await;
}
pub mod test_data {
pub async fn song_id() -> Result<(uuid::Uuid, String, String, String), uuid::Error> {
match uuid::Uuid::parse_str("44cf7940-34ff-489f-9124-d0ec90a55af9") {
Ok(id) => Ok((
id,
String::from("tests/I/"),
String::from("track01.flac"),
String::from("tests/I/Coverart-1.jpg"),
)),
Err(err) => Err(err),
}
}
pub async fn other_song_id() -> Result<(uuid::Uuid, String, String, String), uuid::Error>
{
match uuid::Uuid::parse_str("94cf7940-34ff-489f-9124-d0ec90a55af4") {
Ok(id) => Ok((
id,
String::from("tests/I/"),
String::from("track02.flac"),
String::from("tests/I/Coverart-2.jpg"),
)),
Err(err) => Err(err),
}
}
pub async fn coverart_id() -> Result<uuid::Uuid, uuid::Error> {
uuid::Uuid::parse_str("996122cd-5ae9-4013-9934-60768d3006ed")
}
}
#[tokio::test]
async fn test_stream_song() {
let tm_pool = super::db_mgr::get_pool().await.unwrap();
let db_name = super::db_mgr::generate_db_name().await;
match super::db_mgr::create_database(&tm_pool, &db_name).await {
Ok(_) => {
println!("Success");
}
Err(err) => {
assert!(false, "Error: {:?}", err);
}
}
let pool = super::db_mgr::connect_to_db(&db_name).await.unwrap();
super::db_mgr::migrations(&pool).await;
let app = super::init::app(pool).await;
let (id, _, _, _) = test_data::song_id().await.unwrap();
let my_url = crate::callers::endpoints::STREAMSONG;
let last = my_url.len() - 5;
let uri = format!("{}/{id}", &my_url[0..last]);
match app
.clone()
.oneshot(
axum::http::Request::builder()
.method(axum::http::Method::GET)
.uri(&uri)
.body(axum::body::Body::empty())
.unwrap(),
)
.await
{
Ok(response) => {
let e = response.into_body();
let mut data = e.into_data_stream();
while let Some(chunk) = data.next().await {
match chunk {
Ok(_data) => {}
Err(err) => {
assert!(false, "Error: {err:?}");
}
}
}
}
Err(err) => {
assert!(false, "Error: {err:?}");
}
}
let _ = super::db_mgr::drop_database(&tm_pool, &db_name).await;
}
#[tokio::test]
async fn test_download_song() {
let tm_pool = super::db_mgr::get_pool().await.unwrap();
let db_name = super::db_mgr::generate_db_name().await;
match super::db_mgr::create_database(&tm_pool, &db_name).await {
Ok(_) => {
println!("Success");
}
Err(err) => {
assert!(false, "Error: {:?}", err);
}
}
let pool = super::db_mgr::connect_to_db(&db_name).await.unwrap();
super::db_mgr::migrations(&pool).await;
let app = super::init::app(pool).await;
let (id, _, _, _) = test_data::song_id().await.unwrap();
let uri =
super::format_url_with_value(crate::callers::endpoints::DOWNLOADSONG, &id).await;
match app
.clone()
.oneshot(
axum::http::Request::builder()
.method(axum::http::Method::GET)
.uri(&uri)
.body(axum::body::Body::empty())
.unwrap(),
)
.await
{
Ok(response) => {
let e = response.into_body();
let mut data = e.into_data_stream();
while let Some(chunk) = data.next().await {
match chunk {
Ok(_data) => {}
Err(err) => {
assert!(false, "Error: {err:?}");
}
}
}
}
Err(err) => {
assert!(false, "Error: {err:?}");
}
}
let _ = super::db_mgr::drop_database(&tm_pool, &db_name).await;
}
#[tokio::test]
async fn test_download_coverart() {
let tm_pool = super::db_mgr::get_pool().await.unwrap();
let db_name = super::db_mgr::generate_db_name().await;
match super::db_mgr::create_database(&tm_pool, &db_name).await {
Ok(_) => {
println!("Success");
}
Err(err) => {
assert!(false, "Error: {:?}", err);
}
}
let pool = super::db_mgr::connect_to_db(&db_name).await.unwrap();
super::db_mgr::migrations(&pool).await;
let app = super::init::app(pool).await;
let id = test_data::coverart_id().await.unwrap();
let uri =
super::format_url_with_value(crate::callers::endpoints::DOWNLOADCOVERART, &id)
.await;
match app
.clone()
.oneshot(
axum::http::Request::builder()
.method(axum::http::Method::GET)
.uri(&uri)
.body(axum::body::Body::empty())
.unwrap(),
)
.await
{
Ok(response) => {
let e = response.into_body();
let mut data = e.into_data_stream();
while let Some(chunk) = data.next().await {
match chunk {
Ok(_data) => {}
Err(err) => {
assert!(false, "Error: {err:?}");
}
}
}
}
Err(err) => {
assert!(false, "Error: {err:?}");
}
}
let _ = super::db_mgr::drop_database(&tm_pool, &db_name).await;
}
async fn get_test_data(
song_directory: &String,
song_filename: &String,
coverart_path: &String,
) -> Result<(Vec<u8>, Vec<u8>), std::io::Error> {
let song = icarus_models::song::Song {
directory: song_directory.clone(),
filename: song_filename.clone(),
..Default::default()
};
let coverart = icarus_models::coverart::CoverArt {
path: coverart_path.clone(),
..Default::default()
};
match song.to_data() {
Ok(song_data) => match coverart.to_data() {
Ok(coverart_data) => Ok((song_data, coverart_data)),
Err(err) => Err(err),
},
Err(err) => Err(err),
}
}
async fn save_test_again(
song_directory: &String,
song_filename: &String,
song_data: Vec<u8>,
coverart_path: &String,
coverart_data: Vec<u8>,
) -> Result<(), std::io::Error> {
let song = icarus_models::song::Song {
directory: song_directory.clone(),
filename: song_filename.clone(),
..Default::default()
};
let coverart = icarus_models::coverart::CoverArt {
path: coverart_path.clone(),
..Default::default()
};
use std::io::Write;
match song.song_path() {
Ok(song_path) => {
let song_p = std::path::Path::new(&song_path);
match std::fs::File::create(song_p) {
Ok(mut song_file) => match song_file.write_all(&song_data) {
Ok(_) => {}
Err(err) => {
return Err(err);
}
},
Err(err) => {
return Err(err);
}
}
}
Err(err) => {
return Err(err);
}
}
let coverart_p = std::path::Path::new(&coverart.path);
match std::fs::File::create(coverart_p) {
Ok(mut coverart_file) => match coverart_file.write_all(&coverart_data) {
Ok(_) => Ok(()),
Err(err) => Err(err),
},
Err(err) => Err(err),
}
}
#[tokio::test]
async fn test_last_delete_song() {
let tm_pool = super::db_mgr::get_pool().await.unwrap();
let db_name = super::db_mgr::generate_db_name().await;
match super::db_mgr::create_database(&tm_pool, &db_name).await {
Ok(_) => {
println!("Success");
}
Err(err) => {
assert!(false, "Error: {:?}", err);
}
}
let pool = super::db_mgr::connect_to_db(&db_name).await.unwrap();
super::db_mgr::migrations(&pool).await;
let app = super::init::app(pool).await;
let (id, song_directory, song_filename, coverart_path) =
test_data::other_song_id().await.unwrap();
let (song_data, coverart_data) =
get_test_data(&song_directory, &song_filename, &coverart_path)
.await
.unwrap();
let uri =
super::format_url_with_value(crate::callers::endpoints::DELETESONG, &id).await;
match app
.clone()
.oneshot(
axum::http::Request::builder()
.method(axum::http::Method::DELETE)
.uri(&uri)
.body(axum::body::Body::empty())
.unwrap(),
)
.await
{
Ok(response) => {
let resp = super::get_resp_data::<
crate::callers::song::response::delete_song::Response,
>(response)
.await;
assert_eq!(false, resp.data.is_empty(), "Response has no data");
let song_and_coverart = &resp.data[0];
assert_eq!(
id, song_and_coverart.song.id,
"Song Ids do not match {id:?} {:?}",
song_and_coverart.song.id
);
match save_test_again(
&song_directory,
&song_filename,
song_data,
&coverart_path,
coverart_data,
)
.await
{
Ok(_) => {}
Err(err) => {
assert!(false, "Error: {err:?}");
}
}
}
Err(err) => {
assert!(false, "Error: {err:?}");
}
}
let _ = super::db_mgr::drop_database(&tm_pool, &db_name).await;
}
}
}
-58
View File
@@ -1,58 +0,0 @@
-- Add migration script here
CREATE EXTENSION IF NOT EXISTS pgcrypto;
-- Table to store queued songs to process
CREATE TABLE IF NOT EXISTS "songQueue" (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
filename TEXT NOT NULL,
status TEXT CHECK (status IN ('pending', 'ready', 'processing', 'done')),
data BYTEA NULL,
user_id UUID NULL
);
-- Table to store queued metadata
CREATE TABLE IF NOT EXISTS "metadataQueue" (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
metadata jsonb NOT NULL,
created_at timestamptz DEFAULT now(),
song_queue_id UUID NOT NULL
);
-- Table to store queued coverart
CREATE TABLE IF NOT EXISTS "coverartQueue" (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
data BYTEA NULL,
song_queue_id UUID NULL
);
-- Create an index for better query performance
CREATE INDEX metadata_queue_data_metadata ON "metadataQueue" USING gin (metadata);
-- Table to store a song's info
CREATE TABLE IF NOT EXISTS "song" (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
title TEXT NOT NULL,
artist TEXT NOT NULL,
album_artist TEXT NOT NULL,
album TEXT NOT NULL,
genre TEXT NOT NULL,
year INT NOT NULL,
track INT NOT NULL,
disc INT NOT NULL,
track_count INT NOT NULL,
disc_count INT NOT NULL,
duration INT NOT NULL,
audio_type TEXT NOT NULL,
date_created timestamptz DEFAULT now(),
filename TEXT NOT NULL,
directory TEXT NOT NULL,
user_id UUID NULL
);
CREATE TABLE IF NOT EXISTS "coverart" (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
title TEXT NOT NULL,
path TEXT NOT NULL,
song_id UUID NOT NULL
);
@@ -1,6 +0,0 @@
-- Add migration script here
INSERT INTO "song" (id, title, artist, album_artist, album, genre, year, track, disc, track_count, disc_count, duration, audio_type, date_created, filename, directory, user_id) VALUES('44cf7940-34ff-489f-9124-d0ec90a55af9', 'Hypocrite Like The Rest', 'Kuoth', 'Kuoth', 'I', 'Alternative Hip-Hop', 2020, 1, 1, 9, 1, 139, 'flac', '2020-01-01 13:00:00-05', 'track01.flac', 'tests/I', '47491f9b-725a-4ba4-b9a5-711e1be46670');
INSERT INTO "coverart" VALUES('996122cd-5ae9-4013-9934-60768d3006ed', 'I', 'tests/I/Coverart-1.jpg', '44cf7940-34ff-489f-9124-d0ec90a55af9');
INSERT INTO "song" (id, title, artist, album_artist, album, genre, year, track, disc, track_count, disc_count, duration, audio_type, date_created, filename, directory, user_id) VALUES('94cf7940-34ff-489f-9124-d0ec90a55af4', 'It''s Too Late', 'Kuoth', 'Kuoth', 'I', 'Alternative Hip-Hop', 2020, 2, 1, 9, 1, 116, 'flac', '2020-01-01 13:01:00-05', 'track02.flac', 'tests/I', '47491f9b-725a-4ba4-b9a5-711e1be46670');
INSERT INTO "coverart" VALUES('d96122cd-5ae9-4013-9934-60768d3006e9', 'I', 'tests/I/Coverart-2.jpg', '94cf7940-34ff-489f-9124-d0ec90a55af4');
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.7 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.7 MiB

-73
View File
@@ -1,73 +0,0 @@
{
"album": "I",
"album_artist": "Kuoth",
"disc_count": 1,
"genre": "Alternative Hip-Hop",
"year": 2020,
"track_count": 9,
"tracks": [
{
"artist": "Kuoth",
"disc": 1,
"title": "Hypocrite Like the Rest",
"duration": 139,
"track": 1
},
{
"artist": "Kuoth",
"disc": 1,
"title": "It's Too Late",
"duration": 116,
"track": 2
},
{
"artist": "Kuoth",
"disc": 1,
"title": "Hell Might be Nice",
"duration": 229,
"track": 3
},
{
"artist": "Kuoth",
"disc": 1,
"title": "Dark Side of Progress",
"duration": 187,
"track": 4
},
{
"artist": "Kuoth",
"disc": 1,
"title": "Distractions",
"duration": 141,
"track": 5
},
{
"artist": "Kuoth",
"disc": 1,
"title": "But You Won't Listen",
"duration": 184,
"track": 6
},
{
"artist": "Kuoth",
"disc": 1,
"title": "Guidance",
"duration": 121,
"track": 7
},
{
"artist": "Kuoth",
"disc": 1,
"title": "M",
"duration": 98,
"track": 8
},
{
"artist": "Kuoth",
"disc": 1,
"title": "Social Acceptance",
"duration": 169,
"track": 9
}
]
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 271 KiB