]> Untitled Git - lemmy.git/blob - crates/utils/src/settings/mod.rs
Moving settings to Database. (#2492)
[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;
10 use std::{env, fs, io::Error};
11
12 pub mod structs;
13
14 static DEFAULT_CONFIG_FILE: &str = "config/config.hjson";
15
16 pub static SETTINGS: Lazy<Settings> =
17   Lazy::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.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(crate) 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   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 webfinger_regex(&self) -> Regex {
90     WEBFINGER_REGEX.to_owned()
91   }
92
93   pub fn pictrs_config(&self) -> Result<PictrsConfig, LemmyError> {
94     self
95       .pictrs
96       .to_owned()
97       .ok_or_else(|| anyhow!("images_disabled").into())
98   }
99 }