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