62 Commits

Author SHA1 Message Date
KD ca13f101d7 icarus_models version bump (#84)
* icarus_models version bump

* icarus_models related changes

* Removing method

* Code formatting

* Warning fix

* Removing comments

* Version bump

* cargo update
2025-10-19 23:52:43 -04:00
KD 1e4ffc798e Use official icarus_models version (#75)
* icarus_models v0.7.0

* Version bump
2025-10-13 20:58:30 -04:00
KD ecd025346c tsk-70: Rust update (#74)
* Updated rust in workflow

* Updated rust in cargo

* icarus_models version bump

* Version bump

* Workflow changes
2025-10-12 17:06:57 -04:00
KD 74184fa022 Dependency update (#73)
* Cargo update

* Updated crates

* Removed unused file

* Code cleanup

* Version bump

* Removed commented code
2025-10-12 16:57:49 -04:00
KD c2a2ca049d icarus_models version bump (#71)
* icarus_models version bump

* icarus_models related changes

* Warning fixes

* Version bump

* Test fix
2025-10-11 20:05:34 -04:00
KD 157887bfac Merge pull request #52 from kdeng00/icarus_v2_support
Support for icarus v2 API
2025-08-30 13:23:15 -04:00
kdeng00 2b77bb978c Version bump 2025-08-30 13:18:12 -04:00
KD 206ebf03be Updated License (#69) 2025-08-30 13:17:29 -04:00
KD 0d7d57bf5f Minor refatoring (#68)
* Removed old upload method

* Removed upload commit action

* Version bump
2025-08-30 13:13:53 -04:00
KD 11b8cc21d3 Delete song (#67)
* Changed code to comply with async

* Able to delete song

* Updated readme

* Code formatting and cleanup

* Version bump
2025-08-30 13:06:04 -04:00
KD e109789b18 Retrieve songs (#66)
* Able to retrieve songs

* Updated readme

* Removed unused import

* Code formatting

* Version bump
2025-08-30 12:10:03 -04:00
KD ec0cbd7da0 Download song (#65)
* Got download functionality working

* Updated readme

* Code formatting

* Updated help

* Version bump
2025-08-30 11:52:04 -04:00
KD 809f27cf01 Upload song (#58)
* Queue song (#57)

* Added code to queue song

* Making functions async

* Able to queue song

* Cleanup

* Link user to queued song (#59)

* Renaming queue_song function

* Queued song linked to user

* Cleanup and code formatting

* Queue metadata (#60)

* Added code to queue metadata

* Code formatting

* Queue coverart (#61)

* Added queued coverart code

* Code formatting and cleanup

* Link queued coverart to queued song (#62)

* Added code to link queued coverart to queued song

* Code formatting

* Update queued song status (#63)

* Added function call to update queued song status

* Added skeleton method

* Added more code to the method

* Got it working

* Code formatting

* Multi upload (#64)

* Added comments

* Added TODO

* Got it working

* Updated documentation

* Version bump

* Code formatting and cleanup
2025-08-29 21:59:54 -04:00
KD 8a07718ce8 Token fetch (#56)
* Added print statement and TODO

* Refactoring token fetching code

Adding two APIs. One for auth and the other for the main app

* Fixed token code

* Code formatting

* Cleanup
2025-08-27 16:33:18 -04:00
KD 77cb5c8599 Icarus models bump (#55)
* icarus_models bump

* Fix after depdenency update
2025-08-27 15:07:44 -04:00
KD dbcfcfa109 Warning fixes (#54)
* More warning fixes

* Should be the last of the warning fixes

* Code cleanup

* Code formatting
2025-07-02 19:25:08 -04:00
KD 8b2b2f82e9 Update dependencies (#53)
* Removing new lines

* Updated reqwest, tokio, tokio-utils, and uuid

* Including Cargo.lock in source control

* Not sure how this got here

* Updated icarus_models

* Workflow change

* Removing unused workflow

* Github workflow fix

* Warning fixes

* Fixed what caused failed test

* Code cleanup and formatting
2025-07-02 12:26:38 -04:00
KD 8e6ddbc9df Rust std change (#51)
* Targeting rust 1.88

* Workflow changes
2025-06-30 20:49:15 -04:00
KD c8ba6606be Icarus models update (#50)
* Updated dependencies

* Saving changes

* More changes

* More changes

* Updated dependencies

* Updated readme

* Saving changes

* Cleanup

* Updated icarus_models

* Updated icarus_models
2025-04-10 21:04:58 -04:00
KD b7d55ebcf4 Targeting rust 1.86 (#49)
* Targeting rust 1.86

* Workflow changes
2025-04-05 17:06:49 -04:00
KD d5f95ddf9b Updated dependencies (#48)
* Updated dependencies

* Saving changes

* More changes

* More changes

* Updated dependencies

* Updated readme

* Saving changes

* Cleanup
2025-04-03 23:16:37 -04:00
KD 885f1db3af Removed Versioning section (#46) 2025-04-03 21:46:18 -04:00
KD d6f45c8279 Updated git cloning (#47) 2025-04-03 21:46:04 -04:00
KD 58a88b1abd Merge pull request #45 from kdeng00/version_bump
Version bump
2025-03-30 16:04:07 -04:00
KD 9b181733a6 Version bump 2025-03-30 16:01:36 -04:00
KD 219b95bb2f Updated icarus_models (#44)
* Updated icarus_models

* Constants and url changes

* Refactoring

* Removed functions

* Fixing tests
2025-03-30 16:00:06 -04:00
KD 24e066d8d9 Merge pull request #43 from kdeng00/version_bump
Version bump
2025-03-26 19:09:00 -04:00
KD ab08792ff4 Updated dependencies (#42)
* Updated dependencies

* Will update version in separate commit
2025-03-26 19:07:08 -04:00
phoenix 9799edef33 Version bump 2025-03-26 19:02:22 -04:00
KD 92eb31a687 Add test (#41)
* Code refactoring

* Cleanup

* Added test and moved test files

* Cleanup

* Removed test mod file

* Tests reorganizing

* Removed test file
2025-03-25 22:43:42 -04:00
KD aa946a0a05 Code refactoring (#40)
* Code refactoring

* Cleanup
2025-03-25 22:14:26 -04:00
KD 19d6f2dc33 Code cleanup (#39)
* Code cleanup

* Removed unused source file
2025-03-24 19:51:41 -04:00
KD 4824e6f33a Updated wav reference to flac (#38) 2025-03-24 19:51:28 -04:00
KD 64935ea772 Updated icarus-model (#33)
* Updated icarus-model

* Updated icarus-model

* Saving changes

* Code formatting

* Removing code

* Updated icarus-model

* Updated token secret

* Added host

* Fix build issue

* Fix build warnings

* Saving changes

* Saving changes

* Refactoring

* Migrating over icarus-model coverart

* Removed song module

* Another one

* Meta single upload is functional

* Cleanup

* More cleanup

* Added test files (#37)

* Added test files

Need to add a coverarg image file

* Updated test album file

* Added coverart

* Uploading meta is operational

* Code cleanup

* Moved function

* Added string module
2025-03-24 19:34:38 -04:00
KD de90b0d0a1 Merge pull request #34 from kdeng00/refactoring
Refactoring
2025-03-15 20:37:04 -04:00
KD 19b943eed8 Merge pull request #32 from kdeng00/warning_fix
Warning fix
2025-03-14 22:54:59 -04:00
phoenix 8c781398b4 Wasn't using MyError 2025-03-14 22:51:17 -04:00
KD c575d2e523 Refactoring (#31)
* Refactoring code

* Code formatting

* More changes

* Moved to icarus-models::user

* Some refactoring

* Updated icarus-models

* Removing constants

* Replaced with icarus-models constants

* Formatting

* Switched to constants from icarus-models:

* Replaced Token with AccessToken from icarus-models

* Updated icarus-models

* Formatting

* Removing code
2025-03-13 21:40:22 -04:00
phoenix 03ed3deae6 Removing code 2025-03-13 21:37:32 -04:00
phoenix b69c111b66 Formatting 2025-03-13 21:34:11 -04:00
phoenix 8d97d4eb70 Updated icarus-models 2025-03-13 21:33:22 -04:00
phoenix 2f00ce6abf Replaced Token with AccessToken from icarus-models 2025-03-13 21:26:37 -04:00
phoenix e3cd1f4018 Switched to constants from icarus-models: 2025-03-13 21:19:37 -04:00
phoenix a9f9ba8350 Formatting 2025-03-13 20:58:34 -04:00
phoenix df60bef381 Replaced with icarus-models constants 2025-03-13 20:58:19 -04:00
phoenix 038142eb8a Removing constants 2025-03-13 20:53:43 -04:00
phoenix 69b81bc15c Updated icarus-models 2025-03-13 20:50:13 -04:00
phoenix b2e246d175 Some refactoring 2025-03-13 20:49:29 -04:00
phoenix c76e7b71b5 Moved to icarus-models::user 2025-03-13 19:59:09 -04:00
phoenix b8dccca158 More changes 2025-03-13 19:39:53 -04:00
phoenix b52607b4e3 Code formatting 2025-03-13 19:37:51 -04:00
phoenix ac970a4302 Refactoring code 2025-03-13 19:12:49 -04:00
KD a372bfcc05 Added icarus-models (#30)
* Added icarus-models

* Updated workflow

* Added ci workflow for ssh keys

* More changes

* More changes. again

* More changes. again.agg

* Another one

* Using secrets

* Forgot dereference

* Added variables

* Checking regular variable

* Updating

* Repository secret

* Checking size

* Another one

* Another one

* Another one

* Another one

* Another one

* Cargo file fix

* Another one

* Reorder

* Addded another step

* Change

* Another step

* Remove step

* Remove step

* Move on up

* Remove

* Cleanup

* Cleanup
2025-03-12 20:58:29 -04:00
KD d22850b280 Update packages (#29)
* Updating packages

* Updated serde packages

* Updated packages
2025-03-12 20:58:12 -04:00
KD 4d170f6a85 Merge pull request #28 from kdeng00/refactoring
Removing fields not used
2025-03-10 20:11:25 -04:00
phoenix 7391b1db68 Removing fields not used 2025-03-10 20:08:04 -04:00
KD 772641a8c4 Targeting rust 2024 (#27) 2025-03-02 20:53:14 -05:00
KD 4c99f88baf Updating packages (#24)
* Updating packages

* Updated serde packages
2025-03-02 20:52:33 -05:00
KD c3718c5add Added constant for flac file extension (#25) 2025-02-18 20:09:49 -05:00
KD a4d026e41f Updating song model (#26) 2025-02-18 20:09:11 -05:00
KD 6aa6f548a9 Create rust-ubuntu-latest.yml (#23)
* Create rust-ubuntu-latest.yml

* Create rust-macos-latest

* Delete .github/workflows/rust.yml
2025-02-02 16:07:52 -05:00
KD 53b83a809c Changed id field of the Song model (#22)
* Changed id field of the Song model

* Updated Readme
2025-02-01 21:43:01 -05:00
40 changed files with 3141 additions and 1380 deletions
+39
View File
@@ -0,0 +1,39 @@
name: Rust
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
env:
CARGO_TERM_COLOR: always
jobs:
build:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v5
- name: Install Rust version
run: rustup install 1.90.0 && rustup default 1.90.0
- name: Debug secret
run: echo "${{ secrets.MYREPO_TOKEN }}" | head -c 10 ; echo "..."
- name: Build
run: |
mkdir -p ~/.ssh
echo "$EXTREPO_KEY" > ~/.ssh/gitlab_deploy_key
chmod 600 ~/.ssh/gitlab_deploy_key
ssh-keyscan git.kundeng.us ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBLl/OZiKVDxwnyvMxa+rjKvDpKqTxH1GWuGuDPLmENGQMbTVulajZWr9x8Q1cotoJiHZkt7DA5vczcjB/4lwgWA= >> ~/.ssh/known_hosts
eval $(ssh-agent -s)
ssh-add -v ~/.ssh/gitlab_deploy_key
cargo build --release
env:
EXTREPO_KEY: ${{ secrets.MYREPO_TOKEN }}
- name: Run tests
run: cargo test --verbose
-23
View File
@@ -1,23 +0,0 @@
name: Rust
on:
push:
branches: [ "rust-lg" ]
pull_request:
branches: [ "rust-lg" ]
env:
CARGO_TERM_COLOR: always
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Build
run: cargo build --verbose
- name: Run tests
run: cargo test --verbose
-1
View File
@@ -7,4 +7,3 @@
/target
.vscode/
Cargo.lock
View File
Generated
+1991
View File
File diff suppressed because it is too large Load Diff
+12 -13
View File
@@ -1,18 +1,17 @@
[package]
name = "icarus-dm"
version = "0.4.0"
edition = "2021"
version = "0.8.2"
rust-version = "1.90"
edition = "2024"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
futures = { version = "0.3.30" }
http = { version = "1.1.0" }
reqwest = { version = "0.12.4", features = ["json", "blocking", "multipart", "stream"] }
serde = { version = "1.0.197", features = ["derive"] }
serde_json = "1.0.115"
tokio = { version = "1.37", features = ["full"] }
tokio-util = { version = "0.7.11", features = ["codec"] }
futures = { version = "0.3.31" }
http = { version = "1.3.1" }
reqwest = { version = "0.12.23", features = ["json", "blocking", "multipart", "stream"] }
serde = { version = "1.0.228", features = ["derive"] }
serde_json = "1.0.145"
tokio = { version = "1.47.1", features = ["full"] }
tokio-util = { version = "0.7.16", features = ["codec"] }
uuid = { version = "1.18.1", features = ["v4", "serde"] }
icarus_models = { git = "ssh://git@git.kundeng.us/phoenix/icarus_models.git", tag = "v0.8.0" }
+1 -1
View File
@@ -1,6 +1,6 @@
MIT License
Copyright (c) 2019 Kun Deng
Copyright (c) 2025 Kun Deng
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
+11 -14
View File
@@ -14,6 +14,7 @@ IcarusDownloadManager is a CLI software client application that has the feature
* serde_json
* tokio
* tokio-util
* icarus_models
### Getting Started
@@ -21,7 +22,7 @@ IcarusDownloadManager is a CLI software client application that has the feature
Clone the repo
```BASH
git clone --recursive https://github.com/kdeng00/IcarusDownloadManager
git clone git@github.com:kdeng00/IcarusDownloadManager.git
```
@@ -32,36 +33,40 @@ cd IcarusDownloadManager
cargo build
```
Even though this project is open source, there are some libraries that are closed source (may be opened later).
In order to successfully build it, your ssh public key would be needed to add to the closed libraries. If you
have interest, something could be worked out to provide access.
The program has been built and can be executed by the binary file *icarus-dm*. For information on how to use icarua-dm, merely execute the program without any command line arguments.
### Downloading Song
```BASH
icarus-dm download -u spacecadet -p stellar40 -h https://icarus.com -b 15
icarus-dm download -u spacecadet -p stellar40 -h https://icarus.com -ha https://auth.icarus.com -b e8407fc6-edd2-44c1-993f-08dd7324d91a
```
### Uploading Song with metadata
```BASH
icarus-dm upload-meta -u spacecadet -p stellar40 -h https://icarus.com -s /path/of/song.mp3 -t 1 -m /path/to/metadata/config/collection.json -ca /path/to/cover/art/image.png
icarus-dm upload-meta -u spacecadet -p stellar40 -h https://icarus.com -ha https://auth.icarus.com -s /path/of/song.flac -t 1 -m /path/to/metadata/config/collection.json -ca /path/to/cover/art/image.png
```
### Uploading Song with metadata from directory
```BASH
icarus-dm upload-meta -u spacecadet -p stellar40 -h https://icarus.com -smca /path/where/songs/and/metadata/exists/
icarus-dm upload-meta -u spacecadet -p stellar40 -h https://icarus.com -ha https://auth.icarus.com -smca /path/where/songs/and/metadata/exists/
```
### Retrieving Song in json
```Bash
icarus-dm retrieve -u spacecadet -p stellar40 -h https://icarus.com -rt songs
icarus-dm retrieve -u spacecadet -p stellar40 -h https://icarus.com -ha https://auth.icarus.com -rt songs
```
### Deleting Song
```BASH
icarus-dm delete -u spacecadet -p stellar40 -h https://icarus.com -D 15
icarus-dm delete -u spacecadet -p stellar40 -h https://icarus.com -ha https://auth.icarus.com -D e8407fc6-edd2-44c1-993f-08dd7324d91a
```
@@ -69,15 +74,7 @@ icarus-dm delete -u spacecadet -p stellar40 -h https://icarus.com -D 15
Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on the code of conduct, and the process for submitting pull requests to the project.
## Versioning
[v0.4.0](https://github.com/kdeng00/IcarusDownloadManager/releases/tag/v0.4.0)
[v0.3.2](https://github.com/kdeng00/IcarusDownloadManager/releases/tag/v0.3.2)
[v0.3.0](https://github.com/kdeng00/IcarusDownloadManager/releases/tag/v0.3.0)
[v0.2.0](https://github.com/kdeng00/IcarusDownloadManager/releases/tag/v0.2.0)
[v0.1.2](https://github.com/kdeng00/IcarusDownloadManager/releases/tag/v0.1.2)
[v0.1.1](https://github.com/kdeng00/IcarusDownloadManager/releases/tag/v0.1.1)
[v0.1.0](https://github.com/kdeng00/IcarusDownloadManager/releases/tag/0.1.0)
## License
-3
View File
@@ -1,3 +0,0 @@
pub const WAV_FILE_EXTENSION: &str = ".wav";
pub const _MP3_FILE_EXTENSION: &str = ".mp3";
pub const JPG_FILE_EXTENSION: &str = ".jpg";
-1
View File
@@ -1 +0,0 @@
pub mod file_extensions;
+37
View File
@@ -0,0 +1,37 @@
pub fn print_help() {
let msg: String = String::from(
r#"icd [Action] [flag]
Actions
download
upload-meta
retrieve
delete
Flags
Required for all actions
-u username
-p password
-h api host
-ha auth api host
Required for upload with metadata
-s path of song
-t track number
-m metadata filepath
-ca coverart filepath
-scma directory where songs, metadata, and cover art exists and will be uploaded (Optional)
Required for download
-b song id
-d path to download song (Optional)
Required for retrieving records
-rt retrieve type (songs is only accepted)
Required for deleting a song
-D song id"#,
);
println!("{msg}");
}
+125 -59
View File
@@ -1,4 +1,4 @@
mod constants;
mod help;
mod managers;
mod models;
mod parsers;
@@ -6,76 +6,142 @@ mod syncers;
mod utilities;
use std::env;
use std::process;
fn exit_program(code: i32) {
process::exit(code);
}
fn print_help() {
let msg: String = String::from(
r#"icd [Action] [flag]
Actions
download
upload-meta
retrieve
delete
Flags
Required for all actions
-u username
-p password
-h host
Required for upload with metadata
-s path of song
-t track number
-m metadata filepath
-ca coverart filepath
-scma directory where songs, metadata, and cover art exists and will be uploaded (Optional)
Required for download
-b song id
-d path to download song (Optional)
Required for retrieving records
-rt retrieve type (songs is only accepted)
Required for deleting a song
-D song id"#,
);
println!("{}", msg);
}
fn main() {
#[tokio::main]
async fn main() {
let args: Vec<String> = env::args().collect();
if args.len() == 1 {
print_help();
exit_program(-1);
}
let args_len = args.len() as i32;
println!("Argument count: {}", args_len);
if args_len == 1 {
help::print_help();
utilities::checks::exit_program(-1);
}
let mut act_mgr = managers::action_managers::ActionManager {
action: String::new(),
flags: Vec::new(),
params: args,
param_count: args_len,
};
println!("Argument count: {args_len}");
let mut act_mgr = managers::action_managers::ActionManager::default();
act_mgr.set_params(&args);
act_mgr.initialize();
let chosen_act = act_mgr.retrieve_icarus_action();
chosen_act.print_action_and_flags();
let mut cmt_mgr = managers::commit_manager::CommitManager {
ica_action: chosen_act,
};
cmt_mgr.commit_action();
cmt_mgr.commit_action().await;
}
#[cfg(test)]
mod tests {
use crate::managers;
#[test]
fn test_song_prep_upload() {
let meta_path = String::from("tests/sample2_tracks/album.json");
if !std::path::Path::new(&meta_path).exists() {
assert!(false, "File does not exists: {meta_path:?}");
}
match icarus_models::album::collection::parse_album(&meta_path) {
Ok(album) => {
for track in 1..3 {
let directory_path = std::path::Path::new(&meta_path);
let directory: String = directory_path.parent().unwrap().display().to_string();
let filename: String = if track < 10 {
String::from("track0")
+ &track.to_string()
+ icarus_models::constants::file_extensions::audio::DEFAULTMUSICEXTENSION
} else {
String::from("track")
+ &track.to_string()
+ icarus_models::constants::file_extensions::audio::DEFAULTMUSICEXTENSION
};
let disc = 1;
match managers::commit_manager::retrieve_song(
&album, track, disc, &directory, &filename,
) {
Ok(song) => match icarus_models::song::io::to_data(&song) {
Ok(_) => {
print!("Success");
}
Err(err) => {
assert!(false, "Error: {:?}", err.to_string());
}
},
Err(err) => {
assert!(false, "Error: {:?}", err.to_string());
}
}
}
}
Err(err) => {
assert!(false, "Error: {:?}", err.to_string());
}
}
}
#[test]
fn test_minimum_action_and_args() {
let args: Vec<String> = vec![
"icarus-dm".to_string(),
"download".to_string(),
"-u".to_string(),
"jamborie".to_string(),
"-p".to_string(),
"somethingsecr3t!".to_string(),
"-h".to_string(),
"https://music-server.com".to_string(),
];
let arg_count = args.len() as i32;
let minimum_arg_count = 8;
assert!(arg_count >= minimum_arg_count);
let mut act_mgr = managers::action_managers::ActionManager {
action: String::new(),
flags: Vec::new(),
params: args,
param_count: arg_count,
};
act_mgr.initialize();
let ica = act_mgr.retrieve_icarus_action();
let action = &ica.action;
let flags = &ica.flags;
assert!(action != "");
assert!(flags.len() > 2);
assert!(
!(action != "download"
&& action != "upload"
&& action != "retrieve"
&& action != "upload-meta")
);
let mut found_count = 0;
let mut flags_already_read = Vec::new();
for flag in flags {
if flags_already_read.contains(&flag.flag) {
continue;
}
if flag.flag == "-u" {
found_count += 1;
flags_already_read.push(flag.flag.clone());
} else if flag.flag == "-p" {
found_count += 1;
flags_already_read.push(flag.flag.clone());
} else if flag.flag == "-h" {
found_count += 1;
flags_already_read.push(flag.flag.clone());
}
}
let all_flags_found = found_count == 3;
assert_eq!(found_count, 3, "Three flags are required: -u, -p, -h");
assert!(all_flags_found, "All flags have not been found");
}
}
+35 -91
View File
@@ -1,6 +1,6 @@
use serde::{Deserialize, Serialize};
use crate::models;
use crate::{models, utilities};
#[derive(Debug, Deserialize, Serialize)]
pub struct ActionManager {
@@ -10,20 +10,32 @@ pub struct ActionManager {
pub param_count: i32,
}
impl Default for ActionManager {
fn default() -> Self {
ActionManager {
action: String::new(),
flags: Vec::new(),
params: Vec::new(),
param_count: -1,
}
}
}
impl ActionManager {
pub fn retrieve_icarus_action(&self) -> models::icarus_action::IcarusAction {
return models::icarus_action::IcarusAction {
models::icarus_action::IcarusAction {
flags: self.flags.clone(),
action: String::from(&self.action),
};
}
}
fn supported_flags(&self) -> Vec<String> {
return vec![
vec![
String::from("-u"),
String::from("-p"),
String::from("-t"),
String::from("-h"),
String::from("-ha"),
String::from("-s"),
String::from("-sd"),
String::from("-sr"),
@@ -36,7 +48,7 @@ impl ActionManager {
String::from("-ca"),
String::from("-smca"),
String::from("-t"),
];
]
}
pub fn initialize(&mut self) {
@@ -45,6 +57,11 @@ impl ActionManager {
self.action = self.action.to_lowercase();
}
pub fn set_params(&mut self, args: &[String]) {
self.params = args.to_owned();
self.param_count = self.params.len() as i32;
}
fn validate_flags(&mut self) {
println!("Validating flags");
@@ -55,26 +72,26 @@ impl ActionManager {
while i < flag_vals.len() {
let flag = &flag_vals[i];
println!("Index: {} | Value: {}", i, flag);
println!("Index: {i} | Value: {flag}");
let mut flg = models::flags::Flags::default();
// TODO: Refactor this
if self.is_valid_flag(flag) && self.does_flag_have_value(flag) {
println!("Flag has value");
flg.flag = String::from(flag);
flg.value = String::from(&flag_vals[i + 1]);
i = i + 1;
i += 1;
} else if self.is_valid_flag(flag) {
println!("Flag does not have a value");
flg.flag = String::from(flag);
} else {
println!("Flag {} is not valid", flag);
std::process::exit(-1);
println!("Flag {flag} is not valid");
utilities::checks::exit_program(-1);
}
self.flags.push(flg);
println!("");
i += 1;
}
}
@@ -97,35 +114,30 @@ impl ActionManager {
}
}
return found;
found
}
fn does_flag_have_value(&self, flag: &String) -> bool {
let flags_tmp = self.parsed_flags();
let mut i_found: i32 = -1;
for i in 0..flags_tmp.len() {
let flg = &flags_tmp[i];
if flg == flag {
for (i, item) in flags_tmp.iter().enumerate() {
let flg = &item;
if *flg == flag {
i_found = i as i32;
break;
}
}
if i_found >= 0 {
if (i_found + 1) < flags_tmp.len().try_into().unwrap() {
return true;
(i_found + 1) < flags_tmp.len().try_into().unwrap()
} else {
return false;
}
} else {
return false;
false
}
}
fn _print_action(&self) {
if self.action.len() == 0 {
if self.action.is_empty() {
println!("Action is empty");
} else {
println!("Action is {}", self.action);
@@ -148,74 +160,6 @@ impl ActionManager {
parsed.push(flag);
}
return parsed;
}
}
#[cfg(test)]
mod tests {
use crate::managers::action_managers::ActionManager;
#[test]
fn minimum_action_and_args() {
let args: Vec<String> = vec![
"icarus-dm".to_string(),
"download".to_string(),
"-u".to_string(),
"jamborie".to_string(),
"-p".to_string(),
"somethingsecr3t!".to_string(),
"-h".to_string(),
"https://music-server.com".to_string(),
];
let arg_count = args.len() as i32;
let minimum_arg_count = 8;
assert!(arg_count >= minimum_arg_count);
let mut act_mgr = ActionManager {
action: String::new(),
flags: Vec::new(),
params: args,
param_count: arg_count,
};
act_mgr.initialize();
let ica = act_mgr.retrieve_icarus_action();
let action = &ica.action;
let flags = &ica.flags;
assert!(action != "");
assert!(flags.len() > 2);
assert!(
!(action != "download"
&& action != "upload"
&& action != "retrieve"
&& action != "upload-meta")
);
let mut all_flags_found = false;
let mut found_count = 0;
let mut flags_already_read = Vec::new();
for flag in flags {
if flags_already_read.contains(&flag.flag) {
continue;
}
if flag.flag == "-u" {
found_count += 1;
flags_already_read.push(flag.flag.clone());
} else if flag.flag == "-p" {
found_count += 1;
flags_already_read.push(flag.flag.clone());
} else if flag.flag == "-h" {
found_count += 1;
flags_already_read.push(flag.flag.clone());
}
}
all_flags_found = found_count == 3;
assert_eq!(found_count, 3, "Three flags are required: -u, -p, -h");
assert!(all_flags_found, "All flags have not been found");
parsed
}
}
File diff suppressed because it is too large Load Diff
-64
View File
@@ -1,64 +0,0 @@
use std::default::Default;
pub struct FileManager {
pub filepath: String,
pub filebuffer: String,
pub file_read: bool,
pub file_buffer_length: i32,
}
impl Default for FileManager {
fn default() -> Self {
FileManager {
filepath: String::new(),
filebuffer: String::new(),
file_read: false,
file_buffer_length: -1
}
}
}
impl FileManager {
// TODO: Implement
pub fn init(&mut self) {
self.read_file()
}
pub fn save_file(&mut self, filepath: &String) {
if !self.file_read {
self.read_file();
}
let mut file = File::open(filepath)?;
let mut buffer = Vec::new();
file.read_to_end(&mut buffer)?;
self.file_buffer_length = buffer.len();
self.filebuffer = String::from_utf8(buffer); // Assuming UTF-8 encoding
}
pub fn modify_file_path(&mut self, file: &String) {
self.filepath = file;
}
pub fn retrieve_file_buffer(&self) -> String {
self.filebuffer;
}
pub fn retrieve_file_length(&self) -> i32 {
self.file_buffer_length;
}
fn read_file(&mut self) -> Vec<u8> {
let mut file = File::open(self.filepath)?;
let mut buffer = Vec::new();
file.read_to_end(&mut buffer)?;
self.file_buffer_length = buffer.len();
self.filebuffer = String::from_utf8(buffer); // Assuming UTF-8 encoding
self.file_read = true;
return buffer;
}
}
+39 -19
View File
@@ -2,33 +2,50 @@ use std::default::Default;
use crate::models;
mod response {
pub mod token {
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct Response {
pub message: String,
pub data: Vec<icarus_models::login_result::LoginResult>,
}
}
}
pub struct TokenManager {
pub user: models::user::User,
pub api: models::api::API,
pub user: icarus_models::user::User,
pub api: models::api::Api,
}
impl Default for TokenManager {
fn default() -> Self {
let mut token = TokenManager {
user: models::user::User::default(),
api: models::api::API::default(),
user: icarus_models::user::User::default(),
api: models::api::Api::default(),
};
token.init();
return token;
token
}
}
impl TokenManager {
pub async fn request_token(&self) -> Result<models::token::Token, std::io::Error> {
pub async fn request_token(&self) -> Result<icarus_models::token::AccessToken, std::io::Error> {
println!("Sending request for a token");
let url = self.retrieve_url();
println!("URL: {}", url);
println!("URL: {url}");
let mut token = models::token::Token::default();
let mut token = icarus_models::token::AccessToken {
user_id: uuid::Uuid::nil(),
username: String::new(),
token: String::new(),
token_type: String::new(),
expiration: -1,
message: String::new(),
};
let client = reqwest::Client::new();
let response = client.post(&url).json(&self.user).send().await.unwrap();
@@ -36,11 +53,15 @@ impl TokenManager {
match response.status() {
reqwest::StatusCode::OK => {
// on success, parse our JSON to an APIResponse
let s = response.json::<models::token::Token>().await;
match s {
//
Ok(parsed) => {
token = parsed;
match response.json::<response::token::Response>().await {
Ok(response) => {
let login_result = &response.data[0];
token.user_id = login_result.id;
token.username = login_result.username.clone();
token.token = login_result.token.clone();
token.token_type = login_result.token_type.clone();
token.expiration = login_result.expiration;
token.message = response.message;
}
Err(_) => println!("Hm, the response didn't match the shape we expected."),
};
@@ -49,25 +70,24 @@ impl TokenManager {
println!("Need to grab a new token");
}
other => {
panic!("Uh oh! Something unexpected happened: {:?}", other);
panic!("Uh oh! Something unexpected happened: {other:?}");
}
}
return Ok(token);
Ok(token)
}
pub fn init(&mut self) {
let api = &mut self.api;
api.version = String::from("v1");
api.endpoint = String::from(format!("api/{}/login", api.version));
api.version = String::from(crate::parsers::api_parser::API_VERSION);
api.endpoint = format!("api/{}/login", api.version);
}
pub fn retrieve_url(&self) -> String {
let api = &self.api;
let mut url = String::from(&api.url);
url += &String::from(&api.endpoint);
url += &String::from("/");
return url;
url
}
}
+12 -15
View File
@@ -4,38 +4,35 @@ use serde::{Deserialize, Serialize};
use crate::models::{self};
#[derive(Debug, Deserialize, Serialize)]
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct UserManager {
pub user: models::user::User,
pub user: icarus_models::user::User,
pub ica_action: models::icarus_action::IcarusAction,
}
impl Default for UserManager {
fn default() -> Self {
UserManager {
user: models::user::User::default(),
ica_action: models::icarus_action::IcarusAction::default(),
}
}
}
impl UserManager {
pub fn retrieve_user(&self) -> models::user::User {
return self.user.clone();
pub fn retrieve_user(&self) -> icarus_models::user::User {
self.user.clone()
}
pub fn parse_user_from_actions(&mut self) {
let args = &self.ica_action.flags;
// Quit the loop when two are found
let mut amt: i32 = 0;
for arg in args {
let flag = &arg.flag;
if flag == "-u" {
self.user.username = String::from(&arg.value);
amt += 1;
} else if flag == "-p" {
self.user.password = String::from(&arg.value);
amt += 1;
}
if flag == "-p" {
self.user.password = String::from(&arg.value);
if amt == 2 {
break;
}
}
}
+2 -12
View File
@@ -2,19 +2,9 @@ use std::default::Default;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct API {
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct Api {
pub url: String,
pub endpoint: String,
pub version: String,
}
impl Default for API {
fn default() -> Self {
API {
url: String::new(),
endpoint: String::new(),
version: String::new(),
}
}
}
+1 -10
View File
@@ -2,17 +2,8 @@ use std::default::Default;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, Serialize)]
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct Flags {
pub flag: String,
pub value: String,
}
impl Default for Flags {
fn default() -> Self {
Flags {
flag: String::new(),
value: String::new(),
}
}
}
+2 -11
View File
@@ -4,21 +4,12 @@ use serde::{Deserialize, Serialize};
use crate::models;
#[derive(Clone, Debug, Deserialize, Serialize)]
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct IcarusAction {
pub action: String,
pub flags: Vec<models::flags::Flags>,
}
impl Default for IcarusAction {
fn default() -> Self {
IcarusAction {
action: String::new(),
flags: Vec::new(),
}
}
}
impl IcarusAction {
pub fn retrieve_flag_value(&self, flag: &String) -> String {
let mut val: String = String::new();
@@ -30,7 +21,7 @@ impl IcarusAction {
}
}
return val;
val
}
pub fn print_action_and_flags(&self) {
-4
View File
@@ -1,7 +1,3 @@
pub mod api;
pub mod flags;
pub mod icarus_action;
pub mod song;
pub mod token;
pub mod upload_form;
pub mod user;
-171
View File
@@ -1,171 +0,0 @@
use std::default::Default;
use std::io::Read;
use serde::{Deserialize, Serialize};
use crate::constants;
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Song {
#[serde(alias = "song_id")]
pub id: Option<i32>,
pub title: Option<String>,
pub artist: Option<String>,
pub album: Option<String>,
pub genre: Option<String>,
pub year: Option<i32>,
pub duration: Option<f64>,
pub track: Option<i32>,
pub disc: Option<i32>,
pub data: Option<Vec<u8>>,
pub filepath: Option<String>,
pub directory: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct Album {
#[serde(alias = "album")]
pub title: String,
pub album_artist: String,
pub genre: String,
pub year: i32,
pub track_count: i32,
pub disc_count: i32,
#[serde(alias = "tracks")]
pub songs: Vec<Song>,
}
impl Default for Album {
fn default() -> Self {
Album {
title: String::new(),
album_artist: String::new(),
genre: String::new(),
year: 0,
track_count: 0,
disc_count: 0,
songs: Vec::new(),
}
}
}
impl Default for Song {
fn default() -> Self {
Song {
id: None,
title: None,
artist: None,
album: None,
genre: None,
year: None,
duration: None,
track: None,
disc: None,
data: None,
filepath: None,
directory: None,
}
}
}
impl Song {
pub fn print_info(&self) {
println!("Title: {:?}", self.title);
println!("Artist: {:?}", self.artist);
}
pub fn song_path(&self) -> String {
let directory =
&<std::option::Option<std::string::String> as Clone>::clone(&self.directory).unwrap();
let mut buffer: String = directory.to_string();
let count = buffer.len();
if buffer.chars().nth(count - 1) != Some('/') {
buffer += "/";
}
let filename =
&<std::option::Option<std::string::String> as Clone>::clone(&self.filepath).unwrap();
buffer += filename;
return buffer;
}
pub fn to_data(&self) -> Result<Vec<u8>, std::io::Error> {
let path = self.song_path();
println!("Converting song to data");
println!("Path: {:?}", path);
let mut file = std::fs::File::open(path)?;
let mut buffer = Vec::new();
file.read_to_end(&mut buffer)?;
if buffer.len() == 0 {
println!("Why is it empty?");
}
Ok(buffer)
}
// if 1 - wav, if 0 - mp3, anything else defaults to wav
pub fn _generate_filename_from_track(&mut self, i_type: i32) -> i32 {
let mut filename: String = String::new();
if self.track.unwrap() < 10 {
filename += "0";
}
filename += &self.track.unwrap().to_string();
if i_type == 0 {
filename += constants::file_extensions::_MP3_FILE_EXTENSION;
} else {
filename += constants::file_extensions::WAV_FILE_EXTENSION;
}
self.filepath = Some(filename);
return 0;
}
pub fn _to_metadata_json(&self) -> Result<String, serde_json::Error> {
return serde_json::to_string_pretty(&self);
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CoverArt {
pub id: Option<i32>,
pub title: Option<String>,
pub path: Option<String>,
pub data: Option<Vec<u8>>,
}
impl Default for CoverArt {
fn default() -> Self {
CoverArt {
id: None,
title: None,
path: None,
data: None,
}
}
}
impl CoverArt {
pub fn to_data(&self) -> Result<Vec<u8>, std::io::Error> {
let mut path: String = String::new();
match &self.path {
Some(val) => {
path = String::from(val);
}
None => {
();
}
}
let mut file = std::fs::File::open(path)?;
let mut buffer = Vec::new();
file.read_to_end(&mut buffer)?;
Ok(buffer)
}
}
-47
View File
@@ -1,47 +0,0 @@
use std::default::Default;
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize)]
pub struct Token {
#[serde(alias = "user_id")]
pub user_id: i32,
#[serde(alias = "username")]
pub username: Option<String>,
#[serde(alias = "token")]
pub access_token: Option<String>,
#[serde(alias = "token_type")]
pub token_type: Option<String>,
#[serde(alias = "expiration")]
pub expiration: Option<i32>,
#[serde(alias = "message")]
pub message: Option<String>,
}
impl Default for Token {
fn default() -> Self {
Token {
user_id: -1,
username: None,
access_token: None,
token_type: None,
expiration: None,
message: None,
}
}
}
impl Token {
pub fn bearer_token(&self) -> String {
let mut token: String = String::from("Bearer ");
match &self.access_token {
Some(tok) => {
token += tok;
}
None => {}
}
return token;
}
}
-18
View File
@@ -1,18 +0,0 @@
use std::default::Default;
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize)]
pub struct UploadForm {
pub url: Option<String>,
pub filepath: Option<String>,
}
impl Default for UploadForm {
fn default() -> Self {
UploadForm {
url: None,
filepath: None,
}
}
}
-24
View File
@@ -1,24 +0,0 @@
use std::default::Default;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct User {
pub username: String,
pub password: String,
}
impl Default for User {
fn default() -> Self {
User {
username: String::new(),
password: String::new(),
}
}
}
impl User {
pub fn _to_json(&self) -> Result<String, serde_json::Error> {
return serde_json::to_string_pretty(&self);
}
}
+33 -7
View File
@@ -2,16 +2,26 @@ use crate::models;
#[derive(Clone, Debug)]
pub struct APIParser {
pub api: models::api::API,
pub apis: Vec<models::api::Api>,
pub ica_act: models::icarus_action::IcarusAction,
}
pub const API_VERSION: &str = "v2";
pub enum APIType {
Main,
Auth,
}
impl APIParser {
pub fn retrieve_api(&self) -> models::api::API {
return self.api.clone();
pub fn retrieve_api(&self, api_type: APIType) -> models::api::Api {
match api_type {
APIType::Main => self.apis[0].clone(),
APIType::Auth => self.apis[1].clone(),
}
}
pub fn parse_api(&mut self) {
pub fn parse_api(&mut self, api_type: APIType) {
let flags = self.ica_act.flags.clone();
println!("Parsing api");
@@ -19,16 +29,32 @@ impl APIParser {
let arg = elem.flag;
let value = elem.value;
match api_type {
APIType::Main => {
if arg == "-h" {
if value.chars().nth(value.len() - 1) == Some('/') {
self.api.url = value;
self.apis[0].url = value;
} else {
self.api.url = value + "/";
self.apis[0].url = format!("{value}/");
}
break;
}
}
APIType::Auth => {
if arg == "-ha" {
if value.chars().nth(value.len() - 1) == Some('/') {
self.apis[1].url = value;
} else {
self.apis[1].url = format!("{value}/");
}
break;
}
}
}
}
self.api.version = "v1".to_string();
for api in &mut self.apis {
api.version = String::from(API_VERSION);
}
}
}
+30
View File
@@ -0,0 +1,30 @@
use crate::models;
pub fn retrieve_url(api: &models::api::Api, with_id: bool, id: &uuid::Uuid) -> String {
if with_id {
retrieve_url_with_id(api, id)
} else {
retrieve_url_reg(api)
}
}
fn retrieve_url_reg(api: &models::api::Api) -> String {
let url = format!("{}api/{}/{}/", api.url, api.version, api.endpoint);
url
}
fn retrieve_url_with_id(api: &models::api::Api, id: &uuid::Uuid) -> String {
let url = format!("{}api/{}/{}/{}", api.url, api.version, api.endpoint, id);
url
}
pub async fn auth_header(
token: &icarus_models::token::AccessToken,
) -> (http::HeaderName, http::HeaderValue) {
let auth = reqwest::header::AUTHORIZATION;
let auth_value = http::HeaderValue::from_str(&token.bearer_token()).unwrap();
(auth, auth_value)
}
+32 -40
View File
@@ -4,15 +4,23 @@ use reqwest;
use crate::models;
#[derive(Clone, Debug)]
#[derive(Clone, Debug, Default)]
pub struct Delete {
pub api: models::api::API,
pub api: models::api::Api,
}
impl Default for Delete {
fn default() -> Self {
Delete {
api: models::api::API::default(),
mod response {
pub mod delete_song {
#[derive(Debug, serde::Deserialize)]
pub struct SongAndCoverArt {
pub song: icarus_models::song::Song,
pub coverart: icarus_models::coverart::CoverArt,
}
#[derive(Debug, serde::Deserialize)]
pub struct Response {
pub message: String,
pub data: Vec<SongAndCoverArt>,
}
}
}
@@ -20,11 +28,14 @@ impl Default for Delete {
impl Delete {
pub async fn delete_song(
&mut self,
token: &models::token::Token,
song: &models::song::Song,
) -> Result<models::song::Song, std::io::Error> {
self.api.endpoint = "song/data/delete".to_owned();
let url = self.retrieve_url(&song);
token: &icarus_models::token::AccessToken,
song: &icarus_models::song::Song,
) -> Result<(icarus_models::song::Song, icarus_models::coverart::CoverArt), std::io::Error>
{
self.api.endpoint = "api/v2/song".to_owned();
let url = format!("{}{}/{}", self.api.url, self.api.endpoint, song.id);
println!("Url: {url:?}");
let client = reqwest::Client::builder().build().unwrap();
let access_token = token.bearer_token();
let response = client
@@ -33,40 +44,21 @@ impl Delete {
.send()
.await
.unwrap();
let mut sng = models::song::Song::default();
match response.status() {
reqwest::StatusCode::OK => {
println!("Success!");
let s = response.json::<models::song::Song>().await;
match s {
//
Ok(parsed) => {
sng = parsed;
}
Err(er) => {
println!("Error {:?}", er);
}
};
}
other => {
panic!("Issue occurred: {:?}", other);
}
}
return Ok(sng);
match response.json::<response::delete_song::Response>().await {
Ok(resp) => {
println!("Response message: {:?}", resp.message);
let data = &resp.data[0];
Ok((data.song.clone(), data.coverart.clone()))
}
Err(er) => Err(std::io::Error::other(er.to_string())),
}
}
other => Err(std::io::Error::other(other.to_string())),
}
fn retrieve_url(&self, song: &models::song::Song) -> String {
let api = &self.api;
let mut url: String = String::from(&api.url);
url += &String::from("api/");
url += &String::from(&api.version);
url += &String::from("/");
url += &String::from(&api.endpoint);
url += &String::from("/");
url += &song.id.unwrap().to_string();
return url;
}
}
+21 -53
View File
@@ -1,82 +1,50 @@
use std::default::Default;
use crate::models;
use crate::syncers;
#[derive(Default)]
pub struct Download {
pub api: models::api::API,
}
impl Default for Download {
fn default() -> Self {
Download {
api: models::api::API::default(),
}
}
pub api: models::api::Api,
}
#[derive(Debug)]
pub enum MyError {
_Request(reqwest::Error),
Request(reqwest::Error),
Other(String),
}
impl Download {
pub async fn download_song(
&mut self,
token: &models::token::Token,
song: &models::song::Song,
token: &icarus_models::token::AccessToken,
song: &icarus_models::song::Song,
) -> Result<String, MyError> {
self.api.endpoint = String::from("song/data/download");
let url = self.retrieve_url(&song);
self.api.endpoint = String::from("song/download");
let url = syncers::common::retrieve_url(&self.api, true, &song.id);
let access_token = token.bearer_token();
let mut headers = reqwest::header::HeaderMap::new();
headers.insert(
reqwest::header::AUTHORIZATION,
http::header::HeaderValue::from_str(&access_token.clone()).unwrap(),
);
println!("Url: {url:?}");
let client = reqwest::Client::builder().build().unwrap();
let response = client
match client
.get(&url)
.header(reqwest::header::AUTHORIZATION, &access_token)
.send()
.await
.unwrap();
match response.status() {
reqwest::StatusCode::OK => {
let data = response.text();
match data.await {
Ok(e) => {
return Ok(e);
}
Err(er) => {
println!("Error {:?}", er);
}
}
}
{
Ok(rep) => match rep.status() {
reqwest::StatusCode::OK => match rep.text().await {
Ok(e) => Ok(e),
Err(er) => Err(MyError::Other(er.to_string())),
},
reqwest::StatusCode::UNAUTHORIZED => {
println!("Need to grab a new token");
Err(MyError::Other(String::from("Need to grab a new token")))
}
other => {
panic!("Uh oh! Something unexpected happened: {:?}", other);
other => Err(MyError::Other(other.to_string())),
},
Err(er) => Err(MyError::Request(er)),
}
}
return Err(MyError::Other(String::from("Error downloading")));
}
fn retrieve_url(&self, song: &models::song::Song) -> String {
let api = &self.api;
let mut url: String = String::from(&api.url);
url += &String::from("api/");
url += &String::from(&api.version);
url += &String::from("/");
url += &String::from(&api.endpoint);
url += &String::from("/");
url += &song.id.unwrap().to_string();
return url;
}
}
+1
View File
@@ -1,3 +1,4 @@
pub mod common;
pub mod delete;
pub mod download;
pub mod retrieve_records;
+21 -44
View File
@@ -3,14 +3,17 @@ use std::io::Error;
use crate::models;
#[derive(Default)]
pub struct RetrieveRecords {
pub api: models::api::API,
pub api: models::api::Api,
}
impl Default for RetrieveRecords {
fn default() -> Self {
RetrieveRecords {
api: models::api::API::default(),
mod response {
pub mod get_all_songs {
#[derive(Debug, serde::Deserialize)]
pub struct Response {
pub message: String,
pub data: Vec<icarus_models::song::Song>,
}
}
}
@@ -18,22 +21,13 @@ impl Default for RetrieveRecords {
impl RetrieveRecords {
pub async fn get_all_songs(
&mut self,
token: &models::token::Token,
) -> Result<Vec<models::song::Song>, Error> {
self.api.endpoint = String::from("song");
let mut songs: Vec<models::song::Song> = Vec::new();
let url = self.retrieve_url();
token: &icarus_models::token::AccessToken,
) -> Result<Vec<icarus_models::song::Song>, Error> {
self.api.endpoint = String::from("api/v2/song/all");
let url = format!("{}{}", self.api.url, self.api.endpoint);
let access_token = token.bearer_token();
let mut headers = reqwest::header::HeaderMap::new();
headers.insert(
reqwest::header::AUTHORIZATION,
http::header::HeaderValue::from_str(&access_token.clone()).unwrap(),
);
headers.insert(
reqwest::header::CONTENT_TYPE,
http::header::HeaderValue::from_static("application/json"),
);
println!("url: {url:?}");
let client = reqwest::Client::builder().build().unwrap();
let response = client
@@ -45,36 +39,19 @@ impl RetrieveRecords {
match response.status() {
reqwest::StatusCode::OK => {
// on success, parse our JSON to an APIResponse
let s = response.json::<Vec<models::song::Song>>().await;
match s {
//
// on success, parse our JSON to an API Response
match response.json::<response::get_all_songs::Response>().await {
Ok(parsed) => {
songs = parsed;
println!("Response message: {:?}", parsed.message);
Ok(parsed.data)
}
Err(err) => Err(std::io::Error::other(err.to_string())),
}
Err(_) => println!("Hm, the response didn't match the shape we expected."),
};
}
reqwest::StatusCode::UNAUTHORIZED => {
println!("Need to grab a new token");
Err(std::io::Error::other("Need to grab a new token"))
}
other => {
panic!("Uh oh! Something unexpected happened: {:?}", other);
other => Err(std::io::Error::other(other.to_string())),
}
}
return Ok(songs);
}
fn retrieve_url(&self) -> String {
let api = &self.api;
let mut url: String = String::from(&api.url);
url += &String::from("api/");
url += &String::from(&api.version);
url += &String::from("/");
url += &String::from(&api.endpoint);
url += &String::from("/");
return url;
}
}
+259 -150
View File
@@ -1,195 +1,304 @@
use std::default::Default;
use http::HeaderMap;
use http::HeaderValue;
use reqwest;
use reqwest::multipart::Form;
use serde::{Deserialize, Serialize};
use crate::constants;
use crate::models;
use crate::syncers;
#[derive(Default)]
pub struct Upload {
pub api: models::api::API,
pub api: models::api::Api,
}
#[derive(Debug, Deserialize, Serialize)]
struct Song {
title: String,
album: String,
artist: String,
album_artist: String,
year: i32,
genre: String,
duration: i32,
track: i32,
track_count: i32,
disc: i32,
disc_count: i32,
#[serde(skip_serializing)]
songpath: String,
}
impl Song {
pub fn to_metadata_json(&self) -> Result<String, serde_json::Error> {
return serde_json::to_string_pretty(&self);
mod response {
pub mod queue_song {
#[derive(Debug, serde::Deserialize)]
pub struct Response {
pub message: String,
pub data: Vec<uuid::Uuid>,
}
}
}
impl Default for Upload {
fn default() -> Self {
Upload {
api: models::api::API::default(),
pub mod queue_metadata {
#[derive(Debug, serde::Deserialize)]
pub struct Response {
pub message: String,
pub data: Vec<uuid::Uuid>,
}
}
pub mod queue_coverart {
#[derive(Debug, serde::Deserialize)]
pub struct Response {
pub message: String,
pub data: Vec<uuid::Uuid>,
}
}
}
impl Upload {
pub async fn upload_song_with_metadata(
&mut self,
token: &models::token::Token,
song: &models::song::Song,
cover: &models::song::CoverArt,
album: &models::song::Album,
) -> Result<reqwest::Response, std::io::Error> {
self.api.endpoint = String::from("song/data/upload/with/data");
let url = self.retrieve_url();
let mut new_song = self.initialize_song(&song, &album);
new_song.songpath = song.song_path();
let access_token = token.bearer_token();
pub async fn queue_song(
&self,
token: &icarus_models::token::AccessToken,
song: &icarus_models::song::Song,
) -> Result<uuid::Uuid, reqwest::Error> {
let songpath = song.song_path().unwrap();
let file = tokio::fs::File::open(&songpath).await.unwrap();
let stream = tokio_util::codec::FramedRead::new(file, tokio_util::codec::BytesCodec::new());
let file_body = reqwest::Body::wrap_stream(stream);
if url.is_empty() {
println!("Url is empty");
}
let form = reqwest::multipart::Form::new().part(
"file",
reqwest::multipart::Part::stream(file_body)
.file_name(song.filename.clone())
.mime_str("application/octet-stream")
.unwrap(),
);
println!("Url: {}", url);
println!("Token: {}", access_token);
let endpoint = String::from("api/v2/song/queue");
let url = format!("{}/{endpoint}", self.api.url);
println!("Url: {url:?}");
let mut headers = reqwest::header::HeaderMap::new();
headers.insert(
reqwest::header::AUTHORIZATION,
HeaderValue::from_str(&access_token.clone()).unwrap(),
);
headers.insert(reqwest::header::ACCEPT, HeaderValue::from_static("*/*"));
let (auth, auth_val) = syncers::common::auth_header(token).await;
headers.insert(auth, auth_val);
headers.insert("Accept", HeaderValue::from_str("*/*").unwrap());
headers.insert("Connection", HeaderValue::from_str("keep-alive").unwrap());
headers.insert("Cache-Control", HeaderValue::from_str("no-cache").unwrap());
let form = self.init_form(&new_song, &cover);
let client = reqwest::Client::builder().build().unwrap();
let response = client
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(300))
.pool_idle_timeout(std::time::Duration::from_secs(30))
.build()
.unwrap();
match client
.post(url)
.headers(headers)
.multipart(form)
.send()
.await;
let response_text = response.unwrap();
println!("Something was sent");
println!("{:?}", response_text);
return Ok(response_text);
.await
{
Ok(response) => match response.json::<response::queue_song::Response>().await {
Ok(resp) => {
println!("Message: {:?}", resp.message);
Ok(resp.data[0])
}
Err(err) => Err(err),
},
Err(err) => Err(err),
}
}
fn _initialize_form(
pub async fn link_user_to_queued_song(
&self,
song_raw_data: Vec<u8>,
cover_raw_data: Vec<u8>,
song_detail: String,
) -> Form {
let mut headers = HeaderMap::new();
headers.insert(
http::header::CONTENT_TYPE,
http::HeaderValue::from_static("application/octet-stream"),
);
token: &icarus_models::token::AccessToken,
queued_song_id: &uuid::Uuid,
) -> Result<(), reqwest::Error> {
let endpoint = String::from("api/v2/song/queue/link");
let url = format!("{}/{endpoint}", self.api.url);
let file = reqwest::multipart::Part::bytes(song_raw_data).headers(headers);
let mut headers_i = HeaderMap::new();
headers_i.insert(
http::header::CONTENT_TYPE,
http::HeaderValue::from_static("image/jpeg"),
);
let mut headers = reqwest::header::HeaderMap::new();
let (auth, auth_val) = syncers::common::auth_header(token).await;
headers.insert(auth, auth_val);
let cover = reqwest::multipart::Part::bytes(cover_raw_data).headers(headers_i);
let payload = serde_json::json!({
"song_queue_id": queued_song_id,
"user_id": token.user_id
});
let mut song_filename = String::from("audio");
song_filename += constants::file_extensions::WAV_FILE_EXTENSION;
let mut cover_filename = String::from("cover");
cover_filename += constants::file_extensions::JPG_FILE_EXTENSION;
let client = reqwest::Client::builder().build().unwrap();
return reqwest::multipart::Form::new()
.part("cover", cover.file_name(cover_filename))
.text("metadata", song_detail)
.part("file", file.file_name(song_filename));
match client
.patch(url)
.headers(headers)
.json(&payload)
.send()
.await
{
Ok(_) => Ok(()),
Err(err) => Err(err),
}
}
fn init_form(&self, song: &Song, cover: &models::song::CoverArt) -> reqwest::multipart::Form {
let songpath = song.songpath.clone();
let coverpath = cover.path.clone().unwrap();
let song_detail = song.to_metadata_json().unwrap();
pub async fn queue_metadata(
&self,
token: &icarus_models::token::AccessToken,
album: &icarus_models::album::collection::Album,
song: &icarus_models::song::Song,
queued_song_id: &uuid::Uuid,
) -> Result<uuid::Uuid, reqwest::Error> {
let endpoint = String::from("api/v2/song/metadata/queue");
let url = format!("{}/{endpoint}", self.api.url);
println!("\n{}\n", song_detail);
let mut headers = reqwest::header::HeaderMap::new();
let (auth, auth_val) = syncers::common::auth_header(token).await;
headers.insert(auth, auth_val);
let mut song_filename = String::from("audio");
song_filename += constants::file_extensions::WAV_FILE_EXTENSION;
let mut cover_filename = String::from("cover");
cover_filename += constants::file_extensions::JPG_FILE_EXTENSION;
let payload = serde_json::json!({
"song_queue_id": queued_song_id,
"title": song.title,
"artist": song.artist,
"album_artist": album.artist,
"album": album.title,
"genre": song.genre,
"track": song.track,
"track_count": album.track_count,
"disc": song.disc,
"disc_count": album.disc_count,
"year": album.year,
"duration": song.duration,
});
let form = reqwest::multipart::Form::new()
.part(
let client = reqwest::Client::builder().build().unwrap();
match client
.post(url)
.headers(headers)
.json(&payload)
.send()
.await
{
Ok(response) => match response.json::<response::queue_metadata::Response>().await {
Ok(resp) => {
println!("Message: {:?}", resp.message);
Ok(resp.data[0])
}
Err(err) => Err(err),
},
Err(err) => Err(err),
}
}
pub async fn queue_coverart(
&self,
token: &icarus_models::token::AccessToken,
coverart: &icarus_models::coverart::CoverArt,
) -> Result<uuid::Uuid, reqwest::Error> {
let coverartpath = coverart.get_path().unwrap();
let file = tokio::fs::File::open(&coverartpath).await.unwrap();
let stream = tokio_util::codec::FramedRead::new(file, tokio_util::codec::BytesCodec::new());
let file_body = reqwest::Body::wrap_stream(stream);
let file_name = std::path::Path::new(&coverartpath)
.file_name()
.and_then(|name| name.to_str())
.map(String::from)
.unwrap_or("file".to_string());
let form = reqwest::multipart::Form::new().part(
"file",
reqwest::multipart::Part::bytes(std::fs::read(songpath).unwrap())
.file_name(song_filename),
)
.part(
"cover",
reqwest::multipart::Part::bytes(std::fs::read(coverpath).unwrap())
.file_name(cover_filename),
)
.text("metadata", song_detail);
reqwest::multipart::Part::stream(file_body)
.file_name(file_name)
.mime_str("application/octet-stream")
.unwrap(),
);
return form;
let endpoint = String::from("api/v2/coverart/queue");
let url = format!("{}/{endpoint}", self.api.url);
println!("Url: {url:?}");
let mut headers = reqwest::header::HeaderMap::new();
let (auth, auth_val) = syncers::common::auth_header(token).await;
headers.insert(auth, auth_val);
headers.insert("Accept", HeaderValue::from_str("*/*").unwrap());
headers.insert("Connection", HeaderValue::from_str("keep-alive").unwrap());
headers.insert("Cache-Control", HeaderValue::from_str("no-cache").unwrap());
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(300))
.pool_idle_timeout(std::time::Duration::from_secs(30))
.build()
.unwrap();
match client
.post(url)
.headers(headers)
.multipart(form)
.send()
.await
{
Ok(response) => match response.json::<response::queue_coverart::Response>().await {
Ok(resp) => {
println!("Message: {:?}", resp.message);
Ok(resp.data[0])
}
Err(err) => Err(err),
},
Err(err) => Err(err),
}
}
pub fn set_api(&mut self, host: &String) {
let mut api = models::api::API::default();
api.url = host.clone();
api.version = String::from("v1");
pub async fn link_queued_song_to_queued_coverart(
&self,
token: &icarus_models::token::AccessToken,
queued_song_id: &uuid::Uuid,
queued_coverart_id: &uuid::Uuid,
) -> Result<(), reqwest::Error> {
let endpoint = String::from("api/v2/coverart/queue/link");
let url = format!("{}/{endpoint}", self.api.url);
let mut headers = reqwest::header::HeaderMap::new();
let (auth, auth_val) = syncers::common::auth_header(token).await;
headers.insert(auth, auth_val);
let payload = serde_json::json!({
"song_queue_id": queued_song_id,
"coverart_id": queued_coverart_id
});
let client = reqwest::Client::builder().build().unwrap();
match client
.patch(url)
.headers(headers)
.json(&payload)
.send()
.await
{
Ok(_) => Ok(()),
Err(err) => Err(err),
}
}
pub async fn update_queued_song_status(
&self,
token: &icarus_models::token::AccessToken,
queued_song_id: &uuid::Uuid,
status: &str,
) -> Result<(), reqwest::Error> {
let endpoint = String::from("api/v2/song/queue");
let url = format!("{}/{endpoint}", self.api.url);
let mut headers = reqwest::header::HeaderMap::new();
let (auth, auth_val) = syncers::common::auth_header(token).await;
headers.insert(auth, auth_val);
let payload = serde_json::json!({
"id": queued_song_id,
"status": status
});
let client = reqwest::Client::builder().build().unwrap();
match client
.patch(url)
.headers(headers)
.json(&payload)
.send()
.await
{
Ok(_) => Ok(()),
Err(err) => Err(err),
}
}
pub fn set_api(&mut self, host: &str) {
let api = models::api::Api {
url: host.to_owned(),
version: String::from(crate::parsers::api_parser::API_VERSION),
endpoint: String::new(),
};
self.api = api;
}
fn retrieve_url(&self) -> String {
let api = &self.api;
let mut buffer = api.url.clone();
let count = buffer.len();
if buffer.chars().nth(count - 1) != Some('/') {
buffer += "/";
}
let mut url: String = String::from(&buffer);
url += &String::from("api/");
url += &String::from(&api.version);
url += &String::from("/");
url += &String::from(&api.endpoint);
return url;
}
fn initialize_song(&self, song: &models::song::Song, album: &models::song::Album) -> Song {
let dur = song.duration.clone().unwrap();
println!("Duration: {}", dur);
return Song {
title: String::from(&song.title.clone().unwrap()),
album: album.title.clone(),
artist: String::from(&song.artist.clone().unwrap().clone()),
album_artist: album.album_artist.clone(),
year: album.year.clone(),
genre: album.genre.clone(),
duration: f64::round(dur) as i32,
track: (song.track.clone().unwrap()),
track_count: album.track_count.clone(),
disc: song.disc.clone().unwrap(),
disc_count: album.disc_count.clone(),
songpath: String::new(),
};
}
}
+2 -27
View File
@@ -1,28 +1,3 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize)]
pub struct Checks {}
impl Checks {
pub fn is_numeric(text: &String) -> bool {
text.parse::<f64>().is_ok()
}
pub fn index_of_item_in_container<F>(container: &String, item: &char, func: F) -> i32
where
F: Fn(&char, &char) -> bool,
{
let mut index = -1;
for c in container.chars() {
if func(&c, item) {
index += 1;
break;
}
index += 1;
}
return index;
}
pub fn exit_program(code: i32) {
std::process::exit(code);
}
+1
View File
@@ -1 +1,2 @@
pub mod checks;
pub mod string;
+6
View File
@@ -0,0 +1,6 @@
pub fn o_to_string(val: &std::ffi::OsString) -> Result<std::string::String, std::io::Error> {
match val.clone().into_string() {
Ok(value) => Ok(value),
Err(_) => Err(std::io::Error::other(String::from("Error"))),
}
}
+31
View File
@@ -0,0 +1,31 @@
{
"album": "Sample Tracks 2",
"album_artist": "KD",
"genre": "Country",
"year": 2025,
"track_count": 3,
"disc_count": 1,
"tracks": [
{
"title": "Uh huh",
"artist": "KD",
"disc": 1,
"track": 1,
"duration": 32
},
{
"title": "Bold and brash",
"artist": "KD",
"disc": 1,
"track": 2,
"duration": 37
},
{
"title": "How does this work?",
"artist": "KD",
"disc": 1,
"track": 3,
"duration": 46
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.
Binary file not shown.
Binary file not shown.