]> Untitled Git - lemmy.git/blob - crates/db_views_actor/src/person_view.rs
Strictly typing DB id fields. Fixes #1498
[lemmy.git] / crates / db_views_actor / src / person_view.rs
1 use diesel::{dsl::*, result::Error, *};
2 use lemmy_db_queries::{
3   aggregates::person_aggregates::PersonAggregates,
4   fuzzy_search,
5   limit_and_offset,
6   MaybeOptional,
7   SortType,
8   ToSafe,
9   ViewToVec,
10 };
11 use lemmy_db_schema::{
12   schema::{local_user, person, person_aggregates},
13   source::person::{Person, PersonSafe},
14   PersonId,
15 };
16 use serde::Serialize;
17
18 #[derive(Debug, Serialize, Clone)]
19 pub struct PersonViewSafe {
20   pub person: PersonSafe,
21   pub counts: PersonAggregates,
22 }
23
24 type PersonViewSafeTuple = (PersonSafe, PersonAggregates);
25
26 impl PersonViewSafe {
27   pub fn read(conn: &PgConnection, person_id: PersonId) -> Result<Self, Error> {
28     let (person, counts) = person::table
29       .find(person_id)
30       .inner_join(person_aggregates::table)
31       .select((Person::safe_columns_tuple(), person_aggregates::all_columns))
32       .first::<PersonViewSafeTuple>(conn)?;
33     Ok(Self { person, counts })
34   }
35
36   pub fn admins(conn: &PgConnection) -> Result<Vec<Self>, Error> {
37     let admins = person::table
38       .inner_join(person_aggregates::table)
39       .inner_join(local_user::table)
40       .select((Person::safe_columns_tuple(), person_aggregates::all_columns))
41       .filter(local_user::admin.eq(true))
42       .order_by(person::published)
43       .load::<PersonViewSafeTuple>(conn)?;
44
45     Ok(Self::from_tuple_to_vec(admins))
46   }
47
48   pub fn banned(conn: &PgConnection) -> Result<Vec<Self>, Error> {
49     let banned = person::table
50       .inner_join(person_aggregates::table)
51       .select((Person::safe_columns_tuple(), person_aggregates::all_columns))
52       .filter(person::banned.eq(true))
53       .load::<PersonViewSafeTuple>(conn)?;
54
55     Ok(Self::from_tuple_to_vec(banned))
56   }
57 }
58
59 pub struct PersonQueryBuilder<'a> {
60   conn: &'a PgConnection,
61   sort: &'a SortType,
62   search_term: Option<String>,
63   page: Option<i64>,
64   limit: Option<i64>,
65 }
66
67 impl<'a> PersonQueryBuilder<'a> {
68   pub fn create(conn: &'a PgConnection) -> Self {
69     PersonQueryBuilder {
70       conn,
71       search_term: None,
72       sort: &SortType::Hot,
73       page: None,
74       limit: None,
75     }
76   }
77
78   pub fn sort(mut self, sort: &'a SortType) -> Self {
79     self.sort = sort;
80     self
81   }
82
83   pub fn search_term<T: MaybeOptional<String>>(mut self, search_term: T) -> Self {
84     self.search_term = search_term.get_optional();
85     self
86   }
87
88   pub fn page<T: MaybeOptional<i64>>(mut self, page: T) -> Self {
89     self.page = page.get_optional();
90     self
91   }
92
93   pub fn limit<T: MaybeOptional<i64>>(mut self, limit: T) -> Self {
94     self.limit = limit.get_optional();
95     self
96   }
97
98   pub fn list(self) -> Result<Vec<PersonViewSafe>, Error> {
99     let mut query = person::table
100       .inner_join(person_aggregates::table)
101       .select((Person::safe_columns_tuple(), person_aggregates::all_columns))
102       .into_boxed();
103
104     if let Some(search_term) = self.search_term {
105       query = query.filter(person::name.ilike(fuzzy_search(&search_term)));
106     }
107
108     query = match self.sort {
109       SortType::Hot => query
110         .order_by(person_aggregates::comment_score.desc())
111         .then_order_by(person::published.desc()),
112       SortType::Active => query
113         .order_by(person_aggregates::comment_score.desc())
114         .then_order_by(person::published.desc()),
115       SortType::New | SortType::MostComments | SortType::NewComments => {
116         query.order_by(person::published.desc())
117       }
118       SortType::TopAll => query.order_by(person_aggregates::comment_score.desc()),
119       SortType::TopYear => query
120         .filter(person::published.gt(now - 1.years()))
121         .order_by(person_aggregates::comment_score.desc()),
122       SortType::TopMonth => query
123         .filter(person::published.gt(now - 1.months()))
124         .order_by(person_aggregates::comment_score.desc()),
125       SortType::TopWeek => query
126         .filter(person::published.gt(now - 1.weeks()))
127         .order_by(person_aggregates::comment_score.desc()),
128       SortType::TopDay => query
129         .filter(person::published.gt(now - 1.days()))
130         .order_by(person_aggregates::comment_score.desc()),
131     };
132
133     let (limit, offset) = limit_and_offset(self.page, self.limit);
134     query = query.limit(limit).offset(offset);
135
136     let res = query.load::<PersonViewSafeTuple>(self.conn)?;
137
138     Ok(PersonViewSafe::from_tuple_to_vec(res))
139   }
140 }
141
142 impl ViewToVec for PersonViewSafe {
143   type DbTuple = PersonViewSafeTuple;
144   fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
145     items
146       .iter()
147       .map(|a| Self {
148         person: a.0.to_owned(),
149         counts: a.1.to_owned(),
150       })
151       .collect::<Vec<Self>>()
152   }
153 }