]> Untitled Git - lemmy.git/blob - server/lemmy_utils/src/settings.rs
b7cc2c45f5ecdb26443d10a1477eeea542bfd704
[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: Database,
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 rate_limit: RateLimitConfig,
18   pub email: Option<EmailConfig>,
19   pub federation: Federation,
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 }
40
41 #[derive(Debug, Deserialize, Clone)]
42 pub struct EmailConfig {
43   pub smtp_server: String,
44   pub smtp_login: Option<String>,
45   pub smtp_password: Option<String>,
46   pub smtp_from_address: String,
47   pub use_tls: bool,
48 }
49
50 #[derive(Debug, Deserialize, Clone)]
51 pub struct CaptchaConfig {
52   pub enabled: bool,
53   pub difficulty: String, // easy, medium, or hard
54 }
55
56 #[derive(Debug, Deserialize, Clone)]
57 pub struct Database {
58   pub user: String,
59   pub password: String,
60   pub host: String,
61   pub port: i32,
62   pub database: String,
63   pub pool_size: u32,
64 }
65
66 #[derive(Debug, Deserialize, Clone)]
67 pub struct Federation {
68   pub enabled: bool,
69   pub tls_enabled: bool,
70   pub allowed_instances: String,
71 }
72
73 lazy_static! {
74   static ref SETTINGS: RwLock<Settings> = RwLock::new(match Settings::init() {
75     Ok(c) => c,
76     Err(e) => panic!("{}", e),
77   });
78 }
79
80 impl Settings {
81   /// Reads config from the files and environment.
82   /// First, defaults are loaded from CONFIG_FILE_DEFAULTS, then these values can be overwritten
83   /// from CONFIG_FILE (optional). Finally, values from the environment (with prefix LEMMY) are
84   /// added to the config.
85   ///
86   /// Note: The env var `LEMMY_DATABASE_URL` is parsed in
87   /// `server/lemmy_db/src/lib.rs::get_database_url_from_env()`
88   fn init() -> Result<Self, ConfigError> {
89     let mut s = Config::new();
90
91     s.merge(File::with_name(&Self::get_config_defaults_location()))?;
92
93     s.merge(File::with_name(CONFIG_FILE).required(false))?;
94
95     // Add in settings from the environment (with a prefix of LEMMY)
96     // Eg.. `LEMMY_DEBUG=1 ./target/app` would set the `debug` key
97     // Note: we need to use double underscore here, because otherwise variables containing
98     //       underscore cant be set from environmnet.
99     // https://github.com/mehcode/config-rs/issues/73
100     s.merge(Environment::with_prefix("LEMMY").separator("__"))?;
101
102     s.try_into()
103   }
104
105   /// Returns the config as a struct.
106   pub fn get() -> Self {
107     SETTINGS.read().unwrap().to_owned()
108   }
109
110   pub fn get_database_url(&self) -> String {
111     format!(
112       "postgres://{}:{}@{}:{}/{}",
113       self.database.user,
114       self.database.password,
115       self.database.host,
116       self.database.port,
117       self.database.database
118     )
119   }
120
121   pub fn api_endpoint(&self) -> String {
122     format!("{}/api/v1", self.hostname)
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 save_config_file(data: &str) -> Result<String, Error> {
134     fs::write(CONFIG_FILE, data)?;
135
136     // Reload the new settings
137     // From https://stackoverflow.com/questions/29654927/how-do-i-assign-a-string-to-a-mutable-static-variable/47181804#47181804
138     let mut new_settings = SETTINGS.write().unwrap();
139     *new_settings = match Settings::init() {
140       Ok(c) => c,
141       Err(e) => panic!("{}", e),
142     };
143
144     Self::read_config_file()
145   }
146 }