]> Untitled Git - lemmy.git/blob - crates/utils/src/settings/mod.rs
b247bae93697ce9cdc76e66c441f8473b40f0f77
[lemmy.git] / crates / utils / src / settings / mod.rs
1 use crate::{
2   location_info,
3   settings::structs::{
4     CaptchaConfig,
5     DatabaseConfig,
6     EmailConfig,
7     FederationConfig,
8     RateLimitConfig,
9     Settings,
10     SetupConfig,
11   },
12   LemmyError,
13 };
14 use anyhow::{anyhow, Context};
15 use deser_hjson::from_str;
16 use merge::Merge;
17 use std::{env, fs, io::Error, net::IpAddr, sync::RwLock};
18
19 pub mod defaults;
20 pub mod structs;
21
22 static CONFIG_FILE: &str = "config/config.hjson";
23
24 lazy_static! {
25   static ref SETTINGS: RwLock<Settings> =
26     RwLock::new(Settings::init().expect("Failed to load settings file"));
27 }
28
29 impl Settings {
30   /// Reads config from configuration file.
31   /// Then values from the environment (with prefix LEMMY) are added to the config.
32   /// And then default values are merged into config.
33   /// Defaults are controlled by Default trait implemntation for Settings structs.
34   ///
35   /// Note: The env var `LEMMY_DATABASE_URL` is parsed in
36   /// `lemmy_db_queries/src/lib.rs::get_database_url_from_env()`
37   fn init() -> Result<Self, LemmyError> {
38     // Read the config file
39     let mut custom_config = from_str::<Settings>(&Self::read_config_file()?)?;
40
41     // Merge with env vars
42     custom_config.merge(envy::prefixed("LEMMY_").from_env::<Settings>()?);
43
44     // Merge with default
45     custom_config.merge(Settings::default());
46
47     if custom_config.hostname == Settings::default().hostname {
48       return Err(anyhow!("Hostname variable is not set!").into());
49     }
50
51     Ok(custom_config)
52   }
53
54   /// Returns the config as a struct.
55   pub fn get() -> Self {
56     SETTINGS.read().expect("read config").to_owned()
57   }
58
59   pub fn get_database_url(&self) -> String {
60     let conf = self.database();
61     format!(
62       "postgres://{}:{}@{}:{}/{}",
63       conf.user(),
64       conf.password,
65       conf.host,
66       conf.port(),
67       conf.database(),
68     )
69   }
70
71   pub fn get_config_location() -> String {
72     env::var("LEMMY_CONFIG_LOCATION").unwrap_or_else(|_| CONFIG_FILE.to_string())
73   }
74
75   pub fn read_config_file() -> Result<String, Error> {
76     fs::read_to_string(Self::get_config_location())
77   }
78
79   pub fn get_allowed_instances(&self) -> Option<Vec<String>> {
80     self.federation().allowed_instances
81   }
82
83   pub fn get_blocked_instances(&self) -> Option<Vec<String>> {
84     self.federation().blocked_instances
85   }
86
87   /// Returns either "http" or "https", depending on tls_enabled setting
88   pub fn get_protocol_string(&self) -> &'static str {
89     if let Some(tls_enabled) = self.tls_enabled {
90       if tls_enabled {
91         "https"
92       } else {
93         "http"
94       }
95     } else {
96       "http"
97     }
98   }
99
100   /// Returns something like `http://localhost` or `https://lemmy.ml`,
101   /// with the correct protocol and hostname.
102   pub fn get_protocol_and_hostname(&self) -> String {
103     format!("{}://{}", self.get_protocol_string(), self.hostname())
104   }
105
106   /// When running the federation test setup in `api_tests/` or `docker/federation`, the `hostname`
107   /// variable will be like `lemmy-alpha:8541`. This method removes the port and returns
108   /// `lemmy-alpha` instead. It has no effect in production.
109   pub fn get_hostname_without_port(&self) -> Result<String, anyhow::Error> {
110     Ok(
111       self
112         .hostname()
113         .split(':')
114         .collect::<Vec<&str>>()
115         .first()
116         .context(location_info!())?
117         .to_string(),
118     )
119   }
120
121   pub fn save_config_file(data: &str) -> Result<String, LemmyError> {
122     fs::write(CONFIG_FILE, data)?;
123
124     // Reload the new settings
125     // From https://stackoverflow.com/questions/29654927/how-do-i-assign-a-string-to-a-mutable-static-variable/47181804#47181804
126     let mut new_settings = SETTINGS.write().expect("write config");
127     *new_settings = match Settings::init() {
128       Ok(c) => c,
129       Err(e) => panic!("{}", e),
130     };
131
132     Ok(Self::read_config_file()?)
133   }
134
135   pub fn hostname(&self) -> String {
136     self.hostname.to_owned().expect("No hostname given")
137   }
138   pub fn bind(&self) -> IpAddr {
139     self.bind.expect("return bind address")
140   }
141   pub fn port(&self) -> u16 {
142     self
143       .port
144       .unwrap_or_else(|| Settings::default().port.expect("missing port"))
145   }
146   pub fn tls_enabled(&self) -> bool {
147     self.tls_enabled.unwrap_or_else(|| {
148       Settings::default()
149         .tls_enabled
150         .expect("missing tls_enabled")
151     })
152   }
153   pub fn jwt_secret(&self) -> String {
154     self
155       .jwt_secret
156       .to_owned()
157       .unwrap_or_else(|| Settings::default().jwt_secret.expect("missing jwt_secret"))
158   }
159   pub fn pictrs_url(&self) -> String {
160     self
161       .pictrs_url
162       .to_owned()
163       .unwrap_or_else(|| Settings::default().pictrs_url.expect("missing pictrs_url"))
164   }
165   pub fn iframely_url(&self) -> String {
166     self.iframely_url.to_owned().unwrap_or_else(|| {
167       Settings::default()
168         .iframely_url
169         .expect("missing iframely_url")
170     })
171   }
172   pub fn actor_name_max_length(&self) -> usize {
173     self.actor_name_max_length.unwrap_or_else(|| {
174       Settings::default()
175         .actor_name_max_length
176         .expect("missing actor name length")
177     })
178   }
179   pub fn database(&self) -> DatabaseConfig {
180     self.database.to_owned().unwrap_or_default()
181   }
182   pub fn rate_limit(&self) -> RateLimitConfig {
183     self.rate_limit.to_owned().unwrap_or_default()
184   }
185   pub fn federation(&self) -> FederationConfig {
186     self.federation.to_owned().unwrap_or_default()
187   }
188   pub fn captcha(&self) -> CaptchaConfig {
189     self.captcha.to_owned().unwrap_or_default()
190   }
191   pub fn email(&self) -> Option<EmailConfig> {
192     self.email.to_owned()
193   }
194   pub fn setup(&self) -> Option<SetupConfig> {
195     self.setup.to_owned()
196   }
197 }