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