]> Untitled Git - lemmy.git/blob - server/lemmy_utils/src/settings.rs
1d82b231c4fd39960b99f2064cef1b08e649cdec
[lemmy.git] / server / lemmy_utils / src / settings.rs
1 use config::{Config, ConfigError, Environment, File};
2 use serde::Deserialize;
3 use std::{env, fs, io::Error, net::IpAddr, sync::RwLock};
4
5 static CONFIG_FILE_DEFAULTS: &str = "config/defaults.hjson";
6 static CONFIG_FILE: &str = "config/config.hjson";
7
8 #[derive(Debug, Deserialize, Clone)]
9 pub struct Settings {
10   pub setup: Option<Setup>,
11   pub database: DatabaseConfig,
12   pub hostname: String,
13   pub bind: IpAddr,
14   pub port: u16,
15   pub jwt_secret: String,
16   pub front_end_dir: String,
17   pub pictrs_url: String,
18   pub rate_limit: RateLimitConfig,
19   pub email: Option<EmailConfig>,
20   pub federation: FederationConfig,
21   pub captcha: CaptchaConfig,
22 }
23
24 #[derive(Debug, Deserialize, Clone)]
25 pub struct Setup {
26   pub admin_username: String,
27   pub admin_password: String,
28   pub admin_email: Option<String>,
29   pub site_name: String,
30 }
31
32 #[derive(Debug, Deserialize, Clone)]
33 pub struct RateLimitConfig {
34   pub message: i32,
35   pub message_per_second: i32,
36   pub post: i32,
37   pub post_per_second: i32,
38   pub register: i32,
39   pub register_per_second: i32,
40   pub image: i32,
41   pub image_per_second: i32,
42 }
43
44 #[derive(Debug, Deserialize, Clone)]
45 pub struct EmailConfig {
46   pub smtp_server: String,
47   pub smtp_login: Option<String>,
48   pub smtp_password: Option<String>,
49   pub smtp_from_address: String,
50   pub use_tls: bool,
51 }
52
53 #[derive(Debug, Deserialize, Clone)]
54 pub struct CaptchaConfig {
55   pub enabled: bool,
56   pub difficulty: String, // easy, medium, or hard
57 }
58
59 #[derive(Debug, Deserialize, Clone)]
60 pub struct DatabaseConfig {
61   pub user: String,
62   pub password: String,
63   pub host: String,
64   pub port: i32,
65   pub database: String,
66   pub pool_size: u32,
67 }
68
69 #[derive(Debug, Deserialize, Clone)]
70 pub struct FederationConfig {
71   pub enabled: bool,
72   pub tls_enabled: bool,
73   pub allowed_instances: String,
74   pub blocked_instances: String,
75 }
76
77 lazy_static! {
78   static ref SETTINGS: RwLock<Settings> = RwLock::new(match Settings::init() {
79     Ok(c) => c,
80     Err(e) => panic!("{}", e),
81   });
82 }
83
84 impl Settings {
85   /// Reads config from the files and environment.
86   /// First, defaults are loaded from CONFIG_FILE_DEFAULTS, then these values can be overwritten
87   /// from CONFIG_FILE (optional). Finally, values from the environment (with prefix LEMMY) are
88   /// added to the config.
89   ///
90   /// Note: The env var `LEMMY_DATABASE_URL` is parsed in
91   /// `server/lemmy_db/src/lib.rs::get_database_url_from_env()`
92   fn init() -> Result<Self, ConfigError> {
93     let mut s = Config::new();
94
95     s.merge(File::with_name(&Self::get_config_defaults_location()))?;
96
97     s.merge(File::with_name(CONFIG_FILE).required(false))?;
98
99     // Add in settings from the environment (with a prefix of LEMMY)
100     // Eg.. `LEMMY_DEBUG=1 ./target/app` would set the `debug` key
101     // Note: we need to use double underscore here, because otherwise variables containing
102     //       underscore cant be set from environmnet.
103     // https://github.com/mehcode/config-rs/issues/73
104     s.merge(Environment::with_prefix("LEMMY").separator("__"))?;
105
106     s.try_into()
107   }
108
109   /// Returns the config as a struct.
110   pub fn get() -> Self {
111     SETTINGS.read().unwrap().to_owned()
112   }
113
114   pub fn get_database_url(&self) -> String {
115     format!(
116       "postgres://{}:{}@{}:{}/{}",
117       self.database.user,
118       self.database.password,
119       self.database.host,
120       self.database.port,
121       self.database.database
122     )
123   }
124
125   pub fn get_config_defaults_location() -> String {
126     env::var("LEMMY_CONFIG_LOCATION").unwrap_or_else(|_| CONFIG_FILE_DEFAULTS.to_string())
127   }
128
129   pub fn read_config_file() -> Result<String, Error> {
130     fs::read_to_string(CONFIG_FILE)
131   }
132
133   pub fn get_allowed_instances(&self) -> Vec<String> {
134     let mut allowed_instances: Vec<String> = self
135       .federation
136       .allowed_instances
137       .split(',')
138       .map(|d| d.to_string())
139       .collect();
140
141     // The defaults.hjson config always returns a [""]
142     allowed_instances.retain(|d| !d.eq(""));
143
144     allowed_instances
145   }
146
147   pub fn get_blocked_instances(&self) -> Vec<String> {
148     let mut blocked_instances: Vec<String> = self
149       .federation
150       .blocked_instances
151       .split(',')
152       .map(|d| d.to_string())
153       .collect();
154
155     // The defaults.hjson config always returns a [""]
156     blocked_instances.retain(|d| !d.eq(""));
157
158     blocked_instances
159   }
160
161   pub fn save_config_file(data: &str) -> Result<String, Error> {
162     fs::write(CONFIG_FILE, data)?;
163
164     // Reload the new settings
165     // From https://stackoverflow.com/questions/29654927/how-do-i-assign-a-string-to-a-mutable-static-variable/47181804#47181804
166     let mut new_settings = SETTINGS.write().unwrap();
167     *new_settings = match Settings::init() {
168       Ok(c) => c,
169       Err(e) => panic!("{}", e),
170     };
171
172     Self::read_config_file()
173   }
174 }