First untested pass at reporting.

This commit is contained in:
Dessalines 2021-09-09 22:43:12 -04:00
parent 240de006db
commit 79dd2dd93f
9 changed files with 184 additions and 211 deletions

View file

@ -3,7 +3,6 @@ use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking, blocking,
check_community_ban, check_community_ban,
collect_moderated_communities,
comment::*, comment::*,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
is_mod_or_admin, is_mod_or_admin,
@ -15,22 +14,18 @@ use lemmy_db_views::{
comment_view::CommentView, comment_view::CommentView,
}; };
use lemmy_utils::{ApiError, ConnectionId, LemmyError}; use lemmy_utils::{ApiError, ConnectionId, LemmyError};
use lemmy_websocket::{ use lemmy_websocket::{messages::SendModRoomMessage, LemmyContext, UserOperation};
messages::{SendModRoomMessage, SendUserRoomMessage},
LemmyContext,
UserOperation,
};
/// Creates a comment report and notifies the moderators of the community /// Creates a comment report and notifies the moderators of the community
#[async_trait::async_trait(?Send)] #[async_trait::async_trait(?Send)]
impl Perform for CreateCommentReport { impl Perform for CreateCommentReport {
type Response = CreateCommentReportResponse; type Response = CommentReportResponse;
async fn perform( async fn perform(
&self, &self,
context: &Data<LemmyContext>, context: &Data<LemmyContext>,
websocket_id: Option<ConnectionId>, websocket_id: Option<ConnectionId>,
) -> Result<CreateCommentReportResponse, LemmyError> { ) -> Result<CommentReportResponse, LemmyError> {
let data: &CreateCommentReport = self; let data: &CreateCommentReport = self;
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?;
@ -66,18 +61,18 @@ impl Perform for CreateCommentReport {
.await? .await?
.map_err(|_| ApiError::err("couldnt_create_report"))?; .map_err(|_| ApiError::err("couldnt_create_report"))?;
let res = CreateCommentReportResponse { success: true }; let comment_report_view = blocking(context.pool(), move |conn| {
CommentReportView::read(conn, report.id)
})
.await??;
context.chat_server().do_send(SendUserRoomMessage { let res = CommentReportResponse {
op: UserOperation::CreateCommentReport, comment_report_view,
response: res.clone(), };
local_recipient_id: local_user_view.local_user.id,
websocket_id,
});
context.chat_server().do_send(SendModRoomMessage { context.chat_server().do_send(SendModRoomMessage {
op: UserOperation::CreateCommentReport, op: UserOperation::CreateCommentReport,
response: report, response: res.clone(),
community_id: comment_view.community.id, community_id: comment_view.community.id,
websocket_id, websocket_id,
}); });
@ -89,13 +84,13 @@ impl Perform for CreateCommentReport {
/// Resolves or unresolves a comment report and notifies the moderators of the community /// Resolves or unresolves a comment report and notifies the moderators of the community
#[async_trait::async_trait(?Send)] #[async_trait::async_trait(?Send)]
impl Perform for ResolveCommentReport { impl Perform for ResolveCommentReport {
type Response = ResolveCommentReportResponse; type Response = CommentReportResponse;
async fn perform( async fn perform(
&self, &self,
context: &Data<LemmyContext>, context: &Data<LemmyContext>,
websocket_id: Option<ConnectionId>, websocket_id: Option<ConnectionId>,
) -> Result<ResolveCommentReportResponse, LemmyError> { ) -> Result<CommentReportResponse, LemmyError> {
let data: &ResolveCommentReport = self; let data: &ResolveCommentReport = self;
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?;
@ -123,9 +118,13 @@ impl Perform for ResolveCommentReport {
}; };
let report_id = data.report_id; let report_id = data.report_id;
let res = ResolveCommentReportResponse { let comment_report_view = blocking(context.pool(), move |conn| {
report_id, CommentReportView::read(conn, report_id)
resolved, })
.await??;
let res = CommentReportResponse {
comment_report_view,
}; };
context.chat_server().do_send(SendModRoomMessage { context.chat_server().do_send(SendModRoomMessage {
@ -148,36 +147,27 @@ impl Perform for ListCommentReports {
async fn perform( async fn perform(
&self, &self,
context: &Data<LemmyContext>, context: &Data<LemmyContext>,
websocket_id: Option<ConnectionId>, _websocket_id: Option<ConnectionId>,
) -> Result<ListCommentReportsResponse, LemmyError> { ) -> Result<ListCommentReportsResponse, LemmyError> {
let data: &ListCommentReports = self; let data: &ListCommentReports = self;
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 person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let community_id = data.community; let community_id = data.community_id;
let community_ids =
collect_moderated_communities(person_id, community_id, context.pool()).await?;
let page = data.page; let page = data.page;
let limit = data.limit; let limit = data.limit;
let comments = blocking(context.pool(), move |conn| { let comment_reports = blocking(context.pool(), move |conn| {
CommentReportQueryBuilder::create(conn) CommentReportQueryBuilder::create(conn, person_id)
.community_ids(community_ids) .community_id(community_id)
.page(page) .page(page)
.limit(limit) .limit(limit)
.list() .list()
}) })
.await??; .await??;
let res = ListCommentReportsResponse { comments }; let res = ListCommentReportsResponse { comment_reports };
context.chat_server().do_send(SendUserRoomMessage {
op: UserOperation::ListCommentReports,
response: res.clone(),
local_recipient_id: local_user_view.local_user.id,
websocket_id,
});
Ok(res) Ok(res)
} }

View file

@ -6,7 +6,6 @@ use captcha::{gen, Difficulty};
use chrono::Duration; use chrono::Duration;
use lemmy_api_common::{ use lemmy_api_common::{
blocking, blocking,
collect_moderated_communities,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
is_admin, is_admin,
password_length_check, password_length_check,
@ -67,7 +66,7 @@ use lemmy_utils::{
LemmyError, LemmyError,
}; };
use lemmy_websocket::{ use lemmy_websocket::{
messages::{CaptchaItem, SendAllMessage, SendUserRoomMessage}, messages::{CaptchaItem, SendAllMessage},
LemmyContext, LemmyContext,
UserOperation, UserOperation,
}; };
@ -816,52 +815,31 @@ impl Perform for GetReportCount {
async fn perform( async fn perform(
&self, &self,
context: &Data<LemmyContext>, context: &Data<LemmyContext>,
websocket_id: Option<ConnectionId>, _websocket_id: Option<ConnectionId>,
) -> Result<GetReportCountResponse, LemmyError> { ) -> Result<GetReportCountResponse, LemmyError> {
let data: &GetReportCount = self; let data: &GetReportCount = self;
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 person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let community_id = data.community; let community_id = data.community_id;
let community_ids =
collect_moderated_communities(person_id, community_id, context.pool()).await?;
let res = {
if community_ids.is_empty() {
GetReportCountResponse {
community: None,
comment_reports: 0,
post_reports: 0,
}
} else {
let ids = community_ids.clone();
let comment_reports = blocking(context.pool(), move |conn| { let comment_reports = blocking(context.pool(), move |conn| {
CommentReportView::get_report_count(conn, &ids) CommentReportView::get_report_count(conn, person_id, community_id)
}) })
.await??; .await??;
let ids = community_ids.clone();
let post_reports = blocking(context.pool(), move |conn| { let post_reports = blocking(context.pool(), move |conn| {
PostReportView::get_report_count(conn, &ids) PostReportView::get_report_count(conn, person_id, community_id)
}) })
.await??; .await??;
GetReportCountResponse { let res = GetReportCountResponse {
community: data.community, community_id,
comment_reports, comment_reports,
post_reports, post_reports,
}
}
}; };
context.chat_server().do_send(SendUserRoomMessage {
op: UserOperation::GetReportCount,
response: res.clone(),
local_recipient_id: local_user_view.local_user.id,
websocket_id,
});
Ok(res) Ok(res)
} }
} }

View file

@ -3,16 +3,14 @@ use actix_web::web::Data;
use lemmy_api_common::{ use lemmy_api_common::{
blocking, blocking,
check_community_ban, check_community_ban,
collect_moderated_communities,
get_local_user_view_from_jwt, get_local_user_view_from_jwt,
is_mod_or_admin, is_mod_or_admin,
post::{ post::{
CreatePostReport, CreatePostReport,
CreatePostReportResponse,
ListPostReports, ListPostReports,
ListPostReportsResponse, ListPostReportsResponse,
PostReportResponse,
ResolvePostReport, ResolvePostReport,
ResolvePostReportResponse,
}, },
}; };
use lemmy_db_queries::Reportable; use lemmy_db_queries::Reportable;
@ -22,22 +20,18 @@ use lemmy_db_views::{
post_view::PostView, post_view::PostView,
}; };
use lemmy_utils::{ApiError, ConnectionId, LemmyError}; use lemmy_utils::{ApiError, ConnectionId, LemmyError};
use lemmy_websocket::{ use lemmy_websocket::{messages::SendModRoomMessage, LemmyContext, UserOperation};
messages::{SendModRoomMessage, SendUserRoomMessage},
LemmyContext,
UserOperation,
};
/// Creates a post report and notifies the moderators of the community /// Creates a post report and notifies the moderators of the community
#[async_trait::async_trait(?Send)] #[async_trait::async_trait(?Send)]
impl Perform for CreatePostReport { impl Perform for CreatePostReport {
type Response = CreatePostReportResponse; type Response = PostReportResponse;
async fn perform( async fn perform(
&self, &self,
context: &Data<LemmyContext>, context: &Data<LemmyContext>,
websocket_id: Option<ConnectionId>, websocket_id: Option<ConnectionId>,
) -> Result<CreatePostReportResponse, LemmyError> { ) -> Result<PostReportResponse, LemmyError> {
let data: &CreatePostReport = self; let data: &CreatePostReport = self;
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?;
@ -75,18 +69,16 @@ impl Perform for CreatePostReport {
.await? .await?
.map_err(|_| ApiError::err("couldnt_create_report"))?; .map_err(|_| ApiError::err("couldnt_create_report"))?;
let res = CreatePostReportResponse { success: true }; let post_report_view = blocking(context.pool(), move |conn| {
PostReportView::read(conn, report.id)
})
.await??;
context.chat_server().do_send(SendUserRoomMessage { let res = PostReportResponse { post_report_view };
op: UserOperation::CreatePostReport,
response: res.clone(),
local_recipient_id: local_user_view.local_user.id,
websocket_id,
});
context.chat_server().do_send(SendModRoomMessage { context.chat_server().do_send(SendModRoomMessage {
op: UserOperation::CreatePostReport, op: UserOperation::CreatePostReport,
response: report, response: res.clone(),
community_id: post_view.community.id, community_id: post_view.community.id,
websocket_id, websocket_id,
}); });
@ -98,13 +90,13 @@ impl Perform for CreatePostReport {
/// Resolves or unresolves a post report and notifies the moderators of the community /// Resolves or unresolves a post report and notifies the moderators of the community
#[async_trait::async_trait(?Send)] #[async_trait::async_trait(?Send)]
impl Perform for ResolvePostReport { impl Perform for ResolvePostReport {
type Response = ResolvePostReportResponse; type Response = PostReportResponse;
async fn perform( async fn perform(
&self, &self,
context: &Data<LemmyContext>, context: &Data<LemmyContext>,
websocket_id: Option<ConnectionId>, websocket_id: Option<ConnectionId>,
) -> Result<ResolvePostReportResponse, LemmyError> { ) -> Result<PostReportResponse, LemmyError> {
let data: &ResolvePostReport = self; let data: &ResolvePostReport = self;
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?;
@ -127,15 +119,17 @@ impl Perform for ResolvePostReport {
} }
}; };
let res = ResolvePostReportResponse {
report_id,
resolved: true,
};
if blocking(context.pool(), resolve_fun).await?.is_err() { if blocking(context.pool(), resolve_fun).await?.is_err() {
return Err(ApiError::err("couldnt_resolve_report").into()); return Err(ApiError::err("couldnt_resolve_report").into());
}; };
let post_report_view = blocking(context.pool(), move |conn| {
PostReportView::read(conn, report_id)
})
.await??;
let res = PostReportResponse { post_report_view };
context.chat_server().do_send(SendModRoomMessage { context.chat_server().do_send(SendModRoomMessage {
op: UserOperation::ResolvePostReport, op: UserOperation::ResolvePostReport,
response: res.clone(), response: res.clone(),
@ -156,36 +150,27 @@ impl Perform for ListPostReports {
async fn perform( async fn perform(
&self, &self,
context: &Data<LemmyContext>, context: &Data<LemmyContext>,
websocket_id: Option<ConnectionId>, _websocket_id: Option<ConnectionId>,
) -> Result<ListPostReportsResponse, LemmyError> { ) -> Result<ListPostReportsResponse, LemmyError> {
let data: &ListPostReports = self; let data: &ListPostReports = self;
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 person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let community_id = data.community; let community_id = data.community_id;
let community_ids =
collect_moderated_communities(person_id, community_id, context.pool()).await?;
let page = data.page; let page = data.page;
let limit = data.limit; let limit = data.limit;
let posts = blocking(context.pool(), move |conn| { let post_reports = blocking(context.pool(), move |conn| {
PostReportQueryBuilder::create(conn) PostReportQueryBuilder::create(conn, person_id)
.community_ids(community_ids) .community_id(community_id)
.page(page) .page(page)
.limit(limit) .limit(limit)
.list() .list()
}) })
.await??; .await??;
let res = ListPostReportsResponse { posts }; let res = ListPostReportsResponse { post_reports };
context.chat_server().do_send(SendUserRoomMessage {
op: UserOperation::ListPostReports,
response: res.clone(),
local_recipient_id: local_user_view.local_user.id,
websocket_id,
});
Ok(res) Ok(res)
} }

View file

@ -79,42 +79,35 @@ pub struct GetCommentsResponse {
pub comments: Vec<CommentView>, pub comments: Vec<CommentView>,
} }
#[derive(Serialize, Deserialize)] #[derive(Deserialize)]
pub struct CreateCommentReport { pub struct CreateCommentReport {
pub comment_id: CommentId, pub comment_id: CommentId,
pub reason: String, pub reason: String,
pub auth: String, pub auth: String,
} }
#[derive(Serialize, Deserialize, Clone)] #[derive(Serialize, Clone)]
pub struct CreateCommentReportResponse { pub struct CommentReportResponse {
pub success: bool, pub comment_report_view: CommentReportView,
} }
#[derive(Serialize, Deserialize, Debug)] #[derive(Deserialize)]
pub struct ResolveCommentReport { pub struct ResolveCommentReport {
pub report_id: i32, pub report_id: i32,
pub resolved: bool, pub resolved: bool,
pub auth: String, pub auth: String,
} }
#[derive(Serialize, Deserialize, Clone, Debug)] #[derive(Deserialize)]
pub struct ResolveCommentReportResponse {
// TODO this should probably return the view
pub report_id: i32,
pub resolved: bool,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ListCommentReports { pub struct ListCommentReports {
pub page: Option<i64>, pub page: Option<i64>,
pub limit: Option<i64>, pub limit: Option<i64>,
/// if no community is given, it returns reports for all communities moderated by the auth user /// if no community is given, it returns reports for all communities moderated by the auth user
pub community: Option<CommunityId>, pub community_id: Option<CommunityId>,
pub auth: String, pub auth: String,
} }
#[derive(Serialize, Clone, Debug)] #[derive(Serialize)]
pub struct ListCommentReportsResponse { pub struct ListCommentReportsResponse {
pub comments: Vec<CommentReportView>, pub comment_reports: Vec<CommentReportView>,
} }

View file

@ -8,11 +8,7 @@ pub mod websocket;
use crate::site::FederatedInstances; use crate::site::FederatedInstances;
use diesel::PgConnection; use diesel::PgConnection;
use lemmy_db_queries::{ use lemmy_db_queries::{
source::{ source::{community::Community_, person_block::PersonBlock_, site::Site_},
community::{CommunityModerator_, Community_},
person_block::PersonBlock_,
site::Site_,
},
Crud, Crud,
DbPool, DbPool,
Readable, Readable,
@ -20,7 +16,7 @@ use lemmy_db_queries::{
use lemmy_db_schema::{ use lemmy_db_schema::{
source::{ source::{
comment::Comment, comment::Comment,
community::{Community, CommunityModerator}, community::Community,
person::Person, person::Person,
person_block::PersonBlock, person_block::PersonBlock,
person_mention::{PersonMention, PersonMentionForm}, person_mention::{PersonMention, PersonMentionForm},
@ -384,31 +380,6 @@ pub async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), Le
Ok(()) Ok(())
} }
/// Returns a list of communities that the user moderates
/// or if a community_id is supplied validates the user is a moderator
/// of that community and returns the community id in a vec
///
/// * `person_id` - the person id of the moderator
/// * `community_id` - optional community id to check for moderator privileges
/// * `pool` - the diesel db pool
pub async fn collect_moderated_communities(
person_id: PersonId,
community_id: Option<CommunityId>,
pool: &DbPool,
) -> Result<Vec<CommunityId>, LemmyError> {
if let Some(community_id) = community_id {
// if the user provides a community_id, just check for mod/admin privileges
is_mod_or_admin(pool, person_id, community_id).await?;
Ok(vec![community_id])
} else {
let ids = blocking(pool, move |conn: &'_ _| {
CommunityModerator::get_person_moderated_communities(conn, person_id)
})
.await??;
Ok(ids)
}
}
pub async fn build_federated_instances( pub async fn build_federated_instances(
pool: &DbPool, pool: &DbPool,
federation_config: &FederationConfig, federation_config: &FederationConfig,

View file

@ -253,15 +253,15 @@ pub struct PrivateMessageResponse {
pub private_message_view: PrivateMessageView, pub private_message_view: PrivateMessageView,
} }
#[derive(Serialize, Deserialize, Debug)] #[derive(Deserialize)]
pub struct GetReportCount { pub struct GetReportCount {
pub community: Option<CommunityId>, pub community_id: Option<CommunityId>,
pub auth: String, pub auth: String,
} }
#[derive(Serialize, Deserialize, Clone, Debug)] #[derive(Serialize, Clone)]
pub struct GetReportCountResponse { pub struct GetReportCountResponse {
pub community: Option<CommunityId>, pub community_id: Option<CommunityId>,
pub comment_reports: i64, pub comment_reports: i64,
pub post_reports: i64, pub post_reports: i64,
} }

View file

@ -112,42 +112,37 @@ pub struct SavePost {
pub auth: String, pub auth: String,
} }
#[derive(Serialize, Deserialize)] #[derive(Deserialize)]
pub struct CreatePostReport { pub struct CreatePostReport {
pub post_id: PostId, pub post_id: PostId,
pub reason: String, pub reason: String,
pub auth: String, pub auth: String,
} }
#[derive(Serialize, Deserialize, Clone)] #[derive(Serialize, Clone)]
pub struct CreatePostReportResponse { pub struct PostReportResponse {
pub success: bool, pub post_report_view: PostReportView,
} }
#[derive(Serialize, Deserialize, Debug)] #[derive(Deserialize)]
pub struct ResolvePostReport { pub struct ResolvePostReport {
pub report_id: i32, pub report_id: i32,
pub resolved: bool, pub resolved: bool,
pub auth: String, pub auth: String,
} }
#[derive(Serialize, Deserialize, Clone, Debug)] #[derive(Deserialize)]
pub struct ResolvePostReportResponse {
pub report_id: i32,
pub resolved: bool,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ListPostReports { pub struct ListPostReports {
pub page: Option<i64>, pub page: Option<i64>,
pub limit: Option<i64>, pub limit: Option<i64>,
pub community: Option<CommunityId>, /// if no community is given, it returns reports for all communities moderated by the auth user
pub community_id: Option<CommunityId>,
pub auth: String, pub auth: String,
} }
#[derive(Serialize, Clone, Debug)] #[derive(Serialize)]
pub struct ListPostReportsResponse { pub struct ListPostReportsResponse {
pub posts: Vec<PostReportView>, pub post_reports: Vec<PostReportView>,
} }
#[derive(Deserialize, Debug)] #[derive(Deserialize, Debug)]

View file

@ -1,7 +1,16 @@
use diesel::{result::Error, *}; use diesel::{result::Error, *};
use lemmy_db_queries::{limit_and_offset, MaybeOptional, ToSafe, ViewToVec}; use lemmy_db_queries::{limit_and_offset, MaybeOptional, ToSafe, ViewToVec};
use lemmy_db_schema::{ use lemmy_db_schema::{
schema::{comment, comment_report, community, person, person_alias_1, person_alias_2, post}, schema::{
comment,
comment_report,
community,
community_moderator,
person,
person_alias_1,
person_alias_2,
post,
},
source::{ source::{
comment::Comment, comment::Comment,
comment_report::CommentReport, comment_report::CommentReport,
@ -10,6 +19,7 @@ use lemmy_db_schema::{
post::Post, post::Post,
}, },
CommunityId, CommunityId,
PersonId,
}; };
use serde::Serialize; use serde::Serialize;
@ -76,46 +86,60 @@ impl CommentReportView {
/// ///
/// * `community_ids` - a Vec<i32> of community_ids to get a count for /// * `community_ids` - a Vec<i32> of community_ids to get a count for
/// TODO this eq_any is a bad way to do this, would be better to join to communitymoderator /// TODO this eq_any is a bad way to do this, would be better to join to communitymoderator
/// TODO FIX THIS NOW
/// for a person id /// for a person id
pub fn get_report_count( pub fn get_report_count(
conn: &PgConnection, conn: &PgConnection,
community_ids: &[CommunityId], my_person_id: PersonId,
community_id: Option<CommunityId>,
) -> Result<i64, Error> { ) -> Result<i64, Error> {
use diesel::dsl::*; use diesel::dsl::*;
comment_report::table
let mut query = comment_report::table
.inner_join(comment::table) .inner_join(comment::table)
.inner_join(post::table.on(comment::post_id.eq(post::id))) .inner_join(post::table.on(comment::post_id.eq(post::id)))
.filter( // Test this join
comment_report::resolved .inner_join(
.eq(false) community_moderator::table.on(
.and(post::community_id.eq_any(community_ids)), community_moderator::community_id
.eq(post::community_id)
.and(community_moderator::person_id.eq(my_person_id)),
),
) )
.select(count(comment_report::id)) .filter(comment_report::resolved.eq(false))
.first::<i64>(conn) .into_boxed();
if let Some(community_id) = community_id {
query = query.filter(post::community_id.eq(community_id))
}
query.select(count(comment_report::id)).first::<i64>(conn)
} }
} }
pub struct CommentReportQueryBuilder<'a> { pub struct CommentReportQueryBuilder<'a> {
conn: &'a PgConnection, conn: &'a PgConnection,
community_ids: Option<Vec<CommunityId>>, // TODO bad way to do this my_person_id: PersonId,
community_id: Option<CommunityId>,
page: Option<i64>, page: Option<i64>,
limit: Option<i64>, limit: Option<i64>,
resolved: Option<bool>, resolved: Option<bool>,
} }
impl<'a> CommentReportQueryBuilder<'a> { impl<'a> CommentReportQueryBuilder<'a> {
pub fn create(conn: &'a PgConnection) -> Self { pub fn create(conn: &'a PgConnection, my_person_id: PersonId) -> Self {
CommentReportQueryBuilder { CommentReportQueryBuilder {
conn, conn,
community_ids: None, my_person_id,
community_id: None,
page: None, page: None,
limit: None, limit: None,
resolved: Some(false), resolved: Some(false),
} }
} }
pub fn community_ids<T: MaybeOptional<Vec<CommunityId>>>(mut self, community_ids: T) -> Self { pub fn community_id<T: MaybeOptional<CommunityId>>(mut self, community_id: T) -> Self {
self.community_ids = community_ids.get_optional(); self.community_id = community_id.get_optional();
self self
} }
@ -141,6 +165,14 @@ impl<'a> CommentReportQueryBuilder<'a> {
.inner_join(community::table.on(post::community_id.eq(community::id))) .inner_join(community::table.on(post::community_id.eq(community::id)))
.inner_join(person::table.on(comment_report::creator_id.eq(person::id))) .inner_join(person::table.on(comment_report::creator_id.eq(person::id)))
.inner_join(person_alias_1::table.on(post::creator_id.eq(person_alias_1::id))) .inner_join(person_alias_1::table.on(post::creator_id.eq(person_alias_1::id)))
// Test this join
.inner_join(
community_moderator::table.on(
community_moderator::community_id
.eq(post::community_id)
.and(community_moderator::person_id.eq(self.my_person_id)),
),
)
.left_join( .left_join(
person_alias_2::table.on(comment_report::resolver_id.eq(person_alias_2::id.nullable())), person_alias_2::table.on(comment_report::resolver_id.eq(person_alias_2::id.nullable())),
) )
@ -155,8 +187,8 @@ impl<'a> CommentReportQueryBuilder<'a> {
)) ))
.into_boxed(); .into_boxed();
if let Some(comm_ids) = self.community_ids { if let Some(community_id) = self.community_id {
query = query.filter(post::community_id.eq_any(comm_ids)); query = query.filter(post::community_id.eq(community_id));
} }
if let Some(resolved_flag) = self.resolved { if let Some(resolved_flag) = self.resolved {

View file

@ -1,7 +1,15 @@
use diesel::{result::Error, *}; use diesel::{result::Error, *};
use lemmy_db_queries::{limit_and_offset, MaybeOptional, ToSafe, ViewToVec}; use lemmy_db_queries::{limit_and_offset, MaybeOptional, ToSafe, ViewToVec};
use lemmy_db_schema::{ use lemmy_db_schema::{
schema::{community, person, person_alias_1, person_alias_2, post, post_report}, schema::{
community,
community_moderator,
person,
person_alias_1,
person_alias_2,
post,
post_report,
},
source::{ source::{
community::{Community, CommunitySafe}, community::{Community, CommunitySafe},
person::{Person, PersonAlias1, PersonAlias2, PersonSafe, PersonSafeAlias1, PersonSafeAlias2}, person::{Person, PersonAlias1, PersonAlias2, PersonSafe, PersonSafeAlias1, PersonSafeAlias2},
@ -9,6 +17,7 @@ use lemmy_db_schema::{
post_report::PostReport, post_report::PostReport,
}, },
CommunityId, CommunityId,
PersonId,
}; };
use serde::Serialize; use serde::Serialize;
@ -72,42 +81,54 @@ impl PostReportView {
/// for a person id /// for a person id
pub fn get_report_count( pub fn get_report_count(
conn: &PgConnection, conn: &PgConnection,
community_ids: &[CommunityId], my_person_id: PersonId,
community_id: Option<CommunityId>,
) -> Result<i64, Error> { ) -> Result<i64, Error> {
use diesel::dsl::*; use diesel::dsl::*;
post_report::table let mut query = post_report::table
.inner_join(post::table) .inner_join(post::table)
.filter( // Test this join
post_report::resolved .inner_join(
.eq(false) community_moderator::table.on(
.and(post::community_id.eq_any(community_ids)), community_moderator::community_id
.eq(post::community_id)
.and(community_moderator::person_id.eq(my_person_id)),
),
) )
.select(count(post_report::id)) .filter(post_report::resolved.eq(false))
.first::<i64>(conn) .into_boxed();
if let Some(community_id) = community_id {
query = query.filter(post::community_id.eq(community_id))
}
query.select(count(post_report::id)).first::<i64>(conn)
} }
} }
pub struct PostReportQueryBuilder<'a> { pub struct PostReportQueryBuilder<'a> {
conn: &'a PgConnection, conn: &'a PgConnection,
community_ids: Option<Vec<CommunityId>>, // TODO bad way to do this my_person_id: PersonId,
community_id: Option<CommunityId>,
page: Option<i64>, page: Option<i64>,
limit: Option<i64>, limit: Option<i64>,
resolved: Option<bool>, resolved: Option<bool>,
} }
impl<'a> PostReportQueryBuilder<'a> { impl<'a> PostReportQueryBuilder<'a> {
pub fn create(conn: &'a PgConnection) -> Self { pub fn create(conn: &'a PgConnection, my_person_id: PersonId) -> Self {
PostReportQueryBuilder { PostReportQueryBuilder {
conn, conn,
community_ids: None, my_person_id,
community_id: None,
page: None, page: None,
limit: None, limit: None,
resolved: Some(false), resolved: Some(false),
} }
} }
pub fn community_ids<T: MaybeOptional<Vec<CommunityId>>>(mut self, community_ids: T) -> Self { pub fn community_id<T: MaybeOptional<CommunityId>>(mut self, community_id: T) -> Self {
self.community_ids = community_ids.get_optional(); self.community_id = community_id.get_optional();
self self
} }
@ -132,6 +153,14 @@ impl<'a> PostReportQueryBuilder<'a> {
.inner_join(community::table.on(post::community_id.eq(community::id))) .inner_join(community::table.on(post::community_id.eq(community::id)))
.inner_join(person::table.on(post_report::creator_id.eq(person::id))) .inner_join(person::table.on(post_report::creator_id.eq(person::id)))
.inner_join(person_alias_1::table.on(post::creator_id.eq(person_alias_1::id))) .inner_join(person_alias_1::table.on(post::creator_id.eq(person_alias_1::id)))
// Test this join
.inner_join(
community_moderator::table.on(
community_moderator::community_id
.eq(post::community_id)
.and(community_moderator::person_id.eq(self.my_person_id)),
),
)
.left_join( .left_join(
person_alias_2::table.on(post_report::resolver_id.eq(person_alias_2::id.nullable())), person_alias_2::table.on(post_report::resolver_id.eq(person_alias_2::id.nullable())),
) )
@ -145,8 +174,8 @@ impl<'a> PostReportQueryBuilder<'a> {
)) ))
.into_boxed(); .into_boxed();
if let Some(comm_ids) = self.community_ids { if let Some(community_id) = self.community_id {
query = query.filter(post::community_id.eq_any(comm_ids)); query = query.filter(post::community_id.eq(community_id));
} }
if let Some(resolved_flag) = self.resolved { if let Some(resolved_flag) = self.resolved {