]> Untitled Git - lemmy.git/blob - crates/db_views/src/post_report_view.rs
Get rid of Safe Views, use serde_skip (#2767)
[lemmy.git] / crates / db_views / src / post_report_view.rs
1 use crate::structs::PostReportView;
2 use diesel::{
3   dsl::now,
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},
27     person::Person,
28     post::Post,
29     post_report::PostReport,
30   },
31   traits::JoinView,
32   utils::{get_conn, limit_and_offset, DbPool},
33 };
34 use typed_builder::TypedBuilder;
35
36 type PostReportViewTuple = (
37   PostReport,
38   Post,
39   Community,
40   Person,
41   Person,
42   Option<CommunityPersonBan>,
43   Option<i16>,
44   PostAggregates,
45   Option<Person>,
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::all_columns,
103         person::all_columns,
104         person_alias_1.fields(person::all_columns),
105         community_person_ban::all_columns.nullable(),
106         post_like::score.nullable(),
107         post_aggregates::all_columns,
108         person_alias_2.fields(person::all_columns.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::count;
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::all_columns,
220         person::all_columns,
221         person_alias_1.fields(person::all_columns),
222         community_person_ban::all_columns.nullable(),
223         post_like::score.nullable(),
224         post_aggregates::all_columns,
225         person_alias_2.fields(person::all_columns.nullable()),
226       ))
227       .into_boxed();
228
229     if let Some(community_id) = self.community_id {
230       query = query.filter(post::community_id.eq(community_id));
231     }
232
233     if self.unresolved_only.unwrap_or(true) {
234       query = query.filter(post_report::resolved.eq(false));
235     }
236
237     let (limit, offset) = limit_and_offset(self.page, self.limit)?;
238
239     query = query
240       .order_by(post_report::published.desc())
241       .limit(limit)
242       .offset(offset);
243
244     // If its not an admin, get only the ones you mod
245     let res = if !self.admin {
246       query
247         .inner_join(
248           community_moderator::table.on(
249             community_moderator::community_id
250               .eq(post::community_id)
251               .and(community_moderator::person_id.eq(self.my_person_id)),
252           ),
253         )
254         .load::<PostReportViewTuple>(conn)
255         .await?
256     } else {
257       query.load::<PostReportViewTuple>(conn).await?
258     };
259
260     Ok(res.into_iter().map(PostReportView::from_tuple).collect())
261   }
262 }
263
264 impl JoinView for PostReportView {
265   type JoinTuple = PostReportViewTuple;
266   fn from_tuple(a: Self::JoinTuple) -> Self {
267     Self {
268       post_report: a.0,
269       post: a.1,
270       community: a.2,
271       creator: a.3,
272       post_creator: a.4,
273       creator_banned_from_community: a.5.is_some(),
274       my_vote: a.6,
275       counts: a.7,
276       resolver: a.8,
277     }
278   }
279 }
280
281 #[cfg(test)]
282 mod tests {
283   use crate::post_report_view::{PostReportQuery, PostReportView};
284   use lemmy_db_schema::{
285     aggregates::structs::PostAggregates,
286     source::{
287       community::{Community, CommunityInsertForm, CommunityModerator, CommunityModeratorForm},
288       instance::Instance,
289       person::{Person, PersonInsertForm},
290       post::{Post, PostInsertForm},
291       post_report::{PostReport, PostReportForm},
292     },
293     traits::{Crud, Joinable, Reportable},
294     utils::build_db_pool_for_tests,
295   };
296   use serial_test::serial;
297
298   #[tokio::test]
299   #[serial]
300   async fn test_crud() {
301     let pool = &build_db_pool_for_tests().await;
302
303     let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string())
304       .await
305       .unwrap();
306
307     let new_person = PersonInsertForm::builder()
308       .name("timmy_prv".into())
309       .public_key("pubkey".to_string())
310       .instance_id(inserted_instance.id)
311       .build();
312
313     let inserted_timmy = Person::create(pool, &new_person).await.unwrap();
314
315     let new_person_2 = PersonInsertForm::builder()
316       .name("sara_prv".into())
317       .public_key("pubkey".to_string())
318       .instance_id(inserted_instance.id)
319       .build();
320
321     let inserted_sara = Person::create(pool, &new_person_2).await.unwrap();
322
323     // Add a third person, since new ppl can only report something once.
324     let new_person_3 = PersonInsertForm::builder()
325       .name("jessica_prv".into())
326       .public_key("pubkey".to_string())
327       .instance_id(inserted_instance.id)
328       .build();
329
330     let inserted_jessica = Person::create(pool, &new_person_3).await.unwrap();
331
332     let new_community = CommunityInsertForm::builder()
333       .name("test community prv".to_string())
334       .title("nada".to_owned())
335       .public_key("pubkey".to_string())
336       .instance_id(inserted_instance.id)
337       .build();
338
339     let inserted_community = Community::create(pool, &new_community).await.unwrap();
340
341     // Make timmy a mod
342     let timmy_moderator_form = CommunityModeratorForm {
343       community_id: inserted_community.id,
344       person_id: inserted_timmy.id,
345     };
346
347     let _inserted_moderator = CommunityModerator::join(pool, &timmy_moderator_form)
348       .await
349       .unwrap();
350
351     let new_post = PostInsertForm::builder()
352       .name("A test post crv".into())
353       .creator_id(inserted_timmy.id)
354       .community_id(inserted_community.id)
355       .build();
356
357     let inserted_post = Post::create(pool, &new_post).await.unwrap();
358
359     // sara reports
360     let sara_report_form = PostReportForm {
361       creator_id: inserted_sara.id,
362       post_id: inserted_post.id,
363       original_post_name: "Orig post".into(),
364       original_post_url: None,
365       original_post_body: None,
366       reason: "from sara".into(),
367     };
368
369     let inserted_sara_report = PostReport::report(pool, &sara_report_form).await.unwrap();
370
371     // jessica reports
372     let jessica_report_form = PostReportForm {
373       creator_id: inserted_jessica.id,
374       post_id: inserted_post.id,
375       original_post_name: "Orig post".into(),
376       original_post_url: None,
377       original_post_body: None,
378       reason: "from jessica".into(),
379     };
380
381     let inserted_jessica_report = PostReport::report(pool, &jessica_report_form)
382       .await
383       .unwrap();
384
385     let agg = PostAggregates::read(pool, inserted_post.id).await.unwrap();
386
387     let read_jessica_report_view =
388       PostReportView::read(pool, inserted_jessica_report.id, inserted_timmy.id)
389         .await
390         .unwrap();
391     let expected_jessica_report_view = PostReportView {
392       post_report: inserted_jessica_report.clone(),
393       post: inserted_post.clone(),
394       community: Community {
395         id: inserted_community.id,
396         name: inserted_community.name,
397         icon: None,
398         removed: false,
399         deleted: false,
400         nsfw: false,
401         actor_id: inserted_community.actor_id.clone(),
402         local: true,
403         title: inserted_community.title,
404         description: None,
405         updated: None,
406         banner: None,
407         hidden: false,
408         posting_restricted_to_mods: false,
409         published: inserted_community.published,
410         instance_id: inserted_instance.id,
411         private_key: inserted_community.private_key.clone(),
412         public_key: inserted_community.public_key.clone(),
413         last_refreshed_at: inserted_community.last_refreshed_at,
414         followers_url: inserted_community.followers_url.clone(),
415         inbox_url: inserted_community.inbox_url.clone(),
416         shared_inbox_url: inserted_community.shared_inbox_url.clone(),
417         moderators_url: inserted_community.moderators_url.clone(),
418         featured_url: inserted_community.featured_url.clone(),
419       },
420       creator: Person {
421         id: inserted_jessica.id,
422         name: inserted_jessica.name,
423         display_name: None,
424         published: inserted_jessica.published,
425         avatar: None,
426         actor_id: inserted_jessica.actor_id.clone(),
427         local: true,
428         banned: false,
429         deleted: false,
430         admin: false,
431         bot_account: false,
432         bio: None,
433         banner: None,
434         updated: None,
435         inbox_url: inserted_jessica.inbox_url.clone(),
436         shared_inbox_url: None,
437         matrix_user_id: None,
438         ban_expires: None,
439         instance_id: inserted_instance.id,
440         private_key: inserted_jessica.private_key,
441         public_key: inserted_jessica.public_key,
442         last_refreshed_at: inserted_jessica.last_refreshed_at,
443       },
444       post_creator: Person {
445         id: inserted_timmy.id,
446         name: inserted_timmy.name.clone(),
447         display_name: None,
448         published: inserted_timmy.published,
449         avatar: None,
450         actor_id: inserted_timmy.actor_id.clone(),
451         local: true,
452         banned: false,
453         deleted: false,
454         admin: false,
455         bot_account: false,
456         bio: None,
457         banner: None,
458         updated: None,
459         inbox_url: inserted_timmy.inbox_url.clone(),
460         shared_inbox_url: None,
461         matrix_user_id: None,
462         ban_expires: None,
463         instance_id: inserted_instance.id,
464         private_key: inserted_timmy.private_key.clone(),
465         public_key: inserted_timmy.public_key.clone(),
466         last_refreshed_at: inserted_timmy.last_refreshed_at,
467       },
468       creator_banned_from_community: false,
469       my_vote: None,
470       counts: PostAggregates {
471         id: agg.id,
472         post_id: inserted_post.id,
473         comments: 0,
474         score: 0,
475         upvotes: 0,
476         downvotes: 0,
477         published: agg.published,
478         newest_comment_time_necro: inserted_post.published,
479         newest_comment_time: inserted_post.published,
480         featured_community: false,
481         featured_local: false,
482       },
483       resolver: None,
484     };
485
486     assert_eq!(read_jessica_report_view, expected_jessica_report_view);
487
488     let mut expected_sara_report_view = expected_jessica_report_view.clone();
489     expected_sara_report_view.post_report = inserted_sara_report;
490     expected_sara_report_view.my_vote = None;
491     expected_sara_report_view.creator = Person {
492       id: inserted_sara.id,
493       name: inserted_sara.name,
494       display_name: None,
495       published: inserted_sara.published,
496       avatar: None,
497       actor_id: inserted_sara.actor_id.clone(),
498       local: true,
499       banned: false,
500       deleted: false,
501       admin: false,
502       bot_account: false,
503       bio: None,
504       banner: None,
505       updated: None,
506       inbox_url: inserted_sara.inbox_url.clone(),
507       shared_inbox_url: None,
508       matrix_user_id: None,
509       ban_expires: None,
510       instance_id: inserted_instance.id,
511       private_key: inserted_sara.private_key,
512       public_key: inserted_sara.public_key,
513       last_refreshed_at: inserted_sara.last_refreshed_at,
514     };
515
516     // Do a batch read of timmys reports
517     let reports = PostReportQuery::builder()
518       .pool(pool)
519       .my_person_id(inserted_timmy.id)
520       .admin(false)
521       .build()
522       .list()
523       .await
524       .unwrap();
525
526     assert_eq!(
527       reports,
528       [
529         expected_jessica_report_view.clone(),
530         expected_sara_report_view.clone()
531       ]
532     );
533
534     // Make sure the counts are correct
535     let report_count = PostReportView::get_report_count(pool, inserted_timmy.id, false, None)
536       .await
537       .unwrap();
538     assert_eq!(2, report_count);
539
540     // Try to resolve the report
541     PostReport::resolve(pool, inserted_jessica_report.id, inserted_timmy.id)
542       .await
543       .unwrap();
544     let read_jessica_report_view_after_resolve =
545       PostReportView::read(pool, inserted_jessica_report.id, inserted_timmy.id)
546         .await
547         .unwrap();
548
549     let mut expected_jessica_report_view_after_resolve = expected_jessica_report_view;
550     expected_jessica_report_view_after_resolve
551       .post_report
552       .resolved = true;
553     expected_jessica_report_view_after_resolve
554       .post_report
555       .resolver_id = Some(inserted_timmy.id);
556     expected_jessica_report_view_after_resolve
557       .post_report
558       .updated = read_jessica_report_view_after_resolve.post_report.updated;
559     expected_jessica_report_view_after_resolve.resolver = Some(Person {
560       id: inserted_timmy.id,
561       name: inserted_timmy.name.clone(),
562       display_name: None,
563       published: inserted_timmy.published,
564       avatar: None,
565       actor_id: inserted_timmy.actor_id.clone(),
566       local: true,
567       banned: false,
568       deleted: false,
569       admin: false,
570       bot_account: false,
571       bio: None,
572       banner: None,
573       updated: None,
574       inbox_url: inserted_timmy.inbox_url.clone(),
575       shared_inbox_url: None,
576       matrix_user_id: None,
577       ban_expires: None,
578       instance_id: inserted_instance.id,
579       private_key: inserted_timmy.private_key.clone(),
580       public_key: inserted_timmy.public_key.clone(),
581       last_refreshed_at: inserted_timmy.last_refreshed_at,
582     });
583
584     assert_eq!(
585       read_jessica_report_view_after_resolve,
586       expected_jessica_report_view_after_resolve
587     );
588
589     // Do a batch read of timmys reports
590     // It should only show saras, which is unresolved
591     let reports_after_resolve = PostReportQuery::builder()
592       .pool(pool)
593       .my_person_id(inserted_timmy.id)
594       .admin(false)
595       .build()
596       .list()
597       .await
598       .unwrap();
599     assert_eq!(reports_after_resolve[0], expected_sara_report_view);
600
601     // Make sure the counts are correct
602     let report_count_after_resolved =
603       PostReportView::get_report_count(pool, inserted_timmy.id, false, None)
604         .await
605         .unwrap();
606     assert_eq!(1, report_count_after_resolved);
607
608     Person::delete(pool, inserted_timmy.id).await.unwrap();
609     Person::delete(pool, inserted_sara.id).await.unwrap();
610     Person::delete(pool, inserted_jessica.id).await.unwrap();
611     Community::delete(pool, inserted_community.id)
612       .await
613       .unwrap();
614     Instance::delete(pool, inserted_instance.id).await.unwrap();
615   }
616 }