]> Untitled Git - lemmy.git/blob - crates/db_views_moderator/src/mod_sticky_post_view.rs
Add Modlog Filters (#2313)
[lemmy.git] / crates / db_views_moderator / src / mod_sticky_post_view.rs
1 use crate::structs::{ModStickyPostView, ModlogListParams};
2 use diesel::{result::Error, *};
3 use lemmy_db_schema::{
4   newtypes::PersonId,
5   schema::{community, mod_sticky_post, person, person_alias_1, post},
6   source::{
7     community::{Community, CommunitySafe},
8     moderator::ModStickyPost,
9     person::{Person, PersonSafe},
10     post::Post,
11   },
12   traits::{ToSafe, ViewToVec},
13   utils::limit_and_offset,
14 };
15
16 type ModStickyPostViewTuple = (ModStickyPost, Option<PersonSafe>, Post, CommunitySafe);
17
18 impl ModStickyPostView {
19   pub fn list(conn: &PgConnection, params: ModlogListParams) -> Result<Vec<Self>, Error> {
20     let admin_person_id_join = params.mod_person_id.unwrap_or(PersonId(-1));
21     let show_mod_names = !params.hide_modlog_names;
22     let show_mod_names_expr = show_mod_names.as_sql::<diesel::sql_types::Bool>();
23
24     let admin_names_join = mod_sticky_post::mod_person_id
25       .eq(person::id)
26       .and(show_mod_names_expr.or(person::id.eq(admin_person_id_join)));
27     let mut query = mod_sticky_post::table
28       .left_join(person::table.on(admin_names_join))
29       .inner_join(post::table)
30       .inner_join(person_alias_1::table.on(post::creator_id.eq(person_alias_1::id)))
31       .inner_join(community::table.on(post::community_id.eq(community::id)))
32       .select((
33         mod_sticky_post::all_columns,
34         Person::safe_columns_tuple().nullable(),
35         post::all_columns,
36         Community::safe_columns_tuple(),
37       ))
38       .into_boxed();
39
40     if let Some(community_id) = params.community_id {
41       query = query.filter(post::community_id.eq(community_id));
42     };
43
44     if let Some(mod_person_id) = params.mod_person_id {
45       query = query.filter(mod_sticky_post::mod_person_id.eq(mod_person_id));
46     };
47
48     if let Some(other_person_id) = params.other_person_id {
49       query = query.filter(person_alias_1::id.eq(other_person_id));
50     };
51
52     let (limit, offset) = limit_and_offset(params.page, params.limit)?;
53
54     let res = query
55       .limit(limit)
56       .offset(offset)
57       .order_by(mod_sticky_post::when_.desc())
58       .load::<ModStickyPostViewTuple>(conn)?;
59
60     let results = Self::from_tuple_to_vec(res);
61     Ok(results)
62   }
63 }
64
65 impl ViewToVec for ModStickyPostView {
66   type DbTuple = ModStickyPostViewTuple;
67   fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
68     items
69       .into_iter()
70       .map(|a| Self {
71         mod_sticky_post: a.0,
72         moderator: a.1,
73         post: a.2,
74         community: a.3,
75       })
76       .collect::<Vec<Self>>()
77   }
78 }