8 use crate::site::FederatedInstances;
9 use diesel::PgConnection;
10 use lemmy_db_queries::{
12 community::{CommunityModerator_, Community_},
13 person_block::PersonBlock_,
14 secret::SecretSingleton,
21 use lemmy_db_schema::{
24 community::{Community, CommunityModerator},
26 person_block::PersonBlock,
27 person_mention::{PersonMention, PersonMentionForm},
28 post::{Post, PostRead, PostReadForm},
37 use lemmy_db_views::local_user_view::{LocalUserSettingsView, LocalUserView};
38 use lemmy_db_views_actor::{
39 community_person_ban_view::CommunityPersonBanView,
40 community_view::CommunityView,
45 settings::structs::Settings,
53 pub async fn blocking<F, T>(pool: &DbPool, f: F) -> Result<T, LemmyError>
55 F: FnOnce(&diesel::PgConnection) -> T + Send + 'static,
58 let pool = pool.clone();
59 let res = actix_web::web::block(move || {
60 let conn = pool.get()?;
62 Ok(res) as Result<T, LemmyError>
69 pub async fn send_local_notifs(
70 mentions: Vec<MentionData>,
76 ) -> Result<Vec<LocalUserId>, LemmyError> {
77 let ids = blocking(pool, move |conn| {
78 do_send_local_notifs(conn, &mentions, &comment, &person, &post, do_send_email)
85 fn do_send_local_notifs(
87 mentions: &[MentionData],
92 ) -> Vec<LocalUserId> {
93 let mut recipient_ids = Vec::new();
95 // Send the local mentions
96 for mention in mentions
98 .filter(|m| m.is_local() && m.name.ne(&person.name))
99 .collect::<Vec<&MentionData>>()
101 if let Ok(mention_user_view) = LocalUserView::read_from_name(conn, &mention.name) {
103 // At some point, make it so you can't tag the parent creator either
104 // This can cause two notifications, one for reply and the other for mention
105 recipient_ids.push(mention_user_view.local_user.id);
107 let user_mention_form = PersonMentionForm {
108 recipient_id: mention_user_view.person.id,
109 comment_id: comment.id,
113 // Allow this to fail softly, since comment edits might re-update or replace it
114 // Let the uniqueness handle this fail
115 PersonMention::create(conn, &user_mention_form).ok();
117 // Send an email to those local users that have notifications on
129 // Send notifs to the parent commenter / poster
130 match comment.parent_id {
132 if let Ok(parent_comment) = Comment::read(conn, parent_id) {
133 // Don't send a notif to yourself
134 if parent_comment.creator_id != person.id {
135 // Get the parent commenter local_user
136 if let Ok(parent_user_view) = LocalUserView::read_person(conn, parent_comment.creator_id)
138 recipient_ids.push(parent_user_view.local_user.id);
154 if post.creator_id != person.id {
155 if let Ok(parent_user_view) = LocalUserView::read_person(conn, post.creator_id) {
156 recipient_ids.push(parent_user_view.local_user.id);
173 pub fn send_email_to_user(
174 local_user_view: &LocalUserView,
177 comment_content: &str,
179 if local_user_view.person.banned || !local_user_view.local_user.send_notifications_to_email {
183 if let Some(user_email) = &local_user_view.local_user.email {
184 let subject = &format!(
187 Settings::get().hostname,
188 local_user_view.person.name,
191 "<h1>{}</h1><br><div>{} - {}</div><br><a href={}/inbox>inbox</a>",
193 local_user_view.person.name,
195 Settings::get().get_protocol_and_hostname()
197 match send_email(subject, user_email, &local_user_view.person.name, html) {
199 Err(e) => error!("{}", e),
204 pub async fn is_mod_or_admin(
207 community_id: CommunityId,
208 ) -> Result<(), LemmyError> {
209 let is_mod_or_admin = blocking(pool, move |conn| {
210 CommunityView::is_mod_or_admin(conn, person_id, community_id)
213 if !is_mod_or_admin {
214 return Err(ApiError::err("not_a_mod_or_admin").into());
219 pub fn is_admin(local_user_view: &LocalUserView) -> Result<(), LemmyError> {
220 if !local_user_view.person.admin {
221 return Err(ApiError::err("not_an_admin").into());
226 pub async fn get_post(post_id: PostId, pool: &DbPool) -> Result<Post, LemmyError> {
227 blocking(pool, move |conn| Post::read(conn, post_id))
229 .map_err(|_| ApiError::err("couldnt_find_post").into())
232 pub async fn mark_post_as_read(
236 ) -> Result<PostRead, LemmyError> {
237 let post_read_form = PostReadForm { post_id, person_id };
239 blocking(pool, move |conn| {
240 PostRead::mark_as_read(conn, &post_read_form)
243 .map_err(|_| ApiError::err("couldnt_mark_post_as_read").into())
246 pub async fn get_local_user_view_from_jwt(
249 ) -> Result<LocalUserView, LemmyError> {
250 let jwt_secret = Secret::get().jwt_secret;
251 let claims = Claims::decode(jwt, &jwt_secret)
252 .map_err(|_| ApiError::err("not_logged_in"))?
254 let local_user_id = LocalUserId(claims.sub);
255 let local_user_view =
256 blocking(pool, move |conn| LocalUserView::read(conn, local_user_id)).await??;
257 // Check for a site ban
258 if local_user_view.person.banned {
259 return Err(ApiError::err("site_ban").into());
262 // Check for user deletion
263 if local_user_view.person.deleted {
264 return Err(ApiError::err("deleted").into());
267 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
272 /// Checks if user's token was issued before user's password reset.
273 pub fn check_validator_time(
274 validator_time: &chrono::NaiveDateTime,
276 ) -> Result<(), LemmyError> {
277 let user_validation_time = validator_time.timestamp();
278 if user_validation_time > claims.iat {
279 Err(ApiError::err("not_logged_in").into())
285 pub async fn get_local_user_view_from_jwt_opt(
286 jwt: &Option<String>,
288 ) -> Result<Option<LocalUserView>, LemmyError> {
290 Some(jwt) => Ok(Some(get_local_user_view_from_jwt(jwt, pool).await?)),
295 pub async fn get_local_user_settings_view_from_jwt(
298 ) -> Result<LocalUserSettingsView, LemmyError> {
299 let jwt_secret = Secret::get().jwt_secret;
300 let claims = Claims::decode(jwt, &jwt_secret)
301 .map_err(|_| ApiError::err("not_logged_in"))?
303 let local_user_id = LocalUserId(claims.sub);
304 let local_user_view = blocking(pool, move |conn| {
305 LocalUserSettingsView::read(conn, local_user_id)
308 // Check for a site ban
309 if local_user_view.person.banned {
310 return Err(ApiError::err("site_ban").into());
313 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
318 pub async fn get_local_user_settings_view_from_jwt_opt(
319 jwt: &Option<String>,
321 ) -> Result<Option<LocalUserSettingsView>, LemmyError> {
323 Some(jwt) => Ok(Some(
324 get_local_user_settings_view_from_jwt(jwt, pool).await?,
330 pub async fn check_community_ban(
332 community_id: CommunityId,
334 ) -> Result<(), LemmyError> {
336 move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
337 if blocking(pool, is_banned).await? {
338 Err(ApiError::err("community_ban").into())
344 pub async fn check_person_block(
346 potential_blocker_id: PersonId,
348 ) -> Result<(), LemmyError> {
349 let is_blocked = move |conn: &'_ _| PersonBlock::read(conn, potential_blocker_id, my_id).is_ok();
350 if blocking(pool, is_blocked).await? {
351 Err(ApiError::err("person_block").into())
357 pub async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> {
359 let site = blocking(pool, move |conn| Site::read_simple(conn)).await??;
360 if !site.enable_downvotes {
361 return Err(ApiError::err("downvotes_disabled").into());
367 /// Returns a list of communities that the user moderates
368 /// or if a community_id is supplied validates the user is a moderator
369 /// of that community and returns the community id in a vec
371 /// * `person_id` - the person id of the moderator
372 /// * `community_id` - optional community id to check for moderator privileges
373 /// * `pool` - the diesel db pool
374 pub async fn collect_moderated_communities(
376 community_id: Option<CommunityId>,
378 ) -> Result<Vec<CommunityId>, LemmyError> {
379 if let Some(community_id) = community_id {
380 // if the user provides a community_id, just check for mod/admin privileges
381 is_mod_or_admin(pool, person_id, community_id).await?;
382 Ok(vec![community_id])
384 let ids = blocking(pool, move |conn: &'_ _| {
385 CommunityModerator::get_person_moderated_communities(conn, person_id)
392 pub async fn build_federated_instances(
394 ) -> Result<Option<FederatedInstances>, LemmyError> {
395 if Settings::get().federation.enabled {
396 let distinct_communities = blocking(pool, move |conn| {
397 Community::distinct_federated_communities(conn)
401 let allowed = Settings::get().federation.allowed_instances;
402 let blocked = Settings::get().federation.blocked_instances;
404 let mut linked = distinct_communities
406 .map(|actor_id| Ok(Url::parse(actor_id)?.host_str().unwrap_or("").to_string()))
407 .collect::<Result<Vec<String>, LemmyError>>()?;
409 if let Some(allowed) = allowed.as_ref() {
410 linked.extend_from_slice(allowed);
413 if let Some(blocked) = blocked.as_ref() {
414 linked.retain(|a| !blocked.contains(a) && !a.eq(&Settings::get().hostname));
417 // Sort and remove dupes
418 linked.sort_unstable();
421 Ok(Some(FederatedInstances {
431 /// Checks the password length
432 pub fn password_length_check(pass: &str) -> Result<(), LemmyError> {
433 if !(10..=60).contains(&pass.len()) {
434 Err(ApiError::err("invalid_password").into())
440 /// Checks the site description length
441 pub fn site_description_length_check(description: &str) -> Result<(), LemmyError> {
442 if description.len() > 150 {
443 Err(ApiError::err("site_description_length_overflow").into())