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