]> Untitled Git - lemmy.git/blob - crates/utils/src/settings/mod.rs
Merge pull request #1938 from LemmyNet/once_cell
[lemmy.git] / crates / utils / src / settings / mod.rs
1 use crate::{location_info, settings::structs::Settings, LemmyError};
2 use anyhow::{anyhow, Context};
3 use deser_hjson::from_str;
4 use once_cell::sync::Lazy;
5 use regex::{Regex, RegexBuilder};
6 use std::{env, fs, io::Error, sync::RwLock};
7
8 pub mod structs;
9
10 static DEFAULT_CONFIG_FILE: &str = "config/config.hjson";
11
12 static SETTINGS: Lazy<RwLock<Settings>> =
13   Lazy::new(|| RwLock::new(Settings::init().expect("Failed to load settings file")));
14 static WEBFINGER_REGEX: Lazy<Regex> = Lazy::new(|| {
15   Regex::new(&format!(
16     "^acct:([a-z0-9_]{{3,}})@{}$",
17     Settings::get().hostname
18   ))
19   .expect("compile webfinger regex")
20 });
21
22 impl Settings {
23   /// Reads config from configuration file.
24   ///
25   /// Note: The env var `LEMMY_DATABASE_URL` is parsed in
26   /// `lemmy_db_schema/src/lib.rs::get_database_url_from_env()`
27   /// Warning: Only call this once.
28   pub fn init() -> Result<Self, LemmyError> {
29     // Read the config file
30     let config = from_str::<Settings>(&Self::read_config_file()?)?;
31
32     if config.hostname == "unset" {
33       return Err(anyhow!("Hostname variable is not set!").into());
34     }
35
36     Ok(config)
37   }
38
39   /// Returns the config as a struct.
40   pub fn get() -> Self {
41     SETTINGS.read().expect("read config").to_owned()
42   }
43
44   pub fn get_database_url(&self) -> String {
45     let conf = &self.database;
46     format!(
47       "postgres://{}:{}@{}:{}/{}",
48       conf.user, conf.password, conf.host, conf.port, conf.database,
49     )
50   }
51
52   pub fn get_config_location() -> String {
53     env::var("LEMMY_CONFIG_LOCATION").unwrap_or_else(|_| DEFAULT_CONFIG_FILE.to_string())
54   }
55
56   pub fn read_config_file() -> Result<String, Error> {
57     fs::read_to_string(Self::get_config_location())
58   }
59
60   /// Returns either "http" or "https", depending on tls_enabled setting
61   pub fn get_protocol_string(&self) -> &'static str {
62     if self.tls_enabled {
63       "https"
64     } else {
65       "http"
66     }
67   }
68
69   /// Returns something like `http://localhost` or `https://lemmy.ml`,
70   /// with the correct protocol and hostname.
71   pub fn get_protocol_and_hostname(&self) -> String {
72     format!("{}://{}", self.get_protocol_string(), self.hostname)
73   }
74
75   /// When running the federation test setup in `api_tests/` or `docker/federation`, the `hostname`
76   /// variable will be like `lemmy-alpha:8541`. This method removes the port and returns
77   /// `lemmy-alpha` instead. It has no effect in production.
78   pub fn get_hostname_without_port(&self) -> Result<String, anyhow::Error> {
79     Ok(
80       self
81         .hostname
82         .split(':')
83         .collect::<Vec<&str>>()
84         .first()
85         .context(location_info!())?
86         .to_string(),
87     )
88   }
89
90   pub fn save_config_file(data: &str) -> Result<String, LemmyError> {
91     fs::write(Settings::get_config_location(), data)?;
92
93     // Reload the new settings
94     // From https://stackoverflow.com/questions/29654927/how-do-i-assign-a-string-to-a-mutable-static-variable/47181804#47181804
95     let mut new_settings = SETTINGS.write().expect("write config");
96     *new_settings = match Settings::init() {
97       Ok(c) => c,
98       Err(e) => panic!("{}", e),
99     };
100
101     Ok(Self::read_config_file()?)
102   }
103
104   pub fn webfinger_regex(&self) -> Regex {
105     WEBFINGER_REGEX.to_owned()
106   }
107
108   pub fn slur_regex(&self) -> Option<Regex> {
109     self.slur_filter.as_ref().map(|slurs| {
110       RegexBuilder::new(slurs)
111         .case_insensitive(true)
112         .build()
113         .expect("compile regex")
114     })
115   }
116 }