]> Untitled Git - lemmy.git/blob - crates/db_schema/src/impls/community.rs
Get rid of Safe Views, use serde_skip (#2767)
[lemmy.git] / crates / db_schema / src / impls / community.rs
1 use crate::{
2   newtypes::{CommunityId, DbUrl, PersonId},
3   schema::community::dsl::{actor_id, community, deleted, local, name, removed},
4   source::{
5     actor_language::{CommunityLanguage, SiteLanguage},
6     community::{
7       Community,
8       CommunityFollower,
9       CommunityFollowerForm,
10       CommunityInsertForm,
11       CommunityModerator,
12       CommunityModeratorForm,
13       CommunityPersonBan,
14       CommunityPersonBanForm,
15       CommunityUpdateForm,
16     },
17   },
18   traits::{ApubActor, Bannable, Crud, Followable, Joinable},
19   utils::{functions::lower, get_conn, DbPool},
20   SubscribedType,
21 };
22 use diesel::{dsl::insert_into, result::Error, ExpressionMethods, QueryDsl, TextExpressionMethods};
23 use diesel_async::RunQueryDsl;
24
25 #[async_trait]
26 impl Crud for Community {
27   type InsertForm = CommunityInsertForm;
28   type UpdateForm = CommunityUpdateForm;
29   type IdType = CommunityId;
30   async fn read(pool: &DbPool, community_id: CommunityId) -> Result<Self, Error> {
31     let conn = &mut get_conn(pool).await?;
32     community.find(community_id).first::<Self>(conn).await
33   }
34
35   async fn delete(pool: &DbPool, community_id: CommunityId) -> Result<usize, Error> {
36     let conn = &mut get_conn(pool).await?;
37     diesel::delete(community.find(community_id))
38       .execute(conn)
39       .await
40   }
41
42   async fn create(pool: &DbPool, form: &Self::InsertForm) -> Result<Self, Error> {
43     let conn = &mut get_conn(pool).await?;
44     let community_ = insert_into(community)
45       .values(form)
46       .on_conflict(actor_id)
47       .do_update()
48       .set(form)
49       .get_result::<Self>(conn)
50       .await?;
51
52     let site_languages = SiteLanguage::read_local(pool).await;
53     if let Ok(langs) = site_languages {
54       // if site exists, init user with site languages
55       CommunityLanguage::update(pool, langs, community_.id).await?;
56     } else {
57       // otherwise, init with all languages (this only happens during tests)
58       CommunityLanguage::update(pool, vec![], community_.id).await?;
59     }
60
61     Ok(community_)
62   }
63
64   async fn update(
65     pool: &DbPool,
66     community_id: CommunityId,
67     form: &Self::UpdateForm,
68   ) -> Result<Self, Error> {
69     let conn = &mut get_conn(pool).await?;
70     diesel::update(community.find(community_id))
71       .set(form)
72       .get_result::<Self>(conn)
73       .await
74   }
75 }
76
77 #[async_trait]
78 impl Joinable for CommunityModerator {
79   type Form = CommunityModeratorForm;
80   async fn join(
81     pool: &DbPool,
82     community_moderator_form: &CommunityModeratorForm,
83   ) -> Result<Self, Error> {
84     use crate::schema::community_moderator::dsl::community_moderator;
85     let conn = &mut get_conn(pool).await?;
86     insert_into(community_moderator)
87       .values(community_moderator_form)
88       .get_result::<Self>(conn)
89       .await
90   }
91
92   async fn leave(
93     pool: &DbPool,
94     community_moderator_form: &CommunityModeratorForm,
95   ) -> Result<usize, Error> {
96     use crate::schema::community_moderator::dsl::{community_id, community_moderator, person_id};
97     let conn = &mut get_conn(pool).await?;
98     diesel::delete(
99       community_moderator
100         .filter(community_id.eq(community_moderator_form.community_id))
101         .filter(person_id.eq(community_moderator_form.person_id)),
102     )
103     .execute(conn)
104     .await
105   }
106 }
107
108 pub enum CollectionType {
109   Moderators,
110   Featured,
111 }
112
113 impl Community {
114   /// Get the community which has a given moderators or featured url, also return the collection type
115   pub async fn get_by_collection_url(
116     pool: &DbPool,
117     url: &DbUrl,
118   ) -> Result<(Community, CollectionType), Error> {
119     use crate::schema::community::dsl::{featured_url, moderators_url};
120     use CollectionType::*;
121     let conn = &mut get_conn(pool).await?;
122     let res = community
123       .filter(moderators_url.eq(url))
124       .first::<Self>(conn)
125       .await;
126     if let Ok(c) = res {
127       return Ok((c, Moderators));
128     }
129     let res = community
130       .filter(featured_url.eq(url))
131       .first::<Self>(conn)
132       .await;
133     if let Ok(c) = res {
134       return Ok((c, Featured));
135     }
136     Err(diesel::NotFound)
137   }
138 }
139
140 impl CommunityModerator {
141   pub async fn delete_for_community(
142     pool: &DbPool,
143     for_community_id: CommunityId,
144   ) -> Result<usize, Error> {
145     use crate::schema::community_moderator::dsl::{community_id, community_moderator};
146     let conn = &mut get_conn(pool).await?;
147
148     diesel::delete(community_moderator.filter(community_id.eq(for_community_id)))
149       .execute(conn)
150       .await
151   }
152
153   pub async fn get_person_moderated_communities(
154     pool: &DbPool,
155     for_person_id: PersonId,
156   ) -> Result<Vec<CommunityId>, Error> {
157     use crate::schema::community_moderator::dsl::{community_id, community_moderator, person_id};
158     let conn = &mut get_conn(pool).await?;
159     community_moderator
160       .filter(person_id.eq(for_person_id))
161       .select(community_id)
162       .load::<CommunityId>(conn)
163       .await
164   }
165 }
166
167 #[async_trait]
168 impl Bannable for CommunityPersonBan {
169   type Form = CommunityPersonBanForm;
170   async fn ban(
171     pool: &DbPool,
172     community_person_ban_form: &CommunityPersonBanForm,
173   ) -> Result<Self, Error> {
174     use crate::schema::community_person_ban::dsl::{community_id, community_person_ban, person_id};
175     let conn = &mut get_conn(pool).await?;
176     insert_into(community_person_ban)
177       .values(community_person_ban_form)
178       .on_conflict((community_id, person_id))
179       .do_update()
180       .set(community_person_ban_form)
181       .get_result::<Self>(conn)
182       .await
183   }
184
185   async fn unban(
186     pool: &DbPool,
187     community_person_ban_form: &CommunityPersonBanForm,
188   ) -> Result<usize, Error> {
189     use crate::schema::community_person_ban::dsl::{community_id, community_person_ban, person_id};
190     let conn = &mut get_conn(pool).await?;
191     diesel::delete(
192       community_person_ban
193         .filter(community_id.eq(community_person_ban_form.community_id))
194         .filter(person_id.eq(community_person_ban_form.person_id)),
195     )
196     .execute(conn)
197     .await
198   }
199 }
200
201 impl CommunityFollower {
202   pub fn to_subscribed_type(follower: &Option<Self>) -> SubscribedType {
203     match follower {
204       Some(f) => {
205         if f.pending {
206           SubscribedType::Pending
207         } else {
208           SubscribedType::Subscribed
209         }
210       }
211       // If the row doesn't exist, the person isn't a follower.
212       None => SubscribedType::NotSubscribed,
213     }
214   }
215 }
216
217 #[async_trait]
218 impl Followable for CommunityFollower {
219   type Form = CommunityFollowerForm;
220   async fn follow(pool: &DbPool, form: &CommunityFollowerForm) -> Result<Self, Error> {
221     use crate::schema::community_follower::dsl::{community_follower, community_id, person_id};
222     let conn = &mut get_conn(pool).await?;
223     insert_into(community_follower)
224       .values(form)
225       .on_conflict((community_id, person_id))
226       .do_update()
227       .set(form)
228       .get_result::<Self>(conn)
229       .await
230   }
231   async fn follow_accepted(
232     pool: &DbPool,
233     community_id_: CommunityId,
234     person_id_: PersonId,
235   ) -> Result<Self, Error> {
236     use crate::schema::community_follower::dsl::{
237       community_follower,
238       community_id,
239       pending,
240       person_id,
241     };
242     let conn = &mut get_conn(pool).await?;
243     diesel::update(
244       community_follower
245         .filter(community_id.eq(community_id_))
246         .filter(person_id.eq(person_id_)),
247     )
248     .set(pending.eq(false))
249     .get_result::<Self>(conn)
250     .await
251   }
252   async fn unfollow(pool: &DbPool, form: &CommunityFollowerForm) -> Result<usize, Error> {
253     use crate::schema::community_follower::dsl::{community_follower, community_id, person_id};
254     let conn = &mut get_conn(pool).await?;
255     diesel::delete(
256       community_follower
257         .filter(community_id.eq(&form.community_id))
258         .filter(person_id.eq(&form.person_id)),
259     )
260     .execute(conn)
261     .await
262   }
263 }
264
265 #[async_trait]
266 impl ApubActor for Community {
267   async fn read_from_apub_id(pool: &DbPool, object_id: &DbUrl) -> Result<Option<Self>, Error> {
268     let conn = &mut get_conn(pool).await?;
269     Ok(
270       community
271         .filter(actor_id.eq(object_id))
272         .first::<Community>(conn)
273         .await
274         .ok()
275         .map(Into::into),
276     )
277   }
278
279   async fn read_from_name(
280     pool: &DbPool,
281     community_name: &str,
282     include_deleted: bool,
283   ) -> Result<Community, Error> {
284     let conn = &mut get_conn(pool).await?;
285     let mut q = community
286       .into_boxed()
287       .filter(local.eq(true))
288       .filter(lower(name).eq(lower(community_name)));
289     if !include_deleted {
290       q = q.filter(deleted.eq(false)).filter(removed.eq(false));
291     }
292     q.first::<Self>(conn).await
293   }
294
295   async fn read_from_name_and_domain(
296     pool: &DbPool,
297     community_name: &str,
298     protocol_domain: &str,
299   ) -> Result<Community, Error> {
300     let conn = &mut get_conn(pool).await?;
301     community
302       .filter(lower(name).eq(lower(community_name)))
303       .filter(actor_id.like(format!("{protocol_domain}%")))
304       .first::<Self>(conn)
305       .await
306   }
307 }
308
309 #[cfg(test)]
310 mod tests {
311   use crate::{
312     source::{
313       community::{
314         Community,
315         CommunityFollower,
316         CommunityFollowerForm,
317         CommunityInsertForm,
318         CommunityModerator,
319         CommunityModeratorForm,
320         CommunityPersonBan,
321         CommunityPersonBanForm,
322         CommunityUpdateForm,
323       },
324       instance::Instance,
325       person::{Person, PersonInsertForm},
326     },
327     traits::{Bannable, Crud, Followable, Joinable},
328     utils::build_db_pool_for_tests,
329   };
330   use serial_test::serial;
331
332   #[tokio::test]
333   #[serial]
334   async fn test_crud() {
335     let pool = &build_db_pool_for_tests().await;
336
337     let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string())
338       .await
339       .unwrap();
340
341     let new_person = PersonInsertForm::builder()
342       .name("bobbee".into())
343       .public_key("pubkey".to_string())
344       .instance_id(inserted_instance.id)
345       .build();
346
347     let inserted_person = Person::create(pool, &new_person).await.unwrap();
348
349     let new_community = CommunityInsertForm::builder()
350       .name("TIL".into())
351       .title("nada".to_owned())
352       .public_key("pubkey".to_string())
353       .instance_id(inserted_instance.id)
354       .build();
355
356     let inserted_community = Community::create(pool, &new_community).await.unwrap();
357
358     let expected_community = Community {
359       id: inserted_community.id,
360       name: "TIL".into(),
361       title: "nada".to_owned(),
362       description: None,
363       nsfw: false,
364       removed: false,
365       deleted: false,
366       published: inserted_community.published,
367       updated: None,
368       actor_id: inserted_community.actor_id.clone(),
369       local: true,
370       private_key: None,
371       public_key: "pubkey".to_owned(),
372       last_refreshed_at: inserted_community.published,
373       icon: None,
374       banner: None,
375       followers_url: inserted_community.followers_url.clone(),
376       inbox_url: inserted_community.inbox_url.clone(),
377       shared_inbox_url: None,
378       moderators_url: None,
379       featured_url: None,
380       hidden: false,
381       posting_restricted_to_mods: false,
382       instance_id: inserted_instance.id,
383     };
384
385     let community_follower_form = CommunityFollowerForm {
386       community_id: inserted_community.id,
387       person_id: inserted_person.id,
388       pending: false,
389     };
390
391     let inserted_community_follower = CommunityFollower::follow(pool, &community_follower_form)
392       .await
393       .unwrap();
394
395     let expected_community_follower = CommunityFollower {
396       id: inserted_community_follower.id,
397       community_id: inserted_community.id,
398       person_id: inserted_person.id,
399       pending: false,
400       published: inserted_community_follower.published,
401     };
402
403     let community_moderator_form = CommunityModeratorForm {
404       community_id: inserted_community.id,
405       person_id: inserted_person.id,
406     };
407
408     let inserted_community_moderator = CommunityModerator::join(pool, &community_moderator_form)
409       .await
410       .unwrap();
411
412     let expected_community_moderator = CommunityModerator {
413       id: inserted_community_moderator.id,
414       community_id: inserted_community.id,
415       person_id: inserted_person.id,
416       published: inserted_community_moderator.published,
417     };
418
419     let community_person_ban_form = CommunityPersonBanForm {
420       community_id: inserted_community.id,
421       person_id: inserted_person.id,
422       expires: None,
423     };
424
425     let inserted_community_person_ban = CommunityPersonBan::ban(pool, &community_person_ban_form)
426       .await
427       .unwrap();
428
429     let expected_community_person_ban = CommunityPersonBan {
430       id: inserted_community_person_ban.id,
431       community_id: inserted_community.id,
432       person_id: inserted_person.id,
433       published: inserted_community_person_ban.published,
434       expires: None,
435     };
436
437     let read_community = Community::read(pool, inserted_community.id).await.unwrap();
438
439     let update_community_form = CommunityUpdateForm::builder()
440       .title(Some("nada".to_owned()))
441       .build();
442     let updated_community = Community::update(pool, inserted_community.id, &update_community_form)
443       .await
444       .unwrap();
445
446     let ignored_community = CommunityFollower::unfollow(pool, &community_follower_form)
447       .await
448       .unwrap();
449     let left_community = CommunityModerator::leave(pool, &community_moderator_form)
450       .await
451       .unwrap();
452     let unban = CommunityPersonBan::unban(pool, &community_person_ban_form)
453       .await
454       .unwrap();
455     let num_deleted = Community::delete(pool, inserted_community.id)
456       .await
457       .unwrap();
458     Person::delete(pool, inserted_person.id).await.unwrap();
459     Instance::delete(pool, inserted_instance.id).await.unwrap();
460
461     assert_eq!(expected_community, read_community);
462     assert_eq!(expected_community, inserted_community);
463     assert_eq!(expected_community, updated_community);
464     assert_eq!(expected_community_follower, inserted_community_follower);
465     assert_eq!(expected_community_moderator, inserted_community_moderator);
466     assert_eq!(expected_community_person_ban, inserted_community_person_ban);
467     assert_eq!(1, ignored_community);
468     assert_eq!(1, left_community);
469     assert_eq!(1, unban);
470     // assert_eq!(2, loaded_count);
471     assert_eq!(1, num_deleted);
472   }
473 }