]> Untitled Git - lemmy.git/blob - crates/api_common/src/utils.rs
fd143ed90ca2d7df5285e6a03599dbc6667b1d36
[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 for a honeypot. If this field is filled, fail the rest of the function
303 pub fn honeypot_check(honeypot: &Option<String>) -> Result<(), LemmyError> {
304   if honeypot.is_some() && honeypot != &Some(String::new()) {
305     Err(LemmyError::from_message("honeypot_fail"))
306   } else {
307     Ok(())
308   }
309 }
310
311 pub fn send_email_to_user(
312   local_user_view: &LocalUserView,
313   subject: &str,
314   body: &str,
315   settings: &Settings,
316 ) {
317   if local_user_view.person.banned || !local_user_view.local_user.send_notifications_to_email {
318     return;
319   }
320
321   if let Some(user_email) = &local_user_view.local_user.email {
322     match send_email(
323       subject,
324       user_email,
325       &local_user_view.person.name,
326       body,
327       settings,
328     ) {
329       Ok(_o) => _o,
330       Err(e) => warn!("{}", e),
331     };
332   }
333 }
334
335 pub async fn send_password_reset_email(
336   user: &LocalUserView,
337   pool: &DbPool,
338   settings: &Settings,
339 ) -> Result<(), LemmyError> {
340   // Generate a random token
341   let token = uuid::Uuid::new_v4().to_string();
342
343   // Insert the row
344   let token2 = token.clone();
345   let local_user_id = user.local_user.id;
346   PasswordResetRequest::create_token(pool, local_user_id, &token2).await?;
347
348   let email = &user.local_user.email.clone().expect("email");
349   let lang = get_interface_language(user);
350   let subject = &lang.password_reset_subject(&user.person.name);
351   let protocol_and_hostname = settings.get_protocol_and_hostname();
352   let reset_link = format!("{}/password_change/{}", protocol_and_hostname, &token);
353   let body = &lang.password_reset_body(reset_link, &user.person.name);
354   send_email(subject, email, &user.person.name, body, settings)
355 }
356
357 /// Send a verification email
358 pub async fn send_verification_email(
359   user: &LocalUserView,
360   new_email: &str,
361   pool: &DbPool,
362   settings: &Settings,
363 ) -> Result<(), LemmyError> {
364   let form = EmailVerificationForm {
365     local_user_id: user.local_user.id,
366     email: new_email.to_string(),
367     verification_token: uuid::Uuid::new_v4().to_string(),
368   };
369   let verify_link = format!(
370     "{}/verify_email/{}",
371     settings.get_protocol_and_hostname(),
372     &form.verification_token
373   );
374   EmailVerification::create(pool, &form).await?;
375
376   let lang = get_interface_language(user);
377   let subject = lang.verify_email_subject(&settings.hostname);
378   let body = lang.verify_email_body(&settings.hostname, &user.person.name, verify_link);
379   send_email(&subject, new_email, &user.person.name, &body, settings)?;
380
381   Ok(())
382 }
383
384 pub fn get_interface_language(user: &LocalUserView) -> Lang {
385   lang_str_to_lang(&user.local_user.interface_language)
386 }
387
388 pub fn get_interface_language_from_settings(user: &LocalUserView) -> Lang {
389   lang_str_to_lang(&user.local_user.interface_language)
390 }
391
392 fn lang_str_to_lang(lang: &str) -> Lang {
393   let lang_id = LanguageId::new(lang);
394   Lang::from_language_id(&lang_id).unwrap_or_else(|| {
395     let en = LanguageId::new("en");
396     Lang::from_language_id(&en).expect("default language")
397   })
398 }
399
400 pub fn local_site_rate_limit_to_rate_limit_config(
401   local_site_rate_limit: &LocalSiteRateLimit,
402 ) -> RateLimitConfig {
403   let l = local_site_rate_limit;
404   RateLimitConfig {
405     message: l.message,
406     message_per_second: l.message_per_second,
407     post: l.post,
408     post_per_second: l.post_per_second,
409     register: l.register,
410     register_per_second: l.register_per_second,
411     image: l.image,
412     image_per_second: l.image_per_second,
413     comment: l.comment,
414     comment_per_second: l.comment_per_second,
415     search: l.search,
416     search_per_second: l.search_per_second,
417   }
418 }
419
420 pub fn local_site_to_slur_regex(local_site: &LocalSite) -> Option<Regex> {
421   build_slur_regex(local_site.slur_filter_regex.as_deref())
422 }
423
424 pub fn local_site_opt_to_slur_regex(local_site: &Option<LocalSite>) -> Option<Regex> {
425   local_site
426     .as_ref()
427     .map(local_site_to_slur_regex)
428     .unwrap_or(None)
429 }
430
431 pub fn local_site_opt_to_sensitive(local_site: &Option<LocalSite>) -> bool {
432   local_site
433     .as_ref()
434     .map(|site| site.enable_nsfw)
435     .unwrap_or(false)
436 }
437
438 pub fn send_application_approved_email(
439   user: &LocalUserView,
440   settings: &Settings,
441 ) -> Result<(), LemmyError> {
442   let email = &user.local_user.email.clone().expect("email");
443   let lang = get_interface_language(user);
444   let subject = lang.registration_approved_subject(&user.person.actor_id);
445   let body = lang.registration_approved_body(&settings.hostname);
446   send_email(&subject, email, &user.person.name, &body, settings)
447 }
448
449 /// Send a new applicant email notification to all admins
450 pub async fn send_new_applicant_email_to_admins(
451   applicant_username: &str,
452   pool: &DbPool,
453   settings: &Settings,
454 ) -> Result<(), LemmyError> {
455   // Collect the admins with emails
456   let admins = LocalUserView::list_admins_with_emails(pool).await?;
457
458   let applications_link = &format!(
459     "{}/registration_applications",
460     settings.get_protocol_and_hostname(),
461   );
462
463   for admin in &admins {
464     let email = &admin.local_user.email.clone().expect("email");
465     let lang = get_interface_language_from_settings(admin);
466     let subject = lang.new_application_subject(&settings.hostname, applicant_username);
467     let body = lang.new_application_body(applications_link);
468     send_email(&subject, email, &admin.person.name, &body, settings)?;
469   }
470   Ok(())
471 }
472
473 /// Send a report to all admins
474 pub async fn send_new_report_email_to_admins(
475   reporter_username: &str,
476   reported_username: &str,
477   pool: &DbPool,
478   settings: &Settings,
479 ) -> Result<(), LemmyError> {
480   // Collect the admins with emails
481   let admins = LocalUserView::list_admins_with_emails(pool).await?;
482
483   let reports_link = &format!("{}/reports", settings.get_protocol_and_hostname(),);
484
485   for admin in &admins {
486     let email = &admin.local_user.email.clone().expect("email");
487     let lang = get_interface_language_from_settings(admin);
488     let subject = lang.new_report_subject(&settings.hostname, reported_username, reporter_username);
489     let body = lang.new_report_body(reports_link);
490     send_email(&subject, email, &admin.person.name, &body, settings)?;
491   }
492   Ok(())
493 }
494
495 pub async fn check_registration_application(
496   local_user_view: &LocalUserView,
497   local_site: &LocalSite,
498   pool: &DbPool,
499 ) -> Result<(), LemmyError> {
500   if (local_site.registration_mode == RegistrationMode::RequireApplication
501     || local_site.registration_mode == RegistrationMode::Closed)
502     && !local_user_view.local_user.accepted_application
503     && !local_user_view.person.admin
504   {
505     // Fetch the registration, see if its denied
506     let local_user_id = local_user_view.local_user.id;
507     let registration = RegistrationApplication::find_by_local_user_id(pool, local_user_id).await?;
508     if let Some(deny_reason) = registration.deny_reason {
509       let lang = get_interface_language(local_user_view);
510       let registration_denied_message = format!("{}: {}", lang.registration_denied(), &deny_reason);
511       return Err(LemmyError::from_message(&registration_denied_message));
512     } else {
513       return Err(LemmyError::from_message("registration_application_pending"));
514     }
515   }
516   Ok(())
517 }
518
519 pub fn check_private_instance_and_federation_enabled(
520   local_site: &LocalSite,
521 ) -> Result<(), LemmyError> {
522   if local_site.private_instance && local_site.federation_enabled {
523     return Err(LemmyError::from_message(
524       "Cannot have both private instance and federation enabled.",
525     ));
526   }
527   Ok(())
528 }
529
530 pub async fn purge_image_posts_for_person(
531   banned_person_id: PersonId,
532   pool: &DbPool,
533   settings: &Settings,
534   client: &ClientWithMiddleware,
535 ) -> Result<(), LemmyError> {
536   let posts = Post::fetch_pictrs_posts_for_creator(pool, banned_person_id).await?;
537   for post in posts {
538     if let Some(url) = post.url {
539       purge_image_from_pictrs(client, settings, &url).await.ok();
540     }
541     if let Some(thumbnail_url) = post.thumbnail_url {
542       purge_image_from_pictrs(client, settings, &thumbnail_url)
543         .await
544         .ok();
545     }
546   }
547
548   Post::remove_pictrs_post_images_and_thumbnails_for_creator(pool, banned_person_id).await?;
549
550   Ok(())
551 }
552
553 pub async fn purge_image_posts_for_community(
554   banned_community_id: CommunityId,
555   pool: &DbPool,
556   settings: &Settings,
557   client: &ClientWithMiddleware,
558 ) -> Result<(), LemmyError> {
559   let posts = Post::fetch_pictrs_posts_for_community(pool, banned_community_id).await?;
560   for post in posts {
561     if let Some(url) = post.url {
562       purge_image_from_pictrs(client, settings, &url).await.ok();
563     }
564     if let Some(thumbnail_url) = post.thumbnail_url {
565       purge_image_from_pictrs(client, settings, &thumbnail_url)
566         .await
567         .ok();
568     }
569   }
570
571   Post::remove_pictrs_post_images_and_thumbnails_for_community(pool, banned_community_id).await?;
572
573   Ok(())
574 }
575
576 pub async fn remove_user_data(
577   banned_person_id: PersonId,
578   pool: &DbPool,
579   settings: &Settings,
580   client: &ClientWithMiddleware,
581 ) -> Result<(), LemmyError> {
582   // Purge user images
583   let person = Person::read(pool, banned_person_id).await?;
584   if let Some(avatar) = person.avatar {
585     purge_image_from_pictrs(client, settings, &avatar)
586       .await
587       .ok();
588   }
589   if let Some(banner) = person.banner {
590     purge_image_from_pictrs(client, settings, &banner)
591       .await
592       .ok();
593   }
594
595   // Update the fields to None
596   Person::update(
597     pool,
598     banned_person_id,
599     &PersonUpdateForm::builder()
600       .avatar(Some(None))
601       .banner(Some(None))
602       .build(),
603   )
604   .await?;
605
606   // Posts
607   Post::update_removed_for_creator(pool, banned_person_id, None, true).await?;
608
609   // Purge image posts
610   purge_image_posts_for_person(banned_person_id, pool, settings, client).await?;
611
612   // Communities
613   // Remove all communities where they're the top mod
614   // for now, remove the communities manually
615   let first_mod_communities = CommunityModeratorView::get_community_first_mods(pool).await?;
616
617   // Filter to only this banned users top communities
618   let banned_user_first_communities: Vec<CommunityModeratorView> = first_mod_communities
619     .into_iter()
620     .filter(|fmc| fmc.moderator.id == banned_person_id)
621     .collect();
622
623   for first_mod_community in banned_user_first_communities {
624     let community_id = first_mod_community.community.id;
625     Community::update(
626       pool,
627       community_id,
628       &CommunityUpdateForm::builder().removed(Some(true)).build(),
629     )
630     .await?;
631
632     // Delete the community images
633     if let Some(icon) = first_mod_community.community.icon {
634       purge_image_from_pictrs(client, settings, &icon).await.ok();
635     }
636     if let Some(banner) = first_mod_community.community.banner {
637       purge_image_from_pictrs(client, settings, &banner)
638         .await
639         .ok();
640     }
641     // Update the fields to None
642     Community::update(
643       pool,
644       community_id,
645       &CommunityUpdateForm::builder()
646         .icon(Some(None))
647         .banner(Some(None))
648         .build(),
649     )
650     .await?;
651   }
652
653   // Comments
654   Comment::update_removed_for_creator(pool, banned_person_id, true).await?;
655
656   Ok(())
657 }
658
659 pub async fn remove_user_data_in_community(
660   community_id: CommunityId,
661   banned_person_id: PersonId,
662   pool: &DbPool,
663 ) -> Result<(), LemmyError> {
664   // Posts
665   Post::update_removed_for_creator(pool, banned_person_id, Some(community_id), true).await?;
666
667   // Comments
668   // TODO Diesel doesn't allow updates with joins, so this has to be a loop
669   let comments = CommentQuery::builder()
670     .pool(pool)
671     .creator_id(Some(banned_person_id))
672     .community_id(Some(community_id))
673     .build()
674     .list()
675     .await?;
676
677   for comment_view in &comments {
678     let comment_id = comment_view.comment.id;
679     Comment::update(
680       pool,
681       comment_id,
682       &CommentUpdateForm::builder().removed(Some(true)).build(),
683     )
684     .await?;
685   }
686
687   Ok(())
688 }
689
690 pub async fn delete_user_account(
691   person_id: PersonId,
692   pool: &DbPool,
693   settings: &Settings,
694   client: &ClientWithMiddleware,
695 ) -> Result<(), LemmyError> {
696   // Delete their images
697   let person = Person::read(pool, person_id).await?;
698   if let Some(avatar) = person.avatar {
699     purge_image_from_pictrs(client, settings, &avatar)
700       .await
701       .ok();
702   }
703   if let Some(banner) = person.banner {
704     purge_image_from_pictrs(client, settings, &banner)
705       .await
706       .ok();
707   }
708   // No need to update avatar and banner, those are handled in Person::delete_account
709
710   // Comments
711   Comment::permadelete_for_creator(pool, person_id)
712     .await
713     .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?;
714
715   // Posts
716   Post::permadelete_for_creator(pool, person_id)
717     .await
718     .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_post"))?;
719
720   // Purge image posts
721   purge_image_posts_for_person(person_id, pool, settings, client).await?;
722
723   // Leave communities they mod
724   CommunityModerator::leave_all_communities(pool, person_id).await?;
725
726   Person::delete_account(pool, person_id).await?;
727
728   Ok(())
729 }
730
731 #[cfg(test)]
732 mod tests {
733   use crate::utils::{honeypot_check, password_length_check};
734
735   #[test]
736   #[rustfmt::skip]
737   fn password_length() {
738     assert!(password_length_check("Õ¼¾°3yË,o¸ãtÌÈú|ÇÁÙAøüÒI©·¤(T]/ð>æºWæ[C¤bªWöaÃÎñ·{=û³&§½K/c").is_ok());
739     assert!(password_length_check("1234567890").is_ok());
740     assert!(password_length_check("short").is_err());
741     assert!(password_length_check("looooooooooooooooooooooooooooooooooooooooooooooooooooooooooong").is_err());
742   }
743
744   #[test]
745   fn honeypot() {
746     assert!(honeypot_check(&None).is_ok());
747     assert!(honeypot_check(&Some(String::new())).is_ok());
748     assert!(honeypot_check(&Some("1".to_string())).is_err());
749     assert!(honeypot_check(&Some("message".to_string())).is_err());
750   }
751 }
752
753 pub enum EndpointType {
754   Community,
755   Person,
756   Post,
757   Comment,
758   PrivateMessage,
759 }
760
761 /// Generates an apub endpoint for a given domain, IE xyz.tld
762 pub fn generate_local_apub_endpoint(
763   endpoint_type: EndpointType,
764   name: &str,
765   domain: &str,
766 ) -> Result<DbUrl, ParseError> {
767   let point = match endpoint_type {
768     EndpointType::Community => "c",
769     EndpointType::Person => "u",
770     EndpointType::Post => "post",
771     EndpointType::Comment => "comment",
772     EndpointType::PrivateMessage => "private_message",
773   };
774
775   Ok(Url::parse(&format!("{domain}/{point}/{name}"))?.into())
776 }
777
778 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
779   Ok(Url::parse(&format!("{actor_id}/followers"))?.into())
780 }
781
782 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
783   Ok(Url::parse(&format!("{actor_id}/inbox"))?.into())
784 }
785
786 pub fn generate_site_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
787   let mut actor_id: Url = actor_id.clone().into();
788   actor_id.set_path("site_inbox");
789   Ok(actor_id.into())
790 }
791
792 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
793   let actor_id: Url = actor_id.clone().into();
794   let url = format!(
795     "{}://{}{}/inbox",
796     &actor_id.scheme(),
797     &actor_id.host_str().context(location_info!())?,
798     if let Some(port) = actor_id.port() {
799       format!(":{port}")
800     } else {
801       String::new()
802     },
803   );
804   Ok(Url::parse(&url)?.into())
805 }
806
807 pub fn generate_outbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
808   Ok(Url::parse(&format!("{actor_id}/outbox"))?.into())
809 }
810
811 pub fn generate_featured_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
812   Ok(Url::parse(&format!("{actor_id}/featured"))?.into())
813 }
814
815 pub fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
816   Ok(Url::parse(&format!("{community_id}/moderators"))?.into())
817 }