8 use crate::site::FederatedInstances;
9 use diesel::PgConnection;
10 use lemmy_db_queries::{
12 community::{CommunityModerator_, Community_},
13 person_block::PersonBlock_,
20 use lemmy_db_schema::{
23 community::{Community, CommunityModerator},
25 person_block::PersonBlock,
26 person_mention::{PersonMention, PersonMentionForm},
27 post::{Post, PostRead, PostReadForm},
36 use lemmy_db_views::local_user_view::{LocalUserSettingsView, LocalUserView};
37 use lemmy_db_views_actor::{
38 community_person_ban_view::CommunityPersonBanView,
39 community_view::CommunityView,
44 settings::structs::{FederationConfig, Settings},
52 pub async fn blocking<F, T>(pool: &DbPool, f: F) -> Result<T, LemmyError>
54 F: FnOnce(&diesel::PgConnection) -> T + Send + 'static,
57 let pool = pool.clone();
58 let res = actix_web::web::block(move || {
59 let conn = pool.get()?;
61 Ok(res) as Result<T, LemmyError>
68 pub async fn send_local_notifs(
69 mentions: Vec<MentionData>,
76 ) -> Result<Vec<LocalUserId>, LemmyError> {
77 let settings = settings.to_owned();
78 let ids = blocking(pool, move |conn| {
94 fn do_send_local_notifs(
96 mentions: &[MentionData],
102 ) -> Vec<LocalUserId> {
103 let mut recipient_ids = Vec::new();
105 // Send the local mentions
106 for mention in mentions
108 .filter(|m| m.is_local(&settings.hostname) && m.name.ne(&person.name))
109 .collect::<Vec<&MentionData>>()
111 if let Ok(mention_user_view) = LocalUserView::read_from_name(conn, &mention.name) {
113 // At some point, make it so you can't tag the parent creator either
114 // This can cause two notifications, one for reply and the other for mention
115 recipient_ids.push(mention_user_view.local_user.id);
117 let user_mention_form = PersonMentionForm {
118 recipient_id: mention_user_view.person.id,
119 comment_id: comment.id,
123 // Allow this to fail softly, since comment edits might re-update or replace it
124 // Let the uniqueness handle this fail
125 PersonMention::create(conn, &user_mention_form).ok();
127 // Send an email to those local users that have notifications on
140 // Send notifs to the parent commenter / poster
141 match comment.parent_id {
143 if let Ok(parent_comment) = Comment::read(conn, parent_id) {
144 // Don't send a notif to yourself
145 if parent_comment.creator_id != person.id {
146 // Get the parent commenter local_user
147 if let Ok(parent_user_view) = LocalUserView::read_person(conn, parent_comment.creator_id)
149 recipient_ids.push(parent_user_view.local_user.id);
166 if post.creator_id != person.id {
167 if let Ok(parent_user_view) = LocalUserView::read_person(conn, post.creator_id) {
168 recipient_ids.push(parent_user_view.local_user.id);
186 pub fn send_email_to_user(
187 local_user_view: &LocalUserView,
190 comment_content: &str,
193 if local_user_view.person.banned || !local_user_view.local_user.send_notifications_to_email {
197 if let Some(user_email) = &local_user_view.local_user.email {
198 let subject = &format!(
200 subject_text, settings.hostname, local_user_view.person.name,
203 "<h1>{}</h1><br><div>{} - {}</div><br><a href={}/inbox>inbox</a>",
205 local_user_view.person.name,
207 settings.get_protocol_and_hostname()
212 &local_user_view.person.name,
217 Err(e) => error!("{}", e),
222 pub async fn is_mod_or_admin(
225 community_id: CommunityId,
226 ) -> Result<(), LemmyError> {
227 let is_mod_or_admin = blocking(pool, move |conn| {
228 CommunityView::is_mod_or_admin(conn, person_id, community_id)
231 if !is_mod_or_admin {
232 return Err(ApiError::err("not_a_mod_or_admin").into());
237 pub fn is_admin(local_user_view: &LocalUserView) -> Result<(), LemmyError> {
238 if !local_user_view.person.admin {
239 return Err(ApiError::err("not_an_admin").into());
244 pub async fn get_post(post_id: PostId, pool: &DbPool) -> Result<Post, LemmyError> {
245 blocking(pool, move |conn| Post::read(conn, post_id))
247 .map_err(|_| ApiError::err("couldnt_find_post").into())
250 pub async fn mark_post_as_read(
254 ) -> Result<PostRead, LemmyError> {
255 let post_read_form = PostReadForm { post_id, person_id };
257 blocking(pool, move |conn| {
258 PostRead::mark_as_read(conn, &post_read_form)
261 .map_err(|_| ApiError::err("couldnt_mark_post_as_read").into())
264 pub async fn get_local_user_view_from_jwt(
268 ) -> Result<LocalUserView, LemmyError> {
269 let claims = Claims::decode(jwt, &secret.jwt_secret)
270 .map_err(|_| ApiError::err("not_logged_in"))?
272 let local_user_id = LocalUserId(claims.sub);
273 let local_user_view =
274 blocking(pool, move |conn| LocalUserView::read(conn, local_user_id)).await??;
275 // Check for a site ban
276 if local_user_view.person.banned {
277 return Err(ApiError::err("site_ban").into());
280 // Check for user deletion
281 if local_user_view.person.deleted {
282 return Err(ApiError::err("deleted").into());
285 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
290 /// Checks if user's token was issued before user's password reset.
291 pub fn check_validator_time(
292 validator_time: &chrono::NaiveDateTime,
294 ) -> Result<(), LemmyError> {
295 let user_validation_time = validator_time.timestamp();
296 if user_validation_time > claims.iat {
297 Err(ApiError::err("not_logged_in").into())
303 pub async fn get_local_user_view_from_jwt_opt(
304 jwt: &Option<String>,
307 ) -> Result<Option<LocalUserView>, LemmyError> {
309 Some(jwt) => Ok(Some(get_local_user_view_from_jwt(jwt, pool, secret).await?)),
314 pub async fn get_local_user_settings_view_from_jwt(
318 ) -> Result<LocalUserSettingsView, LemmyError> {
319 let claims = Claims::decode(jwt, &secret.jwt_secret)
320 .map_err(|_| ApiError::err("not_logged_in"))?
322 let local_user_id = LocalUserId(claims.sub);
323 let local_user_view = blocking(pool, move |conn| {
324 LocalUserSettingsView::read(conn, local_user_id)
327 // Check for a site ban
328 if local_user_view.person.banned {
329 return Err(ApiError::err("site_ban").into());
332 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
337 pub async fn get_local_user_settings_view_from_jwt_opt(
338 jwt: &Option<String>,
341 ) -> Result<Option<LocalUserSettingsView>, LemmyError> {
343 Some(jwt) => Ok(Some(
344 get_local_user_settings_view_from_jwt(jwt, pool, secret).await?,
350 pub async fn check_community_ban(
352 community_id: CommunityId,
354 ) -> Result<(), LemmyError> {
356 move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
357 if blocking(pool, is_banned).await? {
358 Err(ApiError::err("community_ban").into())
364 pub async fn check_person_block(
366 potential_blocker_id: PersonId,
368 ) -> Result<(), LemmyError> {
369 let is_blocked = move |conn: &'_ _| PersonBlock::read(conn, potential_blocker_id, my_id).is_ok();
370 if blocking(pool, is_blocked).await? {
371 Err(ApiError::err("person_block").into())
377 pub async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> {
379 let site = blocking(pool, move |conn| Site::read_simple(conn)).await??;
380 if !site.enable_downvotes {
381 return Err(ApiError::err("downvotes_disabled").into());
387 /// Returns a list of communities that the user moderates
388 /// or if a community_id is supplied validates the user is a moderator
389 /// of that community and returns the community id in a vec
391 /// * `person_id` - the person id of the moderator
392 /// * `community_id` - optional community id to check for moderator privileges
393 /// * `pool` - the diesel db pool
394 pub async fn collect_moderated_communities(
396 community_id: Option<CommunityId>,
398 ) -> Result<Vec<CommunityId>, LemmyError> {
399 if let Some(community_id) = community_id {
400 // if the user provides a community_id, just check for mod/admin privileges
401 is_mod_or_admin(pool, person_id, community_id).await?;
402 Ok(vec![community_id])
404 let ids = blocking(pool, move |conn: &'_ _| {
405 CommunityModerator::get_person_moderated_communities(conn, person_id)
412 pub async fn build_federated_instances(
414 federation_config: &FederationConfig,
416 ) -> Result<Option<FederatedInstances>, LemmyError> {
417 let federation = federation_config.to_owned();
418 if federation.enabled {
419 let distinct_communities = blocking(pool, move |conn| {
420 Community::distinct_federated_communities(conn)
424 let allowed = federation.allowed_instances;
425 let blocked = federation.blocked_instances;
427 let mut linked = distinct_communities
429 .map(|actor_id| Ok(Url::parse(actor_id)?.host_str().unwrap_or("").to_string()))
430 .collect::<Result<Vec<String>, LemmyError>>()?;
432 if let Some(allowed) = allowed.as_ref() {
433 linked.extend_from_slice(allowed);
436 if let Some(blocked) = blocked.as_ref() {
437 linked.retain(|a| !blocked.contains(a) && !a.eq(hostname));
440 // Sort and remove dupes
441 linked.sort_unstable();
444 Ok(Some(FederatedInstances {
454 /// Checks the password length
455 pub fn password_length_check(pass: &str) -> Result<(), LemmyError> {
456 if !(10..=60).contains(&pass.len()) {
457 Err(ApiError::err("invalid_password").into())
463 /// Checks the site description length
464 pub fn site_description_length_check(description: &str) -> Result<(), LemmyError> {
465 if description.len() > 150 {
466 Err(ApiError::err("site_description_length_overflow").into())