]> Untitled Git - lemmy.git/blob - server/src/settings.rs
Merge branch 'dev' into federation
[lemmy.git] / server / src / settings.rs
1 use config::{Config, ConfigError, Environment, File};
2 use failure::Error;
3 use serde::Deserialize;
4 use std::env;
5 use std::fs;
6 use std::net::IpAddr;
7 use std::sync::RwLock;
8
9 static CONFIG_FILE_DEFAULTS: &str = "config/defaults.hjson";
10 static CONFIG_FILE: &str = "config/config.hjson";
11
12 #[derive(Debug, Deserialize, Clone)]
13 pub struct Settings {
14   pub setup: Option<Setup>,
15   pub database: Database,
16   pub hostname: String,
17   pub bind: IpAddr,
18   pub port: u16,
19   pub jwt_secret: String,
20   pub front_end_dir: String,
21   pub rate_limit: RateLimitConfig,
22   pub email: Option<EmailConfig>,
23   pub federation: Federation,
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 }
43
44 #[derive(Debug, Deserialize, Clone)]
45 pub struct EmailConfig {
46   pub smtp_server: String,
47   pub smtp_login: Option<String>,
48   pub smtp_password: Option<String>,
49   pub smtp_from_address: String,
50   pub use_tls: bool,
51 }
52
53 #[derive(Debug, Deserialize, Clone)]
54 pub struct Database {
55   pub user: String,
56   pub password: String,
57   pub host: String,
58   pub port: i32,
59   pub database: String,
60   pub pool_size: u32,
61 }
62
63 #[derive(Debug, Deserialize)]
64 pub struct Federation {
65   pub enabled: bool,
66   pub followed_instances: String,
67   pub tls_enabled: bool,
68 }
69
70 lazy_static! {
71   static ref SETTINGS: RwLock<Settings> = RwLock::new(match Settings::init() {
72     Ok(c) => c,
73     Err(e) => panic!("{}", e),
74   });
75 }
76
77 impl Settings {
78   /// Reads config from the files and environment.
79   /// First, defaults are loaded from CONFIG_FILE_DEFAULTS, then these values can be overwritten
80   /// from CONFIG_FILE (optional). Finally, values from the environment (with prefix LEMMY) are
81   /// added to the config.
82   fn init() -> Result<Self, ConfigError> {
83     let mut s = Config::new();
84
85     s.merge(File::with_name(CONFIG_FILE_DEFAULTS))?;
86
87     s.merge(File::with_name(CONFIG_FILE).required(false))?;
88
89     // Add in settings from the environment (with a prefix of LEMMY)
90     // Eg.. `LEMMY_DEBUG=1 ./target/app` would set the `debug` key
91     // Note: we need to use double underscore here, because otherwise variables containing
92     //       underscore cant be set from environmnet.
93     // https://github.com/mehcode/config-rs/issues/73
94     s.merge(Environment::with_prefix("LEMMY").separator("__"))?;
95
96     s.try_into()
97   }
98
99   /// Returns the config as a struct.
100   pub fn get() -> Self {
101     SETTINGS.read().unwrap().to_owned()
102   }
103
104   /// Returns the postgres connection url. If LEMMY_DATABASE_URL is set, that is used,
105   /// otherwise the connection url is generated from the config.
106   pub fn get_database_url(&self) -> String {
107     match env::var("LEMMY_DATABASE_URL") {
108       Ok(url) => url,
109       Err(_) => format!(
110         "postgres://{}:{}@{}:{}/{}",
111         self.database.user,
112         self.database.password,
113         self.database.host,
114         self.database.port,
115         self.database.database
116       ),
117     }
118   }
119
120   pub fn api_endpoint(&self) -> String {
121     format!("{}/api/v1", self.hostname)
122   }
123
124   pub fn read_config_file() -> Result<String, Error> {
125     Ok(fs::read_to_string(CONFIG_FILE)?)
126   }
127
128   pub fn save_config_file(data: &str) -> Result<String, Error> {
129     fs::write(CONFIG_FILE, data)?;
130
131     // Reload the new settings
132     // From https://stackoverflow.com/questions/29654927/how-do-i-assign-a-string-to-a-mutable-static-variable/47181804#47181804
133     let mut new_settings = SETTINGS.write().unwrap();
134     *new_settings = match Settings::init() {
135       Ok(c) => c,
136       Err(e) => panic!("{}", e),
137     };
138
139     Self::read_config_file()
140   }
141 }