]> Untitled Git - lemmy.git/blob - crates/utils/src/settings/mod.rs
Adding admin purging of DB items and pictures. #904 #1331 (#1809)
[lemmy.git] / crates / utils / src / settings / mod.rs
1 use crate::{
2   error::LemmyError,
3   location_info,
4   settings::structs::{PictrsConfig, Settings},
5 };
6 use anyhow::{anyhow, Context};
7 use deser_hjson::from_str;
8 use once_cell::sync::Lazy;
9 use regex::{Regex, RegexBuilder};
10 use std::{env, fs, io::Error, sync::RwLock};
11
12 pub mod structs;
13
14 static DEFAULT_CONFIG_FILE: &str = "config/config.hjson";
15
16 static SETTINGS: Lazy<RwLock<Settings>> =
17   Lazy::new(|| RwLock::new(Settings::init().expect("Failed to load settings file")));
18 static WEBFINGER_REGEX: Lazy<Regex> = Lazy::new(|| {
19   Regex::new(&format!(
20     "^acct:([a-zA-Z0-9_]{{3,}})@{}$",
21     Settings::get().hostname
22   ))
23   .expect("compile webfinger regex")
24 });
25
26 impl Settings {
27   /// Reads config from configuration file.
28   ///
29   /// Note: The env var `LEMMY_DATABASE_URL` is parsed in
30   /// `lemmy_db_schema/src/lib.rs::get_database_url_from_env()`
31   /// Warning: Only call this once.
32   pub fn init() -> Result<Self, LemmyError> {
33     // Read the config file
34     let config = from_str::<Settings>(&Self::read_config_file()?)?;
35
36     if config.hostname == "unset" {
37       return Err(anyhow!("Hostname variable is not set!").into());
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(|_| DEFAULT_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     // check that the config is valid
96     from_str::<Settings>(data)?;
97
98     fs::write(Settings::get_config_location(), data)?;
99
100     // Reload the new settings
101     // From https://stackoverflow.com/questions/29654927/how-do-i-assign-a-string-to-a-mutable-static-variable/47181804#47181804
102     let mut new_settings = SETTINGS.write().expect("write config");
103     *new_settings = match Settings::init() {
104       Ok(c) => c,
105       Err(e) => panic!("{}", e),
106     };
107
108     Ok(Self::read_config_file()?)
109   }
110
111   pub fn webfinger_regex(&self) -> Regex {
112     WEBFINGER_REGEX.to_owned()
113   }
114
115   pub fn slur_regex(&self) -> Option<Regex> {
116     self.slur_filter.as_ref().map(|slurs| {
117       RegexBuilder::new(slurs)
118         .case_insensitive(true)
119         .build()
120         .expect("compile regex")
121     })
122   }
123
124   pub fn pictrs_config(&self) -> Result<PictrsConfig, LemmyError> {
125     self
126       .pictrs_config
127       .to_owned()
128       .ok_or_else(|| anyhow!("images_disabled").into())
129   }
130 }