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