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