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