1 use std::{fs::OpenOptions, io::Write};
2
3 use anyhow::{anyhow, Result};
4 use log::debug;
5 use regex::Regex;
6 use smbpndk_model::Config;
7
8 pub fn email_validation(input: &str) -> Result<(), &'static str> {
9 let email_regex = Regex::new(
10 r"^([a-z0-9_+]([a-z0-9_+.]*[a-z0-9_+])?)@([a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,6})",
11 )
12 .unwrap();
13
14 if email_regex.is_match(input) {
15 Ok(())
16 } else {
17 Err("Username must be an email address.")
18 }
19 }
20
21 pub async fn get_config() -> Result<Config> {
22 match home::home_dir() {
23 Some(mut path) => {
24 path.push(".smb/config");
25 if !path.exists() {
26 let config = Config {
27 current_project: None,
28 current_oten_app: None,
29 current_fun_app: None,
30 current_pkt_app: None,
31 current_rdb_app: None,
32 };
33 return Ok(config);
34 }
35 let config_string = std::fs::read_to_string(path).map_err(|e| {
36 debug!("Error while reading config file: {}", &e);
37 anyhow!("Error while reading config file. Are you logged in?")
38 })?;
39 print!("config_string: {:#?}", config_string);
40 let config: Config = serde_json::from_str(&config_string).map_err(|e| {
41 debug!("Error while parsing config: {}", &e);
42 print!("Error while parsing config: {}", &e);
43 anyhow!("Error while parsing config. Are you logged in?")
44 })?;
45
46 Ok(config)
47 }
48 None => {
49 let config = Config {
50 current_project: None,
51 current_oten_app: None,
52 current_fun_app: None,
53 current_pkt_app: None,
54 current_rdb_app: None,
55 };
56 Ok(config)
57 }
58 }
59 }
60
61 pub fn write_config(config: Config) -> Result<Config> {
62 match home::home_dir() {
63 Some(path) => {
64 debug!("{}", path.to_str().unwrap());
65 let mut file = OpenOptions::new()
66 .create(true)
67 .write(true)
68 .open([path.to_str().unwrap(), "/.smb/config.json"].join(""))?;
69 let json = serde_json::to_string(&config)?;
70 file.write_all(json.as_bytes())?;
71
72 Ok(config)
73 }
74 None => Err(anyhow!("Error getting home directory.")),
75 }
76 }