Replacing r2d2 syncronous DB pool with async deadpool.

- Removes blocking, makes all connection grabs async.
- Fixes #1684
- Note: clippy::needless_borrow is currently broken.
This commit is contained in:
Dessalines 2021-08-20 15:21:56 -04:00
parent f6f169b4eb
commit 1ccae69a47
89 changed files with 896 additions and 1595 deletions

62
Cargo.lock generated
View file

@ -833,6 +833,29 @@ dependencies = [
"syn 1.0.74", "syn 1.0.74",
] ]
[[package]]
name = "deadpool"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef82259c587bceda08349f28ff00f69ae4c897898f254140af6021eb218e8232"
dependencies = [
"async-trait",
"num_cpus",
"tokio",
]
[[package]]
name = "deadpool-diesel"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc59b1d25a4c207b321398ab9c3e3651a6e726731ca8b0a4f07e1d4b22f44a40"
dependencies = [
"async-trait",
"deadpool",
"diesel",
"tokio",
]
[[package]] [[package]]
name = "deflate" name = "deflate"
version = "0.8.6" version = "0.8.6"
@ -901,7 +924,6 @@ dependencies = [
"chrono", "chrono",
"diesel_derives", "diesel_derives",
"pq-sys", "pq-sys",
"r2d2",
"serde_json", "serde_json",
] ]
@ -1403,9 +1425,9 @@ dependencies = [
[[package]] [[package]]
name = "httparse" name = "httparse"
version = "1.4.1" version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3a87b616e37e93c22fb19bcd386f02f3af5ea98a25670ad0fce773de23c5e68" checksum = "acd94fdbe1d4ff688b67b04eee2e17bd50995534a61539e45adfefb45e5e5503"
[[package]] [[package]]
name = "httpdate" name = "httpdate"
@ -1543,9 +1565,9 @@ dependencies = [
[[package]] [[package]]
name = "js-sys" name = "js-sys"
version = "0.3.52" version = "0.3.53"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce791b7ca6638aae45be056e068fc756d871eb3b3b10b8efa62d1c9cec616752" checksum = "e4bf49d50e2961077d9c99f4b7997d770a1114f087c3c2e0069b36c13fc2979d"
dependencies = [ dependencies = [
"wasm-bindgen", "wasm-bindgen",
] ]
@ -1761,6 +1783,7 @@ version = "0.11.3"
dependencies = [ dependencies = [
"bcrypt", "bcrypt",
"chrono", "chrono",
"deadpool-diesel",
"diesel", "diesel",
"diesel_migrations", "diesel_migrations",
"lazy_static", "lazy_static",
@ -1862,6 +1885,7 @@ dependencies = [
"cargo-husky", "cargo-husky",
"chrono", "chrono",
"clokwerk", "clokwerk",
"deadpool-diesel",
"diesel", "diesel",
"diesel_migrations", "diesel_migrations",
"env_logger", "env_logger",
@ -3798,9 +3822,9 @@ checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f"
[[package]] [[package]]
name = "wasm-bindgen" name = "wasm-bindgen"
version = "0.2.75" version = "0.2.76"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b608ecc8f4198fe8680e2ed18eccab5f0cd4caaf3d83516fa5fb2e927fda2586" checksum = "8ce9b1b516211d33767048e5d47fa2a381ed8b76fc48d2ce4aa39877f9f183e0"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"serde", "serde",
@ -3810,9 +3834,9 @@ dependencies = [
[[package]] [[package]]
name = "wasm-bindgen-backend" name = "wasm-bindgen-backend"
version = "0.2.75" version = "0.2.76"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "580aa3a91a63d23aac5b6b267e2d13cb4f363e31dce6c352fca4752ae12e479f" checksum = "cfe8dc78e2326ba5f845f4b5bf548401604fa20b1dd1d365fb73b6c1d6364041"
dependencies = [ dependencies = [
"bumpalo", "bumpalo",
"lazy_static", "lazy_static",
@ -3825,9 +3849,9 @@ dependencies = [
[[package]] [[package]]
name = "wasm-bindgen-futures" name = "wasm-bindgen-futures"
version = "0.4.25" version = "0.4.26"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "16646b21c3add8e13fdb8f20172f8a28c3dbf62f45406bcff0233188226cfe0c" checksum = "95fded345a6559c2cfee778d562300c581f7d4ff3edb9b0d230d69800d213972"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"js-sys", "js-sys",
@ -3837,9 +3861,9 @@ dependencies = [
[[package]] [[package]]
name = "wasm-bindgen-macro" name = "wasm-bindgen-macro"
version = "0.2.75" version = "0.2.76"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "171ebf0ed9e1458810dfcb31f2e766ad6b3a89dbda42d8901f2b268277e5f09c" checksum = "44468aa53335841d9d6b6c023eaab07c0cd4bddbcfdee3e2bb1e8d2cb8069fef"
dependencies = [ dependencies = [
"quote 1.0.9", "quote 1.0.9",
"wasm-bindgen-macro-support", "wasm-bindgen-macro-support",
@ -3847,9 +3871,9 @@ dependencies = [
[[package]] [[package]]
name = "wasm-bindgen-macro-support" name = "wasm-bindgen-macro-support"
version = "0.2.75" version = "0.2.76"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c2657dd393f03aa2a659c25c6ae18a13a4048cebd220e147933ea837efc589f" checksum = "0195807922713af1e67dc66132c7328206ed9766af3858164fb583eedc25fbad"
dependencies = [ dependencies = [
"proc-macro2 1.0.28", "proc-macro2 1.0.28",
"quote 1.0.9", "quote 1.0.9",
@ -3860,15 +3884,15 @@ dependencies = [
[[package]] [[package]]
name = "wasm-bindgen-shared" name = "wasm-bindgen-shared"
version = "0.2.75" version = "0.2.76"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e0c4a743a309662d45f4ede961d7afa4ba4131a59a639f29b0069c3798bbcc2" checksum = "acdb075a845574a1fa5f09fd77e43f7747599301ea3417a9fbffdeedfc1f4a29"
[[package]] [[package]]
name = "web-sys" name = "web-sys"
version = "0.3.52" version = "0.3.53"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "01c70a82d842c9979078c772d4a1344685045f1a5628f677c2b2eab4dd7d2696" checksum = "224b2f6b67919060055ef1a67807367c2066ed520c3862cc013d26cf893a783c"
dependencies = [ dependencies = [
"js-sys", "js-sys",
"wasm-bindgen", "wasm-bindgen",

View file

@ -63,6 +63,7 @@ activitystreams = "0.7.0-alpha.11"
actix-rt = { version = "2.2.0", default-features = false } actix-rt = { version = "2.2.0", default-features = false }
serde_json = { version = "1.0.66", features = ["preserve_order"] } serde_json = { version = "1.0.66", features = ["preserve_order"] }
clokwerk = "0.3.5" clokwerk = "0.3.5"
deadpool-diesel = { version = "0.1.2", features = ["postgres"] }
[dev-dependencies.cargo-husky] [dev-dependencies.cargo-husky]
version = "1.5.0" version = "1.5.0"

View file

@ -1,7 +1,6 @@
use crate::Perform; use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
check_community_ban, check_community_ban,
check_downvotes_enabled, check_downvotes_enabled,
check_person_block, check_person_block,
@ -35,10 +34,7 @@ impl Perform for MarkCommentAsRead {
let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; let local_user_view = get_local_user_view_from_jwt(&data.auth, 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.get().await?, comment_id, None)?;
CommentView::read(conn, comment_id, None)
})
.await??;
check_community_ban( check_community_ban(
local_user_view.person.id, local_user_view.person.id,
@ -54,19 +50,13 @@ impl Perform for MarkCommentAsRead {
// Do the mark as read // Do the mark as read
let read = data.read; let read = data.read;
blocking(context.pool(), move |conn| { Comment::update_read(&&context.pool.get().await?, comment_id, read)
Comment::update_read(conn, comment_id, read) .map_err(|_| ApiError::err("couldnt_update_comment"))?;
})
.await?
.map_err(|_| ApiError::err("couldnt_update_comment"))?;
// Refetch it // Refetch it
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.get().await?, comment_id, Some(person_id))?;
CommentView::read(conn, comment_id, Some(person_id))
})
.await??;
let res = CommentResponse { let res = CommentResponse {
comment_view, comment_view,
@ -96,23 +86,20 @@ impl Perform for SaveComment {
}; };
if data.save { if data.save {
let save_comment = move |conn: &'_ _| CommentSaved::save(conn, &comment_saved_form); let save_comment = CommentSaved::save(&&context.pool.get().await?, &comment_saved_form);
if blocking(context.pool(), save_comment).await?.is_err() { if save_comment.is_err() {
return Err(ApiError::err("couldnt_save_comment").into()); return Err(ApiError::err("couldnt_save_comment").into());
} }
} else { } else {
let unsave_comment = move |conn: &'_ _| CommentSaved::unsave(conn, &comment_saved_form); let unsave_comment = CommentSaved::unsave(&&context.pool.get().await?, &comment_saved_form);
if blocking(context.pool(), unsave_comment).await?.is_err() { if unsave_comment.is_err() {
return Err(ApiError::err("couldnt_save_comment").into()); return Err(ApiError::err("couldnt_save_comment").into());
} }
} }
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.get().await?, comment_id, Some(person_id))?;
CommentView::read(conn, comment_id, Some(person_id))
})
.await??;
Ok(CommentResponse { Ok(CommentResponse {
comment_view, comment_view,
@ -140,10 +127,7 @@ impl Perform for CreateCommentLike {
check_downvotes_enabled(data.score, context.pool()).await?; check_downvotes_enabled(data.score, 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.get().await?, comment_id, None)?;
CommentView::read(conn, comment_id, None)
})
.await??;
check_community_ban( check_community_ban(
local_user_view.person.id, local_user_view.person.id,
@ -161,10 +145,8 @@ impl Perform for CreateCommentLike {
// Add parent user to recipients // Add parent user to recipients
let recipient_id = orig_comment.get_recipient_id(); let recipient_id = orig_comment.get_recipient_id();
if let Ok(local_recipient) = blocking(context.pool(), move |conn| { if let Ok(local_recipient) =
LocalUserView::read_person(conn, recipient_id) LocalUserView::read_person(&&context.pool.get().await?, recipient_id)
})
.await?
{ {
recipient_ids.push(local_recipient.local_user.id); recipient_ids.push(local_recipient.local_user.id);
} }
@ -178,10 +160,7 @@ 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(&&context.pool.get().await?, person_id, comment_id)?;
CommentLike::remove(conn, person_id, comment_id)
})
.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;
@ -189,8 +168,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: &'_ _| CommentLike::like(conn, &like_form2); let like = CommentLike::like(&&context.pool.get().await?, &like_form2);
if blocking(context.pool(), like).await?.is_err() { if like.is_err() {
return Err(ApiError::err("couldnt_like_comment").into()); return Err(ApiError::err("couldnt_like_comment").into());
} }

View file

@ -1,7 +1,6 @@
use crate::Perform; use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
check_community_ban, check_community_ban,
collect_moderated_communities, collect_moderated_communities,
comment::*, comment::*,
@ -45,10 +44,7 @@ impl Perform for CreateCommentReport {
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.get().await?, comment_id, None)?;
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?;
@ -59,11 +55,8 @@ impl Perform for CreateCommentReport {
reason: data.reason.to_owned(), reason: data.reason.to_owned(),
}; };
let report = blocking(context.pool(), move |conn| { let report = CommentReport::report(&&context.pool.get().await?, &report_form)
CommentReport::report(conn, &report_form) .map_err(|_| ApiError::err("couldnt_create_report"))?;
})
.await?
.map_err(|_| ApiError::err("couldnt_create_report"))?;
let res = CreateCommentReportResponse { success: true }; let res = CreateCommentReportResponse { success: true };
@ -99,24 +92,19 @@ impl Perform for ResolveCommentReport {
let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
let report_id = data.report_id; let report_id = data.report_id;
let report = blocking(context.pool(), move |conn| { let report = CommentReportView::read(&&context.pool.get().await?, report_id)?;
CommentReportView::read(conn, report_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; let resolved = data.resolved;
let resolve_fun = move |conn: &'_ _| { let resolve_fun = if resolved {
if resolved { CommentReport::resolve(&&context.pool.get().await?, report_id, person_id)
CommentReport::resolve(conn, report_id, person_id) } else {
} else { CommentReport::unresolve(&&context.pool.get().await?, report_id, person_id)
CommentReport::unresolve(conn, report_id, person_id)
}
}; };
if blocking(context.pool(), resolve_fun).await?.is_err() { if resolve_fun.is_err() {
return Err(ApiError::err("couldnt_resolve_report").into()); return Err(ApiError::err("couldnt_resolve_report").into());
}; };
@ -158,14 +146,11 @@ impl Perform for ListCommentReports {
let page = data.page; let page = data.page;
let limit = data.limit; let limit = data.limit;
let comments = blocking(context.pool(), move |conn| { let comments = CommentReportQueryBuilder::create(&&context.pool.get().await?)
CommentReportQueryBuilder::create(conn) .community_ids(community_ids)
.community_ids(community_ids) .page(page)
.page(page) .limit(limit)
.limit(limit) .list()?;
.list()
})
.await??;
let res = ListCommentReportsResponse { comments }; let res = ListCommentReportsResponse { comments };

View file

@ -2,7 +2,6 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use anyhow::Context; use anyhow::Context;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
check_community_ban, check_community_ban,
community::*, community::*,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
@ -56,10 +55,7 @@ impl Perform for FollowCommunity {
let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; let local_user_view = get_local_user_view_from_jwt(&data.auth, 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.get().await?, community_id)?;
Community::read(conn, community_id)
})
.await??;
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,
@ -70,14 +66,15 @@ impl Perform for FollowCommunity {
if data.follow { if data.follow {
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?;
let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form); let follow =
if blocking(context.pool(), follow).await?.is_err() { CommunityFollower::follow(&&context.pool.get().await?, &community_follower_form);
if follow.is_err() {
return Err(ApiError::err("community_follower_already_exists").into()); return Err(ApiError::err("community_follower_already_exists").into());
} }
} else { } else {
let unfollow = let unfollow =
move |conn: &'_ _| CommunityFollower::unfollow(conn, &community_follower_form); CommunityFollower::unfollow(&&context.pool.get().await?, &community_follower_form);
if blocking(context.pool(), unfollow).await?.is_err() { if unfollow.is_err() {
return Err(ApiError::err("community_follower_already_exists").into()); return Err(ApiError::err("community_follower_already_exists").into());
} }
} }
@ -87,18 +84,17 @@ impl Perform for FollowCommunity {
FollowCommunityApub::send(&local_user_view.person, &community, context).await?; FollowCommunityApub::send(&local_user_view.person, &community, context).await?;
} else { } else {
UndoFollowCommunity::send(&local_user_view.person, &community, context).await?; UndoFollowCommunity::send(&local_user_view.person, &community, context).await?;
let unfollow = move |conn: &'_ _| CommunityFollower::unfollow(conn, &community_follower_form); let unfollow =
if blocking(context.pool(), unfollow).await?.is_err() { CommunityFollower::unfollow(&&context.pool.get().await?, &community_follower_form);
if unfollow.is_err() {
return Err(ApiError::err("community_follower_already_exists").into()); return Err(ApiError::err("community_follower_already_exists").into());
} }
} }
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 mut community_view = blocking(context.pool(), move |conn| { let mut community_view =
CommunityView::read(conn, community_id, Some(person_id)) CommunityView::read(&&context.pool.get().await?, community_id, Some(person_id))?;
})
.await??;
// TODO: this needs to return a "pending" state, until Accept is received from the remote server // TODO: this needs to return a "pending" state, until Accept is received from the remote server
// For now, just assume that remote follows are accepted. // For now, just assume that remote follows are accepted.
@ -131,8 +127,8 @@ impl Perform for BlockCommunity {
}; };
if data.block { if data.block {
let block = move |conn: &'_ _| CommunityBlock::block(conn, &community_block_form); let block = CommunityBlock::block(&&context.pool.get().await?, &community_block_form);
if blocking(context.pool(), block).await?.is_err() { if block.is_err() {
return Err(ApiError::err("community_block_already_exists").into()); return Err(ApiError::err("community_block_already_exists").into());
} }
@ -142,27 +138,18 @@ impl Perform for BlockCommunity {
person_id, person_id,
pending: false, pending: false,
}; };
blocking(context.pool(), move |conn: &'_ _| { CommunityFollower::unfollow(&&context.pool.get().await?, &community_follower_form).ok();
CommunityFollower::unfollow(conn, &community_follower_form) let community = Community::read(&&context.pool.get().await?, community_id)?;
})
.await?
.ok();
let community = blocking(context.pool(), move |conn| {
Community::read(conn, community_id)
})
.await??;
UndoFollowCommunity::send(&local_user_view.person, &community, context).await?; UndoFollowCommunity::send(&local_user_view.person, &community, context).await?;
} else { } else {
let unblock = move |conn: &'_ _| CommunityBlock::unblock(conn, &community_block_form); let unblock = CommunityBlock::unblock(&&context.pool.get().await?, &community_block_form);
if blocking(context.pool(), unblock).await?.is_err() { if unblock.is_err() {
return Err(ApiError::err("community_block_already_exists").into()); return Err(ApiError::err("community_block_already_exists").into());
} }
} }
let community_view = blocking(context.pool(), move |conn| { let community_view =
CommunityView::read(conn, community_id, Some(person_id)) CommunityView::read(&&context.pool.get().await?, community_id, Some(person_id))?;
})
.await??;
Ok(BlockCommunityResponse { Ok(BlockCommunityResponse {
blocked: data.block, blocked: data.block,
@ -194,18 +181,12 @@ impl Perform for BanFromCommunity {
person_id: data.person_id, person_id: data.person_id,
}; };
let community = blocking(context.pool(), move |conn: &'_ _| { let community = Community::read(&&context.pool.get().await?, community_id)?;
Community::read(conn, community_id) let banned_person = Person::read(&&context.pool.get().await?, banned_person_id)?;
})
.await??;
let banned_person = blocking(context.pool(), move |conn: &'_ _| {
Person::read(conn, banned_person_id)
})
.await??;
if data.ban { if data.ban {
let ban = move |conn: &'_ _| CommunityPersonBan::ban(conn, &community_user_ban_form); let ban = CommunityPersonBan::ban(&&context.pool.get().await?, &community_user_ban_form);
if blocking(context.pool(), ban).await?.is_err() { if ban.is_err() {
return Err(ApiError::err("community_user_already_banned").into()); return Err(ApiError::err("community_user_already_banned").into());
} }
@ -215,17 +196,13 @@ impl Perform for BanFromCommunity {
person_id: banned_person_id, person_id: banned_person_id,
pending: false, pending: false,
}; };
blocking(context.pool(), move |conn: &'_ _| { CommunityFollower::unfollow(&&context.pool.get().await?, &community_follower_form).ok();
CommunityFollower::unfollow(conn, &community_follower_form)
})
.await?
.ok();
BlockUserFromCommunity::send(&community, &banned_person, &local_user_view.person, context) BlockUserFromCommunity::send(&community, &banned_person, &local_user_view.person, context)
.await?; .await?;
} else { } else {
let unban = move |conn: &'_ _| CommunityPersonBan::unban(conn, &community_user_ban_form); let unban = CommunityPersonBan::unban(&&context.pool.get().await?, &community_user_ban_form);
if blocking(context.pool(), unban).await?.is_err() { if unban.is_err() {
return Err(ApiError::err("community_user_already_banned").into()); return Err(ApiError::err("community_user_already_banned").into());
} }
UndoBlockUserFromCommunity::send( UndoBlockUserFromCommunity::send(
@ -240,28 +217,24 @@ impl Perform for BanFromCommunity {
// Remove/Restore their data if that's desired // Remove/Restore their data if that's desired
if data.remove_data.unwrap_or(false) { if data.remove_data.unwrap_or(false) {
// Posts // Posts
blocking(context.pool(), move |conn: &'_ _| { Post::update_removed_for_creator(
Post::update_removed_for_creator(conn, banned_person_id, Some(community_id), true) &&context.pool.get().await?,
}) banned_person_id,
.await??; Some(community_id),
true,
)?;
// 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(context.pool(), move |conn| { let comments = CommentQueryBuilder::create(&&context.pool.get().await?)
CommentQueryBuilder::create(conn) .creator_id(banned_person_id)
.creator_id(banned_person_id) .community_id(community_id)
.community_id(community_id) .limit(std::i64::MAX)
.limit(std::i64::MAX) .list()?;
.list()
})
.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(context.pool(), move |conn: &'_ _| { Comment::update_removed(&&context.pool.get().await?, comment_id, true)?;
Comment::update_removed(conn, comment_id, true)
})
.await??;
} }
} }
@ -277,16 +250,10 @@ impl Perform for BanFromCommunity {
banned: Some(data.ban), banned: Some(data.ban),
expires, expires,
}; };
blocking(context.pool(), move |conn| { ModBanFromCommunity::create(&&context.pool.get().await?, &form)?;
ModBanFromCommunity::create(conn, &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.get().await?, person_id)?;
PersonViewSafe::read(conn, person_id)
})
.await??;
let res = BanFromCommunityResponse { let res = BanFromCommunityResponse {
person_view, person_view,
@ -327,13 +294,13 @@ impl Perform for AddModToCommunity {
person_id: data.person_id, person_id: data.person_id,
}; };
if data.added { if data.added {
let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form); let join = CommunityModerator::join(&&context.pool.get().await?, &community_moderator_form);
if blocking(context.pool(), join).await?.is_err() { if join.is_err() {
return Err(ApiError::err("community_moderator_already_exists").into()); return Err(ApiError::err("community_moderator_already_exists").into());
} }
} else { } else {
let leave = move |conn: &'_ _| CommunityModerator::leave(conn, &community_moderator_form); let leave = CommunityModerator::leave(&&context.pool.get().await?, &community_moderator_form);
if blocking(context.pool(), leave).await?.is_err() { if leave.is_err() {
return Err(ApiError::err("community_moderator_already_exists").into()); return Err(ApiError::err("community_moderator_already_exists").into());
} }
} }
@ -345,21 +312,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(&&context.pool.get().await?, &form)?;
ModAddCommunity::create(conn, &form)
})
.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 = blocking(context.pool(), move |conn| { let updated_mod = Person::read(&&context.pool.get().await?, updated_mod_id)?;
Person::read(conn, updated_mod_id) let community = Community::read(&&context.pool.get().await?, community_id)?;
})
.await??;
let community = blocking(context.pool(), move |conn| {
Community::read(conn, community_id)
})
.await??;
if data.added { if data.added {
AddMod::send(&community, &updated_mod, &local_user_view.person, context).await?; AddMod::send(&community, &updated_mod, &local_user_view.person, context).await?;
} else { } else {
@ -369,10 +327,8 @@ 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(conn, community_id) CommunityModeratorView::for_community(&&context.pool.get().await?, community_id)?;
})
.await??;
let res = AddModToCommunityResponse { moderators }; let res = AddModToCommunityResponse { moderators };
context.chat_server().do_send(SendCommunityRoomMessage { context.chat_server().do_send(SendCommunityRoomMessage {
@ -399,12 +355,9 @@ impl Perform for TransferCommunity {
let data: &TransferCommunity = self; let data: &TransferCommunity = self;
let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
let site_creator_id = blocking(context.pool(), move |conn| { let site_creator_id = Site::read(&&context.pool.get().await?, 1).map(|s| s.creator_id)?;
Site::read(conn, 1).map(|s| s.creator_id)
})
.await??;
let mut admins = blocking(context.pool(), move |conn| PersonViewSafe::admins(conn)).await??; let mut admins = PersonViewSafe::admins(&&context.pool.get().await?)?;
// Making sure the site creator, if an admin, is at the top // Making sure the site creator, if an admin, is at the top
let creator_index = admins let creator_index = admins
@ -416,10 +369,8 @@ impl Perform for TransferCommunity {
// 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.get().await?, community_id)?;
})
.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
@ -442,10 +393,7 @@ 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(&&context.pool.get().await?, community_id)?;
CommunityModerator::delete_for_community(conn, community_id)
})
.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
@ -455,8 +403,8 @@ impl Perform for TransferCommunity {
person_id: cmod.moderator.id, person_id: cmod.moderator.id,
}; };
let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form); let join = CommunityModerator::join(&&context.pool.get().await?, &community_moderator_form);
if blocking(context.pool(), join).await?.is_err() { if join.is_err() {
return Err(ApiError::err("community_moderator_already_exists").into()); return Err(ApiError::err("community_moderator_already_exists").into());
} }
} }
@ -468,25 +416,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(&&context.pool.get().await?, &form)?;
ModTransferCommunity::create(conn, &form)
})
.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(conn, community_id, Some(person_id)) CommunityView::read(&&context.pool.get().await?, community_id, Some(person_id))
}) .map_err(|_| ApiError::err("couldnt_find_community"))?;
.await?
.map_err(|_| ApiError::err("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(conn, community_id) CommunityModeratorView::for_community(&&context.pool.get().await?, community_id)
}) .map_err(|_| ApiError::err("couldnt_find_community"))?;
.await?
.map_err(|_| ApiError::err("couldnt_find_community"))?;
// Return the jwt // Return the jwt
Ok(GetCommunityResponse { Ok(GetCommunityResponse {

View file

@ -1,3 +1,8 @@
// Clippy needless_borrow linting is broken currently. Example:
// PersonViewSafe::read(&&context.pool.get().await?, person_details_id)?;
// change this to: `&&context.pool.get().await?`
#![allow(clippy::needless_borrow)]
use actix_web::{web, web::Data}; use actix_web::{web, web::Data};
use captcha::Captcha; use captcha::Captcha;
use lemmy_api_common::{comment::*, community::*, person::*, post::*, site::*, websocket::*}; use lemmy_api_common::{comment::*, community::*, person::*, post::*, site::*, websocket::*};

View file

@ -5,7 +5,6 @@ use bcrypt::verify;
use captcha::{gen, Difficulty}; use captcha::{gen, Difficulty};
use chrono::Duration; use chrono::Duration;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
collect_moderated_communities, collect_moderated_communities,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
is_admin, is_admin,
@ -86,11 +85,9 @@ impl Perform for Login {
// 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(conn, &username_or_email) LocalUserView::find_by_email_or_name(&&context.pool.get().await?, &username_or_email)
}) .map_err(|_| ApiError::err("couldnt_find_that_username_or_email"))?;
.await?
.map_err(|_| ApiError::err("couldnt_find_that_username_or_email"))?;
// Verify the password // Verify the password
let valid: bool = verify( let valid: bool = verify(
@ -220,16 +217,8 @@ impl Perform for SaveUserSettings {
bot_account, bot_account,
}; };
let person_res = blocking(context.pool(), move |conn| { Person::update(&&context.pool.get().await?, person_id, &person_form)
Person::update(conn, person_id, &person_form) .map_err(|_| ApiError::err("user_already_exists"))?;
})
.await?;
let _updated_person: Person = match person_res {
Ok(p) => p,
Err(_) => {
return Err(ApiError::err("user_already_exists").into());
}
};
let local_user_form = LocalUserForm { let local_user_form = LocalUserForm {
person_id, person_id,
@ -248,24 +237,20 @@ impl Perform for SaveUserSettings {
send_notifications_to_email: data.send_notifications_to_email, send_notifications_to_email: data.send_notifications_to_email,
}; };
let local_user_res = blocking(context.pool(), move |conn| { let updated_local_user =
LocalUser::update(conn, local_user_id, &local_user_form) LocalUser::update(&&context.pool.get().await?, local_user_id, &local_user_form).map_err(
}) |e| {
.await?; let err_type = if e.to_string()
let updated_local_user = match local_user_res { == "duplicate key value violates unique constraint \"local_user_email_key\""
Ok(u) => u, {
Err(e) => { "email_already_exists"
let err_type = if e.to_string() } else {
== "duplicate key value violates unique constraint \"local_user_email_key\"" "user_already_exists"
{ };
"email_already_exists"
} else {
"user_already_exists"
};
return Err(ApiError::err(err_type).into()); ApiError::err(err_type)
} },
}; )?;
// Return the jwt // Return the jwt
Ok(LoginResponse { Ok(LoginResponse {
@ -305,10 +290,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.get().await?, local_user_id, &new_password)?;
})
.await??;
// Return the jwt // Return the jwt
Ok(LoginResponse { Ok(LoginResponse {
@ -334,16 +317,8 @@ 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 = match blocking(context.pool(), move |conn| { let added_admin = Person::add_admin(&&context.pool.get().await?, added_person_id, added)
Person::add_admin(conn, added_person_id, added) .map_err(|_| ApiError::err("couldnt_update_user"))?;
})
.await?
{
Ok(a) => a,
Err(_) => {
return Err(ApiError::err("couldnt_update_user").into());
}
};
// Mod tables // Mod tables
let form = ModAddForm { let form = ModAddForm {
@ -352,14 +327,11 @@ 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.get().await?, &form)?;
let site_creator_id = blocking(context.pool(), move |conn| { let site_creator_id = Site::read(&&context.pool.get().await?, 1).map(|s| s.creator_id)?;
Site::read(conn, 1).map(|s| s.creator_id)
})
.await??;
let mut admins = blocking(context.pool(), move |conn| PersonViewSafe::admins(conn)).await??; let mut admins = PersonViewSafe::admins(&&context.pool.get().await?)?;
let creator_index = admins let creator_index = admins
.iter() .iter()
.position(|r| r.person.id == site_creator_id) .position(|r| r.person.id == site_creator_id)
@ -396,26 +368,21 @@ impl Perform for BanPerson {
let ban = data.ban; let ban = data.ban;
let banned_person_id = data.person_id; let banned_person_id = data.person_id;
let ban_person = move |conn: &'_ _| Person::ban_person(conn, banned_person_id, ban); let ban_person = Person::ban_person(&&context.pool.get().await?, banned_person_id, ban);
if blocking(context.pool(), ban_person).await?.is_err() { if ban_person.is_err() {
return Err(ApiError::err("couldnt_update_user").into()); return Err(ApiError::err("couldnt_update_user").into());
} }
// Remove their data if that's desired // Remove their data if that's desired
if data.remove_data.unwrap_or(false) { if data.remove_data.unwrap_or(false) {
// Posts // Posts
blocking(context.pool(), move |conn: &'_ _| { Post::update_removed_for_creator(&&context.pool.get().await?, banned_person_id, None, true)?;
Post::update_removed_for_creator(conn, banned_person_id, None, true)
})
.await??;
// 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(context.pool(), move |conn: &'_ _| { let first_mod_communities =
CommunityModeratorView::get_community_first_mods(conn) CommunityModeratorView::get_community_first_mods(&&context.pool.get().await?)?;
})
.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
@ -424,17 +391,15 @@ impl Perform for BanPerson {
.collect(); .collect();
for first_mod_community in banned_user_first_communities { for first_mod_community in banned_user_first_communities {
blocking(context.pool(), move |conn: &'_ _| { Community::update_removed(
Community::update_removed(conn, first_mod_community.community.id, true) &&context.pool.get().await?,
}) first_mod_community.community.id,
.await??; true,
)?;
} }
// Comments // Comments
blocking(context.pool(), move |conn: &'_ _| { Comment::update_removed_for_creator(&&context.pool.get().await?, banned_person_id, true)?;
Comment::update_removed_for_creator(conn, banned_person_id, true)
})
.await??;
} }
// Mod tables // Mod tables
@ -448,13 +413,10 @@ impl Perform for BanPerson {
expires, expires,
}; };
blocking(context.pool(), move |conn| ModBan::create(conn, &form)).await??; ModBan::create(&&context.pool.get().await?, &form)?;
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.get().await?, person_id)?;
PersonViewSafe::read(conn, person_id)
})
.await??;
let res = BanPersonResponse { let res = BanPersonResponse {
person_view, person_view,
@ -497,23 +459,18 @@ impl Perform for BlockPerson {
}; };
if data.block { if data.block {
let block = move |conn: &'_ _| PersonBlock::block(conn, &person_block_form); let block = PersonBlock::block(&&context.pool.get().await?, &person_block_form);
if blocking(context.pool(), block).await?.is_err() { if block.is_err() {
return Err(ApiError::err("person_block_already_exists").into()); return Err(ApiError::err("person_block_already_exists").into());
} }
} else { } else {
let unblock = move |conn: &'_ _| PersonBlock::unblock(conn, &person_block_form); let unblock = PersonBlock::unblock(&&context.pool.get().await?, &person_block_form);
if blocking(context.pool(), unblock).await?.is_err() { if unblock.is_err() {
return Err(ApiError::err("person_block_already_exists").into()); return Err(ApiError::err("person_block_already_exists").into());
} }
} }
// TODO does any federated stuff need to be done here? let person_view = PersonViewSafe::read(&&context.pool.get().await?, target_id)?;
let person_view = blocking(context.pool(), move |conn| {
PersonViewSafe::read(conn, target_id)
})
.await??;
let res = BlockPersonResponse { let res = BlockPersonResponse {
person_view, person_view,
@ -544,18 +501,15 @@ impl Perform for GetReplies {
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let show_bot_accounts = local_user_view.local_user.show_bot_accounts; let show_bot_accounts = local_user_view.local_user.show_bot_accounts;
let replies = blocking(context.pool(), move |conn| { let replies = CommentQueryBuilder::create(&&context.pool.get().await?)
CommentQueryBuilder::create(conn) .sort(sort)
.sort(sort) .unread_only(unread_only)
.unread_only(unread_only) .recipient_id(person_id)
.recipient_id(person_id) .show_bot_accounts(show_bot_accounts)
.show_bot_accounts(show_bot_accounts) .my_person_id(person_id)
.my_person_id(person_id) .page(page)
.page(page) .limit(limit)
.limit(limit) .list()?;
.list()
})
.await??;
Ok(GetRepliesResponse { replies }) Ok(GetRepliesResponse { replies })
} }
@ -579,17 +533,14 @@ impl Perform for GetPersonMentions {
let limit = data.limit; let limit = data.limit;
let unread_only = data.unread_only; let unread_only = data.unread_only;
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let mentions = blocking(context.pool(), move |conn| { let mentions = PersonMentionQueryBuilder::create(&&context.pool.get().await?)
PersonMentionQueryBuilder::create(conn) .recipient_id(person_id)
.recipient_id(person_id) .my_person_id(person_id)
.my_person_id(person_id) .sort(sort)
.sort(sort) .unread_only(unread_only)
.unread_only(unread_only) .page(page)
.page(page) .limit(limit)
.limit(limit) .list()?;
.list()
})
.await??;
Ok(GetPersonMentionsResponse { mentions }) Ok(GetPersonMentionsResponse { mentions })
} }
@ -608,10 +559,7 @@ impl Perform for MarkPersonMentionAsRead {
let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).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.get().await?, person_mention_id)?;
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(ApiError::err("couldnt_update_comment").into()); return Err(ApiError::err("couldnt_update_comment").into());
@ -620,17 +568,18 @@ impl Perform for MarkPersonMentionAsRead {
let person_mention_id = read_person_mention.id; let person_mention_id = read_person_mention.id;
let read = data.read; let read = data.read;
let update_mention = let update_mention =
move |conn: &'_ _| PersonMention::update_read(conn, person_mention_id, read); PersonMention::update_read(&&context.pool.get().await?, person_mention_id, read);
if blocking(context.pool(), update_mention).await?.is_err() { if update_mention.is_err() {
return Err(ApiError::err("couldnt_update_comment").into()); return Err(ApiError::err("couldnt_update_comment").into());
}; };
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(
PersonMentionView::read(conn, person_mention_id, Some(person_id)) &&context.pool.get().await?,
}) person_mention_id,
.await??; Some(person_id),
)?;
Ok(PersonMentionResponse { Ok(PersonMentionResponse {
person_mention_view, person_mention_view,
@ -651,41 +600,35 @@ impl Perform for MarkAllAsRead {
let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
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 = CommentQueryBuilder::create(&&context.pool.get().await?)
CommentQueryBuilder::create(conn) .my_person_id(person_id)
.my_person_id(person_id) .recipient_id(person_id)
.recipient_id(person_id) .unread_only(true)
.unread_only(true) .page(1)
.page(1) .limit(999)
.limit(999) .list()?;
.list()
})
.await??;
// TODO: this should probably be a bulk operation // TODO: this should probably be a bulk operation
// Not easy to do as a bulk operation, // Not easy to do as a bulk operation,
// because recipient_id isn't in the comment table // because recipient_id isn't in the comment table
for comment_view in &replies { for comment_view in &replies {
let reply_id = comment_view.comment.id; let reply_id = comment_view.comment.id;
let mark_as_read = move |conn: &'_ _| Comment::update_read(conn, reply_id, true); let mark_as_read = Comment::update_read(&&context.pool.get().await?, reply_id, true);
if blocking(context.pool(), mark_as_read).await?.is_err() { if mark_as_read.is_err() {
return Err(ApiError::err("couldnt_update_comment").into()); return Err(ApiError::err("couldnt_update_comment").into());
} }
} }
// Mark all user mentions as read // Mark all user mentions as read
let update_person_mentions = let update_person_mentions =
move |conn: &'_ _| PersonMention::mark_all_as_read(conn, person_id); PersonMention::mark_all_as_read(&&context.pool.get().await?, person_id);
if blocking(context.pool(), update_person_mentions) if update_person_mentions.is_err() {
.await?
.is_err()
{
return Err(ApiError::err("couldnt_update_comment").into()); return Err(ApiError::err("couldnt_update_comment").into());
} }
// Mark all private_messages as read // Mark all private_messages as read
let update_pm = move |conn: &'_ _| PrivateMessage::mark_all_as_read(conn, person_id); let update_pm = PrivateMessage::mark_all_as_read(&&context.pool.get().await?, person_id);
if blocking(context.pool(), update_pm).await?.is_err() { if update_pm.is_err() {
return Err(ApiError::err("couldnt_update_private_message").into()); return Err(ApiError::err("couldnt_update_private_message").into());
} }
@ -706,11 +649,8 @@ impl Perform for PasswordReset {
// Fetch that email // Fetch that email
let email = data.email.clone(); let email = data.email.clone();
let local_user_view = blocking(context.pool(), move |conn| { let local_user_view = LocalUserView::find_by_email(&&context.pool.get().await?, &email)
LocalUserView::find_by_email(conn, &email) .map_err(|_| ApiError::err("couldnt_find_that_username_or_email"))?;
})
.await?
.map_err(|_| ApiError::err("couldnt_find_that_username_or_email"))?;
// Generate a random token // Generate a random token
let token = generate_random_string(); let token = generate_random_string();
@ -718,10 +658,7 @@ impl Perform for PasswordReset {
// Insert the row // Insert the row
let token2 = token.clone(); let token2 = token.clone();
let local_user_id = local_user_view.local_user.id; let local_user_id = local_user_view.local_user.id;
blocking(context.pool(), move |conn| { PasswordResetRequest::create_token(&&context.pool.get().await?, local_user_id, &token2)?;
PasswordResetRequest::create_token(conn, local_user_id, &token2)
})
.await??;
// Email the pure token to the user. // Email the pure token to the user.
// TODO no i18n support here. // TODO no i18n support here.
@ -749,10 +686,8 @@ impl Perform for PasswordChange {
// 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.get().await?, &token)
PasswordResetRequest::read_from_token(conn, &token).map(|p| p.local_user_id) .map(|p| p.local_user_id)?;
})
.await??;
password_length_check(&data.password)?; password_length_check(&data.password)?;
@ -763,11 +698,9 @@ impl Perform for PasswordChange {
// 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(conn, local_user_id, &password) LocalUser::update_password(&&context.pool.get().await?, local_user_id, &password)
}) .map_err(|_| ApiError::err("couldnt_update_user"))?;
.await?
.map_err(|_| ApiError::err("couldnt_update_user"))?;
// Return the jwt // Return the jwt
Ok(LoginResponse { Ok(LoginResponse {
@ -802,16 +735,11 @@ impl Perform for GetReportCount {
} }
} else { } else {
let ids = community_ids.clone(); let ids = community_ids.clone();
let comment_reports = blocking(context.pool(), move |conn| { let comment_reports =
CommentReportView::get_report_count(conn, &ids) CommentReportView::get_report_count(&&context.pool.get().await?, &ids)?;
})
.await??;
let ids = community_ids.clone(); let ids = community_ids.clone();
let post_reports = blocking(context.pool(), move |conn| { let post_reports = PostReportView::get_report_count(&&context.pool.get().await?, &ids)?;
PostReportView::get_report_count(conn, &ids)
})
.await??;
GetReportCountResponse { GetReportCountResponse {
community: data.community, community: data.community,

View file

@ -1,7 +1,6 @@
use crate::Perform; use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
check_community_ban, check_community_ban,
check_downvotes_enabled, check_downvotes_enabled,
check_person_block, check_person_block,
@ -45,7 +44,7 @@ impl Perform for CreatePostLike {
// Check for a community ban // Check for a community ban
let post_id = data.post_id; let post_id = data.post_id;
let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; let post = Post::read(&&context.pool.get().await?, post_id)?;
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?;
@ -59,10 +58,7 @@ 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(&&context.pool.get().await?, person_id, post_id)?;
PostLike::remove(conn, person_id, post_id)
})
.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));
@ -71,8 +67,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: &'_ _| PostLike::like(conn, &like_form2); let like = PostLike::like(&&context.pool.get().await?, &like_form2);
if blocking(context.pool(), like).await?.is_err() { if like.is_err() {
return Err(ApiError::err("couldnt_like_post").into()); return Err(ApiError::err("couldnt_like_post").into());
} }
@ -123,7 +119,7 @@ impl Perform for LockPost {
let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).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.get().await?, post_id)?;
check_community_ban( check_community_ban(
local_user_view.person.id, local_user_view.person.id,
@ -143,10 +139,7 @@ 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 = blocking(context.pool(), move |conn| { let updated_post = Post::update_locked(&&context.pool.get().await?, post_id, locked)?;
Post::update_locked(conn, post_id, locked)
})
.await??;
// Mod tables // Mod tables
let form = ModLockPostForm { let form = ModLockPostForm {
@ -154,7 +147,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.get().await?, &form)?;
// apub updates // apub updates
CreateOrUpdatePost::send( CreateOrUpdatePost::send(
@ -189,7 +182,7 @@ impl Perform for StickyPost {
let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).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.get().await?, post_id)?;
check_community_ban( check_community_ban(
local_user_view.person.id, local_user_view.person.id,
@ -209,10 +202,7 @@ 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 = blocking(context.pool(), move |conn| { let updated_post = Post::update_stickied(&&context.pool.get().await?, post_id, stickied)?;
Post::update_stickied(conn, post_id, stickied)
})
.await??;
// Mod tables // Mod tables
let form = ModStickyPostForm { let form = ModStickyPostForm {
@ -220,10 +210,7 @@ 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(&&context.pool.get().await?, &form)?;
ModStickyPost::create(conn, &form)
})
.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
@ -264,23 +251,20 @@ impl Perform for SavePost {
}; };
if data.save { if data.save {
let save = move |conn: &'_ _| PostSaved::save(conn, &post_saved_form); let save = PostSaved::save(&&context.pool.get().await?, &post_saved_form);
if blocking(context.pool(), save).await?.is_err() { if save.is_err() {
return Err(ApiError::err("couldnt_save_post").into()); return Err(ApiError::err("couldnt_save_post").into());
} }
} else { } else {
let unsave = move |conn: &'_ _| PostSaved::unsave(conn, &post_saved_form); let unsave = PostSaved::unsave(&&context.pool.get().await?, &post_saved_form);
if blocking(context.pool(), unsave).await?.is_err() { if unsave.is_err() {
return Err(ApiError::err("couldnt_save_post").into()); return Err(ApiError::err("couldnt_save_post").into());
} }
} }
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.get().await?, post_id, Some(person_id))?;
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

@ -1,7 +1,6 @@
use crate::Perform; use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
check_community_ban, check_community_ban,
collect_moderated_communities, collect_moderated_communities,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
@ -52,10 +51,7 @@ impl Perform for CreatePostReport {
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.get().await?, post_id, None)?;
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?;
@ -68,11 +64,8 @@ impl Perform for CreatePostReport {
reason: data.reason.to_owned(), reason: data.reason.to_owned(),
}; };
let report = blocking(context.pool(), move |conn| { let report = PostReport::report(&&context.pool.get().await?, &report_form)
PostReport::report(conn, &report_form) .map_err(|_| ApiError::err("couldnt_create_report"))?;
})
.await?
.map_err(|_| ApiError::err("couldnt_create_report"))?;
let res = CreatePostReportResponse { success: true }; let res = CreatePostReportResponse { success: true };
@ -108,21 +101,16 @@ impl Perform for ResolvePostReport {
let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
let report_id = data.report_id; let report_id = data.report_id;
let report = blocking(context.pool(), move |conn| { let report = PostReportView::read(&&context.pool.get().await?, report_id)?;
PostReportView::read(conn, report_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; let resolved = data.resolved;
let resolve_fun = move |conn: &'_ _| { let resolve_fun = if resolved {
if resolved { PostReport::resolve(&&context.pool.get().await?, report_id, person_id)
PostReport::resolve(conn, report_id, person_id) } else {
} else { PostReport::unresolve(&&context.pool.get().await?, report_id, person_id)
PostReport::unresolve(conn, report_id, person_id)
}
}; };
let res = ResolvePostReportResponse { let res = ResolvePostReportResponse {
@ -130,7 +118,7 @@ impl Perform for ResolvePostReport {
resolved: true, resolved: true,
}; };
if blocking(context.pool(), resolve_fun).await?.is_err() { if resolve_fun.is_err() {
return Err(ApiError::err("couldnt_resolve_report").into()); return Err(ApiError::err("couldnt_resolve_report").into());
}; };
@ -166,14 +154,11 @@ impl Perform for ListPostReports {
let page = data.page; let page = data.page;
let limit = data.limit; let limit = data.limit;
let posts = blocking(context.pool(), move |conn| { let posts = PostReportQueryBuilder::create(&&context.pool.get().await?)
PostReportQueryBuilder::create(conn) .community_ids(community_ids)
.community_ids(community_ids) .page(page)
.page(page) .limit(limit)
.limit(limit) .list()?;
.list()
})
.await??;
let res = ListPostReportsResponse { posts }; let res = ListPostReportsResponse { posts };

View file

@ -1,7 +1,6 @@
use crate::Perform; use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
person::{MarkPrivateMessageAsRead, PrivateMessageResponse}, person::{MarkPrivateMessageAsRead, PrivateMessageResponse},
}; };
@ -24,10 +23,8 @@ 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(conn, private_message_id) PrivateMessage::read(&&context.pool.get().await?, 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(ApiError::err("couldnt_update_private_message").into()); return Err(ApiError::err("couldnt_update_private_message").into());
} }
@ -35,11 +32,8 @@ 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_read(&&context.pool.get().await?, private_message_id, read)
PrivateMessage::update_read(conn, private_message_id, read) .map_err(|_| ApiError::err("couldnt_update_private_message"))?;
})
.await?
.map_err(|_| ApiError::err("couldnt_update_private_message"))?;
// No need to send an apub update // No need to send an apub update
let op = UserOperation::MarkPrivateMessageAsRead; let op = UserOperation::MarkPrivateMessageAsRead;

View file

@ -2,7 +2,6 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use anyhow::Context; use anyhow::Context;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
build_federated_instances, build_federated_instances,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
get_local_user_view_from_jwt_opt, get_local_user_view_from_jwt_opt,
@ -67,51 +66,69 @@ impl Perform for GetModlog {
let mod_person_id = data.mod_person_id; let mod_person_id = data.mod_person_id;
let page = data.page; let page = data.page;
let limit = data.limit; let limit = data.limit;
let removed_posts = blocking(context.pool(), move |conn| { let removed_posts = ModRemovePostView::list(
ModRemovePostView::list(conn, community_id, mod_person_id, page, limit) &&context.pool.get().await?,
}) community_id,
.await??; mod_person_id,
page,
limit,
)?;
let locked_posts = blocking(context.pool(), move |conn| { let locked_posts = ModLockPostView::list(
ModLockPostView::list(conn, community_id, mod_person_id, page, limit) &&context.pool.get().await?,
}) community_id,
.await??; mod_person_id,
page,
limit,
)?;
let stickied_posts = blocking(context.pool(), move |conn| { let stickied_posts = ModStickyPostView::list(
ModStickyPostView::list(conn, community_id, mod_person_id, page, limit) &&context.pool.get().await?,
}) community_id,
.await??; mod_person_id,
page,
limit,
)?;
let removed_comments = blocking(context.pool(), move |conn| { let removed_comments = ModRemoveCommentView::list(
ModRemoveCommentView::list(conn, community_id, mod_person_id, page, limit) &&context.pool.get().await?,
}) community_id,
.await??; mod_person_id,
page,
limit,
)?;
let banned_from_community = blocking(context.pool(), move |conn| { let banned_from_community = ModBanFromCommunityView::list(
ModBanFromCommunityView::list(conn, community_id, mod_person_id, page, limit) &&context.pool.get().await?,
}) community_id,
.await??; mod_person_id,
page,
limit,
)?;
let added_to_community = blocking(context.pool(), move |conn| { let added_to_community = ModAddCommunityView::list(
ModAddCommunityView::list(conn, community_id, mod_person_id, page, limit) &&context.pool.get().await?,
}) community_id,
.await??; mod_person_id,
page,
limit,
)?;
let transferred_to_community = blocking(context.pool(), move |conn| { let transferred_to_community = ModTransferCommunityView::list(
ModTransferCommunityView::list(conn, community_id, mod_person_id, page, limit) &&context.pool.get().await?,
}) community_id,
.await??; mod_person_id,
page,
limit,
)?;
// These arrays are only for the full modlog, when a community isn't given // These arrays are only for the full modlog, when a community isn't given
let (removed_communities, banned, added) = if data.community_id.is_none() { let (removed_communities, banned, added) = if data.community_id.is_none() {
blocking(context.pool(), move |conn| { (
Ok(( ModRemoveCommunityView::list(&&context.pool.get().await?, mod_person_id, page, limit)?,
ModRemoveCommunityView::list(conn, mod_person_id, page, limit)?, ModBanView::list(&&context.pool.get().await?, mod_person_id, page, limit)?,
ModBanView::list(conn, mod_person_id, page, limit)?, ModAddView::list(&&context.pool.get().await?, mod_person_id, page, limit)?,
ModAddView::list(conn, mod_person_id, page, limit)?, )
)) as Result<_, LemmyError>
})
.await??
} else { } else {
(Vec::new(), Vec::new(), Vec::new()) (Vec::new(), Vec::new(), Vec::new())
}; };
@ -182,64 +199,52 @@ 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 = PostQueryBuilder::create(&&context.pool.get().await?)
PostQueryBuilder::create(conn) .sort(sort)
.sort(sort) .show_nsfw(show_nsfw)
.show_nsfw(show_nsfw) .show_bot_accounts(show_bot_accounts)
.show_bot_accounts(show_bot_accounts) .show_read_posts(show_read_posts)
.show_read_posts(show_read_posts) .listing_type(listing_type)
.listing_type(listing_type) .community_id(community_id)
.community_id(community_id) .community_actor_id(community_actor_id)
.community_actor_id(community_actor_id) .creator_id(creator_id)
.creator_id(creator_id) .my_person_id(person_id)
.my_person_id(person_id) .search_term(q)
.search_term(q) .page(page)
.page(page) .limit(limit)
.limit(limit) .list()?;
.list()
})
.await??;
} }
SearchType::Comments => { SearchType::Comments => {
comments = blocking(context.pool(), move |conn| { comments = CommentQueryBuilder::create(&&context.pool.get().await?)
CommentQueryBuilder::create(conn) .sort(sort)
.sort(sort) .listing_type(listing_type)
.listing_type(listing_type) .search_term(q)
.search_term(q) .show_bot_accounts(show_bot_accounts)
.show_bot_accounts(show_bot_accounts) .community_id(community_id)
.community_id(community_id) .community_actor_id(community_actor_id)
.community_actor_id(community_actor_id) .creator_id(creator_id)
.creator_id(creator_id) .my_person_id(person_id)
.my_person_id(person_id) .page(page)
.page(page) .limit(limit)
.limit(limit) .list()?;
.list()
})
.await??;
} }
SearchType::Communities => { SearchType::Communities => {
communities = blocking(context.pool(), move |conn| { communities = CommunityQueryBuilder::create(&&context.pool.get().await?)
CommunityQueryBuilder::create(conn) .sort(sort)
.sort(sort) .listing_type(listing_type)
.listing_type(listing_type) .search_term(q)
.search_term(q) .my_person_id(person_id)
.my_person_id(person_id) .page(page)
.page(page) .limit(limit)
.limit(limit) .list()?;
.list()
})
.await??;
} }
SearchType::Users => { SearchType::Users => {
users = blocking(context.pool(), move |conn| { users = PersonQueryBuilder::create(&&context.pool.get().await?)
PersonQueryBuilder::create(conn) .sort(sort)
.sort(sort) .search_term(q)
.search_term(q) .page(page)
.page(page) .limit(limit)
.limit(limit) .list()?;
.list()
})
.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
@ -247,59 +252,50 @@ impl Perform for Search {
data.community_id.is_some() || data.community_name.is_some() || data.creator_id.is_some(); data.community_id.is_some() || data.community_name.is_some() || data.creator_id.is_some();
let community_actor_id_2 = community_actor_id.to_owned(); let community_actor_id_2 = community_actor_id.to_owned();
posts = blocking(context.pool(), move |conn| { posts = PostQueryBuilder::create(&&context.pool.get().await?)
PostQueryBuilder::create(conn) .sort(sort)
.sort(sort) .show_nsfw(show_nsfw)
.show_nsfw(show_nsfw) .show_bot_accounts(show_bot_accounts)
.show_bot_accounts(show_bot_accounts) .show_read_posts(show_read_posts)
.show_read_posts(show_read_posts) .listing_type(listing_type)
.listing_type(listing_type) .community_id(community_id)
.community_id(community_id) .community_actor_id(community_actor_id_2)
.community_actor_id(community_actor_id_2) .creator_id(creator_id)
.creator_id(creator_id) .my_person_id(person_id)
.my_person_id(person_id) .search_term(q)
.search_term(q) .page(page)
.page(page) .limit(limit)
.limit(limit) .list()?;
.list()
})
.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();
comments = blocking(context.pool(), move |conn| { comments = CommentQueryBuilder::create(&&context.pool.get().await?)
CommentQueryBuilder::create(conn) .sort(sort)
.sort(sort) .listing_type(listing_type)
.listing_type(listing_type) .search_term(q)
.search_term(q) .show_bot_accounts(show_bot_accounts)
.show_bot_accounts(show_bot_accounts) .community_id(community_id)
.community_id(community_id) .community_actor_id(community_actor_id)
.community_actor_id(community_actor_id) .creator_id(creator_id)
.creator_id(creator_id) .my_person_id(person_id)
.my_person_id(person_id) .page(page)
.page(page) .limit(limit)
.limit(limit) .list()?;
.list()
})
.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| { CommunityQueryBuilder::create(&&context.pool.get().await?)
CommunityQueryBuilder::create(conn) .sort(sort)
.sort(sort) .listing_type(listing_type)
.listing_type(listing_type) .search_term(q)
.search_term(q) .my_person_id(person_id)
.my_person_id(person_id) .page(page)
.page(page) .limit(limit)
.limit(limit) .list()?
.list()
})
.await??
}; };
let q = data.q.to_owned(); let q = data.q.to_owned();
@ -307,35 +303,29 @@ 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| { PersonQueryBuilder::create(&&context.pool.get().await?)
PersonQueryBuilder::create(conn) .sort(sort)
.sort(sort) .search_term(q)
.search_term(q) .page(page)
.page(page) .limit(limit)
.limit(limit) .list()?
.list()
})
.await??
}; };
} }
SearchType::Url => { SearchType::Url => {
posts = blocking(context.pool(), move |conn| { posts = PostQueryBuilder::create(&&context.pool.get().await?)
PostQueryBuilder::create(conn) .sort(sort)
.sort(sort) .show_nsfw(show_nsfw)
.show_nsfw(show_nsfw) .show_bot_accounts(show_bot_accounts)
.show_bot_accounts(show_bot_accounts) .show_read_posts(show_read_posts)
.show_read_posts(show_read_posts) .listing_type(listing_type)
.listing_type(listing_type) .my_person_id(person_id)
.my_person_id(person_id) .community_id(community_id)
.community_id(community_id) .community_actor_id(community_actor_id)
.community_actor_id(community_actor_id) .creator_id(creator_id)
.creator_id(creator_id) .url_search(q)
.url_search(q) .page(page)
.page(page) .limit(limit)
.limit(limit) .list()?;
.list()
})
.await??;
} }
}; };
@ -386,7 +376,7 @@ impl Perform for TransferSite {
is_admin(&local_user_view)?; is_admin(&local_user_view)?;
let read_site = blocking(context.pool(), move |conn| Site::read_simple(conn)).await??; let read_site = Site::read_simple(&&context.pool.get().await?)?;
// Make sure user is the creator // Make sure user is the creator
if read_site.creator_id != local_user_view.person.id { if read_site.creator_id != local_user_view.person.id {
@ -394,8 +384,8 @@ impl Perform for TransferSite {
} }
let new_creator_id = data.person_id; let new_creator_id = data.person_id;
let transfer_site = move |conn: &'_ _| Site::transfer(conn, new_creator_id); let transfer_site = Site::transfer(&&context.pool.get().await?, new_creator_id);
if blocking(context.pool(), transfer_site).await?.is_err() { if transfer_site.is_err() {
return Err(ApiError::err("couldnt_update_site").into()); return Err(ApiError::err("couldnt_update_site").into());
}; };
@ -406,11 +396,11 @@ impl Perform for TransferSite {
removed: Some(false), removed: Some(false),
}; };
blocking(context.pool(), move |conn| ModAdd::create(conn, &form)).await??; ModAdd::create(&&context.pool.get().await?, &form)?;
let site_view = blocking(context.pool(), move |conn| SiteView::read(conn)).await??; let site_view = SiteView::read(&&context.pool.get().await?)?;
let mut admins = blocking(context.pool(), move |conn| PersonViewSafe::admins(conn)).await??; let mut admins = PersonViewSafe::admins(&&context.pool.get().await?)?;
let creator_index = admins let creator_index = admins
.iter() .iter()
.position(|r| r.person.id == site_view.creator.id) .position(|r| r.person.id == site_view.creator.id)
@ -418,7 +408,7 @@ impl Perform for TransferSite {
let creator_person = admins.remove(creator_index); let creator_person = admins.remove(creator_index);
admins.insert(0, creator_person); admins.insert(0, creator_person);
let banned = blocking(context.pool(), move |conn| PersonViewSafe::banned(conn)).await??; let banned = PersonViewSafe::banned(&&context.pool.get().await?)?;
let federated_instances = build_federated_instances(context.pool()).await?; let federated_instances = build_federated_instances(context.pool()).await?;
Ok(GetSiteResponse { Ok(GetSiteResponse {

View file

@ -1,3 +1,5 @@
#![allow(clippy::needless_borrow)]
pub mod comment; pub mod comment;
pub mod community; pub mod community;
pub mod person; pub mod person;
@ -66,22 +68,6 @@ pub struct WebFingerResponse {
pub links: Vec<WebFingerLink>, pub links: Vec<WebFingerLink>,
} }
pub async fn blocking<F, T>(pool: &DbPool, f: F) -> Result<T, LemmyError>
where
F: FnOnce(&diesel::PgConnection) -> T + Send + 'static,
T: Send + 'static,
{
let pool = pool.clone();
let res = actix_web::web::block(move || {
let conn = pool.get()?;
let res = (f)(&conn);
Ok(res) as Result<T, LemmyError>
})
.await?;
res
}
pub async fn send_local_notifs( pub async fn send_local_notifs(
mentions: Vec<MentionData>, mentions: Vec<MentionData>,
comment: Comment, comment: Comment,
@ -90,10 +76,14 @@ pub async fn send_local_notifs(
pool: &DbPool, pool: &DbPool,
do_send_email: bool, do_send_email: bool,
) -> Result<Vec<LocalUserId>, LemmyError> { ) -> Result<Vec<LocalUserId>, LemmyError> {
let ids = blocking(pool, move |conn| { let ids = do_send_local_notifs(
do_send_local_notifs(conn, &mentions, &comment, &person, &post, do_send_email) &&pool.get().await?,
}) &mentions,
.await?; &comment,
&person,
&post,
do_send_email,
);
Ok(ids) Ok(ids)
} }
@ -222,10 +212,8 @@ pub async fn is_mod_or_admin(
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(conn, person_id, community_id) CommunityView::is_mod_or_admin(&&pool.get().await?, person_id, community_id);
})
.await?;
if !is_mod_or_admin { if !is_mod_or_admin {
return Err(ApiError::err("not_a_mod_or_admin").into()); return Err(ApiError::err("not_a_mod_or_admin").into());
} }
@ -240,9 +228,7 @@ pub fn is_admin(local_user_view: &LocalUserView) -> Result<(), LemmyError> {
} }
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.get().await?, post_id).map_err(|_| ApiError::err("couldnt_find_post").into())
.await?
.map_err(|_| ApiError::err("couldnt_find_post").into())
} }
pub async fn mark_post_as_read( pub async fn mark_post_as_read(
@ -251,12 +237,8 @@ pub async fn mark_post_as_read(
pool: &DbPool, pool: &DbPool,
) -> Result<PostRead, LemmyError> { ) -> Result<PostRead, LemmyError> {
let post_read_form = PostReadForm { post_id, person_id }; let post_read_form = PostReadForm { post_id, person_id };
PostRead::mark_as_read(&&pool.get().await?, &post_read_form)
blocking(pool, move |conn| { .map_err(|_| ApiError::err("couldnt_mark_post_as_read").into())
PostRead::mark_as_read(conn, &post_read_form)
})
.await?
.map_err(|_| ApiError::err("couldnt_mark_post_as_read").into())
} }
pub async fn get_local_user_view_from_jwt( pub async fn get_local_user_view_from_jwt(
@ -267,8 +249,7 @@ pub async fn get_local_user_view_from_jwt(
.map_err(|_| ApiError::err("not_logged_in"))? .map_err(|_| ApiError::err("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.get().await?, local_user_id)?;
blocking(pool, move |conn| LocalUserView::read(conn, local_user_id)).await??;
// Check for a site ban // Check for a site ban
if local_user_view.person.banned { if local_user_view.person.banned {
return Err(ApiError::err("site_ban").into()); return Err(ApiError::err("site_ban").into());
@ -315,10 +296,8 @@ pub async fn get_local_user_settings_view_from_jwt(
.map_err(|_| ApiError::err("not_logged_in"))? .map_err(|_| ApiError::err("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.get().await?, local_user_id)?;
LocalUserSettingsView::read(conn, local_user_id)
})
.await??;
// Check for a site ban // Check for a site ban
if local_user_view.person.banned { if local_user_view.person.banned {
return Err(ApiError::err("site_ban").into()); return Err(ApiError::err("site_ban").into());
@ -346,9 +325,8 @@ 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.get().await?, person_id, community_id).is_ok();
move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok(); if is_banned {
if blocking(pool, is_banned).await? {
Err(ApiError::err("community_ban").into()) Err(ApiError::err("community_ban").into())
} else { } else {
Ok(()) Ok(())
@ -360,8 +338,8 @@ 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: &'_ _| PersonBlock::read(conn, potential_blocker_id, my_id).is_ok(); let is_blocked = PersonBlock::read(&&pool.get().await?, potential_blocker_id, my_id).is_ok();
if blocking(pool, is_blocked).await? { if is_blocked {
Err(ApiError::err("person_block").into()) Err(ApiError::err("person_block").into())
} else { } else {
Ok(()) Ok(())
@ -370,7 +348,7 @@ pub async fn check_person_block(
pub async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> { pub async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> {
if score == -1 { if score == -1 {
let site = blocking(pool, move |conn| Site::read_simple(conn)).await??; let site = Site::read_simple(&&pool.get().await?)?;
if !site.enable_downvotes { if !site.enable_downvotes {
return Err(ApiError::err("downvotes_disabled").into()); return Err(ApiError::err("downvotes_disabled").into());
} }
@ -395,10 +373,7 @@ pub async fn collect_moderated_communities(
is_mod_or_admin(pool, person_id, community_id).await?; is_mod_or_admin(pool, person_id, community_id).await?;
Ok(vec![community_id]) Ok(vec![community_id])
} else { } else {
let ids = blocking(pool, move |conn: &'_ _| { let ids = CommunityModerator::get_person_moderated_communities(&&pool.get().await?, person_id)?;
CommunityModerator::get_person_moderated_communities(conn, person_id)
})
.await??;
Ok(ids) Ok(ids)
} }
} }
@ -407,10 +382,7 @@ pub async fn build_federated_instances(
pool: &DbPool, pool: &DbPool,
) -> Result<Option<FederatedInstances>, LemmyError> { ) -> Result<Option<FederatedInstances>, LemmyError> {
if Settings::get().federation.enabled { if Settings::get().federation.enabled {
let distinct_communities = blocking(pool, move |conn| { let distinct_communities = Community::distinct_federated_communities(&&pool.get().await?)?;
Community::distinct_federated_communities(conn)
})
.await??;
let allowed = Settings::get().federation.allowed_instances; let allowed = Settings::get().federation.allowed_instances;
let blocked = Settings::get().federation.blocked_instances; let blocked = Settings::get().federation.blocked_instances;

View file

@ -1,7 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
check_community_ban, check_community_ban,
check_person_block, check_person_block,
comment::*, comment::*,
@ -60,8 +59,7 @@ impl PerformCrud for CreateComment {
// If there's a parent_id, check to make sure that comment is in that post // If there's a parent_id, check to make sure that comment is in that post
if let Some(parent_id) = data.parent_id { if let Some(parent_id) = data.parent_id {
// Make sure the parent comment exists // Make sure the parent comment exists
let parent = blocking(context.pool(), move |conn| Comment::read(conn, parent_id)) let parent = Comment::read(&&context.pool.get().await?, parent_id)
.await?
.map_err(|_| ApiError::err("couldnt_create_comment"))?; .map_err(|_| ApiError::err("couldnt_create_comment"))?;
check_person_block(local_user_view.person.id, parent.creator_id, context.pool()).await?; check_person_block(local_user_view.person.id, parent.creator_id, context.pool()).await?;
@ -82,22 +80,15 @@ impl PerformCrud for CreateComment {
// Create the comment // Create the comment
let comment_form2 = comment_form.clone(); let comment_form2 = comment_form.clone();
let inserted_comment = blocking(context.pool(), move |conn| { let inserted_comment = Comment::create(&&context.pool.get().await?, &comment_form2)
Comment::create(conn, &comment_form2) .map_err(|_| ApiError::err("couldnt_create_comment"))?;
})
.await?
.map_err(|_| ApiError::err("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 updated_comment: Comment = let apub_id = generate_apub_endpoint(EndpointType::Comment, &inserted_comment_id.to_string())?;
blocking(context.pool(), move |conn| -> Result<Comment, LemmyError> { let updated_comment =
let apub_id = Comment::update_ap_id(&&context.pool.get().await?, inserted_comment_id, apub_id)
generate_apub_endpoint(EndpointType::Comment, &inserted_comment_id.to_string())?; .map_err(|_| ApiError::err("couldnt_create_comment"))?;
Ok(Comment::update_ap_id(conn, inserted_comment_id, apub_id)?)
})
.await?
.map_err(|_| ApiError::err("couldnt_create_comment"))?;
CreateOrUpdateComment::send( CreateOrUpdateComment::send(
&updated_comment, &updated_comment,
@ -128,8 +119,8 @@ impl PerformCrud for CreateComment {
score: 1, score: 1,
}; };
let like = move |conn: &'_ _| CommentLike::like(conn, &like_form); let like = CommentLike::like(&&context.pool.get().await?, &like_form);
if blocking(context.pool(), like).await?.is_err() { if like.is_err() {
return Err(ApiError::err("couldnt_like_comment").into()); return Err(ApiError::err("couldnt_like_comment").into());
} }
@ -146,11 +137,8 @@ impl PerformCrud for CreateComment {
// If its a comment to yourself, mark it as read // If its a comment to yourself, mark it as read
if local_user_view.person.id == inserted_comment.creator_id { if local_user_view.person.id == inserted_comment.creator_id {
let comment_id = inserted_comment.id; let comment_id = inserted_comment.id;
blocking(context.pool(), move |conn| { Comment::update_read(&&context.pool.get().await?, comment_id, true)
Comment::update_read(conn, comment_id, true) .map_err(|_| ApiError::err("couldnt_update_comment"))?;
})
.await?
.map_err(|_| ApiError::err("couldnt_update_comment"))?;
} }
send_comment_ws_message( send_comment_ws_message(

View file

@ -1,7 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
check_community_ban, check_community_ban,
comment::*, comment::*,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
@ -28,10 +27,7 @@ impl PerformCrud for DeleteComment {
let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; let local_user_view = get_local_user_view_from_jwt(&data.auth, 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.get().await?, comment_id, None)?;
CommentView::read(conn, comment_id, None)
})
.await??;
check_community_ban( check_community_ban(
local_user_view.person.id, local_user_view.person.id,
@ -47,17 +43,11 @@ 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_deleted(&&context.pool.get().await?, comment_id, deleted)
Comment::update_deleted(conn, comment_id, deleted) .map_err(|_| ApiError::err("couldnt_update_comment"))?;
})
.await?
.map_err(|_| ApiError::err("couldnt_update_comment"))?;
// Send the apub message // Send the apub message
let community = blocking(context.pool(), move |conn| { let community = Community::read(&&context.pool.get().await?, orig_comment.post.community_id)?;
Community::read(conn, orig_comment.post.community_id)
})
.await??;
send_apub_delete( send_apub_delete(
&local_user_view.person, &local_user_view.person,
&community, &community,
@ -68,7 +58,7 @@ impl PerformCrud for DeleteComment {
.await?; .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.get().await?, post_id)?;
let recipient_ids = send_local_notifs( let recipient_ids = send_local_notifs(
vec![], vec![],
updated_comment, updated_comment,
@ -105,10 +95,7 @@ impl PerformCrud for RemoveComment {
let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; let local_user_view = get_local_user_view_from_jwt(&data.auth, 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.get().await?, comment_id, None)?;
CommentView::read(conn, comment_id, None)
})
.await??;
check_community_ban( check_community_ban(
local_user_view.person.id, local_user_view.person.id,
@ -127,11 +114,8 @@ 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_removed(&&context.pool.get().await?, comment_id, removed)
Comment::update_removed(conn, comment_id, removed) .map_err(|_| ApiError::err("couldnt_update_comment"))?;
})
.await?
.map_err(|_| ApiError::err("couldnt_update_comment"))?;
// Mod tables // Mod tables
let form = ModRemoveCommentForm { let form = ModRemoveCommentForm {
@ -140,16 +124,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.get().await?, &form)?;
ModRemoveComment::create(conn, &form)
})
.await??;
// Send the apub message // Send the apub message
let community = blocking(context.pool(), move |conn| { let community = Community::read(&&context.pool.get().await?, orig_comment.post.community_id)?;
Community::read(conn, orig_comment.post.community_id)
})
.await??;
send_apub_remove( send_apub_remove(
&local_user_view.person, &local_user_view.person,
&community, &community,
@ -161,7 +139,7 @@ impl PerformCrud for RemoveComment {
.await?; .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.get().await?, post_id)?;
let recipient_ids = send_local_notifs( let recipient_ids = send_local_notifs(
vec![], vec![],
updated_comment, updated_comment,

View file

@ -1,6 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{blocking, comment::*, get_local_user_view_from_jwt_opt}; use lemmy_api_common::{comment::*, get_local_user_view_from_jwt_opt};
use lemmy_apub::{build_actor_id_from_shortname, EndpointType}; use lemmy_apub::{build_actor_id_from_shortname, EndpointType};
use lemmy_db_queries::{from_opt_str_to_opt_enum, DeleteableOrRemoveable, ListingType, SortType}; use lemmy_db_queries::{from_opt_str_to_opt_enum, DeleteableOrRemoveable, ListingType, SortType};
use lemmy_db_views::comment_view::CommentQueryBuilder; use lemmy_db_views::comment_view::CommentQueryBuilder;
@ -36,21 +36,18 @@ impl PerformCrud for GetComments {
let saved_only = data.saved_only; let saved_only = data.saved_only;
let page = data.page; let page = data.page;
let limit = data.limit; let limit = data.limit;
let mut comments = blocking(context.pool(), move |conn| { let mut comments = CommentQueryBuilder::create(&&context.pool.get().await?)
CommentQueryBuilder::create(conn) .listing_type(listing_type)
.listing_type(listing_type) .sort(sort)
.sort(sort) .saved_only(saved_only)
.saved_only(saved_only) .community_id(community_id)
.community_id(community_id) .community_actor_id(community_actor_id)
.community_actor_id(community_actor_id) .my_person_id(person_id)
.my_person_id(person_id) .show_bot_accounts(show_bot_accounts)
.show_bot_accounts(show_bot_accounts) .page(page)
.page(page) .limit(limit)
.limit(limit) .list()
.list() .map_err(|_| ApiError::err("couldnt_get_comments"))?;
})
.await?
.map_err(|_| ApiError::err("couldnt_get_comments"))?;
// Blank out deleted or removed info // Blank out deleted or removed info
for cv in comments for cv in comments

View file

@ -1,7 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
check_community_ban, check_community_ban,
comment::*, comment::*,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
@ -35,10 +34,7 @@ impl PerformCrud for EditComment {
let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; let local_user_view = get_local_user_view_from_jwt(&data.auth, 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.get().await?, comment_id, None)?;
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(
@ -56,10 +52,11 @@ impl PerformCrud for EditComment {
// Do the update // Do the update
let content_slurs_removed = remove_slurs(&data.content.to_owned()); let content_slurs_removed = remove_slurs(&data.content.to_owned());
let comment_id = data.comment_id; let comment_id = data.comment_id;
let updated_comment = blocking(context.pool(), move |conn| { let updated_comment = Comment::update_content(
Comment::update_content(conn, comment_id, &content_slurs_removed) &&context.pool.get().await?,
}) comment_id,
.await? &content_slurs_removed,
)
.map_err(|_| ApiError::err("couldnt_update_comment"))?; .map_err(|_| ApiError::err("couldnt_update_comment"))?;
// Send the apub update // Send the apub update

View file

@ -1,7 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
community::{CommunityResponse, CreateCommunity}, community::{CommunityResponse, CreateCommunity},
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
is_admin, is_admin,
@ -47,7 +46,7 @@ impl PerformCrud for CreateCommunity {
let data: &CreateCommunity = self; let data: &CreateCommunity = self;
let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
let site = blocking(context.pool(), move |conn| Site::read(conn, 0)).await??; let site = Site::read(&&context.pool.get().await?, 0)?;
if site.community_creation_admin_only && is_admin(&local_user_view).is_err() { if site.community_creation_admin_only && is_admin(&local_user_view).is_err() {
return Err(ApiError::err("only_admins_can_create_communities").into()); return Err(ApiError::err("only_admins_can_create_communities").into());
} }
@ -63,10 +62,8 @@ impl PerformCrud for CreateCommunity {
// Double check for duplicate community actor_ids // Double check for duplicate community actor_ids
let community_actor_id = generate_apub_endpoint(EndpointType::Community, &data.name)?; let community_actor_id = generate_apub_endpoint(EndpointType::Community, &data.name)?;
let actor_id_cloned = community_actor_id.to_owned(); let actor_id_cloned = community_actor_id.to_owned();
let community_dupe = blocking(context.pool(), move |conn| { let community_dupe =
Community::read_from_apub_id(conn, &actor_id_cloned) Community::read_from_apub_id(&&context.pool.get().await?, &actor_id_cloned);
})
.await?;
if community_dupe.is_ok() { if community_dupe.is_ok() {
return Err(ApiError::err("community_already_exists").into()); return Err(ApiError::err("community_already_exists").into());
} }
@ -94,11 +91,8 @@ impl PerformCrud for CreateCommunity {
..CommunityForm::default() ..CommunityForm::default()
}; };
let inserted_community = blocking(context.pool(), move |conn| { let inserted_community = Community::create(&&context.pool.get().await?, &community_form)
Community::create(conn, &community_form) .map_err(|_| ApiError::err("community_already_exists"))?;
})
.await?
.map_err(|_| ApiError::err("community_already_exists"))?;
// The community creator becomes a moderator // The community creator becomes a moderator
let community_moderator_form = CommunityModeratorForm { let community_moderator_form = CommunityModeratorForm {
@ -106,8 +100,8 @@ impl PerformCrud for CreateCommunity {
person_id: local_user_view.person.id, person_id: local_user_view.person.id,
}; };
let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form); let join = CommunityModerator::join(&&context.pool.get().await?, &community_moderator_form);
if blocking(context.pool(), join).await?.is_err() { if join.is_err() {
return Err(ApiError::err("community_moderator_already_exists").into()); return Err(ApiError::err("community_moderator_already_exists").into());
} }
@ -118,16 +112,17 @@ impl PerformCrud for CreateCommunity {
pending: false, pending: false,
}; };
let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form); let follow = CommunityFollower::follow(&&context.pool.get().await?, &community_follower_form);
if blocking(context.pool(), follow).await?.is_err() { if follow.is_err() {
return Err(ApiError::err("community_follower_already_exists").into()); return Err(ApiError::err("community_follower_already_exists").into());
} }
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(
CommunityView::read(conn, inserted_community.id, Some(person_id)) &&context.pool.get().await?,
}) inserted_community.id,
.await??; Some(person_id),
)?;
Ok(CommunityResponse { community_view }) Ok(CommunityResponse { community_view })
} }

View file

@ -1,6 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{blocking, community::*, get_local_user_view_from_jwt, is_admin}; use lemmy_api_common::{community::*, get_local_user_view_from_jwt, is_admin};
use lemmy_apub::activities::deletion::{send_apub_delete, send_apub_remove}; use lemmy_apub::activities::deletion::{send_apub_delete, send_apub_remove};
use lemmy_db_queries::{source::community::Community_, Crud}; use lemmy_db_queries::{source::community::Community_, Crud};
use lemmy_db_schema::source::{ use lemmy_db_schema::source::{
@ -25,10 +25,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.get().await?, community_id)?;
})
.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 {
@ -38,11 +36,9 @@ 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_deleted(conn, community_id, deleted) Community::update_deleted(&&context.pool.get().await?, community_id, deleted)
}) .map_err(|_| ApiError::err("couldnt_update_community"))?;
.await?
.map_err(|_| ApiError::err("couldnt_update_community"))?;
// Send apub messages // Send apub messages
send_apub_delete( send_apub_delete(
@ -83,11 +79,9 @@ 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_removed(conn, community_id, removed) Community::update_removed(&&context.pool.get().await?, community_id, removed)
}) .map_err(|_| ApiError::err("couldnt_update_community"))?;
.await?
.map_err(|_| ApiError::err("couldnt_update_community"))?;
// Mod tables // Mod tables
let expires = data.expires.map(naive_from_unix); let expires = data.expires.map(naive_from_unix);
@ -98,10 +92,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.get().await?, &form)?;
ModRemoveCommunity::create(conn, &form)
})
.await??;
// Apub messages // Apub messages
send_apub_remove( send_apub_remove(

View file

@ -1,6 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{blocking, community::*, get_local_user_view_from_jwt_opt}; use lemmy_api_common::{community::*, get_local_user_view_from_jwt_opt};
use lemmy_apub::{build_actor_id_from_shortname, EndpointType}; use lemmy_apub::{build_actor_id_from_shortname, EndpointType};
use lemmy_db_queries::{ use lemmy_db_queries::{
from_opt_str_to_opt_enum, from_opt_str_to_opt_enum,
@ -36,31 +36,24 @@ impl PerformCrud for GetCommunity {
let name = data.name.to_owned().unwrap_or_else(|| "main".to_string()); let name = data.name.to_owned().unwrap_or_else(|| "main".to_string());
let community_actor_id = build_actor_id_from_shortname(EndpointType::Community, &name)?; let community_actor_id = build_actor_id_from_shortname(EndpointType::Community, &name)?;
blocking(context.pool(), move |conn| { Community::read_from_apub_id(&&context.pool.get().await?, &community_actor_id)
Community::read_from_apub_id(conn, &community_actor_id) .map_err(|_| ApiError::err("couldnt_find_community"))?
}) .id
.await?
.map_err(|_| ApiError::err("couldnt_find_community"))?
.id
} }
}; };
let mut community_view = blocking(context.pool(), move |conn| { let mut community_view =
CommunityView::read(conn, community_id, person_id) CommunityView::read(&&context.pool.get().await?, community_id, person_id)
}) .map_err(|_| ApiError::err("couldnt_find_community"))?;
.await?
.map_err(|_| ApiError::err("couldnt_find_community"))?;
// Blank out deleted or removed info // Blank out deleted or removed info
if community_view.community.deleted || community_view.community.removed { if community_view.community.deleted || community_view.community.removed {
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: Vec<CommunityModeratorView> =
CommunityModeratorView::for_community(conn, community_id) CommunityModeratorView::for_community(&&context.pool.get().await?, community_id)
}) .map_err(|_| ApiError::err("couldnt_find_community"))?;
.await?
.map_err(|_| ApiError::err("couldnt_find_community"))?;
let online = context let online = context
.chat_server() .chat_server()
@ -104,17 +97,14 @@ impl PerformCrud for ListCommunities {
let page = data.page; let page = data.page;
let limit = data.limit; let limit = data.limit;
let mut communities = blocking(context.pool(), move |conn| { let mut communities = CommunityQueryBuilder::create(&&context.pool.get().await?)
CommunityQueryBuilder::create(conn) .listing_type(listing_type)
.listing_type(listing_type) .sort(sort)
.sort(sort) .show_nsfw(show_nsfw)
.show_nsfw(show_nsfw) .my_person_id(person_id)
.my_person_id(person_id) .page(page)
.page(page) .limit(limit)
.limit(limit) .list()?;
.list()
})
.await??;
// Blank out deleted or removed info // Blank out deleted or removed info
for cv in communities for cv in communities

View file

@ -1,7 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
community::{CommunityResponse, EditCommunity}, community::{CommunityResponse, EditCommunity},
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
}; };
@ -33,20 +32,15 @@ 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(conn, community_id) CommunityModeratorView::for_community(&&context.pool.get().await?, community_id)
.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(ApiError::err("not_a_moderator").into()); return Err(ApiError::err("not_a_moderator").into());
} }
let community_id = data.community_id; let community_id = data.community_id;
let read_community = blocking(context.pool(), move |conn| { let read_community = Community::read(&&context.pool.get().await?, community_id)?;
Community::read(conn, community_id)
})
.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)?;
@ -63,11 +57,9 @@ impl PerformCrud for EditCommunity {
}; };
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(conn, community_id, &community_form) Community::update(&&context.pool.get().await?, community_id, &community_form)
}) .map_err(|_| ApiError::err("couldnt_update_community"))?;
.await?
.map_err(|_| ApiError::err("couldnt_update_community"))?;
UpdateCommunity::send(&updated_community, &local_user_view.person, context).await?; UpdateCommunity::send(&updated_community, &local_user_view.person, context).await?;

View file

@ -1,3 +1,5 @@
#![allow(clippy::needless_borrow)]
use actix_web::{web, web::Data}; use actix_web::{web, web::Data};
use lemmy_api_common::{comment::*, community::*, person::*, post::*, site::*}; use lemmy_api_common::{comment::*, community::*, person::*, post::*, site::*};
use lemmy_utils::{ConnectionId, LemmyError}; use lemmy_utils::{ConnectionId, LemmyError};

View file

@ -1,7 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
check_community_ban, check_community_ban,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
mark_post_as_read, mark_post_as_read,
@ -70,27 +69,20 @@ impl PerformCrud for CreatePost {
..PostForm::default() ..PostForm::default()
}; };
let inserted_post = let inserted_post = Post::create(&&context.pool.get().await?, &post_form).map_err(|e| {
match blocking(context.pool(), move |conn| Post::create(conn, &post_form)).await? { let err_type = if e.to_string() == "value too long for type character varying(200)" {
Ok(post) => post, "post_title_too_long"
Err(e) => { } else {
let err_type = if e.to_string() == "value too long for type character varying(200)" { "couldnt_create_post"
"post_title_too_long"
} else {
"couldnt_create_post"
};
return Err(ApiError::err(err_type).into());
}
}; };
ApiError::err(err_type)
})?;
let inserted_post_id = inserted_post.id; let inserted_post_id = inserted_post.id;
let updated_post = blocking(context.pool(), move |conn| -> Result<Post, LemmyError> { let apub_id = generate_apub_endpoint(EndpointType::Post, &inserted_post_id.to_string())?;
let apub_id = generate_apub_endpoint(EndpointType::Post, &inserted_post_id.to_string())?; let updated_post = Post::update_ap_id(&&context.pool.get().await?, inserted_post_id, apub_id)
Ok(Post::update_ap_id(conn, inserted_post_id, apub_id)?) .map_err(|_| ApiError::err("couldnt_create_post"))?;
})
.await?
.map_err(|_| ApiError::err("couldnt_create_post"))?;
CreateOrUpdatePost::send( CreateOrUpdatePost::send(
&updated_post, &updated_post,
@ -109,8 +101,8 @@ impl PerformCrud for CreatePost {
score: 1, score: 1,
}; };
let like = move |conn: &'_ _| PostLike::like(conn, &like_form); let like = PostLike::like(&&context.pool.get().await?, &like_form);
if blocking(context.pool(), like).await?.is_err() { if like.is_err() {
return Err(ApiError::err("couldnt_like_post").into()); return Err(ApiError::err("couldnt_like_post").into());
} }

View file

@ -1,7 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
check_community_ban, check_community_ban,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
is_mod_or_admin, is_mod_or_admin,
@ -26,7 +25,7 @@ impl PerformCrud for DeletePost {
let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).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.get().await?, post_id)?;
check_community_ban( check_community_ban(
local_user_view.person.id, local_user_view.person.id,
@ -43,16 +42,10 @@ 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_deleted(&&context.pool.get().await?, post_id, deleted)?;
Post::update_deleted(conn, post_id, deleted)
})
.await??;
// apub updates // apub updates
let community = blocking(context.pool(), move |conn| { let community = Community::read(&&context.pool.get().await?, orig_post.community_id)?;
Community::read(conn, orig_post.community_id)
})
.await??;
send_apub_delete( send_apub_delete(
&local_user_view.person, &local_user_view.person,
&community, &community,
@ -86,7 +79,7 @@ impl PerformCrud for RemovePost {
let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?; let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).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.get().await?, post_id)?;
check_community_ban( check_community_ban(
local_user_view.person.id, local_user_view.person.id,
@ -106,10 +99,7 @@ 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_removed(&&context.pool.get().await?, post_id, removed)?;
Post::update_removed(conn, post_id, removed)
})
.await??;
// Mod tables // Mod tables
let form = ModRemovePostForm { let form = ModRemovePostForm {
@ -118,16 +108,10 @@ 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.get().await?, &form)?;
ModRemovePost::create(conn, &form)
})
.await??;
// apub updates // apub updates
let community = blocking(context.pool(), move |conn| { let community = Community::read(&&context.pool.get().await?, orig_post.community_id)?;
Community::read(conn, orig_post.community_id)
})
.await??;
send_apub_remove( send_apub_remove(
&local_user_view.person, &local_user_view.person,
&community, &community,

View file

@ -1,6 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{blocking, get_local_user_view_from_jwt_opt, mark_post_as_read, post::*}; use lemmy_api_common::{get_local_user_view_from_jwt_opt, mark_post_as_read, post::*};
use lemmy_apub::{build_actor_id_from_shortname, EndpointType}; use lemmy_apub::{build_actor_id_from_shortname, EndpointType};
use lemmy_db_queries::{from_opt_str_to_opt_enum, DeleteableOrRemoveable, ListingType, SortType}; use lemmy_db_queries::{from_opt_str_to_opt_enum, DeleteableOrRemoveable, ListingType, SortType};
use lemmy_db_views::{ use lemmy_db_views::{
@ -32,11 +32,8 @@ impl PerformCrud for GetPost {
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 mut post_view = blocking(context.pool(), move |conn| { let mut post_view = PostView::read(&&context.pool.get().await?, id, person_id)
PostView::read(conn, id, person_id) .map_err(|_| ApiError::err("couldnt_find_post"))?;
})
.await?
.map_err(|_| ApiError::err("couldnt_find_post"))?;
// Blank out deleted info // Blank out deleted info
if post_view.post.deleted || post_view.post.removed { if post_view.post.deleted || post_view.post.removed {
@ -49,15 +46,12 @@ impl PerformCrud for GetPost {
} }
let id = data.id; let id = data.id;
let mut comments = blocking(context.pool(), move |conn| { let mut comments = CommentQueryBuilder::create(&&context.pool.get().await?)
CommentQueryBuilder::create(conn) .my_person_id(person_id)
.my_person_id(person_id) .show_bot_accounts(show_bot_accounts)
.show_bot_accounts(show_bot_accounts) .post_id(id)
.post_id(id) .limit(9999)
.limit(9999) .list()?;
.list()
})
.await??;
// Blank out deleted or removed info // Blank out deleted or removed info
for cv in comments for cv in comments
@ -68,17 +62,13 @@ impl PerformCrud for GetPost {
} }
let community_id = post_view.community.id; let community_id = post_view.community.id;
let moderators = blocking(context.pool(), move |conn| { let moderators =
CommunityModeratorView::for_community(conn, community_id) CommunityModeratorView::for_community(&&context.pool.get().await?, community_id)?;
})
.await??;
// Necessary for the sidebar // Necessary for the sidebar
let mut community_view = blocking(context.pool(), move |conn| { let mut community_view =
CommunityView::read(conn, community_id, person_id) CommunityView::read(&&context.pool.get().await?, community_id, person_id)
}) .map_err(|_| ApiError::err("couldnt_find_community"))?;
.await?
.map_err(|_| ApiError::err("couldnt_find_community"))?;
// Blank out deleted or removed info // Blank out deleted or removed info
if community_view.community.deleted || community_view.community.removed { if community_view.community.deleted || community_view.community.removed {
@ -137,23 +127,20 @@ impl PerformCrud for GetPosts {
.unwrap_or(None); .unwrap_or(None);
let saved_only = data.saved_only; let saved_only = data.saved_only;
let mut posts = blocking(context.pool(), move |conn| { let mut posts = PostQueryBuilder::create(&&context.pool.get().await?)
PostQueryBuilder::create(conn) .listing_type(listing_type)
.listing_type(listing_type) .sort(sort)
.sort(sort) .show_nsfw(show_nsfw)
.show_nsfw(show_nsfw) .show_bot_accounts(show_bot_accounts)
.show_bot_accounts(show_bot_accounts) .show_read_posts(show_read_posts)
.show_read_posts(show_read_posts) .community_id(community_id)
.community_id(community_id) .community_actor_id(community_actor_id)
.community_actor_id(community_actor_id) .saved_only(saved_only)
.saved_only(saved_only) .my_person_id(person_id)
.my_person_id(person_id) .page(page)
.page(page) .limit(limit)
.limit(limit) .list()
.list() .map_err(|_| ApiError::err("couldnt_get_posts"))?;
})
.await?
.map_err(|_| ApiError::err("couldnt_get_posts"))?;
// Blank out deleted or removed info // Blank out deleted or removed info
for pv in posts for pv in posts

View file

@ -1,6 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{blocking, check_community_ban, get_local_user_view_from_jwt, post::*}; use lemmy_api_common::{check_community_ban, get_local_user_view_from_jwt, post::*};
use lemmy_apub::activities::{post::create_or_update::CreateOrUpdatePost, CreateOrUpdateType}; use lemmy_apub::activities::{post::create_or_update::CreateOrUpdatePost, CreateOrUpdateType};
use lemmy_db_queries::{source::post::Post_, Crud}; use lemmy_db_queries::{source::post::Post_, Crud};
use lemmy_db_schema::{naive_now, source::post::*}; use lemmy_db_schema::{naive_now, source::post::*};
@ -35,7 +35,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.get().await?, post_id)?;
check_community_ban( check_community_ban(
local_user_view.person.id, local_user_view.person.id,
@ -72,22 +72,16 @@ impl PerformCrud for EditPost {
}; };
let post_id = data.post_id; let post_id = data.post_id;
let res = blocking(context.pool(), move |conn| { let updated_post =
Post::update(conn, post_id, &post_form) Post::update(&&context.pool.get().await?, post_id, &post_form).map_err(|e| {
})
.await?;
let updated_post: Post = match res {
Ok(post) => post,
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)" {
"post_title_too_long" "post_title_too_long"
} else { } else {
"couldnt_update_post" "couldnt_update_post"
}; };
return Err(ApiError::err(err_type).into()); ApiError::err(err_type)
} })?;
};
// Send apub update // Send apub update
CreateOrUpdatePost::send( CreateOrUpdatePost::send(

View file

@ -1,7 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
check_person_block, check_person_block,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
person::{CreatePrivateMessage, PrivateMessageResponse}, person::{CreatePrivateMessage, PrivateMessageResponse},
@ -44,33 +43,21 @@ impl PerformCrud for CreatePrivateMessage {
..PrivateMessageForm::default() ..PrivateMessageForm::default()
}; };
let inserted_private_message = match blocking(context.pool(), move |conn| { let inserted_private_message =
PrivateMessage::create(conn, &private_message_form) PrivateMessage::create(&&context.pool.get().await?, &private_message_form)
}) .map_err(|_| ApiError::err("couldnt_create_private_message"))?;
.await?
{
Ok(private_message) => private_message,
Err(_e) => {
return Err(ApiError::err("couldnt_create_private_message").into());
}
};
let inserted_private_message_id = inserted_private_message.id; let inserted_private_message_id = inserted_private_message.id;
let updated_private_message = blocking( let apub_id = generate_apub_endpoint(
context.pool(), EndpointType::PrivateMessage,
move |conn| -> Result<PrivateMessage, LemmyError> { &inserted_private_message_id.to_string(),
let apub_id = generate_apub_endpoint( )?;
EndpointType::PrivateMessage,
&inserted_private_message_id.to_string(), let updated_private_message = PrivateMessage::update_ap_id(
)?; &&context.pool.get().await?,
Ok(PrivateMessage::update_ap_id( inserted_private_message_id,
conn, apub_id,
inserted_private_message_id,
apub_id,
)?)
},
) )
.await?
.map_err(|_| ApiError::err("couldnt_create_private_message"))?; .map_err(|_| ApiError::err("couldnt_create_private_message"))?;
CreateOrUpdatePrivateMessage::send( CreateOrUpdatePrivateMessage::send(
@ -92,10 +79,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.get().await?, recipient_id)?;
LocalUserView::read_person(conn, recipient_id)
})
.await??;
send_email_to_user( send_email_to_user(
&local_recipient, &local_recipient,
"Private Message from", "Private Message from",

View file

@ -1,7 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
person::{DeletePrivateMessage, PrivateMessageResponse}, person::{DeletePrivateMessage, PrivateMessageResponse},
}; };
@ -28,10 +27,8 @@ 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(conn, private_message_id) PrivateMessage::read(&&context.pool.get().await?, 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(ApiError::err("no_private_message_edit_allowed").into()); return Err(ApiError::err("no_private_message_edit_allowed").into());
} }
@ -39,11 +36,9 @@ 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_deleted(conn, private_message_id, deleted) PrivateMessage::update_deleted(&&context.pool.get().await?, private_message_id, deleted)
}) .map_err(|_| ApiError::err("couldnt_update_private_message"))?;
.await?
.map_err(|_| ApiError::err("couldnt_update_private_message"))?;
// Send the apub update // Send the apub update
if data.deleted { if data.deleted {

View file

@ -1,7 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
person::{GetPrivateMessages, PrivateMessagesResponse}, person::{GetPrivateMessages, PrivateMessagesResponse},
}; };
@ -26,14 +25,11 @@ 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 = PrivateMessageQueryBuilder::create(&&context.pool.get().await?, person_id)
PrivateMessageQueryBuilder::create(conn, person_id) .page(page)
.page(page) .limit(limit)
.limit(limit) .unread_only(unread_only)
.unread_only(unread_only) .list()?;
.list()
})
.await??;
// Blank out deleted or removed info // Blank out deleted or removed info
for pmv in messages for pmv in messages

View file

@ -1,7 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
person::{EditPrivateMessage, PrivateMessageResponse}, person::{EditPrivateMessage, PrivateMessageResponse},
}; };
@ -28,10 +27,8 @@ impl PerformCrud for EditPrivateMessage {
// 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(conn, private_message_id) PrivateMessage::read(&&context.pool.get().await?, 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(ApiError::err("no_private_message_edit_allowed").into()); return Err(ApiError::err("no_private_message_edit_allowed").into());
} }
@ -39,10 +36,11 @@ impl PerformCrud for EditPrivateMessage {
// Doing the update // Doing the update
let content_slurs_removed = remove_slurs(&data.content); let content_slurs_removed = remove_slurs(&data.content);
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_content(
PrivateMessage::update_content(conn, private_message_id, &content_slurs_removed) &&context.pool.get().await?,
}) private_message_id,
.await? &content_slurs_removed,
)
.map_err(|_| ApiError::err("couldnt_update_private_message"))?; .map_err(|_| ApiError::err("couldnt_update_private_message"))?;
// Send the apub update // Send the apub update

View file

@ -1,7 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
is_admin, is_admin,
site::*, site::*,
@ -34,8 +33,8 @@ impl PerformCrud for CreateSite {
) -> Result<SiteResponse, LemmyError> { ) -> Result<SiteResponse, LemmyError> {
let data: &CreateSite = self; let data: &CreateSite = self;
let read_site = move |conn: &'_ _| Site::read_simple(conn); let read_site = Site::read_simple(&&context.pool.get().await?);
if blocking(context.pool(), read_site).await?.is_ok() { if read_site.is_ok() {
return Err(ApiError::err("site_already_exists").into()); return Err(ApiError::err("site_already_exists").into());
}; };
@ -70,12 +69,12 @@ impl PerformCrud for CreateSite {
community_creation_admin_only: data.community_creation_admin_only, community_creation_admin_only: data.community_creation_admin_only,
}; };
let create_site = move |conn: &'_ _| Site::create(conn, &site_form); let create_site = Site::create(&&context.pool.get().await?, &site_form);
if blocking(context.pool(), create_site).await?.is_err() { if create_site.is_err() {
return Err(ApiError::err("site_already_exists").into()); return Err(ApiError::err("site_already_exists").into());
} }
let site_view = blocking(context.pool(), move |conn| SiteView::read(conn)).await??; let site_view = SiteView::read(&&context.pool.get().await?)?;
Ok(SiteResponse { site_view }) Ok(SiteResponse { site_view })
} }

View file

@ -1,7 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
build_federated_instances, build_federated_instances,
get_local_user_settings_view_from_jwt_opt, get_local_user_settings_view_from_jwt_opt,
person::Register, person::Register,
@ -30,7 +29,7 @@ impl PerformCrud for GetSite {
) -> Result<GetSiteResponse, LemmyError> { ) -> Result<GetSiteResponse, LemmyError> {
let data: &GetSite = self; let data: &GetSite = self;
let site_view = match blocking(context.pool(), move |conn| SiteView::read(conn)).await? { let site_view = match SiteView::read(&&context.pool.get().await?) {
Ok(site_view) => Some(site_view), Ok(site_view) => Some(site_view),
// If the site isn't created yet, check the setup // If the site isn't created yet, check the setup
Err(_) => { Err(_) => {
@ -61,14 +60,14 @@ impl PerformCrud for GetSite {
}; };
create_site.perform(context, websocket_id).await?; create_site.perform(context, websocket_id).await?;
info!("Site {} created", setup.site_name); info!("Site {} created", setup.site_name);
Some(blocking(context.pool(), move |conn| SiteView::read(conn)).await??) Some(SiteView::read(&&context.pool.get().await?)?)
} else { } else {
None None
} }
} }
}; };
let mut admins = blocking(context.pool(), move |conn| PersonViewSafe::admins(conn)).await??; let mut admins = PersonViewSafe::admins(&&context.pool.get().await?)?;
// Make sure the site creator is the top admin // Make sure the site creator is the top admin
if let Some(site_view) = site_view.to_owned() { if let Some(site_view) = site_view.to_owned() {
@ -81,7 +80,7 @@ impl PerformCrud for GetSite {
} }
} }
let banned = blocking(context.pool(), move |conn| PersonViewSafe::banned(conn)).await??; let banned = PersonViewSafe::banned(&&context.pool.get().await?)?;
let online = context let online = context
.chat_server() .chat_server()
@ -94,31 +93,19 @@ impl PerformCrud for GetSite {
get_local_user_settings_view_from_jwt_opt(&data.auth, context.pool()).await? get_local_user_settings_view_from_jwt_opt(&data.auth, context.pool()).await?
{ {
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let follows = blocking(context.pool(), move |conn| { let follows = CommunityFollowerView::for_person(&&context.pool.get().await?, person_id)
CommunityFollowerView::for_person(conn, person_id) .map_err(|_| ApiError::err("system_err_login"))?;
})
.await?
.map_err(|_| ApiError::err("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.get().await?, person_id)
CommunityBlockView::for_person(conn, person_id) .map_err(|_| ApiError::err("system_err_login"))?;
})
.await?
.map_err(|_| ApiError::err("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.get().await?, person_id)
PersonBlockView::for_person(conn, person_id) .map_err(|_| ApiError::err("system_err_login"))?;
})
.await?
.map_err(|_| ApiError::err("system_err_login"))?;
let moderates = blocking(context.pool(), move |conn| { let moderates = CommunityModeratorView::for_person(&&context.pool.get().await?, person_id)
CommunityModeratorView::for_person(conn, person_id) .map_err(|_| ApiError::err("system_err_login"))?;
})
.await?
.map_err(|_| ApiError::err("system_err_login"))?;
Some(MyUserInfo { Some(MyUserInfo {
local_user_view, local_user_view,

View file

@ -1,7 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
is_admin, is_admin,
site::{EditSite, SiteResponse}, site::{EditSite, SiteResponse},
@ -38,7 +37,7 @@ impl PerformCrud for EditSite {
// Make sure user is an admin // Make sure user is an admin
is_admin(&local_user_view)?; is_admin(&local_user_view)?;
let found_site = blocking(context.pool(), move |conn| Site::read_simple(conn)).await??; let found_site = Site::read_simple(&&context.pool.get().await?)?;
let sidebar = diesel_option_overwrite(&data.sidebar); let sidebar = diesel_option_overwrite(&data.sidebar);
let description = diesel_option_overwrite(&data.description); let description = diesel_option_overwrite(&data.description);
@ -63,12 +62,12 @@ impl PerformCrud for EditSite {
community_creation_admin_only: data.community_creation_admin_only, community_creation_admin_only: data.community_creation_admin_only,
}; };
let update_site = move |conn: &'_ _| Site::update(conn, 1, &site_form); let update_site = Site::update(&&context.pool.get().await?, 1, &site_form);
if blocking(context.pool(), update_site).await?.is_err() { if update_site.is_err() {
return Err(ApiError::err("couldnt_update_site").into()); return Err(ApiError::err("couldnt_update_site").into());
} }
let site_view = blocking(context.pool(), move |conn| SiteView::read(conn)).await??; let site_view = SiteView::read(&&context.pool.get().await?)?;
let res = SiteResponse { site_view }; let res = SiteResponse { site_view };

View file

@ -1,6 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{blocking, password_length_check, person::*}; use lemmy_api_common::{password_length_check, person::*};
use lemmy_apub::{ use lemmy_apub::{
generate_apub_endpoint, generate_apub_endpoint,
generate_followers_url, generate_followers_url,
@ -49,7 +49,7 @@ impl PerformCrud for Register {
let data: &Register = self; let data: &Register = self;
// Make sure site has open registration // Make sure site has open registration
if let Ok(site) = blocking(context.pool(), move |conn| Site::read_simple(conn)).await? { if let Ok(site) = Site::read_simple(&&context.pool.get().await?) {
if !site.open_registration { if !site.open_registration {
return Err(ApiError::err("registration_closed").into()); return Err(ApiError::err("registration_closed").into());
} }
@ -63,10 +63,7 @@ impl PerformCrud for Register {
} }
// Check if there are admins. False if admins exist // Check if there are admins. False if admins exist
let no_admins = blocking(context.pool(), move |conn| { let no_admins = PersonViewSafe::admins(&&context.pool.get().await?).map(|a| a.is_empty())?;
PersonViewSafe::admins(conn).map(|a| a.is_empty())
})
.await??;
// If its not the admin, check the captcha // If its not the admin, check the captcha
if !no_admins && Settings::get().captcha.enabled { if !no_admins && Settings::get().captcha.enabled {
@ -111,11 +108,8 @@ impl PerformCrud for Register {
}; };
// insert the person // insert the person
let inserted_person = blocking(context.pool(), move |conn| { let inserted_person = Person::create(&&context.pool.get().await?, &person_form)
Person::create(conn, &person_form) .map_err(|_| ApiError::err("user_already_exists"))?;
})
.await?
.map_err(|_| ApiError::err("user_already_exists"))?;
// Create the local user // Create the local user
// TODO some of these could probably use the DB defaults // TODO some of these could probably use the DB defaults
@ -136,39 +130,29 @@ impl PerformCrud for Register {
send_notifications_to_email: Some(false), send_notifications_to_email: Some(false),
}; };
let inserted_local_user = match blocking(context.pool(), move |conn| { let inserted_local_user =
LocalUser::register(conn, &local_user_form) match LocalUser::register(&&context.pool.get().await?, &local_user_form) {
}) Ok(lu) => lu,
.await? Err(e) => {
{ let err_type = if e.to_string()
Ok(lu) => lu, == "duplicate key value violates unique constraint \"local_user_email_key\""
Err(e) => { {
let err_type = if e.to_string() "email_already_exists"
== "duplicate key value violates unique constraint \"local_user_email_key\"" } else {
{ "user_already_exists"
"email_already_exists" };
} else {
"user_already_exists"
};
// 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.get().await?, inserted_person.id)?;
Person::delete(conn, inserted_person.id)
})
.await??;
return Err(ApiError::err(err_type).into()); return Err(ApiError::err(err_type).into());
} }
}; };
let main_community_keypair = generate_actor_keypair()?; let main_community_keypair = generate_actor_keypair()?;
// Create the main community if it doesn't exist // Create the main community if it doesn't exist
let main_community = match blocking(context.pool(), move |conn| { let main_community = match Community::read(&&context.pool.get().await?, CommunityId(2)) {
Community::read(conn, CommunityId(2))
})
.await?
{
Ok(c) => c, Ok(c) => c,
Err(_e) => { Err(_e) => {
let default_community_name = "main"; let default_community_name = "main";
@ -185,10 +169,7 @@ impl PerformCrud for Register {
shared_inbox_url: Some(Some(generate_shared_inbox_url(&actor_id)?)), shared_inbox_url: Some(Some(generate_shared_inbox_url(&actor_id)?)),
..CommunityForm::default() ..CommunityForm::default()
}; };
blocking(context.pool(), move |conn| { Community::create(&&context.pool.get().await?, &community_form)?
Community::create(conn, &community_form)
})
.await??
} }
}; };
@ -199,8 +180,8 @@ impl PerformCrud for Register {
pending: false, pending: false,
}; };
let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form); let follow = CommunityFollower::follow(&&context.pool.get().await?, &community_follower_form);
if blocking(context.pool(), follow).await?.is_err() { if follow.is_err() {
return Err(ApiError::err("community_follower_already_exists").into()); return Err(ApiError::err("community_follower_already_exists").into());
}; };
@ -211,8 +192,8 @@ impl PerformCrud for Register {
person_id: inserted_person.id, person_id: inserted_person.id,
}; };
let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form); let join = CommunityModerator::join(&&context.pool.get().await?, &community_moderator_form);
if blocking(context.pool(), join).await?.is_err() { if join.is_err() {
return Err(ApiError::err("community_moderator_already_exists").into()); return Err(ApiError::err("community_moderator_already_exists").into());
} }
} }

View file

@ -1,7 +1,7 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use bcrypt::verify; use bcrypt::verify;
use lemmy_api_common::{blocking, get_local_user_view_from_jwt, person::*}; use lemmy_api_common::{get_local_user_view_from_jwt, person::*};
use lemmy_db_queries::source::{comment::Comment_, person::Person_, post::Post_}; use lemmy_db_queries::source::{comment::Comment_, person::Person_, post::Post_};
use lemmy_db_schema::source::{comment::Comment, person::*, post::Post}; use lemmy_db_schema::source::{comment::Comment, person::*, post::Post};
use lemmy_utils::{ApiError, ConnectionId, LemmyError}; use lemmy_utils::{ApiError, ConnectionId, LemmyError};
@ -31,21 +31,18 @@ impl PerformCrud for DeleteAccount {
// Comments // Comments
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let permadelete = move |conn: &'_ _| Comment::permadelete_for_creator(conn, person_id); let permadelete = Comment::permadelete_for_creator(&&context.pool.get().await?, person_id);
if blocking(context.pool(), permadelete).await?.is_err() { if permadelete.is_err() {
return Err(ApiError::err("couldnt_update_comment").into()); return Err(ApiError::err("couldnt_update_comment").into());
} }
// Posts // Posts
let permadelete = move |conn: &'_ _| Post::permadelete_for_creator(conn, person_id); let permadelete = Post::permadelete_for_creator(&&context.pool.get().await?, person_id);
if blocking(context.pool(), permadelete).await?.is_err() { if permadelete.is_err() {
return Err(ApiError::err("couldnt_update_post").into()); return Err(ApiError::err("couldnt_update_post").into());
} }
blocking(context.pool(), move |conn| { Person::delete_account(&&context.pool.get().await?, person_id)?;
Person::delete_account(conn, person_id)
})
.await??;
Ok(LoginResponse { Ok(LoginResponse {
jwt: data.auth.to_owned(), jwt: data.auth.to_owned(),

View file

@ -1,6 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{blocking, get_local_user_view_from_jwt_opt, person::*}; use lemmy_api_common::{get_local_user_view_from_jwt_opt, person::*};
use lemmy_apub::{build_actor_id_from_shortname, EndpointType}; use lemmy_apub::{build_actor_id_from_shortname, EndpointType};
use lemmy_db_queries::{from_opt_str_to_opt_enum, ApubObject, SortType}; use lemmy_db_queries::{from_opt_str_to_opt_enum, ApubObject, SortType};
use lemmy_db_schema::source::person::*; use lemmy_db_schema::source::person::*;
@ -43,31 +43,24 @@ impl PerformCrud for GetPersonDetails {
.unwrap_or_else(|| "admin".to_string()); .unwrap_or_else(|| "admin".to_string());
let actor_id = build_actor_id_from_shortname(EndpointType::Person, &name)?; let actor_id = build_actor_id_from_shortname(EndpointType::Person, &name)?;
let person = blocking(context.pool(), move |conn| { let person = Person::read_from_apub_id(&&context.pool.get().await?, &actor_id)
Person::read_from_apub_id(conn, &actor_id) .map_err(|_| ApiError::err("couldnt_find_that_username_or_email"))?;
}) person.id
.await?;
person
.map_err(|_| ApiError::err("couldnt_find_that_username_or_email"))?
.id
} }
}; };
let person_id = local_user_view.map(|uv| uv.person.id); let person_id = local_user_view.map(|uv| uv.person.id);
// 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` let person_view = PersonViewSafe::read(&&context.pool.get().await?, person_details_id)?;
let person_view = blocking(context.pool(), move |conn| {
PersonViewSafe::read(conn, person_details_id)
})
.await??;
let page = data.page; let page = data.page;
let limit = data.limit; let limit = data.limit;
let saved_only = data.saved_only; let saved_only = data.saved_only;
let community_id = data.community_id; let community_id = data.community_id;
let (posts, comments) = blocking(context.pool(), move |conn| { let (posts, comments) = {
let conn = &&context.pool.get().await?;
let mut posts_query = PostQueryBuilder::create(conn) let mut posts_query = PostQueryBuilder::create(conn)
.sort(sort) .sort(sort)
.show_nsfw(show_nsfw) .show_nsfw(show_nsfw)
@ -79,7 +72,8 @@ impl PerformCrud for GetPersonDetails {
.page(page) .page(page)
.limit(limit); .limit(limit);
let mut comments_query = CommentQueryBuilder::create(conn) let conn2 = &&context.pool.get().await?;
let mut comments_query = CommentQueryBuilder::create(conn2)
.my_person_id(person_id) .my_person_id(person_id)
.show_bot_accounts(show_bot_accounts) .show_bot_accounts(show_bot_accounts)
.sort(sort) .sort(sort)
@ -98,14 +92,11 @@ impl PerformCrud for GetPersonDetails {
let posts = posts_query.list()?; let posts = posts_query.list()?;
let comments = comments_query.list()?; let comments = comments_query.list()?;
Ok((posts, comments)) as Result<_, LemmyError> (posts, comments)
}) };
.await??;
let moderates = blocking(context.pool(), move |conn| { let moderates =
CommunityModeratorView::for_person(conn, person_details_id) CommunityModeratorView::for_person(&&context.pool.get().await?, person_details_id)?;
})
.await??;
// Return the jwt // Return the jwt
Ok(GetPersonDetailsResponse { Ok(GetPersonDetailsResponse {

View file

@ -14,7 +14,6 @@ use crate::{
ActorType, ActorType,
}; };
use activitystreams::{base::AnyBase, link::Mention, primitives::OneOrMany, unparsed::Unparsed}; use activitystreams::{base::AnyBase, link::Mention, primitives::OneOrMany, unparsed::Unparsed};
use lemmy_api_common::blocking;
use lemmy_apub_lib::{values::PublicUrl, verify_domains_match, ActivityFields, ActivityHandler}; use lemmy_apub_lib::{values::PublicUrl, verify_domains_match, ActivityFields, ActivityHandler};
use lemmy_db_queries::Crud; use lemmy_db_queries::Crud;
use lemmy_db_schema::source::{comment::Comment, community::Community, person::Person, post::Post}; use lemmy_db_schema::source::{comment::Comment, community::Community, person::Person, post::Post};
@ -49,12 +48,9 @@ impl CreateOrUpdateComment {
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
// TODO: might be helpful to add a comment method to retrieve community directly // TODO: might be helpful to add a comment method to retrieve community directly
let post_id = comment.post_id; let post_id = comment.post_id;
let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; let post = Post::read(&&context.pool.get().await?, post_id)?;
let community_id = post.community_id; let community_id = post.community_id;
let community = blocking(context.pool(), move |conn| { let community = Community::read(&&context.pool.get().await?, community_id)?;
Community::read(conn, community_id)
})
.await??;
let id = generate_activity_id(kind.clone())?; let id = generate_activity_id(kind.clone())?;
let maa = collect_non_local_mentions(comment, &community, context).await?; let maa = collect_non_local_mentions(comment, &community, context).await?;

View file

@ -5,7 +5,7 @@ use activitystreams::{
}; };
use anyhow::anyhow; use anyhow::anyhow;
use itertools::Itertools; use itertools::Itertools;
use lemmy_api_common::{blocking, send_local_notifs, WebFingerResponse}; use lemmy_api_common::{send_local_notifs, WebFingerResponse};
use lemmy_db_queries::{Crud, DbPool}; use lemmy_db_queries::{Crud, DbPool};
use lemmy_db_schema::{ use lemmy_db_schema::{
source::{comment::Comment, community::Community, person::Person, post::Post}, source::{comment::Comment, community::Community, person::Person, post::Post},
@ -31,7 +31,7 @@ async fn get_notif_recipients(
request_counter: &mut i32, request_counter: &mut i32,
) -> Result<Vec<LocalUserId>, LemmyError> { ) -> Result<Vec<LocalUserId>, LemmyError> {
let post_id = comment.post_id; let post_id = comment.post_id;
let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; let post = Post::read(&&context.pool.get().await?, post_id)?;
let actor = get_or_fetch_and_upsert_person(actor, context, request_counter).await?; let actor = get_or_fetch_and_upsert_person(actor, context, request_counter).await?;
// Note: // Note:
@ -103,15 +103,14 @@ async fn get_comment_parent_creator(
comment: &Comment, comment: &Comment,
) -> Result<Person, LemmyError> { ) -> Result<Person, LemmyError> {
let parent_creator_id = if let Some(parent_comment_id) = comment.parent_id { let parent_creator_id = if let Some(parent_comment_id) = comment.parent_id {
let parent_comment = let parent_comment = Comment::read(&&pool.get().await?, parent_comment_id)?;
blocking(pool, move |conn| Comment::read(conn, parent_comment_id)).await??;
parent_comment.creator_id parent_comment.creator_id
} else { } else {
let parent_post_id = comment.post_id; let parent_post_id = comment.post_id;
let parent_post = blocking(pool, move |conn| Post::read(conn, parent_post_id)).await??; let parent_post = Post::read(&&pool.get().await?, parent_post_id)?;
parent_post.creator_id parent_post.creator_id
}; };
Ok(blocking(pool, move |conn| Person::read(conn, parent_creator_id)).await??) Ok(Person::read(&&pool.get().await?, parent_creator_id)?)
} }
/// Turns a person id like `@name@example.com` into an apub ID, like `https://example.com/user/name`, /// Turns a person id like `@name@example.com` into an apub ID, like `https://example.com/user/name`,

View file

@ -19,7 +19,6 @@ use activitystreams::{
primitives::OneOrMany, primitives::OneOrMany,
unparsed::Unparsed, unparsed::Unparsed,
}; };
use lemmy_api_common::blocking;
use lemmy_apub_lib::{values::PublicUrl, ActivityFields, ActivityHandler}; use lemmy_apub_lib::{values::PublicUrl, ActivityFields, ActivityHandler};
use lemmy_db_queries::{source::community::CommunityModerator_, Joinable}; use lemmy_db_queries::{source::community::CommunityModerator_, Joinable};
use lemmy_db_schema::source::{ use lemmy_db_schema::source::{
@ -100,19 +99,16 @@ impl ActivityHandler for AddMod {
// 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(
CommunityModerator::get_person_moderated_communities(conn, new_mod_id) &&context.pool.get().await?,
}) new_mod_id,
.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.get().await?, &form)?;
CommunityModerator::join(conn, &form)
})
.await??;
} }
// TODO: send websocket notification about added mod // TODO: send websocket notification about added mod
Ok(()) Ok(())

View file

@ -17,7 +17,6 @@ use activitystreams::{
primitives::OneOrMany, primitives::OneOrMany,
unparsed::Unparsed, unparsed::Unparsed,
}; };
use lemmy_api_common::blocking;
use lemmy_apub_lib::{values::PublicUrl, ActivityFields, ActivityHandler}; use lemmy_apub_lib::{values::PublicUrl, ActivityFields, ActivityHandler};
use lemmy_db_queries::{Bannable, Followable}; use lemmy_db_queries::{Bannable, Followable};
use lemmy_db_schema::source::{ use lemmy_db_schema::source::{
@ -112,10 +111,7 @@ impl ActivityHandler for BlockUserFromCommunity {
person_id: blocked_user.id, person_id: blocked_user.id,
}; };
blocking(context.pool(), move |conn: &'_ _| { CommunityPersonBan::ban(&&context.pool.get().await?, &community_user_ban_form)?;
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 {
@ -123,11 +119,7 @@ impl ActivityHandler for BlockUserFromCommunity {
person_id: blocked_user.id, person_id: blocked_user.id,
pending: false, pending: false,
}; };
blocking(context.pool(), move |conn: &'_ _| { CommunityFollower::unfollow(&&context.pool.get().await?, &community_follower_form).ok();
CommunityFollower::unfollow(conn, &community_follower_form)
})
.await?
.ok();
Ok(()) Ok(())
} }

View file

@ -20,7 +20,6 @@ use activitystreams::{
primitives::OneOrMany, primitives::OneOrMany,
unparsed::Unparsed, unparsed::Unparsed,
}; };
use lemmy_api_common::blocking;
use lemmy_apub_lib::{values::PublicUrl, ActivityFields, ActivityHandler}; use lemmy_apub_lib::{values::PublicUrl, ActivityFields, ActivityHandler};
use lemmy_db_queries::Joinable; use lemmy_db_queries::Joinable;
use lemmy_db_schema::source::{ use lemmy_db_schema::source::{
@ -117,10 +116,7 @@ impl ActivityHandler for RemoveMod {
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.get().await?, &form)?;
CommunityModerator::leave(conn, &form)
})
.await??;
// TODO: send websocket notification about removed mod // TODO: send websocket notification about removed mod
Ok(()) Ok(())
} else { } else {

View file

@ -17,7 +17,6 @@ use activitystreams::{
primitives::OneOrMany, primitives::OneOrMany,
unparsed::Unparsed, unparsed::Unparsed,
}; };
use lemmy_api_common::blocking;
use lemmy_apub_lib::{values::PublicUrl, ActivityFields, ActivityHandler}; use lemmy_apub_lib::{values::PublicUrl, ActivityFields, ActivityHandler};
use lemmy_db_queries::Bannable; use lemmy_db_queries::Bannable;
use lemmy_db_schema::source::{ use lemmy_db_schema::source::{
@ -101,10 +100,7 @@ impl ActivityHandler for UndoBlockUserFromCommunity {
person_id: blocked_user.id, person_id: blocked_user.id,
}; };
blocking(context.pool(), move |conn: &'_ _| { CommunityPersonBan::unban(&&context.pool.get().await?, &community_user_ban_form)?;
CommunityPersonBan::unban(conn, &community_user_ban_form)
})
.await??;
Ok(()) Ok(())
} }

View file

@ -17,7 +17,6 @@ use activitystreams::{
primitives::OneOrMany, primitives::OneOrMany,
unparsed::Unparsed, unparsed::Unparsed,
}; };
use lemmy_api_common::blocking;
use lemmy_apub_lib::{values::PublicUrl, ActivityFields, ActivityHandler}; use lemmy_apub_lib::{values::PublicUrl, ActivityFields, ActivityHandler};
use lemmy_db_queries::{ApubObject, Crud}; use lemmy_db_queries::{ApubObject, Crud};
use lemmy_db_schema::source::{ use lemmy_db_schema::source::{
@ -90,10 +89,7 @@ impl ActivityHandler for UpdateCommunity {
_request_counter: &mut i32, _request_counter: &mut i32,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let cc = self.cc[0].clone().into(); let cc = self.cc[0].clone().into();
let community = blocking(context.pool(), move |conn| { let community = Community::read_from_apub_id(&&context.pool.get().await?, &cc)?;
Community::read_from_apub_id(conn, &cc)
})
.await??;
let updated_community = let updated_community =
Group::from_apub_to_form(&self.object, &community.actor_id.clone().into()).await?; Group::from_apub_to_form(&self.object, &community.actor_id.clone().into()).await?;
@ -107,10 +103,7 @@ impl ActivityHandler for UpdateCommunity {
banner: updated_community.banner, banner: updated_community.banner,
..CommunityForm::default() ..CommunityForm::default()
}; };
let updated_community = blocking(context.pool(), move |conn| { let updated_community = Community::update(&&context.pool.get().await?, community.id, &cf)?;
Community::update(conn, community.id, &cf)
})
.await??;
send_community_ws_message( send_community_ws_message(
updated_community.id, updated_community.id,

View file

@ -22,7 +22,6 @@ use activitystreams::{
unparsed::Unparsed, unparsed::Unparsed,
}; };
use anyhow::anyhow; use anyhow::anyhow;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{values::PublicUrl, ActivityFields, ActivityHandler}; use lemmy_apub_lib::{values::PublicUrl, ActivityFields, ActivityHandler};
use lemmy_db_queries::{ use lemmy_db_queries::{
source::{comment::Comment_, community::Community_, post::Post_}, source::{comment::Comment_, community::Community_, post::Post_},
@ -185,14 +184,9 @@ pub(in crate::activities) async fn receive_remove_action(
reason, reason,
expires: None, expires: None,
}; };
blocking(context.pool(), move |conn| { ModRemoveCommunity::create(&&context.pool.get().await?, &form)?;
ModRemoveCommunity::create(conn, &form) let deleted_community =
}) Community::update_removed(&&context.pool.get().await?, community.id, true)?;
.await??;
let deleted_community = blocking(context.pool(), move |conn| {
Community::update_removed(conn, community.id, true)
})
.await??;
send_community_ws_message(deleted_community.id, RemoveCommunity, None, None, context).await?; send_community_ws_message(deleted_community.id, RemoveCommunity, None, None, context).await?;
} }
@ -203,14 +197,8 @@ pub(in crate::activities) async fn receive_remove_action(
removed: Some(true), removed: Some(true),
reason, reason,
}; };
blocking(context.pool(), move |conn| { ModRemovePost::create(&&context.pool.get().await?, &form)?;
ModRemovePost::create(conn, &form) let removed_post = Post::update_removed(&&context.pool.get().await?, post.id, true)?;
})
.await??;
let removed_post = blocking(context.pool(), move |conn| {
Post::update_removed(conn, post.id, true)
})
.await??;
send_post_ws_message(removed_post.id, RemovePost, None, None, context).await?; send_post_ws_message(removed_post.id, RemovePost, None, None, context).await?;
} }
@ -221,14 +209,8 @@ pub(in crate::activities) async fn receive_remove_action(
removed: Some(true), removed: Some(true),
reason, reason,
}; };
blocking(context.pool(), move |conn| { ModRemoveComment::create(&&context.pool.get().await?, &form)?;
ModRemoveComment::create(conn, &form) let removed_comment = Comment::update_removed(&&context.pool.get().await?, comment.id, true)?;
})
.await??;
let removed_comment = blocking(context.pool(), move |conn| {
Comment::update_removed(conn, comment.id, true)
})
.await??;
send_comment_ws_message_simple(removed_comment.id, RemoveComment, context).await?; send_comment_ws_message_simple(removed_comment.id, RemoveComment, context).await?;
} }

View file

@ -7,7 +7,6 @@ use crate::{
fetcher::person::get_or_fetch_and_upsert_person, fetcher::person::get_or_fetch_and_upsert_person,
ActorType, ActorType,
}; };
use lemmy_api_common::blocking;
use lemmy_apub_lib::{verify_domains_match, ActivityFields}; use lemmy_apub_lib::{verify_domains_match, ActivityFields};
use lemmy_db_queries::{ use lemmy_db_queries::{
source::{comment::Comment_, community::Community_, post::Post_}, source::{comment::Comment_, community::Community_, post::Post_},
@ -89,10 +88,7 @@ impl DeletableObjects {
ap_id: DbUrl, ap_id: DbUrl,
context: &LemmyContext, context: &LemmyContext,
) -> Result<Option<Type>, LemmyError> { ) -> Result<Option<Type>, LemmyError> {
blocking(context.pool(), move |conn| { Ok(Type::read_from_apub_id(&&context.pool.get().await?, &ap_id).ok())
Type::read_from_apub_id(conn, &ap_id).ok()
})
.await
} }
} }
@ -185,24 +181,17 @@ async fn receive_delete_action(
send_apub_delete(&mod_, &community.clone(), object, true, context).await?; send_apub_delete(&mod_, &community.clone(), object, true, context).await?;
} }
let community = blocking(context.pool(), move |conn| { let community =
Community::update_deleted(conn, community.id, deleted) Community::update_deleted(&&context.pool.get().await?, community.id, deleted)?;
})
.await??;
send_community_ws_message(community.id, ws_messages.community, None, None, context).await?; send_community_ws_message(community.id, ws_messages.community, None, None, context).await?;
} }
DeletableObjects::Post(post) => { DeletableObjects::Post(post) => {
let deleted_post = blocking(context.pool(), move |conn| { let deleted_post = Post::update_deleted(&&context.pool.get().await?, post.id, deleted)?;
Post::update_deleted(conn, post.id, deleted)
})
.await??;
send_post_ws_message(deleted_post.id, ws_messages.post, None, None, context).await?; send_post_ws_message(deleted_post.id, ws_messages.post, None, None, context).await?;
} }
DeletableObjects::Comment(comment) => { DeletableObjects::Comment(comment) => {
let deleted_comment = blocking(context.pool(), move |conn| { let deleted_comment =
Comment::update_deleted(conn, comment.id, deleted) Comment::update_deleted(&&context.pool.get().await?, comment.id, deleted)?;
})
.await??;
send_comment_ws_message_simple(deleted_comment.id, ws_messages.comment, context).await?; send_comment_ws_message_simple(deleted_comment.id, ws_messages.comment, context).await?;
} }
} }

View file

@ -22,7 +22,6 @@ use activitystreams::{
unparsed::Unparsed, unparsed::Unparsed,
}; };
use anyhow::anyhow; use anyhow::anyhow;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{values::PublicUrl, ActivityFields, ActivityHandler}; use lemmy_apub_lib::{values::PublicUrl, ActivityFields, ActivityHandler};
use lemmy_db_queries::source::{comment::Comment_, community::Community_, post::Post_}; use lemmy_db_queries::source::{comment::Comment_, community::Community_, post::Post_};
use lemmy_db_schema::source::{comment::Comment, community::Community, person::Person, post::Post}; use lemmy_db_schema::source::{comment::Comment, community::Community, person::Person, post::Post};
@ -133,24 +132,17 @@ impl UndoDelete {
if community.local { if community.local {
return Err(anyhow!("Only local admin can restore community").into()); return Err(anyhow!("Only local admin can restore community").into());
} }
let deleted_community = blocking(context.pool(), move |conn| { let deleted_community =
Community::update_removed(conn, community.id, false) Community::update_removed(&&context.pool.get().await?, community.id, false)?;
})
.await??;
send_community_ws_message(deleted_community.id, EditCommunity, None, None, context).await?; send_community_ws_message(deleted_community.id, EditCommunity, None, None, context).await?;
} }
DeletableObjects::Post(post) => { DeletableObjects::Post(post) => {
let removed_post = blocking(context.pool(), move |conn| { let removed_post = Post::update_removed(&&context.pool.get().await?, post.id, false)?;
Post::update_removed(conn, post.id, false)
})
.await??;
send_post_ws_message(removed_post.id, EditPost, None, None, context).await?; send_post_ws_message(removed_post.id, EditPost, None, None, context).await?;
} }
DeletableObjects::Comment(comment) => { DeletableObjects::Comment(comment) => {
let removed_comment = blocking(context.pool(), move |conn| { let removed_comment =
Comment::update_removed(conn, comment.id, false) Comment::update_removed(&&context.pool.get().await?, comment.id, false)?;
})
.await??;
send_comment_ws_message_simple(removed_comment.id, EditComment, context).await?; send_comment_ws_message_simple(removed_comment.id, EditComment, context).await?;
} }
} }

View file

@ -16,7 +16,6 @@ use activitystreams::{
primitives::OneOrMany, primitives::OneOrMany,
unparsed::Unparsed, unparsed::Unparsed,
}; };
use lemmy_api_common::blocking;
use lemmy_apub_lib::{verify_urls_match, ActivityFields, ActivityHandler}; use lemmy_apub_lib::{verify_urls_match, ActivityFields, ActivityHandler};
use lemmy_db_queries::{ApubObject, Followable}; use lemmy_db_queries::{ApubObject, Followable};
use lemmy_db_schema::source::{ use lemmy_db_schema::source::{
@ -46,15 +45,10 @@ pub struct AcceptFollowCommunity {
impl AcceptFollowCommunity { impl AcceptFollowCommunity {
pub async fn send(follow: FollowCommunity, context: &LemmyContext) -> Result<(), LemmyError> { pub async fn send(follow: FollowCommunity, context: &LemmyContext) -> Result<(), LemmyError> {
let community_id = follow.object.clone(); let community_id = follow.object.clone();
let community = blocking(context.pool(), move |conn| { let community =
Community::read_from_apub_id(conn, &community_id.into()) Community::read_from_apub_id(&&context.pool.get().await?, &community_id.into())?;
})
.await??;
let person_id = follow.actor().clone(); let person_id = follow.actor().clone();
let person = blocking(context.pool(), move |conn| { let person = Person::read_from_apub_id(&&context.pool.get().await?, &person_id.into())?;
Person::read_from_apub_id(conn, &person_id.into())
})
.await??;
let accept = AcceptFollowCommunity { let accept = AcceptFollowCommunity {
actor: community.actor_id(), actor: community.actor_id(),
@ -93,10 +87,7 @@ impl ActivityHandler for AcceptFollowCommunity {
let actor = get_or_fetch_and_upsert_community(&self.actor, context, request_counter).await?; let actor = get_or_fetch_and_upsert_community(&self.actor, context, request_counter).await?;
let to = get_or_fetch_and_upsert_person(&self.to, context, request_counter).await?; let to = get_or_fetch_and_upsert_person(&self.to, context, request_counter).await?;
// This will throw an error if no follow was requested // This will throw an error if no follow was requested
blocking(context.pool(), move |conn| { CommunityFollower::follow_accepted(&&context.pool.get().await?, actor.id, to.id)?;
CommunityFollower::follow_accepted(conn, actor.id, to.id)
})
.await??;
Ok(()) Ok(())
} }

View file

@ -16,7 +16,6 @@ use activitystreams::{
primitives::OneOrMany, primitives::OneOrMany,
unparsed::Unparsed, unparsed::Unparsed,
}; };
use lemmy_api_common::blocking;
use lemmy_apub_lib::{verify_urls_match, ActivityFields, ActivityHandler}; use lemmy_apub_lib::{verify_urls_match, ActivityFields, ActivityHandler};
use lemmy_db_queries::Followable; use lemmy_db_queries::Followable;
use lemmy_db_schema::source::{ use lemmy_db_schema::source::{
@ -68,10 +67,7 @@ impl FollowCommunity {
person_id: actor.id, person_id: actor.id,
pending: true, pending: true,
}; };
blocking(context.pool(), move |conn| { CommunityFollower::follow(&&context.pool.get().await?, &community_follower_form).ok();
CommunityFollower::follow(conn, &community_follower_form).ok()
})
.await?;
let follow = FollowCommunity::new(actor, community)?; let follow = FollowCommunity::new(actor, community)?;
let inbox = vec![community.inbox_url.clone().into()]; let inbox = vec![community.inbox_url.clone().into()];
@ -107,10 +103,7 @@ impl ActivityHandler for FollowCommunity {
}; };
// This will fail if they're already a follower, but ignore the error. // This will fail if they're already a follower, but ignore the error.
blocking(context.pool(), move |conn| { CommunityFollower::follow(&&context.pool.get().await?, &community_follower_form).ok();
CommunityFollower::follow(conn, &community_follower_form).ok()
})
.await?;
AcceptFollowCommunity::send(self, context).await AcceptFollowCommunity::send(self, context).await
} }

View file

@ -16,7 +16,6 @@ use activitystreams::{
primitives::OneOrMany, primitives::OneOrMany,
unparsed::Unparsed, unparsed::Unparsed,
}; };
use lemmy_api_common::blocking;
use lemmy_apub_lib::{verify_urls_match, ActivityFields, ActivityHandler}; use lemmy_apub_lib::{verify_urls_match, ActivityFields, ActivityHandler};
use lemmy_db_queries::Followable; use lemmy_db_queries::Followable;
use lemmy_db_schema::source::{ use lemmy_db_schema::source::{
@ -94,10 +93,7 @@ impl ActivityHandler for UndoFollowCommunity {
}; };
// This will fail if they aren't a follower, but ignore the error. // This will fail if they aren't a follower, but ignore the error.
blocking(context.pool(), move |conn| { CommunityFollower::unfollow(&&context.pool.get().await?, &community_follower_form).ok();
CommunityFollower::unfollow(conn, &community_follower_form).ok()
})
.await?;
Ok(()) Ok(())
} }
} }

View file

@ -5,7 +5,6 @@ use crate::{
generate_moderators_url, generate_moderators_url,
}; };
use anyhow::anyhow; use anyhow::anyhow;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{verify_domains_match, ActivityFields}; use lemmy_apub_lib::{verify_domains_match, ActivityFields};
use lemmy_db_queries::ApubObject; use lemmy_db_queries::ApubObject;
use lemmy_db_schema::{ use lemmy_db_schema::{
@ -104,26 +103,18 @@ pub(crate) async fn verify_mod_action(
community: Url, community: Url,
context: &LemmyContext, context: &LemmyContext,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let community = blocking(context.pool(), move |conn| { let community = Community::read_from_apub_id(&&context.pool.get().await?, &community.into())?;
Community::read_from_apub_id(conn, &community.into())
})
.await??;
if community.local { if community.local {
let actor_id: DbUrl = actor_id.clone().into(); let actor_id: DbUrl = actor_id.clone().into();
let actor = blocking(context.pool(), move |conn| { let actor = Person::read_from_apub_id(&&context.pool.get().await?, &actor_id)?;
Person::read_from_apub_id(conn, &actor_id)
})
.await??;
// Note: this will also return true for admins in addition to mods, but as we dont know about // Note: this will also return true for admins in addition to mods, but as we dont know about
// remote admins, it doesnt make any difference. // remote admins, it doesnt make any difference.
let community_id = community.id; let community_id = community.id;
let actor_id = actor.id; let actor_id = actor.id;
let is_mod_or_admin = blocking(context.pool(), move |conn| { let is_mod_or_admin =
CommunityView::is_mod_or_admin(conn, actor_id, community_id) CommunityView::is_mod_or_admin(&&context.pool.get().await?, actor_id, community_id);
})
.await?;
if !is_mod_or_admin { if !is_mod_or_admin {
return Err(anyhow!("Not a mod").into()); return Err(anyhow!("Not a mod").into());
} }

View file

@ -16,7 +16,6 @@ use crate::{
}; };
use activitystreams::{base::AnyBase, primitives::OneOrMany, unparsed::Unparsed}; use activitystreams::{base::AnyBase, primitives::OneOrMany, unparsed::Unparsed};
use anyhow::anyhow; use anyhow::anyhow;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
values::PublicUrl, values::PublicUrl,
verify_domains_match, verify_domains_match,
@ -55,10 +54,7 @@ impl CreateOrUpdatePost {
context: &LemmyContext, context: &LemmyContext,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let community_id = post.community_id; let community_id = post.community_id;
let community = blocking(context.pool(), move |conn| { let community = Community::read(&&context.pool.get().await?, community_id)?;
Community::read(conn, community_id)
})
.await??;
let id = generate_activity_id(kind.clone())?; let id = generate_activity_id(kind.clone())?;
let create_or_update = CreateOrUpdatePost { let create_or_update = CreateOrUpdatePost {

View file

@ -6,7 +6,6 @@ use crate::{
ActorType, ActorType,
}; };
use activitystreams::{base::AnyBase, primitives::OneOrMany, unparsed::Unparsed}; use activitystreams::{base::AnyBase, primitives::OneOrMany, unparsed::Unparsed};
use lemmy_api_common::blocking;
use lemmy_apub_lib::{verify_domains_match, ActivityFields, ActivityHandler}; use lemmy_apub_lib::{verify_domains_match, ActivityFields, ActivityHandler};
use lemmy_db_queries::Crud; use lemmy_db_queries::Crud;
use lemmy_db_schema::source::{person::Person, private_message::PrivateMessage}; use lemmy_db_schema::source::{person::Person, private_message::PrivateMessage};
@ -39,8 +38,7 @@ impl CreateOrUpdatePrivateMessage {
context: &LemmyContext, context: &LemmyContext,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let recipient_id = private_message.recipient_id; let recipient_id = private_message.recipient_id;
let recipient = let recipient = Person::read(&&context.pool.get().await?, recipient_id)?;
blocking(context.pool(), move |conn| Person::read(conn, recipient_id)).await??;
let id = generate_activity_id(kind.clone())?; let id = generate_activity_id(kind.clone())?;
let create_or_update = CreateOrUpdatePrivateMessage { let create_or_update = CreateOrUpdatePrivateMessage {

View file

@ -10,7 +10,6 @@ use activitystreams::{
primitives::OneOrMany, primitives::OneOrMany,
unparsed::Unparsed, unparsed::Unparsed,
}; };
use lemmy_api_common::blocking;
use lemmy_apub_lib::{verify_domains_match, ActivityFields, ActivityHandler}; use lemmy_apub_lib::{verify_domains_match, ActivityFields, ActivityHandler};
use lemmy_db_queries::{source::private_message::PrivateMessage_, ApubObject, Crud}; use lemmy_db_queries::{source::private_message::PrivateMessage_, ApubObject, Crud};
use lemmy_db_schema::source::{person::Person, private_message::PrivateMessage}; use lemmy_db_schema::source::{person::Person, private_message::PrivateMessage};
@ -58,8 +57,7 @@ impl DeletePrivateMessage {
let delete_id = delete.id.clone(); let delete_id = delete.id.clone();
let recipient_id = pm.recipient_id; let recipient_id = pm.recipient_id;
let recipient = let recipient = Person::read(&&context.pool.get().await?, recipient_id)?;
blocking(context.pool(), move |conn| Person::read(conn, recipient_id)).await??;
let inbox = vec![recipient.get_shared_inbox_or_inbox_url()]; let inbox = vec![recipient.get_shared_inbox_or_inbox_url()];
send_activity_new(context, &delete, &delete_id, actor, inbox, true).await send_activity_new(context, &delete, &delete_id, actor, inbox, true).await
} }
@ -84,14 +82,10 @@ impl ActivityHandler for DeletePrivateMessage {
_request_counter: &mut i32, _request_counter: &mut i32,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let ap_id = self.object.clone(); let ap_id = self.object.clone();
let private_message = blocking(context.pool(), move |conn| { let private_message =
PrivateMessage::read_from_apub_id(conn, &ap_id.into()) PrivateMessage::read_from_apub_id(&&context.pool.get().await?, &ap_id.into())?;
}) let deleted_private_message =
.await??; PrivateMessage::update_deleted(&&context.pool.get().await?, private_message.id, true)?;
let deleted_private_message = blocking(context.pool(), move |conn| {
PrivateMessage::update_deleted(conn, private_message.id, true)
})
.await??;
send_pm_ws_message( send_pm_ws_message(
deleted_private_message.id, deleted_private_message.id,

View file

@ -15,7 +15,6 @@ use activitystreams::{
primitives::OneOrMany, primitives::OneOrMany,
unparsed::Unparsed, unparsed::Unparsed,
}; };
use lemmy_api_common::blocking;
use lemmy_apub_lib::{verify_domains_match, verify_urls_match, ActivityFields, ActivityHandler}; use lemmy_apub_lib::{verify_domains_match, verify_urls_match, ActivityFields, ActivityHandler};
use lemmy_db_queries::{source::private_message::PrivateMessage_, ApubObject, Crud}; use lemmy_db_queries::{source::private_message::PrivateMessage_, ApubObject, Crud};
use lemmy_db_schema::source::{person::Person, private_message::PrivateMessage}; use lemmy_db_schema::source::{person::Person, private_message::PrivateMessage};
@ -46,8 +45,7 @@ impl UndoDeletePrivateMessage {
context: &LemmyContext, context: &LemmyContext,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let recipient_id = pm.recipient_id; let recipient_id = pm.recipient_id;
let recipient = let recipient = Person::read(&&context.pool.get().await?, recipient_id)?;
blocking(context.pool(), move |conn| Person::read(conn, recipient_id)).await??;
let object = DeletePrivateMessage::new(actor, pm)?; let object = DeletePrivateMessage::new(actor, pm)?;
let id = generate_activity_id(UndoType::Undo)?; let id = generate_activity_id(UndoType::Undo)?;
@ -86,15 +84,11 @@ impl ActivityHandler for UndoDeletePrivateMessage {
_request_counter: &mut i32, _request_counter: &mut i32,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let ap_id = self.object.object.clone(); let ap_id = self.object.object.clone();
let private_message = blocking(context.pool(), move |conn| { let private_message =
PrivateMessage::read_from_apub_id(conn, &ap_id.into()) PrivateMessage::read_from_apub_id(&&context.pool.get().await?, &ap_id.into())?;
})
.await??;
let deleted_private_message = blocking(context.pool(), move |conn| { let deleted_private_message =
PrivateMessage::update_deleted(conn, private_message.id, false) PrivateMessage::update_deleted(&&context.pool.get().await?, private_message.id, false)?;
})
.await??;
send_pm_ws_message( send_pm_ws_message(
deleted_private_message.id, deleted_private_message.id,

View file

@ -1,6 +1,5 @@
use crate::{check_is_apub_id_valid, ActorType, CommunityType}; use crate::{check_is_apub_id_valid, ActorType, CommunityType};
use itertools::Itertools; use itertools::Itertools;
use lemmy_api_common::blocking;
use lemmy_db_queries::DbPool; use lemmy_db_queries::DbPool;
use lemmy_db_schema::source::community::Community; use lemmy_db_schema::source::community::Community;
use lemmy_db_views_actor::community_follower_view::CommunityFollowerView; use lemmy_db_views_actor::community_follower_view::CommunityFollowerView;
@ -43,10 +42,7 @@ impl CommunityType for Community {
async fn get_follower_inboxes(&self, pool: &DbPool) -> Result<Vec<Url>, LemmyError> { async fn get_follower_inboxes(&self, pool: &DbPool) -> Result<Vec<Url>, LemmyError> {
let id = self.id; let id = self.id;
let follows = blocking(pool, move |conn| { let follows = CommunityFollowerView::for_community(&&pool.get().await?, id)?;
CommunityFollowerView::for_community(conn, id)
})
.await??;
let inboxes = follows let inboxes = follows
.into_iter() .into_iter()
.filter(|f| !f.follower.local) .filter(|f| !f.follower.local)

View file

@ -1,5 +1,4 @@
use crate::activities::voting::vote::VoteType; use crate::activities::voting::vote::VoteType;
use lemmy_api_common::blocking;
use lemmy_db_queries::Likeable; use lemmy_db_queries::Likeable;
use lemmy_db_schema::source::{ use lemmy_db_schema::source::{
comment::{Comment, CommentLike, CommentLikeForm}, comment::{Comment, CommentLike, CommentLikeForm},
@ -30,11 +29,8 @@ async fn vote_comment(
score: vote_type.into(), score: vote_type.into(),
}; };
let person_id = actor.id; let person_id = actor.id;
blocking(context.pool(), move |conn| { CommentLike::remove(&&context.pool.get().await?, person_id, comment_id)?;
CommentLike::remove(conn, person_id, comment_id)?; CommentLike::like(&&context.pool.get().await?, &like_form)?;
CommentLike::like(conn, &like_form)
})
.await??;
send_comment_ws_message_simple(comment_id, UserOperation::CreateCommentLike, context).await?; send_comment_ws_message_simple(comment_id, UserOperation::CreateCommentLike, context).await?;
Ok(()) Ok(())
@ -53,11 +49,8 @@ async fn vote_post(
score: vote_type.into(), score: vote_type.into(),
}; };
let person_id = actor.id; let person_id = actor.id;
blocking(context.pool(), move |conn| { PostLike::remove(&&context.pool.get().await?, person_id, post_id)?;
PostLike::remove(conn, person_id, post_id)?; PostLike::like(&&context.pool.get().await?, &like_form)?;
PostLike::like(conn, &like_form)
})
.await??;
send_post_ws_message(post.id, UserOperation::CreatePostLike, None, None, context).await?; send_post_ws_message(post.id, UserOperation::CreatePostLike, None, None, context).await?;
Ok(()) Ok(())
@ -70,10 +63,7 @@ async fn undo_vote_comment(
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let comment_id = comment.id; let comment_id = comment.id;
let person_id = actor.id; let person_id = actor.id;
blocking(context.pool(), move |conn| { CommentLike::remove(&&context.pool.get().await?, person_id, comment_id)?;
CommentLike::remove(conn, person_id, comment_id)
})
.await??;
send_comment_ws_message_simple(comment_id, UserOperation::CreateCommentLike, context).await?; send_comment_ws_message_simple(comment_id, UserOperation::CreateCommentLike, context).await?;
Ok(()) Ok(())
@ -86,10 +76,7 @@ async fn undo_vote_post(
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let post_id = post.id; let post_id = post.id;
let person_id = actor.id; let person_id = actor.id;
blocking(context.pool(), move |conn| { PostLike::remove(&&context.pool.get().await?, person_id, post_id)?;
PostLike::remove(conn, person_id, post_id)
})
.await??;
send_post_ws_message(post_id, UserOperation::CreatePostLike, None, None, context).await?; send_post_ws_message(post_id, UserOperation::CreatePostLike, None, None, context).await?;
Ok(()) Ok(())

View file

@ -25,7 +25,6 @@ use activitystreams::{
primitives::OneOrMany, primitives::OneOrMany,
unparsed::Unparsed, unparsed::Unparsed,
}; };
use lemmy_api_common::blocking;
use lemmy_apub_lib::{values::PublicUrl, verify_urls_match, ActivityFields, ActivityHandler}; use lemmy_apub_lib::{values::PublicUrl, verify_urls_match, ActivityFields, ActivityHandler};
use lemmy_db_queries::Crud; use lemmy_db_queries::Crud;
use lemmy_db_schema::{ use lemmy_db_schema::{
@ -62,10 +61,7 @@ impl UndoVote {
kind: VoteType, kind: VoteType,
context: &LemmyContext, context: &LemmyContext,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let community = blocking(context.pool(), move |conn| { let community = Community::read(&&context.pool.get().await?, community_id)?;
Community::read(conn, community_id)
})
.await??;
let object = Vote::new(object, actor, &community, kind.clone())?; let object = Vote::new(object, actor, &community, kind.clone())?;
let id = generate_activity_id(UndoType::Undo)?; let id = generate_activity_id(UndoType::Undo)?;

View file

@ -17,7 +17,6 @@ use crate::{
}; };
use activitystreams::{base::AnyBase, primitives::OneOrMany, unparsed::Unparsed}; use activitystreams::{base::AnyBase, primitives::OneOrMany, unparsed::Unparsed};
use anyhow::anyhow; use anyhow::anyhow;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{values::PublicUrl, ActivityFields, ActivityHandler}; use lemmy_apub_lib::{values::PublicUrl, ActivityFields, ActivityHandler};
use lemmy_db_queries::Crud; use lemmy_db_queries::Crud;
use lemmy_db_schema::{ use lemmy_db_schema::{
@ -100,10 +99,7 @@ impl Vote {
kind: VoteType, kind: VoteType,
context: &LemmyContext, context: &LemmyContext,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let community = blocking(context.pool(), move |conn| { let community = Community::read(&&context.pool.get().await?, community_id)?;
Community::read(conn, community_id)
})
.await??;
let vote = Vote::new(object, actor, &community, kind)?; let vote = Vote::new(object, actor, &community, kind)?;
let vote_id = vote.id.clone(); let vote_id = vote.id.clone();

View file

@ -11,7 +11,6 @@ use crate::{
use activitystreams::collection::{CollectionExt, OrderedCollection}; use activitystreams::collection::{CollectionExt, OrderedCollection};
use anyhow::Context; use anyhow::Context;
use diesel::result::Error::NotFound; use diesel::result::Error::NotFound;
use lemmy_api_common::blocking;
use lemmy_apub_lib::ActivityHandler; use lemmy_apub_lib::ActivityHandler;
use lemmy_db_queries::{source::community::Community_, ApubObject, Joinable}; use lemmy_db_queries::{source::community::Community_, ApubObject, Joinable};
use lemmy_db_schema::source::community::{Community, CommunityModerator, CommunityModeratorForm}; use lemmy_db_schema::source::community::{Community, CommunityModerator, CommunityModeratorForm};
@ -31,10 +30,7 @@ pub(crate) async fn get_or_fetch_and_upsert_community(
recursion_counter: &mut i32, recursion_counter: &mut i32,
) -> Result<Community, LemmyError> { ) -> Result<Community, LemmyError> {
let apub_id_owned = apub_id.to_owned(); let apub_id_owned = apub_id.to_owned();
let community = blocking(context.pool(), move |conn| { let community = Community::read_from_apub_id(&&context.pool.get().await?, &apub_id_owned.into());
Community::read_from_apub_id(conn, &apub_id_owned.into())
})
.await?;
match community { match community {
Ok(c) if !c.local && should_refetch_actor(c.last_refreshed_at) => { Ok(c) if !c.local && should_refetch_actor(c.last_refreshed_at) => {
@ -63,10 +59,7 @@ async fn fetch_remote_community(
if let Some(c) = old_community.to_owned() { if let Some(c) = old_community.to_owned() {
if is_deleted(&group) { if is_deleted(&group) {
blocking(context.pool(), move |conn| { Community::update_deleted(&&context.pool.get().await?, c.id, true)?;
Community::update_deleted(conn, c.id, true)
})
.await??;
} else if group.is_err() { } else if group.is_err() {
// If fetching failed, return the existing data. // If fetching failed, return the existing data.
return Ok(c); return Ok(c);
@ -94,10 +87,8 @@ async fn update_community_mods(
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let new_moderators = fetch_community_mods(context, group, request_counter).await?; let new_moderators = fetch_community_mods(context, group, request_counter).await?;
let community_id = community.id; let community_id = community.id;
let current_moderators = blocking(context.pool(), move |conn| { let current_moderators =
CommunityModeratorView::for_community(conn, community_id) CommunityModeratorView::for_community(&&context.pool.get().await?, community_id)?;
})
.await??;
// Remove old mods from database which arent in the moderators collection anymore // Remove old mods from database which arent in the moderators collection anymore
for mod_user in &current_moderators { for mod_user in &current_moderators {
if !new_moderators.contains(&mod_user.moderator.actor_id.clone().into()) { if !new_moderators.contains(&mod_user.moderator.actor_id.clone().into()) {
@ -105,10 +96,7 @@ async fn update_community_mods(
community_id: mod_user.community.id, community_id: mod_user.community.id,
person_id: mod_user.moderator.id, person_id: mod_user.moderator.id,
}; };
blocking(context.pool(), move |conn| { CommunityModerator::leave(&&context.pool.get().await?, &community_moderator_form)?;
CommunityModerator::leave(conn, &community_moderator_form)
})
.await??;
} }
} }
@ -126,10 +114,7 @@ async fn update_community_mods(
community_id: community.id, community_id: community.id,
person_id: mod_user.id, person_id: mod_user.id,
}; };
blocking(context.pool(), move |conn| { CommunityModerator::join(&&context.pool.get().await?, &community_moderator_form)?;
CommunityModerator::join(conn, &community_moderator_form)
})
.await??;
} }
} }

View file

@ -5,7 +5,6 @@ use crate::{
}; };
use anyhow::anyhow; use anyhow::anyhow;
use diesel::result::Error::NotFound; use diesel::result::Error::NotFound;
use lemmy_api_common::blocking;
use lemmy_db_queries::{ApubObject, Crud}; use lemmy_db_queries::{ApubObject, Crud};
use lemmy_db_schema::source::{comment::Comment, post::Post}; use lemmy_db_schema::source::{comment::Comment, post::Post};
use lemmy_utils::LemmyError; use lemmy_utils::LemmyError;
@ -23,10 +22,7 @@ pub(crate) async fn get_or_fetch_and_insert_post(
recursion_counter: &mut i32, recursion_counter: &mut i32,
) -> Result<Post, LemmyError> { ) -> Result<Post, LemmyError> {
let post_ap_id_owned = post_ap_id.to_owned(); let post_ap_id_owned = post_ap_id.to_owned();
let post = blocking(context.pool(), move |conn| { let post = Post::read_from_apub_id(&&context.pool.get().await?, &post_ap_id_owned.into());
Post::read_from_apub_id(conn, &post_ap_id_owned.into())
})
.await?;
match post { match post {
Ok(p) => Ok(p), Ok(p) => Ok(p),
@ -52,10 +48,8 @@ pub(crate) async fn get_or_fetch_and_insert_comment(
recursion_counter: &mut i32, recursion_counter: &mut i32,
) -> Result<Comment, LemmyError> { ) -> Result<Comment, LemmyError> {
let comment_ap_id_owned = comment_ap_id.to_owned(); let comment_ap_id_owned = comment_ap_id.to_owned();
let comment = blocking(context.pool(), move |conn| { let comment =
Comment::read_from_apub_id(conn, &comment_ap_id_owned.into()) Comment::read_from_apub_id(&&context.pool.get().await?, &comment_ap_id_owned.into());
})
.await?;
match comment { match comment {
Ok(p) => Ok(p), Ok(p) => Ok(p),
@ -69,7 +63,7 @@ pub(crate) async fn get_or_fetch_and_insert_comment(
let comment = Comment::from_apub(&comment, context, comment_ap_id, recursion_counter).await?; let comment = Comment::from_apub(&comment, context, comment_ap_id, recursion_counter).await?;
let post_id = comment.post_id; let post_id = comment.post_id;
let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; let post = Post::read(&&context.pool.get().await?, post_id)?;
if post.locked { if post.locked {
return Err(anyhow!("Post is locked").into()); return Err(anyhow!("Post is locked").into());
} }

View file

@ -4,7 +4,6 @@ use crate::{
}; };
use anyhow::anyhow; use anyhow::anyhow;
use diesel::result::Error::NotFound; use diesel::result::Error::NotFound;
use lemmy_api_common::blocking;
use lemmy_db_queries::{source::person::Person_, ApubObject}; use lemmy_db_queries::{source::person::Person_, ApubObject};
use lemmy_db_schema::source::person::Person; use lemmy_db_schema::source::person::Person;
use lemmy_utils::LemmyError; use lemmy_utils::LemmyError;
@ -22,10 +21,7 @@ pub(crate) async fn get_or_fetch_and_upsert_person(
recursion_counter: &mut i32, recursion_counter: &mut i32,
) -> Result<Person, LemmyError> { ) -> Result<Person, LemmyError> {
let apub_id_owned = apub_id.to_owned(); let apub_id_owned = apub_id.to_owned();
let person = blocking(context.pool(), move |conn| { let person = Person::read_from_apub_id(&&context.pool.get().await?, &apub_id_owned.into());
Person::read_from_apub_id(conn, &apub_id_owned.into())
})
.await?;
match person { match person {
// If its older than a day, re-fetch it // If its older than a day, re-fetch it
@ -36,10 +32,7 @@ pub(crate) async fn get_or_fetch_and_upsert_person(
if is_deleted(&person) { if is_deleted(&person) {
// TODO: use Person::update_deleted() once implemented // TODO: use Person::update_deleted() once implemented
blocking(context.pool(), move |conn| { Person::delete_account(&&context.pool.get().await?, u.id)?;
Person::delete_account(conn, u.id)
})
.await??;
return Err(anyhow!("Person was deleted by remote instance").into()); return Err(anyhow!("Person was deleted by remote instance").into());
} else if person.is_err() { } else if person.is_err() {
return Ok(u); return Ok(u);
@ -48,10 +41,7 @@ pub(crate) async fn get_or_fetch_and_upsert_person(
let person = Person::from_apub(&person?, context, apub_id, recursion_counter).await?; let person = Person::from_apub(&person?, context, apub_id, recursion_counter).await?;
let person_id = person.id; let person_id = person.id;
blocking(context.pool(), move |conn| { Person::mark_as_updated(&&context.pool.get().await?, person_id)?;
Person::mark_as_updated(conn, person_id)
})
.await??;
Ok(person) Ok(person)
} }

View file

@ -10,7 +10,7 @@ use crate::{
Object, Object,
}; };
use anyhow::anyhow; use anyhow::anyhow;
use lemmy_api_common::{blocking, site::SearchResponse}; use lemmy_api_common::site::SearchResponse;
use lemmy_db_queries::{ use lemmy_db_queries::{
source::{ source::{
comment::Comment_, comment::Comment_,
@ -119,40 +119,31 @@ async fn build_response(
let person_id = p.id(&query_url)?; let person_id = p.id(&query_url)?;
let person = get_or_fetch_and_upsert_person(person_id, context, recursion_counter).await?; let person = get_or_fetch_and_upsert_person(person_id, context, recursion_counter).await?;
response.users = vec![ response.users = vec![PersonViewSafe::read(
blocking(context.pool(), move |conn| { &&context.pool.get().await?,
PersonViewSafe::read(conn, person.id) person.id,
}) )?];
.await??,
];
} }
SearchAcceptedObjects::Group(g) => { SearchAcceptedObjects::Group(g) => {
let community_uri = g.id(&query_url)?; let community_uri = g.id(&query_url)?;
let community = let community =
get_or_fetch_and_upsert_community(community_uri, context, recursion_counter).await?; get_or_fetch_and_upsert_community(community_uri, context, recursion_counter).await?;
response.communities = vec![ response.communities = vec![CommunityView::read(
blocking(context.pool(), move |conn| { &&context.pool.get().await?,
CommunityView::read(conn, community.id, None) community.id,
}) None,
.await??, )?];
];
} }
SearchAcceptedObjects::Page(p) => { SearchAcceptedObjects::Page(p) => {
let p = Post::from_apub(&p, context, &query_url, recursion_counter).await?; let p = Post::from_apub(&p, context, &query_url, recursion_counter).await?;
response.posts = response.posts = vec![PostView::read(&&context.pool.get().await?, p.id, None)?];
vec![blocking(context.pool(), move |conn| PostView::read(conn, p.id, None)).await??];
} }
SearchAcceptedObjects::Comment(c) => { SearchAcceptedObjects::Comment(c) => {
let c = Comment::from_apub(&c, context, &query_url, recursion_counter).await?; let c = Comment::from_apub(&c, context, &query_url, recursion_counter).await?;
response.comments = vec![ response.comments = vec![CommentView::read(&&context.pool.get().await?, c.id, None)?];
blocking(context.pool(), move |conn| {
CommentView::read(conn, c.id, None)
})
.await??,
];
} }
}; };
@ -163,35 +154,20 @@ async fn delete_object_locally(query_url: &Url, context: &LemmyContext) -> Resul
let res = find_object_by_id(context, query_url.to_owned()).await?; let res = find_object_by_id(context, query_url.to_owned()).await?;
match res { match res {
Object::Comment(c) => { Object::Comment(c) => {
blocking(context.pool(), move |conn| { Comment::update_deleted(&&context.pool.get().await?, c.id, true)?;
Comment::update_deleted(conn, c.id, true)
})
.await??;
} }
Object::Post(p) => { Object::Post(p) => {
blocking(context.pool(), move |conn| { Post::update_deleted(&&context.pool.get().await?, p.id, true)?;
Post::update_deleted(conn, p.id, true)
})
.await??;
} }
Object::Person(u) => { Object::Person(u) => {
// TODO: implement update_deleted() for user, move it to ApubObject trait // TODO: implement update_deleted() for user, move it to ApubObject trait
blocking(context.pool(), move |conn| { Person::delete_account(&&context.pool.get().await?, u.id)?;
Person::delete_account(conn, u.id)
})
.await??;
} }
Object::Community(c) => { Object::Community(c) => {
blocking(context.pool(), move |conn| { Community::update_deleted(&&context.pool.get().await?, c.id, true)?;
Community::update_deleted(conn, c.id, true)
})
.await??;
} }
Object::PrivateMessage(pm) => { Object::PrivateMessage(pm) => {
blocking(context.pool(), move |conn| { PrivateMessage::update_deleted(&&context.pool.get().await?, pm.id, true)?;
PrivateMessage::update_deleted(conn, pm.id, true)
})
.await??;
} }
} }
Err(anyhow!("Object was deleted").into()) Err(anyhow!("Object was deleted").into())

View file

@ -4,7 +4,6 @@ use crate::{
}; };
use actix_web::{body::Body, web, web::Path, HttpResponse}; use actix_web::{body::Body, web, web::Path, HttpResponse};
use diesel::result::Error::NotFound; use diesel::result::Error::NotFound;
use lemmy_api_common::blocking;
use lemmy_db_queries::Crud; use lemmy_db_queries::Crud;
use lemmy_db_schema::{source::comment::Comment, CommentId}; use lemmy_db_schema::{source::comment::Comment, CommentId};
use lemmy_utils::LemmyError; use lemmy_utils::LemmyError;
@ -22,7 +21,7 @@ pub(crate) async fn get_apub_comment(
context: web::Data<LemmyContext>, context: web::Data<LemmyContext>,
) -> Result<HttpResponse<Body>, LemmyError> { ) -> Result<HttpResponse<Body>, LemmyError> {
let id = CommentId(info.comment_id.parse::<i32>()?); let id = CommentId(info.comment_id.parse::<i32>()?);
let comment = blocking(context.pool(), move |conn| Comment::read(conn, id)).await??; let comment = Comment::read(&&context.pool.get().await?, id)?;
if !comment.local { if !comment.local {
return Err(NotFound.into()); return Err(NotFound.into());
} }

View file

@ -21,7 +21,6 @@ use activitystreams::{
url::Url, url::Url,
}; };
use actix_web::{body::Body, web, web::Payload, HttpRequest, HttpResponse}; use actix_web::{body::Body, web, web::Payload, HttpRequest, HttpResponse};
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ActivityFields, ActivityHandler}; use lemmy_apub_lib::{ActivityFields, ActivityHandler};
use lemmy_db_queries::source::{activity::Activity_, community::Community_}; use lemmy_db_queries::source::{activity::Activity_, community::Community_};
use lemmy_db_schema::source::{activity::Activity, community::Community}; use lemmy_db_schema::source::{activity::Activity, community::Community};
@ -44,10 +43,7 @@ pub(crate) async fn get_apub_community_http(
info: web::Path<CommunityQuery>, info: web::Path<CommunityQuery>,
context: web::Data<LemmyContext>, context: web::Data<LemmyContext>,
) -> Result<HttpResponse<Body>, LemmyError> { ) -> Result<HttpResponse<Body>, LemmyError> {
let community = blocking(context.pool(), move |conn| { let community = Community::read_from_name(&&context.pool.get().await?, &info.community_name)?;
Community::read_from_name(conn, &info.community_name)
})
.await??;
if !community.deleted { if !community.deleted {
let apub = community.to_apub(context.pool()).await?; let apub = community.to_apub(context.pool()).await?;
@ -101,16 +97,11 @@ pub(crate) async fn get_apub_community_followers(
info: web::Path<CommunityQuery>, info: web::Path<CommunityQuery>,
context: web::Data<LemmyContext>, context: web::Data<LemmyContext>,
) -> Result<HttpResponse<Body>, LemmyError> { ) -> Result<HttpResponse<Body>, LemmyError> {
let community = blocking(context.pool(), move |conn| { let community = Community::read_from_name(&&context.pool.get().await?, &info.community_name)?;
Community::read_from_name(conn, &info.community_name)
})
.await??;
let community_id = community.id; let community_id = community.id;
let community_followers = blocking(context.pool(), move |conn| { let community_followers =
CommunityFollowerView::for_community(conn, community_id) CommunityFollowerView::for_community(&&context.pool.get().await?, community_id)?;
})
.await??;
let mut collection = UnorderedCollection::new(); let mut collection = UnorderedCollection::new();
collection collection
@ -126,16 +117,11 @@ pub(crate) async fn get_apub_community_outbox(
info: web::Path<CommunityQuery>, info: web::Path<CommunityQuery>,
context: web::Data<LemmyContext>, context: web::Data<LemmyContext>,
) -> Result<HttpResponse<Body>, LemmyError> { ) -> Result<HttpResponse<Body>, LemmyError> {
let community = blocking(context.pool(), move |conn| { let community = Community::read_from_name(&&context.pool.get().await?, &info.community_name)?;
Community::read_from_name(conn, &info.community_name)
})
.await??;
let community_actor_id = community.actor_id.to_owned(); let community_actor_id = community.actor_id.to_owned();
let activities = blocking(context.pool(), move |conn| { let activities =
Activity::read_community_outbox(conn, &community_actor_id) Activity::read_community_outbox(&&context.pool.get().await?, &community_actor_id)?;
})
.await??;
let activities = activities let activities = activities
.iter() .iter()
@ -155,10 +141,7 @@ pub(crate) async fn get_apub_community_inbox(
info: web::Path<CommunityQuery>, info: web::Path<CommunityQuery>,
context: web::Data<LemmyContext>, context: web::Data<LemmyContext>,
) -> Result<HttpResponse<Body>, LemmyError> { ) -> Result<HttpResponse<Body>, LemmyError> {
let community = blocking(context.pool(), move |conn| { let community = Community::read_from_name(&&context.pool.get().await?, &info.community_name)?;
Community::read_from_name(conn, &info.community_name)
})
.await??;
let mut collection = OrderedCollection::new(); let mut collection = OrderedCollection::new();
collection collection
@ -171,20 +154,14 @@ pub(crate) async fn get_apub_community_moderators(
info: web::Path<CommunityQuery>, info: web::Path<CommunityQuery>,
context: web::Data<LemmyContext>, context: web::Data<LemmyContext>,
) -> Result<HttpResponse<Body>, LemmyError> { ) -> Result<HttpResponse<Body>, LemmyError> {
let community = blocking(context.pool(), move |conn| { let community = Community::read_from_name(&&context.pool.get().await?, &info.community_name)?;
Community::read_from_name(conn, &info.community_name)
})
.await??;
// The attributed to, is an ordered vector with the creator actor_ids first, // The attributed to, is an ordered vector with the creator actor_ids first,
// then the rest of the moderators // then the rest of the moderators
// TODO Technically the instance admins can mod the community, but lets // TODO Technically the instance admins can mod the community, but lets
// ignore that for now // ignore that for now
let cid = community.id; let cid = community.id;
let moderators = blocking(context.pool(), move |conn| { let moderators = CommunityModeratorView::for_community(&&context.pool.get().await?, cid)?;
CommunityModeratorView::for_community(conn, cid)
})
.await??;
let moderators: Vec<Url> = moderators let moderators: Vec<Url> = moderators
.into_iter() .into_iter()

View file

@ -19,7 +19,6 @@ use actix_web::{
use anyhow::{anyhow, Context}; use anyhow::{anyhow, Context};
use futures::StreamExt; use futures::StreamExt;
use http::StatusCode; use http::StatusCode;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ActivityFields, ActivityHandler}; use lemmy_apub_lib::{ActivityFields, ActivityHandler};
use lemmy_db_queries::{source::activity::Activity_, DbPool}; use lemmy_db_queries::{source::activity::Activity_, DbPool};
use lemmy_db_schema::source::activity::Activity; use lemmy_db_schema::source::activity::Activity;
@ -158,10 +157,7 @@ pub(crate) async fn get_activity(
info.id info.id
))? ))?
.into(); .into();
let activity = blocking(context.pool(), move |conn| { let activity = Activity::read_from_apub_id(&&context.pool.get().await?, &activity_id)?;
Activity::read_from_apub_id(conn, &activity_id)
})
.await??;
let sensitive = activity.sensitive.unwrap_or(true); let sensitive = activity.sensitive.unwrap_or(true);
if !activity.local || sensitive { if !activity.local || sensitive {
@ -176,10 +172,7 @@ pub(crate) async fn is_activity_already_known(
activity_id: &Url, activity_id: &Url,
) -> Result<bool, LemmyError> { ) -> Result<bool, LemmyError> {
let activity_id = activity_id.to_owned().into(); let activity_id = activity_id.to_owned().into();
let existing = blocking(pool, move |conn| { let existing = Activity::read_from_apub_id(&&pool.get().await?, &activity_id);
Activity::read_from_apub_id(conn, &activity_id)
})
.await?;
match existing { match existing {
Ok(_) => Ok(true), Ok(_) => Ok(true),
Err(_) => Ok(false), Err(_) => Ok(false),

View file

@ -23,7 +23,6 @@ use activitystreams::{
collection::{CollectionExt, OrderedCollection}, collection::{CollectionExt, OrderedCollection},
}; };
use actix_web::{body::Body, web, web::Payload, HttpRequest, HttpResponse}; use actix_web::{body::Body, web, web::Payload, HttpRequest, HttpResponse};
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ActivityFields, ActivityHandler}; use lemmy_apub_lib::{ActivityFields, ActivityHandler};
use lemmy_db_queries::source::person::Person_; use lemmy_db_queries::source::person::Person_;
use lemmy_db_schema::source::person::Person; use lemmy_db_schema::source::person::Person;
@ -45,10 +44,7 @@ pub(crate) async fn get_apub_person_http(
) -> Result<HttpResponse<Body>, LemmyError> { ) -> Result<HttpResponse<Body>, LemmyError> {
let user_name = info.into_inner().user_name; let user_name = info.into_inner().user_name;
// TODO: this needs to be able to read deleted persons, so that it can send tombstones // TODO: this needs to be able to read deleted persons, so that it can send tombstones
let person = blocking(context.pool(), move |conn| { let person = Person::find_by_name(&&context.pool.get().await?, &user_name)?;
Person::find_by_name(conn, &user_name)
})
.await??;
if !person.deleted { if !person.deleted {
let apub = person.to_apub(context.pool()).await?; let apub = person.to_apub(context.pool()).await?;
@ -95,10 +91,7 @@ pub(crate) async fn get_apub_person_outbox(
info: web::Path<PersonQuery>, info: web::Path<PersonQuery>,
context: web::Data<LemmyContext>, context: web::Data<LemmyContext>,
) -> Result<HttpResponse<Body>, LemmyError> { ) -> Result<HttpResponse<Body>, LemmyError> {
let person = blocking(context.pool(), move |conn| { let person = Person::find_by_name(&&context.pool.get().await?, &info.user_name)?;
Person::find_by_name(conn, &info.user_name)
})
.await??;
// TODO: populate the person outbox // TODO: populate the person outbox
let mut collection = OrderedCollection::new(); let mut collection = OrderedCollection::new();
collection collection
@ -113,10 +106,7 @@ pub(crate) async fn get_apub_person_inbox(
info: web::Path<PersonQuery>, info: web::Path<PersonQuery>,
context: web::Data<LemmyContext>, context: web::Data<LemmyContext>,
) -> Result<HttpResponse<Body>, LemmyError> { ) -> Result<HttpResponse<Body>, LemmyError> {
let person = blocking(context.pool(), move |conn| { let person = Person::find_by_name(&&context.pool.get().await?, &info.user_name)?;
Person::find_by_name(conn, &info.user_name)
})
.await??;
let mut collection = OrderedCollection::new(); let mut collection = OrderedCollection::new();
collection collection

View file

@ -4,7 +4,6 @@ use crate::{
}; };
use actix_web::{body::Body, web, HttpResponse}; use actix_web::{body::Body, web, HttpResponse};
use diesel::result::Error::NotFound; use diesel::result::Error::NotFound;
use lemmy_api_common::blocking;
use lemmy_db_queries::Crud; use lemmy_db_queries::Crud;
use lemmy_db_schema::{source::post::Post, PostId}; use lemmy_db_schema::{source::post::Post, PostId};
use lemmy_utils::LemmyError; use lemmy_utils::LemmyError;
@ -22,7 +21,7 @@ pub(crate) async fn get_apub_post(
context: web::Data<LemmyContext>, context: web::Data<LemmyContext>,
) -> Result<HttpResponse<Body>, LemmyError> { ) -> Result<HttpResponse<Body>, LemmyError> {
let id = PostId(info.post_id.parse::<i32>()?); let id = PostId(info.post_id.parse::<i32>()?);
let post = blocking(context.pool(), move |conn| Post::read(conn, id)).await??; let post = Post::read(&&context.pool.get().await?, id)?;
if !post.local { if !post.local {
return Err(NotFound.into()); return Err(NotFound.into());
} }

View file

@ -1,3 +1,5 @@
#![allow(clippy::needless_borrow)]
#[macro_use] #[macro_use]
extern crate lazy_static; extern crate lazy_static;
@ -12,7 +14,6 @@ pub mod objects;
use crate::extensions::signatures::PublicKey; use crate::extensions::signatures::PublicKey;
use anyhow::{anyhow, Context}; use anyhow::{anyhow, Context};
use diesel::NotFound; use diesel::NotFound;
use lemmy_api_common::blocking;
use lemmy_db_queries::{source::activity::Activity_, ApubObject, DbPool}; use lemmy_db_queries::{source::activity::Activity_, ApubObject, DbPool};
use lemmy_db_schema::{ use lemmy_db_schema::{
source::{ source::{
@ -237,10 +238,7 @@ where
T: Serialize + std::fmt::Debug + Send + 'static, T: Serialize + std::fmt::Debug + Send + 'static,
{ {
let ap_id = ap_id.to_owned().into(); let ap_id = ap_id.to_owned().into();
blocking(pool, move |conn| { Activity::insert(&&pool.get().await?, ap_id, &activity, local, sensitive)?;
Activity::insert(conn, ap_id, &activity, local, sensitive)
})
.await??;
Ok(()) Ok(())
} }
@ -267,19 +265,13 @@ pub(crate) async fn find_post_or_comment_by_id(
apub_id: Url, apub_id: Url,
) -> Result<PostOrComment, LemmyError> { ) -> Result<PostOrComment, LemmyError> {
let ap_id = apub_id.clone(); let ap_id = apub_id.clone();
let post = blocking(context.pool(), move |conn| { let post = Post::read_from_apub_id(&&context.pool.get().await?, &ap_id.into());
Post::read_from_apub_id(conn, &ap_id.into())
})
.await?;
if let Ok(p) = post { if let Ok(p) = post {
return Ok(PostOrComment::Post(Box::new(p))); return Ok(PostOrComment::Post(Box::new(p)));
} }
let ap_id = apub_id.clone(); let ap_id = apub_id.clone();
let comment = blocking(context.pool(), move |conn| { let comment = Comment::read_from_apub_id(&&context.pool.get().await?, &ap_id.into());
Comment::read_from_apub_id(conn, &ap_id.into())
})
.await?;
if let Ok(c) = comment { if let Ok(c) = comment {
return Ok(PostOrComment::Comment(Box::new(c))); return Ok(PostOrComment::Comment(Box::new(c)));
} }
@ -306,27 +298,19 @@ async fn find_object_by_id(context: &LemmyContext, apub_id: Url) -> Result<Objec
} }
let ap_id = apub_id.clone(); let ap_id = apub_id.clone();
let person = blocking(context.pool(), move |conn| { let person = DbPerson::read_from_apub_id(&&context.pool.get().await?, &ap_id.into());
DbPerson::read_from_apub_id(conn, &ap_id.into())
})
.await?;
if let Ok(u) = person { if let Ok(u) = person {
return Ok(Object::Person(Box::new(u))); return Ok(Object::Person(Box::new(u)));
} }
let ap_id = apub_id.clone(); let ap_id = apub_id.clone();
let community = blocking(context.pool(), move |conn| { let community = Community::read_from_apub_id(&&context.pool.get().await?, &ap_id.into());
Community::read_from_apub_id(conn, &ap_id.into())
})
.await?;
if let Ok(c) = community { if let Ok(c) = community {
return Ok(Object::Community(Box::new(c))); return Ok(Object::Community(Box::new(c)));
} }
let private_message = blocking(context.pool(), move |conn| { let private_message =
PrivateMessage::read_from_apub_id(conn, &apub_id.into()) PrivateMessage::read_from_apub_id(&&context.pool.get().await?, &apub_id.into());
})
.await?;
if let Ok(pm) = private_message { if let Ok(pm) = private_message {
return Ok(Object::PrivateMessage(Box::new(pm))); return Ok(Object::PrivateMessage(Box::new(pm)));
} }
@ -343,9 +327,8 @@ async fn check_community_or_site_ban(
return Err(anyhow!("Person is banned from site").into()); return Err(anyhow!("Person is banned from site").into());
} }
let person_id = person.id; let person_id = person.id;
let is_banned = let is_banned = CommunityPersonBanView::get(&&pool.get().await?, person_id, community_id).is_ok();
move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok(); if is_banned {
if blocking(pool, is_banned).await? {
return Err(anyhow!("Person is banned from community").into()); return Err(anyhow!("Person is banned from community").into());
} }

View file

@ -19,7 +19,6 @@ use activitystreams::{
}; };
use anyhow::{anyhow, Context}; use anyhow::{anyhow, Context};
use chrono::{DateTime, FixedOffset}; use chrono::{DateTime, FixedOffset};
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
values::{MediaTypeHtml, MediaTypeMarkdown, PublicUrl}, values::{MediaTypeHtml, MediaTypeMarkdown, PublicUrl},
verify_domains_match, verify_domains_match,
@ -120,12 +119,12 @@ impl Note {
// Workaround because I cant figure ut how to get the post out of the box (and we dont // Workaround because I cant figure ut how to get the post out of the box (and we dont
// want to stackoverflow in a deep comment hierarchy). // want to stackoverflow in a deep comment hierarchy).
let post_id = p.id; let post_id = p.id;
let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; let post = Post::read(&&context.pool.get().await?, post_id)?;
Ok((post, None)) Ok((post, None))
} }
PostOrComment::Comment(c) => { PostOrComment::Comment(c) => {
let post_id = c.post_id; let post_id = c.post_id;
let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; let post = Post::read(&&context.pool.get().await?, post_id)?;
Ok((post, Some(c.id))) Ok((post, Some(c.id)))
} }
} }
@ -140,10 +139,7 @@ impl Note {
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let (post, _parent_comment_id) = self.get_parents(context, request_counter).await?; let (post, _parent_comment_id) = self.get_parents(context, request_counter).await?;
let community_id = post.community_id; let community_id = post.community_id;
let community = blocking(context.pool(), move |conn| { let community = Community::read(&&context.pool.get().await?, community_id)?;
Community::read(conn, community_id)
})
.await??;
if post.locked { if post.locked {
return Err(anyhow!("Post is locked").into()); return Err(anyhow!("Post is locked").into());
@ -166,17 +162,17 @@ impl ToApub for Comment {
async fn to_apub(&self, pool: &DbPool) -> Result<Note, LemmyError> { async fn to_apub(&self, pool: &DbPool) -> Result<Note, LemmyError> {
let creator_id = self.creator_id; let creator_id = self.creator_id;
let creator = blocking(pool, move |conn| Person::read(conn, creator_id)).await??; let creator = Person::read(&&pool.get().await?, creator_id)?;
let post_id = self.post_id; let post_id = self.post_id;
let post = blocking(pool, move |conn| Post::read(conn, post_id)).await??; let post = Post::read(&&pool.get().await?, post_id)?;
// Add a vector containing some important info to the "in_reply_to" field // Add a vector containing some important info to the "in_reply_to" field
// [post_ap_id, Option(parent_comment_ap_id)] // [post_ap_id, Option(parent_comment_ap_id)]
let mut in_reply_to_vec = vec![post.ap_id.into_inner()]; let mut in_reply_to_vec = vec![post.ap_id.into_inner()];
if let Some(parent_id) = self.parent_id { if let Some(parent_id) = self.parent_id {
let parent_comment = blocking(pool, move |conn| Comment::read(conn, parent_id)).await??; let parent_comment = Comment::read(&&pool.get().await?, parent_id)?;
in_reply_to_vec.push(parent_comment.ap_id.into_inner()); in_reply_to_vec.push(parent_comment.ap_id.into_inner());
} }
@ -246,6 +242,6 @@ impl FromApub for Comment {
ap_id, ap_id,
local: Some(false), local: Some(false),
}; };
Ok(blocking(context.pool(), move |conn| Comment::upsert(conn, &form)).await??) Ok(Comment::upsert(&&context.pool.get().await?, &form)?)
} }
} }

View file

@ -13,7 +13,6 @@ use activitystreams::{
unparsed::Unparsed, unparsed::Unparsed,
}; };
use chrono::{DateTime, FixedOffset}; use chrono::{DateTime, FixedOffset};
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
values::{MediaTypeHtml, MediaTypeMarkdown}, values::{MediaTypeHtml, MediaTypeMarkdown},
verify_domains_match, verify_domains_match,
@ -178,7 +177,7 @@ impl FromApub for Community {
fetch_community_mods(context, group, request_counter).await?; fetch_community_mods(context, group, request_counter).await?;
let form = Group::from_apub_to_form(group, expected_domain).await?; let form = Group::from_apub_to_form(group, expected_domain).await?;
let community = blocking(context.pool(), move |conn| Community::upsert(conn, &form)).await??; let community = Community::upsert(&&context.pool.get().await?, &form)?;
Ok(community) Ok(community)
} }
} }

View file

@ -12,7 +12,6 @@ use activitystreams::{
primitives::OneOrMany, primitives::OneOrMany,
unparsed::Unparsed, unparsed::Unparsed,
}; };
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
values::{MediaTypeHtml, MediaTypeMarkdown}, values::{MediaTypeHtml, MediaTypeMarkdown},
verify_domains_match, verify_domains_match,
@ -176,10 +175,7 @@ impl FromApub for DbPerson {
shared_inbox_url: Some(shared_inbox), shared_inbox_url: Some(shared_inbox),
matrix_user_id: Some(person.matrix_user_id.clone()), matrix_user_id: Some(person.matrix_user_id.clone()),
}; };
let person = blocking(context.pool(), move |conn| { let person = DbPerson::upsert(&&context.pool.get().await?, &person_form)?;
DbPerson::upsert(conn, &person_form)
})
.await??;
Ok(person) Ok(person)
} }
} }

View file

@ -16,7 +16,6 @@ use activitystreams::{
unparsed::Unparsed, unparsed::Unparsed,
}; };
use chrono::{DateTime, FixedOffset}; use chrono::{DateTime, FixedOffset};
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
values::{MediaTypeHtml, MediaTypeMarkdown}, values::{MediaTypeHtml, MediaTypeMarkdown},
verify_domains_match, verify_domains_match,
@ -80,10 +79,7 @@ impl Page {
/// Both stickied and locked need to be false on a newly created post (verified in [[CreatePost]]. /// Both stickied and locked need to be false on a newly created post (verified in [[CreatePost]].
pub(crate) async fn is_mod_action(&self, pool: &DbPool) -> Result<bool, LemmyError> { pub(crate) async fn is_mod_action(&self, pool: &DbPool) -> Result<bool, LemmyError> {
let post_id = self.id.clone(); let post_id = self.id.clone();
let old_post = blocking(pool, move |conn| { let old_post = Post::read_from_apub_id(&&pool.get().await?, &post_id.into());
Post::read_from_apub_id(conn, &post_id.into())
})
.await?;
let is_mod_action = if let Ok(old_post) = old_post { let is_mod_action = if let Ok(old_post) = old_post {
self.stickied != Some(old_post.stickied) || self.comments_enabled != Some(!old_post.locked) self.stickied != Some(old_post.stickied) || self.comments_enabled != Some(!old_post.locked)
@ -120,9 +116,9 @@ impl ToApub for Post {
// Turn a Lemmy post into an ActivityPub page that can be sent out over the network. // Turn a Lemmy post into an ActivityPub page that can be sent out over the network.
async fn to_apub(&self, pool: &DbPool) -> Result<Page, LemmyError> { async fn to_apub(&self, pool: &DbPool) -> Result<Page, LemmyError> {
let creator_id = self.creator_id; let creator_id = self.creator_id;
let creator = blocking(pool, move |conn| Person::read(conn, creator_id)).await??; let creator = Person::read(&&pool.get().await?, creator_id)?;
let community_id = self.community_id; let community_id = self.community_id;
let community = blocking(pool, move |conn| Community::read(conn, community_id)).await??; let community = Community::read(&&pool.get().await?, community_id)?;
let source = self.body.clone().map(|body| Source { let source = self.body.clone().map(|body| Source {
content: body, content: body,
@ -218,6 +214,6 @@ impl FromApub for Post {
ap_id, ap_id,
local: Some(false), local: Some(false),
}; };
Ok(blocking(context.pool(), move |conn| Post::upsert(conn, &form)).await??) Ok(Post::upsert(&&context.pool.get().await?, &form)?)
} }
} }

View file

@ -11,7 +11,6 @@ use activitystreams::{
}; };
use anyhow::anyhow; use anyhow::anyhow;
use chrono::{DateTime, FixedOffset}; use chrono::{DateTime, FixedOffset};
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
values::{MediaTypeHtml, MediaTypeMarkdown}, values::{MediaTypeHtml, MediaTypeMarkdown},
verify_domains_match, verify_domains_match,
@ -76,10 +75,10 @@ impl ToApub for PrivateMessage {
async fn to_apub(&self, pool: &DbPool) -> Result<Note, LemmyError> { async fn to_apub(&self, pool: &DbPool) -> Result<Note, LemmyError> {
let creator_id = self.creator_id; let creator_id = self.creator_id;
let creator = blocking(pool, move |conn| Person::read(conn, creator_id)).await??; let creator = Person::read(&&pool.get().await?, creator_id)?;
let recipient_id = self.recipient_id; let recipient_id = self.recipient_id;
let recipient = blocking(pool, move |conn| Person::read(conn, recipient_id)).await??; let recipient = Person::read(&&pool.get().await?, recipient_id)?;
let note = Note { let note = Note {
context: lemmy_context(), context: lemmy_context(),
@ -136,11 +135,6 @@ impl FromApub for PrivateMessage {
ap_id, ap_id,
local: Some(false), local: Some(false),
}; };
Ok( Ok(PrivateMessage::upsert(&&context.pool.get().await?, &form)?)
blocking(context.pool(), move |conn| {
PrivateMessage::upsert(conn, &form)
})
.await??,
)
} }
} }

View file

@ -13,7 +13,7 @@ doctest = false
[dependencies] [dependencies]
lemmy_utils = { version = "=0.11.3", path = "../utils" } lemmy_utils = { version = "=0.11.3", path = "../utils" }
lemmy_db_schema = { version = "=0.11.3", path = "../db_schema" } lemmy_db_schema = { version = "=0.11.3", path = "../db_schema" }
diesel = { version = "1.4.7", features = ["postgres","chrono","r2d2","serde_json"] } diesel = { version = "1.4.7", features = ["postgres","chrono","serde_json"] }
diesel_migrations = "1.4.0" diesel_migrations = "1.4.0"
chrono = { version = "0.4.19", features = ["serde"] } chrono = { version = "0.4.19", features = ["serde"] }
serde = { version = "1.0.127", features = ["derive"] } serde = { version = "1.0.127", features = ["derive"] }
@ -26,6 +26,7 @@ url = { version = "2.2.2", features = ["serde"] }
lazy_static = "1.4.0" lazy_static = "1.4.0"
regex = "1.5.4" regex = "1.5.4"
bcrypt = "0.10.1" bcrypt = "0.10.1"
deadpool-diesel = { version = "0.1.2", features = ["postgres"] }
[dev-dependencies] [dev-dependencies]
serial_test = "0.5.1" serial_test = "0.5.1"

View file

@ -12,6 +12,7 @@ extern crate diesel_migrations;
#[cfg(test)] #[cfg(test)]
extern crate serial_test; extern crate serial_test;
use deadpool_diesel::postgres::Pool;
use diesel::{result::Error, *}; use diesel::{result::Error, *};
use lemmy_db_schema::{CommunityId, DbUrl, PersonId}; use lemmy_db_schema::{CommunityId, DbUrl, PersonId};
use lemmy_utils::ApiError; use lemmy_utils::ApiError;
@ -23,7 +24,7 @@ use url::Url;
pub mod aggregates; pub mod aggregates;
pub mod source; pub mod source;
pub type DbPool = diesel::r2d2::Pool<diesel::r2d2::ConnectionManager<diesel::PgConnection>>; pub type DbPool = Pool;
pub trait Crud { pub trait Crud {
type Form; type Form;

View file

@ -9,7 +9,7 @@ license = "AGPL-3.0"
doctest = false doctest = false
[dependencies] [dependencies]
diesel = { version = "1.4.7", features = ["postgres","chrono","r2d2","serde_json"] } diesel = { version = "1.4.7", features = ["postgres","chrono","serde_json"] }
chrono = { version = "0.4.19", features = ["serde"] } chrono = { version = "0.4.19", features = ["serde"] }
serde = { version = "1.0.127", features = ["derive"] } serde = { version = "1.0.127", features = ["derive"] }
serde_json = { version = "1.0.66", features = ["preserve_order"] } serde_json = { version = "1.0.66", features = ["preserve_order"] }

View file

@ -11,7 +11,7 @@ doctest = false
[dependencies] [dependencies]
lemmy_db_queries = { version = "=0.11.3", path = "../db_queries" } lemmy_db_queries = { version = "=0.11.3", path = "../db_queries" }
lemmy_db_schema = { version = "=0.11.3", path = "../db_schema" } lemmy_db_schema = { version = "=0.11.3", path = "../db_schema" }
diesel = { version = "1.4.7", features = ["postgres","chrono","r2d2","serde_json"] } diesel = { version = "1.4.7", features = ["postgres","chrono","serde_json"] }
serde = { version = "1.0.127", features = ["derive"] } serde = { version = "1.0.127", features = ["derive"] }
log = "0.4.14" log = "0.4.14"
url = "2.2.2" url = "2.2.2"

View file

@ -708,7 +708,7 @@ mod tests {
); );
// Make sure block set the creator blocked // Make sure block set the creator blocked
assert_eq!(true, read_comment_from_blocked_person.creator_blocked); assert!(read_comment_from_blocked_person.creator_blocked);
assert_eq!(1, num_deleted); assert_eq!(1, num_deleted);
assert_eq!(1, like_removed); assert_eq!(1, like_removed);

View file

@ -11,5 +11,5 @@ doctest = false
[dependencies] [dependencies]
lemmy_db_queries = { version = "=0.11.3", path = "../db_queries" } lemmy_db_queries = { version = "=0.11.3", path = "../db_queries" }
lemmy_db_schema = { version = "=0.11.3", path = "../db_schema" } lemmy_db_schema = { version = "=0.11.3", path = "../db_schema" }
diesel = { version = "1.4.7", features = ["postgres","chrono","r2d2","serde_json"] } diesel = { version = "1.4.7", features = ["postgres","chrono","serde_json"] }
serde = { version = "1.0.127", features = ["derive"] } serde = { version = "1.0.127", features = ["derive"] }

View file

@ -11,5 +11,5 @@ doctest = false
[dependencies] [dependencies]
lemmy_db_queries = { version = "=0.11.3", path = "../db_queries" } lemmy_db_queries = { version = "=0.11.3", path = "../db_queries" }
lemmy_db_schema = { version = "=0.11.3", path = "../db_schema" } lemmy_db_schema = { version = "=0.11.3", path = "../db_schema" }
diesel = { version = "1.4.7", features = ["postgres","chrono","r2d2","serde_json"] } diesel = { version = "1.4.7", features = ["postgres","chrono","serde_json"] }
serde = { version = "1.0.127", features = ["derive"] } serde = { version = "1.0.127", features = ["derive"] }

View file

@ -2,7 +2,6 @@ use actix_web::{error::ErrorBadRequest, *};
use anyhow::anyhow; use anyhow::anyhow;
use chrono::{DateTime, NaiveDateTime, Utc}; use chrono::{DateTime, NaiveDateTime, Utc};
use diesel::PgConnection; use diesel::PgConnection;
use lemmy_api_common::blocking;
use lemmy_db_queries::{ use lemmy_db_queries::{
source::{community::Community_, person::Person_}, source::{community::Community_, person::Person_},
Crud, Crud,
@ -88,15 +87,12 @@ async fn get_feed_data(
listing_type: ListingType, listing_type: ListingType,
sort_type: SortType, sort_type: SortType,
) -> Result<HttpResponse, LemmyError> { ) -> Result<HttpResponse, LemmyError> {
let site_view = blocking(context.pool(), move |conn| SiteView::read(conn)).await??; let site_view = SiteView::read(&&context.pool.get().await?)?;
let posts = blocking(context.pool(), move |conn| { let posts = PostQueryBuilder::create(&&context.pool.get().await?)
PostQueryBuilder::create(conn) .listing_type(listing_type)
.listing_type(listing_type) .sort(sort_type)
.sort(sort_type) .list()?;
.list()
})
.await??;
let items = create_post_items(posts)?; let items = create_post_items(posts)?;
@ -141,13 +137,13 @@ async fn get_feed(
_ => return Err(ErrorBadRequest(LemmyError::from(anyhow!("wrong_type")))), _ => return Err(ErrorBadRequest(LemmyError::from(anyhow!("wrong_type")))),
}; };
let builder = blocking(context.pool(), move |conn| match request_type { let conn = &&context.pool.get().await.map_err(ErrorBadRequest)?;
let builder = match request_type {
RequestType::User => get_feed_user(conn, &sort_type, param), RequestType::User => get_feed_user(conn, &sort_type, param),
RequestType::Community => get_feed_community(conn, &sort_type, param), RequestType::Community => get_feed_community(conn, &sort_type, param),
RequestType::Front => get_feed_front(conn, &sort_type, param), RequestType::Front => get_feed_front(conn, &sort_type, param),
RequestType::Inbox => get_feed_inbox(conn, param), RequestType::Inbox => get_feed_inbox(conn, param),
}) }
.await?
.map_err(ErrorBadRequest)?; .map_err(ErrorBadRequest)?;
let rss = builder.build().map_err(ErrorBadRequest)?.to_string(); let rss = builder.build().map_err(ErrorBadRequest)?.to_string();

View file

@ -1,3 +1,5 @@
#![allow(clippy::needless_borrow)]
#[macro_use] #[macro_use]
extern crate lazy_static; extern crate lazy_static;

View file

@ -1,6 +1,5 @@
use actix_web::{body::Body, error::ErrorBadRequest, *}; use actix_web::{body::Body, error::ErrorBadRequest, *};
use anyhow::anyhow; use anyhow::anyhow;
use lemmy_api_common::blocking;
use lemmy_db_views::site_view::SiteView; use lemmy_db_views::site_view::SiteView;
use lemmy_utils::{settings::structs::Settings, version, LemmyError}; use lemmy_utils::{settings::structs::Settings, version, LemmyError};
use lemmy_websocket::LemmyContext; use lemmy_websocket::LemmyContext;
@ -27,8 +26,7 @@ async fn node_info_well_known() -> Result<HttpResponse<Body>, LemmyError> {
} }
async fn node_info(context: web::Data<LemmyContext>) -> Result<HttpResponse, Error> { async fn node_info(context: web::Data<LemmyContext>) -> Result<HttpResponse, Error> {
let site_view = blocking(context.pool(), SiteView::read) let site_view = SiteView::read(&&context.pool.get().await.map_err(ErrorBadRequest)?)
.await?
.map_err(|_| ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))?; .map_err(|_| ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))?;
let protocols = if Settings::get().federation.enabled { let protocols = if Settings::get().federation.enabled {

View file

@ -1,6 +1,6 @@
use actix_web::{error::ErrorBadRequest, web::Query, *}; use actix_web::{error::ErrorBadRequest, web::Query, *};
use anyhow::anyhow; use anyhow::anyhow;
use lemmy_api_common::{blocking, WebFingerLink, WebFingerResponse}; use lemmy_api_common::{WebFingerLink, WebFingerResponse};
use lemmy_db_queries::source::{community::Community_, person::Person_}; use lemmy_db_queries::source::{community::Community_, person::Person_};
use lemmy_db_schema::source::{community::Community, person::Person}; use lemmy_db_schema::source::{community::Community, person::Person};
use lemmy_utils::{ use lemmy_utils::{
@ -46,24 +46,19 @@ async fn get_webfinger_response(
.map(|c| c.get(1)) .map(|c| c.get(1))
.flatten(); .flatten();
let conn = &&context.pool.get().await.map_err(ErrorBadRequest)?;
let url = if let Some(community_name) = community_regex_parsed { let url = if let Some(community_name) = community_regex_parsed {
let community_name = community_name.as_str().to_owned(); let community_name = community_name.as_str().to_owned();
// Make sure the requested community exists. // Make sure the requested community exists.
blocking(context.pool(), move |conn| { Community::read_from_name(conn, &community_name)
Community::read_from_name(conn, &community_name) .map_err(|_| ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))?
}) .actor_id
.await?
.map_err(|_| ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))?
.actor_id
} else if let Some(person_name) = username_regex_parsed { } else if let Some(person_name) = username_regex_parsed {
let person_name = person_name.as_str().to_owned(); let person_name = person_name.as_str().to_owned();
// Make sure the requested person exists. // Make sure the requested person exists.
blocking(context.pool(), move |conn| { Person::find_by_name(conn, &person_name)
Person::find_by_name(conn, &person_name) .map_err(|_| ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))?
}) .actor_id
.await?
.map_err(|_| ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))?
.actor_id
} else { } else {
return Err(ErrorBadRequest(LemmyError::from(anyhow!("not_found")))); return Err(ErrorBadRequest(LemmyError::from(anyhow!("not_found"))));
}; };

View file

@ -57,7 +57,7 @@ pub struct DatabaseConfig {
#[default("lemmy")] #[default("lemmy")]
pub(super) database: String, pub(super) database: String,
#[default(5)] #[default(5)]
pub pool_size: u32, pub pool_size: usize,
} }
#[derive(Debug, Deserialize, Clone)] #[derive(Debug, Deserialize, Clone)]

View file

@ -9,11 +9,8 @@ use crate::{
use actix::prelude::*; use actix::prelude::*;
use anyhow::Context as acontext; use anyhow::Context as acontext;
use background_jobs::QueueHandle; use background_jobs::QueueHandle;
use diesel::{
r2d2::{ConnectionManager, Pool},
PgConnection,
};
use lemmy_api_common::{comment::*, post::*}; use lemmy_api_common::{comment::*, post::*};
use lemmy_db_queries::DbPool;
use lemmy_db_schema::{CommunityId, LocalUserId, PostId}; use lemmy_db_schema::{CommunityId, LocalUserId, PostId};
use lemmy_utils::{ use lemmy_utils::{
location_info, location_info,
@ -69,7 +66,7 @@ pub struct ChatServer {
pub(super) rng: ThreadRng, pub(super) rng: ThreadRng,
/// The DB Pool /// The DB Pool
pub(super) pool: Pool<ConnectionManager<PgConnection>>, pub(super) pool: DbPool,
/// Rate limiting based on rate type and IP addr /// Rate limiting based on rate type and IP addr
pub(super) rate_limiter: RateLimit, pub(super) rate_limiter: RateLimit,
@ -96,7 +93,7 @@ pub struct SessionInfo {
/// room through `ChatServer`. /// room through `ChatServer`.
impl ChatServer { impl ChatServer {
pub fn startup( pub fn startup(
pool: Pool<ConnectionManager<PgConnection>>, pool: DbPool,
rate_limiter: RateLimit, rate_limiter: RateLimit,
message_handler: MessageHandlerType, message_handler: MessageHandlerType,
message_handler_crud: MessageHandlerCrudType, message_handler_crud: MessageHandlerCrudType,

View file

@ -1,3 +1,5 @@
#![allow(clippy::needless_borrow)]
#[macro_use] #[macro_use]
extern crate strum_macros; extern crate strum_macros;

View file

@ -4,7 +4,6 @@ use crate::{
OperationType, OperationType,
}; };
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
comment::CommentResponse, comment::CommentResponse,
community::CommunityResponse, community::CommunityResponse,
person::PrivateMessageResponse, person::PrivateMessageResponse,
@ -28,10 +27,7 @@ pub async fn send_post_ws_message<OP: ToString + Send + OperationType + 'static>
person_id: Option<PersonId>, person_id: Option<PersonId>,
context: &LemmyContext, context: &LemmyContext,
) -> Result<PostResponse, LemmyError> { ) -> Result<PostResponse, LemmyError> {
let mut post_view = blocking(context.pool(), move |conn| { let mut post_view = PostView::read(&&context.pool.get().await?, post_id, person_id)?;
PostView::read(conn, post_id, person_id)
})
.await??;
if post_view.post.deleted || post_view.post.removed { if post_view.post.deleted || post_view.post.removed {
post_view.post = post_view.post.blank_out_deleted_or_removed_info(); post_view.post = post_view.post.blank_out_deleted_or_removed_info();
@ -67,10 +63,7 @@ pub async fn send_comment_ws_message<OP: ToString + Send + OperationType + 'stat
recipient_ids: Vec<LocalUserId>, recipient_ids: Vec<LocalUserId>,
context: &LemmyContext, context: &LemmyContext,
) -> Result<CommentResponse, LemmyError> { ) -> Result<CommentResponse, LemmyError> {
let mut view = blocking(context.pool(), move |conn| { let mut view = CommentView::read(&&context.pool.get().await?, comment_id, person_id)?;
CommentView::read(conn, comment_id, person_id)
})
.await??;
if view.comment.deleted || view.comment.removed { if view.comment.deleted || view.comment.removed {
view.comment = view.comment.blank_out_deleted_or_removed_info(); view.comment = view.comment.blank_out_deleted_or_removed_info();
@ -98,10 +91,9 @@ pub async fn send_community_ws_message<OP: ToString + Send + OperationType + 'st
person_id: Option<PersonId>, person_id: Option<PersonId>,
context: &LemmyContext, context: &LemmyContext,
) -> Result<CommunityResponse, LemmyError> { ) -> Result<CommunityResponse, LemmyError> {
let mut community_view = blocking(context.pool(), move |conn| { let mut community_view =
CommunityView::read(conn, community_id, person_id) CommunityView::read(&&context.pool.get().await?, community_id, person_id)?;
})
.await??;
// Blank out deleted or removed info // Blank out deleted or removed info
if community_view.community.deleted || community_view.community.removed { if community_view.community.deleted || community_view.community.removed {
community_view.community = community_view.community.blank_out_deleted_or_removed_info(); community_view.community = community_view.community.blank_out_deleted_or_removed_info();
@ -129,10 +121,7 @@ pub async fn send_pm_ws_message<OP: ToString + Send + OperationType + 'static>(
websocket_id: Option<ConnectionId>, websocket_id: Option<ConnectionId>,
context: &LemmyContext, context: &LemmyContext,
) -> Result<PrivateMessageResponse, LemmyError> { ) -> Result<PrivateMessageResponse, LemmyError> {
let mut view = blocking(context.pool(), move |conn| { let mut view = PrivateMessageView::read(&&context.pool.get().await?, private_message_id)?;
PrivateMessageView::read(conn, private_message_id)
})
.await??;
// Blank out deleted or removed info // Blank out deleted or removed info
if view.private_message.deleted { if view.private_message.deleted {
@ -146,10 +135,7 @@ pub async fn send_pm_ws_message<OP: ToString + Send + OperationType + 'static>(
// Send notifications to the local recipient, if one exists // Send notifications to the local recipient, if one exists
if res.private_message_view.recipient.local { if res.private_message_view.recipient.local {
let recipient_id = res.private_message_view.recipient.id; let recipient_id = res.private_message_view.recipient.id;
let local_recipient = blocking(context.pool(), move |conn| { let local_recipient = LocalUserView::read_person(&&context.pool.get().await?, recipient_id)?;
LocalUserView::read_person(conn, recipient_id)
})
.await??;
context.chat_server().do_send(SendUserRoomMessage { context.chat_server().do_send(SendUserRoomMessage {
op, op,
response: res.clone(), response: res.clone(),

View file

@ -3,12 +3,8 @@ extern crate diesel_migrations;
use actix::prelude::*; use actix::prelude::*;
use actix_web::{web::Data, *}; use actix_web::{web::Data, *};
use diesel::{ use deadpool_diesel::postgres::{Manager, Pool};
r2d2::{ConnectionManager, Pool},
PgConnection,
};
use lemmy_api::match_websocket_operation; use lemmy_api::match_websocket_operation;
use lemmy_api_common::blocking;
use lemmy_api_crud::match_websocket_operation_crud; use lemmy_api_crud::match_websocket_operation_crud;
use lemmy_apub::activity_queue::create_activity_queue; use lemmy_apub::activity_queue::create_activity_queue;
use lemmy_db_queries::get_database_url_from_env; use lemmy_db_queries::get_database_url_from_env;
@ -31,28 +27,26 @@ async fn main() -> Result<(), LemmyError> {
env_logger::init(); env_logger::init();
let settings = Settings::get(); let settings = Settings::get();
// Set up the r2d2 connection pool // Set up the deadpool connection pool
let db_url = match get_database_url_from_env() { let db_url = match get_database_url_from_env() {
Ok(url) => url, Ok(url) => url,
Err(_) => settings.get_database_url(), Err(_) => settings.get_database_url(),
}; };
let manager = ConnectionManager::<PgConnection>::new(&db_url);
let pool = Pool::builder() let manager = Manager::new(db_url);
.max_size(settings.database.pool_size) let pool = Pool::new(manager, settings.database.pool_size);
.build(manager) let conn = &pool.get().await?;
.unwrap_or_else(|_| panic!("Error connecting to {}", db_url));
// Run the migrations from code // Run the migrations from code
blocking(&pool, move |conn| { embedded_migrations::run(conn)?;
embedded_migrations::run(conn)?; run_advanced_migrations(conn)?;
run_advanced_migrations(conn)?;
Ok(()) as Result<(), LemmyError>
})
.await??;
let pool2 = pool.clone(); // TODO can't move the pool into clokwerk, it doesn't yet support async
let c1 = pool.get().await?;
let c2 = pool.get().await?;
let c3 = pool.get().await?;
thread::spawn(move || { thread::spawn(move || {
scheduled_tasks::setup(pool2); scheduled_tasks::setup(c1, c2, c3);
}); });
// Set up the rate limiter // Set up the rate limiter

View file

@ -2,27 +2,28 @@
use clokwerk::{Scheduler, TimeUnits}; use clokwerk::{Scheduler, TimeUnits};
// Import week days and WeekDay // Import week days and WeekDay
use diesel::{sql_query, PgConnection, RunQueryDsl}; use diesel::{sql_query, PgConnection, RunQueryDsl};
use lemmy_db_queries::{source::activity::Activity_, DbPool}; use lemmy_db_queries::source::activity::Activity_;
use lemmy_db_schema::source::activity::Activity; use lemmy_db_schema::source::activity::Activity;
use log::info; use log::info;
use std::{thread, time::Duration}; use std::{thread, time::Duration};
type DeadpoolPgConnection = deadpool_diesel::Connection<PgConnection>;
/// Schedules various cleanup tasks for lemmy in a background thread /// Schedules various cleanup tasks for lemmy in a background thread
pub fn setup(pool: DbPool) { pub fn setup(c1: DeadpoolPgConnection, c2: DeadpoolPgConnection, c3: DeadpoolPgConnection) {
let mut scheduler = Scheduler::new(); let mut scheduler = Scheduler::new();
let conn = pool.get().unwrap(); active_counts(&c1);
active_counts(&conn); reindex_aggregates_tables(&c1);
reindex_aggregates_tables(&conn); clear_old_activities(&c1);
scheduler.every(1.hour()).run(move || { scheduler.every(1.hour()).run(move || {
active_counts(&conn); active_counts(&c2);
reindex_aggregates_tables(&conn); reindex_aggregates_tables(&c2);
}); });
let conn = pool.get().unwrap();
clear_old_activities(&conn);
scheduler.every(1.weeks()).run(move || { scheduler.every(1.weeks()).run(move || {
clear_old_activities(&conn); clear_old_activities(&c3);
}); });
// Manually run the scheduler in an event loop // Manually run the scheduler in an event loop