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