]> Untitled Git - lemmy.git/blob - crates/api_common/src/utils.rs
c85344992075cc5742d2612feea7d29ef2b61042
[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,
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(applicant_username, &settings.hostname);
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 pub async fn check_registration_application(
487   local_user_view: &LocalUserView,
488   local_site: &LocalSite,
489   pool: &DbPool,
490 ) -> Result<(), LemmyError> {
491   if local_site.require_application
492     && !local_user_view.local_user.accepted_application
493     && !local_user_view.person.admin
494   {
495     // Fetch the registration, see if its denied
496     let local_user_id = local_user_view.local_user.id;
497     let registration = RegistrationApplication::find_by_local_user_id(pool, local_user_id).await?;
498     if let Some(deny_reason) = registration.deny_reason {
499       let lang = get_interface_language(local_user_view);
500       let registration_denied_message = format!("{}: {}", lang.registration_denied(), &deny_reason);
501       return Err(LemmyError::from_message(&registration_denied_message));
502     } else {
503       return Err(LemmyError::from_message("registration_application_pending"));
504     }
505   }
506   Ok(())
507 }
508
509 pub fn check_private_instance_and_federation_enabled(
510   local_site: &LocalSite,
511 ) -> Result<(), LemmyError> {
512   if local_site.private_instance && local_site.federation_enabled {
513     return Err(LemmyError::from_message(
514       "Cannot have both private instance and federation enabled.",
515     ));
516   }
517   Ok(())
518 }
519
520 pub async fn purge_image_posts_for_person(
521   banned_person_id: PersonId,
522   pool: &DbPool,
523   settings: &Settings,
524   client: &ClientWithMiddleware,
525 ) -> Result<(), LemmyError> {
526   let posts = Post::fetch_pictrs_posts_for_creator(pool, banned_person_id).await?;
527   for post in posts {
528     if let Some(url) = post.url {
529       purge_image_from_pictrs(client, settings, &url).await.ok();
530     }
531     if let Some(thumbnail_url) = post.thumbnail_url {
532       purge_image_from_pictrs(client, settings, &thumbnail_url)
533         .await
534         .ok();
535     }
536   }
537
538   Post::remove_pictrs_post_images_and_thumbnails_for_creator(pool, banned_person_id).await?;
539
540   Ok(())
541 }
542
543 pub async fn purge_image_posts_for_community(
544   banned_community_id: CommunityId,
545   pool: &DbPool,
546   settings: &Settings,
547   client: &ClientWithMiddleware,
548 ) -> Result<(), LemmyError> {
549   let posts = Post::fetch_pictrs_posts_for_community(pool, banned_community_id).await?;
550   for post in posts {
551     if let Some(url) = post.url {
552       purge_image_from_pictrs(client, settings, &url).await.ok();
553     }
554     if let Some(thumbnail_url) = post.thumbnail_url {
555       purge_image_from_pictrs(client, settings, &thumbnail_url)
556         .await
557         .ok();
558     }
559   }
560
561   Post::remove_pictrs_post_images_and_thumbnails_for_community(pool, banned_community_id).await?;
562
563   Ok(())
564 }
565
566 pub async fn remove_user_data(
567   banned_person_id: PersonId,
568   pool: &DbPool,
569   settings: &Settings,
570   client: &ClientWithMiddleware,
571 ) -> Result<(), LemmyError> {
572   // Purge user images
573   let person = Person::read(pool, banned_person_id).await?;
574   if let Some(avatar) = person.avatar {
575     purge_image_from_pictrs(client, settings, &avatar)
576       .await
577       .ok();
578   }
579   if let Some(banner) = person.banner {
580     purge_image_from_pictrs(client, settings, &banner)
581       .await
582       .ok();
583   }
584
585   // Update the fields to None
586   Person::update(
587     pool,
588     banned_person_id,
589     &PersonUpdateForm::builder()
590       .avatar(Some(None))
591       .banner(Some(None))
592       .build(),
593   )
594   .await?;
595
596   // Posts
597   Post::update_removed_for_creator(pool, banned_person_id, None, true).await?;
598
599   // Purge image posts
600   purge_image_posts_for_person(banned_person_id, pool, settings, client).await?;
601
602   // Communities
603   // Remove all communities where they're the top mod
604   // for now, remove the communities manually
605   let first_mod_communities = CommunityModeratorView::get_community_first_mods(pool).await?;
606
607   // Filter to only this banned users top communities
608   let banned_user_first_communities: Vec<CommunityModeratorView> = first_mod_communities
609     .into_iter()
610     .filter(|fmc| fmc.moderator.id == banned_person_id)
611     .collect();
612
613   for first_mod_community in banned_user_first_communities {
614     let community_id = first_mod_community.community.id;
615     Community::update(
616       pool,
617       community_id,
618       &CommunityUpdateForm::builder().removed(Some(true)).build(),
619     )
620     .await?;
621
622     // Delete the community images
623     if let Some(icon) = first_mod_community.community.icon {
624       purge_image_from_pictrs(client, settings, &icon).await.ok();
625     }
626     if let Some(banner) = first_mod_community.community.banner {
627       purge_image_from_pictrs(client, settings, &banner)
628         .await
629         .ok();
630     }
631     // Update the fields to None
632     Community::update(
633       pool,
634       community_id,
635       &CommunityUpdateForm::builder()
636         .icon(Some(None))
637         .banner(Some(None))
638         .build(),
639     )
640     .await?;
641   }
642
643   // Comments
644   Comment::update_removed_for_creator(pool, banned_person_id, true).await?;
645
646   Ok(())
647 }
648
649 pub async fn remove_user_data_in_community(
650   community_id: CommunityId,
651   banned_person_id: PersonId,
652   pool: &DbPool,
653 ) -> Result<(), LemmyError> {
654   // Posts
655   Post::update_removed_for_creator(pool, banned_person_id, Some(community_id), true).await?;
656
657   // Comments
658   // TODO Diesel doesn't allow updates with joins, so this has to be a loop
659   let comments = CommentQuery::builder()
660     .pool(pool)
661     .creator_id(Some(banned_person_id))
662     .community_id(Some(community_id))
663     .limit(Some(i64::MAX))
664     .build()
665     .list()
666     .await?;
667
668   for comment_view in &comments {
669     let comment_id = comment_view.comment.id;
670     Comment::update(
671       pool,
672       comment_id,
673       &CommentUpdateForm::builder().removed(Some(true)).build(),
674     )
675     .await?;
676   }
677
678   Ok(())
679 }
680
681 pub async fn delete_user_account(
682   person_id: PersonId,
683   pool: &DbPool,
684   settings: &Settings,
685   client: &ClientWithMiddleware,
686 ) -> Result<(), LemmyError> {
687   // Delete their images
688   let person = Person::read(pool, person_id).await?;
689   if let Some(avatar) = person.avatar {
690     purge_image_from_pictrs(client, settings, &avatar)
691       .await
692       .ok();
693   }
694   if let Some(banner) = person.banner {
695     purge_image_from_pictrs(client, settings, &banner)
696       .await
697       .ok();
698   }
699   // No need to update avatar and banner, those are handled in Person::delete_account
700
701   // Comments
702   Comment::permadelete_for_creator(pool, person_id)
703     .await
704     .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?;
705
706   // Posts
707   Post::permadelete_for_creator(pool, person_id)
708     .await
709     .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_post"))?;
710
711   // Purge image posts
712   purge_image_posts_for_person(person_id, pool, settings, client).await?;
713
714   Person::delete_account(pool, person_id).await?;
715
716   Ok(())
717 }
718
719 pub fn listing_type_with_site_default(
720   listing_type: Option<ListingType>,
721   local_site: &LocalSite,
722 ) -> Result<ListingType, LemmyError> {
723   Ok(listing_type.unwrap_or(ListingType::from_str(
724     &local_site.default_post_listing_type,
725   )?))
726 }
727
728 #[cfg(test)]
729 mod tests {
730   use crate::utils::{honeypot_check, password_length_check};
731
732   #[test]
733   #[rustfmt::skip]
734   fn password_length() {
735     assert!(password_length_check("Õ¼¾°3yË,o¸ãtÌÈú|ÇÁÙAøüÒI©·¤(T]/ð>æºWæ[C¤bªWöaÃÎñ·{=û³&§½K/c").is_ok());
736     assert!(password_length_check("1234567890").is_ok());
737     assert!(password_length_check("short").is_err());
738     assert!(password_length_check("looooooooooooooooooooooooooooooooooooooooooooooooooooooooooong").is_err());
739   }
740
741   #[test]
742   fn honeypot() {
743     assert!(honeypot_check(&None).is_ok());
744     assert!(honeypot_check(&Some(String::new())).is_ok());
745     assert!(honeypot_check(&Some("1".to_string())).is_err());
746     assert!(honeypot_check(&Some("message".to_string())).is_err());
747   }
748 }
749
750 pub enum EndpointType {
751   Community,
752   Person,
753   Post,
754   Comment,
755   PrivateMessage,
756 }
757
758 /// Generates an apub endpoint for a given domain, IE xyz.tld
759 pub fn generate_local_apub_endpoint(
760   endpoint_type: EndpointType,
761   name: &str,
762   domain: &str,
763 ) -> Result<DbUrl, ParseError> {
764   let point = match endpoint_type {
765     EndpointType::Community => "c",
766     EndpointType::Person => "u",
767     EndpointType::Post => "post",
768     EndpointType::Comment => "comment",
769     EndpointType::PrivateMessage => "private_message",
770   };
771
772   Ok(Url::parse(&format!("{}/{}/{}", domain, point, name))?.into())
773 }
774
775 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
776   Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
777 }
778
779 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
780   Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
781 }
782
783 pub fn generate_site_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
784   let mut actor_id: Url = actor_id.clone().into();
785   actor_id.set_path("site_inbox");
786   Ok(actor_id.into())
787 }
788
789 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
790   let actor_id: Url = actor_id.clone().into();
791   let url = format!(
792     "{}://{}{}/inbox",
793     &actor_id.scheme(),
794     &actor_id.host_str().context(location_info!())?,
795     if let Some(port) = actor_id.port() {
796       format!(":{}", port)
797     } else {
798       String::new()
799     },
800   );
801   Ok(Url::parse(&url)?.into())
802 }
803
804 pub fn generate_outbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
805   Ok(Url::parse(&format!("{}/outbox", actor_id))?.into())
806 }
807
808 pub fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
809   Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
810 }