]> Untitled Git - lemmy.git/blob - crates/api_common/src/utils.rs
Adding a vector indexing check to prevent panics. Fixes #2753 (#2754)
[lemmy.git] / crates / api_common / src / utils.rs
1 use crate::{request::purge_image_from_pictrs, sensitive::Sensitive, site::FederatedInstances};
2 use anyhow::Context;
3 use chrono::NaiveDateTime;
4 use lemmy_db_schema::{
5   impls::person::is_banned,
6   newtypes::{CommunityId, DbUrl, LocalUserId, PersonId, PostId},
7   source::{
8     comment::{Comment, CommentUpdateForm},
9     community::{Community, CommunityUpdateForm},
10     email_verification::{EmailVerification, EmailVerificationForm},
11     instance::Instance,
12     local_site::{LocalSite, RegistrationMode},
13     local_site_rate_limit::LocalSiteRateLimit,
14     password_reset_request::PasswordResetRequest,
15     person::{Person, PersonUpdateForm},
16     person_block::PersonBlock,
17     post::{Post, PostRead, PostReadForm},
18     registration_application::RegistrationApplication,
19     secret::Secret,
20   },
21   traits::{Crud, Readable},
22   utils::DbPool,
23   ListingType,
24 };
25 use lemmy_db_views::{
26   comment_view::CommentQuery,
27   structs::{LocalUserSettingsView, LocalUserView},
28 };
29 use lemmy_db_views_actor::structs::{
30   CommunityModeratorView,
31   CommunityPersonBanView,
32   CommunityView,
33   PersonViewSafe,
34 };
35 use lemmy_utils::{
36   claims::Claims,
37   email::{send_email, translations::Lang},
38   error::LemmyError,
39   location_info,
40   rate_limit::RateLimitConfig,
41   settings::structs::Settings,
42   utils::slurs::build_slur_regex,
43 };
44 use regex::Regex;
45 use reqwest_middleware::ClientWithMiddleware;
46 use rosetta_i18n::{Language, LanguageId};
47 use std::str::FromStr;
48 use tracing::warn;
49 use url::{ParseError, Url};
50
51 #[tracing::instrument(skip_all)]
52 pub async fn is_mod_or_admin(
53   pool: &DbPool,
54   person_id: PersonId,
55   community_id: CommunityId,
56 ) -> Result<(), LemmyError> {
57   let is_mod_or_admin = CommunityView::is_mod_or_admin(pool, person_id, community_id).await?;
58   if !is_mod_or_admin {
59     return Err(LemmyError::from_message("not_a_mod_or_admin"));
60   }
61   Ok(())
62 }
63
64 pub async fn is_top_admin(pool: &DbPool, person_id: PersonId) -> Result<(), LemmyError> {
65   let admins = PersonViewSafe::admins(pool).await?;
66   let top_admin = admins
67     .first()
68     .ok_or_else(|| LemmyError::from_message("no admins"))?;
69
70   if top_admin.person.id != person_id {
71     return Err(LemmyError::from_message("not_top_admin"));
72   }
73   Ok(())
74 }
75
76 pub fn is_admin(local_user_view: &LocalUserView) -> Result<(), LemmyError> {
77   if !local_user_view.person.admin {
78     return Err(LemmyError::from_message("not_an_admin"));
79   }
80   Ok(())
81 }
82
83 pub fn is_top_mod(
84   local_user_view: &LocalUserView,
85   community_mods: &[CommunityModeratorView],
86 ) -> Result<(), LemmyError> {
87   if local_user_view.person.id
88     != community_mods
89       .first()
90       .map(|cm| cm.moderator.id)
91       .unwrap_or(PersonId(0))
92   {
93     return Err(LemmyError::from_message("not_top_mod"));
94   }
95   Ok(())
96 }
97
98 #[tracing::instrument(skip_all)]
99 pub async fn get_post(post_id: PostId, pool: &DbPool) -> Result<Post, LemmyError> {
100   Post::read(pool, post_id)
101     .await
102     .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_post"))
103 }
104
105 #[tracing::instrument(skip_all)]
106 pub async fn mark_post_as_read(
107   person_id: PersonId,
108   post_id: PostId,
109   pool: &DbPool,
110 ) -> Result<PostRead, LemmyError> {
111   let post_read_form = PostReadForm { post_id, person_id };
112
113   PostRead::mark_as_read(pool, &post_read_form)
114     .await
115     .map_err(|e| LemmyError::from_error_message(e, "couldnt_mark_post_as_read"))
116 }
117
118 #[tracing::instrument(skip_all)]
119 pub async fn mark_post_as_unread(
120   person_id: PersonId,
121   post_id: PostId,
122   pool: &DbPool,
123 ) -> Result<usize, LemmyError> {
124   let post_read_form = PostReadForm { post_id, person_id };
125
126   PostRead::mark_as_unread(pool, &post_read_form)
127     .await
128     .map_err(|e| LemmyError::from_error_message(e, "couldnt_mark_post_as_read"))
129 }
130
131 #[tracing::instrument(skip_all)]
132 pub async fn get_local_user_view_from_jwt(
133   jwt: &str,
134   pool: &DbPool,
135   secret: &Secret,
136 ) -> Result<LocalUserView, LemmyError> {
137   let claims = Claims::decode(jwt, &secret.jwt_secret)
138     .map_err(|e| e.with_message("not_logged_in"))?
139     .claims;
140   let local_user_id = LocalUserId(claims.sub);
141   let local_user_view = LocalUserView::read(pool, local_user_id).await?;
142   check_user_valid(
143     local_user_view.person.banned,
144     local_user_view.person.ban_expires,
145     local_user_view.person.deleted,
146   )?;
147
148   check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
149
150   Ok(local_user_view)
151 }
152
153 /// Checks if user's token was issued before user's password reset.
154 pub fn check_validator_time(
155   validator_time: &NaiveDateTime,
156   claims: &Claims,
157 ) -> Result<(), LemmyError> {
158   let user_validation_time = validator_time.timestamp();
159   if user_validation_time > claims.iat {
160     Err(LemmyError::from_message("not_logged_in"))
161   } else {
162     Ok(())
163   }
164 }
165
166 #[tracing::instrument(skip_all)]
167 pub async fn get_local_user_view_from_jwt_opt(
168   jwt: Option<&Sensitive<String>>,
169   pool: &DbPool,
170   secret: &Secret,
171 ) -> Result<Option<LocalUserView>, LemmyError> {
172   match jwt {
173     Some(jwt) => Ok(Some(get_local_user_view_from_jwt(jwt, pool, secret).await?)),
174     None => Ok(None),
175   }
176 }
177
178 #[tracing::instrument(skip_all)]
179 pub async fn get_local_user_settings_view_from_jwt_opt(
180   jwt: Option<&Sensitive<String>>,
181   pool: &DbPool,
182   secret: &Secret,
183 ) -> Result<Option<LocalUserSettingsView>, LemmyError> {
184   match jwt {
185     Some(jwt) => {
186       let claims = Claims::decode(jwt.as_ref(), &secret.jwt_secret)
187         .map_err(|e| e.with_message("not_logged_in"))?
188         .claims;
189       let local_user_id = LocalUserId(claims.sub);
190       let local_user_view = LocalUserSettingsView::read(pool, local_user_id).await?;
191       check_user_valid(
192         local_user_view.person.banned,
193         local_user_view.person.ban_expires,
194         local_user_view.person.deleted,
195       )?;
196
197       check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
198
199       Ok(Some(local_user_view))
200     }
201     None => Ok(None),
202   }
203 }
204 pub fn check_user_valid(
205   banned: bool,
206   ban_expires: Option<NaiveDateTime>,
207   deleted: bool,
208 ) -> Result<(), LemmyError> {
209   // Check for a site ban
210   if is_banned(banned, ban_expires) {
211     return Err(LemmyError::from_message("site_ban"));
212   }
213
214   // check for account deletion
215   if deleted {
216     return Err(LemmyError::from_message("deleted"));
217   }
218
219   Ok(())
220 }
221
222 #[tracing::instrument(skip_all)]
223 pub async fn check_community_ban(
224   person_id: PersonId,
225   community_id: CommunityId,
226   pool: &DbPool,
227 ) -> Result<(), LemmyError> {
228   let is_banned = CommunityPersonBanView::get(pool, person_id, community_id)
229     .await
230     .is_ok();
231   if is_banned {
232     Err(LemmyError::from_message("community_ban"))
233   } else {
234     Ok(())
235   }
236 }
237
238 #[tracing::instrument(skip_all)]
239 pub async fn check_community_deleted_or_removed(
240   community_id: CommunityId,
241   pool: &DbPool,
242 ) -> Result<(), LemmyError> {
243   let community = Community::read(pool, community_id)
244     .await
245     .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_community"))?;
246   if community.deleted || community.removed {
247     Err(LemmyError::from_message("deleted"))
248   } else {
249     Ok(())
250   }
251 }
252
253 pub fn check_post_deleted_or_removed(post: &Post) -> Result<(), LemmyError> {
254   if post.deleted || post.removed {
255     Err(LemmyError::from_message("deleted"))
256   } else {
257     Ok(())
258   }
259 }
260
261 #[tracing::instrument(skip_all)]
262 pub async fn check_person_block(
263   my_id: PersonId,
264   potential_blocker_id: PersonId,
265   pool: &DbPool,
266 ) -> Result<(), LemmyError> {
267   let is_blocked = PersonBlock::read(pool, potential_blocker_id, my_id)
268     .await
269     .is_ok();
270   if is_blocked {
271     Err(LemmyError::from_message("person_block"))
272   } else {
273     Ok(())
274   }
275 }
276
277 #[tracing::instrument(skip_all)]
278 pub fn check_downvotes_enabled(score: i16, local_site: &LocalSite) -> Result<(), LemmyError> {
279   if score == -1 && !local_site.enable_downvotes {
280     return Err(LemmyError::from_message("downvotes_disabled"));
281   }
282   Ok(())
283 }
284
285 #[tracing::instrument(skip_all)]
286 pub fn check_private_instance(
287   local_user_view: &Option<LocalUserView>,
288   local_site: &LocalSite,
289 ) -> Result<(), LemmyError> {
290   if local_user_view.is_none() && local_site.private_instance {
291     return Err(LemmyError::from_message("instance_is_private"));
292   }
293   Ok(())
294 }
295
296 #[tracing::instrument(skip_all)]
297 pub async fn build_federated_instances(
298   local_site: &LocalSite,
299   pool: &DbPool,
300 ) -> Result<Option<FederatedInstances>, LemmyError> {
301   if local_site.federation_enabled {
302     // TODO I hate that this requires 3 queries
303     let linked = Instance::linked(pool).await?;
304     let allowed = Instance::allowlist(pool).await?;
305     let blocked = Instance::blocklist(pool).await?;
306
307     // These can return empty vectors, so convert them to options
308     let allowed = (!allowed.is_empty()).then_some(allowed);
309     let blocked = (!blocked.is_empty()).then_some(blocked);
310
311     Ok(Some(FederatedInstances {
312       linked,
313       allowed,
314       blocked,
315     }))
316   } else {
317     Ok(None)
318   }
319 }
320
321 /// Checks the password length
322 pub fn password_length_check(pass: &str) -> Result<(), LemmyError> {
323   if !(10..=60).contains(&pass.chars().count()) {
324     Err(LemmyError::from_message("invalid_password"))
325   } else {
326     Ok(())
327   }
328 }
329
330 /// Checks the site description length
331 pub fn site_description_length_check(description: &str) -> Result<(), LemmyError> {
332   if description.len() > 150 {
333     Err(LemmyError::from_message("site_description_length_overflow"))
334   } else {
335     Ok(())
336   }
337 }
338
339 /// Checks for a honeypot. If this field is filled, fail the rest of the function
340 pub fn honeypot_check(honeypot: &Option<String>) -> Result<(), LemmyError> {
341   if honeypot.is_some() && honeypot != &Some(String::new()) {
342     Err(LemmyError::from_message("honeypot_fail"))
343   } else {
344     Ok(())
345   }
346 }
347
348 pub fn send_email_to_user(
349   local_user_view: &LocalUserView,
350   subject: &str,
351   body: &str,
352   settings: &Settings,
353 ) {
354   if local_user_view.person.banned || !local_user_view.local_user.send_notifications_to_email {
355     return;
356   }
357
358   if let Some(user_email) = &local_user_view.local_user.email {
359     match send_email(
360       subject,
361       user_email,
362       &local_user_view.person.name,
363       body,
364       settings,
365     ) {
366       Ok(_o) => _o,
367       Err(e) => warn!("{}", e),
368     };
369   }
370 }
371
372 pub async fn send_password_reset_email(
373   user: &LocalUserView,
374   pool: &DbPool,
375   settings: &Settings,
376 ) -> Result<(), LemmyError> {
377   // Generate a random token
378   let token = uuid::Uuid::new_v4().to_string();
379
380   // Insert the row
381   let token2 = token.clone();
382   let local_user_id = user.local_user.id;
383   PasswordResetRequest::create_token(pool, local_user_id, &token2).await?;
384
385   let email = &user.local_user.email.clone().expect("email");
386   let lang = get_interface_language(user);
387   let subject = &lang.password_reset_subject(&user.person.name);
388   let protocol_and_hostname = settings.get_protocol_and_hostname();
389   let reset_link = format!("{}/password_change/{}", protocol_and_hostname, &token);
390   let body = &lang.password_reset_body(reset_link, &user.person.name);
391   send_email(subject, email, &user.person.name, body, settings)
392 }
393
394 /// Send a verification email
395 pub async fn send_verification_email(
396   user: &LocalUserView,
397   new_email: &str,
398   pool: &DbPool,
399   settings: &Settings,
400 ) -> Result<(), LemmyError> {
401   let form = EmailVerificationForm {
402     local_user_id: user.local_user.id,
403     email: new_email.to_string(),
404     verification_token: uuid::Uuid::new_v4().to_string(),
405   };
406   let verify_link = format!(
407     "{}/verify_email/{}",
408     settings.get_protocol_and_hostname(),
409     &form.verification_token
410   );
411   EmailVerification::create(pool, &form).await?;
412
413   let lang = get_interface_language(user);
414   let subject = lang.verify_email_subject(&settings.hostname);
415   let body = lang.verify_email_body(&settings.hostname, &user.person.name, verify_link);
416   send_email(&subject, new_email, &user.person.name, &body, settings)?;
417
418   Ok(())
419 }
420
421 pub fn send_email_verification_success(
422   user: &LocalUserView,
423   settings: &Settings,
424 ) -> Result<(), LemmyError> {
425   let email = &user.local_user.email.clone().expect("email");
426   let lang = get_interface_language(user);
427   let subject = &lang.email_verified_subject(&user.person.actor_id);
428   let body = &lang.email_verified_body();
429   send_email(subject, email, &user.person.name, body, settings)
430 }
431
432 pub fn get_interface_language(user: &LocalUserView) -> Lang {
433   lang_str_to_lang(&user.local_user.interface_language)
434 }
435
436 pub fn get_interface_language_from_settings(user: &LocalUserSettingsView) -> Lang {
437   lang_str_to_lang(&user.local_user.interface_language)
438 }
439
440 fn lang_str_to_lang(lang: &str) -> Lang {
441   let lang_id = LanguageId::new(lang);
442   Lang::from_language_id(&lang_id).unwrap_or_else(|| {
443     let en = LanguageId::new("en");
444     Lang::from_language_id(&en).expect("default language")
445   })
446 }
447
448 pub fn local_site_rate_limit_to_rate_limit_config(
449   local_site_rate_limit: &LocalSiteRateLimit,
450 ) -> RateLimitConfig {
451   let l = local_site_rate_limit;
452   RateLimitConfig {
453     message: l.message,
454     message_per_second: l.message_per_second,
455     post: l.post,
456     post_per_second: l.post_per_second,
457     register: l.register,
458     register_per_second: l.register_per_second,
459     image: l.image,
460     image_per_second: l.image_per_second,
461     comment: l.comment,
462     comment_per_second: l.comment_per_second,
463     search: l.search,
464     search_per_second: l.search_per_second,
465   }
466 }
467
468 pub fn local_site_to_slur_regex(local_site: &LocalSite) -> Option<Regex> {
469   build_slur_regex(local_site.slur_filter_regex.as_deref())
470 }
471
472 pub fn local_site_opt_to_slur_regex(local_site: &Option<LocalSite>) -> Option<Regex> {
473   local_site
474     .as_ref()
475     .map(local_site_to_slur_regex)
476     .unwrap_or(None)
477 }
478
479 pub fn send_application_approved_email(
480   user: &LocalUserView,
481   settings: &Settings,
482 ) -> Result<(), LemmyError> {
483   let email = &user.local_user.email.clone().expect("email");
484   let lang = get_interface_language(user);
485   let subject = lang.registration_approved_subject(&user.person.actor_id);
486   let body = lang.registration_approved_body(&settings.hostname);
487   send_email(&subject, email, &user.person.name, &body, settings)
488 }
489
490 /// Send a new applicant email notification to all admins
491 pub async fn send_new_applicant_email_to_admins(
492   applicant_username: &str,
493   pool: &DbPool,
494   settings: &Settings,
495 ) -> Result<(), LemmyError> {
496   // Collect the admins with emails
497   let admins = LocalUserSettingsView::list_admins_with_emails(pool).await?;
498
499   let applications_link = &format!(
500     "{}/registration_applications",
501     settings.get_protocol_and_hostname(),
502   );
503
504   for admin in &admins {
505     let email = &admin.local_user.email.clone().expect("email");
506     let lang = get_interface_language_from_settings(admin);
507     let subject = lang.new_application_subject(&settings.hostname, applicant_username);
508     let body = lang.new_application_body(applications_link);
509     send_email(&subject, email, &admin.person.name, &body, settings)?;
510   }
511   Ok(())
512 }
513
514 /// Send a report to all admins
515 pub async fn send_new_report_email_to_admins(
516   reporter_username: &str,
517   reported_username: &str,
518   pool: &DbPool,
519   settings: &Settings,
520 ) -> Result<(), LemmyError> {
521   // Collect the admins with emails
522   let admins = LocalUserSettingsView::list_admins_with_emails(pool).await?;
523
524   let reports_link = &format!("{}/reports", settings.get_protocol_and_hostname(),);
525
526   for admin in &admins {
527     let email = &admin.local_user.email.clone().expect("email");
528     let lang = get_interface_language_from_settings(admin);
529     let subject = lang.new_report_subject(&settings.hostname, reporter_username, reported_username);
530     let body = lang.new_report_body(reports_link);
531     send_email(&subject, email, &admin.person.name, &body, settings)?;
532   }
533   Ok(())
534 }
535
536 pub async fn check_registration_application(
537   local_user_view: &LocalUserView,
538   local_site: &LocalSite,
539   pool: &DbPool,
540 ) -> Result<(), LemmyError> {
541   if local_site.registration_mode == RegistrationMode::RequireApplication
542     && !local_user_view.local_user.accepted_application
543     && !local_user_view.person.admin
544   {
545     // Fetch the registration, see if its denied
546     let local_user_id = local_user_view.local_user.id;
547     let registration = RegistrationApplication::find_by_local_user_id(pool, local_user_id).await?;
548     if let Some(deny_reason) = registration.deny_reason {
549       let lang = get_interface_language(local_user_view);
550       let registration_denied_message = format!("{}: {}", lang.registration_denied(), &deny_reason);
551       return Err(LemmyError::from_message(&registration_denied_message));
552     } else {
553       return Err(LemmyError::from_message("registration_application_pending"));
554     }
555   }
556   Ok(())
557 }
558
559 pub fn check_private_instance_and_federation_enabled(
560   local_site: &LocalSite,
561 ) -> Result<(), LemmyError> {
562   if local_site.private_instance && local_site.federation_enabled {
563     return Err(LemmyError::from_message(
564       "Cannot have both private instance and federation enabled.",
565     ));
566   }
567   Ok(())
568 }
569
570 pub async fn purge_image_posts_for_person(
571   banned_person_id: PersonId,
572   pool: &DbPool,
573   settings: &Settings,
574   client: &ClientWithMiddleware,
575 ) -> Result<(), LemmyError> {
576   let posts = Post::fetch_pictrs_posts_for_creator(pool, banned_person_id).await?;
577   for post in posts {
578     if let Some(url) = post.url {
579       purge_image_from_pictrs(client, settings, &url).await.ok();
580     }
581     if let Some(thumbnail_url) = post.thumbnail_url {
582       purge_image_from_pictrs(client, settings, &thumbnail_url)
583         .await
584         .ok();
585     }
586   }
587
588   Post::remove_pictrs_post_images_and_thumbnails_for_creator(pool, banned_person_id).await?;
589
590   Ok(())
591 }
592
593 pub async fn purge_image_posts_for_community(
594   banned_community_id: CommunityId,
595   pool: &DbPool,
596   settings: &Settings,
597   client: &ClientWithMiddleware,
598 ) -> Result<(), LemmyError> {
599   let posts = Post::fetch_pictrs_posts_for_community(pool, banned_community_id).await?;
600   for post in posts {
601     if let Some(url) = post.url {
602       purge_image_from_pictrs(client, settings, &url).await.ok();
603     }
604     if let Some(thumbnail_url) = post.thumbnail_url {
605       purge_image_from_pictrs(client, settings, &thumbnail_url)
606         .await
607         .ok();
608     }
609   }
610
611   Post::remove_pictrs_post_images_and_thumbnails_for_community(pool, banned_community_id).await?;
612
613   Ok(())
614 }
615
616 pub async fn remove_user_data(
617   banned_person_id: PersonId,
618   pool: &DbPool,
619   settings: &Settings,
620   client: &ClientWithMiddleware,
621 ) -> Result<(), LemmyError> {
622   // Purge user images
623   let person = Person::read(pool, banned_person_id).await?;
624   if let Some(avatar) = person.avatar {
625     purge_image_from_pictrs(client, settings, &avatar)
626       .await
627       .ok();
628   }
629   if let Some(banner) = person.banner {
630     purge_image_from_pictrs(client, settings, &banner)
631       .await
632       .ok();
633   }
634
635   // Update the fields to None
636   Person::update(
637     pool,
638     banned_person_id,
639     &PersonUpdateForm::builder()
640       .avatar(Some(None))
641       .banner(Some(None))
642       .build(),
643   )
644   .await?;
645
646   // Posts
647   Post::update_removed_for_creator(pool, banned_person_id, None, true).await?;
648
649   // Purge image posts
650   purge_image_posts_for_person(banned_person_id, pool, settings, client).await?;
651
652   // Communities
653   // Remove all communities where they're the top mod
654   // for now, remove the communities manually
655   let first_mod_communities = CommunityModeratorView::get_community_first_mods(pool).await?;
656
657   // Filter to only this banned users top communities
658   let banned_user_first_communities: Vec<CommunityModeratorView> = first_mod_communities
659     .into_iter()
660     .filter(|fmc| fmc.moderator.id == banned_person_id)
661     .collect();
662
663   for first_mod_community in banned_user_first_communities {
664     let community_id = first_mod_community.community.id;
665     Community::update(
666       pool,
667       community_id,
668       &CommunityUpdateForm::builder().removed(Some(true)).build(),
669     )
670     .await?;
671
672     // Delete the community images
673     if let Some(icon) = first_mod_community.community.icon {
674       purge_image_from_pictrs(client, settings, &icon).await.ok();
675     }
676     if let Some(banner) = first_mod_community.community.banner {
677       purge_image_from_pictrs(client, settings, &banner)
678         .await
679         .ok();
680     }
681     // Update the fields to None
682     Community::update(
683       pool,
684       community_id,
685       &CommunityUpdateForm::builder()
686         .icon(Some(None))
687         .banner(Some(None))
688         .build(),
689     )
690     .await?;
691   }
692
693   // Comments
694   Comment::update_removed_for_creator(pool, banned_person_id, true).await?;
695
696   Ok(())
697 }
698
699 pub async fn remove_user_data_in_community(
700   community_id: CommunityId,
701   banned_person_id: PersonId,
702   pool: &DbPool,
703 ) -> Result<(), LemmyError> {
704   // Posts
705   Post::update_removed_for_creator(pool, banned_person_id, Some(community_id), true).await?;
706
707   // Comments
708   // TODO Diesel doesn't allow updates with joins, so this has to be a loop
709   let comments = CommentQuery::builder()
710     .pool(pool)
711     .creator_id(Some(banned_person_id))
712     .community_id(Some(community_id))
713     .limit(Some(i64::MAX))
714     .build()
715     .list()
716     .await?;
717
718   for comment_view in &comments {
719     let comment_id = comment_view.comment.id;
720     Comment::update(
721       pool,
722       comment_id,
723       &CommentUpdateForm::builder().removed(Some(true)).build(),
724     )
725     .await?;
726   }
727
728   Ok(())
729 }
730
731 pub async fn delete_user_account(
732   person_id: PersonId,
733   pool: &DbPool,
734   settings: &Settings,
735   client: &ClientWithMiddleware,
736 ) -> Result<(), LemmyError> {
737   // Delete their images
738   let person = Person::read(pool, person_id).await?;
739   if let Some(avatar) = person.avatar {
740     purge_image_from_pictrs(client, settings, &avatar)
741       .await
742       .ok();
743   }
744   if let Some(banner) = person.banner {
745     purge_image_from_pictrs(client, settings, &banner)
746       .await
747       .ok();
748   }
749   // No need to update avatar and banner, those are handled in Person::delete_account
750
751   // Comments
752   Comment::permadelete_for_creator(pool, person_id)
753     .await
754     .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?;
755
756   // Posts
757   Post::permadelete_for_creator(pool, person_id)
758     .await
759     .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_post"))?;
760
761   // Purge image posts
762   purge_image_posts_for_person(person_id, pool, settings, client).await?;
763
764   Person::delete_account(pool, person_id).await?;
765
766   Ok(())
767 }
768
769 pub fn listing_type_with_site_default(
770   listing_type: Option<ListingType>,
771   local_site: &LocalSite,
772 ) -> Result<ListingType, LemmyError> {
773   Ok(listing_type.unwrap_or(ListingType::from_str(
774     &local_site.default_post_listing_type,
775   )?))
776 }
777
778 #[cfg(test)]
779 mod tests {
780   use crate::utils::{honeypot_check, password_length_check};
781
782   #[test]
783   #[rustfmt::skip]
784   fn password_length() {
785     assert!(password_length_check("Õ¼¾°3yË,o¸ãtÌÈú|ÇÁÙAøüÒI©·¤(T]/ð>æºWæ[C¤bªWöaÃÎñ·{=û³&§½K/c").is_ok());
786     assert!(password_length_check("1234567890").is_ok());
787     assert!(password_length_check("short").is_err());
788     assert!(password_length_check("looooooooooooooooooooooooooooooooooooooooooooooooooooooooooong").is_err());
789   }
790
791   #[test]
792   fn honeypot() {
793     assert!(honeypot_check(&None).is_ok());
794     assert!(honeypot_check(&Some(String::new())).is_ok());
795     assert!(honeypot_check(&Some("1".to_string())).is_err());
796     assert!(honeypot_check(&Some("message".to_string())).is_err());
797   }
798 }
799
800 pub enum EndpointType {
801   Community,
802   Person,
803   Post,
804   Comment,
805   PrivateMessage,
806 }
807
808 /// Generates an apub endpoint for a given domain, IE xyz.tld
809 pub fn generate_local_apub_endpoint(
810   endpoint_type: EndpointType,
811   name: &str,
812   domain: &str,
813 ) -> Result<DbUrl, ParseError> {
814   let point = match endpoint_type {
815     EndpointType::Community => "c",
816     EndpointType::Person => "u",
817     EndpointType::Post => "post",
818     EndpointType::Comment => "comment",
819     EndpointType::PrivateMessage => "private_message",
820   };
821
822   Ok(Url::parse(&format!("{domain}/{point}/{name}"))?.into())
823 }
824
825 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
826   Ok(Url::parse(&format!("{actor_id}/followers"))?.into())
827 }
828
829 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
830   Ok(Url::parse(&format!("{actor_id}/inbox"))?.into())
831 }
832
833 pub fn generate_site_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
834   let mut actor_id: Url = actor_id.clone().into();
835   actor_id.set_path("site_inbox");
836   Ok(actor_id.into())
837 }
838
839 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
840   let actor_id: Url = actor_id.clone().into();
841   let url = format!(
842     "{}://{}{}/inbox",
843     &actor_id.scheme(),
844     &actor_id.host_str().context(location_info!())?,
845     if let Some(port) = actor_id.port() {
846       format!(":{port}")
847     } else {
848       String::new()
849     },
850   );
851   Ok(Url::parse(&url)?.into())
852 }
853
854 pub fn generate_outbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
855   Ok(Url::parse(&format!("{actor_id}/outbox"))?.into())
856 }
857
858 pub fn generate_featured_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
859   Ok(Url::parse(&format!("{actor_id}/featured"))?.into())
860 }
861
862 pub fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
863   Ok(Url::parse(&format!("{community_id}/moderators"))?.into())
864 }