Refactoring #31

Merged
kdeng00 merged 14 commits from refactoring into master 2025-03-13 21:40:22 -04:00
18 changed files with 105 additions and 169 deletions
+1 -1
View File
@@ -16,4 +16,4 @@ serde = { version = "1.0.219", features = ["derive"] }
serde_json = "1.0.140" serde_json = "1.0.140"
tokio = { version = "1.44.0", features = ["full"] } tokio = { version = "1.44.0", features = ["full"] }
tokio-util = { version = "0.7.13", features = ["codec"] } tokio-util = { version = "0.7.13", features = ["codec"] }
icarus-models = { git = "ssh://git@gitlab.com/kdeng00/icarus-models.git", tag = "v0.1.1" } icarus-models = { git = "ssh://git@gitlab.com/kdeng00/icarus-models.git", tag = "v0.1.7" }
-4
View File
@@ -1,4 +0,0 @@
pub const WAV_FILE_EXTENSION: &str = ".wav";
pub const FLAC_FILE_EXTENSION: &str = ".flac";
pub const _MP3_FILE_EXTENSION: &str = ".mp3";
pub const JPG_FILE_EXTENSION: &str = ".jpg";
-1
View File
@@ -1 +0,0 @@
pub mod file_extensions;
+36
View File
@@ -0,0 +1,36 @@
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 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);
}
+8 -56
View File
@@ -1,4 +1,4 @@
mod constants; mod help;
mod managers; mod managers;
mod models; mod models;
mod parsers; mod parsers;
@@ -6,71 +6,23 @@ mod syncers;
mod utilities; mod utilities;
use std::env; 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() { fn main() {
let args: Vec<String> = env::args().collect(); let args: Vec<String> = env::args().collect();
if args.len() == 1 {
print_help();
exit_program(-1);
}
let args_len = args.len() as i32; let args_len = args.len() as i32;
if args_len == 1 {
help::print_help();
utilities::checks::exit_program(-1);
}
println!("Argument count: {}", args_len); println!("Argument count: {}", args_len);
let mut act_mgr = managers::action_managers::ActionManager { let mut act_mgr = managers::action_managers::ActionManager::default();
action: String::new(), act_mgr.set_params(&args);
flags: Vec::new(),
params: args,
param_count: args_len,
};
act_mgr.initialize(); act_mgr.initialize();
let chosen_act = act_mgr.retrieve_icarus_action(); let chosen_act = act_mgr.retrieve_icarus_action();
chosen_act.print_action_and_flags(); chosen_act.print_action_and_flags();
let mut cmt_mgr = managers::commit_manager::CommitManager { let mut cmt_mgr = managers::commit_manager::CommitManager {
+18 -3
View File
@@ -1,6 +1,6 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::models; use crate::{models, utilities};
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize)]
pub struct ActionManager { pub struct ActionManager {
@@ -10,6 +10,17 @@ pub struct ActionManager {
pub param_count: i32, 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 { impl ActionManager {
pub fn retrieve_icarus_action(&self) -> models::icarus_action::IcarusAction { pub fn retrieve_icarus_action(&self) -> models::icarus_action::IcarusAction {
return models::icarus_action::IcarusAction { return models::icarus_action::IcarusAction {
@@ -45,6 +56,11 @@ impl ActionManager {
self.action = self.action.to_lowercase(); self.action = self.action.to_lowercase();
} }
pub fn set_params(&mut self, args: &Vec<String>) {
self.params = args.clone();
self.param_count = self.params.len() as i32;
}
fn validate_flags(&mut self) { fn validate_flags(&mut self) {
println!("Validating flags"); println!("Validating flags");
@@ -70,7 +86,7 @@ impl ActionManager {
flg.flag = String::from(flag); flg.flag = String::from(flag);
} else { } else {
println!("Flag {} is not valid", flag); println!("Flag {} is not valid", flag);
std::process::exit(-1); utilities::checks::exit_program(-1);
} }
self.flags.push(flg); self.flags.push(flg);
@@ -102,7 +118,6 @@ impl ActionManager {
fn does_flag_have_value(&self, flag: &String) -> bool { fn does_flag_have_value(&self, flag: &String) -> bool {
let flags_tmp = self.parsed_flags(); let flags_tmp = self.parsed_flags();
let mut i_found: i32 = -1; let mut i_found: i32 = -1;
for i in 0..flags_tmp.len() { for i in 0..flags_tmp.len() {
+5 -7
View File
@@ -10,9 +10,9 @@ use tokio::runtime::Runtime;
use crate::managers; use crate::managers;
use crate::models::song::Album; use crate::models::song::Album;
use crate::models::{self}; use crate::models::{self};
use crate::parsers;
use crate::syncers; use crate::syncers;
use crate::utilities; use crate::utilities;
use crate::{constants, parsers};
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize)]
pub struct CommitManager { pub struct CommitManager {
@@ -175,6 +175,7 @@ impl CommitManager {
let api = prsr.retrieve_api(); let api = prsr.retrieve_api();
let token = self.parse_token(&api); let token = self.parse_token(&api);
println!("Message: {}", token.message);
let mut dwn_loader = syncers::download::Download { api: api.clone() }; let mut dwn_loader = syncers::download::Download { api: api.clone() };
let mut song = models::song::Song::default(); let mut song = models::song::Song::default();
@@ -185,7 +186,7 @@ impl CommitManager {
Ok(o) => { Ok(o) => {
println!("Success"); println!("Success");
let mut filename = String::from("audio"); let mut filename = String::from("audio");
filename += constants::file_extensions::WAV_FILE_EXTENSION; filename += icarus_models::constants::WAV_EXTENSION;
let data = o.as_bytes(); let data = o.as_bytes();
let mut file = std::fs::File::create(filename).expect("Failed to save"); let mut file = std::fs::File::create(filename).expect("Failed to save");
file.write_all(&data).expect("ff"); file.write_all(&data).expect("ff");
@@ -233,15 +234,12 @@ impl CommitManager {
panic!("Not supported"); panic!("Not supported");
} }
fn parse_token(&self, api: &models::api::API) -> models::token::Token { fn parse_token(&self, api: &models::api::API) -> icarus_models::token::AccessToken {
println!("Fetching token"); println!("Fetching token");
let mut usr_mgr: managers::user_manager::UserManager = let mut usr_mgr: managers::user_manager::UserManager =
managers::user_manager::UserManager { managers::user_manager::UserManager {
user: models::user::User { user: icarus_models::user::User::default(),
username: String::new(),
password: String::new(),
},
ica_action: self.ica_action.clone(), ica_action: self.ica_action.clone(),
}; };
usr_mgr.parse_user_from_actions(); usr_mgr.parse_user_from_actions();
+12 -6
View File
@@ -3,14 +3,14 @@ use std::default::Default;
use crate::models; use crate::models;
pub struct TokenManager { pub struct TokenManager {
pub user: models::user::User, pub user: icarus_models::user::User,
pub api: models::api::API, pub api: models::api::API,
} }
impl Default for TokenManager { impl Default for TokenManager {
fn default() -> Self { fn default() -> Self {
let mut token = TokenManager { let mut token = TokenManager {
user: models::user::User::default(), user: icarus_models::user::User::default(),
api: models::api::API::default(), api: models::api::API::default(),
}; };
@@ -21,14 +21,21 @@ impl Default for TokenManager {
} }
impl TokenManager { 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"); println!("Sending request for a token");
let url = self.retrieve_url(); 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: -1,
username: String::new(),
token: String::new(),
token_type: String::new(),
expiration: -1,
message: String::new(),
};
let client = reqwest::Client::new(); let client = reqwest::Client::new();
let response = client.post(&url).json(&self.user).send().await.unwrap(); let response = client.post(&url).json(&self.user).send().await.unwrap();
@@ -36,7 +43,7 @@ impl TokenManager {
match response.status() { match response.status() {
reqwest::StatusCode::OK => { reqwest::StatusCode::OK => {
// on success, parse our JSON to an APIResponse // on success, parse our JSON to an APIResponse
let s = response.json::<models::token::Token>().await; let s = response.json::<icarus_models::token::AccessToken>().await;
match s { match s {
// //
Ok(parsed) => { Ok(parsed) => {
@@ -66,7 +73,6 @@ impl TokenManager {
let api = &self.api; let api = &self.api;
let mut url = String::from(&api.url); let mut url = String::from(&api.url);
url += &String::from(&api.endpoint); url += &String::from(&api.endpoint);
url += &String::from("/");
return url; return url;
} }
+11 -5
View File
@@ -6,36 +6,42 @@ use crate::models::{self};
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize)]
pub struct UserManager { pub struct UserManager {
pub user: models::user::User, pub user: icarus_models::user::User,
pub ica_action: models::icarus_action::IcarusAction, pub ica_action: models::icarus_action::IcarusAction,
} }
impl Default for UserManager { impl Default for UserManager {
fn default() -> Self { fn default() -> Self {
UserManager { UserManager {
user: models::user::User::default(), user: icarus_models::user::User::default(),
ica_action: models::icarus_action::IcarusAction::default(), ica_action: models::icarus_action::IcarusAction::default(),
} }
} }
} }
impl UserManager { impl UserManager {
pub fn retrieve_user(&self) -> models::user::User { pub fn retrieve_user(&self) -> icarus_models::user::User {
return self.user.clone(); return self.user.clone();
} }
pub fn parse_user_from_actions(&mut self) { pub fn parse_user_from_actions(&mut self) {
let args = &self.ica_action.flags; let args = &self.ica_action.flags;
// Quit the loop when two are found
let mut amt: i32 = 0;
for arg in args { for arg in args {
let flag = &arg.flag; let flag = &arg.flag;
if flag == "-u" { if flag == "-u" {
self.user.username = String::from(&arg.value); 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" { if amt == 2 {
self.user.password = String::from(&arg.value); break;
} }
} }
} }
-2
View File
@@ -2,6 +2,4 @@ pub mod api;
pub mod flags; pub mod flags;
pub mod icarus_action; pub mod icarus_action;
pub mod song; pub mod song;
pub mod token;
pub mod upload_form; pub mod upload_form;
pub mod user;
+2 -4
View File
@@ -3,8 +3,6 @@ use std::io::Read;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::constants;
#[derive(Clone, Debug, Deserialize, Serialize)] #[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Song { pub struct Song {
#[serde(alias = "id")] #[serde(alias = "id")]
@@ -127,9 +125,9 @@ impl Song {
filename += &self.track.unwrap().to_string(); filename += &self.track.unwrap().to_string();
if i_type == 0 { if i_type == 0 {
filename += constants::file_extensions::_MP3_FILE_EXTENSION; filename += icarus_models::constants::MPTHREE_EXTENSION;
} else { } else {
filename += constants::file_extensions::WAV_FILE_EXTENSION; filename += icarus_models::constants::WAV_EXTENSION;
} }
self.filename = Some(filename); self.filename = Some(filename);
-47
View File
@@ -1,47 +0,0 @@
use std::default::Default;
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize)]
pub struct Token {
#[serde(alias = "user_id")]
pub user_id: i32,
#[serde(alias = "username")]
pub username: Option<String>,
#[serde(alias = "token")]
pub access_token: Option<String>,
#[serde(alias = "token_type")]
pub token_type: Option<String>,
#[serde(alias = "expiration")]
pub expiration: Option<i32>,
#[serde(alias = "message")]
pub message: Option<String>,
}
impl Default for Token {
fn default() -> Self {
Token {
user_id: -1,
username: None,
access_token: None,
token_type: None,
expiration: None,
message: None,
}
}
}
impl Token {
pub fn bearer_token(&self) -> String {
let mut token: String = String::from("Bearer ");
match &self.access_token {
Some(tok) => {
token += tok;
}
None => {}
}
return token;
}
}
-24
View File
@@ -1,24 +0,0 @@
use std::default::Default;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct User {
pub username: String,
pub password: String,
}
impl Default for User {
fn default() -> Self {
User {
username: String::new(),
password: String::new(),
}
}
}
impl User {
pub fn _to_json(&self) -> Result<String, serde_json::Error> {
return serde_json::to_string_pretty(&self);
}
}
+1 -1
View File
@@ -20,7 +20,7 @@ impl Default for Delete {
impl Delete { impl Delete {
pub async fn delete_song( pub async fn delete_song(
&mut self, &mut self,
token: &models::token::Token, token: &icarus_models::token::AccessToken,
song: &models::song::Song, song: &models::song::Song,
) -> Result<models::song::Song, std::io::Error> { ) -> Result<models::song::Song, std::io::Error> {
self.api.endpoint = "song/data/delete".to_owned(); self.api.endpoint = "song/data/delete".to_owned();
+1 -1
View File
@@ -23,7 +23,7 @@ pub enum MyError {
impl Download { impl Download {
pub async fn download_song( pub async fn download_song(
&mut self, &mut self,
token: &models::token::Token, token: &icarus_models::token::AccessToken,
song: &models::song::Song, song: &models::song::Song,
) -> Result<String, MyError> { ) -> Result<String, MyError> {
self.api.endpoint = String::from("song/data/download"); self.api.endpoint = String::from("song/data/download");
+1 -1
View File
@@ -18,7 +18,7 @@ impl Default for RetrieveRecords {
impl RetrieveRecords { impl RetrieveRecords {
pub async fn get_all_songs( pub async fn get_all_songs(
&mut self, &mut self,
token: &models::token::Token, token: &icarus_models::token::AccessToken,
) -> Result<Vec<models::song::Song>, Error> { ) -> Result<Vec<models::song::Song>, Error> {
self.api.endpoint = String::from("song"); self.api.endpoint = String::from("song");
let mut songs: Vec<models::song::Song> = Vec::new(); let mut songs: Vec<models::song::Song> = Vec::new();
+5 -6
View File
@@ -6,7 +6,6 @@ use reqwest;
use reqwest::multipart::Form; use reqwest::multipart::Form;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::constants;
use crate::models; use crate::models;
pub struct Upload { pub struct Upload {
@@ -47,7 +46,7 @@ impl Default for Upload {
impl Upload { impl Upload {
pub async fn upload_song_with_metadata( pub async fn upload_song_with_metadata(
&mut self, &mut self,
token: &models::token::Token, token: &icarus_models::token::AccessToken,
song: &models::song::Song, song: &models::song::Song,
cover: &models::song::CoverArt, cover: &models::song::CoverArt,
album: &models::song::Album, album: &models::song::Album,
@@ -110,9 +109,9 @@ impl Upload {
let cover = reqwest::multipart::Part::bytes(cover_raw_data).headers(headers_i); let cover = reqwest::multipart::Part::bytes(cover_raw_data).headers(headers_i);
let mut song_filename = String::from("audio"); let mut song_filename = String::from("audio");
song_filename += constants::file_extensions::WAV_FILE_EXTENSION; song_filename += icarus_models::constants::WAV_EXTENSION;
let mut cover_filename = String::from("cover"); let mut cover_filename = String::from("cover");
cover_filename += constants::file_extensions::JPG_FILE_EXTENSION; cover_filename += icarus_models::constants::JPG_EXTENSION;
return reqwest::multipart::Form::new() return reqwest::multipart::Form::new()
.part("cover", cover.file_name(cover_filename)) .part("cover", cover.file_name(cover_filename))
@@ -128,9 +127,9 @@ impl Upload {
println!("\n{}\n", song_detail); println!("\n{}\n", song_detail);
let mut song_filename = String::from("audio"); let mut song_filename = String::from("audio");
song_filename += constants::file_extensions::WAV_FILE_EXTENSION; song_filename += icarus_models::constants::WAV_EXTENSION;
let mut cover_filename = String::from("cover"); let mut cover_filename = String::from("cover");
cover_filename += constants::file_extensions::JPG_FILE_EXTENSION; cover_filename += icarus_models::constants::JPG_EXTENSION;
let form = reqwest::multipart::Form::new() let form = reqwest::multipart::Form::new()
.part( .part(
+4
View File
@@ -26,3 +26,7 @@ impl Checks {
return index; return index;
} }
} }
pub fn exit_program(code: i32) {
std::process::exit(code);
}