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