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