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,10 +41,11 @@ 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)
})
.await??;
let orig_comment = context
.conn()
.await?
.interact(move |conn| CommentView::read(conn, comment_id, None))
.await??;
check_community_ban(
local_user_view.person.id,
@ -61,19 +61,21 @@ 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)
})
.await?
.map_err(|_| ApiError::err_plain("couldnt_update_comment"))?;
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))
})
.await??;
let comment_view = context
.conn()
.await?
.interact(move |conn| CommentView::read(conn, comment_id, Some(person_id)))
.await??;
let res = CommentResponse {
comment_view,
@ -104,23 +106,28 @@ 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))
})
.await??;
let comment_view = context
.conn()
.await?
.interact(move |conn| CommentView::read(conn, comment_id, Some(person_id)))
.await??;
Ok(CommentResponse {
comment_view,
@ -149,10 +156,11 @@ 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)
})
.await??;
let orig_comment = context
.conn()
.await?
.interact(move |conn| CommentView::read(conn, comment_id, None))
.await??;
check_community_ban(
local_user_view.person.id,
@ -170,10 +178,11 @@ 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)
})
.await?
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,10 +196,11 @@ 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)
})
.await??;
context
.conn()
.await?
.interact(move |conn| CommentLike::remove(conn, person_id, comment_id))
.await??;
// Only add the like if the score isnt 0
let comment = orig_comment.comment;
@ -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,10 +41,11 @@ 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)
})
.await??;
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,16 +56,18 @@ impl Perform for CreateCommentReport {
reason: data.reason.to_owned(),
};
let report = blocking(context.pool(), move |conn| {
CommentReport::report(conn, &report_form)
})
.await?
.map_err(|e| ApiError::err("couldnt_create_report", e))?;
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)
})
.await??;
let comment_report_view = context
.conn()
.await?
.interact(move |conn| CommentReportView::read(conn, report.id, person_id))
.await??;
let res = CommentReportResponse {
comment_report_view,
@ -107,32 +109,36 @@ 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)
})
.await??;
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: &'_ _| {
if resolved {
CommentReport::resolve(conn, report_id, person_id)
} else {
CommentReport::unresolve(conn, report_id, person_id)
}
};
blocking(context.pool(), resolve_fun)
context
.conn()
.await?
.interact(move |conn| {
if resolved {
CommentReport::resolve(conn, report_id, person_id)
} else {
CommentReport::unresolve(conn, report_id, person_id)
}
})
.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)
})
.await??;
let comment_report_view = context
.conn()
.await?
.interact(move |conn| CommentReportView::read(conn, report_id, person_id))
.await??;
let res = CommentReportResponse {
comment_report_view,
@ -171,15 +177,18 @@ impl Perform for ListCommentReports {
let page = data.page;
let limit = data.limit;
let comment_reports = blocking(context.pool(), move |conn| {
CommentReportQueryBuilder::create(conn, person_id, admin)
.community_id(community_id)
.unresolved_only(unresolved_only)
.page(page)
.limit(limit)
.list()
})
.await??;
let comment_reports = context
.conn()
.await?
.interact(move |conn| {
CommentReportQueryBuilder::create(conn, person_id, admin)
.community_id(community_id)
.unresolved_only(unresolved_only)
.page(page)
.limit(limit)
.list()
})
.await??;
let res = ListCommentReportsResponse { comment_reports };

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,11 +70,12 @@ 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)
})
.await??
.into();
let community: ApubCommunity = context
.conn()
.await?
.interact(move |conn| Community::read(conn, community_id))
.await??
.into();
let community_follower_form = CommunityFollowerForm {
community_id: data.community_id,
person_id: local_user_view.person.id,
@ -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,18 +109,21 @@ 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))
})
.await??;
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
// For now, just assume that remote follows are accepted.
@ -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,27 +170,32 @@ impl Perform for BlockCommunity {
person_id,
pending: false,
};
blocking(context.pool(), move |conn: &'_ _| {
CommunityFollower::unfollow(conn, &community_follower_form)
})
.await?
.ok();
let community = blocking(context.pool(), move |conn| {
Community::read(conn, community_id)
})
.await??;
context
.conn()
.await?
.interact(move |conn| CommunityFollower::unfollow(conn, &community_follower_form))
.await?
.ok();
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))
})
.await??;
let community_view = context
.conn()
.await?
.interact(move |conn| CommunityView::read(conn, community_id, Some(person_id)))
.await??;
Ok(BlockCommunityResponse {
blocked: data.block,
@ -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)
})
.await??
.into();
let banned_person: ApubPerson = blocking(context.pool(), move |conn: &'_ _| {
Person::read(conn, banned_person_id)
})
.await??
.into();
let community: ApubCommunity = context
.conn()
.await?
.interact(move |conn| Community::read(conn, community_id))
.await??
.into();
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,11 +255,12 @@ impl Perform for BanFromCommunity {
person_id: banned_person_id,
pending: false,
};
blocking(context.pool(), move |conn: &'_ _| {
CommunityFollower::unfollow(conn, &community_follower_form)
})
.await?
.ok();
context
.conn()
.await?
.interact(move |conn| CommunityFollower::unfollow(conn, &community_follower_form))
.await?
.ok();
BlockUserFromCommunity::send(
&community,
@ -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,28 +288,35 @@ 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: &'_ _| {
Post::update_removed_for_creator(conn, banned_person_id, Some(community_id), true)
})
.await??;
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| {
CommentQueryBuilder::create(conn)
.creator_id(banned_person_id)
.community_id(community_id)
.limit(std::i64::MAX)
.list()
})
.await??;
let comments = context
.conn()
.await?
.interact(move |conn| {
CommentQueryBuilder::create(conn)
.creator_id(banned_person_id)
.community_id(community_id)
.limit(std::i64::MAX)
.list()
})
.await??;
for comment_view in &comments {
let comment_id = comment_view.comment.id;
blocking(context.pool(), move |conn: &'_ _| {
Comment::update_removed(conn, comment_id, true)
})
.await??;
context
.conn()
.await?
.interact(move |conn| Comment::update_removed(conn, comment_id, true))
.await??;
}
}
@ -305,16 +332,18 @@ impl Perform for BanFromCommunity {
banned: Some(data.ban),
expires,
};
blocking(context.pool(), move |conn| {
ModBanFromCommunity::create(conn, &form)
})
.await??;
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)
})
.await??;
let person_view = context
.conn()
.await?
.interact(move |conn| PersonViewSafe::read(conn, person_id))
.await??;
let res = BanFromCommunityResponse {
person_view,
@ -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,23 +407,26 @@ impl Perform for AddModToCommunity {
community_id: data.community_id,
removed: Some(!data.added),
};
blocking(context.pool(), move |conn| {
ModAddCommunity::create(conn, &form)
})
.await??;
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)
})
.await??
.into();
let community: ApubCommunity = blocking(context.pool(), move |conn| {
Community::read(conn, community_id)
})
.await??
.into();
let updated_mod: ApubPerson = context
.conn()
.await?
.interact(move |conn| Person::read(conn, updated_mod_id))
.await??
.into();
let community: ApubCommunity = context
.conn()
.await?
.interact(move |conn| Community::read(conn, community_id))
.await??
.into();
if data.added {
AddMod::send(
&community,
@ -412,10 +448,11 @@ 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)
})
.await??;
let moderators = context
.conn()
.await?
.interact(move |conn| CommunityModeratorView::for_community(conn, community_id))
.await??;
let res = AddModToCommunityResponse { moderators };
context.chat_server().do_send(SendCommunityRoomMessage {
@ -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)
})
.await??;
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,10 +502,11 @@ 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)
})
.await??;
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
if local_user_view.person.id != community_mods[0].moderator.id
@ -486,10 +529,11 @@ 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)
})
.await??;
context
.conn()
.await?
.interact(move |conn| CommunityModerator::delete_for_community(conn, community_id))
.await??;
// TODO: this should probably be a bulk operation
// Re-add the mods, in the new order
@ -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,25 +558,28 @@ impl Perform for TransferCommunity {
community_id: data.community_id,
removed: Some(false),
};
blocking(context.pool(), move |conn| {
ModTransferCommunity::create(conn, &form)
})
.await??;
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))
})
.await?
.map_err(|e| ApiError::err("couldnt_find_community", e))?;
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)
})
.await?
.map_err(|e| ApiError::err("couldnt_find_community", e))?;
let moderators = context
.conn()
.await?
.interact(move |conn| CommunityModeratorView::for_community(conn, community_id))
.await?
.map_err(|e| ApiError::err("couldnt_find_community", e))?;
// Return the jwt
Ok(GetCommunityResponse {

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,11 +66,12 @@ 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)
})
.await?
.map_err(|e| ApiError::err("couldnt_find_that_username_or_email", e))?;
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))?;
// Verify the password
let valid: bool = verify(
@ -214,11 +209,12 @@ impl Perform for SaveUserSettings {
bot_account,
};
blocking(context.pool(), move |conn| {
Person::update(conn, person_id, &person_form)
})
.await?
.map_err(|e| ApiError::err("user_already_exists", e))?;
context
.conn()
.await?
.interact(move |conn| Person::update(conn, person_id, &person_form))
.await?
.map_err(|e| ApiError::err("user_already_exists", e))?;
let local_user_form = LocalUserForm {
person_id,
@ -237,10 +233,11 @@ 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)
})
.await?;
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,
Err(e) => {
@ -299,10 +296,11 @@ 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)
})
.await??;
let updated_local_user = context
.conn()
.await?
.interact(move |conn| LocalUser::update_password(conn, local_user_id, &new_password))
.await??;
// Return the jwt
Ok(LoginResponse {
@ -333,11 +331,12 @@ 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)
})
.await?
.map_err(|e| ApiError::err("couldnt_update_user", e))?;
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))?;
// Mod tables
let form = ModAddForm {
@ -346,14 +345,23 @@ impl Perform for AddAdmin {
removed: Some(!data.added),
};
blocking(context.pool(), move |conn| ModAdd::create(conn, &form)).await??;
context
.conn()
.await?
.interact(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)
})
.await??;
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??;
let creator_index = admins
.iter()
.position(|r| r.person.id == site_creator_id)
@ -391,26 +399,30 @@ 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)
})
.await??;
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)
})
.await??;
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
let banned_user_first_communities: Vec<CommunityModeratorView> = first_mod_communities
@ -419,17 +431,21 @@ impl Perform for BanPerson {
.collect();
for first_mod_community in banned_user_first_communities {
blocking(context.pool(), move |conn: &'_ _| {
Community::update_removed(conn, first_mod_community.community.id, true)
})
.await??;
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)
})
.await??;
context
.conn()
.await?
.interact(move |conn| Comment::update_removed_for_creator(conn, banned_person_id, true))
.await??;
}
// Mod tables
@ -443,13 +459,18 @@ 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)
})
.await??;
let person_view = context
.conn()
.await?
.interact(move |conn| PersonViewSafe::read(conn, person_id))
.await??;
let res = BanPersonResponse {
person_view,
@ -493,23 +514,28 @@ 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)
})
.await??;
let person_view = context
.conn()
.await?
.interact(move |conn| PersonViewSafe::read(conn, target_id))
.await??;
let res = BlockPersonResponse {
person_view,
@ -541,18 +567,21 @@ 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| {
CommentQueryBuilder::create(conn)
.sort(sort)
.unread_only(unread_only)
.recipient_id(person_id)
.show_bot_accounts(show_bot_accounts)
.my_person_id(person_id)
.page(page)
.limit(limit)
.list()
})
.await??;
let replies = context
.conn()
.await?
.interact(move |conn| {
CommentQueryBuilder::create(conn)
.sort(sort)
.unread_only(unread_only)
.recipient_id(person_id)
.show_bot_accounts(show_bot_accounts)
.my_person_id(person_id)
.page(page)
.limit(limit)
.list()
})
.await??;
Ok(GetRepliesResponse { replies })
}
@ -577,17 +606,20 @@ 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| {
PersonMentionQueryBuilder::create(conn)
.recipient_id(person_id)
.my_person_id(person_id)
.sort(sort)
.unread_only(unread_only)
.page(page)
.limit(limit)
.list()
})
.await??;
let mentions = context
.conn()
.await?
.interact(move |conn| {
PersonMentionQueryBuilder::create(conn)
.recipient_id(person_id)
.my_person_id(person_id)
.sort(sort)
.unread_only(unread_only)
.page(page)
.limit(limit)
.list()
})
.await??;
Ok(GetPersonMentionsResponse { mentions })
}
@ -607,10 +639,11 @@ 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)
})
.await??;
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 {
return Err(ApiError::err_plain("couldnt_update_comment").into());
@ -618,18 +651,21 @@ 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))
})
.await??;
let person_mention_view = context
.conn()
.await?
.interact(move |conn| PersonMentionView::read(conn, person_mention_id, Some(person_id)))
.await??;
Ok(PersonMentionResponse {
person_mention_view,
@ -651,38 +687,46 @@ 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| {
CommentQueryBuilder::create(conn)
.my_person_id(person_id)
.recipient_id(person_id)
.unread_only(true)
.page(1)
.limit(999)
.list()
})
.await??;
let replies = context
.conn()
.await?
.interact(move |conn| {
CommentQueryBuilder::create(conn)
.my_person_id(person_id)
.recipient_id(person_id)
.unread_only(true)
.page(1)
.limit(999)
.list()
})
.await??;
// TODO: this should probably be a bulk operation
// Not easy to do as a bulk operation,
// 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,11 +747,12 @@ 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)
})
.await?
.map_err(|e| ApiError::err("couldnt_find_that_username_or_email", e))?;
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))?;
// Generate a random token
let token = generate_random_string();
@ -715,10 +760,11 @@ 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)
})
.await??;
context
.conn()
.await?
.interact(move |conn| PasswordResetRequest::create_token(conn, local_user_id, &token2))
.await??;
// Email the pure token to the user.
// TODO no i18n support here.
@ -752,10 +798,13 @@ 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| {
PasswordResetRequest::read_from_token(conn, &token).map(|p| p.local_user_id)
})
.await??;
let local_user_id = context
.conn()
.await?
.interact(move |conn| {
PasswordResetRequest::read_from_token(conn, &token).map(|p| p.local_user_id)
})
.await??;
password_length_check(&data.password)?;
@ -766,11 +815,12 @@ 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)
})
.await?
.map_err(|e| ApiError::err("couldnt_update_user", e))?;
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))?;
// Return the jwt
Ok(LoginResponse {
@ -800,15 +850,19 @@ 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| {
CommentReportView::get_report_count(conn, person_id, admin, community_id)
})
.await??;
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)
})
.await??;
let post_reports = context
.conn()
.await?
.interact(move |conn| PostReportView::get_report_count(conn, person_id, admin, community_id))
.await??;
let res = GetReportCountResponse {
community_id,
@ -835,20 +889,23 @@ 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)
})
.await??;
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)
})
.await??;
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)
})
.await??;
let private_messages = context
.conn()
.await?
.interact(move |conn| PrivateMessageView::get_unread_messages(conn, person_id))
.await??;
let res = Self::Response {
replies,

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,10 +69,11 @@ 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)
})
.await??;
context
.conn()
.await?
.interact(move |conn| PostLike::remove(conn, person_id, post_id))
.await??;
let community_id = post.community_id;
let object = PostOrComment::Post(Box::new(post));
@ -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,11 +162,12 @@ 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)
})
.await??
.into();
let updated_post: ApubPost = context
.conn()
.await?
.interact(move |conn| Post::update_locked(conn, post_id, locked))
.await??
.into();
// Mod tables
let form = ModLockPostForm {
@ -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,11 +240,12 @@ 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)
})
.await??
.into();
let updated_post: ApubPost = context
.conn()
.await?
.interact(move |conn| Post::update_stickied(conn, post_id, stickied))
.await??
.into();
// Mod tables
let form = ModStickyPostForm {
@ -234,10 +253,11 @@ impl Perform for StickyPost {
post_id: data.post_id,
stickied: Some(stickied),
};
blocking(context.pool(), move |conn| {
ModStickyPost::create(conn, &form)
})
.await??;
context
.conn()
.await?
.interact(move |conn| ModStickyPost::create(conn, &form))
.await??;
// Apub updates
// TODO stickied should pry work like locked for ease of use
@ -279,23 +299,28 @@ 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))
})
.await??;
let post_view = context
.conn()
.await?
.interact(move |conn| PostView::read(conn, post_id, Some(person_id)))
.await??;
// Mark the post as read
mark_post_as_read(person_id, post_id, context.pool()).await?;

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,10 +50,11 @@ 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)
})
.await??;
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,16 +67,18 @@ impl Perform for CreatePostReport {
reason: data.reason.to_owned(),
};
let report = blocking(context.pool(), move |conn| {
PostReport::report(conn, &report_form)
})
.await?
.map_err(|e| ApiError::err("couldnt_create_report", e))?;
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)
})
.await??;
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,31 +118,34 @@ 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)
})
.await??;
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: &'_ _| {
if resolved {
PostReport::resolve(conn, report_id, person_id)
} else {
PostReport::unresolve(conn, report_id, person_id)
}
};
blocking(context.pool(), resolve_fun)
context
.conn()
.await?
.interact(move |conn| {
if resolved {
PostReport::resolve(conn, report_id, person_id)
} else {
PostReport::unresolve(conn, report_id, person_id)
}
})
.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)
})
.await??;
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,15 +182,18 @@ impl Perform for ListPostReports {
let page = data.page;
let limit = data.limit;
let post_reports = blocking(context.pool(), move |conn| {
PostReportQueryBuilder::create(conn, person_id, admin)
.community_id(community_id)
.unresolved_only(unresolved_only)
.page(page)
.limit(limit)
.list()
})
.await??;
let post_reports = context
.conn()
.await?
.interact(move |conn| {
PostReportQueryBuilder::create(conn, person_id, admin)
.community_id(community_id)
.unresolved_only(unresolved_only)
.page(page)
.limit(limit)
.list()
})
.await??;
let res = ListPostReportsResponse { post_reports };

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,10 +23,11 @@ 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)
})
.await??;
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,11 +35,12 @@ 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)
})
.await?
.map_err(|e| ApiError::err("couldnt_update_private_message", e))?;
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))?;
// No need to send an apub update
let op = UserOperation::MarkPrivateMessageAsRead;

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,51 +70,69 @@ 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)
})
.await??;
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)
})
.await??;
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)
})
.await??;
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| {
ModRemoveCommentView::list(conn, community_id, mod_person_id, page, limit)
})
.await??;
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| {
ModBanFromCommunityView::list(conn, community_id, mod_person_id, page, limit)
})
.await??;
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| {
ModAddCommunityView::list(conn, community_id, mod_person_id, page, limit)
})
.await??;
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| {
ModTransferCommunityView::list(conn, community_id, mod_person_id, page, limit)
})
.await??;
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| {
Ok((
ModRemoveCommunityView::list(conn, mod_person_id, page, limit)?,
ModBanView::list(conn, mod_person_id, page, limit)?,
ModAddView::list(conn, mod_person_id, page, limit)?,
)) as Result<_, LemmyError>
})
.await??
context
.conn()
.await?
.interact(move |conn| {
Ok((
ModRemoveCommunityView::list(conn, mod_person_id, page, limit)?,
ModBanView::list(conn, mod_person_id, page, limit)?,
ModAddView::list(conn, mod_person_id, page, limit)?,
)) as Result<_, LemmyError>
})
.await??
} else {
(Vec::new(), Vec::new(), Vec::new())
};
@ -184,114 +201,52 @@ impl Perform for Search {
let creator_id = data.creator_id;
match search_type {
SearchType::Posts => {
posts = blocking(context.pool(), move |conn| {
PostQueryBuilder::create(conn)
.sort(sort)
.show_nsfw(show_nsfw)
.show_bot_accounts(show_bot_accounts)
.show_read_posts(show_read_posts)
.listing_type(listing_type)
.community_id(community_id)
.community_actor_id(community_actor_id)
.creator_id(creator_id)
.my_person_id(person_id)
.search_term(q)
.page(page)
.limit(limit)
.list()
})
.await??;
posts = context
.conn()
.await?
.interact(move |conn| {
PostQueryBuilder::create(conn)
.sort(sort)
.show_nsfw(show_nsfw)
.show_bot_accounts(show_bot_accounts)
.show_read_posts(show_read_posts)
.listing_type(listing_type)
.community_id(community_id)
.community_actor_id(community_actor_id)
.creator_id(creator_id)
.my_person_id(person_id)
.search_term(q)
.page(page)
.limit(limit)
.list()
})
.await??;
}
SearchType::Comments => {
comments = blocking(context.pool(), move |conn| {
CommentQueryBuilder::create(conn)
.sort(sort)
.listing_type(listing_type)
.search_term(q)
.show_bot_accounts(show_bot_accounts)
.community_id(community_id)
.community_actor_id(community_actor_id)
.creator_id(creator_id)
.my_person_id(person_id)
.page(page)
.limit(limit)
.list()
})
.await??;
comments = context
.conn()
.await?
.interact(move |conn| {
CommentQueryBuilder::create(conn)
.sort(sort)
.listing_type(listing_type)
.search_term(q)
.show_bot_accounts(show_bot_accounts)
.community_id(community_id)
.community_actor_id(community_actor_id)
.creator_id(creator_id)
.my_person_id(person_id)
.page(page)
.limit(limit)
.list()
})
.await??;
}
SearchType::Communities => {
communities = blocking(context.pool(), move |conn| {
CommunityQueryBuilder::create(conn)
.sort(sort)
.listing_type(listing_type)
.search_term(q)
.my_person_id(person_id)
.page(page)
.limit(limit)
.list()
})
.await??;
}
SearchType::Users => {
users = blocking(context.pool(), move |conn| {
PersonQueryBuilder::create(conn)
.sort(sort)
.search_term(q)
.page(page)
.limit(limit)
.list()
})
.await??;
}
SearchType::All => {
// If the community or creator is included, dont search communities or users
let community_or_creator_included =
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| {
PostQueryBuilder::create(conn)
.sort(sort)
.show_nsfw(show_nsfw)
.show_bot_accounts(show_bot_accounts)
.show_read_posts(show_read_posts)
.listing_type(listing_type)
.community_id(community_id)
.community_actor_id(community_actor_id_2)
.creator_id(creator_id)
.my_person_id(person_id)
.search_term(q)
.page(page)
.limit(limit)
.list()
})
.await??;
let q = data.q.to_owned();
let community_actor_id = community_actor_id.to_owned();
comments = blocking(context.pool(), move |conn| {
CommentQueryBuilder::create(conn)
.sort(sort)
.listing_type(listing_type)
.search_term(q)
.show_bot_accounts(show_bot_accounts)
.community_id(community_id)
.community_actor_id(community_actor_id)
.creator_id(creator_id)
.my_person_id(person_id)
.page(page)
.limit(limit)
.list()
})
.await??;
let q = data.q.to_owned();
communities = if community_or_creator_included {
vec![]
} else {
blocking(context.pool(), move |conn| {
communities = context
.conn()
.await?
.interact(move |conn| {
CommunityQueryBuilder::create(conn)
.sort(sort)
.listing_type(listing_type)
@ -301,15 +256,13 @@ impl Perform for Search {
.limit(limit)
.list()
})
.await??
};
let q = data.q.to_owned();
users = if community_or_creator_included {
vec![]
} else {
blocking(context.pool(), move |conn| {
.await??;
}
SearchType::Users => {
users = context
.conn()
.await?
.interact(move |conn| {
PersonQueryBuilder::create(conn)
.sort(sort)
.search_term(q)
@ -317,27 +270,118 @@ impl Perform for Search {
.limit(limit)
.list()
})
.await??
.await??;
}
SearchType::All => {
// If the community or creator is included, dont search communities or users
let community_or_creator_included =
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 = context
.conn()
.await?
.interact(move |conn| {
PostQueryBuilder::create(conn)
.sort(sort)
.show_nsfw(show_nsfw)
.show_bot_accounts(show_bot_accounts)
.show_read_posts(show_read_posts)
.listing_type(listing_type)
.community_id(community_id)
.community_actor_id(community_actor_id_2)
.creator_id(creator_id)
.my_person_id(person_id)
.search_term(q)
.page(page)
.limit(limit)
.list()
})
.await??;
let q = data.q.to_owned();
let community_actor_id = community_actor_id.to_owned();
comments = context
.conn()
.await?
.interact(move |conn| {
CommentQueryBuilder::create(conn)
.sort(sort)
.listing_type(listing_type)
.search_term(q)
.show_bot_accounts(show_bot_accounts)
.community_id(community_id)
.community_actor_id(community_actor_id)
.creator_id(creator_id)
.my_person_id(person_id)
.page(page)
.limit(limit)
.list()
})
.await??;
let q = data.q.to_owned();
communities = if community_or_creator_included {
vec![]
} else {
context
.conn()
.await?
.interact(move |conn| {
CommunityQueryBuilder::create(conn)
.sort(sort)
.listing_type(listing_type)
.search_term(q)
.my_person_id(person_id)
.page(page)
.limit(limit)
.list()
})
.await??
};
let q = data.q.to_owned();
users = if community_or_creator_included {
vec![]
} else {
context
.conn()
.await?
.interact(move |conn| {
PersonQueryBuilder::create(conn)
.sort(sort)
.search_term(q)
.page(page)
.limit(limit)
.list()
})
.await??
};
}
SearchType::Url => {
posts = blocking(context.pool(), move |conn| {
PostQueryBuilder::create(conn)
.sort(sort)
.show_nsfw(show_nsfw)
.show_bot_accounts(show_bot_accounts)
.show_read_posts(show_read_posts)
.listing_type(listing_type)
.my_person_id(person_id)
.community_id(community_id)
.community_actor_id(community_actor_id)
.creator_id(creator_id)
.url_search(q)
.page(page)
.limit(limit)
.list()
})
.await??;
posts = context
.conn()
.await?
.interact(move |conn| {
PostQueryBuilder::create(conn)
.sort(sort)
.show_nsfw(show_nsfw)
.show_bot_accounts(show_bot_accounts)
.show_read_posts(show_read_posts)
.listing_type(listing_type)
.my_person_id(person_id)
.community_id(community_id)
.community_actor_id(community_actor_id)
.creator_id(creator_id)
.url_search(q)
.page(page)
.limit(limit)
.list()
})
.await??;
}
};
@ -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,31 +26,16 @@ 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)
})
.await?;
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,11 +65,12 @@ 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)
})
.await?
.map_err(|_| ApiError::err_plain("couldnt_mark_post_as_read").into())
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())
}
pub async fn get_local_user_view_from_jwt(
@ -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,10 +135,11 @@ 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)
})
.await??;
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 {
return Err(ApiError::err_plain("site_ban").into());
@ -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,10 +243,11 @@ 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)
})
.await??;
let distinct_communities = pool
.get()
.await?
.interact(move |conn| Community::distinct_federated_communities(conn))
.await??;
let allowed = federation.allowed_instances;
let blocked = federation.blocked_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,18 +100,21 @@ 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)
})
.await?
.map_err(|e| ApiError::err("couldnt_create_comment", e))?;
let inserted_comment = context
.conn()
.await?
.interact(move |conn| Comment::create(conn, &comment_form2))
.await?
.map_err(|e| ApiError::err("couldnt_create_comment", e))?;
// Necessary to update the ap_id
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,45 +173,51 @@ 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))
})
.await??;
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)
})
.await?
.map_err(|e| ApiError::err("couldnt_update_comment", e))?;
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))
})
.await??;
if local_user_view.person.id == parent_comment.get_recipient_id() {
blocking(context.pool(), move |conn| {
Comment::update_read(conn, parent_id, true)
})
let parent_comment = context
.conn()
.await?
.map_err(|e| ApiError::err("couldnt_update_parent_comment", e))?;
.interact(move |conn| CommentView::read(conn, parent_id, Some(person_id)))
.await??;
if local_user_view.person.id == parent_comment.get_recipient_id() {
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)
})
.await?;
if let Ok(mention) = person_mention {
blocking(context.pool(), move |conn| {
PersonMention::update_read(conn, mention.id, true)
})
let person_mention = context
.conn()
.await?
.map_err(|e| ApiError::err("couldnt_update_person_mentions", e))?;
.interact(move |conn| PersonMention::read_by_comment_and_person(conn, parent_id, person_id))
.await?;
if let Ok(mention) = person_mention {
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,10 +38,11 @@ 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)
})
.await??;
let orig_comment = context
.conn()
.await?
.interact(move |conn| CommentView::read(conn, comment_id, None))
.await??;
// Dont delete it if its already been deleted.
if orig_comment.comment.deleted == data.deleted {
@ -63,17 +63,19 @@ 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)
})
.await?
.map_err(|e| ApiError::err("couldnt_update_comment", e))?;
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)
})
.await??;
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(),
&community.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,10 +128,11 @@ 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)
})
.await??;
let orig_comment = context
.conn()
.await?
.interact(move |conn| CommentView::read(conn, comment_id, None))
.await??;
check_community_ban(
local_user_view.person.id,
@ -144,11 +151,12 @@ 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)
})
.await?
.map_err(|e| ApiError::err("couldnt_update_comment", e))?;
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))?;
// Mod tables
let form = ModRemoveCommentForm {
@ -157,16 +165,18 @@ impl PerformCrud for RemoveComment {
removed: Some(removed),
reason: data.reason.to_owned(),
};
blocking(context.pool(), move |conn| {
ModRemoveComment::create(conn, &form)
})
.await??;
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)
})
.await??;
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(),
&community.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,21 +45,24 @@ 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| {
CommentQueryBuilder::create(conn)
.listing_type(listing_type)
.sort(sort)
.saved_only(saved_only)
.community_id(community_id)
.community_actor_id(community_actor_id)
.my_person_id(person_id)
.show_bot_accounts(show_bot_accounts)
.page(page)
.limit(limit)
.list()
})
.await?
.map_err(|e| ApiError::err("couldnt_get_comments", e))?;
let mut comments = context
.conn()
.await?
.interact(move |conn| {
CommentQueryBuilder::create(conn)
.listing_type(listing_type)
.sort(sort)
.saved_only(saved_only)
.community_id(community_id)
.community_actor_id(community_actor_id)
.my_person_id(person_id)
.show_bot_accounts(show_bot_accounts)
.page(page)
.limit(limit)
.list()
})
.await?
.map_err(|e| ApiError::err("couldnt_get_comments", e))?;
// Blank out deleted or removed info
for cv in comments

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,10 +41,11 @@ 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)
})
.await??;
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
check_community_ban(
@ -66,11 +66,12 @@ 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)
})
.await?
.map_err(|e| ApiError::err("couldnt_update_comment", e))?;
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))?;
// Do the mentions / recipients
let updated_comment_content = updated_comment.content.to_owned();

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,11 +104,12 @@ impl PerformCrud for CreateCommunity {
..CommunityForm::default()
};
let inserted_community = blocking(context.pool(), move |conn| {
Community::create(conn, &community_form)
})
.await?
.map_err(|e| ApiError::err("community_already_exists", e))?;
let inserted_community = context
.conn()
.await?
.interact(move |conn| Community::create(conn, &community_form))
.await?
.map_err(|e| ApiError::err("community_already_exists", e))?;
// The community creator becomes a moderator
let community_moderator_form = CommunityModeratorForm {
@ -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,16 +134,22 @@ 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))
})
.await??;
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,10 +28,11 @@ 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)
})
.await??;
let community_mods = context
.conn()
.await?
.interact(move |conn| CommunityModeratorView::for_community(conn, community_id))
.await??;
// Make sure deleter is the top mod
if local_user_view.person.id != community_mods[0].moderator.id {
@ -41,11 +42,12 @@ 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)
})
.await?
.map_err(|e| ApiError::err("couldnt_update_community", e))?;
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))?;
// Send apub messages
send_apub_delete(
@ -87,11 +89,12 @@ 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)
})
.await?
.map_err(|e| ApiError::err("couldnt_update_community", e))?;
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))?;
// Mod tables
let expires = data.expires.map(naive_from_unix);
@ -102,10 +105,11 @@ impl PerformCrud for RemoveCommunity {
reason: data.reason.to_owned(),
expires,
};
blocking(context.pool(), move |conn| {
ModRemoveCommunity::create(conn, &form)
})
.await??;
context
.conn()
.await?
.interact(move |conn| ModRemoveCommunity::create(conn, &form))
.await??;
// Apub messages
send_apub_remove(

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,11 +45,12 @@ impl PerformCrud for GetCommunity {
}
};
let mut community_view = blocking(context.pool(), move |conn| {
CommunityView::read(conn, community_id, person_id)
})
.await?
.map_err(|e| ApiError::err("couldnt_find_community", e))?;
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))?;
// Blank out deleted or removed info for non-logged in users
if person_id.is_none() && (community_view.community.deleted || community_view.community.removed)
@ -57,11 +58,12 @@ 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)
})
.await?
.map_err(|e| ApiError::err("couldnt_find_community", e))?;
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))?;
let online = context
.chat_server()
@ -106,17 +108,20 @@ impl PerformCrud for ListCommunities {
let page = data.page;
let limit = data.limit;
let mut communities = blocking(context.pool(), move |conn| {
CommunityQueryBuilder::create(conn)
.listing_type(listing_type)
.sort(sort)
.show_nsfw(show_nsfw)
.my_person_id(person_id)
.page(page)
.limit(limit)
.list()
})
.await??;
let mut communities = context
.conn()
.await?
.interact(move |conn| {
CommunityQueryBuilder::create(conn)
.listing_type(listing_type)
.sort(sort)
.show_nsfw(show_nsfw)
.my_person_id(person_id)
.page(page)
.limit(limit)
.list()
})
.await??;
// Blank out deleted or removed info for non-logged in users
if person_id.is_none() {

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,20 +34,24 @@ 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| {
CommunityModeratorView::for_community(conn, community_id)
.map(|v| v.into_iter().map(|m| m.moderator.id).collect())
})
.await??;
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())
})
.await??;
if !mods.contains(&local_user_view.person.id) {
return Err(ApiError::err_plain("not_a_moderator").into());
}
let community_id = data.community_id;
let read_community = blocking(context.pool(), move |conn| {
Community::read(conn, community_id)
})
.await??;
let read_community = context
.conn()
.await?
.interact(move |conn| Community::read(conn, community_id))
.await??;
let icon = diesel_option_overwrite_to_url(&data.icon)?;
let banner = diesel_option_overwrite_to_url(&data.banner)?;
@ -65,11 +68,12 @@ 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)
})
.await?
.map_err(|e| ApiError::err("couldnt_update_community", e))?;
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))?;
UpdateCommunity::send(
updated_community.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,
@ -83,32 +82,39 @@ impl PerformCrud for CreatePost {
..PostForm::default()
};
let inserted_post =
match blocking(context.pool(), 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)" {
"post_title_too_long"
} else {
"couldnt_create_post"
};
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)" {
"post_title_too_long"
} else {
"couldnt_create_post"
};
return Err(ApiError::err(err_type, e).into());
}
};
return Err(ApiError::err(err_type, e).into());
}
};
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 apub_id = generate_local_apub_endpoint(
EndpointType::Post,
&inserted_post_id.to_string(),
&protocol_and_hostname,
)?;
Ok(Post::update_ap_id(conn, inserted_post_id, apub_id)?)
})
.await?
.map_err(|e| ApiError::err("couldnt_create_post", e))?;
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(),
&protocol_and_hostname,
)?;
Ok(Post::update_ap_id(conn, inserted_post_id, apub_id)?)
})
.await?
.map_err(|e| ApiError::err("couldnt_create_post", e))?;
// They like their own post by default
let person_id = local_user_view.person.id;
@ -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,16 +60,18 @@ 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)
})
.await??;
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)
})
.await??;
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(),
&community.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,10 +130,11 @@ 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)
})
.await??;
let updated_post = context
.conn()
.await?
.interact(move |conn| Post::update_removed(conn, post_id, removed))
.await??;
// Mod tables
let form = ModRemovePostForm {
@ -133,16 +143,18 @@ impl PerformCrud for RemovePost {
removed: Some(removed),
reason: data.reason.to_owned(),
};
blocking(context.pool(), move |conn| {
ModRemovePost::create(conn, &form)
})
.await??;
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)
})
.await??;
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(),
&community.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,11 +39,12 @@ 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)
})
.await?
.map_err(|e| ApiError::err("couldnt_find_post", e))?;
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))?;
// Mark the post as read
if let Some(person_id) = person_id {
@ -51,23 +52,27 @@ impl PerformCrud for GetPost {
}
let id = data.id;
let mut comments = blocking(context.pool(), move |conn| {
CommentQueryBuilder::create(conn)
.my_person_id(person_id)
.show_bot_accounts(show_bot_accounts)
.post_id(id)
.limit(9999)
.list()
})
.await??;
let mut comments = context
.conn()
.await?
.interact(move |conn| {
CommentQueryBuilder::create(conn)
.my_person_id(person_id)
.show_bot_accounts(show_bot_accounts)
.post_id(id)
.limit(9999)
.list()
})
.await??;
// 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)
})
.await?
.map_err(|e| ApiError::err("couldnt_find_community", e))?;
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))?;
// Blank out deleted or removed info for non-logged in users
if person_id.is_none() {
@ -86,10 +91,11 @@ impl PerformCrud for GetPost {
}
}
let moderators = blocking(context.pool(), move |conn| {
CommunityModeratorView::for_community(conn, community_id)
})
.await??;
let moderators = context
.conn()
.await?
.interact(move |conn| CommunityModeratorView::for_community(conn, community_id))
.await??;
let online = context
.chat_server()
@ -146,23 +152,26 @@ impl PerformCrud for GetPosts {
};
let saved_only = data.saved_only;
let mut posts = blocking(context.pool(), move |conn| {
PostQueryBuilder::create(conn)
.listing_type(listing_type)
.sort(sort)
.show_nsfw(show_nsfw)
.show_bot_accounts(show_bot_accounts)
.show_read_posts(show_read_posts)
.community_id(community_id)
.community_actor_id(community_actor_id)
.saved_only(saved_only)
.my_person_id(person_id)
.page(page)
.limit(limit)
.list()
})
.await?
.map_err(|e| ApiError::err("couldnt_get_posts", e))?;
let mut posts = context
.conn()
.await?
.interact(move |conn| {
PostQueryBuilder::create(conn)
.listing_type(listing_type)
.sort(sort)
.show_nsfw(show_nsfw)
.show_bot_accounts(show_bot_accounts)
.show_read_posts(show_read_posts)
.community_id(community_id)
.community_actor_id(community_actor_id)
.saved_only(saved_only)
.my_person_id(person_id)
.page(page)
.limit(limit)
.list()
})
.await?
.map_err(|e| ApiError::err("couldnt_get_posts", e))?;
// Blank out deleted or removed info for non-logged in users
if person_id.is_none() {

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,10 +93,11 @@ impl PerformCrud for EditPost {
};
let post_id = data.post_id;
let res = blocking(context.pool(), move |conn| {
Post::update(conn, post_id, &post_form)
})
.await?;
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,
Err(e) => {

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,10 +50,11 @@ impl PerformCrud for CreatePrivateMessage {
..PrivateMessageForm::default()
};
let inserted_private_message = match blocking(context.pool(), move |conn| {
PrivateMessage::create(conn, &private_message_form)
})
.await?
let inserted_private_message = match context
.conn()
.await?
.interact(move |conn| PrivateMessage::create(conn, &private_message_form))
.await?
{
Ok(private_message) => private_message,
Err(e) => {
@ -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,10 +78,9 @@ impl PerformCrud for CreatePrivateMessage {
inserted_private_message_id,
apub_id,
)?)
},
)
.await?
.map_err(|e| ApiError::err("couldnt_create_private_message", e))?;
})
.await?
.map_err(|e| ApiError::err("couldnt_create_private_message", e))?;
CreateOrUpdatePrivateMessage::send(
updated_private_message.into(),
@ -101,10 +101,11 @@ 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)
})
.await??;
let local_recipient = context
.conn()
.await?
.interact(move |conn| LocalUserView::read_person(conn, recipient_id))
.await??;
send_email_to_user(
&local_recipient,
"Private Message from",

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,10 +30,11 @@ 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)
})
.await??;
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,11 +42,12 @@ 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)
})
.await?
.map_err(|e| ApiError::err("couldnt_update_private_message", e))?;
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))?;
// Send the apub update
if data.deleted {

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,14 +26,17 @@ 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| {
PrivateMessageQueryBuilder::create(conn, person_id)
.page(page)
.limit(limit)
.unread_only(unread_only)
.list()
})
.await??;
let mut messages = context
.conn()
.await?
.interact(move |conn| {
PrivateMessageQueryBuilder::create(conn, person_id)
.page(page)
.limit(limit)
.unread_only(unread_only)
.list()
})
.await??;
// Blank out deleted or removed info
for pmv in messages

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,10 +27,11 @@ 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)
})
.await??;
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,11 +39,14 @@ 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| {
PrivateMessage::update_content(conn, private_message_id, &content_slurs_removed)
})
.await?
.map_err(|e| ApiError::err("couldnt_update_private_message", e))?;
let updated_private_message = context
.conn()
.await?
.interact(move |conn| {
PrivateMessage::update_content(conn, private_message_id, &content_slurs_removed)
})
.await?
.map_err(|e| ApiError::err("couldnt_update_private_message", e))?;
// Send the apub update
CreateOrUpdatePrivateMessage::send(

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,31 +114,35 @@ 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)
})
.await?
.map_err(|e| ApiError::err("system_err_login", e))?;
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)
})
.await?
.map_err(|e| ApiError::err("system_err_login", e))?;
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)
})
.await?
.map_err(|e| ApiError::err("system_err_login", e))?;
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)
})
.await?
.map_err(|e| ApiError::err("system_err_login", e))?;
let moderates = context
.conn()
.await?
.interact(move |conn| CommunityModeratorView::for_person(conn, person_id))
.await?
.map_err(|e| ApiError::err("system_err_login", e))?;
Some(MyUserInfo {
local_user_view,

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,10 +70,11 @@ 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())
})
.await??;
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
if !no_admins && context.settings().captcha.enabled {
@ -117,11 +123,12 @@ impl PerformCrud for Register {
};
// insert the person
let inserted_person = blocking(context.pool(), move |conn| {
Person::create(conn, &person_form)
})
.await?
.map_err(|e| ApiError::err("user_already_exists", e))?;
let inserted_person = context
.conn()
.await?
.interact(move |conn| Person::create(conn, &person_form))
.await?
.map_err(|e| ApiError::err("user_already_exists", e))?;
// Create the local user
// TODO some of these could probably use the DB defaults
@ -142,10 +149,11 @@ 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)
})
.await?
let inserted_local_user = match context
.conn()
.await?
.interact(move |conn| LocalUser::register(conn, &local_user_form))
.await?
{
Ok(lu) => lu,
Err(e) => {
@ -158,10 +166,11 @@ 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)
})
.await??;
context
.conn()
.await?
.interact(move |conn| Person::delete(conn, inserted_person.id))
.await??;
return Err(ApiError::err(err_type, e).into());
}
@ -171,10 +180,11 @@ 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))
})
.await?
let main_community = match context
.conn()
.await?
.interact(move |conn| Community::read(conn, CommunityId(2)))
.await?
{
Ok(c) => c,
Err(_e) => {
@ -196,10 +206,11 @@ 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)
})
.await??
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,21 +31,26 @@ 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)
})
.await??;
context
.conn()
.await?
.interact(move |conn| Person::delete_account(conn, person_id))
.await??;
Ok(LoginResponse {
jwt: data.auth.to_owned(),

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,55 +57,60 @@ 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)
})
.await??;
let person_view = context
.conn()
.await?
.interact(move |conn| PersonViewSafe::read(conn, person_details_id))
.await??;
let page = data.page;
let limit = data.limit;
let saved_only = data.saved_only;
let community_id = data.community_id;
let (posts, comments) = blocking(context.pool(), move |conn| {
let mut posts_query = PostQueryBuilder::create(conn)
.sort(sort)
.show_nsfw(show_nsfw)
.show_bot_accounts(show_bot_accounts)
.show_read_posts(show_read_posts)
.saved_only(saved_only)
.community_id(community_id)
.my_person_id(person_id)
.page(page)
.limit(limit);
let (posts, comments) = context
.conn()
.await?
.interact(move |conn| {
let mut posts_query = PostQueryBuilder::create(conn)
.sort(sort)
.show_nsfw(show_nsfw)
.show_bot_accounts(show_bot_accounts)
.show_read_posts(show_read_posts)
.saved_only(saved_only)
.community_id(community_id)
.my_person_id(person_id)
.page(page)
.limit(limit);
let mut comments_query = CommentQueryBuilder::create(conn)
.my_person_id(person_id)
.show_bot_accounts(show_bot_accounts)
.sort(sort)
.saved_only(saved_only)
.community_id(community_id)
.page(page)
.limit(limit);
let mut comments_query = CommentQueryBuilder::create(conn)
.my_person_id(person_id)
.show_bot_accounts(show_bot_accounts)
.sort(sort)
.saved_only(saved_only)
.community_id(community_id)
.page(page)
.limit(limit);
// If its saved only, you don't care what creator it was
// Or, if its not saved, then you only want it for that specific creator
if !saved_only.unwrap_or(false) {
posts_query = posts_query.creator_id(person_details_id);
comments_query = comments_query.creator_id(person_details_id);
}
// If its saved only, you don't care what creator it was
// Or, if its not saved, then you only want it for that specific creator
if !saved_only.unwrap_or(false) {
posts_query = posts_query.creator_id(person_details_id);
comments_query = comments_query.creator_id(person_details_id);
}
let posts = posts_query.list()?;
let comments = comments_query.list()?;
let posts = posts_query.list()?;
let comments = comments_query.list()?;
Ok((posts, comments)) as Result<_, LemmyError>
})
.await??;
Ok((posts, comments)) as Result<_, LemmyError>
})
.await??;
let moderates = blocking(context.pool(), move |conn| {
CommunityModeratorView::for_person(conn, person_details_id)
})
.await??;
let moderates = context
.conn()
.await?
.interact(move |conn| CommunityModeratorView::for_person(conn, person_details_id))
.await??;
// Return the jwt
Ok(GetPersonDetailsResponse {

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,13 +36,18 @@ 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)
})
.await??
.into();
let community: ApubCommunity = context
.conn()
.await?
.interact(move |conn| Community::read(conn, community_id))
.await??
.into();
let id = generate_activity_id(
kind.clone(),
@ -116,10 +121,11 @@ 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)
})
.await??;
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,19 +83,21 @@ 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)
})
.await??;
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)
})
.await??;
context
.conn()
.await?
.interact(move |conn| CommunityModerator::join(conn, &form))
.await??;
}
// TODO: send websocket notification about added mod
Ok(())

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,10 +95,11 @@ impl ActivityHandler for BlockUserFromCommunity {
person_id: blocked_user.id,
};
blocking(context.pool(), move |conn: &'_ _| {
CommunityPersonBan::ban(conn, &community_user_ban_form)
})
.await??;
context
.conn()
.await?
.interact(move |conn| CommunityPersonBan::ban(conn, &community_user_ban_form))
.await??;
// Also unsubscribe them from the community, if they are subscribed
let community_follower_form = CommunityFollowerForm {
@ -107,11 +107,12 @@ impl ActivityHandler for BlockUserFromCommunity {
person_id: blocked_user.id,
pending: false,
};
blocking(context.pool(), move |conn: &'_ _| {
CommunityFollower::unfollow(conn, &community_follower_form)
})
.await?
.ok();
context
.conn()
.await?
.interact(move |conn| CommunityFollower::unfollow(conn, &community_follower_form))
.await?
.ok();
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,10 +83,11 @@ impl ActivityHandler for RemoveMod {
community_id: community.id,
person_id: remove_mod.id,
};
blocking(context.pool(), move |conn| {
CommunityModerator::leave(conn, &form)
})
.await??;
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,15 +93,17 @@ impl ActivityHandler for Report {
original_post_body: post.body.clone(),
};
let report = blocking(context.pool(), move |conn| {
PostReport::report(conn, &report_form)
})
.await??;
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)
})
.await??;
let post_report_view = context
.conn()
.await?
.interact(move |conn| PostReportView::read(conn, report.id, actor.id))
.await??;
context.chat_server().do_send(SendModRoomMessage {
op: UserOperation::CreateCommentReport,
@ -118,15 +120,17 @@ impl ActivityHandler for Report {
reason: self.summary,
};
let report = blocking(context.pool(), move |conn| {
CommentReport::report(conn, &report_form)
})
.await??;
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)
})
.await??;
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;
context.chat_server().do_send(SendModRoomMessage {

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,10 +90,11 @@ impl ActivityHandler for UndoBlockUserFromCommunity {
person_id: blocked_user.id,
};
blocking(context.pool(), move |conn: &'_ _| {
CommunityPersonBan::unban(conn, &community_user_ban_form)
})
.await??;
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,10 +90,11 @@ impl ActivityHandler for UpdateCommunity {
banner: updated_community.banner,
..CommunityForm::default()
};
let updated_community = blocking(context.pool(), move |conn| {
Community::update(conn, community.id, &cf)
})
.await??;
let updated_community = context
.conn()
.await?
.interact(move |conn| Community::update(conn, community.id, &cf))
.await??;
send_community_ws_message(
updated_community.id,

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,14 +142,16 @@ pub(in crate::activities) async fn receive_remove_action(
reason,
expires: None,
};
blocking(context.pool(), move |conn| {
ModRemoveCommunity::create(conn, &form)
})
.await??;
let deleted_community = blocking(context.pool(), move |conn| {
Community::update_removed(conn, community.id, true)
})
.await??;
context
.conn()
.await?
.interact(move |conn| ModRemoveCommunity::create(conn, &form))
.await??;
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,14 +162,16 @@ pub(in crate::activities) async fn receive_remove_action(
removed: Some(true),
reason,
};
blocking(context.pool(), move |conn| {
ModRemovePost::create(conn, &form)
})
.await??;
let removed_post = blocking(context.pool(), move |conn| {
Post::update_removed(conn, post.id, true)
})
.await??;
context
.conn()
.await?
.interact(move |conn| ModRemovePost::create(conn, &form))
.await??;
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,14 +182,16 @@ pub(in crate::activities) async fn receive_remove_action(
removed: Some(true),
reason,
};
blocking(context.pool(), move |conn| {
ModRemoveComment::create(conn, &form)
})
.await??;
let removed_comment = blocking(context.pool(), move |conn| {
Comment::update_removed(conn, comment.id, true)
})
.await??;
context
.conn()
.await?
.interact(move |conn| ModRemoveComment::create(conn, &form))
.await??;
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,15 +209,20 @@ 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)
})
.await??;
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,10 +156,11 @@ 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)
})
.await??;
let community = context
.conn()
.await?
.interact(move |conn| Community::update_deleted(conn, community.id, deleted))
.await??;
send_community_ws_message(
community.id,
UserOperationCrud::DeleteCommunity,
@ -172,10 +172,11 @@ 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)
})
.await??;
let deleted_post = context
.conn()
.await?
.interact(move |conn| Post::update_deleted(conn, post.id, deleted))
.await??;
send_post_ws_message(
deleted_post.id,
UserOperationCrud::DeletePost,
@ -188,10 +189,11 @@ 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)
})
.await??;
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,
UserOperationCrud::DeleteComment,

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,24 +108,27 @@ 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)
})
.await??;
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)
})
.await??;
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)
})
.await??;
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,10 +65,11 @@ 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)
})
.await??;
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,10 +51,11 @@ impl FollowCommunity {
person_id: actor.id,
pending: true,
};
blocking(context.pool(), move |conn| {
CommunityFollower::follow(conn, &community_follower_form).ok()
})
.await?;
context
.conn()
.await?
.interact(move |conn| CommunityFollower::follow(conn, &community_follower_form).ok())
.await?;
let follow = FollowCommunity::new(actor, community, context)?;
let inbox = vec![community.inbox_url.clone().into()];
@ -93,10 +93,11 @@ 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()
})
.await?;
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,10 +71,11 @@ 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()
})
.await?;
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,10 +95,11 @@ 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)
})
.await?;
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,11 +53,12 @@ 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)
})
.await??
.into();
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?;
let id = create_or_update.id.clone();
let activity = AnnouncableActivities::CreateOrUpdatePost(create_or_update);

View file

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

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,10 +44,12 @@ 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))
.await??
.into();
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()];
send_lemmy_activity(context, &delete, &delete_id, actor, inbox, true).await
}
@ -74,10 +75,11 @@ 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)
})
.await??;
let deleted_private_message = context
.conn()
.await?
.interact(move |conn| PrivateMessage::update_deleted(conn, private_message.id, true))
.await??;
send_pm_ws_message(
deleted_private_message.id,

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,10 +27,12 @@ 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))
.await??
.into();
let recipient: ApubPerson = context
.conn()
.await?
.interact(move |conn| Person::read(conn, recipient_id))
.await??
.into();
let object = DeletePrivateMessage::new(actor, pm, context)?;
let id = generate_activity_id(
@ -75,10 +76,11 @@ 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)
})
.await??;
let deleted_private_message = context
.conn()
.await?
.interact(move |conn| PrivateMessage::update_deleted(conn, private_message.id, false))
.await??;
send_pm_ws_message(
deleted_private_message.id,

View file

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

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,11 +34,12 @@ impl UndoVote {
kind: VoteType,
context: &LemmyContext,
) -> Result<(), LemmyError> {
let community: ApubCommunity = blocking(context.pool(), move |conn| {
Community::read(conn, community_id)
})
.await??
.into();
let community: ApubCommunity = context
.conn()
.await?
.interact(move |conn| Community::read(conn, community_id))
.await??
.into();
let object = Vote::new(object, actor, &community, kind.clone(), context)?;
let id = generate_activity_id(

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,11 +52,12 @@ impl Vote {
kind: VoteType,
context: &LemmyContext,
) -> Result<(), LemmyError> {
let community = blocking(context.pool(), move |conn| {
Community::read(conn, community_id)
})
.await??
.into();
let community = context
.conn()
.await?
.interact(move |conn| Community::read(conn, community_id))
.await??
.into();
let vote = Vote::new(object, actor, &community, kind, context)?;
let vote_id = vote.id.clone();
@ -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,13 +31,15 @@ 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)
})
.await??;
let moderators = context
.conn()
.await?
.interact(move |conn| CommunityModeratorView::for_community(conn, cid))
.await??;
Ok(Some(ApubCommunityModerators { 0: moderators }))
} else {
Ok(None)
@ -81,11 +82,13 @@ 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)
})
.await??;
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 {
let mod_id = ObjectId::new(mod_user.moderator.actor_id.clone());
@ -94,10 +97,11 @@ 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)
})
.await??;
context
.conn()
.await?
.interact(move |conn| CommunityModerator::leave(conn, &community_moderator_form))
.await??;
}
}
@ -115,10 +119,11 @@ 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)
})
.await??;
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,16 +38,18 @@ 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)
})
.await??
.into_iter()
.map(Into::into)
.collect();
let post_list: Vec<ApubPost> = context
.conn()
.await?
.interact(move |conn| Post::list_for_community(conn, community_id))
.await??
.into_iter()
.map(Into::into)
.collect();
Ok(Some(ApubCommunityOutbox(post_list)))
} else {
Ok(None)
@ -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,11 +39,12 @@ 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)
})
.await??
.into();
let community: ApubCommunity = context
.conn()
.await?
.interact(move |conn| Community::read_from_name(conn, &info.community_name))
.await??
.into();
if !community.deleted {
let apub = community.into_apub(&**context).await?;
@ -97,10 +97,11 @@ 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)
})
.await??;
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,10 +112,11 @@ 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)
})
.await??;
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());
let outbox: ApubCommunityOutbox = id.dereference(&outbox_data, &mut 0).await?;
@ -125,11 +127,12 @@ 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)
})
.await??
.into();
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)?);
let outbox_data = CommunityContext(community, context.get_ref().clone());
let moderators: ApubCommunityModerators = id.dereference(&outbox_data, &mut 0).await?;

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,10 +164,11 @@ pub(crate) async fn get_activity(
info.id
))?
.into();
let activity = blocking(context.pool(), move |conn| {
Activity::read_from_apub_id(conn, &activity_id)
})
.await??;
let activity = context
.conn()
.await?
.interact(move |conn| Activity::read_from_apub_id(conn, &activity_id))
.await??;
let sensitive = activity.sensitive.unwrap_or(true);
if !activity.local || sensitive {
@ -179,14 +179,15 @@ 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)
})
.await?;
let existing = context
.conn()
.await?
.interact(move |conn| Activity::read_from_apub_id(conn, &activity_id))
.await?;
match existing {
Ok(_) => Ok(true),
Err(_) => Ok(false),

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,11 +31,12 @@ 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)
})
.await??
.into();
let person: ApubPerson = context
.conn()
.await?
.interact(move |conn| Person::find_by_name(conn, &user_name))
.await??
.into();
if !person.deleted {
let apub = person.into_apub(&context).await?;
@ -73,10 +73,11 @@ 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)
})
.await??;
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)
})
.await??;
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,34 +68,47 @@ impl ApubObject for ApubComment {
context: &LemmyContext,
) -> Result<Option<Self>, LemmyError> {
Ok(
blocking(context.pool(), move |conn| {
Comment::read_from_apub_id(conn, object_id)
})
.await??
.map(Into::into),
context
.conn()
.await?
.interact(move |conn| Comment::read_from_apub_id(conn, object_id))
.await??
.map(Into::into),
)
}
async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
if !self.deleted {
blocking(context.pool(), move |conn| {
Comment::update_deleted(conn, self.id, true)
})
.await??;
context
.conn()
.await?
.interact(move |conn| Comment::update_deleted(conn, self.id, true))
.await??;
}
Ok(())
}
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,10 +153,11 @@ 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)
})
.await??;
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(
&note.attributed_to,
@ -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,19 +59,21 @@ impl ApubObject for ApubCommunity {
context: &LemmyContext,
) -> Result<Option<Self>, LemmyError> {
Ok(
blocking(context.pool(), move |conn| {
Community::read_from_apub_id(conn, object_id)
})
.await??
.map(Into::into),
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)
})
.await??;
context
.conn()
.await?
.interact(move |conn| Community::update_deleted(conn, self.id, true))
.await??;
Ok(())
}
@ -143,10 +144,12 @@ 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))
.await??
.into();
let community: ApubCommunity = context
.conn()
.await?
.interact(move |conn| Community::upsert(conn, &form))
.await??
.into();
let outbox_data = CommunityContext(community.clone(), context.clone());
group
@ -197,10 +200,11 @@ impl ApubCommunity {
) -> Result<Vec<Url>, LemmyError> {
let id = self.id;
let follows = blocking(context.pool(), move |conn| {
CommunityFollowerView::for_community(conn, id)
})
.await??;
let follows = context
.conn()
.await?
.interact(move |conn| CommunityFollowerView::for_community(conn, id))
.await??;
let follower_inboxes: Vec<Url> = follows
.into_iter()
.filter(|f| !f.follower.local)
@ -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,19 +62,21 @@ impl ApubObject for ApubPerson {
context: &LemmyContext,
) -> Result<Option<Self>, LemmyError> {
Ok(
blocking(context.pool(), move |conn| {
DbPerson::read_from_apub_id(conn, object_id)
})
.await??
.map(Into::into),
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)
})
.await??;
context
.conn()
.await?
.interact(move |conn| DbPerson::update_deleted(conn, self.id, true))
.await??;
Ok(())
}
@ -171,10 +172,11 @@ 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)
})
.await??;
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,20 +67,22 @@ impl ApubObject for ApubPost {
context: &LemmyContext,
) -> Result<Option<Self>, LemmyError> {
Ok(
blocking(context.pool(), move |conn| {
Post::read_from_apub_id(conn, object_id)
})
.await??
.map(Into::into),
context
.conn()
.await?
.interact(move |conn| Post::read_from_apub_id(conn, object_id))
.await??
.map(Into::into),
)
}
async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
if !self.deleted {
blocking(context.pool(), move |conn| {
Post::update_deleted(conn, self.id, true)
})
.await??;
context
.conn()
.await?
.interact(move |conn| Post::update_deleted(conn, self.id, true))
.await??;
}
Ok(())
}
@ -89,12 +90,17 @@ 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)
})
.await??;
let community = context
.conn()
.await?
.interact(move |conn| Community::read(conn, community_id))
.await??;
let source = self.body.clone().map(|body| Source {
content: body,
@ -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,11 +57,12 @@ impl ApubObject for ApubPrivateMessage {
context: &LemmyContext,
) -> Result<Option<Self>, LemmyError> {
Ok(
blocking(context.pool(), move |conn| {
PrivateMessage::read_from_apub_id(conn, object_id)
})
.await??
.map(Into::into),
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,10 +153,11 @@ impl ApubObject for ApubPrivateMessage {
ap_id: Some(note.id.into()),
local: Some(false),
};
let pm = blocking(context.pool(), move |conn| {
PrivateMessage::upsert(conn, &form)
})
.await??;
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,10 +22,11 @@ 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)
})
.await??;
let community_followers = context
.conn()
.await?
.interact(move |conn| CommunityFollowerView::for_community(conn, community_id))
.await??;
Ok(GroupFollowers {
id: generate_followers_url(&community.actor_id)?.into(),

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,15 +79,22 @@ 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| {
PostQueryBuilder::create(conn)
.listing_type(listing_type)
.sort(sort_type)
.list()
})
.await??;
let posts = context
.conn()
.await?
.interact(move |conn| {
PostQueryBuilder::create(conn)
.listing_type(listing_type)
.sort(sort_type)
.list()
})
.await??;
let items = create_post_items(posts, &context.settings().get_protocol_and_hostname())?;
@ -136,20 +142,26 @@ 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 {
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::Front => get_feed_front(
conn,
&jwt_secret,
&sort_type,
&param,
&protocol_and_hostname,
),
RequestType::Inbox => get_feed_inbox(conn, &jwt_secret, &param, &protocol_and_hostname),
})
.await?
.map_err(ErrorBadRequest)?;
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::Front => get_feed_front(
conn,
&jwt_secret,
&sort_type,
&param,
&protocol_and_hostname,
),
RequestType::Inbox => get_feed_inbox(conn, &jwt_secret, &param, &protocol_and_hostname),
})
.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,21 +47,27 @@ 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?
.map_err(|_| ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))?
.actor_id
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?
.map_err(|_| ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))?
.actor_id
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 {
return Err(ErrorBadRequest(LemmyError::from(anyhow!("not_found"))));
};

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,10 +42,11 @@ 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)
})
.await??;
let post_view = context
.conn()
.await?
.interact(move |conn| PostView::read(conn, post_id, person_id))
.await??;
let res = PostResponse { post_view };
@ -78,10 +78,11 @@ 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)
})
.await??;
let mut view = context
.conn()
.await?
.interact(move |conn| CommentView::read(conn, comment_id, person_id))
.await??;
if view.comment.deleted || view.comment.removed {
view.comment = view.comment.blank_out_deleted_or_removed_info();
@ -114,10 +115,11 @@ 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)
})
.await??;
let community_view = context
.conn()
.await?
.interact(move |conn| CommunityView::read(conn, community_id, person_id))
.await??;
let res = CommunityResponse { community_view };
@ -141,10 +143,11 @@ 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)
})
.await??;
let mut view = context
.conn()
.await?
.interact(move |conn| PrivateMessageView::read(conn, private_message_id))
.await??;
// Blank out deleted or removed info
if view.private_message.deleted {
@ -158,10 +161,11 @@ 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)
})
.await??;
let local_recipient = context
.conn()
.await?
.interact(move |conn| LocalUserView::read_person(conn, recipient_id))
.await??;
context.chat_server().do_send(SendUserRoomMessage {
op,
response: res.clone(),
@ -190,10 +194,11 @@ 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)
})
.await?;
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
// At some point, make it so you can't tag the parent creator either
@ -208,11 +213,12 @@ 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)
})
.await?
.ok();
context
.conn()
.await?
.interact(move |conn| PersonMention::create(conn, &user_mention_form))
.await?
.ok();
// Send an email to those local users that have notifications on
if do_send_email {
@ -230,16 +236,20 @@ 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)
})
.await?;
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,10 +270,11 @@ 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)
})
.await?;
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| {
embedded_migrations::run(conn)?;
run_advanced_migrations(conn, &protocol_and_hostname)?;
Ok(()) as Result<(), LemmyError>
})
.await??;
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