1use crate::errors::ConfigError;
2use serde::{Deserialize, Serialize};
3use std::fs;
4
5#[derive(Deserialize, Serialize, Clone)]
6pub struct AppConfig {
7 website: Option<String>,
8 jwt_key: Option<String>,
9}
10
11impl AppConfig {
12 pub fn website(self) -> Option<String> {
13 self.website.clone()
14 }
15
16 pub fn jwt_key(self) -> Option<String> {
17 self.jwt_key.clone()
18 }
19
20 pub fn get() -> Result<Self, ConfigError> {
21 let cfg_dir = home::home_dir().unwrap().join(".config/chamber");
22 let cfg_file = home::home_dir()
23 .unwrap()
24 .join(".config/chamber/config.toml");
25 if !cfg_dir.as_path().exists() {
26 fs::create_dir_all(cfg_dir)?;
27 }
28
29 if !cfg_file.as_path().exists() {
30 fs::File::create(cfg_file.clone())?;
31 }
32
33 let file = std::fs::read_to_string(cfg_file)?;
34
35 let cfg: Self = toml::from_str(&file)?;
36
37 Ok(cfg)
38 }
39
40 pub fn set_website(mut self, website: &str) -> Result<(), ConfigError> {
41 let cfg_file = home::home_dir()
42 .unwrap()
43 .join(".config/chamber/config.toml");
44
45 let website = if website.starts_with("localhost") {
46 format!("http://{website}")
47 } else {
48 website.to_string()
49 };
50
51 if website.starts_with("http://") & !website.contains("localhost") {
52 println!("Please note that HTTP is much less secure than using HTTPS.");
53 }
54
55 self.website = Some(website);
56
57 let toml_string = toml::to_string_pretty(&self)?;
58
59 fs::write(cfg_file, toml_string)?;
60
61 Ok(())
62 }
63
64 pub fn set_token(mut self, token: &str) -> Result<(), ConfigError> {
65 let cfg_file = home::home_dir()
66 .unwrap()
67 .join(".config/chamber/config.toml");
68
69 self.jwt_key = Some(token.to_owned());
70
71 let toml = toml::to_string_pretty(&self)?;
72
73 fs::write(cfg_file, toml)?;
74
75 Ok(())
76 }
77}