4 settings::structs::{PictrsConfig, Settings},
6 use anyhow::{anyhow, Context};
7 use deser_hjson::from_str;
8 use once_cell::sync::Lazy;
9 use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};
11 use std::{env, fs, io::Error};
15 use structs::DatabaseConnection;
17 static DEFAULT_CONFIG_FILE: &str = "config/config.hjson";
19 pub static SETTINGS: Lazy<Settings> = Lazy::new(|| {
20 Settings::init().expect("Failed to load settings file, see documentation (https://join-lemmy.org/docs/en/administration/configuration.html)")
22 static WEBFINGER_REGEX: Lazy<Regex> = Lazy::new(|| {
24 "^acct:([a-zA-Z0-9_]{{3,}})@{}$",
27 .expect("compile webfinger regex")
31 /// Reads config from configuration file.
33 /// Note: The env var `LEMMY_DATABASE_URL` is parsed in
34 /// `lemmy_db_schema/src/lib.rs::get_database_url_from_env()`
35 /// Warning: Only call this once.
36 pub(crate) fn init() -> Result<Self, LemmyError> {
37 // Read the config file
38 let config = from_str::<Settings>(&Self::read_config_file()?)?;
40 if config.hostname == "unset" {
41 return Err(anyhow!("Hostname variable is not set!").into());
47 pub fn get_database_url(&self) -> String {
48 match &self.database.connection {
49 DatabaseConnection::Uri { uri } => uri.clone(),
50 DatabaseConnection::Parts(parts) => {
52 "postgres://{}:{}@{}:{}/{}",
53 utf8_percent_encode(&parts.user, NON_ALPHANUMERIC),
54 utf8_percent_encode(&parts.password, NON_ALPHANUMERIC),
57 utf8_percent_encode(&parts.database, NON_ALPHANUMERIC),
63 fn get_config_location() -> String {
64 env::var("LEMMY_CONFIG_LOCATION").unwrap_or_else(|_| DEFAULT_CONFIG_FILE.to_string())
67 fn read_config_file() -> Result<String, Error> {
68 fs::read_to_string(Self::get_config_location())
71 /// Returns either "http" or "https", depending on tls_enabled setting
72 pub fn get_protocol_string(&self) -> &'static str {
80 /// Returns something like `http://localhost` or `https://lemmy.ml`,
81 /// with the correct protocol and hostname.
82 pub fn get_protocol_and_hostname(&self) -> String {
83 format!("{}://{}", self.get_protocol_string(), self.hostname)
86 /// When running the federation test setup in `api_tests/` or `docker/federation`, the `hostname`
87 /// variable will be like `lemmy-alpha:8541`. This method removes the port and returns
88 /// `lemmy-alpha` instead. It has no effect in production.
89 pub fn get_hostname_without_port(&self) -> Result<String, anyhow::Error> {
94 .collect::<Vec<&str>>()
96 .context(location_info!())?)
101 pub fn webfinger_regex(&self) -> Regex {
102 WEBFINGER_REGEX.clone()
105 pub fn pictrs_config(&self) -> Result<PictrsConfig, LemmyError> {
109 .ok_or_else(|| anyhow!("images_disabled").into())