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",
]
[[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]]
name = "deflate"
version = "0.8.6"
@ -950,7 +991,6 @@ dependencies = [
"chrono",
"diesel_derives",
"pq-sys",
"r2d2",
"serde_json",
]
@ -1828,6 +1868,7 @@ dependencies = [
"background-jobs",
"bcrypt",
"chrono",
"deadpool-diesel",
"diesel",
"futures",
"html2md",
@ -1901,6 +1942,7 @@ version = "0.13.5-rc.7"
dependencies = [
"bcrypt",
"chrono",
"deadpool-diesel",
"diesel",
"diesel-derive-newtype",
"diesel_migrations",
@ -1988,6 +2030,7 @@ dependencies = [
"cargo-husky",
"chrono",
"clokwerk",
"deadpool-diesel",
"diesel",
"diesel_migrations",
"doku",
@ -2019,16 +2062,25 @@ dependencies = [
name = "lemmy_utils"
version = "0.13.5-rc.7"
dependencies = [
"activitystreams",
"actix",
"actix-rt",
"actix-web",
"anyhow",
"base64 0.13.0",
"chrono",
"comrak",
"deadpool",
"deadpool-diesel",
"deadpool-sync",
"deser-hjson",
"diesel",
"diesel_migrations",
"doku",
"futures",
"http",
"http-signature-normalization-actix",
"http-signature-normalization-reqwest",
"itertools",
"jsonwebtoken",
"lazy_static",
@ -2061,6 +2113,8 @@ dependencies = [
"anyhow",
"background-jobs",
"chrono",
"deadpool",
"deadpool-diesel",
"diesel",
"lemmy_api_common",
"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" }
diesel = "1.4.8"
diesel_migrations = "1.4.0"
deadpool-diesel = { version = "0.3.1", features = ["postgres"] }
chrono = { version = "0.4.19", features = ["serde"] }
serde = { version = "1.0.130", features = ["derive"] }
actix = "0.12.0"

View file

@ -3,7 +3,6 @@ use std::convert::TryInto;
use actix_web::web::Data;
use lemmy_api_common::{
blocking,
check_community_ban,
check_downvotes_enabled,
check_person_block,
@ -42,9 +41,10 @@ impl Perform for MarkCommentAsRead {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let comment_id = data.comment_id;
let orig_comment = blocking(context.pool(), move |conn| {
CommentView::read(conn, comment_id, None)
})
let orig_comment = context
.conn()
.await?
.interact(move |conn| CommentView::read(conn, comment_id, None))
.await??;
check_community_ban(
@ -61,18 +61,20 @@ impl Perform for MarkCommentAsRead {
// Do the mark as read
let read = data.read;
blocking(context.pool(), move |conn| {
Comment::update_read(conn, comment_id, read)
})
context
.conn()
.await?
.interact(move |conn| Comment::update_read(conn, comment_id, read))
.await?
.map_err(|_| ApiError::err_plain("couldnt_update_comment"))?;
// Refetch it
let comment_id = data.comment_id;
let person_id = local_user_view.person.id;
let comment_view = blocking(context.pool(), move |conn| {
CommentView::read(conn, comment_id, Some(person_id))
})
let comment_view = context
.conn()
.await?
.interact(move |conn| CommentView::read(conn, comment_id, Some(person_id)))
.await??;
let res = CommentResponse {
@ -104,22 +106,27 @@ impl Perform for SaveComment {
};
if data.save {
let save_comment = move |conn: &'_ _| CommentSaved::save(conn, &comment_saved_form);
blocking(context.pool(), save_comment)
context
.conn()
.await?
.interact(move |conn| CommentSaved::save(conn, &comment_saved_form))
.await?
.map_err(|e| ApiError::err("couldnt_save_comment", e))?;
} else {
let unsave_comment = move |conn: &'_ _| CommentSaved::unsave(conn, &comment_saved_form);
blocking(context.pool(), unsave_comment)
context
.conn()
.await?
.interact(move |conn| CommentSaved::unsave(conn, &comment_saved_form))
.await?
.map_err(|e| ApiError::err("couldnt_save_comment", e))?;
}
let comment_id = data.comment_id;
let person_id = local_user_view.person.id;
let comment_view = blocking(context.pool(), move |conn| {
CommentView::read(conn, comment_id, Some(person_id))
})
let comment_view = context
.conn()
.await?
.interact(move |conn| CommentView::read(conn, comment_id, Some(person_id)))
.await??;
Ok(CommentResponse {
@ -149,9 +156,10 @@ impl Perform for CreateCommentLike {
check_downvotes_enabled(data.score, context.pool()).await?;
let comment_id = data.comment_id;
let orig_comment = blocking(context.pool(), move |conn| {
CommentView::read(conn, comment_id, None)
})
let orig_comment = context
.conn()
.await?
.interact(move |conn| CommentView::read(conn, comment_id, None))
.await??;
check_community_ban(
@ -170,9 +178,10 @@ impl Perform for CreateCommentLike {
// Add parent user to recipients
let recipient_id = orig_comment.get_recipient_id();
if let Ok(local_recipient) = blocking(context.pool(), move |conn| {
LocalUserView::read_person(conn, recipient_id)
})
if let Ok(local_recipient) = context
.conn()
.await?
.interact(move |conn| LocalUserView::read_person(conn, recipient_id))
.await?
{
recipient_ids.push(local_recipient.local_user.id);
@ -187,9 +196,10 @@ impl Perform for CreateCommentLike {
// Remove any likes first
let person_id = local_user_view.person.id;
blocking(context.pool(), move |conn| {
CommentLike::remove(conn, person_id, comment_id)
})
context
.conn()
.await?
.interact(move |conn| CommentLike::remove(conn, person_id, comment_id))
.await??;
// 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);
if do_add {
let like_form2 = like_form.clone();
let like = move |conn: &'_ _| CommentLike::like(conn, &like_form2);
blocking(context.pool(), like)
context
.conn()
.await?
.interact(move |conn| CommentLike::like(conn, &like_form2))
.await?
.map_err(|e| ApiError::err("couldnt_like_comment", e))?;

View file

@ -1,7 +1,6 @@
use crate::Perform;
use actix_web::web::Data;
use lemmy_api_common::{
blocking,
check_community_ban,
comment::*,
get_local_user_view_from_jwt,
@ -42,9 +41,10 @@ impl Perform for CreateCommentReport {
let person_id = local_user_view.person.id;
let comment_id = data.comment_id;
let comment_view = blocking(context.pool(), move |conn| {
CommentView::read(conn, comment_id, None)
})
let comment_view = context
.conn()
.await?
.interact(move |conn| CommentView::read(conn, comment_id, None))
.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(),
};
let report = blocking(context.pool(), move |conn| {
CommentReport::report(conn, &report_form)
})
let report = context
.conn()
.await?
.interact(move |conn| CommentReport::report(conn, &report_form))
.await?
.map_err(|e| ApiError::err("couldnt_create_report", e))?;
let comment_report_view = blocking(context.pool(), move |conn| {
CommentReportView::read(conn, report.id, person_id)
})
let comment_report_view = context
.conn()
.await?
.interact(move |conn| CommentReportView::read(conn, report.id, person_id))
.await??;
let res = CommentReportResponse {
@ -107,31 +109,35 @@ impl Perform for ResolveCommentReport {
let report_id = data.report_id;
let person_id = local_user_view.person.id;
let report = blocking(context.pool(), move |conn| {
CommentReportView::read(conn, report_id, person_id)
})
let report = context
.conn()
.await?
.interact(move |conn| CommentReportView::read(conn, report_id, person_id))
.await??;
let person_id = local_user_view.person.id;
is_mod_or_admin(context.pool(), person_id, report.community.id).await?;
let resolved = data.resolved;
let resolve_fun = move |conn: &'_ _| {
context
.conn()
.await?
.interact(move |conn| {
if resolved {
CommentReport::resolve(conn, report_id, person_id)
} else {
CommentReport::unresolve(conn, report_id, person_id)
}
};
blocking(context.pool(), resolve_fun)
})
.await?
.map_err(|e| ApiError::err("couldnt_resolve_report", e))?;
let report_id = data.report_id;
let comment_report_view = blocking(context.pool(), move |conn| {
CommentReportView::read(conn, report_id, person_id)
})
let comment_report_view = context
.conn()
.await?
.interact(move |conn| CommentReportView::read(conn, report_id, person_id))
.await??;
let res = CommentReportResponse {
@ -171,7 +177,10 @@ impl Perform for ListCommentReports {
let page = data.page;
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)
.community_id(community_id)
.unresolved_only(unresolved_only)

View file

@ -2,7 +2,6 @@ use crate::Perform;
use actix_web::web::Data;
use anyhow::Context;
use lemmy_api_common::{
blocking,
check_community_ban,
check_community_deleted_or_removed,
community::*,
@ -71,9 +70,10 @@ impl Perform for FollowCommunity {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let community_id = data.community_id;
let community: ApubCommunity = blocking(context.pool(), move |conn| {
Community::read(conn, community_id)
})
let community: ApubCommunity = context
.conn()
.await?
.interact(move |conn| Community::read(conn, community_id))
.await??
.into();
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_deleted_or_removed(community_id, context.pool()).await?;
let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form);
blocking(context.pool(), follow)
context
.conn()
.await?
.interact(move |conn| CommunityFollower::follow(conn, &community_follower_form))
.await?
.map_err(|e| ApiError::err("community_follower_already_exists", e))?;
} else {
let unfollow =
move |conn: &'_ _| CommunityFollower::unfollow(conn, &community_follower_form);
blocking(context.pool(), unfollow)
context
.conn()
.await?
.interact(move |conn| CommunityFollower::unfollow(conn, &community_follower_form))
.await?
.map_err(|e| ApiError::err("community_follower_already_exists", e))?;
}
@ -106,17 +109,20 @@ impl Perform for FollowCommunity {
} else {
UndoFollowCommunity::send(&local_user_view.person.clone().into(), &community, context)
.await?;
let unfollow = move |conn: &'_ _| CommunityFollower::unfollow(conn, &community_follower_form);
blocking(context.pool(), unfollow)
context
.conn()
.await?
.interact(move |conn| CommunityFollower::unfollow(conn, &community_follower_form))
.await?
.map_err(|e| ApiError::err("community_follower_already_exists", e))?;
}
let community_id = data.community_id;
let person_id = local_user_view.person.id;
let mut community_view = blocking(context.pool(), move |conn| {
CommunityView::read(conn, community_id, Some(person_id))
})
let mut community_view = context
.conn()
.await?
.interact(move |conn| CommunityView::read(conn, community_id, Some(person_id)))
.await??;
// 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 {
let block = move |conn: &'_ _| CommunityBlock::block(conn, &community_block_form);
blocking(context.pool(), block)
context
.conn()
.await?
.interact(move |conn| CommunityBlock::block(conn, &community_block_form))
.await?
.map_err(|e| ApiError::err("community_block_already_exists", e))?;
@ -162,26 +170,31 @@ impl Perform for BlockCommunity {
person_id,
pending: false,
};
blocking(context.pool(), move |conn: &'_ _| {
CommunityFollower::unfollow(conn, &community_follower_form)
})
context
.conn()
.await?
.interact(move |conn| CommunityFollower::unfollow(conn, &community_follower_form))
.await?
.ok();
let community = blocking(context.pool(), move |conn| {
Community::read(conn, community_id)
})
let community = context
.conn()
.await?
.interact(move |conn| Community::read(conn, community_id))
.await??;
UndoFollowCommunity::send(&local_user_view.person.into(), &community.into(), context).await?;
} else {
let unblock = move |conn: &'_ _| CommunityBlock::unblock(conn, &community_block_form);
blocking(context.pool(), unblock)
context
.conn()
.await?
.interact(move |conn| CommunityBlock::unblock(conn, &community_block_form))
.await?
.map_err(|e| ApiError::err("community_block_already_exists", e))?;
}
let community_view = blocking(context.pool(), move |conn| {
CommunityView::read(conn, community_id, Some(person_id))
})
let community_view = context
.conn()
.await?
.interact(move |conn| CommunityView::read(conn, community_id, Some(person_id)))
.await??;
Ok(BlockCommunityResponse {
@ -215,20 +228,24 @@ impl Perform for BanFromCommunity {
person_id: data.person_id,
};
let community: ApubCommunity = blocking(context.pool(), move |conn: &'_ _| {
Community::read(conn, community_id)
})
let community: ApubCommunity = context
.conn()
.await?
.interact(move |conn| Community::read(conn, community_id))
.await??
.into();
let banned_person: ApubPerson = blocking(context.pool(), move |conn: &'_ _| {
Person::read(conn, banned_person_id)
})
let banned_person: ApubPerson = context
.conn()
.await?
.interact(move |conn| Person::read(conn, banned_person_id))
.await??
.into();
if data.ban {
let ban = move |conn: &'_ _| CommunityPersonBan::ban(conn, &community_user_ban_form);
blocking(context.pool(), ban)
context
.conn()
.await?
.interact(move |conn| CommunityPersonBan::ban(conn, &community_user_ban_form))
.await?
.map_err(|e| ApiError::err("community_user_already_banned", e))?;
@ -238,9 +255,10 @@ impl Perform for BanFromCommunity {
person_id: banned_person_id,
pending: false,
};
blocking(context.pool(), move |conn: &'_ _| {
CommunityFollower::unfollow(conn, &community_follower_form)
})
context
.conn()
.await?
.interact(move |conn| CommunityFollower::unfollow(conn, &community_follower_form))
.await?
.ok();
@ -252,8 +270,10 @@ impl Perform for BanFromCommunity {
)
.await?;
} else {
let unban = move |conn: &'_ _| CommunityPersonBan::unban(conn, &community_user_ban_form);
blocking(context.pool(), unban)
context
.conn()
.await?
.interact(move |conn| CommunityPersonBan::unban(conn, &community_user_ban_form))
.await?
.map_err(|e| ApiError::err("community_user_already_banned", e))?;
UndoBlockUserFromCommunity::send(
@ -268,14 +288,20 @@ impl Perform for BanFromCommunity {
// Remove/Restore their data if that's desired
if data.remove_data.unwrap_or(false) {
// 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)
})
.await??;
// Comments
// 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)
.creator_id(banned_person_id)
.community_id(community_id)
@ -286,9 +312,10 @@ impl Perform for BanFromCommunity {
for comment_view in &comments {
let comment_id = comment_view.comment.id;
blocking(context.pool(), move |conn: &'_ _| {
Comment::update_removed(conn, comment_id, true)
})
context
.conn()
.await?
.interact(move |conn| Comment::update_removed(conn, comment_id, true))
.await??;
}
}
@ -305,15 +332,17 @@ impl Perform for BanFromCommunity {
banned: Some(data.ban),
expires,
};
blocking(context.pool(), move |conn| {
ModBanFromCommunity::create(conn, &form)
})
context
.conn()
.await?
.interact(move |conn| ModBanFromCommunity::create(conn, &form))
.await??;
let person_id = data.person_id;
let person_view = blocking(context.pool(), move |conn| {
PersonViewSafe::read(conn, person_id)
})
let person_view = context
.conn()
.await?
.interact(move |conn| PersonViewSafe::read(conn, person_id))
.await??;
let res = BanFromCommunityResponse {
@ -356,13 +385,17 @@ impl Perform for AddModToCommunity {
person_id: data.person_id,
};
if data.added {
let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form);
blocking(context.pool(), join)
context
.conn()
.await?
.interact(move |conn| CommunityModerator::join(conn, &community_moderator_form))
.await?
.map_err(|e| ApiError::err("community_moderator_already_exists", e))?;
} else {
let leave = move |conn: &'_ _| CommunityModerator::leave(conn, &community_moderator_form);
blocking(context.pool(), leave)
context
.conn()
.await?
.interact(move |conn| CommunityModerator::leave(conn, &community_moderator_form))
.await?
.map_err(|e| ApiError::err("community_moderator_already_exists", e))?;
}
@ -374,21 +407,24 @@ impl Perform for AddModToCommunity {
community_id: data.community_id,
removed: Some(!data.added),
};
blocking(context.pool(), move |conn| {
ModAddCommunity::create(conn, &form)
})
context
.conn()
.await?
.interact(move |conn| ModAddCommunity::create(conn, &form))
.await??;
// Send to federated instances
let updated_mod_id = data.person_id;
let updated_mod: ApubPerson = blocking(context.pool(), move |conn| {
Person::read(conn, updated_mod_id)
})
let updated_mod: ApubPerson = context
.conn()
.await?
.interact(move |conn| Person::read(conn, updated_mod_id))
.await??
.into();
let community: ApubCommunity = blocking(context.pool(), move |conn| {
Community::read(conn, community_id)
})
let community: ApubCommunity = context
.conn()
.await?
.interact(move |conn| Community::read(conn, community_id))
.await??
.into();
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
// updated once we receive an activity from the community (like `Announce/Add/Moderator`)
let community_id = data.community_id;
let moderators = blocking(context.pool(), move |conn| {
CommunityModeratorView::for_community(conn, community_id)
})
let moderators = context
.conn()
.await?
.interact(move |conn| CommunityModeratorView::for_community(conn, community_id))
.await??;
let res = AddModToCommunityResponse { moderators };
@ -443,12 +480,17 @@ impl Perform for TransferCommunity {
let local_user_view =
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let site_creator_id = blocking(context.pool(), move |conn| {
Site::read(conn, 1).map(|s| s.creator_id)
})
let site_creator_id = context
.conn()
.await?
.interact(move |conn| Site::read(conn, 1).map(|s| s.creator_id))
.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
let creator_index = admins
@ -460,9 +502,10 @@ impl Perform for TransferCommunity {
// Fetch the community mods
let community_id = data.community_id;
let mut community_mods = blocking(context.pool(), move |conn| {
CommunityModeratorView::for_community(conn, community_id)
})
let mut community_mods = context
.conn()
.await?
.interact(move |conn| CommunityModeratorView::for_community(conn, community_id))
.await??;
// Make sure transferrer is either the top community mod, or an admin
@ -486,9 +529,10 @@ impl Perform for TransferCommunity {
// Delete all the mods
let community_id = data.community_id;
blocking(context.pool(), move |conn| {
CommunityModerator::delete_for_community(conn, community_id)
})
context
.conn()
.await?
.interact(move |conn| CommunityModerator::delete_for_community(conn, community_id))
.await??;
// TODO: this should probably be a bulk operation
@ -499,8 +543,10 @@ impl Perform for TransferCommunity {
person_id: cmod.moderator.id,
};
let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form);
blocking(context.pool(), join)
context
.conn()
.await?
.interact(move |conn| CommunityModerator::join(conn, &community_moderator_form))
.await?
.map_err(|e| ApiError::err("community_moderator_already_exists", e))?;
}
@ -512,23 +558,26 @@ impl Perform for TransferCommunity {
community_id: data.community_id,
removed: Some(false),
};
blocking(context.pool(), move |conn| {
ModTransferCommunity::create(conn, &form)
})
context
.conn()
.await?
.interact(move |conn| ModTransferCommunity::create(conn, &form))
.await??;
let community_id = data.community_id;
let person_id = local_user_view.person.id;
let community_view = blocking(context.pool(), move |conn| {
CommunityView::read(conn, community_id, Some(person_id))
})
let community_view = context
.conn()
.await?
.interact(move |conn| CommunityView::read(conn, community_id, Some(person_id)))
.await?
.map_err(|e| ApiError::err("couldnt_find_community", e))?;
let community_id = data.community_id;
let moderators = blocking(context.pool(), move |conn| {
CommunityModeratorView::for_community(conn, community_id)
})
let moderators = context
.conn()
.await?
.interact(move |conn| CommunityModeratorView::for_community(conn, community_id))
.await?
.map_err(|e| ApiError::err("couldnt_find_community", e))?;

View file

@ -4,13 +4,7 @@ use anyhow::Context;
use bcrypt::verify;
use captcha::{gen, Difficulty};
use chrono::Duration;
use lemmy_api_common::{
blocking,
get_local_user_view_from_jwt,
is_admin,
password_length_check,
person::*,
};
use lemmy_api_common::{get_local_user_view_from_jwt, is_admin, password_length_check, person::*};
use lemmy_db_schema::{
diesel_option_overwrite,
diesel_option_overwrite_to_url,
@ -72,9 +66,10 @@ impl Perform for Login {
// Fetch that username / email
let username_or_email = data.username_or_email.clone();
let local_user_view = blocking(context.pool(), move |conn| {
LocalUserView::find_by_email_or_name(conn, &username_or_email)
})
let local_user_view = context
.conn()
.await?
.interact(move |conn| LocalUserView::find_by_email_or_name(conn, &username_or_email))
.await?
.map_err(|e| ApiError::err("couldnt_find_that_username_or_email", e))?;
@ -214,9 +209,10 @@ impl Perform for SaveUserSettings {
bot_account,
};
blocking(context.pool(), move |conn| {
Person::update(conn, person_id, &person_form)
})
context
.conn()
.await?
.interact(move |conn| Person::update(conn, person_id, &person_form))
.await?
.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,
};
let local_user_res = blocking(context.pool(), move |conn| {
LocalUser::update(conn, local_user_id, &local_user_form)
})
let local_user_res = context
.conn()
.await?
.interact(move |conn| LocalUser::update(conn, local_user_id, &local_user_form))
.await?;
let updated_local_user = match local_user_res {
Ok(u) => u,
@ -299,9 +296,10 @@ impl Perform for ChangePassword {
let local_user_id = local_user_view.local_user.id;
let new_password = data.new_password.to_owned();
let updated_local_user = blocking(context.pool(), move |conn| {
LocalUser::update_password(conn, local_user_id, &new_password)
})
let updated_local_user = context
.conn()
.await?
.interact(move |conn| LocalUser::update_password(conn, local_user_id, &new_password))
.await??;
// Return the jwt
@ -333,9 +331,10 @@ impl Perform for AddAdmin {
let added = data.added;
let added_person_id = data.person_id;
let added_admin = blocking(context.pool(), move |conn| {
Person::add_admin(conn, added_person_id, added)
})
let added_admin = context
.conn()
.await?
.interact(move |conn| Person::add_admin(conn, added_person_id, added))
.await?
.map_err(|e| ApiError::err("couldnt_update_user", e))?;
@ -346,14 +345,23 @@ impl Perform for AddAdmin {
removed: Some(!data.added),
};
blocking(context.pool(), move |conn| ModAdd::create(conn, &form)).await??;
let site_creator_id = blocking(context.pool(), move |conn| {
Site::read(conn, 1).map(|s| s.creator_id)
})
context
.conn()
.await?
.interact(move |conn| ModAdd::create(conn, &form))
.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
.iter()
.position(|r| r.person.id == site_creator_id)
@ -391,25 +399,29 @@ impl Perform for BanPerson {
let ban = data.ban;
let banned_person_id = data.person_id;
let ban_person = move |conn: &'_ _| Person::ban_person(conn, banned_person_id, ban);
blocking(context.pool(), ban_person)
context
.conn()
.await?
.interact(move |conn| Person::ban_person(conn, banned_person_id, ban))
.await?
.map_err(|e| ApiError::err("couldnt_update_user", e))?;
// Remove their data if that's desired
if data.remove_data.unwrap_or(false) {
// Posts
blocking(context.pool(), move |conn: &'_ _| {
Post::update_removed_for_creator(conn, banned_person_id, None, true)
})
context
.conn()
.await?
.interact(move |conn| Post::update_removed_for_creator(conn, banned_person_id, None, true))
.await??;
// Communities
// Remove all communities where they're the top mod
// for now, remove the communities manually
let first_mod_communities = blocking(context.pool(), move |conn: &'_ _| {
CommunityModeratorView::get_community_first_mods(conn)
})
let first_mod_communities = context
.conn()
.await?
.interact(move |conn| CommunityModeratorView::get_community_first_mods(conn))
.await??;
// Filter to only this banned users top communities
@ -419,16 +431,20 @@ impl Perform for BanPerson {
.collect();
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)
})
.await??;
}
// Comments
blocking(context.pool(), move |conn: &'_ _| {
Comment::update_removed_for_creator(conn, banned_person_id, true)
})
context
.conn()
.await?
.interact(move |conn| Comment::update_removed_for_creator(conn, banned_person_id, true))
.await??;
}
@ -443,12 +459,17 @@ impl Perform for BanPerson {
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_view = blocking(context.pool(), move |conn| {
PersonViewSafe::read(conn, person_id)
})
let person_view = context
.conn()
.await?
.interact(move |conn| PersonViewSafe::read(conn, person_id))
.await??;
let res = BanPersonResponse {
@ -493,22 +514,27 @@ impl Perform for BlockPerson {
};
if data.block {
let block = move |conn: &'_ _| PersonBlock::block(conn, &person_block_form);
blocking(context.pool(), block)
context
.conn()
.await?
.interact(move |conn| PersonBlock::block(conn, &person_block_form))
.await?
.map_err(|e| ApiError::err("person_block_already_exists", e))?;
} else {
let unblock = move |conn: &'_ _| PersonBlock::unblock(conn, &person_block_form);
blocking(context.pool(), unblock)
context
.conn()
.await?
.interact(move |conn| PersonBlock::unblock(conn, &person_block_form))
.await?
.map_err(|e| ApiError::err("person_block_already_exists", e))?;
}
// TODO does any federated stuff need to be done here?
let person_view = blocking(context.pool(), move |conn| {
PersonViewSafe::read(conn, target_id)
})
let person_view = context
.conn()
.await?
.interact(move |conn| PersonViewSafe::read(conn, target_id))
.await??;
let res = BlockPersonResponse {
@ -541,7 +567,10 @@ impl Perform for GetReplies {
let person_id = local_user_view.person.id;
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)
.sort(sort)
.unread_only(unread_only)
@ -577,7 +606,10 @@ impl Perform for GetPersonMentions {
let limit = data.limit;
let unread_only = data.unread_only;
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)
.recipient_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?;
let person_mention_id = data.person_mention_id;
let read_person_mention = blocking(context.pool(), move |conn| {
PersonMention::read(conn, person_mention_id)
})
let read_person_mention = context
.conn()
.await?
.interact(move |conn| PersonMention::read(conn, person_mention_id))
.await??;
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 read = data.read;
let update_mention =
move |conn: &'_ _| PersonMention::update_read(conn, person_mention_id, read);
blocking(context.pool(), update_mention)
context
.conn()
.await?
.interact(move |conn| PersonMention::update_read(conn, person_mention_id, read))
.await?
.map_err(|e| ApiError::err("couldnt_update_comment", e))?;
let person_mention_id = read_person_mention.id;
let person_id = local_user_view.person.id;
let person_mention_view = blocking(context.pool(), move |conn| {
PersonMentionView::read(conn, person_mention_id, Some(person_id))
})
let person_mention_view = context
.conn()
.await?
.interact(move |conn| PersonMentionView::read(conn, person_mention_id, Some(person_id)))
.await??;
Ok(PersonMentionResponse {
@ -651,7 +687,10 @@ impl Perform for MarkAllAsRead {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
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)
.my_person_id(person_id)
.recipient_id(person_id)
@ -667,22 +706,27 @@ impl Perform for MarkAllAsRead {
// because recipient_id isn't in the comment table
for comment_view in &replies {
let reply_id = comment_view.comment.id;
let mark_as_read = move |conn: &'_ _| Comment::update_read(conn, reply_id, true);
blocking(context.pool(), mark_as_read)
context
.conn()
.await?
.interact(move |conn| Comment::update_read(conn, reply_id, true))
.await?
.map_err(|e| ApiError::err("couldnt_update_comment", e))?;
}
// Mark all user mentions as read
let update_person_mentions =
move |conn: &'_ _| PersonMention::mark_all_as_read(conn, person_id);
blocking(context.pool(), update_person_mentions)
context
.conn()
.await?
.interact(move |conn| PersonMention::mark_all_as_read(conn, person_id))
.await?
.map_err(|e| ApiError::err("couldnt_update_comment", e))?;
// Mark all private_messages as read
let update_pm = move |conn: &'_ _| PrivateMessage::mark_all_as_read(conn, person_id);
blocking(context.pool(), update_pm)
context
.conn()
.await?
.interact(move |conn| PrivateMessage::mark_all_as_read(conn, person_id))
.await?
.map_err(|e| ApiError::err("couldnt_update_private_message", e))?;
@ -703,9 +747,10 @@ impl Perform for PasswordReset {
// Fetch that email
let email = data.email.clone();
let local_user_view = blocking(context.pool(), move |conn| {
LocalUserView::find_by_email(conn, &email)
})
let local_user_view = context
.conn()
.await?
.interact(move |conn| LocalUserView::find_by_email(conn, &email))
.await?
.map_err(|e| ApiError::err("couldnt_find_that_username_or_email", e))?;
@ -715,9 +760,10 @@ impl Perform for PasswordReset {
// Insert the row
let token2 = token.clone();
let local_user_id = local_user_view.local_user.id;
blocking(context.pool(), move |conn| {
PasswordResetRequest::create_token(conn, local_user_id, &token2)
})
context
.conn()
.await?
.interact(move |conn| PasswordResetRequest::create_token(conn, local_user_id, &token2))
.await??;
// Email the pure token to the user.
@ -752,7 +798,10 @@ impl Perform for PasswordChange {
// Fetch the user_id from the token
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)
})
.await??;
@ -766,9 +815,10 @@ impl Perform for PasswordChange {
// Update the user with the new password
let password = data.password.clone();
let updated_local_user = blocking(context.pool(), move |conn| {
LocalUser::update_password(conn, local_user_id, &password)
})
let updated_local_user = context
.conn()
.await?
.interact(move |conn| LocalUser::update_password(conn, local_user_id, &password))
.await?
.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 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)
})
.await??;
let post_reports = blocking(context.pool(), move |conn| {
PostReportView::get_report_count(conn, person_id, admin, community_id)
})
let post_reports = context
.conn()
.await?
.interact(move |conn| PostReportView::get_report_count(conn, person_id, admin, community_id))
.await??;
let res = GetReportCountResponse {
@ -835,19 +889,22 @@ impl Perform for GetUnreadCount {
let person_id = local_user_view.person.id;
let replies = blocking(context.pool(), move |conn| {
CommentView::get_unread_replies(conn, person_id)
})
let replies = context
.conn()
.await?
.interact(move |conn| CommentView::get_unread_replies(conn, person_id))
.await??;
let mentions = blocking(context.pool(), move |conn| {
PersonMentionView::get_unread_mentions(conn, person_id)
})
let mentions = context
.conn()
.await?
.interact(move |conn| PersonMentionView::get_unread_mentions(conn, person_id))
.await??;
let private_messages = blocking(context.pool(), move |conn| {
PrivateMessageView::get_unread_messages(conn, person_id)
})
let private_messages = context
.conn()
.await?
.interact(move |conn| PrivateMessageView::get_unread_messages(conn, person_id))
.await??;
let res = Self::Response {

View file

@ -1,7 +1,6 @@
use crate::Perform;
use actix_web::web::Data;
use lemmy_api_common::{
blocking,
check_community_ban,
check_community_deleted_or_removed,
check_downvotes_enabled,
@ -50,7 +49,10 @@ impl Perform for CreatePostLike {
// Check for a community ban
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??
.into();
@ -67,9 +69,10 @@ impl Perform for CreatePostLike {
// Remove any likes first
let person_id = local_user_view.person.id;
blocking(context.pool(), move |conn| {
PostLike::remove(conn, person_id, post_id)
})
context
.conn()
.await?
.interact(move |conn| PostLike::remove(conn, person_id, post_id))
.await??;
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);
if do_add {
let like_form2 = like_form.clone();
let like = move |conn: &'_ _| PostLike::like(conn, &like_form2);
blocking(context.pool(), like)
context
.conn()
.await?
.interact(move |conn| PostLike::like(conn, &like_form2))
.await?
.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?;
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(
local_user_view.person.id,
@ -153,9 +162,10 @@ impl Perform for LockPost {
// Update the post
let post_id = data.post_id;
let locked = data.locked;
let updated_post: ApubPost = blocking(context.pool(), move |conn| {
Post::update_locked(conn, post_id, locked)
})
let updated_post: ApubPost = context
.conn()
.await?
.interact(move |conn| Post::update_locked(conn, post_id, locked))
.await??
.into();
@ -165,7 +175,11 @@ impl Perform for LockPost {
post_id: data.post_id,
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
CreateOrUpdatePost::send(
@ -201,7 +215,11 @@ impl Perform for StickyPost {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
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(
local_user_view.person.id,
@ -222,9 +240,10 @@ impl Perform for StickyPost {
// Update the post
let post_id = data.post_id;
let stickied = data.stickied;
let updated_post: ApubPost = blocking(context.pool(), move |conn| {
Post::update_stickied(conn, post_id, stickied)
})
let updated_post: ApubPost = context
.conn()
.await?
.interact(move |conn| Post::update_stickied(conn, post_id, stickied))
.await??
.into();
@ -234,9 +253,10 @@ impl Perform for StickyPost {
post_id: data.post_id,
stickied: Some(stickied),
};
blocking(context.pool(), move |conn| {
ModStickyPost::create(conn, &form)
})
context
.conn()
.await?
.interact(move |conn| ModStickyPost::create(conn, &form))
.await??;
// Apub updates
@ -279,22 +299,27 @@ impl Perform for SavePost {
};
if data.save {
let save = move |conn: &'_ _| PostSaved::save(conn, &post_saved_form);
blocking(context.pool(), save)
context
.conn()
.await?
.interact(move |conn| PostSaved::save(conn, &post_saved_form))
.await?
.map_err(|e| ApiError::err("couldnt_save_post", e))?;
} else {
let unsave = move |conn: &'_ _| PostSaved::unsave(conn, &post_saved_form);
blocking(context.pool(), unsave)
context
.conn()
.await?
.interact(move |conn| PostSaved::unsave(conn, &post_saved_form))
.await?
.map_err(|e| ApiError::err("couldnt_save_post", e))?;
}
let post_id = data.post_id;
let person_id = local_user_view.person.id;
let post_view = blocking(context.pool(), move |conn| {
PostView::read(conn, post_id, Some(person_id))
})
let post_view = context
.conn()
.await?
.interact(move |conn| PostView::read(conn, post_id, Some(person_id)))
.await??;
// Mark the post as read

View file

@ -1,7 +1,6 @@
use crate::Perform;
use actix_web::web::Data;
use lemmy_api_common::{
blocking,
check_community_ban,
get_local_user_view_from_jwt,
is_mod_or_admin,
@ -51,9 +50,10 @@ impl Perform for CreatePostReport {
let person_id = local_user_view.person.id;
let post_id = data.post_id;
let post_view = blocking(context.pool(), move |conn| {
PostView::read(conn, post_id, None)
})
let post_view = context
.conn()
.await?
.interact(move |conn| PostView::read(conn, post_id, None))
.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(),
};
let report = blocking(context.pool(), move |conn| {
PostReport::report(conn, &report_form)
})
let report = context
.conn()
.await?
.interact(move |conn| PostReport::report(conn, &report_form))
.await?
.map_err(|e| ApiError::err("couldnt_create_report", e))?;
let post_report_view = blocking(context.pool(), move |conn| {
PostReportView::read(conn, report.id, person_id)
})
let post_report_view = context
.conn()
.await?
.interact(move |conn| PostReportView::read(conn, report.id, person_id))
.await??;
let res = PostReportResponse { post_report_view };
@ -116,30 +118,33 @@ impl Perform for ResolvePostReport {
let report_id = data.report_id;
let person_id = local_user_view.person.id;
let report = blocking(context.pool(), move |conn| {
PostReportView::read(conn, report_id, person_id)
})
let report = context
.conn()
.await?
.interact(move |conn| PostReportView::read(conn, report_id, person_id))
.await??;
let person_id = local_user_view.person.id;
is_mod_or_admin(context.pool(), person_id, report.community.id).await?;
let resolved = data.resolved;
let resolve_fun = move |conn: &'_ _| {
context
.conn()
.await?
.interact(move |conn| {
if resolved {
PostReport::resolve(conn, report_id, person_id)
} else {
PostReport::unresolve(conn, report_id, person_id)
}
};
blocking(context.pool(), resolve_fun)
})
.await?
.map_err(|e| ApiError::err("couldnt_resolve_report", e))?;
let post_report_view = blocking(context.pool(), move |conn| {
PostReportView::read(conn, report_id, person_id)
})
let post_report_view = context
.conn()
.await?
.interact(move |conn| PostReportView::read(conn, report_id, person_id))
.await??;
let res = PostReportResponse { post_report_view };
@ -177,7 +182,10 @@ impl Perform for ListPostReports {
let page = data.page;
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)
.community_id(community_id)
.unresolved_only(unresolved_only)

View file

@ -1,7 +1,6 @@
use crate::Perform;
use actix_web::web::Data;
use lemmy_api_common::{
blocking,
get_local_user_view_from_jwt,
person::{MarkPrivateMessageAsRead, PrivateMessageResponse},
};
@ -24,9 +23,10 @@ impl Perform for MarkPrivateMessageAsRead {
// Checking permissions
let private_message_id = data.private_message_id;
let orig_private_message = blocking(context.pool(), move |conn| {
PrivateMessage::read(conn, private_message_id)
})
let orig_private_message = context
.conn()
.await?
.interact(move |conn| PrivateMessage::read(conn, private_message_id))
.await??;
if local_user_view.person.id != orig_private_message.recipient_id {
return Err(ApiError::err_plain("couldnt_update_private_message").into());
@ -35,9 +35,10 @@ impl Perform for MarkPrivateMessageAsRead {
// Doing the update
let private_message_id = data.private_message_id;
let read = data.read;
blocking(context.pool(), move |conn| {
PrivateMessage::update_read(conn, private_message_id, read)
})
context
.conn()
.await?
.interact(move |conn| PrivateMessage::update_read(conn, private_message_id, read))
.await?
.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 diesel::NotFound;
use lemmy_api_common::{
blocking,
build_federated_instances,
get_local_user_view_from_jwt,
get_local_user_view_from_jwt_opt,
@ -71,44 +70,62 @@ impl Perform for GetModlog {
let mod_person_id = data.mod_person_id;
let page = data.page;
let limit = data.limit;
let removed_posts = blocking(context.pool(), move |conn| {
ModRemovePostView::list(conn, community_id, mod_person_id, page, limit)
})
let removed_posts = context
.conn()
.await?
.interact(move |conn| ModRemovePostView::list(conn, community_id, mod_person_id, page, limit))
.await??;
let locked_posts = blocking(context.pool(), move |conn| {
ModLockPostView::list(conn, community_id, mod_person_id, page, limit)
})
let locked_posts = context
.conn()
.await?
.interact(move |conn| ModLockPostView::list(conn, community_id, mod_person_id, page, limit))
.await??;
let stickied_posts = blocking(context.pool(), move |conn| {
ModStickyPostView::list(conn, community_id, mod_person_id, page, limit)
})
let stickied_posts = context
.conn()
.await?
.interact(move |conn| ModStickyPostView::list(conn, community_id, mod_person_id, page, limit))
.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)
})
.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)
})
.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)
})
.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)
})
.await??;
// 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() {
blocking(context.pool(), move |conn| {
context
.conn()
.await?
.interact(move |conn| {
Ok((
ModRemoveCommunityView::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;
match search_type {
SearchType::Posts => {
posts = blocking(context.pool(), move |conn| {
posts = context
.conn()
.await?
.interact(move |conn| {
PostQueryBuilder::create(conn)
.sort(sort)
.show_nsfw(show_nsfw)
@ -203,7 +223,10 @@ impl Perform for Search {
.await??;
}
SearchType::Comments => {
comments = blocking(context.pool(), move |conn| {
comments = context
.conn()
.await?
.interact(move |conn| {
CommentQueryBuilder::create(conn)
.sort(sort)
.listing_type(listing_type)
@ -220,7 +243,10 @@ impl Perform for Search {
.await??;
}
SearchType::Communities => {
communities = blocking(context.pool(), move |conn| {
communities = context
.conn()
.await?
.interact(move |conn| {
CommunityQueryBuilder::create(conn)
.sort(sort)
.listing_type(listing_type)
@ -233,7 +259,10 @@ impl Perform for Search {
.await??;
}
SearchType::Users => {
users = blocking(context.pool(), move |conn| {
users = context
.conn()
.await?
.interact(move |conn| {
PersonQueryBuilder::create(conn)
.sort(sort)
.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();
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)
.sort(sort)
.show_nsfw(show_nsfw)
@ -270,7 +302,10 @@ impl Perform for Search {
let q = data.q.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)
.sort(sort)
.listing_type(listing_type)
@ -291,7 +326,10 @@ impl Perform for Search {
communities = if community_or_creator_included {
vec![]
} else {
blocking(context.pool(), move |conn| {
context
.conn()
.await?
.interact(move |conn| {
CommunityQueryBuilder::create(conn)
.sort(sort)
.listing_type(listing_type)
@ -309,7 +347,10 @@ impl Perform for Search {
users = if community_or_creator_included {
vec![]
} else {
blocking(context.pool(), move |conn| {
context
.conn()
.await?
.interact(move |conn| {
PersonQueryBuilder::create(conn)
.sort(sort)
.search_term(q)
@ -321,7 +362,10 @@ impl Perform for Search {
};
}
SearchType::Url => {
posts = blocking(context.pool(), move |conn| {
posts = context
.conn()
.await?
.interact(move |conn| {
PostQueryBuilder::create(conn)
.sort(sort)
.show_nsfw(show_nsfw)
@ -409,23 +453,39 @@ async fn convert_response(
person: None,
};
use SearchableObjects::*;
let conn = pool.get().await?;
match object {
Person(p) => {
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) => {
removed_or_deleted = c.deleted || c.removed;
res.community =
Some(blocking(pool, move |conn| CommunityView::read(conn, c.id, user_id)).await??)
res.community = Some(
conn
.interact(move |conn| CommunityView::read(conn, c.id, user_id))
.await??,
)
}
Post(p) => {
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) => {
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
@ -450,7 +510,11 @@ impl Perform for TransferSite {
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
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 transfer_site = move |conn: &'_ _| Site::transfer(conn, new_creator_id);
blocking(context.pool(), transfer_site)
context
.conn()
.await?
.interact(move |conn| Site::transfer(conn, new_creator_id))
.await?
.map_err(|e| ApiError::err("couldnt_update_site", e))?;
@ -470,11 +536,23 @@ impl Perform for TransferSite {
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
.iter()
.position(|r| r.person.id == site_view.creator.id)
@ -482,7 +560,11 @@ impl Perform for TransferSite {
let creator_person = admins.remove(creator_index);
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(
context.pool(),
&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 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(
pool: &DbPool,
person_id: PersonId,
community_id: CommunityId,
) -> Result<(), LemmyError> {
let is_mod_or_admin = blocking(pool, move |conn| {
CommunityView::is_mod_or_admin(conn, person_id, community_id)
})
let is_mod_or_admin = pool
.get()
.await?
.interact(move |conn| CommunityView::is_mod_or_admin(conn, person_id, community_id))
.await?;
if !is_mod_or_admin {
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> {
blocking(pool, move |conn| Post::read(conn, post_id))
pool
.get()
.await?
.interact(move |conn| Post::read(conn, post_id))
.await?
.map_err(|_| ApiError::err_plain("couldnt_find_post").into())
}
@ -77,9 +65,10 @@ pub async fn mark_post_as_read(
) -> Result<PostRead, LemmyError> {
let post_read_form = PostReadForm { post_id, person_id };
blocking(pool, move |conn| {
PostRead::mark_as_read(conn, &post_read_form)
})
pool
.get()
.await?
.interact(move |conn| PostRead::mark_as_read(conn, &post_read_form))
.await?
.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))?
.claims;
let local_user_id = LocalUserId(claims.sub);
let local_user_view =
blocking(pool, move |conn| LocalUserView::read(conn, local_user_id)).await??;
let local_user_view = pool
.get()
.await?
.interact(move |conn| LocalUserView::read(conn, local_user_id))
.await??;
// Check for a site ban
if local_user_view.person.banned {
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))?
.claims;
let local_user_id = LocalUserId(claims.sub);
let local_user_view = blocking(pool, move |conn| {
LocalUserSettingsView::read(conn, local_user_id)
})
let local_user_view = pool
.get()
.await?
.interact(move |conn| LocalUserSettingsView::read(conn, local_user_id))
.await??;
// Check for a site ban
if local_user_view.person.banned {
@ -175,9 +168,12 @@ pub async fn check_community_ban(
community_id: CommunityId,
pool: &DbPool,
) -> Result<(), LemmyError> {
let is_banned =
move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
if blocking(pool, is_banned).await? {
if pool
.get()
.await?
.interact(move |conn| CommunityPersonBanView::get(conn, person_id, community_id).is_ok())
.await?
{
Err(ApiError::err_plain("community_ban").into())
} else {
Ok(())
@ -188,7 +184,10 @@ pub async fn check_community_deleted_or_removed(
community_id: CommunityId,
pool: &DbPool,
) -> 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?
.map_err(|e| ApiError::err("couldnt_find_community", e))?;
if community.deleted || community.removed {
@ -211,8 +210,12 @@ pub async fn check_person_block(
potential_blocker_id: PersonId,
pool: &DbPool,
) -> Result<(), LemmyError> {
let is_blocked = move |conn: &'_ _| PersonBlock::read(conn, potential_blocker_id, my_id).is_ok();
if blocking(pool, is_blocked).await? {
if pool
.get()
.await?
.interact(move |conn| PersonBlock::read(conn, potential_blocker_id, my_id).is_ok())
.await?
{
Err(ApiError::err_plain("person_block").into())
} else {
Ok(())
@ -221,7 +224,11 @@ pub async fn check_person_block(
pub async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> {
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 {
return Err(ApiError::err_plain("downvotes_disabled").into());
}
@ -236,9 +243,10 @@ pub async fn build_federated_instances(
) -> Result<Option<FederatedInstances>, LemmyError> {
let federation = federation_config.to_owned();
if federation.enabled {
let distinct_communities = blocking(pool, move |conn| {
Community::distinct_federated_communities(conn)
})
let distinct_communities = pool
.get()
.await?
.interact(move |conn| Community::distinct_federated_communities(conn))
.await??;
let allowed = federation.allowed_instances;

View file

@ -1,7 +1,6 @@
use crate::PerformCrud;
use actix_web::web::Data;
use lemmy_api_common::{
blocking,
check_community_ban,
check_community_deleted_or_removed,
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 let Some(parent_id) = data.parent_id {
// 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?
.map_err(|e| ApiError::err("couldnt_create_comment", e))?;
@ -98,9 +100,10 @@ impl PerformCrud for CreateComment {
// Create the comment
let comment_form2 = comment_form.clone();
let inserted_comment = blocking(context.pool(), move |conn| {
Comment::create(conn, &comment_form2)
})
let inserted_comment = context
.conn()
.await?
.interact(move |conn| Comment::create(conn, &comment_form2))
.await?
.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 protocol_and_hostname = context.settings().get_protocol_and_hostname();
let updated_comment: Comment =
blocking(context.pool(), move |conn| -> Result<Comment, LemmyError> {
let updated_comment: Comment = context
.conn()
.await?
.interact(move |conn| -> Result<Comment, LemmyError> {
let apub_id = generate_local_apub_endpoint(
EndpointType::Comment,
&inserted_comment_id.to_string(),
@ -141,8 +146,10 @@ impl PerformCrud for CreateComment {
score: 1,
};
let like = move |conn: &'_ _| CommentLike::like(conn, &like_form);
blocking(context.pool(), like)
context
.conn()
.await?
.interact(move |conn| CommentLike::like(conn, &like_form))
.await?
.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 comment_id = inserted_comment.id;
let comment_view = blocking(context.pool(), move |conn| {
CommentView::read(conn, comment_id, Some(person_id))
})
let comment_view = context
.conn()
.await?
.interact(move |conn| CommentView::read(conn, comment_id, Some(person_id)))
.await??;
// If its a comment to yourself, mark it as read
if local_user_view.person.id == comment_view.get_recipient_id() {
let comment_id = inserted_comment.id;
blocking(context.pool(), move |conn| {
Comment::update_read(conn, comment_id, true)
})
context
.conn()
.await?
.interact(move |conn| Comment::update_read(conn, comment_id, true))
.await?
.map_err(|e| ApiError::err("couldnt_update_comment", e))?;
}
// If its a reply, mark the parent as read
if let Some(parent_id) = data.parent_id {
let parent_comment = blocking(context.pool(), move |conn| {
CommentView::read(conn, parent_id, Some(person_id))
})
let parent_comment = context
.conn()
.await?
.interact(move |conn| CommentView::read(conn, parent_id, Some(person_id)))
.await??;
if local_user_view.person.id == parent_comment.get_recipient_id() {
blocking(context.pool(), move |conn| {
Comment::update_read(conn, parent_id, true)
})
context
.conn()
.await?
.interact(move |conn| Comment::update_read(conn, parent_id, true))
.await?
.map_err(|e| ApiError::err("couldnt_update_parent_comment", e))?;
}
// If the parent has PersonMentions mark them as read too
let person_id = local_user_view.person.id;
let person_mention = blocking(context.pool(), move |conn| {
PersonMention::read_by_comment_and_person(conn, parent_id, person_id)
})
let person_mention = context
.conn()
.await?
.interact(move |conn| PersonMention::read_by_comment_and_person(conn, parent_id, person_id))
.await?;
if let Ok(mention) = person_mention {
blocking(context.pool(), move |conn| {
PersonMention::update_read(conn, mention.id, true)
})
context
.conn()
.await?
.interact(move |conn| PersonMention::update_read(conn, mention.id, true))
.await?
.map_err(|e| ApiError::err("couldnt_update_person_mentions", e))?;
}

View file

@ -1,7 +1,6 @@
use crate::PerformCrud;
use actix_web::web::Data;
use lemmy_api_common::{
blocking,
check_community_ban,
comment::*,
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?;
let comment_id = data.comment_id;
let orig_comment = blocking(context.pool(), move |conn| {
CommentView::read(conn, comment_id, None)
})
let orig_comment = context
.conn()
.await?
.interact(move |conn| CommentView::read(conn, comment_id, None))
.await??;
// Dont delete it if its already been deleted.
@ -63,16 +63,18 @@ impl PerformCrud for DeleteComment {
// Do the delete
let deleted = data.deleted;
let updated_comment = blocking(context.pool(), move |conn| {
Comment::update_deleted(conn, comment_id, deleted)
})
let updated_comment = context
.conn()
.await?
.interact(move |conn| Comment::update_deleted(conn, comment_id, deleted))
.await?
.map_err(|e| ApiError::err("couldnt_update_comment", e))?;
// Send the apub message
let community = blocking(context.pool(), move |conn| {
Community::read(conn, orig_comment.post.community_id)
})
let community = context
.conn()
.await?
.interact(move |conn| Community::read(conn, orig_comment.post.community_id))
.await??;
send_apub_delete(
&local_user_view.person.clone().into(),
@ -84,7 +86,11 @@ impl PerformCrud for DeleteComment {
.await?;
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(
vec![],
&updated_comment,
@ -122,9 +128,10 @@ impl PerformCrud for RemoveComment {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let comment_id = data.comment_id;
let orig_comment = blocking(context.pool(), move |conn| {
CommentView::read(conn, comment_id, None)
})
let orig_comment = context
.conn()
.await?
.interact(move |conn| CommentView::read(conn, comment_id, None))
.await??;
check_community_ban(
@ -144,9 +151,10 @@ impl PerformCrud for RemoveComment {
// Do the remove
let removed = data.removed;
let updated_comment = blocking(context.pool(), move |conn| {
Comment::update_removed(conn, comment_id, removed)
})
let updated_comment = context
.conn()
.await?
.interact(move |conn| Comment::update_removed(conn, comment_id, removed))
.await?
.map_err(|e| ApiError::err("couldnt_update_comment", e))?;
@ -157,15 +165,17 @@ impl PerformCrud for RemoveComment {
removed: Some(removed),
reason: data.reason.to_owned(),
};
blocking(context.pool(), move |conn| {
ModRemoveComment::create(conn, &form)
})
context
.conn()
.await?
.interact(move |conn| ModRemoveComment::create(conn, &form))
.await??;
// Send the apub message
let community = blocking(context.pool(), move |conn| {
Community::read(conn, orig_comment.post.community_id)
})
let community = context
.conn()
.await?
.interact(move |conn| Community::read(conn, orig_comment.post.community_id))
.await??;
send_apub_remove(
&local_user_view.person.clone().into(),
@ -178,7 +188,11 @@ impl PerformCrud for RemoveComment {
.await?;
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(
vec![],
&updated_comment,

View file

@ -1,6 +1,6 @@
use crate::PerformCrud;
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_lib::webfinger::WebfingerType;
use lemmy_db_schema::{
@ -45,7 +45,10 @@ impl PerformCrud for GetComments {
let saved_only = data.saved_only;
let page = data.page;
let limit = data.limit;
let mut comments = blocking(context.pool(), move |conn| {
let mut comments = context
.conn()
.await?
.interact(move |conn| {
CommentQueryBuilder::create(conn)
.listing_type(listing_type)
.sort(sort)

View file

@ -1,7 +1,6 @@
use actix_web::web::Data;
use lemmy_api_common::{
blocking,
check_community_ban,
check_community_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?;
let comment_id = data.comment_id;
let orig_comment = blocking(context.pool(), move |conn| {
CommentView::read(conn, comment_id, None)
})
let orig_comment = context
.conn()
.await?
.interact(move |conn| CommentView::read(conn, comment_id, None))
.await??;
// 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 =
remove_slurs(&data.content.to_owned(), &context.settings().slur_regex());
let comment_id = data.comment_id;
let updated_comment = blocking(context.pool(), move |conn| {
Comment::update_content(conn, comment_id, &content_slurs_removed)
})
let updated_comment = context
.conn()
.await?
.interact(move |conn| Comment::update_content(conn, comment_id, &content_slurs_removed))
.await?
.map_err(|e| ApiError::err("couldnt_update_comment", e))?;

View file

@ -1,7 +1,6 @@
use crate::PerformCrud;
use actix_web::web::Data;
use lemmy_api_common::{
blocking,
community::{CommunityResponse, CreateCommunity},
get_local_user_view_from_jwt,
is_admin,
@ -53,7 +52,11 @@ impl PerformCrud for CreateCommunity {
let local_user_view =
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() {
return Err(ApiError::err_plain("only_admins_can_create_communities").into());
}
@ -101,9 +104,10 @@ impl PerformCrud for CreateCommunity {
..CommunityForm::default()
};
let inserted_community = blocking(context.pool(), move |conn| {
Community::create(conn, &community_form)
})
let inserted_community = context
.conn()
.await?
.interact(move |conn| Community::create(conn, &community_form))
.await?
.map_err(|e| ApiError::err("community_already_exists", e))?;
@ -113,8 +117,13 @@ impl PerformCrud for CreateCommunity {
person_id: local_user_view.person.id,
};
let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form);
if blocking(context.pool(), join).await?.is_err() {
if context
.conn()
.await?
.interact(move |conn| CommunityModerator::join(conn, &community_moderator_form))
.await?
.is_err()
{
return Err(ApiError::err_plain("community_moderator_already_exists").into());
}
@ -125,15 +134,21 @@ impl PerformCrud for CreateCommunity {
pending: false,
};
let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form);
if blocking(context.pool(), follow).await?.is_err() {
if context
.conn()
.await?
.interact(move |conn| CommunityFollower::follow(conn, &community_follower_form))
.await?
.is_err()
{
return Err(ApiError::err_plain("community_follower_already_exists").into());
}
let person_id = local_user_view.person.id;
let community_view = blocking(context.pool(), move |conn| {
CommunityView::read(conn, inserted_community.id, Some(person_id))
})
let community_view = context
.conn()
.await?
.interact(move |conn| CommunityView::read(conn, inserted_community.id, Some(person_id)))
.await??;
Ok(CommunityResponse { community_view })

View file

@ -1,6 +1,6 @@
use crate::PerformCrud;
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_db_schema::{
source::{
@ -28,9 +28,10 @@ impl PerformCrud for DeleteCommunity {
// Fetch the community mods
let community_id = data.community_id;
let community_mods = blocking(context.pool(), move |conn| {
CommunityModeratorView::for_community(conn, community_id)
})
let community_mods = context
.conn()
.await?
.interact(move |conn| CommunityModeratorView::for_community(conn, community_id))
.await??;
// Make sure deleter is the top mod
@ -41,9 +42,10 @@ impl PerformCrud for DeleteCommunity {
// Do the delete
let community_id = data.community_id;
let deleted = data.deleted;
let updated_community = blocking(context.pool(), move |conn| {
Community::update_deleted(conn, community_id, deleted)
})
let updated_community = context
.conn()
.await?
.interact(move |conn| Community::update_deleted(conn, community_id, deleted))
.await?
.map_err(|e| ApiError::err("couldnt_update_community", e))?;
@ -87,9 +89,10 @@ impl PerformCrud for RemoveCommunity {
// Do the remove
let community_id = data.community_id;
let removed = data.removed;
let updated_community = blocking(context.pool(), move |conn| {
Community::update_removed(conn, community_id, removed)
})
let updated_community = context
.conn()
.await?
.interact(move |conn| Community::update_removed(conn, community_id, removed))
.await?
.map_err(|e| ApiError::err("couldnt_update_community", e))?;
@ -102,9 +105,10 @@ impl PerformCrud for RemoveCommunity {
reason: data.reason.to_owned(),
expires,
};
blocking(context.pool(), move |conn| {
ModRemoveCommunity::create(conn, &form)
})
context
.conn()
.await?
.interact(move |conn| ModRemoveCommunity::create(conn, &form))
.await??;
// Apub messages

View file

@ -1,6 +1,6 @@
use crate::PerformCrud;
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_lib::{object_id::ObjectId, webfinger::WebfingerType};
use lemmy_db_schema::{
@ -45,9 +45,10 @@ impl PerformCrud for GetCommunity {
}
};
let mut community_view = blocking(context.pool(), move |conn| {
CommunityView::read(conn, community_id, person_id)
})
let mut community_view = context
.conn()
.await?
.interact(move |conn| CommunityView::read(conn, community_id, person_id))
.await?
.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();
}
let moderators: Vec<CommunityModeratorView> = blocking(context.pool(), move |conn| {
CommunityModeratorView::for_community(conn, community_id)
})
let moderators: Vec<CommunityModeratorView> = context
.conn()
.await?
.interact(move |conn| CommunityModeratorView::for_community(conn, community_id))
.await?
.map_err(|e| ApiError::err("couldnt_find_community", e))?;
@ -106,7 +108,10 @@ impl PerformCrud for ListCommunities {
let page = data.page;
let limit = data.limit;
let mut communities = blocking(context.pool(), move |conn| {
let mut communities = context
.conn()
.await?
.interact(move |conn| {
CommunityQueryBuilder::create(conn)
.listing_type(listing_type)
.sort(sort)

View file

@ -1,7 +1,6 @@
use crate::PerformCrud;
use actix_web::web::Data;
use lemmy_api_common::{
blocking,
community::{CommunityResponse, EditCommunity},
get_local_user_view_from_jwt,
};
@ -35,7 +34,10 @@ impl PerformCrud for EditCommunity {
// Verify its a mod (only mods can edit it)
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)
.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 read_community = blocking(context.pool(), move |conn| {
Community::read(conn, community_id)
})
let read_community = context
.conn()
.await?
.interact(move |conn| Community::read(conn, community_id))
.await??;
let icon = diesel_option_overwrite_to_url(&data.icon)?;
@ -65,9 +68,10 @@ impl PerformCrud for EditCommunity {
};
let community_id = data.community_id;
let updated_community = blocking(context.pool(), move |conn| {
Community::update(conn, community_id, &community_form)
})
let updated_community = context
.conn()
.await?
.interact(move |conn| Community::update(conn, community_id, &community_form))
.await?
.map_err(|e| ApiError::err("couldnt_update_community", e))?;

View file

@ -1,7 +1,6 @@
use crate::PerformCrud;
use actix_web::web::Data;
use lemmy_api_common::{
blocking,
check_community_ban,
check_community_deleted_or_removed,
get_local_user_view_from_jwt,
@ -83,8 +82,12 @@ impl PerformCrud for CreatePost {
..PostForm::default()
};
let inserted_post =
match blocking(context.pool(), move |conn| Post::create(conn, &post_form)).await? {
let inserted_post = match context
.conn()
.await?
.interact(move |conn| Post::create(conn, &post_form))
.await?
{
Ok(post) => post,
Err(e) => {
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 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(
EndpointType::Post,
&inserted_post_id.to_string(),
@ -119,8 +125,13 @@ impl PerformCrud for CreatePost {
score: 1,
};
let like = move |conn: &'_ _| PostLike::like(conn, &like_form);
if blocking(context.pool(), like).await?.is_err() {
if context
.conn()
.await?
.interact(move |conn| PostLike::like(conn, &like_form))
.await?
.is_err()
{
return Err(ApiError::err_plain("couldnt_like_post").into());
}

View file

@ -1,7 +1,6 @@
use crate::PerformCrud;
use actix_web::web::Data;
use lemmy_api_common::{
blocking,
check_community_ban,
check_community_deleted_or_removed,
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?;
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.
if orig_post.deleted == data.deleted {
@ -57,15 +60,17 @@ impl PerformCrud for DeletePost {
// Update the post
let post_id = data.post_id;
let deleted = data.deleted;
let updated_post = blocking(context.pool(), move |conn| {
Post::update_deleted(conn, post_id, deleted)
})
let updated_post = context
.conn()
.await?
.interact(move |conn| Post::update_deleted(conn, post_id, deleted))
.await??;
// apub updates
let community = blocking(context.pool(), move |conn| {
Community::read(conn, orig_post.community_id)
})
let community = context
.conn()
.await?
.interact(move |conn| Community::read(conn, orig_post.community_id))
.await??;
send_apub_delete(
&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?;
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(
local_user_view.person.id,
@ -121,9 +130,10 @@ impl PerformCrud for RemovePost {
// Update the post
let post_id = data.post_id;
let removed = data.removed;
let updated_post = blocking(context.pool(), move |conn| {
Post::update_removed(conn, post_id, removed)
})
let updated_post = context
.conn()
.await?
.interact(move |conn| Post::update_removed(conn, post_id, removed))
.await??;
// Mod tables
@ -133,15 +143,17 @@ impl PerformCrud for RemovePost {
removed: Some(removed),
reason: data.reason.to_owned(),
};
blocking(context.pool(), move |conn| {
ModRemovePost::create(conn, &form)
})
context
.conn()
.await?
.interact(move |conn| ModRemovePost::create(conn, &form))
.await??;
// apub updates
let community = blocking(context.pool(), move |conn| {
Community::read(conn, orig_post.community_id)
})
let community = context
.conn()
.await?
.interact(move |conn| Community::read(conn, orig_post.community_id))
.await??;
send_apub_remove(
&local_user_view.person.clone().into(),

View file

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

View file

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

View file

@ -1,7 +1,6 @@
use crate::PerformCrud;
use actix_web::web::Data;
use lemmy_api_common::{
blocking,
check_person_block,
get_local_user_view_from_jwt,
person::{CreatePrivateMessage, PrivateMessageResponse},
@ -51,9 +50,10 @@ impl PerformCrud for CreatePrivateMessage {
..PrivateMessageForm::default()
};
let inserted_private_message = match blocking(context.pool(), move |conn| {
PrivateMessage::create(conn, &private_message_form)
})
let inserted_private_message = match context
.conn()
.await?
.interact(move |conn| PrivateMessage::create(conn, &private_message_form))
.await?
{
Ok(private_message) => private_message,
@ -64,9 +64,10 @@ impl PerformCrud for CreatePrivateMessage {
let inserted_private_message_id = inserted_private_message.id;
let protocol_and_hostname = context.settings().get_protocol_and_hostname();
let updated_private_message = blocking(
context.pool(),
move |conn| -> Result<PrivateMessage, LemmyError> {
let updated_private_message = context
.conn()
.await?
.interact(move |conn| -> Result<PrivateMessage, LemmyError> {
let apub_id = generate_local_apub_endpoint(
EndpointType::PrivateMessage,
&inserted_private_message_id.to_string(),
@ -77,8 +78,7 @@ impl PerformCrud for CreatePrivateMessage {
inserted_private_message_id,
apub_id,
)?)
},
)
})
.await?
.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
if res.private_message_view.recipient.local {
let recipient_id = data.recipient_id;
let local_recipient = blocking(context.pool(), move |conn| {
LocalUserView::read_person(conn, recipient_id)
})
let local_recipient = context
.conn()
.await?
.interact(move |conn| LocalUserView::read_person(conn, recipient_id))
.await??;
send_email_to_user(
&local_recipient,

View file

@ -1,7 +1,6 @@
use crate::PerformCrud;
use actix_web::web::Data;
use lemmy_api_common::{
blocking,
get_local_user_view_from_jwt,
person::{DeletePrivateMessage, PrivateMessageResponse},
};
@ -31,9 +30,10 @@ impl PerformCrud for DeletePrivateMessage {
// Checking permissions
let private_message_id = data.private_message_id;
let orig_private_message = blocking(context.pool(), move |conn| {
PrivateMessage::read(conn, private_message_id)
})
let orig_private_message = context
.conn()
.await?
.interact(move |conn| PrivateMessage::read(conn, private_message_id))
.await??;
if local_user_view.person.id != orig_private_message.creator_id {
return Err(ApiError::err_plain("no_private_message_edit_allowed").into());
@ -42,9 +42,10 @@ impl PerformCrud for DeletePrivateMessage {
// Doing the update
let private_message_id = data.private_message_id;
let deleted = data.deleted;
let updated_private_message = blocking(context.pool(), move |conn| {
PrivateMessage::update_deleted(conn, private_message_id, deleted)
})
let updated_private_message = context
.conn()
.await?
.interact(move |conn| PrivateMessage::update_deleted(conn, private_message_id, deleted))
.await?
.map_err(|e| ApiError::err("couldnt_update_private_message", e))?;

View file

@ -1,7 +1,6 @@
use crate::PerformCrud;
use actix_web::web::Data;
use lemmy_api_common::{
blocking,
get_local_user_view_from_jwt,
person::{GetPrivateMessages, PrivateMessagesResponse},
};
@ -27,7 +26,10 @@ impl PerformCrud for GetPrivateMessages {
let page = data.page;
let limit = data.limit;
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)
.page(page)
.limit(limit)

View file

@ -1,7 +1,6 @@
use crate::PerformCrud;
use actix_web::web::Data;
use lemmy_api_common::{
blocking,
get_local_user_view_from_jwt,
person::{EditPrivateMessage, PrivateMessageResponse},
};
@ -28,9 +27,10 @@ impl PerformCrud for EditPrivateMessage {
// Checking permissions
let private_message_id = data.private_message_id;
let orig_private_message = blocking(context.pool(), move |conn| {
PrivateMessage::read(conn, private_message_id)
})
let orig_private_message = context
.conn()
.await?
.interact(move |conn| PrivateMessage::read(conn, private_message_id))
.await??;
if local_user_view.person.id != orig_private_message.creator_id {
return Err(ApiError::err_plain("no_private_message_edit_allowed").into());
@ -39,7 +39,10 @@ impl PerformCrud for EditPrivateMessage {
// Doing the update
let content_slurs_removed = remove_slurs(&data.content, &context.settings().slur_regex());
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)
})
.await?

View file

@ -1,7 +1,6 @@
use crate::PerformCrud;
use actix_web::web::Data;
use lemmy_api_common::{
blocking,
get_local_user_view_from_jwt,
is_admin,
site::*,
@ -33,8 +32,13 @@ impl PerformCrud for CreateSite {
) -> Result<SiteResponse, LemmyError> {
let data: &CreateSite = self;
let read_site = Site::read_simple;
if blocking(context.pool(), read_site).await?.is_ok() {
if context
.conn()
.await?
.interact(|conn| Site::read_simple(conn))
.await?
.is_ok()
{
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,
};
let create_site = move |conn: &'_ _| Site::create(conn, &site_form);
if blocking(context.pool(), create_site).await?.is_err() {
if context
.conn()
.await?
.interact(move |conn| Site::create(conn, &site_form))
.await?
.is_err()
{
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 })
}

View file

@ -1,7 +1,6 @@
use crate::PerformCrud;
use actix_web::web::Data;
use lemmy_api_common::{
blocking,
build_federated_instances,
get_local_user_settings_view_from_jwt_opt,
person::Register,
@ -30,7 +29,12 @@ impl PerformCrud for GetSite {
) -> Result<GetSiteResponse, LemmyError> {
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),
// If the site isn't created yet, check the setup
Err(_) => {
@ -62,14 +66,24 @@ impl PerformCrud for GetSite {
};
create_site.perform(context, websocket_id).await?;
info!("Site {} created", setup.site_name);
Some(blocking(context.pool(), SiteView::read).await??)
Some(
context
.conn()
.await?
.interact(|conn| SiteView::read(conn))
.await??,
)
} else {
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
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
.chat_server()
@ -96,29 +114,33 @@ impl PerformCrud for GetSite {
.await?
{
let person_id = local_user_view.person.id;
let follows = blocking(context.pool(), move |conn| {
CommunityFollowerView::for_person(conn, person_id)
})
let follows = context
.conn()
.await?
.interact(move |conn| CommunityFollowerView::for_person(conn, person_id))
.await?
.map_err(|e| ApiError::err("system_err_login", e))?;
let person_id = local_user_view.person.id;
let community_blocks = blocking(context.pool(), move |conn| {
CommunityBlockView::for_person(conn, person_id)
})
let community_blocks = context
.conn()
.await?
.interact(move |conn| CommunityBlockView::for_person(conn, person_id))
.await?
.map_err(|e| ApiError::err("system_err_login", e))?;
let person_id = local_user_view.person.id;
let person_blocks = blocking(context.pool(), move |conn| {
PersonBlockView::for_person(conn, person_id)
})
let person_blocks = context
.conn()
.await?
.interact(move |conn| PersonBlockView::for_person(conn, person_id))
.await?
.map_err(|e| ApiError::err("system_err_login", e))?;
let moderates = blocking(context.pool(), move |conn| {
CommunityModeratorView::for_person(conn, person_id)
})
let moderates = context
.conn()
.await?
.interact(move |conn| CommunityModeratorView::for_person(conn, person_id))
.await?
.map_err(|e| ApiError::err("system_err_login", e))?;

View file

@ -1,7 +1,6 @@
use crate::PerformCrud;
use actix_web::web::Data;
use lemmy_api_common::{
blocking,
get_local_user_view_from_jwt,
is_admin,
site::{EditSite, SiteResponse},
@ -36,7 +35,11 @@ impl PerformCrud for EditSite {
// Make sure user is an admin
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 description = diesel_option_overwrite(&data.description);
@ -61,12 +64,18 @@ impl PerformCrud for EditSite {
community_creation_admin_only: data.community_creation_admin_only,
};
let update_site = move |conn: &'_ _| Site::update(conn, 1, &site_form);
blocking(context.pool(), update_site)
context
.conn()
.await?
.interact(move |conn| Site::update(conn, 1, &site_form))
.await?
.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 };

View file

@ -1,6 +1,6 @@
use crate::PerformCrud;
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::{
generate_followers_url,
generate_inbox_url,
@ -50,7 +50,12 @@ impl PerformCrud for Register {
let data: &Register = self;
// 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 {
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
let no_admins = blocking(context.pool(), move |conn| {
PersonViewSafe::admins(conn).map(|a| a.is_empty())
})
let no_admins = context
.conn()
.await?
.interact(move |conn| PersonViewSafe::admins(conn).map(|a| a.is_empty()))
.await??;
// If its not the admin, check the captcha
@ -117,9 +123,10 @@ impl PerformCrud for Register {
};
// insert the person
let inserted_person = blocking(context.pool(), move |conn| {
Person::create(conn, &person_form)
})
let inserted_person = context
.conn()
.await?
.interact(move |conn| Person::create(conn, &person_form))
.await?
.map_err(|e| ApiError::err("user_already_exists", e))?;
@ -142,9 +149,10 @@ impl PerformCrud for Register {
send_notifications_to_email: Some(false),
};
let inserted_local_user = match blocking(context.pool(), move |conn| {
LocalUser::register(conn, &local_user_form)
})
let inserted_local_user = match context
.conn()
.await?
.interact(move |conn| LocalUser::register(conn, &local_user_form))
.await?
{
Ok(lu) => lu,
@ -158,9 +166,10 @@ impl PerformCrud for Register {
};
// If the local user creation errored, then delete that person
blocking(context.pool(), move |conn| {
Person::delete(conn, inserted_person.id)
})
context
.conn()
.await?
.interact(move |conn| Person::delete(conn, inserted_person.id))
.await??;
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
let protocol_and_hostname = context.settings().get_protocol_and_hostname();
let main_community = match blocking(context.pool(), move |conn| {
Community::read(conn, CommunityId(2))
})
let main_community = match context
.conn()
.await?
.interact(move |conn| Community::read(conn, CommunityId(2)))
.await?
{
Ok(c) => c,
@ -196,9 +206,10 @@ impl PerformCrud for Register {
shared_inbox_url: Some(Some(generate_shared_inbox_url(&actor_id)?)),
..CommunityForm::default()
};
blocking(context.pool(), move |conn| {
Community::create(conn, &community_form)
})
context
.conn()
.await?
.interact(move |conn| Community::create(conn, &community_form))
.await??
}
};
@ -210,8 +221,10 @@ impl PerformCrud for Register {
pending: false,
};
let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form);
blocking(context.pool(), follow)
context
.conn()
.await?
.interact(move |conn| CommunityFollower::follow(conn, &community_follower_form))
.await?
.map_err(|e| ApiError::err("community_follower_already_exists", e))?;
@ -222,8 +235,10 @@ impl PerformCrud for Register {
person_id: inserted_person.id,
};
let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form);
blocking(context.pool(), join)
context
.conn()
.await?
.interact(move |conn| CommunityModerator::join(conn, &community_moderator_form))
.await?
.map_err(|e| ApiError::err("community_moderator_already_exists", e))?;
}

View file

@ -1,7 +1,7 @@
use crate::PerformCrud;
use actix_web::web::Data;
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_utils::{ApiError, ConnectionId, LemmyError};
use lemmy_websocket::LemmyContext;
@ -31,20 +31,25 @@ impl PerformCrud for DeleteAccount {
// Comments
let person_id = local_user_view.person.id;
let permadelete = move |conn: &'_ _| Comment::permadelete_for_creator(conn, person_id);
blocking(context.pool(), permadelete)
context
.conn()
.await?
.interact(move |conn| Comment::permadelete_for_creator(conn, person_id))
.await?
.map_err(|e| ApiError::err("couldnt_update_comment", e))?;
// Posts
let permadelete = move |conn: &'_ _| Post::permadelete_for_creator(conn, person_id);
blocking(context.pool(), permadelete)
context
.conn()
.await?
.interact(move |conn| Post::permadelete_for_creator(conn, person_id))
.await?
.map_err(|e| ApiError::err("couldnt_update_post", e))?;
blocking(context.pool(), move |conn| {
Person::delete_account(conn, person_id)
})
context
.conn()
.await?
.interact(move |conn| Person::delete_account(conn, person_id))
.await??;
Ok(LoginResponse {

View file

@ -1,6 +1,6 @@
use crate::PerformCrud;
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_lib::{object_id::ObjectId, webfinger::WebfingerType};
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
// `my_user`
let person_view = blocking(context.pool(), move |conn| {
PersonViewSafe::read(conn, person_details_id)
})
let person_view = context
.conn()
.await?
.interact(move |conn| PersonViewSafe::read(conn, person_details_id))
.await??;
let page = data.page;
@ -67,7 +68,10 @@ impl PerformCrud for GetPersonDetails {
let saved_only = data.saved_only;
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)
.sort(sort)
.show_nsfw(show_nsfw)
@ -102,9 +106,10 @@ impl PerformCrud for GetPersonDetails {
})
.await??;
let moderates = blocking(context.pool(), move |conn| {
CommunityModeratorView::for_person(conn, person_details_id)
})
let moderates = context
.conn()
.await?
.interact(move |conn| CommunityModeratorView::for_person(conn, person_details_id))
.await??;
// Return the jwt

View file

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

View file

@ -13,7 +13,7 @@ use crate::{
protocol::activities::{create_or_update::comment::CreateOrUpdateComment, CreateOrUpdateType},
};
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::{
data::Data,
object_id::ObjectId,
@ -36,11 +36,16 @@ impl CreateOrUpdateComment {
) -> Result<(), LemmyError> {
// TODO: might be helpful to add a comment method to retrieve community directly
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: ApubCommunity = blocking(context.pool(), move |conn| {
Community::read(conn, community_id)
})
let community: ApubCommunity = context
.conn()
.await?
.interact(move |conn| Community::read(conn, community_id))
.await??
.into();
@ -116,9 +121,10 @@ impl GetCommunity for CreateOrUpdateComment {
request_counter: &mut i32,
) -> Result<ApubCommunity, LemmyError> {
let post = self.object.get_parents(context, request_counter).await?.0;
let community = blocking(context.pool(), move |conn| {
Community::read(conn, post.community_id)
})
let community = context
.conn()
.await?
.interact(move |conn| Community::read(conn, post.community_id))
.await??;
Ok(community.into())
}

View file

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

View file

@ -14,7 +14,6 @@ use crate::{
protocol::activities::community::add_mod::AddMod,
};
use activitystreams::{activity::kind::AddType, public};
use lemmy_api_common::blocking;
use lemmy_apub_lib::{
data::Data,
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
// been added. Skip it here as it would result in a duplicate key error.
let new_mod_id = new_mod.id;
let moderated_communities = blocking(context.pool(), move |conn| {
CommunityModerator::get_person_moderated_communities(conn, new_mod_id)
})
let moderated_communities = context
.conn()
.await?
.interact(move |conn| CommunityModerator::get_person_moderated_communities(conn, new_mod_id))
.await??;
if !moderated_communities.contains(&community.id) {
let form = CommunityModeratorForm {
community_id: community.id,
person_id: new_mod.id,
};
blocking(context.pool(), move |conn| {
CommunityModerator::join(conn, &form)
})
context
.conn()
.await?
.interact(move |conn| CommunityModerator::join(conn, &form))
.await??;
}
// 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_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(());
}
insert_activity(

View file

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

View file

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

View file

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

View file

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

View file

@ -12,7 +12,6 @@ use crate::{
protocol::activities::community::update::UpdateCommunity,
};
use activitystreams::{activity::kind::UpdateType, public};
use lemmy_api_common::blocking;
use lemmy_apub_lib::{
data::Data,
object_id::ObjectId,
@ -91,9 +90,10 @@ impl ActivityHandler for UpdateCommunity {
banner: updated_community.banner,
..CommunityForm::default()
};
let updated_community = blocking(context.pool(), move |conn| {
Community::update(conn, community.id, &cf)
})
let updated_community = context
.conn()
.await?
.interact(move |conn| Community::update(conn, community.id, &cf))
.await??;
send_community_ws_message(

View file

@ -12,7 +12,6 @@ use crate::{
};
use activitystreams::{activity::kind::DeleteType, public};
use anyhow::anyhow;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{
data::Data,
object_id::ObjectId,
@ -143,13 +142,15 @@ pub(in crate::activities) async fn receive_remove_action(
reason,
expires: None,
};
blocking(context.pool(), move |conn| {
ModRemoveCommunity::create(conn, &form)
})
context
.conn()
.await?
.interact(move |conn| ModRemoveCommunity::create(conn, &form))
.await??;
let deleted_community = blocking(context.pool(), move |conn| {
Community::update_removed(conn, community.id, true)
})
let deleted_community = context
.conn()
.await?
.interact(move |conn| Community::update_removed(conn, community.id, true))
.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),
reason,
};
blocking(context.pool(), move |conn| {
ModRemovePost::create(conn, &form)
})
context
.conn()
.await?
.interact(move |conn| ModRemovePost::create(conn, &form))
.await??;
let removed_post = blocking(context.pool(), move |conn| {
Post::update_removed(conn, post.id, true)
})
let removed_post = context
.conn()
.await?
.interact(move |conn| Post::update_removed(conn, post.id, true))
.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),
reason,
};
blocking(context.pool(), move |conn| {
ModRemoveComment::create(conn, &form)
})
context
.conn()
.await?
.interact(move |conn| ModRemoveComment::create(conn, &form))
.await??;
let removed_comment = blocking(context.pool(), move |conn| {
Comment::update_removed(conn, comment.id, true)
})
let removed_comment = context
.conn()
.await?
.interact(move |conn| Comment::update_removed(conn, comment.id, true))
.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? {
DeletableObjects::Community(c) => c.id,
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
}
DeletableObjects::Post(p) => p.community_id,
};
let community = blocking(context.pool(), move |conn| {
Community::read(conn, community_id)
})
let community = context
.conn()
.await?
.interact(move |conn| Community::read(conn, community_id))
.await??;
Ok(community.into())
}

View file

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

View file

@ -12,7 +12,6 @@ use crate::{
};
use activitystreams::{activity::kind::UndoType, public};
use anyhow::anyhow;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{
data::Data,
object_id::ObjectId,
@ -109,23 +108,26 @@ impl UndoDelete {
if community.local {
return Err(anyhow!("Only local admin can restore community").into());
}
let deleted_community = blocking(context.pool(), move |conn| {
Community::update_removed(conn, community.id, false)
})
let deleted_community = context
.conn()
.await?
.interact(move |conn| Community::update_removed(conn, community.id, false))
.await??;
send_community_ws_message(deleted_community.id, EditCommunity, None, None, context).await?;
}
DeletableObjects::Post(post) => {
let removed_post = blocking(context.pool(), move |conn| {
Post::update_removed(conn, post.id, false)
})
let removed_post = context
.conn()
.await?
.interact(move |conn| Post::update_removed(conn, post.id, false))
.await??;
send_post_ws_message(removed_post.id, EditPost, None, None, context).await?;
}
DeletableObjects::Comment(comment) => {
let removed_comment = blocking(context.pool(), move |conn| {
Comment::update_removed(conn, comment.id, false)
})
let removed_comment = context
.conn()
.await?
.interact(move |conn| Comment::update_removed(conn, comment.id, false))
.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},
};
use activitystreams::activity::kind::AcceptType;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{
data::Data,
object_id::ObjectId,
@ -66,9 +65,10 @@ impl ActivityHandler for AcceptFollowCommunity {
let actor = self.actor.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
blocking(context.pool(), move |conn| {
CommunityFollower::follow_accepted(conn, actor.id, to.id)
})
context
.conn()
.await?
.interact(move |conn| CommunityFollower::follow_accepted(conn, actor.id, to.id))
.await??;
Ok(())

View file

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

View file

@ -4,7 +4,6 @@ use crate::{
protocol::activities::following::{follow::FollowCommunity, undo_follow::UndoFollowCommunity},
};
use activitystreams::activity::kind::UndoType;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{
data::Data,
object_id::ObjectId,
@ -72,9 +71,10 @@ impl ActivityHandler for UndoFollowCommunity {
};
// This will fail if they aren't a follower, but ignore the error.
blocking(context.pool(), move |conn| {
CommunityFollower::unfollow(conn, &community_follower_form).ok()
})
context
.conn()
.await?
.interact(move |conn| CommunityFollower::unfollow(conn, &community_follower_form).ok())
.await?;
Ok(())
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,4 +1,3 @@
use lemmy_api_common::blocking;
use lemmy_db_schema::{
source::{
comment::{CommentLike, CommentLikeForm},
@ -35,7 +34,10 @@ async fn vote_comment(
score: vote_type.into(),
};
let person_id = actor.id;
blocking(context.pool(), move |conn| {
context
.conn()
.await?
.interact(move |conn| {
CommentLike::remove(conn, person_id, comment_id)?;
CommentLike::like(conn, &like_form)
})
@ -58,7 +60,10 @@ async fn vote_post(
score: vote_type.into(),
};
let person_id = actor.id;
blocking(context.pool(), move |conn| {
context
.conn()
.await?
.interact(move |conn| {
PostLike::remove(conn, person_id, post_id)?;
PostLike::like(conn, &like_form)
})
@ -75,9 +80,10 @@ async fn undo_vote_comment(
) -> Result<(), LemmyError> {
let comment_id = comment.id;
let person_id = actor.id;
blocking(context.pool(), move |conn| {
CommentLike::remove(conn, person_id, comment_id)
})
context
.conn()
.await?
.interact(move |conn| CommentLike::remove(conn, person_id, comment_id))
.await??;
send_comment_ws_message_simple(comment_id, UserOperation::CreateCommentLike, context).await?;
@ -91,9 +97,10 @@ async fn undo_vote_post(
) -> Result<(), LemmyError> {
let post_id = post.id;
let person_id = actor.id;
blocking(context.pool(), move |conn| {
PostLike::remove(conn, person_id, post_id)
})
context
.conn()
.await?
.interact(move |conn| PostLike::remove(conn, person_id, post_id))
.await??;
send_post_ws_message(post_id, UserOperation::CreatePostLike, None, None, context).await?;

View file

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

View file

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

View file

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

View file

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

View file

@ -5,16 +5,12 @@ use crate::{
use anyhow::anyhow;
use chrono::NaiveDateTime;
use itertools::Itertools;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{
object_id::ObjectId,
traits::ApubObject,
webfinger::{webfinger_resolve_actor, WebfingerType},
};
use lemmy_db_schema::{
source::{community::Community, person::Person as DbPerson},
DbPool,
};
use lemmy_db_schema::source::{community::Community, person::Person as DbPerson};
use lemmy_utils::LemmyError;
use lemmy_websocket::LemmyContext;
use serde::Deserialize;
@ -54,7 +50,7 @@ pub async fn search_by_apub_id(
}
// local actor, read from database and return
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(
name: &str,
kind: WebfingerType,
pool: &DbPool,
context: &LemmyContext,
) -> Result<SearchableObjects, LemmyError> {
let name: String = name.into();
Ok(match kind {
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??
.into(),
),
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??
.into(),
),

View file

@ -4,7 +4,6 @@ use crate::{
};
use actix_web::{body::Body, web, web::Path, HttpResponse};
use diesel::result::Error::NotFound;
use lemmy_api_common::blocking;
use lemmy_apub_lib::traits::ApubObject;
use lemmy_db_schema::{newtypes::CommentId, source::comment::Comment, traits::Crud};
use lemmy_utils::LemmyError;
@ -22,7 +21,10 @@ pub(crate) async fn get_apub_comment(
context: web::Data<LemmyContext>,
) -> Result<HttpResponse<Body>, LemmyError> {
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??
.into();
if !comment.local {

View file

@ -22,7 +22,6 @@ use crate::{
},
};
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_db_schema::source::community::Community;
use lemmy_utils::LemmyError;
@ -40,9 +39,10 @@ pub(crate) async fn get_apub_community_http(
info: web::Path<CommunityQuery>,
context: web::Data<LemmyContext>,
) -> Result<HttpResponse<Body>, LemmyError> {
let community: ApubCommunity = blocking(context.pool(), move |conn| {
Community::read_from_name(conn, &info.community_name)
})
let community: ApubCommunity = context
.conn()
.await?
.interact(move |conn| Community::read_from_name(conn, &info.community_name))
.await??
.into();
@ -97,9 +97,10 @@ pub(crate) async fn get_apub_community_followers(
info: web::Path<CommunityQuery>,
context: web::Data<LemmyContext>,
) -> Result<HttpResponse<Body>, LemmyError> {
let community = blocking(context.pool(), move |conn| {
Community::read_from_name(conn, &info.community_name)
})
let community = context
.conn()
.await?
.interact(move |conn| Community::read_from_name(conn, &info.community_name))
.await??;
let followers = GroupFollowers::new(community, &context).await?;
Ok(create_apub_response(&followers))
@ -111,9 +112,10 @@ pub(crate) async fn get_apub_community_outbox(
info: web::Path<CommunityQuery>,
context: web::Data<LemmyContext>,
) -> Result<HttpResponse<Body>, LemmyError> {
let community = blocking(context.pool(), move |conn| {
Community::read_from_name(conn, &info.community_name)
})
let community = context
.conn()
.await?
.interact(move |conn| Community::read_from_name(conn, &info.community_name))
.await??;
let id = ObjectId::new(generate_outbox_url(&community.actor_id)?);
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>,
context: web::Data<LemmyContext>,
) -> Result<HttpResponse<Body>, LemmyError> {
let community: ApubCommunity = blocking(context.pool(), move |conn| {
Community::read_from_name(conn, &info.community_name)
})
let community: ApubCommunity = context
.conn()
.await?
.interact(move |conn| Community::read_from_name(conn, &info.community_name))
.await??
.into();
let id = ObjectId::new(generate_outbox_url(&community.actor_id)?);

View file

@ -16,7 +16,6 @@ use actix_web::{
use anyhow::{anyhow, Context};
use futures::StreamExt;
use http::StatusCode;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{
data::Data,
object_id::ObjectId,
@ -24,7 +23,7 @@ use lemmy_apub_lib::{
traits::{ActivityHandler, ActorType},
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_websocket::LemmyContext;
use log::info;
@ -98,7 +97,7 @@ where
verify_signature(&request, &actor.public_key().context(location_info!())?)?;
// 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());
}
info!("Verifying activity {}", activity_data.id.to_string());
@ -165,9 +164,10 @@ pub(crate) async fn get_activity(
info.id
))?
.into();
let activity = blocking(context.pool(), move |conn| {
Activity::read_from_apub_id(conn, &activity_id)
})
let activity = context
.conn()
.await?
.interact(move |conn| Activity::read_from_apub_id(conn, &activity_id))
.await??;
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(
pool: &DbPool,
context: &LemmyContext,
activity_id: &Url,
) -> Result<bool, LemmyError> {
let activity_id = activity_id.to_owned().into();
let existing = blocking(pool, move |conn| {
Activity::read_from_apub_id(conn, &activity_id)
})
let existing = context
.conn()
.await?
.interact(move |conn| Activity::read_from_apub_id(conn, &activity_id))
.await?;
match existing {
Ok(_) => Ok(true),

View file

@ -12,7 +12,6 @@ use crate::{
protocol::collections::person_outbox::PersonOutbox,
};
use actix_web::{body::Body, web, web::Payload, HttpRequest, HttpResponse};
use lemmy_api_common::blocking;
use lemmy_apub_lib::traits::ApubObject;
use lemmy_db_schema::source::person::Person;
use lemmy_utils::LemmyError;
@ -32,9 +31,10 @@ pub(crate) async fn get_apub_person_http(
) -> Result<HttpResponse<Body>, LemmyError> {
let user_name = info.into_inner().user_name;
// TODO: this needs to be able to read deleted persons, so that it can send tombstones
let person: ApubPerson = blocking(context.pool(), move |conn| {
Person::find_by_name(conn, &user_name)
})
let person: ApubPerson = context
.conn()
.await?
.interact(move |conn| Person::find_by_name(conn, &user_name))
.await??
.into();
@ -73,9 +73,10 @@ pub(crate) async fn get_apub_person_outbox(
info: web::Path<PersonQuery>,
context: web::Data<LemmyContext>,
) -> Result<HttpResponse<Body>, LemmyError> {
let person = blocking(context.pool(), move |conn| {
Person::find_by_name(conn, &info.user_name)
})
let person = context
.conn()
.await?
.interact(move |conn| Person::find_by_name(conn, &info.user_name))
.await??;
let outbox = PersonOutbox::new(person).await?;
Ok(create_apub_response(&outbox))

View file

@ -4,7 +4,6 @@ use crate::{
};
use actix_web::{body::Body, web, HttpResponse};
use diesel::result::Error::NotFound;
use lemmy_api_common::blocking;
use lemmy_apub_lib::traits::ApubObject;
use lemmy_db_schema::{newtypes::PostId, source::post::Post, traits::Crud};
use lemmy_utils::LemmyError;
@ -22,7 +21,10 @@ pub(crate) async fn get_apub_post(
context: web::Data<LemmyContext>,
) -> Result<HttpResponse<Body>, LemmyError> {
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??
.into();
if !post.local {

View file

@ -13,7 +13,6 @@ extern crate lazy_static;
use crate::fetcher::post_or_comment::PostOrComment;
use anyhow::{anyhow, Context};
use lemmy_api_common::blocking;
use lemmy_apub_lib::webfinger::{webfinger_resolve_actor, WebfingerType};
use lemmy_db_schema::{newtypes::DbUrl, source::activity::Activity, DbPool};
use lemmy_utils::{location_info, settings::structs::Settings, LemmyError};
@ -188,9 +187,10 @@ where
T: Serialize + std::fmt::Debug + Send + 'static,
{
let ap_id = ap_id.to_owned().into();
blocking(pool, move |conn| {
Activity::insert(conn, ap_id, &activity, local, sensitive)
})
pool
.get()
.await?
.interact(move |conn| Activity::insert(conn, ap_id, &activity, local, sensitive))
.await??;
Ok(())
}

View file

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

View file

@ -12,7 +12,6 @@ use crate::{
use activitystreams::{actor::kind::GroupType, object::kind::ImageType};
use chrono::NaiveDateTime;
use itertools::Itertools;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{
object_id::ObjectId,
traits::{ActorType, ApubObject},
@ -60,18 +59,20 @@ impl ApubObject for ApubCommunity {
context: &LemmyContext,
) -> Result<Option<Self>, LemmyError> {
Ok(
blocking(context.pool(), move |conn| {
Community::read_from_apub_id(conn, object_id)
})
context
.conn()
.await?
.interact(move |conn| Community::read_from_apub_id(conn, object_id))
.await??
.map(Into::into),
)
}
async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
blocking(context.pool(), move |conn| {
Community::update_deleted(conn, self.id, true)
})
context
.conn()
.await?
.interact(move |conn| Community::update_deleted(conn, self.id, true))
.await??;
Ok(())
}
@ -143,8 +144,10 @@ impl ApubObject for ApubCommunity {
// 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.
let community: ApubCommunity =
blocking(context.pool(), move |conn| Community::upsert(conn, &form))
let community: ApubCommunity = context
.conn()
.await?
.interact(move |conn| Community::upsert(conn, &form))
.await??
.into();
let outbox_data = CommunityContext(community.clone(), context.clone());
@ -197,9 +200,10 @@ impl ApubCommunity {
) -> Result<Vec<Url>, LemmyError> {
let id = self.id;
let follows = blocking(context.pool(), move |conn| {
CommunityFollowerView::for_community(conn, id)
})
let follows = context
.conn()
.await?
.interact(move |conn| CommunityFollowerView::for_community(conn, id))
.await??;
let follower_inboxes: Vec<Url> = follows
.into_iter()
@ -228,7 +232,7 @@ impl ApubCommunity {
pub(crate) mod tests {
use super::*;
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;
pub(crate) async fn parse_lemmy_community(context: &LemmyContext) -> ApubCommunity {
@ -256,12 +260,13 @@ pub(crate) mod tests {
async fn test_parse_lemmy_community() {
let context = init_context();
let community = parse_lemmy_community(&context).await;
let conn = establish_unpooled_connection();
assert_eq!(community.title, "Ten Forward");
assert!(community.public_key.is_some());
assert!(!community.local);
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)]
pub(crate) mod tests {
use actix::Actor;
use diesel::{
r2d2::{ConnectionManager, Pool},
PgConnection,
};
use deadpool_diesel::postgres::{Manager, Pool, Runtime};
use lemmy_apub_lib::activity_queue::create_activity_queue;
use lemmy_db_schema::{
establish_unpooled_connection,
@ -66,11 +63,12 @@ pub(crate) mod tests {
Ok(url) => 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)
.build(manager)
.unwrap_or_else(|_| panic!("Error connecting to {}", db_url));
.build()
.unwrap();
async fn x() -> Result<String, LemmyError> {
Ok("".to_string())
}

View file

@ -13,7 +13,6 @@ use crate::{
};
use activitystreams::object::kind::ImageType;
use chrono::NaiveDateTime;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{
object_id::ObjectId,
traits::{ActorType, ApubObject},
@ -63,18 +62,20 @@ impl ApubObject for ApubPerson {
context: &LemmyContext,
) -> Result<Option<Self>, LemmyError> {
Ok(
blocking(context.pool(), move |conn| {
DbPerson::read_from_apub_id(conn, object_id)
})
context
.conn()
.await?
.interact(move |conn| DbPerson::read_from_apub_id(conn, object_id))
.await??
.map(Into::into),
)
}
async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
blocking(context.pool(), move |conn| {
DbPerson::update_deleted(conn, self.id, true)
})
context
.conn()
.await?
.interact(move |conn| DbPerson::update_deleted(conn, self.id, true))
.await??;
Ok(())
}
@ -171,9 +172,10 @@ impl ApubObject for ApubPerson {
shared_inbox_url: Some(person.endpoints.shared_inbox.map(|s| s.into())),
matrix_user_id: Some(person.matrix_user_id),
};
let person = blocking(context.pool(), move |conn| {
DbPerson::upsert(conn, &person_form)
})
let person = context
.conn()
.await?
.interact(move |conn| DbPerson::upsert(conn, &person_form))
.await??;
Ok(person.into())
}
@ -205,7 +207,7 @@ impl ActorType for ApubPerson {
pub(crate) mod tests {
use super::*;
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;
pub(crate) async fn parse_lemmy_person(context: &LemmyContext) -> ApubPerson {
@ -226,6 +228,7 @@ pub(crate) mod tests {
#[serial]
async fn test_parse_lemmy_person() {
let context = init_context();
let conn = establish_unpooled_connection();
let person = parse_lemmy_person(&context).await;
assert_eq!(person.display_name, Some("Jean-Luc Picard".to_string()));
@ -233,13 +236,14 @@ pub(crate) mod tests {
assert!(!person.local);
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]
#[serial]
async fn test_parse_pleroma_person() {
let context = init_context();
let conn = establish_unpooled_connection();
let json = file_to_json_object("assets/pleroma/objects/person.json");
let url = Url::parse("https://queer.hacktivis.me/users/lanodan").unwrap();
let mut request_counter = 0;
@ -257,6 +261,6 @@ pub(crate) mod tests {
assert_eq!(request_counter, 0);
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,
};
use chrono::NaiveDateTime;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{
object_id::ObjectId,
traits::ApubObject,
@ -68,9 +67,10 @@ impl ApubObject for ApubPost {
context: &LemmyContext,
) -> Result<Option<Self>, LemmyError> {
Ok(
blocking(context.pool(), move |conn| {
Post::read_from_apub_id(conn, object_id)
})
context
.conn()
.await?
.interact(move |conn| Post::read_from_apub_id(conn, object_id))
.await??
.map(Into::into),
)
@ -78,9 +78,10 @@ impl ApubObject for ApubPost {
async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
if !self.deleted {
blocking(context.pool(), move |conn| {
Post::update_deleted(conn, self.id, true)
})
context
.conn()
.await?
.interact(move |conn| Post::update_deleted(conn, self.id, true))
.await??;
}
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.
async fn into_apub(self, context: &LemmyContext) -> Result<Page, LemmyError> {
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 = blocking(context.pool(), move |conn| {
Community::read(conn, community_id)
})
let community = context
.conn()
.await?
.interact(move |conn| Community::read(conn, community_id))
.await??;
let source = self.body.clone().map(|body| Source {
@ -200,7 +206,11 @@ impl ApubObject for ApubPost {
ap_id: Some(page.id.into()),
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())
}
}
@ -214,12 +224,14 @@ mod tests {
post::ApubPost,
tests::{file_to_json_object, init_context},
};
use lemmy_db_schema::establish_unpooled_connection;
use serial_test::serial;
#[actix_rt::test]
#[serial]
async fn test_parse_lemmy_post() {
let context = init_context();
let conn = establish_unpooled_connection();
let community = parse_lemmy_community(&context).await;
let person = parse_lemmy_person(&context).await;
@ -241,8 +253,8 @@ mod tests {
assert!(post.stickied);
assert_eq!(request_counter, 0);
Post::delete(&*context.pool().get().unwrap(), post.id).unwrap();
Person::delete(&*context.pool().get().unwrap(), person.id).unwrap();
Community::delete(&*context.pool().get().unwrap(), community.id).unwrap();
Post::delete(&conn, post.id).unwrap();
Person::delete(&conn, person.id).unwrap();
Community::delete(&conn, community.id).unwrap();
}
}

View file

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

View file

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

View file

@ -5,7 +5,6 @@ use crate::{
};
use activitystreams::{object::kind::NoteType, unparsed::Unparsed};
use chrono::{DateTime, FixedOffset};
use lemmy_api_common::blocking;
use lemmy_apub_lib::{object_id::ObjectId, values::MediaTypeHtml};
use lemmy_db_schema::{newtypes::CommentId, source::post::Post, traits::Crud};
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
// want to stackoverflow in a deep comment hierarchy).
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))
}
PostOrComment::Comment(c) => {
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)))
}
}

View file

@ -13,8 +13,9 @@ doctest = false
[dependencies]
lemmy_utils = { version = "=0.13.5-rc.7", path = "../utils" }
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"
deadpool-diesel = { version = "0.3.1", features = ["postgres"] }
chrono = { version = "0.4.19", features = ["serde"] }
serde = { version = "1.0.130", features = ["derive"] }
serde_json = { version = "1.0.68", features = ["preserve_order"] }

View file

@ -18,8 +18,6 @@ pub mod schema;
pub mod source;
pub mod traits;
pub type DbPool = diesel::r2d2::Pool<diesel::r2d2::ConnectionManager<diesel::PgConnection>>;
use crate::newtypes::DbUrl;
use chrono::NaiveDateTime;
use diesel::{Connection, PgConnection};
@ -29,6 +27,8 @@ use serde::{Deserialize, Serialize};
use std::{env, env::VarError};
use url::Url;
pub type DbPool = deadpool_diesel::postgres::Pool;
pub fn get_database_url_from_env() -> Result<String, VarError> {
env::var("LEMMY_DATABASE_URL")
}
@ -129,6 +129,13 @@ pub fn establish_unpooled_connection() -> PgConnection {
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 {
chrono::prelude::Utc::now().naive_utc()
}

View file

@ -12,7 +12,7 @@ doctest = false
[dependencies]
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"] }
log = "0.4.14"
url = "2.2.2"

View file

@ -12,5 +12,5 @@ doctest = false
[dependencies]
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"] }

View file

@ -12,5 +12,5 @@ doctest = false
[dependencies]
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"] }

View file

@ -2,7 +2,6 @@ use actix_web::{error::ErrorBadRequest, *};
use anyhow::anyhow;
use chrono::{DateTime, NaiveDateTime, Utc};
use diesel::PgConnection;
use lemmy_api_common::blocking;
use lemmy_db_schema::{
newtypes::LocalUserId,
source::{community::Community, local_user::LocalUser, person::Person},
@ -80,9 +79,16 @@ async fn get_feed_data(
listing_type: ListingType,
sort_type: SortType,
) -> 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)
.listing_type(listing_type)
.sort(sort_type)
@ -136,9 +142,15 @@ async fn get_feed(
let jwt_secret = context.secret().jwt_secret.to_owned();
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::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(
conn,
&jwt_secret,
@ -148,8 +160,8 @@ async fn get_feed(
),
RequestType::Inbox => get_feed_inbox(conn, &jwt_secret, &param, &protocol_and_hostname),
})
.await?
.map_err(ErrorBadRequest)?;
.await
.map_err(ErrorBadRequest)??;
let rss = builder.build().map_err(ErrorBadRequest)?.to_string();

View file

@ -1,6 +1,5 @@
use actix_web::{body::Body, error::ErrorBadRequest, *};
use anyhow::anyhow;
use lemmy_api_common::blocking;
use lemmy_db_views::site_view::SiteView;
use lemmy_utils::{version, LemmyError};
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> {
let site_view = blocking(context.pool(), SiteView::read)
.await?
let site_view = context
.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"))))?;
let protocols = if context.settings().federation.enabled {

View file

@ -1,6 +1,5 @@
use actix_web::{error::ErrorBadRequest, web::Query, *};
use anyhow::anyhow;
use lemmy_api_common::blocking;
use lemmy_apub_lib::webfinger::{WebfingerLink, WebfingerResponse};
use lemmy_db_schema::source::{community::Community, person::Person};
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 community_name = community_name.as_str().to_owned();
// Make sure the requested community exists.
blocking(context.pool(), move |conn| {
Community::read_from_name(conn, &community_name)
})
.await?
context
.conn()
.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"))))?
.actor_id
} else if let Some(person_name) = username_regex_parsed {
let person_name = person_name.as_str().to_owned();
// Make sure the requested person exists.
blocking(context.pool(), move |conn| {
Person::find_by_name(conn, &person_name)
})
.await?
context
.conn()
.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"))))?
.actor_id
} else {

View file

@ -29,6 +29,7 @@ openssl = "0.10.36"
url = { version = "2.2.2", features = ["serde"] }
actix-web = { version = "4.0.0-beta.9", default-features = false, features = ["rustls"] }
actix-rt = { version = "2.2.0", default-features = false }
actix = "0.12.0"
anyhow = "1.0.44"
reqwest = { version = "0.11.4", features = ["json"] }
tokio = { version = "1.12.0", features = ["sync"] }
@ -36,6 +37,10 @@ strum = "0.21.0"
strum_macros = "0.21.1"
futures = "0.3.17"
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"
deser-hjson = "1.0.2"
smart-default = "0.6.0"
@ -43,3 +48,7 @@ webpage = { version = "1.3.0", default-features = false, features = ["serde"] }
jsonwebtoken = "7.2.0"
doku = "0.10.1"
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,
}
impl<T> From<T> for LemmyError
where
T: Into<anyhow::Error>,
{
fn from(t: T) -> Self {
LemmyError { inner: t.into() }
impl From<deadpool_sync::InteractError> for LemmyError {
fn from(e: deadpool_sync::InteractError) -> Self {
LemmyError {
inner: anyhow::anyhow!(e.to_string()),
}
}
}
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,
/// Maximum number of active sql connections
#[default(5)]
pub pool_size: u32,
pub pool_size: usize,
}
#[derive(Debug, Deserialize, Serialize, Clone, Document)]

View file

@ -33,3 +33,5 @@ strum_macros = "0.21.1"
chrono = { version = "0.4.19", features = ["serde"] }
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 }
deadpool-diesel = { version = "0.3.1", features = ["postgres"] }
deadpool = "0.9.1"

View file

@ -9,14 +9,11 @@ use crate::{
use actix::prelude::*;
use anyhow::Context as acontext;
use background_jobs::QueueHandle;
use diesel::{
r2d2::{ConnectionManager, Pool},
PgConnection,
};
use lemmy_api_common::{comment::*, post::*};
use lemmy_db_schema::{
newtypes::{CommunityId, LocalUserId, PostId},
source::secret::Secret,
DbPool,
};
use lemmy_utils::{
location_info,
@ -73,7 +70,7 @@ pub struct ChatServer {
pub(super) rng: ThreadRng,
/// The DB Pool
pub(super) pool: Pool<ConnectionManager<PgConnection>>,
pub(super) pool: DbPool,
/// The Settings
pub(super) settings: Settings,
@ -107,7 +104,7 @@ pub struct SessionInfo {
impl ChatServer {
#![allow(clippy::too_many_arguments)]
pub fn startup(
pool: Pool<ConnectionManager<PgConnection>>,
pool: DbPool,
rate_limiter: RateLimit,
message_handler: MessageHandlerType,
message_handler_crud: MessageHandlerCrudType,

View file

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

View file

@ -4,7 +4,6 @@ use crate::{
OperationType,
};
use lemmy_api_common::{
blocking,
comment::CommentResponse,
community::CommunityResponse,
person::PrivateMessageResponse,
@ -43,9 +42,10 @@ pub async fn send_post_ws_message<OP: ToString + Send + OperationType + 'static>
person_id: Option<PersonId>,
context: &LemmyContext,
) -> Result<PostResponse, LemmyError> {
let post_view = blocking(context.pool(), move |conn| {
PostView::read(conn, post_id, person_id)
})
let post_view = context
.conn()
.await?
.interact(move |conn| PostView::read(conn, post_id, person_id))
.await??;
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>,
context: &LemmyContext,
) -> Result<CommentResponse, LemmyError> {
let mut view = blocking(context.pool(), move |conn| {
CommentView::read(conn, comment_id, person_id)
})
let mut view = context
.conn()
.await?
.interact(move |conn| CommentView::read(conn, comment_id, person_id))
.await??;
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>,
context: &LemmyContext,
) -> Result<CommunityResponse, LemmyError> {
let community_view = blocking(context.pool(), move |conn| {
CommunityView::read(conn, community_id, person_id)
})
let community_view = context
.conn()
.await?
.interact(move |conn| CommunityView::read(conn, community_id, person_id))
.await??;
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>,
context: &LemmyContext,
) -> Result<PrivateMessageResponse, LemmyError> {
let mut view = blocking(context.pool(), move |conn| {
PrivateMessageView::read(conn, private_message_id)
})
let mut view = context
.conn()
.await?
.interact(move |conn| PrivateMessageView::read(conn, private_message_id))
.await??;
// 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
if res.private_message_view.recipient.local {
let recipient_id = res.private_message_view.recipient.id;
let local_recipient = blocking(context.pool(), move |conn| {
LocalUserView::read_person(conn, recipient_id)
})
let local_recipient = context
.conn()
.await?
.interact(move |conn| LocalUserView::read_person(conn, recipient_id))
.await??;
context.chat_server().do_send(SendUserRoomMessage {
op,
@ -190,9 +194,10 @@ pub async fn send_local_notifs(
.collect::<Vec<&MentionData>>()
{
let mention_name = mention.name.clone();
let user_view = blocking(context.pool(), move |conn| {
LocalUserView::read_from_name(conn, &mention_name)
})
let user_view = context
.conn()
.await?
.interact(move |conn| LocalUserView::read_from_name(conn, &mention_name))
.await?;
if let Ok(mention_user_view) = user_view {
// 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
// Let the uniqueness handle this fail
blocking(context.pool(), move |conn| {
PersonMention::create(conn, &user_mention_form)
})
context
.conn()
.await?
.interact(move |conn| PersonMention::create(conn, &user_mention_form))
.await?
.ok();
@ -230,15 +236,19 @@ pub async fn send_local_notifs(
// Send notifs to the parent commenter / poster
match comment.parent_id {
Some(parent_id) => {
let parent_comment =
blocking(context.pool(), move |conn| Comment::read(conn, parent_id)).await?;
let parent_comment = context
.conn()
.await?
.interact(move |conn| Comment::read(conn, parent_id))
.await?;
if let Ok(parent_comment) = parent_comment {
// Don't send a notif to yourself
if parent_comment.creator_id != person.id {
// Get the parent commenter local_user
let user_view = blocking(context.pool(), move |conn| {
LocalUserView::read_person(conn, parent_comment.creator_id)
})
let user_view = context
.conn()
.await?
.interact(move |conn| LocalUserView::read_person(conn, parent_comment.creator_id))
.await?;
if let Ok(parent_user_view) = user_view {
recipient_ids.push(parent_user_view.local_user.id);
@ -260,9 +270,10 @@ pub async fn send_local_notifs(
None => {
if post.creator_id != person.id {
let creator_id = post.creator_id;
let parent_user = blocking(context.pool(), move |conn| {
LocalUserView::read_person(conn, creator_id)
})
let parent_user = context
.conn()
.await?
.interact(move |conn| LocalUserView::read_person(conn, creator_id))
.await?;
if let Ok(parent_user_view) = parent_user {
recipient_ids.push(parent_user_view.local_user.id);

View file

@ -3,13 +3,9 @@ extern crate diesel_migrations;
use actix::prelude::*;
use actix_web::{web::Data, *};
use diesel::{
r2d2::{ConnectionManager, Pool},
PgConnection,
};
use deadpool_diesel::postgres::{Manager, Pool, Runtime};
use doku::json::{AutoComments, Formatting};
use lemmy_api::match_websocket_operation;
use lemmy_api_common::blocking;
use lemmy_api_crud::match_websocket_operation_crud;
use lemmy_apub_lib::activity_queue::create_activity_queue;
use lemmy_db_schema::{get_database_url_from_env, source::secret::Secret};
@ -43,29 +39,30 @@ async fn main() -> Result<(), LemmyError> {
env_logger::init();
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() {
Ok(url) => 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)
.build(manager)
.unwrap_or_else(|_| panic!("Error connecting to {}", db_url));
.build()?;
// Run the migrations from code
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)?;
run_advanced_migrations(conn, &protocol_and_hostname)?;
Ok(()) as Result<(), LemmyError>
})
.await??;
let pool2 = pool.clone();
thread::spawn(move || {
scheduled_tasks::setup(pool2);
scheduled_tasks::setup(&db_url);
});
// Set up the rate limiter
@ -75,8 +72,11 @@ async fn main() -> Result<(), LemmyError> {
};
// Initialize the secrets
let conn = pool.get()?;
let secret = Secret::init(&conn).expect("Couldn't initialize secrets.");
let conn = pool.get().await?;
let secret = conn
.interact(|conn| Secret::init(conn))
.await?
.expect("Couldn't initialize secrets.");
println!(
"Starting http server at {}:{}",

View file

@ -2,29 +2,33 @@
use clokwerk::{Scheduler, TimeUnits};
// Import week days and WeekDay
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 std::{thread, time::Duration};
/// 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 conn = pool.get().unwrap();
active_counts(&conn);
let conn = &establish_unpooled_connection_with_db_url(db_url);
active_counts(conn);
// On startup, reindex the tables non-concurrently
// 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 || {
active_counts(&conn);
reindex_aggregates_tables(&conn, true);
let conn = &establish_unpooled_connection_with_db_url(&db_url2);
active_counts(conn);
reindex_aggregates_tables(conn, true);
});
let conn = pool.get().unwrap();
clear_old_activities(&conn);
let db_url3 = db_url.to_owned();
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