]> Untitled Git - lemmy.git/blob - crates/db_views/src/post_report_view.rs
555a65ae548b85bca870fc9128536150be9161d6
[lemmy.git] / crates / db_views / src / post_report_view.rs
1 use crate::structs::PostReportView;
2 use diesel::{
3   dsl::*,
4   result::Error,
5   BoolExpressionMethods,
6   ExpressionMethods,
7   JoinOnDsl,
8   NullableExpressionMethods,
9   QueryDsl,
10 };
11 use diesel_async::RunQueryDsl;
12 use lemmy_db_schema::{
13   aggregates::structs::PostAggregates,
14   newtypes::{CommunityId, PersonId, PostReportId},
15   schema::{
16     community,
17     community_moderator,
18     community_person_ban,
19     person,
20     post,
21     post_aggregates,
22     post_like,
23     post_report,
24   },
25   source::{
26     community::{Community, CommunityPersonBan, CommunitySafe},
27     person::{Person, PersonSafe},
28     post::Post,
29     post_report::PostReport,
30   },
31   traits::{ToSafe, ViewToVec},
32   utils::{get_conn, limit_and_offset, DbPool},
33 };
34 use typed_builder::TypedBuilder;
35
36 type PostReportViewTuple = (
37   PostReport,
38   Post,
39   CommunitySafe,
40   PersonSafe,
41   PersonSafe,
42   Option<CommunityPersonBan>,
43   Option<i16>,
44   PostAggregates,
45   Option<PersonSafe>,
46 );
47
48 impl PostReportView {
49   /// returns the PostReportView for the provided report_id
50   ///
51   /// * `report_id` - the report id to obtain
52   pub async fn read(
53     pool: &DbPool,
54     report_id: PostReportId,
55     my_person_id: PersonId,
56   ) -> Result<Self, Error> {
57     let conn = &mut get_conn(pool).await?;
58     let (person_alias_1, person_alias_2) = diesel::alias!(person as person1, person as person2);
59
60     let (
61       post_report,
62       post,
63       community,
64       creator,
65       post_creator,
66       creator_banned_from_community,
67       post_like,
68       counts,
69       resolver,
70     ) = post_report::table
71       .find(report_id)
72       .inner_join(post::table)
73       .inner_join(community::table.on(post::community_id.eq(community::id)))
74       .inner_join(person::table.on(post_report::creator_id.eq(person::id)))
75       .inner_join(person_alias_1.on(post::creator_id.eq(person_alias_1.field(person::id))))
76       .left_join(
77         community_person_ban::table.on(
78           post::community_id
79             .eq(community_person_ban::community_id)
80             .and(community_person_ban::person_id.eq(post::creator_id))
81             .and(
82               community_person_ban::expires
83                 .is_null()
84                 .or(community_person_ban::expires.gt(now)),
85             ),
86         ),
87       )
88       .left_join(
89         post_like::table.on(
90           post::id
91             .eq(post_like::post_id)
92             .and(post_like::person_id.eq(my_person_id)),
93         ),
94       )
95       .inner_join(post_aggregates::table.on(post_report::post_id.eq(post_aggregates::post_id)))
96       .left_join(
97         person_alias_2.on(post_report::resolver_id.eq(person_alias_2.field(person::id).nullable())),
98       )
99       .select((
100         post_report::all_columns,
101         post::all_columns,
102         Community::safe_columns_tuple(),
103         Person::safe_columns_tuple(),
104         person_alias_1.fields(Person::safe_columns_tuple()),
105         community_person_ban::all_columns.nullable(),
106         post_like::score.nullable(),
107         post_aggregates::all_columns,
108         person_alias_2.fields(Person::safe_columns_tuple().nullable()),
109       ))
110       .first::<PostReportViewTuple>(conn)
111       .await?;
112
113     let my_vote = post_like;
114
115     Ok(Self {
116       post_report,
117       post,
118       community,
119       creator,
120       post_creator,
121       creator_banned_from_community: creator_banned_from_community.is_some(),
122       my_vote,
123       counts,
124       resolver,
125     })
126   }
127
128   /// returns the current unresolved post report count for the communities you mod
129   pub async fn get_report_count(
130     pool: &DbPool,
131     my_person_id: PersonId,
132     admin: bool,
133     community_id: Option<CommunityId>,
134   ) -> Result<i64, Error> {
135     use diesel::dsl::*;
136     let conn = &mut get_conn(pool).await?;
137     let mut query = post_report::table
138       .inner_join(post::table)
139       .filter(post_report::resolved.eq(false))
140       .into_boxed();
141
142     if let Some(community_id) = community_id {
143       query = query.filter(post::community_id.eq(community_id))
144     }
145
146     // If its not an admin, get only the ones you mod
147     if !admin {
148       query
149         .inner_join(
150           community_moderator::table.on(
151             community_moderator::community_id
152               .eq(post::community_id)
153               .and(community_moderator::person_id.eq(my_person_id)),
154           ),
155         )
156         .select(count(post_report::id))
157         .first::<i64>(conn)
158         .await
159     } else {
160       query
161         .select(count(post_report::id))
162         .first::<i64>(conn)
163         .await
164     }
165   }
166 }
167
168 #[derive(TypedBuilder)]
169 #[builder(field_defaults(default))]
170 pub struct PostReportQuery<'a> {
171   #[builder(!default)]
172   pool: &'a DbPool,
173   #[builder(!default)]
174   my_person_id: PersonId,
175   #[builder(!default)]
176   admin: bool,
177   community_id: Option<CommunityId>,
178   page: Option<i64>,
179   limit: Option<i64>,
180   unresolved_only: Option<bool>,
181 }
182
183 impl<'a> PostReportQuery<'a> {
184   pub async fn list(self) -> Result<Vec<PostReportView>, Error> {
185     let conn = &mut get_conn(self.pool).await?;
186     let (person_alias_1, person_alias_2) = diesel::alias!(person as person1, person as person2);
187
188     let mut query = post_report::table
189       .inner_join(post::table)
190       .inner_join(community::table.on(post::community_id.eq(community::id)))
191       .inner_join(person::table.on(post_report::creator_id.eq(person::id)))
192       .inner_join(person_alias_1.on(post::creator_id.eq(person_alias_1.field(person::id))))
193       .left_join(
194         community_person_ban::table.on(
195           post::community_id
196             .eq(community_person_ban::community_id)
197             .and(community_person_ban::person_id.eq(post::creator_id))
198             .and(
199               community_person_ban::expires
200                 .is_null()
201                 .or(community_person_ban::expires.gt(now)),
202             ),
203         ),
204       )
205       .left_join(
206         post_like::table.on(
207           post::id
208             .eq(post_like::post_id)
209             .and(post_like::person_id.eq(self.my_person_id)),
210         ),
211       )
212       .inner_join(post_aggregates::table.on(post_report::post_id.eq(post_aggregates::post_id)))
213       .left_join(
214         person_alias_2.on(post_report::resolver_id.eq(person_alias_2.field(person::id).nullable())),
215       )
216       .select((
217         post_report::all_columns,
218         post::all_columns,
219         Community::safe_columns_tuple(),
220         Person::safe_columns_tuple(),
221         person_alias_1.fields(Person::safe_columns_tuple()),
222         community_person_ban::all_columns.nullable(),
223         post_like::score.nullable(),
224         post_aggregates::all_columns,
225         person_alias_2
226           .fields(Person::safe_columns_tuple())
227           .nullable(),
228       ))
229       .into_boxed();
230
231     if let Some(community_id) = self.community_id {
232       query = query.filter(post::community_id.eq(community_id));
233     }
234
235     if self.unresolved_only.unwrap_or(true) {
236       query = query.filter(post_report::resolved.eq(false));
237     }
238
239     let (limit, offset) = limit_and_offset(self.page, self.limit)?;
240
241     query = query
242       .order_by(post_report::published.desc())
243       .limit(limit)
244       .offset(offset);
245
246     // If its not an admin, get only the ones you mod
247     let res = if !self.admin {
248       query
249         .inner_join(
250           community_moderator::table.on(
251             community_moderator::community_id
252               .eq(post::community_id)
253               .and(community_moderator::person_id.eq(self.my_person_id)),
254           ),
255         )
256         .load::<PostReportViewTuple>(conn)
257         .await?
258     } else {
259       query.load::<PostReportViewTuple>(conn).await?
260     };
261
262     Ok(PostReportView::from_tuple_to_vec(res))
263   }
264 }
265
266 impl ViewToVec for PostReportView {
267   type DbTuple = PostReportViewTuple;
268   fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
269     items
270       .into_iter()
271       .map(|a| Self {
272         post_report: a.0,
273         post: a.1,
274         community: a.2,
275         creator: a.3,
276         post_creator: a.4,
277         creator_banned_from_community: a.5.is_some(),
278         my_vote: a.6,
279         counts: a.7,
280         resolver: a.8,
281       })
282       .collect::<Vec<Self>>()
283   }
284 }
285
286 #[cfg(test)]
287 mod tests {
288   use crate::post_report_view::{PostReportQuery, PostReportView};
289   use lemmy_db_schema::{
290     aggregates::structs::PostAggregates,
291     source::{
292       community::*,
293       instance::Instance,
294       person::*,
295       post::*,
296       post_report::{PostReport, PostReportForm},
297     },
298     traits::{Crud, Joinable, Reportable},
299     utils::build_db_pool_for_tests,
300   };
301   use serial_test::serial;
302
303   #[tokio::test]
304   #[serial]
305   async fn test_crud() {
306     let pool = &build_db_pool_for_tests().await;
307
308     let inserted_instance = Instance::create(pool, "my_domain.tld").await.unwrap();
309
310     let new_person = PersonInsertForm::builder()
311       .name("timmy_prv".into())
312       .public_key("pubkey".to_string())
313       .instance_id(inserted_instance.id)
314       .build();
315
316     let inserted_timmy = Person::create(pool, &new_person).await.unwrap();
317
318     let new_person_2 = PersonInsertForm::builder()
319       .name("sara_prv".into())
320       .public_key("pubkey".to_string())
321       .instance_id(inserted_instance.id)
322       .build();
323
324     let inserted_sara = Person::create(pool, &new_person_2).await.unwrap();
325
326     // Add a third person, since new ppl can only report something once.
327     let new_person_3 = PersonInsertForm::builder()
328       .name("jessica_prv".into())
329       .public_key("pubkey".to_string())
330       .instance_id(inserted_instance.id)
331       .build();
332
333     let inserted_jessica = Person::create(pool, &new_person_3).await.unwrap();
334
335     let new_community = CommunityInsertForm::builder()
336       .name("test community prv".to_string())
337       .title("nada".to_owned())
338       .public_key("pubkey".to_string())
339       .instance_id(inserted_instance.id)
340       .build();
341
342     let inserted_community = Community::create(pool, &new_community).await.unwrap();
343
344     // Make timmy a mod
345     let timmy_moderator_form = CommunityModeratorForm {
346       community_id: inserted_community.id,
347       person_id: inserted_timmy.id,
348     };
349
350     let _inserted_moderator = CommunityModerator::join(pool, &timmy_moderator_form)
351       .await
352       .unwrap();
353
354     let new_post = PostInsertForm::builder()
355       .name("A test post crv".into())
356       .creator_id(inserted_timmy.id)
357       .community_id(inserted_community.id)
358       .build();
359
360     let inserted_post = Post::create(pool, &new_post).await.unwrap();
361
362     // sara reports
363     let sara_report_form = PostReportForm {
364       creator_id: inserted_sara.id,
365       post_id: inserted_post.id,
366       original_post_name: "Orig post".into(),
367       original_post_url: None,
368       original_post_body: None,
369       reason: "from sara".into(),
370     };
371
372     let inserted_sara_report = PostReport::report(pool, &sara_report_form).await.unwrap();
373
374     // jessica reports
375     let jessica_report_form = PostReportForm {
376       creator_id: inserted_jessica.id,
377       post_id: inserted_post.id,
378       original_post_name: "Orig post".into(),
379       original_post_url: None,
380       original_post_body: None,
381       reason: "from jessica".into(),
382     };
383
384     let inserted_jessica_report = PostReport::report(pool, &jessica_report_form)
385       .await
386       .unwrap();
387
388     let agg = PostAggregates::read(pool, inserted_post.id).await.unwrap();
389
390     let read_jessica_report_view =
391       PostReportView::read(pool, inserted_jessica_report.id, inserted_timmy.id)
392         .await
393         .unwrap();
394     let expected_jessica_report_view = PostReportView {
395       post_report: inserted_jessica_report.to_owned(),
396       post: inserted_post.to_owned(),
397       community: CommunitySafe {
398         id: inserted_community.id,
399         name: inserted_community.name,
400         icon: None,
401         removed: false,
402         deleted: false,
403         nsfw: false,
404         actor_id: inserted_community.actor_id.to_owned(),
405         local: true,
406         title: inserted_community.title,
407         description: None,
408         updated: None,
409         banner: None,
410         hidden: false,
411         posting_restricted_to_mods: false,
412         published: inserted_community.published,
413         instance_id: inserted_instance.id,
414       },
415       creator: PersonSafe {
416         id: inserted_jessica.id,
417         name: inserted_jessica.name,
418         display_name: None,
419         published: inserted_jessica.published,
420         avatar: None,
421         actor_id: inserted_jessica.actor_id.to_owned(),
422         local: true,
423         banned: false,
424         deleted: false,
425         admin: false,
426         bot_account: false,
427         bio: None,
428         banner: None,
429         updated: None,
430         inbox_url: inserted_jessica.inbox_url.to_owned(),
431         shared_inbox_url: None,
432         matrix_user_id: None,
433         ban_expires: None,
434         instance_id: inserted_instance.id,
435       },
436       post_creator: PersonSafe {
437         id: inserted_timmy.id,
438         name: inserted_timmy.name.to_owned(),
439         display_name: None,
440         published: inserted_timmy.published,
441         avatar: None,
442         actor_id: inserted_timmy.actor_id.to_owned(),
443         local: true,
444         banned: false,
445         deleted: false,
446         admin: false,
447         bot_account: false,
448         bio: None,
449         banner: None,
450         updated: None,
451         inbox_url: inserted_timmy.inbox_url.to_owned(),
452         shared_inbox_url: None,
453         matrix_user_id: None,
454         ban_expires: None,
455         instance_id: inserted_instance.id,
456       },
457       creator_banned_from_community: false,
458       my_vote: None,
459       counts: PostAggregates {
460         id: agg.id,
461         post_id: inserted_post.id,
462         comments: 0,
463         score: 0,
464         upvotes: 0,
465         downvotes: 0,
466         stickied: false,
467         published: agg.published,
468         newest_comment_time_necro: inserted_post.published,
469         newest_comment_time: inserted_post.published,
470       },
471       resolver: None,
472     };
473
474     assert_eq!(read_jessica_report_view, expected_jessica_report_view);
475
476     let mut expected_sara_report_view = expected_jessica_report_view.clone();
477     expected_sara_report_view.post_report = inserted_sara_report;
478     expected_sara_report_view.my_vote = None;
479     expected_sara_report_view.creator = PersonSafe {
480       id: inserted_sara.id,
481       name: inserted_sara.name,
482       display_name: None,
483       published: inserted_sara.published,
484       avatar: None,
485       actor_id: inserted_sara.actor_id.to_owned(),
486       local: true,
487       banned: false,
488       deleted: false,
489       admin: false,
490       bot_account: false,
491       bio: None,
492       banner: None,
493       updated: None,
494       inbox_url: inserted_sara.inbox_url.to_owned(),
495       shared_inbox_url: None,
496       matrix_user_id: None,
497       ban_expires: None,
498       instance_id: inserted_instance.id,
499     };
500
501     // Do a batch read of timmys reports
502     let reports = PostReportQuery::builder()
503       .pool(pool)
504       .my_person_id(inserted_timmy.id)
505       .admin(false)
506       .build()
507       .list()
508       .await
509       .unwrap();
510
511     assert_eq!(
512       reports,
513       [
514         expected_jessica_report_view.to_owned(),
515         expected_sara_report_view.to_owned()
516       ]
517     );
518
519     // Make sure the counts are correct
520     let report_count = PostReportView::get_report_count(pool, inserted_timmy.id, false, None)
521       .await
522       .unwrap();
523     assert_eq!(2, report_count);
524
525     // Try to resolve the report
526     PostReport::resolve(pool, inserted_jessica_report.id, inserted_timmy.id)
527       .await
528       .unwrap();
529     let read_jessica_report_view_after_resolve =
530       PostReportView::read(pool, inserted_jessica_report.id, inserted_timmy.id)
531         .await
532         .unwrap();
533
534     let mut expected_jessica_report_view_after_resolve = expected_jessica_report_view;
535     expected_jessica_report_view_after_resolve
536       .post_report
537       .resolved = true;
538     expected_jessica_report_view_after_resolve
539       .post_report
540       .resolver_id = Some(inserted_timmy.id);
541     expected_jessica_report_view_after_resolve
542       .post_report
543       .updated = read_jessica_report_view_after_resolve.post_report.updated;
544     expected_jessica_report_view_after_resolve.resolver = Some(PersonSafe {
545       id: inserted_timmy.id,
546       name: inserted_timmy.name.to_owned(),
547       display_name: None,
548       published: inserted_timmy.published,
549       avatar: None,
550       actor_id: inserted_timmy.actor_id.to_owned(),
551       local: true,
552       banned: false,
553       deleted: false,
554       admin: false,
555       bot_account: false,
556       bio: None,
557       banner: None,
558       updated: None,
559       inbox_url: inserted_timmy.inbox_url.to_owned(),
560       shared_inbox_url: None,
561       matrix_user_id: None,
562       ban_expires: None,
563       instance_id: inserted_instance.id,
564     });
565
566     assert_eq!(
567       read_jessica_report_view_after_resolve,
568       expected_jessica_report_view_after_resolve
569     );
570
571     // Do a batch read of timmys reports
572     // It should only show saras, which is unresolved
573     let reports_after_resolve = PostReportQuery::builder()
574       .pool(pool)
575       .my_person_id(inserted_timmy.id)
576       .admin(false)
577       .build()
578       .list()
579       .await
580       .unwrap();
581     assert_eq!(reports_after_resolve[0], expected_sara_report_view);
582
583     // Make sure the counts are correct
584     let report_count_after_resolved =
585       PostReportView::get_report_count(pool, inserted_timmy.id, false, None)
586         .await
587         .unwrap();
588     assert_eq!(1, report_count_after_resolved);
589
590     Person::delete(pool, inserted_timmy.id).await.unwrap();
591     Person::delete(pool, inserted_sara.id).await.unwrap();
592     Person::delete(pool, inserted_jessica.id).await.unwrap();
593     Community::delete(pool, inserted_community.id)
594       .await
595       .unwrap();
596     Instance::delete(pool, inserted_instance.id).await.unwrap();
597   }
598 }