Remove enable nsfw (#5017)

* Remove `local_site.enable_nsfw` in favor of `site.content_warning` (fixes #4627)

* cleanup usage of SiteView::read_local

* test

* uppercase
This commit is contained in:
Nutomic 2024-09-16 17:18:16 +02:00 committed by GitHub
parent 5febf2b8fb
commit 6454a4d43d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
35 changed files with 126 additions and 153 deletions

View file

@ -2,8 +2,11 @@ use crate::{build_totp_2fa, generate_totp_2fa_secret};
use activitypub_federation::config::Data; use activitypub_federation::config::Data;
use actix_web::web::Json; use actix_web::web::Json;
use lemmy_api_common::{context::LemmyContext, person::GenerateTotpSecretResponse}; use lemmy_api_common::{context::LemmyContext, person::GenerateTotpSecretResponse};
use lemmy_db_schema::source::local_user::{LocalUser, LocalUserUpdateForm}; use lemmy_db_schema::source::{
use lemmy_db_views::structs::{LocalUserView, SiteView}; local_user::{LocalUser, LocalUserUpdateForm},
site::Site,
};
use lemmy_db_views::structs::LocalUserView;
use lemmy_utils::error::{LemmyErrorType, LemmyResult}; use lemmy_utils::error::{LemmyErrorType, LemmyResult};
/// Generate a new secret for two-factor-authentication. Afterwards you need to call [toggle_totp] /// Generate a new secret for two-factor-authentication. Afterwards you need to call [toggle_totp]
@ -13,17 +16,14 @@ pub async fn generate_totp_secret(
local_user_view: LocalUserView, local_user_view: LocalUserView,
context: Data<LemmyContext>, context: Data<LemmyContext>,
) -> LemmyResult<Json<GenerateTotpSecretResponse>> { ) -> LemmyResult<Json<GenerateTotpSecretResponse>> {
let site_view = SiteView::read_local(&mut context.pool()) let site = Site::read_local(&mut context.pool()).await?;
.await?
.ok_or(LemmyErrorType::LocalSiteNotSetup)?;
if local_user_view.local_user.totp_2fa_enabled { if local_user_view.local_user.totp_2fa_enabled {
return Err(LemmyErrorType::TotpAlreadyEnabled)?; return Err(LemmyErrorType::TotpAlreadyEnabled)?;
} }
let secret = generate_totp_2fa_secret(); let secret = generate_totp_2fa_secret();
let secret_url = let secret_url = build_totp_2fa(&site.name, &local_user_view.person.name, &secret)?.get_url();
build_totp_2fa(&site_view.site.name, &local_user_view.person.name, &secret)?.get_url();
let local_user_form = LocalUserUpdateForm { let local_user_form = LocalUserUpdateForm {
totp_2fa_secret: Some(Some(secret)), totp_2fa_secret: Some(Some(secret)),

View file

@ -24,9 +24,7 @@ pub async fn login(
req: HttpRequest, req: HttpRequest,
context: Data<LemmyContext>, context: Data<LemmyContext>,
) -> LemmyResult<Json<LoginResponse>> { ) -> LemmyResult<Json<LoginResponse>> {
let site_view = SiteView::read_local(&mut context.pool()) let site_view = SiteView::read_local(&mut context.pool()).await?;
.await?
.ok_or(LemmyErrorType::LocalSiteNotSetup)?;
// Fetch that username / email // Fetch that username / email
let username_or_email = data.username_or_email.clone(); let username_or_email = data.username_or_email.clone();

View file

@ -20,9 +20,7 @@ pub async fn reset_password(
.await? .await?
.ok_or(LemmyErrorType::IncorrectLogin)?; .ok_or(LemmyErrorType::IncorrectLogin)?;
let site_view = SiteView::read_local(&mut context.pool()) let site_view = SiteView::read_local(&mut context.pool()).await?;
.await?
.ok_or(LemmyErrorType::LocalSiteNotSetup)?;
check_email_verified(&local_user_view, &site_view)?; check_email_verified(&local_user_view, &site_view)?;
// Email the pure token to the user. // Email the pure token to the user.

View file

@ -36,9 +36,7 @@ pub async fn save_user_settings(
context: Data<LemmyContext>, context: Data<LemmyContext>,
local_user_view: LocalUserView, local_user_view: LocalUserView,
) -> LemmyResult<Json<SuccessResponse>> { ) -> LemmyResult<Json<SuccessResponse>> {
let site_view = SiteView::read_local(&mut context.pool()) let site_view = SiteView::read_local(&mut context.pool()).await?;
.await?
.ok_or(LemmyErrorType::LocalSiteNotSetup)?;
let slur_regex = local_site_to_slur_regex(&site_view.local_site); let slur_regex = local_site_to_slur_regex(&site_view.local_site);
let url_blocklist = get_url_blocklist(&context).await?; let url_blocklist = get_url_blocklist(&context).await?;

View file

@ -16,9 +16,7 @@ pub async fn verify_email(
data: Json<VerifyEmail>, data: Json<VerifyEmail>,
context: Data<LemmyContext>, context: Data<LemmyContext>,
) -> LemmyResult<Json<SuccessResponse>> { ) -> LemmyResult<Json<SuccessResponse>> {
let site_view = SiteView::read_local(&mut context.pool()) let site_view = SiteView::read_local(&mut context.pool()).await?;
.await?
.ok_or(LemmyErrorType::LocalSiteNotSetup)?;
let token = data.token.clone(); let token = data.token.clone();
let verification = EmailVerification::read_for_token(&mut context.pool(), &token) let verification = EmailVerification::read_for_token(&mut context.pool(), &token)
.await? .await?

View file

@ -5,15 +5,13 @@ use lemmy_api_common::{
utils::build_federated_instances, utils::build_federated_instances,
}; };
use lemmy_db_views::structs::SiteView; use lemmy_db_views::structs::SiteView;
use lemmy_utils::{error::LemmyResult, LemmyErrorType}; use lemmy_utils::error::LemmyResult;
#[tracing::instrument(skip(context))] #[tracing::instrument(skip(context))]
pub async fn get_federated_instances( pub async fn get_federated_instances(
context: Data<LemmyContext>, context: Data<LemmyContext>,
) -> LemmyResult<Json<GetFederatedInstancesResponse>> { ) -> LemmyResult<Json<GetFederatedInstancesResponse>> {
let site_view = SiteView::read_local(&mut context.pool()) let site_view = SiteView::read_local(&mut context.pool()).await?;
.await?
.ok_or(LemmyErrorType::LocalSiteNotSetup)?;
let federated_instances = let federated_instances =
build_federated_instances(&site_view.local_site, &mut context.pool()).await?; build_federated_instances(&site_view.local_site, &mut context.pool()).await?;

View file

@ -55,9 +55,7 @@ pub async fn leave_admin(
ModAdd::create(&mut context.pool(), &form).await?; ModAdd::create(&mut context.pool(), &form).await?;
// Reread site and admins // Reread site and admins
let site_view = SiteView::read_local(&mut context.pool()) let site_view = SiteView::read_local(&mut context.pool()).await?;
.await?
.ok_or(LemmyErrorType::LocalSiteNotSetup)?;
let admins = PersonView::admins(&mut context.pool()).await?; let admins = PersonView::admins(&mut context.pool()).await?;
let all_languages = Language::read_all(&mut context.pool()).await?; let all_languages = Language::read_all(&mut context.pool()).await?;

View file

@ -3,7 +3,7 @@ use crate::{
lemmy_db_schema::traits::Crud, lemmy_db_schema::traits::Crud,
post::{LinkMetadata, OpenGraphData}, post::{LinkMetadata, OpenGraphData},
send_activity::{ActivityChannel, SendActivityData}, send_activity::{ActivityChannel, SendActivityData},
utils::{local_site_opt_to_sensitive, proxy_image_link}, utils::proxy_image_link,
}; };
use activitypub_federation::config::Data; use activitypub_federation::config::Data;
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
@ -13,8 +13,8 @@ use lemmy_db_schema::{
newtypes::DbUrl, newtypes::DbUrl,
source::{ source::{
images::{ImageDetailsForm, LocalImage, LocalImageForm}, images::{ImageDetailsForm, LocalImage, LocalImageForm},
local_site::LocalSite,
post::{Post, PostUpdateForm}, post::{Post, PostUpdateForm},
site::Site,
}, },
}; };
use lemmy_utils::{ use lemmy_utils::{
@ -130,7 +130,6 @@ pub async fn generate_post_link_metadata(
post: Post, post: Post,
custom_thumbnail: Option<Url>, custom_thumbnail: Option<Url>,
send_activity: impl FnOnce(Post) -> Option<SendActivityData> + Send + 'static, send_activity: impl FnOnce(Post) -> Option<SendActivityData> + Send + 'static,
local_site: Option<LocalSite>,
context: Data<LemmyContext>, context: Data<LemmyContext>,
) -> LemmyResult<()> { ) -> LemmyResult<()> {
let metadata = match &post.url { let metadata = match &post.url {
@ -144,7 +143,8 @@ pub async fn generate_post_link_metadata(
.is_some_and(|content_type| content_type.starts_with("image")); .is_some_and(|content_type| content_type.starts_with("image"));
// Decide if we are allowed to generate local thumbnail // Decide if we are allowed to generate local thumbnail
let allow_sensitive = local_site_opt_to_sensitive(&local_site); let site = Site::read_local(&mut context.pool()).await?;
let allow_sensitive = site.content_warning.is_some();
let allow_generate_thumbnail = allow_sensitive || !post.nsfw; let allow_generate_thumbnail = allow_sensitive || !post.nsfw;
let image_url = if is_image_post { let image_url = if is_image_post {

View file

@ -538,13 +538,6 @@ pub fn local_site_opt_to_slur_regex(local_site: &Option<LocalSite>) -> Option<Re
.unwrap_or(None) .unwrap_or(None)
} }
pub fn local_site_opt_to_sensitive(local_site: &Option<LocalSite>) -> bool {
local_site
.as_ref()
.map(|site| site.enable_nsfw)
.unwrap_or(false)
}
pub async fn get_url_blocklist(context: &LemmyContext) -> LemmyResult<RegexSet> { pub async fn get_url_blocklist(context: &LemmyContext) -> LemmyResult<RegexSet> {
static URL_BLOCKLIST: LazyLock<Cache<(), RegexSet>> = LazyLock::new(|| { static URL_BLOCKLIST: LazyLock<Cache<(), RegexSet>> = LazyLock::new(|| {
Cache::builder() Cache::builder()

View file

@ -47,9 +47,7 @@ pub async fn create_community(
context: Data<LemmyContext>, context: Data<LemmyContext>,
local_user_view: LocalUserView, local_user_view: LocalUserView,
) -> LemmyResult<Json<CommunityResponse>> { ) -> LemmyResult<Json<CommunityResponse>> {
let site_view = SiteView::read_local(&mut context.pool()) let site_view = SiteView::read_local(&mut context.pool()).await?;
.await?
.ok_or(LemmyErrorType::LocalSiteNotSetup)?;
let local_site = site_view.local_site; let local_site = site_view.local_site;
if local_site.community_creation_admin_only && is_admin(&local_user_view).is_err() { if local_site.community_creation_admin_only && is_admin(&local_user_view).is_err() {

View file

@ -6,7 +6,7 @@ use lemmy_api_common::{
}; };
use lemmy_db_views::structs::{LocalUserView, SiteView}; use lemmy_db_views::structs::{LocalUserView, SiteView};
use lemmy_db_views_actor::community_view::CommunityQuery; use lemmy_db_views_actor::community_view::CommunityQuery;
use lemmy_utils::{error::LemmyResult, LemmyErrorType}; use lemmy_utils::error::LemmyResult;
#[tracing::instrument(skip(context))] #[tracing::instrument(skip(context))]
pub async fn list_communities( pub async fn list_communities(
@ -14,9 +14,7 @@ pub async fn list_communities(
context: Data<LemmyContext>, context: Data<LemmyContext>,
local_user_view: Option<LocalUserView>, local_user_view: Option<LocalUserView>,
) -> LemmyResult<Json<ListCommunitiesResponse>> { ) -> LemmyResult<Json<ListCommunitiesResponse>> {
let local_site = SiteView::read_local(&mut context.pool()) let local_site = SiteView::read_local(&mut context.pool()).await?;
.await?
.ok_or(LemmyErrorType::LocalSiteNotSetup)?;
let is_admin = local_user_view let is_admin = local_user_view
.as_ref() .as_ref()
.map(|luv| is_admin(luv).is_ok()) .map(|luv| is_admin(luv).is_ok())

View file

@ -149,7 +149,6 @@ pub async fn create_post(
inserted_post.clone(), inserted_post.clone(),
custom_thumbnail.map(Into::into), custom_thumbnail.map(Into::into),
|post| Some(SendActivityData::CreatePost(post)), |post| Some(SendActivityData::CreatePost(post)),
Some(local_site),
context.reset_request_count(), context.reset_request_count(),
) )
.await?; .await?;

View file

@ -21,9 +21,7 @@ pub async fn get_post(
context: Data<LemmyContext>, context: Data<LemmyContext>,
local_user_view: Option<LocalUserView>, local_user_view: Option<LocalUserView>,
) -> LemmyResult<Json<GetPostResponse>> { ) -> LemmyResult<Json<GetPostResponse>> {
let local_site = SiteView::read_local(&mut context.pool()) let local_site = SiteView::read_local(&mut context.pool()).await?;
.await?
.ok_or(LemmyErrorType::LocalSiteNotSetup)?;
check_private_instance(&local_user_view, &local_site.local_site)?; check_private_instance(&local_user_view, &local_site.local_site)?;

View file

@ -129,7 +129,6 @@ pub async fn update_post(
updated_post.clone(), updated_post.clone(),
custom_thumbnail.flatten().map(Into::into), custom_thumbnail.flatten().map(Into::into),
|post| Some(SendActivityData::UpdatePost(post)), |post| Some(SendActivityData::UpdatePost(post)),
Some(local_site),
context.reset_request_count(), context.reset_request_count(),
) )
.await?; .await?;

View file

@ -92,7 +92,6 @@ pub async fn create_site(
site_setup: Some(true), site_setup: Some(true),
enable_downvotes: data.enable_downvotes, enable_downvotes: data.enable_downvotes,
registration_mode: data.registration_mode, registration_mode: data.registration_mode,
enable_nsfw: data.enable_nsfw,
community_creation_admin_only: data.community_creation_admin_only, community_creation_admin_only: data.community_creation_admin_only,
require_email_verification: data.require_email_verification, require_email_verification: data.require_email_verification,
application_question: diesel_string_update(data.application_question.as_deref()), application_question: diesel_string_update(data.application_question.as_deref()),
@ -133,9 +132,7 @@ pub async fn create_site(
LocalSiteRateLimit::update(&mut context.pool(), &local_site_rate_limit_form).await?; LocalSiteRateLimit::update(&mut context.pool(), &local_site_rate_limit_form).await?;
let site_view = SiteView::read_local(&mut context.pool()) let site_view = SiteView::read_local(&mut context.pool()).await?;
.await?
.ok_or(LemmyErrorType::LocalSiteNotSetup)?;
let new_taglines = data.taglines.clone(); let new_taglines = data.taglines.clone();
let taglines = Tagline::replace(&mut context.pool(), local_site.id, new_taglines).await?; let taglines = Tagline::replace(&mut context.pool(), local_site.id, new_taglines).await?;

View file

@ -37,9 +37,7 @@ pub async fn get_site(
// This data is independent from the user account so we can cache it across requests // This data is independent from the user account so we can cache it across requests
let mut site_response = CACHE let mut site_response = CACHE
.try_get_with::<_, LemmyError>((), async { .try_get_with::<_, LemmyError>((), async {
let site_view = SiteView::read_local(&mut context.pool()) let site_view = SiteView::read_local(&mut context.pool()).await?;
.await?
.ok_or(LemmyErrorType::LocalSiteNotSetup)?;
let admins = PersonView::admins(&mut context.pool()).await?; let admins = PersonView::admins(&mut context.pool()).await?;
let all_languages = Language::read_all(&mut context.pool()).await?; let all_languages = Language::read_all(&mut context.pool()).await?;
let discussion_languages = SiteLanguage::read_local_raw(&mut context.pool()).await?; let discussion_languages = SiteLanguage::read_local_raw(&mut context.pool()).await?;

View file

@ -52,9 +52,7 @@ pub async fn update_site(
context: Data<LemmyContext>, context: Data<LemmyContext>,
local_user_view: LocalUserView, local_user_view: LocalUserView,
) -> LemmyResult<Json<SiteResponse>> { ) -> LemmyResult<Json<SiteResponse>> {
let site_view = SiteView::read_local(&mut context.pool()) let site_view = SiteView::read_local(&mut context.pool()).await?;
.await?
.ok_or(LemmyErrorType::LocalSiteNotSetup)?;
let local_site = site_view.local_site; let local_site = site_view.local_site;
let site = site_view.site; let site = site_view.site;
@ -103,7 +101,6 @@ pub async fn update_site(
let local_site_form = LocalSiteUpdateForm { let local_site_form = LocalSiteUpdateForm {
enable_downvotes: data.enable_downvotes, enable_downvotes: data.enable_downvotes,
registration_mode: data.registration_mode, registration_mode: data.registration_mode,
enable_nsfw: data.enable_nsfw,
community_creation_admin_only: data.community_creation_admin_only, community_creation_admin_only: data.community_creation_admin_only,
require_email_verification: data.require_email_verification, require_email_verification: data.require_email_verification,
application_question: diesel_string_update(data.application_question.as_deref()), application_question: diesel_string_update(data.application_question.as_deref()),
@ -191,9 +188,7 @@ pub async fn update_site(
let new_taglines = data.taglines.clone(); let new_taglines = data.taglines.clone();
let taglines = Tagline::replace(&mut context.pool(), local_site.id, new_taglines).await?; let taglines = Tagline::replace(&mut context.pool(), local_site.id, new_taglines).await?;
let site_view = SiteView::read_local(&mut context.pool()) let site_view = SiteView::read_local(&mut context.pool()).await?;
.await?
.ok_or(LemmyErrorType::LocalSiteNotSetup)?;
let rate_limit_config = let rate_limit_config =
local_site_rate_limit_to_rate_limit_config(&site_view.local_site_rate_limit); local_site_rate_limit_to_rate_limit_config(&site_view.local_site_rate_limit);

View file

@ -45,9 +45,7 @@ pub async fn register(
req: HttpRequest, req: HttpRequest,
context: Data<LemmyContext>, context: Data<LemmyContext>,
) -> LemmyResult<Json<LoginResponse>> { ) -> LemmyResult<Json<LoginResponse>> {
let site_view = SiteView::read_local(&mut context.pool()) let site_view = SiteView::read_local(&mut context.pool()).await?;
.await?
.ok_or(LemmyErrorType::LocalSiteNotSetup)?;
let local_site = site_view.local_site; let local_site = site_view.local_site;
let require_registration_application = let require_registration_application =
local_site.registration_mode == RegistrationMode::RequireApplication; local_site.registration_mode == RegistrationMode::RequireApplication;

View file

@ -22,7 +22,6 @@ use lemmy_db_schema::{
traits::Crud, traits::Crud,
utils::DbPool, utils::DbPool,
}; };
use lemmy_db_views::structs::SiteView;
use lemmy_utils::{ use lemmy_utils::{
error::{LemmyError, LemmyResult}, error::{LemmyError, LemmyResult},
LemmyErrorType, LemmyErrorType,
@ -142,13 +141,7 @@ pub(crate) async fn send_ban_from_site(
expires: Option<i64>, expires: Option<i64>,
context: Data<LemmyContext>, context: Data<LemmyContext>,
) -> LemmyResult<()> { ) -> LemmyResult<()> {
let site = SiteOrCommunity::Site( let site = SiteOrCommunity::Site(Site::read_local(&mut context.pool()).await?.into());
SiteView::read_local(&mut context.pool())
.await?
.ok_or(LemmyErrorType::LocalSiteNotSetup)?
.site
.into(),
);
let expires = check_expire_time(expires)?; let expires = check_expire_time(expires)?;
// if the action affects a local user, federate to other instances // if the action affects a local user, federate to other instances

View file

@ -23,9 +23,7 @@ pub async fn list_posts(
context: Data<LemmyContext>, context: Data<LemmyContext>,
local_user_view: Option<LocalUserView>, local_user_view: Option<LocalUserView>,
) -> LemmyResult<Json<GetPostsResponse>> { ) -> LemmyResult<Json<GetPostsResponse>> {
let local_site = SiteView::read_local(&mut context.pool()) let local_site = SiteView::read_local(&mut context.pool()).await?;
.await?
.ok_or(LemmyErrorType::LocalSiteNotSetup)?;
check_private_instance(&local_user_view, &local_site.local_site)?; check_private_instance(&local_user_view, &local_site.local_site)?;

View file

@ -26,9 +26,7 @@ pub async fn read_person(
Err(LemmyErrorType::NoIdGiven)? Err(LemmyErrorType::NoIdGiven)?
} }
let local_site = SiteView::read_local(&mut context.pool()) let local_site = SiteView::read_local(&mut context.pool()).await?;
.await?
.ok_or(LemmyErrorType::LocalSiteNotSetup)?;
check_private_instance(&local_user_view, &local_site.local_site)?; check_private_instance(&local_user_view, &local_site.local_site)?;

View file

@ -13,7 +13,7 @@ use lemmy_db_views::{
structs::{LocalUserView, SiteView}, structs::{LocalUserView, SiteView},
}; };
use lemmy_db_views_actor::{community_view::CommunityQuery, person_view::PersonQuery}; use lemmy_db_views_actor::{community_view::CommunityQuery, person_view::PersonQuery};
use lemmy_utils::{error::LemmyResult, LemmyErrorType}; use lemmy_utils::error::LemmyResult;
#[tracing::instrument(skip(context))] #[tracing::instrument(skip(context))]
pub async fn search( pub async fn search(
@ -21,9 +21,7 @@ pub async fn search(
context: Data<LemmyContext>, context: Data<LemmyContext>,
local_user_view: Option<LocalUserView>, local_user_view: Option<LocalUserView>,
) -> LemmyResult<Json<SearchResponse>> { ) -> LemmyResult<Json<SearchResponse>> {
let local_site = SiteView::read_local(&mut context.pool()) let local_site = SiteView::read_local(&mut context.pool()).await?;
.await?
.ok_or(LemmyErrorType::LocalSiteNotSetup)?;
check_private_instance(&local_user_view, &local_site.local_site)?; check_private_instance(&local_user_view, &local_site.local_site)?;

View file

@ -18,12 +18,9 @@ use activitypub_federation::{
}; };
use futures::future::join_all; use futures::future::join_all;
use lemmy_api_common::{context::LemmyContext, utils::generate_outbox_url}; use lemmy_api_common::{context::LemmyContext, utils::generate_outbox_url};
use lemmy_db_schema::{utils::FETCH_LIMIT_MAX, SortType}; use lemmy_db_schema::{source::site::Site, utils::FETCH_LIMIT_MAX, SortType};
use lemmy_db_views::{post_view::PostQuery, structs::SiteView}; use lemmy_db_views::post_view::PostQuery;
use lemmy_utils::{ use lemmy_utils::error::{LemmyError, LemmyResult};
error::{LemmyError, LemmyResult},
LemmyErrorType,
};
use url::Url; use url::Url;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
@ -38,10 +35,7 @@ impl Collection for ApubCommunityOutbox {
#[tracing::instrument(skip_all)] #[tracing::instrument(skip_all)]
async fn read_local(owner: &Self::Owner, data: &Data<Self::DataType>) -> LemmyResult<Self::Kind> { async fn read_local(owner: &Self::Owner, data: &Data<Self::DataType>) -> LemmyResult<Self::Kind> {
let site = SiteView::read_local(&mut data.pool()) let site = Site::read_local(&mut data.pool()).await?;
.await?
.ok_or(LemmyErrorType::LocalSiteNotSetup)?
.site;
let post_views = PostQuery { let post_views = PostQuery {
community_id: Some(owner.id), community_id: Some(owner.id),

View file

@ -6,16 +6,12 @@ use crate::{
use activitypub_federation::{config::Data, traits::Object}; use activitypub_federation::{config::Data, traits::Object};
use actix_web::HttpResponse; use actix_web::HttpResponse;
use lemmy_api_common::context::LemmyContext; use lemmy_api_common::context::LemmyContext;
use lemmy_db_views::structs::SiteView; use lemmy_db_schema::source::site::Site;
use lemmy_utils::{error::LemmyResult, LemmyErrorType}; use lemmy_utils::error::LemmyResult;
use url::Url; use url::Url;
pub(crate) async fn get_apub_site_http(context: Data<LemmyContext>) -> LemmyResult<HttpResponse> { pub(crate) async fn get_apub_site_http(context: Data<LemmyContext>) -> LemmyResult<HttpResponse> {
let site: ApubSite = SiteView::read_local(&mut context.pool()) let site: ApubSite = Site::read_local(&mut context.pool()).await?.into();
.await?
.ok_or(LemmyErrorType::LocalSiteNotSetup)?
.site
.into();
let apub = site.into_json(&context).await?; let apub = site.into_json(&context).await?;
create_apub_response(&apub) create_apub_response(&apub)

View file

@ -270,9 +270,9 @@ impl Object for ApubPost {
// Generates a post thumbnail in background task, because some sites can be very slow to // Generates a post thumbnail in background task, because some sites can be very slow to
// respond. // respond.
spawn_try_task(async move { spawn_try_task(
generate_post_link_metadata(post_, None, |_| None, local_site, context_).await async move { generate_post_link_metadata(post_, None, |_| None, context_).await },
}); );
Ok(post.into()) Ok(post.into())
} }

View file

@ -1,6 +1,6 @@
use crate::{ use crate::{
newtypes::{DbUrl, InstanceId, SiteId}, newtypes::{DbUrl, InstanceId, SiteId},
schema::site, schema::{local_site, site},
source::{ source::{
actor_language::SiteLanguage, actor_language::SiteLanguage,
site::{Site, SiteInsertForm, SiteUpdateForm}, site::{Site, SiteInsertForm, SiteUpdateForm},
@ -10,6 +10,7 @@ use crate::{
}; };
use diesel::{dsl::insert_into, result::Error, ExpressionMethods, OptionalExtension, QueryDsl}; use diesel::{dsl::insert_into, result::Error, ExpressionMethods, OptionalExtension, QueryDsl};
use diesel_async::RunQueryDsl; use diesel_async::RunQueryDsl;
use lemmy_utils::{error::LemmyResult, LemmyErrorType};
use url::Url; use url::Url;
#[async_trait] #[async_trait]
@ -102,4 +103,18 @@ impl Site {
url.set_query(None); url.set_query(None);
url url
} }
pub async fn read_local(pool: &mut DbPool<'_>) -> LemmyResult<Self> {
let conn = &mut get_conn(pool).await?;
Ok(
site::table
.inner_join(local_site::table)
.select(site::all_columns)
.first(conn)
.await
.optional()?
.ok_or(LemmyErrorType::LocalSiteNotSetup)?,
)
}
} }

View file

@ -370,7 +370,6 @@ diesel::table! {
site_id -> Int4, site_id -> Int4,
site_setup -> Bool, site_setup -> Bool,
enable_downvotes -> Bool, enable_downvotes -> Bool,
enable_nsfw -> Bool,
community_creation_admin_only -> Bool, community_creation_admin_only -> Bool,
require_email_verification -> Bool, require_email_verification -> Bool,
application_question -> Nullable<Text>, application_question -> Nullable<Text>,

View file

@ -29,8 +29,6 @@ pub struct LocalSite {
pub site_setup: bool, pub site_setup: bool,
/// Whether downvotes are enabled. /// Whether downvotes are enabled.
pub enable_downvotes: bool, pub enable_downvotes: bool,
/// Whether NSFW is enabled.
pub enable_nsfw: bool,
/// Whether only admins can create communities. /// Whether only admins can create communities.
pub community_creation_admin_only: bool, pub community_creation_admin_only: bool,
/// Whether emails are required. /// Whether emails are required.
@ -81,7 +79,6 @@ pub struct LocalSiteInsertForm {
pub site_id: SiteId, pub site_id: SiteId,
pub site_setup: Option<bool>, pub site_setup: Option<bool>,
pub enable_downvotes: Option<bool>, pub enable_downvotes: Option<bool>,
pub enable_nsfw: Option<bool>,
pub community_creation_admin_only: Option<bool>, pub community_creation_admin_only: Option<bool>,
pub require_email_verification: Option<bool>, pub require_email_verification: Option<bool>,
pub application_question: Option<String>, pub application_question: Option<String>,
@ -109,7 +106,6 @@ pub struct LocalSiteInsertForm {
pub struct LocalSiteUpdateForm { pub struct LocalSiteUpdateForm {
pub site_setup: Option<bool>, pub site_setup: Option<bool>,
pub enable_downvotes: Option<bool>, pub enable_downvotes: Option<bool>,
pub enable_nsfw: Option<bool>,
pub community_creation_admin_only: Option<bool>, pub community_creation_admin_only: Option<bool>,
pub require_email_verification: Option<bool>, pub require_email_verification: Option<bool>,
pub application_question: Option<Option<String>>, pub application_question: Option<Option<String>>,

View file

@ -1,14 +1,16 @@
use crate::structs::SiteView; use crate::structs::SiteView;
use diesel::{result::Error, ExpressionMethods, JoinOnDsl, OptionalExtension, QueryDsl}; use diesel::{ExpressionMethods, JoinOnDsl, OptionalExtension, QueryDsl};
use diesel_async::RunQueryDsl; use diesel_async::RunQueryDsl;
use lemmy_db_schema::{ use lemmy_db_schema::{
schema::{local_site, local_site_rate_limit, site, site_aggregates}, schema::{local_site, local_site_rate_limit, site, site_aggregates},
utils::{get_conn, DbPool}, utils::{get_conn, DbPool},
}; };
use lemmy_utils::{error::LemmyResult, LemmyErrorType};
impl SiteView { impl SiteView {
pub async fn read_local(pool: &mut DbPool<'_>) -> Result<Option<Self>, Error> { pub async fn read_local(pool: &mut DbPool<'_>) -> LemmyResult<Self> {
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
Ok(
site::table site::table
.inner_join(local_site::table) .inner_join(local_site::table)
.inner_join( .inner_join(
@ -23,6 +25,8 @@ impl SiteView {
)) ))
.first(conn) .first(conn)
.await .await
.optional() .optional()?
.ok_or(LemmyErrorType::LocalSiteNotSetup)?,
)
} }
} }

View file

@ -151,9 +151,7 @@ async fn get_feed_data(
limit: i64, limit: i64,
page: i64, page: i64,
) -> LemmyResult<HttpResponse> { ) -> LemmyResult<HttpResponse> {
let site_view = SiteView::read_local(&mut context.pool()) let site_view = SiteView::read_local(&mut context.pool()).await?;
.await?
.ok_or(LemmyErrorType::LocalSiteNotSetup)?;
check_private_instance(&None, &site_view.local_site)?; check_private_instance(&None, &site_view.local_site)?;
@ -258,9 +256,7 @@ async fn get_feed_user(
page: &i64, page: &i64,
user_name: &str, user_name: &str,
) -> LemmyResult<Channel> { ) -> LemmyResult<Channel> {
let site_view = SiteView::read_local(&mut context.pool()) let site_view = SiteView::read_local(&mut context.pool()).await?;
.await?
.ok_or(LemmyErrorType::LocalSiteNotSetup)?;
let person = Person::read_from_name(&mut context.pool(), user_name, false) let person = Person::read_from_name(&mut context.pool(), user_name, false)
.await? .await?
.ok_or(LemmyErrorType::CouldntFindPerson)?; .ok_or(LemmyErrorType::CouldntFindPerson)?;
@ -298,9 +294,7 @@ async fn get_feed_community(
page: &i64, page: &i64,
community_name: &str, community_name: &str,
) -> LemmyResult<Channel> { ) -> LemmyResult<Channel> {
let site_view = SiteView::read_local(&mut context.pool()) let site_view = SiteView::read_local(&mut context.pool()).await?;
.await?
.ok_or(LemmyErrorType::LocalSiteNotSetup)?;
let community = Community::read_from_name(&mut context.pool(), community_name, false) let community = Community::read_from_name(&mut context.pool(), community_name, false)
.await? .await?
.ok_or(LemmyErrorType::CouldntFindCommunity)?; .ok_or(LemmyErrorType::CouldntFindCommunity)?;
@ -345,9 +339,7 @@ async fn get_feed_front(
page: &i64, page: &i64,
jwt: &str, jwt: &str,
) -> LemmyResult<Channel> { ) -> LemmyResult<Channel> {
let site_view = SiteView::read_local(&mut context.pool()) let site_view = SiteView::read_local(&mut context.pool()).await?;
.await?
.ok_or(LemmyErrorType::LocalSiteNotSetup)?;
let local_user = local_user_view_from_jwt(jwt, context).await?; let local_user = local_user_view_from_jwt(jwt, context).await?;
check_private_instance(&Some(local_user.clone()), &site_view.local_site)?; check_private_instance(&Some(local_user.clone()), &site_view.local_site)?;
@ -382,9 +374,7 @@ async fn get_feed_front(
#[tracing::instrument(skip_all)] #[tracing::instrument(skip_all)]
async fn get_feed_inbox(context: &LemmyContext, jwt: &str) -> LemmyResult<Channel> { async fn get_feed_inbox(context: &LemmyContext, jwt: &str) -> LemmyResult<Channel> {
let site_view = SiteView::read_local(&mut context.pool()) let site_view = SiteView::read_local(&mut context.pool()).await?;
.await?
.ok_or(LemmyErrorType::LocalSiteNotSetup)?;
let local_user = local_user_view_from_jwt(jwt, context).await?; let local_user = local_user_view_from_jwt(jwt, context).await?;
let person_id = local_user.local_user.person_id; let person_id = local_user.local_user.person_id;
let show_bot_accounts = local_user.local_user.show_bot_accounts; let show_bot_accounts = local_user.local_user.show_bot_accounts;

View file

@ -1,11 +1,10 @@
use actix_web::{error::ErrorBadRequest, web, Error, HttpResponse, Result}; use actix_web::{web, Error, HttpResponse, Result};
use anyhow::anyhow;
use lemmy_api_common::context::LemmyContext; use lemmy_api_common::context::LemmyContext;
use lemmy_db_schema::RegistrationMode; use lemmy_db_schema::RegistrationMode;
use lemmy_db_views::structs::SiteView; use lemmy_db_views::structs::SiteView;
use lemmy_utils::{ use lemmy_utils::{
cache_header::{cache_1hour, cache_3days}, cache_header::{cache_1hour, cache_3days},
error::{LemmyError, LemmyResult}, error::LemmyResult,
VERSION, VERSION,
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@ -44,10 +43,7 @@ async fn node_info_well_known(context: web::Data<LemmyContext>) -> LemmyResult<H
} }
async fn node_info(context: web::Data<LemmyContext>) -> Result<HttpResponse, Error> { async fn node_info(context: web::Data<LemmyContext>) -> Result<HttpResponse, Error> {
let site_view = SiteView::read_local(&mut context.pool()) let site_view = SiteView::read_local(&mut context.pool()).await?;
.await
.map_err(|_| ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))?
.ok_or(ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))?;
// Since there are 3 registration options, // Since there are 3 registration options,
// we need to set open_registrations as true if RegistrationMode is not Closed. // we need to set open_registrations as true if RegistrationMode is not Closed.

View file

@ -0,0 +1,17 @@
ALTER TABLE local_site
ADD COLUMN enable_nsfw boolean NOT NULL DEFAULT FALSE;
UPDATE
local_site
SET
enable_nsfw = CASE WHEN site.content_warning IS NULL THEN
FALSE
ELSE
TRUE
END
FROM
site
WHERE
-- only local site has private key
site.private_key IS NOT NULL;

View file

@ -0,0 +1,20 @@
-- if site has enable_nsfw, set a default content warning
UPDATE
site
SET
content_warning = CASE WHEN local_site.enable_nsfw THEN
'NSFW'
ELSE
NULL
END
FROM
local_site
-- only local site has private key
WHERE
private_key IS NOT NULL
-- dont overwrite existing content warning
AND content_warning IS NOT NULL;
ALTER TABLE local_site
DROP enable_nsfw;

View file

@ -345,7 +345,7 @@ async fn instance_actor_2022_01_28(
settings: &Settings, settings: &Settings,
) -> LemmyResult<()> { ) -> LemmyResult<()> {
info!("Running instance_actor_2021_09_29"); info!("Running instance_actor_2021_09_29");
if let Ok(Some(site_view)) = SiteView::read_local(pool).await { if let Ok(site_view) = SiteView::read_local(pool).await {
let site = site_view.site; let site = site_view.site;
// if site already has public key, we dont need to do anything here // if site already has public key, we dont need to do anything here
if !site.public_key.is_empty() { if !site.public_key.is_empty() {

View file

@ -127,9 +127,7 @@ pub async fn start_lemmy_server(args: CmdArgs) -> LemmyResult<()> {
.expect("Couldn't initialize secrets."); .expect("Couldn't initialize secrets.");
// Make sure the local site is set up. // Make sure the local site is set up.
let site_view = SiteView::read_local(&mut (&pool).into()) let site_view = SiteView::read_local(&mut (&pool).into()).await?;
.await?
.expect("local site not set up");
let local_site = site_view.local_site; let local_site = site_view.local_site;
let federation_enabled = local_site.federation_enabled; let federation_enabled = local_site.federation_enabled;