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