Dont pass settings as parameter

This commit is contained in:
Felix Ableitner 2024-10-18 11:02:30 +02:00
parent 859dfb3f81
commit e87da6c5d1
55 changed files with 211 additions and 358 deletions

View file

@ -72,7 +72,6 @@ pub async fn create_comment_report(
&comment_report_view.creator.name,
&comment_report_view.comment_creator.name,
&mut context.pool(),
context.settings(),
)
.await?;
}

View file

@ -11,7 +11,10 @@ use lemmy_api_common::{
utils::{check_email_verified, check_registration_application, check_user_valid},
};
use lemmy_db_views::structs::{LocalUserView, SiteView};
use lemmy_utils::error::{LemmyErrorType, LemmyResult};
use lemmy_utils::{
error::{LemmyErrorType, LemmyResult},
settings::SETTINGS,
};
#[tracing::instrument(skip(context))]
pub async fn login(
@ -44,11 +47,7 @@ pub async fn login(
// Check the totp if enabled
if local_user_view.local_user.totp_2fa_enabled {
check_totp_2fa_valid(
&local_user_view,
&data.totp_2fa_token,
&context.settings().hostname,
)?;
check_totp_2fa_valid(&local_user_view, &data.totp_2fa_token, &SETTINGS.hostname)?;
}
let jwt = Claims::generate(local_user_view.local_user.id, req, &context).await?;

View file

@ -23,6 +23,6 @@ pub async fn reset_password(
check_email_verified(&local_user_view, &site_view)?;
// Email the pure token to the user.
send_password_reset_email(&local_user_view, &mut context.pool(), context.settings()).await?;
send_password_reset_email(&local_user_view, &mut context.pool()).await?;
Ok(Json(SuccessResponse::default()))
}

View file

@ -64,13 +64,7 @@ pub async fn save_user_settings(
// if email was changed, check that it is not taken and send verification mail
if previous_email.deref() != email {
LocalUser::check_is_email_taken(&mut context.pool(), email).await?;
send_verification_email(
&local_user_view,
email,
&mut context.pool(),
context.settings(),
)
.await?;
send_verification_email(&local_user_view, email, &mut context.pool()).await?;
}
}

View file

@ -6,7 +6,7 @@ use lemmy_api_common::{
};
use lemmy_db_schema::source::local_user::{LocalUser, LocalUserUpdateForm};
use lemmy_db_views::structs::LocalUserView;
use lemmy_utils::error::LemmyResult;
use lemmy_utils::{error::LemmyResult, settings::SETTINGS};
/// Enable or disable two-factor-authentication. The current setting is determined from
/// [LocalUser.totp_2fa_enabled].
@ -25,7 +25,7 @@ pub async fn update_totp(
check_totp_2fa_valid(
&local_user_view,
&Some(data.totp_token.clone()),
&context.settings().hostname,
&SETTINGS.hostname,
)?;
// toggle the 2fa setting

View file

@ -37,12 +37,7 @@ pub async fn verify_email(
if site_view.local_site.application_email_admins {
let local_user = LocalUserView::read(&mut context.pool(), local_user_id).await?;
send_new_applicant_email_to_admins(
&local_user.person.name,
&mut context.pool(),
context.settings(),
)
.await?;
send_new_applicant_email_to_admins(&local_user.person.name, &mut context.pool()).await?;
}
Ok(Json(SuccessResponse::default()))

View file

@ -67,7 +67,6 @@ pub async fn create_post_report(
&post_report_view.creator.name,
&post_report_view.post_creator.name,
&mut context.pool(),
context.settings(),
)
.await?;
}

View file

@ -56,7 +56,6 @@ pub async fn create_pm_report(
&private_message_report_view.creator.name,
&private_message_report_view.private_message_creator.name,
&mut context.pool(),
context.settings(),
)
.await?;
}

View file

@ -62,7 +62,7 @@ pub async fn approve_registration_application(
LocalUserView::read(&mut context.pool(), approved_user_id).await?;
if approved_local_user_view.local_user.email.is_some() {
// Email sending may fail, but this won't revert the application approval
send_application_approved_email(&approved_local_user_view, context.settings()).await?;
send_application_approved_email(&approved_local_user_view).await?;
}
};

View file

@ -26,6 +26,7 @@ use lemmy_db_views::structs::{CommentView, LocalUserView, PostView};
use lemmy_db_views_actor::structs::CommunityView;
use lemmy_utils::{
error::LemmyResult,
settings::SETTINGS,
utils::{markdown::markdown_to_html, mention::MentionData},
};
@ -99,7 +100,7 @@ pub async fn send_local_notifs(
local_user_view: Option<&LocalUserView>,
) -> LemmyResult<Vec<LocalUserId>> {
let mut recipient_ids = Vec::new();
let inbox_link = format!("{}/inbox", context.settings().get_protocol_and_hostname());
let inbox_link = format!("{}/inbox", SETTINGS.get_protocol_and_hostname());
// let person = my_local_user.person;
// Read the comment view to get extra info
@ -116,7 +117,7 @@ pub async fn send_local_notifs(
// Send the local mentions
for mention in mentions
.iter()
.filter(|m| m.is_local(&context.settings().hostname) && m.name.ne(&person.name))
.filter(|m| m.is_local() && m.name.ne(&person.name))
{
let mention_name = mention.name.clone();
let user_view = LocalUserView::read_from_name(&mut context.pool(), &mention_name).await;
@ -147,7 +148,6 @@ pub async fn send_local_notifs(
&mention_user_view,
&lang.notification_mentioned_by_subject(&person.name),
&lang.notification_mentioned_by_body(&content, &inbox_link, &person.name),
context.settings(),
)
.await
}
@ -199,7 +199,6 @@ pub async fn send_local_notifs(
&parent_user_view,
&lang.notification_comment_reply_subject(&person.name),
&lang.notification_comment_reply_body(&content, &inbox_link, &person.name),
context.settings(),
)
.await
}
@ -245,7 +244,6 @@ pub async fn send_local_notifs(
&parent_user_view,
&lang.notification_post_reply_subject(&person.name),
&lang.notification_post_reply_body(&content, &inbox_link, &person.name),
context.settings(),
)
.await
}

View file

@ -7,7 +7,10 @@ use lemmy_db_schema::{
sensitive::SensitiveString,
source::login_token::{LoginToken, LoginTokenCreateForm},
};
use lemmy_utils::error::{LemmyErrorExt, LemmyErrorType, LemmyResult};
use lemmy_utils::{
error::{LemmyErrorExt, LemmyErrorType, LemmyResult},
settings::SETTINGS,
};
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Hash)]
@ -38,7 +41,7 @@ impl Claims {
req: HttpRequest,
context: &LemmyContext,
) -> LemmyResult<SensitiveString> {
let hostname = context.settings().hostname.clone();
let hostname = SETTINGS.hostname.clone();
let my_claims = Claims {
sub: user_id.0.to_string(),
iss: hostname,

View file

@ -4,10 +4,7 @@ use lemmy_db_schema::{
source::secret::Secret,
utils::{build_db_pool_for_tests, ActualDbPool, DbPool},
};
use lemmy_utils::{
rate_limit::RateLimitCell,
settings::{structs::Settings, SETTINGS},
};
use lemmy_utils::{rate_limit::RateLimitCell, settings::SETTINGS};
use reqwest_middleware::{ClientBuilder, ClientWithMiddleware};
use std::sync::Arc;
@ -42,9 +39,6 @@ impl LemmyContext {
pub fn client(&self) -> &ClientWithMiddleware {
&self.client
}
pub fn settings(&self) -> &'static Settings {
&SETTINGS
}
pub fn secret(&self) -> &Secret {
&self.secret
}
@ -72,7 +66,7 @@ impl LemmyContext {
let context = LemmyContext::create(pool, client, secret, rate_limit_cell.clone());
FederationConfig::builder()
.domain(context.settings().hostname.clone())
.domain(SETTINGS.hostname.clone())
.app_data(context)
.debug(true)
// Dont allow any network fetches

View file

@ -19,7 +19,10 @@ use lemmy_db_schema::{
};
use lemmy_utils::{
error::{LemmyError, LemmyErrorType, LemmyResult},
settings::structs::{PictrsImageMode, Settings},
settings::{
structs::{PictrsImageMode, Settings},
SETTINGS,
},
REQWEST_TIMEOUT,
VERSION,
};
@ -296,7 +299,7 @@ pub async fn purge_image_from_pictrs(image_url: &Url, context: &LemmyContext) ->
.next_back()
.ok_or(LemmyErrorType::ImageUrlMissingLastPathSegment)?;
let pictrs_config = context.settings().pictrs_config()?;
let pictrs_config = SETTINGS.pictrs_config()?;
let purge_url = format!("{}internal/purge?alias={}", pictrs_config.url, alias);
let pictrs_api_key = pictrs_config
@ -323,7 +326,7 @@ pub async fn delete_image_from_pictrs(
delete_token: &str,
context: &LemmyContext,
) -> LemmyResult<()> {
let pictrs_config = context.settings().pictrs_config()?;
let pictrs_config = SETTINGS.pictrs_config()?;
let url = format!(
"{}image/delete/{}/{}",
pictrs_config.url, &delete_token, &alias
@ -341,7 +344,7 @@ pub async fn delete_image_from_pictrs(
/// Retrieves the image with local pict-rs and generates a thumbnail. Returns the thumbnail url.
#[tracing::instrument(skip_all)]
async fn generate_pictrs_thumbnail(image_url: &Url, context: &LemmyContext) -> LemmyResult<Url> {
let pictrs_config = context.settings().pictrs_config()?;
let pictrs_config = SETTINGS.pictrs_config()?;
match pictrs_config.image_mode() {
PictrsImageMode::None => return Ok(image_url.clone()),
@ -357,7 +360,7 @@ async fn generate_pictrs_thumbnail(image_url: &Url, context: &LemmyContext) -> L
"{}image/download?url={}&resize={}",
pictrs_config.url,
encode(image_url.as_str()),
context.settings().pictrs_config()?.max_thumbnail_size
SETTINGS.pictrs_config()?.max_thumbnail_size
);
let res = context
@ -382,7 +385,7 @@ async fn generate_pictrs_thumbnail(image_url: &Url, context: &LemmyContext) -> L
pictrs_alias: image.file.clone(),
pictrs_delete_token: image.delete_token.clone(),
};
let protocol_and_hostname = context.settings().get_protocol_and_hostname();
let protocol_and_hostname = SETTINGS.get_protocol_and_hostname();
let thumbnail_url = image.thumbnail_url(&protocol_and_hostname)?;
// Also store the details for the image
@ -400,7 +403,7 @@ pub async fn fetch_pictrs_proxied_image_details(
image_url: &Url,
context: &LemmyContext,
) -> LemmyResult<PictrsFileDetails> {
let pictrs_url = context.settings().pictrs_config()?.url;
let pictrs_url = SETTINGS.pictrs_config()?.url;
let encoded_image_url = encode(image_url.as_str());
// Pictrs needs you to fetch the proxied image before you can fetch the details

View file

@ -50,7 +50,7 @@ use lemmy_utils::{
email::{send_email, translations::Lang},
error::{LemmyError, LemmyErrorExt, LemmyErrorType, LemmyResult},
rate_limit::{ActionType, BucketConfig},
settings::structs::{PictrsImageMode, Settings},
settings::{structs::PictrsImageMode, SETTINGS},
utils::{
markdown::{image_links::markdown_rewrite_image_links, markdown_check_for_blocked_urls},
slurs::{build_slur_regex, remove_slurs},
@ -409,26 +409,13 @@ pub fn honeypot_check(honeypot: &Option<String>) -> LemmyResult<()> {
}
}
pub async fn send_email_to_user(
local_user_view: &LocalUserView,
subject: &str,
body: &str,
settings: &Settings,
) {
pub async fn send_email_to_user(local_user_view: &LocalUserView, subject: &str, body: &str) {
if local_user_view.person.banned || !local_user_view.local_user.send_notifications_to_email {
return;
}
if let Some(user_email) = &local_user_view.local_user.email {
match send_email(
subject,
user_email,
&local_user_view.person.name,
body,
settings,
)
.await
{
match send_email(subject, user_email, &local_user_view.person.name, body).await {
Ok(_o) => _o,
Err(e) => warn!("{}", e),
};
@ -438,7 +425,6 @@ pub async fn send_email_to_user(
pub async fn send_password_reset_email(
user: &LocalUserView,
pool: &mut DbPool<'_>,
settings: &Settings,
) -> LemmyResult<()> {
// Generate a random token
let token = uuid::Uuid::new_v4().to_string();
@ -446,10 +432,10 @@ pub async fn send_password_reset_email(
let email = &user.local_user.email.clone().expect("email");
let lang = get_interface_language(user);
let subject = &lang.password_reset_subject(&user.person.name);
let protocol_and_hostname = settings.get_protocol_and_hostname();
let protocol_and_hostname = SETTINGS.get_protocol_and_hostname();
let reset_link = format!("{}/password_change/{}", protocol_and_hostname, &token);
let body = &lang.password_reset_body(reset_link, &user.person.name);
send_email(subject, email, &user.person.name, body, settings).await?;
send_email(subject, email, &user.person.name, body).await?;
// Insert the row after successful send, to avoid using daily reset limit while
// email sending is broken.
@ -463,7 +449,6 @@ pub async fn send_verification_email(
user: &LocalUserView,
new_email: &str,
pool: &mut DbPool<'_>,
settings: &Settings,
) -> LemmyResult<()> {
let form = EmailVerificationForm {
local_user_id: user.local_user.id,
@ -472,15 +457,15 @@ pub async fn send_verification_email(
};
let verify_link = format!(
"{}/verify_email/{}",
settings.get_protocol_and_hostname(),
SETTINGS.get_protocol_and_hostname(),
&form.verification_token
);
EmailVerification::create(pool, &form).await?;
let lang = get_interface_language(user);
let subject = lang.verify_email_subject(&settings.hostname);
let body = lang.verify_email_body(&settings.hostname, &user.person.name, verify_link);
send_email(&subject, new_email, &user.person.name, &body, settings).await?;
let subject = lang.verify_email_subject(&SETTINGS.hostname);
let body = lang.verify_email_body(&SETTINGS.hostname, &user.person.name, verify_link);
send_email(&subject, new_email, &user.person.name, &body).await?;
Ok(())
}
@ -554,37 +539,33 @@ pub async fn get_url_blocklist(context: &LemmyContext) -> LemmyResult<RegexSet>
)
}
pub async fn send_application_approved_email(
user: &LocalUserView,
settings: &Settings,
) -> LemmyResult<()> {
pub async fn send_application_approved_email(user: &LocalUserView) -> LemmyResult<()> {
let email = &user.local_user.email.clone().expect("email");
let lang = get_interface_language(user);
let subject = lang.registration_approved_subject(&user.person.actor_id);
let body = lang.registration_approved_body(&settings.hostname);
send_email(&subject, email, &user.person.name, &body, settings).await
let body = lang.registration_approved_body(&SETTINGS.hostname);
send_email(&subject, email, &user.person.name, &body).await
}
/// Send a new applicant email notification to all admins
pub async fn send_new_applicant_email_to_admins(
applicant_username: &str,
pool: &mut DbPool<'_>,
settings: &Settings,
) -> LemmyResult<()> {
// Collect the admins with emails
let admins = LocalUserView::list_admins_with_emails(pool).await?;
let applications_link = &format!(
"{}/registration_applications",
settings.get_protocol_and_hostname(),
SETTINGS.get_protocol_and_hostname(),
);
for admin in &admins {
let email = &admin.local_user.email.clone().expect("email");
let lang = get_interface_language_from_settings(admin);
let subject = lang.new_application_subject(&settings.hostname, applicant_username);
let subject = lang.new_application_subject(&SETTINGS.hostname, applicant_username);
let body = lang.new_application_body(applications_link);
send_email(&subject, email, &admin.person.name, &body, settings).await?;
send_email(&subject, email, &admin.person.name, &body).await?;
}
Ok(())
}
@ -594,19 +575,18 @@ pub async fn send_new_report_email_to_admins(
reporter_username: &str,
reported_username: &str,
pool: &mut DbPool<'_>,
settings: &Settings,
) -> LemmyResult<()> {
// Collect the admins with emails
let admins = LocalUserView::list_admins_with_emails(pool).await?;
let reports_link = &format!("{}/reports", settings.get_protocol_and_hostname(),);
let reports_link = &format!("{}/reports", SETTINGS.get_protocol_and_hostname(),);
for admin in &admins {
let email = &admin.local_user.email.clone().expect("email");
let lang = get_interface_language_from_settings(admin);
let subject = lang.new_report_subject(&settings.hostname, reported_username, reporter_username);
let subject = lang.new_report_subject(&SETTINGS.hostname, reported_username, reporter_username);
let body = lang.new_report_body(reports_link);
send_email(&subject, email, &admin.person.name, &body, settings).await?;
send_email(&subject, email, &admin.person.name, &body).await?;
}
Ok(())
}
@ -956,7 +936,6 @@ pub enum EndpointType {
pub fn generate_local_apub_endpoint(
endpoint_type: EndpointType,
name: &str,
domain: &str,
) -> Result<DbUrl, ParseError> {
let point = match endpoint_type {
EndpointType::Community => "c",
@ -966,6 +945,7 @@ pub fn generate_local_apub_endpoint(
EndpointType::PrivateMessage => "private_message",
};
let domain = &SETTINGS.get_protocol_and_hostname();
Ok(Url::parse(&format!("{domain}/{point}/{name}"))?.into())
}
@ -977,8 +957,8 @@ pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
Ok(Url::parse(&format!("{actor_id}/inbox"))?.into())
}
pub fn generate_shared_inbox_url(settings: &Settings) -> LemmyResult<DbUrl> {
let url = format!("{}/inbox", settings.get_protocol_and_hostname());
pub fn generate_shared_inbox_url() -> LemmyResult<DbUrl> {
let url = format!("{}/inbox", SETTINGS.get_protocol_and_hostname());
Ok(Url::parse(&url)?.into())
}
@ -1044,7 +1024,7 @@ pub async fn process_markdown(
markdown_check_for_blocked_urls(&text, url_blocklist)?;
if context.settings().pictrs_config()?.image_mode() == PictrsImageMode::ProxyAllImages {
if SETTINGS.pictrs_config()?.image_mode() == PictrsImageMode::ProxyAllImages {
let (text, links) = markdown_rewrite_image_links(text);
RemoteImage::create(&mut context.pool(), links.clone()).await?;
@ -1053,8 +1033,7 @@ pub async fn process_markdown(
// Insert image details for the remote image
let details_res = fetch_pictrs_proxied_image_details(&link, context).await;
if let Ok(details) = details_res {
let proxied =
build_proxied_image_url(&link, &context.settings().get_protocol_and_hostname())?;
let proxied = build_proxied_image_url(&link, &SETTINGS.get_protocol_and_hostname())?;
let details_form = details.build_image_details_form(&proxied);
ImageDetails::create(&mut context.pool(), &details_form).await?;
}
@ -1089,12 +1068,12 @@ async fn proxy_image_link_internal(
context: &LemmyContext,
) -> LemmyResult<DbUrl> {
// Dont rewrite links pointing to local domain.
if link.domain() == Some(&context.settings().hostname) {
if link.domain() == Some(&SETTINGS.hostname) {
Ok(link.into())
} else if image_mode == PictrsImageMode::ProxyAllImages {
RemoteImage::create(&mut context.pool(), vec![link.clone()]).await?;
let proxied = build_proxied_image_url(&link, &context.settings().get_protocol_and_hostname())?;
let proxied = build_proxied_image_url(&link, &SETTINGS.get_protocol_and_hostname())?;
// This should fail softly, since pictrs might not even be running
let details_res = fetch_pictrs_proxied_image_details(&link, context).await;
@ -1112,12 +1091,7 @@ async fn proxy_image_link_internal(
/// Rewrite a link to go through `/api/v3/image_proxy` endpoint. This is only for remote urls and
/// if image_proxy setting is enabled.
pub(crate) async fn proxy_image_link(link: Url, context: &LemmyContext) -> LemmyResult<DbUrl> {
proxy_image_link_internal(
link,
context.settings().pictrs_config()?.image_mode(),
context,
)
.await
proxy_image_link_internal(link, SETTINGS.pictrs_config()?.image_mode(), context).await
}
pub async fn proxy_image_link_opt_api(

View file

@ -74,11 +74,7 @@ pub async fn create_community(
}
// Double check for duplicate community actor_ids
let community_actor_id = generate_local_apub_endpoint(
EndpointType::Community,
&data.name,
&context.settings().get_protocol_and_hostname(),
)?;
let community_actor_id = generate_local_apub_endpoint(EndpointType::Community, &data.name)?;
let community_dupe =
Community::read_from_apub_id(&mut context.pool(), &community_actor_id).await?;
if community_dupe.is_some() {
@ -97,7 +93,7 @@ pub async fn create_community(
private_key: Some(keypair.private_key),
followers_url: Some(generate_followers_url(&community_actor_id)?),
inbox_url: Some(generate_inbox_url(&community_actor_id)?),
shared_inbox_url: Some(generate_shared_inbox_url(context.settings())?),
shared_inbox_url: Some(generate_shared_inbox_url()?),
posting_restricted_to_mods: data.posting_restricted_to_mods,
visibility: data.visibility,
..CommunityInsertForm::new(

View file

@ -23,6 +23,7 @@ use lemmy_db_schema::{
use lemmy_db_views::structs::{LocalUserView, PrivateMessageView};
use lemmy_utils::{
error::{LemmyErrorExt, LemmyErrorType, LemmyResult},
settings::SETTINGS,
utils::{markdown::markdown_to_html, validation::is_valid_body_field},
};
@ -63,14 +64,13 @@ pub async fn create_private_message(
let recipient_id = data.recipient_id;
let local_recipient = LocalUserView::read_person(&mut context.pool(), recipient_id).await?;
let lang = get_interface_language(&local_recipient);
let inbox_link = format!("{}/inbox", context.settings().get_protocol_and_hostname());
let inbox_link = format!("{}/inbox", SETTINGS.get_protocol_and_hostname());
let sender_name = &local_user_view.person.name;
let content = markdown_to_html(&content);
send_email_to_user(
&local_recipient,
&lang.notification_private_message_subject(sender_name),
&lang.notification_private_message_body(inbox_link, &content, sender_name),
context.settings(),
)
.await;
}

View file

@ -28,6 +28,7 @@ use lemmy_db_schema::{
use lemmy_db_views::structs::{LocalUserView, SiteView};
use lemmy_utils::{
error::{LemmyErrorType, LemmyResult},
settings::SETTINGS,
utils::{
slurs::{check_slurs, check_slurs_opt},
validation::{
@ -54,8 +55,8 @@ pub async fn create_site(
validate_create_payload(&local_site, &data)?;
let actor_id: DbUrl = Url::parse(&context.settings().get_protocol_and_hostname())?.into();
let inbox_url = Some(generate_shared_inbox_url(context.settings())?);
let actor_id: DbUrl = Url::parse(&SETTINGS.get_protocol_and_hostname())?.into();
let inbox_url = Some(generate_shared_inbox_url()?);
let keypair = generate_actor_keypair()?;
let slur_regex = local_site_to_slur_regex(&local_site);

View file

@ -161,8 +161,7 @@ pub async fn register(
// Email the admins, only if email verification is not required
if local_site.application_email_admins && !local_site.require_email_verification {
send_new_applicant_email_to_admins(&data.username, &mut context.pool(), context.settings())
.await?;
send_new_applicant_email_to_admins(&data.username, &mut context.pool()).await?;
}
let mut login_response = LoginResponse {
@ -409,17 +408,13 @@ async fn create_person(
) -> Result<Person, LemmyError> {
let actor_keypair = generate_actor_keypair()?;
is_valid_actor_name(&username, local_site.actor_name_max_length as usize)?;
let actor_id = generate_local_apub_endpoint(
EndpointType::Person,
&username,
&context.settings().get_protocol_and_hostname(),
)?;
let actor_id = generate_local_apub_endpoint(EndpointType::Person, &username)?;
// Register the new person
let person_form = PersonInsertForm {
actor_id: Some(actor_id.clone()),
inbox_url: Some(generate_inbox_url(&actor_id)?),
shared_inbox_url: Some(generate_shared_inbox_url(context.settings())?),
shared_inbox_url: Some(generate_shared_inbox_url()?),
private_key: Some(actor_keypair.private_key),
..PersonInsertForm::new(username.clone(), actor_keypair.public_key, instance_id)
};
@ -487,7 +482,6 @@ async fn send_verification_email_if_required(
.clone()
.expect("invalid verification email"),
&mut context.pool(),
context.settings(),
)
.await?;

View file

@ -41,6 +41,7 @@ use lemmy_db_schema::{
};
use lemmy_utils::{
error::{LemmyError, LemmyResult},
settings::SETTINGS,
LemmyErrorType,
};
use url::Url;
@ -69,10 +70,7 @@ impl BlockUser {
kind: BlockType::Block,
remove_data,
summary: reason,
id: generate_activity_id(
BlockType::Block,
&context.settings().get_protocol_and_hostname(),
)?,
id: generate_activity_id(BlockType::Block)?,
audience,
end_time: expires,
})
@ -136,7 +134,7 @@ impl ActivityHandler for BlockUser {
.inner()
.domain()
.ok_or(LemmyErrorType::UrlWithoutDomain)?;
if context.settings().hostname == domain {
if SETTINGS.hostname == domain {
return Err(
anyhow!("Site bans from remote instance can't affect user's home instance").into(),
);

View file

@ -50,10 +50,7 @@ impl UndoBlockUser {
None
};
let id = generate_activity_id(
UndoType::Undo,
&context.settings().get_protocol_and_hostname(),
)?;
let id = generate_activity_id(UndoType::Undo)?;
let undo = UndoBlockUser {
actor: mod_.id().into(),
to: vec![public()],

View file

@ -81,15 +81,13 @@ impl AnnounceActivity {
pub(crate) fn new(
object: RawAnnouncableActivities,
community: &ApubCommunity,
context: &Data<LemmyContext>,
) -> LemmyResult<AnnounceActivity> {
let inner_kind = object
.other
.get("type")
.and_then(serde_json::Value::as_str)
.unwrap_or("other");
let id =
generate_announce_activity_id(inner_kind, &context.settings().get_protocol_and_hostname())?;
let id = generate_announce_activity_id(inner_kind)?;
Ok(AnnounceActivity {
actor: community.id().into(),
to: vec![public()],
@ -111,7 +109,7 @@ impl AnnounceActivity {
community: &ApubCommunity,
context: &Data<LemmyContext>,
) -> LemmyResult<()> {
let announce = AnnounceActivity::new(object.clone(), community, context)?;
let announce = AnnounceActivity::new(object.clone(), community)?;
let inboxes = ActivitySendTargets::to_local_community_followers(community.id);
send_lemmy_activity(context, announce, community, inboxes.clone(), false).await?;
@ -122,17 +120,14 @@ impl AnnounceActivity {
// Hack: need to convert Page into a format which can be sent as activity, which requires
// adding actor field.
let announcable_page = RawAnnouncableActivities {
id: generate_activity_id(
AnnounceType::Announce,
&context.settings().get_protocol_and_hostname(),
)?,
id: generate_activity_id(AnnounceType::Announce)?,
actor: c.actor.clone().into_inner(),
other: serde_json::to_value(c.object)?
.as_object()
.expect("is object")
.clone(),
};
let announce_compat = AnnounceActivity::new(announcable_page, community, context)?;
let announce_compat = AnnounceActivity::new(announcable_page, community)?;
send_lemmy_activity(context, announce_compat, community, inboxes, false).await?;
}
Ok(())

View file

@ -47,10 +47,7 @@ impl CollectionAdd {
actor: &ApubPerson,
context: &Data<LemmyContext>,
) -> LemmyResult<()> {
let id = generate_activity_id(
AddType::Add,
&context.settings().get_protocol_and_hostname(),
)?;
let id = generate_activity_id(AddType::Add)?;
let add = CollectionAdd {
actor: actor.id().into(),
to: vec![public()],
@ -73,10 +70,7 @@ impl CollectionAdd {
actor: &ApubPerson,
context: &Data<LemmyContext>,
) -> LemmyResult<()> {
let id = generate_activity_id(
AddType::Add,
&context.settings().get_protocol_and_hostname(),
)?;
let id = generate_activity_id(AddType::Add)?;
let add = CollectionAdd {
actor: actor.id().into(),
to: vec![public()],

View file

@ -42,10 +42,7 @@ impl CollectionRemove {
actor: &ApubPerson,
context: &Data<LemmyContext>,
) -> LemmyResult<()> {
let id = generate_activity_id(
RemoveType::Remove,
&context.settings().get_protocol_and_hostname(),
)?;
let id = generate_activity_id(RemoveType::Remove)?;
let remove = CollectionRemove {
actor: actor.id().into(),
to: vec![public()],
@ -68,10 +65,7 @@ impl CollectionRemove {
actor: &ApubPerson,
context: &Data<LemmyContext>,
) -> LemmyResult<()> {
let id = generate_activity_id(
RemoveType::Remove,
&context.settings().get_protocol_and_hostname(),
)?;
let id = generate_activity_id(RemoveType::Remove)?;
let remove = CollectionRemove {
actor: actor.id().into(),
to: vec![public()],

View file

@ -130,10 +130,7 @@ pub(crate) async fn send_lock_post(
let community: ApubCommunity = Community::read(&mut context.pool(), post.community_id)
.await?
.into();
let id = generate_activity_id(
LockType::Lock,
&context.settings().get_protocol_and_hostname(),
)?;
let id = generate_activity_id(LockType::Lock)?;
let community_id = community.actor_id.inner().clone();
let lock = LockPage {
actor: actor.actor_id.clone().into(),
@ -147,10 +144,7 @@ pub(crate) async fn send_lock_post(
let activity = if locked {
AnnouncableActivities::LockPost(lock)
} else {
let id = generate_activity_id(
UndoType::Undo,
&context.settings().get_protocol_and_hostname(),
)?;
let id = generate_activity_id(UndoType::Undo)?;
let undo = UndoLockPage {
actor: lock.actor.clone(),
to: vec![public()],

View file

@ -44,10 +44,7 @@ impl Report {
let actor: ApubPerson = actor.into();
let community: ApubCommunity = community.into();
let kind = FlagType::Flag;
let id = generate_activity_id(
kind.clone(),
&context.settings().get_protocol_and_hostname(),
)?;
let id = generate_activity_id(kind.clone())?;
let report = Report {
actor: actor.id().into(),
to: [community.id().into()],

View file

@ -36,10 +36,7 @@ pub(crate) async fn send_update_community(
) -> LemmyResult<()> {
let community: ApubCommunity = community.into();
let actor: ApubPerson = actor.into();
let id = generate_activity_id(
UpdateType::Update,
&context.settings().get_protocol_and_hostname(),
)?;
let id = generate_activity_id(UpdateType::Update)?;
let update = UpdateCommunity {
actor: actor.id().into(),
to: vec![public()],

View file

@ -62,10 +62,7 @@ impl CreateOrUpdateNote {
.await?
.into();
let id = generate_activity_id(
kind.clone(),
&context.settings().get_protocol_and_hostname(),
)?;
let id = generate_activity_id(kind.clone())?;
let note = ApubComment(comment).into_json(&context).await?;
let create_or_update = CreateOrUpdateNote {

View file

@ -43,10 +43,7 @@ impl CreateOrUpdatePage {
kind: CreateOrUpdateType,
context: &Data<LemmyContext>,
) -> LemmyResult<CreateOrUpdatePage> {
let id = generate_activity_id(
kind.clone(),
&context.settings().get_protocol_and_hostname(),
)?;
let id = generate_activity_id(kind.clone())?;
Ok(CreateOrUpdatePage {
actor: actor.id().into(),
to: vec![public()],

View file

@ -26,10 +26,7 @@ pub(crate) async fn send_create_or_update_pm(
let actor: ApubPerson = pm_view.creator.into();
let recipient: ApubPerson = pm_view.recipient.into();
let id = generate_activity_id(
kind.clone(),
&context.settings().get_protocol_and_hostname(),
)?;
let id = generate_activity_id(kind.clone())?;
let create_or_update = CreateOrUpdateChatMessage {
id: id.clone(),
actor: actor.id().into(),

View file

@ -87,12 +87,8 @@ impl Delete {
to: Url,
community: Option<&Community>,
summary: Option<String>,
context: &Data<LemmyContext>,
) -> LemmyResult<Delete> {
let id = generate_activity_id(
DeleteType::Delete,
&context.settings().get_protocol_and_hostname(),
)?;
let id = generate_activity_id(DeleteType::Delete)?;
let cc: Option<Url> = community.map(|c| c.actor_id.clone().into());
Ok(Delete {
actor: actor.actor_id.clone().into(),

View file

@ -60,10 +60,10 @@ pub(crate) async fn send_apub_delete_in_community(
let actor = ApubPerson::from(actor);
let is_mod_action = reason.is_some();
let activity = if deleted {
let delete = Delete::new(&actor, object, public(), Some(&community), reason, context)?;
let delete = Delete::new(&actor, object, public(), Some(&community), reason)?;
AnnouncableActivities::Delete(delete)
} else {
let undo = UndoDelete::new(&actor, object, public(), Some(&community), reason, context)?;
let undo = UndoDelete::new(&actor, object, public(), Some(&community), reason)?;
AnnouncableActivities::UndoDelete(undo)
};
send_activity_in_community(
@ -92,10 +92,10 @@ pub(crate) async fn send_apub_delete_private_message(
let deletable = DeletableObjects::PrivateMessage(pm.into());
let inbox = ActivitySendTargets::to_inbox(recipient.shared_inbox_or_inbox());
if deleted {
let delete: Delete = Delete::new(actor, deletable, recipient.id(), None, None, &context)?;
let delete: Delete = Delete::new(actor, deletable, recipient.id(), None, None)?;
send_lemmy_activity(&context, delete, actor, inbox, true).await?;
} else {
let undo = UndoDelete::new(actor, deletable, recipient.id(), None, None, &context)?;
let undo = UndoDelete::new(actor, deletable, recipient.id(), None, None)?;
send_lemmy_activity(&context, undo, actor, inbox, true).await?;
};
Ok(())
@ -109,7 +109,7 @@ pub async fn send_apub_delete_user(
let person: ApubPerson = person.into();
let deletable = DeletableObjects::Person(person.clone());
let mut delete: Delete = Delete::new(&person, deletable, public(), None, None, &context)?;
let mut delete: Delete = Delete::new(&person, deletable, public(), None, None)?;
delete.remove_data = Some(remove_data);
let inboxes = ActivitySendTargets::to_all_instances();

View file

@ -71,14 +71,10 @@ impl UndoDelete {
to: Url,
community: Option<&Community>,
summary: Option<String>,
context: &Data<LemmyContext>,
) -> LemmyResult<UndoDelete> {
let object = Delete::new(actor, object, to.clone(), community, summary, context)?;
let object = Delete::new(actor, object, to.clone(), community, summary)?;
let id = generate_activity_id(
UndoType::Undo,
&context.settings().get_protocol_and_hostname(),
)?;
let id = generate_activity_id(UndoType::Undo)?;
let cc: Option<Url> = community.map(|c| c.actor_id.clone().into());
Ok(UndoDelete {
actor: actor.actor_id.clone().into(),

View file

@ -27,10 +27,7 @@ impl AcceptFollow {
to: Some([person.id().into()]),
object: follow,
kind: AcceptType::Accept,
id: generate_activity_id(
AcceptType::Accept,
&context.settings().get_protocol_and_hostname(),
)?,
id: generate_activity_id(AcceptType::Accept)?,
};
let inbox = ActivitySendTargets::to_inbox(person.shared_inbox_or_inbox());
send_lemmy_activity(context, accept, &user_or_community, inbox, true).await

View file

@ -33,17 +33,13 @@ impl Follow {
pub(in crate::activities::following) fn new(
actor: &ApubPerson,
community: &ApubCommunity,
context: &Data<LemmyContext>,
) -> LemmyResult<Follow> {
Ok(Follow {
actor: actor.id().into(),
object: community.id().into(),
to: Some([community.id().into()]),
kind: FollowType::Follow,
id: generate_activity_id(
FollowType::Follow,
&context.settings().get_protocol_and_hostname(),
)?,
id: generate_activity_id(FollowType::Follow)?,
})
}
@ -53,7 +49,7 @@ impl Follow {
community: &ApubCommunity,
context: &Data<LemmyContext>,
) -> LemmyResult<()> {
let follow = Follow::new(actor, community, context)?;
let follow = Follow::new(actor, community)?;
let inbox = if community.local {
ActivitySendTargets::empty()
} else {

View file

@ -30,16 +30,13 @@ impl UndoFollow {
community: &ApubCommunity,
context: &Data<LemmyContext>,
) -> LemmyResult<()> {
let object = Follow::new(actor, community, context)?;
let object = Follow::new(actor, community)?;
let undo = UndoFollow {
actor: actor.id().into(),
to: Some([community.id().into()]),
object,
kind: UndoType::Undo,
id: generate_activity_id(
UndoType::Undo,
&context.settings().get_protocol_and_hostname(),
)?,
id: generate_activity_id(UndoType::Undo)?,
};
let inbox = if community.local {
ActivitySendTargets::empty()

View file

@ -42,7 +42,10 @@ use lemmy_db_schema::{
traits::Crud,
};
use lemmy_db_views_actor::structs::{CommunityPersonBanView, CommunityView};
use lemmy_utils::error::{LemmyError, LemmyErrorExt, LemmyErrorType, LemmyResult};
use lemmy_utils::{
error::{LemmyError, LemmyErrorExt, LemmyErrorType, LemmyResult},
settings::SETTINGS,
};
use serde::Serialize;
use tracing::info;
use url::{ParseError, Url};
@ -142,10 +145,11 @@ pub(crate) fn check_community_deleted_or_removed(community: &Community) -> Lemmy
/// Generate a unique ID for an activity, in the format:
/// `http(s)://example.com/receive/create/202daf0a-1489-45df-8d2e-c8a3173fed36`
fn generate_activity_id<T>(kind: T, protocol_and_hostname: &str) -> Result<Url, ParseError>
fn generate_activity_id<T>(kind: T) -> Result<Url, ParseError>
where
T: ToString,
{
let protocol_and_hostname = &SETTINGS.get_protocol_and_hostname();
let id = format!(
"{}/activities/{}/{}",
protocol_and_hostname,
@ -156,10 +160,8 @@ where
}
/// like generate_activity_id but also add the inner kind for easier debugging
fn generate_announce_activity_id(
inner_kind: &str,
protocol_and_hostname: &str,
) -> Result<Url, ParseError> {
fn generate_announce_activity_id(inner_kind: &str) -> Result<Url, ParseError> {
let protocol_and_hostname = &SETTINGS.get_protocol_and_hostname();
let id = format!(
"{}/activities/{}/{}/{}",
protocol_and_hostname,

View file

@ -40,13 +40,13 @@ pub(crate) async fn send_like_activity(
let empty = ActivitySendTargets::empty();
// score of 1 means upvote, -1 downvote, 0 undo a previous vote
if score != 0 {
let vote = Vote::new(object_id, &actor, &community, score.try_into()?, &context)?;
let vote = Vote::new(object_id, &actor, &community, score.try_into()?)?;
let activity = AnnouncableActivities::Vote(vote);
send_activity_in_community(activity, &actor, &community, empty, false, &context).await
} else {
// Lemmy API doesn't distinguish between Undo/Like and Undo/Dislike, so we hardcode it here.
let vote = Vote::new(object_id, &actor, &community, VoteType::Like, &context)?;
let undo_vote = UndoVote::new(vote, &actor, &community, &context)?;
let vote = Vote::new(object_id, &actor, &community, VoteType::Like)?;
let undo_vote = UndoVote::new(vote, &actor, &community)?;
let activity = AnnouncableActivities::UndoVote(undo_vote);
send_activity_in_community(activity, &actor, &community, empty, false, &context).await
}

View file

@ -27,16 +27,12 @@ impl UndoVote {
vote: Vote,
actor: &ApubPerson,
community: &ApubCommunity,
context: &Data<LemmyContext>,
) -> LemmyResult<Self> {
Ok(UndoVote {
actor: actor.id().into(),
object: vote,
kind: UndoType::Undo,
id: generate_activity_id(
UndoType::Undo,
&context.settings().get_protocol_and_hostname(),
)?,
id: generate_activity_id(UndoType::Undo)?,
audience: Some(community.id().into()),
})
}

View file

@ -28,13 +28,12 @@ impl Vote {
actor: &ApubPerson,
community: &ApubCommunity,
kind: VoteType,
context: &Data<LemmyContext>,
) -> LemmyResult<Vote> {
Ok(Vote {
actor: actor.id().into(),
object: object_id,
kind: kind.clone(),
id: generate_activity_id(kind, &context.settings().get_protocol_and_hostname())?,
id: generate_activity_id(kind)?,
audience: Some(community.id().into()),
})
}

View file

@ -57,7 +57,7 @@ impl Collection for ApubCommunityOutbox {
)
.await?;
let announcable = AnnouncableActivities::CreateOrUpdatePost(create);
let announce = AnnounceActivity::new(announcable.try_into()?, owner, data)?;
let announce = AnnounceActivity::new(announcable.try_into()?, owner)?;
ordered_items.push(announce);
}

View file

@ -8,6 +8,7 @@ use lemmy_api_common::{
use lemmy_db_schema::{newtypes::InstanceId, source::instance::Instance};
use lemmy_utils::{
error::LemmyResult,
settings::SETTINGS,
utils::markdown::image_links::{markdown_find_links, markdown_handle_title},
};
use url::Url;
@ -52,7 +53,7 @@ pub async fn markdown_rewrite_remote_links(
}
pub(crate) async fn to_local_url(url: &str, context: &Data<LemmyContext>) -> Option<Url> {
let local_domain = &context.settings().get_protocol_and_hostname();
let local_domain = &SETTINGS.get_protocol_and_hostname();
let object_id = ObjectId::<SearchableObjects>::parse(url).ok()?;
if object_id.inner().domain() == Some(local_domain) {
return None;
@ -61,10 +62,10 @@ pub(crate) async fn to_local_url(url: &str, context: &Data<LemmyContext>) -> Opt
match dereferenced {
SearchableObjects::PostOrComment(pc) => match *pc {
PostOrComment::Post(post) => {
generate_local_apub_endpoint(EndpointType::Post, &post.id.to_string(), local_domain)
generate_local_apub_endpoint(EndpointType::Post, &post.id.to_string())
}
PostOrComment::Comment(comment) => {
generate_local_apub_endpoint(EndpointType::Comment, &comment.id.to_string(), local_domain)
generate_local_apub_endpoint(EndpointType::Comment, &comment.id.to_string())
}
}
.ok()
@ -87,8 +88,8 @@ async fn format_actor_url(
instance_id: InstanceId,
context: &LemmyContext,
) -> LemmyResult<Url> {
let local_protocol_and_hostname = context.settings().get_protocol_and_hostname();
let local_hostname = &context.settings().hostname;
let local_protocol_and_hostname = SETTINGS.get_protocol_and_hostname();
let local_hostname = &SETTINGS.hostname;
let instance = Instance::read(&mut context.pool(), instance_id).await?;
let url = if &instance.domain != local_hostname {
format!(

View file

@ -17,7 +17,10 @@ use lemmy_db_schema::{
source::{activity::SentActivity, community::Community},
CommunityVisibility,
};
use lemmy_utils::error::{LemmyErrorType, LemmyResult};
use lemmy_utils::{
error::{LemmyErrorType, LemmyResult},
settings::SETTINGS,
};
use serde::{Deserialize, Serialize};
use std::{ops::Deref, time::Duration};
use tokio::time::timeout;
@ -98,10 +101,9 @@ pub(crate) async fn get_activity(
info: web::Path<ActivityQuery>,
context: web::Data<LemmyContext>,
) -> LemmyResult<HttpResponse> {
let settings = context.settings();
let activity_id = Url::parse(&format!(
"{}/activities/{}/{}",
settings.get_protocol_and_hostname(),
SETTINGS.get_protocol_and_hostname(),
info.type_,
info.id
))?

View file

@ -7,7 +7,7 @@ use activitypub_federation::{config::Data, traits::Object};
use actix_web::HttpResponse;
use lemmy_api_common::context::LemmyContext;
use lemmy_db_schema::source::site::Site;
use lemmy_utils::error::LemmyResult;
use lemmy_utils::{error::LemmyResult, settings::SETTINGS};
use url::Url;
pub(crate) async fn get_apub_site_http(context: Data<LemmyContext>) -> LemmyResult<HttpResponse> {
@ -18,11 +18,8 @@ pub(crate) async fn get_apub_site_http(context: Data<LemmyContext>) -> LemmyResu
}
#[tracing::instrument(skip_all)]
pub(crate) async fn get_apub_site_outbox(context: Data<LemmyContext>) -> LemmyResult<HttpResponse> {
let outbox_id = format!(
"{}/site_outbox",
context.settings().get_protocol_and_hostname()
);
pub(crate) async fn get_apub_site_outbox() -> LemmyResult<HttpResponse> {
let outbox_id = format!("{}/site_outbox", SETTINGS.get_protocol_and_hostname());
let outbox = EmptyOutbox::new(Url::parse(&outbox_id)?)?;
create_apub_response(&outbox)
}

View file

@ -11,6 +11,7 @@ use lemmy_db_schema::{
};
use lemmy_utils::{
error::{LemmyError, LemmyErrorType, LemmyResult},
settings::SETTINGS,
CACHE_DURATION_FEDERATION,
};
use moka::future::Cache;
@ -166,8 +167,7 @@ pub(crate) async fn check_apub_id_valid_with_strictness(
.domain()
.ok_or(LemmyErrorType::UrlWithoutDomain)?
.to_string();
let local_instance = context
.settings()
let local_instance = SETTINGS
.get_hostname_without_port()
.expect("local hostname is valid");
if domain == local_instance {
@ -186,8 +186,7 @@ pub(crate) async fn check_apub_id_valid_with_strictness(
.iter()
.map(|i| i.domain.clone())
.collect::<Vec<String>>();
let local_instance = context
.settings()
let local_instance = SETTINGS
.get_hostname_without_port()
.expect("local hostname is valid");
allowed_and_local.push(local_instance);

View file

@ -67,7 +67,7 @@ pub async fn collect_non_local_mentions(
let mentions = scrape_text_for_mentions(&comment.content)
.into_iter()
// Filter only the non-local ones
.filter(|m| !m.is_local(&context.settings().hostname));
.filter(|m| !m.is_local());
for mention in mentions {
let identifier = format!("{}@{}", mention.name, mention.domain);

View file

@ -42,6 +42,7 @@ use lemmy_db_schema::{
use lemmy_db_views_actor::structs::CommunityFollowerView;
use lemmy_utils::{
error::{LemmyError, LemmyResult},
settings::SETTINGS,
spawn_try_task,
utils::markdown::markdown_to_html,
};
@ -247,7 +248,7 @@ impl ApubCommunity {
let inboxes: Vec<Url> = follows
.into_iter()
.map(Into::into)
.filter(|inbox: &Url| inbox.host_str() != Some(&context.settings().hostname))
.filter(|inbox: &Url| inbox.host_str() != Some(&SETTINGS.hostname))
// Don't send to blocked instances
.filter(|inbox| check_apub_id_valid(inbox, &local_site_data).is_ok())
.collect();

View file

@ -5,7 +5,7 @@ use lemmy_api_common::{
lemmy_utils::settings::structs::FederationWorkerConfig,
};
use lemmy_db_schema::{newtypes::InstanceId, source::instance::Instance};
use lemmy_utils::error::LemmyResult;
use lemmy_utils::{error::LemmyResult, settings::SETTINGS};
use stats::receive_print_stats;
use std::{collections::HashMap, time::Duration};
use tokio::{
@ -105,7 +105,7 @@ impl SendManager {
"Starting federation workers for process count {} and index {}",
self.opts.process_count, process_index
);
let local_domain = self.context.settings().get_hostname_without_port()?;
let local_domain = SETTINGS.get_hostname_without_port()?;
let mut pool = self.context.pool();
loop {
let mut total_count = 0;

View file

@ -492,7 +492,7 @@ mod test {
actor_id: Some(actor_id.clone()),
private_key: (Some(actor_keypair.private_key)),
inbox_url: Some(generate_inbox_url(&actor_id)?),
shared_inbox_url: Some(generate_shared_inbox_url(context.settings())?),
shared_inbox_url: Some(generate_shared_inbox_url()?),
..PersonInsertForm::new("alice".to_string(), actor_keypair.public_key, instance.id)
};
let person = Person::create(&mut context.pool(), &person_form).await?;

View file

@ -23,6 +23,7 @@ use lemmy_db_views_actor::{
use lemmy_utils::{
cache_header::cache_1hour,
error::{LemmyError, LemmyErrorType, LemmyResult},
settings::SETTINGS,
utils::markdown::{markdown_to_html, sanitize_html},
};
use rss::{
@ -166,12 +167,12 @@ async fn get_feed_data(
.list(&site_view.site, &mut context.pool())
.await?;
let items = create_post_items(posts, &context.settings().get_protocol_and_hostname())?;
let items = create_post_items(posts)?;
let mut channel = Channel {
namespaces: RSS_NAMESPACE.clone(),
title: format!("{} - {}", site_view.site.name, listing_type),
link: context.settings().get_protocol_and_hostname(),
link: SETTINGS.get_protocol_and_hostname(),
items,
..Default::default()
};
@ -275,7 +276,7 @@ async fn get_feed_user(
.list(&site_view.site, &mut context.pool())
.await?;
let items = create_post_items(posts, &context.settings().get_protocol_and_hostname())?;
let items = create_post_items(posts)?;
let channel = Channel {
namespaces: RSS_NAMESPACE.clone(),
title: format!("{} - {}", sanitize_xml(site_view.site.name), person.name),
@ -315,7 +316,7 @@ async fn get_feed_community(
.list(&site_view.site, &mut context.pool())
.await?;
let items = create_post_items(posts, &context.settings().get_protocol_and_hostname())?;
let items = create_post_items(posts)?;
let mut channel = Channel {
namespaces: RSS_NAMESPACE.clone(),
@ -356,8 +357,8 @@ async fn get_feed_front(
.list(&site_view.site, &mut context.pool())
.await?;
let protocol_and_hostname = context.settings().get_protocol_and_hostname();
let items = create_post_items(posts, &protocol_and_hostname)?;
let protocol_and_hostname = SETTINGS.get_protocol_and_hostname();
let items = create_post_items(posts)?;
let mut channel = Channel {
namespaces: RSS_NAMESPACE.clone(),
title: format!("{} - Subscribed", sanitize_xml(site_view.site.name)),
@ -406,7 +407,7 @@ async fn get_feed_inbox(context: &LemmyContext, jwt: &str) -> LemmyResult<Channe
.list(&mut context.pool())
.await?;
let protocol_and_hostname = context.settings().get_protocol_and_hostname();
let protocol_and_hostname = SETTINGS.get_protocol_and_hostname();
let items = create_reply_and_mention_items(replies, mentions, &protocol_and_hostname)?;
let mut channel = Channel {
@ -493,7 +494,8 @@ fn build_item(
}
#[tracing::instrument(skip_all)]
fn create_post_items(posts: Vec<PostView>, protocol_and_hostname: &str) -> LemmyResult<Vec<Item>> {
fn create_post_items(posts: Vec<PostView>) -> LemmyResult<Vec<Item>> {
let protocol_and_hostname = &SETTINGS.get_protocol_and_hostname();
let mut items: Vec<Item> = Vec::new();
for p in posts {

View file

@ -17,7 +17,12 @@ use lemmy_db_schema::source::{
local_site::LocalSite,
};
use lemmy_db_views::structs::LocalUserView;
use lemmy_utils::{error::LemmyResult, rate_limit::RateLimitCell, REQWEST_TIMEOUT};
use lemmy_utils::{
error::LemmyResult,
rate_limit::RateLimitCell,
settings::SETTINGS,
REQWEST_TIMEOUT,
};
use reqwest::Body;
use reqwest_middleware::{ClientWithMiddleware, RequestBuilder};
use serde::Deserialize;
@ -135,7 +140,7 @@ async fn upload(
context: web::Data<LemmyContext>,
) -> LemmyResult<HttpResponse> {
// TODO: check rate limit here
let pictrs_config = context.settings().pictrs_config()?;
let pictrs_config = SETTINGS.pictrs_config()?;
let image_url = format!("{}image", pictrs_config.url);
let mut client_req = adapt_request(&req, &client, image_url);
@ -159,7 +164,7 @@ async fn upload(
pictrs_delete_token: image.delete_token.to_string(),
};
let protocol_and_hostname = context.settings().get_protocol_and_hostname();
let protocol_and_hostname = SETTINGS.get_protocol_and_hostname();
let thumbnail_url = image.thumbnail_url(&protocol_and_hostname)?;
// Also store the details for the image
@ -187,7 +192,7 @@ async fn full_res(
let name = &filename.into_inner();
// If there are no query params, the URL is original
let pictrs_config = context.settings().pictrs_config()?;
let pictrs_config = SETTINGS.pictrs_config()?;
let processed_url = params.process_url(name, &pictrs_config.url);
@ -234,7 +239,7 @@ async fn delete(
) -> LemmyResult<HttpResponse> {
let (token, file) = components.into_inner();
let pictrs_config = context.settings().pictrs_config()?;
let pictrs_config = SETTINGS.pictrs_config()?;
let url = format!("{}image/delete/{}/{}", pictrs_config.url, &token, &file);
let mut client_req = adapt_request(&req, &client, url);
@ -262,7 +267,7 @@ pub async fn image_proxy(
// for arbitrary purposes.
RemoteImage::validate(&mut context.pool(), url.clone().into()).await?;
let pictrs_config = context.settings().pictrs_config()?;
let pictrs_config = SETTINGS.pictrs_config()?;
let processed_url = params.process_url(&params.url, &pictrs_config.url);

View file

@ -5,6 +5,7 @@ use lemmy_db_views::structs::SiteView;
use lemmy_utils::{
cache_header::{cache_1hour, cache_3days},
error::LemmyResult,
settings::SETTINGS,
VERSION,
};
use serde::{Deserialize, Serialize};
@ -29,13 +30,13 @@ pub fn config(cfg: &mut web::ServiceConfig) {
);
}
async fn node_info_well_known(context: web::Data<LemmyContext>) -> LemmyResult<HttpResponse> {
async fn node_info_well_known() -> LemmyResult<HttpResponse> {
let node_info = NodeInfoWellKnown {
links: vec![NodeInfoWellKnownLinks {
rel: Url::parse("http://nodeinfo.diaspora.software/ns/schema/2.1")?,
href: Url::parse(&format!(
"{}/nodeinfo/2.1",
&context.settings().get_protocol_and_hostname(),
&SETTINGS.get_protocol_and_hostname(),
))?,
}],
};

View file

@ -9,7 +9,7 @@ use lemmy_db_schema::{
traits::ApubActor,
CommunityVisibility,
};
use lemmy_utils::{cache_header::cache_3days, error::LemmyResult};
use lemmy_utils::{cache_header::cache_3days, error::LemmyResult, settings::SETTINGS};
use serde::Deserialize;
use std::collections::HashMap;
use url::Url;
@ -38,10 +38,10 @@ async fn get_webfinger_response(
) -> LemmyResult<HttpResponse> {
let name = extract_webfinger_name(&info.resource, &context)?;
let links = if name == context.settings().hostname {
let links = if name == SETTINGS.hostname {
// webfinger response for instance actor (required for mastodon authorized fetch)
let url = Url::parse(&context.settings().get_protocol_and_hostname())?;
vec![webfinger_link_for_actor(Some(url), "none", &context)]
let url = Url::parse(&SETTINGS.get_protocol_and_hostname())?;
vec![webfinger_link_for_actor(Some(url), "none")]
} else {
// webfinger response for user/community
let user_id: Option<Url> = Person::read_from_name(&mut context.pool(), name, false)
@ -65,8 +65,8 @@ async fn get_webfinger_response(
// Mastodon seems to prioritize the last webfinger item in case of duplicates. Put
// community last so that it gets prioritized. For Lemmy the order doesn't matter.
vec![
webfinger_link_for_actor(user_id, "Person", &context),
webfinger_link_for_actor(community_id, "Group", &context),
webfinger_link_for_actor(user_id, "Person"),
webfinger_link_for_actor(community_id, "Group"),
]
}
.into_iter()
@ -90,11 +90,7 @@ async fn get_webfinger_response(
}
}
fn webfinger_link_for_actor(
url: Option<Url>,
kind: &str,
context: &LemmyContext,
) -> Vec<WebfingerLink> {
fn webfinger_link_for_actor(url: Option<Url>, kind: &str) -> Vec<WebfingerLink> {
if let Some(url) = url {
let type_key = "https://www.w3.org/ns/activitystreams#type"
.parse()
@ -120,7 +116,7 @@ fn webfinger_link_for_actor(
if kind == "Person" {
let template = format!(
"{}/activitypub/externalInteraction?uri={{uri}}",
context.settings().get_protocol_and_hostname()
SETTINGS.get_protocol_and_hostname()
);
vec.push(WebfingerLink {
rel: Some("http://ostatus.org/schema/1.0/subscribe".into()),

View file

@ -1,6 +1,6 @@
use crate::{
error::{LemmyErrorExt, LemmyErrorType, LemmyResult},
settings::structs::Settings,
settings::SETTINGS,
};
use html2text;
use lettre::{
@ -24,10 +24,9 @@ pub async fn send_email(
to_email: &str,
to_username: &str,
html: &str,
settings: &Settings,
) -> LemmyResult<()> {
let email_config = settings.email.clone().ok_or(LemmyErrorType::NoEmailSetup)?;
let domain = settings.hostname.clone();
let email_config = SETTINGS.email.clone().ok_or(LemmyErrorType::NoEmailSetup)?;
let domain = SETTINGS.hostname.clone();
let (smtp_server, smtp_port) = {
let email_and_port = email_config.smtp_server.split(':').collect::<Vec<&str>>();
@ -56,7 +55,7 @@ pub async fn send_email(
Some(to_username.to_string()),
Address::from_str(to_email).expect("email to address isn't valid"),
))
.message_id(Some(format!("<{}@{}>", Uuid::new_v4(), settings.hostname)))
.message_id(Some(format!("<{}@{}>", Uuid::new_v4(), SETTINGS.hostname)))
.subject(subject)
.multipart(MultiPart::alternative_plain_html(
plain_text,

View file

@ -1,3 +1,4 @@
use crate::settings::SETTINGS;
use itertools::Itertools;
use regex::Regex;
use std::sync::LazyLock;
@ -13,8 +14,8 @@ pub struct MentionData {
}
impl MentionData {
pub fn is_local(&self, hostname: &str) -> bool {
hostname.eq(&self.domain)
pub fn is_local(&self) -> bool {
SETTINGS.hostname.eq(&self.domain)
}
pub fn full_name(&self) -> String {
format!("@{}@{}", &self.name, &self.domain)

View file

@ -34,7 +34,10 @@ use lemmy_db_schema::{
traits::Crud,
utils::{get_conn, naive_now, DbPool},
};
use lemmy_utils::{error::LemmyResult, settings::structs::Settings};
use lemmy_utils::{
error::LemmyResult,
settings::{structs::Settings, SETTINGS},
};
use tracing::info;
use url::Url;
@ -43,24 +46,21 @@ pub async fn run_advanced_migrations(
settings: &Settings,
) -> LemmyResult<()> {
let protocol_and_hostname = &settings.get_protocol_and_hostname();
user_updates_2020_04_02(pool, protocol_and_hostname).await?;
community_updates_2020_04_02(pool, protocol_and_hostname).await?;
post_updates_2020_04_03(pool, protocol_and_hostname).await?;
comment_updates_2020_04_03(pool, protocol_and_hostname).await?;
private_message_updates_2020_05_05(pool, protocol_and_hostname).await?;
user_updates_2020_04_02(pool).await?;
community_updates_2020_04_02(pool).await?;
post_updates_2020_04_03(pool).await?;
comment_updates_2020_04_03(pool).await?;
private_message_updates_2020_05_05(pool).await?;
post_thumbnail_url_updates_2020_07_27(pool, protocol_and_hostname).await?;
apub_columns_2021_02_02(pool, settings).await?;
instance_actor_2022_01_28(pool, protocol_and_hostname, settings).await?;
apub_columns_2021_02_02(pool).await?;
instance_actor_2022_01_28(pool, protocol_and_hostname).await?;
regenerate_public_keys_2022_07_05(pool).await?;
initialize_local_site_2022_10_10(pool, settings).await?;
initialize_local_site_2022_10_10(pool).await?;
Ok(())
}
async fn user_updates_2020_04_02(
pool: &mut DbPool<'_>,
protocol_and_hostname: &str,
) -> LemmyResult<()> {
async fn user_updates_2020_04_02(pool: &mut DbPool<'_>) -> LemmyResult<()> {
use lemmy_db_schema::schema::person::dsl::{actor_id, local, person};
let conn = &mut get_conn(pool).await?;
@ -80,7 +80,6 @@ async fn user_updates_2020_04_02(
actor_id: Some(generate_local_apub_endpoint(
EndpointType::Person,
&cperson.name,
protocol_and_hostname,
)?),
private_key: Some(Some(keypair.private_key)),
public_key: Some(keypair.public_key),
@ -96,10 +95,7 @@ async fn user_updates_2020_04_02(
Ok(())
}
async fn community_updates_2020_04_02(
pool: &mut DbPool<'_>,
protocol_and_hostname: &str,
) -> LemmyResult<()> {
async fn community_updates_2020_04_02(pool: &mut DbPool<'_>) -> LemmyResult<()> {
use lemmy_db_schema::schema::community::dsl::{actor_id, community, local};
let conn = &mut get_conn(pool).await?;
@ -114,11 +110,8 @@ async fn community_updates_2020_04_02(
for ccommunity in &incorrect_communities {
let keypair = generate_actor_keypair()?;
let community_actor_id = generate_local_apub_endpoint(
EndpointType::Community,
&ccommunity.name,
protocol_and_hostname,
)?;
let community_actor_id =
generate_local_apub_endpoint(EndpointType::Community, &ccommunity.name)?;
let form = CommunityUpdateForm {
actor_id: Some(community_actor_id.clone()),
@ -136,10 +129,7 @@ async fn community_updates_2020_04_02(
Ok(())
}
async fn post_updates_2020_04_03(
pool: &mut DbPool<'_>,
protocol_and_hostname: &str,
) -> LemmyResult<()> {
async fn post_updates_2020_04_03(pool: &mut DbPool<'_>) -> LemmyResult<()> {
use lemmy_db_schema::schema::post::dsl::{ap_id, local, post};
let conn = &mut get_conn(pool).await?;
@ -153,11 +143,7 @@ async fn post_updates_2020_04_03(
.await?;
for cpost in &incorrect_posts {
let apub_id = generate_local_apub_endpoint(
EndpointType::Post,
&cpost.id.to_string(),
protocol_and_hostname,
)?;
let apub_id = generate_local_apub_endpoint(EndpointType::Post, &cpost.id.to_string())?;
Post::update(
pool,
cpost.id,
@ -174,10 +160,7 @@ async fn post_updates_2020_04_03(
Ok(())
}
async fn comment_updates_2020_04_03(
pool: &mut DbPool<'_>,
protocol_and_hostname: &str,
) -> LemmyResult<()> {
async fn comment_updates_2020_04_03(pool: &mut DbPool<'_>) -> LemmyResult<()> {
use lemmy_db_schema::schema::comment::dsl::{ap_id, comment, local};
let conn = &mut get_conn(pool).await?;
@ -191,11 +174,7 @@ async fn comment_updates_2020_04_03(
.await?;
for ccomment in &incorrect_comments {
let apub_id = generate_local_apub_endpoint(
EndpointType::Comment,
&ccomment.id.to_string(),
protocol_and_hostname,
)?;
let apub_id = generate_local_apub_endpoint(EndpointType::Comment, &ccomment.id.to_string())?;
Comment::update(
pool,
ccomment.id,
@ -212,10 +191,7 @@ async fn comment_updates_2020_04_03(
Ok(())
}
async fn private_message_updates_2020_05_05(
pool: &mut DbPool<'_>,
protocol_and_hostname: &str,
) -> LemmyResult<()> {
async fn private_message_updates_2020_05_05(pool: &mut DbPool<'_>) -> LemmyResult<()> {
use lemmy_db_schema::schema::private_message::dsl::{ap_id, local, private_message};
let conn = &mut get_conn(pool).await?;
@ -229,11 +205,7 @@ async fn private_message_updates_2020_05_05(
.await?;
for cpm in &incorrect_pms {
let apub_id = generate_local_apub_endpoint(
EndpointType::PrivateMessage,
&cpm.id.to_string(),
protocol_and_hostname,
)?;
let apub_id = generate_local_apub_endpoint(EndpointType::PrivateMessage, &cpm.id.to_string())?;
PrivateMessage::update(
pool,
cpm.id,
@ -282,7 +254,7 @@ async fn post_thumbnail_url_updates_2020_07_27(
/// We are setting inbox and follower URLs for local and remote actors alike, because for now
/// all federated instances are also Lemmy and use the same URL scheme.
async fn apub_columns_2021_02_02(pool: &mut DbPool<'_>, settings: &Settings) -> LemmyResult<()> {
async fn apub_columns_2021_02_02(pool: &mut DbPool<'_>) -> LemmyResult<()> {
let conn = &mut get_conn(pool).await?;
info!("Running apub_columns_2021_02_02");
{
@ -294,7 +266,7 @@ async fn apub_columns_2021_02_02(pool: &mut DbPool<'_>, settings: &Settings) ->
for p in &persons {
let inbox_url_ = generate_inbox_url(&p.actor_id)?;
let shared_inbox_url_ = generate_shared_inbox_url(settings)?;
let shared_inbox_url_ = generate_shared_inbox_url()?;
diesel::update(person.find(p.id))
.set((
inbox_url.eq(inbox_url_),
@ -320,7 +292,7 @@ async fn apub_columns_2021_02_02(pool: &mut DbPool<'_>, settings: &Settings) ->
for c in &communities {
let followers_url_ = generate_followers_url(&c.actor_id)?;
let inbox_url_ = generate_inbox_url(&c.actor_id)?;
let shared_inbox_url_ = generate_shared_inbox_url(settings)?;
let shared_inbox_url_ = generate_shared_inbox_url()?;
diesel::update(community.find(c.id))
.set((
followers_url.eq(followers_url_),
@ -342,7 +314,6 @@ async fn apub_columns_2021_02_02(pool: &mut DbPool<'_>, settings: &Settings) ->
async fn instance_actor_2022_01_28(
pool: &mut DbPool<'_>,
protocol_and_hostname: &str,
settings: &Settings,
) -> LemmyResult<()> {
info!("Running instance_actor_2021_09_29");
if let Ok(site_view) = SiteView::read_local(pool).await {
@ -356,7 +327,7 @@ async fn instance_actor_2022_01_28(
let site_form = SiteUpdateForm {
actor_id: Some(actor_id.clone().into()),
last_refreshed_at: Some(naive_now()),
inbox_url: Some(generate_shared_inbox_url(settings)?),
inbox_url: Some(generate_shared_inbox_url()?),
private_key: Some(Some(key_pair.private_key)),
public_key: Some(key_pair.public_key),
..Default::default()
@ -427,10 +398,7 @@ async fn regenerate_public_keys_2022_07_05(pool: &mut DbPool<'_>) -> LemmyResult
///
/// If a site already exists, the DB migration should generate a local_site row.
/// This will only be run for brand new sites.
async fn initialize_local_site_2022_10_10(
pool: &mut DbPool<'_>,
settings: &Settings,
) -> LemmyResult<()> {
async fn initialize_local_site_2022_10_10(pool: &mut DbPool<'_>) -> LemmyResult<()> {
info!("Running initialize_local_site_2022_10_10");
// Check to see if local_site exists
@ -439,26 +407,23 @@ async fn initialize_local_site_2022_10_10(
}
info!("No Local Site found, creating it.");
let domain = settings
let domain = SETTINGS
.get_hostname_without_port()
.expect("must have domain");
// Upsert this to the instance table
let instance = Instance::read_or_create(pool, domain).await?;
if let Some(setup) = &settings.setup {
if let Some(setup) = &SETTINGS.setup {
let person_keypair = generate_actor_keypair()?;
let person_actor_id = generate_local_apub_endpoint(
EndpointType::Person,
&setup.admin_username,
&settings.get_protocol_and_hostname(),
)?;
let person_actor_id =
generate_local_apub_endpoint(EndpointType::Person, &setup.admin_username)?;
// Register the user if there's a site setup
let person_form = PersonInsertForm {
actor_id: Some(person_actor_id.clone()),
inbox_url: Some(generate_inbox_url(&person_actor_id)?),
shared_inbox_url: Some(generate_shared_inbox_url(settings)?),
shared_inbox_url: Some(generate_shared_inbox_url()?),
private_key: Some(person_keypair.private_key),
..PersonInsertForm::new(
setup.admin_username.clone(),
@ -478,9 +443,9 @@ async fn initialize_local_site_2022_10_10(
// Add an entry for the site table
let site_key_pair = generate_actor_keypair()?;
let site_actor_id = Url::parse(&settings.get_protocol_and_hostname())?;
let site_actor_id = Url::parse(&SETTINGS.get_protocol_and_hostname())?;
let name = settings
let name = SETTINGS
.setup
.clone()
.map(|s| s.site_name)
@ -488,7 +453,7 @@ async fn initialize_local_site_2022_10_10(
let site_form = SiteInsertForm {
actor_id: Some(site_actor_id.clone().into()),
last_refreshed_at: Some(naive_now()),
inbox_url: Some(generate_shared_inbox_url(settings)?),
inbox_url: Some(generate_shared_inbox_url()?),
private_key: Some(site_key_pair.private_key),
public_key: Some(site_key_pair.public_key),
@ -498,7 +463,7 @@ async fn initialize_local_site_2022_10_10(
// Finally create the local_site row
let local_site_form = LocalSiteInsertForm {
site_setup: Some(settings.setup.is_some()),
site_setup: Some(SETTINGS.setup.is_some()),
..LocalSiteInsertForm::new(site.id)
};
let local_site = LocalSite::create(pool, &local_site_form).await?;