Compare commits
51 Commits
v0.5.0-dev
...
v0.10.0-92
| Author | SHA1 | Date | |
|---|---|---|---|
|
0102036684
|
|||
|
9955c22468
|
|||
|
c6682ae69a
|
|||
|
0e86fb0cef
|
|||
|
368590c3a2
|
|||
| 0552561851 | |||
| 678d2c2b3d | |||
| b5429f80b0 | |||
| 432078e3c2 | |||
| 0a27b8ccb1 | |||
| afc4ca21a2 | |||
| 02b6157e0d | |||
| 860d684e7b | |||
|
97783568e9
|
|||
|
5a8118726b
|
|||
|
9dcf46ec0a
|
|||
| 44d08cdb1f | |||
| 51c8b5c7b3 | |||
| 8041dc6ff5 | |||
| 11e5b1745c | |||
| 4e649fa390 | |||
| 668d371f7f | |||
| eac7562b80 | |||
| e3ca2c5781 | |||
| 440caca7c2 | |||
| 0c0b4ba7ca | |||
| c263cedf28 | |||
| 0637a9432e | |||
| d7c078d95a | |||
| 00cada74e2 | |||
|
9436c9033a
|
|||
|
85d8f839f1
|
|||
|
16f633d563
|
|||
|
0b53eb8208
|
|||
|
73c8fd2634
|
|||
|
fa8643e73a
|
|||
| 2d6b550ae6 | |||
| f43bcaa314 | |||
| a6ef7d8a62 | |||
| bd793db08e | |||
| 1e95822b5a | |||
| 228ca67a16 | |||
| d3251f935e | |||
| 1c5de9dc26 | |||
| 569fb632e5 | |||
| 6aa4c3d741 | |||
| 97853a42c1 | |||
| fdae8056b1 | |||
| 24aa60cb48 | |||
| d8eadb8187 | |||
| 2b2e96c02d |
@@ -3,21 +3,24 @@ name: Release Tagging
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- devel
|
||||
- main
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v3
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0 # Important for git describe --tags
|
||||
|
||||
- name: Install Rust
|
||||
uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: 1.88.0
|
||||
toolchain: 1.94
|
||||
components: cargo
|
||||
|
||||
- name: Extract Version from Cargo.toml
|
||||
@@ -25,12 +28,15 @@ jobs:
|
||||
run: |
|
||||
VERSION=$(grep '^version = "' Cargo.toml | sed -E 's/version = "([^"]+)"/\1/')
|
||||
PROJECT_COMMIT_HASH=$(git rev-parse HEAD | cut -c 1-10)
|
||||
BRANCH_REF="${GITHUB_REF}"
|
||||
BRANCH_REF="${{ gitea.ref }}"
|
||||
BRANCH_NAME=$(echo "$BRANCH_REF" | cut -d '/' -f 3)
|
||||
PROJECT_TAG_RELEASE="v$VERSION-$BRANCH_NAME-$PROJECT_COMMIT_HASH"
|
||||
echo "::set-output name=project_tag_release::$PROJECT_TAG_RELEASE-111"
|
||||
PROJECT_TAG_RELEASE="v$VERSION-$BRANCH_NAME-$PROJECT_COMMIT_HASH-111"
|
||||
|
||||
echo "::set-output name=project_tag_release::$PROJECT_TAG_RELEASE"
|
||||
|
||||
echo "Version: $VERSION"
|
||||
echo "Hash: $PROJECT_COMMIT_HASH"
|
||||
echo "Branh ref: $BRANCH_REF"
|
||||
echo "Branch: $BRANCH_NAME"
|
||||
echo "Tag Release: $PROJECT_TAG_RELEASE"
|
||||
|
||||
|
||||
@@ -4,41 +4,39 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- devel
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
- devel
|
||||
|
||||
jobs:
|
||||
check:
|
||||
name: Check
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
with:
|
||||
toolchain: 1.88.0
|
||||
toolchain: 1.94
|
||||
- run: cargo check
|
||||
|
||||
test:
|
||||
name: Test Suite
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
with:
|
||||
toolchain: 1.88.0
|
||||
toolchain: 1.94
|
||||
- run: cargo test
|
||||
|
||||
fmt:
|
||||
name: Rustfmt
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
with:
|
||||
toolchain: 1.88.0
|
||||
toolchain: 1.94
|
||||
- run: rustup component add rustfmt
|
||||
- run: cargo fmt --all -- --check
|
||||
|
||||
@@ -46,10 +44,10 @@ jobs:
|
||||
name: Clippy
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
with:
|
||||
toolchain: 1.88.0
|
||||
toolchain: 1.94
|
||||
- run: rustup component add clippy
|
||||
- run: cargo clippy -- -D warnings
|
||||
|
||||
@@ -57,10 +55,8 @@ jobs:
|
||||
name: build
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
with:
|
||||
toolchain: 1.88.0
|
||||
toolchain: 1.94
|
||||
- run: cargo build
|
||||
|
||||
|
||||
|
||||
788
Cargo.lock
generated
788
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
18
Cargo.toml
18
Cargo.toml
@@ -1,17 +1,19 @@
|
||||
[package]
|
||||
name = "icarus_models"
|
||||
version = "0.5.0"
|
||||
version = "0.10.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.88"
|
||||
rust-version = "1.94"
|
||||
description = "models used for the icarus project"
|
||||
license = "MIT"
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1.0.219", features = ["derive"] }
|
||||
serde_json = { version = "1.0.140" }
|
||||
rand = { version = "0.9.1" }
|
||||
time = { version = "0.3.41", features = ["formatting", "macros", "parsing", "serde"] }
|
||||
uuid = { version = "1.17.0", features = ["v4", "serde"] }
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
serde_json = { version = "1.0.145" }
|
||||
rand = { version = "0.9.2" }
|
||||
time = { version = "0.3.44", features = ["formatting", "macros", "parsing", "serde"] }
|
||||
uuid = { version = "1.18.1", features = ["v4", "serde"] }
|
||||
josekit = { version = "0.10.3" }
|
||||
utoipa = { version = "5.4.0", features = ["uuid", "time"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = { version = "3.20.0" }
|
||||
tempfile = { version = "3.23.0" }
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
A library containing commonly used models and functions that is used throughout
|
||||
icarus projects. This reduces the amount of duplicated code without a benefit.
|
||||
A library containing commonly used structs, functions, enums, constants and other code
|
||||
that is used throughout the icarus projects. Code from this library serves as the model
|
||||
for other projects in the icarus project.
|
||||
|
||||
@@ -2,7 +2,7 @@ use std::default::Default;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[derive(Clone, Debug, Deserialize, Serialize, utoipa::ToSchema)]
|
||||
pub struct AccessLevel {
|
||||
pub id: uuid::Uuid,
|
||||
pub level: String,
|
||||
|
||||
@@ -12,3 +12,9 @@ pub mod file_extensions {
|
||||
pub const PNGEXTENSION: &str = ".png";
|
||||
}
|
||||
}
|
||||
|
||||
pub mod error {
|
||||
pub const DIRECTORY_NOT_INITIALIZED: &str = "Directory has not been initialized";
|
||||
pub const FILENAME_NOT_INITIALIZED: &str = "Filename has not bee initialized";
|
||||
pub const LAST_CHARACTER_IN_DIRECTORY: &str = "Could not access last character of directory";
|
||||
}
|
||||
|
||||
154
src/coverart.rs
154
src/coverart.rs
@@ -1,36 +1,146 @@
|
||||
use std::io::Read;
|
||||
use std::io::Write;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use rand::Rng;
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
|
||||
const FILENAME_LENGTH: i32 = 16;
|
||||
|
||||
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
|
||||
pub struct CoverArt {
|
||||
pub id: uuid::Uuid,
|
||||
pub title: String,
|
||||
pub path: String,
|
||||
#[serde(skip)]
|
||||
pub directory: String,
|
||||
pub filename: String,
|
||||
pub file_type: String,
|
||||
#[serde(skip)]
|
||||
pub data: Vec<u8>,
|
||||
pub song_id: uuid::Uuid,
|
||||
}
|
||||
|
||||
pub mod init {
|
||||
use crate::coverart::CoverArt;
|
||||
|
||||
pub fn init_coverart_only_path(path: String) -> CoverArt {
|
||||
CoverArt {
|
||||
id: uuid::Uuid::nil(),
|
||||
title: String::new(),
|
||||
path: path.clone(),
|
||||
data: Vec::new(),
|
||||
/// Initializes the CoverArt with just the directory and filename
|
||||
pub fn init_coverart_dir_and_filename(directory: &str, filename: &str) -> super::CoverArt {
|
||||
super::CoverArt {
|
||||
directory: String::from(directory),
|
||||
filename: String::from(filename),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CoverArt {
|
||||
pub fn to_data(&self) -> Result<Vec<u8>, std::io::Error> {
|
||||
let path: &String = &self.path;
|
||||
let mut file = std::fs::File::open(path)?;
|
||||
let mut buffer = Vec::new();
|
||||
match file.read_to_end(&mut buffer) {
|
||||
Ok(_) => Ok(buffer),
|
||||
/// Saves the coverart to the filesystem
|
||||
pub fn save_to_filesystem(&self) -> Result<(), std::io::Error> {
|
||||
match self.get_path() {
|
||||
Ok(path) => match std::fs::File::create(&path) {
|
||||
Ok(mut file) => match file.write_all(&self.data) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(err) => Err(err),
|
||||
},
|
||||
Err(err) => Err(err),
|
||||
},
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes the coverart from the filesystem
|
||||
pub fn remove_from_filesystem(&self) -> Result<(), std::io::Error> {
|
||||
match self.get_path() {
|
||||
Ok(path) => {
|
||||
let p = std::path::Path::new(&path);
|
||||
if p.exists() {
|
||||
match std::fs::remove_file(p) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
} else {
|
||||
Err(std::io::Error::other(
|
||||
"Cannot delete file that does not exist",
|
||||
))
|
||||
}
|
||||
}
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets the path of the CoverArt
|
||||
pub fn get_path(&self) -> Result<String, std::io::Error> {
|
||||
if self.directory.is_empty() {
|
||||
return Err(std::io::Error::other(
|
||||
crate::constants::error::DIRECTORY_NOT_INITIALIZED,
|
||||
));
|
||||
} else if self.filename.is_empty() {
|
||||
return Err(std::io::Error::other(
|
||||
crate::constants::error::FILENAME_NOT_INITIALIZED,
|
||||
));
|
||||
}
|
||||
|
||||
let directory = &self.directory;
|
||||
let last_index = directory.len() - 1;
|
||||
|
||||
match crate::util::concatenate_path(directory, &self.filename, last_index) {
|
||||
Ok(path) => Ok(path),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Generates filename for a CoverArt
|
||||
pub fn generate_filename(
|
||||
typ: crate::types::CoverArtType,
|
||||
randomize: bool,
|
||||
) -> Result<String, std::io::Error> {
|
||||
let file_extension = match typ {
|
||||
crate::types::CoverArtType::PngExtension => {
|
||||
String::from(crate::constants::file_extensions::image::PNGEXTENSION)
|
||||
}
|
||||
crate::types::CoverArtType::JpegExtension => {
|
||||
String::from(crate::constants::file_extensions::image::JPEGEXTENSION)
|
||||
}
|
||||
crate::types::CoverArtType::JpgExtension => {
|
||||
String::from(crate::constants::file_extensions::image::JPGEXTENSION)
|
||||
}
|
||||
crate::types::CoverArtType::None => {
|
||||
return Err(std::io::Error::other("Unsupported CoverArtTypes"));
|
||||
}
|
||||
};
|
||||
|
||||
let filename: String = if randomize {
|
||||
let mut filename: String = String::from("coverart-");
|
||||
let some_chars: String = String::from("abcdefghij0123456789");
|
||||
let some_chars_length = some_chars.len();
|
||||
let mut rng = rand::rng();
|
||||
|
||||
for _ in 0..FILENAME_LENGTH {
|
||||
let index = rng.random_range(0..=some_chars_length);
|
||||
let rando_char = some_chars.chars().nth(index);
|
||||
|
||||
if let Some(c) = rando_char {
|
||||
filename.push(c);
|
||||
}
|
||||
}
|
||||
format!("{filename}{file_extension}")
|
||||
} else {
|
||||
format!("coverart-output{file_extension}")
|
||||
};
|
||||
|
||||
Ok(filename)
|
||||
}
|
||||
|
||||
pub mod io {
|
||||
use std::io::Read;
|
||||
|
||||
/// Gets the raw data of the cover art
|
||||
pub fn to_data(coverart: &super::CoverArt) -> Result<Vec<u8>, std::io::Error> {
|
||||
match coverart.get_path() {
|
||||
Ok(path) => {
|
||||
let mut file = std::fs::File::open(path)?;
|
||||
let mut buffer = Vec::new();
|
||||
match file.read_to_end(&mut buffer) {
|
||||
Ok(_) => Ok(buffer),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
@@ -42,9 +152,11 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_cover_art_image() {
|
||||
let path: String = String::from("somepath");
|
||||
let coverart = coverart::init::init_coverart_only_path(path.clone());
|
||||
let dir = String::from("./");
|
||||
let filename = String::from("CoverArt.png");
|
||||
let coverart = coverart::init::init_coverart_dir_and_filename(&dir, &filename);
|
||||
|
||||
assert_eq!(path, coverart.path);
|
||||
assert_eq!(dir, coverart.directory);
|
||||
assert_eq!(filename, coverart.filename);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ pub mod song;
|
||||
pub mod token;
|
||||
pub mod types;
|
||||
pub mod user;
|
||||
pub mod util;
|
||||
|
||||
pub mod init {
|
||||
pub fn is_id_valid(num: &i32) -> bool {
|
||||
|
||||
@@ -2,7 +2,7 @@ use std::default::Default;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize, utoipa::ToSchema)]
|
||||
pub struct LoginResult {
|
||||
pub id: uuid::Uuid,
|
||||
pub username: String,
|
||||
@@ -12,20 +12,14 @@ pub struct LoginResult {
|
||||
pub expiration: i64,
|
||||
}
|
||||
|
||||
impl Default for LoginResult {
|
||||
fn default() -> Self {
|
||||
LoginResult {
|
||||
id: uuid::Uuid::nil(),
|
||||
username: String::new(),
|
||||
token: String::new(),
|
||||
token_type: String::new(),
|
||||
expiration: -1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl LoginResult {
|
||||
pub fn _to_json(&self) -> Result<String, serde_json::Error> {
|
||||
pub fn to_json(&self) -> Result<String, serde_json::Error> {
|
||||
serde_json::to_string_pretty(&self)
|
||||
}
|
||||
|
||||
pub fn token_expired(&self) -> bool {
|
||||
let current_time = time::OffsetDateTime::now_utc();
|
||||
let expired = time::OffsetDateTime::from_unix_timestamp(self.expiration).unwrap();
|
||||
current_time > expired
|
||||
}
|
||||
}
|
||||
|
||||
196
src/song.rs
196
src/song.rs
@@ -1,13 +1,16 @@
|
||||
use std::io::Read;
|
||||
use std::io::Write;
|
||||
|
||||
use rand::Rng;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::constants;
|
||||
use crate::init;
|
||||
use crate::types;
|
||||
|
||||
use rand::Rng;
|
||||
use serde::{Deserialize, Serialize};
|
||||
/// Length of characters of a filename to be generated
|
||||
const FILENAME_LENGTH: i32 = 16;
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize, utoipa::ToSchema)]
|
||||
pub struct Song {
|
||||
#[serde(skip_serializing_if = "init::is_uuid_nil")]
|
||||
#[serde(alias = "id")]
|
||||
@@ -36,8 +39,8 @@ pub struct Song {
|
||||
pub track_count: i32,
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub audio_type: String,
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub date_created: String,
|
||||
#[serde(with = "time::serde::rfc3339::option")]
|
||||
pub date_created: Option<time::OffsetDateTime>,
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub filename: String,
|
||||
#[serde(skip_serializing_if = "init::is_uuid_nil")]
|
||||
@@ -66,34 +69,139 @@ impl Song {
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets the path of a Song
|
||||
pub fn song_path(&self) -> Result<String, std::io::Error> {
|
||||
if self.directory.is_empty() {
|
||||
return Err(std::io::Error::other("Directory does not exist"));
|
||||
return Err(std::io::Error::other(
|
||||
crate::constants::error::DIRECTORY_NOT_INITIALIZED,
|
||||
));
|
||||
} else if self.filename.is_empty() {
|
||||
return Err(std::io::Error::other(
|
||||
crate::constants::error::FILENAME_NOT_INITIALIZED,
|
||||
));
|
||||
}
|
||||
|
||||
let directory = &self.directory;
|
||||
let mut buffer: String = directory.clone();
|
||||
let last_index = directory.len() - 1;
|
||||
|
||||
if let Some(character) = directory.chars().nth(last_index) {
|
||||
if character != '/' {
|
||||
buffer += "/";
|
||||
}
|
||||
|
||||
buffer += &self.filename.clone();
|
||||
|
||||
Ok(buffer)
|
||||
} else {
|
||||
Err(std::io::Error::other(
|
||||
"Could not access last character of directory",
|
||||
))
|
||||
match crate::util::concatenate_path(directory, &self.filename, last_index) {
|
||||
Ok(path) => Ok(path),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_data(&self) -> Result<Vec<u8>, std::io::Error> {
|
||||
let path_result = self.song_path();
|
||||
/// Saves the song to the filesystem using the song's data
|
||||
pub fn save_to_filesystem(&self) -> Result<(), std::io::Error> {
|
||||
match self.song_path() {
|
||||
Ok(song_path) => match std::fs::File::create(&song_path) {
|
||||
Ok(mut file) => match file.write_all(&self.data) {
|
||||
Ok(_res) => Ok(()),
|
||||
Err(err) => Err(err),
|
||||
},
|
||||
Err(err) => Err(err),
|
||||
},
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
match path_result {
|
||||
/// Removes the song from the filesystem
|
||||
pub fn remove_from_filesystem(&self) -> Result<(), std::io::Error> {
|
||||
match self.song_path() {
|
||||
Ok(song_path) => {
|
||||
let p = std::path::Path::new(&song_path);
|
||||
if p.exists() {
|
||||
match std::fs::remove_file(p) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
} else {
|
||||
Err(std::io::Error::other(
|
||||
"Cannot delete file that does not exist",
|
||||
))
|
||||
}
|
||||
}
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Generates a filename. In order to save a song to the filesystem
|
||||
pub fn generate_filename(typ: types::MusicType, randomize: bool) -> Result<String, std::io::Error> {
|
||||
let file_extension = match typ {
|
||||
types::MusicType::DefaultMusicExtension => {
|
||||
String::from(constants::file_extensions::audio::DEFAULTMUSICEXTENSION)
|
||||
}
|
||||
types::MusicType::WavExtension => {
|
||||
String::from(constants::file_extensions::audio::WAVEXTENSION)
|
||||
}
|
||||
types::MusicType::FlacExtension => {
|
||||
String::from(constants::file_extensions::audio::FLACEXTENSION)
|
||||
}
|
||||
types::MusicType::MPThreeExtension => {
|
||||
String::from(constants::file_extensions::audio::MPTHREEEXTENSION)
|
||||
}
|
||||
types::MusicType::None => return Err(std::io::Error::other("Unsupported MusicTypes")),
|
||||
};
|
||||
|
||||
let filename: String = if randomize {
|
||||
let mut filename: String = String::from("track-");
|
||||
let some_chars: String = String::from("abcdefghij0123456789");
|
||||
let some_chars_length = some_chars.len();
|
||||
let mut rng = rand::rng();
|
||||
|
||||
for _ in 0..FILENAME_LENGTH {
|
||||
let index = rng.random_range(0..=some_chars_length);
|
||||
let rando_char = some_chars.chars().nth(index);
|
||||
|
||||
if let Some(c) = rando_char {
|
||||
filename.push(c);
|
||||
}
|
||||
}
|
||||
format!("{filename}{file_extension}")
|
||||
} else {
|
||||
format!("track-output{file_extension}")
|
||||
};
|
||||
|
||||
Ok(filename)
|
||||
}
|
||||
|
||||
/// I/O operations for songs
|
||||
pub mod io {
|
||||
use std::io::Read;
|
||||
|
||||
/// Copies a song using the source song's data
|
||||
pub fn copy_song(
|
||||
song_source: &super::Song,
|
||||
song_target: &mut super::Song,
|
||||
) -> Result<(), std::io::Error> {
|
||||
match song_target.song_path() {
|
||||
Ok(songpath) => {
|
||||
let p = std::path::Path::new(&songpath);
|
||||
if p.exists() {
|
||||
Err(std::io::Error::other(
|
||||
"Cannot copy song over to one that already exists",
|
||||
))
|
||||
} else {
|
||||
if song_target.data.is_empty() {
|
||||
song_target.data = song_source.data.clone();
|
||||
} else {
|
||||
song_target.data.clear();
|
||||
song_target.data = song_source.data.clone();
|
||||
}
|
||||
|
||||
match song_target.save_to_filesystem() {
|
||||
Ok(_) => Ok(()),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets the raw file data of a song from the filesystem
|
||||
pub fn to_data(song: &super::Song) -> Result<Vec<u8>, std::io::Error> {
|
||||
match song.song_path() {
|
||||
Ok(path) => {
|
||||
let mut file = std::fs::File::open(path)?;
|
||||
let mut buffer: Vec<u8> = Vec::new();
|
||||
@@ -108,46 +216,4 @@ impl Song {
|
||||
Err(er) => Err(er),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn generate_filename(&self, typ: types::MusicTypes, randomize: bool) -> String {
|
||||
let mut filename: String = String::new();
|
||||
let filename_len = 10;
|
||||
|
||||
let file_extension = match typ {
|
||||
types::MusicTypes::DefaultMusicExtension => {
|
||||
String::from(constants::file_extensions::audio::DEFAULTMUSICEXTENSION)
|
||||
}
|
||||
|
||||
types::MusicTypes::WavExtension => {
|
||||
String::from(constants::file_extensions::audio::WAVEXTENSION)
|
||||
}
|
||||
types::MusicTypes::FlacExtension => {
|
||||
String::from(constants::file_extensions::audio::FLACEXTENSION)
|
||||
}
|
||||
types::MusicTypes::MPThreeExtension => {
|
||||
String::from(constants::file_extensions::audio::MPTHREEEXTENSION)
|
||||
}
|
||||
};
|
||||
|
||||
if randomize {
|
||||
let some_chars: String = String::from("abcdefghij0123456789");
|
||||
let mut rng = rand::rng();
|
||||
|
||||
for _i in 0..filename_len {
|
||||
let random_number: i32 = rng.random_range(0..=19);
|
||||
let index = random_number as usize;
|
||||
let rando_char = some_chars.chars().nth(index);
|
||||
|
||||
if let Some(c) = rando_char {
|
||||
filename.push(c);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
filename += "track-output";
|
||||
}
|
||||
|
||||
filename += &file_extension;
|
||||
|
||||
filename
|
||||
}
|
||||
}
|
||||
|
||||
182
src/token.rs
182
src/token.rs
@@ -1,8 +1,8 @@
|
||||
use std::default::Default;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[derive(Clone, Debug, Default, Deserialize, serde::Serialize)]
|
||||
pub struct Token {
|
||||
pub scope: String,
|
||||
pub expiration: i64,
|
||||
@@ -11,7 +11,7 @@ pub struct Token {
|
||||
pub issued: i64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[derive(Clone, Debug, Deserialize, serde::Serialize)]
|
||||
pub struct AccessToken {
|
||||
#[serde(alias = "init::is_uuid_nil")]
|
||||
pub user_id: uuid::Uuid,
|
||||
@@ -27,23 +27,31 @@ pub struct AccessToken {
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl Default for Token {
|
||||
fn default() -> Self {
|
||||
Token {
|
||||
scope: String::new(),
|
||||
expiration: -1,
|
||||
audience: String::new(),
|
||||
issuer: String::new(),
|
||||
issued: -1,
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug, serde::Serialize, Deserialize)]
|
||||
pub struct UserClaims {
|
||||
pub iss: String,
|
||||
pub aud: String, // Audience
|
||||
pub sub: String, // Subject (user ID)
|
||||
#[serde(deserialize_with = "deserialize_i64_from_f64")]
|
||||
pub exp: i64, // Expiration time (UTC timestamp)
|
||||
#[serde(deserialize_with = "deserialize_i64_from_f64")]
|
||||
pub iat: i64, // Issued at (UTC timestamp)
|
||||
// pub azp: String,
|
||||
// pub gty: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub roles: Option<Vec<String>>, // Optional roles
|
||||
}
|
||||
|
||||
impl AccessToken {
|
||||
/// Get the token fit for Bearer authentication
|
||||
pub fn bearer_token(&self) -> String {
|
||||
let mut token: String = String::from("Bearer ");
|
||||
token += &self.token.clone();
|
||||
token
|
||||
format!("Bearer {}", self.token)
|
||||
}
|
||||
|
||||
pub fn token_expired(&self) -> bool {
|
||||
let current_time = time::OffsetDateTime::now_utc();
|
||||
let expired = time::OffsetDateTime::from_unix_timestamp(self.expiration).unwrap();
|
||||
current_time > expired
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,9 +60,10 @@ impl Token {
|
||||
serde_json::to_string_pretty(&self)
|
||||
}
|
||||
|
||||
// TODO: Implement
|
||||
pub fn token_expired(&self) -> bool {
|
||||
false
|
||||
let current_time = time::OffsetDateTime::now_utc();
|
||||
let expired = time::OffsetDateTime::from_unix_timestamp(self.expiration).unwrap();
|
||||
current_time > expired
|
||||
}
|
||||
|
||||
pub fn contains_scope(&self, des_scope: &String) -> bool {
|
||||
@@ -62,10 +71,106 @@ impl Token {
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_i64_from_f64<'de, D>(deserializer: D) -> Result<i64, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
let val = f64::deserialize(deserializer)?;
|
||||
// Handle NaN and infinity cases
|
||||
if val.is_nan() || val.is_infinite() {
|
||||
return Err(serde::de::Error::custom("invalid float value"));
|
||||
}
|
||||
// Round to nearest integer and convert
|
||||
let rounded = val.round();
|
||||
// Check if the rounded value can fit in i64
|
||||
if rounded < (i64::MIN as f64) || rounded > (i64::MAX as f64) {
|
||||
Err(serde::de::Error::custom("float out of i64 range"))
|
||||
} else {
|
||||
Ok(rounded as i64)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_issued() -> time::Result<time::OffsetDateTime> {
|
||||
Ok(time::OffsetDateTime::now_utc())
|
||||
}
|
||||
|
||||
mod util {
|
||||
pub fn time_to_std_time(
|
||||
provided_time: &time::OffsetDateTime,
|
||||
) -> Result<std::time::SystemTime, std::time::SystemTimeError> {
|
||||
let converted = std::time::SystemTime::from(*provided_time);
|
||||
Ok(converted)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct TokenResource {
|
||||
pub message: String,
|
||||
pub issuer: String,
|
||||
pub audiences: Vec<String>,
|
||||
pub id: uuid::Uuid,
|
||||
}
|
||||
|
||||
pub const TOKEN_TYPE: &str = "JWT";
|
||||
|
||||
pub fn create_token(
|
||||
key: &String,
|
||||
token_resource: &TokenResource,
|
||||
duration: time::Duration,
|
||||
) -> Result<(String, i64), josekit::JoseError> {
|
||||
let mut header = josekit::jws::JwsHeader::new();
|
||||
header.set_token_type(TOKEN_TYPE);
|
||||
|
||||
let mut payload = josekit::jwt::JwtPayload::new();
|
||||
let message = &token_resource.message;
|
||||
let issuer = &token_resource.issuer;
|
||||
let audiences: &Vec<String> = &token_resource.audiences;
|
||||
payload.set_subject(message);
|
||||
payload.set_issuer(issuer);
|
||||
payload.set_audience(audiences.clone());
|
||||
if !token_resource.id.is_nil() {
|
||||
match payload.set_claim("id", Some(serde_json::json!(token_resource.id))) {
|
||||
Ok(_) => {}
|
||||
Err(err) => {
|
||||
return Err(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
match get_issued() {
|
||||
Ok(issued) => {
|
||||
let expire = issued + duration;
|
||||
payload.set_issued_at(&util::time_to_std_time(&issued).unwrap());
|
||||
payload.set_expires_at(&util::time_to_std_time(&expire).unwrap());
|
||||
|
||||
let signer = josekit::jws::alg::hmac::HmacJwsAlgorithm::Hs256
|
||||
.signer_from_bytes(key.as_bytes())
|
||||
.unwrap();
|
||||
Ok((
|
||||
josekit::jwt::encode_with_signer(&payload, &header, &signer).unwrap(),
|
||||
(expire - time::OffsetDateTime::UNIX_EPOCH).whole_seconds(),
|
||||
))
|
||||
}
|
||||
Err(e) => Err(josekit::JoseError::InvalidClaim(e.into())),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn test_key() -> String {
|
||||
String::from("c3092urmc2219ix320i40m293ic29IM09IN0u879Y8B98YB8yb86TN7B55R4yv4RCVU6Bi8YO8U")
|
||||
}
|
||||
|
||||
fn test_resource() -> TokenResource {
|
||||
TokenResource {
|
||||
issuer: String::from("icarus_auth_test"),
|
||||
message: String::from("Authorization"),
|
||||
audiences: vec![String::from("icarus_test")],
|
||||
id: uuid::Uuid::nil(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_token_scope_check() {
|
||||
let mut token = Token::default();
|
||||
@@ -80,4 +185,45 @@ mod tests {
|
||||
check_scope, token.scope
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_token_creation() {
|
||||
let key = test_key();
|
||||
let test_token_resource = test_resource();
|
||||
let token_expiration_duration = time::Duration::hours(2);
|
||||
|
||||
match create_token(&key, &test_token_resource, token_expiration_duration) {
|
||||
Ok((token, expire_duration)) => {
|
||||
assert_eq!(false, token.is_empty(), "Error: Token is empty");
|
||||
assert!(
|
||||
expire_duration > 0,
|
||||
"Token expire duration is invalid {expire_duration:?}"
|
||||
);
|
||||
}
|
||||
Err(err) => {
|
||||
assert!(false, "Error: {err:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_token_creation_with_id() {
|
||||
let key = test_key();
|
||||
let mut test_token_resource = test_resource();
|
||||
test_token_resource.id = uuid::Uuid::new_v4();
|
||||
let token_expiration_duration = time::Duration::hours(2);
|
||||
|
||||
match create_token(&key, &test_token_resource, token_expiration_duration) {
|
||||
Ok((token, expire_duration)) => {
|
||||
assert_eq!(false, token.is_empty(), "Error: Token is empty");
|
||||
assert!(
|
||||
expire_duration > 0,
|
||||
"Token expire duration is invalid {expire_duration:?}"
|
||||
);
|
||||
}
|
||||
Err(err) => {
|
||||
assert!(false, "Error: {err:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
12
src/types.rs
12
src/types.rs
@@ -1,6 +1,16 @@
|
||||
pub enum MusicTypes {
|
||||
#[derive(Debug)]
|
||||
pub enum MusicType {
|
||||
DefaultMusicExtension,
|
||||
WavExtension,
|
||||
FlacExtension,
|
||||
MPThreeExtension,
|
||||
None,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum CoverArtType {
|
||||
PngExtension,
|
||||
JpegExtension,
|
||||
JpgExtension,
|
||||
None,
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ use crate::init;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[derive(Clone, Debug, Deserialize, Serialize, utoipa::ToSchema)]
|
||||
pub struct User {
|
||||
#[serde(skip_serializing_if = "init::is_uuid_nil")]
|
||||
pub id: uuid::Uuid,
|
||||
|
||||
19
src/util/mod.rs
Normal file
19
src/util/mod.rs
Normal file
@@ -0,0 +1,19 @@
|
||||
pub fn concatenate_path(
|
||||
directory: &str,
|
||||
filename: &str,
|
||||
last_index: usize,
|
||||
) -> Result<String, std::io::Error> {
|
||||
if let Some(character) = directory.chars().nth(last_index) {
|
||||
let buffer: String = if character != '/' {
|
||||
format!("{directory}/")
|
||||
} else {
|
||||
String::from(directory)
|
||||
};
|
||||
|
||||
Ok(format!("{buffer}{filename}"))
|
||||
} else {
|
||||
Err(std::io::Error::other(
|
||||
crate::constants::error::LAST_CHARACTER_IN_DIRECTORY,
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -30,16 +30,12 @@ mod utils {
|
||||
|
||||
#[cfg(test)]
|
||||
mod song_tests {
|
||||
use std::fs::File;
|
||||
use std::io::Write;
|
||||
|
||||
use tempfile::tempdir;
|
||||
|
||||
use crate::utils;
|
||||
use icarus_models::song;
|
||||
use icarus_models::types;
|
||||
|
||||
use crate::utils;
|
||||
|
||||
#[test]
|
||||
fn test_song_to_data() {
|
||||
println!("Test");
|
||||
@@ -65,7 +61,7 @@ mod song_tests {
|
||||
Ok(buffer) => {
|
||||
assert_eq!(buffer.is_empty(), false);
|
||||
|
||||
match song.to_data() {
|
||||
match song::io::to_data(&song) {
|
||||
Ok(song_data) => {
|
||||
println!("Both files match");
|
||||
assert_eq!(buffer, song_data);
|
||||
@@ -103,50 +99,56 @@ mod song_tests {
|
||||
song.directory = utils::get_tests_directory();
|
||||
song.filename = String::from("track01.flac");
|
||||
|
||||
match song.song_path() {
|
||||
Ok(songpath) => match utils::extract_data_from_file(&songpath) {
|
||||
Ok(buffer) => {
|
||||
let mut song_cpy = song.clone();
|
||||
let temp_dir = tempdir().expect("Failed to create temp dir");
|
||||
song_cpy.directory = match temp_dir.path().to_str() {
|
||||
Some(s) => String::from(s),
|
||||
None => String::new(),
|
||||
};
|
||||
let mut song_cpy = song.clone();
|
||||
let temp_dir = tempdir().expect("Failed to create temp dir");
|
||||
song_cpy.directory = match temp_dir.path().to_str() {
|
||||
Some(s) => String::from(s),
|
||||
None => String::new(),
|
||||
};
|
||||
|
||||
assert_eq!(song.directory.is_empty(), false);
|
||||
song_cpy.filename =
|
||||
song.generate_filename(types::MusicTypes::FlacExtension, true);
|
||||
println!("Directory: {:?}", song_cpy.directory);
|
||||
println!("File to be created: {:?}", song_cpy.filename);
|
||||
assert_eq!(song.directory.is_empty(), false);
|
||||
match song::generate_filename(types::MusicType::FlacExtension, true) {
|
||||
Ok(filename) => {
|
||||
song_cpy.filename = filename;
|
||||
}
|
||||
Err(err) => {
|
||||
assert!(false, "Error generatig filename: {err:?}");
|
||||
}
|
||||
};
|
||||
println!("Directory: {:?}", song_cpy.directory);
|
||||
println!("File to be created: {:?}", song_cpy.filename);
|
||||
|
||||
let path = match song_cpy.song_path() {
|
||||
Ok(s_path) => s_path,
|
||||
Err(err) => {
|
||||
assert!(false, "Error: {:?}", err);
|
||||
String::new()
|
||||
}
|
||||
};
|
||||
match song::io::copy_song(&song, &mut song_cpy) {
|
||||
Ok(_) => {
|
||||
println!("Song copied");
|
||||
}
|
||||
Err(err) => {
|
||||
assert!(false, "Error copying song: Error: {err:?}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match File::create(path) {
|
||||
Ok(mut file_cpy) => match file_cpy.write_all(&buffer) {
|
||||
Ok(success) => {
|
||||
println!("Success: {:?}", success);
|
||||
}
|
||||
Err(err) => {
|
||||
assert!(false, "Error saving file: {:?}", err);
|
||||
}
|
||||
},
|
||||
Err(err) => {
|
||||
assert!(false, "Error: {:?}", err);
|
||||
}
|
||||
};
|
||||
}
|
||||
#[test]
|
||||
fn test_save_song_to_filesystem_and_remove() {
|
||||
let mut song = song::Song::default();
|
||||
song.directory = utils::get_tests_directory();
|
||||
song.filename = String::from("track02.flac");
|
||||
|
||||
let mut copied_song = song::Song {
|
||||
directory: utils::get_tests_directory(),
|
||||
filename: String::from("track02-coppied.flac"),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
match song::io::copy_song(&song, &mut copied_song) {
|
||||
Ok(_) => match copied_song.remove_from_filesystem() {
|
||||
Ok(_) => {}
|
||||
Err(err) => {
|
||||
assert!(false, "Error: {:?}", err);
|
||||
assert!(false, "Error: {err:?}")
|
||||
}
|
||||
},
|
||||
Err(err) => {
|
||||
assert!(false, "Error extracting song data: {:?}", err);
|
||||
assert!(false, "Error: {err:?}")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -154,7 +156,6 @@ mod song_tests {
|
||||
|
||||
#[cfg(test)]
|
||||
mod album_tests {
|
||||
|
||||
use crate::utils;
|
||||
use icarus_models::album;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user