]> Untitled Git - lemmy.git/blob - crates/db_views/src/post_view.rs
Mark accounts as bot nutomic (#1565)
[lemmy.git] / crates / db_views / src / post_view.rs
1 use diesel::{pg::Pg, result::Error, *};
2 use lemmy_db_queries::{
3   aggregates::post_aggregates::PostAggregates,
4   functions::hot_rank,
5   fuzzy_search,
6   limit_and_offset,
7   ListingType,
8   MaybeOptional,
9   SortType,
10   ToSafe,
11   ViewToVec,
12 };
13 use lemmy_db_schema::{
14   schema::{
15     community,
16     community_follower,
17     community_person_ban,
18     person,
19     post,
20     post_aggregates,
21     post_like,
22     post_read,
23     post_saved,
24   },
25   source::{
26     community::{Community, CommunityFollower, CommunityPersonBan, CommunitySafe},
27     person::{Person, PersonSafe},
28     post::{Post, PostRead, PostSaved},
29   },
30   CommunityId,
31   PersonId,
32   PostId,
33 };
34 use log::debug;
35 use serde::Serialize;
36
37 #[derive(Debug, PartialEq, Serialize, Clone)]
38 pub struct PostView {
39   pub post: Post,
40   pub creator: PersonSafe,
41   pub community: CommunitySafe,
42   pub creator_banned_from_community: bool, // Left Join to CommunityPersonBan
43   pub counts: PostAggregates,
44   pub subscribed: bool,     // Left join to CommunityFollower
45   pub saved: bool,          // Left join to PostSaved
46   pub read: bool,           // Left join to PostRead
47   pub my_vote: Option<i16>, // Left join to PostLike
48 }
49
50 type PostViewTuple = (
51   Post,
52   PersonSafe,
53   CommunitySafe,
54   Option<CommunityPersonBan>,
55   PostAggregates,
56   Option<CommunityFollower>,
57   Option<PostSaved>,
58   Option<PostRead>,
59   Option<i16>,
60 );
61
62 impl PostView {
63   pub fn read(
64     conn: &PgConnection,
65     post_id: PostId,
66     my_person_id: Option<PersonId>,
67   ) -> Result<Self, Error> {
68     // The left join below will return None in this case
69     let person_id_join = my_person_id.unwrap_or(PersonId(-1));
70
71     let (
72       post,
73       creator,
74       community,
75       creator_banned_from_community,
76       counts,
77       follower,
78       saved,
79       read,
80       post_like,
81     ) = post::table
82       .find(post_id)
83       .inner_join(person::table)
84       .inner_join(community::table)
85       .left_join(
86         community_person_ban::table.on(
87           post::community_id
88             .eq(community_person_ban::community_id)
89             .and(community_person_ban::person_id.eq(post::creator_id)),
90         ),
91       )
92       .inner_join(post_aggregates::table)
93       .left_join(
94         community_follower::table.on(
95           post::community_id
96             .eq(community_follower::community_id)
97             .and(community_follower::person_id.eq(person_id_join)),
98         ),
99       )
100       .left_join(
101         post_saved::table.on(
102           post::id
103             .eq(post_saved::post_id)
104             .and(post_saved::person_id.eq(person_id_join)),
105         ),
106       )
107       .left_join(
108         post_read::table.on(
109           post::id
110             .eq(post_read::post_id)
111             .and(post_read::person_id.eq(person_id_join)),
112         ),
113       )
114       .left_join(
115         post_like::table.on(
116           post::id
117             .eq(post_like::post_id)
118             .and(post_like::person_id.eq(person_id_join)),
119         ),
120       )
121       .select((
122         post::all_columns,
123         Person::safe_columns_tuple(),
124         Community::safe_columns_tuple(),
125         community_person_ban::all_columns.nullable(),
126         post_aggregates::all_columns,
127         community_follower::all_columns.nullable(),
128         post_saved::all_columns.nullable(),
129         post_read::all_columns.nullable(),
130         post_like::score.nullable(),
131       ))
132       .first::<PostViewTuple>(conn)?;
133
134     // If a person is given, then my_vote, if None, should be 0, not null
135     // Necessary to differentiate between other person's votes
136     let my_vote = if my_person_id.is_some() && post_like.is_none() {
137       Some(0)
138     } else {
139       post_like
140     };
141
142     Ok(PostView {
143       post,
144       creator,
145       community,
146       creator_banned_from_community: creator_banned_from_community.is_some(),
147       counts,
148       subscribed: follower.is_some(),
149       saved: saved.is_some(),
150       read: read.is_some(),
151       my_vote,
152     })
153   }
154 }
155
156 pub struct PostQueryBuilder<'a> {
157   conn: &'a PgConnection,
158   listing_type: &'a ListingType,
159   sort: &'a SortType,
160   creator_id: Option<PersonId>,
161   community_id: Option<CommunityId>,
162   community_name: Option<String>,
163   my_person_id: Option<PersonId>,
164   search_term: Option<String>,
165   url_search: Option<String>,
166   show_nsfw: bool,
167   show_bot_accounts: bool,
168   saved_only: bool,
169   unread_only: bool,
170   page: Option<i64>,
171   limit: Option<i64>,
172 }
173
174 impl<'a> PostQueryBuilder<'a> {
175   pub fn create(conn: &'a PgConnection) -> Self {
176     PostQueryBuilder {
177       conn,
178       listing_type: &ListingType::All,
179       sort: &SortType::Hot,
180       creator_id: None,
181       community_id: None,
182       community_name: None,
183       my_person_id: None,
184       search_term: None,
185       url_search: None,
186       show_nsfw: true,
187       show_bot_accounts: true,
188       saved_only: false,
189       unread_only: false,
190       page: None,
191       limit: None,
192     }
193   }
194
195   pub fn listing_type(mut self, listing_type: &'a ListingType) -> Self {
196     self.listing_type = listing_type;
197     self
198   }
199
200   pub fn sort(mut self, sort: &'a SortType) -> Self {
201     self.sort = sort;
202     self
203   }
204
205   pub fn community_id<T: MaybeOptional<CommunityId>>(mut self, community_id: T) -> Self {
206     self.community_id = community_id.get_optional();
207     self
208   }
209
210   pub fn my_person_id<T: MaybeOptional<PersonId>>(mut self, my_person_id: T) -> Self {
211     self.my_person_id = my_person_id.get_optional();
212     self
213   }
214
215   pub fn community_name<T: MaybeOptional<String>>(mut self, community_name: T) -> Self {
216     self.community_name = community_name.get_optional();
217     self
218   }
219
220   pub fn creator_id<T: MaybeOptional<PersonId>>(mut self, creator_id: T) -> Self {
221     self.creator_id = creator_id.get_optional();
222     self
223   }
224
225   pub fn search_term<T: MaybeOptional<String>>(mut self, search_term: T) -> Self {
226     self.search_term = search_term.get_optional();
227     self
228   }
229
230   pub fn url_search<T: MaybeOptional<String>>(mut self, url_search: T) -> Self {
231     self.url_search = url_search.get_optional();
232     self
233   }
234
235   pub fn show_nsfw(mut self, show_nsfw: bool) -> Self {
236     self.show_nsfw = show_nsfw;
237     self
238   }
239
240   pub fn show_bot_accounts(mut self, show_bot_accounts: bool) -> Self {
241     self.show_bot_accounts = show_bot_accounts;
242     self
243   }
244
245   pub fn saved_only(mut self, saved_only: bool) -> Self {
246     self.saved_only = saved_only;
247     self
248   }
249
250   pub fn page<T: MaybeOptional<i64>>(mut self, page: T) -> Self {
251     self.page = page.get_optional();
252     self
253   }
254
255   pub fn limit<T: MaybeOptional<i64>>(mut self, limit: T) -> Self {
256     self.limit = limit.get_optional();
257     self
258   }
259
260   pub fn list(self) -> Result<Vec<PostView>, Error> {
261     use diesel::dsl::*;
262
263     // The left join below will return None in this case
264     let person_id_join = self.my_person_id.unwrap_or(PersonId(-1));
265
266     let mut query = post::table
267       .inner_join(person::table)
268       .inner_join(community::table)
269       .left_join(
270         community_person_ban::table.on(
271           post::community_id
272             .eq(community_person_ban::community_id)
273             .and(community_person_ban::person_id.eq(post::creator_id)),
274         ),
275       )
276       .inner_join(post_aggregates::table)
277       .left_join(
278         community_follower::table.on(
279           post::community_id
280             .eq(community_follower::community_id)
281             .and(community_follower::person_id.eq(person_id_join)),
282         ),
283       )
284       .left_join(
285         post_saved::table.on(
286           post::id
287             .eq(post_saved::post_id)
288             .and(post_saved::person_id.eq(person_id_join)),
289         ),
290       )
291       .left_join(
292         post_read::table.on(
293           post::id
294             .eq(post_read::post_id)
295             .and(post_read::person_id.eq(person_id_join)),
296         ),
297       )
298       .left_join(
299         post_like::table.on(
300           post::id
301             .eq(post_like::post_id)
302             .and(post_like::person_id.eq(person_id_join)),
303         ),
304       )
305       .select((
306         post::all_columns,
307         Person::safe_columns_tuple(),
308         Community::safe_columns_tuple(),
309         community_person_ban::all_columns.nullable(),
310         post_aggregates::all_columns,
311         community_follower::all_columns.nullable(),
312         post_saved::all_columns.nullable(),
313         post_read::all_columns.nullable(),
314         post_like::score.nullable(),
315       ))
316       .into_boxed();
317
318     query = match self.listing_type {
319       ListingType::Subscribed => query.filter(community_follower::person_id.is_not_null()), // TODO could be this: and(community_follower::person_id.eq(person_id_join)),
320       ListingType::Local => query.filter(community::local.eq(true)),
321       _ => query,
322     };
323
324     if let Some(community_id) = self.community_id {
325       query = query
326         .filter(post::community_id.eq(community_id))
327         .then_order_by(post_aggregates::stickied.desc());
328     }
329
330     if let Some(community_name) = self.community_name {
331       query = query
332         .filter(community::name.eq(community_name))
333         .filter(community::local.eq(true))
334         .then_order_by(post_aggregates::stickied.desc());
335     }
336
337     if let Some(url_search) = self.url_search {
338       query = query.filter(post::url.eq(url_search));
339     }
340
341     if let Some(search_term) = self.search_term {
342       let searcher = fuzzy_search(&search_term);
343       query = query.filter(
344         post::name
345           .ilike(searcher.to_owned())
346           .or(post::body.ilike(searcher)),
347       );
348     }
349
350     // If its for a specific person, show the removed / deleted
351     if let Some(creator_id) = self.creator_id {
352       query = query.filter(post::creator_id.eq(creator_id));
353     }
354
355     if !self.show_nsfw {
356       query = query
357         .filter(post::nsfw.eq(false))
358         .filter(community::nsfw.eq(false));
359     };
360
361     if !self.show_bot_accounts {
362       query = query.filter(person::bot_account.eq(false));
363     };
364
365     // TODO  These two might be wrong
366     if self.saved_only {
367       query = query.filter(post_saved::id.is_not_null());
368     };
369
370     if self.unread_only {
371       query = query.filter(post_read::id.is_not_null());
372     };
373
374     query = match self.sort {
375       SortType::Active => query
376         .then_order_by(
377           hot_rank(
378             post_aggregates::score,
379             post_aggregates::newest_comment_time_necro,
380           )
381           .desc(),
382         )
383         .then_order_by(post_aggregates::newest_comment_time_necro.desc()),
384       SortType::Hot => query
385         .then_order_by(hot_rank(post_aggregates::score, post_aggregates::published).desc())
386         .then_order_by(post_aggregates::published.desc()),
387       SortType::New => query.then_order_by(post_aggregates::published.desc()),
388       SortType::MostComments => query.then_order_by(post_aggregates::comments.desc()),
389       SortType::NewComments => query.then_order_by(post_aggregates::newest_comment_time.desc()),
390       SortType::TopAll => query.then_order_by(post_aggregates::score.desc()),
391       SortType::TopYear => query
392         .filter(post::published.gt(now - 1.years()))
393         .then_order_by(post_aggregates::score.desc()),
394       SortType::TopMonth => query
395         .filter(post::published.gt(now - 1.months()))
396         .then_order_by(post_aggregates::score.desc()),
397       SortType::TopWeek => query
398         .filter(post::published.gt(now - 1.weeks()))
399         .then_order_by(post_aggregates::score.desc()),
400       SortType::TopDay => query
401         .filter(post::published.gt(now - 1.days()))
402         .then_order_by(post_aggregates::score.desc()),
403     };
404
405     let (limit, offset) = limit_and_offset(self.page, self.limit);
406
407     query = query
408       .limit(limit)
409       .offset(offset)
410       .filter(post::removed.eq(false))
411       .filter(post::deleted.eq(false))
412       .filter(community::removed.eq(false))
413       .filter(community::deleted.eq(false));
414
415     debug!("Post View Query: {:?}", debug_query::<Pg, _>(&query));
416
417     let res = query.load::<PostViewTuple>(self.conn)?;
418
419     Ok(PostView::from_tuple_to_vec(res))
420   }
421 }
422
423 impl ViewToVec for PostView {
424   type DbTuple = PostViewTuple;
425   fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
426     items
427       .iter()
428       .map(|a| Self {
429         post: a.0.to_owned(),
430         creator: a.1.to_owned(),
431         community: a.2.to_owned(),
432         creator_banned_from_community: a.3.is_some(),
433         counts: a.4.to_owned(),
434         subscribed: a.5.is_some(),
435         saved: a.6.is_some(),
436         read: a.7.is_some(),
437         my_vote: a.8,
438       })
439       .collect::<Vec<Self>>()
440   }
441 }
442
443 #[cfg(test)]
444 mod tests {
445   use crate::post_view::{PostQueryBuilder, PostView};
446   use lemmy_db_queries::{
447     aggregates::post_aggregates::PostAggregates,
448     establish_unpooled_connection,
449     Crud,
450     Likeable,
451     ListingType,
452     SortType,
453   };
454   use lemmy_db_schema::source::{community::*, person::*, post::*};
455   use serial_test::serial;
456
457   #[test]
458   #[serial]
459   fn test_crud() {
460     let conn = establish_unpooled_connection();
461
462     let person_name = "tegan".to_string();
463     let community_name = "test_community_3".to_string();
464     let post_name = "test post 3".to_string();
465     let bot_post_name = "test bot post".to_string();
466
467     let new_person = PersonForm {
468       name: person_name.to_owned(),
469       ..PersonForm::default()
470     };
471
472     let inserted_person = Person::create(&conn, &new_person).unwrap();
473
474     let new_bot = PersonForm {
475       name: person_name.to_owned(),
476       bot_account: Some(true),
477       ..PersonForm::default()
478     };
479
480     let inserted_bot = Person::create(&conn, &new_bot).unwrap();
481
482     let new_community = CommunityForm {
483       name: community_name.to_owned(),
484       title: "nada".to_owned(),
485       ..CommunityForm::default()
486     };
487
488     let inserted_community = Community::create(&conn, &new_community).unwrap();
489
490     let new_post = PostForm {
491       name: post_name.to_owned(),
492       creator_id: inserted_person.id,
493       community_id: inserted_community.id,
494       ..PostForm::default()
495     };
496
497     let inserted_post = Post::create(&conn, &new_post).unwrap();
498
499     let new_bot_post = PostForm {
500       name: bot_post_name,
501       creator_id: inserted_bot.id,
502       community_id: inserted_community.id,
503       ..PostForm::default()
504     };
505
506     let _inserted_bot_post = Post::create(&conn, &new_bot_post).unwrap();
507
508     let post_like_form = PostLikeForm {
509       post_id: inserted_post.id,
510       person_id: inserted_person.id,
511       score: 1,
512     };
513
514     let inserted_post_like = PostLike::like(&conn, &post_like_form).unwrap();
515
516     let expected_post_like = PostLike {
517       id: inserted_post_like.id,
518       post_id: inserted_post.id,
519       person_id: inserted_person.id,
520       published: inserted_post_like.published,
521       score: 1,
522     };
523
524     let read_post_listings_with_person = PostQueryBuilder::create(&conn)
525       .listing_type(&ListingType::Community)
526       .sort(&SortType::New)
527       .show_bot_accounts(false)
528       .community_id(inserted_community.id)
529       .my_person_id(inserted_person.id)
530       .list()
531       .unwrap();
532
533     let read_post_listings_no_person = PostQueryBuilder::create(&conn)
534       .listing_type(&ListingType::Community)
535       .sort(&SortType::New)
536       .community_id(inserted_community.id)
537       .list()
538       .unwrap();
539
540     let read_post_listing_no_person = PostView::read(&conn, inserted_post.id, None).unwrap();
541     let read_post_listing_with_person =
542       PostView::read(&conn, inserted_post.id, Some(inserted_person.id)).unwrap();
543
544     let agg = PostAggregates::read(&conn, inserted_post.id).unwrap();
545
546     // the non person version
547     let expected_post_listing_no_person = PostView {
548       post: Post {
549         id: inserted_post.id,
550         name: post_name,
551         creator_id: inserted_person.id,
552         url: None,
553         body: None,
554         published: inserted_post.published,
555         updated: None,
556         community_id: inserted_community.id,
557         removed: false,
558         deleted: false,
559         locked: false,
560         stickied: false,
561         nsfw: false,
562         embed_title: None,
563         embed_description: None,
564         embed_html: None,
565         thumbnail_url: None,
566         ap_id: inserted_post.ap_id.to_owned(),
567         local: true,
568       },
569       my_vote: None,
570       creator: PersonSafe {
571         id: inserted_person.id,
572         name: person_name,
573         display_name: None,
574         published: inserted_person.published,
575         avatar: None,
576         actor_id: inserted_person.actor_id.to_owned(),
577         local: true,
578         admin: false,
579         bot_account: false,
580         banned: false,
581         deleted: false,
582         bio: None,
583         banner: None,
584         updated: None,
585         inbox_url: inserted_person.inbox_url.to_owned(),
586         shared_inbox_url: None,
587         matrix_user_id: None,
588       },
589       creator_banned_from_community: false,
590       community: CommunitySafe {
591         id: inserted_community.id,
592         name: community_name,
593         icon: None,
594         removed: false,
595         deleted: false,
596         nsfw: false,
597         actor_id: inserted_community.actor_id.to_owned(),
598         local: true,
599         title: "nada".to_owned(),
600         description: None,
601         updated: None,
602         banner: None,
603         published: inserted_community.published,
604       },
605       counts: PostAggregates {
606         id: agg.id,
607         post_id: inserted_post.id,
608         comments: 0,
609         score: 1,
610         upvotes: 1,
611         downvotes: 0,
612         stickied: false,
613         published: agg.published,
614         newest_comment_time_necro: inserted_post.published,
615         newest_comment_time: inserted_post.published,
616       },
617       subscribed: false,
618       read: false,
619       saved: false,
620     };
621
622     // TODO More needs to be added here
623     let mut expected_post_listing_with_user = expected_post_listing_no_person.to_owned();
624     expected_post_listing_with_user.my_vote = Some(1);
625
626     let like_removed = PostLike::remove(&conn, inserted_person.id, inserted_post.id).unwrap();
627     let num_deleted = Post::delete(&conn, inserted_post.id).unwrap();
628     Community::delete(&conn, inserted_community.id).unwrap();
629     Person::delete(&conn, inserted_person.id).unwrap();
630     Person::delete(&conn, inserted_bot.id).unwrap();
631
632     // The with user
633     assert_eq!(
634       expected_post_listing_with_user,
635       read_post_listings_with_person[0]
636     );
637     assert_eq!(
638       expected_post_listing_with_user,
639       read_post_listing_with_person
640     );
641
642     // Should be only one person, IE the bot post should be missing
643     assert_eq!(1, read_post_listings_with_person.len());
644
645     // Without the user
646     assert_eq!(
647       expected_post_listing_no_person,
648       read_post_listings_no_person[1]
649     );
650     assert_eq!(expected_post_listing_no_person, read_post_listing_no_person);
651
652     // Should be 2 posts, with the bot post
653     assert_eq!(2, read_post_listings_no_person.len());
654
655     assert_eq!(expected_post_like, inserted_post_like);
656     assert_eq!(1, like_removed);
657     assert_eq!(1, num_deleted);
658   }
659 }