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