Compare commits
34 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 489d13227b | |||
| 0e6438cf0d | |||
| 00615532ce | |||
| abd16eeba2 | |||
| 5c9fcf2ec5 | |||
| 6bedab0d88 | |||
| 686e0d8f1f | |||
| 05a9134aaa | |||
| 3cadac4efd | |||
| 2188c2b746 | |||
| 9328f3d3da | |||
| ca13f101d7 | |||
| 1e4ffc798e | |||
| ecd025346c | |||
| 74184fa022 | |||
| c2a2ca049d | |||
| 157887bfac | |||
|
2b77bb978c
|
|||
| 206ebf03be | |||
| 0d7d57bf5f | |||
| 11b8cc21d3 | |||
| e109789b18 | |||
| ec0cbd7da0 | |||
| 809f27cf01 | |||
| 8a07718ce8 | |||
| 77cb5c8599 | |||
| dbcfcfa109 | |||
| 8b2b2f82e9 | |||
| 8e6ddbc9df | |||
| c8ba6606be | |||
| b7d55ebcf4 | |||
| d5f95ddf9b | |||
| 885f1db3af | |||
| d6f45c8279 |
@@ -1,22 +0,0 @@
|
||||
name: Rust
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "master" ]
|
||||
pull_request:
|
||||
branches: [ "master" ]
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
|
||||
jobs:
|
||||
build:
|
||||
|
||||
runs-on: macos-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Build
|
||||
run: cargo build --verbose
|
||||
- name: Run tests
|
||||
run: cargo test --verbose
|
||||
@@ -2,9 +2,9 @@ name: Rust
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "master" ]
|
||||
branches: [ "main" ]
|
||||
pull_request:
|
||||
branches: [ "master" ]
|
||||
branches: [ "main" ]
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
@@ -12,12 +12,12 @@ env:
|
||||
jobs:
|
||||
build:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
- name: Install Rust version
|
||||
run: rustup install 1.85.0 && rustup default 1.85.0
|
||||
run: rustup install 1.95 && rustup default 1.95
|
||||
|
||||
- name: Debug secret
|
||||
run: echo "${{ secrets.MYREPO_TOKEN }}" | head -c 10 ; echo "..."
|
||||
@@ -27,7 +27,7 @@ jobs:
|
||||
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
|
||||
ssh-keyscan ${{ vars.MYHOST }}= >> ~/.ssh/known_hosts
|
||||
|
||||
eval $(ssh-agent -s)
|
||||
ssh-add -v ~/.ssh/gitlab_deploy_key
|
||||
|
||||
@@ -7,4 +7,3 @@
|
||||
|
||||
/target
|
||||
.vscode/
|
||||
Cargo.lock
|
||||
|
||||
Generated
+2425
File diff suppressed because it is too large
Load Diff
+11
-13
@@ -1,19 +1,17 @@
|
||||
[package]
|
||||
name = "icarus-dm"
|
||||
version = "0.6.0"
|
||||
version = "0.10.0"
|
||||
rust-version = "1.95"
|
||||
edition = "2024"
|
||||
|
||||
|
||||
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
futures = { version = "0.3.31" }
|
||||
http = { version = "1.3.1" }
|
||||
reqwest = { version = "0.12.15", features = ["json", "blocking", "multipart", "stream"] }
|
||||
serde = { version = "1.0.219", features = ["derive"] }
|
||||
serde_json = "1.0.140"
|
||||
tokio = { version = "1.44.1", features = ["full"] }
|
||||
tokio-util = { version = "0.7.14", features = ["codec"] }
|
||||
icarus_models = { git = "ssh://git@git.kundeng.us/phoenix/icarus_models.git", tag = "v0.2.0" }
|
||||
futures = { version = "0.3.32" }
|
||||
http = { version = "1.4.0" }
|
||||
reqwest = { version = "0.13.3", features = ["json", "blocking", "multipart", "stream"] }
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
serde_json = "1.0.149"
|
||||
tokio = { version = "1.52", features = ["full"] }
|
||||
tokio-util = { version = "0.7.18", features = ["codec"] }
|
||||
uuid = { version = "1.23.1", features = ["v4", "serde"] }
|
||||
icarus_models = { git = "ssh://git@git.kundeng.us/phoenix/icarus_models.git", tag = "v0.11.1" }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2019 Kun Deng
|
||||
Copyright (c) 2026 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.flac -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
|
||||
|
||||
|
||||
+7
-3
@@ -12,7 +12,8 @@ pub fn print_help() {
|
||||
Required for all actions
|
||||
-u username
|
||||
-p password
|
||||
-h host
|
||||
-h api host
|
||||
-ha auth api host
|
||||
|
||||
Required for upload with metadata
|
||||
-s path of song
|
||||
@@ -29,8 +30,11 @@ pub fn print_help() {
|
||||
-rt retrieve type (songs is only accepted)
|
||||
|
||||
Required for deleting a song
|
||||
-D song id"#,
|
||||
-D song id
|
||||
|
||||
Print version
|
||||
-v"#,
|
||||
);
|
||||
|
||||
println!("{}", msg);
|
||||
println!("{msg}");
|
||||
}
|
||||
|
||||
+13
-6
@@ -4,10 +4,12 @@ mod models;
|
||||
mod parsers;
|
||||
mod syncers;
|
||||
mod utilities;
|
||||
mod version;
|
||||
|
||||
use std::env;
|
||||
|
||||
fn main() {
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let args: Vec<String> = env::args().collect();
|
||||
let args_len = args.len() as i32;
|
||||
|
||||
@@ -16,20 +18,25 @@ fn main() {
|
||||
utilities::checks::exit_program(-1);
|
||||
}
|
||||
|
||||
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();
|
||||
for act in &chosen_act.flags {
|
||||
if act.flag == "-v" {
|
||||
version::print_version();
|
||||
utilities::checks::exit_program(-1);
|
||||
}
|
||||
}
|
||||
chosen_act.print_action_and_flags();
|
||||
|
||||
let mut cmt_mgr = managers::commit_manager::CommitManager {
|
||||
ica_action: chosen_act,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
cmt_mgr.commit_action();
|
||||
cmt_mgr.commit_action().await;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -41,7 +48,7 @@ mod tests {
|
||||
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);
|
||||
assert!(false, "File does not exists: {meta_path:?}");
|
||||
}
|
||||
|
||||
match icarus_models::album::collection::parse_album(&meta_path) {
|
||||
@@ -62,7 +69,7 @@ mod tests {
|
||||
match managers::commit_manager::retrieve_song(
|
||||
&album, track, disc, &directory, &filename,
|
||||
) {
|
||||
Ok(song) => match song.to_data() {
|
||||
Ok(song) => match icarus_models::song::io::to_data(&song) {
|
||||
Ok(_) => {
|
||||
print!("Success");
|
||||
}
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{models, utilities};
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[derive(Debug)]
|
||||
pub struct ActionManager {
|
||||
pub action: String,
|
||||
pub flags: Vec<models::flags::Flags>,
|
||||
@@ -23,18 +21,19 @@ impl Default for ActionManager {
|
||||
|
||||
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"),
|
||||
@@ -47,7 +46,8 @@ impl ActionManager {
|
||||
String::from("-ca"),
|
||||
String::from("-smca"),
|
||||
String::from("-t"),
|
||||
];
|
||||
String::from("-v"),
|
||||
]
|
||||
}
|
||||
|
||||
pub fn initialize(&mut self) {
|
||||
@@ -56,41 +56,34 @@ impl ActionManager {
|
||||
self.action = self.action.to_lowercase();
|
||||
}
|
||||
|
||||
pub fn set_params(&mut self, args: &Vec<String>) {
|
||||
self.params = args.clone();
|
||||
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");
|
||||
|
||||
let flag_vals = self.parsed_flags();
|
||||
|
||||
let mut i = 0;
|
||||
println!("Flag count: {}", flag_vals.len());
|
||||
|
||||
while i < flag_vals.len() {
|
||||
let flag = &flag_vals[i];
|
||||
println!("Index: {} | Value: {}", i, flag);
|
||||
|
||||
let mut flg = models::flags::Flags::default();
|
||||
|
||||
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]);
|
||||
if self.is_valid_flag(flag) {
|
||||
if self.does_flag_have_value(flag) {
|
||||
flg.flag = String::from(flag);
|
||||
flg.value = String::from(&flag_vals[i + 1]);
|
||||
|
||||
i = i + 1;
|
||||
} else if self.is_valid_flag(flag) {
|
||||
println!("Flag does not have a value");
|
||||
flg.flag = String::from(flag);
|
||||
i += 1;
|
||||
} else {
|
||||
flg.flag = String::from(flag);
|
||||
}
|
||||
} else {
|
||||
println!("Flag {} is not valid", flag);
|
||||
utilities::checks::exit_program(-1);
|
||||
}
|
||||
|
||||
self.flags.push(flg);
|
||||
println!("");
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
@@ -113,34 +106,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;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
(i_found + 1) < flags_tmp.len().try_into().unwrap()
|
||||
} 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);
|
||||
@@ -158,11 +147,18 @@ impl ActionManager {
|
||||
fn parsed_flags(&self) -> Vec<String> {
|
||||
let mut parsed: Vec<String> = Vec::new();
|
||||
|
||||
for i in 2..self.params.len() {
|
||||
let flag = String::from(&self.params[i]);
|
||||
parsed.push(flag);
|
||||
if self.param_count <= 2 {
|
||||
let flag = String::from(&self.params[1]);
|
||||
if flag == "-v" {
|
||||
parsed.push(flag);
|
||||
}
|
||||
} else {
|
||||
for i in 2..self.params.len() {
|
||||
let flag = String::from(&self.params[i]);
|
||||
parsed.push(flag);
|
||||
}
|
||||
}
|
||||
|
||||
return parsed;
|
||||
parsed
|
||||
}
|
||||
}
|
||||
|
||||
+291
-274
@@ -1,21 +1,20 @@
|
||||
use std::collections::HashMap;
|
||||
use std::default::Default;
|
||||
use std::fs::read_dir;
|
||||
use std::io::{Result, Write};
|
||||
use std::io::Result;
|
||||
use std::str::FromStr;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::runtime::Runtime;
|
||||
|
||||
use crate::managers;
|
||||
use crate::models::{self};
|
||||
use crate::parsers;
|
||||
use crate::syncers;
|
||||
use crate::utilities;
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[derive(Debug, Default)]
|
||||
pub struct CommitManager {
|
||||
pub ica_action: models::icarus_action::IcarusAction,
|
||||
pub api: models::api::Api,
|
||||
pub auth_api: models::api::Api,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -23,7 +22,6 @@ enum ActionValues {
|
||||
DeleteAct,
|
||||
DownloadAct,
|
||||
RetrieveAct,
|
||||
UploadAct,
|
||||
UploadSongWithMetadata,
|
||||
None,
|
||||
}
|
||||
@@ -36,12 +34,20 @@ enum En {
|
||||
Other,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct UploadSongMembers {
|
||||
pub song: icarus_models::song::Song,
|
||||
pub coverart: icarus_models::coverart::CoverArt,
|
||||
pub token: icarus_models::token::AccessToken,
|
||||
pub album: icarus_models::album::collection::Album,
|
||||
}
|
||||
|
||||
pub fn retrieve_song(
|
||||
album: &icarus_models::album::collection::Album,
|
||||
track: i32,
|
||||
disc: i32,
|
||||
directory: &String,
|
||||
filename: &String,
|
||||
directory: &str,
|
||||
filename: &str,
|
||||
) -> Result<icarus_models::song::Song> {
|
||||
let mut found = false;
|
||||
let mut song = icarus_models::song::Song::default();
|
||||
@@ -55,16 +61,16 @@ pub fn retrieve_song(
|
||||
song.audio_type = String::from(
|
||||
icarus_models::constants::file_extensions::audio::DEFAULTMUSICEXTENSION,
|
||||
);
|
||||
song.disc = track.disc.clone();
|
||||
song.disc_count = album.disc_count.clone();
|
||||
song.disc = track.disc;
|
||||
song.disc_count = album.disc_count;
|
||||
song.duration = track.duration as i32;
|
||||
song.genre = album.genre.clone();
|
||||
song.title = track.title.clone();
|
||||
song.year = album.year.clone();
|
||||
song.track = track.track.clone();
|
||||
song.track_count = album.track_count.clone();
|
||||
song.directory = directory.clone();
|
||||
song.filename = filename.clone();
|
||||
song.year = album.year;
|
||||
song.track = track.track;
|
||||
song.track_count = album.track_count;
|
||||
song.directory = directory.to_owned();
|
||||
song.filename = filename.to_owned();
|
||||
|
||||
found = true;
|
||||
break;
|
||||
@@ -72,37 +78,44 @@ pub fn retrieve_song(
|
||||
}
|
||||
|
||||
if found {
|
||||
return Ok(song);
|
||||
Ok(song)
|
||||
} else {
|
||||
Err(std::io::Error::other("Song not found"))
|
||||
}
|
||||
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::NotFound,
|
||||
"Song not found",
|
||||
));
|
||||
}
|
||||
|
||||
impl CommitManager {
|
||||
pub fn commit_action(&mut self) {
|
||||
pub async fn commit_action(&mut self) {
|
||||
self.init_api().await;
|
||||
|
||||
let action = &self.ica_action.action;
|
||||
println!("Committing {} action", action);
|
||||
println!("Committing {action} action");
|
||||
|
||||
let mapped_actions = &self.map_actions();
|
||||
let mapped_action = self.find_mapped_action(&mapped_actions, action);
|
||||
let token = self.parse_token(&self.auth_api).await;
|
||||
|
||||
println!("{:?}", mapped_action);
|
||||
|
||||
match mapped_action {
|
||||
ActionValues::DeleteAct => self.delete_song(),
|
||||
ActionValues::DownloadAct => self.download_song(),
|
||||
ActionValues::RetrieveAct => self.retrieve_object(),
|
||||
ActionValues::UploadAct => self.upload_song(),
|
||||
ActionValues::UploadSongWithMetadata => self.upload_song_with_metadata(),
|
||||
match self.find_mapped_action(mapped_actions, action) {
|
||||
ActionValues::DeleteAct => self.delete_song(&token).await,
|
||||
ActionValues::DownloadAct => self.download_song(&token).await,
|
||||
ActionValues::RetrieveAct => self.retrieve_object(&token).await,
|
||||
ActionValues::UploadSongWithMetadata => self.upload_song_with_metadata(&token).await,
|
||||
_ => {
|
||||
println!("Nothing good here");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn init_api(&mut self) {
|
||||
let mut prsr = parsers::api_parser::APIParser {
|
||||
apis: vec![models::api::Api::default(), models::api::Api::default()],
|
||||
ica_act: self.ica_action.clone(),
|
||||
};
|
||||
prsr.parse_api(parsers::api_parser::APIType::Main);
|
||||
prsr.parse_api(parsers::api_parser::APIType::Auth);
|
||||
self.api = prsr.retrieve_api(parsers::api_parser::APIType::Main);
|
||||
self.auth_api = prsr.retrieve_api(parsers::api_parser::APIType::Auth);
|
||||
}
|
||||
|
||||
fn find_mapped_action(
|
||||
&self,
|
||||
actions: &HashMap<String, ActionValues>,
|
||||
@@ -114,37 +127,28 @@ impl CommitManager {
|
||||
}
|
||||
}
|
||||
|
||||
return ActionValues::None;
|
||||
ActionValues::None
|
||||
}
|
||||
|
||||
fn map_actions(&self) -> HashMap<String, ActionValues> {
|
||||
let actions: HashMap<String, ActionValues> = HashMap::from([
|
||||
HashMap::from([
|
||||
("download".to_string(), ActionValues::DownloadAct),
|
||||
("download".to_string(), ActionValues::DownloadAct),
|
||||
("upload".to_string(), ActionValues::UploadAct),
|
||||
(
|
||||
"upload-meta".to_string(),
|
||||
ActionValues::UploadSongWithMetadata,
|
||||
),
|
||||
("retrieve".to_string(), ActionValues::RetrieveAct),
|
||||
("delete".to_string(), ActionValues::DeleteAct),
|
||||
]);
|
||||
|
||||
return actions;
|
||||
])
|
||||
}
|
||||
|
||||
fn delete_song(&self) {
|
||||
let mut prsr = parsers::api_parser::APIParser {
|
||||
ica_act: self.ica_action.clone(),
|
||||
api: models::api::API::default(),
|
||||
};
|
||||
prsr.parse_api();
|
||||
let api = prsr.retrieve_api();
|
||||
|
||||
let token = self.parse_token(&api);
|
||||
|
||||
async fn delete_song(&self, token: &icarus_models::token::AccessToken) {
|
||||
println!("Deleting song");
|
||||
|
||||
let mut del = syncers::delete::Delete {
|
||||
api: self.api.clone(),
|
||||
};
|
||||
let mut song = icarus_models::song::Song::default();
|
||||
|
||||
for arg in &self.ica_action.flags {
|
||||
@@ -152,90 +156,87 @@ impl CommitManager {
|
||||
let value = &arg.value;
|
||||
|
||||
if flag == "-D" {
|
||||
song.id = value.parse::<i32>().unwrap();
|
||||
song.id = uuid::Uuid::from_str(value.as_str()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
let mut del = syncers::delete::Delete { api: api.clone() };
|
||||
|
||||
println!("Deleting song..");
|
||||
|
||||
let res_fut = del.delete_song(&token, &song);
|
||||
let result = Runtime::new().unwrap().block_on(res_fut);
|
||||
match result {
|
||||
Ok(o) => {
|
||||
println!("Song (Id {:?}) has been successfully deleted", o.id);
|
||||
match del.delete_song(token, &song).await {
|
||||
Ok((song, _coverart)) => {
|
||||
println!("Song (Id {:?}) has been successfully deleted", song.id);
|
||||
}
|
||||
Err(er) => {
|
||||
println!("Error {:?}", er);
|
||||
println!("Error {er:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn download_song(&self) {
|
||||
println!("Deleting song");
|
||||
async fn download_song(&self, token: &icarus_models::token::AccessToken) {
|
||||
println!("Downloading song");
|
||||
let dwn = self.ica_action.retrieve_flag_value(&String::from("-b"));
|
||||
let id: i32 = dwn.parse::<i32>().unwrap();
|
||||
|
||||
let mut prsr = parsers::api_parser::APIParser {
|
||||
api: models::api::API::default(),
|
||||
ica_act: self.ica_action.clone(),
|
||||
let mut dwn_loader = syncers::download::Download {
|
||||
api: self.api.clone(),
|
||||
};
|
||||
let mut song = icarus_models::song::Song {
|
||||
id: uuid::Uuid::from_str(dwn.as_str()).unwrap(),
|
||||
..Default::default()
|
||||
};
|
||||
prsr.parse_api();
|
||||
|
||||
let api = prsr.retrieve_api();
|
||||
let token = self.parse_token(&api);
|
||||
println!("Message: {}", token.message);
|
||||
|
||||
let mut dwn_loader = syncers::download::Download { api: api.clone() };
|
||||
let mut song = icarus_models::song::Song::default();
|
||||
song.id = id;
|
||||
let result_fut = dwn_loader.download_song(&token, &song);
|
||||
match Runtime::new().unwrap().block_on(result_fut) {
|
||||
match dwn_loader.download_song(token, &song).await {
|
||||
Ok(o) => {
|
||||
println!("Success");
|
||||
let filename = String::from("audio")
|
||||
+ icarus_models::constants::file_extensions::audio::DEFAULTMUSICEXTENSION;
|
||||
let data = o.as_bytes();
|
||||
let mut file = std::fs::File::create(filename).expect("Failed to save");
|
||||
file.write_all(&data)
|
||||
.expect("Failed to save downloaded song");
|
||||
println!("Song downloaded");
|
||||
|
||||
song.data = o.as_bytes().to_vec();
|
||||
song.directory = String::from(".");
|
||||
song.filename = match icarus_models::song::generate_filename(
|
||||
icarus_models::types::MusicType::FlacExtension,
|
||||
true,
|
||||
) {
|
||||
Ok(filename) => filename,
|
||||
Err(err) => {
|
||||
eprintln!("Error generating song filename: {err:?}");
|
||||
utilities::checks::exit_program(-3);
|
||||
return;
|
||||
}
|
||||
};
|
||||
match song.save_to_filesystem() {
|
||||
Ok(_) => {
|
||||
println!("Song saved");
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("Error saving song: {err:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(er) => {
|
||||
println!("Error {:?}", er);
|
||||
println!("Error {er:?}");
|
||||
match er {
|
||||
syncers::download::MyError::Request(error) => {
|
||||
println!("Error: {:?}", error);
|
||||
println!("Error: {error:?}");
|
||||
}
|
||||
syncers::download::MyError::Other(ss) => {
|
||||
println!("Error: {:?}", ss);
|
||||
println!("Error: {ss:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn retrieve_object(&self) {
|
||||
async fn retrieve_object(&self, token: &icarus_models::token::AccessToken) {
|
||||
println!("Retrieving song");
|
||||
let rt = self.ica_action.retrieve_flag_value(&String::from("-rt"));
|
||||
|
||||
if rt != "songs" {
|
||||
panic!("Unsupported -rt: {}", rt);
|
||||
panic!("Unsupported -rt: {rt}");
|
||||
}
|
||||
|
||||
let mut prsr = parsers::api_parser::APIParser {
|
||||
api: models::api::API::default(),
|
||||
ica_act: self.ica_action.clone(),
|
||||
let mut repo = syncers::retrieve_records::RetrieveRecords {
|
||||
api: self.api.clone(),
|
||||
};
|
||||
prsr.parse_api();
|
||||
|
||||
let api = prsr.retrieve_api();
|
||||
let token = self.parse_token(&api);
|
||||
let mut repo = syncers::retrieve_records::RetrieveRecords { api: api.clone() };
|
||||
let result_fut = repo.get_all_songs(&token);
|
||||
|
||||
match Runtime::new().unwrap().block_on(result_fut) {
|
||||
match repo.get_all_songs(token).await {
|
||||
Ok(o) => {
|
||||
println!("Songs");
|
||||
println!("=====");
|
||||
for song in o {
|
||||
println!("Title: {:?}", song.title);
|
||||
println!("Artist: {:?}", song.artist);
|
||||
@@ -244,17 +245,12 @@ impl CommitManager {
|
||||
}
|
||||
}
|
||||
Err(er) => {
|
||||
println!("Error: {:?}", er);
|
||||
println!("Error: {er:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn upload_song(&self) {
|
||||
println!("Deleting song");
|
||||
panic!("Not supported");
|
||||
}
|
||||
|
||||
fn parse_token(&self, api: &models::api::API) -> icarus_models::token::AccessToken {
|
||||
async fn parse_token(&self, api: &models::api::Api) -> icarus_models::token::AccessToken {
|
||||
println!("Fetching token");
|
||||
|
||||
let mut usr_mgr: managers::user_manager::UserManager =
|
||||
@@ -271,12 +267,12 @@ impl CommitManager {
|
||||
};
|
||||
tok_mgr.init();
|
||||
|
||||
let token = Runtime::new().unwrap().block_on(tok_mgr.request_token());
|
||||
let token = tok_mgr.request_token().await;
|
||||
|
||||
return token.unwrap();
|
||||
token.unwrap()
|
||||
}
|
||||
|
||||
fn upload_song_with_metadata(&mut self) {
|
||||
async fn upload_song_with_metadata(&mut self, token: &icarus_models::token::AccessToken) {
|
||||
println!("Uplodaring song with metadara");
|
||||
|
||||
let songpath = self.ica_action.retrieve_flag_value(&String::from("-s"));
|
||||
@@ -284,13 +280,13 @@ impl CommitManager {
|
||||
let coverpath = self.ica_action.retrieve_flag_value(&String::from("-ca"));
|
||||
let track_id = self.ica_action.retrieve_flag_value(&String::from("-t"));
|
||||
|
||||
let single_target = songpath.len() > 0
|
||||
&& metadata_path.len() > 0
|
||||
&& coverpath.len() > 0
|
||||
&& track_id.len() > 0;
|
||||
let single_target = !songpath.is_empty()
|
||||
&& !metadata_path.is_empty()
|
||||
&& !coverpath.is_empty()
|
||||
&& !track_id.is_empty();
|
||||
|
||||
let uni = self.ica_action.retrieve_flag_value(&String::from("-smca"));
|
||||
let multitarget = uni.len() > 0;
|
||||
let multitarget = !uni.is_empty();
|
||||
|
||||
if single_target && multitarget {
|
||||
println!("Cannot upload from source and directory");
|
||||
@@ -298,37 +294,30 @@ impl CommitManager {
|
||||
}
|
||||
|
||||
if single_target {
|
||||
println!("Song path: {}", songpath);
|
||||
println!("Track ID: {}", track_id);
|
||||
println!("metadata path: {}", metadata_path);
|
||||
println!("cover art path: {}", coverpath);
|
||||
println!("Song path: {songpath}");
|
||||
println!("Track ID: {track_id}");
|
||||
println!("metadata path: {metadata_path}");
|
||||
println!("cover art path: {coverpath}");
|
||||
|
||||
let _ = self.sing_target_upload(&songpath, &track_id, &metadata_path, &coverpath);
|
||||
let _ = self
|
||||
.sing_target_upload(&songpath, &track_id, &metadata_path, &coverpath, token)
|
||||
.await;
|
||||
} else if multitarget {
|
||||
let _ = self.multi_target_upload(&uni);
|
||||
let _ = self.multi_target_upload(&uni, token).await;
|
||||
} else {
|
||||
println!("Single or Multi target has not been chosen");
|
||||
eprintln!("Single or Multi target has not been chosen");
|
||||
}
|
||||
}
|
||||
|
||||
fn sing_target_upload(
|
||||
/// Only uploading one song
|
||||
async fn sing_target_upload(
|
||||
&mut self,
|
||||
songpath: &String,
|
||||
track_id: &String,
|
||||
track_id: &str,
|
||||
meta_path: &String,
|
||||
cover_path: &String,
|
||||
cover_path: &str,
|
||||
token: &icarus_models::token::AccessToken,
|
||||
) -> Result<()> {
|
||||
let mut prsr = parsers::api_parser::APIParser {
|
||||
api: models::api::API::default(),
|
||||
ica_act: self.ica_action.clone(),
|
||||
};
|
||||
prsr.parse_api();
|
||||
|
||||
let api = prsr.retrieve_api();
|
||||
let token = self.parse_token(&api);
|
||||
|
||||
println!("Token: {:?}", token.token);
|
||||
|
||||
let song_file = std::path::Path::new(&songpath);
|
||||
|
||||
if !song_file.exists() {
|
||||
@@ -336,20 +325,21 @@ impl CommitManager {
|
||||
panic!("Error");
|
||||
}
|
||||
|
||||
let pa = std::path::Path::new(&cover_path);
|
||||
|
||||
let mut cover_art = icarus_models::coverart::CoverArt {
|
||||
id: 0,
|
||||
title: String::new(),
|
||||
path: cover_path.clone(),
|
||||
data: Vec::new(),
|
||||
directory: String::from(pa.parent().unwrap().to_str().unwrap()),
|
||||
filename: String::from(pa.file_name().unwrap().to_str().unwrap()),
|
||||
..Default::default()
|
||||
};
|
||||
let file_name = std::ffi::OsString::from(&song_file.file_name().unwrap());
|
||||
|
||||
match self.find_file_extension(&file_name) {
|
||||
En::SongFile => match utilities::string::o_to_string(&file_name) {
|
||||
Ok(s) => {
|
||||
println!("file name: {:?}", file_name);
|
||||
println!("file name: {file_name:?}");
|
||||
|
||||
match icarus_models::album::collection::parse_album(&meta_path) {
|
||||
match icarus_models::album::collection::parse_album(meta_path) {
|
||||
Ok(album) => {
|
||||
let filename = s.clone();
|
||||
let directory = song_file.parent().unwrap().display().to_string();
|
||||
@@ -359,67 +349,112 @@ impl CommitManager {
|
||||
println!("Directory: {:?}", s.directory);
|
||||
println!("Filename: {:?}", s.filename);
|
||||
println!("Path: {:?}", s.song_path());
|
||||
s.data = s.to_data().unwrap();
|
||||
s.data = icarus_models::song::io::to_data(&s).unwrap();
|
||||
cover_art.data =
|
||||
icarus_models::coverart::io::to_data(&cover_art).unwrap();
|
||||
|
||||
cover_art.data = cover_art.to_data().unwrap();
|
||||
let members = UploadSongMembers {
|
||||
song: s,
|
||||
coverart: cover_art,
|
||||
token: token.clone(),
|
||||
album,
|
||||
};
|
||||
|
||||
let mut up = syncers::upload::Upload::default();
|
||||
let host = self.ica_action.retrieve_flag_value(&String::from("-h"));
|
||||
up.set_api(&host);
|
||||
|
||||
let res = up.upload_song_with_metadata(&token, &s, &cover_art);
|
||||
|
||||
match Runtime::new().unwrap().block_on(res) {
|
||||
Ok(o) => {
|
||||
println!("Successfully sent {:?}", o);
|
||||
Ok(())
|
||||
}
|
||||
Err(er) => {
|
||||
println!("Some error {:?}", er);
|
||||
Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Other,
|
||||
er.to_string(),
|
||||
))
|
||||
}
|
||||
match self.upload_song_process(&members).await {
|
||||
Ok(_) => Ok(()),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
println!("Error: {:?}", err);
|
||||
Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Other,
|
||||
err.to_string(),
|
||||
))
|
||||
println!("Error: {err:?}");
|
||||
Err(std::io::Error::other(err.to_string()))
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(er) => {
|
||||
println!("Error: {:?}", er);
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Other,
|
||||
er.to_string(),
|
||||
));
|
||||
println!("Error: {er:?}");
|
||||
Err(std::io::Error::other(er.to_string()))
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Other,
|
||||
"No sutitable file found".to_owned(),
|
||||
));
|
||||
_ => Err(std::io::Error::other("No sutitable file found".to_owned())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Upload song to the queue to get processed
|
||||
async fn upload_song_process(&self, data: &UploadSongMembers) -> Result<()> {
|
||||
let mut up = syncers::upload::Upload::default();
|
||||
let host = self.ica_action.retrieve_flag_value(&String::from("-h"));
|
||||
up.set_api(&host);
|
||||
|
||||
let token = &data.token;
|
||||
let song = &data.song;
|
||||
let album = &data.album;
|
||||
let coverart = &data.coverart;
|
||||
|
||||
println!("Queueing song");
|
||||
|
||||
let queued_song_id = match up.queue_song(token, song).await {
|
||||
Ok(id) => id,
|
||||
Err(err) => {
|
||||
return Err(std::io::Error::other(err.to_string()));
|
||||
}
|
||||
};
|
||||
|
||||
println!("Queued song Id: {queued_song_id:?}");
|
||||
|
||||
match up.link_user_to_queued_song(token, &queued_song_id).await {
|
||||
Ok(_) => {
|
||||
println!("Queued song linked to user");
|
||||
}
|
||||
Err(err) => {
|
||||
return Err(std::io::Error::other(err.to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
let queued_metadata_id = match up.queue_metadata(token, album, song, &queued_song_id).await
|
||||
{
|
||||
Ok(id) => id,
|
||||
Err(err) => {
|
||||
return Err(std::io::Error::other(err.to_string()));
|
||||
}
|
||||
};
|
||||
|
||||
println!("Queued metadata Id: {queued_metadata_id:?}");
|
||||
|
||||
match up.queue_coverart(token, coverart).await {
|
||||
Ok(id) => match up
|
||||
.link_queued_song_to_queued_coverart(token, &queued_song_id, &id)
|
||||
.await
|
||||
{
|
||||
Ok(_) => match up
|
||||
.update_queued_song_status(token, &queued_song_id, "ready")
|
||||
.await
|
||||
{
|
||||
Ok(_) => {
|
||||
println!("Queued coverart Id: {id:?}");
|
||||
println!("Linked queued song to queued coverart");
|
||||
println!("Queued status updated");
|
||||
Ok(())
|
||||
}
|
||||
Err(err) => Err(std::io::Error::other(err.to_string())),
|
||||
},
|
||||
Err(err) => Err(std::io::Error::other(err.to_string())),
|
||||
},
|
||||
Err(err) => Err(std::io::Error::other(err.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
fn get_songs(
|
||||
&self,
|
||||
metadata_path: &String,
|
||||
source_directory: &String,
|
||||
source_directory: &str,
|
||||
) -> Result<Vec<icarus_models::song::Song>> {
|
||||
match icarus_models::album::collection::parse_album(metadata_path) {
|
||||
Ok(albums) => {
|
||||
let mut songs: Vec<icarus_models::song::Song> = Vec::new();
|
||||
|
||||
for track in &albums.tracks {
|
||||
let filename = if track.track < 10 {
|
||||
let song_filename = if track.track < 10 {
|
||||
"track0".to_owned()
|
||||
+ &track.track.to_string()
|
||||
+ icarus_models::constants::file_extensions::audio::DEFAULTMUSICEXTENSION
|
||||
@@ -430,91 +465,109 @@ impl CommitManager {
|
||||
};
|
||||
|
||||
songs.push(icarus_models::song::Song {
|
||||
id: -1,
|
||||
title: track.title.clone(),
|
||||
artist: track.artist.clone(),
|
||||
disc: track.disc.clone(),
|
||||
track: track.track.clone(),
|
||||
duration: track.duration.clone() as i32,
|
||||
year: albums.year.clone(),
|
||||
disc: track.disc,
|
||||
track: track.track,
|
||||
duration: track.duration as i32,
|
||||
year: albums.year,
|
||||
album_artist: albums.artist.clone(),
|
||||
genre: albums.genre.clone(),
|
||||
disc_count: albums.disc_count.clone(),
|
||||
track_count: albums.track_count.clone(),
|
||||
disc_count: albums.disc_count,
|
||||
track_count: albums.track_count,
|
||||
album: albums.title.clone(),
|
||||
audio_type: String::from("FLAC"),
|
||||
directory: source_directory.clone(),
|
||||
filename: filename,
|
||||
user_id: -1,
|
||||
data: Vec::new(),
|
||||
date_created: String::new(),
|
||||
directory: source_directory.to_owned(),
|
||||
filename: song_filename,
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
Ok(songs)
|
||||
}
|
||||
Err(_) => Ok(Vec::new()),
|
||||
Err(_) => Err(std::io::Error::other("Songs not retrieved")),
|
||||
}
|
||||
}
|
||||
|
||||
fn multi_target_upload(&mut self, sourcepath: &String) -> std::io::Result<()> {
|
||||
let mut prsr = parsers::api_parser::APIParser {
|
||||
api: models::api::API::default(),
|
||||
ica_act: self.ica_action.clone(),
|
||||
};
|
||||
prsr.parse_api();
|
||||
let api = prsr.retrieve_api();
|
||||
let token = self.parse_token(&api);
|
||||
|
||||
async fn multi_target_upload(
|
||||
&mut self,
|
||||
sourcepath: &String,
|
||||
token: &icarus_models::token::AccessToken,
|
||||
) -> std::io::Result<()> {
|
||||
let directory_path = std::path::Path::new(&sourcepath);
|
||||
|
||||
if !directory_path.exists() {
|
||||
panic!("Directory does not exist");
|
||||
}
|
||||
|
||||
let mut cover_art = icarus_models::coverart::CoverArt {
|
||||
id: 0,
|
||||
title: String::new(),
|
||||
path: match self.get_cover_art_path(&sourcepath) {
|
||||
Ok(o) => o,
|
||||
Err(_) => String::new(),
|
||||
},
|
||||
data: Vec::new(),
|
||||
};
|
||||
let metadatapath = match self.get_metadata_path(&sourcepath) {
|
||||
Ok(o) => o,
|
||||
Err(_) => String::new(),
|
||||
};
|
||||
let (coverart_directory, coverart_filename) =
|
||||
self.get_coverart_dir_and_filename(sourcepath).unwrap();
|
||||
let mut cover_art = icarus_models::coverart::init::init_coverart_dir_and_filename(
|
||||
&coverart_directory,
|
||||
&coverart_filename,
|
||||
);
|
||||
let metadatapath = self.get_metadata_path(sourcepath).unwrap_or_default();
|
||||
|
||||
let mut up = syncers::upload::Upload::default();
|
||||
let host = self.ica_action.retrieve_flag_value(&String::from("-h"));
|
||||
up.set_api(&host);
|
||||
|
||||
cover_art.data = cover_art.to_data().unwrap();
|
||||
cover_art.data = icarus_models::coverart::io::to_data(&cover_art).unwrap();
|
||||
|
||||
println!("");
|
||||
match self.get_songs(&metadatapath, sourcepath) {
|
||||
Ok(sngs) => match icarus_models::album::collection::parse_album(&metadatapath) {
|
||||
Ok(album) => {
|
||||
for song in sngs {
|
||||
let members = UploadSongMembers {
|
||||
song,
|
||||
coverart: cover_art.clone(),
|
||||
token: token.clone(),
|
||||
album: album.clone(),
|
||||
};
|
||||
|
||||
match self.get_songs(&metadatapath, &sourcepath) {
|
||||
Ok(sngs) => {
|
||||
for song in sngs {
|
||||
match Runtime::new()
|
||||
.unwrap()
|
||||
.block_on(up.upload_song_with_metadata(&token, &song, &cover_art))
|
||||
{
|
||||
Ok(o) => {
|
||||
println!("Response: {:?}", o);
|
||||
match self.upload_song_process(&members).await {
|
||||
Ok(o) => {
|
||||
println!("Response: {o:?}");
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("Error: {err:?}");
|
||||
return Err(err);
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
println!("Error: {:?}", err);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("Error: {err:?}");
|
||||
Err(std::io::Error::other(err.to_string()))
|
||||
}
|
||||
},
|
||||
Err(error) => {
|
||||
println!("Error: {:?}", error);
|
||||
eprintln!("Error: {error:?}");
|
||||
Err(std::io::Error::other(error.to_string()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn get_coverart_dir_and_filename(&self, directory: &str) -> Result<(String, String)> {
|
||||
for entry in read_dir(std::path::Path::new(directory))? {
|
||||
let entry = entry?;
|
||||
|
||||
let file_type = entry.file_type();
|
||||
let file_name = entry.file_name();
|
||||
|
||||
println!("file type: {file_type:?}");
|
||||
println!("file name: {file_name:?}");
|
||||
|
||||
if let En::ImageFile = self.find_file_extension(&file_name) {
|
||||
let fname = utilities::string::o_to_string(&file_name);
|
||||
return Ok((directory.to_string(), fname.unwrap()));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
Err(std::io::Error::other(
|
||||
"CoverArt directory and filename not found",
|
||||
))
|
||||
}
|
||||
|
||||
fn find_file_extension(&self, file_name: &std::ffi::OsString) -> En {
|
||||
@@ -562,31 +615,7 @@ impl CommitManager {
|
||||
}
|
||||
}
|
||||
|
||||
return En::Other;
|
||||
}
|
||||
|
||||
fn get_cover_art_path(&self, directory_path: &String) -> Result<String> {
|
||||
for entry in read_dir(std::path::Path::new(directory_path))? {
|
||||
let entry = entry?;
|
||||
|
||||
let file_type = entry.file_type();
|
||||
let file_name = entry.file_name();
|
||||
|
||||
println!("file type: {:?}", file_type);
|
||||
println!("file name: {:?}", file_name);
|
||||
|
||||
match self.find_file_extension(&file_name) {
|
||||
En::ImageFile => {
|
||||
let directory_part = directory_path.clone();
|
||||
let fname = utilities::string::o_to_string(&file_name);
|
||||
let fullpath = directory_part + "/" + &fname.unwrap();
|
||||
return Ok(fullpath);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(String::new())
|
||||
En::Other
|
||||
}
|
||||
|
||||
fn get_metadata_path(&self, directory_path: &String) -> Result<String> {
|
||||
@@ -596,28 +625,16 @@ impl CommitManager {
|
||||
let file_type = entry.file_type();
|
||||
let file_name = entry.file_name();
|
||||
|
||||
println!("file type: {:?}", file_type);
|
||||
println!("file name: {:?}", file_name);
|
||||
println!("file type: {file_type:?}");
|
||||
println!("file name: {file_name:?}");
|
||||
|
||||
match self.find_file_extension(&file_name) {
|
||||
En::MetadataFile => {
|
||||
let directory_part = directory_path.clone();
|
||||
let fname = utilities::string::o_to_string(&file_name);
|
||||
return Ok(directory_part + "/" + &fname.unwrap());
|
||||
}
|
||||
_ => {}
|
||||
if let En::MetadataFile = self.find_file_extension(&file_name) {
|
||||
let directory_part = directory_path.clone();
|
||||
let fname = utilities::string::o_to_string(&file_name);
|
||||
return Ok(format!("{}/{}", directory_part, &fname.unwrap()));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(String::new())
|
||||
}
|
||||
|
||||
fn _check_for_no_confirm(&self) -> bool {
|
||||
for flag in self.ica_action.flags.iter() {
|
||||
if flag.flag == "-nc" {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
Err(std::io::Error::other("Metadata path not found"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,21 +2,30 @@ 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: icarus_models::user::User,
|
||||
pub api: models::api::API,
|
||||
pub api: models::api::Api,
|
||||
}
|
||||
|
||||
impl Default for TokenManager {
|
||||
fn default() -> Self {
|
||||
let mut token = TokenManager {
|
||||
user: icarus_models::user::User::default(),
|
||||
api: models::api::API::default(),
|
||||
api: models::api::Api::default(),
|
||||
};
|
||||
|
||||
token.init();
|
||||
|
||||
return token;
|
||||
token
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,11 +34,10 @@ impl TokenManager {
|
||||
println!("Sending request for a token");
|
||||
|
||||
let url = self.retrieve_url();
|
||||
|
||||
println!("URL: {}", url);
|
||||
println!("URL: {url}");
|
||||
|
||||
let mut token = icarus_models::token::AccessToken {
|
||||
user_id: -1,
|
||||
user_id: uuid::Uuid::nil(),
|
||||
username: String::new(),
|
||||
token: String::new(),
|
||||
token_type: String::new(),
|
||||
@@ -43,37 +51,36 @@ impl TokenManager {
|
||||
match response.status() {
|
||||
reqwest::StatusCode::OK => {
|
||||
// on success, parse our JSON to an APIResponse
|
||||
let s = response.json::<icarus_models::token::AccessToken>().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;
|
||||
Ok(token)
|
||||
}
|
||||
Err(_) => println!("Hm, the response didn't match the shape we expected."),
|
||||
};
|
||||
Err(err) => Err(std::io::Error::other(err.to_string())),
|
||||
}
|
||||
}
|
||||
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);
|
||||
panic!("Uh oh! Something unexpected happened: {other:?}");
|
||||
}
|
||||
}
|
||||
|
||||
return 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);
|
||||
|
||||
return url;
|
||||
format!("{}{}", self.api.url, self.api.endpoint)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,27 +1,16 @@
|
||||
use std::default::Default;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::models::{self};
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[derive(Debug, Default)]
|
||||
pub struct UserManager {
|
||||
pub user: icarus_models::user::User,
|
||||
pub ica_action: models::icarus_action::IcarusAction,
|
||||
}
|
||||
|
||||
impl Default for UserManager {
|
||||
fn default() -> Self {
|
||||
UserManager {
|
||||
user: icarus_models::user::User::default(),
|
||||
ica_action: models::icarus_action::IcarusAction::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl UserManager {
|
||||
pub fn retrieve_user(&self) -> icarus_models::user::User {
|
||||
return self.user.clone();
|
||||
self.user.clone()
|
||||
}
|
||||
|
||||
pub fn parse_user_from_actions(&mut self) {
|
||||
|
||||
+2
-14
@@ -1,20 +1,8 @@
|
||||
use std::default::Default;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct API {
|
||||
#[derive(Clone, Debug, Default)]
|
||||
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
-12
@@ -1,18 +1,7 @@
|
||||
use std::default::Default;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Flags {
|
||||
pub flag: String,
|
||||
pub value: String,
|
||||
}
|
||||
|
||||
impl Default for Flags {
|
||||
fn default() -> Self {
|
||||
Flags {
|
||||
flag: String::new(),
|
||||
value: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,24 +1,13 @@
|
||||
use std::default::Default;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::models;
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[derive(Clone, Debug, Default)]
|
||||
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 +19,7 @@ impl IcarusAction {
|
||||
}
|
||||
}
|
||||
|
||||
return val;
|
||||
val
|
||||
}
|
||||
|
||||
pub fn print_action_and_flags(&self) {
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
pub mod api;
|
||||
pub mod flags;
|
||||
pub mod icarus_action;
|
||||
pub mod upload_form;
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
}
|
||||
+37
-11
@@ -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;
|
||||
|
||||
if arg == "-h" {
|
||||
if value.chars().nth(value.len() - 1) == Some('/') {
|
||||
self.api.url = value;
|
||||
} else {
|
||||
self.api.url = value + "/";
|
||||
match api_type {
|
||||
APIType::Main => {
|
||||
if arg == "-h" {
|
||||
if value.chars().nth(value.len() - 1) == Some('/') {
|
||||
self.apis[0].url = value;
|
||||
} else {
|
||||
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;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
self.api.version = "v1".to_string();
|
||||
for api in &mut self.apis {
|
||||
api.version = String::from(API_VERSION);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+16
-22
@@ -1,32 +1,26 @@
|
||||
use crate::models;
|
||||
|
||||
pub fn retrieve_url(api: &models::api::API, with_id: bool, id: i32) -> String {
|
||||
pub fn retrieve_url(api: &models::api::Api, with_id: bool, id: &uuid::Uuid) -> String {
|
||||
if with_id {
|
||||
retrieve_url_with_id(&api, id)
|
||||
retrieve_url_with_id(api, id)
|
||||
} else {
|
||||
retrieve_url_reg(&api)
|
||||
retrieve_url_reg(api)
|
||||
}
|
||||
}
|
||||
|
||||
fn retrieve_url_reg(api: &models::api::API) -> String {
|
||||
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;
|
||||
fn retrieve_url_reg(api: &models::api::Api) -> String {
|
||||
format!("{}api/{}/{}/", api.url, api.version, api.endpoint)
|
||||
}
|
||||
|
||||
fn retrieve_url_with_id(api: &models::api::API, id: i32) -> String {
|
||||
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 += &id.to_string();
|
||||
|
||||
return url;
|
||||
fn retrieve_url_with_id(api: &models::api::Api, id: &uuid::Uuid) -> String {
|
||||
format!("{}api/{}/{}/{}", api.url, api.version, api.endpoint, id)
|
||||
}
|
||||
|
||||
pub async fn auth_header(
|
||||
token: &icarus_models::token::AccessToken,
|
||||
) -> Result<(http::HeaderName, http::HeaderValue), http::header::InvalidHeaderValue> {
|
||||
match http::HeaderValue::from_str(&token.bearer_token()) {
|
||||
Ok(auth_value) => Ok((reqwest::header::AUTHORIZATION, auth_value)),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
+28
-20
@@ -3,17 +3,24 @@ use std::default::Default;
|
||||
use reqwest;
|
||||
|
||||
use crate::models;
|
||||
use crate::syncers;
|
||||
|
||||
#[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>,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,9 +30,12 @@ impl Delete {
|
||||
&mut self,
|
||||
token: &icarus_models::token::AccessToken,
|
||||
song: &icarus_models::song::Song,
|
||||
) -> Result<icarus_models::song::Song, std::io::Error> {
|
||||
self.api.endpoint = "song/data/delete".to_owned();
|
||||
let url = syncers::common::retrieve_url(&self.api, true, song.id);
|
||||
) -> 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
|
||||
@@ -39,18 +49,16 @@ impl Delete {
|
||||
reqwest::StatusCode::OK => {
|
||||
println!("Success!");
|
||||
|
||||
match response.json::<icarus_models::song::Song>().await {
|
||||
Ok(sng) => Ok(sng),
|
||||
Err(er) => Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Other,
|
||||
er.to_string(),
|
||||
)),
|
||||
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::new(
|
||||
std::io::ErrorKind::Other,
|
||||
other.to_string(),
|
||||
)),
|
||||
other => Err(std::io::Error::other(other.to_string())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+13
-29
@@ -3,16 +3,9 @@ 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)]
|
||||
@@ -27,10 +20,12 @@ impl Download {
|
||||
token: &icarus_models::token::AccessToken,
|
||||
song: &icarus_models::song::Song,
|
||||
) -> Result<String, MyError> {
|
||||
self.api.endpoint = String::from("song/data/download");
|
||||
let url = syncers::common::retrieve_url(&self.api, true, song.id);
|
||||
self.api.endpoint = String::from("song/download");
|
||||
let url = syncers::common::retrieve_url(&self.api, true, &song.id);
|
||||
let access_token = token.bearer_token();
|
||||
|
||||
println!("Url: {url:?}");
|
||||
|
||||
let client = reqwest::Client::builder().build().unwrap();
|
||||
|
||||
match client
|
||||
@@ -40,27 +35,16 @@ impl Download {
|
||||
.await
|
||||
{
|
||||
Ok(rep) => match rep.status() {
|
||||
reqwest::StatusCode::OK => {
|
||||
let data = rep.text();
|
||||
match data.await {
|
||||
Ok(e) => {
|
||||
return Ok(e);
|
||||
}
|
||||
Err(er) => {
|
||||
return Err(MyError::Other(er.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
reqwest::StatusCode::OK => match rep.text().await {
|
||||
Ok(e) => Ok(e),
|
||||
Err(er) => Err(MyError::Other(er.to_string())),
|
||||
},
|
||||
reqwest::StatusCode::UNAUTHORIZED => {
|
||||
return Err(MyError::Other(String::from("Need to grab a new token")));
|
||||
}
|
||||
other => {
|
||||
return Err(MyError::Other(other.to_string()));
|
||||
Err(MyError::Other(String::from("Need to grab a new token")))
|
||||
}
|
||||
other => Err(MyError::Other(other.to_string())),
|
||||
},
|
||||
Err(er) => {
|
||||
return Err(MyError::Request(er));
|
||||
}
|
||||
Err(er) => Err(MyError::Request(er)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,16 +2,18 @@ use std::default::Default;
|
||||
use std::io::Error;
|
||||
|
||||
use crate::models;
|
||||
use crate::syncers;
|
||||
|
||||
#[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>,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,10 +23,12 @@ impl RetrieveRecords {
|
||||
&mut self,
|
||||
token: &icarus_models::token::AccessToken,
|
||||
) -> Result<Vec<icarus_models::song::Song>, Error> {
|
||||
self.api.endpoint = String::from("song");
|
||||
let url = syncers::common::retrieve_url(&self.api, false, 0);
|
||||
self.api.endpoint = String::from("api/v2/song/all");
|
||||
let url = format!("{}{}", self.api.url, self.api.endpoint);
|
||||
let access_token = token.bearer_token();
|
||||
|
||||
println!("url: {url:?}");
|
||||
|
||||
let client = reqwest::Client::builder().build().unwrap();
|
||||
let response = client
|
||||
.get(&url)
|
||||
@@ -35,29 +39,19 @@ impl RetrieveRecords {
|
||||
|
||||
match response.status() {
|
||||
reqwest::StatusCode::OK => {
|
||||
// on success, parse our JSON to an APIResponse
|
||||
match response.json::<Vec<icarus_models::song::Song>>().await {
|
||||
Ok(parsed) => Ok(parsed),
|
||||
Err(err) => {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Other,
|
||||
err.to_string(),
|
||||
));
|
||||
// on success, parse our JSON to an API Response
|
||||
match response.json::<response::get_all_songs::Response>().await {
|
||||
Ok(parsed) => {
|
||||
println!("Response message: {:?}", parsed.message);
|
||||
Ok(parsed.data)
|
||||
}
|
||||
Err(err) => Err(std::io::Error::other(err.to_string())),
|
||||
}
|
||||
}
|
||||
reqwest::StatusCode::UNAUTHORIZED => {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Other,
|
||||
"Need to grab a new token",
|
||||
));
|
||||
}
|
||||
other => {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Other,
|
||||
other.to_string(),
|
||||
));
|
||||
Err(std::io::Error::other("Need to grab a new token"))
|
||||
}
|
||||
other => Err(std::io::Error::other(other.to_string())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+261
-67
@@ -6,46 +6,72 @@ use reqwest;
|
||||
use crate::models;
|
||||
use crate::syncers;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Upload {
|
||||
pub api: models::api::API,
|
||||
pub api: models::api::Api,
|
||||
}
|
||||
|
||||
impl Default for Upload {
|
||||
fn default() -> Self {
|
||||
Upload {
|
||||
api: models::api::API::default(),
|
||||
mod response {
|
||||
pub mod queue_song {
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
pub struct Response {
|
||||
pub message: String,
|
||||
pub data: Vec<uuid::Uuid>,
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
pub async fn queue_song(
|
||||
&self,
|
||||
token: &icarus_models::token::AccessToken,
|
||||
song: &icarus_models::song::Song,
|
||||
cover: &icarus_models::coverart::CoverArt,
|
||||
) -> Result<reqwest::Response, reqwest::Error> {
|
||||
self.api.endpoint = String::from("song/data/upload/with/data");
|
||||
let url = syncers::common::retrieve_url(&self.api, false, 0);
|
||||
let access_token = token.bearer_token();
|
||||
) -> 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);
|
||||
println!("Path: {:?}", song.song_path());
|
||||
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.unwrap();
|
||||
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(&song, &cover);
|
||||
let client = reqwest::Client::builder().build().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)
|
||||
@@ -53,58 +79,226 @@ impl Upload {
|
||||
.send()
|
||||
.await
|
||||
{
|
||||
Ok(r) => {
|
||||
return Ok(r);
|
||||
}
|
||||
Err(err) => {
|
||||
return Err(err);
|
||||
}
|
||||
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 init_form(
|
||||
pub async fn link_user_to_queued_song(
|
||||
&self,
|
||||
song: &icarus_models::song::Song,
|
||||
cover: &icarus_models::coverart::CoverArt,
|
||||
) -> reqwest::multipart::Form {
|
||||
let songpath = match song.song_path() {
|
||||
Ok(s) => s,
|
||||
Err(_) => String::new(),
|
||||
};
|
||||
let coverpath = cover.path.clone();
|
||||
println!("Cover path: {:?}", coverpath);
|
||||
let song_detail = match song.to_metadata_json(true) {
|
||||
Ok(s) => s,
|
||||
Err(_) => String::new(),
|
||||
};
|
||||
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);
|
||||
|
||||
println!("\n{}\n", song_detail);
|
||||
let mut headers = reqwest::header::HeaderMap::new();
|
||||
let (auth, auth_val) = syncers::common::auth_header(token).await.unwrap();
|
||||
headers.insert(auth, auth_val);
|
||||
|
||||
let mut song_filename = String::from("audio");
|
||||
song_filename += icarus_models::constants::file_extensions::audio::DEFAULTMUSICEXTENSION;
|
||||
let mut cover_filename = String::from("cover");
|
||||
cover_filename += icarus_models::constants::file_extensions::image::JPGEXTENSION;
|
||||
let payload = serde_json::json!({
|
||||
"song_queue_id": queued_song_id,
|
||||
"user_id": token.user_id
|
||||
});
|
||||
|
||||
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);
|
||||
let client = reqwest::Client::builder().build().unwrap();
|
||||
|
||||
return form;
|
||||
match client
|
||||
.patch(url)
|
||||
.headers(headers)
|
||||
.json(&payload)
|
||||
.send()
|
||||
.await
|
||||
{
|
||||
Ok(_) => Ok(()),
|
||||
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 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);
|
||||
|
||||
let mut headers = reqwest::header::HeaderMap::new();
|
||||
let (auth, auth_val) = syncers::common::auth_header(token).await.unwrap();
|
||||
headers.insert(auth, auth_val);
|
||||
|
||||
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 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::stream(file_body)
|
||||
.file_name(file_name)
|
||||
.mime_str("application/octet-stream")
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
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.unwrap();
|
||||
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 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.unwrap();
|
||||
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.unwrap();
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,32 +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,9 +1,12 @@
|
||||
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::new(
|
||||
std::io::ErrorKind::Other,
|
||||
String::from("Error"),
|
||||
)),
|
||||
Err(err) => match err.into_string() {
|
||||
Ok(res) => Err(std::io::Error::other(res.to_string())),
|
||||
Err(err) => match err.to_str() {
|
||||
Some(err) => Err(std::io::Error::other(err)),
|
||||
None => Err(std::io::Error::other("Undefined error")),
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
pub fn print_version() {
|
||||
let name = env!("CARGO_PKG_NAME");
|
||||
let version = env!("CARGO_PKG_VERSION");
|
||||
|
||||
println!("{name:?} {version:?}");
|
||||
}
|
||||
Reference in New Issue
Block a user