Adding deadpool, v2. Fixes #1684

This commit is contained in:
Dessalines 2021-11-08 16:49:41 -05:00
parent 2b6d2e2585
commit de8e6ac453
91 changed files with 2486 additions and 1648 deletions

56
Cargo.lock generated
View file

@ -882,6 +882,47 @@ dependencies = [
"syn 1.0.80", "syn 1.0.80",
] ]
[[package]]
name = "deadpool"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "51dc1e92ba8164da131a4753a26cb1e7ebcfe617e56bb3c2b6136049c8ee5730"
dependencies = [
"async-trait",
"deadpool-runtime",
"num_cpus",
"tokio",
]
[[package]]
name = "deadpool-diesel"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f19e58f3b8948ab3408fb9c28534a9d7e34b3e34deb93114f6cddf1aa1fbe81d"
dependencies = [
"deadpool",
"deadpool-sync",
"diesel",
]
[[package]]
name = "deadpool-runtime"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eaa37046cc0f6c3cc6090fbdbf73ef0b8ef4cfcc37f6befc0020f63e8cf121e1"
dependencies = [
"tokio",
]
[[package]]
name = "deadpool-sync"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1bea344b64b32537fde6e0f0179b1ede34d435636719dd40fe6a0f28218a61c"
dependencies = [
"deadpool",
]
[[package]] [[package]]
name = "deflate" name = "deflate"
version = "0.8.6" version = "0.8.6"
@ -950,7 +991,6 @@ dependencies = [
"chrono", "chrono",
"diesel_derives", "diesel_derives",
"pq-sys", "pq-sys",
"r2d2",
"serde_json", "serde_json",
] ]
@ -1828,6 +1868,7 @@ dependencies = [
"background-jobs", "background-jobs",
"bcrypt", "bcrypt",
"chrono", "chrono",
"deadpool-diesel",
"diesel", "diesel",
"futures", "futures",
"html2md", "html2md",
@ -1901,6 +1942,7 @@ version = "0.13.5-rc.7"
dependencies = [ dependencies = [
"bcrypt", "bcrypt",
"chrono", "chrono",
"deadpool-diesel",
"diesel", "diesel",
"diesel-derive-newtype", "diesel-derive-newtype",
"diesel_migrations", "diesel_migrations",
@ -1988,6 +2030,7 @@ dependencies = [
"cargo-husky", "cargo-husky",
"chrono", "chrono",
"clokwerk", "clokwerk",
"deadpool-diesel",
"diesel", "diesel",
"diesel_migrations", "diesel_migrations",
"doku", "doku",
@ -2019,16 +2062,25 @@ dependencies = [
name = "lemmy_utils" name = "lemmy_utils"
version = "0.13.5-rc.7" version = "0.13.5-rc.7"
dependencies = [ dependencies = [
"activitystreams",
"actix",
"actix-rt", "actix-rt",
"actix-web", "actix-web",
"anyhow", "anyhow",
"base64 0.13.0",
"chrono", "chrono",
"comrak", "comrak",
"deadpool",
"deadpool-diesel",
"deadpool-sync",
"deser-hjson", "deser-hjson",
"diesel", "diesel",
"diesel_migrations",
"doku", "doku",
"futures", "futures",
"http", "http",
"http-signature-normalization-actix",
"http-signature-normalization-reqwest",
"itertools", "itertools",
"jsonwebtoken", "jsonwebtoken",
"lazy_static", "lazy_static",
@ -2061,6 +2113,8 @@ dependencies = [
"anyhow", "anyhow",
"background-jobs", "background-jobs",
"chrono", "chrono",
"deadpool",
"deadpool-diesel",
"diesel", "diesel",
"lemmy_api_common", "lemmy_api_common",
"lemmy_db_schema", "lemmy_db_schema",

View file

@ -45,6 +45,7 @@ lemmy_websocket = { version = "=0.13.5-rc.7", path = "./crates/websocket" }
lemmy_routes = { version = "=0.13.5-rc.7", path = "./crates/routes" } lemmy_routes = { version = "=0.13.5-rc.7", path = "./crates/routes" }
diesel = "1.4.8" diesel = "1.4.8"
diesel_migrations = "1.4.0" diesel_migrations = "1.4.0"
deadpool-diesel = { version = "0.3.1", features = ["postgres"] }
chrono = { version = "0.4.19", features = ["serde"] } chrono = { version = "0.4.19", features = ["serde"] }
serde = { version = "1.0.130", features = ["derive"] } serde = { version = "1.0.130", features = ["derive"] }
actix = "0.12.0" actix = "0.12.0"

View file

@ -3,7 +3,6 @@ use std::convert::TryInto;
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,
@ -42,9 +41,10 @@ impl Perform for MarkCommentAsRead {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let comment_id = data.comment_id; let comment_id = data.comment_id;
let orig_comment = blocking(context.pool(), move |conn| { let orig_comment = context
CommentView::read(conn, comment_id, None) .conn()
}) .await?
.interact(move |conn| CommentView::read(conn, comment_id, None))
.await??; .await??;
check_community_ban( check_community_ban(
@ -61,18 +61,20 @@ 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| { context
Comment::update_read(conn, comment_id, read) .conn()
}) .await?
.interact(move |conn| Comment::update_read(conn, comment_id, read))
.await? .await?
.map_err(|_| ApiError::err_plain("couldnt_update_comment"))?; .map_err(|_| ApiError::err_plain("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 = context
CommentView::read(conn, comment_id, Some(person_id)) .conn()
}) .await?
.interact(move |conn| CommentView::read(conn, comment_id, Some(person_id)))
.await??; .await??;
let res = CommentResponse { let res = CommentResponse {
@ -104,22 +106,27 @@ impl Perform for SaveComment {
}; };
if data.save { if data.save {
let save_comment = move |conn: &'_ _| CommentSaved::save(conn, &comment_saved_form); context
blocking(context.pool(), save_comment) .conn()
.await?
.interact(move |conn| CommentSaved::save(conn, &comment_saved_form))
.await? .await?
.map_err(|e| ApiError::err("couldnt_save_comment", e))?; .map_err(|e| ApiError::err("couldnt_save_comment", e))?;
} else { } else {
let unsave_comment = move |conn: &'_ _| CommentSaved::unsave(conn, &comment_saved_form); context
blocking(context.pool(), unsave_comment) .conn()
.await?
.interact(move |conn| CommentSaved::unsave(conn, &comment_saved_form))
.await? .await?
.map_err(|e| ApiError::err("couldnt_save_comment", e))?; .map_err(|e| ApiError::err("couldnt_save_comment", e))?;
} }
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 = context
CommentView::read(conn, comment_id, Some(person_id)) .conn()
}) .await?
.interact(move |conn| CommentView::read(conn, comment_id, Some(person_id)))
.await??; .await??;
Ok(CommentResponse { Ok(CommentResponse {
@ -149,9 +156,10 @@ 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 = context
CommentView::read(conn, comment_id, None) .conn()
}) .await?
.interact(move |conn| CommentView::read(conn, comment_id, None))
.await??; .await??;
check_community_ban( check_community_ban(
@ -170,9 +178,10 @@ 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) = context
LocalUserView::read_person(conn, recipient_id) .conn()
}) .await?
.interact(move |conn| LocalUserView::read_person(conn, recipient_id))
.await? .await?
{ {
recipient_ids.push(local_recipient.local_user.id); recipient_ids.push(local_recipient.local_user.id);
@ -187,9 +196,10 @@ 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| { context
CommentLike::remove(conn, person_id, comment_id) .conn()
}) .await?
.interact(move |conn| CommentLike::remove(conn, person_id, comment_id))
.await??; .await??;
// Only add the like if the score isnt 0 // Only add the like if the score isnt 0
@ -198,8 +208,10 @@ 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); context
blocking(context.pool(), like) .conn()
.await?
.interact(move |conn| CommentLike::like(conn, &like_form2))
.await? .await?
.map_err(|e| ApiError::err("couldnt_like_comment", e))?; .map_err(|e| ApiError::err("couldnt_like_comment", e))?;

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,
comment::*, comment::*,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
@ -42,9 +41,10 @@ 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 = context
CommentView::read(conn, comment_id, None) .conn()
}) .await?
.interact(move |conn| CommentView::read(conn, comment_id, None))
.await??; .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?;
@ -56,15 +56,17 @@ impl Perform for CreateCommentReport {
reason: data.reason.to_owned(), reason: data.reason.to_owned(),
}; };
let report = blocking(context.pool(), move |conn| { let report = context
CommentReport::report(conn, &report_form) .conn()
}) .await?
.interact(move |conn| CommentReport::report(conn, &report_form))
.await? .await?
.map_err(|e| ApiError::err("couldnt_create_report", e))?; .map_err(|e| ApiError::err("couldnt_create_report", e))?;
let comment_report_view = blocking(context.pool(), move |conn| { let comment_report_view = context
CommentReportView::read(conn, report.id, person_id) .conn()
}) .await?
.interact(move |conn| CommentReportView::read(conn, report.id, person_id))
.await??; .await??;
let res = CommentReportResponse { let res = CommentReportResponse {
@ -107,31 +109,35 @@ impl Perform for ResolveCommentReport {
let report_id = data.report_id; let report_id = data.report_id;
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let report = blocking(context.pool(), move |conn| { let report = context
CommentReportView::read(conn, report_id, person_id) .conn()
}) .await?
.interact(move |conn| CommentReportView::read(conn, report_id, person_id))
.await??; .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: &'_ _| {
context
.conn()
.await?
.interact(move |conn| {
if resolved { if resolved {
CommentReport::resolve(conn, report_id, person_id) CommentReport::resolve(conn, report_id, person_id)
} else { } else {
CommentReport::unresolve(conn, report_id, person_id) CommentReport::unresolve(conn, report_id, person_id)
} }
}; })
blocking(context.pool(), resolve_fun)
.await? .await?
.map_err(|e| ApiError::err("couldnt_resolve_report", e))?; .map_err(|e| ApiError::err("couldnt_resolve_report", e))?;
let report_id = data.report_id; let report_id = data.report_id;
let comment_report_view = blocking(context.pool(), move |conn| { let comment_report_view = context
CommentReportView::read(conn, report_id, person_id) .conn()
}) .await?
.interact(move |conn| CommentReportView::read(conn, report_id, person_id))
.await??; .await??;
let res = CommentReportResponse { let res = CommentReportResponse {
@ -171,7 +177,10 @@ impl Perform for ListCommentReports {
let page = data.page; let page = data.page;
let limit = data.limit; let limit = data.limit;
let comment_reports = blocking(context.pool(), move |conn| { let comment_reports = context
.conn()
.await?
.interact(move |conn| {
CommentReportQueryBuilder::create(conn, person_id, admin) CommentReportQueryBuilder::create(conn, person_id, admin)
.community_id(community_id) .community_id(community_id)
.unresolved_only(unresolved_only) .unresolved_only(unresolved_only)

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,
check_community_deleted_or_removed, check_community_deleted_or_removed,
community::*, community::*,
@ -71,9 +70,10 @@ impl Perform for FollowCommunity {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let community_id = data.community_id; let community_id = data.community_id;
let community: ApubCommunity = blocking(context.pool(), move |conn| { let community: ApubCommunity = context
Community::read(conn, community_id) .conn()
}) .await?
.interact(move |conn| Community::read(conn, community_id))
.await?? .await??
.into(); .into();
let community_follower_form = CommunityFollowerForm { let community_follower_form = CommunityFollowerForm {
@ -87,14 +87,17 @@ impl Perform for FollowCommunity {
check_community_ban(local_user_view.person.id, community_id, context.pool()).await?; check_community_ban(local_user_view.person.id, community_id, context.pool()).await?;
check_community_deleted_or_removed(community_id, context.pool()).await?; check_community_deleted_or_removed(community_id, context.pool()).await?;
let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form); context
blocking(context.pool(), follow) .conn()
.await?
.interact(move |conn| CommunityFollower::follow(conn, &community_follower_form))
.await? .await?
.map_err(|e| ApiError::err("community_follower_already_exists", e))?; .map_err(|e| ApiError::err("community_follower_already_exists", e))?;
} else { } else {
let unfollow = context
move |conn: &'_ _| CommunityFollower::unfollow(conn, &community_follower_form); .conn()
blocking(context.pool(), unfollow) .await?
.interact(move |conn| CommunityFollower::unfollow(conn, &community_follower_form))
.await? .await?
.map_err(|e| ApiError::err("community_follower_already_exists", e))?; .map_err(|e| ApiError::err("community_follower_already_exists", e))?;
} }
@ -106,17 +109,20 @@ impl Perform for FollowCommunity {
} else { } else {
UndoFollowCommunity::send(&local_user_view.person.clone().into(), &community, context) UndoFollowCommunity::send(&local_user_view.person.clone().into(), &community, context)
.await?; .await?;
let unfollow = move |conn: &'_ _| CommunityFollower::unfollow(conn, &community_follower_form); context
blocking(context.pool(), unfollow) .conn()
.await?
.interact(move |conn| CommunityFollower::unfollow(conn, &community_follower_form))
.await? .await?
.map_err(|e| ApiError::err("community_follower_already_exists", e))?; .map_err(|e| ApiError::err("community_follower_already_exists", e))?;
} }
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 = context
CommunityView::read(conn, community_id, Some(person_id)) .conn()
}) .await?
.interact(move |conn| CommunityView::read(conn, community_id, Some(person_id)))
.await??; .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
@ -151,8 +157,10 @@ impl Perform for BlockCommunity {
}; };
if data.block { if data.block {
let block = move |conn: &'_ _| CommunityBlock::block(conn, &community_block_form); context
blocking(context.pool(), block) .conn()
.await?
.interact(move |conn| CommunityBlock::block(conn, &community_block_form))
.await? .await?
.map_err(|e| ApiError::err("community_block_already_exists", e))?; .map_err(|e| ApiError::err("community_block_already_exists", e))?;
@ -162,26 +170,31 @@ impl Perform for BlockCommunity {
person_id, person_id,
pending: false, pending: false,
}; };
blocking(context.pool(), move |conn: &'_ _| { context
CommunityFollower::unfollow(conn, &community_follower_form) .conn()
}) .await?
.interact(move |conn| CommunityFollower::unfollow(conn, &community_follower_form))
.await? .await?
.ok(); .ok();
let community = blocking(context.pool(), move |conn| { let community = context
Community::read(conn, community_id) .conn()
}) .await?
.interact(move |conn| Community::read(conn, community_id))
.await??; .await??;
UndoFollowCommunity::send(&local_user_view.person.into(), &community.into(), context).await?; UndoFollowCommunity::send(&local_user_view.person.into(), &community.into(), context).await?;
} else { } else {
let unblock = move |conn: &'_ _| CommunityBlock::unblock(conn, &community_block_form); context
blocking(context.pool(), unblock) .conn()
.await?
.interact(move |conn| CommunityBlock::unblock(conn, &community_block_form))
.await? .await?
.map_err(|e| ApiError::err("community_block_already_exists", e))?; .map_err(|e| ApiError::err("community_block_already_exists", e))?;
} }
let community_view = blocking(context.pool(), move |conn| { let community_view = context
CommunityView::read(conn, community_id, Some(person_id)) .conn()
}) .await?
.interact(move |conn| CommunityView::read(conn, community_id, Some(person_id)))
.await??; .await??;
Ok(BlockCommunityResponse { Ok(BlockCommunityResponse {
@ -215,20 +228,24 @@ impl Perform for BanFromCommunity {
person_id: data.person_id, person_id: data.person_id,
}; };
let community: ApubCommunity = blocking(context.pool(), move |conn: &'_ _| { let community: ApubCommunity = context
Community::read(conn, community_id) .conn()
}) .await?
.interact(move |conn| Community::read(conn, community_id))
.await?? .await??
.into(); .into();
let banned_person: ApubPerson = blocking(context.pool(), move |conn: &'_ _| { let banned_person: ApubPerson = context
Person::read(conn, banned_person_id) .conn()
}) .await?
.interact(move |conn| Person::read(conn, banned_person_id))
.await?? .await??
.into(); .into();
if data.ban { if data.ban {
let ban = move |conn: &'_ _| CommunityPersonBan::ban(conn, &community_user_ban_form); context
blocking(context.pool(), ban) .conn()
.await?
.interact(move |conn| CommunityPersonBan::ban(conn, &community_user_ban_form))
.await? .await?
.map_err(|e| ApiError::err("community_user_already_banned", e))?; .map_err(|e| ApiError::err("community_user_already_banned", e))?;
@ -238,9 +255,10 @@ impl Perform for BanFromCommunity {
person_id: banned_person_id, person_id: banned_person_id,
pending: false, pending: false,
}; };
blocking(context.pool(), move |conn: &'_ _| { context
CommunityFollower::unfollow(conn, &community_follower_form) .conn()
}) .await?
.interact(move |conn| CommunityFollower::unfollow(conn, &community_follower_form))
.await? .await?
.ok(); .ok();
@ -252,8 +270,10 @@ impl Perform for BanFromCommunity {
) )
.await?; .await?;
} else { } else {
let unban = move |conn: &'_ _| CommunityPersonBan::unban(conn, &community_user_ban_form); context
blocking(context.pool(), unban) .conn()
.await?
.interact(move |conn| CommunityPersonBan::unban(conn, &community_user_ban_form))
.await? .await?
.map_err(|e| ApiError::err("community_user_already_banned", e))?; .map_err(|e| ApiError::err("community_user_already_banned", e))?;
UndoBlockUserFromCommunity::send( UndoBlockUserFromCommunity::send(
@ -268,14 +288,20 @@ 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: &'_ _| { context
.conn()
.await?
.interact(move |conn| {
Post::update_removed_for_creator(conn, banned_person_id, Some(community_id), true) Post::update_removed_for_creator(conn, banned_person_id, Some(community_id), true)
}) })
.await??; .await??;
// Comments // Comments
// TODO Diesel doesn't allow updates with joins, so this has to be a loop // TODO Diesel doesn't allow updates with joins, so this has to be a loop
let comments = blocking(context.pool(), move |conn| { let comments = context
.conn()
.await?
.interact(move |conn| {
CommentQueryBuilder::create(conn) CommentQueryBuilder::create(conn)
.creator_id(banned_person_id) .creator_id(banned_person_id)
.community_id(community_id) .community_id(community_id)
@ -286,9 +312,10 @@ impl Perform for BanFromCommunity {
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: &'_ _| { context
Comment::update_removed(conn, comment_id, true) .conn()
}) .await?
.interact(move |conn| Comment::update_removed(conn, comment_id, true))
.await??; .await??;
} }
} }
@ -305,15 +332,17 @@ impl Perform for BanFromCommunity {
banned: Some(data.ban), banned: Some(data.ban),
expires, expires,
}; };
blocking(context.pool(), move |conn| { context
ModBanFromCommunity::create(conn, &form) .conn()
}) .await?
.interact(move |conn| ModBanFromCommunity::create(conn, &form))
.await??; .await??;
let person_id = data.person_id; let person_id = data.person_id;
let person_view = blocking(context.pool(), move |conn| { let person_view = context
PersonViewSafe::read(conn, person_id) .conn()
}) .await?
.interact(move |conn| PersonViewSafe::read(conn, person_id))
.await??; .await??;
let res = BanFromCommunityResponse { let res = BanFromCommunityResponse {
@ -356,13 +385,17 @@ 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); context
blocking(context.pool(), join) .conn()
.await?
.interact(move |conn| CommunityModerator::join(conn, &community_moderator_form))
.await? .await?
.map_err(|e| ApiError::err("community_moderator_already_exists", e))?; .map_err(|e| ApiError::err("community_moderator_already_exists", e))?;
} else { } else {
let leave = move |conn: &'_ _| CommunityModerator::leave(conn, &community_moderator_form); context
blocking(context.pool(), leave) .conn()
.await?
.interact(move |conn| CommunityModerator::leave(conn, &community_moderator_form))
.await? .await?
.map_err(|e| ApiError::err("community_moderator_already_exists", e))?; .map_err(|e| ApiError::err("community_moderator_already_exists", e))?;
} }
@ -374,21 +407,24 @@ 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| { context
ModAddCommunity::create(conn, &form) .conn()
}) .await?
.interact(move |conn| ModAddCommunity::create(conn, &form))
.await??; .await??;
// Send to federated instances // Send to federated instances
let updated_mod_id = data.person_id; let updated_mod_id = data.person_id;
let updated_mod: ApubPerson = blocking(context.pool(), move |conn| { let updated_mod: ApubPerson = context
Person::read(conn, updated_mod_id) .conn()
}) .await?
.interact(move |conn| Person::read(conn, updated_mod_id))
.await?? .await??
.into(); .into();
let community: ApubCommunity = blocking(context.pool(), move |conn| { let community: ApubCommunity = context
Community::read(conn, community_id) .conn()
}) .await?
.interact(move |conn| Community::read(conn, community_id))
.await?? .await??
.into(); .into();
if data.added { if data.added {
@ -412,9 +448,10 @@ 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 = context
CommunityModeratorView::for_community(conn, community_id) .conn()
}) .await?
.interact(move |conn| CommunityModeratorView::for_community(conn, community_id))
.await??; .await??;
let res = AddModToCommunityResponse { moderators }; let res = AddModToCommunityResponse { moderators };
@ -443,12 +480,17 @@ impl Perform for TransferCommunity {
let local_user_view = let local_user_view =
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let site_creator_id = blocking(context.pool(), move |conn| { let site_creator_id = context
Site::read(conn, 1).map(|s| s.creator_id) .conn()
}) .await?
.interact(move |conn| Site::read(conn, 1).map(|s| s.creator_id))
.await??; .await??;
let mut admins = blocking(context.pool(), PersonViewSafe::admins).await??; let mut admins = context
.conn()
.await?
.interact(|conn| PersonViewSafe::admins(conn))
.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
@ -460,9 +502,10 @@ 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 = context
CommunityModeratorView::for_community(conn, community_id) .conn()
}) .await?
.interact(move |conn| CommunityModeratorView::for_community(conn, community_id))
.await??; .await??;
// Make sure transferrer is either the top community mod, or an admin // Make sure transferrer is either the top community mod, or an admin
@ -486,9 +529,10 @@ 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| { context
CommunityModerator::delete_for_community(conn, community_id) .conn()
}) .await?
.interact(move |conn| CommunityModerator::delete_for_community(conn, community_id))
.await??; .await??;
// TODO: this should probably be a bulk operation // TODO: this should probably be a bulk operation
@ -499,8 +543,10 @@ impl Perform for TransferCommunity {
person_id: cmod.moderator.id, person_id: cmod.moderator.id,
}; };
let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form); context
blocking(context.pool(), join) .conn()
.await?
.interact(move |conn| CommunityModerator::join(conn, &community_moderator_form))
.await? .await?
.map_err(|e| ApiError::err("community_moderator_already_exists", e))?; .map_err(|e| ApiError::err("community_moderator_already_exists", e))?;
} }
@ -512,23 +558,26 @@ 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| { context
ModTransferCommunity::create(conn, &form) .conn()
}) .await?
.interact(move |conn| ModTransferCommunity::create(conn, &form))
.await??; .await??;
let community_id = data.community_id; let community_id = data.community_id;
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let community_view = blocking(context.pool(), move |conn| { let community_view = context
CommunityView::read(conn, community_id, Some(person_id)) .conn()
}) .await?
.interact(move |conn| CommunityView::read(conn, community_id, Some(person_id)))
.await? .await?
.map_err(|e| ApiError::err("couldnt_find_community", e))?; .map_err(|e| ApiError::err("couldnt_find_community", e))?;
let community_id = data.community_id; let community_id = data.community_id;
let moderators = blocking(context.pool(), move |conn| { let moderators = context
CommunityModeratorView::for_community(conn, community_id) .conn()
}) .await?
.interact(move |conn| CommunityModeratorView::for_community(conn, community_id))
.await? .await?
.map_err(|e| ApiError::err("couldnt_find_community", e))?; .map_err(|e| ApiError::err("couldnt_find_community", e))?;

View file

@ -4,13 +4,7 @@ use anyhow::Context;
use bcrypt::verify; 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::{get_local_user_view_from_jwt, is_admin, password_length_check, person::*};
blocking,
get_local_user_view_from_jwt,
is_admin,
password_length_check,
person::*,
};
use lemmy_db_schema::{ use lemmy_db_schema::{
diesel_option_overwrite, diesel_option_overwrite,
diesel_option_overwrite_to_url, diesel_option_overwrite_to_url,
@ -72,9 +66,10 @@ 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 = context
LocalUserView::find_by_email_or_name(conn, &username_or_email) .conn()
}) .await?
.interact(move |conn| LocalUserView::find_by_email_or_name(conn, &username_or_email))
.await? .await?
.map_err(|e| ApiError::err("couldnt_find_that_username_or_email", e))?; .map_err(|e| ApiError::err("couldnt_find_that_username_or_email", e))?;
@ -214,9 +209,10 @@ impl Perform for SaveUserSettings {
bot_account, bot_account,
}; };
blocking(context.pool(), move |conn| { context
Person::update(conn, person_id, &person_form) .conn()
}) .await?
.interact(move |conn| Person::update(conn, person_id, &person_form))
.await? .await?
.map_err(|e| ApiError::err("user_already_exists", e))?; .map_err(|e| ApiError::err("user_already_exists", e))?;
@ -237,9 +233,10 @@ 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 local_user_res = context
LocalUser::update(conn, local_user_id, &local_user_form) .conn()
}) .await?
.interact(move |conn| LocalUser::update(conn, local_user_id, &local_user_form))
.await?; .await?;
let updated_local_user = match local_user_res { let updated_local_user = match local_user_res {
Ok(u) => u, Ok(u) => u,
@ -299,9 +296,10 @@ 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 = context
LocalUser::update_password(conn, local_user_id, &new_password) .conn()
}) .await?
.interact(move |conn| LocalUser::update_password(conn, local_user_id, &new_password))
.await??; .await??;
// Return the jwt // Return the jwt
@ -333,9 +331,10 @@ impl Perform for AddAdmin {
let added = data.added; let added = data.added;
let added_person_id = data.person_id; let added_person_id = data.person_id;
let added_admin = blocking(context.pool(), move |conn| { let added_admin = context
Person::add_admin(conn, added_person_id, added) .conn()
}) .await?
.interact(move |conn| Person::add_admin(conn, added_person_id, added))
.await? .await?
.map_err(|e| ApiError::err("couldnt_update_user", e))?; .map_err(|e| ApiError::err("couldnt_update_user", e))?;
@ -346,14 +345,23 @@ impl Perform for AddAdmin {
removed: Some(!data.added), removed: Some(!data.added),
}; };
blocking(context.pool(), move |conn| ModAdd::create(conn, &form)).await??; context
.conn()
let site_creator_id = blocking(context.pool(), move |conn| { .await?
Site::read(conn, 1).map(|s| s.creator_id) .interact(move |conn| ModAdd::create(conn, &form))
})
.await??; .await??;
let mut admins = blocking(context.pool(), PersonViewSafe::admins).await??; let site_creator_id = context
.conn()
.await?
.interact(move |conn| Site::read(conn, 1).map(|s| s.creator_id))
.await??;
let mut admins = context
.conn()
.await?
.interact(|conn| PersonViewSafe::admins(conn))
.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)
@ -391,25 +399,29 @@ 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); context
blocking(context.pool(), ban_person) .conn()
.await?
.interact(move |conn| Person::ban_person(conn, banned_person_id, ban))
.await? .await?
.map_err(|e| ApiError::err("couldnt_update_user", e))?; .map_err(|e| ApiError::err("couldnt_update_user", e))?;
// 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: &'_ _| { context
Post::update_removed_for_creator(conn, banned_person_id, None, true) .conn()
}) .await?
.interact(move |conn| Post::update_removed_for_creator(conn, banned_person_id, None, true))
.await??; .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 = context
CommunityModeratorView::get_community_first_mods(conn) .conn()
}) .await?
.interact(move |conn| CommunityModeratorView::get_community_first_mods(conn))
.await??; .await??;
// Filter to only this banned users top communities // Filter to only this banned users top communities
@ -419,16 +431,20 @@ 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: &'_ _| { context
.conn()
.await?
.interact(move |conn| {
Community::update_removed(conn, first_mod_community.community.id, true) Community::update_removed(conn, first_mod_community.community.id, true)
}) })
.await??; .await??;
} }
// Comments // Comments
blocking(context.pool(), move |conn: &'_ _| { context
Comment::update_removed_for_creator(conn, banned_person_id, true) .conn()
}) .await?
.interact(move |conn| Comment::update_removed_for_creator(conn, banned_person_id, true))
.await??; .await??;
} }
@ -443,12 +459,17 @@ impl Perform for BanPerson {
expires, expires,
}; };
blocking(context.pool(), move |conn| ModBan::create(conn, &form)).await??; context
.conn()
.await?
.interact(move |conn| ModBan::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 = context
PersonViewSafe::read(conn, person_id) .conn()
}) .await?
.interact(move |conn| PersonViewSafe::read(conn, person_id))
.await??; .await??;
let res = BanPersonResponse { let res = BanPersonResponse {
@ -493,22 +514,27 @@ impl Perform for BlockPerson {
}; };
if data.block { if data.block {
let block = move |conn: &'_ _| PersonBlock::block(conn, &person_block_form); context
blocking(context.pool(), block) .conn()
.await?
.interact(move |conn| PersonBlock::block(conn, &person_block_form))
.await? .await?
.map_err(|e| ApiError::err("person_block_already_exists", e))?; .map_err(|e| ApiError::err("person_block_already_exists", e))?;
} else { } else {
let unblock = move |conn: &'_ _| PersonBlock::unblock(conn, &person_block_form); context
blocking(context.pool(), unblock) .conn()
.await?
.interact(move |conn| PersonBlock::unblock(conn, &person_block_form))
.await? .await?
.map_err(|e| ApiError::err("person_block_already_exists", e))?; .map_err(|e| ApiError::err("person_block_already_exists", e))?;
} }
// TODO does any federated stuff need to be done here? // TODO does any federated stuff need to be done here?
let person_view = blocking(context.pool(), move |conn| { let person_view = context
PersonViewSafe::read(conn, target_id) .conn()
}) .await?
.interact(move |conn| PersonViewSafe::read(conn, target_id))
.await??; .await??;
let res = BlockPersonResponse { let res = BlockPersonResponse {
@ -541,7 +567,10 @@ 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 = context
.conn()
.await?
.interact(move |conn| {
CommentQueryBuilder::create(conn) CommentQueryBuilder::create(conn)
.sort(sort) .sort(sort)
.unread_only(unread_only) .unread_only(unread_only)
@ -577,7 +606,10 @@ 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 = context
.conn()
.await?
.interact(move |conn| {
PersonMentionQueryBuilder::create(conn) PersonMentionQueryBuilder::create(conn)
.recipient_id(person_id) .recipient_id(person_id)
.my_person_id(person_id) .my_person_id(person_id)
@ -607,9 +639,10 @@ impl Perform for MarkPersonMentionAsRead {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let person_mention_id = data.person_mention_id; let person_mention_id = data.person_mention_id;
let read_person_mention = blocking(context.pool(), move |conn| { let read_person_mention = context
PersonMention::read(conn, person_mention_id) .conn()
}) .await?
.interact(move |conn| PersonMention::read(conn, person_mention_id))
.await??; .await??;
if local_user_view.person.id != read_person_mention.recipient_id { if local_user_view.person.id != read_person_mention.recipient_id {
@ -618,17 +651,20 @@ 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 =
move |conn: &'_ _| PersonMention::update_read(conn, person_mention_id, read); context
blocking(context.pool(), update_mention) .conn()
.await?
.interact(move |conn| PersonMention::update_read(conn, person_mention_id, read))
.await? .await?
.map_err(|e| ApiError::err("couldnt_update_comment", e))?; .map_err(|e| ApiError::err("couldnt_update_comment", e))?;
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 = context
PersonMentionView::read(conn, person_mention_id, Some(person_id)) .conn()
}) .await?
.interact(move |conn| PersonMentionView::read(conn, person_mention_id, Some(person_id)))
.await??; .await??;
Ok(PersonMentionResponse { Ok(PersonMentionResponse {
@ -651,7 +687,10 @@ impl Perform for MarkAllAsRead {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let replies = blocking(context.pool(), move |conn| { let replies = context
.conn()
.await?
.interact(move |conn| {
CommentQueryBuilder::create(conn) CommentQueryBuilder::create(conn)
.my_person_id(person_id) .my_person_id(person_id)
.recipient_id(person_id) .recipient_id(person_id)
@ -667,22 +706,27 @@ impl Perform for MarkAllAsRead {
// 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); context
blocking(context.pool(), mark_as_read) .conn()
.await?
.interact(move |conn| Comment::update_read(conn, reply_id, true))
.await? .await?
.map_err(|e| ApiError::err("couldnt_update_comment", e))?; .map_err(|e| ApiError::err("couldnt_update_comment", e))?;
} }
// Mark all user mentions as read // Mark all user mentions as read
let update_person_mentions = context
move |conn: &'_ _| PersonMention::mark_all_as_read(conn, person_id); .conn()
blocking(context.pool(), update_person_mentions) .await?
.interact(move |conn| PersonMention::mark_all_as_read(conn, person_id))
.await? .await?
.map_err(|e| ApiError::err("couldnt_update_comment", e))?; .map_err(|e| ApiError::err("couldnt_update_comment", e))?;
// 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); context
blocking(context.pool(), update_pm) .conn()
.await?
.interact(move |conn| PrivateMessage::mark_all_as_read(conn, person_id))
.await? .await?
.map_err(|e| ApiError::err("couldnt_update_private_message", e))?; .map_err(|e| ApiError::err("couldnt_update_private_message", e))?;
@ -703,9 +747,10 @@ 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 = context
LocalUserView::find_by_email(conn, &email) .conn()
}) .await?
.interact(move |conn| LocalUserView::find_by_email(conn, &email))
.await? .await?
.map_err(|e| ApiError::err("couldnt_find_that_username_or_email", e))?; .map_err(|e| ApiError::err("couldnt_find_that_username_or_email", e))?;
@ -715,9 +760,10 @@ 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| { context
PasswordResetRequest::create_token(conn, local_user_id, &token2) .conn()
}) .await?
.interact(move |conn| PasswordResetRequest::create_token(conn, local_user_id, &token2))
.await??; .await??;
// Email the pure token to the user. // Email the pure token to the user.
@ -752,7 +798,10 @@ 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 = context
.conn()
.await?
.interact(move |conn| {
PasswordResetRequest::read_from_token(conn, &token).map(|p| p.local_user_id) PasswordResetRequest::read_from_token(conn, &token).map(|p| p.local_user_id)
}) })
.await??; .await??;
@ -766,9 +815,10 @@ 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 = context
LocalUser::update_password(conn, local_user_id, &password) .conn()
}) .await?
.interact(move |conn| LocalUser::update_password(conn, local_user_id, &password))
.await? .await?
.map_err(|e| ApiError::err("couldnt_update_user", e))?; .map_err(|e| ApiError::err("couldnt_update_user", e))?;
@ -800,14 +850,18 @@ impl Perform for GetReportCount {
let admin = local_user_view.person.admin; let admin = local_user_view.person.admin;
let community_id = data.community_id; let community_id = data.community_id;
let comment_reports = blocking(context.pool(), move |conn| { let comment_reports = context
.conn()
.await?
.interact(move |conn| {
CommentReportView::get_report_count(conn, person_id, admin, community_id) CommentReportView::get_report_count(conn, person_id, admin, community_id)
}) })
.await??; .await??;
let post_reports = blocking(context.pool(), move |conn| { let post_reports = context
PostReportView::get_report_count(conn, person_id, admin, community_id) .conn()
}) .await?
.interact(move |conn| PostReportView::get_report_count(conn, person_id, admin, community_id))
.await??; .await??;
let res = GetReportCountResponse { let res = GetReportCountResponse {
@ -835,19 +889,22 @@ impl Perform for GetUnreadCount {
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let replies = blocking(context.pool(), move |conn| { let replies = context
CommentView::get_unread_replies(conn, person_id) .conn()
}) .await?
.interact(move |conn| CommentView::get_unread_replies(conn, person_id))
.await??; .await??;
let mentions = blocking(context.pool(), move |conn| { let mentions = context
PersonMentionView::get_unread_mentions(conn, person_id) .conn()
}) .await?
.interact(move |conn| PersonMentionView::get_unread_mentions(conn, person_id))
.await??; .await??;
let private_messages = blocking(context.pool(), move |conn| { let private_messages = context
PrivateMessageView::get_unread_messages(conn, person_id) .conn()
}) .await?
.interact(move |conn| PrivateMessageView::get_unread_messages(conn, person_id))
.await??; .await??;
let res = Self::Response { let res = Self::Response {

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_community_deleted_or_removed, check_community_deleted_or_removed,
check_downvotes_enabled, check_downvotes_enabled,
@ -50,7 +49,10 @@ 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: ApubPost = blocking(context.pool(), move |conn| Post::read(conn, post_id)) let post: ApubPost = context
.conn()
.await?
.interact(move |conn| Post::read(conn, post_id))
.await?? .await??
.into(); .into();
@ -67,9 +69,10 @@ 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| { context
PostLike::remove(conn, person_id, post_id) .conn()
}) .await?
.interact(move |conn| PostLike::remove(conn, person_id, post_id))
.await??; .await??;
let community_id = post.community_id; let community_id = post.community_id;
@ -79,8 +82,10 @@ 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); context
blocking(context.pool(), like) .conn()
.await?
.interact(move |conn| PostLike::like(conn, &like_form2))
.await? .await?
.map_err(|e| ApiError::err("couldnt_like_post", e))?; .map_err(|e| ApiError::err("couldnt_like_post", e))?;
@ -132,7 +137,11 @@ impl Perform for LockPost {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let post_id = data.post_id; let post_id = data.post_id;
let orig_post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; let orig_post = context
.conn()
.await?
.interact(move |conn| Post::read(conn, post_id))
.await??;
check_community_ban( check_community_ban(
local_user_view.person.id, local_user_view.person.id,
@ -153,9 +162,10 @@ impl Perform for LockPost {
// Update the post // Update the post
let post_id = data.post_id; let post_id = data.post_id;
let locked = data.locked; let locked = data.locked;
let updated_post: ApubPost = blocking(context.pool(), move |conn| { let updated_post: ApubPost = context
Post::update_locked(conn, post_id, locked) .conn()
}) .await?
.interact(move |conn| Post::update_locked(conn, post_id, locked))
.await?? .await??
.into(); .into();
@ -165,7 +175,11 @@ 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??; context
.conn()
.await?
.interact(move |conn| ModLockPost::create(conn, &form))
.await??;
// apub updates // apub updates
CreateOrUpdatePost::send( CreateOrUpdatePost::send(
@ -201,7 +215,11 @@ impl Perform for StickyPost {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let post_id = data.post_id; let post_id = data.post_id;
let orig_post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; let orig_post = context
.conn()
.await?
.interact(move |conn| Post::read(conn, post_id))
.await??;
check_community_ban( check_community_ban(
local_user_view.person.id, local_user_view.person.id,
@ -222,9 +240,10 @@ impl Perform for StickyPost {
// Update the post // Update the post
let post_id = data.post_id; let post_id = data.post_id;
let stickied = data.stickied; let stickied = data.stickied;
let updated_post: ApubPost = blocking(context.pool(), move |conn| { let updated_post: ApubPost = context
Post::update_stickied(conn, post_id, stickied) .conn()
}) .await?
.interact(move |conn| Post::update_stickied(conn, post_id, stickied))
.await?? .await??
.into(); .into();
@ -234,9 +253,10 @@ 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| { context
ModStickyPost::create(conn, &form) .conn()
}) .await?
.interact(move |conn| ModStickyPost::create(conn, &form))
.await??; .await??;
// Apub updates // Apub updates
@ -279,22 +299,27 @@ impl Perform for SavePost {
}; };
if data.save { if data.save {
let save = move |conn: &'_ _| PostSaved::save(conn, &post_saved_form); context
blocking(context.pool(), save) .conn()
.await?
.interact(move |conn| PostSaved::save(conn, &post_saved_form))
.await? .await?
.map_err(|e| ApiError::err("couldnt_save_post", e))?; .map_err(|e| ApiError::err("couldnt_save_post", e))?;
} else { } else {
let unsave = move |conn: &'_ _| PostSaved::unsave(conn, &post_saved_form); context
blocking(context.pool(), unsave) .conn()
.await?
.interact(move |conn| PostSaved::unsave(conn, &post_saved_form))
.await? .await?
.map_err(|e| ApiError::err("couldnt_save_post", e))?; .map_err(|e| ApiError::err("couldnt_save_post", e))?;
} }
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 = context
PostView::read(conn, post_id, Some(person_id)) .conn()
}) .await?
.interact(move |conn| PostView::read(conn, post_id, Some(person_id)))
.await??; .await??;
// Mark the post as read // Mark the post as read

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,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
is_mod_or_admin, is_mod_or_admin,
@ -51,9 +50,10 @@ 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 = context
PostView::read(conn, post_id, None) .conn()
}) .await?
.interact(move |conn| PostView::read(conn, post_id, None))
.await??; .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?;
@ -67,15 +67,17 @@ impl Perform for CreatePostReport {
reason: data.reason.to_owned(), reason: data.reason.to_owned(),
}; };
let report = blocking(context.pool(), move |conn| { let report = context
PostReport::report(conn, &report_form) .conn()
}) .await?
.interact(move |conn| PostReport::report(conn, &report_form))
.await? .await?
.map_err(|e| ApiError::err("couldnt_create_report", e))?; .map_err(|e| ApiError::err("couldnt_create_report", e))?;
let post_report_view = blocking(context.pool(), move |conn| { let post_report_view = context
PostReportView::read(conn, report.id, person_id) .conn()
}) .await?
.interact(move |conn| PostReportView::read(conn, report.id, person_id))
.await??; .await??;
let res = PostReportResponse { post_report_view }; let res = PostReportResponse { post_report_view };
@ -116,30 +118,33 @@ impl Perform for ResolvePostReport {
let report_id = data.report_id; let report_id = data.report_id;
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let report = blocking(context.pool(), move |conn| { let report = context
PostReportView::read(conn, report_id, person_id) .conn()
}) .await?
.interact(move |conn| PostReportView::read(conn, report_id, person_id))
.await??; .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: &'_ _| { context
.conn()
.await?
.interact(move |conn| {
if resolved { if resolved {
PostReport::resolve(conn, report_id, person_id) PostReport::resolve(conn, report_id, person_id)
} else { } else {
PostReport::unresolve(conn, report_id, person_id) PostReport::unresolve(conn, report_id, person_id)
} }
}; })
blocking(context.pool(), resolve_fun)
.await? .await?
.map_err(|e| ApiError::err("couldnt_resolve_report", e))?; .map_err(|e| ApiError::err("couldnt_resolve_report", e))?;
let post_report_view = blocking(context.pool(), move |conn| { let post_report_view = context
PostReportView::read(conn, report_id, person_id) .conn()
}) .await?
.interact(move |conn| PostReportView::read(conn, report_id, person_id))
.await??; .await??;
let res = PostReportResponse { post_report_view }; let res = PostReportResponse { post_report_view };
@ -177,7 +182,10 @@ impl Perform for ListPostReports {
let page = data.page; let page = data.page;
let limit = data.limit; let limit = data.limit;
let post_reports = blocking(context.pool(), move |conn| { let post_reports = context
.conn()
.await?
.interact(move |conn| {
PostReportQueryBuilder::create(conn, person_id, admin) PostReportQueryBuilder::create(conn, person_id, admin)
.community_id(community_id) .community_id(community_id)
.unresolved_only(unresolved_only) .unresolved_only(unresolved_only)

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,9 +23,10 @@ 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 = context
PrivateMessage::read(conn, private_message_id) .conn()
}) .await?
.interact(move |conn| PrivateMessage::read(conn, private_message_id))
.await??; .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_plain("couldnt_update_private_message").into()); return Err(ApiError::err_plain("couldnt_update_private_message").into());
@ -35,9 +35,10 @@ 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| { context
PrivateMessage::update_read(conn, private_message_id, read) .conn()
}) .await?
.interact(move |conn| PrivateMessage::update_read(conn, private_message_id, read))
.await? .await?
.map_err(|e| ApiError::err("couldnt_update_private_message", e))?; .map_err(|e| ApiError::err("couldnt_update_private_message", e))?;

View file

@ -3,7 +3,6 @@ use actix_web::web::Data;
use anyhow::Context; use anyhow::Context;
use diesel::NotFound; use diesel::NotFound;
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,
@ -71,44 +70,62 @@ 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 = context
ModRemovePostView::list(conn, community_id, mod_person_id, page, limit) .conn()
}) .await?
.interact(move |conn| ModRemovePostView::list(conn, community_id, mod_person_id, page, limit))
.await??; .await??;
let locked_posts = blocking(context.pool(), move |conn| { let locked_posts = context
ModLockPostView::list(conn, community_id, mod_person_id, page, limit) .conn()
}) .await?
.interact(move |conn| ModLockPostView::list(conn, community_id, mod_person_id, page, limit))
.await??; .await??;
let stickied_posts = blocking(context.pool(), move |conn| { let stickied_posts = context
ModStickyPostView::list(conn, community_id, mod_person_id, page, limit) .conn()
}) .await?
.interact(move |conn| ModStickyPostView::list(conn, community_id, mod_person_id, page, limit))
.await??; .await??;
let removed_comments = blocking(context.pool(), move |conn| { let removed_comments = context
.conn()
.await?
.interact(move |conn| {
ModRemoveCommentView::list(conn, community_id, mod_person_id, page, limit) ModRemoveCommentView::list(conn, community_id, mod_person_id, page, limit)
}) })
.await??; .await??;
let banned_from_community = blocking(context.pool(), move |conn| { let banned_from_community = context
.conn()
.await?
.interact(move |conn| {
ModBanFromCommunityView::list(conn, community_id, mod_person_id, page, limit) ModBanFromCommunityView::list(conn, community_id, mod_person_id, page, limit)
}) })
.await??; .await??;
let added_to_community = blocking(context.pool(), move |conn| { let added_to_community = context
.conn()
.await?
.interact(move |conn| {
ModAddCommunityView::list(conn, community_id, mod_person_id, page, limit) ModAddCommunityView::list(conn, community_id, mod_person_id, page, limit)
}) })
.await??; .await??;
let transferred_to_community = blocking(context.pool(), move |conn| { let transferred_to_community = context
.conn()
.await?
.interact(move |conn| {
ModTransferCommunityView::list(conn, community_id, mod_person_id, page, limit) ModTransferCommunityView::list(conn, community_id, mod_person_id, page, limit)
}) })
.await??; .await??;
// 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| { context
.conn()
.await?
.interact(move |conn| {
Ok(( Ok((
ModRemoveCommunityView::list(conn, mod_person_id, page, limit)?, ModRemoveCommunityView::list(conn, mod_person_id, page, limit)?,
ModBanView::list(conn, mod_person_id, page, limit)?, ModBanView::list(conn, mod_person_id, page, limit)?,
@ -184,7 +201,10 @@ 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 = context
.conn()
.await?
.interact(move |conn| {
PostQueryBuilder::create(conn) PostQueryBuilder::create(conn)
.sort(sort) .sort(sort)
.show_nsfw(show_nsfw) .show_nsfw(show_nsfw)
@ -203,7 +223,10 @@ impl Perform for Search {
.await??; .await??;
} }
SearchType::Comments => { SearchType::Comments => {
comments = blocking(context.pool(), move |conn| { comments = context
.conn()
.await?
.interact(move |conn| {
CommentQueryBuilder::create(conn) CommentQueryBuilder::create(conn)
.sort(sort) .sort(sort)
.listing_type(listing_type) .listing_type(listing_type)
@ -220,7 +243,10 @@ impl Perform for Search {
.await??; .await??;
} }
SearchType::Communities => { SearchType::Communities => {
communities = blocking(context.pool(), move |conn| { communities = context
.conn()
.await?
.interact(move |conn| {
CommunityQueryBuilder::create(conn) CommunityQueryBuilder::create(conn)
.sort(sort) .sort(sort)
.listing_type(listing_type) .listing_type(listing_type)
@ -233,7 +259,10 @@ impl Perform for Search {
.await??; .await??;
} }
SearchType::Users => { SearchType::Users => {
users = blocking(context.pool(), move |conn| { users = context
.conn()
.await?
.interact(move |conn| {
PersonQueryBuilder::create(conn) PersonQueryBuilder::create(conn)
.sort(sort) .sort(sort)
.search_term(q) .search_term(q)
@ -249,7 +278,10 @@ 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 = context
.conn()
.await?
.interact(move |conn| {
PostQueryBuilder::create(conn) PostQueryBuilder::create(conn)
.sort(sort) .sort(sort)
.show_nsfw(show_nsfw) .show_nsfw(show_nsfw)
@ -270,7 +302,10 @@ impl Perform for Search {
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 = context
.conn()
.await?
.interact(move |conn| {
CommentQueryBuilder::create(conn) CommentQueryBuilder::create(conn)
.sort(sort) .sort(sort)
.listing_type(listing_type) .listing_type(listing_type)
@ -291,7 +326,10 @@ impl Perform for Search {
communities = if community_or_creator_included { communities = if community_or_creator_included {
vec![] vec![]
} else { } else {
blocking(context.pool(), move |conn| { context
.conn()
.await?
.interact(move |conn| {
CommunityQueryBuilder::create(conn) CommunityQueryBuilder::create(conn)
.sort(sort) .sort(sort)
.listing_type(listing_type) .listing_type(listing_type)
@ -309,7 +347,10 @@ 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| { context
.conn()
.await?
.interact(move |conn| {
PersonQueryBuilder::create(conn) PersonQueryBuilder::create(conn)
.sort(sort) .sort(sort)
.search_term(q) .search_term(q)
@ -321,7 +362,10 @@ impl Perform for Search {
}; };
} }
SearchType::Url => { SearchType::Url => {
posts = blocking(context.pool(), move |conn| { posts = context
.conn()
.await?
.interact(move |conn| {
PostQueryBuilder::create(conn) PostQueryBuilder::create(conn)
.sort(sort) .sort(sort)
.show_nsfw(show_nsfw) .show_nsfw(show_nsfw)
@ -409,23 +453,39 @@ async fn convert_response(
person: None, person: None,
}; };
use SearchableObjects::*; use SearchableObjects::*;
let conn = pool.get().await?;
match object { match object {
Person(p) => { Person(p) => {
removed_or_deleted = p.deleted; removed_or_deleted = p.deleted;
res.person = Some(blocking(pool, move |conn| PersonViewSafe::read(conn, p.id)).await??) res.person = Some(
conn
.interact(move |conn| PersonViewSafe::read(conn, p.id))
.await??,
)
} }
Community(c) => { Community(c) => {
removed_or_deleted = c.deleted || c.removed; removed_or_deleted = c.deleted || c.removed;
res.community = res.community = Some(
Some(blocking(pool, move |conn| CommunityView::read(conn, c.id, user_id)).await??) conn
.interact(move |conn| CommunityView::read(conn, c.id, user_id))
.await??,
)
} }
Post(p) => { Post(p) => {
removed_or_deleted = p.deleted || p.removed; removed_or_deleted = p.deleted || p.removed;
res.post = Some(blocking(pool, move |conn| PostView::read(conn, p.id, user_id)).await??) res.post = Some(
conn
.interact(move |conn| PostView::read(conn, p.id, user_id))
.await??,
)
} }
Comment(c) => { Comment(c) => {
removed_or_deleted = c.deleted || c.removed; removed_or_deleted = c.deleted || c.removed;
res.comment = Some(blocking(pool, move |conn| CommentView::read(conn, c.id, user_id)).await??) res.comment = Some(
conn
.interact(move |conn| CommentView::read(conn, c.id, user_id))
.await??,
)
} }
}; };
// if the object was deleted from database, dont return it // if the object was deleted from database, dont return it
@ -450,7 +510,11 @@ impl Perform for TransferSite {
is_admin(&local_user_view)?; is_admin(&local_user_view)?;
let read_site = blocking(context.pool(), Site::read_simple).await??; let read_site = context
.conn()
.await?
.interact(|conn| Site::read_simple(conn))
.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 {
@ -458,8 +522,10 @@ 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); context
blocking(context.pool(), transfer_site) .conn()
.await?
.interact(move |conn| Site::transfer(conn, new_creator_id))
.await? .await?
.map_err(|e| ApiError::err("couldnt_update_site", e))?; .map_err(|e| ApiError::err("couldnt_update_site", e))?;
@ -470,11 +536,23 @@ impl Perform for TransferSite {
removed: Some(false), removed: Some(false),
}; };
blocking(context.pool(), move |conn| ModAdd::create(conn, &form)).await??; context
.conn()
.await?
.interact(move |conn| ModAdd::create(conn, &form))
.await??;
let site_view = blocking(context.pool(), SiteView::read).await??; let site_view = context
.conn()
.await?
.interact(|conn| SiteView::read(conn))
.await??;
let mut admins = blocking(context.pool(), PersonViewSafe::admins).await??; let mut admins = context
.conn()
.await?
.interact(|conn| PersonViewSafe::admins(conn))
.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)
@ -482,7 +560,11 @@ 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(), PersonViewSafe::banned).await??; let banned = context
.conn()
.await?
.interact(|conn| PersonViewSafe::banned(conn))
.await??;
let federated_instances = build_federated_instances( let federated_instances = build_federated_instances(
context.pool(), context.pool(),
&context.settings().federation, &context.settings().federation,

View file

@ -26,30 +26,15 @@ use lemmy_db_views_actor::{
use lemmy_utils::{claims::Claims, settings::structs::FederationConfig, ApiError, LemmyError}; use lemmy_utils::{claims::Claims, settings::structs::FederationConfig, ApiError, LemmyError};
use url::Url; use url::Url;
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 is_mod_or_admin( pub async fn is_mod_or_admin(
pool: &DbPool, pool: &DbPool,
person_id: PersonId, person_id: PersonId,
community_id: CommunityId, community_id: CommunityId,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let is_mod_or_admin = blocking(pool, move |conn| { let is_mod_or_admin = pool
CommunityView::is_mod_or_admin(conn, person_id, community_id) .get()
}) .await?
.interact(move |conn| CommunityView::is_mod_or_admin(conn, person_id, community_id))
.await?; .await?;
if !is_mod_or_admin { if !is_mod_or_admin {
return Err(ApiError::err_plain("not_a_mod_or_admin").into()); return Err(ApiError::err_plain("not_a_mod_or_admin").into());
@ -65,7 +50,10 @@ 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)) pool
.get()
.await?
.interact(move |conn| Post::read(conn, post_id))
.await? .await?
.map_err(|_| ApiError::err_plain("couldnt_find_post").into()) .map_err(|_| ApiError::err_plain("couldnt_find_post").into())
} }
@ -77,9 +65,10 @@ pub async fn mark_post_as_read(
) -> Result<PostRead, LemmyError> { ) -> Result<PostRead, LemmyError> {
let post_read_form = PostReadForm { post_id, person_id }; let post_read_form = PostReadForm { post_id, person_id };
blocking(pool, move |conn| { pool
PostRead::mark_as_read(conn, &post_read_form) .get()
}) .await?
.interact(move |conn| PostRead::mark_as_read(conn, &post_read_form))
.await? .await?
.map_err(|_| ApiError::err_plain("couldnt_mark_post_as_read").into()) .map_err(|_| ApiError::err_plain("couldnt_mark_post_as_read").into())
} }
@ -93,8 +82,11 @@ pub async fn get_local_user_view_from_jwt(
.map_err(|e| ApiError::err("not_logged_in", e))? .map_err(|e| ApiError::err("not_logged_in", e))?
.claims; .claims;
let local_user_id = LocalUserId(claims.sub); let local_user_id = LocalUserId(claims.sub);
let local_user_view = let local_user_view = pool
blocking(pool, move |conn| LocalUserView::read(conn, local_user_id)).await??; .get()
.await?
.interact(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_plain("site_ban").into()); return Err(ApiError::err_plain("site_ban").into());
@ -143,9 +135,10 @@ pub async fn get_local_user_settings_view_from_jwt(
.map_err(|e| ApiError::err("not_logged_in", e))? .map_err(|e| ApiError::err("not_logged_in", e))?
.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 = pool
LocalUserSettingsView::read(conn, local_user_id) .get()
}) .await?
.interact(move |conn| LocalUserSettingsView::read(conn, local_user_id))
.await??; .await??;
// Check for a site ban // Check for a site ban
if local_user_view.person.banned { if local_user_view.person.banned {
@ -175,9 +168,12 @@ pub async fn check_community_ban(
community_id: CommunityId, community_id: CommunityId,
pool: &DbPool, pool: &DbPool,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let is_banned = if pool
move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok(); .get()
if blocking(pool, is_banned).await? { .await?
.interact(move |conn| CommunityPersonBanView::get(conn, person_id, community_id).is_ok())
.await?
{
Err(ApiError::err_plain("community_ban").into()) Err(ApiError::err_plain("community_ban").into())
} else { } else {
Ok(()) Ok(())
@ -188,7 +184,10 @@ pub async fn check_community_deleted_or_removed(
community_id: CommunityId, community_id: CommunityId,
pool: &DbPool, pool: &DbPool,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let community = blocking(pool, move |conn| Community::read(conn, community_id)) let community = pool
.get()
.await?
.interact(move |conn| Community::read(conn, community_id))
.await? .await?
.map_err(|e| ApiError::err("couldnt_find_community", e))?; .map_err(|e| ApiError::err("couldnt_find_community", e))?;
if community.deleted || community.removed { if community.deleted || community.removed {
@ -211,8 +210,12 @@ 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(); if pool
if blocking(pool, is_blocked).await? { .get()
.await?
.interact(move |conn| PersonBlock::read(conn, potential_blocker_id, my_id).is_ok())
.await?
{
Err(ApiError::err_plain("person_block").into()) Err(ApiError::err_plain("person_block").into())
} else { } else {
Ok(()) Ok(())
@ -221,7 +224,11 @@ 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, Site::read_simple).await??; let site = pool
.get()
.await?
.interact(|conn| Site::read_simple(conn))
.await??;
if !site.enable_downvotes { if !site.enable_downvotes {
return Err(ApiError::err_plain("downvotes_disabled").into()); return Err(ApiError::err_plain("downvotes_disabled").into());
} }
@ -236,9 +243,10 @@ pub async fn build_federated_instances(
) -> Result<Option<FederatedInstances>, LemmyError> { ) -> Result<Option<FederatedInstances>, LemmyError> {
let federation = federation_config.to_owned(); let federation = federation_config.to_owned();
if federation.enabled { if federation.enabled {
let distinct_communities = blocking(pool, move |conn| { let distinct_communities = pool
Community::distinct_federated_communities(conn) .get()
}) .await?
.interact(move |conn| Community::distinct_federated_communities(conn))
.await??; .await??;
let allowed = federation.allowed_instances; let allowed = federation.allowed_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_community_deleted_or_removed, check_community_deleted_or_removed,
check_person_block, check_person_block,
@ -76,7 +75,10 @@ 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 = context
.conn()
.await?
.interact(move |conn| Comment::read(conn, parent_id))
.await? .await?
.map_err(|e| ApiError::err("couldnt_create_comment", e))?; .map_err(|e| ApiError::err("couldnt_create_comment", e))?;
@ -98,9 +100,10 @@ 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 = context
Comment::create(conn, &comment_form2) .conn()
}) .await?
.interact(move |conn| Comment::create(conn, &comment_form2))
.await? .await?
.map_err(|e| ApiError::err("couldnt_create_comment", e))?; .map_err(|e| ApiError::err("couldnt_create_comment", e))?;
@ -108,8 +111,10 @@ impl PerformCrud for CreateComment {
let inserted_comment_id = inserted_comment.id; let inserted_comment_id = inserted_comment.id;
let protocol_and_hostname = context.settings().get_protocol_and_hostname(); let protocol_and_hostname = context.settings().get_protocol_and_hostname();
let updated_comment: Comment = let updated_comment: Comment = context
blocking(context.pool(), move |conn| -> Result<Comment, LemmyError> { .conn()
.await?
.interact(move |conn| -> Result<Comment, LemmyError> {
let apub_id = generate_local_apub_endpoint( let apub_id = generate_local_apub_endpoint(
EndpointType::Comment, EndpointType::Comment,
&inserted_comment_id.to_string(), &inserted_comment_id.to_string(),
@ -141,8 +146,10 @@ impl PerformCrud for CreateComment {
score: 1, score: 1,
}; };
let like = move |conn: &'_ _| CommentLike::like(conn, &like_form); context
blocking(context.pool(), like) .conn()
.await?
.interact(move |conn| CommentLike::like(conn, &like_form))
.await? .await?
.map_err(|e| ApiError::err("couldnt_like_comment", e))?; .map_err(|e| ApiError::err("couldnt_like_comment", e))?;
@ -166,43 +173,49 @@ impl PerformCrud for CreateComment {
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let comment_id = inserted_comment.id; let comment_id = inserted_comment.id;
let comment_view = blocking(context.pool(), move |conn| { let comment_view = context
CommentView::read(conn, comment_id, Some(person_id)) .conn()
}) .await?
.interact(move |conn| CommentView::read(conn, comment_id, Some(person_id)))
.await??; .await??;
// 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 == comment_view.get_recipient_id() { if local_user_view.person.id == comment_view.get_recipient_id() {
let comment_id = inserted_comment.id; let comment_id = inserted_comment.id;
blocking(context.pool(), move |conn| { context
Comment::update_read(conn, comment_id, true) .conn()
}) .await?
.interact(move |conn| Comment::update_read(conn, comment_id, true))
.await? .await?
.map_err(|e| ApiError::err("couldnt_update_comment", e))?; .map_err(|e| ApiError::err("couldnt_update_comment", e))?;
} }
// If its a reply, mark the parent as read // If its a reply, mark the parent as read
if let Some(parent_id) = data.parent_id { if let Some(parent_id) = data.parent_id {
let parent_comment = blocking(context.pool(), move |conn| { let parent_comment = context
CommentView::read(conn, parent_id, Some(person_id)) .conn()
}) .await?
.interact(move |conn| CommentView::read(conn, parent_id, Some(person_id)))
.await??; .await??;
if local_user_view.person.id == parent_comment.get_recipient_id() { if local_user_view.person.id == parent_comment.get_recipient_id() {
blocking(context.pool(), move |conn| { context
Comment::update_read(conn, parent_id, true) .conn()
}) .await?
.interact(move |conn| Comment::update_read(conn, parent_id, true))
.await? .await?
.map_err(|e| ApiError::err("couldnt_update_parent_comment", e))?; .map_err(|e| ApiError::err("couldnt_update_parent_comment", e))?;
} }
// If the parent has PersonMentions mark them as read too // If the parent has PersonMentions mark them as read too
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let person_mention = blocking(context.pool(), move |conn| { let person_mention = context
PersonMention::read_by_comment_and_person(conn, parent_id, person_id) .conn()
}) .await?
.interact(move |conn| PersonMention::read_by_comment_and_person(conn, parent_id, person_id))
.await?; .await?;
if let Ok(mention) = person_mention { if let Ok(mention) = person_mention {
blocking(context.pool(), move |conn| { context
PersonMention::update_read(conn, mention.id, true) .conn()
}) .await?
.interact(move |conn| PersonMention::update_read(conn, mention.id, true))
.await? .await?
.map_err(|e| ApiError::err("couldnt_update_person_mentions", e))?; .map_err(|e| ApiError::err("couldnt_update_person_mentions", e))?;
} }

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,
@ -39,9 +38,10 @@ impl PerformCrud for DeleteComment {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let comment_id = data.comment_id; let comment_id = data.comment_id;
let orig_comment = blocking(context.pool(), move |conn| { let orig_comment = context
CommentView::read(conn, comment_id, None) .conn()
}) .await?
.interact(move |conn| CommentView::read(conn, comment_id, None))
.await??; .await??;
// Dont delete it if its already been deleted. // Dont delete it if its already been deleted.
@ -63,16 +63,18 @@ 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 = context
Comment::update_deleted(conn, comment_id, deleted) .conn()
}) .await?
.interact(move |conn| Comment::update_deleted(conn, comment_id, deleted))
.await? .await?
.map_err(|e| ApiError::err("couldnt_update_comment", e))?; .map_err(|e| ApiError::err("couldnt_update_comment", e))?;
// Send the apub message // Send the apub message
let community = blocking(context.pool(), move |conn| { let community = context
Community::read(conn, orig_comment.post.community_id) .conn()
}) .await?
.interact(move |conn| Community::read(conn, orig_comment.post.community_id))
.await??; .await??;
send_apub_delete( send_apub_delete(
&local_user_view.person.clone().into(), &local_user_view.person.clone().into(),
@ -84,7 +86,11 @@ 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 = context
.conn()
.await?
.interact(move |conn| Post::read(conn, post_id))
.await??;
let recipient_ids = send_local_notifs( let recipient_ids = send_local_notifs(
vec![], vec![],
&updated_comment, &updated_comment,
@ -122,9 +128,10 @@ impl PerformCrud for RemoveComment {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let comment_id = data.comment_id; let comment_id = data.comment_id;
let orig_comment = blocking(context.pool(), move |conn| { let orig_comment = context
CommentView::read(conn, comment_id, None) .conn()
}) .await?
.interact(move |conn| CommentView::read(conn, comment_id, None))
.await??; .await??;
check_community_ban( check_community_ban(
@ -144,9 +151,10 @@ 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 = context
Comment::update_removed(conn, comment_id, removed) .conn()
}) .await?
.interact(move |conn| Comment::update_removed(conn, comment_id, removed))
.await? .await?
.map_err(|e| ApiError::err("couldnt_update_comment", e))?; .map_err(|e| ApiError::err("couldnt_update_comment", e))?;
@ -157,15 +165,17 @@ 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| { context
ModRemoveComment::create(conn, &form) .conn()
}) .await?
.interact(move |conn| ModRemoveComment::create(conn, &form))
.await??; .await??;
// Send the apub message // Send the apub message
let community = blocking(context.pool(), move |conn| { let community = context
Community::read(conn, orig_comment.post.community_id) .conn()
}) .await?
.interact(move |conn| Community::read(conn, orig_comment.post.community_id))
.await??; .await??;
send_apub_remove( send_apub_remove(
&local_user_view.person.clone().into(), &local_user_view.person.clone().into(),
@ -178,7 +188,11 @@ 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 = context
.conn()
.await?
.interact(move |conn| Post::read(conn, post_id))
.await??;
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::get_actor_id_from_name; use lemmy_apub::get_actor_id_from_name;
use lemmy_apub_lib::webfinger::WebfingerType; use lemmy_apub_lib::webfinger::WebfingerType;
use lemmy_db_schema::{ use lemmy_db_schema::{
@ -45,7 +45,10 @@ 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 = context
.conn()
.await?
.interact(move |conn| {
CommentQueryBuilder::create(conn) CommentQueryBuilder::create(conn)
.listing_type(listing_type) .listing_type(listing_type)
.sort(sort) .sort(sort)

View file

@ -1,7 +1,6 @@
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_community_deleted_or_removed, check_community_deleted_or_removed,
check_post_deleted_or_removed, check_post_deleted_or_removed,
@ -42,9 +41,10 @@ impl PerformCrud for EditComment {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let comment_id = data.comment_id; let comment_id = data.comment_id;
let orig_comment = blocking(context.pool(), move |conn| { let orig_comment = context
CommentView::read(conn, comment_id, None) .conn()
}) .await?
.interact(move |conn| CommentView::read(conn, comment_id, None))
.await??; .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
@ -66,9 +66,10 @@ impl PerformCrud for EditComment {
let content_slurs_removed = let content_slurs_removed =
remove_slurs(&data.content.to_owned(), &context.settings().slur_regex()); remove_slurs(&data.content.to_owned(), &context.settings().slur_regex());
let comment_id = data.comment_id; let comment_id = data.comment_id;
let updated_comment = blocking(context.pool(), move |conn| { let updated_comment = context
Comment::update_content(conn, comment_id, &content_slurs_removed) .conn()
}) .await?
.interact(move |conn| Comment::update_content(conn, comment_id, &content_slurs_removed))
.await? .await?
.map_err(|e| ApiError::err("couldnt_update_comment", e))?; .map_err(|e| ApiError::err("couldnt_update_comment", e))?;

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,
@ -53,7 +52,11 @@ impl PerformCrud for CreateCommunity {
let local_user_view = let local_user_view =
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let site = blocking(context.pool(), move |conn| Site::read(conn, 0)).await??; let site = context
.conn()
.await?
.interact(move |conn| Site::read(conn, 0))
.await??;
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_plain("only_admins_can_create_communities").into()); return Err(ApiError::err_plain("only_admins_can_create_communities").into());
} }
@ -101,9 +104,10 @@ impl PerformCrud for CreateCommunity {
..CommunityForm::default() ..CommunityForm::default()
}; };
let inserted_community = blocking(context.pool(), move |conn| { let inserted_community = context
Community::create(conn, &community_form) .conn()
}) .await?
.interact(move |conn| Community::create(conn, &community_form))
.await? .await?
.map_err(|e| ApiError::err("community_already_exists", e))?; .map_err(|e| ApiError::err("community_already_exists", e))?;
@ -113,8 +117,13 @@ 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); if context
if blocking(context.pool(), join).await?.is_err() { .conn()
.await?
.interact(move |conn| CommunityModerator::join(conn, &community_moderator_form))
.await?
.is_err()
{
return Err(ApiError::err_plain("community_moderator_already_exists").into()); return Err(ApiError::err_plain("community_moderator_already_exists").into());
} }
@ -125,15 +134,21 @@ impl PerformCrud for CreateCommunity {
pending: false, pending: false,
}; };
let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form); if context
if blocking(context.pool(), follow).await?.is_err() { .conn()
.await?
.interact(move |conn| CommunityFollower::follow(conn, &community_follower_form))
.await?
.is_err()
{
return Err(ApiError::err_plain("community_follower_already_exists").into()); return Err(ApiError::err_plain("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 = context
CommunityView::read(conn, inserted_community.id, Some(person_id)) .conn()
}) .await?
.interact(move |conn| CommunityView::read(conn, inserted_community.id, Some(person_id)))
.await??; .await??;
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_schema::{ use lemmy_db_schema::{
source::{ source::{
@ -28,9 +28,10 @@ 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 = context
CommunityModeratorView::for_community(conn, community_id) .conn()
}) .await?
.interact(move |conn| CommunityModeratorView::for_community(conn, community_id))
.await??; .await??;
// Make sure deleter is the top mod // Make sure deleter is the top mod
@ -41,9 +42,10 @@ 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 = context
Community::update_deleted(conn, community_id, deleted) .conn()
}) .await?
.interact(move |conn| Community::update_deleted(conn, community_id, deleted))
.await? .await?
.map_err(|e| ApiError::err("couldnt_update_community", e))?; .map_err(|e| ApiError::err("couldnt_update_community", e))?;
@ -87,9 +89,10 @@ 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 = context
Community::update_removed(conn, community_id, removed) .conn()
}) .await?
.interact(move |conn| Community::update_removed(conn, community_id, removed))
.await? .await?
.map_err(|e| ApiError::err("couldnt_update_community", e))?; .map_err(|e| ApiError::err("couldnt_update_community", e))?;
@ -102,9 +105,10 @@ impl PerformCrud for RemoveCommunity {
reason: data.reason.to_owned(), reason: data.reason.to_owned(),
expires, expires,
}; };
blocking(context.pool(), move |conn| { context
ModRemoveCommunity::create(conn, &form) .conn()
}) .await?
.interact(move |conn| ModRemoveCommunity::create(conn, &form))
.await??; .await??;
// Apub messages // Apub messages

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::{get_actor_id_from_name, objects::community::ApubCommunity}; use lemmy_apub::{get_actor_id_from_name, objects::community::ApubCommunity};
use lemmy_apub_lib::{object_id::ObjectId, webfinger::WebfingerType}; use lemmy_apub_lib::{object_id::ObjectId, webfinger::WebfingerType};
use lemmy_db_schema::{ use lemmy_db_schema::{
@ -45,9 +45,10 @@ impl PerformCrud for GetCommunity {
} }
}; };
let mut community_view = blocking(context.pool(), move |conn| { let mut community_view = context
CommunityView::read(conn, community_id, person_id) .conn()
}) .await?
.interact(move |conn| CommunityView::read(conn, community_id, person_id))
.await? .await?
.map_err(|e| ApiError::err("couldnt_find_community", e))?; .map_err(|e| ApiError::err("couldnt_find_community", e))?;
@ -57,9 +58,10 @@ impl PerformCrud for GetCommunity {
community_view.community = community_view.community.blank_out_deleted_or_removed_info(); community_view.community = community_view.community.blank_out_deleted_or_removed_info();
} }
let moderators: Vec<CommunityModeratorView> = blocking(context.pool(), move |conn| { let moderators: Vec<CommunityModeratorView> = context
CommunityModeratorView::for_community(conn, community_id) .conn()
}) .await?
.interact(move |conn| CommunityModeratorView::for_community(conn, community_id))
.await? .await?
.map_err(|e| ApiError::err("couldnt_find_community", e))?; .map_err(|e| ApiError::err("couldnt_find_community", e))?;
@ -106,7 +108,10 @@ 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 = context
.conn()
.await?
.interact(move |conn| {
CommunityQueryBuilder::create(conn) CommunityQueryBuilder::create(conn)
.listing_type(listing_type) .listing_type(listing_type)
.sort(sort) .sort(sort)

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,
}; };
@ -35,7 +34,10 @@ 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> = context
.conn()
.await?
.interact(move |conn| {
CommunityModeratorView::for_community(conn, community_id) CommunityModeratorView::for_community(conn, community_id)
.map(|v| v.into_iter().map(|m| m.moderator.id).collect()) .map(|v| v.into_iter().map(|m| m.moderator.id).collect())
}) })
@ -45,9 +47,10 @@ impl PerformCrud for EditCommunity {
} }
let community_id = data.community_id; let community_id = data.community_id;
let read_community = blocking(context.pool(), move |conn| { let read_community = context
Community::read(conn, community_id) .conn()
}) .await?
.interact(move |conn| Community::read(conn, community_id))
.await??; .await??;
let icon = diesel_option_overwrite_to_url(&data.icon)?; let icon = diesel_option_overwrite_to_url(&data.icon)?;
@ -65,9 +68,10 @@ 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 = context
Community::update(conn, community_id, &community_form) .conn()
}) .await?
.interact(move |conn| Community::update(conn, community_id, &community_form))
.await? .await?
.map_err(|e| ApiError::err("couldnt_update_community", e))?; .map_err(|e| ApiError::err("couldnt_update_community", e))?;

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_community_deleted_or_removed, check_community_deleted_or_removed,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
@ -83,8 +82,12 @@ impl PerformCrud for CreatePost {
..PostForm::default() ..PostForm::default()
}; };
let inserted_post = let inserted_post = match context
match blocking(context.pool(), move |conn| Post::create(conn, &post_form)).await? { .conn()
.await?
.interact(move |conn| Post::create(conn, &post_form))
.await?
{
Ok(post) => post, Ok(post) => post,
Err(e) => { Err(e) => {
let err_type = if e.to_string() == "value too long for type character varying(200)" { let err_type = if e.to_string() == "value too long for type character varying(200)" {
@ -99,7 +102,10 @@ impl PerformCrud for CreatePost {
let inserted_post_id = inserted_post.id; let inserted_post_id = inserted_post.id;
let protocol_and_hostname = context.settings().get_protocol_and_hostname(); let protocol_and_hostname = context.settings().get_protocol_and_hostname();
let updated_post = blocking(context.pool(), move |conn| -> Result<Post, LemmyError> { let updated_post = context
.conn()
.await?
.interact(move |conn| -> Result<Post, LemmyError> {
let apub_id = generate_local_apub_endpoint( let apub_id = generate_local_apub_endpoint(
EndpointType::Post, EndpointType::Post,
&inserted_post_id.to_string(), &inserted_post_id.to_string(),
@ -119,8 +125,13 @@ impl PerformCrud for CreatePost {
score: 1, score: 1,
}; };
let like = move |conn: &'_ _| PostLike::like(conn, &like_form); if context
if blocking(context.pool(), like).await?.is_err() { .conn()
.await?
.interact(move |conn| PostLike::like(conn, &like_form))
.await?
.is_err()
{
return Err(ApiError::err_plain("couldnt_like_post").into()); return Err(ApiError::err_plain("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,
check_community_deleted_or_removed, check_community_deleted_or_removed,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
@ -34,7 +33,11 @@ impl PerformCrud for DeletePost {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let post_id = data.post_id; let post_id = data.post_id;
let orig_post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; let orig_post = context
.conn()
.await?
.interact(move |conn| Post::read(conn, post_id))
.await??;
// Dont delete it if its already been deleted. // Dont delete it if its already been deleted.
if orig_post.deleted == data.deleted { if orig_post.deleted == data.deleted {
@ -57,15 +60,17 @@ 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 = context
Post::update_deleted(conn, post_id, deleted) .conn()
}) .await?
.interact(move |conn| Post::update_deleted(conn, post_id, deleted))
.await??; .await??;
// apub updates // apub updates
let community = blocking(context.pool(), move |conn| { let community = context
Community::read(conn, orig_post.community_id) .conn()
}) .await?
.interact(move |conn| Community::read(conn, orig_post.community_id))
.await??; .await??;
send_apub_delete( send_apub_delete(
&local_user_view.person.clone().into(), &local_user_view.person.clone().into(),
@ -101,7 +106,11 @@ impl PerformCrud for RemovePost {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let post_id = data.post_id; let post_id = data.post_id;
let orig_post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; let orig_post = context
.conn()
.await?
.interact(move |conn| Post::read(conn, post_id))
.await??;
check_community_ban( check_community_ban(
local_user_view.person.id, local_user_view.person.id,
@ -121,9 +130,10 @@ 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 = context
Post::update_removed(conn, post_id, removed) .conn()
}) .await?
.interact(move |conn| Post::update_removed(conn, post_id, removed))
.await??; .await??;
// Mod tables // Mod tables
@ -133,15 +143,17 @@ 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| { context
ModRemovePost::create(conn, &form) .conn()
}) .await?
.interact(move |conn| ModRemovePost::create(conn, &form))
.await??; .await??;
// apub updates // apub updates
let community = blocking(context.pool(), move |conn| { let community = context
Community::read(conn, orig_post.community_id) .conn()
}) .await?
.interact(move |conn| Community::read(conn, orig_post.community_id))
.await??; .await??;
send_apub_remove( send_apub_remove(
&local_user_view.person.clone().into(), &local_user_view.person.clone().into(),

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::get_actor_id_from_name; use lemmy_apub::get_actor_id_from_name;
use lemmy_apub_lib::webfinger::WebfingerType; use lemmy_apub_lib::webfinger::WebfingerType;
use lemmy_db_schema::{ use lemmy_db_schema::{
@ -39,9 +39,10 @@ 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 = context
PostView::read(conn, id, person_id) .conn()
}) .await?
.interact(move |conn| PostView::read(conn, id, person_id))
.await? .await?
.map_err(|e| ApiError::err("couldnt_find_post", e))?; .map_err(|e| ApiError::err("couldnt_find_post", e))?;
@ -51,7 +52,10 @@ impl PerformCrud for GetPost {
} }
let id = data.id; let id = data.id;
let mut comments = blocking(context.pool(), move |conn| { let mut comments = context
.conn()
.await?
.interact(move |conn| {
CommentQueryBuilder::create(conn) 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)
@ -63,9 +67,10 @@ impl PerformCrud for GetPost {
// Necessary for the sidebar // Necessary for the sidebar
let community_id = post_view.community.id; let community_id = post_view.community.id;
let mut community_view = blocking(context.pool(), move |conn| { let mut community_view = context
CommunityView::read(conn, community_id, person_id) .conn()
}) .await?
.interact(move |conn| CommunityView::read(conn, community_id, person_id))
.await? .await?
.map_err(|e| ApiError::err("couldnt_find_community", e))?; .map_err(|e| ApiError::err("couldnt_find_community", e))?;
@ -86,9 +91,10 @@ impl PerformCrud for GetPost {
} }
} }
let moderators = blocking(context.pool(), move |conn| { let moderators = context
CommunityModeratorView::for_community(conn, community_id) .conn()
}) .await?
.interact(move |conn| CommunityModeratorView::for_community(conn, community_id))
.await??; .await??;
let online = context let online = context
@ -146,7 +152,10 @@ impl PerformCrud for GetPosts {
}; };
let saved_only = data.saved_only; let saved_only = data.saved_only;
let mut posts = blocking(context.pool(), move |conn| { let mut posts = context
.conn()
.await?
.interact(move |conn| {
PostQueryBuilder::create(conn) PostQueryBuilder::create(conn)
.listing_type(listing_type) .listing_type(listing_type)
.sort(sort) .sort(sort)

View file

@ -1,7 +1,6 @@
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_community_deleted_or_removed, check_community_deleted_or_removed,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
@ -51,7 +50,11 @@ 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 = context
.conn()
.await?
.interact(move |conn| Post::read(conn, post_id))
.await??;
check_community_ban( check_community_ban(
local_user_view.person.id, local_user_view.person.id,
@ -90,9 +93,10 @@ impl PerformCrud for EditPost {
}; };
let post_id = data.post_id; let post_id = data.post_id;
let res = blocking(context.pool(), move |conn| { let res = context
Post::update(conn, post_id, &post_form) .conn()
}) .await?
.interact(move |conn| Post::update(conn, post_id, &post_form))
.await?; .await?;
let updated_post: Post = match res { let updated_post: Post = match res {
Ok(post) => post, Ok(post) => post,

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},
@ -51,9 +50,10 @@ impl PerformCrud for CreatePrivateMessage {
..PrivateMessageForm::default() ..PrivateMessageForm::default()
}; };
let inserted_private_message = match blocking(context.pool(), move |conn| { let inserted_private_message = match context
PrivateMessage::create(conn, &private_message_form) .conn()
}) .await?
.interact(move |conn| PrivateMessage::create(conn, &private_message_form))
.await? .await?
{ {
Ok(private_message) => private_message, Ok(private_message) => private_message,
@ -64,9 +64,10 @@ impl PerformCrud for CreatePrivateMessage {
let inserted_private_message_id = inserted_private_message.id; let inserted_private_message_id = inserted_private_message.id;
let protocol_and_hostname = context.settings().get_protocol_and_hostname(); let protocol_and_hostname = context.settings().get_protocol_and_hostname();
let updated_private_message = blocking( let updated_private_message = context
context.pool(), .conn()
move |conn| -> Result<PrivateMessage, LemmyError> { .await?
.interact(move |conn| -> Result<PrivateMessage, LemmyError> {
let apub_id = generate_local_apub_endpoint( let apub_id = generate_local_apub_endpoint(
EndpointType::PrivateMessage, EndpointType::PrivateMessage,
&inserted_private_message_id.to_string(), &inserted_private_message_id.to_string(),
@ -77,8 +78,7 @@ impl PerformCrud for CreatePrivateMessage {
inserted_private_message_id, inserted_private_message_id,
apub_id, apub_id,
)?) )?)
}, })
)
.await? .await?
.map_err(|e| ApiError::err("couldnt_create_private_message", e))?; .map_err(|e| ApiError::err("couldnt_create_private_message", e))?;
@ -101,9 +101,10 @@ 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 = context
LocalUserView::read_person(conn, recipient_id) .conn()
}) .await?
.interact(move |conn| LocalUserView::read_person(conn, recipient_id))
.await??; .await??;
send_email_to_user( send_email_to_user(
&local_recipient, &local_recipient,

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},
}; };
@ -31,9 +30,10 @@ 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 = context
PrivateMessage::read(conn, private_message_id) .conn()
}) .await?
.interact(move |conn| PrivateMessage::read(conn, private_message_id))
.await??; .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_plain("no_private_message_edit_allowed").into()); return Err(ApiError::err_plain("no_private_message_edit_allowed").into());
@ -42,9 +42,10 @@ 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 = context
PrivateMessage::update_deleted(conn, private_message_id, deleted) .conn()
}) .await?
.interact(move |conn| PrivateMessage::update_deleted(conn, private_message_id, deleted))
.await? .await?
.map_err(|e| ApiError::err("couldnt_update_private_message", e))?; .map_err(|e| ApiError::err("couldnt_update_private_message", e))?;

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},
}; };
@ -27,7 +26,10 @@ 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 = context
.conn()
.await?
.interact(move |conn| {
PrivateMessageQueryBuilder::create(conn, person_id) PrivateMessageQueryBuilder::create(conn, person_id)
.page(page) .page(page)
.limit(limit) .limit(limit)

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,9 +27,10 @@ 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 = context
PrivateMessage::read(conn, private_message_id) .conn()
}) .await?
.interact(move |conn| PrivateMessage::read(conn, private_message_id))
.await??; .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_plain("no_private_message_edit_allowed").into()); return Err(ApiError::err_plain("no_private_message_edit_allowed").into());
@ -39,7 +39,10 @@ impl PerformCrud for EditPrivateMessage {
// Doing the update // Doing the update
let content_slurs_removed = remove_slurs(&data.content, &context.settings().slur_regex()); let content_slurs_removed = remove_slurs(&data.content, &context.settings().slur_regex());
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 = context
.conn()
.await?
.interact(move |conn| {
PrivateMessage::update_content(conn, private_message_id, &content_slurs_removed) PrivateMessage::update_content(conn, private_message_id, &content_slurs_removed)
}) })
.await? .await?

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::*,
@ -33,8 +32,13 @@ impl PerformCrud for CreateSite {
) -> Result<SiteResponse, LemmyError> { ) -> Result<SiteResponse, LemmyError> {
let data: &CreateSite = self; let data: &CreateSite = self;
let read_site = Site::read_simple; if context
if blocking(context.pool(), read_site).await?.is_ok() { .conn()
.await?
.interact(|conn| Site::read_simple(conn))
.await?
.is_ok()
{
return Err(ApiError::err_plain("site_already_exists").into()); return Err(ApiError::err_plain("site_already_exists").into());
}; };
@ -70,12 +74,21 @@ 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); if context
if blocking(context.pool(), create_site).await?.is_err() { .conn()
.await?
.interact(move |conn| Site::create(conn, &site_form))
.await?
.is_err()
{
return Err(ApiError::err_plain("site_already_exists").into()); return Err(ApiError::err_plain("site_already_exists").into());
} }
let site_view = blocking(context.pool(), SiteView::read).await??; let site_view = context
.conn()
.await?
.interact(|conn| SiteView::read(conn))
.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,12 @@ 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(), SiteView::read).await? { let site_view = match context
.conn()
.await?
.interact(|conn| SiteView::read(conn))
.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(_) => {
@ -62,14 +66,24 @@ 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(), SiteView::read).await??) Some(
context
.conn()
.await?
.interact(|conn| SiteView::read(conn))
.await??,
)
} else { } else {
None None
} }
} }
}; };
let mut admins = blocking(context.pool(), PersonViewSafe::admins).await??; let mut admins = context
.conn()
.await?
.interact(|conn| PersonViewSafe::admins(conn))
.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() {
@ -82,7 +96,11 @@ impl PerformCrud for GetSite {
} }
} }
let banned = blocking(context.pool(), PersonViewSafe::banned).await??; let banned = context
.conn()
.await?
.interact(|conn| PersonViewSafe::banned(conn))
.await??;
let online = context let online = context
.chat_server() .chat_server()
@ -96,29 +114,33 @@ impl PerformCrud for GetSite {
.await? .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 = context
CommunityFollowerView::for_person(conn, person_id) .conn()
}) .await?
.interact(move |conn| CommunityFollowerView::for_person(conn, person_id))
.await? .await?
.map_err(|e| ApiError::err("system_err_login", e))?; .map_err(|e| ApiError::err("system_err_login", e))?;
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 = context
CommunityBlockView::for_person(conn, person_id) .conn()
}) .await?
.interact(move |conn| CommunityBlockView::for_person(conn, person_id))
.await? .await?
.map_err(|e| ApiError::err("system_err_login", e))?; .map_err(|e| ApiError::err("system_err_login", e))?;
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 = context
PersonBlockView::for_person(conn, person_id) .conn()
}) .await?
.interact(move |conn| PersonBlockView::for_person(conn, person_id))
.await? .await?
.map_err(|e| ApiError::err("system_err_login", e))?; .map_err(|e| ApiError::err("system_err_login", e))?;
let moderates = blocking(context.pool(), move |conn| { let moderates = context
CommunityModeratorView::for_person(conn, person_id) .conn()
}) .await?
.interact(move |conn| CommunityModeratorView::for_person(conn, person_id))
.await? .await?
.map_err(|e| ApiError::err("system_err_login", e))?; .map_err(|e| ApiError::err("system_err_login", e))?;

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},
@ -36,7 +35,11 @@ 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(), Site::read_simple).await??; let found_site = context
.conn()
.await?
.interact(|conn| Site::read_simple(conn))
.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);
@ -61,12 +64,18 @@ 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); context
blocking(context.pool(), update_site) .conn()
.await?
.interact(move |conn| Site::update(conn, 1, &site_form))
.await? .await?
.map_err(|e| ApiError::err("couldnt_update_site", e))?; .map_err(|e| ApiError::err("couldnt_update_site", e))?;
let site_view = blocking(context.pool(), SiteView::read).await??; let site_view = context
.conn()
.await?
.interact(|conn| SiteView::read(conn))
.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, honeypot_check, password_length_check, person::*}; use lemmy_api_common::{honeypot_check, password_length_check, person::*};
use lemmy_apub::{ use lemmy_apub::{
generate_followers_url, generate_followers_url,
generate_inbox_url, generate_inbox_url,
@ -50,7 +50,12 @@ 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(), Site::read_simple).await? { if let Ok(site) = context
.conn()
.await?
.interact(|conn| Site::read_simple(conn))
.await?
{
if !site.open_registration { if !site.open_registration {
return Err(ApiError::err_plain("registration_closed").into()); return Err(ApiError::err_plain("registration_closed").into());
} }
@ -65,9 +70,10 @@ 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 = context
PersonViewSafe::admins(conn).map(|a| a.is_empty()) .conn()
}) .await?
.interact(move |conn| PersonViewSafe::admins(conn).map(|a| a.is_empty()))
.await??; .await??;
// If its not the admin, check the captcha // If its not the admin, check the captcha
@ -117,9 +123,10 @@ impl PerformCrud for Register {
}; };
// insert the person // insert the person
let inserted_person = blocking(context.pool(), move |conn| { let inserted_person = context
Person::create(conn, &person_form) .conn()
}) .await?
.interact(move |conn| Person::create(conn, &person_form))
.await? .await?
.map_err(|e| ApiError::err("user_already_exists", e))?; .map_err(|e| ApiError::err("user_already_exists", e))?;
@ -142,9 +149,10 @@ 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 = match context
LocalUser::register(conn, &local_user_form) .conn()
}) .await?
.interact(move |conn| LocalUser::register(conn, &local_user_form))
.await? .await?
{ {
Ok(lu) => lu, Ok(lu) => lu,
@ -158,9 +166,10 @@ impl PerformCrud for Register {
}; };
// If the local user creation errored, then delete that person // If the local user creation errored, then delete that person
blocking(context.pool(), move |conn| { context
Person::delete(conn, inserted_person.id) .conn()
}) .await?
.interact(move |conn| Person::delete(conn, inserted_person.id))
.await??; .await??;
return Err(ApiError::err(err_type, e).into()); return Err(ApiError::err(err_type, e).into());
@ -171,9 +180,10 @@ impl PerformCrud for Register {
// Create the main community if it doesn't exist // Create the main community if it doesn't exist
let protocol_and_hostname = context.settings().get_protocol_and_hostname(); let protocol_and_hostname = context.settings().get_protocol_and_hostname();
let main_community = match blocking(context.pool(), move |conn| { let main_community = match context
Community::read(conn, CommunityId(2)) .conn()
}) .await?
.interact(move |conn| Community::read(conn, CommunityId(2)))
.await? .await?
{ {
Ok(c) => c, Ok(c) => c,
@ -196,9 +206,10 @@ 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| { context
Community::create(conn, &community_form) .conn()
}) .await?
.interact(move |conn| Community::create(conn, &community_form))
.await?? .await??
} }
}; };
@ -210,8 +221,10 @@ impl PerformCrud for Register {
pending: false, pending: false,
}; };
let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form); context
blocking(context.pool(), follow) .conn()
.await?
.interact(move |conn| CommunityFollower::follow(conn, &community_follower_form))
.await? .await?
.map_err(|e| ApiError::err("community_follower_already_exists", e))?; .map_err(|e| ApiError::err("community_follower_already_exists", e))?;
@ -222,8 +235,10 @@ impl PerformCrud for Register {
person_id: inserted_person.id, person_id: inserted_person.id,
}; };
let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form); context
blocking(context.pool(), join) .conn()
.await?
.interact(move |conn| CommunityModerator::join(conn, &community_moderator_form))
.await? .await?
.map_err(|e| ApiError::err("community_moderator_already_exists", e))?; .map_err(|e| ApiError::err("community_moderator_already_exists", e))?;
} }

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_schema::source::{comment::Comment, person::Person, post::Post}; use lemmy_db_schema::source::{comment::Comment, person::Person, post::Post};
use lemmy_utils::{ApiError, ConnectionId, LemmyError}; use lemmy_utils::{ApiError, ConnectionId, LemmyError};
use lemmy_websocket::LemmyContext; use lemmy_websocket::LemmyContext;
@ -31,20 +31,25 @@ 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); context
blocking(context.pool(), permadelete) .conn()
.await?
.interact(move |conn| Comment::permadelete_for_creator(conn, person_id))
.await? .await?
.map_err(|e| ApiError::err("couldnt_update_comment", e))?; .map_err(|e| ApiError::err("couldnt_update_comment", e))?;
// Posts // Posts
let permadelete = move |conn: &'_ _| Post::permadelete_for_creator(conn, person_id); context
blocking(context.pool(), permadelete) .conn()
.await?
.interact(move |conn| Post::permadelete_for_creator(conn, person_id))
.await? .await?
.map_err(|e| ApiError::err("couldnt_update_post", e))?; .map_err(|e| ApiError::err("couldnt_update_post", e))?;
blocking(context.pool(), move |conn| { context
Person::delete_account(conn, person_id) .conn()
}) .await?
.interact(move |conn| Person::delete_account(conn, person_id))
.await??; .await??;
Ok(LoginResponse { Ok(LoginResponse {

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::{get_actor_id_from_name, objects::person::ApubPerson}; use lemmy_apub::{get_actor_id_from_name, objects::person::ApubPerson};
use lemmy_apub_lib::{object_id::ObjectId, webfinger::WebfingerType}; use lemmy_apub_lib::{object_id::ObjectId, webfinger::WebfingerType};
use lemmy_db_schema::{from_opt_str_to_opt_enum, SortType}; use lemmy_db_schema::{from_opt_str_to_opt_enum, SortType};
@ -57,9 +57,10 @@ impl PerformCrud for GetPersonDetails {
// You don't need to return settings for the user, since this comes back with GetSite // You don't need to return settings for the user, since this comes back with GetSite
// `my_user` // `my_user`
let person_view = blocking(context.pool(), move |conn| { let person_view = context
PersonViewSafe::read(conn, person_details_id) .conn()
}) .await?
.interact(move |conn| PersonViewSafe::read(conn, person_details_id))
.await??; .await??;
let page = data.page; let page = data.page;
@ -67,7 +68,10 @@ impl PerformCrud for GetPersonDetails {
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) = context
.conn()
.await?
.interact(move |conn| {
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)
@ -102,9 +106,10 @@ impl PerformCrud for GetPersonDetails {
}) })
.await??; .await??;
let moderates = blocking(context.pool(), move |conn| { let moderates = context
CommunityModeratorView::for_person(conn, person_details_id) .conn()
}) .await?
.interact(move |conn| CommunityModeratorView::for_person(conn, person_details_id))
.await??; .await??;
// Return the jwt // Return the jwt

View file

@ -51,6 +51,7 @@ background-jobs = "0.9.1"
reqwest = { version = "0.11.4", features = ["json"] } reqwest = { version = "0.11.4", features = ["json"] }
html2md = "0.2.13" html2md = "0.2.13"
lazy_static = "1.4.0" lazy_static = "1.4.0"
deadpool-diesel = { version = "0.3.1", features = ["postgres"] }
[dev-dependencies] [dev-dependencies]
serial_test = "0.5.1" serial_test = "0.5.1"

View file

@ -13,7 +13,7 @@ use crate::{
protocol::activities::{create_or_update::comment::CreateOrUpdateComment, CreateOrUpdateType}, protocol::activities::{create_or_update::comment::CreateOrUpdateComment, CreateOrUpdateType},
}; };
use activitystreams::public; use activitystreams::public;
use lemmy_api_common::{blocking, check_post_deleted_or_removed}; use lemmy_api_common::check_post_deleted_or_removed;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
data::Data, data::Data,
object_id::ObjectId, object_id::ObjectId,
@ -36,11 +36,16 @@ 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 = context
.conn()
.await?
.interact(move |conn| Post::read(conn, post_id))
.await??;
let community_id = post.community_id; let community_id = post.community_id;
let community: ApubCommunity = blocking(context.pool(), move |conn| { let community: ApubCommunity = context
Community::read(conn, community_id) .conn()
}) .await?
.interact(move |conn| Community::read(conn, community_id))
.await?? .await??
.into(); .into();
@ -116,9 +121,10 @@ impl GetCommunity for CreateOrUpdateComment {
request_counter: &mut i32, request_counter: &mut i32,
) -> Result<ApubCommunity, LemmyError> { ) -> Result<ApubCommunity, LemmyError> {
let post = self.object.get_parents(context, request_counter).await?.0; let post = self.object.get_parents(context, request_counter).await?.0;
let community = blocking(context.pool(), move |conn| { let community = context
Community::read(conn, post.community_id) .conn()
}) .await?
.interact(move |conn| Community::read(conn, post.community_id))
.await??; .await??;
Ok(community.into()) Ok(community.into())
} }

View file

@ -5,7 +5,6 @@ use activitystreams::{
}; };
use anyhow::anyhow; use anyhow::anyhow;
use itertools::Itertools; use itertools::Itertools;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{object_id::ObjectId, traits::ActorType, webfinger::WebfingerResponse}; use lemmy_apub_lib::{object_id::ObjectId, traits::ActorType, webfinger::WebfingerResponse};
use lemmy_db_schema::{ use lemmy_db_schema::{
newtypes::LocalUserId, newtypes::LocalUserId,
@ -31,7 +30,11 @@ 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 = context
.conn()
.await?
.interact(move |conn| Post::read(conn, post_id))
.await??;
let actor = actor.dereference(context, request_counter).await?; let actor = actor.dereference(context, request_counter).await?;
// Note: // Note:
@ -106,16 +109,26 @@ async fn get_comment_parent_creator(
comment: &Comment, comment: &Comment,
) -> Result<ApubPerson, LemmyError> { ) -> Result<ApubPerson, 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 = pool
blocking(pool, move |conn| Comment::read(conn, parent_comment_id)).await??; .get()
.await?
.interact(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 = pool
.get()
.await?
.interact(move |conn| Post::read(conn, parent_post_id))
.await??;
parent_post.creator_id parent_post.creator_id
}; };
Ok( Ok(
blocking(pool, move |conn| Person::read(conn, parent_creator_id)) pool
.get()
.await?
.interact(move |conn| Person::read(conn, parent_creator_id))
.await?? .await??
.into(), .into(),
) )

View file

@ -14,7 +14,6 @@ use crate::{
protocol::activities::community::add_mod::AddMod, protocol::activities::community::add_mod::AddMod,
}; };
use activitystreams::{activity::kind::AddType, public}; use activitystreams::{activity::kind::AddType, public};
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
data::Data, data::Data,
object_id::ObjectId, object_id::ObjectId,
@ -84,18 +83,20 @@ 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 = context
CommunityModerator::get_person_moderated_communities(conn, new_mod_id) .conn()
}) .await?
.interact(move |conn| CommunityModerator::get_person_moderated_communities(conn, new_mod_id))
.await??; .await??;
if !moderated_communities.contains(&community.id) { if !moderated_communities.contains(&community.id) {
let form = CommunityModeratorForm { let form = CommunityModeratorForm {
community_id: community.id, community_id: community.id,
person_id: new_mod.id, person_id: new_mod.id,
}; };
blocking(context.pool(), move |conn| { context
CommunityModerator::join(conn, &form) .conn()
}) .await?
.interact(move |conn| CommunityModerator::join(conn, &form))
.await??; .await??;
} }
// TODO: send websocket notification about added mod // TODO: send websocket notification about added mod

View file

@ -74,7 +74,7 @@ impl ActivityHandler for AnnounceActivity {
let object = serde_json::to_string(&self.object)?; let object = serde_json::to_string(&self.object)?;
let object_data: ActivityCommonFields = serde_json::from_str(&object)?; let object_data: ActivityCommonFields = serde_json::from_str(&object)?;
if is_activity_already_known(context.pool(), &object_data.id).await? { if is_activity_already_known(context, &object_data.id).await? {
return Ok(()); return Ok(());
} }
insert_activity( insert_activity(

View file

@ -12,7 +12,6 @@ use crate::{
protocol::activities::community::block_user::BlockUserFromCommunity, protocol::activities::community::block_user::BlockUserFromCommunity,
}; };
use activitystreams::{activity::kind::BlockType, public}; use activitystreams::{activity::kind::BlockType, public};
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
data::Data, data::Data,
object_id::ObjectId, object_id::ObjectId,
@ -96,9 +95,10 @@ impl ActivityHandler for BlockUserFromCommunity {
person_id: blocked_user.id, person_id: blocked_user.id,
}; };
blocking(context.pool(), move |conn: &'_ _| { context
CommunityPersonBan::ban(conn, &community_user_ban_form) .conn()
}) .await?
.interact(move |conn| CommunityPersonBan::ban(conn, &community_user_ban_form))
.await??; .await??;
// Also unsubscribe them from the community, if they are subscribed // Also unsubscribe them from the community, if they are subscribed
@ -107,9 +107,10 @@ impl ActivityHandler for BlockUserFromCommunity {
person_id: blocked_user.id, person_id: blocked_user.id,
pending: false, pending: false,
}; };
blocking(context.pool(), move |conn: &'_ _| { context
CommunityFollower::unfollow(conn, &community_follower_form) .conn()
}) .await?
.interact(move |conn| CommunityFollower::unfollow(conn, &community_follower_form))
.await? .await?
.ok(); .ok();

View file

@ -14,7 +14,6 @@ use crate::{
protocol::activities::community::remove_mod::RemoveMod, protocol::activities::community::remove_mod::RemoveMod,
}; };
use activitystreams::{activity::kind::RemoveType, public}; use activitystreams::{activity::kind::RemoveType, public};
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
data::Data, data::Data,
object_id::ObjectId, object_id::ObjectId,
@ -84,9 +83,10 @@ 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| { context
CommunityModerator::leave(conn, &form) .conn()
}) .await?
.interact(move |conn| CommunityModerator::leave(conn, &form))
.await??; .await??;
// TODO: send websocket notification about removed mod // TODO: send websocket notification about removed mod
Ok(()) Ok(())

View file

@ -10,7 +10,7 @@ use crate::{
PostOrComment, PostOrComment,
}; };
use activitystreams::activity::kind::FlagType; use activitystreams::activity::kind::FlagType;
use lemmy_api_common::{blocking, comment::CommentReportResponse, post::PostReportResponse}; use lemmy_api_common::{comment::CommentReportResponse, post::PostReportResponse};
use lemmy_apub_lib::{ use lemmy_apub_lib::{
data::Data, data::Data,
object_id::ObjectId, object_id::ObjectId,
@ -93,14 +93,16 @@ impl ActivityHandler for Report {
original_post_body: post.body.clone(), original_post_body: post.body.clone(),
}; };
let report = blocking(context.pool(), move |conn| { let report = context
PostReport::report(conn, &report_form) .conn()
}) .await?
.interact(move |conn| PostReport::report(conn, &report_form))
.await??; .await??;
let post_report_view = blocking(context.pool(), move |conn| { let post_report_view = context
PostReportView::read(conn, report.id, actor.id) .conn()
}) .await?
.interact(move |conn| PostReportView::read(conn, report.id, actor.id))
.await??; .await??;
context.chat_server().do_send(SendModRoomMessage { context.chat_server().do_send(SendModRoomMessage {
@ -118,14 +120,16 @@ impl ActivityHandler for Report {
reason: self.summary, reason: self.summary,
}; };
let report = blocking(context.pool(), move |conn| { let report = context
CommentReport::report(conn, &report_form) .conn()
}) .await?
.interact(move |conn| CommentReport::report(conn, &report_form))
.await??; .await??;
let comment_report_view = blocking(context.pool(), move |conn| { let comment_report_view = context
CommentReportView::read(conn, report.id, actor.id) .conn()
}) .await?
.interact(move |conn| CommentReportView::read(conn, report.id, actor.id))
.await??; .await??;
let community_id = comment_report_view.community.id; let community_id = comment_report_view.community.id;

View file

@ -15,7 +15,6 @@ use crate::{
}, },
}; };
use activitystreams::{activity::kind::UndoType, public}; use activitystreams::{activity::kind::UndoType, public};
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
data::Data, data::Data,
object_id::ObjectId, object_id::ObjectId,
@ -91,9 +90,10 @@ impl ActivityHandler for UndoBlockUserFromCommunity {
person_id: blocked_user.id, person_id: blocked_user.id,
}; };
blocking(context.pool(), move |conn: &'_ _| { context
CommunityPersonBan::unban(conn, &community_user_ban_form) .conn()
}) .await?
.interact(move |conn| CommunityPersonBan::unban(conn, &community_user_ban_form))
.await??; .await??;
Ok(()) Ok(())

View file

@ -12,7 +12,6 @@ use crate::{
protocol::activities::community::update::UpdateCommunity, protocol::activities::community::update::UpdateCommunity,
}; };
use activitystreams::{activity::kind::UpdateType, public}; use activitystreams::{activity::kind::UpdateType, public};
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
data::Data, data::Data,
object_id::ObjectId, object_id::ObjectId,
@ -91,9 +90,10 @@ 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 = context
Community::update(conn, community.id, &cf) .conn()
}) .await?
.interact(move |conn| Community::update(conn, community.id, &cf))
.await??; .await??;
send_community_ws_message( send_community_ws_message(

View file

@ -12,7 +12,6 @@ use crate::{
}; };
use activitystreams::{activity::kind::DeleteType, public}; use activitystreams::{activity::kind::DeleteType, public};
use anyhow::anyhow; use anyhow::anyhow;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
data::Data, data::Data,
object_id::ObjectId, object_id::ObjectId,
@ -143,13 +142,15 @@ pub(in crate::activities) async fn receive_remove_action(
reason, reason,
expires: None, expires: None,
}; };
blocking(context.pool(), move |conn| { context
ModRemoveCommunity::create(conn, &form) .conn()
}) .await?
.interact(move |conn| ModRemoveCommunity::create(conn, &form))
.await??; .await??;
let deleted_community = blocking(context.pool(), move |conn| { let deleted_community = context
Community::update_removed(conn, community.id, true) .conn()
}) .await?
.interact(move |conn| Community::update_removed(conn, community.id, true))
.await??; .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?;
@ -161,13 +162,15 @@ pub(in crate::activities) async fn receive_remove_action(
removed: Some(true), removed: Some(true),
reason, reason,
}; };
blocking(context.pool(), move |conn| { context
ModRemovePost::create(conn, &form) .conn()
}) .await?
.interact(move |conn| ModRemovePost::create(conn, &form))
.await??; .await??;
let removed_post = blocking(context.pool(), move |conn| { let removed_post = context
Post::update_removed(conn, post.id, true) .conn()
}) .await?
.interact(move |conn| Post::update_removed(conn, post.id, true))
.await??; .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?;
@ -179,13 +182,15 @@ pub(in crate::activities) async fn receive_remove_action(
removed: Some(true), removed: Some(true),
reason, reason,
}; };
blocking(context.pool(), move |conn| { context
ModRemoveComment::create(conn, &form) .conn()
}) .await?
.interact(move |conn| ModRemoveComment::create(conn, &form))
.await??; .await??;
let removed_comment = blocking(context.pool(), move |conn| { let removed_comment = context
Comment::update_removed(conn, comment.id, true) .conn()
}) .await?
.interact(move |conn| Comment::update_removed(conn, comment.id, true))
.await??; .await??;
send_comment_ws_message_simple(removed_comment.id, RemoveComment, context).await?; send_comment_ws_message_simple(removed_comment.id, RemoveComment, context).await?;
@ -204,14 +209,19 @@ impl GetCommunity for Delete {
let community_id = match DeletableObjects::read_from_db(&self.object, context).await? { let community_id = match DeletableObjects::read_from_db(&self.object, context).await? {
DeletableObjects::Community(c) => c.id, DeletableObjects::Community(c) => c.id,
DeletableObjects::Comment(c) => { DeletableObjects::Comment(c) => {
let post = blocking(context.pool(), move |conn| Post::read(conn, c.post_id)).await??; let post = context
.conn()
.await?
.interact(move |conn| Post::read(conn, c.post_id))
.await??;
post.community_id post.community_id
} }
DeletableObjects::Post(p) => p.community_id, DeletableObjects::Post(p) => p.community_id,
}; };
let community = blocking(context.pool(), move |conn| { let community = context
Community::read(conn, community_id) .conn()
}) .await?
.interact(move |conn| Community::read(conn, community_id))
.await??; .await??;
Ok(community.into()) Ok(community.into())
} }

View file

@ -3,7 +3,6 @@ use crate::{
objects::{comment::ApubComment, community::ApubCommunity, person::ApubPerson, post::ApubPost}, objects::{comment::ApubComment, community::ApubCommunity, person::ApubPerson, post::ApubPost},
protocol::activities::deletion::{delete::Delete, undo_delete::UndoDelete}, protocol::activities::deletion::{delete::Delete, undo_delete::UndoDelete},
}; };
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
object_id::ObjectId, object_id::ObjectId,
traits::{ActorType, ApubObject}, traits::{ActorType, ApubObject},
@ -157,9 +156,10 @@ 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 = context
Community::update_deleted(conn, community.id, deleted) .conn()
}) .await?
.interact(move |conn| Community::update_deleted(conn, community.id, deleted))
.await??; .await??;
send_community_ws_message( send_community_ws_message(
community.id, community.id,
@ -172,9 +172,10 @@ async fn receive_delete_action(
} }
DeletableObjects::Post(post) => { DeletableObjects::Post(post) => {
if deleted != post.deleted { if deleted != post.deleted {
let deleted_post = blocking(context.pool(), move |conn| { let deleted_post = context
Post::update_deleted(conn, post.id, deleted) .conn()
}) .await?
.interact(move |conn| Post::update_deleted(conn, post.id, deleted))
.await??; .await??;
send_post_ws_message( send_post_ws_message(
deleted_post.id, deleted_post.id,
@ -188,9 +189,10 @@ async fn receive_delete_action(
} }
DeletableObjects::Comment(comment) => { DeletableObjects::Comment(comment) => {
if deleted != comment.deleted { if deleted != comment.deleted {
let deleted_comment = blocking(context.pool(), move |conn| { let deleted_comment = context
Comment::update_deleted(conn, comment.id, deleted) .conn()
}) .await?
.interact(move |conn| Comment::update_deleted(conn, comment.id, deleted))
.await??; .await??;
send_comment_ws_message_simple( send_comment_ws_message_simple(
deleted_comment.id, deleted_comment.id,

View file

@ -12,7 +12,6 @@ use crate::{
}; };
use activitystreams::{activity::kind::UndoType, public}; use activitystreams::{activity::kind::UndoType, public};
use anyhow::anyhow; use anyhow::anyhow;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
data::Data, data::Data,
object_id::ObjectId, object_id::ObjectId,
@ -109,23 +108,26 @@ 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 = context
Community::update_removed(conn, community.id, false) .conn()
}) .await?
.interact(move |conn| Community::update_removed(conn, community.id, false))
.await??; .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 = context
Post::update_removed(conn, post.id, false) .conn()
}) .await?
.interact(move |conn| Post::update_removed(conn, post.id, false))
.await??; .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 = context
Comment::update_removed(conn, comment.id, false) .conn()
}) .await?
.interact(move |conn| Comment::update_removed(conn, comment.id, false))
.await??; .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

@ -3,7 +3,6 @@ use crate::{
protocol::activities::following::{accept::AcceptFollowCommunity, follow::FollowCommunity}, protocol::activities::following::{accept::AcceptFollowCommunity, follow::FollowCommunity},
}; };
use activitystreams::activity::kind::AcceptType; use activitystreams::activity::kind::AcceptType;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
data::Data, data::Data,
object_id::ObjectId, object_id::ObjectId,
@ -66,9 +65,10 @@ impl ActivityHandler for AcceptFollowCommunity {
let actor = self.actor.dereference(context, request_counter).await?; let actor = self.actor.dereference(context, request_counter).await?;
let to = self.to[0].dereference(context, request_counter).await?; let to = self.to[0].dereference(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| { context
CommunityFollower::follow_accepted(conn, actor.id, to.id) .conn()
}) .await?
.interact(move |conn| CommunityFollower::follow_accepted(conn, actor.id, to.id))
.await??; .await??;
Ok(()) Ok(())

View file

@ -10,7 +10,6 @@ use crate::{
protocol::activities::following::{accept::AcceptFollowCommunity, follow::FollowCommunity}, protocol::activities::following::{accept::AcceptFollowCommunity, follow::FollowCommunity},
}; };
use activitystreams::activity::kind::FollowType; use activitystreams::activity::kind::FollowType;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
data::Data, data::Data,
object_id::ObjectId, object_id::ObjectId,
@ -52,9 +51,10 @@ impl FollowCommunity {
person_id: actor.id, person_id: actor.id,
pending: true, pending: true,
}; };
blocking(context.pool(), move |conn| { context
CommunityFollower::follow(conn, &community_follower_form).ok() .conn()
}) .await?
.interact(move |conn| CommunityFollower::follow(conn, &community_follower_form).ok())
.await?; .await?;
let follow = FollowCommunity::new(actor, community, context)?; let follow = FollowCommunity::new(actor, community, context)?;
@ -93,9 +93,10 @@ 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| { context
CommunityFollower::follow(conn, &community_follower_form).ok() .conn()
}) .await?
.interact(move |conn| CommunityFollower::follow(conn, &community_follower_form).ok())
.await?; .await?;
AcceptFollowCommunity::send(self, context, request_counter).await AcceptFollowCommunity::send(self, context, request_counter).await

View file

@ -4,7 +4,6 @@ use crate::{
protocol::activities::following::{follow::FollowCommunity, undo_follow::UndoFollowCommunity}, protocol::activities::following::{follow::FollowCommunity, undo_follow::UndoFollowCommunity},
}; };
use activitystreams::activity::kind::UndoType; use activitystreams::activity::kind::UndoType;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
data::Data, data::Data,
object_id::ObjectId, object_id::ObjectId,
@ -72,9 +71,10 @@ 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| { context
CommunityFollower::unfollow(conn, &community_follower_form).ok() .conn()
}) .await?
.interact(move |conn| CommunityFollower::unfollow(conn, &community_follower_form).ok())
.await?; .await?;
Ok(()) Ok(())
} }

View file

@ -7,7 +7,6 @@ use crate::{
}; };
use activitystreams::public; use activitystreams::public;
use anyhow::anyhow; use anyhow::anyhow;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
activity_queue::send_activity, activity_queue::send_activity,
object_id::ObjectId, object_id::ObjectId,
@ -62,9 +61,12 @@ pub(crate) async fn verify_person_in_community(
} }
let person_id = person.id; let person_id = person.id;
let community_id = community.id; let community_id = community.id;
let is_banned = if context
move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok(); .conn()
if blocking(context.pool(), is_banned).await? { .await?
.interact(move |conn| CommunityPersonBanView::get(conn, person_id, community_id).is_ok())
.await?
{
return Err(anyhow!("Person is banned from community").into()); return Err(anyhow!("Person is banned from community").into());
} }
@ -93,9 +95,10 @@ pub(crate) async fn verify_mod_action(
// 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 = context
CommunityView::is_mod_or_admin(conn, actor_id, community_id) .conn()
}) .await?
.interact(move |conn| CommunityView::is_mod_or_admin(conn, actor_id, community_id))
.await?; .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

@ -14,7 +14,6 @@ use crate::{
}; };
use activitystreams::public; use activitystreams::public;
use anyhow::anyhow; use anyhow::anyhow;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
data::Data, data::Data,
object_id::ObjectId, object_id::ObjectId,
@ -54,9 +53,10 @@ impl CreateOrUpdatePost {
context: &LemmyContext, context: &LemmyContext,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let community_id = post.community_id; let community_id = post.community_id;
let community: ApubCommunity = blocking(context.pool(), move |conn| { let community: ApubCommunity = context
Community::read(conn, community_id) .conn()
}) .await?
.interact(move |conn| Community::read(conn, community_id))
.await?? .await??
.into(); .into();
let create_or_update = CreateOrUpdatePost::new(post, actor, &community, kind, context).await?; let create_or_update = CreateOrUpdatePost::new(post, actor, &community, kind, context).await?;

View file

@ -6,7 +6,6 @@ use crate::{
CreateOrUpdateType, CreateOrUpdateType,
}, },
}; };
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
data::Data, data::Data,
object_id::ObjectId, object_id::ObjectId,
@ -25,8 +24,10 @@ 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: ApubPerson = let recipient: ApubPerson = context
blocking(context.pool(), move |conn| Person::read(conn, recipient_id)) .conn()
.await?
.interact(move |conn| Person::read(conn, recipient_id))
.await?? .await??
.into(); .into();

View file

@ -4,7 +4,6 @@ use crate::{
protocol::activities::private_message::delete::DeletePrivateMessage, protocol::activities::private_message::delete::DeletePrivateMessage,
}; };
use activitystreams::activity::kind::DeleteType; use activitystreams::activity::kind::DeleteType;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
data::Data, data::Data,
object_id::ObjectId, object_id::ObjectId,
@ -45,8 +44,10 @@ 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: ApubPerson = let recipient: ApubPerson = context
blocking(context.pool(), move |conn| Person::read(conn, recipient_id)) .conn()
.await?
.interact(move |conn| Person::read(conn, recipient_id))
.await?? .await??
.into(); .into();
let inbox = vec![recipient.shared_inbox_or_inbox_url()]; let inbox = vec![recipient.shared_inbox_or_inbox_url()];
@ -74,9 +75,10 @@ impl ActivityHandler for DeletePrivateMessage {
_request_counter: &mut i32, _request_counter: &mut i32,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let private_message = self.object.dereference_local(context).await?; let private_message = self.object.dereference_local(context).await?;
let deleted_private_message = blocking(context.pool(), move |conn| { let deleted_private_message = context
PrivateMessage::update_deleted(conn, private_message.id, true) .conn()
}) .await?
.interact(move |conn| PrivateMessage::update_deleted(conn, private_message.id, true))
.await??; .await??;
send_pm_ws_message( send_pm_ws_message(

View file

@ -7,7 +7,6 @@ use crate::{
}, },
}; };
use activitystreams::activity::kind::UndoType; use activitystreams::activity::kind::UndoType;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
data::Data, data::Data,
object_id::ObjectId, object_id::ObjectId,
@ -28,8 +27,10 @@ impl UndoDeletePrivateMessage {
context: &LemmyContext, context: &LemmyContext,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let recipient_id = pm.recipient_id; let recipient_id = pm.recipient_id;
let recipient: ApubPerson = let recipient: ApubPerson = context
blocking(context.pool(), move |conn| Person::read(conn, recipient_id)) .conn()
.await?
.interact(move |conn| Person::read(conn, recipient_id))
.await?? .await??
.into(); .into();
@ -75,9 +76,10 @@ impl ActivityHandler for UndoDeletePrivateMessage {
let ap_id = self.object.object.clone(); let ap_id = self.object.object.clone();
let private_message = ap_id.dereference_local(context).await?; let private_message = ap_id.dereference_local(context).await?;
let deleted_private_message = blocking(context.pool(), move |conn| { let deleted_private_message = context
PrivateMessage::update_deleted(conn, private_message.id, false) .conn()
}) .await?
.interact(move |conn| PrivateMessage::update_deleted(conn, private_message.id, false))
.await??; .await??;
send_pm_ws_message( send_pm_ws_message(

View file

@ -1,4 +1,3 @@
use lemmy_api_common::blocking;
use lemmy_db_schema::{ use lemmy_db_schema::{
source::{ source::{
comment::{CommentLike, CommentLikeForm}, comment::{CommentLike, CommentLikeForm},
@ -35,7 +34,10 @@ 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| { context
.conn()
.await?
.interact(move |conn| {
CommentLike::remove(conn, person_id, comment_id)?; CommentLike::remove(conn, person_id, comment_id)?;
CommentLike::like(conn, &like_form) CommentLike::like(conn, &like_form)
}) })
@ -58,7 +60,10 @@ 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| { context
.conn()
.await?
.interact(move |conn| {
PostLike::remove(conn, person_id, post_id)?; PostLike::remove(conn, person_id, post_id)?;
PostLike::like(conn, &like_form) PostLike::like(conn, &like_form)
}) })
@ -75,9 +80,10 @@ 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| { context
CommentLike::remove(conn, person_id, comment_id) .conn()
}) .await?
.interact(move |conn| CommentLike::remove(conn, person_id, comment_id))
.await??; .await??;
send_comment_ws_message_simple(comment_id, UserOperation::CreateCommentLike, context).await?; send_comment_ws_message_simple(comment_id, UserOperation::CreateCommentLike, context).await?;
@ -91,9 +97,10 @@ 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| { context
PostLike::remove(conn, person_id, post_id) .conn()
}) .await?
.interact(move |conn| PostLike::remove(conn, person_id, post_id))
.await??; .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?;

View file

@ -16,7 +16,6 @@ use crate::{
PostOrComment, PostOrComment,
}; };
use activitystreams::{activity::kind::UndoType, public}; use activitystreams::{activity::kind::UndoType, public};
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
data::Data, data::Data,
object_id::ObjectId, object_id::ObjectId,
@ -35,9 +34,10 @@ impl UndoVote {
kind: VoteType, kind: VoteType,
context: &LemmyContext, context: &LemmyContext,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let community: ApubCommunity = blocking(context.pool(), move |conn| { let community: ApubCommunity = context
Community::read(conn, community_id) .conn()
}) .await?
.interact(move |conn| Community::read(conn, community_id))
.await?? .await??
.into(); .into();

View file

@ -13,7 +13,6 @@ use crate::{
PostOrComment, PostOrComment,
}; };
use activitystreams::public; use activitystreams::public;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
data::Data, data::Data,
object_id::ObjectId, object_id::ObjectId,
@ -53,9 +52,10 @@ impl Vote {
kind: VoteType, kind: VoteType,
context: &LemmyContext, context: &LemmyContext,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let community = blocking(context.pool(), move |conn| { let community = context
Community::read(conn, community_id) .conn()
}) .await?
.interact(move |conn| Community::read(conn, community_id))
.await?? .await??
.into(); .into();
let vote = Vote::new(object, actor, &community, kind, context)?; let vote = Vote::new(object, actor, &community, kind, context)?;
@ -106,12 +106,19 @@ impl GetCommunity for Vote {
let cid = match object { let cid = match object {
PostOrComment::Post(p) => p.community_id, PostOrComment::Post(p) => p.community_id,
PostOrComment::Comment(c) => { PostOrComment::Comment(c) => {
blocking(context.pool(), move |conn| Post::read(conn, c.post_id)) context
.conn()
.await?
.interact(move |conn| Post::read(conn, c.post_id))
.await?? .await??
.community_id .community_id
} }
}; };
let community = blocking(context.pool(), move |conn| Community::read(conn, cid)).await??; let community = context
.conn()
.await?
.interact(move |conn| Community::read(conn, cid))
.await??;
Ok(community.into()) Ok(community.into())
} }
} }

View file

@ -5,7 +5,6 @@ use crate::{
protocol::collections::group_moderators::GroupModerators, protocol::collections::group_moderators::GroupModerators,
}; };
use activitystreams::{chrono::NaiveDateTime, collection::kind::OrderedCollectionType}; use activitystreams::{chrono::NaiveDateTime, collection::kind::OrderedCollectionType};
use lemmy_api_common::blocking;
use lemmy_apub_lib::{object_id::ObjectId, traits::ApubObject, verify::verify_domains_match}; use lemmy_apub_lib::{object_id::ObjectId, traits::ApubObject, verify::verify_domains_match};
use lemmy_db_schema::{ use lemmy_db_schema::{
source::community::{CommunityModerator, CommunityModeratorForm}, source::community::{CommunityModerator, CommunityModeratorForm},
@ -32,12 +31,14 @@ impl ApubObject for ApubCommunityModerators {
_object_id: Url, _object_id: Url,
data: &Self::DataType, data: &Self::DataType,
) -> Result<Option<Self>, LemmyError> { ) -> Result<Option<Self>, LemmyError> {
let context = &data.1;
// Only read from database if its a local community, otherwise fetch over http // Only read from database if its a local community, otherwise fetch over http
if data.0.local { if data.0.local {
let cid = data.0.id; let cid = data.0.id;
let moderators = blocking(data.1.pool(), move |conn| { let moderators = context
CommunityModeratorView::for_community(conn, cid) .conn()
}) .await?
.interact(move |conn| CommunityModeratorView::for_community(conn, cid))
.await??; .await??;
Ok(Some(ApubCommunityModerators { 0: moderators })) Ok(Some(ApubCommunityModerators { 0: moderators }))
} else { } else {
@ -81,10 +82,12 @@ impl ApubObject for ApubCommunityModerators {
data: &Self::DataType, data: &Self::DataType,
request_counter: &mut i32, request_counter: &mut i32,
) -> Result<Self, LemmyError> { ) -> Result<Self, LemmyError> {
let context = &data.1;
let community_id = data.0.id; let community_id = data.0.id;
let current_moderators = blocking(data.1.pool(), move |conn| { let current_moderators = context
CommunityModeratorView::for_community(conn, community_id) .conn()
}) .await?
.interact(move |conn| CommunityModeratorView::for_community(conn, community_id))
.await??; .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 {
@ -94,9 +97,10 @@ impl ApubObject for ApubCommunityModerators {
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(data.1.pool(), move |conn| { context
CommunityModerator::leave(conn, &community_moderator_form) .conn()
}) .await?
.interact(move |conn| CommunityModerator::leave(conn, &community_moderator_form))
.await??; .await??;
} }
} }
@ -115,9 +119,10 @@ impl ApubObject for ApubCommunityModerators {
community_id: data.0.id, community_id: data.0.id,
person_id: mod_user.id, person_id: mod_user.id,
}; };
blocking(data.1.pool(), move |conn| { context
CommunityModerator::join(conn, &community_moderator_form) .conn()
}) .await?
.interact(move |conn| CommunityModerator::join(conn, &community_moderator_form))
.await??; .await??;
} }
} }
@ -136,6 +141,7 @@ mod tests {
tests::{file_to_json_object, init_context}, tests::{file_to_json_object, init_context},
}; };
use lemmy_db_schema::{ use lemmy_db_schema::{
establish_unpooled_connection,
source::{ source::{
community::Community, community::Community,
person::{Person, PersonForm}, person::{Person, PersonForm},
@ -150,18 +156,19 @@ mod tests {
let context = init_context(); let context = init_context();
let community = parse_lemmy_community(&context).await; let community = parse_lemmy_community(&context).await;
let community_id = community.id; let community_id = community.id;
let conn = establish_unpooled_connection();
let old_mod = PersonForm { let old_mod = PersonForm {
name: "holly".into(), name: "holly".into(),
..PersonForm::default() ..PersonForm::default()
}; };
let old_mod = Person::create(&context.pool().get().unwrap(), &old_mod).unwrap(); let old_mod = Person::create(&conn, &old_mod).unwrap();
let community_moderator_form = CommunityModeratorForm { let community_moderator_form = CommunityModeratorForm {
community_id: community.id, community_id: community.id,
person_id: old_mod.id, person_id: old_mod.id,
}; };
CommunityModerator::join(&context.pool().get().unwrap(), &community_moderator_form).unwrap(); CommunityModerator::join(&conn, &community_moderator_form).unwrap();
let new_mod = parse_lemmy_person(&context).await; let new_mod = parse_lemmy_person(&context).await;
@ -181,22 +188,13 @@ mod tests {
.unwrap(); .unwrap();
assert_eq!(request_counter, 0); assert_eq!(request_counter, 0);
let current_moderators = blocking(community_context.1.pool(), move |conn| { let current_moderators = CommunityModeratorView::for_community(&conn, community_id).unwrap();
CommunityModeratorView::for_community(conn, community_id)
})
.await
.unwrap()
.unwrap();
assert_eq!(current_moderators.len(), 1); assert_eq!(current_moderators.len(), 1);
assert_eq!(current_moderators[0].moderator.id, new_mod.id); assert_eq!(current_moderators[0].moderator.id, new_mod.id);
Person::delete(&*community_context.1.pool().get().unwrap(), old_mod.id).unwrap(); Person::delete(&conn, old_mod.id).unwrap();
Person::delete(&*community_context.1.pool().get().unwrap(), new_mod.id).unwrap(); Person::delete(&conn, new_mod.id).unwrap();
Community::delete( Community::delete(&conn, community_context.0.id).unwrap();
&*community_context.1.pool().get().unwrap(),
community_context.0.id,
)
.unwrap();
} }
} }

View file

@ -9,7 +9,6 @@ use crate::{
}; };
use activitystreams::collection::kind::OrderedCollectionType; use activitystreams::collection::kind::OrderedCollectionType;
use chrono::NaiveDateTime; use chrono::NaiveDateTime;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
data::Data, data::Data,
traits::{ActivityHandler, ApubObject}, traits::{ActivityHandler, ApubObject},
@ -39,12 +38,14 @@ impl ApubObject for ApubCommunityOutbox {
_object_id: Url, _object_id: Url,
data: &Self::DataType, data: &Self::DataType,
) -> Result<Option<Self>, LemmyError> { ) -> Result<Option<Self>, LemmyError> {
let context = &data.1;
// Only read from database if its a local community, otherwise fetch over http // Only read from database if its a local community, otherwise fetch over http
if data.0.local { if data.0.local {
let community_id = data.0.id; let community_id = data.0.id;
let post_list: Vec<ApubPost> = blocking(data.1.pool(), move |conn| { let post_list: Vec<ApubPost> = context
Post::list_for_community(conn, community_id) .conn()
}) .await?
.interact(move |conn| Post::list_for_community(conn, community_id))
.await?? .await??
.into_iter() .into_iter()
.map(Into::into) .map(Into::into)
@ -61,14 +62,18 @@ impl ApubObject for ApubCommunityOutbox {
} }
async fn into_apub(self, data: &Self::DataType) -> Result<Self::ApubType, LemmyError> { async fn into_apub(self, data: &Self::DataType) -> Result<Self::ApubType, LemmyError> {
let context = &data.1;
let mut ordered_items = vec![]; let mut ordered_items = vec![];
for post in self.0 { for post in self.0 {
let actor = post.creator_id; let actor = post.creator_id;
let actor: ApubPerson = blocking(data.1.pool(), move |conn| Person::read(conn, actor)) let actor: ApubPerson = context
.conn()
.await?
.interact(move |conn| Person::read(conn, actor))
.await?? .await??
.into(); .into();
let a = let a =
CreateOrUpdatePost::new(post, &actor, &data.0, CreateOrUpdateType::Create, &data.1).await?; CreateOrUpdatePost::new(post, &actor, &data.0, CreateOrUpdateType::Create, context).await?;
ordered_items.push(a); ordered_items.push(a);
} }
@ -100,6 +105,7 @@ impl ApubObject for ApubCommunityOutbox {
data: &Self::DataType, data: &Self::DataType,
request_counter: &mut i32, request_counter: &mut i32,
) -> Result<Self, LemmyError> { ) -> Result<Self, LemmyError> {
let context = &data.1;
let mut outbox_activities = apub.ordered_items; let mut outbox_activities = apub.ordered_items;
if outbox_activities.len() > 20 { if outbox_activities.len() > 20 {
outbox_activities = outbox_activities[0..20].to_vec(); outbox_activities = outbox_activities[0..20].to_vec();
@ -110,7 +116,7 @@ impl ApubObject for ApubCommunityOutbox {
// item and only parse the ones that work. // item and only parse the ones that work.
for activity in outbox_activities { for activity in outbox_activities {
activity activity
.receive(&Data::new(data.1.clone()), request_counter) .receive(&Data::new(context.clone()), request_counter)
.await .await
.ok(); .ok();
} }

View file

@ -5,16 +5,12 @@ use crate::{
use anyhow::anyhow; use anyhow::anyhow;
use chrono::NaiveDateTime; use chrono::NaiveDateTime;
use itertools::Itertools; use itertools::Itertools;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
object_id::ObjectId, object_id::ObjectId,
traits::ApubObject, traits::ApubObject,
webfinger::{webfinger_resolve_actor, WebfingerType}, webfinger::{webfinger_resolve_actor, WebfingerType},
}; };
use lemmy_db_schema::{ use lemmy_db_schema::source::{community::Community, person::Person as DbPerson};
source::{community::Community, person::Person as DbPerson},
DbPool,
};
use lemmy_utils::LemmyError; use lemmy_utils::LemmyError;
use lemmy_websocket::LemmyContext; use lemmy_websocket::LemmyContext;
use serde::Deserialize; use serde::Deserialize;
@ -54,7 +50,7 @@ pub async fn search_by_apub_id(
} }
// local actor, read from database and return // local actor, read from database and return
else { else {
return find_local_actor_by_name(name, kind, context.pool()).await; return find_local_actor_by_name(name, kind, context).await;
} }
} }
}; };
@ -68,17 +64,23 @@ pub async fn search_by_apub_id(
async fn find_local_actor_by_name( async fn find_local_actor_by_name(
name: &str, name: &str,
kind: WebfingerType, kind: WebfingerType,
pool: &DbPool, context: &LemmyContext,
) -> Result<SearchableObjects, LemmyError> { ) -> Result<SearchableObjects, LemmyError> {
let name: String = name.into(); let name: String = name.into();
Ok(match kind { Ok(match kind {
WebfingerType::Group => SearchableObjects::Community( WebfingerType::Group => SearchableObjects::Community(
blocking(pool, move |conn| Community::read_from_name(conn, &name)) context
.conn()
.await?
.interact(move |conn| Community::read_from_name(conn, &name))
.await?? .await??
.into(), .into(),
), ),
WebfingerType::Person => SearchableObjects::Person( WebfingerType::Person => SearchableObjects::Person(
blocking(pool, move |conn| DbPerson::find_by_name(conn, &name)) context
.conn()
.await?
.interact(move |conn| DbPerson::find_by_name(conn, &name))
.await?? .await??
.into(), .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_apub_lib::traits::ApubObject; use lemmy_apub_lib::traits::ApubObject;
use lemmy_db_schema::{newtypes::CommentId, source::comment::Comment, traits::Crud}; use lemmy_db_schema::{newtypes::CommentId, source::comment::Comment, traits::Crud};
use lemmy_utils::LemmyError; use lemmy_utils::LemmyError;
@ -22,7 +21,10 @@ 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: ApubComment = blocking(context.pool(), move |conn| Comment::read(conn, id)) let comment: ApubComment = context
.conn()
.await?
.interact(move |conn| Comment::read(conn, id))
.await?? .await??
.into(); .into();
if !comment.local { if !comment.local {

View file

@ -22,7 +22,6 @@ use crate::{
}, },
}; };
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::{object_id::ObjectId, traits::ApubObject}; use lemmy_apub_lib::{object_id::ObjectId, traits::ApubObject};
use lemmy_db_schema::source::community::Community; use lemmy_db_schema::source::community::Community;
use lemmy_utils::LemmyError; use lemmy_utils::LemmyError;
@ -40,9 +39,10 @@ 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: ApubCommunity = blocking(context.pool(), move |conn| { let community: ApubCommunity = context
Community::read_from_name(conn, &info.community_name) .conn()
}) .await?
.interact(move |conn| Community::read_from_name(conn, &info.community_name))
.await?? .await??
.into(); .into();
@ -97,9 +97,10 @@ 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 = context
Community::read_from_name(conn, &info.community_name) .conn()
}) .await?
.interact(move |conn| Community::read_from_name(conn, &info.community_name))
.await??; .await??;
let followers = GroupFollowers::new(community, &context).await?; let followers = GroupFollowers::new(community, &context).await?;
Ok(create_apub_response(&followers)) Ok(create_apub_response(&followers))
@ -111,9 +112,10 @@ 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 = context
Community::read_from_name(conn, &info.community_name) .conn()
}) .await?
.interact(move |conn| Community::read_from_name(conn, &info.community_name))
.await??; .await??;
let id = ObjectId::new(generate_outbox_url(&community.actor_id)?); let id = ObjectId::new(generate_outbox_url(&community.actor_id)?);
let outbox_data = CommunityContext(community.into(), context.get_ref().clone()); let outbox_data = CommunityContext(community.into(), context.get_ref().clone());
@ -125,9 +127,10 @@ 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: ApubCommunity = blocking(context.pool(), move |conn| { let community: ApubCommunity = context
Community::read_from_name(conn, &info.community_name) .conn()
}) .await?
.interact(move |conn| Community::read_from_name(conn, &info.community_name))
.await?? .await??
.into(); .into();
let id = ObjectId::new(generate_outbox_url(&community.actor_id)?); let id = ObjectId::new(generate_outbox_url(&community.actor_id)?);

View file

@ -16,7 +16,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::{ use lemmy_apub_lib::{
data::Data, data::Data,
object_id::ObjectId, object_id::ObjectId,
@ -24,7 +23,7 @@ use lemmy_apub_lib::{
traits::{ActivityHandler, ActorType}, traits::{ActivityHandler, ActorType},
APUB_JSON_CONTENT_TYPE, APUB_JSON_CONTENT_TYPE,
}; };
use lemmy_db_schema::{source::activity::Activity, DbPool}; use lemmy_db_schema::source::activity::Activity;
use lemmy_utils::{location_info, LemmyError}; use lemmy_utils::{location_info, LemmyError};
use lemmy_websocket::LemmyContext; use lemmy_websocket::LemmyContext;
use log::info; use log::info;
@ -98,7 +97,7 @@ where
verify_signature(&request, &actor.public_key().context(location_info!())?)?; verify_signature(&request, &actor.public_key().context(location_info!())?)?;
// Do nothing if we received the same activity before // Do nothing if we received the same activity before
if is_activity_already_known(context.pool(), &activity_data.id).await? { if is_activity_already_known(context, &activity_data.id).await? {
return Ok(HttpResponse::Ok().finish()); return Ok(HttpResponse::Ok().finish());
} }
info!("Verifying activity {}", activity_data.id.to_string()); info!("Verifying activity {}", activity_data.id.to_string());
@ -165,9 +164,10 @@ pub(crate) async fn get_activity(
info.id info.id
))? ))?
.into(); .into();
let activity = blocking(context.pool(), move |conn| { let activity = context
Activity::read_from_apub_id(conn, &activity_id) .conn()
}) .await?
.interact(move |conn| Activity::read_from_apub_id(conn, &activity_id))
.await??; .await??;
let sensitive = activity.sensitive.unwrap_or(true); let sensitive = activity.sensitive.unwrap_or(true);
@ -179,13 +179,14 @@ pub(crate) async fn get_activity(
} }
pub(crate) async fn is_activity_already_known( pub(crate) async fn is_activity_already_known(
pool: &DbPool, context: &LemmyContext,
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 = context
Activity::read_from_apub_id(conn, &activity_id) .conn()
}) .await?
.interact(move |conn| Activity::read_from_apub_id(conn, &activity_id))
.await?; .await?;
match existing { match existing {
Ok(_) => Ok(true), Ok(_) => Ok(true),

View file

@ -12,7 +12,6 @@ use crate::{
protocol::collections::person_outbox::PersonOutbox, protocol::collections::person_outbox::PersonOutbox,
}; };
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::traits::ApubObject; use lemmy_apub_lib::traits::ApubObject;
use lemmy_db_schema::source::person::Person; use lemmy_db_schema::source::person::Person;
use lemmy_utils::LemmyError; use lemmy_utils::LemmyError;
@ -32,9 +31,10 @@ 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: ApubPerson = blocking(context.pool(), move |conn| { let person: ApubPerson = context
Person::find_by_name(conn, &user_name) .conn()
}) .await?
.interact(move |conn| Person::find_by_name(conn, &user_name))
.await?? .await??
.into(); .into();
@ -73,9 +73,10 @@ 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 = context
Person::find_by_name(conn, &info.user_name) .conn()
}) .await?
.interact(move |conn| Person::find_by_name(conn, &info.user_name))
.await??; .await??;
let outbox = PersonOutbox::new(person).await?; let outbox = PersonOutbox::new(person).await?;
Ok(create_apub_response(&outbox)) Ok(create_apub_response(&outbox))

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_apub_lib::traits::ApubObject; use lemmy_apub_lib::traits::ApubObject;
use lemmy_db_schema::{newtypes::PostId, source::post::Post, traits::Crud}; use lemmy_db_schema::{newtypes::PostId, source::post::Post, traits::Crud};
use lemmy_utils::LemmyError; use lemmy_utils::LemmyError;
@ -22,7 +21,10 @@ 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: ApubPost = blocking(context.pool(), move |conn| Post::read(conn, id)) let post: ApubPost = context
.conn()
.await?
.interact(move |conn| Post::read(conn, id))
.await?? .await??
.into(); .into();
if !post.local { if !post.local {

View file

@ -13,7 +13,6 @@ extern crate lazy_static;
use crate::fetcher::post_or_comment::PostOrComment; use crate::fetcher::post_or_comment::PostOrComment;
use anyhow::{anyhow, Context}; use anyhow::{anyhow, Context};
use lemmy_api_common::blocking;
use lemmy_apub_lib::webfinger::{webfinger_resolve_actor, WebfingerType}; use lemmy_apub_lib::webfinger::{webfinger_resolve_actor, WebfingerType};
use lemmy_db_schema::{newtypes::DbUrl, source::activity::Activity, DbPool}; use lemmy_db_schema::{newtypes::DbUrl, source::activity::Activity, DbPool};
use lemmy_utils::{location_info, settings::structs::Settings, LemmyError}; use lemmy_utils::{location_info, settings::structs::Settings, LemmyError};
@ -188,9 +187,10 @@ 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| { pool
Activity::insert(conn, ap_id, &activity, local, sensitive) .get()
}) .await?
.interact(move |conn| Activity::insert(conn, ap_id, &activity, local, sensitive))
.await??; .await??;
Ok(()) Ok(())
} }

View file

@ -14,7 +14,6 @@ use activitystreams::{object::kind::NoteType, public};
use anyhow::anyhow; use anyhow::anyhow;
use chrono::NaiveDateTime; use chrono::NaiveDateTime;
use html2md::parse_html; use html2md::parse_html;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
object_id::ObjectId, object_id::ObjectId,
traits::ApubObject, traits::ApubObject,
@ -69,9 +68,10 @@ impl ApubObject for ApubComment {
context: &LemmyContext, context: &LemmyContext,
) -> Result<Option<Self>, LemmyError> { ) -> Result<Option<Self>, LemmyError> {
Ok( Ok(
blocking(context.pool(), move |conn| { context
Comment::read_from_apub_id(conn, object_id) .conn()
}) .await?
.interact(move |conn| Comment::read_from_apub_id(conn, object_id))
.await?? .await??
.map(Into::into), .map(Into::into),
) )
@ -79,9 +79,10 @@ impl ApubObject for ApubComment {
async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> { async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
if !self.deleted { if !self.deleted {
blocking(context.pool(), move |conn| { context
Comment::update_deleted(conn, self.id, true) .conn()
}) .await?
.interact(move |conn| Comment::update_deleted(conn, self.id, true))
.await??; .await??;
} }
Ok(()) Ok(())
@ -89,14 +90,25 @@ impl ApubObject for ApubComment {
async fn into_apub(self, context: &LemmyContext) -> Result<Note, LemmyError> { async fn into_apub(self, context: &LemmyContext) -> Result<Note, LemmyError> {
let creator_id = self.creator_id; let creator_id = self.creator_id;
let creator = blocking(context.pool(), move |conn| Person::read(conn, creator_id)).await??; let creator = context
.conn()
.await?
.interact(move |conn| Person::read(conn, creator_id))
.await??;
let post_id = self.post_id; let post_id = self.post_id;
let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; let post = context
.conn()
.await?
.interact(move |conn| Post::read(conn, post_id))
.await??;
let in_reply_to = if let Some(comment_id) = self.parent_id { let in_reply_to = if let Some(comment_id) = self.parent_id {
let parent_comment = let parent_comment = context
blocking(context.pool(), move |conn| Comment::read(conn, comment_id)).await??; .conn()
.await?
.interact(move |conn| Comment::read(conn, comment_id))
.await??;
ObjectId::<PostOrComment>::new(parent_comment.ap_id) ObjectId::<PostOrComment>::new(parent_comment.ap_id)
} else { } else {
ObjectId::<PostOrComment>::new(post.ap_id) ObjectId::<PostOrComment>::new(post.ap_id)
@ -141,9 +153,10 @@ impl ApubObject for ApubComment {
verify_is_public(&note.to, &note.cc)?; verify_is_public(&note.to, &note.cc)?;
let (post, _) = note.get_parents(context, request_counter).await?; let (post, _) = note.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 = context
Community::read(conn, community_id) .conn()
}) .await?
.interact(move |conn| Community::read(conn, community_id))
.await??; .await??;
check_is_apub_id_valid(note.id.inner(), community.local, &context.settings())?; check_is_apub_id_valid(note.id.inner(), community.local, &context.settings())?;
verify_person_in_community( verify_person_in_community(
@ -193,7 +206,11 @@ impl ApubObject for ApubComment {
ap_id: Some(note.id.into()), ap_id: Some(note.id.into()),
local: Some(false), local: Some(false),
}; };
let comment = blocking(context.pool(), move |conn| Comment::upsert(conn, &form)).await??; let comment = context
.conn()
.await?
.interact(move |conn| Comment::upsert(conn, &form))
.await??;
Ok(comment.into()) Ok(comment.into())
} }
} }
@ -208,6 +225,7 @@ pub(crate) mod tests {
tests::{file_to_json_object, init_context}, tests::{file_to_json_object, init_context},
}; };
use assert_json_diff::assert_json_include; use assert_json_diff::assert_json_include;
use lemmy_db_schema::establish_unpooled_connection;
use serial_test::serial; use serial_test::serial;
async fn prepare_comment_test( async fn prepare_comment_test(
@ -226,16 +244,18 @@ pub(crate) mod tests {
(person, community, post) (person, community, post)
} }
fn cleanup(data: (ApubPerson, ApubCommunity, ApubPost), context: &LemmyContext) { fn cleanup(data: (ApubPerson, ApubCommunity, ApubPost), _context: &LemmyContext) {
Post::delete(&*context.pool().get().unwrap(), data.2.id).unwrap(); let conn = establish_unpooled_connection();
Community::delete(&*context.pool().get().unwrap(), data.1.id).unwrap(); Post::delete(&conn, data.2.id).unwrap();
Person::delete(&*context.pool().get().unwrap(), data.0.id).unwrap(); Community::delete(&conn, data.1.id).unwrap();
Person::delete(&conn, data.0.id).unwrap();
} }
#[actix_rt::test] #[actix_rt::test]
#[serial] #[serial]
pub(crate) async fn test_parse_lemmy_comment() { pub(crate) async fn test_parse_lemmy_comment() {
let context = init_context(); let context = init_context();
let conn = establish_unpooled_connection();
let url = Url::parse("https://enterprise.lemmy.ml/comment/38741").unwrap(); let url = Url::parse("https://enterprise.lemmy.ml/comment/38741").unwrap();
let data = prepare_comment_test(&url, &context).await; let data = prepare_comment_test(&url, &context).await;
@ -257,7 +277,7 @@ pub(crate) mod tests {
let to_apub = comment.into_apub(&context).await.unwrap(); let to_apub = comment.into_apub(&context).await.unwrap();
assert_json_include!(actual: json, expected: to_apub); assert_json_include!(actual: json, expected: to_apub);
Comment::delete(&*context.pool().get().unwrap(), comment_id).unwrap(); Comment::delete(&conn, comment_id).unwrap();
cleanup(data, &context); cleanup(data, &context);
} }
@ -265,6 +285,7 @@ pub(crate) mod tests {
#[serial] #[serial]
async fn test_parse_pleroma_comment() { async fn test_parse_pleroma_comment() {
let context = init_context(); let context = init_context();
let conn = establish_unpooled_connection();
let url = Url::parse("https://enterprise.lemmy.ml/comment/38741").unwrap(); let url = Url::parse("https://enterprise.lemmy.ml/comment/38741").unwrap();
let data = prepare_comment_test(&url, &context).await; let data = prepare_comment_test(&url, &context).await;
@ -292,7 +313,7 @@ pub(crate) mod tests {
assert!(!comment.local); assert!(!comment.local);
assert_eq!(request_counter, 0); assert_eq!(request_counter, 0);
Comment::delete(&*context.pool().get().unwrap(), comment.id).unwrap(); Comment::delete(&conn, comment.id).unwrap();
cleanup(data, &context); cleanup(data, &context);
} }

View file

@ -12,7 +12,6 @@ use crate::{
use activitystreams::{actor::kind::GroupType, object::kind::ImageType}; use activitystreams::{actor::kind::GroupType, object::kind::ImageType};
use chrono::NaiveDateTime; use chrono::NaiveDateTime;
use itertools::Itertools; use itertools::Itertools;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
object_id::ObjectId, object_id::ObjectId,
traits::{ActorType, ApubObject}, traits::{ActorType, ApubObject},
@ -60,18 +59,20 @@ impl ApubObject for ApubCommunity {
context: &LemmyContext, context: &LemmyContext,
) -> Result<Option<Self>, LemmyError> { ) -> Result<Option<Self>, LemmyError> {
Ok( Ok(
blocking(context.pool(), move |conn| { context
Community::read_from_apub_id(conn, object_id) .conn()
}) .await?
.interact(move |conn| Community::read_from_apub_id(conn, object_id))
.await?? .await??
.map(Into::into), .map(Into::into),
) )
} }
async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> { async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
blocking(context.pool(), move |conn| { context
Community::update_deleted(conn, self.id, true) .conn()
}) .await?
.interact(move |conn| Community::update_deleted(conn, self.id, true))
.await??; .await??;
Ok(()) Ok(())
} }
@ -143,8 +144,10 @@ impl ApubObject for ApubCommunity {
// Fetching mods and outbox is not necessary for Lemmy to work, so ignore errors. Besides, // Fetching mods and outbox is not necessary for Lemmy to work, so ignore errors. Besides,
// we need to ignore these errors so that tests can work entirely offline. // we need to ignore these errors so that tests can work entirely offline.
let community: ApubCommunity = let community: ApubCommunity = context
blocking(context.pool(), move |conn| Community::upsert(conn, &form)) .conn()
.await?
.interact(move |conn| Community::upsert(conn, &form))
.await?? .await??
.into(); .into();
let outbox_data = CommunityContext(community.clone(), context.clone()); let outbox_data = CommunityContext(community.clone(), context.clone());
@ -197,9 +200,10 @@ impl ApubCommunity {
) -> Result<Vec<Url>, LemmyError> { ) -> Result<Vec<Url>, LemmyError> {
let id = self.id; let id = self.id;
let follows = blocking(context.pool(), move |conn| { let follows = context
CommunityFollowerView::for_community(conn, id) .conn()
}) .await?
.interact(move |conn| CommunityFollowerView::for_community(conn, id))
.await??; .await??;
let follower_inboxes: Vec<Url> = follows let follower_inboxes: Vec<Url> = follows
.into_iter() .into_iter()
@ -228,7 +232,7 @@ impl ApubCommunity {
pub(crate) mod tests { pub(crate) mod tests {
use super::*; use super::*;
use crate::objects::tests::{file_to_json_object, init_context}; use crate::objects::tests::{file_to_json_object, init_context};
use lemmy_db_schema::traits::Crud; use lemmy_db_schema::{establish_unpooled_connection, traits::Crud};
use serial_test::serial; use serial_test::serial;
pub(crate) async fn parse_lemmy_community(context: &LemmyContext) -> ApubCommunity { pub(crate) async fn parse_lemmy_community(context: &LemmyContext) -> ApubCommunity {
@ -256,12 +260,13 @@ pub(crate) mod tests {
async fn test_parse_lemmy_community() { async fn test_parse_lemmy_community() {
let context = init_context(); let context = init_context();
let community = parse_lemmy_community(&context).await; let community = parse_lemmy_community(&context).await;
let conn = establish_unpooled_connection();
assert_eq!(community.title, "Ten Forward"); assert_eq!(community.title, "Ten Forward");
assert!(community.public_key.is_some()); assert!(community.public_key.is_some());
assert!(!community.local); assert!(!community.local);
assert_eq!(community.description.as_ref().unwrap().len(), 132); assert_eq!(community.description.as_ref().unwrap().len(), 132);
Community::delete(&*context.pool().get().unwrap(), community.id).unwrap(); Community::delete(&conn, community.id).unwrap();
} }
} }

View file

@ -21,10 +21,7 @@ pub(crate) fn get_summary_from_string_or_source(
#[cfg(test)] #[cfg(test)]
pub(crate) mod tests { pub(crate) mod tests {
use actix::Actor; use actix::Actor;
use diesel::{ use deadpool_diesel::postgres::{Manager, Pool, Runtime};
r2d2::{ConnectionManager, Pool},
PgConnection,
};
use lemmy_apub_lib::activity_queue::create_activity_queue; use lemmy_apub_lib::activity_queue::create_activity_queue;
use lemmy_db_schema::{ use lemmy_db_schema::{
establish_unpooled_connection, establish_unpooled_connection,
@ -66,11 +63,12 @@ pub(crate) mod tests {
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, Runtime::Tokio1);
let pool = Pool::builder(manager)
.max_size(settings.database.pool_size) .max_size(settings.database.pool_size)
.build(manager) .build()
.unwrap_or_else(|_| panic!("Error connecting to {}", db_url)); .unwrap();
async fn x() -> Result<String, LemmyError> { async fn x() -> Result<String, LemmyError> {
Ok("".to_string()) Ok("".to_string())
} }

View file

@ -13,7 +13,6 @@ use crate::{
}; };
use activitystreams::object::kind::ImageType; use activitystreams::object::kind::ImageType;
use chrono::NaiveDateTime; use chrono::NaiveDateTime;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
object_id::ObjectId, object_id::ObjectId,
traits::{ActorType, ApubObject}, traits::{ActorType, ApubObject},
@ -63,18 +62,20 @@ impl ApubObject for ApubPerson {
context: &LemmyContext, context: &LemmyContext,
) -> Result<Option<Self>, LemmyError> { ) -> Result<Option<Self>, LemmyError> {
Ok( Ok(
blocking(context.pool(), move |conn| { context
DbPerson::read_from_apub_id(conn, object_id) .conn()
}) .await?
.interact(move |conn| DbPerson::read_from_apub_id(conn, object_id))
.await?? .await??
.map(Into::into), .map(Into::into),
) )
} }
async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> { async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
blocking(context.pool(), move |conn| { context
DbPerson::update_deleted(conn, self.id, true) .conn()
}) .await?
.interact(move |conn| DbPerson::update_deleted(conn, self.id, true))
.await??; .await??;
Ok(()) Ok(())
} }
@ -171,9 +172,10 @@ impl ApubObject for ApubPerson {
shared_inbox_url: Some(person.endpoints.shared_inbox.map(|s| s.into())), shared_inbox_url: Some(person.endpoints.shared_inbox.map(|s| s.into())),
matrix_user_id: Some(person.matrix_user_id), matrix_user_id: Some(person.matrix_user_id),
}; };
let person = blocking(context.pool(), move |conn| { let person = context
DbPerson::upsert(conn, &person_form) .conn()
}) .await?
.interact(move |conn| DbPerson::upsert(conn, &person_form))
.await??; .await??;
Ok(person.into()) Ok(person.into())
} }
@ -205,7 +207,7 @@ impl ActorType for ApubPerson {
pub(crate) mod tests { pub(crate) mod tests {
use super::*; use super::*;
use crate::objects::tests::{file_to_json_object, init_context}; use crate::objects::tests::{file_to_json_object, init_context};
use lemmy_db_schema::traits::Crud; use lemmy_db_schema::{establish_unpooled_connection, traits::Crud};
use serial_test::serial; use serial_test::serial;
pub(crate) async fn parse_lemmy_person(context: &LemmyContext) -> ApubPerson { pub(crate) async fn parse_lemmy_person(context: &LemmyContext) -> ApubPerson {
@ -226,6 +228,7 @@ pub(crate) mod tests {
#[serial] #[serial]
async fn test_parse_lemmy_person() { async fn test_parse_lemmy_person() {
let context = init_context(); let context = init_context();
let conn = establish_unpooled_connection();
let person = parse_lemmy_person(&context).await; let person = parse_lemmy_person(&context).await;
assert_eq!(person.display_name, Some("Jean-Luc Picard".to_string())); assert_eq!(person.display_name, Some("Jean-Luc Picard".to_string()));
@ -233,13 +236,14 @@ pub(crate) mod tests {
assert!(!person.local); assert!(!person.local);
assert_eq!(person.bio.as_ref().unwrap().len(), 39); assert_eq!(person.bio.as_ref().unwrap().len(), 39);
DbPerson::delete(&*context.pool().get().unwrap(), person.id).unwrap(); DbPerson::delete(&conn, person.id).unwrap();
} }
#[actix_rt::test] #[actix_rt::test]
#[serial] #[serial]
async fn test_parse_pleroma_person() { async fn test_parse_pleroma_person() {
let context = init_context(); let context = init_context();
let conn = establish_unpooled_connection();
let json = file_to_json_object("assets/pleroma/objects/person.json"); let json = file_to_json_object("assets/pleroma/objects/person.json");
let url = Url::parse("https://queer.hacktivis.me/users/lanodan").unwrap(); let url = Url::parse("https://queer.hacktivis.me/users/lanodan").unwrap();
let mut request_counter = 0; let mut request_counter = 0;
@ -257,6 +261,6 @@ pub(crate) mod tests {
assert_eq!(request_counter, 0); assert_eq!(request_counter, 0);
assert_eq!(person.bio.as_ref().unwrap().len(), 873); assert_eq!(person.bio.as_ref().unwrap().len(), 873);
DbPerson::delete(&*context.pool().get().unwrap(), person.id).unwrap(); DbPerson::delete(&conn, person.id).unwrap();
} }
} }

View file

@ -12,7 +12,6 @@ use activitystreams::{
public, public,
}; };
use chrono::NaiveDateTime; use chrono::NaiveDateTime;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
object_id::ObjectId, object_id::ObjectId,
traits::ApubObject, traits::ApubObject,
@ -68,9 +67,10 @@ impl ApubObject for ApubPost {
context: &LemmyContext, context: &LemmyContext,
) -> Result<Option<Self>, LemmyError> { ) -> Result<Option<Self>, LemmyError> {
Ok( Ok(
blocking(context.pool(), move |conn| { context
Post::read_from_apub_id(conn, object_id) .conn()
}) .await?
.interact(move |conn| Post::read_from_apub_id(conn, object_id))
.await?? .await??
.map(Into::into), .map(Into::into),
) )
@ -78,9 +78,10 @@ impl ApubObject for ApubPost {
async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> { async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
if !self.deleted { if !self.deleted {
blocking(context.pool(), move |conn| { context
Post::update_deleted(conn, self.id, true) .conn()
}) .await?
.interact(move |conn| Post::update_deleted(conn, self.id, true))
.await??; .await??;
} }
Ok(()) Ok(())
@ -89,11 +90,16 @@ impl ApubObject for ApubPost {
// 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 into_apub(self, context: &LemmyContext) -> Result<Page, LemmyError> { async fn into_apub(self, context: &LemmyContext) -> Result<Page, LemmyError> {
let creator_id = self.creator_id; let creator_id = self.creator_id;
let creator = blocking(context.pool(), move |conn| Person::read(conn, creator_id)).await??; let creator = context
.conn()
.await?
.interact(move |conn| Person::read(conn, creator_id))
.await??;
let community_id = self.community_id; let community_id = self.community_id;
let community = blocking(context.pool(), move |conn| { let community = context
Community::read(conn, community_id) .conn()
}) .await?
.interact(move |conn| Community::read(conn, community_id))
.await??; .await??;
let source = self.body.clone().map(|body| Source { let source = self.body.clone().map(|body| Source {
@ -200,7 +206,11 @@ impl ApubObject for ApubPost {
ap_id: Some(page.id.into()), ap_id: Some(page.id.into()),
local: Some(false), local: Some(false),
}; };
let post = blocking(context.pool(), move |conn| Post::upsert(conn, &form)).await??; let post = context
.conn()
.await?
.interact(move |conn| Post::upsert(conn, &form))
.await??;
Ok(post.into()) Ok(post.into())
} }
} }
@ -214,12 +224,14 @@ mod tests {
post::ApubPost, post::ApubPost,
tests::{file_to_json_object, init_context}, tests::{file_to_json_object, init_context},
}; };
use lemmy_db_schema::establish_unpooled_connection;
use serial_test::serial; use serial_test::serial;
#[actix_rt::test] #[actix_rt::test]
#[serial] #[serial]
async fn test_parse_lemmy_post() { async fn test_parse_lemmy_post() {
let context = init_context(); let context = init_context();
let conn = establish_unpooled_connection();
let community = parse_lemmy_community(&context).await; let community = parse_lemmy_community(&context).await;
let person = parse_lemmy_person(&context).await; let person = parse_lemmy_person(&context).await;
@ -241,8 +253,8 @@ mod tests {
assert!(post.stickied); assert!(post.stickied);
assert_eq!(request_counter, 0); assert_eq!(request_counter, 0);
Post::delete(&*context.pool().get().unwrap(), post.id).unwrap(); Post::delete(&conn, post.id).unwrap();
Person::delete(&*context.pool().get().unwrap(), person.id).unwrap(); Person::delete(&conn, person.id).unwrap();
Community::delete(&*context.pool().get().unwrap(), community.id).unwrap(); Community::delete(&conn, community.id).unwrap();
} }
} }

View file

@ -5,7 +5,6 @@ use crate::protocol::{
use anyhow::anyhow; use anyhow::anyhow;
use chrono::NaiveDateTime; use chrono::NaiveDateTime;
use html2md::parse_html; use html2md::parse_html;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
object_id::ObjectId, object_id::ObjectId,
traits::ApubObject, traits::ApubObject,
@ -58,9 +57,10 @@ impl ApubObject for ApubPrivateMessage {
context: &LemmyContext, context: &LemmyContext,
) -> Result<Option<Self>, LemmyError> { ) -> Result<Option<Self>, LemmyError> {
Ok( Ok(
blocking(context.pool(), move |conn| { context
PrivateMessage::read_from_apub_id(conn, object_id) .conn()
}) .await?
.interact(move |conn| PrivateMessage::read_from_apub_id(conn, object_id))
.await?? .await??
.map(Into::into), .map(Into::into),
) )
@ -73,11 +73,18 @@ impl ApubObject for ApubPrivateMessage {
async fn into_apub(self, context: &LemmyContext) -> Result<ChatMessage, LemmyError> { async fn into_apub(self, context: &LemmyContext) -> Result<ChatMessage, LemmyError> {
let creator_id = self.creator_id; let creator_id = self.creator_id;
let creator = blocking(context.pool(), move |conn| Person::read(conn, creator_id)).await??; let creator = context
.conn()
.await?
.interact(move |conn| Person::read(conn, creator_id))
.await??;
let recipient_id = self.recipient_id; let recipient_id = self.recipient_id;
let recipient = let recipient = context
blocking(context.pool(), move |conn| Person::read(conn, recipient_id)).await??; .conn()
.await?
.interact(move |conn| Person::read(conn, recipient_id))
.await??;
let note = ChatMessage { let note = ChatMessage {
r#type: ChatMessageType::ChatMessage, r#type: ChatMessageType::ChatMessage,
@ -146,9 +153,10 @@ impl ApubObject for ApubPrivateMessage {
ap_id: Some(note.id.into()), ap_id: Some(note.id.into()),
local: Some(false), local: Some(false),
}; };
let pm = blocking(context.pool(), move |conn| { let pm = context
PrivateMessage::upsert(conn, &form) .conn()
}) .await?
.interact(move |conn| PrivateMessage::upsert(conn, &form))
.await??; .await??;
Ok(pm.into()) Ok(pm.into())
} }
@ -162,6 +170,7 @@ mod tests {
tests::{file_to_json_object, init_context}, tests::{file_to_json_object, init_context},
}; };
use assert_json_diff::assert_json_include; use assert_json_diff::assert_json_include;
use lemmy_db_schema::establish_unpooled_connection;
use serial_test::serial; use serial_test::serial;
async fn prepare_comment_test(url: &Url, context: &LemmyContext) -> (ApubPerson, ApubPerson) { async fn prepare_comment_test(url: &Url, context: &LemmyContext) -> (ApubPerson, ApubPerson) {
@ -183,15 +192,17 @@ mod tests {
(person1, person2) (person1, person2)
} }
fn cleanup(data: (ApubPerson, ApubPerson), context: &LemmyContext) { fn cleanup(data: (ApubPerson, ApubPerson), _context: &LemmyContext) {
Person::delete(&*context.pool().get().unwrap(), data.0.id).unwrap(); let conn = establish_unpooled_connection();
Person::delete(&*context.pool().get().unwrap(), data.1.id).unwrap(); Person::delete(&conn, data.0.id).unwrap();
Person::delete(&conn, data.1.id).unwrap();
} }
#[actix_rt::test] #[actix_rt::test]
#[serial] #[serial]
async fn test_parse_lemmy_pm() { async fn test_parse_lemmy_pm() {
let context = init_context(); let context = init_context();
let conn = establish_unpooled_connection();
let url = Url::parse("https://enterprise.lemmy.ml/private_message/1621").unwrap(); let url = Url::parse("https://enterprise.lemmy.ml/private_message/1621").unwrap();
let data = prepare_comment_test(&url, &context).await; let data = prepare_comment_test(&url, &context).await;
let json: ChatMessage = file_to_json_object("assets/lemmy/objects/chat_message.json"); let json: ChatMessage = file_to_json_object("assets/lemmy/objects/chat_message.json");
@ -211,7 +222,7 @@ mod tests {
let to_apub = pm.into_apub(&context).await.unwrap(); let to_apub = pm.into_apub(&context).await.unwrap();
assert_json_include!(actual: json, expected: to_apub); assert_json_include!(actual: json, expected: to_apub);
PrivateMessage::delete(&*context.pool().get().unwrap(), pm_id).unwrap(); PrivateMessage::delete(&conn, pm_id).unwrap();
cleanup(data, &context); cleanup(data, &context);
} }
@ -219,6 +230,7 @@ mod tests {
#[serial] #[serial]
async fn test_parse_pleroma_pm() { async fn test_parse_pleroma_pm() {
let context = init_context(); let context = init_context();
let conn = establish_unpooled_connection();
let url = Url::parse("https://enterprise.lemmy.ml/private_message/1621").unwrap(); let url = Url::parse("https://enterprise.lemmy.ml/private_message/1621").unwrap();
let data = prepare_comment_test(&url, &context).await; let data = prepare_comment_test(&url, &context).await;
let pleroma_url = Url::parse("https://queer.hacktivis.me/objects/2").unwrap(); let pleroma_url = Url::parse("https://queer.hacktivis.me/objects/2").unwrap();
@ -235,7 +247,7 @@ mod tests {
assert_eq!(pm.content.len(), 3); assert_eq!(pm.content.len(), 3);
assert_eq!(request_counter, 0); assert_eq!(request_counter, 0);
PrivateMessage::delete(&*context.pool().get().unwrap(), pm.id).unwrap(); PrivateMessage::delete(&conn, pm.id).unwrap();
cleanup(data, &context); cleanup(data, &context);
} }
} }

View file

@ -1,6 +1,5 @@
use crate::generate_followers_url; use crate::generate_followers_url;
use activitystreams::collection::kind::CollectionType; use activitystreams::collection::kind::CollectionType;
use lemmy_api_common::blocking;
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;
use lemmy_utils::LemmyError; use lemmy_utils::LemmyError;
@ -23,9 +22,10 @@ impl GroupFollowers {
context: &LemmyContext, context: &LemmyContext,
) -> Result<GroupFollowers, LemmyError> { ) -> Result<GroupFollowers, LemmyError> {
let community_id = community.id; let community_id = community.id;
let community_followers = blocking(context.pool(), move |conn| { let community_followers = context
CommunityFollowerView::for_community(conn, community_id) .conn()
}) .await?
.interact(move |conn| CommunityFollowerView::for_community(conn, community_id))
.await??; .await??;
Ok(GroupFollowers { Ok(GroupFollowers {

View file

@ -5,7 +5,6 @@ use crate::{
}; };
use activitystreams::{object::kind::NoteType, unparsed::Unparsed}; use activitystreams::{object::kind::NoteType, unparsed::Unparsed};
use chrono::{DateTime, FixedOffset}; use chrono::{DateTime, FixedOffset};
use lemmy_api_common::blocking;
use lemmy_apub_lib::{object_id::ObjectId, values::MediaTypeHtml}; use lemmy_apub_lib::{object_id::ObjectId, values::MediaTypeHtml};
use lemmy_db_schema::{newtypes::CommentId, source::post::Post, traits::Crud}; use lemmy_db_schema::{newtypes::CommentId, source::post::Post, traits::Crud};
use lemmy_utils::LemmyError; use lemmy_utils::LemmyError;
@ -62,12 +61,20 @@ impl Note {
// Workaround because I cant figure out how to get the post out of the box (and we dont // Workaround because I cant figure out 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 = context
.conn()
.await?
.interact(move |conn| Post::read(conn, post_id))
.await??;
Ok((post.into(), None)) Ok((post.into(), 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 = context
.conn()
.await?
.interact(move |conn| Post::read(conn, post_id))
.await??;
Ok((post.into(), Some(c.id))) Ok((post.into(), Some(c.id)))
} }
} }

View file

@ -13,8 +13,9 @@ doctest = false
[dependencies] [dependencies]
lemmy_utils = { version = "=0.13.5-rc.7", path = "../utils" } lemmy_utils = { version = "=0.13.5-rc.7", path = "../utils" }
lemmy_apub_lib = { version = "=0.13.5-rc.7", path = "../apub_lib" } lemmy_apub_lib = { version = "=0.13.5-rc.7", path = "../apub_lib" }
diesel = { version = "1.4.8", features = ["postgres","chrono","r2d2","serde_json"] } diesel = { version = "1.4.8", features = ["postgres","chrono","serde_json"] }
diesel_migrations = "1.4.0" diesel_migrations = "1.4.0"
deadpool-diesel = { version = "0.3.1", features = ["postgres"] }
chrono = { version = "0.4.19", features = ["serde"] } chrono = { version = "0.4.19", features = ["serde"] }
serde = { version = "1.0.130", features = ["derive"] } serde = { version = "1.0.130", features = ["derive"] }
serde_json = { version = "1.0.68", features = ["preserve_order"] } serde_json = { version = "1.0.68", features = ["preserve_order"] }

View file

@ -18,8 +18,6 @@ pub mod schema;
pub mod source; pub mod source;
pub mod traits; pub mod traits;
pub type DbPool = diesel::r2d2::Pool<diesel::r2d2::ConnectionManager<diesel::PgConnection>>;
use crate::newtypes::DbUrl; use crate::newtypes::DbUrl;
use chrono::NaiveDateTime; use chrono::NaiveDateTime;
use diesel::{Connection, PgConnection}; use diesel::{Connection, PgConnection};
@ -29,6 +27,8 @@ use serde::{Deserialize, Serialize};
use std::{env, env::VarError}; use std::{env, env::VarError};
use url::Url; use url::Url;
pub type DbPool = deadpool_diesel::postgres::Pool;
pub fn get_database_url_from_env() -> Result<String, VarError> { pub fn get_database_url_from_env() -> Result<String, VarError> {
env::var("LEMMY_DATABASE_URL") env::var("LEMMY_DATABASE_URL")
} }
@ -129,6 +129,13 @@ pub fn establish_unpooled_connection() -> PgConnection {
conn conn
} }
pub fn establish_unpooled_connection_with_db_url(db_url: &str) -> PgConnection {
let conn =
PgConnection::establish(db_url).unwrap_or_else(|_| panic!("Error connecting to {}", db_url));
embedded_migrations::run(&conn).expect("load migrations");
conn
}
pub fn naive_now() -> NaiveDateTime { pub fn naive_now() -> NaiveDateTime {
chrono::prelude::Utc::now().naive_utc() chrono::prelude::Utc::now().naive_utc()
} }

View file

@ -12,7 +12,7 @@ doctest = false
[dependencies] [dependencies]
lemmy_db_schema = { version = "=0.13.5-rc.7", path = "../db_schema" } lemmy_db_schema = { version = "=0.13.5-rc.7", path = "../db_schema" }
diesel = { version = "1.4.8", features = ["postgres","chrono","r2d2","serde_json"] } diesel = { version = "1.4.8", features = ["postgres","chrono","serde_json"] }
serde = { version = "1.0.130", features = ["derive"] } serde = { version = "1.0.130", features = ["derive"] }
log = "0.4.14" log = "0.4.14"
url = "2.2.2" url = "2.2.2"

View file

@ -12,5 +12,5 @@ doctest = false
[dependencies] [dependencies]
lemmy_db_schema = { version = "=0.13.5-rc.7", path = "../db_schema" } lemmy_db_schema = { version = "=0.13.5-rc.7", path = "../db_schema" }
diesel = { version = "1.4.8", features = ["postgres","chrono","r2d2","serde_json"] } diesel = { version = "1.4.8", features = ["postgres","chrono","serde_json"] }
serde = { version = "1.0.130", features = ["derive"] } serde = { version = "1.0.130", features = ["derive"] }

View file

@ -12,5 +12,5 @@ doctest = false
[dependencies] [dependencies]
lemmy_db_schema = { version = "=0.13.5-rc.7", path = "../db_schema" } lemmy_db_schema = { version = "=0.13.5-rc.7", path = "../db_schema" }
diesel = { version = "1.4.8", features = ["postgres","chrono","r2d2","serde_json"] } diesel = { version = "1.4.8", features = ["postgres","chrono","serde_json"] }
serde = { version = "1.0.130", features = ["derive"] } serde = { version = "1.0.130", 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_schema::{ use lemmy_db_schema::{
newtypes::LocalUserId, newtypes::LocalUserId,
source::{community::Community, local_user::LocalUser, person::Person}, source::{community::Community, local_user::LocalUser, person::Person},
@ -80,9 +79,16 @@ 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(), SiteView::read).await??; let site_view = context
.conn()
.await?
.interact(|conn| SiteView::read(conn))
.await??;
let posts = blocking(context.pool(), move |conn| { let posts = context
.conn()
.await?
.interact(move |conn| {
PostQueryBuilder::create(conn) PostQueryBuilder::create(conn)
.listing_type(listing_type) .listing_type(listing_type)
.sort(sort_type) .sort(sort_type)
@ -136,9 +142,15 @@ async fn get_feed(
let jwt_secret = context.secret().jwt_secret.to_owned(); let jwt_secret = context.secret().jwt_secret.to_owned();
let protocol_and_hostname = context.settings().get_protocol_and_hostname(); let protocol_and_hostname = context.settings().get_protocol_and_hostname();
let builder = blocking(context.pool(), move |conn| match request_type { let builder = context
.conn()
.await
.map_err(ErrorBadRequest)?
.interact(move |conn| match request_type {
RequestType::User => get_feed_user(conn, &sort_type, &param, &protocol_and_hostname), RequestType::User => get_feed_user(conn, &sort_type, &param, &protocol_and_hostname),
RequestType::Community => get_feed_community(conn, &sort_type, &param, &protocol_and_hostname), RequestType::Community => {
get_feed_community(conn, &sort_type, &param, &protocol_and_hostname)
}
RequestType::Front => get_feed_front( RequestType::Front => get_feed_front(
conn, conn,
&jwt_secret, &jwt_secret,
@ -148,8 +160,8 @@ async fn get_feed(
), ),
RequestType::Inbox => get_feed_inbox(conn, &jwt_secret, &param, &protocol_and_hostname), RequestType::Inbox => get_feed_inbox(conn, &jwt_secret, &param, &protocol_and_hostname),
}) })
.await? .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,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::{version, LemmyError}; use lemmy_utils::{version, LemmyError};
use lemmy_websocket::LemmyContext; use lemmy_websocket::LemmyContext;
@ -29,8 +28,13 @@ async fn node_info_well_known(
} }
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 = context
.await? .conn()
.await
.map_err(|_| ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))?
.interact(|conn| SiteView::read(conn))
.await
.map_err(|_| ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))?
.map_err(|_| ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))?; .map_err(|_| ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))?;
let protocols = if context.settings().federation.enabled { let protocols = if context.settings().federation.enabled {

View file

@ -1,6 +1,5 @@
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;
use lemmy_apub_lib::webfinger::{WebfingerLink, WebfingerResponse}; use lemmy_apub_lib::webfinger::{WebfingerLink, WebfingerResponse};
use lemmy_db_schema::source::{community::Community, person::Person}; use lemmy_db_schema::source::{community::Community, person::Person};
use lemmy_utils::{settings::structs::Settings, LemmyError}; use lemmy_utils::{settings::structs::Settings, LemmyError};
@ -48,19 +47,25 @@ async fn get_webfinger_response(
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| { context
Community::read_from_name(conn, &community_name) .conn()
}) .await
.await? .map_err(|_| ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))?
.interact(move |conn| Community::read_from_name(conn, &community_name))
.await
.map_err(|_| ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))?
.map_err(|_| ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))? .map_err(|_| ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))?
.actor_id .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| { context
Person::find_by_name(conn, &person_name) .conn()
}) .await
.await? .map_err(|_| ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))?
.interact(move |conn| Person::find_by_name(conn, &person_name))
.await
.map_err(|_| ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))?
.map_err(|_| ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))? .map_err(|_| ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))?
.actor_id .actor_id
} else { } else {

View file

@ -29,6 +29,7 @@ openssl = "0.10.36"
url = { version = "2.2.2", features = ["serde"] } url = { version = "2.2.2", features = ["serde"] }
actix-web = { version = "4.0.0-beta.9", default-features = false, features = ["rustls"] } actix-web = { version = "4.0.0-beta.9", default-features = false, features = ["rustls"] }
actix-rt = { version = "2.2.0", default-features = false } actix-rt = { version = "2.2.0", default-features = false }
actix = "0.12.0"
anyhow = "1.0.44" anyhow = "1.0.44"
reqwest = { version = "0.11.4", features = ["json"] } reqwest = { version = "0.11.4", features = ["json"] }
tokio = { version = "1.12.0", features = ["sync"] } tokio = { version = "1.12.0", features = ["sync"] }
@ -36,6 +37,10 @@ strum = "0.21.0"
strum_macros = "0.21.1" strum_macros = "0.21.1"
futures = "0.3.17" futures = "0.3.17"
diesel = "1.4.8" diesel = "1.4.8"
diesel_migrations = "1.4.0"
deadpool-sync = "0.1.0"
deadpool = "0.9.1"
deadpool-diesel = { version = "0.3.1", features = ["postgres"] }
http = "0.2.5" http = "0.2.5"
deser-hjson = "1.0.2" deser-hjson = "1.0.2"
smart-default = "0.6.0" smart-default = "0.6.0"
@ -43,3 +48,7 @@ webpage = { version = "1.3.0", default-features = false, features = ["serde"] }
jsonwebtoken = "7.2.0" jsonwebtoken = "7.2.0"
doku = "0.10.1" doku = "0.10.1"
uuid = { version = "0.8.2", features = ["serde", "v4"] } uuid = { version = "0.8.2", features = ["serde", "v4"] }
activitystreams = "0.7.0-alpha.11"
base64 = "0.13.0"
http-signature-normalization-reqwest = { version = "0.2.0", default-features = false, features = ["sha-2"] }
http-signature-normalization-actix = { version = "0.5.0-beta.10", default-features = false, features = ["server", "sha-2"] }

View file

@ -70,12 +70,175 @@ pub struct LemmyError {
pub inner: anyhow::Error, pub inner: anyhow::Error,
} }
impl<T> From<T> for LemmyError impl From<deadpool_sync::InteractError> for LemmyError {
where fn from(e: deadpool_sync::InteractError) -> Self {
T: Into<anyhow::Error>, LemmyError {
{ inner: anyhow::anyhow!(e.to_string()),
fn from(t: T) -> Self { }
LemmyError { inner: t.into() } }
}
impl From<deadpool::managed::PoolError<deadpool_diesel::Error>> for LemmyError {
fn from(e: deadpool::managed::PoolError<deadpool_diesel::Error>) -> Self {
LemmyError { inner: e.into() }
}
}
impl From<deadpool::managed::BuildError<deadpool_diesel::Error>> for LemmyError {
fn from(e: deadpool::managed::BuildError<deadpool_diesel::Error>) -> Self {
LemmyError { inner: e.into() }
}
}
impl From<jsonwebtoken::errors::Error> for LemmyError {
fn from(e: jsonwebtoken::errors::Error) -> Self {
LemmyError { inner: e.into() }
}
}
impl From<std::io::Error> for LemmyError {
fn from(e: std::io::Error) -> Self {
LemmyError { inner: e.into() }
}
}
impl From<deser_hjson::Error> for LemmyError {
fn from(e: deser_hjson::Error) -> Self {
LemmyError { inner: e.into() }
}
}
impl From<actix_web::error::PayloadError> for LemmyError {
fn from(e: actix_web::error::PayloadError) -> Self {
LemmyError { inner: e.into() }
}
}
impl From<std::time::SystemTimeError> for LemmyError {
fn from(e: std::time::SystemTimeError) -> Self {
LemmyError { inner: e.into() }
}
}
impl From<ApiError> for LemmyError {
fn from(e: ApiError) -> Self {
LemmyError { inner: e.into() }
}
}
impl From<reqwest::Error> for LemmyError {
fn from(e: reqwest::Error) -> Self {
LemmyError { inner: e.into() }
}
}
impl From<actix::MailboxError> for LemmyError {
fn from(e: actix::MailboxError) -> Self {
LemmyError { inner: e.into() }
}
}
impl From<actix_web::error::Error> for LemmyError {
fn from(e: actix_web::error::Error) -> Self {
LemmyError {
inner: anyhow::anyhow!(e.to_string()),
}
}
}
impl From<http::header::ToStrError> for LemmyError {
fn from(e: http::header::ToStrError) -> Self {
LemmyError { inner: e.into() }
}
}
impl From<request::RecvError> for LemmyError {
fn from(e: request::RecvError) -> Self {
LemmyError { inner: e.into() }
}
}
impl From<serde_json::Error> for LemmyError {
fn from(e: serde_json::Error) -> Self {
LemmyError { inner: e.into() }
}
}
impl From<strum::ParseError> for LemmyError {
fn from(e: strum::ParseError) -> Self {
LemmyError { inner: e.into() }
}
}
impl From<openssl::error::ErrorStack> for LemmyError {
fn from(e: openssl::error::ErrorStack) -> Self {
LemmyError { inner: e.into() }
}
}
impl From<std::num::ParseIntError> for LemmyError {
fn from(e: std::num::ParseIntError) -> Self {
LemmyError { inner: e.into() }
}
}
impl From<url::ParseError> for LemmyError {
fn from(e: url::ParseError) -> Self {
LemmyError { inner: e.into() }
}
}
impl From<activitystreams::error::DomainError> for LemmyError {
fn from(e: activitystreams::error::DomainError) -> Self {
LemmyError { inner: e.into() }
}
}
impl From<base64::DecodeError> for LemmyError {
fn from(e: base64::DecodeError) -> Self {
LemmyError { inner: e.into() }
}
}
impl From<diesel::result::Error> for LemmyError {
fn from(e: diesel::result::Error) -> Self {
LemmyError { inner: e.into() }
}
}
impl From<diesel_migrations::RunMigrationsError> for LemmyError {
fn from(e: diesel_migrations::RunMigrationsError) -> Self {
LemmyError { inner: e.into() }
}
}
impl From<http::header::InvalidHeaderValue> for LemmyError {
fn from(e: http::header::InvalidHeaderValue) -> Self {
LemmyError { inner: e.into() }
}
}
impl From<http::header::InvalidHeaderName> for LemmyError {
fn from(e: http::header::InvalidHeaderName) -> Self {
LemmyError { inner: e.into() }
}
}
impl From<http_signature_normalization_reqwest::SignError> for LemmyError {
fn from(e: http_signature_normalization_reqwest::SignError) -> Self {
LemmyError { inner: e.into() }
}
}
impl From<http_signature_normalization_actix::PrepareVerifyError> for LemmyError {
fn from(e: http_signature_normalization_actix::PrepareVerifyError) -> Self {
LemmyError { inner: e.into() }
}
}
impl From<anyhow::Error> for LemmyError {
fn from(e: anyhow::Error) -> Self {
LemmyError { inner: e }
} }
} }
@ -93,3 +256,7 @@ impl actix_web::error::ResponseError for LemmyError {
} }
} }
} }
// impl From<deadpool_sync::InteractError> for LemmyError {
// }

View file

@ -79,7 +79,7 @@ pub struct DatabaseConfig {
pub(super) database: String, pub(super) database: String,
/// Maximum number of active sql connections /// Maximum number of active sql connections
#[default(5)] #[default(5)]
pub pool_size: u32, pub pool_size: usize,
} }
#[derive(Debug, Deserialize, Serialize, Clone, Document)] #[derive(Debug, Deserialize, Serialize, Clone, Document)]

View file

@ -33,3 +33,5 @@ strum_macros = "0.21.1"
chrono = { version = "0.4.19", features = ["serde"] } chrono = { version = "0.4.19", features = ["serde"] }
actix-web = { version = "4.0.0-beta.9", default-features = false, features = ["rustls"] } actix-web = { version = "4.0.0-beta.9", default-features = false, features = ["rustls"] }
actix-web-actors = { version = "4.0.0-beta.7", default-features = false } actix-web-actors = { version = "4.0.0-beta.7", default-features = false }
deadpool-diesel = { version = "0.3.1", features = ["postgres"] }
deadpool = "0.9.1"

View file

@ -9,14 +9,11 @@ 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_schema::{ use lemmy_db_schema::{
newtypes::{CommunityId, LocalUserId, PostId}, newtypes::{CommunityId, LocalUserId, PostId},
source::secret::Secret, source::secret::Secret,
DbPool,
}; };
use lemmy_utils::{ use lemmy_utils::{
location_info, location_info,
@ -73,7 +70,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,
/// The Settings /// The Settings
pub(super) settings: Settings, pub(super) settings: Settings,
@ -107,7 +104,7 @@ pub struct SessionInfo {
impl ChatServer { impl ChatServer {
#![allow(clippy::too_many_arguments)] #![allow(clippy::too_many_arguments)]
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

@ -4,6 +4,8 @@ extern crate strum_macros;
use crate::chat_server::ChatServer; use crate::chat_server::ChatServer;
use actix::Addr; use actix::Addr;
use background_jobs::QueueHandle; use background_jobs::QueueHandle;
use deadpool::managed::{Object, PoolError};
use deadpool_diesel::postgres::Manager;
use lemmy_db_schema::{source::secret::Secret, DbPool}; use lemmy_db_schema::{source::secret::Secret, DbPool};
use lemmy_utils::{settings::structs::Settings, LemmyError}; use lemmy_utils::{settings::structs::Settings, LemmyError};
use reqwest::Client; use reqwest::Client;
@ -45,6 +47,9 @@ impl LemmyContext {
pub fn pool(&self) -> &DbPool { pub fn pool(&self) -> &DbPool {
&self.pool &self.pool
} }
pub async fn conn(&self) -> Result<Object<Manager>, PoolError<deadpool_diesel::Error>> {
self.pool.get().await
}
pub fn chat_server(&self) -> &Addr<ChatServer> { pub fn chat_server(&self) -> &Addr<ChatServer> {
&self.chat_server &self.chat_server
} }

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,
@ -43,9 +42,10 @@ 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 post_view = blocking(context.pool(), move |conn| { let post_view = context
PostView::read(conn, post_id, person_id) .conn()
}) .await?
.interact(move |conn| PostView::read(conn, post_id, person_id))
.await??; .await??;
let res = PostResponse { post_view }; let res = PostResponse { post_view };
@ -78,9 +78,10 @@ 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 = context
CommentView::read(conn, comment_id, person_id) .conn()
}) .await?
.interact(move |conn| CommentView::read(conn, comment_id, person_id))
.await??; .await??;
if view.comment.deleted || view.comment.removed { if view.comment.deleted || view.comment.removed {
@ -114,9 +115,10 @@ 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 community_view = blocking(context.pool(), move |conn| { let community_view = context
CommunityView::read(conn, community_id, person_id) .conn()
}) .await?
.interact(move |conn| CommunityView::read(conn, community_id, person_id))
.await??; .await??;
let res = CommunityResponse { community_view }; let res = CommunityResponse { community_view };
@ -141,9 +143,10 @@ 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 = context
PrivateMessageView::read(conn, private_message_id) .conn()
}) .await?
.interact(move |conn| PrivateMessageView::read(conn, private_message_id))
.await??; .await??;
// Blank out deleted or removed info // Blank out deleted or removed info
@ -158,9 +161,10 @@ 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 = context
LocalUserView::read_person(conn, recipient_id) .conn()
}) .await?
.interact(move |conn| LocalUserView::read_person(conn, recipient_id))
.await??; .await??;
context.chat_server().do_send(SendUserRoomMessage { context.chat_server().do_send(SendUserRoomMessage {
op, op,
@ -190,9 +194,10 @@ pub async fn send_local_notifs(
.collect::<Vec<&MentionData>>() .collect::<Vec<&MentionData>>()
{ {
let mention_name = mention.name.clone(); let mention_name = mention.name.clone();
let user_view = blocking(context.pool(), move |conn| { let user_view = context
LocalUserView::read_from_name(conn, &mention_name) .conn()
}) .await?
.interact(move |conn| LocalUserView::read_from_name(conn, &mention_name))
.await?; .await?;
if let Ok(mention_user_view) = user_view { if let Ok(mention_user_view) = user_view {
// TODO // TODO
@ -208,9 +213,10 @@ pub async fn send_local_notifs(
// Allow this to fail softly, since comment edits might re-update or replace it // Allow this to fail softly, since comment edits might re-update or replace it
// Let the uniqueness handle this fail // Let the uniqueness handle this fail
blocking(context.pool(), move |conn| { context
PersonMention::create(conn, &user_mention_form) .conn()
}) .await?
.interact(move |conn| PersonMention::create(conn, &user_mention_form))
.await? .await?
.ok(); .ok();
@ -230,15 +236,19 @@ pub async fn send_local_notifs(
// Send notifs to the parent commenter / poster // Send notifs to the parent commenter / poster
match comment.parent_id { match comment.parent_id {
Some(parent_id) => { Some(parent_id) => {
let parent_comment = let parent_comment = context
blocking(context.pool(), move |conn| Comment::read(conn, parent_id)).await?; .conn()
.await?
.interact(move |conn| Comment::read(conn, parent_id))
.await?;
if let Ok(parent_comment) = parent_comment { if let Ok(parent_comment) = parent_comment {
// Don't send a notif to yourself // Don't send a notif to yourself
if parent_comment.creator_id != person.id { if parent_comment.creator_id != person.id {
// Get the parent commenter local_user // Get the parent commenter local_user
let user_view = blocking(context.pool(), move |conn| { let user_view = context
LocalUserView::read_person(conn, parent_comment.creator_id) .conn()
}) .await?
.interact(move |conn| LocalUserView::read_person(conn, parent_comment.creator_id))
.await?; .await?;
if let Ok(parent_user_view) = user_view { if let Ok(parent_user_view) = user_view {
recipient_ids.push(parent_user_view.local_user.id); recipient_ids.push(parent_user_view.local_user.id);
@ -260,9 +270,10 @@ pub async fn send_local_notifs(
None => { None => {
if post.creator_id != person.id { if post.creator_id != person.id {
let creator_id = post.creator_id; let creator_id = post.creator_id;
let parent_user = blocking(context.pool(), move |conn| { let parent_user = context
LocalUserView::read_person(conn, creator_id) .conn()
}) .await?
.interact(move |conn| LocalUserView::read_person(conn, creator_id))
.await?; .await?;
if let Ok(parent_user_view) = parent_user { if let Ok(parent_user_view) = parent_user {
recipient_ids.push(parent_user_view.local_user.id); recipient_ids.push(parent_user_view.local_user.id);

View file

@ -3,13 +3,9 @@ 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, Runtime};
r2d2::{ConnectionManager, Pool},
PgConnection,
};
use doku::json::{AutoComments, Formatting}; use doku::json::{AutoComments, Formatting};
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_lib::activity_queue::create_activity_queue; use lemmy_apub_lib::activity_queue::create_activity_queue;
use lemmy_db_schema::{get_database_url_from_env, source::secret::Secret}; use lemmy_db_schema::{get_database_url_from_env, source::secret::Secret};
@ -43,29 +39,30 @@ async fn main() -> Result<(), LemmyError> {
env_logger::init(); env_logger::init();
let settings = Settings::init().expect("Couldn't initialize settings."); let settings = Settings::init().expect("Couldn't initialize settings.");
// 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, Runtime::Tokio1);
let pool = Pool::builder(manager)
.max_size(settings.database.pool_size) .max_size(settings.database.pool_size)
.build(manager) .build()?;
.unwrap_or_else(|_| panic!("Error connecting to {}", db_url));
// Run the migrations from code // Run the migrations from code
let protocol_and_hostname = settings.get_protocol_and_hostname(); let protocol_and_hostname = settings.get_protocol_and_hostname();
blocking(&pool, move |conn| { let conn = pool.get().await?;
conn
.interact(move |conn| {
embedded_migrations::run(conn)?; embedded_migrations::run(conn)?;
run_advanced_migrations(conn, &protocol_and_hostname)?; run_advanced_migrations(conn, &protocol_and_hostname)?;
Ok(()) as Result<(), LemmyError> Ok(()) as Result<(), LemmyError>
}) })
.await??; .await??;
let pool2 = pool.clone();
thread::spawn(move || { thread::spawn(move || {
scheduled_tasks::setup(pool2); scheduled_tasks::setup(&db_url);
}); });
// Set up the rate limiter // Set up the rate limiter
@ -75,8 +72,11 @@ async fn main() -> Result<(), LemmyError> {
}; };
// Initialize the secrets // Initialize the secrets
let conn = pool.get()?; let conn = pool.get().await?;
let secret = Secret::init(&conn).expect("Couldn't initialize secrets."); let secret = conn
.interact(|conn| Secret::init(conn))
.await?
.expect("Couldn't initialize secrets.");
println!( println!(
"Starting http server at {}:{}", "Starting http server at {}:{}",

View file

@ -2,29 +2,33 @@
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_schema::{source::activity::Activity, DbPool}; use lemmy_db_schema::{establish_unpooled_connection_with_db_url, source::activity::Activity};
use log::info; use log::info;
use std::{thread, time::Duration}; use std::{thread, time::Duration};
/// 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(db_url: &str) {
let mut scheduler = Scheduler::new(); let mut scheduler = Scheduler::new();
let conn = pool.get().unwrap(); let conn = &establish_unpooled_connection_with_db_url(db_url);
active_counts(&conn);
active_counts(conn);
// On startup, reindex the tables non-concurrently // On startup, reindex the tables non-concurrently
// TODO remove this for now, since it slows down startup a lot on lemmy.ml // TODO remove this for now, since it slows down startup a lot on lemmy.ml
reindex_aggregates_tables(&conn, true); reindex_aggregates_tables(conn, true);
clear_old_activities(conn);
let db_url2 = db_url.to_owned();
scheduler.every(1.hour()).run(move || { scheduler.every(1.hour()).run(move || {
active_counts(&conn); let conn = &establish_unpooled_connection_with_db_url(&db_url2);
reindex_aggregates_tables(&conn, true); active_counts(conn);
reindex_aggregates_tables(conn, true);
}); });
let conn = pool.get().unwrap(); let db_url3 = db_url.to_owned();
clear_old_activities(&conn);
scheduler.every(1.weeks()).run(move || { scheduler.every(1.weeks()).run(move || {
clear_old_activities(&conn); let conn = &establish_unpooled_connection_with_db_url(&db_url3);
clear_old_activities(conn);
}); });
// Manually run the scheduler in an event loop // Manually run the scheduler in an event loop