4 settings::structs::{PictrsConfig, Settings},
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};
14 static DEFAULT_CONFIG_FILE: &str = "config/config.hjson";
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(|| {
20 "^acct:([a-zA-Z0-9_]{{3,}})@{}$",
23 .expect("compile webfinger regex")
27 /// Reads config from configuration file.
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()?)?;
36 if config.hostname == "unset" {
37 return Err(anyhow!("Hostname variable is not set!").into());
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 webfinger_regex(&self) -> Regex {
90 WEBFINGER_REGEX.to_owned()
93 pub fn slur_regex(&self) -> Option<Regex> {
94 self.slur_filter.as_ref().map(|slurs| {
95 RegexBuilder::new(slurs)
96 .case_insensitive(true)
98 .expect("compile regex")
102 pub fn pictrs_config(&self) -> Result<PictrsConfig, LemmyError> {
106 .ok_or_else(|| anyhow!("images_disabled").into())