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