2 captcha_espeak_wav_base64,
3 collect_moderated_communities,
4 get_local_user_view_from_jwt,
5 get_local_user_view_from_jwt_opt,
10 use actix_web::web::Data;
13 use captcha::{gen, Difficulty};
15 use lemmy_api_structs::{blocking, person::*, send_email_to_user};
17 generate_apub_endpoint,
18 generate_followers_url,
20 generate_shared_inbox_url,
24 use lemmy_db_queries::{
25 diesel_option_overwrite,
26 diesel_option_overwrite_to_url,
29 community::Community_,
30 local_user::LocalUser_,
31 password_reset_request::PasswordResetRequest_,
33 person_mention::PersonMention_,
35 private_message::PrivateMessage_,
44 use lemmy_db_schema::{
49 local_user::{LocalUser, LocalUserForm},
51 password_reset_request::*,
60 comment_report_view::CommentReportView,
61 comment_view::CommentQueryBuilder,
62 local_user_view::LocalUserView,
63 post_report_view::PostReportView,
64 post_view::PostQueryBuilder,
65 private_message_view::{PrivateMessageQueryBuilder, PrivateMessageView},
67 use lemmy_db_views_actor::{
68 community_follower_view::CommunityFollowerView,
69 community_moderator_view::CommunityModeratorView,
70 person_mention_view::{PersonMentionQueryBuilder, PersonMentionView},
71 person_view::PersonViewSafe,
74 apub::generate_actor_keypair,
78 settings::structs::Settings,
81 generate_random_string,
82 is_valid_preferred_username,
91 use lemmy_websocket::{
92 messages::{CaptchaItem, CheckCaptcha, SendAllMessage, SendUserRoomMessage},
96 use std::str::FromStr;
98 #[async_trait::async_trait(?Send)]
99 impl Perform for Login {
100 type Response = LoginResponse;
104 context: &Data<LemmyContext>,
105 _websocket_id: Option<ConnectionId>,
106 ) -> Result<LoginResponse, LemmyError> {
107 let data: &Login = &self;
109 // Fetch that username / email
110 let username_or_email = data.username_or_email.clone();
111 let local_user_view = match blocking(context.pool(), move |conn| {
112 LocalUserView::find_by_email_or_name(conn, &username_or_email)
117 Err(_e) => return Err(ApiError::err("couldnt_find_that_username_or_email").into()),
120 // Verify the password
121 let valid: bool = verify(
123 &local_user_view.local_user.password_encrypted,
127 return Err(ApiError::err("password_incorrect").into());
132 jwt: Claims::jwt(local_user_view.local_user.id, Settings::get().hostname())?,
137 #[async_trait::async_trait(?Send)]
138 impl Perform for Register {
139 type Response = LoginResponse;
143 context: &Data<LemmyContext>,
144 _websocket_id: Option<ConnectionId>,
145 ) -> Result<LoginResponse, LemmyError> {
146 let data: &Register = &self;
148 // Make sure site has open registration
149 if let Ok(site) = blocking(context.pool(), move |conn| Site::read_simple(conn)).await? {
150 if !site.open_registration {
151 return Err(ApiError::err("registration_closed").into());
155 password_length_check(&data.password)?;
157 // Make sure passwords match
158 if data.password != data.password_verify {
159 return Err(ApiError::err("passwords_dont_match").into());
162 // Check if there are admins. False if admins exist
163 let no_admins = blocking(context.pool(), move |conn| {
164 PersonViewSafe::admins(conn).map(|a| a.is_empty())
168 // If its not the admin, check the captcha
169 if !no_admins && Settings::get().captcha().enabled {
176 .unwrap_or_else(|| "".to_string()),
180 .unwrap_or_else(|| "".to_string()),
184 return Err(ApiError::err("captcha_incorrect").into());
188 check_slurs(&data.username)?;
190 let actor_keypair = generate_actor_keypair()?;
191 if !is_valid_username(&data.username) {
192 return Err(ApiError::err("invalid_username").into());
194 let actor_id = generate_apub_endpoint(EndpointType::Person, &data.username)?;
196 // We have to create both a person, and local_user
198 // Register the new person
199 let person_form = PersonForm {
200 name: data.username.to_owned(),
203 preferred_username: None,
208 actor_id: Some(actor_id.clone()),
211 private_key: Some(Some(actor_keypair.private_key)),
212 public_key: Some(Some(actor_keypair.public_key)),
213 last_refreshed_at: None,
214 inbox_url: Some(generate_inbox_url(&actor_id)?),
215 shared_inbox_url: Some(Some(generate_shared_inbox_url(&actor_id)?)),
219 let inserted_person = match blocking(context.pool(), move |conn| {
220 Person::create(conn, &person_form)
226 return Err(ApiError::err("user_already_exists").into());
230 // Create the local user
231 let local_user_form = LocalUserForm {
232 person_id: inserted_person.id,
233 email: Some(data.email.to_owned()),
234 matrix_user_id: None,
235 password_encrypted: data.password.to_owned(),
236 admin: Some(no_admins),
237 show_nsfw: Some(data.show_nsfw),
238 theme: Some("browser".into()),
239 default_sort_type: Some(SortType::Active as i16),
240 default_listing_type: Some(ListingType::Subscribed as i16),
241 lang: Some("browser".into()),
242 show_avatars: Some(true),
243 send_notifications_to_email: Some(false),
246 let inserted_local_user = match blocking(context.pool(), move |conn| {
247 LocalUser::register(conn, &local_user_form)
253 let err_type = if e.to_string()
254 == "duplicate key value violates unique constraint \"local_user_email_key\""
256 "email_already_exists"
258 "user_already_exists"
261 // If the local user creation errored, then delete that person
262 blocking(context.pool(), move |conn| {
263 Person::delete(&conn, inserted_person.id)
267 return Err(ApiError::err(err_type).into());
271 let main_community_keypair = generate_actor_keypair()?;
273 // Create the main community if it doesn't exist
275 match blocking(context.pool(), move |conn| Community::read(conn, 2)).await? {
278 let default_community_name = "main";
279 let actor_id = generate_apub_endpoint(EndpointType::Community, default_community_name)?;
280 let community_form = CommunityForm {
281 name: default_community_name.to_string(),
282 title: "The Default Community".to_string(),
283 description: Some("The Default Community".to_string()),
285 creator_id: inserted_person.id,
289 actor_id: Some(actor_id.to_owned()),
291 private_key: Some(main_community_keypair.private_key),
292 public_key: Some(main_community_keypair.public_key),
293 last_refreshed_at: None,
297 followers_url: Some(generate_followers_url(&actor_id)?),
298 inbox_url: Some(generate_inbox_url(&actor_id)?),
299 shared_inbox_url: Some(Some(generate_shared_inbox_url(&actor_id)?)),
301 blocking(context.pool(), move |conn| {
302 Community::create(conn, &community_form)
308 // Sign them up for main community no matter what
309 let community_follower_form = CommunityFollowerForm {
310 community_id: main_community.id,
311 person_id: inserted_person.id,
315 let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form);
316 if blocking(context.pool(), follow).await?.is_err() {
317 return Err(ApiError::err("community_follower_already_exists").into());
320 // If its an admin, add them as a mod and follower to main
322 let community_moderator_form = CommunityModeratorForm {
323 community_id: main_community.id,
324 person_id: inserted_person.id,
327 let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form);
328 if blocking(context.pool(), join).await?.is_err() {
329 return Err(ApiError::err("community_moderator_already_exists").into());
335 jwt: Claims::jwt(inserted_local_user.id, Settings::get().hostname())?,
340 #[async_trait::async_trait(?Send)]
341 impl Perform for GetCaptcha {
342 type Response = GetCaptchaResponse;
346 context: &Data<LemmyContext>,
347 _websocket_id: Option<ConnectionId>,
348 ) -> Result<Self::Response, LemmyError> {
349 let captcha_settings = Settings::get().captcha();
351 if !captcha_settings.enabled {
352 return Ok(GetCaptchaResponse { ok: None });
355 let captcha = match captcha_settings.difficulty.as_str() {
356 "easy" => gen(Difficulty::Easy),
357 "medium" => gen(Difficulty::Medium),
358 "hard" => gen(Difficulty::Hard),
359 _ => gen(Difficulty::Medium),
362 let answer = captcha.chars_as_string();
364 let png_byte_array = captcha.as_png().expect("failed to generate captcha");
366 let png = base64::encode(png_byte_array);
368 let uuid = uuid::Uuid::new_v4().to_string();
370 let wav = captcha_espeak_wav_base64(&answer).ok();
372 let captcha_item = CaptchaItem {
374 uuid: uuid.to_owned(),
375 expires: naive_now() + Duration::minutes(10), // expires in 10 minutes
378 // Stores the captcha item on the queue
379 context.chat_server().do_send(captcha_item);
381 Ok(GetCaptchaResponse {
382 ok: Some(CaptchaResponse { png, uuid, wav }),
387 #[async_trait::async_trait(?Send)]
388 impl Perform for SaveUserSettings {
389 type Response = LoginResponse;
393 context: &Data<LemmyContext>,
394 _websocket_id: Option<ConnectionId>,
395 ) -> Result<LoginResponse, LemmyError> {
396 let data: &SaveUserSettings = &self;
397 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
399 let avatar = diesel_option_overwrite_to_url(&data.avatar)?;
400 let banner = diesel_option_overwrite_to_url(&data.banner)?;
401 let email = diesel_option_overwrite(&data.email);
402 let bio = diesel_option_overwrite(&data.bio);
403 let preferred_username = diesel_option_overwrite(&data.preferred_username);
404 let matrix_user_id = diesel_option_overwrite(&data.matrix_user_id);
406 if let Some(Some(bio)) = &bio {
407 if bio.chars().count() > 300 {
408 return Err(ApiError::err("bio_length_overflow").into());
412 if let Some(Some(preferred_username)) = &preferred_username {
413 if !is_valid_preferred_username(preferred_username.trim()) {
414 return Err(ApiError::err("invalid_username").into());
418 let local_user_id = local_user_view.local_user.id;
419 let person_id = local_user_view.person.id;
420 let password_encrypted = match &data.new_password {
421 Some(new_password) => {
422 match &data.new_password_verify {
423 Some(new_password_verify) => {
424 password_length_check(&new_password)?;
426 // Make sure passwords match
427 if new_password != new_password_verify {
428 return Err(ApiError::err("passwords_dont_match").into());
431 // Check the old password
432 match &data.old_password {
433 Some(old_password) => {
435 verify(old_password, &local_user_view.local_user.password_encrypted)
438 return Err(ApiError::err("password_incorrect").into());
440 let new_password = new_password.to_owned();
441 let user = blocking(context.pool(), move |conn| {
442 LocalUser::update_password(conn, local_user_id, &new_password)
445 user.password_encrypted
447 None => return Err(ApiError::err("password_incorrect").into()),
450 None => return Err(ApiError::err("passwords_dont_match").into()),
453 None => local_user_view.local_user.password_encrypted,
456 let default_listing_type = data.default_listing_type;
457 let default_sort_type = data.default_sort_type;
459 let person_form = PersonForm {
460 name: local_user_view.person.name,
466 updated: Some(naive_now()),
474 last_refreshed_at: None,
475 shared_inbox_url: None,
478 let person_res = blocking(context.pool(), move |conn| {
479 Person::update(conn, person_id, &person_form)
482 let _updated_person: Person = match person_res {
485 return Err(ApiError::err("user_already_exists").into());
489 let local_user_form = LocalUserForm {
495 show_nsfw: data.show_nsfw,
496 theme: data.theme.to_owned(),
498 default_listing_type,
499 lang: data.lang.to_owned(),
500 show_avatars: data.show_avatars,
501 send_notifications_to_email: data.send_notifications_to_email,
504 let local_user_res = blocking(context.pool(), move |conn| {
505 LocalUser::update(conn, local_user_id, &local_user_form)
508 let updated_local_user = match local_user_res {
511 let err_type = if e.to_string()
512 == "duplicate key value violates unique constraint \"local_user_email_key\""
514 "email_already_exists"
516 "user_already_exists"
519 return Err(ApiError::err(err_type).into());
525 jwt: Claims::jwt(updated_local_user.id, Settings::get().hostname())?,
530 #[async_trait::async_trait(?Send)]
531 impl Perform for GetPersonDetails {
532 type Response = GetPersonDetailsResponse;
536 context: &Data<LemmyContext>,
537 _websocket_id: Option<ConnectionId>,
538 ) -> Result<GetPersonDetailsResponse, LemmyError> {
539 let data: &GetPersonDetails = &self;
540 let local_user_view = get_local_user_view_from_jwt_opt(&data.auth, context.pool()).await?;
542 let show_nsfw = match &local_user_view {
543 Some(uv) => uv.local_user.show_nsfw,
547 let sort = SortType::from_str(&data.sort)?;
552 .unwrap_or_else(|| "admin".to_string());
553 let person_details_id = match data.person_id {
556 let person = blocking(context.pool(), move |conn| {
557 Person::find_by_name(conn, &username)
562 Err(_e) => return Err(ApiError::err("couldnt_find_that_username_or_email").into()),
567 let person_id = local_user_view.map(|uv| uv.person.id);
569 // You don't need to return settings for the user, since this comes back with GetSite
571 let person_view = blocking(context.pool(), move |conn| {
572 PersonViewSafe::read(conn, person_details_id)
576 let page = data.page;
577 let limit = data.limit;
578 let saved_only = data.saved_only;
579 let community_id = data.community_id;
581 let (posts, comments) = blocking(context.pool(), move |conn| {
582 let mut posts_query = PostQueryBuilder::create(conn)
584 .show_nsfw(show_nsfw)
585 .saved_only(saved_only)
586 .community_id(community_id)
587 .my_person_id(person_id)
591 let mut comments_query = CommentQueryBuilder::create(conn)
592 .my_person_id(person_id)
594 .saved_only(saved_only)
598 // If its saved only, you don't care what creator it was
599 // Or, if its not saved, then you only want it for that specific creator
601 posts_query = posts_query.creator_id(person_details_id);
602 comments_query = comments_query.creator_id(person_details_id);
605 let posts = posts_query.list()?;
606 let comments = comments_query.list()?;
608 Ok((posts, comments)) as Result<_, LemmyError>
612 let mut follows = vec![];
613 if let Some(pid) = person_id {
614 if pid == person_details_id {
615 follows = blocking(context.pool(), move |conn| {
616 CommunityFollowerView::for_person(conn, person_details_id)
621 let moderates = blocking(context.pool(), move |conn| {
622 CommunityModeratorView::for_person(conn, person_details_id)
627 Ok(GetPersonDetailsResponse {
637 #[async_trait::async_trait(?Send)]
638 impl Perform for AddAdmin {
639 type Response = AddAdminResponse;
643 context: &Data<LemmyContext>,
644 websocket_id: Option<ConnectionId>,
645 ) -> Result<AddAdminResponse, LemmyError> {
646 let data: &AddAdmin = &self;
647 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
649 // Make sure user is an admin
650 is_admin(&local_user_view)?;
652 let added = data.added;
653 let added_local_user_id = data.local_user_id;
654 let added_admin = match blocking(context.pool(), move |conn| {
655 LocalUser::add_admin(conn, added_local_user_id, added)
661 return Err(ApiError::err("couldnt_update_user").into());
666 let form = ModAddForm {
667 mod_person_id: local_user_view.person.id,
668 other_person_id: added_admin.person_id,
669 removed: Some(!data.added),
672 blocking(context.pool(), move |conn| ModAdd::create(conn, &form)).await??;
674 let site_creator_id = blocking(context.pool(), move |conn| {
675 Site::read(conn, 1).map(|s| s.creator_id)
679 let mut admins = blocking(context.pool(), move |conn| PersonViewSafe::admins(conn)).await??;
680 let creator_index = admins
682 .position(|r| r.person.id == site_creator_id)
683 .context(location_info!())?;
684 let creator_person = admins.remove(creator_index);
685 admins.insert(0, creator_person);
687 let res = AddAdminResponse { admins };
689 context.chat_server().do_send(SendAllMessage {
690 op: UserOperation::AddAdmin,
691 response: res.clone(),
699 #[async_trait::async_trait(?Send)]
700 impl Perform for BanPerson {
701 type Response = BanPersonResponse;
705 context: &Data<LemmyContext>,
706 websocket_id: Option<ConnectionId>,
707 ) -> Result<BanPersonResponse, LemmyError> {
708 let data: &BanPerson = &self;
709 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
711 // Make sure user is an admin
712 is_admin(&local_user_view)?;
715 let banned_person_id = data.person_id;
716 let ban_person = move |conn: &'_ _| Person::ban_person(conn, banned_person_id, ban);
717 if blocking(context.pool(), ban_person).await?.is_err() {
718 return Err(ApiError::err("couldnt_update_user").into());
721 // Remove their data if that's desired
722 if data.remove_data {
724 blocking(context.pool(), move |conn: &'_ _| {
725 Post::update_removed_for_creator(conn, banned_person_id, None, true)
730 blocking(context.pool(), move |conn: &'_ _| {
731 Community::update_removed_for_creator(conn, banned_person_id, true)
736 blocking(context.pool(), move |conn: &'_ _| {
737 Comment::update_removed_for_creator(conn, banned_person_id, true)
743 let expires = match data.expires {
744 Some(time) => Some(naive_from_unix(time)),
748 let form = ModBanForm {
749 mod_person_id: local_user_view.person.id,
750 other_person_id: data.person_id,
751 reason: data.reason.to_owned(),
752 banned: Some(data.ban),
756 blocking(context.pool(), move |conn| ModBan::create(conn, &form)).await??;
758 let person_id = data.person_id;
759 let person_view = blocking(context.pool(), move |conn| {
760 PersonViewSafe::read(conn, person_id)
764 let res = BanPersonResponse {
769 context.chat_server().do_send(SendAllMessage {
770 op: UserOperation::BanPerson,
771 response: res.clone(),
779 #[async_trait::async_trait(?Send)]
780 impl Perform for GetReplies {
781 type Response = GetRepliesResponse;
785 context: &Data<LemmyContext>,
786 _websocket_id: Option<ConnectionId>,
787 ) -> Result<GetRepliesResponse, LemmyError> {
788 let data: &GetReplies = &self;
789 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
791 let sort = SortType::from_str(&data.sort)?;
793 let page = data.page;
794 let limit = data.limit;
795 let unread_only = data.unread_only;
796 let person_id = local_user_view.person.id;
797 let replies = blocking(context.pool(), move |conn| {
798 CommentQueryBuilder::create(conn)
800 .unread_only(unread_only)
801 .recipient_id(person_id)
802 .my_person_id(person_id)
809 Ok(GetRepliesResponse { replies })
813 #[async_trait::async_trait(?Send)]
814 impl Perform for GetPersonMentions {
815 type Response = GetPersonMentionsResponse;
819 context: &Data<LemmyContext>,
820 _websocket_id: Option<ConnectionId>,
821 ) -> Result<GetPersonMentionsResponse, LemmyError> {
822 let data: &GetPersonMentions = &self;
823 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
825 let sort = SortType::from_str(&data.sort)?;
827 let page = data.page;
828 let limit = data.limit;
829 let unread_only = data.unread_only;
830 let person_id = local_user_view.person.id;
831 let mentions = blocking(context.pool(), move |conn| {
832 PersonMentionQueryBuilder::create(conn)
833 .recipient_id(person_id)
834 .my_person_id(person_id)
836 .unread_only(unread_only)
843 Ok(GetPersonMentionsResponse { mentions })
847 #[async_trait::async_trait(?Send)]
848 impl Perform for MarkPersonMentionAsRead {
849 type Response = PersonMentionResponse;
853 context: &Data<LemmyContext>,
854 _websocket_id: Option<ConnectionId>,
855 ) -> Result<PersonMentionResponse, LemmyError> {
856 let data: &MarkPersonMentionAsRead = &self;
857 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
859 let person_mention_id = data.person_mention_id;
860 let read_person_mention = blocking(context.pool(), move |conn| {
861 PersonMention::read(conn, person_mention_id)
865 if local_user_view.person.id != read_person_mention.recipient_id {
866 return Err(ApiError::err("couldnt_update_comment").into());
869 let person_mention_id = read_person_mention.id;
870 let read = data.read;
872 move |conn: &'_ _| PersonMention::update_read(conn, person_mention_id, read);
873 if blocking(context.pool(), update_mention).await?.is_err() {
874 return Err(ApiError::err("couldnt_update_comment").into());
877 let person_mention_id = read_person_mention.id;
878 let person_id = local_user_view.person.id;
879 let person_mention_view = blocking(context.pool(), move |conn| {
880 PersonMentionView::read(conn, person_mention_id, Some(person_id))
884 Ok(PersonMentionResponse {
890 #[async_trait::async_trait(?Send)]
891 impl Perform for MarkAllAsRead {
892 type Response = GetRepliesResponse;
896 context: &Data<LemmyContext>,
897 _websocket_id: Option<ConnectionId>,
898 ) -> Result<GetRepliesResponse, LemmyError> {
899 let data: &MarkAllAsRead = &self;
900 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
902 let person_id = local_user_view.person.id;
903 let replies = blocking(context.pool(), move |conn| {
904 CommentQueryBuilder::create(conn)
905 .my_person_id(person_id)
906 .recipient_id(person_id)
914 // TODO: this should probably be a bulk operation
915 // Not easy to do as a bulk operation,
916 // because recipient_id isn't in the comment table
917 for comment_view in &replies {
918 let reply_id = comment_view.comment.id;
919 let mark_as_read = move |conn: &'_ _| Comment::update_read(conn, reply_id, true);
920 if blocking(context.pool(), mark_as_read).await?.is_err() {
921 return Err(ApiError::err("couldnt_update_comment").into());
925 // Mark all user mentions as read
926 let update_person_mentions =
927 move |conn: &'_ _| PersonMention::mark_all_as_read(conn, person_id);
928 if blocking(context.pool(), update_person_mentions)
932 return Err(ApiError::err("couldnt_update_comment").into());
935 // Mark all private_messages as read
936 let update_pm = move |conn: &'_ _| PrivateMessage::mark_all_as_read(conn, person_id);
937 if blocking(context.pool(), update_pm).await?.is_err() {
938 return Err(ApiError::err("couldnt_update_private_message").into());
941 Ok(GetRepliesResponse { replies: vec![] })
945 #[async_trait::async_trait(?Send)]
946 impl Perform for DeleteAccount {
947 type Response = LoginResponse;
951 context: &Data<LemmyContext>,
952 _websocket_id: Option<ConnectionId>,
953 ) -> Result<LoginResponse, LemmyError> {
954 let data: &DeleteAccount = &self;
955 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
957 // Verify the password
958 let valid: bool = verify(
960 &local_user_view.local_user.password_encrypted,
964 return Err(ApiError::err("password_incorrect").into());
968 let person_id = local_user_view.person.id;
969 let permadelete = move |conn: &'_ _| Comment::permadelete_for_creator(conn, person_id);
970 if blocking(context.pool(), permadelete).await?.is_err() {
971 return Err(ApiError::err("couldnt_update_comment").into());
975 let permadelete = move |conn: &'_ _| Post::permadelete_for_creator(conn, person_id);
976 if blocking(context.pool(), permadelete).await?.is_err() {
977 return Err(ApiError::err("couldnt_update_post").into());
980 blocking(context.pool(), move |conn| {
981 Person::delete_account(conn, person_id)
986 jwt: data.auth.to_owned(),
991 #[async_trait::async_trait(?Send)]
992 impl Perform for PasswordReset {
993 type Response = PasswordResetResponse;
997 context: &Data<LemmyContext>,
998 _websocket_id: Option<ConnectionId>,
999 ) -> Result<PasswordResetResponse, LemmyError> {
1000 let data: &PasswordReset = &self;
1003 let email = data.email.clone();
1004 let local_user_view = match blocking(context.pool(), move |conn| {
1005 LocalUserView::find_by_email(conn, &email)
1010 Err(_e) => return Err(ApiError::err("couldnt_find_that_username_or_email").into()),
1013 // Generate a random token
1014 let token = generate_random_string();
1017 let token2 = token.clone();
1018 let local_user_id = local_user_view.local_user.id;
1019 blocking(context.pool(), move |conn| {
1020 PasswordResetRequest::create_token(conn, local_user_id, &token2)
1024 // Email the pure token to the user.
1025 // TODO no i18n support here.
1026 let email = &local_user_view.local_user.email.expect("email");
1027 let subject = &format!("Password reset for {}", local_user_view.person.name);
1028 let hostname = &Settings::get().get_protocol_and_hostname();
1029 let html = &format!("<h1>Password Reset Request for {}</h1><br><a href={}/password_change/{}>Click here to reset your password</a>", local_user_view.person.name, hostname, &token);
1030 match send_email(subject, email, &local_user_view.person.name, html) {
1032 Err(_e) => return Err(ApiError::err(&_e).into()),
1035 Ok(PasswordResetResponse {})
1039 #[async_trait::async_trait(?Send)]
1040 impl Perform for PasswordChange {
1041 type Response = LoginResponse;
1045 context: &Data<LemmyContext>,
1046 _websocket_id: Option<ConnectionId>,
1047 ) -> Result<LoginResponse, LemmyError> {
1048 let data: &PasswordChange = &self;
1050 // Fetch the user_id from the token
1051 let token = data.token.clone();
1052 let local_user_id = blocking(context.pool(), move |conn| {
1053 PasswordResetRequest::read_from_token(conn, &token).map(|p| p.local_user_id)
1057 password_length_check(&data.password)?;
1059 // Make sure passwords match
1060 if data.password != data.password_verify {
1061 return Err(ApiError::err("passwords_dont_match").into());
1064 // Update the user with the new password
1065 let password = data.password.clone();
1066 let updated_local_user = match blocking(context.pool(), move |conn| {
1067 LocalUser::update_password(conn, local_user_id, &password)
1072 Err(_e) => return Err(ApiError::err("couldnt_update_user").into()),
1077 jwt: Claims::jwt(updated_local_user.id, Settings::get().hostname())?,
1082 #[async_trait::async_trait(?Send)]
1083 impl Perform for CreatePrivateMessage {
1084 type Response = PrivateMessageResponse;
1088 context: &Data<LemmyContext>,
1089 websocket_id: Option<ConnectionId>,
1090 ) -> Result<PrivateMessageResponse, LemmyError> {
1091 let data: &CreatePrivateMessage = &self;
1092 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
1094 let content_slurs_removed = remove_slurs(&data.content.to_owned());
1096 let private_message_form = PrivateMessageForm {
1097 content: content_slurs_removed.to_owned(),
1098 creator_id: local_user_view.person.id,
1099 recipient_id: data.recipient_id,
1108 let inserted_private_message = match blocking(context.pool(), move |conn| {
1109 PrivateMessage::create(conn, &private_message_form)
1113 Ok(private_message) => private_message,
1115 return Err(ApiError::err("couldnt_create_private_message").into());
1119 let inserted_private_message_id = inserted_private_message.id;
1120 let updated_private_message = match blocking(
1122 move |conn| -> Result<PrivateMessage, LemmyError> {
1123 let apub_id = generate_apub_endpoint(
1124 EndpointType::PrivateMessage,
1125 &inserted_private_message_id.to_string(),
1127 Ok(PrivateMessage::update_ap_id(
1129 inserted_private_message_id,
1136 Ok(private_message) => private_message,
1137 Err(_e) => return Err(ApiError::err("couldnt_create_private_message").into()),
1140 updated_private_message
1141 .send_create(&local_user_view.person, context)
1144 // Send notifications to the recipient
1145 let recipient_id = data.recipient_id;
1146 let recipient = blocking(context.pool(), move |conn| {
1147 LocalUserView::read_person(conn, recipient_id)
1150 if recipient.local_user.send_notifications_to_email {
1153 "Private Message from",
1155 &content_slurs_removed,
1159 let private_message_view = blocking(context.pool(), move |conn| {
1160 PrivateMessageView::read(conn, inserted_private_message.id)
1164 let res = PrivateMessageResponse {
1165 private_message_view,
1168 context.chat_server().do_send(SendUserRoomMessage {
1169 op: UserOperation::CreatePrivateMessage,
1170 response: res.clone(),
1179 #[async_trait::async_trait(?Send)]
1180 impl Perform for EditPrivateMessage {
1181 type Response = PrivateMessageResponse;
1185 context: &Data<LemmyContext>,
1186 websocket_id: Option<ConnectionId>,
1187 ) -> Result<PrivateMessageResponse, LemmyError> {
1188 let data: &EditPrivateMessage = &self;
1189 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
1191 // Checking permissions
1192 let private_message_id = data.private_message_id;
1193 let orig_private_message = blocking(context.pool(), move |conn| {
1194 PrivateMessage::read(conn, private_message_id)
1197 if local_user_view.person.id != orig_private_message.creator_id {
1198 return Err(ApiError::err("no_private_message_edit_allowed").into());
1202 let content_slurs_removed = remove_slurs(&data.content);
1203 let private_message_id = data.private_message_id;
1204 let updated_private_message = match blocking(context.pool(), move |conn| {
1205 PrivateMessage::update_content(conn, private_message_id, &content_slurs_removed)
1209 Ok(private_message) => private_message,
1210 Err(_e) => return Err(ApiError::err("couldnt_update_private_message").into()),
1213 // Send the apub update
1214 updated_private_message
1215 .send_update(&local_user_view.person, context)
1218 let private_message_id = data.private_message_id;
1219 let private_message_view = blocking(context.pool(), move |conn| {
1220 PrivateMessageView::read(conn, private_message_id)
1223 let recipient_id = private_message_view.recipient.id;
1225 let res = PrivateMessageResponse {
1226 private_message_view,
1229 context.chat_server().do_send(SendUserRoomMessage {
1230 op: UserOperation::EditPrivateMessage,
1231 response: res.clone(),
1240 #[async_trait::async_trait(?Send)]
1241 impl Perform for DeletePrivateMessage {
1242 type Response = PrivateMessageResponse;
1246 context: &Data<LemmyContext>,
1247 websocket_id: Option<ConnectionId>,
1248 ) -> Result<PrivateMessageResponse, LemmyError> {
1249 let data: &DeletePrivateMessage = &self;
1250 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
1252 // Checking permissions
1253 let private_message_id = data.private_message_id;
1254 let orig_private_message = blocking(context.pool(), move |conn| {
1255 PrivateMessage::read(conn, private_message_id)
1258 if local_user_view.person.id != orig_private_message.creator_id {
1259 return Err(ApiError::err("no_private_message_edit_allowed").into());
1263 let private_message_id = data.private_message_id;
1264 let deleted = data.deleted;
1265 let updated_private_message = match blocking(context.pool(), move |conn| {
1266 PrivateMessage::update_deleted(conn, private_message_id, deleted)
1270 Ok(private_message) => private_message,
1271 Err(_e) => return Err(ApiError::err("couldnt_update_private_message").into()),
1274 // Send the apub update
1276 updated_private_message
1277 .send_delete(&local_user_view.person, context)
1280 updated_private_message
1281 .send_undo_delete(&local_user_view.person, context)
1285 let private_message_id = data.private_message_id;
1286 let private_message_view = blocking(context.pool(), move |conn| {
1287 PrivateMessageView::read(conn, private_message_id)
1290 let recipient_id = private_message_view.recipient.id;
1292 let res = PrivateMessageResponse {
1293 private_message_view,
1296 context.chat_server().do_send(SendUserRoomMessage {
1297 op: UserOperation::DeletePrivateMessage,
1298 response: res.clone(),
1307 #[async_trait::async_trait(?Send)]
1308 impl Perform for MarkPrivateMessageAsRead {
1309 type Response = PrivateMessageResponse;
1313 context: &Data<LemmyContext>,
1314 websocket_id: Option<ConnectionId>,
1315 ) -> Result<PrivateMessageResponse, LemmyError> {
1316 let data: &MarkPrivateMessageAsRead = &self;
1317 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
1319 // Checking permissions
1320 let private_message_id = data.private_message_id;
1321 let orig_private_message = blocking(context.pool(), move |conn| {
1322 PrivateMessage::read(conn, private_message_id)
1325 if local_user_view.person.id != orig_private_message.recipient_id {
1326 return Err(ApiError::err("couldnt_update_private_message").into());
1330 let private_message_id = data.private_message_id;
1331 let read = data.read;
1332 match blocking(context.pool(), move |conn| {
1333 PrivateMessage::update_read(conn, private_message_id, read)
1337 Ok(private_message) => private_message,
1338 Err(_e) => return Err(ApiError::err("couldnt_update_private_message").into()),
1341 // No need to send an apub update
1343 let private_message_id = data.private_message_id;
1344 let private_message_view = blocking(context.pool(), move |conn| {
1345 PrivateMessageView::read(conn, private_message_id)
1348 let recipient_id = private_message_view.recipient.id;
1350 let res = PrivateMessageResponse {
1351 private_message_view,
1354 context.chat_server().do_send(SendUserRoomMessage {
1355 op: UserOperation::MarkPrivateMessageAsRead,
1356 response: res.clone(),
1365 #[async_trait::async_trait(?Send)]
1366 impl Perform for GetPrivateMessages {
1367 type Response = PrivateMessagesResponse;
1371 context: &Data<LemmyContext>,
1372 _websocket_id: Option<ConnectionId>,
1373 ) -> Result<PrivateMessagesResponse, LemmyError> {
1374 let data: &GetPrivateMessages = &self;
1375 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
1376 let person_id = local_user_view.person.id;
1378 let page = data.page;
1379 let limit = data.limit;
1380 let unread_only = data.unread_only;
1381 let messages = blocking(context.pool(), move |conn| {
1382 PrivateMessageQueryBuilder::create(&conn, person_id)
1385 .unread_only(unread_only)
1390 Ok(PrivateMessagesResponse {
1391 private_messages: messages,
1396 #[async_trait::async_trait(?Send)]
1397 impl Perform for GetReportCount {
1398 type Response = GetReportCountResponse;
1402 context: &Data<LemmyContext>,
1403 websocket_id: Option<ConnectionId>,
1404 ) -> Result<GetReportCountResponse, LemmyError> {
1405 let data: &GetReportCount = &self;
1406 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
1408 let person_id = local_user_view.person.id;
1409 let community_id = data.community;
1411 collect_moderated_communities(person_id, community_id, context.pool()).await?;
1414 if community_ids.is_empty() {
1415 GetReportCountResponse {
1421 let ids = community_ids.clone();
1422 let comment_reports = blocking(context.pool(), move |conn| {
1423 CommentReportView::get_report_count(conn, &ids)
1427 let ids = community_ids.clone();
1428 let post_reports = blocking(context.pool(), move |conn| {
1429 PostReportView::get_report_count(conn, &ids)
1433 GetReportCountResponse {
1434 community: data.community,
1441 context.chat_server().do_send(SendUserRoomMessage {
1442 op: UserOperation::GetReportCount,
1443 response: res.clone(),
1444 recipient_id: local_user_view.person.id,