Adding deadpool, v2. Fixes #1684

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

56
Cargo.lock generated
View file

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

View file

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

View file

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

View file

@ -1,7 +1,6 @@
use crate::Perform; use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
check_community_ban, check_community_ban,
comment::*, comment::*,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
@ -42,10 +41,11 @@ impl Perform for CreateCommentReport {
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let comment_id = data.comment_id; let comment_id = data.comment_id;
let comment_view = blocking(context.pool(), move |conn| { let comment_view = context
CommentView::read(conn, comment_id, None) .conn()
}) .await?
.await??; .interact(move |conn| CommentView::read(conn, comment_id, None))
.await??;
check_community_ban(person_id, comment_view.community.id, context.pool()).await?; check_community_ban(person_id, comment_view.community.id, context.pool()).await?;
@ -56,16 +56,18 @@ impl Perform for CreateCommentReport {
reason: data.reason.to_owned(), reason: data.reason.to_owned(),
}; };
let report = blocking(context.pool(), move |conn| { let report = context
CommentReport::report(conn, &report_form) .conn()
}) .await?
.await? .interact(move |conn| CommentReport::report(conn, &report_form))
.map_err(|e| ApiError::err("couldnt_create_report", e))?; .await?
.map_err(|e| ApiError::err("couldnt_create_report", e))?;
let comment_report_view = blocking(context.pool(), move |conn| { let comment_report_view = context
CommentReportView::read(conn, report.id, person_id) .conn()
}) .await?
.await??; .interact(move |conn| CommentReportView::read(conn, report.id, person_id))
.await??;
let res = CommentReportResponse { let res = CommentReportResponse {
comment_report_view, comment_report_view,
@ -107,32 +109,36 @@ impl Perform for ResolveCommentReport {
let report_id = data.report_id; let report_id = data.report_id;
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let report = blocking(context.pool(), move |conn| { let report = context
CommentReportView::read(conn, report_id, person_id) .conn()
}) .await?
.await??; .interact(move |conn| CommentReportView::read(conn, report_id, person_id))
.await??;
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
is_mod_or_admin(context.pool(), person_id, report.community.id).await?; is_mod_or_admin(context.pool(), person_id, report.community.id).await?;
let resolved = data.resolved; 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? .await?
.map_err(|e| ApiError::err("couldnt_resolve_report", e))?; .map_err(|e| ApiError::err("couldnt_resolve_report", e))?;
let report_id = data.report_id; let report_id = data.report_id;
let comment_report_view = blocking(context.pool(), move |conn| { let comment_report_view = context
CommentReportView::read(conn, report_id, person_id) .conn()
}) .await?
.await??; .interact(move |conn| CommentReportView::read(conn, report_id, person_id))
.await??;
let res = CommentReportResponse { let res = CommentReportResponse {
comment_report_view, comment_report_view,
@ -171,15 +177,18 @@ impl Perform for ListCommentReports {
let page = data.page; let page = data.page;
let limit = data.limit; let limit = data.limit;
let comment_reports = blocking(context.pool(), move |conn| { let comment_reports = context
CommentReportQueryBuilder::create(conn, person_id, admin) .conn()
.community_id(community_id) .await?
.unresolved_only(unresolved_only) .interact(move |conn| {
.page(page) CommentReportQueryBuilder::create(conn, person_id, admin)
.limit(limit) .community_id(community_id)
.list() .unresolved_only(unresolved_only)
}) .page(page)
.await??; .limit(limit)
.list()
})
.await??;
let res = ListCommentReportsResponse { comment_reports }; let res = ListCommentReportsResponse { comment_reports };

View file

@ -2,7 +2,6 @@ use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use anyhow::Context; use anyhow::Context;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
check_community_ban, check_community_ban,
check_community_deleted_or_removed, check_community_deleted_or_removed,
community::*, community::*,
@ -71,11 +70,12 @@ impl Perform for FollowCommunity {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let community_id = data.community_id; let community_id = data.community_id;
let community: ApubCommunity = blocking(context.pool(), move |conn| { let community: ApubCommunity = context
Community::read(conn, community_id) .conn()
}) .await?
.await?? .interact(move |conn| Community::read(conn, community_id))
.into(); .await??
.into();
let community_follower_form = CommunityFollowerForm { let community_follower_form = CommunityFollowerForm {
community_id: data.community_id, community_id: data.community_id,
person_id: local_user_view.person.id, person_id: local_user_view.person.id,
@ -87,14 +87,17 @@ impl Perform for FollowCommunity {
check_community_ban(local_user_view.person.id, community_id, context.pool()).await?; check_community_ban(local_user_view.person.id, community_id, context.pool()).await?;
check_community_deleted_or_removed(community_id, context.pool()).await?; check_community_deleted_or_removed(community_id, context.pool()).await?;
let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form); context
blocking(context.pool(), follow) .conn()
.await?
.interact(move |conn| CommunityFollower::follow(conn, &community_follower_form))
.await? .await?
.map_err(|e| ApiError::err("community_follower_already_exists", e))?; .map_err(|e| ApiError::err("community_follower_already_exists", e))?;
} else { } else {
let unfollow = context
move |conn: &'_ _| CommunityFollower::unfollow(conn, &community_follower_form); .conn()
blocking(context.pool(), unfollow) .await?
.interact(move |conn| CommunityFollower::unfollow(conn, &community_follower_form))
.await? .await?
.map_err(|e| ApiError::err("community_follower_already_exists", e))?; .map_err(|e| ApiError::err("community_follower_already_exists", e))?;
} }
@ -106,18 +109,21 @@ impl Perform for FollowCommunity {
} else { } else {
UndoFollowCommunity::send(&local_user_view.person.clone().into(), &community, context) UndoFollowCommunity::send(&local_user_view.person.clone().into(), &community, context)
.await?; .await?;
let unfollow = move |conn: &'_ _| CommunityFollower::unfollow(conn, &community_follower_form); context
blocking(context.pool(), unfollow) .conn()
.await?
.interact(move |conn| CommunityFollower::unfollow(conn, &community_follower_form))
.await? .await?
.map_err(|e| ApiError::err("community_follower_already_exists", e))?; .map_err(|e| ApiError::err("community_follower_already_exists", e))?;
} }
let community_id = data.community_id; let community_id = data.community_id;
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let mut community_view = blocking(context.pool(), move |conn| { let mut community_view = context
CommunityView::read(conn, community_id, Some(person_id)) .conn()
}) .await?
.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 // TODO: this needs to return a "pending" state, until Accept is received from the remote server
// For now, just assume that remote follows are accepted. // For now, just assume that remote follows are accepted.
@ -151,8 +157,10 @@ impl Perform for BlockCommunity {
}; };
if data.block { if data.block {
let block = move |conn: &'_ _| CommunityBlock::block(conn, &community_block_form); context
blocking(context.pool(), block) .conn()
.await?
.interact(move |conn| CommunityBlock::block(conn, &community_block_form))
.await? .await?
.map_err(|e| ApiError::err("community_block_already_exists", e))?; .map_err(|e| ApiError::err("community_block_already_exists", e))?;
@ -162,27 +170,32 @@ impl Perform for BlockCommunity {
person_id, person_id,
pending: false, pending: false,
}; };
blocking(context.pool(), move |conn: &'_ _| { context
CommunityFollower::unfollow(conn, &community_follower_form) .conn()
}) .await?
.await? .interact(move |conn| CommunityFollower::unfollow(conn, &community_follower_form))
.ok(); .await?
let community = blocking(context.pool(), move |conn| { .ok();
Community::read(conn, community_id) let community = context
}) .conn()
.await??; .await?
.interact(move |conn| Community::read(conn, community_id))
.await??;
UndoFollowCommunity::send(&local_user_view.person.into(), &community.into(), context).await?; UndoFollowCommunity::send(&local_user_view.person.into(), &community.into(), context).await?;
} else { } else {
let unblock = move |conn: &'_ _| CommunityBlock::unblock(conn, &community_block_form); context
blocking(context.pool(), unblock) .conn()
.await?
.interact(move |conn| CommunityBlock::unblock(conn, &community_block_form))
.await? .await?
.map_err(|e| ApiError::err("community_block_already_exists", e))?; .map_err(|e| ApiError::err("community_block_already_exists", e))?;
} }
let community_view = blocking(context.pool(), move |conn| { let community_view = context
CommunityView::read(conn, community_id, Some(person_id)) .conn()
}) .await?
.await??; .interact(move |conn| CommunityView::read(conn, community_id, Some(person_id)))
.await??;
Ok(BlockCommunityResponse { Ok(BlockCommunityResponse {
blocked: data.block, blocked: data.block,
@ -215,20 +228,24 @@ impl Perform for BanFromCommunity {
person_id: data.person_id, person_id: data.person_id,
}; };
let community: ApubCommunity = blocking(context.pool(), move |conn: &'_ _| { let community: ApubCommunity = context
Community::read(conn, community_id) .conn()
}) .await?
.await?? .interact(move |conn| Community::read(conn, community_id))
.into(); .await??
let banned_person: ApubPerson = blocking(context.pool(), move |conn: &'_ _| { .into();
Person::read(conn, banned_person_id) let banned_person: ApubPerson = context
}) .conn()
.await?? .await?
.into(); .interact(move |conn| Person::read(conn, banned_person_id))
.await??
.into();
if data.ban { if data.ban {
let ban = move |conn: &'_ _| CommunityPersonBan::ban(conn, &community_user_ban_form); context
blocking(context.pool(), ban) .conn()
.await?
.interact(move |conn| CommunityPersonBan::ban(conn, &community_user_ban_form))
.await? .await?
.map_err(|e| ApiError::err("community_user_already_banned", e))?; .map_err(|e| ApiError::err("community_user_already_banned", e))?;
@ -238,11 +255,12 @@ impl Perform for BanFromCommunity {
person_id: banned_person_id, person_id: banned_person_id,
pending: false, pending: false,
}; };
blocking(context.pool(), move |conn: &'_ _| { context
CommunityFollower::unfollow(conn, &community_follower_form) .conn()
}) .await?
.await? .interact(move |conn| CommunityFollower::unfollow(conn, &community_follower_form))
.ok(); .await?
.ok();
BlockUserFromCommunity::send( BlockUserFromCommunity::send(
&community, &community,
@ -252,8 +270,10 @@ impl Perform for BanFromCommunity {
) )
.await?; .await?;
} else { } else {
let unban = move |conn: &'_ _| CommunityPersonBan::unban(conn, &community_user_ban_form); context
blocking(context.pool(), unban) .conn()
.await?
.interact(move |conn| CommunityPersonBan::unban(conn, &community_user_ban_form))
.await? .await?
.map_err(|e| ApiError::err("community_user_already_banned", e))?; .map_err(|e| ApiError::err("community_user_already_banned", e))?;
UndoBlockUserFromCommunity::send( UndoBlockUserFromCommunity::send(
@ -268,28 +288,35 @@ impl Perform for BanFromCommunity {
// Remove/Restore their data if that's desired // Remove/Restore their data if that's desired
if data.remove_data.unwrap_or(false) { if data.remove_data.unwrap_or(false) {
// Posts // Posts
blocking(context.pool(), move |conn: &'_ _| { context
Post::update_removed_for_creator(conn, banned_person_id, Some(community_id), true) .conn()
}) .await?
.await??; .interact(move |conn| {
Post::update_removed_for_creator(conn, banned_person_id, Some(community_id), true)
})
.await??;
// Comments // Comments
// TODO Diesel doesn't allow updates with joins, so this has to be a loop // TODO Diesel doesn't allow updates with joins, so this has to be a loop
let comments = blocking(context.pool(), move |conn| { let comments = context
CommentQueryBuilder::create(conn) .conn()
.creator_id(banned_person_id) .await?
.community_id(community_id) .interact(move |conn| {
.limit(std::i64::MAX) CommentQueryBuilder::create(conn)
.list() .creator_id(banned_person_id)
}) .community_id(community_id)
.await??; .limit(std::i64::MAX)
.list()
})
.await??;
for comment_view in &comments { for comment_view in &comments {
let comment_id = comment_view.comment.id; let comment_id = comment_view.comment.id;
blocking(context.pool(), move |conn: &'_ _| { context
Comment::update_removed(conn, comment_id, true) .conn()
}) .await?
.await??; .interact(move |conn| Comment::update_removed(conn, comment_id, true))
.await??;
} }
} }
@ -305,16 +332,18 @@ impl Perform for BanFromCommunity {
banned: Some(data.ban), banned: Some(data.ban),
expires, expires,
}; };
blocking(context.pool(), move |conn| { context
ModBanFromCommunity::create(conn, &form) .conn()
}) .await?
.await??; .interact(move |conn| ModBanFromCommunity::create(conn, &form))
.await??;
let person_id = data.person_id; let person_id = data.person_id;
let person_view = blocking(context.pool(), move |conn| { let person_view = context
PersonViewSafe::read(conn, person_id) .conn()
}) .await?
.await??; .interact(move |conn| PersonViewSafe::read(conn, person_id))
.await??;
let res = BanFromCommunityResponse { let res = BanFromCommunityResponse {
person_view, person_view,
@ -356,13 +385,17 @@ impl Perform for AddModToCommunity {
person_id: data.person_id, person_id: data.person_id,
}; };
if data.added { if data.added {
let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form); context
blocking(context.pool(), join) .conn()
.await?
.interact(move |conn| CommunityModerator::join(conn, &community_moderator_form))
.await? .await?
.map_err(|e| ApiError::err("community_moderator_already_exists", e))?; .map_err(|e| ApiError::err("community_moderator_already_exists", e))?;
} else { } else {
let leave = move |conn: &'_ _| CommunityModerator::leave(conn, &community_moderator_form); context
blocking(context.pool(), leave) .conn()
.await?
.interact(move |conn| CommunityModerator::leave(conn, &community_moderator_form))
.await? .await?
.map_err(|e| ApiError::err("community_moderator_already_exists", e))?; .map_err(|e| ApiError::err("community_moderator_already_exists", e))?;
} }
@ -374,23 +407,26 @@ impl Perform for AddModToCommunity {
community_id: data.community_id, community_id: data.community_id,
removed: Some(!data.added), removed: Some(!data.added),
}; };
blocking(context.pool(), move |conn| { context
ModAddCommunity::create(conn, &form) .conn()
}) .await?
.await??; .interact(move |conn| ModAddCommunity::create(conn, &form))
.await??;
// Send to federated instances // Send to federated instances
let updated_mod_id = data.person_id; let updated_mod_id = data.person_id;
let updated_mod: ApubPerson = blocking(context.pool(), move |conn| { let updated_mod: ApubPerson = context
Person::read(conn, updated_mod_id) .conn()
}) .await?
.await?? .interact(move |conn| Person::read(conn, updated_mod_id))
.into(); .await??
let community: ApubCommunity = blocking(context.pool(), move |conn| { .into();
Community::read(conn, community_id) let community: ApubCommunity = context
}) .conn()
.await?? .await?
.into(); .interact(move |conn| Community::read(conn, community_id))
.await??
.into();
if data.added { if data.added {
AddMod::send( AddMod::send(
&community, &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 // Note: in case a remote mod is added, this returns the old moderators list, it will only get
// updated once we receive an activity from the community (like `Announce/Add/Moderator`) // updated once we receive an activity from the community (like `Announce/Add/Moderator`)
let community_id = data.community_id; let community_id = data.community_id;
let moderators = blocking(context.pool(), move |conn| { let moderators = context
CommunityModeratorView::for_community(conn, community_id) .conn()
}) .await?
.await??; .interact(move |conn| CommunityModeratorView::for_community(conn, community_id))
.await??;
let res = AddModToCommunityResponse { moderators }; let res = AddModToCommunityResponse { moderators };
context.chat_server().do_send(SendCommunityRoomMessage { context.chat_server().do_send(SendCommunityRoomMessage {
@ -443,12 +480,17 @@ impl Perform for TransferCommunity {
let local_user_view = let local_user_view =
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let site_creator_id = blocking(context.pool(), move |conn| { let site_creator_id = context
Site::read(conn, 1).map(|s| s.creator_id) .conn()
}) .await?
.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 // Making sure the site creator, if an admin, is at the top
let creator_index = admins let creator_index = admins
@ -460,10 +502,11 @@ impl Perform for TransferCommunity {
// Fetch the community mods // Fetch the community mods
let community_id = data.community_id; let community_id = data.community_id;
let mut community_mods = blocking(context.pool(), move |conn| { let mut community_mods = context
CommunityModeratorView::for_community(conn, community_id) .conn()
}) .await?
.await??; .interact(move |conn| CommunityModeratorView::for_community(conn, community_id))
.await??;
// Make sure transferrer is either the top community mod, or an admin // Make sure transferrer is either the top community mod, or an admin
if local_user_view.person.id != community_mods[0].moderator.id if local_user_view.person.id != community_mods[0].moderator.id
@ -486,10 +529,11 @@ impl Perform for TransferCommunity {
// Delete all the mods // Delete all the mods
let community_id = data.community_id; let community_id = data.community_id;
blocking(context.pool(), move |conn| { context
CommunityModerator::delete_for_community(conn, community_id) .conn()
}) .await?
.await??; .interact(move |conn| CommunityModerator::delete_for_community(conn, community_id))
.await??;
// TODO: this should probably be a bulk operation // TODO: this should probably be a bulk operation
// Re-add the mods, in the new order // Re-add the mods, in the new order
@ -499,8 +543,10 @@ impl Perform for TransferCommunity {
person_id: cmod.moderator.id, person_id: cmod.moderator.id,
}; };
let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form); context
blocking(context.pool(), join) .conn()
.await?
.interact(move |conn| CommunityModerator::join(conn, &community_moderator_form))
.await? .await?
.map_err(|e| ApiError::err("community_moderator_already_exists", e))?; .map_err(|e| ApiError::err("community_moderator_already_exists", e))?;
} }
@ -512,25 +558,28 @@ impl Perform for TransferCommunity {
community_id: data.community_id, community_id: data.community_id,
removed: Some(false), removed: Some(false),
}; };
blocking(context.pool(), move |conn| { context
ModTransferCommunity::create(conn, &form) .conn()
}) .await?
.await??; .interact(move |conn| ModTransferCommunity::create(conn, &form))
.await??;
let community_id = data.community_id; let community_id = data.community_id;
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let community_view = blocking(context.pool(), move |conn| { let community_view = context
CommunityView::read(conn, community_id, Some(person_id)) .conn()
}) .await?
.await? .interact(move |conn| CommunityView::read(conn, community_id, Some(person_id)))
.map_err(|e| ApiError::err("couldnt_find_community", e))?; .await?
.map_err(|e| ApiError::err("couldnt_find_community", e))?;
let community_id = data.community_id; let community_id = data.community_id;
let moderators = blocking(context.pool(), move |conn| { let moderators = context
CommunityModeratorView::for_community(conn, community_id) .conn()
}) .await?
.await? .interact(move |conn| CommunityModeratorView::for_community(conn, community_id))
.map_err(|e| ApiError::err("couldnt_find_community", e))?; .await?
.map_err(|e| ApiError::err("couldnt_find_community", e))?;
// Return the jwt // Return the jwt
Ok(GetCommunityResponse { Ok(GetCommunityResponse {

View file

@ -4,13 +4,7 @@ use anyhow::Context;
use bcrypt::verify; use bcrypt::verify;
use captcha::{gen, Difficulty}; use captcha::{gen, Difficulty};
use chrono::Duration; use chrono::Duration;
use lemmy_api_common::{ use lemmy_api_common::{get_local_user_view_from_jwt, is_admin, password_length_check, person::*};
blocking,
get_local_user_view_from_jwt,
is_admin,
password_length_check,
person::*,
};
use lemmy_db_schema::{ use lemmy_db_schema::{
diesel_option_overwrite, diesel_option_overwrite,
diesel_option_overwrite_to_url, diesel_option_overwrite_to_url,
@ -72,11 +66,12 @@ impl Perform for Login {
// Fetch that username / email // Fetch that username / email
let username_or_email = data.username_or_email.clone(); let username_or_email = data.username_or_email.clone();
let local_user_view = blocking(context.pool(), move |conn| { let local_user_view = context
LocalUserView::find_by_email_or_name(conn, &username_or_email) .conn()
}) .await?
.await? .interact(move |conn| LocalUserView::find_by_email_or_name(conn, &username_or_email))
.map_err(|e| ApiError::err("couldnt_find_that_username_or_email", e))?; .await?
.map_err(|e| ApiError::err("couldnt_find_that_username_or_email", e))?;
// Verify the password // Verify the password
let valid: bool = verify( let valid: bool = verify(
@ -214,11 +209,12 @@ impl Perform for SaveUserSettings {
bot_account, bot_account,
}; };
blocking(context.pool(), move |conn| { context
Person::update(conn, person_id, &person_form) .conn()
}) .await?
.await? .interact(move |conn| Person::update(conn, person_id, &person_form))
.map_err(|e| ApiError::err("user_already_exists", e))?; .await?
.map_err(|e| ApiError::err("user_already_exists", e))?;
let local_user_form = LocalUserForm { let local_user_form = LocalUserForm {
person_id, person_id,
@ -237,10 +233,11 @@ impl Perform for SaveUserSettings {
send_notifications_to_email: data.send_notifications_to_email, send_notifications_to_email: data.send_notifications_to_email,
}; };
let local_user_res = blocking(context.pool(), move |conn| { let local_user_res = context
LocalUser::update(conn, local_user_id, &local_user_form) .conn()
}) .await?
.await?; .interact(move |conn| LocalUser::update(conn, local_user_id, &local_user_form))
.await?;
let updated_local_user = match local_user_res { let updated_local_user = match local_user_res {
Ok(u) => u, Ok(u) => u,
Err(e) => { Err(e) => {
@ -299,10 +296,11 @@ impl Perform for ChangePassword {
let local_user_id = local_user_view.local_user.id; let local_user_id = local_user_view.local_user.id;
let new_password = data.new_password.to_owned(); let new_password = data.new_password.to_owned();
let updated_local_user = blocking(context.pool(), move |conn| { let updated_local_user = context
LocalUser::update_password(conn, local_user_id, &new_password) .conn()
}) .await?
.await??; .interact(move |conn| LocalUser::update_password(conn, local_user_id, &new_password))
.await??;
// Return the jwt // Return the jwt
Ok(LoginResponse { Ok(LoginResponse {
@ -333,11 +331,12 @@ impl Perform for AddAdmin {
let added = data.added; let added = data.added;
let added_person_id = data.person_id; let added_person_id = data.person_id;
let added_admin = blocking(context.pool(), move |conn| { let added_admin = context
Person::add_admin(conn, added_person_id, added) .conn()
}) .await?
.await? .interact(move |conn| Person::add_admin(conn, added_person_id, added))
.map_err(|e| ApiError::err("couldnt_update_user", e))?; .await?
.map_err(|e| ApiError::err("couldnt_update_user", e))?;
// Mod tables // Mod tables
let form = ModAddForm { let form = ModAddForm {
@ -346,14 +345,23 @@ impl Perform for AddAdmin {
removed: Some(!data.added), removed: Some(!data.added),
}; };
blocking(context.pool(), move |conn| ModAdd::create(conn, &form)).await??; context
.conn()
.await?
.interact(move |conn| ModAdd::create(conn, &form))
.await??;
let site_creator_id = blocking(context.pool(), move |conn| { let site_creator_id = context
Site::read(conn, 1).map(|s| s.creator_id) .conn()
}) .await?
.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 let creator_index = admins
.iter() .iter()
.position(|r| r.person.id == site_creator_id) .position(|r| r.person.id == site_creator_id)
@ -391,26 +399,30 @@ impl Perform for BanPerson {
let ban = data.ban; let ban = data.ban;
let banned_person_id = data.person_id; let banned_person_id = data.person_id;
let ban_person = move |conn: &'_ _| Person::ban_person(conn, banned_person_id, ban); context
blocking(context.pool(), ban_person) .conn()
.await?
.interact(move |conn| Person::ban_person(conn, banned_person_id, ban))
.await? .await?
.map_err(|e| ApiError::err("couldnt_update_user", e))?; .map_err(|e| ApiError::err("couldnt_update_user", e))?;
// Remove their data if that's desired // Remove their data if that's desired
if data.remove_data.unwrap_or(false) { if data.remove_data.unwrap_or(false) {
// Posts // Posts
blocking(context.pool(), move |conn: &'_ _| { context
Post::update_removed_for_creator(conn, banned_person_id, None, true) .conn()
}) .await?
.await??; .interact(move |conn| Post::update_removed_for_creator(conn, banned_person_id, None, true))
.await??;
// Communities // Communities
// Remove all communities where they're the top mod // Remove all communities where they're the top mod
// for now, remove the communities manually // for now, remove the communities manually
let first_mod_communities = blocking(context.pool(), move |conn: &'_ _| { let first_mod_communities = context
CommunityModeratorView::get_community_first_mods(conn) .conn()
}) .await?
.await??; .interact(move |conn| CommunityModeratorView::get_community_first_mods(conn))
.await??;
// Filter to only this banned users top communities // Filter to only this banned users top communities
let banned_user_first_communities: Vec<CommunityModeratorView> = first_mod_communities let banned_user_first_communities: Vec<CommunityModeratorView> = first_mod_communities
@ -419,17 +431,21 @@ impl Perform for BanPerson {
.collect(); .collect();
for first_mod_community in banned_user_first_communities { for first_mod_community in banned_user_first_communities {
blocking(context.pool(), move |conn: &'_ _| { context
Community::update_removed(conn, first_mod_community.community.id, true) .conn()
}) .await?
.await??; .interact(move |conn| {
Community::update_removed(conn, first_mod_community.community.id, true)
})
.await??;
} }
// Comments // Comments
blocking(context.pool(), move |conn: &'_ _| { context
Comment::update_removed_for_creator(conn, banned_person_id, true) .conn()
}) .await?
.await??; .interact(move |conn| Comment::update_removed_for_creator(conn, banned_person_id, true))
.await??;
} }
// Mod tables // Mod tables
@ -443,13 +459,18 @@ impl Perform for BanPerson {
expires, expires,
}; };
blocking(context.pool(), move |conn| ModBan::create(conn, &form)).await??; context
.conn()
.await?
.interact(move |conn| ModBan::create(conn, &form))
.await??;
let person_id = data.person_id; let person_id = data.person_id;
let person_view = blocking(context.pool(), move |conn| { let person_view = context
PersonViewSafe::read(conn, person_id) .conn()
}) .await?
.await??; .interact(move |conn| PersonViewSafe::read(conn, person_id))
.await??;
let res = BanPersonResponse { let res = BanPersonResponse {
person_view, person_view,
@ -493,23 +514,28 @@ impl Perform for BlockPerson {
}; };
if data.block { if data.block {
let block = move |conn: &'_ _| PersonBlock::block(conn, &person_block_form); context
blocking(context.pool(), block) .conn()
.await?
.interact(move |conn| PersonBlock::block(conn, &person_block_form))
.await? .await?
.map_err(|e| ApiError::err("person_block_already_exists", e))?; .map_err(|e| ApiError::err("person_block_already_exists", e))?;
} else { } else {
let unblock = move |conn: &'_ _| PersonBlock::unblock(conn, &person_block_form); context
blocking(context.pool(), unblock) .conn()
.await?
.interact(move |conn| PersonBlock::unblock(conn, &person_block_form))
.await? .await?
.map_err(|e| ApiError::err("person_block_already_exists", e))?; .map_err(|e| ApiError::err("person_block_already_exists", e))?;
} }
// TODO does any federated stuff need to be done here? // TODO does any federated stuff need to be done here?
let person_view = blocking(context.pool(), move |conn| { let person_view = context
PersonViewSafe::read(conn, target_id) .conn()
}) .await?
.await??; .interact(move |conn| PersonViewSafe::read(conn, target_id))
.await??;
let res = BlockPersonResponse { let res = BlockPersonResponse {
person_view, person_view,
@ -541,18 +567,21 @@ impl Perform for GetReplies {
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let show_bot_accounts = local_user_view.local_user.show_bot_accounts; let show_bot_accounts = local_user_view.local_user.show_bot_accounts;
let replies = blocking(context.pool(), move |conn| { let replies = context
CommentQueryBuilder::create(conn) .conn()
.sort(sort) .await?
.unread_only(unread_only) .interact(move |conn| {
.recipient_id(person_id) CommentQueryBuilder::create(conn)
.show_bot_accounts(show_bot_accounts) .sort(sort)
.my_person_id(person_id) .unread_only(unread_only)
.page(page) .recipient_id(person_id)
.limit(limit) .show_bot_accounts(show_bot_accounts)
.list() .my_person_id(person_id)
}) .page(page)
.await??; .limit(limit)
.list()
})
.await??;
Ok(GetRepliesResponse { replies }) Ok(GetRepliesResponse { replies })
} }
@ -577,17 +606,20 @@ impl Perform for GetPersonMentions {
let limit = data.limit; let limit = data.limit;
let unread_only = data.unread_only; let unread_only = data.unread_only;
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let mentions = blocking(context.pool(), move |conn| { let mentions = context
PersonMentionQueryBuilder::create(conn) .conn()
.recipient_id(person_id) .await?
.my_person_id(person_id) .interact(move |conn| {
.sort(sort) PersonMentionQueryBuilder::create(conn)
.unread_only(unread_only) .recipient_id(person_id)
.page(page) .my_person_id(person_id)
.limit(limit) .sort(sort)
.list() .unread_only(unread_only)
}) .page(page)
.await??; .limit(limit)
.list()
})
.await??;
Ok(GetPersonMentionsResponse { mentions }) Ok(GetPersonMentionsResponse { mentions })
} }
@ -607,10 +639,11 @@ impl Perform for MarkPersonMentionAsRead {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let person_mention_id = data.person_mention_id; let person_mention_id = data.person_mention_id;
let read_person_mention = blocking(context.pool(), move |conn| { let read_person_mention = context
PersonMention::read(conn, person_mention_id) .conn()
}) .await?
.await??; .interact(move |conn| PersonMention::read(conn, person_mention_id))
.await??;
if local_user_view.person.id != read_person_mention.recipient_id { if local_user_view.person.id != read_person_mention.recipient_id {
return Err(ApiError::err_plain("couldnt_update_comment").into()); 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 person_mention_id = read_person_mention.id;
let read = data.read; let read = data.read;
let update_mention =
move |conn: &'_ _| PersonMention::update_read(conn, person_mention_id, read); context
blocking(context.pool(), update_mention) .conn()
.await?
.interact(move |conn| PersonMention::update_read(conn, person_mention_id, read))
.await? .await?
.map_err(|e| ApiError::err("couldnt_update_comment", e))?; .map_err(|e| ApiError::err("couldnt_update_comment", e))?;
let person_mention_id = read_person_mention.id; let person_mention_id = read_person_mention.id;
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let person_mention_view = blocking(context.pool(), move |conn| { let person_mention_view = context
PersonMentionView::read(conn, person_mention_id, Some(person_id)) .conn()
}) .await?
.await??; .interact(move |conn| PersonMentionView::read(conn, person_mention_id, Some(person_id)))
.await??;
Ok(PersonMentionResponse { Ok(PersonMentionResponse {
person_mention_view, person_mention_view,
@ -651,38 +687,46 @@ impl Perform for MarkAllAsRead {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let replies = blocking(context.pool(), move |conn| { let replies = context
CommentQueryBuilder::create(conn) .conn()
.my_person_id(person_id) .await?
.recipient_id(person_id) .interact(move |conn| {
.unread_only(true) CommentQueryBuilder::create(conn)
.page(1) .my_person_id(person_id)
.limit(999) .recipient_id(person_id)
.list() .unread_only(true)
}) .page(1)
.await??; .limit(999)
.list()
})
.await??;
// TODO: this should probably be a bulk operation // TODO: this should probably be a bulk operation
// Not easy to do as a bulk operation, // Not easy to do as a bulk operation,
// because recipient_id isn't in the comment table // because recipient_id isn't in the comment table
for comment_view in &replies { for comment_view in &replies {
let reply_id = comment_view.comment.id; let reply_id = comment_view.comment.id;
let mark_as_read = move |conn: &'_ _| Comment::update_read(conn, reply_id, true); context
blocking(context.pool(), mark_as_read) .conn()
.await?
.interact(move |conn| Comment::update_read(conn, reply_id, true))
.await? .await?
.map_err(|e| ApiError::err("couldnt_update_comment", e))?; .map_err(|e| ApiError::err("couldnt_update_comment", e))?;
} }
// Mark all user mentions as read // Mark all user mentions as read
let update_person_mentions = context
move |conn: &'_ _| PersonMention::mark_all_as_read(conn, person_id); .conn()
blocking(context.pool(), update_person_mentions) .await?
.interact(move |conn| PersonMention::mark_all_as_read(conn, person_id))
.await? .await?
.map_err(|e| ApiError::err("couldnt_update_comment", e))?; .map_err(|e| ApiError::err("couldnt_update_comment", e))?;
// Mark all private_messages as read // Mark all private_messages as read
let update_pm = move |conn: &'_ _| PrivateMessage::mark_all_as_read(conn, person_id); context
blocking(context.pool(), update_pm) .conn()
.await?
.interact(move |conn| PrivateMessage::mark_all_as_read(conn, person_id))
.await? .await?
.map_err(|e| ApiError::err("couldnt_update_private_message", e))?; .map_err(|e| ApiError::err("couldnt_update_private_message", e))?;
@ -703,11 +747,12 @@ impl Perform for PasswordReset {
// Fetch that email // Fetch that email
let email = data.email.clone(); let email = data.email.clone();
let local_user_view = blocking(context.pool(), move |conn| { let local_user_view = context
LocalUserView::find_by_email(conn, &email) .conn()
}) .await?
.await? .interact(move |conn| LocalUserView::find_by_email(conn, &email))
.map_err(|e| ApiError::err("couldnt_find_that_username_or_email", e))?; .await?
.map_err(|e| ApiError::err("couldnt_find_that_username_or_email", e))?;
// Generate a random token // Generate a random token
let token = generate_random_string(); let token = generate_random_string();
@ -715,10 +760,11 @@ impl Perform for PasswordReset {
// Insert the row // Insert the row
let token2 = token.clone(); let token2 = token.clone();
let local_user_id = local_user_view.local_user.id; let local_user_id = local_user_view.local_user.id;
blocking(context.pool(), move |conn| { context
PasswordResetRequest::create_token(conn, local_user_id, &token2) .conn()
}) .await?
.await??; .interact(move |conn| PasswordResetRequest::create_token(conn, local_user_id, &token2))
.await??;
// Email the pure token to the user. // Email the pure token to the user.
// TODO no i18n support here. // TODO no i18n support here.
@ -752,10 +798,13 @@ impl Perform for PasswordChange {
// Fetch the user_id from the token // Fetch the user_id from the token
let token = data.token.clone(); let token = data.token.clone();
let local_user_id = blocking(context.pool(), move |conn| { let local_user_id = context
PasswordResetRequest::read_from_token(conn, &token).map(|p| p.local_user_id) .conn()
}) .await?
.await??; .interact(move |conn| {
PasswordResetRequest::read_from_token(conn, &token).map(|p| p.local_user_id)
})
.await??;
password_length_check(&data.password)?; password_length_check(&data.password)?;
@ -766,11 +815,12 @@ impl Perform for PasswordChange {
// Update the user with the new password // Update the user with the new password
let password = data.password.clone(); let password = data.password.clone();
let updated_local_user = blocking(context.pool(), move |conn| { let updated_local_user = context
LocalUser::update_password(conn, local_user_id, &password) .conn()
}) .await?
.await? .interact(move |conn| LocalUser::update_password(conn, local_user_id, &password))
.map_err(|e| ApiError::err("couldnt_update_user", e))?; .await?
.map_err(|e| ApiError::err("couldnt_update_user", e))?;
// Return the jwt // Return the jwt
Ok(LoginResponse { Ok(LoginResponse {
@ -800,15 +850,19 @@ impl Perform for GetReportCount {
let admin = local_user_view.person.admin; let admin = local_user_view.person.admin;
let community_id = data.community_id; let community_id = data.community_id;
let comment_reports = blocking(context.pool(), move |conn| { let comment_reports = context
CommentReportView::get_report_count(conn, person_id, admin, community_id) .conn()
}) .await?
.await??; .interact(move |conn| {
CommentReportView::get_report_count(conn, person_id, admin, community_id)
})
.await??;
let post_reports = blocking(context.pool(), move |conn| { let post_reports = context
PostReportView::get_report_count(conn, person_id, admin, community_id) .conn()
}) .await?
.await??; .interact(move |conn| PostReportView::get_report_count(conn, person_id, admin, community_id))
.await??;
let res = GetReportCountResponse { let res = GetReportCountResponse {
community_id, community_id,
@ -835,20 +889,23 @@ impl Perform for GetUnreadCount {
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let replies = blocking(context.pool(), move |conn| { let replies = context
CommentView::get_unread_replies(conn, person_id) .conn()
}) .await?
.await??; .interact(move |conn| CommentView::get_unread_replies(conn, person_id))
.await??;
let mentions = blocking(context.pool(), move |conn| { let mentions = context
PersonMentionView::get_unread_mentions(conn, person_id) .conn()
}) .await?
.await??; .interact(move |conn| PersonMentionView::get_unread_mentions(conn, person_id))
.await??;
let private_messages = blocking(context.pool(), move |conn| { let private_messages = context
PrivateMessageView::get_unread_messages(conn, person_id) .conn()
}) .await?
.await??; .interact(move |conn| PrivateMessageView::get_unread_messages(conn, person_id))
.await??;
let res = Self::Response { let res = Self::Response {
replies, replies,

View file

@ -1,7 +1,6 @@
use crate::Perform; use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
check_community_ban, check_community_ban,
check_community_deleted_or_removed, check_community_deleted_or_removed,
check_downvotes_enabled, check_downvotes_enabled,
@ -50,7 +49,10 @@ impl Perform for CreatePostLike {
// Check for a community ban // Check for a community ban
let post_id = data.post_id; let post_id = data.post_id;
let post: ApubPost = blocking(context.pool(), move |conn| Post::read(conn, post_id)) let post: ApubPost = context
.conn()
.await?
.interact(move |conn| Post::read(conn, post_id))
.await?? .await??
.into(); .into();
@ -67,10 +69,11 @@ impl Perform for CreatePostLike {
// Remove any likes first // Remove any likes first
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
blocking(context.pool(), move |conn| { context
PostLike::remove(conn, person_id, post_id) .conn()
}) .await?
.await??; .interact(move |conn| PostLike::remove(conn, person_id, post_id))
.await??;
let community_id = post.community_id; let community_id = post.community_id;
let object = PostOrComment::Post(Box::new(post)); let object = PostOrComment::Post(Box::new(post));
@ -79,8 +82,10 @@ impl Perform for CreatePostLike {
let do_add = like_form.score != 0 && (like_form.score == 1 || like_form.score == -1); let do_add = like_form.score != 0 && (like_form.score == 1 || like_form.score == -1);
if do_add { if do_add {
let like_form2 = like_form.clone(); let like_form2 = like_form.clone();
let like = move |conn: &'_ _| PostLike::like(conn, &like_form2); context
blocking(context.pool(), like) .conn()
.await?
.interact(move |conn| PostLike::like(conn, &like_form2))
.await? .await?
.map_err(|e| ApiError::err("couldnt_like_post", e))?; .map_err(|e| ApiError::err("couldnt_like_post", e))?;
@ -132,7 +137,11 @@ impl Perform for LockPost {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let post_id = data.post_id; let post_id = data.post_id;
let orig_post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; let orig_post = context
.conn()
.await?
.interact(move |conn| Post::read(conn, post_id))
.await??;
check_community_ban( check_community_ban(
local_user_view.person.id, local_user_view.person.id,
@ -153,11 +162,12 @@ impl Perform for LockPost {
// Update the post // Update the post
let post_id = data.post_id; let post_id = data.post_id;
let locked = data.locked; let locked = data.locked;
let updated_post: ApubPost = blocking(context.pool(), move |conn| { let updated_post: ApubPost = context
Post::update_locked(conn, post_id, locked) .conn()
}) .await?
.await?? .interact(move |conn| Post::update_locked(conn, post_id, locked))
.into(); .await??
.into();
// Mod tables // Mod tables
let form = ModLockPostForm { let form = ModLockPostForm {
@ -165,7 +175,11 @@ impl Perform for LockPost {
post_id: data.post_id, post_id: data.post_id,
locked: Some(locked), locked: Some(locked),
}; };
blocking(context.pool(), move |conn| ModLockPost::create(conn, &form)).await??; context
.conn()
.await?
.interact(move |conn| ModLockPost::create(conn, &form))
.await??;
// apub updates // apub updates
CreateOrUpdatePost::send( CreateOrUpdatePost::send(
@ -201,7 +215,11 @@ impl Perform for StickyPost {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let post_id = data.post_id; let post_id = data.post_id;
let orig_post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; let orig_post = context
.conn()
.await?
.interact(move |conn| Post::read(conn, post_id))
.await??;
check_community_ban( check_community_ban(
local_user_view.person.id, local_user_view.person.id,
@ -222,11 +240,12 @@ impl Perform for StickyPost {
// Update the post // Update the post
let post_id = data.post_id; let post_id = data.post_id;
let stickied = data.stickied; let stickied = data.stickied;
let updated_post: ApubPost = blocking(context.pool(), move |conn| { let updated_post: ApubPost = context
Post::update_stickied(conn, post_id, stickied) .conn()
}) .await?
.await?? .interact(move |conn| Post::update_stickied(conn, post_id, stickied))
.into(); .await??
.into();
// Mod tables // Mod tables
let form = ModStickyPostForm { let form = ModStickyPostForm {
@ -234,10 +253,11 @@ impl Perform for StickyPost {
post_id: data.post_id, post_id: data.post_id,
stickied: Some(stickied), stickied: Some(stickied),
}; };
blocking(context.pool(), move |conn| { context
ModStickyPost::create(conn, &form) .conn()
}) .await?
.await??; .interact(move |conn| ModStickyPost::create(conn, &form))
.await??;
// Apub updates // Apub updates
// TODO stickied should pry work like locked for ease of use // TODO stickied should pry work like locked for ease of use
@ -279,23 +299,28 @@ impl Perform for SavePost {
}; };
if data.save { if data.save {
let save = move |conn: &'_ _| PostSaved::save(conn, &post_saved_form); context
blocking(context.pool(), save) .conn()
.await?
.interact(move |conn| PostSaved::save(conn, &post_saved_form))
.await? .await?
.map_err(|e| ApiError::err("couldnt_save_post", e))?; .map_err(|e| ApiError::err("couldnt_save_post", e))?;
} else { } else {
let unsave = move |conn: &'_ _| PostSaved::unsave(conn, &post_saved_form); context
blocking(context.pool(), unsave) .conn()
.await?
.interact(move |conn| PostSaved::unsave(conn, &post_saved_form))
.await? .await?
.map_err(|e| ApiError::err("couldnt_save_post", e))?; .map_err(|e| ApiError::err("couldnt_save_post", e))?;
} }
let post_id = data.post_id; let post_id = data.post_id;
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let post_view = blocking(context.pool(), move |conn| { let post_view = context
PostView::read(conn, post_id, Some(person_id)) .conn()
}) .await?
.await??; .interact(move |conn| PostView::read(conn, post_id, Some(person_id)))
.await??;
// Mark the post as read // Mark the post as read
mark_post_as_read(person_id, post_id, context.pool()).await?; mark_post_as_read(person_id, post_id, context.pool()).await?;

View file

@ -1,7 +1,6 @@
use crate::Perform; use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
check_community_ban, check_community_ban,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
is_mod_or_admin, is_mod_or_admin,
@ -51,10 +50,11 @@ impl Perform for CreatePostReport {
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let post_id = data.post_id; let post_id = data.post_id;
let post_view = blocking(context.pool(), move |conn| { let post_view = context
PostView::read(conn, post_id, None) .conn()
}) .await?
.await??; .interact(move |conn| PostView::read(conn, post_id, None))
.await??;
check_community_ban(person_id, post_view.community.id, context.pool()).await?; check_community_ban(person_id, post_view.community.id, context.pool()).await?;
@ -67,16 +67,18 @@ impl Perform for CreatePostReport {
reason: data.reason.to_owned(), reason: data.reason.to_owned(),
}; };
let report = blocking(context.pool(), move |conn| { let report = context
PostReport::report(conn, &report_form) .conn()
}) .await?
.await? .interact(move |conn| PostReport::report(conn, &report_form))
.map_err(|e| ApiError::err("couldnt_create_report", e))?; .await?
.map_err(|e| ApiError::err("couldnt_create_report", e))?;
let post_report_view = blocking(context.pool(), move |conn| { let post_report_view = context
PostReportView::read(conn, report.id, person_id) .conn()
}) .await?
.await??; .interact(move |conn| PostReportView::read(conn, report.id, person_id))
.await??;
let res = PostReportResponse { post_report_view }; let res = PostReportResponse { post_report_view };
@ -116,31 +118,34 @@ impl Perform for ResolvePostReport {
let report_id = data.report_id; let report_id = data.report_id;
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let report = blocking(context.pool(), move |conn| { let report = context
PostReportView::read(conn, report_id, person_id) .conn()
}) .await?
.await??; .interact(move |conn| PostReportView::read(conn, report_id, person_id))
.await??;
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
is_mod_or_admin(context.pool(), person_id, report.community.id).await?; is_mod_or_admin(context.pool(), person_id, report.community.id).await?;
let resolved = data.resolved; let resolved = data.resolved;
let resolve_fun = move |conn: &'_ _| { context
if resolved { .conn()
PostReport::resolve(conn, report_id, person_id) .await?
} else { .interact(move |conn| {
PostReport::unresolve(conn, report_id, person_id) if resolved {
} PostReport::resolve(conn, report_id, person_id)
}; } else {
PostReport::unresolve(conn, report_id, person_id)
blocking(context.pool(), resolve_fun) }
})
.await? .await?
.map_err(|e| ApiError::err("couldnt_resolve_report", e))?; .map_err(|e| ApiError::err("couldnt_resolve_report", e))?;
let post_report_view = blocking(context.pool(), move |conn| { let post_report_view = context
PostReportView::read(conn, report_id, person_id) .conn()
}) .await?
.await??; .interact(move |conn| PostReportView::read(conn, report_id, person_id))
.await??;
let res = PostReportResponse { post_report_view }; let res = PostReportResponse { post_report_view };
@ -177,15 +182,18 @@ impl Perform for ListPostReports {
let page = data.page; let page = data.page;
let limit = data.limit; let limit = data.limit;
let post_reports = blocking(context.pool(), move |conn| { let post_reports = context
PostReportQueryBuilder::create(conn, person_id, admin) .conn()
.community_id(community_id) .await?
.unresolved_only(unresolved_only) .interact(move |conn| {
.page(page) PostReportQueryBuilder::create(conn, person_id, admin)
.limit(limit) .community_id(community_id)
.list() .unresolved_only(unresolved_only)
}) .page(page)
.await??; .limit(limit)
.list()
})
.await??;
let res = ListPostReportsResponse { post_reports }; let res = ListPostReportsResponse { post_reports };

View file

@ -1,7 +1,6 @@
use crate::Perform; use crate::Perform;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
person::{MarkPrivateMessageAsRead, PrivateMessageResponse}, person::{MarkPrivateMessageAsRead, PrivateMessageResponse},
}; };
@ -24,10 +23,11 @@ impl Perform for MarkPrivateMessageAsRead {
// Checking permissions // Checking permissions
let private_message_id = data.private_message_id; let private_message_id = data.private_message_id;
let orig_private_message = blocking(context.pool(), move |conn| { let orig_private_message = context
PrivateMessage::read(conn, private_message_id) .conn()
}) .await?
.await??; .interact(move |conn| PrivateMessage::read(conn, private_message_id))
.await??;
if local_user_view.person.id != orig_private_message.recipient_id { if local_user_view.person.id != orig_private_message.recipient_id {
return Err(ApiError::err_plain("couldnt_update_private_message").into()); return Err(ApiError::err_plain("couldnt_update_private_message").into());
} }
@ -35,11 +35,12 @@ impl Perform for MarkPrivateMessageAsRead {
// Doing the update // Doing the update
let private_message_id = data.private_message_id; let private_message_id = data.private_message_id;
let read = data.read; let read = data.read;
blocking(context.pool(), move |conn| { context
PrivateMessage::update_read(conn, private_message_id, read) .conn()
}) .await?
.await? .interact(move |conn| PrivateMessage::update_read(conn, private_message_id, read))
.map_err(|e| ApiError::err("couldnt_update_private_message", e))?; .await?
.map_err(|e| ApiError::err("couldnt_update_private_message", e))?;
// No need to send an apub update // No need to send an apub update
let op = UserOperation::MarkPrivateMessageAsRead; let op = UserOperation::MarkPrivateMessageAsRead;

View file

@ -3,7 +3,6 @@ use actix_web::web::Data;
use anyhow::Context; use anyhow::Context;
use diesel::NotFound; use diesel::NotFound;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
build_federated_instances, build_federated_instances,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
get_local_user_view_from_jwt_opt, get_local_user_view_from_jwt_opt,
@ -71,51 +70,69 @@ impl Perform for GetModlog {
let mod_person_id = data.mod_person_id; let mod_person_id = data.mod_person_id;
let page = data.page; let page = data.page;
let limit = data.limit; let limit = data.limit;
let removed_posts = blocking(context.pool(), move |conn| { let removed_posts = context
ModRemovePostView::list(conn, community_id, mod_person_id, page, limit) .conn()
}) .await?
.await??; .interact(move |conn| ModRemovePostView::list(conn, community_id, mod_person_id, page, limit))
.await??;
let locked_posts = blocking(context.pool(), move |conn| { let locked_posts = context
ModLockPostView::list(conn, community_id, mod_person_id, page, limit) .conn()
}) .await?
.await??; .interact(move |conn| ModLockPostView::list(conn, community_id, mod_person_id, page, limit))
.await??;
let stickied_posts = blocking(context.pool(), move |conn| { let stickied_posts = context
ModStickyPostView::list(conn, community_id, mod_person_id, page, limit) .conn()
}) .await?
.await??; .interact(move |conn| ModStickyPostView::list(conn, community_id, mod_person_id, page, limit))
.await??;
let removed_comments = blocking(context.pool(), move |conn| { let removed_comments = context
ModRemoveCommentView::list(conn, community_id, mod_person_id, page, limit) .conn()
}) .await?
.await??; .interact(move |conn| {
ModRemoveCommentView::list(conn, community_id, mod_person_id, page, limit)
})
.await??;
let banned_from_community = blocking(context.pool(), move |conn| { let banned_from_community = context
ModBanFromCommunityView::list(conn, community_id, mod_person_id, page, limit) .conn()
}) .await?
.await??; .interact(move |conn| {
ModBanFromCommunityView::list(conn, community_id, mod_person_id, page, limit)
})
.await??;
let added_to_community = blocking(context.pool(), move |conn| { let added_to_community = context
ModAddCommunityView::list(conn, community_id, mod_person_id, page, limit) .conn()
}) .await?
.await??; .interact(move |conn| {
ModAddCommunityView::list(conn, community_id, mod_person_id, page, limit)
})
.await??;
let transferred_to_community = blocking(context.pool(), move |conn| { let transferred_to_community = context
ModTransferCommunityView::list(conn, community_id, mod_person_id, page, limit) .conn()
}) .await?
.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 // These arrays are only for the full modlog, when a community isn't given
let (removed_communities, banned, added) = if data.community_id.is_none() { let (removed_communities, banned, added) = if data.community_id.is_none() {
blocking(context.pool(), move |conn| { context
Ok(( .conn()
ModRemoveCommunityView::list(conn, mod_person_id, page, limit)?, .await?
ModBanView::list(conn, mod_person_id, page, limit)?, .interact(move |conn| {
ModAddView::list(conn, mod_person_id, page, limit)?, Ok((
)) as Result<_, LemmyError> ModRemoveCommunityView::list(conn, mod_person_id, page, limit)?,
}) ModBanView::list(conn, mod_person_id, page, limit)?,
.await?? ModAddView::list(conn, mod_person_id, page, limit)?,
)) as Result<_, LemmyError>
})
.await??
} else { } else {
(Vec::new(), Vec::new(), Vec::new()) (Vec::new(), Vec::new(), Vec::new())
}; };
@ -184,114 +201,52 @@ impl Perform for Search {
let creator_id = data.creator_id; let creator_id = data.creator_id;
match search_type { match search_type {
SearchType::Posts => { SearchType::Posts => {
posts = blocking(context.pool(), move |conn| { posts = context
PostQueryBuilder::create(conn) .conn()
.sort(sort) .await?
.show_nsfw(show_nsfw) .interact(move |conn| {
.show_bot_accounts(show_bot_accounts) PostQueryBuilder::create(conn)
.show_read_posts(show_read_posts) .sort(sort)
.listing_type(listing_type) .show_nsfw(show_nsfw)
.community_id(community_id) .show_bot_accounts(show_bot_accounts)
.community_actor_id(community_actor_id) .show_read_posts(show_read_posts)
.creator_id(creator_id) .listing_type(listing_type)
.my_person_id(person_id) .community_id(community_id)
.search_term(q) .community_actor_id(community_actor_id)
.page(page) .creator_id(creator_id)
.limit(limit) .my_person_id(person_id)
.list() .search_term(q)
}) .page(page)
.await??; .limit(limit)
.list()
})
.await??;
} }
SearchType::Comments => { SearchType::Comments => {
comments = blocking(context.pool(), move |conn| { comments = context
CommentQueryBuilder::create(conn) .conn()
.sort(sort) .await?
.listing_type(listing_type) .interact(move |conn| {
.search_term(q) CommentQueryBuilder::create(conn)
.show_bot_accounts(show_bot_accounts) .sort(sort)
.community_id(community_id) .listing_type(listing_type)
.community_actor_id(community_actor_id) .search_term(q)
.creator_id(creator_id) .show_bot_accounts(show_bot_accounts)
.my_person_id(person_id) .community_id(community_id)
.page(page) .community_actor_id(community_actor_id)
.limit(limit) .creator_id(creator_id)
.list() .my_person_id(person_id)
}) .page(page)
.await??; .limit(limit)
.list()
})
.await??;
} }
SearchType::Communities => { SearchType::Communities => {
communities = blocking(context.pool(), move |conn| { communities = context
CommunityQueryBuilder::create(conn) .conn()
.sort(sort) .await?
.listing_type(listing_type) .interact(move |conn| {
.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| {
CommunityQueryBuilder::create(conn) CommunityQueryBuilder::create(conn)
.sort(sort) .sort(sort)
.listing_type(listing_type) .listing_type(listing_type)
@ -301,15 +256,13 @@ impl Perform for Search {
.limit(limit) .limit(limit)
.list() .list()
}) })
.await?? .await??;
}; }
SearchType::Users => {
let q = data.q.to_owned(); users = context
.conn()
users = if community_or_creator_included { .await?
vec![] .interact(move |conn| {
} else {
blocking(context.pool(), move |conn| {
PersonQueryBuilder::create(conn) PersonQueryBuilder::create(conn)
.sort(sort) .sort(sort)
.search_term(q) .search_term(q)
@ -317,27 +270,118 @@ impl Perform for Search {
.limit(limit) .limit(limit)
.list() .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 => { SearchType::Url => {
posts = blocking(context.pool(), move |conn| { posts = context
PostQueryBuilder::create(conn) .conn()
.sort(sort) .await?
.show_nsfw(show_nsfw) .interact(move |conn| {
.show_bot_accounts(show_bot_accounts) PostQueryBuilder::create(conn)
.show_read_posts(show_read_posts) .sort(sort)
.listing_type(listing_type) .show_nsfw(show_nsfw)
.my_person_id(person_id) .show_bot_accounts(show_bot_accounts)
.community_id(community_id) .show_read_posts(show_read_posts)
.community_actor_id(community_actor_id) .listing_type(listing_type)
.creator_id(creator_id) .my_person_id(person_id)
.url_search(q) .community_id(community_id)
.page(page) .community_actor_id(community_actor_id)
.limit(limit) .creator_id(creator_id)
.list() .url_search(q)
}) .page(page)
.await??; .limit(limit)
.list()
})
.await??;
} }
}; };
@ -409,23 +453,39 @@ async fn convert_response(
person: None, person: None,
}; };
use SearchableObjects::*; use SearchableObjects::*;
let conn = pool.get().await?;
match object { match object {
Person(p) => { Person(p) => {
removed_or_deleted = p.deleted; removed_or_deleted = p.deleted;
res.person = Some(blocking(pool, move |conn| PersonViewSafe::read(conn, p.id)).await??) res.person = Some(
conn
.interact(move |conn| PersonViewSafe::read(conn, p.id))
.await??,
)
} }
Community(c) => { Community(c) => {
removed_or_deleted = c.deleted || c.removed; removed_or_deleted = c.deleted || c.removed;
res.community = res.community = Some(
Some(blocking(pool, move |conn| CommunityView::read(conn, c.id, user_id)).await??) conn
.interact(move |conn| CommunityView::read(conn, c.id, user_id))
.await??,
)
} }
Post(p) => { Post(p) => {
removed_or_deleted = p.deleted || p.removed; removed_or_deleted = p.deleted || p.removed;
res.post = Some(blocking(pool, move |conn| PostView::read(conn, p.id, user_id)).await??) res.post = Some(
conn
.interact(move |conn| PostView::read(conn, p.id, user_id))
.await??,
)
} }
Comment(c) => { Comment(c) => {
removed_or_deleted = c.deleted || c.removed; removed_or_deleted = c.deleted || c.removed;
res.comment = Some(blocking(pool, move |conn| CommentView::read(conn, c.id, user_id)).await??) res.comment = Some(
conn
.interact(move |conn| CommentView::read(conn, c.id, user_id))
.await??,
)
} }
}; };
// if the object was deleted from database, dont return it // if the object was deleted from database, dont return it
@ -450,7 +510,11 @@ impl Perform for TransferSite {
is_admin(&local_user_view)?; is_admin(&local_user_view)?;
let read_site = blocking(context.pool(), Site::read_simple).await??; let read_site = context
.conn()
.await?
.interact(|conn| Site::read_simple(conn))
.await??;
// Make sure user is the creator // Make sure user is the creator
if read_site.creator_id != local_user_view.person.id { if read_site.creator_id != local_user_view.person.id {
@ -458,8 +522,10 @@ impl Perform for TransferSite {
} }
let new_creator_id = data.person_id; let new_creator_id = data.person_id;
let transfer_site = move |conn: &'_ _| Site::transfer(conn, new_creator_id); context
blocking(context.pool(), transfer_site) .conn()
.await?
.interact(move |conn| Site::transfer(conn, new_creator_id))
.await? .await?
.map_err(|e| ApiError::err("couldnt_update_site", e))?; .map_err(|e| ApiError::err("couldnt_update_site", e))?;
@ -470,11 +536,23 @@ impl Perform for TransferSite {
removed: Some(false), removed: Some(false),
}; };
blocking(context.pool(), move |conn| ModAdd::create(conn, &form)).await??; context
.conn()
.await?
.interact(move |conn| ModAdd::create(conn, &form))
.await??;
let site_view = blocking(context.pool(), SiteView::read).await??; let site_view = context
.conn()
.await?
.interact(|conn| SiteView::read(conn))
.await??;
let mut admins = blocking(context.pool(), PersonViewSafe::admins).await??; let mut admins = context
.conn()
.await?
.interact(|conn| PersonViewSafe::admins(conn))
.await??;
let creator_index = admins let creator_index = admins
.iter() .iter()
.position(|r| r.person.id == site_view.creator.id) .position(|r| r.person.id == site_view.creator.id)
@ -482,7 +560,11 @@ impl Perform for TransferSite {
let creator_person = admins.remove(creator_index); let creator_person = admins.remove(creator_index);
admins.insert(0, creator_person); admins.insert(0, creator_person);
let banned = blocking(context.pool(), PersonViewSafe::banned).await??; let banned = context
.conn()
.await?
.interact(|conn| PersonViewSafe::banned(conn))
.await??;
let federated_instances = build_federated_instances( let federated_instances = build_federated_instances(
context.pool(), context.pool(),
&context.settings().federation, &context.settings().federation,

View file

@ -26,31 +26,16 @@ use lemmy_db_views_actor::{
use lemmy_utils::{claims::Claims, settings::structs::FederationConfig, ApiError, LemmyError}; use lemmy_utils::{claims::Claims, settings::structs::FederationConfig, ApiError, LemmyError};
use url::Url; use url::Url;
pub async fn blocking<F, T>(pool: &DbPool, f: F) -> Result<T, LemmyError>
where
F: FnOnce(&diesel::PgConnection) -> T + Send + 'static,
T: Send + 'static,
{
let pool = pool.clone();
let res = actix_web::web::block(move || {
let conn = pool.get()?;
let res = (f)(&conn);
Ok(res) as Result<T, LemmyError>
})
.await?;
res
}
pub async fn is_mod_or_admin( pub async fn is_mod_or_admin(
pool: &DbPool, pool: &DbPool,
person_id: PersonId, person_id: PersonId,
community_id: CommunityId, community_id: CommunityId,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let is_mod_or_admin = blocking(pool, move |conn| { let is_mod_or_admin = pool
CommunityView::is_mod_or_admin(conn, person_id, community_id) .get()
}) .await?
.await?; .interact(move |conn| CommunityView::is_mod_or_admin(conn, person_id, community_id))
.await?;
if !is_mod_or_admin { if !is_mod_or_admin {
return Err(ApiError::err_plain("not_a_mod_or_admin").into()); return Err(ApiError::err_plain("not_a_mod_or_admin").into());
} }
@ -65,7 +50,10 @@ pub fn is_admin(local_user_view: &LocalUserView) -> Result<(), LemmyError> {
} }
pub async fn get_post(post_id: PostId, pool: &DbPool) -> Result<Post, LemmyError> { pub async fn get_post(post_id: PostId, pool: &DbPool) -> Result<Post, LemmyError> {
blocking(pool, move |conn| Post::read(conn, post_id)) pool
.get()
.await?
.interact(move |conn| Post::read(conn, post_id))
.await? .await?
.map_err(|_| ApiError::err_plain("couldnt_find_post").into()) .map_err(|_| ApiError::err_plain("couldnt_find_post").into())
} }
@ -77,11 +65,12 @@ pub async fn mark_post_as_read(
) -> Result<PostRead, LemmyError> { ) -> Result<PostRead, LemmyError> {
let post_read_form = PostReadForm { post_id, person_id }; let post_read_form = PostReadForm { post_id, person_id };
blocking(pool, move |conn| { pool
PostRead::mark_as_read(conn, &post_read_form) .get()
}) .await?
.await? .interact(move |conn| PostRead::mark_as_read(conn, &post_read_form))
.map_err(|_| ApiError::err_plain("couldnt_mark_post_as_read").into()) .await?
.map_err(|_| ApiError::err_plain("couldnt_mark_post_as_read").into())
} }
pub async fn get_local_user_view_from_jwt( 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))? .map_err(|e| ApiError::err("not_logged_in", e))?
.claims; .claims;
let local_user_id = LocalUserId(claims.sub); let local_user_id = LocalUserId(claims.sub);
let local_user_view = let local_user_view = pool
blocking(pool, move |conn| LocalUserView::read(conn, local_user_id)).await??; .get()
.await?
.interact(move |conn| LocalUserView::read(conn, local_user_id))
.await??;
// Check for a site ban // Check for a site ban
if local_user_view.person.banned { if local_user_view.person.banned {
return Err(ApiError::err_plain("site_ban").into()); return Err(ApiError::err_plain("site_ban").into());
@ -143,10 +135,11 @@ pub async fn get_local_user_settings_view_from_jwt(
.map_err(|e| ApiError::err("not_logged_in", e))? .map_err(|e| ApiError::err("not_logged_in", e))?
.claims; .claims;
let local_user_id = LocalUserId(claims.sub); let local_user_id = LocalUserId(claims.sub);
let local_user_view = blocking(pool, move |conn| { let local_user_view = pool
LocalUserSettingsView::read(conn, local_user_id) .get()
}) .await?
.await??; .interact(move |conn| LocalUserSettingsView::read(conn, local_user_id))
.await??;
// Check for a site ban // Check for a site ban
if local_user_view.person.banned { if local_user_view.person.banned {
return Err(ApiError::err_plain("site_ban").into()); return Err(ApiError::err_plain("site_ban").into());
@ -175,9 +168,12 @@ pub async fn check_community_ban(
community_id: CommunityId, community_id: CommunityId,
pool: &DbPool, pool: &DbPool,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let is_banned = if pool
move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok(); .get()
if blocking(pool, is_banned).await? { .await?
.interact(move |conn| CommunityPersonBanView::get(conn, person_id, community_id).is_ok())
.await?
{
Err(ApiError::err_plain("community_ban").into()) Err(ApiError::err_plain("community_ban").into())
} else { } else {
Ok(()) Ok(())
@ -188,7 +184,10 @@ pub async fn check_community_deleted_or_removed(
community_id: CommunityId, community_id: CommunityId,
pool: &DbPool, pool: &DbPool,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let community = blocking(pool, move |conn| Community::read(conn, community_id)) let community = pool
.get()
.await?
.interact(move |conn| Community::read(conn, community_id))
.await? .await?
.map_err(|e| ApiError::err("couldnt_find_community", e))?; .map_err(|e| ApiError::err("couldnt_find_community", e))?;
if community.deleted || community.removed { if community.deleted || community.removed {
@ -211,8 +210,12 @@ pub async fn check_person_block(
potential_blocker_id: PersonId, potential_blocker_id: PersonId,
pool: &DbPool, pool: &DbPool,
) -> Result<(), LemmyError> { ) -> Result<(), LemmyError> {
let is_blocked = move |conn: &'_ _| PersonBlock::read(conn, potential_blocker_id, my_id).is_ok(); if pool
if blocking(pool, is_blocked).await? { .get()
.await?
.interact(move |conn| PersonBlock::read(conn, potential_blocker_id, my_id).is_ok())
.await?
{
Err(ApiError::err_plain("person_block").into()) Err(ApiError::err_plain("person_block").into())
} else { } else {
Ok(()) Ok(())
@ -221,7 +224,11 @@ pub async fn check_person_block(
pub async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> { pub async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> {
if score == -1 { if score == -1 {
let site = blocking(pool, Site::read_simple).await??; let site = pool
.get()
.await?
.interact(|conn| Site::read_simple(conn))
.await??;
if !site.enable_downvotes { if !site.enable_downvotes {
return Err(ApiError::err_plain("downvotes_disabled").into()); return Err(ApiError::err_plain("downvotes_disabled").into());
} }
@ -236,10 +243,11 @@ pub async fn build_federated_instances(
) -> Result<Option<FederatedInstances>, LemmyError> { ) -> Result<Option<FederatedInstances>, LemmyError> {
let federation = federation_config.to_owned(); let federation = federation_config.to_owned();
if federation.enabled { if federation.enabled {
let distinct_communities = blocking(pool, move |conn| { let distinct_communities = pool
Community::distinct_federated_communities(conn) .get()
}) .await?
.await??; .interact(move |conn| Community::distinct_federated_communities(conn))
.await??;
let allowed = federation.allowed_instances; let allowed = federation.allowed_instances;
let blocked = federation.blocked_instances; let blocked = federation.blocked_instances;

View file

@ -1,7 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
check_community_ban, check_community_ban,
check_community_deleted_or_removed, check_community_deleted_or_removed,
check_person_block, check_person_block,
@ -76,7 +75,10 @@ impl PerformCrud for CreateComment {
// If there's a parent_id, check to make sure that comment is in that post // If there's a parent_id, check to make sure that comment is in that post
if let Some(parent_id) = data.parent_id { if let Some(parent_id) = data.parent_id {
// Make sure the parent comment exists // Make sure the parent comment exists
let parent = blocking(context.pool(), move |conn| Comment::read(conn, parent_id)) let parent = context
.conn()
.await?
.interact(move |conn| Comment::read(conn, parent_id))
.await? .await?
.map_err(|e| ApiError::err("couldnt_create_comment", e))?; .map_err(|e| ApiError::err("couldnt_create_comment", e))?;
@ -98,18 +100,21 @@ impl PerformCrud for CreateComment {
// Create the comment // Create the comment
let comment_form2 = comment_form.clone(); let comment_form2 = comment_form.clone();
let inserted_comment = blocking(context.pool(), move |conn| { let inserted_comment = context
Comment::create(conn, &comment_form2) .conn()
}) .await?
.await? .interact(move |conn| Comment::create(conn, &comment_form2))
.map_err(|e| ApiError::err("couldnt_create_comment", e))?; .await?
.map_err(|e| ApiError::err("couldnt_create_comment", e))?;
// Necessary to update the ap_id // Necessary to update the ap_id
let inserted_comment_id = inserted_comment.id; let inserted_comment_id = inserted_comment.id;
let protocol_and_hostname = context.settings().get_protocol_and_hostname(); let protocol_and_hostname = context.settings().get_protocol_and_hostname();
let updated_comment: Comment = let updated_comment: Comment = context
blocking(context.pool(), move |conn| -> Result<Comment, LemmyError> { .conn()
.await?
.interact(move |conn| -> Result<Comment, LemmyError> {
let apub_id = generate_local_apub_endpoint( let apub_id = generate_local_apub_endpoint(
EndpointType::Comment, EndpointType::Comment,
&inserted_comment_id.to_string(), &inserted_comment_id.to_string(),
@ -141,8 +146,10 @@ impl PerformCrud for CreateComment {
score: 1, score: 1,
}; };
let like = move |conn: &'_ _| CommentLike::like(conn, &like_form); context
blocking(context.pool(), like) .conn()
.await?
.interact(move |conn| CommentLike::like(conn, &like_form))
.await? .await?
.map_err(|e| ApiError::err("couldnt_like_comment", e))?; .map_err(|e| ApiError::err("couldnt_like_comment", e))?;
@ -166,45 +173,51 @@ impl PerformCrud for CreateComment {
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let comment_id = inserted_comment.id; let comment_id = inserted_comment.id;
let comment_view = blocking(context.pool(), move |conn| { let comment_view = context
CommentView::read(conn, comment_id, Some(person_id)) .conn()
}) .await?
.await??; .interact(move |conn| CommentView::read(conn, comment_id, Some(person_id)))
.await??;
// If its a comment to yourself, mark it as read // If its a comment to yourself, mark it as read
if local_user_view.person.id == comment_view.get_recipient_id() { if local_user_view.person.id == comment_view.get_recipient_id() {
let comment_id = inserted_comment.id; let comment_id = inserted_comment.id;
blocking(context.pool(), move |conn| { context
Comment::update_read(conn, comment_id, true) .conn()
}) .await?
.await? .interact(move |conn| Comment::update_read(conn, comment_id, true))
.map_err(|e| ApiError::err("couldnt_update_comment", e))?; .await?
.map_err(|e| ApiError::err("couldnt_update_comment", e))?;
} }
// If its a reply, mark the parent as read // If its a reply, mark the parent as read
if let Some(parent_id) = data.parent_id { if let Some(parent_id) = data.parent_id {
let parent_comment = blocking(context.pool(), move |conn| { let parent_comment = context
CommentView::read(conn, parent_id, Some(person_id)) .conn()
})
.await??;
if local_user_view.person.id == parent_comment.get_recipient_id() {
blocking(context.pool(), move |conn| {
Comment::update_read(conn, parent_id, true)
})
.await? .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 // If the parent has PersonMentions mark them as read too
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let person_mention = blocking(context.pool(), move |conn| { let person_mention = context
PersonMention::read_by_comment_and_person(conn, parent_id, person_id) .conn()
})
.await?;
if let Ok(mention) = person_mention {
blocking(context.pool(), move |conn| {
PersonMention::update_read(conn, mention.id, true)
})
.await? .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 crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
check_community_ban, check_community_ban,
comment::*, comment::*,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
@ -39,10 +38,11 @@ impl PerformCrud for DeleteComment {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let comment_id = data.comment_id; let comment_id = data.comment_id;
let orig_comment = blocking(context.pool(), move |conn| { let orig_comment = context
CommentView::read(conn, comment_id, None) .conn()
}) .await?
.await??; .interact(move |conn| CommentView::read(conn, comment_id, None))
.await??;
// Dont delete it if its already been deleted. // Dont delete it if its already been deleted.
if orig_comment.comment.deleted == data.deleted { if orig_comment.comment.deleted == data.deleted {
@ -63,17 +63,19 @@ impl PerformCrud for DeleteComment {
// Do the delete // Do the delete
let deleted = data.deleted; let deleted = data.deleted;
let updated_comment = blocking(context.pool(), move |conn| { let updated_comment = context
Comment::update_deleted(conn, comment_id, deleted) .conn()
}) .await?
.await? .interact(move |conn| Comment::update_deleted(conn, comment_id, deleted))
.map_err(|e| ApiError::err("couldnt_update_comment", e))?; .await?
.map_err(|e| ApiError::err("couldnt_update_comment", e))?;
// Send the apub message // Send the apub message
let community = blocking(context.pool(), move |conn| { let community = context
Community::read(conn, orig_comment.post.community_id) .conn()
}) .await?
.await??; .interact(move |conn| Community::read(conn, orig_comment.post.community_id))
.await??;
send_apub_delete( send_apub_delete(
&local_user_view.person.clone().into(), &local_user_view.person.clone().into(),
&community.clone().into(), &community.clone().into(),
@ -84,7 +86,11 @@ impl PerformCrud for DeleteComment {
.await?; .await?;
let post_id = updated_comment.post_id; let post_id = updated_comment.post_id;
let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; let post = context
.conn()
.await?
.interact(move |conn| Post::read(conn, post_id))
.await??;
let recipient_ids = send_local_notifs( let recipient_ids = send_local_notifs(
vec![], vec![],
&updated_comment, &updated_comment,
@ -122,10 +128,11 @@ impl PerformCrud for RemoveComment {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let comment_id = data.comment_id; let comment_id = data.comment_id;
let orig_comment = blocking(context.pool(), move |conn| { let orig_comment = context
CommentView::read(conn, comment_id, None) .conn()
}) .await?
.await??; .interact(move |conn| CommentView::read(conn, comment_id, None))
.await??;
check_community_ban( check_community_ban(
local_user_view.person.id, local_user_view.person.id,
@ -144,11 +151,12 @@ impl PerformCrud for RemoveComment {
// Do the remove // Do the remove
let removed = data.removed; let removed = data.removed;
let updated_comment = blocking(context.pool(), move |conn| { let updated_comment = context
Comment::update_removed(conn, comment_id, removed) .conn()
}) .await?
.await? .interact(move |conn| Comment::update_removed(conn, comment_id, removed))
.map_err(|e| ApiError::err("couldnt_update_comment", e))?; .await?
.map_err(|e| ApiError::err("couldnt_update_comment", e))?;
// Mod tables // Mod tables
let form = ModRemoveCommentForm { let form = ModRemoveCommentForm {
@ -157,16 +165,18 @@ impl PerformCrud for RemoveComment {
removed: Some(removed), removed: Some(removed),
reason: data.reason.to_owned(), reason: data.reason.to_owned(),
}; };
blocking(context.pool(), move |conn| { context
ModRemoveComment::create(conn, &form) .conn()
}) .await?
.await??; .interact(move |conn| ModRemoveComment::create(conn, &form))
.await??;
// Send the apub message // Send the apub message
let community = blocking(context.pool(), move |conn| { let community = context
Community::read(conn, orig_comment.post.community_id) .conn()
}) .await?
.await??; .interact(move |conn| Community::read(conn, orig_comment.post.community_id))
.await??;
send_apub_remove( send_apub_remove(
&local_user_view.person.clone().into(), &local_user_view.person.clone().into(),
&community.into(), &community.into(),
@ -178,7 +188,11 @@ impl PerformCrud for RemoveComment {
.await?; .await?;
let post_id = updated_comment.post_id; let post_id = updated_comment.post_id;
let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; let post = context
.conn()
.await?
.interact(move |conn| Post::read(conn, post_id))
.await??;
let recipient_ids = send_local_notifs( let recipient_ids = send_local_notifs(
vec![], vec![],
&updated_comment, &updated_comment,

View file

@ -1,6 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{blocking, comment::*, get_local_user_view_from_jwt_opt}; use lemmy_api_common::{comment::*, get_local_user_view_from_jwt_opt};
use lemmy_apub::get_actor_id_from_name; use lemmy_apub::get_actor_id_from_name;
use lemmy_apub_lib::webfinger::WebfingerType; use lemmy_apub_lib::webfinger::WebfingerType;
use lemmy_db_schema::{ use lemmy_db_schema::{
@ -45,21 +45,24 @@ impl PerformCrud for GetComments {
let saved_only = data.saved_only; let saved_only = data.saved_only;
let page = data.page; let page = data.page;
let limit = data.limit; let limit = data.limit;
let mut comments = blocking(context.pool(), move |conn| { let mut comments = context
CommentQueryBuilder::create(conn) .conn()
.listing_type(listing_type) .await?
.sort(sort) .interact(move |conn| {
.saved_only(saved_only) CommentQueryBuilder::create(conn)
.community_id(community_id) .listing_type(listing_type)
.community_actor_id(community_actor_id) .sort(sort)
.my_person_id(person_id) .saved_only(saved_only)
.show_bot_accounts(show_bot_accounts) .community_id(community_id)
.page(page) .community_actor_id(community_actor_id)
.limit(limit) .my_person_id(person_id)
.list() .show_bot_accounts(show_bot_accounts)
}) .page(page)
.await? .limit(limit)
.map_err(|e| ApiError::err("couldnt_get_comments", e))?; .list()
})
.await?
.map_err(|e| ApiError::err("couldnt_get_comments", e))?;
// Blank out deleted or removed info // Blank out deleted or removed info
for cv in comments for cv in comments

View file

@ -1,7 +1,6 @@
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
check_community_ban, check_community_ban,
check_community_deleted_or_removed, check_community_deleted_or_removed,
check_post_deleted_or_removed, check_post_deleted_or_removed,
@ -42,10 +41,11 @@ impl PerformCrud for EditComment {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let comment_id = data.comment_id; let comment_id = data.comment_id;
let orig_comment = blocking(context.pool(), move |conn| { let orig_comment = context
CommentView::read(conn, comment_id, None) .conn()
}) .await?
.await??; .interact(move |conn| CommentView::read(conn, comment_id, None))
.await??;
// TODO is this necessary? It should really only need to check on create // TODO is this necessary? It should really only need to check on create
check_community_ban( check_community_ban(
@ -66,11 +66,12 @@ impl PerformCrud for EditComment {
let content_slurs_removed = let content_slurs_removed =
remove_slurs(&data.content.to_owned(), &context.settings().slur_regex()); remove_slurs(&data.content.to_owned(), &context.settings().slur_regex());
let comment_id = data.comment_id; let comment_id = data.comment_id;
let updated_comment = blocking(context.pool(), move |conn| { let updated_comment = context
Comment::update_content(conn, comment_id, &content_slurs_removed) .conn()
}) .await?
.await? .interact(move |conn| Comment::update_content(conn, comment_id, &content_slurs_removed))
.map_err(|e| ApiError::err("couldnt_update_comment", e))?; .await?
.map_err(|e| ApiError::err("couldnt_update_comment", e))?;
// Do the mentions / recipients // Do the mentions / recipients
let updated_comment_content = updated_comment.content.to_owned(); let updated_comment_content = updated_comment.content.to_owned();

View file

@ -1,7 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
community::{CommunityResponse, CreateCommunity}, community::{CommunityResponse, CreateCommunity},
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
is_admin, is_admin,
@ -53,7 +52,11 @@ impl PerformCrud for CreateCommunity {
let local_user_view = let local_user_view =
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let site = blocking(context.pool(), move |conn| Site::read(conn, 0)).await??; let site = context
.conn()
.await?
.interact(move |conn| Site::read(conn, 0))
.await??;
if site.community_creation_admin_only && is_admin(&local_user_view).is_err() { if site.community_creation_admin_only && is_admin(&local_user_view).is_err() {
return Err(ApiError::err_plain("only_admins_can_create_communities").into()); return Err(ApiError::err_plain("only_admins_can_create_communities").into());
} }
@ -101,11 +104,12 @@ impl PerformCrud for CreateCommunity {
..CommunityForm::default() ..CommunityForm::default()
}; };
let inserted_community = blocking(context.pool(), move |conn| { let inserted_community = context
Community::create(conn, &community_form) .conn()
}) .await?
.await? .interact(move |conn| Community::create(conn, &community_form))
.map_err(|e| ApiError::err("community_already_exists", e))?; .await?
.map_err(|e| ApiError::err("community_already_exists", e))?;
// The community creator becomes a moderator // The community creator becomes a moderator
let community_moderator_form = CommunityModeratorForm { let community_moderator_form = CommunityModeratorForm {
@ -113,8 +117,13 @@ impl PerformCrud for CreateCommunity {
person_id: local_user_view.person.id, person_id: local_user_view.person.id,
}; };
let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form); if context
if blocking(context.pool(), join).await?.is_err() { .conn()
.await?
.interact(move |conn| CommunityModerator::join(conn, &community_moderator_form))
.await?
.is_err()
{
return Err(ApiError::err_plain("community_moderator_already_exists").into()); return Err(ApiError::err_plain("community_moderator_already_exists").into());
} }
@ -125,16 +134,22 @@ impl PerformCrud for CreateCommunity {
pending: false, pending: false,
}; };
let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form); if context
if blocking(context.pool(), follow).await?.is_err() { .conn()
.await?
.interact(move |conn| CommunityFollower::follow(conn, &community_follower_form))
.await?
.is_err()
{
return Err(ApiError::err_plain("community_follower_already_exists").into()); return Err(ApiError::err_plain("community_follower_already_exists").into());
} }
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let community_view = blocking(context.pool(), move |conn| { let community_view = context
CommunityView::read(conn, inserted_community.id, Some(person_id)) .conn()
}) .await?
.await??; .interact(move |conn| CommunityView::read(conn, inserted_community.id, Some(person_id)))
.await??;
Ok(CommunityResponse { community_view }) Ok(CommunityResponse { community_view })
} }

View file

@ -1,6 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{blocking, community::*, get_local_user_view_from_jwt, is_admin}; use lemmy_api_common::{community::*, get_local_user_view_from_jwt, is_admin};
use lemmy_apub::activities::deletion::{send_apub_delete, send_apub_remove}; use lemmy_apub::activities::deletion::{send_apub_delete, send_apub_remove};
use lemmy_db_schema::{ use lemmy_db_schema::{
source::{ source::{
@ -28,10 +28,11 @@ impl PerformCrud for DeleteCommunity {
// Fetch the community mods // Fetch the community mods
let community_id = data.community_id; let community_id = data.community_id;
let community_mods = blocking(context.pool(), move |conn| { let community_mods = context
CommunityModeratorView::for_community(conn, community_id) .conn()
}) .await?
.await??; .interact(move |conn| CommunityModeratorView::for_community(conn, community_id))
.await??;
// Make sure deleter is the top mod // Make sure deleter is the top mod
if local_user_view.person.id != community_mods[0].moderator.id { if local_user_view.person.id != community_mods[0].moderator.id {
@ -41,11 +42,12 @@ impl PerformCrud for DeleteCommunity {
// Do the delete // Do the delete
let community_id = data.community_id; let community_id = data.community_id;
let deleted = data.deleted; let deleted = data.deleted;
let updated_community = blocking(context.pool(), move |conn| { let updated_community = context
Community::update_deleted(conn, community_id, deleted) .conn()
}) .await?
.await? .interact(move |conn| Community::update_deleted(conn, community_id, deleted))
.map_err(|e| ApiError::err("couldnt_update_community", e))?; .await?
.map_err(|e| ApiError::err("couldnt_update_community", e))?;
// Send apub messages // Send apub messages
send_apub_delete( send_apub_delete(
@ -87,11 +89,12 @@ impl PerformCrud for RemoveCommunity {
// Do the remove // Do the remove
let community_id = data.community_id; let community_id = data.community_id;
let removed = data.removed; let removed = data.removed;
let updated_community = blocking(context.pool(), move |conn| { let updated_community = context
Community::update_removed(conn, community_id, removed) .conn()
}) .await?
.await? .interact(move |conn| Community::update_removed(conn, community_id, removed))
.map_err(|e| ApiError::err("couldnt_update_community", e))?; .await?
.map_err(|e| ApiError::err("couldnt_update_community", e))?;
// Mod tables // Mod tables
let expires = data.expires.map(naive_from_unix); let expires = data.expires.map(naive_from_unix);
@ -102,10 +105,11 @@ impl PerformCrud for RemoveCommunity {
reason: data.reason.to_owned(), reason: data.reason.to_owned(),
expires, expires,
}; };
blocking(context.pool(), move |conn| { context
ModRemoveCommunity::create(conn, &form) .conn()
}) .await?
.await??; .interact(move |conn| ModRemoveCommunity::create(conn, &form))
.await??;
// Apub messages // Apub messages
send_apub_remove( send_apub_remove(

View file

@ -1,6 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{blocking, community::*, get_local_user_view_from_jwt_opt}; use lemmy_api_common::{community::*, get_local_user_view_from_jwt_opt};
use lemmy_apub::{get_actor_id_from_name, objects::community::ApubCommunity}; use lemmy_apub::{get_actor_id_from_name, objects::community::ApubCommunity};
use lemmy_apub_lib::{object_id::ObjectId, webfinger::WebfingerType}; use lemmy_apub_lib::{object_id::ObjectId, webfinger::WebfingerType};
use lemmy_db_schema::{ use lemmy_db_schema::{
@ -45,11 +45,12 @@ impl PerformCrud for GetCommunity {
} }
}; };
let mut community_view = blocking(context.pool(), move |conn| { let mut community_view = context
CommunityView::read(conn, community_id, person_id) .conn()
}) .await?
.await? .interact(move |conn| CommunityView::read(conn, community_id, person_id))
.map_err(|e| ApiError::err("couldnt_find_community", e))?; .await?
.map_err(|e| ApiError::err("couldnt_find_community", e))?;
// Blank out deleted or removed info for non-logged in users // Blank out deleted or removed info for non-logged in users
if person_id.is_none() && (community_view.community.deleted || community_view.community.removed) 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(); community_view.community = community_view.community.blank_out_deleted_or_removed_info();
} }
let moderators: Vec<CommunityModeratorView> = blocking(context.pool(), move |conn| { let moderators: Vec<CommunityModeratorView> = context
CommunityModeratorView::for_community(conn, community_id) .conn()
}) .await?
.await? .interact(move |conn| CommunityModeratorView::for_community(conn, community_id))
.map_err(|e| ApiError::err("couldnt_find_community", e))?; .await?
.map_err(|e| ApiError::err("couldnt_find_community", e))?;
let online = context let online = context
.chat_server() .chat_server()
@ -106,17 +108,20 @@ impl PerformCrud for ListCommunities {
let page = data.page; let page = data.page;
let limit = data.limit; let limit = data.limit;
let mut communities = blocking(context.pool(), move |conn| { let mut communities = context
CommunityQueryBuilder::create(conn) .conn()
.listing_type(listing_type) .await?
.sort(sort) .interact(move |conn| {
.show_nsfw(show_nsfw) CommunityQueryBuilder::create(conn)
.my_person_id(person_id) .listing_type(listing_type)
.page(page) .sort(sort)
.limit(limit) .show_nsfw(show_nsfw)
.list() .my_person_id(person_id)
}) .page(page)
.await??; .limit(limit)
.list()
})
.await??;
// Blank out deleted or removed info for non-logged in users // Blank out deleted or removed info for non-logged in users
if person_id.is_none() { if person_id.is_none() {

View file

@ -1,7 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
community::{CommunityResponse, EditCommunity}, community::{CommunityResponse, EditCommunity},
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
}; };
@ -35,20 +34,24 @@ impl PerformCrud for EditCommunity {
// Verify its a mod (only mods can edit it) // Verify its a mod (only mods can edit it)
let community_id = data.community_id; let community_id = data.community_id;
let mods: Vec<PersonId> = blocking(context.pool(), move |conn| { let mods: Vec<PersonId> = context
CommunityModeratorView::for_community(conn, community_id) .conn()
.map(|v| v.into_iter().map(|m| m.moderator.id).collect()) .await?
}) .interact(move |conn| {
.await??; 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) { if !mods.contains(&local_user_view.person.id) {
return Err(ApiError::err_plain("not_a_moderator").into()); return Err(ApiError::err_plain("not_a_moderator").into());
} }
let community_id = data.community_id; let community_id = data.community_id;
let read_community = blocking(context.pool(), move |conn| { let read_community = context
Community::read(conn, community_id) .conn()
}) .await?
.await??; .interact(move |conn| Community::read(conn, community_id))
.await??;
let icon = diesel_option_overwrite_to_url(&data.icon)?; let icon = diesel_option_overwrite_to_url(&data.icon)?;
let banner = diesel_option_overwrite_to_url(&data.banner)?; let banner = diesel_option_overwrite_to_url(&data.banner)?;
@ -65,11 +68,12 @@ impl PerformCrud for EditCommunity {
}; };
let community_id = data.community_id; let community_id = data.community_id;
let updated_community = blocking(context.pool(), move |conn| { let updated_community = context
Community::update(conn, community_id, &community_form) .conn()
}) .await?
.await? .interact(move |conn| Community::update(conn, community_id, &community_form))
.map_err(|e| ApiError::err("couldnt_update_community", e))?; .await?
.map_err(|e| ApiError::err("couldnt_update_community", e))?;
UpdateCommunity::send( UpdateCommunity::send(
updated_community.into(), updated_community.into(),

View file

@ -1,7 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
check_community_ban, check_community_ban,
check_community_deleted_or_removed, check_community_deleted_or_removed,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
@ -83,32 +82,39 @@ impl PerformCrud for CreatePost {
..PostForm::default() ..PostForm::default()
}; };
let inserted_post = let inserted_post = match context
match blocking(context.pool(), move |conn| Post::create(conn, &post_form)).await? { .conn()
Ok(post) => post, .await?
Err(e) => { .interact(move |conn| Post::create(conn, &post_form))
let err_type = if e.to_string() == "value too long for type character varying(200)" { .await?
"post_title_too_long" {
} else { Ok(post) => post,
"couldnt_create_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 inserted_post_id = inserted_post.id;
let protocol_and_hostname = context.settings().get_protocol_and_hostname(); let protocol_and_hostname = context.settings().get_protocol_and_hostname();
let updated_post = blocking(context.pool(), move |conn| -> Result<Post, LemmyError> { let updated_post = context
let apub_id = generate_local_apub_endpoint( .conn()
EndpointType::Post, .await?
&inserted_post_id.to_string(), .interact(move |conn| -> Result<Post, LemmyError> {
&protocol_and_hostname, let apub_id = generate_local_apub_endpoint(
)?; EndpointType::Post,
Ok(Post::update_ap_id(conn, inserted_post_id, apub_id)?) &inserted_post_id.to_string(),
}) &protocol_and_hostname,
.await? )?;
.map_err(|e| ApiError::err("couldnt_create_post", e))?; 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 // They like their own post by default
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
@ -119,8 +125,13 @@ impl PerformCrud for CreatePost {
score: 1, score: 1,
}; };
let like = move |conn: &'_ _| PostLike::like(conn, &like_form); if context
if blocking(context.pool(), like).await?.is_err() { .conn()
.await?
.interact(move |conn| PostLike::like(conn, &like_form))
.await?
.is_err()
{
return Err(ApiError::err_plain("couldnt_like_post").into()); return Err(ApiError::err_plain("couldnt_like_post").into());
} }

View file

@ -1,7 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
check_community_ban, check_community_ban,
check_community_deleted_or_removed, check_community_deleted_or_removed,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
@ -34,7 +33,11 @@ impl PerformCrud for DeletePost {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let post_id = data.post_id; let post_id = data.post_id;
let orig_post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; let orig_post = context
.conn()
.await?
.interact(move |conn| Post::read(conn, post_id))
.await??;
// Dont delete it if its already been deleted. // Dont delete it if its already been deleted.
if orig_post.deleted == data.deleted { if orig_post.deleted == data.deleted {
@ -57,16 +60,18 @@ impl PerformCrud for DeletePost {
// Update the post // Update the post
let post_id = data.post_id; let post_id = data.post_id;
let deleted = data.deleted; let deleted = data.deleted;
let updated_post = blocking(context.pool(), move |conn| { let updated_post = context
Post::update_deleted(conn, post_id, deleted) .conn()
}) .await?
.await??; .interact(move |conn| Post::update_deleted(conn, post_id, deleted))
.await??;
// apub updates // apub updates
let community = blocking(context.pool(), move |conn| { let community = context
Community::read(conn, orig_post.community_id) .conn()
}) .await?
.await??; .interact(move |conn| Community::read(conn, orig_post.community_id))
.await??;
send_apub_delete( send_apub_delete(
&local_user_view.person.clone().into(), &local_user_view.person.clone().into(),
&community.into(), &community.into(),
@ -101,7 +106,11 @@ impl PerformCrud for RemovePost {
get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?; get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
let post_id = data.post_id; let post_id = data.post_id;
let orig_post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??; let orig_post = context
.conn()
.await?
.interact(move |conn| Post::read(conn, post_id))
.await??;
check_community_ban( check_community_ban(
local_user_view.person.id, local_user_view.person.id,
@ -121,10 +130,11 @@ impl PerformCrud for RemovePost {
// Update the post // Update the post
let post_id = data.post_id; let post_id = data.post_id;
let removed = data.removed; let removed = data.removed;
let updated_post = blocking(context.pool(), move |conn| { let updated_post = context
Post::update_removed(conn, post_id, removed) .conn()
}) .await?
.await??; .interact(move |conn| Post::update_removed(conn, post_id, removed))
.await??;
// Mod tables // Mod tables
let form = ModRemovePostForm { let form = ModRemovePostForm {
@ -133,16 +143,18 @@ impl PerformCrud for RemovePost {
removed: Some(removed), removed: Some(removed),
reason: data.reason.to_owned(), reason: data.reason.to_owned(),
}; };
blocking(context.pool(), move |conn| { context
ModRemovePost::create(conn, &form) .conn()
}) .await?
.await??; .interact(move |conn| ModRemovePost::create(conn, &form))
.await??;
// apub updates // apub updates
let community = blocking(context.pool(), move |conn| { let community = context
Community::read(conn, orig_post.community_id) .conn()
}) .await?
.await??; .interact(move |conn| Community::read(conn, orig_post.community_id))
.await??;
send_apub_remove( send_apub_remove(
&local_user_view.person.clone().into(), &local_user_view.person.clone().into(),
&community.into(), &community.into(),

View file

@ -1,6 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{blocking, get_local_user_view_from_jwt_opt, mark_post_as_read, post::*}; use lemmy_api_common::{get_local_user_view_from_jwt_opt, mark_post_as_read, post::*};
use lemmy_apub::get_actor_id_from_name; use lemmy_apub::get_actor_id_from_name;
use lemmy_apub_lib::webfinger::WebfingerType; use lemmy_apub_lib::webfinger::WebfingerType;
use lemmy_db_schema::{ use lemmy_db_schema::{
@ -39,11 +39,12 @@ impl PerformCrud for GetPost {
let person_id = local_user_view.map(|u| u.person.id); let person_id = local_user_view.map(|u| u.person.id);
let id = data.id; let id = data.id;
let mut post_view = blocking(context.pool(), move |conn| { let mut post_view = context
PostView::read(conn, id, person_id) .conn()
}) .await?
.await? .interact(move |conn| PostView::read(conn, id, person_id))
.map_err(|e| ApiError::err("couldnt_find_post", e))?; .await?
.map_err(|e| ApiError::err("couldnt_find_post", e))?;
// Mark the post as read // Mark the post as read
if let Some(person_id) = person_id { if let Some(person_id) = person_id {
@ -51,23 +52,27 @@ impl PerformCrud for GetPost {
} }
let id = data.id; let id = data.id;
let mut comments = blocking(context.pool(), move |conn| { let mut comments = context
CommentQueryBuilder::create(conn) .conn()
.my_person_id(person_id) .await?
.show_bot_accounts(show_bot_accounts) .interact(move |conn| {
.post_id(id) CommentQueryBuilder::create(conn)
.limit(9999) .my_person_id(person_id)
.list() .show_bot_accounts(show_bot_accounts)
}) .post_id(id)
.await??; .limit(9999)
.list()
})
.await??;
// Necessary for the sidebar // Necessary for the sidebar
let community_id = post_view.community.id; let community_id = post_view.community.id;
let mut community_view = blocking(context.pool(), move |conn| { let mut community_view = context
CommunityView::read(conn, community_id, person_id) .conn()
}) .await?
.await? .interact(move |conn| CommunityView::read(conn, community_id, person_id))
.map_err(|e| ApiError::err("couldnt_find_community", e))?; .await?
.map_err(|e| ApiError::err("couldnt_find_community", e))?;
// Blank out deleted or removed info for non-logged in users // Blank out deleted or removed info for non-logged in users
if person_id.is_none() { if person_id.is_none() {
@ -86,10 +91,11 @@ impl PerformCrud for GetPost {
} }
} }
let moderators = blocking(context.pool(), move |conn| { let moderators = context
CommunityModeratorView::for_community(conn, community_id) .conn()
}) .await?
.await??; .interact(move |conn| CommunityModeratorView::for_community(conn, community_id))
.await??;
let online = context let online = context
.chat_server() .chat_server()
@ -146,23 +152,26 @@ impl PerformCrud for GetPosts {
}; };
let saved_only = data.saved_only; let saved_only = data.saved_only;
let mut posts = blocking(context.pool(), move |conn| { let mut posts = context
PostQueryBuilder::create(conn) .conn()
.listing_type(listing_type) .await?
.sort(sort) .interact(move |conn| {
.show_nsfw(show_nsfw) PostQueryBuilder::create(conn)
.show_bot_accounts(show_bot_accounts) .listing_type(listing_type)
.show_read_posts(show_read_posts) .sort(sort)
.community_id(community_id) .show_nsfw(show_nsfw)
.community_actor_id(community_actor_id) .show_bot_accounts(show_bot_accounts)
.saved_only(saved_only) .show_read_posts(show_read_posts)
.my_person_id(person_id) .community_id(community_id)
.page(page) .community_actor_id(community_actor_id)
.limit(limit) .saved_only(saved_only)
.list() .my_person_id(person_id)
}) .page(page)
.await? .limit(limit)
.map_err(|e| ApiError::err("couldnt_get_posts", e))?; .list()
})
.await?
.map_err(|e| ApiError::err("couldnt_get_posts", e))?;
// Blank out deleted or removed info for non-logged in users // Blank out deleted or removed info for non-logged in users
if person_id.is_none() { if person_id.is_none() {

View file

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

View file

@ -1,7 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
check_person_block, check_person_block,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
person::{CreatePrivateMessage, PrivateMessageResponse}, person::{CreatePrivateMessage, PrivateMessageResponse},
@ -51,10 +50,11 @@ impl PerformCrud for CreatePrivateMessage {
..PrivateMessageForm::default() ..PrivateMessageForm::default()
}; };
let inserted_private_message = match blocking(context.pool(), move |conn| { let inserted_private_message = match context
PrivateMessage::create(conn, &private_message_form) .conn()
}) .await?
.await? .interact(move |conn| PrivateMessage::create(conn, &private_message_form))
.await?
{ {
Ok(private_message) => private_message, Ok(private_message) => private_message,
Err(e) => { Err(e) => {
@ -64,9 +64,10 @@ impl PerformCrud for CreatePrivateMessage {
let inserted_private_message_id = inserted_private_message.id; let inserted_private_message_id = inserted_private_message.id;
let protocol_and_hostname = context.settings().get_protocol_and_hostname(); let protocol_and_hostname = context.settings().get_protocol_and_hostname();
let updated_private_message = blocking( let updated_private_message = context
context.pool(), .conn()
move |conn| -> Result<PrivateMessage, LemmyError> { .await?
.interact(move |conn| -> Result<PrivateMessage, LemmyError> {
let apub_id = generate_local_apub_endpoint( let apub_id = generate_local_apub_endpoint(
EndpointType::PrivateMessage, EndpointType::PrivateMessage,
&inserted_private_message_id.to_string(), &inserted_private_message_id.to_string(),
@ -77,10 +78,9 @@ impl PerformCrud for CreatePrivateMessage {
inserted_private_message_id, inserted_private_message_id,
apub_id, apub_id,
)?) )?)
}, })
) .await?
.await? .map_err(|e| ApiError::err("couldnt_create_private_message", e))?;
.map_err(|e| ApiError::err("couldnt_create_private_message", e))?;
CreateOrUpdatePrivateMessage::send( CreateOrUpdatePrivateMessage::send(
updated_private_message.into(), updated_private_message.into(),
@ -101,10 +101,11 @@ impl PerformCrud for CreatePrivateMessage {
// Send email to the local recipient, if one exists // Send email to the local recipient, if one exists
if res.private_message_view.recipient.local { if res.private_message_view.recipient.local {
let recipient_id = data.recipient_id; let recipient_id = data.recipient_id;
let local_recipient = blocking(context.pool(), move |conn| { let local_recipient = context
LocalUserView::read_person(conn, recipient_id) .conn()
}) .await?
.await??; .interact(move |conn| LocalUserView::read_person(conn, recipient_id))
.await??;
send_email_to_user( send_email_to_user(
&local_recipient, &local_recipient,
"Private Message from", "Private Message from",

View file

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

View file

@ -1,7 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
person::{GetPrivateMessages, PrivateMessagesResponse}, person::{GetPrivateMessages, PrivateMessagesResponse},
}; };
@ -27,14 +26,17 @@ impl PerformCrud for GetPrivateMessages {
let page = data.page; let page = data.page;
let limit = data.limit; let limit = data.limit;
let unread_only = data.unread_only; let unread_only = data.unread_only;
let mut messages = blocking(context.pool(), move |conn| { let mut messages = context
PrivateMessageQueryBuilder::create(conn, person_id) .conn()
.page(page) .await?
.limit(limit) .interact(move |conn| {
.unread_only(unread_only) PrivateMessageQueryBuilder::create(conn, person_id)
.list() .page(page)
}) .limit(limit)
.await??; .unread_only(unread_only)
.list()
})
.await??;
// Blank out deleted or removed info // Blank out deleted or removed info
for pmv in messages for pmv in messages

View file

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

View file

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

View file

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

View file

@ -1,7 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
is_admin, is_admin,
site::{EditSite, SiteResponse}, site::{EditSite, SiteResponse},
@ -36,7 +35,11 @@ impl PerformCrud for EditSite {
// Make sure user is an admin // Make sure user is an admin
is_admin(&local_user_view)?; is_admin(&local_user_view)?;
let found_site = blocking(context.pool(), Site::read_simple).await??; let found_site = context
.conn()
.await?
.interact(|conn| Site::read_simple(conn))
.await??;
let sidebar = diesel_option_overwrite(&data.sidebar); let sidebar = diesel_option_overwrite(&data.sidebar);
let description = diesel_option_overwrite(&data.description); let description = diesel_option_overwrite(&data.description);
@ -61,12 +64,18 @@ impl PerformCrud for EditSite {
community_creation_admin_only: data.community_creation_admin_only, community_creation_admin_only: data.community_creation_admin_only,
}; };
let update_site = move |conn: &'_ _| Site::update(conn, 1, &site_form); context
blocking(context.pool(), update_site) .conn()
.await?
.interact(move |conn| Site::update(conn, 1, &site_form))
.await? .await?
.map_err(|e| ApiError::err("couldnt_update_site", e))?; .map_err(|e| ApiError::err("couldnt_update_site", e))?;
let site_view = blocking(context.pool(), SiteView::read).await??; let site_view = context
.conn()
.await?
.interact(|conn| SiteView::read(conn))
.await??;
let res = SiteResponse { site_view }; let res = SiteResponse { site_view };

View file

@ -1,6 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{blocking, honeypot_check, password_length_check, person::*}; use lemmy_api_common::{honeypot_check, password_length_check, person::*};
use lemmy_apub::{ use lemmy_apub::{
generate_followers_url, generate_followers_url,
generate_inbox_url, generate_inbox_url,
@ -50,7 +50,12 @@ impl PerformCrud for Register {
let data: &Register = self; let data: &Register = self;
// Make sure site has open registration // Make sure site has open registration
if let Ok(site) = blocking(context.pool(), Site::read_simple).await? { if let Ok(site) = context
.conn()
.await?
.interact(|conn| Site::read_simple(conn))
.await?
{
if !site.open_registration { if !site.open_registration {
return Err(ApiError::err_plain("registration_closed").into()); return Err(ApiError::err_plain("registration_closed").into());
} }
@ -65,10 +70,11 @@ impl PerformCrud for Register {
} }
// Check if there are admins. False if admins exist // Check if there are admins. False if admins exist
let no_admins = blocking(context.pool(), move |conn| { let no_admins = context
PersonViewSafe::admins(conn).map(|a| a.is_empty()) .conn()
}) .await?
.await??; .interact(move |conn| PersonViewSafe::admins(conn).map(|a| a.is_empty()))
.await??;
// If its not the admin, check the captcha // If its not the admin, check the captcha
if !no_admins && context.settings().captcha.enabled { if !no_admins && context.settings().captcha.enabled {
@ -117,11 +123,12 @@ impl PerformCrud for Register {
}; };
// insert the person // insert the person
let inserted_person = blocking(context.pool(), move |conn| { let inserted_person = context
Person::create(conn, &person_form) .conn()
}) .await?
.await? .interact(move |conn| Person::create(conn, &person_form))
.map_err(|e| ApiError::err("user_already_exists", e))?; .await?
.map_err(|e| ApiError::err("user_already_exists", e))?;
// Create the local user // Create the local user
// TODO some of these could probably use the DB defaults // TODO some of these could probably use the DB defaults
@ -142,10 +149,11 @@ impl PerformCrud for Register {
send_notifications_to_email: Some(false), send_notifications_to_email: Some(false),
}; };
let inserted_local_user = match blocking(context.pool(), move |conn| { let inserted_local_user = match context
LocalUser::register(conn, &local_user_form) .conn()
}) .await?
.await? .interact(move |conn| LocalUser::register(conn, &local_user_form))
.await?
{ {
Ok(lu) => lu, Ok(lu) => lu,
Err(e) => { Err(e) => {
@ -158,10 +166,11 @@ impl PerformCrud for Register {
}; };
// If the local user creation errored, then delete that person // If the local user creation errored, then delete that person
blocking(context.pool(), move |conn| { context
Person::delete(conn, inserted_person.id) .conn()
}) .await?
.await??; .interact(move |conn| Person::delete(conn, inserted_person.id))
.await??;
return Err(ApiError::err(err_type, e).into()); 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 // Create the main community if it doesn't exist
let protocol_and_hostname = context.settings().get_protocol_and_hostname(); let protocol_and_hostname = context.settings().get_protocol_and_hostname();
let main_community = match blocking(context.pool(), move |conn| { let main_community = match context
Community::read(conn, CommunityId(2)) .conn()
}) .await?
.await? .interact(move |conn| Community::read(conn, CommunityId(2)))
.await?
{ {
Ok(c) => c, Ok(c) => c,
Err(_e) => { Err(_e) => {
@ -196,10 +206,11 @@ impl PerformCrud for Register {
shared_inbox_url: Some(Some(generate_shared_inbox_url(&actor_id)?)), shared_inbox_url: Some(Some(generate_shared_inbox_url(&actor_id)?)),
..CommunityForm::default() ..CommunityForm::default()
}; };
blocking(context.pool(), move |conn| { context
Community::create(conn, &community_form) .conn()
}) .await?
.await?? .interact(move |conn| Community::create(conn, &community_form))
.await??
} }
}; };
@ -210,8 +221,10 @@ impl PerformCrud for Register {
pending: false, pending: false,
}; };
let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form); context
blocking(context.pool(), follow) .conn()
.await?
.interact(move |conn| CommunityFollower::follow(conn, &community_follower_form))
.await? .await?
.map_err(|e| ApiError::err("community_follower_already_exists", e))?; .map_err(|e| ApiError::err("community_follower_already_exists", e))?;
@ -222,8 +235,10 @@ impl PerformCrud for Register {
person_id: inserted_person.id, person_id: inserted_person.id,
}; };
let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form); context
blocking(context.pool(), join) .conn()
.await?
.interact(move |conn| CommunityModerator::join(conn, &community_moderator_form))
.await? .await?
.map_err(|e| ApiError::err("community_moderator_already_exists", e))?; .map_err(|e| ApiError::err("community_moderator_already_exists", e))?;
} }

View file

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

View file

@ -1,6 +1,6 @@
use crate::PerformCrud; use crate::PerformCrud;
use actix_web::web::Data; use actix_web::web::Data;
use lemmy_api_common::{blocking, get_local_user_view_from_jwt_opt, person::*}; use lemmy_api_common::{get_local_user_view_from_jwt_opt, person::*};
use lemmy_apub::{get_actor_id_from_name, objects::person::ApubPerson}; use lemmy_apub::{get_actor_id_from_name, objects::person::ApubPerson};
use lemmy_apub_lib::{object_id::ObjectId, webfinger::WebfingerType}; use lemmy_apub_lib::{object_id::ObjectId, webfinger::WebfingerType};
use lemmy_db_schema::{from_opt_str_to_opt_enum, SortType}; use lemmy_db_schema::{from_opt_str_to_opt_enum, SortType};
@ -57,55 +57,60 @@ impl PerformCrud for GetPersonDetails {
// You don't need to return settings for the user, since this comes back with GetSite // You don't need to return settings for the user, since this comes back with GetSite
// `my_user` // `my_user`
let person_view = blocking(context.pool(), move |conn| { let person_view = context
PersonViewSafe::read(conn, person_details_id) .conn()
}) .await?
.await??; .interact(move |conn| PersonViewSafe::read(conn, person_details_id))
.await??;
let page = data.page; let page = data.page;
let limit = data.limit; let limit = data.limit;
let saved_only = data.saved_only; let saved_only = data.saved_only;
let community_id = data.community_id; let community_id = data.community_id;
let (posts, comments) = blocking(context.pool(), move |conn| { let (posts, comments) = context
let mut posts_query = PostQueryBuilder::create(conn) .conn()
.sort(sort) .await?
.show_nsfw(show_nsfw) .interact(move |conn| {
.show_bot_accounts(show_bot_accounts) let mut posts_query = PostQueryBuilder::create(conn)
.show_read_posts(show_read_posts) .sort(sort)
.saved_only(saved_only) .show_nsfw(show_nsfw)
.community_id(community_id) .show_bot_accounts(show_bot_accounts)
.my_person_id(person_id) .show_read_posts(show_read_posts)
.page(page) .saved_only(saved_only)
.limit(limit); .community_id(community_id)
.my_person_id(person_id)
.page(page)
.limit(limit);
let mut comments_query = CommentQueryBuilder::create(conn) let mut comments_query = CommentQueryBuilder::create(conn)
.my_person_id(person_id) .my_person_id(person_id)
.show_bot_accounts(show_bot_accounts) .show_bot_accounts(show_bot_accounts)
.sort(sort) .sort(sort)
.saved_only(saved_only) .saved_only(saved_only)
.community_id(community_id) .community_id(community_id)
.page(page) .page(page)
.limit(limit); .limit(limit);
// If its saved only, you don't care what creator it was // If its saved only, you don't care what creator it was
// Or, if its not saved, then you only want it for that specific creator // Or, if its not saved, then you only want it for that specific creator
if !saved_only.unwrap_or(false) { if !saved_only.unwrap_or(false) {
posts_query = posts_query.creator_id(person_details_id); posts_query = posts_query.creator_id(person_details_id);
comments_query = comments_query.creator_id(person_details_id); comments_query = comments_query.creator_id(person_details_id);
} }
let posts = posts_query.list()?; let posts = posts_query.list()?;
let comments = comments_query.list()?; let comments = comments_query.list()?;
Ok((posts, comments)) as Result<_, LemmyError> Ok((posts, comments)) as Result<_, LemmyError>
}) })
.await??; .await??;
let moderates = blocking(context.pool(), move |conn| { let moderates = context
CommunityModeratorView::for_person(conn, person_details_id) .conn()
}) .await?
.await??; .interact(move |conn| CommunityModeratorView::for_person(conn, person_details_id))
.await??;
// Return the jwt // Return the jwt
Ok(GetPersonDetailsResponse { Ok(GetPersonDetailsResponse {

View file

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

View file

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

View file

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

View file

@ -14,7 +14,6 @@ use crate::{
protocol::activities::community::add_mod::AddMod, protocol::activities::community::add_mod::AddMod,
}; };
use activitystreams::{activity::kind::AddType, public}; use activitystreams::{activity::kind::AddType, public};
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
data::Data, data::Data,
object_id::ObjectId, object_id::ObjectId,
@ -84,19 +83,21 @@ impl ActivityHandler for AddMod {
// If we had to refetch the community while parsing the activity, then the new mod has already // If we had to refetch the community while parsing the activity, then the new mod has already
// been added. Skip it here as it would result in a duplicate key error. // been added. Skip it here as it would result in a duplicate key error.
let new_mod_id = new_mod.id; let new_mod_id = new_mod.id;
let moderated_communities = blocking(context.pool(), move |conn| { let moderated_communities = context
CommunityModerator::get_person_moderated_communities(conn, new_mod_id) .conn()
}) .await?
.await??; .interact(move |conn| CommunityModerator::get_person_moderated_communities(conn, new_mod_id))
.await??;
if !moderated_communities.contains(&community.id) { if !moderated_communities.contains(&community.id) {
let form = CommunityModeratorForm { let form = CommunityModeratorForm {
community_id: community.id, community_id: community.id,
person_id: new_mod.id, person_id: new_mod.id,
}; };
blocking(context.pool(), move |conn| { context
CommunityModerator::join(conn, &form) .conn()
}) .await?
.await??; .interact(move |conn| CommunityModerator::join(conn, &form))
.await??;
} }
// TODO: send websocket notification about added mod // TODO: send websocket notification about added mod
Ok(()) Ok(())

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -12,7 +12,6 @@ use crate::{
}; };
use activitystreams::{activity::kind::UndoType, public}; use activitystreams::{activity::kind::UndoType, public};
use anyhow::anyhow; use anyhow::anyhow;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
data::Data, data::Data,
object_id::ObjectId, object_id::ObjectId,
@ -109,24 +108,27 @@ impl UndoDelete {
if community.local { if community.local {
return Err(anyhow!("Only local admin can restore community").into()); return Err(anyhow!("Only local admin can restore community").into());
} }
let deleted_community = blocking(context.pool(), move |conn| { let deleted_community = context
Community::update_removed(conn, community.id, false) .conn()
}) .await?
.await??; .interact(move |conn| Community::update_removed(conn, community.id, false))
.await??;
send_community_ws_message(deleted_community.id, EditCommunity, None, None, context).await?; send_community_ws_message(deleted_community.id, EditCommunity, None, None, context).await?;
} }
DeletableObjects::Post(post) => { DeletableObjects::Post(post) => {
let removed_post = blocking(context.pool(), move |conn| { let removed_post = context
Post::update_removed(conn, post.id, false) .conn()
}) .await?
.await??; .interact(move |conn| Post::update_removed(conn, post.id, false))
.await??;
send_post_ws_message(removed_post.id, EditPost, None, None, context).await?; send_post_ws_message(removed_post.id, EditPost, None, None, context).await?;
} }
DeletableObjects::Comment(comment) => { DeletableObjects::Comment(comment) => {
let removed_comment = blocking(context.pool(), move |conn| { let removed_comment = context
Comment::update_removed(conn, comment.id, false) .conn()
}) .await?
.await??; .interact(move |conn| Comment::update_removed(conn, comment.id, false))
.await??;
send_comment_ws_message_simple(removed_comment.id, EditComment, context).await?; send_comment_ws_message_simple(removed_comment.id, EditComment, context).await?;
} }
} }

View file

@ -3,7 +3,6 @@ use crate::{
protocol::activities::following::{accept::AcceptFollowCommunity, follow::FollowCommunity}, protocol::activities::following::{accept::AcceptFollowCommunity, follow::FollowCommunity},
}; };
use activitystreams::activity::kind::AcceptType; use activitystreams::activity::kind::AcceptType;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
data::Data, data::Data,
object_id::ObjectId, object_id::ObjectId,
@ -66,10 +65,11 @@ impl ActivityHandler for AcceptFollowCommunity {
let actor = self.actor.dereference(context, request_counter).await?; let actor = self.actor.dereference(context, request_counter).await?;
let to = self.to[0].dereference(context, request_counter).await?; let to = self.to[0].dereference(context, request_counter).await?;
// This will throw an error if no follow was requested // This will throw an error if no follow was requested
blocking(context.pool(), move |conn| { context
CommunityFollower::follow_accepted(conn, actor.id, to.id) .conn()
}) .await?
.await??; .interact(move |conn| CommunityFollower::follow_accepted(conn, actor.id, to.id))
.await??;
Ok(()) Ok(())
} }

View file

@ -10,7 +10,6 @@ use crate::{
protocol::activities::following::{accept::AcceptFollowCommunity, follow::FollowCommunity}, protocol::activities::following::{accept::AcceptFollowCommunity, follow::FollowCommunity},
}; };
use activitystreams::activity::kind::FollowType; use activitystreams::activity::kind::FollowType;
use lemmy_api_common::blocking;
use lemmy_apub_lib::{ use lemmy_apub_lib::{
data::Data, data::Data,
object_id::ObjectId, object_id::ObjectId,
@ -52,10 +51,11 @@ impl FollowCommunity {
person_id: actor.id, person_id: actor.id,
pending: true, pending: true,
}; };
blocking(context.pool(), move |conn| { context
CommunityFollower::follow(conn, &community_follower_form).ok() .conn()
}) .await?
.await?; .interact(move |conn| CommunityFollower::follow(conn, &community_follower_form).ok())
.await?;
let follow = FollowCommunity::new(actor, community, context)?; let follow = FollowCommunity::new(actor, community, context)?;
let inbox = vec![community.inbox_url.clone().into()]; 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. // This will fail if they're already a follower, but ignore the error.
blocking(context.pool(), move |conn| { context
CommunityFollower::follow(conn, &community_follower_form).ok() .conn()
}) .await?
.await?; .interact(move |conn| CommunityFollower::follow(conn, &community_follower_form).ok())
.await?;
AcceptFollowCommunity::send(self, context, request_counter).await AcceptFollowCommunity::send(self, context, request_counter).await
} }

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -22,7 +22,6 @@ use crate::{
}, },
}; };
use actix_web::{body::Body, web, web::Payload, HttpRequest, HttpResponse}; use actix_web::{body::Body, web, web::Payload, HttpRequest, HttpResponse};
use lemmy_api_common::blocking;
use lemmy_apub_lib::{object_id::ObjectId, traits::ApubObject}; use lemmy_apub_lib::{object_id::ObjectId, traits::ApubObject};
use lemmy_db_schema::source::community::Community; use lemmy_db_schema::source::community::Community;
use lemmy_utils::LemmyError; use lemmy_utils::LemmyError;
@ -40,11 +39,12 @@ pub(crate) async fn get_apub_community_http(
info: web::Path<CommunityQuery>, info: web::Path<CommunityQuery>,
context: web::Data<LemmyContext>, context: web::Data<LemmyContext>,
) -> Result<HttpResponse<Body>, LemmyError> { ) -> Result<HttpResponse<Body>, LemmyError> {
let community: ApubCommunity = blocking(context.pool(), move |conn| { let community: ApubCommunity = context
Community::read_from_name(conn, &info.community_name) .conn()
}) .await?
.await?? .interact(move |conn| Community::read_from_name(conn, &info.community_name))
.into(); .await??
.into();
if !community.deleted { if !community.deleted {
let apub = community.into_apub(&**context).await?; let apub = community.into_apub(&**context).await?;
@ -97,10 +97,11 @@ pub(crate) async fn get_apub_community_followers(
info: web::Path<CommunityQuery>, info: web::Path<CommunityQuery>,
context: web::Data<LemmyContext>, context: web::Data<LemmyContext>,
) -> Result<HttpResponse<Body>, LemmyError> { ) -> Result<HttpResponse<Body>, LemmyError> {
let community = blocking(context.pool(), move |conn| { let community = context
Community::read_from_name(conn, &info.community_name) .conn()
}) .await?
.await??; .interact(move |conn| Community::read_from_name(conn, &info.community_name))
.await??;
let followers = GroupFollowers::new(community, &context).await?; let followers = GroupFollowers::new(community, &context).await?;
Ok(create_apub_response(&followers)) Ok(create_apub_response(&followers))
} }
@ -111,10 +112,11 @@ pub(crate) async fn get_apub_community_outbox(
info: web::Path<CommunityQuery>, info: web::Path<CommunityQuery>,
context: web::Data<LemmyContext>, context: web::Data<LemmyContext>,
) -> Result<HttpResponse<Body>, LemmyError> { ) -> Result<HttpResponse<Body>, LemmyError> {
let community = blocking(context.pool(), move |conn| { let community = context
Community::read_from_name(conn, &info.community_name) .conn()
}) .await?
.await??; .interact(move |conn| Community::read_from_name(conn, &info.community_name))
.await??;
let id = ObjectId::new(generate_outbox_url(&community.actor_id)?); let id = ObjectId::new(generate_outbox_url(&community.actor_id)?);
let outbox_data = CommunityContext(community.into(), context.get_ref().clone()); let outbox_data = CommunityContext(community.into(), context.get_ref().clone());
let outbox: ApubCommunityOutbox = id.dereference(&outbox_data, &mut 0).await?; 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>, info: web::Path<CommunityQuery>,
context: web::Data<LemmyContext>, context: web::Data<LemmyContext>,
) -> Result<HttpResponse<Body>, LemmyError> { ) -> Result<HttpResponse<Body>, LemmyError> {
let community: ApubCommunity = blocking(context.pool(), move |conn| { let community: ApubCommunity = context
Community::read_from_name(conn, &info.community_name) .conn()
}) .await?
.await?? .interact(move |conn| Community::read_from_name(conn, &info.community_name))
.into(); .await??
.into();
let id = ObjectId::new(generate_outbox_url(&community.actor_id)?); let id = ObjectId::new(generate_outbox_url(&community.actor_id)?);
let outbox_data = CommunityContext(community, context.get_ref().clone()); let outbox_data = CommunityContext(community, context.get_ref().clone());
let moderators: ApubCommunityModerators = id.dereference(&outbox_data, &mut 0).await?; let moderators: ApubCommunityModerators = id.dereference(&outbox_data, &mut 0).await?;

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -2,7 +2,6 @@ use actix_web::{error::ErrorBadRequest, *};
use anyhow::anyhow; use anyhow::anyhow;
use chrono::{DateTime, NaiveDateTime, Utc}; use chrono::{DateTime, NaiveDateTime, Utc};
use diesel::PgConnection; use diesel::PgConnection;
use lemmy_api_common::blocking;
use lemmy_db_schema::{ use lemmy_db_schema::{
newtypes::LocalUserId, newtypes::LocalUserId,
source::{community::Community, local_user::LocalUser, person::Person}, source::{community::Community, local_user::LocalUser, person::Person},
@ -80,15 +79,22 @@ async fn get_feed_data(
listing_type: ListingType, listing_type: ListingType,
sort_type: SortType, sort_type: SortType,
) -> Result<HttpResponse, LemmyError> { ) -> Result<HttpResponse, LemmyError> {
let site_view = blocking(context.pool(), SiteView::read).await??; let site_view = context
.conn()
.await?
.interact(|conn| SiteView::read(conn))
.await??;
let posts = blocking(context.pool(), move |conn| { let posts = context
PostQueryBuilder::create(conn) .conn()
.listing_type(listing_type) .await?
.sort(sort_type) .interact(move |conn| {
.list() PostQueryBuilder::create(conn)
}) .listing_type(listing_type)
.await??; .sort(sort_type)
.list()
})
.await??;
let items = create_post_items(posts, &context.settings().get_protocol_and_hostname())?; 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 jwt_secret = context.secret().jwt_secret.to_owned();
let protocol_and_hostname = context.settings().get_protocol_and_hostname(); let protocol_and_hostname = context.settings().get_protocol_and_hostname();
let builder = blocking(context.pool(), move |conn| match request_type { let builder = context
RequestType::User => get_feed_user(conn, &sort_type, &param, &protocol_and_hostname), .conn()
RequestType::Community => get_feed_community(conn, &sort_type, &param, &protocol_and_hostname), .await
RequestType::Front => get_feed_front( .map_err(ErrorBadRequest)?
conn, .interact(move |conn| match request_type {
&jwt_secret, RequestType::User => get_feed_user(conn, &sort_type, &param, &protocol_and_hostname),
&sort_type, RequestType::Community => {
&param, get_feed_community(conn, &sort_type, &param, &protocol_and_hostname)
&protocol_and_hostname, }
), RequestType::Front => get_feed_front(
RequestType::Inbox => get_feed_inbox(conn, &jwt_secret, &param, &protocol_and_hostname), conn,
}) &jwt_secret,
.await? &sort_type,
.map_err(ErrorBadRequest)?; &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(); let rss = builder.build().map_err(ErrorBadRequest)?.to_string();

View file

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

View file

@ -1,6 +1,5 @@
use actix_web::{error::ErrorBadRequest, web::Query, *}; use actix_web::{error::ErrorBadRequest, web::Query, *};
use anyhow::anyhow; use anyhow::anyhow;
use lemmy_api_common::blocking;
use lemmy_apub_lib::webfinger::{WebfingerLink, WebfingerResponse}; use lemmy_apub_lib::webfinger::{WebfingerLink, WebfingerResponse};
use lemmy_db_schema::source::{community::Community, person::Person}; use lemmy_db_schema::source::{community::Community, person::Person};
use lemmy_utils::{settings::structs::Settings, LemmyError}; use lemmy_utils::{settings::structs::Settings, LemmyError};
@ -48,21 +47,27 @@ async fn get_webfinger_response(
let url = if let Some(community_name) = community_regex_parsed { let url = if let Some(community_name) = community_regex_parsed {
let community_name = community_name.as_str().to_owned(); let community_name = community_name.as_str().to_owned();
// Make sure the requested community exists. // Make sure the requested community exists.
blocking(context.pool(), move |conn| { context
Community::read_from_name(conn, &community_name) .conn()
}) .await
.await? .map_err(|_| ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))?
.map_err(|_| ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))? .interact(move |conn| Community::read_from_name(conn, &community_name))
.actor_id .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 { } else if let Some(person_name) = username_regex_parsed {
let person_name = person_name.as_str().to_owned(); let person_name = person_name.as_str().to_owned();
// Make sure the requested person exists. // Make sure the requested person exists.
blocking(context.pool(), move |conn| { context
Person::find_by_name(conn, &person_name) .conn()
}) .await
.await? .map_err(|_| ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))?
.map_err(|_| ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))? .interact(move |conn| Person::find_by_name(conn, &person_name))
.actor_id .await
.map_err(|_| ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))?
.map_err(|_| ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))?
.actor_id
} else { } else {
return Err(ErrorBadRequest(LemmyError::from(anyhow!("not_found")))); return Err(ErrorBadRequest(LemmyError::from(anyhow!("not_found"))));
}; };

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -4,7 +4,6 @@ use crate::{
OperationType, OperationType,
}; };
use lemmy_api_common::{ use lemmy_api_common::{
blocking,
comment::CommentResponse, comment::CommentResponse,
community::CommunityResponse, community::CommunityResponse,
person::PrivateMessageResponse, person::PrivateMessageResponse,
@ -43,10 +42,11 @@ pub async fn send_post_ws_message<OP: ToString + Send + OperationType + 'static>
person_id: Option<PersonId>, person_id: Option<PersonId>,
context: &LemmyContext, context: &LemmyContext,
) -> Result<PostResponse, LemmyError> { ) -> Result<PostResponse, LemmyError> {
let post_view = blocking(context.pool(), move |conn| { let post_view = context
PostView::read(conn, post_id, person_id) .conn()
}) .await?
.await??; .interact(move |conn| PostView::read(conn, post_id, person_id))
.await??;
let res = PostResponse { post_view }; 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>, recipient_ids: Vec<LocalUserId>,
context: &LemmyContext, context: &LemmyContext,
) -> Result<CommentResponse, LemmyError> { ) -> Result<CommentResponse, LemmyError> {
let mut view = blocking(context.pool(), move |conn| { let mut view = context
CommentView::read(conn, comment_id, person_id) .conn()
}) .await?
.await??; .interact(move |conn| CommentView::read(conn, comment_id, person_id))
.await??;
if view.comment.deleted || view.comment.removed { if view.comment.deleted || view.comment.removed {
view.comment = view.comment.blank_out_deleted_or_removed_info(); view.comment = view.comment.blank_out_deleted_or_removed_info();
@ -114,10 +115,11 @@ pub async fn send_community_ws_message<OP: ToString + Send + OperationType + 'st
person_id: Option<PersonId>, person_id: Option<PersonId>,
context: &LemmyContext, context: &LemmyContext,
) -> Result<CommunityResponse, LemmyError> { ) -> Result<CommunityResponse, LemmyError> {
let community_view = blocking(context.pool(), move |conn| { let community_view = context
CommunityView::read(conn, community_id, person_id) .conn()
}) .await?
.await??; .interact(move |conn| CommunityView::read(conn, community_id, person_id))
.await??;
let res = CommunityResponse { community_view }; 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>, websocket_id: Option<ConnectionId>,
context: &LemmyContext, context: &LemmyContext,
) -> Result<PrivateMessageResponse, LemmyError> { ) -> Result<PrivateMessageResponse, LemmyError> {
let mut view = blocking(context.pool(), move |conn| { let mut view = context
PrivateMessageView::read(conn, private_message_id) .conn()
}) .await?
.await??; .interact(move |conn| PrivateMessageView::read(conn, private_message_id))
.await??;
// Blank out deleted or removed info // Blank out deleted or removed info
if view.private_message.deleted { if view.private_message.deleted {
@ -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 // Send notifications to the local recipient, if one exists
if res.private_message_view.recipient.local { if res.private_message_view.recipient.local {
let recipient_id = res.private_message_view.recipient.id; let recipient_id = res.private_message_view.recipient.id;
let local_recipient = blocking(context.pool(), move |conn| { let local_recipient = context
LocalUserView::read_person(conn, recipient_id) .conn()
}) .await?
.await??; .interact(move |conn| LocalUserView::read_person(conn, recipient_id))
.await??;
context.chat_server().do_send(SendUserRoomMessage { context.chat_server().do_send(SendUserRoomMessage {
op, op,
response: res.clone(), response: res.clone(),
@ -190,10 +194,11 @@ pub async fn send_local_notifs(
.collect::<Vec<&MentionData>>() .collect::<Vec<&MentionData>>()
{ {
let mention_name = mention.name.clone(); let mention_name = mention.name.clone();
let user_view = blocking(context.pool(), move |conn| { let user_view = context
LocalUserView::read_from_name(conn, &mention_name) .conn()
}) .await?
.await?; .interact(move |conn| LocalUserView::read_from_name(conn, &mention_name))
.await?;
if let Ok(mention_user_view) = user_view { if let Ok(mention_user_view) = user_view {
// TODO // TODO
// At some point, make it so you can't tag the parent creator either // 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 // Allow this to fail softly, since comment edits might re-update or replace it
// Let the uniqueness handle this fail // Let the uniqueness handle this fail
blocking(context.pool(), move |conn| { context
PersonMention::create(conn, &user_mention_form) .conn()
}) .await?
.await? .interact(move |conn| PersonMention::create(conn, &user_mention_form))
.ok(); .await?
.ok();
// Send an email to those local users that have notifications on // Send an email to those local users that have notifications on
if do_send_email { if do_send_email {
@ -230,16 +236,20 @@ pub async fn send_local_notifs(
// Send notifs to the parent commenter / poster // Send notifs to the parent commenter / poster
match comment.parent_id { match comment.parent_id {
Some(parent_id) => { Some(parent_id) => {
let parent_comment = let parent_comment = context
blocking(context.pool(), move |conn| Comment::read(conn, parent_id)).await?; .conn()
.await?
.interact(move |conn| Comment::read(conn, parent_id))
.await?;
if let Ok(parent_comment) = parent_comment { if let Ok(parent_comment) = parent_comment {
// Don't send a notif to yourself // Don't send a notif to yourself
if parent_comment.creator_id != person.id { if parent_comment.creator_id != person.id {
// Get the parent commenter local_user // Get the parent commenter local_user
let user_view = blocking(context.pool(), move |conn| { let user_view = context
LocalUserView::read_person(conn, parent_comment.creator_id) .conn()
}) .await?
.await?; .interact(move |conn| LocalUserView::read_person(conn, parent_comment.creator_id))
.await?;
if let Ok(parent_user_view) = user_view { if let Ok(parent_user_view) = user_view {
recipient_ids.push(parent_user_view.local_user.id); recipient_ids.push(parent_user_view.local_user.id);
@ -260,10 +270,11 @@ pub async fn send_local_notifs(
None => { None => {
if post.creator_id != person.id { if post.creator_id != person.id {
let creator_id = post.creator_id; let creator_id = post.creator_id;
let parent_user = blocking(context.pool(), move |conn| { let parent_user = context
LocalUserView::read_person(conn, creator_id) .conn()
}) .await?
.await?; .interact(move |conn| LocalUserView::read_person(conn, creator_id))
.await?;
if let Ok(parent_user_view) = parent_user { if let Ok(parent_user_view) = parent_user {
recipient_ids.push(parent_user_view.local_user.id); recipient_ids.push(parent_user_view.local_user.id);

View file

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

View file

@ -2,29 +2,33 @@
use clokwerk::{Scheduler, TimeUnits}; use clokwerk::{Scheduler, TimeUnits};
// Import week days and WeekDay // Import week days and WeekDay
use diesel::{sql_query, PgConnection, RunQueryDsl}; use diesel::{sql_query, PgConnection, RunQueryDsl};
use lemmy_db_schema::{source::activity::Activity, DbPool}; use lemmy_db_schema::{establish_unpooled_connection_with_db_url, source::activity::Activity};
use log::info; use log::info;
use std::{thread, time::Duration}; use std::{thread, time::Duration};
/// Schedules various cleanup tasks for lemmy in a background thread /// Schedules various cleanup tasks for lemmy in a background thread
pub fn setup(pool: DbPool) { pub fn setup(db_url: &str) {
let mut scheduler = Scheduler::new(); let mut scheduler = Scheduler::new();
let conn = pool.get().unwrap(); let conn = &establish_unpooled_connection_with_db_url(db_url);
active_counts(&conn);
active_counts(conn);
// On startup, reindex the tables non-concurrently // On startup, reindex the tables non-concurrently
// TODO remove this for now, since it slows down startup a lot on lemmy.ml // TODO remove this for now, since it slows down startup a lot on lemmy.ml
reindex_aggregates_tables(&conn, true); reindex_aggregates_tables(conn, true);
clear_old_activities(conn);
let db_url2 = db_url.to_owned();
scheduler.every(1.hour()).run(move || { scheduler.every(1.hour()).run(move || {
active_counts(&conn); let conn = &establish_unpooled_connection_with_db_url(&db_url2);
reindex_aggregates_tables(&conn, true); active_counts(conn);
reindex_aggregates_tables(conn, true);
}); });
let conn = pool.get().unwrap(); let db_url3 = db_url.to_owned();
clear_old_activities(&conn);
scheduler.every(1.weeks()).run(move || { scheduler.every(1.weeks()).run(move || {
clear_old_activities(&conn); let conn = &establish_unpooled_connection_with_db_url(&db_url3);
clear_old_activities(conn);
}); });
// Manually run the scheduler in an event loop // Manually run the scheduler in an event loop