Add diesel_async, get rid of blocking function (#2510)

* Moving settings to Database.

- Moves many settings into the database. Fixes #2285
- Adds a local_site and instance table. Fixes #2365 . Fixes #2368
- Separates SQL update an insert forms, to avoid runtime errors.
- Adds TypedBuilder to all the SQL forms, instead of default.

* Fix weird clippy issue.

* Removing extra lines.

* Some fixes from suggestions.

* Fixing apub tests.

* Using instance creation helper function.

* Move forms to their own line.

* Trying to fix local_site_data, still broken.

* Testing out async

* Testing out async 2

* Fixing federation tests.

* Trying to fix check features 1.

* Starting on adding diesel async. 1/4th done.

* Added async to views and schema.

* Adding some more async

* Compiling now.

* Added diesel async. Fixes #2465

* Running clippy --fix

* Trying to fix cargo test on drone.

* Trying new muslrust.

* Trying a custom dns

* Trying a custom dns 2

* Trying a custom dns 3

* Trying a custom dns 4

* Trying a custom dns 5

* Trying a custom dns 6

* Trying a custom dns 7

* Addressing PR comments.

* Adding check_apub to all verify functions.

* Reverting back drone.

* Fixing merge

* Fix docker images.

* Adding missing discussion_languages.

* Trying to fix federation tests.

* Fix site setup user creation.

* Fix clippy

* Fix clippy 2

* Test api faster

* Try to fix 1

* Try to fix 2

* What are these lines about

* Trying to fix 3

* Moving federation test back to top.

* Remove logging cat.
This commit is contained in:
Dessalines 2022-11-09 05:05:00 -05:00 committed by GitHub
parent ceae0f5993
commit 5d837780f5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
239 changed files with 5350 additions and 4898 deletions

View file

@ -10,8 +10,7 @@ steps:
# use minimum supported rust version for most steps # use minimum supported rust version for most steps
- name: prepare repo - name: prepare repo
image: clux/muslrust:1.59.0 image: clux/muslrust:1.64.0
user: root
commands: commands:
- git fetch --tags - git fetch --tags
- git submodule init - git submodule init
@ -34,7 +33,7 @@ steps:
- cargo clippy --workspace --all-features -- -D clippy::unwrap_used - cargo clippy --workspace --all-features -- -D clippy::unwrap_used
- name: cargo test - name: cargo test
image: clux/muslrust:1.59.0 image: clux/muslrust:1.64.0
environment: environment:
LEMMY_DATABASE_URL: postgres://lemmy:password@database:5432/lemmy LEMMY_DATABASE_URL: postgres://lemmy:password@database:5432/lemmy
LEMMY_CONFIG_LOCATION: ../../config/config.hjson LEMMY_CONFIG_LOCATION: ../../config/config.hjson
@ -46,20 +45,20 @@ steps:
- cargo test --workspace --no-fail-fast --all-features - cargo test --workspace --no-fail-fast --all-features
- name: check defaults.hjson updated - name: check defaults.hjson updated
image: clux/muslrust:1.59.0 image: clux/muslrust:1.64.0
commands: commands:
- ./scripts/update_config_defaults.sh config/defaults_current.hjson - ./scripts/update_config_defaults.sh config/defaults_current.hjson
- diff config/defaults.hjson config/defaults_current.hjson - diff config/defaults.hjson config/defaults_current.hjson
- name: check with different features - name: check with different features
image: clux/muslrust:1.59.0 image: clux/muslrust:1.64.0
commands: commands:
- cargo install cargo-workspaces - cargo install cargo-workspaces
- cargo workspaces exec cargo check --no-default-features - cargo workspaces exec cargo check --no-default-features
- cargo workspaces exec cargo check --all-features - cargo workspaces exec cargo check --all-features
- name: cargo build - name: cargo build
image: clux/muslrust:1.59.0 image: clux/muslrust:1.64.0
commands: commands:
- cargo build - cargo build
- mv target/x86_64-unknown-linux-musl/debug/lemmy_server target/lemmy_server - mv target/x86_64-unknown-linux-musl/debug/lemmy_server target/lemmy_server

897
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -50,9 +50,10 @@ lemmy_api_common = { version = "=0.16.5", path = "crates/api_common" }
lemmy_websocket = { version = "=0.16.5", path = "./crates/websocket" } lemmy_websocket = { version = "=0.16.5", path = "./crates/websocket" }
lemmy_routes = { version = "=0.16.5", path = "./crates/routes" } lemmy_routes = { version = "=0.16.5", path = "./crates/routes" }
activitypub_federation = "0.2.3" activitypub_federation = "0.2.3"
diesel = "2.0.0" diesel = "2.0.2"
diesel_migrations = "2.0.0" diesel_migrations = "2.0.0"
serde = { version = "1.0.145", features = ["derive"] } diesel-async = "0.1.1"
serde = { version = "1.0.147", features = ["derive"] }
actix = "0.13.0" actix = "0.13.0"
actix-web = { version = "4.2.1", default-features = false, features = ["macros", "rustls"] } actix-web = { version = "4.2.1", default-features = false, features = ["macros", "rustls"] }
tracing = "0.1.36" tracing = "0.1.36"

View file

@ -20,7 +20,7 @@
"eslint": "^8.25.0", "eslint": "^8.25.0",
"eslint-plugin-prettier": "^4.0.0", "eslint-plugin-prettier": "^4.0.0",
"jest": "^27.0.6", "jest": "^27.0.6",
"lemmy-js-client": "0.17.0-rc.47", "lemmy-js-client": "0.17.0-rc.48",
"node-fetch": "^2.6.1", "node-fetch": "^2.6.1",
"prettier": "^2.7.1", "prettier": "^2.7.1",
"reflect-metadata": "^0.1.13", "reflect-metadata": "^0.1.13",

View file

@ -31,41 +31,35 @@ killall lemmy_server || true
echo "$PWD" echo "$PWD"
echo "start alpha" echo "start alpha"
LEMMY_HOSTNAME=lemmy-alpha:8541 \
LEMMY_CONFIG_LOCATION=./docker/federation/lemmy_alpha.hjson \ LEMMY_CONFIG_LOCATION=./docker/federation/lemmy_alpha.hjson \
LEMMY_DATABASE_URL="${LEMMY_DATABASE_URL}/lemmy_alpha" \ LEMMY_DATABASE_URL="${LEMMY_DATABASE_URL}/lemmy_alpha" \
LEMMY_HOSTNAME="lemmy-alpha:8541" \
target/lemmy_server >/tmp/lemmy_alpha.out 2>&1 & target/lemmy_server >/tmp/lemmy_alpha.out 2>&1 &
echo "start beta" echo "start beta"
LEMMY_HOSTNAME=lemmy-beta:8551 \
LEMMY_CONFIG_LOCATION=./docker/federation/lemmy_beta.hjson \ LEMMY_CONFIG_LOCATION=./docker/federation/lemmy_beta.hjson \
LEMMY_DATABASE_URL="${LEMMY_DATABASE_URL}/lemmy_beta" \ LEMMY_DATABASE_URL="${LEMMY_DATABASE_URL}/lemmy_beta" \
target/lemmy_server >/tmp/lemmy_beta.out 2>&1 & target/lemmy_server >/tmp/lemmy_beta.out 2>&1 &
echo "start gamma" echo "start gamma"
LEMMY_HOSTNAME=lemmy-gamma:8561 \
LEMMY_CONFIG_LOCATION=./docker/federation/lemmy_gamma.hjson \ LEMMY_CONFIG_LOCATION=./docker/federation/lemmy_gamma.hjson \
LEMMY_DATABASE_URL="${LEMMY_DATABASE_URL}/lemmy_gamma" \ LEMMY_DATABASE_URL="${LEMMY_DATABASE_URL}/lemmy_gamma" \
target/lemmy_server >/tmp/lemmy_gamma.out 2>&1 & target/lemmy_server >/tmp/lemmy_gamma.out 2>&1 &
echo "start delta" echo "start delta"
# An instance with only an allowlist for beta # An instance with only an allowlist for beta
LEMMY_HOSTNAME=lemmy-delta:8571 \
LEMMY_CONFIG_LOCATION=./docker/federation/lemmy_delta.hjson \ LEMMY_CONFIG_LOCATION=./docker/federation/lemmy_delta.hjson \
LEMMY_DATABASE_URL="${LEMMY_DATABASE_URL}/lemmy_delta" \ LEMMY_DATABASE_URL="${LEMMY_DATABASE_URL}/lemmy_delta" \
target/lemmy_server >/tmp/lemmy_delta.out 2>&1 & target/lemmy_server >/tmp/lemmy_delta.out 2>&1 &
echo "start epsilon" echo "start epsilon"
# An instance who has a blocklist, with lemmy-alpha blocked # An instance who has a blocklist, with lemmy-alpha blocked
LEMMY_HOSTNAME=lemmy-epsilon:8581 \
LEMMY_CONFIG_LOCATION=./docker/federation/lemmy_epsilon.hjson \ LEMMY_CONFIG_LOCATION=./docker/federation/lemmy_epsilon.hjson \
LEMMY_DATABASE_URL="${LEMMY_DATABASE_URL}/lemmy_epsilon" \ LEMMY_DATABASE_URL="${LEMMY_DATABASE_URL}/lemmy_epsilon" \
target/lemmy_server >/tmp/lemmy_epsilon.out 2>&1 & target/lemmy_server >/tmp/lemmy_epsilon.out 2>&1 &
echo "wait for all instances to start" echo "wait for all instances to start"
while [[ "$(curl -s -o /dev/null -w '%{http_code}' 'localhost:8541/api/v3/site')" != "200" ]]; do sleep 1; done while [[ "$(curl -s -o /dev/null -w '%{http_code}' 'lemmy-alpha:8541/api/v3/site')" != "200" ]]; do sleep 1; done
while [[ "$(curl -s -o /dev/null -w '%{http_code}' 'localhost:8551/api/v3/site')" != "200" ]]; do sleep 1; done while [[ "$(curl -s -o /dev/null -w '%{http_code}' 'lemmy-beta:8551/api/v3/site')" != "200" ]]; do sleep 1; done
while [[ "$(curl -s -o /dev/null -w '%{http_code}' 'localhost:8561/api/v3/site')" != "200" ]]; do sleep 1; done while [[ "$(curl -s -o /dev/null -w '%{http_code}' 'lemmy-gamma:8561/api/v3/site')" != "200" ]]; do sleep 1; done
while [[ "$(curl -s -o /dev/null -w '%{http_code}' 'localhost:8571/api/v3/site')" != "200" ]]; do sleep 1; done while [[ "$(curl -s -o /dev/null -w '%{http_code}' 'lemmy-delta:8571/api/v3/site')" != "200" ]]; do sleep 1; done
while [[ "$(curl -s -o /dev/null -w '%{http_code}' 'localhost:8581/api/v3/site')" != "200" ]]; do sleep 1; done while [[ "$(curl -s -o /dev/null -w '%{http_code}' 'lemmy-epsilon:8581/api/v3/site')" != "200" ]]; do sleep 1; done

View file

@ -2373,10 +2373,10 @@ kleur@^3.0.3:
resolved "https://registry.yarnpkg.com/kleur/-/kleur-3.0.3.tgz#a79c9ecc86ee1ce3fa6206d1216c501f147fc07e" resolved "https://registry.yarnpkg.com/kleur/-/kleur-3.0.3.tgz#a79c9ecc86ee1ce3fa6206d1216c501f147fc07e"
integrity sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w== integrity sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==
lemmy-js-client@0.17.0-rc.47: lemmy-js-client@0.17.0-rc.48:
version "0.17.0-rc.47" version "0.17.0-rc.48"
resolved "https://registry.yarnpkg.com/lemmy-js-client/-/lemmy-js-client-0.17.0-rc.47.tgz#6094657d2868767532c0e837a31f9af6273b345b" resolved "https://registry.yarnpkg.com/lemmy-js-client/-/lemmy-js-client-0.17.0-rc.48.tgz#6085812d4901b7d12b3fca237d8aced7f5210eac"
integrity sha512-Pc1wyr6sX4Z6LS75NVu46WAXeci5G80+Y9ZBXEAmgM+OZGuOCLUq8lAHRvTwr7M0pj0gxo5yP+i3qPVmTPf+EA== integrity sha512-Lz8Nzq/kczQtDj6STlbhxoEarFHtTCoWcWBabyPs6X6em/pfK/cnZqx1mMn7EaBSDUVQ+WL8UNFjQiqjhR4kww==
leven@^3.1.0: leven@^3.1.0:
version "3.1.0" version "3.1.0"

View file

@ -23,15 +23,19 @@ lemmy_db_views_actor = { version = "=0.16.5", path = "../db_views_actor", featur
lemmy_api_common = { version = "=0.16.5", path = "../api_common", features = ["full"] } lemmy_api_common = { version = "=0.16.5", path = "../api_common", features = ["full"] }
lemmy_websocket = { version = "=0.16.5", path = "../websocket" } lemmy_websocket = { version = "=0.16.5", path = "../websocket" }
activitypub_federation = "0.2.3" activitypub_federation = "0.2.3"
diesel = "2.0.0" diesel = "2.0.2"
bcrypt = "0.13.0" bcrypt = "0.13.0"
chrono = { version = "0.4.22", features = ["serde"], default-features = false } chrono = { version = "0.4.22", features = ["serde"], default-features = false }
serde_json = { version = "1.0.85", features = ["preserve_order"] } serde_json = { version = "1.0.87", features = ["preserve_order"] }
serde = { version = "1.0.145", features = ["derive"] } serde = { version = "1.0.147", features = ["derive"] }
actix-web = { version = "4.2.1", default-features = false } actix-web = { version = "4.2.1", default-features = false }
base64 = "0.13.0" base64 = "0.13.1"
uuid = { version = "1.1.2", features = ["serde", "v4"] } uuid = { version = "1.2.1", features = ["serde", "v4"] }
async-trait = "0.1.57" async-trait = "0.1.58"
captcha = "0.0.9" captcha = "0.0.9"
anyhow = "1.0.65" anyhow = "1.0.66"
tracing = "0.1.36" tracing = "0.1.37"
[dev-dependencies]
serial_test = "0.9.0"
tokio = "1.21.2"

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
comment::{CommentResponse, CreateCommentLike}, comment::{CommentResponse, CreateCommentLike},
utils::{blocking, check_community_ban, check_downvotes_enabled, get_local_user_view_from_jwt}, utils::{check_community_ban, check_downvotes_enabled, get_local_user_view_from_jwt},
}; };
use lemmy_apub::{ use lemmy_apub::{
fetcher::post_or_comment::PostOrComment, fetcher::post_or_comment::PostOrComment,
@ -36,7 +36,7 @@ impl Perform for CreateCommentLike {
websocket_id: Option<ConnectionId>, websocket_id: Option<ConnectionId>,
) -> Result<CommentResponse, LemmyError> { ) -> Result<CommentResponse, LemmyError> {
let data: &CreateCommentLike = self; let data: &CreateCommentLike = self;
let local_site = blocking(context.pool(), LocalSite::read).await??; let local_site = LocalSite::read(context.pool()).await?;
let local_user_view = let local_user_view =
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
@ -46,10 +46,7 @@ impl Perform for CreateCommentLike {
check_downvotes_enabled(data.score, &local_site)?; check_downvotes_enabled(data.score, &local_site)?;
let comment_id = data.comment_id; let comment_id = data.comment_id;
let orig_comment = blocking(context.pool(), move |conn| { let orig_comment = CommentView::read(context.pool(), comment_id, None).await?;
CommentView::read(conn, comment_id, None)
})
.await??;
check_community_ban( check_community_ban(
local_user_view.person.id, local_user_view.person.id,
@ -59,17 +56,10 @@ impl Perform for CreateCommentLike {
.await?; .await?;
// Add parent poster or commenter to recipients // Add parent poster or commenter to recipients
let comment_reply = blocking(context.pool(), move |conn| { let comment_reply = CommentReply::read_by_comment(context.pool(), comment_id).await;
CommentReply::read_by_comment(conn, comment_id)
})
.await?;
if let Ok(reply) = comment_reply { if let Ok(reply) = comment_reply {
let recipient_id = reply.recipient_id; let recipient_id = reply.recipient_id;
if let Ok(local_recipient) = blocking(context.pool(), move |conn| { if let Ok(local_recipient) = LocalUserView::read_person(context.pool(), recipient_id).await {
LocalUserView::read_person(conn, recipient_id)
})
.await?
{
recipient_ids.push(local_recipient.local_user.id); recipient_ids.push(local_recipient.local_user.id);
} }
} }
@ -83,10 +73,8 @@ impl Perform for CreateCommentLike {
// Remove any likes first // Remove any likes first
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
blocking(context.pool(), move |conn| {
CommentLike::remove(conn, person_id, comment_id) CommentLike::remove(context.pool(), person_id, comment_id).await?;
})
.await??;
// Only add the like if the score isnt 0 // Only add the like if the score isnt 0
let comment = orig_comment.comment; let comment = orig_comment.comment;
@ -94,9 +82,8 @@ impl Perform for CreateCommentLike {
let do_add = like_form.score != 0 && (like_form.score == 1 || like_form.score == -1); let do_add = like_form.score != 0 && (like_form.score == 1 || like_form.score == -1);
if do_add { if do_add {
let like_form2 = like_form.clone(); let like_form2 = like_form.clone();
let like = move |conn: &mut _| CommentLike::like(conn, &like_form2); CommentLike::like(context.pool(), &like_form2)
blocking(context.pool(), like) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_like_comment"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_like_comment"))?;
Vote::send( Vote::send(

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
comment::{CommentResponse, SaveComment}, comment::{CommentResponse, SaveComment},
utils::{blocking, get_local_user_view_from_jwt}, utils::get_local_user_view_from_jwt,
}; };
use lemmy_db_schema::{ use lemmy_db_schema::{
source::comment::{CommentSaved, CommentSavedForm}, source::comment::{CommentSaved, CommentSavedForm},
@ -32,23 +32,18 @@ impl Perform for SaveComment {
}; };
if data.save { if data.save {
let save_comment = move |conn: &mut _| CommentSaved::save(conn, &comment_saved_form); CommentSaved::save(context.pool(), &comment_saved_form)
blocking(context.pool(), save_comment) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_save_comment"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_save_comment"))?;
} else { } else {
let unsave_comment = move |conn: &mut _| CommentSaved::unsave(conn, &comment_saved_form); CommentSaved::unsave(context.pool(), &comment_saved_form)
blocking(context.pool(), unsave_comment) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_save_comment"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_save_comment"))?;
} }
let comment_id = data.comment_id; let comment_id = data.comment_id;
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let comment_view = blocking(context.pool(), move |conn| { let comment_view = CommentView::read(context.pool(), comment_id, Some(person_id)).await?;
CommentView::read(conn, comment_id, Some(person_id))
})
.await??;
Ok(CommentResponse { Ok(CommentResponse {
comment_view, comment_view,

View file

@ -3,7 +3,7 @@ use activitypub_federation::core::object_id::ObjectId;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
comment::{CommentReportResponse, CreateCommentReport}, comment::{CommentReportResponse, CreateCommentReport},
utils::{blocking, check_community_ban, get_local_user_view_from_jwt}, utils::{check_community_ban, get_local_user_view_from_jwt},
}; };
use lemmy_apub::protocol::activities::community::report::Report; use lemmy_apub::protocol::activities::community::report::Report;
use lemmy_db_schema::{ use lemmy_db_schema::{
@ -31,17 +31,14 @@ impl Perform for CreateCommentReport {
let data: &CreateCommentReport = self; let data: &CreateCommentReport = self;
let local_user_view = let local_user_view =
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let local_site = blocking(context.pool(), LocalSite::read).await??; let local_site = LocalSite::read(context.pool()).await?;
let reason = self.reason.trim(); let reason = self.reason.trim();
check_report_reason(reason, &local_site)?; check_report_reason(reason, &local_site)?;
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let comment_id = data.comment_id; let comment_id = data.comment_id;
let comment_view = blocking(context.pool(), move |conn| { let comment_view = CommentView::read(context.pool(), comment_id, None).await?;
CommentView::read(conn, comment_id, None)
})
.await??;
check_community_ban(person_id, comment_view.community.id, context.pool()).await?; check_community_ban(person_id, comment_view.community.id, context.pool()).await?;
@ -52,16 +49,11 @@ impl Perform for CreateCommentReport {
reason: reason.to_owned(), reason: reason.to_owned(),
}; };
let report = blocking(context.pool(), move |conn| { let report = CommentReport::report(context.pool(), &report_form)
CommentReport::report(conn, &report_form) .await
})
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_create_report"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_create_report"))?;
let comment_report_view = blocking(context.pool(), move |conn| { let comment_report_view = CommentReportView::read(context.pool(), report.id, person_id).await?;
CommentReportView::read(conn, report.id, person_id)
})
.await??;
let res = CommentReportResponse { let res = CommentReportResponse {
comment_report_view, comment_report_view,

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
comment::{ListCommentReports, ListCommentReportsResponse}, comment::{ListCommentReports, ListCommentReportsResponse},
utils::{blocking, get_local_user_view_from_jwt}, utils::get_local_user_view_from_jwt,
}; };
use lemmy_db_views::comment_report_view::CommentReportQuery; use lemmy_db_views::comment_report_view::CommentReportQuery;
use lemmy_utils::{error::LemmyError, ConnectionId}; use lemmy_utils::{error::LemmyError, ConnectionId};
@ -31,9 +31,8 @@ impl Perform for ListCommentReports {
let page = data.page; let page = data.page;
let limit = data.limit; let limit = data.limit;
let comment_reports = blocking(context.pool(), move |conn| { let comment_reports = CommentReportQuery::builder()
CommentReportQuery::builder() .pool(context.pool())
.conn(conn)
.my_person_id(person_id) .my_person_id(person_id)
.admin(admin) .admin(admin)
.community_id(community_id) .community_id(community_id)
@ -42,8 +41,7 @@ impl Perform for ListCommentReports {
.limit(limit) .limit(limit)
.build() .build()
.list() .list()
}) .await?;
.await??;
let res = ListCommentReportsResponse { comment_reports }; let res = ListCommentReportsResponse { comment_reports };

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
comment::{CommentReportResponse, ResolveCommentReport}, comment::{CommentReportResponse, ResolveCommentReport},
utils::{blocking, get_local_user_view_from_jwt, is_mod_or_admin}, utils::{get_local_user_view_from_jwt, is_mod_or_admin},
}; };
use lemmy_db_schema::{source::comment_report::CommentReport, traits::Reportable}; use lemmy_db_schema::{source::comment_report::CommentReport, traits::Reportable};
use lemmy_db_views::structs::CommentReportView; use lemmy_db_views::structs::CommentReportView;
@ -26,32 +26,23 @@ impl Perform for ResolveCommentReport {
let report_id = data.report_id; let report_id = data.report_id;
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let report = blocking(context.pool(), move |conn| { let report = CommentReportView::read(context.pool(), report_id, person_id).await?;
CommentReportView::read(conn, report_id, person_id)
})
.await??;
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
is_mod_or_admin(context.pool(), person_id, report.community.id).await?; is_mod_or_admin(context.pool(), person_id, report.community.id).await?;
let resolved = data.resolved; if data.resolved {
let resolve_fun = move |conn: &mut _| { CommentReport::resolve(context.pool(), report_id, person_id)
if resolved { .await
CommentReport::resolve(conn, report_id, person_id)
} else {
CommentReport::unresolve(conn, report_id, person_id)
}
};
blocking(context.pool(), resolve_fun)
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_resolve_report"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_resolve_report"))?;
} else {
CommentReport::unresolve(context.pool(), report_id, person_id)
.await
.map_err(|e| LemmyError::from_error_message(e, "couldnt_resolve_report"))?;
}
let report_id = data.report_id; let report_id = data.report_id;
let comment_report_view = blocking(context.pool(), move |conn| { let comment_report_view = CommentReportView::read(context.pool(), report_id, person_id).await?;
CommentReportView::read(conn, report_id, person_id)
})
.await??;
let res = CommentReportResponse { let res = CommentReportResponse {
comment_report_view, comment_report_view,

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
community::{AddModToCommunity, AddModToCommunityResponse}, community::{AddModToCommunity, AddModToCommunityResponse},
utils::{blocking, get_local_user_view_from_jwt, is_mod_or_admin}, utils::{get_local_user_view_from_jwt, is_mod_or_admin},
}; };
use lemmy_apub::{ use lemmy_apub::{
objects::{community::ApubCommunity, person::ApubPerson}, objects::{community::ApubCommunity, person::ApubPerson},
@ -38,10 +38,7 @@ impl Perform for AddModToCommunity {
// Verify that only mods or admins can add mod // Verify that only mods or admins can add mod
is_mod_or_admin(context.pool(), local_user_view.person.id, community_id).await?; is_mod_or_admin(context.pool(), local_user_view.person.id, community_id).await?;
let community = blocking(context.pool(), move |conn| { let community = Community::read(context.pool(), community_id).await?;
Community::read(conn, community_id)
})
.await??;
if local_user_view.person.admin && !community.local { if local_user_view.person.admin && !community.local {
return Err(LemmyError::from_message("not_a_moderator")); return Err(LemmyError::from_message("not_a_moderator"));
} }
@ -52,14 +49,12 @@ impl Perform for AddModToCommunity {
person_id: data.person_id, person_id: data.person_id,
}; };
if data.added { if data.added {
let join = move |conn: &mut _| CommunityModerator::join(conn, &community_moderator_form); CommunityModerator::join(context.pool(), &community_moderator_form)
blocking(context.pool(), join) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "community_moderator_already_exists"))?; .map_err(|e| LemmyError::from_error_message(e, "community_moderator_already_exists"))?;
} else { } else {
let leave = move |conn: &mut _| CommunityModerator::leave(conn, &community_moderator_form); CommunityModerator::leave(context.pool(), &community_moderator_form)
blocking(context.pool(), leave) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "community_moderator_already_exists"))?; .map_err(|e| LemmyError::from_error_message(e, "community_moderator_already_exists"))?;
} }
@ -70,18 +65,12 @@ impl Perform for AddModToCommunity {
community_id: data.community_id, community_id: data.community_id,
removed: Some(!data.added), removed: Some(!data.added),
}; };
blocking(context.pool(), move |conn| {
ModAddCommunity::create(conn, &form) ModAddCommunity::create(context.pool(), &form).await?;
})
.await??;
// Send to federated instances // Send to federated instances
let updated_mod_id = data.person_id; let updated_mod_id = data.person_id;
let updated_mod: ApubPerson = blocking(context.pool(), move |conn| { let updated_mod: ApubPerson = Person::read(context.pool(), updated_mod_id).await?.into();
Person::read(conn, updated_mod_id)
})
.await??
.into();
let community: ApubCommunity = community.into(); let community: ApubCommunity = community.into();
if data.added { if data.added {
AddMod::send( AddMod::send(
@ -104,10 +93,7 @@ impl Perform for AddModToCommunity {
// Note: in case a remote mod is added, this returns the old moderators list, it will only get // Note: in case a remote mod is added, this returns the old moderators list, it will only get
// updated once we receive an activity from the community (like `Announce/Add/Moderator`) // updated once we receive an activity from the community (like `Announce/Add/Moderator`)
let community_id = data.community_id; let community_id = data.community_id;
let moderators = blocking(context.pool(), move |conn| { let moderators = CommunityModeratorView::for_community(context.pool(), community_id).await?;
CommunityModeratorView::for_community(conn, community_id)
})
.await??;
let res = AddModToCommunityResponse { moderators }; let res = AddModToCommunityResponse { moderators };
context.chat_server().do_send(SendCommunityRoomMessage { context.chat_server().do_send(SendCommunityRoomMessage {

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
community::{BanFromCommunity, BanFromCommunityResponse}, community::{BanFromCommunity, BanFromCommunityResponse},
utils::{blocking, get_local_user_view_from_jwt, is_mod_or_admin, remove_user_data_in_community}, utils::{get_local_user_view_from_jwt, is_mod_or_admin, remove_user_data_in_community},
}; };
use lemmy_apub::{ use lemmy_apub::{
activities::block::SiteOrCommunity, activities::block::SiteOrCommunity,
@ -55,21 +55,12 @@ impl Perform for BanFromCommunity {
expires: Some(expires), expires: Some(expires),
}; };
let community: ApubCommunity = blocking(context.pool(), move |conn: &mut _| { let community: ApubCommunity = Community::read(context.pool(), community_id).await?.into();
Community::read(conn, community_id) let banned_person: ApubPerson = Person::read(context.pool(), banned_person_id).await?.into();
})
.await??
.into();
let banned_person: ApubPerson = blocking(context.pool(), move |conn: &mut _| {
Person::read(conn, banned_person_id)
})
.await??
.into();
if data.ban { if data.ban {
let ban = move |conn: &mut _| CommunityPersonBan::ban(conn, &community_user_ban_form); CommunityPersonBan::ban(context.pool(), &community_user_ban_form)
blocking(context.pool(), ban) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "community_user_already_banned"))?; .map_err(|e| LemmyError::from_error_message(e, "community_user_already_banned"))?;
// Also unsubscribe them from the community, if they are subscribed // Also unsubscribe them from the community, if they are subscribed
@ -78,10 +69,9 @@ impl Perform for BanFromCommunity {
person_id: banned_person_id, person_id: banned_person_id,
pending: false, pending: false,
}; };
blocking(context.pool(), move |conn: &mut _| {
CommunityFollower::unfollow(conn, &community_follower_form) CommunityFollower::unfollow(context.pool(), &community_follower_form)
}) .await
.await?
.ok(); .ok();
BlockUser::send( BlockUser::send(
@ -95,9 +85,8 @@ impl Perform for BanFromCommunity {
) )
.await?; .await?;
} else { } else {
let unban = move |conn: &mut _| CommunityPersonBan::unban(conn, &community_user_ban_form); CommunityPersonBan::unban(context.pool(), &community_user_ban_form)
blocking(context.pool(), unban) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "community_user_already_banned"))?; .map_err(|e| LemmyError::from_error_message(e, "community_user_already_banned"))?;
UndoBlockUser::send( UndoBlockUser::send(
&SiteOrCommunity::Community(community), &SiteOrCommunity::Community(community),
@ -123,16 +112,11 @@ impl Perform for BanFromCommunity {
banned: Some(data.ban), banned: Some(data.ban),
expires, expires,
}; };
blocking(context.pool(), move |conn| {
ModBanFromCommunity::create(conn, &form) ModBanFromCommunity::create(context.pool(), &form).await?;
})
.await??;
let person_id = data.person_id; let person_id = data.person_id;
let person_view = blocking(context.pool(), move |conn| { let person_view = PersonViewSafe::read(context.pool(), person_id).await?;
PersonViewSafe::read(conn, person_id)
})
.await??;
let res = BanFromCommunityResponse { let res = BanFromCommunityResponse {
person_view, person_view,

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
community::{BlockCommunity, BlockCommunityResponse}, community::{BlockCommunity, BlockCommunityResponse},
utils::{blocking, get_local_user_view_from_jwt}, utils::get_local_user_view_from_jwt,
}; };
use lemmy_apub::protocol::activities::following::undo_follow::UndoFollowCommunity; use lemmy_apub::protocol::activities::following::undo_follow::UndoFollowCommunity;
use lemmy_db_schema::{ use lemmy_db_schema::{
@ -38,9 +38,8 @@ impl Perform for BlockCommunity {
}; };
if data.block { if data.block {
let block = move |conn: &mut _| CommunityBlock::block(conn, &community_block_form); CommunityBlock::block(context.pool(), &community_block_form)
blocking(context.pool(), block) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "community_block_already_exists"))?; .map_err(|e| LemmyError::from_error_message(e, "community_block_already_exists"))?;
// Also, unfollow the community, and send a federated unfollow // Also, unfollow the community, and send a federated unfollow
@ -49,27 +48,19 @@ impl Perform for BlockCommunity {
person_id, person_id,
pending: false, pending: false,
}; };
blocking(context.pool(), move |conn: &mut _| {
CommunityFollower::unfollow(conn, &community_follower_form) CommunityFollower::unfollow(context.pool(), &community_follower_form)
}) .await
.await?
.ok(); .ok();
let community = blocking(context.pool(), move |conn| { let community = Community::read(context.pool(), community_id).await?;
Community::read(conn, community_id)
})
.await??;
UndoFollowCommunity::send(&local_user_view.person.into(), &community.into(), context).await?; UndoFollowCommunity::send(&local_user_view.person.into(), &community.into(), context).await?;
} else { } else {
let unblock = move |conn: &mut _| CommunityBlock::unblock(conn, &community_block_form); CommunityBlock::unblock(context.pool(), &community_block_form)
blocking(context.pool(), unblock) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "community_block_already_exists"))?; .map_err(|e| LemmyError::from_error_message(e, "community_block_already_exists"))?;
} }
let community_view = blocking(context.pool(), move |conn| { let community_view = CommunityView::read(context.pool(), community_id, Some(person_id)).await?;
CommunityView::read(conn, community_id, Some(person_id))
})
.await??;
Ok(BlockCommunityResponse { Ok(BlockCommunityResponse {
blocked: data.block, blocked: data.block,

View file

@ -2,12 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
community::{CommunityResponse, FollowCommunity}, community::{CommunityResponse, FollowCommunity},
utils::{ utils::{check_community_ban, check_community_deleted_or_removed, get_local_user_view_from_jwt},
blocking,
check_community_ban,
check_community_deleted_or_removed,
get_local_user_view_from_jwt,
},
}; };
use lemmy_apub::{ use lemmy_apub::{
objects::community::ApubCommunity, objects::community::ApubCommunity,
@ -39,11 +34,7 @@ impl Perform for FollowCommunity {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let community_id = data.community_id; let community_id = data.community_id;
let community: ApubCommunity = blocking(context.pool(), move |conn| { let community: ApubCommunity = Community::read(context.pool(), community_id).await?.into();
Community::read(conn, community_id)
})
.await??
.into();
let community_follower_form = CommunityFollowerForm { let community_follower_form = CommunityFollowerForm {
community_id: data.community_id, community_id: data.community_id,
person_id: local_user_view.person.id, person_id: local_user_view.person.id,
@ -55,15 +46,12 @@ impl Perform for FollowCommunity {
check_community_ban(local_user_view.person.id, community_id, context.pool()).await?; check_community_ban(local_user_view.person.id, community_id, context.pool()).await?;
check_community_deleted_or_removed(community_id, context.pool()).await?; check_community_deleted_or_removed(community_id, context.pool()).await?;
let follow = move |conn: &mut _| CommunityFollower::follow(conn, &community_follower_form); CommunityFollower::follow(context.pool(), &community_follower_form)
blocking(context.pool(), follow) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "community_follower_already_exists"))?; .map_err(|e| LemmyError::from_error_message(e, "community_follower_already_exists"))?;
} else { } else {
let unfollow = CommunityFollower::unfollow(context.pool(), &community_follower_form)
move |conn: &mut _| CommunityFollower::unfollow(conn, &community_follower_form); .await
blocking(context.pool(), unfollow)
.await?
.map_err(|e| LemmyError::from_error_message(e, "community_follower_already_exists"))?; .map_err(|e| LemmyError::from_error_message(e, "community_follower_already_exists"))?;
} }
} else if data.follow { } else if data.follow {
@ -74,19 +62,14 @@ impl Perform for FollowCommunity {
} else { } else {
UndoFollowCommunity::send(&local_user_view.person.clone().into(), &community, context) UndoFollowCommunity::send(&local_user_view.person.clone().into(), &community, context)
.await?; .await?;
let unfollow = CommunityFollower::unfollow(context.pool(), &community_follower_form)
move |conn: &mut _| CommunityFollower::unfollow(conn, &community_follower_form); .await
blocking(context.pool(), unfollow)
.await?
.map_err(|e| LemmyError::from_error_message(e, "community_follower_already_exists"))?; .map_err(|e| LemmyError::from_error_message(e, "community_follower_already_exists"))?;
} }
let community_id = data.community_id; let community_id = data.community_id;
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let community_view = blocking(context.pool(), move |conn| { let community_view = CommunityView::read(context.pool(), community_id, Some(person_id)).await?;
CommunityView::read(conn, community_id, Some(person_id))
})
.await??;
Ok(Self::Response { community_view }) Ok(Self::Response { community_view })
} }

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
community::{CommunityResponse, HideCommunity}, community::{CommunityResponse, HideCommunity},
utils::{blocking, get_local_user_view_from_jwt, is_admin}, utils::{get_local_user_view_from_jwt, is_admin},
}; };
use lemmy_apub::protocol::activities::community::update::UpdateCommunity; use lemmy_apub::protocol::activities::community::update::UpdateCommunity;
use lemmy_db_schema::{ use lemmy_db_schema::{
@ -44,16 +44,11 @@ impl Perform for HideCommunity {
}; };
let community_id = data.community_id; let community_id = data.community_id;
let updated_community = blocking(context.pool(), move |conn| { let updated_community = Community::update(context.pool(), community_id, &community_form)
Community::update(conn, community_id, &community_form) .await
})
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_update_community_hidden_status"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_community_hidden_status"))?;
blocking(context.pool(), move |conn| { ModHideCommunity::create(context.pool(), &mod_hide_community_form).await?;
ModHideCommunity::create(conn, &mod_hide_community_form)
})
.await??;
UpdateCommunity::send( UpdateCommunity::send(
updated_community.into(), updated_community.into(),

View file

@ -3,7 +3,7 @@ use actix_web::web::Data;
use anyhow::Context; use anyhow::Context;
use lemmy_api_common::{ use lemmy_api_common::{
community::{GetCommunityResponse, TransferCommunity}, community::{GetCommunityResponse, TransferCommunity},
utils::{blocking, get_local_user_view_from_jwt}, utils::get_local_user_view_from_jwt,
}; };
use lemmy_db_schema::{ use lemmy_db_schema::{
source::{ source::{
@ -32,14 +32,12 @@ impl Perform for TransferCommunity {
let local_user_view = let local_user_view =
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let admins = blocking(context.pool(), PersonViewSafe::admins).await??; let admins = PersonViewSafe::admins(context.pool()).await?;
// Fetch the community mods // Fetch the community mods
let community_id = data.community_id; let community_id = data.community_id;
let mut community_mods = blocking(context.pool(), move |conn| { let mut community_mods =
CommunityModeratorView::for_community(conn, community_id) CommunityModeratorView::for_community(context.pool(), community_id).await?;
})
.await??;
// Make sure transferrer is either the top community mod, or an admin // Make sure transferrer is either the top community mod, or an admin
if local_user_view.person.id != community_mods[0].moderator.id if local_user_view.person.id != community_mods[0].moderator.id
@ -62,10 +60,8 @@ impl Perform for TransferCommunity {
// Delete all the mods // Delete all the mods
let community_id = data.community_id; let community_id = data.community_id;
blocking(context.pool(), move |conn| {
CommunityModerator::delete_for_community(conn, community_id) CommunityModerator::delete_for_community(context.pool(), community_id).await?;
})
.await??;
// TODO: this should probably be a bulk operation // TODO: this should probably be a bulk operation
// Re-add the mods, in the new order // Re-add the mods, in the new order
@ -75,9 +71,8 @@ impl Perform for TransferCommunity {
person_id: cmod.moderator.id, person_id: cmod.moderator.id,
}; };
let join = move |conn: &mut _| CommunityModerator::join(conn, &community_moderator_form); CommunityModerator::join(context.pool(), &community_moderator_form)
blocking(context.pool(), join) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "community_moderator_already_exists"))?; .map_err(|e| LemmyError::from_error_message(e, "community_moderator_already_exists"))?;
} }
@ -88,24 +83,18 @@ impl Perform for TransferCommunity {
community_id: data.community_id, community_id: data.community_id,
removed: Some(false), removed: Some(false),
}; };
blocking(context.pool(), move |conn| {
ModTransferCommunity::create(conn, &form) ModTransferCommunity::create(context.pool(), &form).await?;
})
.await??;
let community_id = data.community_id; let community_id = data.community_id;
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let community_view = blocking(context.pool(), move |conn| { let community_view = CommunityView::read(context.pool(), community_id, Some(person_id))
CommunityView::read(conn, community_id, Some(person_id)) .await
})
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_find_community"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_community"))?;
let community_id = data.community_id; let community_id = data.community_id;
let moderators = blocking(context.pool(), move |conn| { let moderators = CommunityModeratorView::for_community(context.pool(), community_id)
CommunityModeratorView::for_community(conn, community_id) .await
})
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_find_community"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_community"))?;
// Return the jwt // Return the jwt

View file

@ -253,17 +253,19 @@ mod tests {
secret::Secret, secret::Secret,
}, },
traits::Crud, traits::Crud,
utils::establish_unpooled_connection, utils::build_db_pool_for_tests,
}; };
use lemmy_utils::{claims::Claims, settings::SETTINGS}; use lemmy_utils::{claims::Claims, settings::SETTINGS};
use serial_test::serial;
#[test] #[tokio::test]
fn test_should_not_validate_user_token_after_password_change() { #[serial]
let conn = &mut establish_unpooled_connection(); async fn test_should_not_validate_user_token_after_password_change() {
let secret = Secret::init(conn).unwrap(); let pool = &build_db_pool_for_tests().await;
let secret = Secret::init(pool).await.unwrap();
let settings = &SETTINGS.to_owned(); let settings = &SETTINGS.to_owned();
let inserted_instance = Instance::create(conn, "my_domain.tld").unwrap(); let inserted_instance = Instance::create(pool, "my_domain.tld").await.unwrap();
let new_person = PersonInsertForm::builder() let new_person = PersonInsertForm::builder()
.name("Gerry9812".into()) .name("Gerry9812".into())
@ -271,14 +273,14 @@ mod tests {
.instance_id(inserted_instance.id) .instance_id(inserted_instance.id)
.build(); .build();
let inserted_person = Person::create(conn, &new_person).unwrap(); let inserted_person = Person::create(pool, &new_person).await.unwrap();
let local_user_form = LocalUserInsertForm::builder() let local_user_form = LocalUserInsertForm::builder()
.person_id(inserted_person.id) .person_id(inserted_person.id)
.password_encrypted("123456".to_string()) .password_encrypted("123456".to_string())
.build(); .build();
let inserted_local_user = LocalUser::create(conn, &local_user_form).unwrap(); let inserted_local_user = LocalUser::create(pool, &local_user_form).await.unwrap();
let jwt = Claims::jwt( let jwt = Claims::jwt(
inserted_local_user.id.0, inserted_local_user.id.0,
@ -292,11 +294,13 @@ mod tests {
// The check should fail, since the validator time is now newer than the jwt issue time // The check should fail, since the validator time is now newer than the jwt issue time
let updated_local_user = let updated_local_user =
LocalUser::update_password(conn, inserted_local_user.id, "password111").unwrap(); LocalUser::update_password(pool, inserted_local_user.id, "password111")
.await
.unwrap();
let check_after = check_validator_time(&updated_local_user.validator_time, &claims); let check_after = check_validator_time(&updated_local_user.validator_time, &claims);
assert!(check_after.is_err()); assert!(check_after.is_err());
let num_deleted = Person::delete(conn, inserted_person.id).unwrap(); let num_deleted = Person::delete(pool, inserted_person.id).await.unwrap();
assert_eq!(1, num_deleted); assert_eq!(1, num_deleted);
} }
} }

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
person::{AddAdmin, AddAdminResponse}, person::{AddAdmin, AddAdminResponse},
utils::{blocking, get_local_user_view_from_jwt, is_admin}, utils::{get_local_user_view_from_jwt, is_admin},
}; };
use lemmy_db_schema::{ use lemmy_db_schema::{
source::{ source::{
@ -34,14 +34,12 @@ impl Perform for AddAdmin {
let added = data.added; let added = data.added;
let added_person_id = data.person_id; let added_person_id = data.person_id;
let added_admin = blocking(context.pool(), move |conn| { let added_admin = Person::update(
Person::update( context.pool(),
conn,
added_person_id, added_person_id,
&PersonUpdateForm::builder().admin(Some(added)).build(), &PersonUpdateForm::builder().admin(Some(added)).build(),
) )
}) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_update_user"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_user"))?;
// Mod tables // Mod tables
@ -51,9 +49,9 @@ impl Perform for AddAdmin {
removed: Some(!data.added), removed: Some(!data.added),
}; };
blocking(context.pool(), move |conn| ModAdd::create(conn, &form)).await??; ModAdd::create(context.pool(), &form).await?;
let admins = blocking(context.pool(), PersonViewSafe::admins).await??; let admins = PersonViewSafe::admins(context.pool()).await?;
let res = AddAdminResponse { admins }; let res = AddAdminResponse { admins };

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
person::{BanPerson, BanPersonResponse}, person::{BanPerson, BanPersonResponse},
utils::{blocking, get_local_user_view_from_jwt, is_admin, remove_user_data}, utils::{get_local_user_view_from_jwt, is_admin, remove_user_data},
}; };
use lemmy_apub::{ use lemmy_apub::{
activities::block::SiteOrCommunity, activities::block::SiteOrCommunity,
@ -41,17 +41,15 @@ impl Perform for BanPerson {
let banned_person_id = data.person_id; let banned_person_id = data.person_id;
let expires = data.expires.map(naive_from_unix); let expires = data.expires.map(naive_from_unix);
let person = blocking(context.pool(), move |conn| { let person = Person::update(
Person::update( context.pool(),
conn,
banned_person_id, banned_person_id,
&PersonUpdateForm::builder() &PersonUpdateForm::builder()
.banned(Some(ban)) .banned(Some(ban))
.ban_expires(Some(expires)) .ban_expires(Some(expires))
.build(), .build(),
) )
}) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_update_user"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_user"))?;
// Remove their data if that's desired // Remove their data if that's desired
@ -75,20 +73,12 @@ impl Perform for BanPerson {
expires, expires,
}; };
blocking(context.pool(), move |conn| ModBan::create(conn, &form)).await??; ModBan::create(context.pool(), &form).await?;
let person_id = data.person_id; let person_id = data.person_id;
let person_view = blocking(context.pool(), move |conn| { let person_view = PersonViewSafe::read(context.pool(), person_id).await?;
PersonViewSafe::read(conn, person_id)
})
.await??;
let site = SiteOrCommunity::Site( let site = SiteOrCommunity::Site(SiteView::read_local(context.pool()).await?.site.into());
blocking(context.pool(), SiteView::read_local)
.await??
.site
.into(),
);
// if the action affects a local user, federate to other instances // if the action affects a local user, federate to other instances
if person.local { if person.local {
if ban { if ban {

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
person::{BlockPerson, BlockPersonResponse}, person::{BlockPerson, BlockPersonResponse},
utils::{blocking, get_local_user_view_from_jwt}, utils::get_local_user_view_from_jwt,
}; };
use lemmy_db_schema::{ use lemmy_db_schema::{
source::person_block::{PersonBlock, PersonBlockForm}, source::person_block::{PersonBlock, PersonBlockForm},
@ -39,24 +39,19 @@ impl Perform for BlockPerson {
target_id, target_id,
}; };
let target_person_view = blocking(context.pool(), move |conn| { let target_person_view = PersonViewSafe::read(context.pool(), target_id).await?;
PersonViewSafe::read(conn, target_id)
})
.await??;
if target_person_view.person.admin { if target_person_view.person.admin {
return Err(LemmyError::from_message("cant_block_admin")); return Err(LemmyError::from_message("cant_block_admin"));
} }
if data.block { if data.block {
let block = move |conn: &mut _| PersonBlock::block(conn, &person_block_form); PersonBlock::block(context.pool(), &person_block_form)
blocking(context.pool(), block) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "person_block_already_exists"))?; .map_err(|e| LemmyError::from_error_message(e, "person_block_already_exists"))?;
} else { } else {
let unblock = move |conn: &mut _| PersonBlock::unblock(conn, &person_block_form); PersonBlock::unblock(context.pool(), &person_block_form)
blocking(context.pool(), unblock) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "person_block_already_exists"))?; .map_err(|e| LemmyError::from_error_message(e, "person_block_already_exists"))?;
} }

View file

@ -3,7 +3,7 @@ use actix_web::web::Data;
use bcrypt::verify; use bcrypt::verify;
use lemmy_api_common::{ use lemmy_api_common::{
person::{ChangePassword, LoginResponse}, person::{ChangePassword, LoginResponse},
utils::{blocking, get_local_user_view_from_jwt, password_length_check}, utils::{get_local_user_view_from_jwt, password_length_check},
}; };
use lemmy_db_schema::source::local_user::LocalUser; use lemmy_db_schema::source::local_user::LocalUser;
use lemmy_utils::{claims::Claims, error::LemmyError, ConnectionId}; use lemmy_utils::{claims::Claims, error::LemmyError, ConnectionId};
@ -42,10 +42,8 @@ impl Perform for ChangePassword {
let local_user_id = local_user_view.local_user.id; let local_user_id = local_user_view.local_user.id;
let new_password = data.new_password.to_owned(); let new_password = data.new_password.to_owned();
let updated_local_user = blocking(context.pool(), move |conn| { let updated_local_user =
LocalUser::update_password(conn, local_user_id, &new_password) LocalUser::update_password(context.pool(), local_user_id, &new_password).await?;
})
.await??;
// Return the jwt // Return the jwt
Ok(LoginResponse { Ok(LoginResponse {

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
person::{LoginResponse, PasswordChangeAfterReset}, person::{LoginResponse, PasswordChangeAfterReset},
utils::{blocking, password_length_check}, utils::password_length_check,
}; };
use lemmy_db_schema::source::{ use lemmy_db_schema::source::{
local_user::LocalUser, local_user::LocalUser,
@ -25,10 +25,9 @@ impl Perform for PasswordChangeAfterReset {
// Fetch the user_id from the token // Fetch the user_id from the token
let token = data.token.clone(); let token = data.token.clone();
let local_user_id = blocking(context.pool(), move |conn| { let local_user_id = PasswordResetRequest::read_from_token(context.pool(), &token)
PasswordResetRequest::read_from_token(conn, &token).map(|p| p.local_user_id) .await
}) .map(|p| p.local_user_id)?;
.await??;
password_length_check(&data.password)?; password_length_check(&data.password)?;
@ -39,10 +38,8 @@ impl Perform for PasswordChangeAfterReset {
// Update the user with the new password // Update the user with the new password
let password = data.password.clone(); let password = data.password.clone();
let updated_local_user = blocking(context.pool(), move |conn| { let updated_local_user = LocalUser::update_password(context.pool(), local_user_id, &password)
LocalUser::update_password(conn, local_user_id, &password) .await
})
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_update_user"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_user"))?;
// Return the jwt // Return the jwt

View file

@ -2,10 +2,7 @@ use crate::{captcha_as_wav_base64, Perform};
use actix_web::web::Data; use actix_web::web::Data;
use captcha::{gen, Difficulty}; use captcha::{gen, Difficulty};
use chrono::Duration; use chrono::Duration;
use lemmy_api_common::{ use lemmy_api_common::person::{CaptchaResponse, GetCaptcha, GetCaptchaResponse};
person::{CaptchaResponse, GetCaptcha, GetCaptchaResponse},
utils::blocking,
};
use lemmy_db_schema::{source::local_site::LocalSite, utils::naive_now}; use lemmy_db_schema::{source::local_site::LocalSite, utils::naive_now};
use lemmy_utils::{error::LemmyError, ConnectionId}; use lemmy_utils::{error::LemmyError, ConnectionId};
use lemmy_websocket::{messages::CaptchaItem, LemmyContext}; use lemmy_websocket::{messages::CaptchaItem, LemmyContext};
@ -20,7 +17,7 @@ impl Perform for GetCaptcha {
context: &Data<LemmyContext>, context: &Data<LemmyContext>,
_websocket_id: Option<ConnectionId>, _websocket_id: Option<ConnectionId>,
) -> Result<Self::Response, LemmyError> { ) -> Result<Self::Response, LemmyError> {
let local_site = blocking(context.pool(), LocalSite::read).await??; let local_site = LocalSite::read(context.pool()).await?;
if !local_site.captcha_enabled { if !local_site.captcha_enabled {
return Ok(GetCaptchaResponse { ok: None }); return Ok(GetCaptchaResponse { ok: None });

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
person::{BannedPersonsResponse, GetBannedPersons}, person::{BannedPersonsResponse, GetBannedPersons},
utils::{blocking, get_local_user_view_from_jwt, is_admin}, utils::{get_local_user_view_from_jwt, is_admin},
}; };
use lemmy_db_views_actor::structs::PersonViewSafe; use lemmy_db_views_actor::structs::PersonViewSafe;
use lemmy_utils::{error::LemmyError, ConnectionId}; use lemmy_utils::{error::LemmyError, ConnectionId};
@ -24,7 +24,7 @@ impl Perform for GetBannedPersons {
// Make sure user is an admin // Make sure user is an admin
is_admin(&local_user_view)?; is_admin(&local_user_view)?;
let banned = blocking(context.pool(), PersonViewSafe::banned).await??; let banned = PersonViewSafe::banned(context.pool()).await?;
let res = Self::Response { banned }; let res = Self::Response { banned };

View file

@ -3,7 +3,7 @@ use actix_web::web::Data;
use bcrypt::verify; use bcrypt::verify;
use lemmy_api_common::{ use lemmy_api_common::{
person::{Login, LoginResponse}, person::{Login, LoginResponse},
utils::{blocking, check_registration_application, check_user_valid}, utils::{check_registration_application, check_user_valid},
}; };
use lemmy_db_schema::source::local_site::LocalSite; use lemmy_db_schema::source::local_site::LocalSite;
use lemmy_db_views::structs::LocalUserView; use lemmy_db_views::structs::LocalUserView;
@ -22,14 +22,12 @@ impl Perform for Login {
) -> Result<LoginResponse, LemmyError> { ) -> Result<LoginResponse, LemmyError> {
let data: &Login = self; let data: &Login = self;
let local_site = blocking(context.pool(), LocalSite::read).await??; let local_site = LocalSite::read(context.pool()).await?;
// 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();
let local_user_view = blocking(context.pool(), move |conn| { let local_user_view = LocalUserView::find_by_email_or_name(context.pool(), &username_or_email)
LocalUserView::find_by_email_or_name(conn, &username_or_email) .await
})
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_find_that_username_or_email"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_that_username_or_email"))?;
// Verify the password // Verify the password

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
person::{GetPersonMentions, GetPersonMentionsResponse}, person::{GetPersonMentions, GetPersonMentionsResponse},
utils::{blocking, get_local_user_view_from_jwt}, utils::get_local_user_view_from_jwt,
}; };
use lemmy_db_views_actor::person_mention_view::PersonMentionQuery; use lemmy_db_views_actor::person_mention_view::PersonMentionQuery;
use lemmy_utils::{error::LemmyError, ConnectionId}; use lemmy_utils::{error::LemmyError, ConnectionId};
@ -29,9 +29,8 @@ impl Perform for GetPersonMentions {
let person_id = Some(local_user_view.person.id); let person_id = Some(local_user_view.person.id);
let show_bot_accounts = Some(local_user_view.local_user.show_bot_accounts); let show_bot_accounts = Some(local_user_view.local_user.show_bot_accounts);
let mentions = blocking(context.pool(), move |conn| { let mentions = PersonMentionQuery::builder()
PersonMentionQuery::builder() .pool(context.pool())
.conn(conn)
.recipient_id(person_id) .recipient_id(person_id)
.my_person_id(person_id) .my_person_id(person_id)
.sort(sort) .sort(sort)
@ -41,8 +40,7 @@ impl Perform for GetPersonMentions {
.limit(limit) .limit(limit)
.build() .build()
.list() .list()
}) .await?;
.await??;
Ok(GetPersonMentionsResponse { mentions }) Ok(GetPersonMentionsResponse { mentions })
} }

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
person::{GetReplies, GetRepliesResponse}, person::{GetReplies, GetRepliesResponse},
utils::{blocking, get_local_user_view_from_jwt}, utils::get_local_user_view_from_jwt,
}; };
use lemmy_db_views_actor::comment_reply_view::CommentReplyQuery; use lemmy_db_views_actor::comment_reply_view::CommentReplyQuery;
use lemmy_utils::{error::LemmyError, ConnectionId}; use lemmy_utils::{error::LemmyError, ConnectionId};
@ -29,9 +29,8 @@ impl Perform for GetReplies {
let person_id = Some(local_user_view.person.id); let person_id = Some(local_user_view.person.id);
let show_bot_accounts = Some(local_user_view.local_user.show_bot_accounts); let show_bot_accounts = Some(local_user_view.local_user.show_bot_accounts);
let replies = blocking(context.pool(), move |conn| { let replies = CommentReplyQuery::builder()
CommentReplyQuery::builder() .pool(context.pool())
.conn(conn)
.recipient_id(person_id) .recipient_id(person_id)
.my_person_id(person_id) .my_person_id(person_id)
.sort(sort) .sort(sort)
@ -41,8 +40,7 @@ impl Perform for GetReplies {
.limit(limit) .limit(limit)
.build() .build()
.list() .list()
}) .await?;
.await??;
Ok(GetRepliesResponse { replies }) Ok(GetRepliesResponse { replies })
} }

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
person::{GetRepliesResponse, MarkAllAsRead}, person::{GetRepliesResponse, MarkAllAsRead},
utils::{blocking, get_local_user_view_from_jwt}, utils::get_local_user_view_from_jwt,
}; };
use lemmy_db_schema::source::{ use lemmy_db_schema::source::{
comment_reply::CommentReply, comment_reply::CommentReply,
@ -28,24 +28,18 @@ impl Perform for MarkAllAsRead {
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
// Mark all comment_replies as read // Mark all comment_replies as read
blocking(context.pool(), move |conn| { CommentReply::mark_all_as_read(context.pool(), person_id)
CommentReply::mark_all_as_read(conn, person_id) .await
})
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?;
// Mark all user mentions as read // Mark all user mentions as read
blocking(context.pool(), move |conn| { PersonMention::mark_all_as_read(context.pool(), person_id)
PersonMention::mark_all_as_read(conn, person_id) .await
})
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?;
// Mark all private_messages as read // Mark all private_messages as read
blocking(context.pool(), move |conn| { PrivateMessage::mark_all_as_read(context.pool(), person_id)
PrivateMessage::mark_all_as_read(conn, person_id) .await
})
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_update_private_message"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_private_message"))?;
Ok(GetRepliesResponse { replies: vec![] }) Ok(GetRepliesResponse { replies: vec![] })

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
person::{MarkPersonMentionAsRead, PersonMentionResponse}, person::{MarkPersonMentionAsRead, PersonMentionResponse},
utils::{blocking, get_local_user_view_from_jwt}, utils::get_local_user_view_from_jwt,
}; };
use lemmy_db_schema::{ use lemmy_db_schema::{
source::person_mention::{PersonMention, PersonMentionUpdateForm}, source::person_mention::{PersonMention, PersonMentionUpdateForm},
@ -27,10 +27,7 @@ impl Perform for MarkPersonMentionAsRead {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let person_mention_id = data.person_mention_id; let person_mention_id = data.person_mention_id;
let read_person_mention = blocking(context.pool(), move |conn| { let read_person_mention = PersonMention::read(context.pool(), person_mention_id).await?;
PersonMention::read(conn, person_mention_id)
})
.await??;
if local_user_view.person.id != read_person_mention.recipient_id { if local_user_view.person.id != read_person_mention.recipient_id {
return Err(LemmyError::from_message("couldnt_update_comment")); return Err(LemmyError::from_message("couldnt_update_comment"));
@ -38,18 +35,18 @@ impl Perform for MarkPersonMentionAsRead {
let person_mention_id = read_person_mention.id; let person_mention_id = read_person_mention.id;
let read = Some(data.read); let read = Some(data.read);
blocking(context.pool(), move |conn| { PersonMention::update(
PersonMention::update(conn, person_mention_id, &PersonMentionUpdateForm { read }) context.pool(),
}) person_mention_id,
.await? &PersonMentionUpdateForm { read },
)
.await
.map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?;
let person_mention_id = read_person_mention.id; let person_mention_id = read_person_mention.id;
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let person_mention_view = blocking(context.pool(), move |conn| { let person_mention_view =
PersonMentionView::read(conn, person_mention_id, Some(person_id)) PersonMentionView::read(context.pool(), person_mention_id, Some(person_id)).await?;
})
.await??;
Ok(PersonMentionResponse { Ok(PersonMentionResponse {
person_mention_view, person_mention_view,

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
person::{CommentReplyResponse, MarkCommentReplyAsRead}, person::{CommentReplyResponse, MarkCommentReplyAsRead},
utils::{blocking, get_local_user_view_from_jwt}, utils::get_local_user_view_from_jwt,
}; };
use lemmy_db_schema::{ use lemmy_db_schema::{
source::comment_reply::{CommentReply, CommentReplyUpdateForm}, source::comment_reply::{CommentReply, CommentReplyUpdateForm},
@ -27,10 +27,7 @@ impl Perform for MarkCommentReplyAsRead {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let comment_reply_id = data.comment_reply_id; let comment_reply_id = data.comment_reply_id;
let read_comment_reply = blocking(context.pool(), move |conn| { let read_comment_reply = CommentReply::read(context.pool(), comment_reply_id).await?;
CommentReply::read(conn, comment_reply_id)
})
.await??;
if local_user_view.person.id != read_comment_reply.recipient_id { if local_user_view.person.id != read_comment_reply.recipient_id {
return Err(LemmyError::from_message("couldnt_update_comment")); return Err(LemmyError::from_message("couldnt_update_comment"));
@ -38,18 +35,19 @@ impl Perform for MarkCommentReplyAsRead {
let comment_reply_id = read_comment_reply.id; let comment_reply_id = read_comment_reply.id;
let read = Some(data.read); let read = Some(data.read);
blocking(context.pool(), move |conn| {
CommentReply::update(conn, comment_reply_id, &CommentReplyUpdateForm { read }) CommentReply::update(
}) context.pool(),
.await? comment_reply_id,
&CommentReplyUpdateForm { read },
)
.await
.map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?;
let comment_reply_id = read_comment_reply.id; let comment_reply_id = read_comment_reply.id;
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let comment_reply_view = blocking(context.pool(), move |conn| { let comment_reply_view =
CommentReplyView::read(conn, comment_reply_id, Some(person_id)) CommentReplyView::read(context.pool(), comment_reply_id, Some(person_id)).await?;
})
.await??;
Ok(CommentReplyResponse { comment_reply_view }) Ok(CommentReplyResponse { comment_reply_view })
} }

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
person::{GetUnreadCount, GetUnreadCountResponse}, person::{GetUnreadCount, GetUnreadCountResponse},
utils::{blocking, get_local_user_view_from_jwt}, utils::get_local_user_view_from_jwt,
}; };
use lemmy_db_views::structs::PrivateMessageView; use lemmy_db_views::structs::PrivateMessageView;
use lemmy_db_views_actor::structs::{CommentReplyView, PersonMentionView}; use lemmy_db_views_actor::structs::{CommentReplyView, PersonMentionView};
@ -25,20 +25,12 @@ impl Perform for GetUnreadCount {
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let replies = blocking(context.pool(), move |conn| { let replies = CommentReplyView::get_unread_replies(context.pool(), person_id).await?;
CommentReplyView::get_unread_replies(conn, person_id)
})
.await??;
let mentions = blocking(context.pool(), move |conn| { let mentions = PersonMentionView::get_unread_mentions(context.pool(), person_id).await?;
PersonMentionView::get_unread_mentions(conn, person_id)
})
.await??;
let private_messages = blocking(context.pool(), move |conn| { let private_messages =
PrivateMessageView::get_unread_messages(conn, person_id) PrivateMessageView::get_unread_messages(context.pool(), person_id).await?;
})
.await??;
let res = Self::Response { let res = Self::Response {
replies, replies,

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
person::{GetReportCount, GetReportCountResponse}, person::{GetReportCount, GetReportCountResponse},
utils::{blocking, get_local_user_view_from_jwt}, utils::get_local_user_view_from_jwt,
}; };
use lemmy_db_views::structs::{CommentReportView, PostReportView, PrivateMessageReportView}; use lemmy_db_views::structs::{CommentReportView, PostReportView, PrivateMessageReportView};
use lemmy_utils::{error::LemmyError, ConnectionId}; use lemmy_utils::{error::LemmyError, ConnectionId};
@ -26,23 +26,14 @@ impl Perform for GetReportCount {
let admin = local_user_view.person.admin; let admin = local_user_view.person.admin;
let community_id = data.community_id; let community_id = data.community_id;
let comment_reports = blocking(context.pool(), move |conn| { let comment_reports =
CommentReportView::get_report_count(conn, person_id, admin, community_id) CommentReportView::get_report_count(context.pool(), person_id, admin, community_id).await?;
})
.await??;
let post_reports = blocking(context.pool(), move |conn| { let post_reports =
PostReportView::get_report_count(conn, person_id, admin, community_id) PostReportView::get_report_count(context.pool(), person_id, admin, community_id).await?;
})
.await??;
let private_message_reports = if admin && community_id.is_none() { let private_message_reports = if admin && community_id.is_none() {
Some( Some(PrivateMessageReportView::get_report_count(context.pool()).await?)
blocking(context.pool(), move |conn| {
PrivateMessageReportView::get_report_count(conn)
})
.await??,
)
} else { } else {
None None
}; };

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
person::{PasswordReset, PasswordResetResponse}, person::{PasswordReset, PasswordResetResponse},
utils::{blocking, send_password_reset_email}, utils::send_password_reset_email,
}; };
use lemmy_db_views::structs::LocalUserView; use lemmy_db_views::structs::LocalUserView;
use lemmy_utils::{error::LemmyError, ConnectionId}; use lemmy_utils::{error::LemmyError, ConnectionId};
@ -22,10 +22,8 @@ impl Perform for PasswordReset {
// Fetch that email // Fetch that email
let email = data.email.to_lowercase(); let email = data.email.to_lowercase();
let local_user_view = blocking(context.pool(), move |conn| { let local_user_view = LocalUserView::find_by_email(context.pool(), &email)
LocalUserView::find_by_email(conn, &email) .await
})
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_find_that_username_or_email"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_that_username_or_email"))?;
// Email the pure token to the user. // Email the pure token to the user.

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
person::{LoginResponse, SaveUserSettings}, person::{LoginResponse, SaveUserSettings},
utils::{blocking, get_local_user_view_from_jwt, send_verification_email}, utils::{get_local_user_view_from_jwt, send_verification_email},
}; };
use lemmy_db_schema::{ use lemmy_db_schema::{
source::{ source::{
@ -35,7 +35,7 @@ impl Perform for SaveUserSettings {
let data: &SaveUserSettings = self; let data: &SaveUserSettings = self;
let local_user_view = let local_user_view =
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let local_site = blocking(context.pool(), LocalSite::read).await??; let local_site = LocalSite::read(context.pool()).await?;
let avatar = diesel_option_overwrite_to_url(&data.avatar)?; let avatar = diesel_option_overwrite_to_url(&data.avatar)?;
let banner = diesel_option_overwrite_to_url(&data.banner)?; let banner = diesel_option_overwrite_to_url(&data.banner)?;
@ -97,17 +97,12 @@ impl Perform for SaveUserSettings {
.banner(banner) .banner(banner)
.build(); .build();
blocking(context.pool(), move |conn| { Person::update(context.pool(), person_id, &person_form)
Person::update(conn, person_id, &person_form) .await
})
.await?
.map_err(|e| LemmyError::from_error_message(e, "user_already_exists"))?; .map_err(|e| LemmyError::from_error_message(e, "user_already_exists"))?;
if let Some(discussion_languages) = data.discussion_languages.clone() { if let Some(discussion_languages) = data.discussion_languages.clone() {
blocking(context.pool(), move |conn| { LocalUserLanguage::update(context.pool(), discussion_languages, local_user_id).await?;
LocalUserLanguage::update(conn, discussion_languages, local_user_id)
})
.await??;
} }
let local_user_form = LocalUserUpdateForm::builder() let local_user_form = LocalUserUpdateForm::builder()
@ -125,10 +120,7 @@ impl Perform for SaveUserSettings {
.interface_language(data.interface_language.to_owned()) .interface_language(data.interface_language.to_owned())
.build(); .build();
let local_user_res = blocking(context.pool(), move |conn| { let local_user_res = LocalUser::update(context.pool(), local_user_id, &local_user_form).await;
LocalUser::update(conn, local_user_id, &local_user_form)
})
.await?;
let updated_local_user = match local_user_res { let updated_local_user = match local_user_res {
Ok(u) => u, Ok(u) => u,
Err(e) => { Err(e) => {

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
person::{VerifyEmail, VerifyEmailResponse}, person::{VerifyEmail, VerifyEmailResponse},
utils::{blocking, send_email_verification_success}, utils::send_email_verification_success,
}; };
use lemmy_db_schema::{ use lemmy_db_schema::{
source::{ source::{
@ -25,10 +25,8 @@ impl Perform for VerifyEmail {
_websocket_id: Option<usize>, _websocket_id: Option<usize>,
) -> Result<Self::Response, LemmyError> { ) -> Result<Self::Response, LemmyError> {
let token = self.token.clone(); let token = self.token.clone();
let verification = blocking(context.pool(), move |conn| { let verification = EmailVerification::read_for_token(context.pool(), &token)
EmailVerification::read_for_token(conn, &token) .await
})
.await?
.map_err(|e| LemmyError::from_error_message(e, "token_not_found"))?; .map_err(|e| LemmyError::from_error_message(e, "token_not_found"))?;
let form = LocalUserUpdateForm::builder() let form = LocalUserUpdateForm::builder()
@ -38,22 +36,14 @@ impl Perform for VerifyEmail {
.email(Some(Some(verification.email))) .email(Some(Some(verification.email)))
.build(); .build();
let local_user_id = verification.local_user_id; let local_user_id = verification.local_user_id;
blocking(context.pool(), move |conn| {
LocalUser::update(conn, local_user_id, &form)
})
.await??;
let local_user_view = blocking(context.pool(), move |conn| { LocalUser::update(context.pool(), local_user_id, &form).await?;
LocalUserView::read(conn, local_user_id)
}) let local_user_view = LocalUserView::read(context.pool(), local_user_id).await?;
.await??;
send_email_verification_success(&local_user_view, context.settings())?; send_email_verification_success(&local_user_view, context.settings())?;
blocking(context.pool(), move |conn| { EmailVerification::delete_old_tokens_for_local_user(context.pool(), local_user_id).await?;
EmailVerification::delete_old_tokens_for_local_user(conn, local_user_id)
})
.await??;
Ok(VerifyEmailResponse {}) Ok(VerifyEmailResponse {})
} }

View file

@ -3,7 +3,6 @@ use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
post::{CreatePostLike, PostResponse}, post::{CreatePostLike, PostResponse},
utils::{ utils::{
blocking,
check_community_ban, check_community_ban,
check_community_deleted_or_removed, check_community_deleted_or_removed,
check_downvotes_enabled, check_downvotes_enabled,
@ -42,16 +41,14 @@ impl Perform for CreatePostLike {
let data: &CreatePostLike = self; let data: &CreatePostLike = self;
let local_user_view = let local_user_view =
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let local_site = blocking(context.pool(), LocalSite::read).await??; let local_site = LocalSite::read(context.pool()).await?;
// Don't do a downvote if site has downvotes disabled // Don't do a downvote if site has downvotes disabled
check_downvotes_enabled(data.score, &local_site)?; check_downvotes_enabled(data.score, &local_site)?;
// Check for a community ban // Check for a community ban
let post_id = data.post_id; let post_id = data.post_id;
let post: ApubPost = blocking(context.pool(), move |conn| Post::read(conn, post_id)) let post: ApubPost = Post::read(context.pool(), post_id).await?.into();
.await??
.into();
check_community_ban(local_user_view.person.id, post.community_id, context.pool()).await?; check_community_ban(local_user_view.person.id, post.community_id, context.pool()).await?;
check_community_deleted_or_removed(post.community_id, context.pool()).await?; check_community_deleted_or_removed(post.community_id, context.pool()).await?;
@ -64,10 +61,8 @@ impl Perform for CreatePostLike {
// Remove any likes first // Remove any likes first
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
blocking(context.pool(), move |conn| {
PostLike::remove(conn, person_id, post_id) PostLike::remove(context.pool(), person_id, post_id).await?;
})
.await??;
let community_id = post.community_id; let community_id = post.community_id;
let object = PostOrComment::Post(Box::new(post)); let object = PostOrComment::Post(Box::new(post));
@ -76,9 +71,8 @@ impl Perform for CreatePostLike {
let do_add = like_form.score != 0 && (like_form.score == 1 || like_form.score == -1); let do_add = like_form.score != 0 && (like_form.score == 1 || like_form.score == -1);
if do_add { if do_add {
let like_form2 = like_form.clone(); let like_form2 = like_form.clone();
let like = move |conn: &mut _| PostLike::like(conn, &like_form2); PostLike::like(context.pool(), &like_form2)
blocking(context.pool(), like) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_like_post"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_like_post"))?;
Vote::send( Vote::send(

View file

@ -3,7 +3,6 @@ use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
post::{LockPost, PostResponse}, post::{LockPost, PostResponse},
utils::{ utils::{
blocking,
check_community_ban, check_community_ban,
check_community_deleted_or_removed, check_community_deleted_or_removed,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
@ -39,7 +38,7 @@ impl Perform for LockPost {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let post_id = data.post_id; let post_id = data.post_id;
let orig_post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; let orig_post = Post::read(context.pool(), post_id).await?;
check_community_ban( check_community_ban(
local_user_view.person.id, local_user_view.person.id,
@ -60,14 +59,12 @@ impl Perform for LockPost {
// Update the post // Update the post
let post_id = data.post_id; let post_id = data.post_id;
let locked = data.locked; let locked = data.locked;
let updated_post: ApubPost = blocking(context.pool(), move |conn| { let updated_post: ApubPost = Post::update(
Post::update( context.pool(),
conn,
post_id, post_id,
&PostUpdateForm::builder().locked(Some(locked)).build(), &PostUpdateForm::builder().locked(Some(locked)).build(),
) )
}) .await?
.await??
.into(); .into();
// Mod tables // Mod tables
@ -76,7 +73,7 @@ impl Perform for LockPost {
post_id: data.post_id, post_id: data.post_id,
locked: Some(locked), locked: Some(locked),
}; };
blocking(context.pool(), move |conn| ModLockPost::create(conn, &form)).await??; ModLockPost::create(context.pool(), &form).await?;
// apub updates // apub updates
CreateOrUpdatePost::send( CreateOrUpdatePost::send(

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
post::{MarkPostAsRead, PostResponse}, post::{MarkPostAsRead, PostResponse},
utils::{blocking, get_local_user_view_from_jwt, mark_post_as_read, mark_post_as_unread}, utils::{get_local_user_view_from_jwt, mark_post_as_read, mark_post_as_unread},
}; };
use lemmy_db_views::structs::PostView; use lemmy_db_views::structs::PostView;
use lemmy_utils::{error::LemmyError, ConnectionId}; use lemmy_utils::{error::LemmyError, ConnectionId};
@ -33,10 +33,7 @@ impl Perform for MarkPostAsRead {
} }
// Fetch it // Fetch it
let post_view = blocking(context.pool(), move |conn| { let post_view = PostView::read(context.pool(), post_id, Some(person_id)).await?;
PostView::read(conn, post_id, Some(person_id))
})
.await??;
let res = Self::Response { post_view }; let res = Self::Response { post_view };

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
post::{PostResponse, SavePost}, post::{PostResponse, SavePost},
utils::{blocking, get_local_user_view_from_jwt, mark_post_as_read}, utils::{get_local_user_view_from_jwt, mark_post_as_read},
}; };
use lemmy_db_schema::{ use lemmy_db_schema::{
source::post::{PostSaved, PostSavedForm}, source::post::{PostSaved, PostSavedForm},
@ -32,23 +32,18 @@ impl Perform for SavePost {
}; };
if data.save { if data.save {
let save = move |conn: &mut _| PostSaved::save(conn, &post_saved_form); PostSaved::save(context.pool(), &post_saved_form)
blocking(context.pool(), save) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_save_post"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_save_post"))?;
} else { } else {
let unsave = move |conn: &mut _| PostSaved::unsave(conn, &post_saved_form); PostSaved::unsave(context.pool(), &post_saved_form)
blocking(context.pool(), unsave) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_save_post"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_save_post"))?;
} }
let post_id = data.post_id; let post_id = data.post_id;
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let post_view = blocking(context.pool(), move |conn| { let post_view = PostView::read(context.pool(), post_id, Some(person_id)).await?;
PostView::read(conn, post_id, Some(person_id))
})
.await??;
// Mark the post as read // Mark the post as read
mark_post_as_read(person_id, post_id, context.pool()).await?; mark_post_as_read(person_id, post_id, context.pool()).await?;

View file

@ -3,7 +3,6 @@ use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
post::{PostResponse, StickyPost}, post::{PostResponse, StickyPost},
utils::{ utils::{
blocking,
check_community_ban, check_community_ban,
check_community_deleted_or_removed, check_community_deleted_or_removed,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
@ -39,7 +38,7 @@ impl Perform for StickyPost {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let post_id = data.post_id; let post_id = data.post_id;
let orig_post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; let orig_post = Post::read(context.pool(), post_id).await?;
check_community_ban( check_community_ban(
local_user_view.person.id, local_user_view.person.id,
@ -60,14 +59,12 @@ impl Perform for StickyPost {
// Update the post // Update the post
let post_id = data.post_id; let post_id = data.post_id;
let stickied = data.stickied; let stickied = data.stickied;
let updated_post: ApubPost = blocking(context.pool(), move |conn| { let updated_post: ApubPost = Post::update(
Post::update( context.pool(),
conn,
post_id, post_id,
&PostUpdateForm::builder().stickied(Some(stickied)).build(), &PostUpdateForm::builder().stickied(Some(stickied)).build(),
) )
}) .await?
.await??
.into(); .into();
// Mod tables // Mod tables
@ -76,10 +73,8 @@ impl Perform for StickyPost {
post_id: data.post_id, post_id: data.post_id,
stickied: Some(stickied), stickied: Some(stickied),
}; };
blocking(context.pool(), move |conn| {
ModStickyPost::create(conn, &form) ModStickyPost::create(context.pool(), &form).await?;
})
.await??;
// Apub updates // Apub updates
// TODO stickied should pry work like locked for ease of use // TODO stickied should pry work like locked for ease of use

View file

@ -3,7 +3,7 @@ use activitypub_federation::core::object_id::ObjectId;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
post::{CreatePostReport, PostReportResponse}, post::{CreatePostReport, PostReportResponse},
utils::{blocking, check_community_ban, get_local_user_view_from_jwt}, utils::{check_community_ban, get_local_user_view_from_jwt},
}; };
use lemmy_apub::protocol::activities::community::report::Report; use lemmy_apub::protocol::activities::community::report::Report;
use lemmy_db_schema::{ use lemmy_db_schema::{
@ -31,17 +31,14 @@ impl Perform for CreatePostReport {
let data: &CreatePostReport = self; let data: &CreatePostReport = self;
let local_user_view = let local_user_view =
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let local_site = blocking(context.pool(), LocalSite::read).await??; let local_site = LocalSite::read(context.pool()).await?;
let reason = self.reason.trim(); let reason = self.reason.trim();
check_report_reason(reason, &local_site)?; check_report_reason(reason, &local_site)?;
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let post_id = data.post_id; let post_id = data.post_id;
let post_view = blocking(context.pool(), move |conn| { let post_view = PostView::read(context.pool(), post_id, None).await?;
PostView::read(conn, post_id, None)
})
.await??;
check_community_ban(person_id, post_view.community.id, context.pool()).await?; check_community_ban(person_id, post_view.community.id, context.pool()).await?;
@ -54,16 +51,11 @@ impl Perform for CreatePostReport {
reason: reason.to_owned(), reason: reason.to_owned(),
}; };
let report = blocking(context.pool(), move |conn| { let report = PostReport::report(context.pool(), &report_form)
PostReport::report(conn, &report_form) .await
})
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_create_report"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_create_report"))?;
let post_report_view = blocking(context.pool(), move |conn| { let post_report_view = PostReportView::read(context.pool(), report.id, person_id).await?;
PostReportView::read(conn, report.id, person_id)
})
.await??;
let res = PostReportResponse { post_report_view }; let res = PostReportResponse { post_report_view };

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
post::{ListPostReports, ListPostReportsResponse}, post::{ListPostReports, ListPostReportsResponse},
utils::{blocking, get_local_user_view_from_jwt}, utils::get_local_user_view_from_jwt,
}; };
use lemmy_db_views::post_report_view::PostReportQuery; use lemmy_db_views::post_report_view::PostReportQuery;
use lemmy_utils::{error::LemmyError, ConnectionId}; use lemmy_utils::{error::LemmyError, ConnectionId};
@ -31,9 +31,8 @@ impl Perform for ListPostReports {
let page = data.page; let page = data.page;
let limit = data.limit; let limit = data.limit;
let post_reports = blocking(context.pool(), move |conn| { let post_reports = PostReportQuery::builder()
PostReportQuery::builder() .pool(context.pool())
.conn(conn)
.my_person_id(person_id) .my_person_id(person_id)
.admin(admin) .admin(admin)
.community_id(community_id) .community_id(community_id)
@ -42,8 +41,7 @@ impl Perform for ListPostReports {
.limit(limit) .limit(limit)
.build() .build()
.list() .list()
}) .await?;
.await??;
let res = ListPostReportsResponse { post_reports }; let res = ListPostReportsResponse { post_reports };

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
post::{PostReportResponse, ResolvePostReport}, post::{PostReportResponse, ResolvePostReport},
utils::{blocking, get_local_user_view_from_jwt, is_mod_or_admin}, utils::{get_local_user_view_from_jwt, is_mod_or_admin},
}; };
use lemmy_db_schema::{source::post_report::PostReport, traits::Reportable}; use lemmy_db_schema::{source::post_report::PostReport, traits::Reportable};
use lemmy_db_views::structs::PostReportView; use lemmy_db_views::structs::PostReportView;
@ -26,31 +26,22 @@ impl Perform for ResolvePostReport {
let report_id = data.report_id; let report_id = data.report_id;
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let report = blocking(context.pool(), move |conn| { let report = PostReportView::read(context.pool(), report_id, person_id).await?;
PostReportView::read(conn, report_id, person_id)
})
.await??;
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
is_mod_or_admin(context.pool(), person_id, report.community.id).await?; is_mod_or_admin(context.pool(), person_id, report.community.id).await?;
let resolved = data.resolved; if data.resolved {
let resolve_fun = move |conn: &mut _| { PostReport::resolve(context.pool(), report_id, person_id)
if resolved { .await
PostReport::resolve(conn, report_id, person_id)
} else {
PostReport::unresolve(conn, report_id, person_id)
}
};
blocking(context.pool(), resolve_fun)
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_resolve_report"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_resolve_report"))?;
} else {
PostReport::unresolve(context.pool(), report_id, person_id)
.await
.map_err(|e| LemmyError::from_error_message(e, "couldnt_resolve_report"))?;
}
let post_report_view = blocking(context.pool(), move |conn| { let post_report_view = PostReportView::read(context.pool(), report_id, person_id).await?;
PostReportView::read(conn, report_id, person_id)
})
.await??;
let res = PostReportResponse { post_report_view }; let res = PostReportResponse { post_report_view };

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
private_message::{MarkPrivateMessageAsRead, PrivateMessageResponse}, private_message::{MarkPrivateMessageAsRead, PrivateMessageResponse},
utils::{blocking, get_local_user_view_from_jwt}, utils::get_local_user_view_from_jwt,
}; };
use lemmy_db_schema::{ use lemmy_db_schema::{
source::private_message::{PrivateMessage, PrivateMessageUpdateForm}, source::private_message::{PrivateMessage, PrivateMessageUpdateForm},
@ -27,10 +27,7 @@ impl Perform for MarkPrivateMessageAsRead {
// Checking permissions // Checking permissions
let private_message_id = data.private_message_id; let private_message_id = data.private_message_id;
let orig_private_message = blocking(context.pool(), move |conn| { let orig_private_message = PrivateMessage::read(context.pool(), private_message_id).await?;
PrivateMessage::read(conn, private_message_id)
})
.await??;
if local_user_view.person.id != orig_private_message.recipient_id { if local_user_view.person.id != orig_private_message.recipient_id {
return Err(LemmyError::from_message("couldnt_update_private_message")); return Err(LemmyError::from_message("couldnt_update_private_message"));
} }
@ -38,14 +35,12 @@ impl Perform for MarkPrivateMessageAsRead {
// Doing the update // Doing the update
let private_message_id = data.private_message_id; let private_message_id = data.private_message_id;
let read = data.read; let read = data.read;
blocking(context.pool(), move |conn| {
PrivateMessage::update( PrivateMessage::update(
conn, context.pool(),
private_message_id, private_message_id,
&PrivateMessageUpdateForm::builder().read(Some(read)).build(), &PrivateMessageUpdateForm::builder().read(Some(read)).build(),
) )
}) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_update_private_message"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_private_message"))?;
// No need to send an apub update // No need to send an apub update

View file

@ -2,7 +2,7 @@ use crate::{check_report_reason, Perform};
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
private_message::{CreatePrivateMessageReport, PrivateMessageReportResponse}, private_message::{CreatePrivateMessageReport, PrivateMessageReportResponse},
utils::{blocking, get_local_user_view_from_jwt}, utils::get_local_user_view_from_jwt,
}; };
use lemmy_db_schema::{ use lemmy_db_schema::{
newtypes::CommunityId, newtypes::CommunityId,
@ -29,17 +29,14 @@ impl Perform for CreatePrivateMessageReport {
) -> Result<Self::Response, LemmyError> { ) -> Result<Self::Response, LemmyError> {
let local_user_view = let local_user_view =
get_local_user_view_from_jwt(&self.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&self.auth, context.pool(), context.secret()).await?;
let local_site = blocking(context.pool(), LocalSite::read).await??; let local_site = LocalSite::read(context.pool()).await?;
let reason = self.reason.trim(); let reason = self.reason.trim();
check_report_reason(reason, &local_site)?; check_report_reason(reason, &local_site)?;
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let private_message_id = self.private_message_id; let private_message_id = self.private_message_id;
let private_message = blocking(context.pool(), move |conn| { let private_message = PrivateMessage::read(context.pool(), private_message_id).await?;
PrivateMessage::read(conn, private_message_id)
})
.await??;
let report_form = PrivateMessageReportForm { let report_form = PrivateMessageReportForm {
creator_id: person_id, creator_id: person_id,
@ -48,16 +45,12 @@ impl Perform for CreatePrivateMessageReport {
reason: reason.to_owned(), reason: reason.to_owned(),
}; };
let report = blocking(context.pool(), move |conn| { let report = PrivateMessageReport::report(context.pool(), &report_form)
PrivateMessageReport::report(conn, &report_form) .await
})
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_create_report"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_create_report"))?;
let private_message_report_view = blocking(context.pool(), move |conn| { let private_message_report_view =
PrivateMessageReportView::read(conn, report.id) PrivateMessageReportView::read(context.pool(), report.id).await?;
})
.await??;
let res = PrivateMessageReportResponse { let res = PrivateMessageReportResponse {
private_message_report_view, private_message_report_view,

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
private_message::{ListPrivateMessageReports, ListPrivateMessageReportsResponse}, private_message::{ListPrivateMessageReports, ListPrivateMessageReportsResponse},
utils::{blocking, get_local_user_view_from_jwt, is_admin}, utils::{get_local_user_view_from_jwt, is_admin},
}; };
use lemmy_db_views::private_message_report_view::PrivateMessageReportQuery; use lemmy_db_views::private_message_report_view::PrivateMessageReportQuery;
use lemmy_utils::{error::LemmyError, ConnectionId}; use lemmy_utils::{error::LemmyError, ConnectionId};
@ -26,16 +26,14 @@ impl Perform for ListPrivateMessageReports {
let unresolved_only = self.unresolved_only; let unresolved_only = self.unresolved_only;
let page = self.page; let page = self.page;
let limit = self.limit; let limit = self.limit;
let private_message_reports = blocking(context.pool(), move |conn| { let private_message_reports = PrivateMessageReportQuery::builder()
PrivateMessageReportQuery::builder() .pool(context.pool())
.conn(conn)
.unresolved_only(unresolved_only) .unresolved_only(unresolved_only)
.page(page) .page(page)
.limit(limit) .limit(limit)
.build() .build()
.list() .list()
}) .await?;
.await??;
let res = ListPrivateMessageReportsResponse { let res = ListPrivateMessageReportsResponse {
private_message_reports, private_message_reports,

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
private_message::{PrivateMessageReportResponse, ResolvePrivateMessageReport}, private_message::{PrivateMessageReportResponse, ResolvePrivateMessageReport},
utils::{blocking, get_local_user_view_from_jwt, is_admin}, utils::{get_local_user_view_from_jwt, is_admin},
}; };
use lemmy_db_schema::{ use lemmy_db_schema::{
newtypes::CommunityId, newtypes::CommunityId,
@ -28,25 +28,20 @@ impl Perform for ResolvePrivateMessageReport {
is_admin(&local_user_view)?; is_admin(&local_user_view)?;
let resolved = self.resolved;
let report_id = self.report_id; let report_id = self.report_id;
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let resolve_fn = move |conn: &mut _| { if self.resolved {
if resolved { PrivateMessageReport::resolve(context.pool(), report_id, person_id)
PrivateMessageReport::resolve(conn, report_id, person_id) .await
} else {
PrivateMessageReport::unresolve(conn, report_id, person_id)
}
};
blocking(context.pool(), resolve_fn)
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_resolve_report"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_resolve_report"))?;
} else {
PrivateMessageReport::unresolve(context.pool(), report_id, person_id)
.await
.map_err(|e| LemmyError::from_error_message(e, "couldnt_resolve_report"))?;
}
let private_message_report_view = blocking(context.pool(), move |conn| { let private_message_report_view =
PrivateMessageReportView::read(conn, report_id) PrivateMessageReportView::read(context.pool(), report_id).await?;
})
.await??;
let res = PrivateMessageReportResponse { let res = PrivateMessageReportResponse {
private_message_report_view, private_message_report_view,

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
site::{GetSiteResponse, LeaveAdmin}, site::{GetSiteResponse, LeaveAdmin},
utils::{blocking, get_local_user_view_from_jwt, is_admin}, utils::{get_local_user_view_from_jwt, is_admin},
}; };
use lemmy_db_schema::{ use lemmy_db_schema::{
source::{ source::{
@ -35,20 +35,18 @@ impl Perform for LeaveAdmin {
is_admin(&local_user_view)?; is_admin(&local_user_view)?;
// Make sure there isn't just one admin (so if one leaves, there will still be one left) // Make sure there isn't just one admin (so if one leaves, there will still be one left)
let admins = blocking(context.pool(), PersonViewSafe::admins).await??; let admins = PersonViewSafe::admins(context.pool()).await?;
if admins.len() == 1 { if admins.len() == 1 {
return Err(LemmyError::from_message("cannot_leave_admin")); return Err(LemmyError::from_message("cannot_leave_admin"));
} }
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
blocking(context.pool(), move |conn| {
Person::update( Person::update(
conn, context.pool(),
person_id, person_id,
&PersonUpdateForm::builder().admin(Some(false)).build(), &PersonUpdateForm::builder().admin(Some(false)).build(),
) )
}) .await?;
.await??;
// Mod tables // Mod tables
let form = ModAddForm { let form = ModAddForm {
@ -57,14 +55,14 @@ impl Perform for LeaveAdmin {
removed: Some(true), removed: Some(true),
}; };
blocking(context.pool(), move |conn| ModAdd::create(conn, &form)).await??; ModAdd::create(context.pool(), &form).await?;
// Reread site and admins // Reread site and admins
let site_view = blocking(context.pool(), SiteView::read_local).await??; let site_view = SiteView::read_local(context.pool()).await?;
let admins = blocking(context.pool(), PersonViewSafe::admins).await??; let admins = PersonViewSafe::admins(context.pool()).await?;
let all_languages = blocking(context.pool(), Language::read_all).await??; let all_languages = Language::read_all(context.pool()).await?;
let discussion_languages = blocking(context.pool(), SiteLanguage::read_local).await??; let discussion_languages = SiteLanguage::read_local(context.pool()).await?;
Ok(GetSiteResponse { Ok(GetSiteResponse {
site_view, site_view,

View file

@ -2,13 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
site::{GetModlog, GetModlogResponse}, site::{GetModlog, GetModlogResponse},
utils::{ utils::{check_private_instance, get_local_user_view_from_jwt_opt, is_admin, is_mod_or_admin},
blocking,
check_private_instance,
get_local_user_view_from_jwt_opt,
is_admin,
is_mod_or_admin,
},
}; };
use lemmy_db_schema::{ use lemmy_db_schema::{
newtypes::{CommunityId, PersonId}, newtypes::{CommunityId, PersonId},
@ -52,7 +46,7 @@ impl Perform for GetModlog {
let local_user_view = let local_user_view =
get_local_user_view_from_jwt_opt(data.auth.as_ref(), context.pool(), context.secret()) get_local_user_view_from_jwt_opt(data.auth.as_ref(), context.pool(), context.secret())
.await?; .await?;
let local_site = blocking(context.pool(), LocalSite::read).await??; let local_site = LocalSite::read(context.pool()).await?;
check_private_instance(&local_user_view, &local_site)?; check_private_instance(&local_user_view, &local_site)?;
@ -88,81 +82,43 @@ impl Perform for GetModlog {
hide_modlog_names, hide_modlog_names,
}; };
let removed_posts = match type_ { let removed_posts = match type_ {
All | ModRemovePost => { All | ModRemovePost => ModRemovePostView::list(context.pool(), params).await?,
blocking(context.pool(), move |conn| {
ModRemovePostView::list(conn, params)
})
.await??
}
_ => Default::default(), _ => Default::default(),
}; };
let locked_posts = match type_ { let locked_posts = match type_ {
All | ModLockPost => { All | ModLockPost => ModLockPostView::list(context.pool(), params).await?,
blocking(context.pool(), move |conn| {
ModLockPostView::list(conn, params)
})
.await??
}
_ => Default::default(), _ => Default::default(),
}; };
let stickied_posts = match type_ { let stickied_posts = match type_ {
All | ModStickyPost => { All | ModStickyPost => ModStickyPostView::list(context.pool(), params).await?,
blocking(context.pool(), move |conn| {
ModStickyPostView::list(conn, params)
})
.await??
}
_ => Default::default(), _ => Default::default(),
}; };
let removed_comments = match type_ { let removed_comments = match type_ {
All | ModRemoveComment => { All | ModRemoveComment => ModRemoveCommentView::list(context.pool(), params).await?,
blocking(context.pool(), move |conn| {
ModRemoveCommentView::list(conn, params)
})
.await??
}
_ => Default::default(), _ => Default::default(),
}; };
let banned_from_community = match type_ { let banned_from_community = match type_ {
All | ModBanFromCommunity => { All | ModBanFromCommunity => ModBanFromCommunityView::list(context.pool(), params).await?,
blocking(context.pool(), move |conn| {
ModBanFromCommunityView::list(conn, params)
})
.await??
}
_ => Default::default(), _ => Default::default(),
}; };
let added_to_community = match type_ { let added_to_community = match type_ {
All | ModAddCommunity => { All | ModAddCommunity => ModAddCommunityView::list(context.pool(), params).await?,
blocking(context.pool(), move |conn| {
ModAddCommunityView::list(conn, params)
})
.await??
}
_ => Default::default(), _ => Default::default(),
}; };
let transferred_to_community = match type_ { let transferred_to_community = match type_ {
All | ModTransferCommunity => { All | ModTransferCommunity => ModTransferCommunityView::list(context.pool(), params).await?,
blocking(context.pool(), move |conn| {
ModTransferCommunityView::list(conn, params)
})
.await??
}
_ => Default::default(), _ => Default::default(),
}; };
let hidden_communities = match type_ { let hidden_communities = match type_ {
All | ModHideCommunity if other_person_id.is_none() => { All | ModHideCommunity if other_person_id.is_none() => {
blocking(context.pool(), move |conn| { ModHideCommunityView::list(context.pool(), params).await?
ModHideCommunityView::list(conn, params)
})
.await??
} }
_ => Default::default(), _ => Default::default(),
}; };
@ -177,49 +133,46 @@ impl Perform for GetModlog {
admin_purged_posts, admin_purged_posts,
admin_purged_comments, admin_purged_comments,
) = if data.community_id.is_none() { ) = if data.community_id.is_none() {
blocking(context.pool(), move |conn| { (
Ok((
match type_ { match type_ {
All | ModBan => ModBanView::list(conn, params)?, All | ModBan => ModBanView::list(context.pool(), params).await?,
_ => Default::default(), _ => Default::default(),
}, },
match type_ { match type_ {
All | ModAdd => ModAddView::list(conn, params)?, All | ModAdd => ModAddView::list(context.pool(), params).await?,
_ => Default::default(), _ => Default::default(),
}, },
match type_ { match type_ {
All | ModRemoveCommunity if other_person_id.is_none() => { All | ModRemoveCommunity if other_person_id.is_none() => {
ModRemoveCommunityView::list(conn, params)? ModRemoveCommunityView::list(context.pool(), params).await?
} }
_ => Default::default(), _ => Default::default(),
}, },
match type_ { match type_ {
All | AdminPurgePerson if other_person_id.is_none() => { All | AdminPurgePerson if other_person_id.is_none() => {
AdminPurgePersonView::list(conn, params)? AdminPurgePersonView::list(context.pool(), params).await?
} }
_ => Default::default(), _ => Default::default(),
}, },
match type_ { match type_ {
All | AdminPurgeCommunity if other_person_id.is_none() => { All | AdminPurgeCommunity if other_person_id.is_none() => {
AdminPurgeCommunityView::list(conn, params)? AdminPurgeCommunityView::list(context.pool(), params).await?
} }
_ => Default::default(), _ => Default::default(),
}, },
match type_ { match type_ {
All | AdminPurgePost if other_person_id.is_none() => { All | AdminPurgePost if other_person_id.is_none() => {
AdminPurgePostView::list(conn, params)? AdminPurgePostView::list(context.pool(), params).await?
} }
_ => Default::default(), _ => Default::default(),
}, },
match type_ { match type_ {
All | AdminPurgeComment if other_person_id.is_none() => { All | AdminPurgeComment if other_person_id.is_none() => {
AdminPurgeCommentView::list(conn, params)? AdminPurgeCommentView::list(context.pool(), params).await?
} }
_ => Default::default(), _ => Default::default(),
}, },
)) as Result<_, LemmyError> )
})
.await??
} else { } else {
Default::default() Default::default()
}; };

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
site::{PurgeComment, PurgeItemResponse}, site::{PurgeComment, PurgeItemResponse},
utils::{blocking, get_local_user_view_from_jwt, is_admin}, utils::{get_local_user_view_from_jwt, is_admin},
}; };
use lemmy_db_schema::{ use lemmy_db_schema::{
source::{ source::{
@ -34,16 +34,13 @@ impl Perform for PurgeComment {
let comment_id = data.comment_id; let comment_id = data.comment_id;
// Read the comment to get the post_id // Read the comment to get the post_id
let comment = blocking(context.pool(), move |conn| Comment::read(conn, comment_id)).await??; let comment = Comment::read(context.pool(), comment_id).await?;
let post_id = comment.post_id; let post_id = comment.post_id;
// TODO read comments for pictrs images and purge them // TODO read comments for pictrs images and purge them
blocking(context.pool(), move |conn| { Comment::delete(context.pool(), comment_id).await?;
Comment::delete(conn, comment_id)
})
.await??;
// Mod tables // Mod tables
let reason = data.reason.to_owned(); let reason = data.reason.to_owned();
@ -53,10 +50,7 @@ impl Perform for PurgeComment {
post_id, post_id,
}; };
blocking(context.pool(), move |conn| { AdminPurgeComment::create(context.pool(), &form).await?;
AdminPurgeComment::create(conn, &form)
})
.await??;
Ok(PurgeItemResponse { success: true }) Ok(PurgeItemResponse { success: true })
} }

View file

@ -3,7 +3,7 @@ use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
request::purge_image_from_pictrs, request::purge_image_from_pictrs,
site::{PurgeCommunity, PurgeItemResponse}, site::{PurgeCommunity, PurgeItemResponse},
utils::{blocking, get_local_user_view_from_jwt, is_admin, purge_image_posts_for_community}, utils::{get_local_user_view_from_jwt, is_admin, purge_image_posts_for_community},
}; };
use lemmy_db_schema::{ use lemmy_db_schema::{
source::{ source::{
@ -35,10 +35,7 @@ impl Perform for PurgeCommunity {
let community_id = data.community_id; let community_id = data.community_id;
// Read the community to get its images // Read the community to get its images
let community = blocking(context.pool(), move |conn| { let community = Community::read(context.pool(), community_id).await?;
Community::read(conn, community_id)
})
.await??;
if let Some(banner) = community.banner { if let Some(banner) = community.banner {
purge_image_from_pictrs(context.client(), context.settings(), &banner) purge_image_from_pictrs(context.client(), context.settings(), &banner)
@ -60,10 +57,7 @@ impl Perform for PurgeCommunity {
) )
.await?; .await?;
blocking(context.pool(), move |conn| { Community::delete(context.pool(), community_id).await?;
Community::delete(conn, community_id)
})
.await??;
// Mod tables // Mod tables
let reason = data.reason.to_owned(); let reason = data.reason.to_owned();
@ -72,10 +66,7 @@ impl Perform for PurgeCommunity {
reason, reason,
}; };
blocking(context.pool(), move |conn| { AdminPurgeCommunity::create(context.pool(), &form).await?;
AdminPurgeCommunity::create(conn, &form)
})
.await??;
Ok(PurgeItemResponse { success: true }) Ok(PurgeItemResponse { success: true })
} }

View file

@ -3,7 +3,7 @@ use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
request::purge_image_from_pictrs, request::purge_image_from_pictrs,
site::{PurgeItemResponse, PurgePerson}, site::{PurgeItemResponse, PurgePerson},
utils::{blocking, get_local_user_view_from_jwt, is_admin, purge_image_posts_for_person}, utils::{get_local_user_view_from_jwt, is_admin, purge_image_posts_for_person},
}; };
use lemmy_db_schema::{ use lemmy_db_schema::{
source::{ source::{
@ -34,7 +34,7 @@ impl Perform for PurgePerson {
// Read the person to get their images // Read the person to get their images
let person_id = data.person_id; let person_id = data.person_id;
let person = blocking(context.pool(), move |conn| Person::read(conn, person_id)).await??; let person = Person::read(context.pool(), person_id).await?;
if let Some(banner) = person.banner { if let Some(banner) = person.banner {
purge_image_from_pictrs(context.client(), context.settings(), &banner) purge_image_from_pictrs(context.client(), context.settings(), &banner)
@ -56,7 +56,7 @@ impl Perform for PurgePerson {
) )
.await?; .await?;
blocking(context.pool(), move |conn| Person::delete(conn, person_id)).await??; Person::delete(context.pool(), person_id).await?;
// Mod tables // Mod tables
let reason = data.reason.to_owned(); let reason = data.reason.to_owned();
@ -65,10 +65,7 @@ impl Perform for PurgePerson {
reason, reason,
}; };
blocking(context.pool(), move |conn| { AdminPurgePerson::create(context.pool(), &form).await?;
AdminPurgePerson::create(conn, &form)
})
.await??;
Ok(PurgeItemResponse { success: true }) Ok(PurgeItemResponse { success: true })
} }

View file

@ -3,7 +3,7 @@ use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
request::purge_image_from_pictrs, request::purge_image_from_pictrs,
site::{PurgeItemResponse, PurgePost}, site::{PurgeItemResponse, PurgePost},
utils::{blocking, get_local_user_view_from_jwt, is_admin}, utils::{get_local_user_view_from_jwt, is_admin},
}; };
use lemmy_db_schema::{ use lemmy_db_schema::{
source::{ source::{
@ -35,7 +35,7 @@ impl Perform for PurgePost {
let post_id = data.post_id; let post_id = data.post_id;
// Read the post to get the community_id // Read the post to get the community_id
let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; let post = Post::read(context.pool(), post_id).await?;
// Purge image // Purge image
if let Some(url) = post.url { if let Some(url) = post.url {
@ -52,7 +52,7 @@ impl Perform for PurgePost {
let community_id = post.community_id; let community_id = post.community_id;
blocking(context.pool(), move |conn| Post::delete(conn, post_id)).await??; Post::delete(context.pool(), post_id).await?;
// Mod tables // Mod tables
let reason = data.reason.to_owned(); let reason = data.reason.to_owned();
@ -62,10 +62,7 @@ impl Perform for PurgePost {
community_id, community_id,
}; };
blocking(context.pool(), move |conn| { AdminPurgePost::create(context.pool(), &form).await?;
AdminPurgePost::create(conn, &form)
})
.await??;
Ok(PurgeItemResponse { success: true }) Ok(PurgeItemResponse { success: true })
} }

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
site::{ApproveRegistrationApplication, RegistrationApplicationResponse}, site::{ApproveRegistrationApplication, RegistrationApplicationResponse},
utils::{blocking, get_local_user_view_from_jwt, is_admin, send_application_approved_email}, utils::{get_local_user_view_from_jwt, is_admin, send_application_approved_email},
}; };
use lemmy_db_schema::{ use lemmy_db_schema::{
source::{ source::{
@ -41,10 +41,8 @@ impl Perform for ApproveRegistrationApplication {
deny_reason, deny_reason,
}; };
let registration_application = blocking(context.pool(), move |conn| { let registration_application =
RegistrationApplication::update(conn, app_id, &app_form) RegistrationApplication::update(context.pool(), app_id, &app_form).await?;
})
.await??;
// Update the local_user row // Update the local_user row
let local_user_form = LocalUserUpdateForm::builder() let local_user_form = LocalUserUpdateForm::builder()
@ -52,16 +50,10 @@ impl Perform for ApproveRegistrationApplication {
.build(); .build();
let approved_user_id = registration_application.local_user_id; let approved_user_id = registration_application.local_user_id;
blocking(context.pool(), move |conn| { LocalUser::update(context.pool(), approved_user_id, &local_user_form).await?;
LocalUser::update(conn, approved_user_id, &local_user_form)
})
.await??;
if data.approve { if data.approve {
let approved_local_user_view = blocking(context.pool(), move |conn| { let approved_local_user_view = LocalUserView::read(context.pool(), approved_user_id).await?;
LocalUserView::read(conn, approved_user_id)
})
.await??;
if approved_local_user_view.local_user.email.is_some() { if approved_local_user_view.local_user.email.is_some() {
send_application_approved_email(&approved_local_user_view, context.settings())?; send_application_approved_email(&approved_local_user_view, context.settings())?;
@ -69,10 +61,8 @@ impl Perform for ApproveRegistrationApplication {
} }
// Read the view // Read the view
let registration_application = blocking(context.pool(), move |conn| { let registration_application =
RegistrationApplicationView::read(conn, app_id) RegistrationApplicationView::read(context.pool(), app_id).await?;
})
.await??;
Ok(Self::Response { Ok(Self::Response {
registration_application, registration_application,

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
site::{ListRegistrationApplications, ListRegistrationApplicationsResponse}, site::{ListRegistrationApplications, ListRegistrationApplicationsResponse},
utils::{blocking, get_local_user_view_from_jwt, is_admin}, utils::{get_local_user_view_from_jwt, is_admin},
}; };
use lemmy_db_schema::source::local_site::LocalSite; use lemmy_db_schema::source::local_site::LocalSite;
use lemmy_db_views::registration_application_view::RegistrationApplicationQuery; use lemmy_db_views::registration_application_view::RegistrationApplicationQuery;
@ -22,7 +22,7 @@ impl Perform for ListRegistrationApplications {
let data = self; let data = self;
let local_user_view = let local_user_view =
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let local_site = blocking(context.pool(), LocalSite::read).await??; let local_site = LocalSite::read(context.pool()).await?;
// Make sure user is an admin // Make sure user is an admin
is_admin(&local_user_view)?; is_admin(&local_user_view)?;
@ -32,17 +32,15 @@ impl Perform for ListRegistrationApplications {
let page = data.page; let page = data.page;
let limit = data.limit; let limit = data.limit;
let registration_applications = blocking(context.pool(), move |conn| { let registration_applications = RegistrationApplicationQuery::builder()
RegistrationApplicationQuery::builder() .pool(context.pool())
.conn(conn)
.unread_only(unread_only) .unread_only(unread_only)
.verified_email_only(Some(verified_email_only)) .verified_email_only(Some(verified_email_only))
.page(page) .page(page)
.limit(limit) .limit(limit)
.build() .build()
.list() .list()
}) .await?;
.await??;
let res = Self::Response { let res = Self::Response {
registration_applications, registration_applications,

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
site::{GetUnreadRegistrationApplicationCount, GetUnreadRegistrationApplicationCountResponse}, site::{GetUnreadRegistrationApplicationCount, GetUnreadRegistrationApplicationCountResponse},
utils::{blocking, get_local_user_view_from_jwt, is_admin}, utils::{get_local_user_view_from_jwt, is_admin},
}; };
use lemmy_db_schema::source::local_site::LocalSite; use lemmy_db_schema::source::local_site::LocalSite;
use lemmy_db_views::structs::RegistrationApplicationView; use lemmy_db_views::structs::RegistrationApplicationView;
@ -21,17 +21,15 @@ impl Perform for GetUnreadRegistrationApplicationCount {
let data = self; let data = self;
let local_user_view = let local_user_view =
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let local_site = blocking(context.pool(), LocalSite::read).await??; let local_site = LocalSite::read(context.pool()).await?;
// Only let admins do this // Only let admins do this
is_admin(&local_user_view)?; is_admin(&local_user_view)?;
let verified_email_only = local_site.require_email_verification; let verified_email_only = local_site.require_email_verification;
let registration_applications = blocking(context.pool(), move |conn| { let registration_applications =
RegistrationApplicationView::get_unread_count(conn, verified_email_only) RegistrationApplicationView::get_unread_count(context.pool(), verified_email_only).await?;
})
.await??;
Ok(Self::Response { Ok(Self::Response {
registration_applications, registration_applications,

View file

@ -3,7 +3,7 @@ use actix_web::web::Data;
use diesel::NotFound; use diesel::NotFound;
use lemmy_api_common::{ use lemmy_api_common::{
site::{ResolveObject, ResolveObjectResponse}, site::{ResolveObject, ResolveObjectResponse},
utils::{blocking, check_private_instance, get_local_user_view_from_jwt_opt}, utils::{check_private_instance, get_local_user_view_from_jwt_opt},
}; };
use lemmy_apub::fetcher::search::{search_query_to_object_id, SearchableObjects}; use lemmy_apub::fetcher::search::{search_query_to_object_id, SearchableObjects};
use lemmy_db_schema::{newtypes::PersonId, source::local_site::LocalSite, utils::DbPool}; use lemmy_db_schema::{newtypes::PersonId, source::local_site::LocalSite, utils::DbPool};
@ -25,7 +25,7 @@ impl Perform for ResolveObject {
let local_user_view = let local_user_view =
get_local_user_view_from_jwt_opt(self.auth.as_ref(), context.pool(), context.secret()) get_local_user_view_from_jwt_opt(self.auth.as_ref(), context.pool(), context.secret())
.await?; .await?;
let local_site = blocking(context.pool(), LocalSite::read).await??; let local_site = LocalSite::read(context.pool()).await?;
check_private_instance(&local_user_view, &local_site)?; check_private_instance(&local_user_view, &local_site)?;
let res = search_query_to_object_id(&self.q, local_user_view.is_none(), context) let res = search_query_to_object_id(&self.q, local_user_view.is_none(), context)
@ -53,20 +53,19 @@ async fn convert_response(
match object { match object {
Person(p) => { Person(p) => {
removed_or_deleted = p.deleted; removed_or_deleted = p.deleted;
res.person = Some(blocking(pool, move |conn| PersonViewSafe::read(conn, p.id)).await??) res.person = Some(PersonViewSafe::read(pool, p.id).await?)
} }
Community(c) => { Community(c) => {
removed_or_deleted = c.deleted || c.removed; removed_or_deleted = c.deleted || c.removed;
res.community = res.community = Some(CommunityView::read(pool, c.id, user_id).await?)
Some(blocking(pool, move |conn| CommunityView::read(conn, c.id, user_id)).await??)
} }
Post(p) => { Post(p) => {
removed_or_deleted = p.deleted || p.removed; removed_or_deleted = p.deleted || p.removed;
res.post = Some(blocking(pool, move |conn| PostView::read(conn, p.id, user_id)).await??) res.post = Some(PostView::read(pool, p.id, user_id).await?)
} }
Comment(c) => { Comment(c) => {
removed_or_deleted = c.deleted || c.removed; removed_or_deleted = c.deleted || c.removed;
res.comment = Some(blocking(pool, move |conn| CommentView::read(conn, c.id, user_id)).await??) res.comment = Some(CommentView::read(pool, c.id, user_id).await?)
} }
}; };
// if the object was deleted from database, dont return it // if the object was deleted from database, dont return it

View file

@ -2,7 +2,7 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
site::{Search, SearchResponse}, site::{Search, SearchResponse},
utils::{blocking, check_private_instance, get_local_user_view_from_jwt_opt}, utils::{check_private_instance, get_local_user_view_from_jwt_opt},
}; };
use lemmy_apub::{fetcher::resolve_actor_identifier, objects::community::ApubCommunity}; use lemmy_apub::{fetcher::resolve_actor_identifier, objects::community::ApubCommunity};
use lemmy_db_schema::{ use lemmy_db_schema::{
@ -31,7 +31,7 @@ impl Perform for Search {
let local_user_view = let local_user_view =
get_local_user_view_from_jwt_opt(data.auth.as_ref(), context.pool(), context.secret()) get_local_user_view_from_jwt_opt(data.auth.as_ref(), context.pool(), context.secret())
.await?; .await?;
let local_site = blocking(context.pool(), LocalSite::read).await??; let local_site = LocalSite::read(context.pool()).await?;
check_private_instance(&local_user_view, &local_site)?; check_private_instance(&local_user_view, &local_site)?;
@ -63,9 +63,8 @@ impl Perform for Search {
let creator_id = data.creator_id; let creator_id = data.creator_id;
match search_type { match search_type {
SearchType::Posts => { SearchType::Posts => {
posts = blocking(context.pool(), move |conn| { posts = PostQuery::builder()
PostQuery::builder() .pool(context.pool())
.conn(conn)
.sort(sort) .sort(sort)
.listing_type(listing_type) .listing_type(listing_type)
.community_id(community_id) .community_id(community_id)
@ -77,13 +76,11 @@ impl Perform for Search {
.limit(limit) .limit(limit)
.build() .build()
.list() .list()
}) .await?;
.await??;
} }
SearchType::Comments => { SearchType::Comments => {
comments = blocking(context.pool(), move |conn| { comments = CommentQuery::builder()
CommentQuery::builder() .pool(context.pool())
.conn(conn)
.sort(sort.map(post_to_comment_sort_type)) .sort(sort.map(post_to_comment_sort_type))
.listing_type(listing_type) .listing_type(listing_type)
.search_term(Some(q)) .search_term(Some(q))
@ -95,13 +92,11 @@ impl Perform for Search {
.limit(limit) .limit(limit)
.build() .build()
.list() .list()
}) .await?;
.await??;
} }
SearchType::Communities => { SearchType::Communities => {
communities = blocking(context.pool(), move |conn| { communities = CommunityQuery::builder()
CommunityQuery::builder() .pool(context.pool())
.conn(conn)
.sort(sort) .sort(sort)
.listing_type(listing_type) .listing_type(listing_type)
.search_term(Some(q)) .search_term(Some(q))
@ -110,21 +105,18 @@ impl Perform for Search {
.limit(limit) .limit(limit)
.build() .build()
.list() .list()
}) .await?;
.await??;
} }
SearchType::Users => { SearchType::Users => {
users = blocking(context.pool(), move |conn| { users = PersonQuery::builder()
PersonQuery::builder() .pool(context.pool())
.conn(conn)
.sort(sort) .sort(sort)
.search_term(Some(q)) .search_term(Some(q))
.page(page) .page(page)
.limit(limit) .limit(limit)
.build() .build()
.list() .list()
}) .await?;
.await??;
} }
SearchType::All => { SearchType::All => {
// If the community or creator is included, dont search communities or users // If the community or creator is included, dont search communities or users
@ -133,9 +125,8 @@ impl Perform for Search {
let community_actor_id_2 = community_actor_id.to_owned(); let community_actor_id_2 = community_actor_id.to_owned();
let local_user_ = local_user.clone(); let local_user_ = local_user.clone();
posts = blocking(context.pool(), move |conn| { posts = PostQuery::builder()
PostQuery::builder() .pool(context.pool())
.conn(conn)
.sort(sort) .sort(sort)
.listing_type(listing_type) .listing_type(listing_type)
.community_id(community_id) .community_id(community_id)
@ -147,16 +138,14 @@ impl Perform for Search {
.limit(limit) .limit(limit)
.build() .build()
.list() .list()
}) .await?;
.await??;
let q = data.q.to_owned(); let q = data.q.to_owned();
let community_actor_id = community_actor_id.to_owned(); let community_actor_id = community_actor_id.to_owned();
let local_user_ = local_user.clone(); let local_user_ = local_user.clone();
comments = blocking(context.pool(), move |conn| { comments = CommentQuery::builder()
CommentQuery::builder() .pool(context.pool())
.conn(conn)
.sort(sort.map(post_to_comment_sort_type)) .sort(sort.map(post_to_comment_sort_type))
.listing_type(listing_type) .listing_type(listing_type)
.search_term(Some(q)) .search_term(Some(q))
@ -168,17 +157,15 @@ impl Perform for Search {
.limit(limit) .limit(limit)
.build() .build()
.list() .list()
}) .await?;
.await??;
let q = data.q.to_owned(); let q = data.q.to_owned();
communities = if community_or_creator_included { communities = if community_or_creator_included {
vec![] vec![]
} else { } else {
blocking(context.pool(), move |conn| {
CommunityQuery::builder() CommunityQuery::builder()
.conn(conn) .pool(context.pool())
.sort(sort) .sort(sort)
.listing_type(listing_type) .listing_type(listing_type)
.search_term(Some(q)) .search_term(Some(q))
@ -187,8 +174,7 @@ impl Perform for Search {
.limit(limit) .limit(limit)
.build() .build()
.list() .list()
}) .await?
.await??
}; };
let q = data.q.to_owned(); let q = data.q.to_owned();
@ -196,23 +182,20 @@ impl Perform for Search {
users = if community_or_creator_included { users = if community_or_creator_included {
vec![] vec![]
} else { } else {
blocking(context.pool(), move |conn| {
PersonQuery::builder() PersonQuery::builder()
.conn(conn) .pool(context.pool())
.sort(sort) .sort(sort)
.search_term(Some(q)) .search_term(Some(q))
.page(page) .page(page)
.limit(limit) .limit(limit)
.build() .build()
.list() .list()
}) .await?
.await??
}; };
} }
SearchType::Url => { SearchType::Url => {
posts = blocking(context.pool(), move |conn| { posts = PostQuery::builder()
PostQuery::builder() .pool(context.pool())
.conn(conn)
.sort(sort) .sort(sort)
.listing_type(listing_type) .listing_type(listing_type)
.community_id(community_id) .community_id(community_id)
@ -223,8 +206,7 @@ impl Perform for Search {
.limit(limit) .limit(limit)
.build() .build()
.list() .list()
}) .await?;
.await??;
} }
}; };

View file

@ -24,11 +24,11 @@ lemmy_db_views_moderator = { version = "=0.16.5", path = "../db_views_moderator"
lemmy_db_views_actor = { version = "=0.16.5", path = "../db_views_actor" } lemmy_db_views_actor = { version = "=0.16.5", path = "../db_views_actor" }
lemmy_db_schema = { version = "=0.16.5", path = "../db_schema", default-features = false } lemmy_db_schema = { version = "=0.16.5", path = "../db_schema", default-features = false }
lemmy_utils = { version = "=0.16.5", path = "../utils", optional = true } lemmy_utils = { version = "=0.16.5", path = "../utils", optional = true }
serde = { version = "1.0.145", features = ["derive"] } serde = { version = "1.0.147", features = ["derive"] }
url = "2.3.1" url = "2.3.1"
actix-web = { version = "4.2.1", default-features = false, features = ["cookies"], optional = true } actix-web = { version = "4.2.1", default-features = false, features = ["cookies"], optional = true }
chrono = { version = "0.4.22", features = ["serde"], optional = true } chrono = { version = "0.4.22", features = ["serde"], optional = true }
diesel = { version = "2.0.0", optional = true } diesel = { version = "2.0.2", optional = true }
tracing = { version = "0.1.36", optional = true } tracing = { version = "0.1.36", optional = true }
rosetta-i18n = { version = "0.1.2", optional = true } rosetta-i18n = { version = "0.1.2", optional = true }
percent-encoding = { version = "2.2.0", optional = true } percent-encoding = { version = "2.2.0", optional = true }

View file

@ -125,10 +125,10 @@ pub struct CreateSite {
pub private_instance: Option<bool>, pub private_instance: Option<bool>,
pub default_theme: Option<String>, pub default_theme: Option<String>,
pub default_post_listing_type: Option<String>, pub default_post_listing_type: Option<String>,
pub application_email_admins: Option<bool>,
pub auth: Sensitive<String>,
pub hide_modlog_mod_names: Option<bool>,
pub legal_information: Option<String>, pub legal_information: Option<String>,
pub application_email_admins: Option<bool>,
pub hide_modlog_mod_names: Option<bool>,
pub discussion_languages: Option<Vec<LanguageId>>,
pub slur_filter_regex: Option<String>, pub slur_filter_regex: Option<String>,
pub actor_name_max_length: Option<i32>, pub actor_name_max_length: Option<i32>,
pub rate_limit_message: Option<i32>, pub rate_limit_message: Option<i32>,
@ -152,6 +152,7 @@ pub struct CreateSite {
pub captcha_difficulty: Option<String>, pub captcha_difficulty: Option<String>,
pub allowed_instances: Option<Vec<String>>, pub allowed_instances: Option<Vec<String>>,
pub blocked_instances: Option<Vec<String>>, pub blocked_instances: Option<Vec<String>>,
pub auth: Sensitive<String>,
} }
#[derive(Debug, Serialize, Deserialize, Clone, Default)] #[derive(Debug, Serialize, Deserialize, Clone, Default)]

View file

@ -44,33 +44,13 @@ use rosetta_i18n::{Language, LanguageId};
use std::str::FromStr; use std::str::FromStr;
use tracing::warn; use tracing::warn;
pub async fn blocking<F, T>(pool: &DbPool, f: F) -> Result<T, LemmyError>
where
F: FnOnce(&mut diesel::PgConnection) -> T + Send + 'static,
T: Send + 'static,
{
let pool = pool.clone();
let blocking_span = tracing::info_span!("blocking operation");
actix_web::web::block(move || {
let entered = blocking_span.enter();
let mut conn = pool.get()?;
let res = (f)(&mut conn);
drop(entered);
Ok(res) as Result<T, LemmyError>
})
.await?
}
#[tracing::instrument(skip_all)] #[tracing::instrument(skip_all)]
pub async fn is_mod_or_admin( pub async fn is_mod_or_admin(
pool: &DbPool, pool: &DbPool,
person_id: PersonId, person_id: PersonId,
community_id: CommunityId, community_id: CommunityId,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let is_mod_or_admin = blocking(pool, move |conn| { let is_mod_or_admin = CommunityView::is_mod_or_admin(pool, person_id, community_id).await?;
CommunityView::is_mod_or_admin(conn, person_id, community_id)
})
.await?;
if !is_mod_or_admin { if !is_mod_or_admin {
return Err(LemmyError::from_message("not_a_mod_or_admin")); return Err(LemmyError::from_message("not_a_mod_or_admin"));
} }
@ -86,8 +66,8 @@ pub fn is_admin(local_user_view: &LocalUserView) -> Result<(), LemmyError> {
#[tracing::instrument(skip_all)] #[tracing::instrument(skip_all)]
pub async fn get_post(post_id: PostId, pool: &DbPool) -> Result<Post, LemmyError> { pub async fn get_post(post_id: PostId, pool: &DbPool) -> Result<Post, LemmyError> {
blocking(pool, move |conn| Post::read(conn, post_id)) Post::read(pool, post_id)
.await? .await
.map_err(|e| LemmyError::from_error_message(e, "couldnt_find_post")) .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_post"))
} }
@ -99,10 +79,8 @@ pub async fn mark_post_as_read(
) -> Result<PostRead, LemmyError> { ) -> Result<PostRead, LemmyError> {
let post_read_form = PostReadForm { post_id, person_id }; let post_read_form = PostReadForm { post_id, person_id };
blocking(pool, move |conn| { PostRead::mark_as_read(pool, &post_read_form)
PostRead::mark_as_read(conn, &post_read_form) .await
})
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_mark_post_as_read")) .map_err(|e| LemmyError::from_error_message(e, "couldnt_mark_post_as_read"))
} }
@ -114,10 +92,8 @@ pub async fn mark_post_as_unread(
) -> Result<usize, LemmyError> { ) -> Result<usize, LemmyError> {
let post_read_form = PostReadForm { post_id, person_id }; let post_read_form = PostReadForm { post_id, person_id };
blocking(pool, move |conn| { PostRead::mark_as_unread(pool, &post_read_form)
PostRead::mark_as_unread(conn, &post_read_form) .await
})
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_mark_post_as_read")) .map_err(|e| LemmyError::from_error_message(e, "couldnt_mark_post_as_read"))
} }
@ -131,8 +107,7 @@ pub async fn get_local_user_view_from_jwt(
.map_err(|e| e.with_message("not_logged_in"))? .map_err(|e| e.with_message("not_logged_in"))?
.claims; .claims;
let local_user_id = LocalUserId(claims.sub); let local_user_id = LocalUserId(claims.sub);
let local_user_view = let local_user_view = LocalUserView::read(pool, local_user_id).await?;
blocking(pool, move |conn| LocalUserView::read(conn, local_user_id)).await??;
check_user_valid( check_user_valid(
local_user_view.person.banned, local_user_view.person.banned,
local_user_view.person.ban_expires, local_user_view.person.ban_expires,
@ -181,10 +156,7 @@ pub async fn get_local_user_settings_view_from_jwt_opt(
.map_err(|e| e.with_message("not_logged_in"))? .map_err(|e| e.with_message("not_logged_in"))?
.claims; .claims;
let local_user_id = LocalUserId(claims.sub); let local_user_id = LocalUserId(claims.sub);
let local_user_view = blocking(pool, move |conn| { let local_user_view = LocalUserSettingsView::read(pool, local_user_id).await?;
LocalUserSettingsView::read(conn, local_user_id)
})
.await??;
check_user_valid( check_user_valid(
local_user_view.person.banned, local_user_view.person.banned,
local_user_view.person.ban_expires, local_user_view.person.ban_expires,
@ -222,9 +194,10 @@ pub async fn check_community_ban(
community_id: CommunityId, community_id: CommunityId,
pool: &DbPool, pool: &DbPool,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let is_banned = let is_banned = CommunityPersonBanView::get(pool, person_id, community_id)
move |conn: &mut _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok(); .await
if blocking(pool, is_banned).await? { .is_ok();
if is_banned {
Err(LemmyError::from_message("community_ban")) Err(LemmyError::from_message("community_ban"))
} else { } else {
Ok(()) Ok(())
@ -236,8 +209,8 @@ pub async fn check_community_deleted_or_removed(
community_id: CommunityId, community_id: CommunityId,
pool: &DbPool, pool: &DbPool,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let community = blocking(pool, move |conn| Community::read(conn, community_id)) let community = Community::read(pool, community_id)
.await? .await
.map_err(|e| LemmyError::from_error_message(e, "couldnt_find_community"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_community"))?;
if community.deleted || community.removed { if community.deleted || community.removed {
Err(LemmyError::from_message("deleted")) Err(LemmyError::from_message("deleted"))
@ -260,8 +233,10 @@ pub async fn check_person_block(
potential_blocker_id: PersonId, potential_blocker_id: PersonId,
pool: &DbPool, pool: &DbPool,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let is_blocked = move |conn: &mut _| PersonBlock::read(conn, potential_blocker_id, my_id).is_ok(); let is_blocked = PersonBlock::read(pool, potential_blocker_id, my_id)
if blocking(pool, is_blocked).await? { .await
.is_ok();
if is_blocked {
Err(LemmyError::from_message("person_block")) Err(LemmyError::from_message("person_block"))
} else { } else {
Ok(()) Ok(())
@ -294,9 +269,9 @@ pub async fn build_federated_instances(
) -> Result<Option<FederatedInstances>, LemmyError> { ) -> Result<Option<FederatedInstances>, LemmyError> {
if local_site.federation_enabled { if local_site.federation_enabled {
// TODO I hate that this requires 3 queries // TODO I hate that this requires 3 queries
let linked = blocking(pool, Instance::linked).await??; let linked = Instance::linked(pool).await?;
let allowed = blocking(pool, Instance::allowlist).await??; let allowed = Instance::allowlist(pool).await?;
let blocked = blocking(pool, Instance::blocklist).await??; let blocked = Instance::blocklist(pool).await?;
// These can return empty vectors, so convert them to options // These can return empty vectors, so convert them to options
let allowed = (!allowed.is_empty()).then(|| allowed); let allowed = (!allowed.is_empty()).then(|| allowed);
@ -374,10 +349,7 @@ pub async fn send_password_reset_email(
// Insert the row // Insert the row
let token2 = token.clone(); let token2 = token.clone();
let local_user_id = user.local_user.id; let local_user_id = user.local_user.id;
blocking(pool, move |conn| { PasswordResetRequest::create_token(pool, local_user_id, &token2).await?;
PasswordResetRequest::create_token(conn, local_user_id, &token2)
})
.await??;
let email = &user.local_user.email.to_owned().expect("email"); let email = &user.local_user.email.to_owned().expect("email");
let lang = get_interface_language(user); let lang = get_interface_language(user);
@ -405,7 +377,7 @@ pub async fn send_verification_email(
settings.get_protocol_and_hostname(), settings.get_protocol_and_hostname(),
&form.verification_token &form.verification_token
); );
blocking(pool, move |conn| EmailVerification::create(conn, &form)).await??; EmailVerification::create(pool, &form).await?;
let lang = get_interface_language(user); let lang = get_interface_language(user);
let subject = lang.verify_email_subject(&settings.hostname); let subject = lang.verify_email_subject(&settings.hostname);
@ -491,10 +463,7 @@ pub async fn send_new_applicant_email_to_admins(
settings: &Settings, settings: &Settings,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
// Collect the admins with emails // Collect the admins with emails
let admins = blocking(pool, move |conn| { let admins = LocalUserSettingsView::list_admins_with_emails(pool).await?;
LocalUserSettingsView::list_admins_with_emails(conn)
})
.await??;
let applications_link = &format!( let applications_link = &format!(
"{}/registration_applications", "{}/registration_applications",
@ -522,10 +491,7 @@ pub async fn check_registration_application(
{ {
// Fetch the registration, see if its denied // Fetch the registration, see if its denied
let local_user_id = local_user_view.local_user.id; let local_user_id = local_user_view.local_user.id;
let registration = blocking(pool, move |conn| { let registration = RegistrationApplication::find_by_local_user_id(pool, local_user_id).await?;
RegistrationApplication::find_by_local_user_id(conn, local_user_id)
})
.await??;
if let Some(deny_reason) = registration.deny_reason { if let Some(deny_reason) = registration.deny_reason {
let lang = get_interface_language(local_user_view); let lang = get_interface_language(local_user_view);
let registration_denied_message = format!("{}: {}", lang.registration_denied(), &deny_reason); let registration_denied_message = format!("{}: {}", lang.registration_denied(), &deny_reason);
@ -554,10 +520,7 @@ pub async fn purge_image_posts_for_person(
settings: &Settings, settings: &Settings,
client: &ClientWithMiddleware, client: &ClientWithMiddleware,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let posts = blocking(pool, move |conn: &mut _| { let posts = Post::fetch_pictrs_posts_for_creator(pool, banned_person_id).await?;
Post::fetch_pictrs_posts_for_creator(conn, banned_person_id)
})
.await??;
for post in posts { for post in posts {
if let Some(url) = post.url { if let Some(url) = post.url {
purge_image_from_pictrs(client, settings, &url).await.ok(); purge_image_from_pictrs(client, settings, &url).await.ok();
@ -569,10 +532,7 @@ pub async fn purge_image_posts_for_person(
} }
} }
blocking(pool, move |conn| { Post::remove_pictrs_post_images_and_thumbnails_for_creator(pool, banned_person_id).await?;
Post::remove_pictrs_post_images_and_thumbnails_for_creator(conn, banned_person_id)
})
.await??;
Ok(()) Ok(())
} }
@ -583,10 +543,7 @@ pub async fn purge_image_posts_for_community(
settings: &Settings, settings: &Settings,
client: &ClientWithMiddleware, client: &ClientWithMiddleware,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let posts = blocking(pool, move |conn: &mut _| { let posts = Post::fetch_pictrs_posts_for_community(pool, banned_community_id).await?;
Post::fetch_pictrs_posts_for_community(conn, banned_community_id)
})
.await??;
for post in posts { for post in posts {
if let Some(url) = post.url { if let Some(url) = post.url {
purge_image_from_pictrs(client, settings, &url).await.ok(); purge_image_from_pictrs(client, settings, &url).await.ok();
@ -598,10 +555,7 @@ pub async fn purge_image_posts_for_community(
} }
} }
blocking(pool, move |conn| { Post::remove_pictrs_post_images_and_thumbnails_for_community(pool, banned_community_id).await?;
Post::remove_pictrs_post_images_and_thumbnails_for_community(conn, banned_community_id)
})
.await??;
Ok(()) Ok(())
} }
@ -613,7 +567,7 @@ pub async fn remove_user_data(
client: &ClientWithMiddleware, client: &ClientWithMiddleware,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
// Purge user images // Purge user images
let person = blocking(pool, move |conn| Person::read(conn, banned_person_id)).await??; let person = Person::read(pool, banned_person_id).await?;
if let Some(avatar) = person.avatar { if let Some(avatar) = person.avatar {
purge_image_from_pictrs(client, settings, &avatar) purge_image_from_pictrs(client, settings, &avatar)
.await .await
@ -626,23 +580,18 @@ pub async fn remove_user_data(
} }
// Update the fields to None // Update the fields to None
blocking(pool, move |conn| {
Person::update( Person::update(
conn, pool,
banned_person_id, banned_person_id,
&PersonUpdateForm::builder() &PersonUpdateForm::builder()
.avatar(Some(None)) .avatar(Some(None))
.banner(Some(None)) .banner(Some(None))
.build(), .build(),
) )
}) .await?;
.await??;
// Posts // Posts
blocking(pool, move |conn: &mut _| { Post::update_removed_for_creator(pool, banned_person_id, None, true).await?;
Post::update_removed_for_creator(conn, banned_person_id, None, true)
})
.await??;
// Purge image posts // Purge image posts
purge_image_posts_for_person(banned_person_id, pool, settings, client).await?; purge_image_posts_for_person(banned_person_id, pool, settings, client).await?;
@ -650,10 +599,7 @@ pub async fn remove_user_data(
// Communities // Communities
// Remove all communities where they're the top mod // Remove all communities where they're the top mod
// for now, remove the communities manually // for now, remove the communities manually
let first_mod_communities = blocking(pool, move |conn: &mut _| { let first_mod_communities = CommunityModeratorView::get_community_first_mods(pool).await?;
CommunityModeratorView::get_community_first_mods(conn)
})
.await??;
// Filter to only this banned users top communities // Filter to only this banned users top communities
let banned_user_first_communities: Vec<CommunityModeratorView> = first_mod_communities let banned_user_first_communities: Vec<CommunityModeratorView> = first_mod_communities
@ -663,14 +609,12 @@ pub async fn remove_user_data(
for first_mod_community in banned_user_first_communities { for first_mod_community in banned_user_first_communities {
let community_id = first_mod_community.community.id; let community_id = first_mod_community.community.id;
blocking(pool, move |conn| {
Community::update( Community::update(
conn, pool,
community_id, community_id,
&CommunityUpdateForm::builder().removed(Some(true)).build(), &CommunityUpdateForm::builder().removed(Some(true)).build(),
) )
}) .await?;
.await??;
// Delete the community images // Delete the community images
if let Some(icon) = first_mod_community.community.icon { if let Some(icon) = first_mod_community.community.icon {
@ -682,24 +626,19 @@ pub async fn remove_user_data(
.ok(); .ok();
} }
// Update the fields to None // Update the fields to None
blocking(pool, move |conn| {
Community::update( Community::update(
conn, pool,
community_id, community_id,
&CommunityUpdateForm::builder() &CommunityUpdateForm::builder()
.icon(Some(None)) .icon(Some(None))
.banner(Some(None)) .banner(Some(None))
.build(), .build(),
) )
}) .await?;
.await??;
} }
// Comments // Comments
blocking(pool, move |conn: &mut _| { Comment::update_removed_for_creator(pool, banned_person_id, true).await?;
Comment::update_removed_for_creator(conn, banned_person_id, true)
})
.await??;
Ok(()) Ok(())
} }
@ -710,34 +649,27 @@ pub async fn remove_user_data_in_community(
pool: &DbPool, pool: &DbPool,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
// Posts // Posts
blocking(pool, move |conn| { Post::update_removed_for_creator(pool, banned_person_id, Some(community_id), true).await?;
Post::update_removed_for_creator(conn, banned_person_id, Some(community_id), true)
})
.await??;
// Comments // Comments
// TODO Diesel doesn't allow updates with joins, so this has to be a loop // TODO Diesel doesn't allow updates with joins, so this has to be a loop
let comments = blocking(pool, move |conn| { let comments = CommentQuery::builder()
CommentQuery::builder() .pool(pool)
.conn(conn)
.creator_id(Some(banned_person_id)) .creator_id(Some(banned_person_id))
.community_id(Some(community_id)) .community_id(Some(community_id))
.limit(Some(i64::MAX)) .limit(Some(i64::MAX))
.build() .build()
.list() .list()
}) .await?;
.await??;
for comment_view in &comments { for comment_view in &comments {
let comment_id = comment_view.comment.id; let comment_id = comment_view.comment.id;
blocking(pool, move |conn| {
Comment::update( Comment::update(
conn, pool,
comment_id, comment_id,
&CommentUpdateForm::builder().removed(Some(true)).build(), &CommentUpdateForm::builder().removed(Some(true)).build(),
) )
}) .await?;
.await??;
} }
Ok(()) Ok(())
@ -750,7 +682,7 @@ pub async fn delete_user_account(
client: &ClientWithMiddleware, client: &ClientWithMiddleware,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
// Delete their images // Delete their images
let person = blocking(pool, move |conn| Person::read(conn, person_id)).await??; let person = Person::read(pool, person_id).await?;
if let Some(avatar) = person.avatar { if let Some(avatar) = person.avatar {
purge_image_from_pictrs(client, settings, &avatar) purge_image_from_pictrs(client, settings, &avatar)
.await .await
@ -764,21 +696,19 @@ pub async fn delete_user_account(
// No need to update avatar and banner, those are handled in Person::delete_account // No need to update avatar and banner, those are handled in Person::delete_account
// Comments // Comments
let permadelete = move |conn: &mut _| Comment::permadelete_for_creator(conn, person_id); Comment::permadelete_for_creator(pool, person_id)
blocking(pool, permadelete) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?;
// Posts // Posts
let permadelete = move |conn: &mut _| Post::permadelete_for_creator(conn, person_id); Post::permadelete_for_creator(pool, person_id)
blocking(pool, permadelete) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_update_post"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_post"))?;
// Purge image posts // Purge image posts
purge_image_posts_for_person(person_id, pool, settings, client).await?; purge_image_posts_for_person(person_id, pool, settings, client).await?;
blocking(pool, move |conn| Person::delete_account(conn, person_id)).await??; Person::delete_account(pool, person_id).await?;
Ok(()) Ok(())
} }

View file

@ -18,10 +18,10 @@ lemmy_api_common = { version = "=0.16.5", path = "../api_common", features = ["f
lemmy_websocket = { version = "=0.16.5", path = "../websocket" } lemmy_websocket = { version = "=0.16.5", path = "../websocket" }
activitypub_federation = "0.2.3" activitypub_federation = "0.2.3"
bcrypt = "0.13.0" bcrypt = "0.13.0"
serde_json = { version = "1.0.85", features = ["preserve_order"] } serde_json = { version = "1.0.87", features = ["preserve_order"] }
serde = { version = "1.0.145", features = ["derive"] } serde = { version = "1.0.147", features = ["derive"] }
actix-web = { version = "4.2.1", default-features = false } actix-web = { version = "4.2.1", default-features = false }
tracing = "0.1.36" tracing = "0.1.36"
url = { version = "2.3.1", features = ["serde"] } url = { version = "2.3.1", features = ["serde"] }
async-trait = "0.1.57" async-trait = "0.1.58"
webmention = "0.4.0" webmention = "0.4.0"

View file

@ -3,7 +3,6 @@ use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
comment::{CommentResponse, CreateComment}, comment::{CommentResponse, CreateComment},
utils::{ utils::{
blocking,
check_community_ban, check_community_ban,
check_community_deleted_or_removed, check_community_deleted_or_removed,
check_post_deleted_or_removed, check_post_deleted_or_removed,
@ -52,7 +51,7 @@ impl PerformCrud for CreateComment {
let data: &CreateComment = self; let data: &CreateComment = self;
let local_user_view = let local_user_view =
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let local_site = blocking(context.pool(), LocalSite::read).await??; let local_site = LocalSite::read(context.pool()).await?;
let content_slurs_removed = remove_slurs( let content_slurs_removed = remove_slurs(
&data.content.to_owned(), &data.content.to_owned(),
@ -75,9 +74,7 @@ impl PerformCrud for CreateComment {
// Fetch the parent, if it exists // Fetch the parent, if it exists
let parent_opt = if let Some(parent_id) = data.parent_id { let parent_opt = if let Some(parent_id) = data.parent_id {
blocking(context.pool(), move |conn| Comment::read(conn, parent_id)) Comment::read(context.pool(), parent_id).await.ok()
.await?
.ok()
} else { } else {
None None
}; };
@ -97,10 +94,12 @@ impl PerformCrud for CreateComment {
.unwrap_or(post.language_id); .unwrap_or(post.language_id);
let language_id = data.language_id.unwrap_or(parent_language); let language_id = data.language_id.unwrap_or(parent_language);
blocking(context.pool(), move |conn| { CommunityLanguage::is_allowed_community_language(
CommunityLanguage::is_allowed_community_language(conn, Some(language_id), community_id) context.pool(),
}) Some(language_id),
.await??; community_id,
)
.await?;
let comment_form = CommentInsertForm::builder() let comment_form = CommentInsertForm::builder()
.content(content_slurs_removed.to_owned()) .content(content_slurs_removed.to_owned())
@ -112,31 +111,26 @@ impl PerformCrud for CreateComment {
// Create the comment // Create the comment
let comment_form2 = comment_form.clone(); let comment_form2 = comment_form.clone();
let parent_path = parent_opt.to_owned().map(|t| t.path); let parent_path = parent_opt.to_owned().map(|t| t.path);
let inserted_comment = blocking(context.pool(), move |conn| { let inserted_comment = Comment::create(context.pool(), &comment_form2, parent_path.as_ref())
Comment::create(conn, &comment_form2, parent_path.as_ref()) .await
})
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_create_comment"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_create_comment"))?;
// Necessary to update the ap_id // Necessary to update the ap_id
let inserted_comment_id = inserted_comment.id; let inserted_comment_id = inserted_comment.id;
let protocol_and_hostname = context.settings().get_protocol_and_hostname(); let protocol_and_hostname = context.settings().get_protocol_and_hostname();
let updated_comment: Comment =
blocking(context.pool(), move |conn| -> Result<Comment, LemmyError> {
let apub_id = generate_local_apub_endpoint( let apub_id = generate_local_apub_endpoint(
EndpointType::Comment, EndpointType::Comment,
&inserted_comment_id.to_string(), &inserted_comment_id.to_string(),
&protocol_and_hostname, &protocol_and_hostname,
)?; )?;
Ok(Comment::update( let updated_comment = Comment::update(
conn, context.pool(),
inserted_comment_id, inserted_comment_id,
&CommentUpdateForm::builder().ap_id(Some(apub_id)).build(), &CommentUpdateForm::builder().ap_id(Some(apub_id)).build(),
)?) )
}) .await
.await? .map_err(|e| LemmyError::from_error_message(e, "couldnt_create_comment"))?;
.map_err(|e| e.with_message("couldnt_create_comment"))?;
// Scan the comment for user mentions, add those rows // Scan the comment for user mentions, add those rows
let post_id = post.id; let post_id = post.id;
@ -159,9 +153,8 @@ impl PerformCrud for CreateComment {
score: 1, score: 1,
}; };
let like = move |conn: &mut _| CommentLike::like(conn, &like_form); CommentLike::like(context.pool(), &like_form)
blocking(context.pool(), like) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_like_comment"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_like_comment"))?;
let apub_comment: ApubComment = updated_comment.into(); let apub_comment: ApubComment = updated_comment.into();
@ -177,33 +170,28 @@ impl PerformCrud for CreateComment {
// If its a reply, mark the parent as read // If its a reply, mark the parent as read
if let Some(parent) = parent_opt { if let Some(parent) = parent_opt {
let parent_id = parent.id; let parent_id = parent.id;
let comment_reply = blocking(context.pool(), move |conn| { let comment_reply = CommentReply::read_by_comment(context.pool(), parent_id).await;
CommentReply::read_by_comment(conn, parent_id)
})
.await?;
if let Ok(reply) = comment_reply { if let Ok(reply) = comment_reply {
blocking(context.pool(), move |conn| { CommentReply::update(
CommentReply::update(conn, reply.id, &CommentReplyUpdateForm { read: Some(true) }) context.pool(),
}) reply.id,
.await? &CommentReplyUpdateForm { read: Some(true) },
)
.await
.map_err(|e| LemmyError::from_error_message(e, "couldnt_update_replies"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_replies"))?;
} }
// If the parent has PersonMentions mark them as read too // If the parent has PersonMentions mark them as read too
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let person_mention = blocking(context.pool(), move |conn| { let person_mention =
PersonMention::read_by_comment_and_person(conn, parent_id, person_id) PersonMention::read_by_comment_and_person(context.pool(), parent_id, person_id).await;
})
.await?;
if let Ok(mention) = person_mention { if let Ok(mention) = person_mention {
blocking(context.pool(), move |conn| {
PersonMention::update( PersonMention::update(
conn, context.pool(),
mention.id, mention.id,
&PersonMentionUpdateForm { read: Some(true) }, &PersonMentionUpdateForm { read: Some(true) },
) )
}) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_update_person_mentions"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_person_mentions"))?;
} }
} }

View file

@ -2,7 +2,7 @@ use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
comment::{CommentResponse, DeleteComment}, comment::{CommentResponse, DeleteComment},
utils::{blocking, check_community_ban, get_local_user_view_from_jwt}, utils::{check_community_ban, get_local_user_view_from_jwt},
}; };
use lemmy_apub::activities::deletion::{send_apub_delete_in_community, DeletableObjects}; use lemmy_apub::activities::deletion::{send_apub_delete_in_community, DeletableObjects};
use lemmy_db_schema::{ use lemmy_db_schema::{
@ -36,10 +36,7 @@ impl PerformCrud for DeleteComment {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let comment_id = data.comment_id; let comment_id = data.comment_id;
let orig_comment = blocking(context.pool(), move |conn| { let orig_comment = CommentView::read(context.pool(), comment_id, None).await?;
CommentView::read(conn, comment_id, None)
})
.await??;
// Dont delete it if its already been deleted. // Dont delete it if its already been deleted.
if orig_comment.comment.deleted == data.deleted { if orig_comment.comment.deleted == data.deleted {
@ -60,18 +57,16 @@ impl PerformCrud for DeleteComment {
// Do the delete // Do the delete
let deleted = data.deleted; let deleted = data.deleted;
let updated_comment = blocking(context.pool(), move |conn| { let updated_comment = Comment::update(
Comment::update( context.pool(),
conn,
comment_id, comment_id,
&CommentUpdateForm::builder().deleted(Some(deleted)).build(), &CommentUpdateForm::builder().deleted(Some(deleted)).build(),
) )
}) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?;
let post_id = updated_comment.post_id; let post_id = updated_comment.post_id;
let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; let post = Post::read(context.pool(), post_id).await?;
let recipient_ids = send_local_notifs( let recipient_ids = send_local_notifs(
vec![], vec![],
&updated_comment, &updated_comment,
@ -94,10 +89,7 @@ impl PerformCrud for DeleteComment {
.await?; .await?;
// Send the apub message // Send the apub message
let community = blocking(context.pool(), move |conn| { let community = Community::read(context.pool(), orig_comment.post.community_id).await?;
Community::read(conn, orig_comment.post.community_id)
})
.await??;
let deletable = DeletableObjects::Comment(Box::new(updated_comment.clone().into())); let deletable = DeletableObjects::Comment(Box::new(updated_comment.clone().into()));
send_apub_delete_in_community( send_apub_delete_in_community(
local_user_view.person, local_user_view.person,

View file

@ -3,7 +3,6 @@ use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
comment::{GetComments, GetCommentsResponse}, comment::{GetComments, GetCommentsResponse},
utils::{ utils::{
blocking,
check_private_instance, check_private_instance,
get_local_user_view_from_jwt_opt, get_local_user_view_from_jwt_opt,
listing_type_with_site_default, listing_type_with_site_default,
@ -32,7 +31,7 @@ impl PerformCrud for GetComments {
let local_user_view = let local_user_view =
get_local_user_view_from_jwt_opt(data.auth.as_ref(), context.pool(), context.secret()) get_local_user_view_from_jwt_opt(data.auth.as_ref(), context.pool(), context.secret())
.await?; .await?;
let local_site = blocking(context.pool(), LocalSite::read).await??; let local_site = LocalSite::read(context.pool()).await?;
check_private_instance(&local_user_view, &local_site)?; check_private_instance(&local_user_view, &local_site)?;
let community_id = data.community_id; let community_id = data.community_id;
@ -55,11 +54,7 @@ impl PerformCrud for GetComments {
// If a parent_id is given, fetch the comment to get the path // If a parent_id is given, fetch the comment to get the path
let parent_path = if let Some(parent_id) = parent_id { let parent_path = if let Some(parent_id) = parent_id {
Some( Some(Comment::read(context.pool(), parent_id).await?.path)
blocking(context.pool(), move |conn| Comment::read(conn, parent_id))
.await??
.path,
)
} else { } else {
None None
}; };
@ -67,9 +62,8 @@ impl PerformCrud for GetComments {
let parent_path_cloned = parent_path.to_owned(); let parent_path_cloned = parent_path.to_owned();
let post_id = data.post_id; let post_id = data.post_id;
let local_user = local_user_view.map(|l| l.local_user); let local_user = local_user_view.map(|l| l.local_user);
let mut comments = blocking(context.pool(), move |conn| { let mut comments = CommentQuery::builder()
CommentQuery::builder() .pool(context.pool())
.conn(conn)
.listing_type(Some(listing_type)) .listing_type(Some(listing_type))
.sort(sort) .sort(sort)
.max_depth(max_depth) .max_depth(max_depth)
@ -83,8 +77,7 @@ impl PerformCrud for GetComments {
.limit(limit) .limit(limit)
.build() .build()
.list() .list()
}) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_get_comments"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_get_comments"))?;
// Blank out deleted or removed info // Blank out deleted or removed info

View file

@ -2,7 +2,7 @@ use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
comment::{CommentResponse, GetComment}, comment::{CommentResponse, GetComment},
utils::{blocking, check_private_instance, get_local_user_view_from_jwt_opt}, utils::{check_private_instance, get_local_user_view_from_jwt_opt},
}; };
use lemmy_db_schema::source::local_site::LocalSite; use lemmy_db_schema::source::local_site::LocalSite;
use lemmy_db_views::structs::CommentView; use lemmy_db_views::structs::CommentView;
@ -23,16 +23,14 @@ impl PerformCrud for GetComment {
let local_user_view = let local_user_view =
get_local_user_view_from_jwt_opt(data.auth.as_ref(), context.pool(), context.secret()) get_local_user_view_from_jwt_opt(data.auth.as_ref(), context.pool(), context.secret())
.await?; .await?;
let local_site = blocking(context.pool(), LocalSite::read).await??; let local_site = LocalSite::read(context.pool()).await?;
check_private_instance(&local_user_view, &local_site)?; check_private_instance(&local_user_view, &local_site)?;
let person_id = local_user_view.map(|u| u.person.id); let person_id = local_user_view.map(|u| u.person.id);
let id = data.id; let id = data.id;
let comment_view = blocking(context.pool(), move |conn| { let comment_view = CommentView::read(context.pool(), id, person_id)
CommentView::read(conn, id, person_id) .await
})
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_find_comment"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_comment"))?;
Ok(Self::Response { Ok(Self::Response {

View file

@ -2,7 +2,7 @@ use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
comment::{CommentResponse, RemoveComment}, comment::{CommentResponse, RemoveComment},
utils::{blocking, check_community_ban, get_local_user_view_from_jwt, is_mod_or_admin}, utils::{check_community_ban, get_local_user_view_from_jwt, is_mod_or_admin},
}; };
use lemmy_apub::activities::deletion::{send_apub_delete_in_community, DeletableObjects}; use lemmy_apub::activities::deletion::{send_apub_delete_in_community, DeletableObjects};
use lemmy_db_schema::{ use lemmy_db_schema::{
@ -37,10 +37,7 @@ impl PerformCrud for RemoveComment {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let comment_id = data.comment_id; let comment_id = data.comment_id;
let orig_comment = blocking(context.pool(), move |conn| { let orig_comment = CommentView::read(context.pool(), comment_id, None).await?;
CommentView::read(conn, comment_id, None)
})
.await??;
check_community_ban( check_community_ban(
local_user_view.person.id, local_user_view.person.id,
@ -59,14 +56,12 @@ impl PerformCrud for RemoveComment {
// Do the remove // Do the remove
let removed = data.removed; let removed = data.removed;
let updated_comment = blocking(context.pool(), move |conn| { let updated_comment = Comment::update(
Comment::update( context.pool(),
conn,
comment_id, comment_id,
&CommentUpdateForm::builder().removed(Some(removed)).build(), &CommentUpdateForm::builder().removed(Some(removed)).build(),
) )
}) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?;
// Mod tables // Mod tables
@ -76,13 +71,10 @@ impl PerformCrud for RemoveComment {
removed: Some(removed), removed: Some(removed),
reason: data.reason.to_owned(), reason: data.reason.to_owned(),
}; };
blocking(context.pool(), move |conn| { ModRemoveComment::create(context.pool(), &form).await?;
ModRemoveComment::create(conn, &form)
})
.await??;
let post_id = updated_comment.post_id; let post_id = updated_comment.post_id;
let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; let post = Post::read(context.pool(), post_id).await?;
let recipient_ids = send_local_notifs( let recipient_ids = send_local_notifs(
vec![], vec![],
&updated_comment, &updated_comment,
@ -105,10 +97,7 @@ impl PerformCrud for RemoveComment {
.await?; .await?;
// Send the apub message // Send the apub message
let community = blocking(context.pool(), move |conn| { let community = Community::read(context.pool(), orig_comment.post.community_id).await?;
Community::read(conn, orig_comment.post.community_id)
})
.await??;
let deletable = DeletableObjects::Comment(Box::new(updated_comment.clone().into())); let deletable = DeletableObjects::Comment(Box::new(updated_comment.clone().into()));
send_apub_delete_in_community( send_apub_delete_in_community(
local_user_view.person, local_user_view.person,

View file

@ -3,7 +3,6 @@ use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
comment::{CommentResponse, EditComment}, comment::{CommentResponse, EditComment},
utils::{ utils::{
blocking,
check_community_ban, check_community_ban,
check_community_deleted_or_removed, check_community_deleted_or_removed,
check_post_deleted_or_removed, check_post_deleted_or_removed,
@ -49,13 +48,10 @@ impl PerformCrud for EditComment {
let data: &EditComment = self; let data: &EditComment = self;
let local_user_view = let local_user_view =
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let local_site = blocking(context.pool(), LocalSite::read).await??; let local_site = LocalSite::read(context.pool()).await?;
let comment_id = data.comment_id; let comment_id = data.comment_id;
let orig_comment = blocking(context.pool(), move |conn| { let orig_comment = CommentView::read(context.pool(), comment_id, None).await?;
CommentView::read(conn, comment_id, None)
})
.await??;
// TODO is this necessary? It should really only need to check on create // TODO is this necessary? It should really only need to check on create
check_community_ban( check_community_ban(
@ -83,10 +79,12 @@ impl PerformCrud for EditComment {
} }
let language_id = self.language_id; let language_id = self.language_id;
blocking(context.pool(), move |conn| { CommunityLanguage::is_allowed_community_language(
CommunityLanguage::is_allowed_community_language(conn, language_id, orig_comment.community.id) context.pool(),
}) language_id,
.await??; orig_comment.community.id,
)
.await?;
// Update the Content // Update the Content
let content_slurs_removed = data let content_slurs_removed = data
@ -99,10 +97,8 @@ impl PerformCrud for EditComment {
.distinguished(data.distinguished) .distinguished(data.distinguished)
.language_id(data.language_id) .language_id(data.language_id)
.build(); .build();
let updated_comment = blocking(context.pool(), move |conn| { let updated_comment = Comment::update(context.pool(), comment_id, &form)
Comment::update(conn, comment_id, &form) .await
})
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?;
// Do the mentions / recipients // Do the mentions / recipients

View file

@ -3,7 +3,7 @@ use activitypub_federation::core::{object_id::ObjectId, signatures::generate_act
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
community::{CommunityResponse, CreateCommunity}, community::{CommunityResponse, CreateCommunity},
utils::{blocking, get_local_user_view_from_jwt, is_admin, local_site_to_slur_regex}, utils::{get_local_user_view_from_jwt, is_admin, local_site_to_slur_regex},
}; };
use lemmy_apub::{ use lemmy_apub::{
generate_followers_url, generate_followers_url,
@ -47,7 +47,7 @@ impl PerformCrud for CreateCommunity {
let data: &CreateCommunity = self; let data: &CreateCommunity = self;
let local_user_view = let local_user_view =
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let site_view = blocking(context.pool(), SiteView::read_local).await??; let site_view = SiteView::read_local(context.pool()).await?;
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() {
@ -101,10 +101,8 @@ impl PerformCrud for CreateCommunity {
.instance_id(site_view.site.instance_id) .instance_id(site_view.site.instance_id)
.build(); .build();
let inserted_community = blocking(context.pool(), move |conn| { let inserted_community = Community::create(context.pool(), &community_form)
Community::create(conn, &community_form) .await
})
.await?
.map_err(|e| LemmyError::from_error_message(e, "community_already_exists"))?; .map_err(|e| LemmyError::from_error_message(e, "community_already_exists"))?;
// The community creator becomes a moderator // The community creator becomes a moderator
@ -113,9 +111,8 @@ impl PerformCrud for CreateCommunity {
person_id: local_user_view.person.id, person_id: local_user_view.person.id,
}; };
let join = move |conn: &mut _| CommunityModerator::join(conn, &community_moderator_form); CommunityModerator::join(context.pool(), &community_moderator_form)
blocking(context.pool(), join) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "community_moderator_already_exists"))?; .map_err(|e| LemmyError::from_error_message(e, "community_moderator_already_exists"))?;
// Follow your own community // Follow your own community
@ -125,16 +122,13 @@ impl PerformCrud for CreateCommunity {
pending: false, pending: false,
}; };
let follow = move |conn: &mut _| CommunityFollower::follow(conn, &community_follower_form); CommunityFollower::follow(context.pool(), &community_follower_form)
blocking(context.pool(), follow) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "community_follower_already_exists"))?; .map_err(|e| LemmyError::from_error_message(e, "community_follower_already_exists"))?;
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let community_view = blocking(context.pool(), move |conn| { let community_view =
CommunityView::read(conn, inserted_community.id, Some(person_id)) CommunityView::read(context.pool(), inserted_community.id, Some(person_id)).await?;
})
.await??;
Ok(CommunityResponse { community_view }) Ok(CommunityResponse { community_view })
} }

View file

@ -2,7 +2,7 @@ use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
community::{CommunityResponse, DeleteCommunity}, community::{CommunityResponse, DeleteCommunity},
utils::{blocking, get_local_user_view_from_jwt}, utils::get_local_user_view_from_jwt,
}; };
use lemmy_apub::activities::deletion::{send_apub_delete_in_community, DeletableObjects}; use lemmy_apub::activities::deletion::{send_apub_delete_in_community, DeletableObjects};
use lemmy_db_schema::{ use lemmy_db_schema::{
@ -29,10 +29,8 @@ impl PerformCrud for DeleteCommunity {
// Fetch the community mods // Fetch the community mods
let community_id = data.community_id; let community_id = data.community_id;
let community_mods = blocking(context.pool(), move |conn| { let community_mods =
CommunityModeratorView::for_community(conn, community_id) CommunityModeratorView::for_community(context.pool(), community_id).await?;
})
.await??;
// Make sure deleter is the top mod // Make sure deleter is the top mod
if local_user_view.person.id != community_mods[0].moderator.id { if local_user_view.person.id != community_mods[0].moderator.id {
@ -42,16 +40,14 @@ impl PerformCrud for DeleteCommunity {
// Do the delete // Do the delete
let community_id = data.community_id; let community_id = data.community_id;
let deleted = data.deleted; let deleted = data.deleted;
let updated_community = blocking(context.pool(), move |conn| { let updated_community = Community::update(
Community::update( context.pool(),
conn,
community_id, community_id,
&CommunityUpdateForm::builder() &CommunityUpdateForm::builder()
.deleted(Some(deleted)) .deleted(Some(deleted))
.build(), .build(),
) )
}) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_update_community"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_community"))?;
let res = send_community_ws_message( let res = send_community_ws_message(

View file

@ -2,7 +2,7 @@ use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
community::{ListCommunities, ListCommunitiesResponse}, community::{ListCommunities, ListCommunitiesResponse},
utils::{blocking, check_private_instance, get_local_user_view_from_jwt_opt}, utils::{check_private_instance, get_local_user_view_from_jwt_opt},
}; };
use lemmy_db_schema::{source::local_site::LocalSite, traits::DeleteableOrRemoveable}; use lemmy_db_schema::{source::local_site::LocalSite, traits::DeleteableOrRemoveable};
use lemmy_db_views_actor::community_view::CommunityQuery; use lemmy_db_views_actor::community_view::CommunityQuery;
@ -23,7 +23,7 @@ impl PerformCrud for ListCommunities {
let local_user_view = let local_user_view =
get_local_user_view_from_jwt_opt(data.auth.as_ref(), context.pool(), context.secret()) get_local_user_view_from_jwt_opt(data.auth.as_ref(), context.pool(), context.secret())
.await?; .await?;
let local_site = blocking(context.pool(), LocalSite::read).await??; let local_site = LocalSite::read(context.pool()).await?;
check_private_instance(&local_user_view, &local_site)?; check_private_instance(&local_user_view, &local_site)?;
@ -34,9 +34,8 @@ impl PerformCrud for ListCommunities {
let page = data.page; let page = data.page;
let limit = data.limit; let limit = data.limit;
let local_user = local_user_view.map(|l| l.local_user); let local_user = local_user_view.map(|l| l.local_user);
let mut communities = blocking(context.pool(), move |conn| { let mut communities = CommunityQuery::builder()
CommunityQuery::builder() .pool(context.pool())
.conn(conn)
.listing_type(listing_type) .listing_type(listing_type)
.sort(sort) .sort(sort)
.local_user(local_user.as_ref()) .local_user(local_user.as_ref())
@ -44,8 +43,7 @@ impl PerformCrud for ListCommunities {
.limit(limit) .limit(limit)
.build() .build()
.list() .list()
}) .await?;
.await??;
// Blank out deleted or removed info for non-logged in users // Blank out deleted or removed info for non-logged in users
if person_id.is_none() { if person_id.is_none() {

View file

@ -2,7 +2,7 @@ use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
community::{GetCommunity, GetCommunityResponse}, community::{GetCommunity, GetCommunityResponse},
utils::{blocking, check_private_instance, get_local_user_view_from_jwt_opt}, utils::{check_private_instance, get_local_user_view_from_jwt_opt},
}; };
use lemmy_apub::{ use lemmy_apub::{
fetcher::resolve_actor_identifier, fetcher::resolve_actor_identifier,
@ -36,7 +36,7 @@ impl PerformCrud for GetCommunity {
let local_user_view = let local_user_view =
get_local_user_view_from_jwt_opt(data.auth.as_ref(), context.pool(), context.secret()) get_local_user_view_from_jwt_opt(data.auth.as_ref(), context.pool(), context.secret())
.await?; .await?;
let local_site = blocking(context.pool(), LocalSite::read).await??; let local_site = LocalSite::read(context.pool()).await?;
if data.name.is_none() && data.id.is_none() { if data.name.is_none() && data.id.is_none() {
return Err(LemmyError::from_message("no_id_given")); return Err(LemmyError::from_message("no_id_given"));
@ -57,10 +57,8 @@ impl PerformCrud for GetCommunity {
} }
}; };
let mut community_view = blocking(context.pool(), move |conn| { let mut community_view = CommunityView::read(context.pool(), community_id, person_id)
CommunityView::read(conn, community_id, person_id) .await
})
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_find_community"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_community"))?;
// Blank out deleted or removed info for non-logged in users // Blank out deleted or removed info for non-logged in users
@ -69,10 +67,8 @@ impl PerformCrud for GetCommunity {
community_view.community = community_view.community.blank_out_deleted_or_removed_info(); community_view.community = community_view.community.blank_out_deleted_or_removed_info();
} }
let moderators: Vec<CommunityModeratorView> = blocking(context.pool(), move |conn| { let moderators = CommunityModeratorView::for_community(context.pool(), community_id)
CommunityModeratorView::for_community(conn, community_id) .await
})
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_find_community"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_community"))?;
let online = context let online = context
@ -82,10 +78,7 @@ impl PerformCrud for GetCommunity {
.unwrap_or(1); .unwrap_or(1);
let site_id = instance_actor_id_from_url(community_view.community.actor_id.clone().into()); let site_id = instance_actor_id_from_url(community_view.community.actor_id.clone().into());
let mut site: Option<Site> = blocking(context.pool(), move |conn| { let mut site = Site::read_from_apub_id(context.pool(), site_id).await?;
Site::read_from_apub_id(conn, site_id)
})
.await??;
// no need to include metadata for local site (its already available through other endpoints). // no need to include metadata for local site (its already available through other endpoints).
// this also prevents us from leaking the federation private key. // this also prevents us from leaking the federation private key.
if let Some(s) = &site { if let Some(s) = &site {
@ -95,15 +88,9 @@ impl PerformCrud for GetCommunity {
} }
let community_id = community_view.community.id; let community_id = community_view.community.id;
let discussion_languages = blocking(context.pool(), move |conn| { let discussion_languages = CommunityLanguage::read(context.pool(), community_id).await?;
CommunityLanguage::read(conn, community_id)
})
.await??;
let default_post_language = if let Some(user) = local_user_view { let default_post_language = if let Some(user) = local_user_view {
blocking(context.pool(), move |conn| { default_post_language(context.pool(), community_id, user.local_user.id).await?
default_post_language(conn, community_id, user.local_user.id)
})
.await??
} else { } else {
None None
}; };

View file

@ -2,7 +2,7 @@ use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
community::{CommunityResponse, RemoveCommunity}, community::{CommunityResponse, RemoveCommunity},
utils::{blocking, get_local_user_view_from_jwt, is_admin}, utils::{get_local_user_view_from_jwt, is_admin},
}; };
use lemmy_apub::activities::deletion::{send_apub_delete_in_community, DeletableObjects}; use lemmy_apub::activities::deletion::{send_apub_delete_in_community, DeletableObjects};
use lemmy_db_schema::{ use lemmy_db_schema::{
@ -35,16 +35,14 @@ impl PerformCrud for RemoveCommunity {
// Do the remove // Do the remove
let community_id = data.community_id; let community_id = data.community_id;
let removed = data.removed; let removed = data.removed;
let updated_community = blocking(context.pool(), move |conn| { let updated_community = Community::update(
Community::update( context.pool(),
conn,
community_id, community_id,
&CommunityUpdateForm::builder() &CommunityUpdateForm::builder()
.removed(Some(removed)) .removed(Some(removed))
.build(), .build(),
) )
}) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_update_community"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_community"))?;
// Mod tables // Mod tables
@ -56,10 +54,7 @@ impl PerformCrud for RemoveCommunity {
reason: data.reason.to_owned(), reason: data.reason.to_owned(),
expires, expires,
}; };
blocking(context.pool(), move |conn| { ModRemoveCommunity::create(context.pool(), &form).await?;
ModRemoveCommunity::create(conn, &form)
})
.await??;
let res = send_community_ws_message( let res = send_community_ws_message(
data.community_id, data.community_id,

View file

@ -2,11 +2,11 @@ use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
community::{CommunityResponse, EditCommunity}, community::{CommunityResponse, EditCommunity},
utils::{blocking, get_local_user_view_from_jwt, local_site_to_slur_regex}, utils::{get_local_user_view_from_jwt, local_site_to_slur_regex},
}; };
use lemmy_apub::protocol::activities::community::update::UpdateCommunity; use lemmy_apub::protocol::activities::community::update::UpdateCommunity;
use lemmy_db_schema::{ use lemmy_db_schema::{
newtypes::{LanguageId, PersonId}, newtypes::PersonId,
source::{ source::{
actor_language::{CommunityLanguage, SiteLanguage}, actor_language::{CommunityLanguage, SiteLanguage},
community::{Community, CommunityUpdateForm}, community::{Community, CommunityUpdateForm},
@ -32,7 +32,7 @@ impl PerformCrud for EditCommunity {
let data: &EditCommunity = self; let data: &EditCommunity = self;
let local_user_view = let local_user_view =
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let local_site = blocking(context.pool(), LocalSite::read).await??; let local_site = LocalSite::read(context.pool()).await?;
let icon = diesel_option_overwrite_to_url(&data.icon)?; let icon = diesel_option_overwrite_to_url(&data.icon)?;
let banner = diesel_option_overwrite_to_url(&data.banner)?; let banner = diesel_option_overwrite_to_url(&data.banner)?;
@ -44,29 +44,23 @@ impl PerformCrud for EditCommunity {
// Verify its a mod (only mods can edit it) // Verify its a mod (only mods can edit it)
let community_id = data.community_id; let community_id = data.community_id;
let mods: Vec<PersonId> = blocking(context.pool(), move |conn| { let mods: Vec<PersonId> = CommunityModeratorView::for_community(context.pool(), community_id)
CommunityModeratorView::for_community(conn, community_id) .await
.map(|v| v.into_iter().map(|m| m.moderator.id).collect()) .map(|v| v.into_iter().map(|m| m.moderator.id).collect())?;
})
.await??;
if !mods.contains(&local_user_view.person.id) { if !mods.contains(&local_user_view.person.id) {
return Err(LemmyError::from_message("not_a_moderator")); return Err(LemmyError::from_message("not_a_moderator"));
} }
let community_id = data.community_id; let community_id = data.community_id;
if let Some(languages) = data.discussion_languages.clone() { if let Some(languages) = data.discussion_languages.clone() {
let site_languages: Vec<LanguageId> = let site_languages = SiteLanguage::read_local(context.pool()).await?;
blocking(context.pool(), SiteLanguage::read_local).await??;
// check that community languages are a subset of site languages // check that community languages are a subset of site languages
// https://stackoverflow.com/a/64227550 // https://stackoverflow.com/a/64227550
let is_subset = languages.iter().all(|item| site_languages.contains(item)); let is_subset = languages.iter().all(|item| site_languages.contains(item));
if !is_subset { if !is_subset {
return Err(LemmyError::from_message("language_not_allowed")); return Err(LemmyError::from_message("language_not_allowed"));
} }
blocking(context.pool(), move |conn| { CommunityLanguage::update(context.pool(), languages, community_id).await?;
CommunityLanguage::update(conn, languages, community_id)
})
.await??;
} }
let community_form = CommunityUpdateForm::builder() let community_form = CommunityUpdateForm::builder()
@ -79,10 +73,8 @@ impl PerformCrud for EditCommunity {
.build(); .build();
let community_id = data.community_id; let community_id = data.community_id;
let updated_community = blocking(context.pool(), move |conn| { let updated_community = Community::update(context.pool(), community_id, &community_form)
Community::update(conn, community_id, &community_form) .await
})
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_update_community"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_community"))?;
UpdateCommunity::send( UpdateCommunity::send(

View file

@ -4,7 +4,6 @@ use lemmy_api_common::{
post::{CreatePost, PostResponse}, post::{CreatePost, PostResponse},
request::fetch_site_data, request::fetch_site_data,
utils::{ utils::{
blocking,
check_community_ban, check_community_ban,
check_community_deleted_or_removed, check_community_deleted_or_removed,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
@ -53,7 +52,7 @@ impl PerformCrud for CreatePost {
let data: &CreatePost = self; let data: &CreatePost = self;
let local_user_view = let local_user_view =
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let local_site = blocking(context.pool(), LocalSite::read).await??; let local_site = LocalSite::read(context.pool()).await?;
let slur_regex = local_site_to_slur_regex(&local_site); let slur_regex = local_site_to_slur_regex(&local_site);
check_slurs(&data.name, &slur_regex)?; check_slurs(&data.name, &slur_regex)?;
@ -71,15 +70,14 @@ impl PerformCrud for CreatePost {
check_community_deleted_or_removed(data.community_id, context.pool()).await?; check_community_deleted_or_removed(data.community_id, context.pool()).await?;
let community_id = data.community_id; let community_id = data.community_id;
let community = blocking(context.pool(), move |conn| { let community = Community::read(context.pool(), community_id).await?;
Community::read(conn, community_id)
})
.await??;
if community.posting_restricted_to_mods { if community.posting_restricted_to_mods {
let community_id = data.community_id; let community_id = data.community_id;
let is_mod = blocking(context.pool(), move |conn| { let is_mod = CommunityView::is_mod_or_admin(
CommunityView::is_mod_or_admin(conn, local_user_view.local_user.person_id, community_id) context.pool(),
}) local_user_view.local_user.person_id,
community_id,
)
.await?; .await?;
if !is_mod { if !is_mod {
return Err(LemmyError::from_message("only_mods_can_post_in_community")); return Err(LemmyError::from_message("only_mods_can_post_in_community"));
@ -96,16 +94,11 @@ impl PerformCrud for CreatePost {
let language_id = match data.language_id { let language_id = match data.language_id {
Some(lid) => Some(lid), Some(lid) => Some(lid),
None => { None => {
blocking(context.pool(), move |conn| { default_post_language(context.pool(), community_id, local_user_view.local_user.id).await?
default_post_language(conn, community_id, local_user_view.local_user.id)
})
.await??
} }
}; };
blocking(context.pool(), move |conn| { CommunityLanguage::is_allowed_community_language(context.pool(), language_id, community_id)
CommunityLanguage::is_allowed_community_language(conn, language_id, community_id) .await?;
})
.await??;
let post_form = PostInsertForm::builder() let post_form = PostInsertForm::builder()
.name(data.name.trim().to_owned()) .name(data.name.trim().to_owned())
@ -121,8 +114,7 @@ impl PerformCrud for CreatePost {
.thumbnail_url(thumbnail_url) .thumbnail_url(thumbnail_url)
.build(); .build();
let inserted_post = let inserted_post = match Post::create(context.pool(), &post_form).await {
match blocking(context.pool(), move |conn| Post::create(conn, &post_form)).await? {
Ok(post) => post, Ok(post) => post,
Err(e) => { Err(e) => {
let err_type = if e.to_string() == "value too long for type character varying(200)" { let err_type = if e.to_string() == "value too long for type character varying(200)" {
@ -137,20 +129,18 @@ impl PerformCrud for CreatePost {
let inserted_post_id = inserted_post.id; let inserted_post_id = inserted_post.id;
let protocol_and_hostname = context.settings().get_protocol_and_hostname(); let protocol_and_hostname = context.settings().get_protocol_and_hostname();
let updated_post = blocking(context.pool(), move |conn| -> Result<Post, LemmyError> {
let apub_id = generate_local_apub_endpoint( let apub_id = generate_local_apub_endpoint(
EndpointType::Post, EndpointType::Post,
&inserted_post_id.to_string(), &inserted_post_id.to_string(),
&protocol_and_hostname, &protocol_and_hostname,
)?; )?;
Ok(Post::update( let updated_post = Post::update(
conn, context.pool(),
inserted_post_id, inserted_post_id,
&PostUpdateForm::builder().ap_id(Some(apub_id)).build(), &PostUpdateForm::builder().ap_id(Some(apub_id)).build(),
)?) )
}) .await
.await? .map_err(|e| LemmyError::from_error_message(e, "couldnt_create_post"))?;
.map_err(|e| e.with_message("couldnt_create_post"))?;
// They like their own post by default // They like their own post by default
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
@ -161,9 +151,8 @@ impl PerformCrud for CreatePost {
score: 1, score: 1,
}; };
let like = move |conn: &mut _| PostLike::like(conn, &like_form); PostLike::like(context.pool(), &like_form)
blocking(context.pool(), like) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_like_post"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_like_post"))?;
// Mark the post as read // Mark the post as read

View file

@ -2,12 +2,7 @@ use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
post::{DeletePost, PostResponse}, post::{DeletePost, PostResponse},
utils::{ utils::{check_community_ban, check_community_deleted_or_removed, get_local_user_view_from_jwt},
blocking,
check_community_ban,
check_community_deleted_or_removed,
get_local_user_view_from_jwt,
},
}; };
use lemmy_apub::activities::deletion::{send_apub_delete_in_community, DeletableObjects}; use lemmy_apub::activities::deletion::{send_apub_delete_in_community, DeletableObjects};
use lemmy_db_schema::{ use lemmy_db_schema::{
@ -35,7 +30,7 @@ impl PerformCrud for DeletePost {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let post_id = data.post_id; let post_id = data.post_id;
let orig_post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; let orig_post = Post::read(context.pool(), post_id).await?;
// Dont delete it if its already been deleted. // Dont delete it if its already been deleted.
if orig_post.deleted == data.deleted { if orig_post.deleted == data.deleted {
@ -58,14 +53,12 @@ impl PerformCrud for DeletePost {
// Update the post // Update the post
let post_id = data.post_id; let post_id = data.post_id;
let deleted = data.deleted; let deleted = data.deleted;
let updated_post = blocking(context.pool(), move |conn| { let updated_post = Post::update(
Post::update( context.pool(),
conn,
post_id, post_id,
&PostUpdateForm::builder().deleted(Some(deleted)).build(), &PostUpdateForm::builder().deleted(Some(deleted)).build(),
) )
}) .await?;
.await??;
let res = send_post_ws_message( let res = send_post_ws_message(
data.post_id, data.post_id,
@ -77,10 +70,7 @@ impl PerformCrud for DeletePost {
.await?; .await?;
// apub updates // apub updates
let community = blocking(context.pool(), move |conn| { let community = Community::read(context.pool(), orig_post.community_id).await?;
Community::read(conn, orig_post.community_id)
})
.await??;
let deletable = DeletableObjects::Post(Box::new(updated_post.into())); let deletable = DeletableObjects::Post(Box::new(updated_post.into()));
send_apub_delete_in_community( send_apub_delete_in_community(
local_user_view.person, local_user_view.person,

View file

@ -3,7 +3,6 @@ use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
post::{GetPosts, GetPostsResponse}, post::{GetPosts, GetPostsResponse},
utils::{ utils::{
blocking,
check_private_instance, check_private_instance,
get_local_user_view_from_jwt_opt, get_local_user_view_from_jwt_opt,
listing_type_with_site_default, listing_type_with_site_default,
@ -32,7 +31,7 @@ impl PerformCrud for GetPosts {
let local_user_view = let local_user_view =
get_local_user_view_from_jwt_opt(data.auth.as_ref(), context.pool(), context.secret()) get_local_user_view_from_jwt_opt(data.auth.as_ref(), context.pool(), context.secret())
.await?; .await?;
let local_site = blocking(context.pool(), LocalSite::read).await??; let local_site = LocalSite::read(context.pool()).await?;
check_private_instance(&local_user_view, &local_site)?; check_private_instance(&local_user_view, &local_site)?;
@ -54,9 +53,8 @@ impl PerformCrud for GetPosts {
}; };
let saved_only = data.saved_only; let saved_only = data.saved_only;
let mut posts = blocking(context.pool(), move |conn| { let mut posts = PostQuery::builder()
PostQuery::builder() .pool(context.pool())
.conn(conn)
.local_user(local_user_view.map(|l| l.local_user).as_ref()) .local_user(local_user_view.map(|l| l.local_user).as_ref())
.listing_type(Some(listing_type)) .listing_type(Some(listing_type))
.sort(sort) .sort(sort)
@ -67,8 +65,7 @@ impl PerformCrud for GetPosts {
.limit(limit) .limit(limit)
.build() .build()
.list() .list()
}) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_get_posts"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_get_posts"))?;
// Blank out deleted or removed info for non-logged in users // Blank out deleted or removed info for non-logged in users

View file

@ -2,7 +2,7 @@ use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
post::{GetPost, GetPostResponse}, post::{GetPost, GetPostResponse},
utils::{blocking, check_private_instance, get_local_user_view_from_jwt_opt, mark_post_as_read}, utils::{check_private_instance, get_local_user_view_from_jwt_opt, mark_post_as_read},
}; };
use lemmy_db_schema::{ use lemmy_db_schema::{
aggregates::structs::{PersonPostAggregates, PersonPostAggregatesForm}, aggregates::structs::{PersonPostAggregates, PersonPostAggregatesForm},
@ -28,7 +28,7 @@ impl PerformCrud for GetPost {
let local_user_view = let local_user_view =
get_local_user_view_from_jwt_opt(data.auth.as_ref(), context.pool(), context.secret()) get_local_user_view_from_jwt_opt(data.auth.as_ref(), context.pool(), context.secret())
.await?; .await?;
let local_site = blocking(context.pool(), LocalSite::read).await??; let local_site = LocalSite::read(context.pool()).await?;
check_private_instance(&local_user_view, &local_site)?; check_private_instance(&local_user_view, &local_site)?;
@ -38,18 +38,16 @@ impl PerformCrud for GetPost {
let post_id = if let Some(id) = data.id { let post_id = if let Some(id) = data.id {
id id
} else if let Some(comment_id) = data.comment_id { } else if let Some(comment_id) = data.comment_id {
blocking(context.pool(), move |conn| Comment::read(conn, comment_id)) Comment::read(context.pool(), comment_id)
.await? .await
.map_err(|e| LemmyError::from_error_message(e, "couldnt_find_post"))? .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_post"))?
.post_id .post_id
} else { } else {
Err(LemmyError::from_message("couldnt_find_post"))? Err(LemmyError::from_message("couldnt_find_post"))?
}; };
let mut post_view = blocking(context.pool(), move |conn| { let mut post_view = PostView::read(context.pool(), post_id, person_id)
PostView::read(conn, post_id, person_id) .await
})
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_find_post"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_post"))?;
// Mark the post as read // Mark the post as read
@ -60,10 +58,8 @@ impl PerformCrud for GetPost {
// Necessary for the sidebar subscribed // Necessary for the sidebar subscribed
let community_id = post_view.community.id; let community_id = post_view.community.id;
let mut community_view = blocking(context.pool(), move |conn| { let mut community_view = CommunityView::read(context.pool(), community_id, person_id)
CommunityView::read(conn, community_id, person_id) .await
})
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_find_community"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_community"))?;
// Insert into PersonPostAggregates // Insert into PersonPostAggregates
@ -76,10 +72,8 @@ impl PerformCrud for GetPost {
read_comments, read_comments,
..PersonPostAggregatesForm::default() ..PersonPostAggregatesForm::default()
}; };
blocking(context.pool(), move |conn| { PersonPostAggregates::upsert(context.pool(), &person_post_agg_form)
PersonPostAggregates::upsert(conn, &person_post_agg_form) .await
})
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_find_post"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_post"))?;
} }
@ -94,10 +88,7 @@ impl PerformCrud for GetPost {
} }
} }
let moderators = blocking(context.pool(), move |conn| { let moderators = CommunityModeratorView::for_community(context.pool(), community_id).await?;
CommunityModeratorView::for_community(conn, community_id)
})
.await??;
let online = context let online = context
.chat_server() .chat_server()

View file

@ -2,7 +2,7 @@ use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
post::{PostResponse, RemovePost}, post::{PostResponse, RemovePost},
utils::{blocking, check_community_ban, get_local_user_view_from_jwt, is_mod_or_admin}, utils::{check_community_ban, get_local_user_view_from_jwt, is_mod_or_admin},
}; };
use lemmy_apub::activities::deletion::{send_apub_delete_in_community, DeletableObjects}; use lemmy_apub::activities::deletion::{send_apub_delete_in_community, DeletableObjects};
use lemmy_db_schema::{ use lemmy_db_schema::{
@ -31,7 +31,7 @@ impl PerformCrud for RemovePost {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let post_id = data.post_id; let post_id = data.post_id;
let orig_post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; let orig_post = Post::read(context.pool(), post_id).await?;
check_community_ban( check_community_ban(
local_user_view.person.id, local_user_view.person.id,
@ -51,14 +51,12 @@ impl PerformCrud for RemovePost {
// Update the post // Update the post
let post_id = data.post_id; let post_id = data.post_id;
let removed = data.removed; let removed = data.removed;
let updated_post = blocking(context.pool(), move |conn| { let updated_post = Post::update(
Post::update( context.pool(),
conn,
post_id, post_id,
&PostUpdateForm::builder().removed(Some(removed)).build(), &PostUpdateForm::builder().removed(Some(removed)).build(),
) )
}) .await?;
.await??;
// Mod tables // Mod tables
let form = ModRemovePostForm { let form = ModRemovePostForm {
@ -67,10 +65,7 @@ impl PerformCrud for RemovePost {
removed: Some(removed), removed: Some(removed),
reason: data.reason.to_owned(), reason: data.reason.to_owned(),
}; };
blocking(context.pool(), move |conn| { ModRemovePost::create(context.pool(), &form).await?;
ModRemovePost::create(conn, &form)
})
.await??;
let res = send_post_ws_message( let res = send_post_ws_message(
data.post_id, data.post_id,
@ -82,10 +77,7 @@ impl PerformCrud for RemovePost {
.await?; .await?;
// apub updates // apub updates
let community = blocking(context.pool(), move |conn| { let community = Community::read(context.pool(), orig_post.community_id).await?;
Community::read(conn, orig_post.community_id)
})
.await??;
let deletable = DeletableObjects::Post(Box::new(updated_post.into())); let deletable = DeletableObjects::Post(Box::new(updated_post.into()));
send_apub_delete_in_community( send_apub_delete_in_community(
local_user_view.person, local_user_view.person,

View file

@ -4,7 +4,6 @@ use lemmy_api_common::{
post::{EditPost, PostResponse}, post::{EditPost, PostResponse},
request::fetch_site_data, request::fetch_site_data,
utils::{ utils::{
blocking,
check_community_ban, check_community_ban,
check_community_deleted_or_removed, check_community_deleted_or_removed,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
@ -44,7 +43,7 @@ impl PerformCrud for EditPost {
let data: &EditPost = self; let data: &EditPost = self;
let local_user_view = let local_user_view =
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let local_site = blocking(context.pool(), LocalSite::read).await??; let local_site = LocalSite::read(context.pool()).await?;
let data_url = data.url.as_ref(); let data_url = data.url.as_ref();
@ -64,7 +63,7 @@ impl PerformCrud for EditPost {
} }
let post_id = data.post_id; let post_id = data.post_id;
let orig_post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; let orig_post = Post::read(context.pool(), post_id).await?;
check_community_ban( check_community_ban(
local_user_view.person.id, local_user_view.person.id,
@ -88,10 +87,12 @@ impl PerformCrud for EditPost {
.unwrap_or_default(); .unwrap_or_default();
let language_id = self.language_id; let language_id = self.language_id;
blocking(context.pool(), move |conn| { CommunityLanguage::is_allowed_community_language(
CommunityLanguage::is_allowed_community_language(conn, language_id, orig_post.community_id) context.pool(),
}) language_id,
.await??; orig_post.community_id,
)
.await?;
let post_form = PostUpdateForm::builder() let post_form = PostUpdateForm::builder()
.name(data.name.to_owned()) .name(data.name.to_owned())
@ -106,10 +107,7 @@ impl PerformCrud for EditPost {
.build(); .build();
let post_id = data.post_id; let post_id = data.post_id;
let res = blocking(context.pool(), move |conn| { let res = Post::update(context.pool(), post_id, &post_form).await;
Post::update(conn, post_id, &post_form)
})
.await?;
let updated_post: Post = match res { let updated_post: Post = match res {
Ok(post) => post, Ok(post) => post,
Err(e) => { Err(e) => {

View file

@ -3,7 +3,6 @@ use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
private_message::{CreatePrivateMessage, PrivateMessageResponse}, private_message::{CreatePrivateMessage, PrivateMessageResponse},
utils::{ utils::{
blocking,
check_person_block, check_person_block,
get_interface_language, get_interface_language,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
@ -43,7 +42,7 @@ impl PerformCrud for CreatePrivateMessage {
let data: &CreatePrivateMessage = self; let data: &CreatePrivateMessage = self;
let local_user_view = let local_user_view =
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let local_site = blocking(context.pool(), LocalSite::read).await??; let local_site = LocalSite::read(context.pool()).await?;
let content_slurs_removed = remove_slurs( let content_slurs_removed = remove_slurs(
&data.content.to_owned(), &data.content.to_owned(),
@ -58,11 +57,8 @@ impl PerformCrud for CreatePrivateMessage {
.recipient_id(data.recipient_id) .recipient_id(data.recipient_id)
.build(); .build();
let inserted_private_message = match blocking(context.pool(), move |conn| { let inserted_private_message =
PrivateMessage::create(conn, &private_message_form) match PrivateMessage::create(context.pool(), &private_message_form).await {
})
.await?
{
Ok(private_message) => private_message, Ok(private_message) => private_message,
Err(e) => { Err(e) => {
return Err(LemmyError::from_error_message( return Err(LemmyError::from_error_message(
@ -74,25 +70,20 @@ impl PerformCrud for CreatePrivateMessage {
let inserted_private_message_id = inserted_private_message.id; let inserted_private_message_id = inserted_private_message.id;
let protocol_and_hostname = context.settings().get_protocol_and_hostname(); let protocol_and_hostname = context.settings().get_protocol_and_hostname();
let updated_private_message = blocking(
context.pool(),
move |conn| -> Result<PrivateMessage, LemmyError> {
let apub_id = generate_local_apub_endpoint( let apub_id = generate_local_apub_endpoint(
EndpointType::PrivateMessage, EndpointType::PrivateMessage,
&inserted_private_message_id.to_string(), &inserted_private_message_id.to_string(),
&protocol_and_hostname, &protocol_and_hostname,
)?; )?;
Ok(PrivateMessage::update( let updated_private_message = PrivateMessage::update(
conn, context.pool(),
inserted_private_message.id, inserted_private_message.id,
&PrivateMessageUpdateForm::builder() &PrivateMessageUpdateForm::builder()
.ap_id(Some(apub_id)) .ap_id(Some(apub_id))
.build(), .build(),
)?)
},
) )
.await? .await
.map_err(|e| e.with_message("couldnt_create_private_message"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_create_private_message"))?;
CreateOrUpdatePrivateMessage::send( CreateOrUpdatePrivateMessage::send(
updated_private_message.into(), updated_private_message.into(),
@ -113,10 +104,7 @@ impl PerformCrud for CreatePrivateMessage {
// Send email to the local recipient, if one exists // Send email to the local recipient, if one exists
if res.private_message_view.recipient.local { if res.private_message_view.recipient.local {
let recipient_id = data.recipient_id; let recipient_id = data.recipient_id;
let local_recipient = blocking(context.pool(), move |conn| { let local_recipient = LocalUserView::read_person(context.pool(), recipient_id).await?;
LocalUserView::read_person(conn, recipient_id)
})
.await??;
let lang = get_interface_language(&local_recipient); let lang = get_interface_language(&local_recipient);
let inbox_link = format!("{}/inbox", context.settings().get_protocol_and_hostname()); let inbox_link = format!("{}/inbox", context.settings().get_protocol_and_hostname());
send_email_to_user( send_email_to_user(

View file

@ -2,7 +2,7 @@ use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
private_message::{DeletePrivateMessage, PrivateMessageResponse}, private_message::{DeletePrivateMessage, PrivateMessageResponse},
utils::{blocking, get_local_user_view_from_jwt}, utils::get_local_user_view_from_jwt,
}; };
use lemmy_apub::activities::deletion::send_apub_delete_private_message; use lemmy_apub::activities::deletion::send_apub_delete_private_message;
use lemmy_db_schema::{ use lemmy_db_schema::{
@ -28,10 +28,7 @@ impl PerformCrud for DeletePrivateMessage {
// Checking permissions // Checking permissions
let private_message_id = data.private_message_id; let private_message_id = data.private_message_id;
let orig_private_message = blocking(context.pool(), move |conn| { let orig_private_message = PrivateMessage::read(context.pool(), private_message_id).await?;
PrivateMessage::read(conn, private_message_id)
})
.await??;
if local_user_view.person.id != orig_private_message.creator_id { if local_user_view.person.id != orig_private_message.creator_id {
return Err(LemmyError::from_message("no_private_message_edit_allowed")); return Err(LemmyError::from_message("no_private_message_edit_allowed"));
} }
@ -39,16 +36,14 @@ impl PerformCrud for DeletePrivateMessage {
// Doing the update // Doing the update
let private_message_id = data.private_message_id; let private_message_id = data.private_message_id;
let deleted = data.deleted; let deleted = data.deleted;
let updated_private_message = blocking(context.pool(), move |conn| { let updated_private_message = PrivateMessage::update(
PrivateMessage::update( context.pool(),
conn,
private_message_id, private_message_id,
&PrivateMessageUpdateForm::builder() &PrivateMessageUpdateForm::builder()
.deleted(Some(deleted)) .deleted(Some(deleted))
.build(), .build(),
) )
}) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_update_private_message"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_private_message"))?;
// Send the apub update // Send the apub update

View file

@ -2,7 +2,7 @@ use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
private_message::{GetPrivateMessages, PrivateMessagesResponse}, private_message::{GetPrivateMessages, PrivateMessagesResponse},
utils::{blocking, get_local_user_view_from_jwt}, utils::get_local_user_view_from_jwt,
}; };
use lemmy_db_schema::traits::DeleteableOrRemoveable; use lemmy_db_schema::traits::DeleteableOrRemoveable;
use lemmy_db_views::private_message_view::PrivateMessageQuery; use lemmy_db_views::private_message_view::PrivateMessageQuery;
@ -27,17 +27,15 @@ impl PerformCrud for GetPrivateMessages {
let page = data.page; let page = data.page;
let limit = data.limit; let limit = data.limit;
let unread_only = data.unread_only; let unread_only = data.unread_only;
let mut messages = blocking(context.pool(), move |conn| { let mut messages = PrivateMessageQuery::builder()
PrivateMessageQuery::builder() .pool(context.pool())
.conn(conn)
.recipient_id(person_id) .recipient_id(person_id)
.page(page) .page(page)
.limit(limit) .limit(limit)
.unread_only(unread_only) .unread_only(unread_only)
.build() .build()
.list() .list()
}) .await?;
.await??;
// Messages sent by ourselves should be marked as read. The `read` column in database is only // Messages sent by ourselves should be marked as read. The `read` column in database is only
// for the recipient, and shouldnt be exposed to sender. // for the recipient, and shouldnt be exposed to sender.

View file

@ -2,7 +2,7 @@ use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
private_message::{EditPrivateMessage, PrivateMessageResponse}, private_message::{EditPrivateMessage, PrivateMessageResponse},
utils::{blocking, get_local_user_view_from_jwt, local_site_to_slur_regex}, utils::{get_local_user_view_from_jwt, local_site_to_slur_regex},
}; };
use lemmy_apub::protocol::activities::{ use lemmy_apub::protocol::activities::{
create_or_update::private_message::CreateOrUpdatePrivateMessage, create_or_update::private_message::CreateOrUpdatePrivateMessage,
@ -32,14 +32,11 @@ impl PerformCrud for EditPrivateMessage {
let data: &EditPrivateMessage = self; let data: &EditPrivateMessage = self;
let local_user_view = let local_user_view =
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let local_site = blocking(context.pool(), LocalSite::read).await??; let local_site = LocalSite::read(context.pool()).await?;
// Checking permissions // Checking permissions
let private_message_id = data.private_message_id; let private_message_id = data.private_message_id;
let orig_private_message = blocking(context.pool(), move |conn| { let orig_private_message = PrivateMessage::read(context.pool(), private_message_id).await?;
PrivateMessage::read(conn, private_message_id)
})
.await??;
if local_user_view.person.id != orig_private_message.creator_id { if local_user_view.person.id != orig_private_message.creator_id {
return Err(LemmyError::from_message("no_private_message_edit_allowed")); return Err(LemmyError::from_message("no_private_message_edit_allowed"));
} }
@ -47,17 +44,15 @@ impl PerformCrud for EditPrivateMessage {
// Doing the update // Doing the update
let content_slurs_removed = remove_slurs(&data.content, &local_site_to_slur_regex(&local_site)); let content_slurs_removed = remove_slurs(&data.content, &local_site_to_slur_regex(&local_site));
let private_message_id = data.private_message_id; let private_message_id = data.private_message_id;
let updated_private_message = blocking(context.pool(), move |conn| { let updated_private_message = PrivateMessage::update(
PrivateMessage::update( context.pool(),
conn,
private_message_id, private_message_id,
&PrivateMessageUpdateForm::builder() &PrivateMessageUpdateForm::builder()
.content(Some(content_slurs_removed)) .content(Some(content_slurs_removed))
.updated(Some(Some(naive_now()))) .updated(Some(Some(naive_now())))
.build(), .build(),
) )
}) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_update_private_message"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_private_message"))?;
// Send the apub update // Send the apub update

View file

@ -4,7 +4,6 @@ use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
site::{CreateSite, SiteResponse}, site::{CreateSite, SiteResponse},
utils::{ utils::{
blocking,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
is_admin, is_admin,
local_site_to_slur_regex, local_site_to_slur_regex,
@ -43,7 +42,7 @@ impl PerformCrud for CreateSite {
) -> Result<SiteResponse, LemmyError> { ) -> Result<SiteResponse, LemmyError> {
let data: &CreateSite = self; let data: &CreateSite = self;
let local_site = blocking(context.pool(), LocalSite::read).await??; let local_site = LocalSite::read(context.pool()).await?;
if local_site.site_setup { if local_site.site_setup {
return Err(LemmyError::from_message("site_already_exists")); return Err(LemmyError::from_message("site_already_exists"));
@ -88,10 +87,8 @@ impl PerformCrud for CreateSite {
.build(); .build();
let site_id = local_site.site_id; let site_id = local_site.site_id;
blocking(context.pool(), move |conn| {
Site::update(conn, site_id, &site_form) Site::update(context.pool(), site_id, &site_form).await?;
})
.await??;
let local_site_form = LocalSiteUpdateForm::builder() let local_site_form = LocalSiteUpdateForm::builder()
// Set the site setup to true // Set the site setup to true
@ -120,10 +117,8 @@ impl PerformCrud for CreateSite {
.captcha_enabled(data.captcha_enabled) .captcha_enabled(data.captcha_enabled)
.captcha_difficulty(data.captcha_difficulty.to_owned()) .captcha_difficulty(data.captcha_difficulty.to_owned())
.build(); .build();
blocking(context.pool(), move |conn| {
LocalSite::update(conn, &local_site_form) LocalSite::update(context.pool(), &local_site_form).await?;
})
.await??;
let local_site_rate_limit_form = LocalSiteRateLimitUpdateForm::builder() let local_site_rate_limit_form = LocalSiteRateLimitUpdateForm::builder()
.message(data.rate_limit_message) .message(data.rate_limit_message)
@ -140,12 +135,9 @@ impl PerformCrud for CreateSite {
.search_per_second(data.rate_limit_search_per_second) .search_per_second(data.rate_limit_search_per_second)
.build(); .build();
blocking(context.pool(), move |conn| { LocalSiteRateLimit::update(context.pool(), &local_site_rate_limit_form).await?;
LocalSiteRateLimit::update(conn, &local_site_rate_limit_form)
})
.await??;
let site_view = blocking(context.pool(), SiteView::read_local).await??; let site_view = SiteView::read_local(context.pool()).await?;
Ok(SiteResponse { site_view }) Ok(SiteResponse { site_view })
} }

View file

@ -2,7 +2,7 @@ use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
site::{GetSite, GetSiteResponse, MyUserInfo}, site::{GetSite, GetSiteResponse, MyUserInfo},
utils::{blocking, build_federated_instances, get_local_user_settings_view_from_jwt_opt}, utils::{build_federated_instances, get_local_user_settings_view_from_jwt_opt},
}; };
use lemmy_db_schema::source::{actor_language::SiteLanguage, language::Language}; use lemmy_db_schema::source::{actor_language::SiteLanguage, language::Language};
use lemmy_db_views::structs::{LocalUserDiscussionLanguageView, SiteView}; use lemmy_db_views::structs::{LocalUserDiscussionLanguageView, SiteView};
@ -28,9 +28,9 @@ impl PerformCrud for GetSite {
) -> Result<GetSiteResponse, LemmyError> { ) -> Result<GetSiteResponse, LemmyError> {
let data: &GetSite = self; let data: &GetSite = self;
let site_view = blocking(context.pool(), SiteView::read_local).await??; let site_view = SiteView::read_local(context.pool()).await?;
let admins = blocking(context.pool(), PersonViewSafe::admins).await??; let admins = PersonViewSafe::admins(context.pool()).await?;
let online = context let online = context
.chat_server() .chat_server()
@ -49,36 +49,27 @@ impl PerformCrud for GetSite {
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let local_user_id = local_user_view.local_user.id; let local_user_id = local_user_view.local_user.id;
let follows = blocking(context.pool(), move |conn| { let follows = CommunityFollowerView::for_person(context.pool(), person_id)
CommunityFollowerView::for_person(conn, person_id) .await
})
.await?
.map_err(|e| LemmyError::from_error_message(e, "system_err_login"))?; .map_err(|e| LemmyError::from_error_message(e, "system_err_login"))?;
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let community_blocks = blocking(context.pool(), move |conn| { let community_blocks = CommunityBlockView::for_person(context.pool(), person_id)
CommunityBlockView::for_person(conn, person_id) .await
})
.await?
.map_err(|e| LemmyError::from_error_message(e, "system_err_login"))?; .map_err(|e| LemmyError::from_error_message(e, "system_err_login"))?;
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let person_blocks = blocking(context.pool(), move |conn| { let person_blocks = PersonBlockView::for_person(context.pool(), person_id)
PersonBlockView::for_person(conn, person_id) .await
})
.await?
.map_err(|e| LemmyError::from_error_message(e, "system_err_login"))?; .map_err(|e| LemmyError::from_error_message(e, "system_err_login"))?;
let moderates = blocking(context.pool(), move |conn| { let moderates = CommunityModeratorView::for_person(context.pool(), person_id)
CommunityModeratorView::for_person(conn, person_id) .await
})
.await?
.map_err(|e| LemmyError::from_error_message(e, "system_err_login"))?; .map_err(|e| LemmyError::from_error_message(e, "system_err_login"))?;
let discussion_languages = blocking(context.pool(), move |conn| { let discussion_languages =
LocalUserDiscussionLanguageView::read_languages(conn, local_user_id) LocalUserDiscussionLanguageView::read_languages(context.pool(), local_user_id)
}) .await
.await?
.map_err(|e| LemmyError::from_error_message(e, "system_err_login"))?; .map_err(|e| LemmyError::from_error_message(e, "system_err_login"))?;
Some(MyUserInfo { Some(MyUserInfo {
@ -96,8 +87,8 @@ impl PerformCrud for GetSite {
let federated_instances = let federated_instances =
build_federated_instances(&site_view.local_site, context.pool()).await?; build_federated_instances(&site_view.local_site, context.pool()).await?;
let all_languages = blocking(context.pool(), Language::read_all).await??; let all_languages = Language::read_all(context.pool()).await?;
let discussion_languages = blocking(context.pool(), SiteLanguage::read_local).await??; let discussion_languages = SiteLanguage::read_local(context.pool()).await?;
Ok(GetSiteResponse { Ok(GetSiteResponse {
site_view, site_view,

View file

@ -3,7 +3,6 @@ use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
site::{EditSite, SiteResponse}, site::{EditSite, SiteResponse},
utils::{ utils::{
blocking,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
is_admin, is_admin,
local_site_to_slur_regex, local_site_to_slur_regex,
@ -46,7 +45,7 @@ impl PerformCrud for EditSite {
let data: &EditSite = self; let data: &EditSite = self;
let local_user_view = let local_user_view =
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let local_site = blocking(context.pool(), LocalSite::read).await??; let local_site = LocalSite::read(context.pool()).await?;
// Make sure user is an admin // Make sure user is an admin
is_admin(&local_user_view)?; is_admin(&local_user_view)?;
@ -75,11 +74,8 @@ impl PerformCrud for EditSite {
let site_id = local_site.site_id; let site_id = local_site.site_id;
if let Some(discussion_languages) = data.discussion_languages.clone() { if let Some(discussion_languages) = data.discussion_languages.clone() {
blocking(context.pool(), move |conn| { let site = Site::read(context.pool(), site_id).await?;
let site = Site::read(conn, site_id)?; SiteLanguage::update(context.pool(), discussion_languages.clone(), &site).await?;
SiteLanguage::update(conn, discussion_languages, &site)
})
.await??;
} }
let name = data.name.to_owned(); let name = data.name.to_owned();
@ -92,9 +88,7 @@ impl PerformCrud for EditSite {
.updated(Some(Some(naive_now()))) .updated(Some(Some(naive_now())))
.build(); .build();
blocking(context.pool(), move |conn| { Site::update(context.pool(), site_id, &site_form)
Site::update(conn, local_site.site_id, &site_form)
})
.await .await
// Ignore errors for all these, so as to not throw errors if no update occurs // Ignore errors for all these, so as to not throw errors if no update occurs
// Diesel will throw an error for empty update forms // Diesel will throw an error for empty update forms
@ -126,9 +120,7 @@ impl PerformCrud for EditSite {
.captcha_difficulty(data.captcha_difficulty.to_owned()) .captcha_difficulty(data.captcha_difficulty.to_owned())
.build(); .build();
let update_local_site = blocking(context.pool(), move |conn| { let update_local_site = LocalSite::update(context.pool(), &local_site_form)
LocalSite::update(conn, &local_site_form)
})
.await .await
.ok(); .ok();
@ -147,23 +139,15 @@ impl PerformCrud for EditSite {
.search_per_second(data.rate_limit_search_per_second) .search_per_second(data.rate_limit_search_per_second)
.build(); .build();
blocking(context.pool(), move |conn| { LocalSiteRateLimit::update(context.pool(), &local_site_rate_limit_form)
LocalSiteRateLimit::update(conn, &local_site_rate_limit_form)
})
.await .await
.ok(); .ok();
// Replace the blocked and allowed instances // Replace the blocked and allowed instances
let allowed = data.allowed_instances.to_owned(); let allowed = data.allowed_instances.to_owned();
blocking(context.pool(), move |conn| { FederationAllowList::replace(context.pool(), allowed).await?;
FederationAllowList::replace(conn, allowed)
})
.await??;
let blocked = data.blocked_instances.to_owned(); let blocked = data.blocked_instances.to_owned();
blocking(context.pool(), move |conn| { FederationBlockList::replace(context.pool(), blocked).await?;
FederationBlockList::replace(conn, blocked)
})
.await??;
// TODO can't think of a better way to do this. // TODO can't think of a better way to do this.
// If the server suddenly requires email verification, or required applications, no old users // If the server suddenly requires email verification, or required applications, no old users
@ -172,39 +156,25 @@ impl PerformCrud for EditSite {
let new_require_application = update_local_site let new_require_application = update_local_site
.as_ref() .as_ref()
.map(|ols| { .map(|ols| ols.require_application)
ols
.as_ref()
.map(|ls| ls.require_application)
.unwrap_or(false)
})
.unwrap_or(false); .unwrap_or(false);
if !local_site.require_application && new_require_application { if !local_site.require_application && new_require_application {
blocking(context.pool(), move |conn| { LocalUser::set_all_users_registration_applications_accepted(context.pool())
LocalUser::set_all_users_registration_applications_accepted(conn) .await
})
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_set_all_registrations_accepted"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_set_all_registrations_accepted"))?;
} }
let new_require_email_verification = update_local_site let new_require_email_verification = update_local_site
.as_ref() .as_ref()
.map(|ols| { .map(|ols| ols.require_email_verification)
ols
.as_ref()
.map(|ls| ls.require_email_verification)
.unwrap_or(false)
})
.unwrap_or(false); .unwrap_or(false);
if !local_site.require_email_verification && new_require_email_verification { if !local_site.require_email_verification && new_require_email_verification {
blocking(context.pool(), move |conn| { LocalUser::set_all_users_email_verified(context.pool())
LocalUser::set_all_users_email_verified(conn) .await
})
.await?
.map_err(|e| LemmyError::from_error_message(e, "couldnt_set_all_email_verified"))?; .map_err(|e| LemmyError::from_error_message(e, "couldnt_set_all_email_verified"))?;
} }
let site_view = blocking(context.pool(), SiteView::read_local).await??; let site_view = SiteView::read_local(context.pool()).await?;
let res = SiteResponse { site_view }; let res = SiteResponse { site_view };

View file

@ -4,7 +4,6 @@ use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
person::{LoginResponse, Register}, person::{LoginResponse, Register},
utils::{ utils::{
blocking,
honeypot_check, honeypot_check,
local_site_to_slur_regex, local_site_to_slur_regex,
password_length_check, password_length_check,
@ -28,7 +27,6 @@ use lemmy_db_schema::{
traits::Crud, traits::Crud,
}; };
use lemmy_db_views::structs::{LocalUserView, SiteView}; use lemmy_db_views::structs::{LocalUserView, SiteView};
use lemmy_db_views_actor::structs::PersonViewSafe;
use lemmy_utils::{ use lemmy_utils::{
claims::Claims, claims::Claims,
error::LemmyError, error::LemmyError,
@ -49,7 +47,7 @@ impl PerformCrud for Register {
) -> Result<LoginResponse, LemmyError> { ) -> Result<LoginResponse, LemmyError> {
let data: &Register = self; let data: &Register = self;
let site_view = blocking(context.pool(), SiteView::read_local).await??; let site_view = SiteView::read_local(context.pool()).await?;
let local_site = site_view.local_site; let local_site = site_view.local_site;
if !local_site.open_registration { if !local_site.open_registration {
@ -63,7 +61,7 @@ impl PerformCrud for Register {
return Err(LemmyError::from_message("email_required")); return Err(LemmyError::from_message("email_required"));
} }
if local_site.require_application && data.answer.is_none() { if local_site.site_setup && local_site.require_application && data.answer.is_none() {
return Err(LemmyError::from_message( return Err(LemmyError::from_message(
"registration_application_answer_required", "registration_application_answer_required",
)); ));
@ -74,14 +72,8 @@ impl PerformCrud for Register {
return Err(LemmyError::from_message("passwords_dont_match")); return Err(LemmyError::from_message("passwords_dont_match"));
} }
// Check if there are admins. False if admins exist // If the site is set up, check the captcha
let no_admins = blocking(context.pool(), move |conn| { if local_site.site_setup && local_site.captcha_enabled {
PersonViewSafe::admins(conn).map(|a| a.is_empty())
})
.await??;
// If its not the admin, check the captcha
if !no_admins && local_site.captcha_enabled {
let check = context let check = context
.chat_server() .chat_server()
.send(CheckCaptcha { .send(CheckCaptcha {
@ -124,15 +116,14 @@ impl PerformCrud for Register {
.public_key(actor_keypair.public_key) .public_key(actor_keypair.public_key)
.inbox_url(Some(generate_inbox_url(&actor_id)?)) .inbox_url(Some(generate_inbox_url(&actor_id)?))
.shared_inbox_url(Some(generate_shared_inbox_url(&actor_id)?)) .shared_inbox_url(Some(generate_shared_inbox_url(&actor_id)?))
.admin(Some(no_admins)) // If its the initial site setup, they are an admin
.admin(Some(!local_site.site_setup))
.instance_id(site_view.site.instance_id) .instance_id(site_view.site.instance_id)
.build(); .build();
// insert the person // insert the person
let inserted_person = blocking(context.pool(), move |conn| { let inserted_person = Person::create(context.pool(), &person_form)
Person::create(conn, &person_form) .await
})
.await?
.map_err(|e| LemmyError::from_error_message(e, "user_already_exists"))?; .map_err(|e| LemmyError::from_error_message(e, "user_already_exists"))?;
// Create the local user // Create the local user
@ -143,11 +134,7 @@ impl PerformCrud for Register {
.show_nsfw(Some(data.show_nsfw)) .show_nsfw(Some(data.show_nsfw))
.build(); .build();
let inserted_local_user = match blocking(context.pool(), move |conn| { let inserted_local_user = match LocalUser::create(context.pool(), &local_user_form).await {
LocalUser::create(conn, &local_user_form)
})
.await?
{
Ok(lu) => lu, Ok(lu) => lu,
Err(e) => { Err(e) => {
let err_type = if e.to_string() let err_type = if e.to_string()
@ -159,16 +146,13 @@ impl PerformCrud for Register {
}; };
// If the local user creation errored, then delete that person // If the local user creation errored, then delete that person
blocking(context.pool(), move |conn| { Person::delete(context.pool(), inserted_person.id).await?;
Person::delete(conn, inserted_person.id)
})
.await??;
return Err(LemmyError::from_error_message(e, err_type)); return Err(LemmyError::from_error_message(e, err_type));
} }
}; };
if local_site.require_application { if local_site.site_setup && local_site.require_application {
// Create the registration application // Create the registration application
let form = RegistrationApplicationInsertForm { let form = RegistrationApplicationInsertForm {
local_user_id: inserted_local_user.id, local_user_id: inserted_local_user.id,
@ -176,10 +160,7 @@ impl PerformCrud for Register {
answer: data.answer.to_owned().expect("must have an answer"), answer: data.answer.to_owned().expect("must have an answer"),
}; };
blocking(context.pool(), move |conn| { RegistrationApplication::create(context.pool(), &form).await?;
RegistrationApplication::create(conn, &form)
})
.await??;
} }
// Email the admins // Email the admins
@ -194,8 +175,10 @@ impl PerformCrud for Register {
verify_email_sent: false, verify_email_sent: false,
}; };
// Log the user in directly if email verification and application aren't required // Log the user in directly if the site is not setup, or email verification and application aren't required
if !local_site.require_application && !local_site.require_email_verification { if !local_site.site_setup
|| (!local_site.require_application && !local_site.require_email_verification)
{
login_response.jwt = Some( login_response.jwt = Some(
Claims::jwt( Claims::jwt(
inserted_local_user.id.0, inserted_local_user.id.0,

View file

@ -2,7 +2,7 @@ use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
person::{GetPersonDetails, GetPersonDetailsResponse}, person::{GetPersonDetails, GetPersonDetailsResponse},
utils::{blocking, check_private_instance, get_local_user_view_from_jwt_opt}, utils::{check_private_instance, get_local_user_view_from_jwt_opt},
}; };
use lemmy_apub::{fetcher::resolve_actor_identifier, objects::person::ApubPerson}; use lemmy_apub::{fetcher::resolve_actor_identifier, objects::person::ApubPerson};
use lemmy_db_schema::{ use lemmy_db_schema::{
@ -34,7 +34,7 @@ impl PerformCrud for GetPersonDetails {
let local_user_view = let local_user_view =
get_local_user_view_from_jwt_opt(data.auth.as_ref(), context.pool(), context.secret()) get_local_user_view_from_jwt_opt(data.auth.as_ref(), context.pool(), context.secret())
.await?; .await?;
let local_site = blocking(context.pool(), LocalSite::read).await??; let local_site = LocalSite::read(context.pool()).await?;
check_private_instance(&local_user_view, &local_site)?; check_private_instance(&local_user_view, &local_site)?;
@ -56,10 +56,7 @@ impl PerformCrud for GetPersonDetails {
// You don't need to return settings for the user, since this comes back with GetSite // You don't need to return settings for the user, since this comes back with GetSite
// `my_user` // `my_user`
let person_view = blocking(context.pool(), move |conn| { let person_view = PersonViewSafe::read(context.pool(), person_details_id).await?;
PersonViewSafe::read(conn, person_details_id)
})
.await??;
let sort = data.sort; let sort = data.sort;
let page = data.page; let page = data.page;
@ -69,9 +66,8 @@ impl PerformCrud for GetPersonDetails {
let local_user = local_user_view.map(|l| l.local_user); let local_user = local_user_view.map(|l| l.local_user);
let local_user_clone = local_user.to_owned(); let local_user_clone = local_user.to_owned();
let posts = blocking(context.pool(), move |conn| {
let posts_query = PostQuery::builder() let posts_query = PostQuery::builder()
.conn(conn) .pool(context.pool())
.sort(sort) .sort(sort)
.saved_only(saved_only) .saved_only(saved_only)
.local_user(local_user.as_ref()) .local_user(local_user.as_ref())
@ -81,7 +77,7 @@ impl PerformCrud for GetPersonDetails {
// If its saved only, you don't care what creator it was // If its saved only, you don't care what creator it was
// Or, if its not saved, then you only want it for that specific creator // Or, if its not saved, then you only want it for that specific creator
if !saved_only.unwrap_or(false) { let posts = if !saved_only.unwrap_or(false) {
posts_query posts_query
.creator_id(Some(person_details_id)) .creator_id(Some(person_details_id))
.build() .build()
@ -89,12 +85,10 @@ impl PerformCrud for GetPersonDetails {
} else { } else {
posts_query.build().list() posts_query.build().list()
} }
}) .await?;
.await??;
let comments = blocking(context.pool(), move |conn| {
let comments_query = CommentQuery::builder() let comments_query = CommentQuery::builder()
.conn(conn) .pool(context.pool())
.local_user(local_user_clone.as_ref()) .local_user(local_user_clone.as_ref())
.sort(sort.map(post_to_comment_sort_type)) .sort(sort.map(post_to_comment_sort_type))
.saved_only(saved_only) .saved_only(saved_only)
@ -105,7 +99,7 @@ impl PerformCrud for GetPersonDetails {
// If its saved only, you don't care what creator it was // If its saved only, you don't care what creator it was
// Or, if its not saved, then you only want it for that specific creator // Or, if its not saved, then you only want it for that specific creator
if !saved_only.unwrap_or(false) { let comments = if !saved_only.unwrap_or(false) {
comments_query comments_query
.creator_id(Some(person_details_id)) .creator_id(Some(person_details_id))
.build() .build()
@ -113,13 +107,9 @@ impl PerformCrud for GetPersonDetails {
} else { } else {
comments_query.build().list() comments_query.build().list()
} }
}) .await?;
.await??;
let moderates = blocking(context.pool(), move |conn| { let moderates = CommunityModeratorView::for_person(context.pool(), person_details_id).await?;
CommunityModeratorView::for_person(conn, person_details_id)
})
.await??;
// Return the jwt // Return the jwt
Ok(GetPersonDetailsResponse { Ok(GetPersonDetailsResponse {

View file

@ -21,11 +21,11 @@ lemmy_db_views_actor = { version = "=0.16.5", path = "../db_views_actor", featur
lemmy_api_common = { version = "=0.16.5", path = "../api_common", features = ["full"] } lemmy_api_common = { version = "=0.16.5", path = "../api_common", features = ["full"] }
lemmy_websocket = { version = "=0.16.5", path = "../websocket" } lemmy_websocket = { version = "=0.16.5", path = "../websocket" }
activitypub_federation = "0.2.3" activitypub_federation = "0.2.3"
diesel = "2.0.0" diesel = "2.0.2"
activitystreams-kinds = "0.2.1" activitystreams-kinds = "0.2.1"
chrono = { version = "0.4.22", features = ["serde"], default-features = false } chrono = { version = "0.4.22", features = ["serde"], default-features = false }
serde_json = { version = "1.0.85", features = ["preserve_order"] } serde_json = { version = "1.0.87", features = ["preserve_order"] }
serde = { version = "1.0.145", features = ["derive"] } serde = { version = "1.0.147", features = ["derive"] }
serde_with = "1.14.0" serde_with = "1.14.0"
actix = "0.13.0" actix = "0.13.0"
actix-web = { version = "4.2.1", default-features = false } actix-web = { version = "4.2.1", default-features = false }
@ -35,15 +35,16 @@ strum_macros = "0.24.3"
url = { version = "2.3.1", features = ["serde"] } url = { version = "2.3.1", features = ["serde"] }
http = "0.2.8" http = "0.2.8"
http-signature-normalization-actix = { version = "0.6.1", default-features = false, features = ["server", "sha-2"] } http-signature-normalization-actix = { version = "0.6.1", default-features = false, features = ["server", "sha-2"] }
futures = "0.3.24" futures = "0.3.25"
itertools = "0.10.5" itertools = "0.10.5"
uuid = { version = "1.1.2", features = ["serde", "v4"] } uuid = { version = "1.2.1", features = ["serde", "v4"] }
sha2 = "0.10.6" sha2 = "0.10.6"
async-trait = "0.1.57" async-trait = "0.1.58"
anyhow = "1.0.65" anyhow = "1.0.66"
reqwest = { version = "0.11.12", features = ["json"] } reqwest = { version = "0.11.12", features = ["json"] }
html2md = "0.2.13" html2md = "0.2.13"
once_cell = "1.15.0" once_cell = "1.15.0"
tokio = "1.21.2"
[dev-dependencies] [dev-dependencies]
serial_test = "0.9.0" serial_test = "0.9.0"

View file

@ -23,7 +23,7 @@ use activitypub_federation::{
use activitystreams_kinds::{activity::BlockType, public}; use activitystreams_kinds::{activity::BlockType, public};
use anyhow::anyhow; use anyhow::anyhow;
use chrono::NaiveDateTime; use chrono::NaiveDateTime;
use lemmy_api_common::utils::{blocking, remove_user_data, remove_user_data_in_community}; use lemmy_api_common::utils::{remove_user_data, remove_user_data_in_community};
use lemmy_db_schema::{ use lemmy_db_schema::{
source::{ source::{
community::{ community::{
@ -126,7 +126,7 @@ impl ActivityHandler for BlockUser {
verify_is_public(&self.to, &self.cc)?; verify_is_public(&self.to, &self.cc)?;
match self match self
.target .target
.dereference(context, local_instance(context), request_counter) .dereference(context, local_instance(context).await, request_counter)
.await? .await?
{ {
SiteOrCommunity::Site(site) => { SiteOrCommunity::Site(site) => {
@ -164,29 +164,27 @@ impl ActivityHandler for BlockUser {
let expires = self.expires.map(|u| u.naive_local()); let expires = self.expires.map(|u| u.naive_local());
let mod_person = self let mod_person = self
.actor .actor
.dereference(context, local_instance(context), request_counter) .dereference(context, local_instance(context).await, request_counter)
.await?; .await?;
let blocked_person = self let blocked_person = self
.object .object
.dereference(context, local_instance(context), request_counter) .dereference(context, local_instance(context).await, request_counter)
.await?; .await?;
let target = self let target = self
.target .target
.dereference(context, local_instance(context), request_counter) .dereference(context, local_instance(context).await, request_counter)
.await?; .await?;
match target { match target {
SiteOrCommunity::Site(_site) => { SiteOrCommunity::Site(_site) => {
let blocked_person = blocking(context.pool(), move |conn| { let blocked_person = Person::update(
Person::update( context.pool(),
conn,
blocked_person.id, blocked_person.id,
&PersonUpdateForm::builder() &PersonUpdateForm::builder()
.banned(Some(true)) .banned(Some(true))
.ban_expires(Some(expires)) .ban_expires(Some(expires))
.build(), .build(),
) )
}) .await?;
.await??;
if self.remove_data.unwrap_or(false) { if self.remove_data.unwrap_or(false) {
remove_user_data( remove_user_data(
blocked_person.id, blocked_person.id,
@ -205,7 +203,7 @@ impl ActivityHandler for BlockUser {
banned: Some(true), banned: Some(true),
expires, expires,
}; };
blocking(context.pool(), move |conn| ModBan::create(conn, &form)).await??; ModBan::create(context.pool(), &form).await?;
} }
SiteOrCommunity::Community(community) => { SiteOrCommunity::Community(community) => {
let community_user_ban_form = CommunityPersonBanForm { let community_user_ban_form = CommunityPersonBanForm {
@ -213,10 +211,7 @@ impl ActivityHandler for BlockUser {
person_id: blocked_person.id, person_id: blocked_person.id,
expires: Some(expires), expires: Some(expires),
}; };
blocking(context.pool(), move |conn| { CommunityPersonBan::ban(context.pool(), &community_user_ban_form).await?;
CommunityPersonBan::ban(conn, &community_user_ban_form)
})
.await??;
// Also unsubscribe them from the community, if they are subscribed // Also unsubscribe them from the community, if they are subscribed
let community_follower_form = CommunityFollowerForm { let community_follower_form = CommunityFollowerForm {
@ -224,10 +219,8 @@ impl ActivityHandler for BlockUser {
person_id: blocked_person.id, person_id: blocked_person.id,
pending: false, pending: false,
}; };
blocking(context.pool(), move |conn: &mut _| { CommunityFollower::unfollow(context.pool(), &community_follower_form)
CommunityFollower::unfollow(conn, &community_follower_form) .await
})
.await?
.ok(); .ok();
if self.remove_data.unwrap_or(false) { if self.remove_data.unwrap_or(false) {
@ -243,10 +236,7 @@ impl ActivityHandler for BlockUser {
banned: Some(true), banned: Some(true),
expires, expires,
}; };
blocking(context.pool(), move |conn| { ModBanFromCommunity::create(context.pool(), &form).await?;
ModBanFromCommunity::create(conn, &form)
})
.await??;
} }
} }
@ -264,7 +254,7 @@ impl GetCommunity for BlockUser {
) -> Result<ApubCommunity, LemmyError> { ) -> Result<ApubCommunity, LemmyError> {
let target = self let target = self
.target .target
.dereference(context, local_instance(context), request_counter) .dereference(context, local_instance(context).await, request_counter)
.await?; .await?;
match target { match target {
SiteOrCommunity::Community(c) => Ok(c), SiteOrCommunity::Community(c) => Ok(c),

View file

@ -5,7 +5,6 @@ use crate::{
}; };
use activitypub_federation::{core::object_id::ObjectId, traits::ApubObject}; use activitypub_federation::{core::object_id::ObjectId, traits::ApubObject};
use chrono::NaiveDateTime; use chrono::NaiveDateTime;
use lemmy_api_common::utils::blocking;
use lemmy_db_schema::{source::site::Site, utils::DbPool}; use lemmy_db_schema::{source::site::Site, utils::DbPool};
use lemmy_utils::error::LemmyError; use lemmy_utils::error::LemmyError;
use lemmy_websocket::LemmyContext; use lemmy_websocket::LemmyContext;
@ -116,8 +115,8 @@ impl SiteOrCommunity {
async fn generate_cc(target: &SiteOrCommunity, pool: &DbPool) -> Result<Vec<Url>, LemmyError> { async fn generate_cc(target: &SiteOrCommunity, pool: &DbPool) -> Result<Vec<Url>, LemmyError> {
Ok(match target { Ok(match target {
SiteOrCommunity::Site(_) => blocking(pool, Site::read_remote_sites) SiteOrCommunity::Site(_) => Site::read_remote_sites(pool)
.await?? .await?
.into_iter() .into_iter()
.map(|s| s.actor_id.into()) .map(|s| s.actor_id.into())
.collect(), .collect(),

View file

@ -19,7 +19,6 @@ use activitypub_federation::{
utils::verify_domains_match, utils::verify_domains_match,
}; };
use activitystreams_kinds::{activity::UndoType, public}; use activitystreams_kinds::{activity::UndoType, public};
use lemmy_api_common::utils::blocking;
use lemmy_db_schema::{ use lemmy_db_schema::{
source::{ source::{
community::{CommunityPersonBan, CommunityPersonBanForm}, community::{CommunityPersonBan, CommunityPersonBanForm},
@ -102,7 +101,7 @@ impl ActivityHandler for UndoBlockUser {
context: &Data<LemmyContext>, context: &Data<LemmyContext>,
request_counter: &mut i32, request_counter: &mut i32,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let instance = local_instance(context); let instance = local_instance(context).await;
let expires = self.object.expires.map(|u| u.naive_local()); let expires = self.object.expires.map(|u| u.naive_local());
let mod_person = self let mod_person = self
.actor .actor
@ -120,17 +119,15 @@ impl ActivityHandler for UndoBlockUser {
.await? .await?
{ {
SiteOrCommunity::Site(_site) => { SiteOrCommunity::Site(_site) => {
let blocked_person = blocking(context.pool(), move |conn| { let blocked_person = Person::update(
Person::update( context.pool(),
conn,
blocked_person.id, blocked_person.id,
&PersonUpdateForm::builder() &PersonUpdateForm::builder()
.banned(Some(false)) .banned(Some(false))
.ban_expires(Some(expires)) .ban_expires(Some(expires))
.build(), .build(),
) )
}) .await?;
.await??;
// write mod log // write mod log
let form = ModBanForm { let form = ModBanForm {
@ -140,7 +137,7 @@ impl ActivityHandler for UndoBlockUser {
banned: Some(false), banned: Some(false),
expires, expires,
}; };
blocking(context.pool(), move |conn| ModBan::create(conn, &form)).await??; ModBan::create(context.pool(), &form).await?;
} }
SiteOrCommunity::Community(community) => { SiteOrCommunity::Community(community) => {
let community_user_ban_form = CommunityPersonBanForm { let community_user_ban_form = CommunityPersonBanForm {
@ -148,10 +145,7 @@ impl ActivityHandler for UndoBlockUser {
person_id: blocked_person.id, person_id: blocked_person.id,
expires: None, expires: None,
}; };
blocking(context.pool(), move |conn: &mut _| { CommunityPersonBan::unban(context.pool(), &community_user_ban_form).await?;
CommunityPersonBan::unban(conn, &community_user_ban_form)
})
.await??;
// write to mod log // write to mod log
let form = ModBanFromCommunityForm { let form = ModBanFromCommunityForm {
@ -162,10 +156,7 @@ impl ActivityHandler for UndoBlockUser {
banned: Some(false), banned: Some(false),
expires, expires,
}; };
blocking(context.pool(), move |conn| { ModBanFromCommunity::create(context.pool(), &form).await?;
ModBanFromCommunity::create(conn, &form)
})
.await??;
} }
} }

View file

@ -24,7 +24,6 @@ use activitypub_federation::{
traits::{ActivityHandler, Actor}, traits::{ActivityHandler, Actor},
}; };
use activitystreams_kinds::{activity::AddType, public}; use activitystreams_kinds::{activity::AddType, public};
use lemmy_api_common::utils::blocking;
use lemmy_db_schema::{ use lemmy_db_schema::{
source::{ source::{
community::{CommunityModerator, CommunityModeratorForm}, community::{CommunityModerator, CommunityModeratorForm},
@ -108,30 +107,25 @@ impl ActivityHandler for AddMod {
let community = self.get_community(context, request_counter).await?; let community = self.get_community(context, request_counter).await?;
let new_mod = self let new_mod = self
.object .object
.dereference(context, local_instance(context), request_counter) .dereference(context, local_instance(context).await, request_counter)
.await?; .await?;
// If we had to refetch the community while parsing the activity, then the new mod has already // If we had to refetch the community while parsing the activity, then the new mod has already
// been added. Skip it here as it would result in a duplicate key error. // been added. Skip it here as it would result in a duplicate key error.
let new_mod_id = new_mod.id; let new_mod_id = new_mod.id;
let moderated_communities = blocking(context.pool(), move |conn| { let moderated_communities =
CommunityModerator::get_person_moderated_communities(conn, new_mod_id) CommunityModerator::get_person_moderated_communities(context.pool(), new_mod_id).await?;
})
.await??;
if !moderated_communities.contains(&community.id) { if !moderated_communities.contains(&community.id) {
let form = CommunityModeratorForm { let form = CommunityModeratorForm {
community_id: community.id, community_id: community.id,
person_id: new_mod.id, person_id: new_mod.id,
}; };
blocking(context.pool(), move |conn| { CommunityModerator::join(context.pool(), &form).await?;
CommunityModerator::join(conn, &form)
})
.await??;
// write mod log // write mod log
let actor = self let actor = self
.actor .actor
.dereference(context, local_instance(context), request_counter) .dereference(context, local_instance(context).await, request_counter)
.await?; .await?;
let form = ModAddCommunityForm { let form = ModAddCommunityForm {
mod_person_id: actor.id, mod_person_id: actor.id,
@ -139,10 +133,7 @@ impl ActivityHandler for AddMod {
community_id: community.id, community_id: community.id,
removed: Some(false), removed: Some(false),
}; };
blocking(context.pool(), move |conn| { ModAddCommunity::create(context.pool(), &form).await?;
ModAddCommunity::create(conn, &form)
})
.await??;
} }
// TODO: send websocket notification about added mod // TODO: send websocket notification about added mod
Ok(()) Ok(())

View file

@ -46,6 +46,6 @@ async fn get_community_from_moderators_url(
) -> Result<ApubCommunity, LemmyError> { ) -> Result<ApubCommunity, LemmyError> {
let community_id = Url::parse(&moderators.to_string().replace("/moderators", ""))?; let community_id = Url::parse(&moderators.to_string().replace("/moderators", ""))?;
ObjectId::new(community_id) ObjectId::new(community_id)
.dereference(context, local_instance(context), request_counter) .dereference(context, local_instance(context).await, request_counter)
.await .await
} }

View file

@ -24,7 +24,6 @@ use activitypub_federation::{
traits::{ActivityHandler, Actor}, traits::{ActivityHandler, Actor},
}; };
use activitystreams_kinds::{activity::RemoveType, public}; use activitystreams_kinds::{activity::RemoveType, public};
use lemmy_api_common::utils::blocking;
use lemmy_db_schema::{ use lemmy_db_schema::{
source::{ source::{
community::{CommunityModerator, CommunityModeratorForm}, community::{CommunityModerator, CommunityModeratorForm},
@ -108,22 +107,19 @@ impl ActivityHandler for RemoveMod {
let community = self.get_community(context, request_counter).await?; let community = self.get_community(context, request_counter).await?;
let remove_mod = self let remove_mod = self
.object .object
.dereference(context, local_instance(context), request_counter) .dereference(context, local_instance(context).await, request_counter)
.await?; .await?;
let form = CommunityModeratorForm { let form = CommunityModeratorForm {
community_id: community.id, community_id: community.id,
person_id: remove_mod.id, person_id: remove_mod.id,
}; };
blocking(context.pool(), move |conn| { CommunityModerator::leave(context.pool(), &form).await?;
CommunityModerator::leave(conn, &form)
})
.await??;
// write mod log // write mod log
let actor = self let actor = self
.actor .actor
.dereference(context, local_instance(context), request_counter) .dereference(context, local_instance(context).await, request_counter)
.await?; .await?;
let form = ModAddCommunityForm { let form = ModAddCommunityForm {
mod_person_id: actor.id, mod_person_id: actor.id,
@ -131,10 +127,7 @@ impl ActivityHandler for RemoveMod {
community_id: community.id, community_id: community.id,
removed: Some(true), removed: Some(true),
}; };
blocking(context.pool(), move |conn| { ModAddCommunity::create(context.pool(), &form).await?;
ModAddCommunity::create(conn, &form)
})
.await??;
// TODO: send websocket notification about removed mod // TODO: send websocket notification about removed mod
Ok(()) Ok(())

View file

@ -12,7 +12,7 @@ use activitypub_federation::{
traits::{ActivityHandler, Actor}, traits::{ActivityHandler, Actor},
}; };
use activitystreams_kinds::activity::FlagType; use activitystreams_kinds::activity::FlagType;
use lemmy_api_common::{comment::CommentReportResponse, post::PostReportResponse, utils::blocking}; use lemmy_api_common::{comment::CommentReportResponse, post::PostReportResponse};
use lemmy_db_schema::{ use lemmy_db_schema::{
source::{ source::{
comment_report::{CommentReport, CommentReportForm}, comment_report::{CommentReport, CommentReportForm},
@ -75,7 +75,7 @@ impl ActivityHandler for Report {
request_counter: &mut i32, request_counter: &mut i32,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let community = self.to[0] let community = self.to[0]
.dereference(context, local_instance(context), request_counter) .dereference(context, local_instance(context).await, request_counter)
.await?; .await?;
verify_person_in_community(&self.actor, &community, context, request_counter).await?; verify_person_in_community(&self.actor, &community, context, request_counter).await?;
Ok(()) Ok(())
@ -89,11 +89,11 @@ impl ActivityHandler for Report {
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let actor = self let actor = self
.actor .actor
.dereference(context, local_instance(context), request_counter) .dereference(context, local_instance(context).await, request_counter)
.await?; .await?;
match self match self
.object .object
.dereference(context, local_instance(context), request_counter) .dereference(context, local_instance(context).await, request_counter)
.await? .await?
{ {
PostOrComment::Post(post) => { PostOrComment::Post(post) => {
@ -106,15 +106,9 @@ impl ActivityHandler for Report {
original_post_body: post.body.clone(), original_post_body: post.body.clone(),
}; };
let report = blocking(context.pool(), move |conn| { let report = PostReport::report(context.pool(), &report_form).await?;
PostReport::report(conn, &report_form)
})
.await??;
let post_report_view = blocking(context.pool(), move |conn| { let post_report_view = PostReportView::read(context.pool(), report.id, actor.id).await?;
PostReportView::read(conn, report.id, actor.id)
})
.await??;
context.chat_server().do_send(SendModRoomMessage { context.chat_server().do_send(SendModRoomMessage {
op: UserOperation::CreateCommentReport, op: UserOperation::CreateCommentReport,
@ -131,15 +125,10 @@ impl ActivityHandler for Report {
reason: self.summary, reason: self.summary,
}; };
let report = blocking(context.pool(), move |conn| { let report = CommentReport::report(context.pool(), &report_form).await?;
CommentReport::report(conn, &report_form)
})
.await??;
let comment_report_view = blocking(context.pool(), move |conn| { let comment_report_view =
CommentReportView::read(conn, report.id, actor.id) CommentReportView::read(context.pool(), report.id, actor.id).await?;
})
.await??;
let community_id = comment_report_view.community.id; let community_id = comment_report_view.community.id;
context.chat_server().do_send(SendModRoomMessage { context.chat_server().do_send(SendModRoomMessage {

View file

@ -18,7 +18,6 @@ use activitypub_federation::{
traits::{ActivityHandler, ApubObject}, traits::{ActivityHandler, ApubObject},
}; };
use activitystreams_kinds::{activity::UpdateType, public}; use activitystreams_kinds::{activity::UpdateType, public};
use lemmy_api_common::utils::blocking;
use lemmy_db_schema::{source::community::Community, traits::Crud}; use lemmy_db_schema::{source::community::Community, traits::Crud};
use lemmy_utils::error::LemmyError; use lemmy_utils::error::LemmyError;
use lemmy_websocket::{send::send_community_ws_message, LemmyContext, UserOperationCrud}; use lemmy_websocket::{send::send_community_ws_message, LemmyContext, UserOperationCrud};
@ -100,10 +99,8 @@ impl ActivityHandler for UpdateCommunity {
let community_update_form = self.object.into_update_form(); let community_update_form = self.object.into_update_form();
let updated_community = blocking(context.pool(), move |conn| { let updated_community =
Community::update(conn, community.id, &community_update_form) Community::update(context.pool(), community.id, &community_update_form).await?;
})
.await??;
send_community_ws_message( send_community_ws_message(
updated_community.id, updated_community.id,
@ -127,7 +124,7 @@ impl GetCommunity for UpdateCommunity {
) -> Result<ApubCommunity, LemmyError> { ) -> Result<ApubCommunity, LemmyError> {
let cid = ObjectId::new(self.object.id.clone()); let cid = ObjectId::new(self.object.id.clone());
cid cid
.dereference(context, local_instance(context), request_counter) .dereference(context, local_instance(context).await, request_counter)
.await .await
} }
} }

Some files were not shown because too many files have changed in this diff Show more