]> Untitled Git - lemmy.git/blob - crates/db_schema/src/impls/person.rs
Correct error messages if user registers with taken user/email (#3093)
[lemmy.git] / crates / db_schema / src / impls / person.rs
1 use crate::{
2   newtypes::{CommunityId, DbUrl, PersonId},
3   schema::{instance, local_user, person, person_follower},
4   source::person::{
5     Person,
6     PersonFollower,
7     PersonFollowerForm,
8     PersonInsertForm,
9     PersonUpdateForm,
10   },
11   traits::{ApubActor, Crud, Followable},
12   utils::{functions::lower, get_conn, naive_now, DbPool},
13 };
14 use diesel::{dsl::insert_into, result::Error, ExpressionMethods, JoinOnDsl, QueryDsl};
15 use diesel_async::RunQueryDsl;
16
17 #[async_trait]
18 impl Crud for Person {
19   type InsertForm = PersonInsertForm;
20   type UpdateForm = PersonUpdateForm;
21   type IdType = PersonId;
22   async fn read(pool: &DbPool, person_id: PersonId) -> Result<Self, Error> {
23     let conn = &mut get_conn(pool).await?;
24     person::table
25       .filter(person::deleted.eq(false))
26       .find(person_id)
27       .first::<Self>(conn)
28       .await
29   }
30   async fn delete(pool: &DbPool, person_id: PersonId) -> Result<usize, Error> {
31     let conn = &mut get_conn(pool).await?;
32     diesel::delete(person::table.find(person_id))
33       .execute(conn)
34       .await
35   }
36   async fn create(pool: &DbPool, form: &PersonInsertForm) -> Result<Self, Error> {
37     let conn = &mut get_conn(pool).await?;
38     insert_into(person::table)
39       .values(form)
40       .get_result::<Self>(conn)
41       .await
42   }
43   async fn update(
44     pool: &DbPool,
45     person_id: PersonId,
46     form: &PersonUpdateForm,
47   ) -> Result<Self, Error> {
48     let conn = &mut get_conn(pool).await?;
49     diesel::update(person::table.find(person_id))
50       .set(form)
51       .get_result::<Self>(conn)
52       .await
53   }
54 }
55
56 impl Person {
57   /// Update or insert the person.
58   ///
59   /// This is necessary for federation, because Activitypub doesnt distinguish between these actions.
60   pub async fn upsert(pool: &DbPool, form: &PersonInsertForm) -> Result<Self, Error> {
61     let conn = &mut get_conn(pool).await?;
62     insert_into(person::table)
63       .values(form)
64       .on_conflict(person::actor_id)
65       .do_update()
66       .set(form)
67       .get_result::<Self>(conn)
68       .await
69   }
70   pub async fn delete_account(pool: &DbPool, person_id: PersonId) -> Result<Person, Error> {
71     let conn = &mut get_conn(pool).await?;
72
73     // Set the local user info to none
74     diesel::update(local_user::table.filter(local_user::person_id.eq(person_id)))
75       .set((
76         local_user::email.eq::<Option<String>>(None),
77         local_user::validator_time.eq(naive_now()),
78       ))
79       .execute(conn)
80       .await?;
81
82     diesel::update(person::table.find(person_id))
83       .set((
84         person::display_name.eq::<Option<String>>(None),
85         person::avatar.eq::<Option<String>>(None),
86         person::banner.eq::<Option<String>>(None),
87         person::bio.eq::<Option<String>>(None),
88         person::matrix_user_id.eq::<Option<String>>(None),
89         person::deleted.eq(true),
90         person::updated.eq(naive_now()),
91       ))
92       .get_result::<Self>(conn)
93       .await
94   }
95 }
96
97 pub fn is_banned(banned_: bool, expires: Option<chrono::NaiveDateTime>) -> bool {
98   if let Some(expires) = expires {
99     banned_ && expires.gt(&naive_now())
100   } else {
101     banned_
102   }
103 }
104
105 #[async_trait]
106 impl ApubActor for Person {
107   async fn read_from_apub_id(pool: &DbPool, object_id: &DbUrl) -> Result<Option<Self>, Error> {
108     let conn = &mut get_conn(pool).await?;
109     Ok(
110       person::table
111         .filter(person::deleted.eq(false))
112         .filter(person::actor_id.eq(object_id))
113         .first::<Person>(conn)
114         .await
115         .ok()
116         .map(Into::into),
117     )
118   }
119
120   async fn read_from_name(
121     pool: &DbPool,
122     from_name: &str,
123     include_deleted: bool,
124   ) -> Result<Person, Error> {
125     let conn = &mut get_conn(pool).await?;
126     let mut q = person::table
127       .into_boxed()
128       .filter(person::local.eq(true))
129       .filter(lower(person::name).eq(from_name.to_lowercase()));
130     if !include_deleted {
131       q = q.filter(person::deleted.eq(false))
132     }
133     q.first::<Self>(conn).await
134   }
135
136   async fn read_from_name_and_domain(
137     pool: &DbPool,
138     person_name: &str,
139     for_domain: &str,
140   ) -> Result<Person, Error> {
141     let conn = &mut get_conn(pool).await?;
142
143     person::table
144       .inner_join(instance::table)
145       .filter(lower(person::name).eq(person_name.to_lowercase()))
146       .filter(instance::domain.eq(for_domain))
147       .select(person::all_columns)
148       .first::<Self>(conn)
149       .await
150   }
151 }
152
153 #[async_trait]
154 impl Followable for PersonFollower {
155   type Form = PersonFollowerForm;
156   async fn follow(pool: &DbPool, form: &PersonFollowerForm) -> Result<Self, Error> {
157     use crate::schema::person_follower::dsl::{follower_id, person_follower, person_id};
158     let conn = &mut get_conn(pool).await?;
159     insert_into(person_follower)
160       .values(form)
161       .on_conflict((follower_id, person_id))
162       .do_update()
163       .set(form)
164       .get_result::<Self>(conn)
165       .await
166   }
167   async fn follow_accepted(_: &DbPool, _: CommunityId, _: PersonId) -> Result<Self, Error> {
168     unimplemented!()
169   }
170   async fn unfollow(pool: &DbPool, form: &PersonFollowerForm) -> Result<usize, Error> {
171     use crate::schema::person_follower::dsl::{follower_id, person_follower, person_id};
172     let conn = &mut get_conn(pool).await?;
173     diesel::delete(
174       person_follower
175         .filter(follower_id.eq(&form.follower_id))
176         .filter(person_id.eq(&form.person_id)),
177     )
178     .execute(conn)
179     .await
180   }
181 }
182
183 impl PersonFollower {
184   pub async fn list_followers(
185     pool: &DbPool,
186     for_person_id: PersonId,
187   ) -> Result<Vec<Person>, Error> {
188     let conn = &mut get_conn(pool).await?;
189     person_follower::table
190       .inner_join(person::table.on(person_follower::follower_id.eq(person::id)))
191       .filter(person_follower::person_id.eq(for_person_id))
192       .select(person::all_columns)
193       .load(conn)
194       .await
195   }
196 }
197
198 #[cfg(test)]
199 mod tests {
200   use crate::{
201     source::{
202       instance::Instance,
203       person::{Person, PersonFollower, PersonFollowerForm, PersonInsertForm, PersonUpdateForm},
204     },
205     traits::{Crud, Followable},
206     utils::build_db_pool_for_tests,
207   };
208   use serial_test::serial;
209
210   #[tokio::test]
211   #[serial]
212   async fn test_crud() {
213     let pool = &build_db_pool_for_tests().await;
214
215     let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string())
216       .await
217       .unwrap();
218
219     let new_person = PersonInsertForm::builder()
220       .name("holly".into())
221       .public_key("nada".to_owned())
222       .instance_id(inserted_instance.id)
223       .build();
224
225     let inserted_person = Person::create(pool, &new_person).await.unwrap();
226
227     let expected_person = Person {
228       id: inserted_person.id,
229       name: "holly".into(),
230       display_name: None,
231       avatar: None,
232       banner: None,
233       banned: false,
234       deleted: false,
235       published: inserted_person.published,
236       updated: None,
237       actor_id: inserted_person.actor_id.clone(),
238       bio: None,
239       local: true,
240       bot_account: false,
241       admin: false,
242       private_key: None,
243       public_key: "nada".to_owned(),
244       last_refreshed_at: inserted_person.published,
245       inbox_url: inserted_person.inbox_url.clone(),
246       shared_inbox_url: None,
247       matrix_user_id: None,
248       ban_expires: None,
249       instance_id: inserted_instance.id,
250     };
251
252     let read_person = Person::read(pool, inserted_person.id).await.unwrap();
253
254     let update_person_form = PersonUpdateForm::builder()
255       .actor_id(Some(inserted_person.actor_id.clone()))
256       .build();
257     let updated_person = Person::update(pool, inserted_person.id, &update_person_form)
258       .await
259       .unwrap();
260
261     let num_deleted = Person::delete(pool, inserted_person.id).await.unwrap();
262     Instance::delete(pool, inserted_instance.id).await.unwrap();
263
264     assert_eq!(expected_person, read_person);
265     assert_eq!(expected_person, inserted_person);
266     assert_eq!(expected_person, updated_person);
267     assert_eq!(1, num_deleted);
268   }
269
270   #[tokio::test]
271   #[serial]
272   async fn follow() {
273     let pool = &build_db_pool_for_tests().await;
274     let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string())
275       .await
276       .unwrap();
277
278     let person_form_1 = PersonInsertForm::builder()
279       .name("erich".into())
280       .public_key("pubkey".to_string())
281       .instance_id(inserted_instance.id)
282       .build();
283     let person_1 = Person::create(pool, &person_form_1).await.unwrap();
284     let person_form_2 = PersonInsertForm::builder()
285       .name("michele".into())
286       .public_key("pubkey".to_string())
287       .instance_id(inserted_instance.id)
288       .build();
289     let person_2 = Person::create(pool, &person_form_2).await.unwrap();
290
291     let follow_form = PersonFollowerForm {
292       person_id: person_1.id,
293       follower_id: person_2.id,
294       pending: false,
295     };
296     let person_follower = PersonFollower::follow(pool, &follow_form).await.unwrap();
297     assert_eq!(person_1.id, person_follower.person_id);
298     assert_eq!(person_2.id, person_follower.follower_id);
299     assert!(!person_follower.pending);
300
301     let followers = PersonFollower::list_followers(pool, person_1.id)
302       .await
303       .unwrap();
304     assert_eq!(vec![person_2], followers);
305
306     let unfollow = PersonFollower::unfollow(pool, &follow_form).await.unwrap();
307     assert_eq!(1, unfollow);
308   }
309 }