lemmy/crates/utils/src/settings/mod.rs

132 lines
3.7 KiB
Rust
Raw Normal View History

use crate::{error::LemmyResult, location_info};
use anyhow::{anyhow, Context};
use deser_hjson::from_str;
2021-11-22 18:58:31 +00:00
use once_cell::sync::Lazy;
use regex::Regex;
use std::{env, fs, io::Error};
Rewrite images to use local proxy (#4035) * Add markdown rule to add rel=nofollow for all links * Add markdown image rule to add local image proxy (fixes #1036) * comments * rewrite markdown image links working * add comment * perform markdown image processing in api/apub receivers * clippy * add db table to validate proxied links * rewrite link fields for avatar, banner etc * sql fmt * proxy links received over federation * add config option * undo post.url rewriting, move http route definition * add tests * proxy images through pictrs * testing * cleanup request.rs file * more cleanup (fixes #2611) * include url content type when sending post over apub (fixes #2611) * store post url content type in db * should be media_type * get rid of cache_remote_thumbnails setting, instead automatically take thumbnail from federation data if available. * fix tests * add setting disable_external_link_previews * federate post url as image depending on mime type * change setting again * machete * invert * support custom emoji * clippy * update defaults * add image proxy test, fix test * fix test * clippy * revert accidental changes * address review * clippy * Markdown link rule-dess (#4356) * Extracting opengraph_data to its own type. * A few additions for markdown-link-rule. --------- Co-authored-by: Nutomic <me@nutomic.com> * fix setting * use enum for image proxy setting * fix test configs * add config backwards compat * clippy * machete --------- Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2024-01-25 14:22:11 +00:00
use urlencoding::encode;
pub mod structs;
use structs::{DatabaseConnection, PictrsConfig, PictrsImageMode, Settings};
static DEFAULT_CONFIG_FILE: &str = "config/config.hjson";
pub static SETTINGS: Lazy<Settings> = Lazy::new(|| {
if env::var("LEMMY_INITIALIZE_WITH_DEFAULT_SETTINGS").is_ok() {
println!(
"LEMMY_INITIALIZE_WITH_DEFAULT_SETTINGS was set, any configuration file has been ignored."
);
println!("Use with other environment variables to configure this instance further; e.g. LEMMY_DATABASE_URL.");
Settings::default()
} else {
Settings::init().expect("Failed to load settings file, see documentation (https://join-lemmy.org/docs/en/administration/configuration.html).")
}
});
2021-11-22 18:58:31 +00:00
static WEBFINGER_REGEX: Lazy<Regex> = Lazy::new(|| {
Regex::new(&format!(
"^acct:([a-zA-Z0-9_]{{3,}})@{}$",
SETTINGS.hostname
))
2021-11-22 18:58:31 +00:00
.expect("compile webfinger regex")
});
impl Settings {
/// Reads config from configuration file.
///
/// Note: The env var `LEMMY_DATABASE_URL` is parsed in
2021-10-16 13:33:38 +00:00
/// `lemmy_db_schema/src/lib.rs::get_database_url_from_env()`
/// Warning: Only call this once.
pub(crate) fn init() -> LemmyResult<Self> {
let config = from_str::<Settings>(&Self::read_config_file()?)?;
if config.hostname == "unset" {
Err(anyhow!("Hostname variable is not set!").into())
} else {
Ok(config)
}
}
pub fn get_database_url(&self) -> String {
if let Ok(url) = env::var("LEMMY_DATABASE_URL") {
return url;
}
match &self.database.connection {
DatabaseConnection::Uri { uri } => uri.clone(),
DatabaseConnection::Parts(parts) => {
format!(
"postgres://{}:{}@{}:{}/{}",
Rewrite images to use local proxy (#4035) * Add markdown rule to add rel=nofollow for all links * Add markdown image rule to add local image proxy (fixes #1036) * comments * rewrite markdown image links working * add comment * perform markdown image processing in api/apub receivers * clippy * add db table to validate proxied links * rewrite link fields for avatar, banner etc * sql fmt * proxy links received over federation * add config option * undo post.url rewriting, move http route definition * add tests * proxy images through pictrs * testing * cleanup request.rs file * more cleanup (fixes #2611) * include url content type when sending post over apub (fixes #2611) * store post url content type in db * should be media_type * get rid of cache_remote_thumbnails setting, instead automatically take thumbnail from federation data if available. * fix tests * add setting disable_external_link_previews * federate post url as image depending on mime type * change setting again * machete * invert * support custom emoji * clippy * update defaults * add image proxy test, fix test * fix test * clippy * revert accidental changes * address review * clippy * Markdown link rule-dess (#4356) * Extracting opengraph_data to its own type. * A few additions for markdown-link-rule. --------- Co-authored-by: Nutomic <me@nutomic.com> * fix setting * use enum for image proxy setting * fix test configs * add config backwards compat * clippy * machete --------- Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2024-01-25 14:22:11 +00:00
encode(&parts.user),
encode(&parts.password),
parts.host,
parts.port,
Rewrite images to use local proxy (#4035) * Add markdown rule to add rel=nofollow for all links * Add markdown image rule to add local image proxy (fixes #1036) * comments * rewrite markdown image links working * add comment * perform markdown image processing in api/apub receivers * clippy * add db table to validate proxied links * rewrite link fields for avatar, banner etc * sql fmt * proxy links received over federation * add config option * undo post.url rewriting, move http route definition * add tests * proxy images through pictrs * testing * cleanup request.rs file * more cleanup (fixes #2611) * include url content type when sending post over apub (fixes #2611) * store post url content type in db * should be media_type * get rid of cache_remote_thumbnails setting, instead automatically take thumbnail from federation data if available. * fix tests * add setting disable_external_link_previews * federate post url as image depending on mime type * change setting again * machete * invert * support custom emoji * clippy * update defaults * add image proxy test, fix test * fix test * clippy * revert accidental changes * address review * clippy * Markdown link rule-dess (#4356) * Extracting opengraph_data to its own type. * A few additions for markdown-link-rule. --------- Co-authored-by: Nutomic <me@nutomic.com> * fix setting * use enum for image proxy setting * fix test configs * add config backwards compat * clippy * machete --------- Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2024-01-25 14:22:11 +00:00
encode(&parts.database),
)
}
}
}
fn get_config_location() -> String {
env::var("LEMMY_CONFIG_LOCATION").unwrap_or_else(|_| DEFAULT_CONFIG_FILE.to_string())
}
fn read_config_file() -> Result<String, Error> {
fs::read_to_string(Self::get_config_location())
}
/// Returns either "http" or "https", depending on tls_enabled setting
pub fn get_protocol_string(&self) -> &'static str {
if self.tls_enabled {
"https"
} else {
"http"
}
}
/// Returns something like `http://localhost` or `https://lemmy.ml`,
/// with the correct protocol and hostname.
pub fn get_protocol_and_hostname(&self) -> String {
format!("{}://{}", self.get_protocol_string(), self.hostname)
}
/// When running the federation test setup in `api_tests/` or `docker/federation`, the `hostname`
/// variable will be like `lemmy-alpha:8541`. This method removes the port and returns
/// `lemmy-alpha` instead. It has no effect in production.
pub fn get_hostname_without_port(&self) -> Result<String, anyhow::Error> {
Ok(
(*self
.hostname
.split(':')
.collect::<Vec<&str>>()
.first()
.context(location_info!())?)
.to_string(),
)
}
2021-11-16 17:03:09 +00:00
pub fn webfinger_regex(&self) -> Regex {
WEBFINGER_REGEX.clone()
}
pub fn pictrs_config(&self) -> LemmyResult<PictrsConfig> {
self
2022-07-14 18:25:10 +00:00
.pictrs
.clone()
.ok_or_else(|| anyhow!("images_disabled").into())
}
}
Rewrite images to use local proxy (#4035) * Add markdown rule to add rel=nofollow for all links * Add markdown image rule to add local image proxy (fixes #1036) * comments * rewrite markdown image links working * add comment * perform markdown image processing in api/apub receivers * clippy * add db table to validate proxied links * rewrite link fields for avatar, banner etc * sql fmt * proxy links received over federation * add config option * undo post.url rewriting, move http route definition * add tests * proxy images through pictrs * testing * cleanup request.rs file * more cleanup (fixes #2611) * include url content type when sending post over apub (fixes #2611) * store post url content type in db * should be media_type * get rid of cache_remote_thumbnails setting, instead automatically take thumbnail from federation data if available. * fix tests * add setting disable_external_link_previews * federate post url as image depending on mime type * change setting again * machete * invert * support custom emoji * clippy * update defaults * add image proxy test, fix test * fix test * clippy * revert accidental changes * address review * clippy * Markdown link rule-dess (#4356) * Extracting opengraph_data to its own type. * A few additions for markdown-link-rule. --------- Co-authored-by: Nutomic <me@nutomic.com> * fix setting * use enum for image proxy setting * fix test configs * add config backwards compat * clippy * machete --------- Co-authored-by: Dessalines <dessalines@users.noreply.github.com>
2024-01-25 14:22:11 +00:00
impl PictrsConfig {
pub fn image_mode(&self) -> PictrsImageMode {
if let Some(cache_external_link_previews) = self.cache_external_link_previews {
if cache_external_link_previews {
PictrsImageMode::StoreLinkPreviews
} else {
PictrsImageMode::None
}
} else {
self.image_mode.clone()
}
}
}