]> Untitled Git - lemmy.git/blob - server/src/settings.rs
Remove federation option from master. (#745)
[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 }
24
25 #[derive(Debug, Deserialize, Clone)]
26 pub struct Setup {
27   pub admin_username: String,
28   pub admin_password: String,
29   pub admin_email: Option<String>,
30   pub site_name: String,
31 }
32
33 #[derive(Debug, Deserialize, Clone)]
34 pub struct RateLimitConfig {
35   pub message: i32,
36   pub message_per_second: i32,
37   pub post: i32,
38   pub post_per_second: i32,
39   pub register: i32,
40   pub register_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 Database {
54   pub user: String,
55   pub password: String,
56   pub host: String,
57   pub port: i32,
58   pub database: String,
59   pub pool_size: u32,
60 }
61
62 lazy_static! {
63   static ref SETTINGS: RwLock<Settings> = RwLock::new(match Settings::init() {
64     Ok(c) => c,
65     Err(e) => panic!("{}", e),
66   });
67 }
68
69 impl Settings {
70   /// Reads config from the files and environment.
71   /// First, defaults are loaded from CONFIG_FILE_DEFAULTS, then these values can be overwritten
72   /// from CONFIG_FILE (optional). Finally, values from the environment (with prefix LEMMY) are
73   /// added to the config.
74   fn init() -> Result<Self, ConfigError> {
75     let mut s = Config::new();
76
77     s.merge(File::with_name(CONFIG_FILE_DEFAULTS))?;
78
79     s.merge(File::with_name(CONFIG_FILE).required(false))?;
80
81     // Add in settings from the environment (with a prefix of LEMMY)
82     // Eg.. `LEMMY_DEBUG=1 ./target/app` would set the `debug` key
83     // Note: we need to use double underscore here, because otherwise variables containing
84     //       underscore cant be set from environmnet.
85     // https://github.com/mehcode/config-rs/issues/73
86     s.merge(Environment::with_prefix("LEMMY").separator("__"))?;
87
88     s.try_into()
89   }
90
91   /// Returns the config as a struct.
92   pub fn get() -> Self {
93     SETTINGS.read().unwrap().to_owned()
94   }
95
96   /// Returns the postgres connection url. If LEMMY_DATABASE_URL is set, that is used,
97   /// otherwise the connection url is generated from the config.
98   pub fn get_database_url(&self) -> String {
99     match env::var("LEMMY_DATABASE_URL") {
100       Ok(url) => url,
101       Err(_) => format!(
102         "postgres://{}:{}@{}:{}/{}",
103         self.database.user,
104         self.database.password,
105         self.database.host,
106         self.database.port,
107         self.database.database
108       ),
109     }
110   }
111
112   pub fn api_endpoint(&self) -> String {
113     format!("{}/api/v1", self.hostname)
114   }
115
116   pub fn read_config_file() -> Result<String, Error> {
117     Ok(fs::read_to_string(CONFIG_FILE)?)
118   }
119
120   pub fn save_config_file(data: &str) -> Result<String, Error> {
121     fs::write(CONFIG_FILE, data)?;
122
123     // Reload the new settings
124     // From https://stackoverflow.com/questions/29654927/how-do-i-assign-a-string-to-a-mutable-static-variable/47181804#47181804
125     let mut new_settings = SETTINGS.write().unwrap();
126     *new_settings = match Settings::init() {
127       Ok(c) => c,
128       Err(e) => panic!("{}", e),
129     };
130
131     Self::read_config_file()
132   }
133 }