]> Untitled Git - lemmy.git/blob - crates/utils/src/settings/mod.rs
Moving settings and secrets to context.
[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 regex::{Regex, RegexBuilder};
5 use std::{env, fs, io::Error, sync::RwLock};
6
7 pub mod structs;
8
9 static CONFIG_FILE: &str = "config/config.hjson";
10
11 lazy_static! {
12   static ref SETTINGS: RwLock<Settings> =
13     RwLock::new(Settings::init().expect("Failed to load settings file"));
14 }
15
16 impl Settings {
17   /// Reads config from configuration file.
18   ///
19   /// Note: The env var `LEMMY_DATABASE_URL` is parsed in
20   /// `lemmy_db_queries/src/lib.rs::get_database_url_from_env()`
21   /// Warning: Only call this once.
22   pub fn init() -> Result<Self, LemmyError> {
23     // Read the config file
24     let mut config = from_str::<Settings>(&Self::read_config_file()?)?;
25
26     if config.hostname == "unset" {
27       return Err(anyhow!("Hostname variable is not set!").into());
28     }
29
30     // Initialize the regexes
31     config.webfinger_community_regex = Some(
32       Regex::new(&format!("^group:([a-z0-9_]{{3,}})@{}$", config.hostname))
33         .expect("compile webfinger regex"),
34     );
35     config.webfinger_username_regex = Some(
36       Regex::new(&format!("^acct:([a-z0-9_]{{3,}})@{}$", config.hostname))
37         .expect("compile webfinger regex"),
38     );
39
40     Ok(config)
41   }
42
43   /// Returns the config as a struct.
44   pub fn get() -> Self {
45     SETTINGS.read().expect("read config").to_owned()
46   }
47
48   pub fn get_database_url(&self) -> String {
49     let conf = &self.database;
50     format!(
51       "postgres://{}:{}@{}:{}/{}",
52       conf.user, conf.password, conf.host, conf.port, conf.database,
53     )
54   }
55
56   pub fn get_config_location() -> String {
57     env::var("LEMMY_CONFIG_LOCATION").unwrap_or_else(|_| CONFIG_FILE.to_string())
58   }
59
60   pub fn read_config_file() -> Result<String, Error> {
61     fs::read_to_string(Self::get_config_location())
62   }
63
64   /// Returns either "http" or "https", depending on tls_enabled setting
65   pub fn get_protocol_string(&self) -> &'static str {
66     if self.tls_enabled {
67       "https"
68     } else {
69       "http"
70     }
71   }
72
73   /// Returns something like `http://localhost` or `https://lemmy.ml`,
74   /// with the correct protocol and hostname.
75   pub fn get_protocol_and_hostname(&self) -> String {
76     format!("{}://{}", self.get_protocol_string(), self.hostname)
77   }
78
79   /// When running the federation test setup in `api_tests/` or `docker/federation`, the `hostname`
80   /// variable will be like `lemmy-alpha:8541`. This method removes the port and returns
81   /// `lemmy-alpha` instead. It has no effect in production.
82   pub fn get_hostname_without_port(&self) -> Result<String, anyhow::Error> {
83     Ok(
84       self
85         .hostname
86         .split(':')
87         .collect::<Vec<&str>>()
88         .first()
89         .context(location_info!())?
90         .to_string(),
91     )
92   }
93
94   pub fn save_config_file(data: &str) -> Result<String, LemmyError> {
95     fs::write(CONFIG_FILE, data)?;
96
97     // Reload the new settings
98     // From https://stackoverflow.com/questions/29654927/how-do-i-assign-a-string-to-a-mutable-static-variable/47181804#47181804
99     let mut new_settings = SETTINGS.write().expect("write config");
100     *new_settings = match Settings::init() {
101       Ok(c) => c,
102       Err(e) => panic!("{}", e),
103     };
104
105     Ok(Self::read_config_file()?)
106   }
107
108   pub fn webfinger_community_regex(&self) -> Regex {
109     self
110       .webfinger_community_regex
111       .to_owned()
112       .expect("compile webfinger regex")
113   }
114
115   pub fn webfinger_username_regex(&self) -> Regex {
116     self
117       .webfinger_username_regex
118       .to_owned()
119       .expect("compile webfinger regex")
120   }
121
122   pub fn slur_regex(&self) -> Regex {
123     let mut slurs = r"(fag(g|got|tard)?\b|cock\s?sucker(s|ing)?|ni((g{2,}|q)+|[gq]{2,})[e3r]+(s|z)?|mudslime?s?|kikes?|\bspi(c|k)s?\b|\bchinks?|gooks?|bitch(es|ing|y)?|whor(es?|ing)|\btr(a|@)nn?(y|ies?)|\b(b|re|r)tard(ed)?s?)".to_string();
124     if let Some(additional_slurs) = &self.additional_slurs {
125       slurs.push('|');
126       slurs.push_str(additional_slurs);
127     };
128     RegexBuilder::new(&slurs)
129       .case_insensitive(true)
130       .build()
131       .expect("compile regex")
132   }
133 }