]> Untitled Git - lemmy.git/blob - crates/utils/src/settings/mod.rs
Rewrite fetcher (#1792)
[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 std::{env, fs, io::Error, sync::RwLock};
5
6 pub mod structs;
7
8 static CONFIG_FILE: &str = "config/config.hjson";
9
10 lazy_static! {
11   static ref SETTINGS: RwLock<Settings> =
12     RwLock::new(Settings::init().expect("Failed to load settings file"));
13 }
14
15 impl Settings {
16   /// Reads config from configuration file.
17   ///
18   /// Note: The env var `LEMMY_DATABASE_URL` is parsed in
19   /// `lemmy_db_queries/src/lib.rs::get_database_url_from_env()`
20   fn init() -> Result<Self, LemmyError> {
21     // Read the config file
22     let config = from_str::<Settings>(&Self::read_config_file()?)?;
23
24     if config.hostname == "unset" {
25       return Err(anyhow!("Hostname variable is not set!").into());
26     }
27
28     Ok(config)
29   }
30
31   /// Returns the config as a struct.
32   pub fn get() -> Self {
33     SETTINGS.read().expect("read config").to_owned()
34   }
35
36   pub fn get_database_url(&self) -> String {
37     let conf = &self.database;
38     format!(
39       "postgres://{}:{}@{}:{}/{}",
40       conf.user, conf.password, conf.host, conf.port, conf.database,
41     )
42   }
43
44   pub fn get_config_location() -> String {
45     env::var("LEMMY_CONFIG_LOCATION").unwrap_or_else(|_| CONFIG_FILE.to_string())
46   }
47
48   pub fn read_config_file() -> Result<String, Error> {
49     fs::read_to_string(Self::get_config_location())
50   }
51
52   /// Returns either "http" or "https", depending on tls_enabled setting
53   pub fn get_protocol_string(&self) -> &'static str {
54     if self.tls_enabled {
55       "https"
56     } else {
57       "http"
58     }
59   }
60
61   /// Returns something like `http://localhost` or `https://lemmy.ml`,
62   /// with the correct protocol and hostname.
63   pub fn get_protocol_and_hostname(&self) -> String {
64     format!("{}://{}", self.get_protocol_string(), self.hostname)
65   }
66
67   /// When running the federation test setup in `api_tests/` or `docker/federation`, the `hostname`
68   /// variable will be like `lemmy-alpha:8541`. This method removes the port and returns
69   /// `lemmy-alpha` instead. It has no effect in production.
70   pub fn get_hostname_without_port(&self) -> Result<String, anyhow::Error> {
71     Ok(
72       self
73         .hostname
74         .split(':')
75         .collect::<Vec<&str>>()
76         .first()
77         .context(location_info!())?
78         .to_string(),
79     )
80   }
81
82   pub fn save_config_file(data: &str) -> Result<String, LemmyError> {
83     fs::write(CONFIG_FILE, data)?;
84
85     // Reload the new settings
86     // From https://stackoverflow.com/questions/29654927/how-do-i-assign-a-string-to-a-mutable-static-variable/47181804#47181804
87     let mut new_settings = SETTINGS.write().expect("write config");
88     *new_settings = match Settings::init() {
89       Ok(c) => c,
90       Err(e) => panic!("{}", e),
91     };
92
93     Ok(Self::read_config_file()?)
94   }
95 }