]> Untitled Git - lemmy.git/blob - crates/db_views/src/post_report_view.rs
Add support for Featured Posts (#2585)
[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, 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::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::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         Community,
294         CommunityInsertForm,
295         CommunityModerator,
296         CommunityModeratorForm,
297         CommunitySafe,
298       },
299       instance::Instance,
300       person::{Person, PersonInsertForm, PersonSafe},
301       post::{Post, PostInsertForm},
302       post_report::{PostReport, PostReportForm},
303     },
304     traits::{Crud, Joinable, Reportable},
305     utils::build_db_pool_for_tests,
306   };
307   use serial_test::serial;
308
309   #[tokio::test]
310   #[serial]
311   async fn test_crud() {
312     let pool = &build_db_pool_for_tests().await;
313
314     let inserted_instance = Instance::create(pool, "my_domain.tld").await.unwrap();
315
316     let new_person = PersonInsertForm::builder()
317       .name("timmy_prv".into())
318       .public_key("pubkey".to_string())
319       .instance_id(inserted_instance.id)
320       .build();
321
322     let inserted_timmy = Person::create(pool, &new_person).await.unwrap();
323
324     let new_person_2 = PersonInsertForm::builder()
325       .name("sara_prv".into())
326       .public_key("pubkey".to_string())
327       .instance_id(inserted_instance.id)
328       .build();
329
330     let inserted_sara = Person::create(pool, &new_person_2).await.unwrap();
331
332     // Add a third person, since new ppl can only report something once.
333     let new_person_3 = PersonInsertForm::builder()
334       .name("jessica_prv".into())
335       .public_key("pubkey".to_string())
336       .instance_id(inserted_instance.id)
337       .build();
338
339     let inserted_jessica = Person::create(pool, &new_person_3).await.unwrap();
340
341     let new_community = CommunityInsertForm::builder()
342       .name("test community prv".to_string())
343       .title("nada".to_owned())
344       .public_key("pubkey".to_string())
345       .instance_id(inserted_instance.id)
346       .build();
347
348     let inserted_community = Community::create(pool, &new_community).await.unwrap();
349
350     // Make timmy a mod
351     let timmy_moderator_form = CommunityModeratorForm {
352       community_id: inserted_community.id,
353       person_id: inserted_timmy.id,
354     };
355
356     let _inserted_moderator = CommunityModerator::join(pool, &timmy_moderator_form)
357       .await
358       .unwrap();
359
360     let new_post = PostInsertForm::builder()
361       .name("A test post crv".into())
362       .creator_id(inserted_timmy.id)
363       .community_id(inserted_community.id)
364       .build();
365
366     let inserted_post = Post::create(pool, &new_post).await.unwrap();
367
368     // sara reports
369     let sara_report_form = PostReportForm {
370       creator_id: inserted_sara.id,
371       post_id: inserted_post.id,
372       original_post_name: "Orig post".into(),
373       original_post_url: None,
374       original_post_body: None,
375       reason: "from sara".into(),
376     };
377
378     let inserted_sara_report = PostReport::report(pool, &sara_report_form).await.unwrap();
379
380     // jessica reports
381     let jessica_report_form = PostReportForm {
382       creator_id: inserted_jessica.id,
383       post_id: inserted_post.id,
384       original_post_name: "Orig post".into(),
385       original_post_url: None,
386       original_post_body: None,
387       reason: "from jessica".into(),
388     };
389
390     let inserted_jessica_report = PostReport::report(pool, &jessica_report_form)
391       .await
392       .unwrap();
393
394     let agg = PostAggregates::read(pool, inserted_post.id).await.unwrap();
395
396     let read_jessica_report_view =
397       PostReportView::read(pool, inserted_jessica_report.id, inserted_timmy.id)
398         .await
399         .unwrap();
400     let expected_jessica_report_view = PostReportView {
401       post_report: inserted_jessica_report.clone(),
402       post: inserted_post.clone(),
403       community: CommunitySafe {
404         id: inserted_community.id,
405         name: inserted_community.name,
406         icon: None,
407         removed: false,
408         deleted: false,
409         nsfw: false,
410         actor_id: inserted_community.actor_id.clone(),
411         local: true,
412         title: inserted_community.title,
413         description: None,
414         updated: None,
415         banner: None,
416         hidden: false,
417         posting_restricted_to_mods: false,
418         published: inserted_community.published,
419         instance_id: inserted_instance.id,
420       },
421       creator: PersonSafe {
422         id: inserted_jessica.id,
423         name: inserted_jessica.name,
424         display_name: None,
425         published: inserted_jessica.published,
426         avatar: None,
427         actor_id: inserted_jessica.actor_id.clone(),
428         local: true,
429         banned: false,
430         deleted: false,
431         admin: false,
432         bot_account: false,
433         bio: None,
434         banner: None,
435         updated: None,
436         inbox_url: inserted_jessica.inbox_url.clone(),
437         shared_inbox_url: None,
438         matrix_user_id: None,
439         ban_expires: None,
440         instance_id: inserted_instance.id,
441       },
442       post_creator: PersonSafe {
443         id: inserted_timmy.id,
444         name: inserted_timmy.name.clone(),
445         display_name: None,
446         published: inserted_timmy.published,
447         avatar: None,
448         actor_id: inserted_timmy.actor_id.clone(),
449         local: true,
450         banned: false,
451         deleted: false,
452         admin: false,
453         bot_account: false,
454         bio: None,
455         banner: None,
456         updated: None,
457         inbox_url: inserted_timmy.inbox_url.clone(),
458         shared_inbox_url: None,
459         matrix_user_id: None,
460         ban_expires: None,
461         instance_id: inserted_instance.id,
462       },
463       creator_banned_from_community: false,
464       my_vote: None,
465       counts: PostAggregates {
466         id: agg.id,
467         post_id: inserted_post.id,
468         comments: 0,
469         score: 0,
470         upvotes: 0,
471         downvotes: 0,
472         published: agg.published,
473         newest_comment_time_necro: inserted_post.published,
474         newest_comment_time: inserted_post.published,
475         featured_community: false,
476         featured_local: false,
477       },
478       resolver: None,
479     };
480
481     assert_eq!(read_jessica_report_view, expected_jessica_report_view);
482
483     let mut expected_sara_report_view = expected_jessica_report_view.clone();
484     expected_sara_report_view.post_report = inserted_sara_report;
485     expected_sara_report_view.my_vote = None;
486     expected_sara_report_view.creator = PersonSafe {
487       id: inserted_sara.id,
488       name: inserted_sara.name,
489       display_name: None,
490       published: inserted_sara.published,
491       avatar: None,
492       actor_id: inserted_sara.actor_id.clone(),
493       local: true,
494       banned: false,
495       deleted: false,
496       admin: false,
497       bot_account: false,
498       bio: None,
499       banner: None,
500       updated: None,
501       inbox_url: inserted_sara.inbox_url.clone(),
502       shared_inbox_url: None,
503       matrix_user_id: None,
504       ban_expires: None,
505       instance_id: inserted_instance.id,
506     };
507
508     // Do a batch read of timmys reports
509     let reports = PostReportQuery::builder()
510       .pool(pool)
511       .my_person_id(inserted_timmy.id)
512       .admin(false)
513       .build()
514       .list()
515       .await
516       .unwrap();
517
518     assert_eq!(
519       reports,
520       [
521         expected_jessica_report_view.clone(),
522         expected_sara_report_view.clone()
523       ]
524     );
525
526     // Make sure the counts are correct
527     let report_count = PostReportView::get_report_count(pool, inserted_timmy.id, false, None)
528       .await
529       .unwrap();
530     assert_eq!(2, report_count);
531
532     // Try to resolve the report
533     PostReport::resolve(pool, inserted_jessica_report.id, inserted_timmy.id)
534       .await
535       .unwrap();
536     let read_jessica_report_view_after_resolve =
537       PostReportView::read(pool, inserted_jessica_report.id, inserted_timmy.id)
538         .await
539         .unwrap();
540
541     let mut expected_jessica_report_view_after_resolve = expected_jessica_report_view;
542     expected_jessica_report_view_after_resolve
543       .post_report
544       .resolved = true;
545     expected_jessica_report_view_after_resolve
546       .post_report
547       .resolver_id = Some(inserted_timmy.id);
548     expected_jessica_report_view_after_resolve
549       .post_report
550       .updated = read_jessica_report_view_after_resolve.post_report.updated;
551     expected_jessica_report_view_after_resolve.resolver = Some(PersonSafe {
552       id: inserted_timmy.id,
553       name: inserted_timmy.name.clone(),
554       display_name: None,
555       published: inserted_timmy.published,
556       avatar: None,
557       actor_id: inserted_timmy.actor_id.clone(),
558       local: true,
559       banned: false,
560       deleted: false,
561       admin: false,
562       bot_account: false,
563       bio: None,
564       banner: None,
565       updated: None,
566       inbox_url: inserted_timmy.inbox_url.clone(),
567       shared_inbox_url: None,
568       matrix_user_id: None,
569       ban_expires: None,
570       instance_id: inserted_instance.id,
571     });
572
573     assert_eq!(
574       read_jessica_report_view_after_resolve,
575       expected_jessica_report_view_after_resolve
576     );
577
578     // Do a batch read of timmys reports
579     // It should only show saras, which is unresolved
580     let reports_after_resolve = PostReportQuery::builder()
581       .pool(pool)
582       .my_person_id(inserted_timmy.id)
583       .admin(false)
584       .build()
585       .list()
586       .await
587       .unwrap();
588     assert_eq!(reports_after_resolve[0], expected_sara_report_view);
589
590     // Make sure the counts are correct
591     let report_count_after_resolved =
592       PostReportView::get_report_count(pool, inserted_timmy.id, false, None)
593         .await
594         .unwrap();
595     assert_eq!(1, report_count_after_resolved);
596
597     Person::delete(pool, inserted_timmy.id).await.unwrap();
598     Person::delete(pool, inserted_sara.id).await.unwrap();
599     Person::delete(pool, inserted_jessica.id).await.unwrap();
600     Community::delete(pool, inserted_community.id)
601       .await
602       .unwrap();
603     Instance::delete(pool, inserted_instance.id).await.unwrap();
604   }
605 }