Compare commits
57 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 157887bfac | |||
|
2b77bb978c
|
|||
| 206ebf03be | |||
| 0d7d57bf5f | |||
| 11b8cc21d3 | |||
| e109789b18 | |||
| ec0cbd7da0 | |||
| 809f27cf01 | |||
| 8a07718ce8 | |||
| 77cb5c8599 | |||
| dbcfcfa109 | |||
| 8b2b2f82e9 | |||
| 8e6ddbc9df | |||
| c8ba6606be | |||
| b7d55ebcf4 | |||
| d5f95ddf9b | |||
| 885f1db3af | |||
| d6f45c8279 | |||
| 58a88b1abd | |||
| 9b181733a6 | |||
| 219b95bb2f | |||
| 24e066d8d9 | |||
| ab08792ff4 | |||
| 9799edef33 | |||
| 92eb31a687 | |||
| aa946a0a05 | |||
| 19d6f2dc33 | |||
| 4824e6f33a | |||
| 64935ea772 | |||
| de90b0d0a1 | |||
| 19b943eed8 | |||
| 8c781398b4 | |||
| c575d2e523 | |||
| 03ed3deae6 | |||
| b69c111b66 | |||
| 8d97d4eb70 | |||
| 2f00ce6abf | |||
| e3cd1f4018 | |||
| a9f9ba8350 | |||
| df60bef381 | |||
| 038142eb8a | |||
| 69b81bc15c | |||
| b2e246d175 | |||
| c76e7b71b5 | |||
| b8dccca158 | |||
| b52607b4e3 | |||
| ac970a4302 | |||
| a372bfcc05 | |||
| d22850b280 | |||
| 4d170f6a85 | |||
| 7391b1db68 | |||
| 772641a8c4 | |||
| 4c99f88baf | |||
| c3718c5add | |||
| a4d026e41f | |||
| 6aa6f548a9 | |||
| 53b83a809c |
@@ -0,0 +1,39 @@
|
||||
name: Rust
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "master" ]
|
||||
pull_request:
|
||||
branches: [ "master", "icarus_v2_support" ]
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
|
||||
jobs:
|
||||
build:
|
||||
|
||||
runs-on: ubuntu-24.04
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install Rust version
|
||||
run: rustup install 1.88.0 && rustup default 1.88.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
|
||||
@@ -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
|
||||
|
||||
@@ -7,4 +7,3 @@
|
||||
|
||||
/target
|
||||
.vscode/
|
||||
Cargo.lock
|
||||
|
||||
Generated
+1962
File diff suppressed because it is too large
Load Diff
+12
-13
@@ -1,18 +1,17 @@
|
||||
[package]
|
||||
name = "icarus-dm"
|
||||
version = "0.4.0"
|
||||
edition = "2021"
|
||||
|
||||
|
||||
|
||||
version = "0.7.0"
|
||||
rust-version = "1.88"
|
||||
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.20", features = ["json", "blocking", "multipart", "stream"] }
|
||||
serde = { version = "1.0.219", features = ["derive"] }
|
||||
serde_json = "1.0.140"
|
||||
tokio = { version = "1.45.1", features = ["full"] }
|
||||
tokio-util = { version = "0.7.15", features = ["codec"] }
|
||||
uuid = { version = "1.17.0", features = ["v4", "serde"] }
|
||||
icarus_models = { git = "ssh://git@git.kundeng.us/phoenix/icarus_models.git", tag = "v0.5.6" }
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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 +0,0 @@
|
||||
pub mod file_extensions;
|
||||
+37
@@ -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
@@ -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 song.to_data() {
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
+381
-441
File diff suppressed because it is too large
Load Diff
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
@@ -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
@@ -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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
pub mod api;
|
||||
pub mod flags;
|
||||
pub mod icarus_action;
|
||||
pub mod song;
|
||||
pub mod token;
|
||||
pub mod upload_form;
|
||||
pub mod user;
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -2,17 +2,8 @@ use std::default::Default;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[derive(Debug, Default, 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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
@@ -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
@@ -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,3 +1,4 @@
|
||||
pub mod common;
|
||||
pub mod delete;
|
||||
pub mod download;
|
||||
pub mod retrieve_records;
|
||||
|
||||
@@ -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
@@ -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.path.clone();
|
||||
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(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,11 +4,11 @@ use serde::{Deserialize, Serialize};
|
||||
pub struct Checks {}
|
||||
|
||||
impl Checks {
|
||||
pub fn is_numeric(text: &String) -> bool {
|
||||
pub fn _is_numeric(text: &str) -> bool {
|
||||
text.parse::<f64>().is_ok()
|
||||
}
|
||||
|
||||
pub fn index_of_item_in_container<F>(container: &String, item: &char, func: F) -> i32
|
||||
pub fn _index_of_item_in_container<F>(container: &str, item: &char, func: F) -> i32
|
||||
where
|
||||
F: Fn(&char, &char) -> bool,
|
||||
{
|
||||
@@ -23,6 +23,10 @@ impl Checks {
|
||||
index += 1;
|
||||
}
|
||||
|
||||
return index;
|
||||
index
|
||||
}
|
||||
}
|
||||
|
||||
pub fn exit_program(code: i32) {
|
||||
std::process::exit(code);
|
||||
}
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
pub mod checks;
|
||||
pub mod string;
|
||||
|
||||
@@ -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"))),
|
||||
}
|
||||
}
|
||||
@@ -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.
Reference in New Issue
Block a user