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};
9 static DEFAULT_CONFIG_FILE: &str = "config/config.hjson";
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
18 .expect("compile webfinger regex");
22 /// Reads config from configuration file.
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()?)?;
31 if config.hostname == "unset" {
32 return Err(anyhow!("Hostname variable is not set!").into());
38 /// Returns the config as a struct.
39 pub fn get() -> Self {
40 SETTINGS.read().expect("read config").to_owned()
43 pub fn get_database_url(&self) -> String {
44 let conf = &self.database;
46 "postgres://{}:{}@{}:{}/{}",
47 conf.user, conf.password, conf.host, conf.port, conf.database,
51 pub fn get_config_location() -> String {
52 env::var("LEMMY_CONFIG_LOCATION").unwrap_or_else(|_| DEFAULT_CONFIG_FILE.to_string())
55 pub fn read_config_file() -> Result<String, Error> {
56 fs::read_to_string(Self::get_config_location())
59 /// Returns either "http" or "https", depending on tls_enabled setting
60 pub fn get_protocol_string(&self) -> &'static str {
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)
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> {
82 .collect::<Vec<&str>>()
84 .context(location_info!())?
89 pub fn save_config_file(data: &str) -> Result<String, LemmyError> {
90 fs::write(Settings::get_config_location(), data)?;
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() {
97 Err(e) => panic!("{}", e),
100 Ok(Self::read_config_file()?)
103 pub fn webfinger_regex(&self) -> Regex {
104 WEBFINGER_REGEX.to_owned()
107 pub fn slur_regex(&self) -> Option<Regex> {
108 self.slur_filter.as_ref().map(|slurs| {
109 RegexBuilder::new(slurs)
110 .case_insensitive(true)
112 .expect("compile regex")