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