1 use config::{Config, ConfigError, Environment, File};
3 use serde::Deserialize;
8 static CONFIG_FILE_DEFAULTS: &str = "config/defaults.hjson";
9 static CONFIG_FILE: &str = "config/config.hjson";
11 #[derive(Debug, Deserialize)]
13 pub setup: Option<Setup>,
14 pub database: Database,
18 pub jwt_secret: String,
19 pub front_end_dir: String,
20 pub rate_limit: RateLimitConfig,
21 pub email: Option<EmailConfig>,
22 pub federation_enabled: bool,
25 #[derive(Debug, Deserialize)]
27 pub admin_username: String,
28 pub admin_password: String,
29 pub admin_email: Option<String>,
30 pub site_name: String,
33 #[derive(Debug, Deserialize)]
34 pub struct RateLimitConfig {
36 pub message_per_second: i32,
38 pub post_per_second: i32,
40 pub register_per_second: i32,
43 #[derive(Debug, Deserialize)]
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,
52 #[derive(Debug, Deserialize)]
63 static ref SETTINGS: Settings = {
64 match Settings::init() {
66 Err(e) => panic!("{}", e),
72 /// Reads config from the files and environment.
73 /// First, defaults are loaded from CONFIG_FILE_DEFAULTS, then these values can be overwritten
74 /// from CONFIG_FILE (optional). Finally, values from the environment (with prefix LEMMY) are
75 /// added to the config.
76 fn init() -> Result<Self, ConfigError> {
77 let mut s = Config::new();
79 s.merge(File::with_name(CONFIG_FILE_DEFAULTS))?;
81 s.merge(File::with_name(CONFIG_FILE).required(false))?;
83 // Add in settings from the environment (with a prefix of LEMMY)
84 // Eg.. `LEMMY_DEBUG=1 ./target/app` would set the `debug` key
85 // Note: we need to use double underscore here, because otherwise variables containing
86 // underscore cant be set from environmnet.
87 // https://github.com/mehcode/config-rs/issues/73
88 s.merge(Environment::with_prefix("LEMMY").separator("__"))?;
93 /// Returns the config as a struct.
94 pub fn get() -> &'static Self {
98 /// Returns the postgres connection url. If LEMMY_DATABASE_URL is set, that is used,
99 /// otherwise the connection url is generated from the config.
100 pub fn get_database_url(&self) -> String {
101 match env::var("LEMMY_DATABASE_URL") {
104 "postgres://{}:{}@{}:{}/{}",
106 self.database.password,
109 self.database.database
114 pub fn api_endpoint(&self) -> String {
115 format!("{}/api/v1", self.hostname)
118 pub fn read_config_file() -> Result<String, Error> {
119 Ok(fs::read_to_string(CONFIG_FILE)?)
122 pub fn save_config_file(data: &str) -> Result<String, Error> {
123 fs::write(CONFIG_FILE, data)?;
125 Self::read_config_file()