]> Untitled Git - lemmy.git/blob - crates/api_crud/src/site/update.rs
Fix limit_languages to operate on correct instance (fixes #2496) (#2518)
[lemmy.git] / crates / api_crud / src / site / update.rs
1 use crate::PerformCrud;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   site::{EditSite, SiteResponse},
5   utils::{
6     blocking,
7     get_local_user_view_from_jwt,
8     is_admin,
9     local_site_to_slur_regex,
10     site_description_length_check,
11   },
12 };
13 use lemmy_db_schema::{
14   source::{
15     actor_language::SiteLanguage,
16     federation_allowlist::FederationAllowList,
17     federation_blocklist::FederationBlockList,
18     local_site::{LocalSite, LocalSiteUpdateForm},
19     local_site_rate_limit::{LocalSiteRateLimit, LocalSiteRateLimitUpdateForm},
20     local_user::LocalUser,
21     site::{Site, SiteUpdateForm},
22   },
23   traits::Crud,
24   utils::{diesel_option_overwrite, diesel_option_overwrite_to_url, naive_now},
25   ListingType,
26 };
27 use lemmy_db_views::structs::SiteView;
28 use lemmy_utils::{
29   error::LemmyError,
30   utils::{check_application_question, check_slurs_opt},
31   ConnectionId,
32 };
33 use lemmy_websocket::{messages::SendAllMessage, LemmyContext, UserOperationCrud};
34 use std::str::FromStr;
35
36 #[async_trait::async_trait(?Send)]
37 impl PerformCrud for EditSite {
38   type Response = SiteResponse;
39
40   #[tracing::instrument(skip(context, websocket_id))]
41   async fn perform(
42     &self,
43     context: &Data<LemmyContext>,
44     websocket_id: Option<ConnectionId>,
45   ) -> Result<SiteResponse, LemmyError> {
46     let data: &EditSite = self;
47     let local_user_view =
48       get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
49     let local_site = blocking(context.pool(), LocalSite::read).await??;
50
51     // Make sure user is an admin
52     is_admin(&local_user_view)?;
53
54     let slur_regex = local_site_to_slur_regex(&local_site);
55
56     check_slurs_opt(&data.name, &slur_regex)?;
57     check_slurs_opt(&data.description, &slur_regex)?;
58
59     if let Some(desc) = &data.description {
60       site_description_length_check(desc)?;
61     }
62
63     let application_question = diesel_option_overwrite(&data.application_question);
64     check_application_question(&application_question, &data.require_application)?;
65
66     if let Some(default_post_listing_type) = &data.default_post_listing_type {
67       // only allow all or local as default listing types
68       let val = ListingType::from_str(default_post_listing_type);
69       if val != Ok(ListingType::All) && val != Ok(ListingType::Local) {
70         return Err(LemmyError::from_message(
71           "invalid_default_post_listing_type",
72         ));
73       }
74     }
75
76     let site_id = local_site.site_id;
77     if let Some(discussion_languages) = data.discussion_languages.clone() {
78       blocking(context.pool(), move |conn| {
79         let site = Site::read(conn, site_id)?;
80         SiteLanguage::update(conn, discussion_languages, &site)
81       })
82       .await??;
83     }
84
85     let name = data.name.to_owned();
86     let site_form = SiteUpdateForm::builder()
87       .name(name)
88       .sidebar(diesel_option_overwrite(&data.sidebar))
89       .description(diesel_option_overwrite(&data.description))
90       .icon(diesel_option_overwrite_to_url(&data.icon)?)
91       .banner(diesel_option_overwrite_to_url(&data.banner)?)
92       .updated(Some(Some(naive_now())))
93       .build();
94
95     blocking(context.pool(), move |conn| {
96       Site::update(conn, local_site.site_id, &site_form)
97     })
98     .await
99     // Ignore errors for all these, so as to not throw errors if no update occurs
100     // Diesel will throw an error for empty update forms
101     .ok();
102
103     let local_site_form = LocalSiteUpdateForm::builder()
104       .enable_downvotes(data.enable_downvotes)
105       .open_registration(data.open_registration)
106       .enable_nsfw(data.enable_nsfw)
107       .community_creation_admin_only(data.community_creation_admin_only)
108       .require_email_verification(data.require_email_verification)
109       .require_application(data.require_application)
110       .application_question(application_question)
111       .private_instance(data.private_instance)
112       .default_theme(data.default_theme.clone())
113       .default_post_listing_type(data.default_post_listing_type.clone())
114       .legal_information(diesel_option_overwrite(&data.legal_information))
115       .application_email_admins(data.application_email_admins)
116       .hide_modlog_mod_names(data.hide_modlog_mod_names)
117       .updated(Some(Some(naive_now())))
118       .slur_filter_regex(diesel_option_overwrite(&data.slur_filter_regex))
119       .actor_name_max_length(data.actor_name_max_length)
120       .federation_enabled(data.federation_enabled)
121       .federation_debug(data.federation_debug)
122       .federation_strict_allowlist(data.federation_strict_allowlist)
123       .federation_http_fetch_retry_limit(data.federation_http_fetch_retry_limit)
124       .federation_worker_count(data.federation_worker_count)
125       .captcha_enabled(data.captcha_enabled)
126       .captcha_difficulty(data.captcha_difficulty.to_owned())
127       .build();
128
129     let update_local_site = blocking(context.pool(), move |conn| {
130       LocalSite::update(conn, &local_site_form)
131     })
132     .await
133     .ok();
134
135     let local_site_rate_limit_form = LocalSiteRateLimitUpdateForm::builder()
136       .message(data.rate_limit_message)
137       .message_per_second(data.rate_limit_message_per_second)
138       .post(data.rate_limit_post)
139       .post_per_second(data.rate_limit_post_per_second)
140       .register(data.rate_limit_register)
141       .register_per_second(data.rate_limit_register_per_second)
142       .image(data.rate_limit_image)
143       .image_per_second(data.rate_limit_image_per_second)
144       .comment(data.rate_limit_comment)
145       .comment_per_second(data.rate_limit_comment_per_second)
146       .search(data.rate_limit_search)
147       .search_per_second(data.rate_limit_search_per_second)
148       .build();
149
150     blocking(context.pool(), move |conn| {
151       LocalSiteRateLimit::update(conn, &local_site_rate_limit_form)
152     })
153     .await
154     .ok();
155
156     // Replace the blocked and allowed instances
157     let allowed = data.allowed_instances.to_owned();
158     blocking(context.pool(), move |conn| {
159       FederationAllowList::replace(conn, allowed)
160     })
161     .await??;
162     let blocked = data.blocked_instances.to_owned();
163     blocking(context.pool(), move |conn| {
164       FederationBlockList::replace(conn, blocked)
165     })
166     .await??;
167
168     // TODO can't think of a better way to do this.
169     // If the server suddenly requires email verification, or required applications, no old users
170     // will be able to log in. It really only wants this to be a requirement for NEW signups.
171     // So if it was set from false, to true, you need to update all current users columns to be verified.
172
173     let new_require_application = update_local_site
174       .as_ref()
175       .map(|ols| {
176         ols
177           .as_ref()
178           .map(|ls| ls.require_application)
179           .unwrap_or(false)
180       })
181       .unwrap_or(false);
182     if !local_site.require_application && new_require_application {
183       blocking(context.pool(), move |conn| {
184         LocalUser::set_all_users_registration_applications_accepted(conn)
185       })
186       .await?
187       .map_err(|e| LemmyError::from_error_message(e, "couldnt_set_all_registrations_accepted"))?;
188     }
189
190     let new_require_email_verification = update_local_site
191       .as_ref()
192       .map(|ols| {
193         ols
194           .as_ref()
195           .map(|ls| ls.require_email_verification)
196           .unwrap_or(false)
197       })
198       .unwrap_or(false);
199     if !local_site.require_email_verification && new_require_email_verification {
200       blocking(context.pool(), move |conn| {
201         LocalUser::set_all_users_email_verified(conn)
202       })
203       .await?
204       .map_err(|e| LemmyError::from_error_message(e, "couldnt_set_all_email_verified"))?;
205     }
206
207     let site_view = blocking(context.pool(), SiteView::read_local).await??;
208
209     let res = SiteResponse { site_view };
210
211     context.chat_server().do_send(SendAllMessage {
212       op: UserOperationCrud::EditSite,
213       response: res.clone(),
214       websocket_id,
215     });
216
217     Ok(res)
218   }
219 }