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},
35 use lemmy_db_views::local_user_view::{LocalUserSettingsView, LocalUserView};
36 use lemmy_db_views_actor::{
37 community_person_ban_view::CommunityPersonBanView,
38 community_view::CommunityView,
43 settings::structs::Settings,
51 pub async fn blocking<F, T>(pool: &DbPool, f: F) -> Result<T, LemmyError>
53 F: FnOnce(&diesel::PgConnection) -> T + Send + 'static,
56 let pool = pool.clone();
57 let res = actix_web::web::block(move || {
58 let conn = pool.get()?;
60 Ok(res) as Result<T, LemmyError>
67 pub async fn send_local_notifs(
68 mentions: Vec<MentionData>,
74 ) -> Result<Vec<LocalUserId>, LemmyError> {
75 let ids = blocking(pool, move |conn| {
76 do_send_local_notifs(conn, &mentions, &comment, &person, &post, do_send_email)
83 fn do_send_local_notifs(
85 mentions: &[MentionData],
90 ) -> Vec<LocalUserId> {
91 let mut recipient_ids = Vec::new();
93 // Send the local mentions
94 for mention in mentions
96 .filter(|m| m.is_local() && m.name.ne(&person.name))
97 .collect::<Vec<&MentionData>>()
99 if let Ok(mention_user_view) = LocalUserView::read_from_name(conn, &mention.name) {
101 // At some point, make it so you can't tag the parent creator either
102 // This can cause two notifications, one for reply and the other for mention
103 recipient_ids.push(mention_user_view.local_user.id);
105 let user_mention_form = PersonMentionForm {
106 recipient_id: mention_user_view.person.id,
107 comment_id: comment.id,
111 // Allow this to fail softly, since comment edits might re-update or replace it
112 // Let the uniqueness handle this fail
113 PersonMention::create(conn, &user_mention_form).ok();
115 // Send an email to those local users that have notifications on
127 // Send notifs to the parent commenter / poster
128 match comment.parent_id {
130 if let Ok(parent_comment) = Comment::read(conn, parent_id) {
131 // Don't send a notif to yourself
132 if parent_comment.creator_id != person.id {
133 // Get the parent commenter local_user
134 if let Ok(parent_user_view) = LocalUserView::read_person(conn, parent_comment.creator_id)
136 recipient_ids.push(parent_user_view.local_user.id);
152 if post.creator_id != person.id {
153 if let Ok(parent_user_view) = LocalUserView::read_person(conn, post.creator_id) {
154 recipient_ids.push(parent_user_view.local_user.id);
171 pub fn send_email_to_user(
172 local_user_view: &LocalUserView,
175 comment_content: &str,
177 if local_user_view.person.banned || !local_user_view.local_user.send_notifications_to_email {
181 if let Some(user_email) = &local_user_view.local_user.email {
182 let subject = &format!(
185 Settings::get().hostname,
186 local_user_view.person.name,
189 "<h1>{}</h1><br><div>{} - {}</div><br><a href={}/inbox>inbox</a>",
191 local_user_view.person.name,
193 Settings::get().get_protocol_and_hostname()
195 match send_email(subject, user_email, &local_user_view.person.name, html) {
197 Err(e) => error!("{}", e),
202 pub async fn is_mod_or_admin(
205 community_id: CommunityId,
206 ) -> Result<(), LemmyError> {
207 let is_mod_or_admin = blocking(pool, move |conn| {
208 CommunityView::is_mod_or_admin(conn, person_id, community_id)
211 if !is_mod_or_admin {
212 return Err(ApiError::err("not_a_mod_or_admin").into());
217 pub fn is_admin(local_user_view: &LocalUserView) -> Result<(), LemmyError> {
218 if !local_user_view.person.admin {
219 return Err(ApiError::err("not_an_admin").into());
224 pub async fn get_post(post_id: PostId, pool: &DbPool) -> Result<Post, LemmyError> {
225 blocking(pool, move |conn| Post::read(conn, post_id))
227 .map_err(|_| ApiError::err("couldnt_find_post").into())
230 pub async fn mark_post_as_read(
234 ) -> Result<PostRead, LemmyError> {
235 let post_read_form = PostReadForm { post_id, person_id };
237 blocking(pool, move |conn| {
238 PostRead::mark_as_read(conn, &post_read_form)
241 .map_err(|_| ApiError::err("couldnt_mark_post_as_read").into())
244 pub async fn get_local_user_view_from_jwt(
247 ) -> Result<LocalUserView, LemmyError> {
248 let claims = Claims::decode(jwt)
249 .map_err(|_| ApiError::err("not_logged_in"))?
251 let local_user_id = LocalUserId(claims.sub);
252 let local_user_view =
253 blocking(pool, move |conn| LocalUserView::read(conn, local_user_id)).await??;
254 // Check for a site ban
255 if local_user_view.person.banned {
256 return Err(ApiError::err("site_ban").into());
259 // Check for user deletion
260 if local_user_view.person.deleted {
261 return Err(ApiError::err("deleted").into());
264 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
269 /// Checks if user's token was issued before user's password reset.
270 pub fn check_validator_time(
271 validator_time: &chrono::NaiveDateTime,
273 ) -> Result<(), LemmyError> {
274 let user_validation_time = validator_time.timestamp();
275 if user_validation_time > claims.iat {
276 Err(ApiError::err("not_logged_in").into())
282 pub async fn get_local_user_view_from_jwt_opt(
283 jwt: &Option<String>,
285 ) -> Result<Option<LocalUserView>, LemmyError> {
287 Some(jwt) => Ok(Some(get_local_user_view_from_jwt(jwt, pool).await?)),
292 pub async fn get_local_user_settings_view_from_jwt(
295 ) -> Result<LocalUserSettingsView, LemmyError> {
296 let claims = Claims::decode(jwt)
297 .map_err(|_| ApiError::err("not_logged_in"))?
299 let local_user_id = LocalUserId(claims.sub);
300 let local_user_view = blocking(pool, move |conn| {
301 LocalUserSettingsView::read(conn, local_user_id)
304 // Check for a site ban
305 if local_user_view.person.banned {
306 return Err(ApiError::err("site_ban").into());
309 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
314 pub async fn get_local_user_settings_view_from_jwt_opt(
315 jwt: &Option<String>,
317 ) -> Result<Option<LocalUserSettingsView>, LemmyError> {
319 Some(jwt) => Ok(Some(
320 get_local_user_settings_view_from_jwt(jwt, pool).await?,
326 pub async fn check_community_ban(
328 community_id: CommunityId,
330 ) -> Result<(), LemmyError> {
332 move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
333 if blocking(pool, is_banned).await? {
334 Err(ApiError::err("community_ban").into())
340 pub async fn check_person_block(
342 potential_blocker_id: PersonId,
344 ) -> Result<(), LemmyError> {
345 let is_blocked = move |conn: &'_ _| PersonBlock::read(conn, potential_blocker_id, my_id).is_ok();
346 if blocking(pool, is_blocked).await? {
347 Err(ApiError::err("person_block").into())
353 pub async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> {
355 let site = blocking(pool, move |conn| Site::read_simple(conn)).await??;
356 if !site.enable_downvotes {
357 return Err(ApiError::err("downvotes_disabled").into());
363 /// Returns a list of communities that the user moderates
364 /// or if a community_id is supplied validates the user is a moderator
365 /// of that community and returns the community id in a vec
367 /// * `person_id` - the person id of the moderator
368 /// * `community_id` - optional community id to check for moderator privileges
369 /// * `pool` - the diesel db pool
370 pub async fn collect_moderated_communities(
372 community_id: Option<CommunityId>,
374 ) -> Result<Vec<CommunityId>, LemmyError> {
375 if let Some(community_id) = community_id {
376 // if the user provides a community_id, just check for mod/admin privileges
377 is_mod_or_admin(pool, person_id, community_id).await?;
378 Ok(vec![community_id])
380 let ids = blocking(pool, move |conn: &'_ _| {
381 CommunityModerator::get_person_moderated_communities(conn, person_id)
388 pub async fn build_federated_instances(
390 ) -> Result<Option<FederatedInstances>, LemmyError> {
391 if Settings::get().federation.enabled {
392 let distinct_communities = blocking(pool, move |conn| {
393 Community::distinct_federated_communities(conn)
397 let allowed = Settings::get().federation.allowed_instances;
398 let blocked = Settings::get().federation.blocked_instances;
400 let mut linked = distinct_communities
402 .map(|actor_id| Ok(Url::parse(actor_id)?.host_str().unwrap_or("").to_string()))
403 .collect::<Result<Vec<String>, LemmyError>>()?;
405 if let Some(allowed) = allowed.as_ref() {
406 linked.extend_from_slice(allowed);
409 if let Some(blocked) = blocked.as_ref() {
410 linked.retain(|a| !blocked.contains(a) && !a.eq(&Settings::get().hostname));
413 // Sort and remove dupes
414 linked.sort_unstable();
417 Ok(Some(FederatedInstances {
427 /// Checks the password length
428 pub fn password_length_check(pass: &str) -> Result<(), LemmyError> {
430 Err(ApiError::err("invalid_password").into())
436 /// Checks the site description length
437 pub fn site_description_length_check(description: &str) -> Result<(), LemmyError> {
438 if description.len() > 150 {
439 Err(ApiError::err("site_description_length_overflow").into())