8 use crate::site::FederatedInstances;
9 use diesel::PgConnection;
10 use lemmy_db_schema::{
11 newtypes::{CommunityId, LocalUserId, PersonId, PostId},
16 person_block::PersonBlock,
17 person_mention::{PersonMention, PersonMentionForm},
18 post::{Post, PostRead, PostReadForm},
22 traits::{Crud, Readable},
25 use lemmy_db_views::local_user_view::{LocalUserSettingsView, LocalUserView};
26 use lemmy_db_views_actor::{
27 community_person_ban_view::CommunityPersonBanView,
28 community_view::CommunityView,
33 settings::structs::{FederationConfig, Settings},
41 pub async fn blocking<F, T>(pool: &DbPool, f: F) -> Result<T, LemmyError>
43 F: FnOnce(&diesel::PgConnection) -> T + Send + 'static,
46 let pool = pool.clone();
47 let res = actix_web::web::block(move || {
48 let conn = pool.get()?;
50 Ok(res) as Result<T, LemmyError>
57 pub async fn send_local_notifs(
58 mentions: Vec<MentionData>,
65 ) -> Result<Vec<LocalUserId>, LemmyError> {
66 let settings = settings.to_owned();
67 let ids = blocking(pool, move |conn| {
83 fn do_send_local_notifs(
85 mentions: &[MentionData],
91 ) -> Vec<LocalUserId> {
92 let mut recipient_ids = Vec::new();
94 // Send the local mentions
95 for mention in mentions
97 .filter(|m| m.is_local(&settings.hostname) && m.name.ne(&person.name))
98 .collect::<Vec<&MentionData>>()
100 if let Ok(mention_user_view) = LocalUserView::read_from_name(conn, &mention.name) {
102 // At some point, make it so you can't tag the parent creator either
103 // This can cause two notifications, one for reply and the other for mention
104 recipient_ids.push(mention_user_view.local_user.id);
106 let user_mention_form = PersonMentionForm {
107 recipient_id: mention_user_view.person.id,
108 comment_id: comment.id,
112 // Allow this to fail softly, since comment edits might re-update or replace it
113 // Let the uniqueness handle this fail
114 PersonMention::create(conn, &user_mention_form).ok();
116 // 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);
155 if post.creator_id != person.id {
156 if let Ok(parent_user_view) = LocalUserView::read_person(conn, post.creator_id) {
157 recipient_ids.push(parent_user_view.local_user.id);
175 pub fn send_email_to_user(
176 local_user_view: &LocalUserView,
179 comment_content: &str,
182 if local_user_view.person.banned || !local_user_view.local_user.send_notifications_to_email {
186 if let Some(user_email) = &local_user_view.local_user.email {
187 let subject = &format!(
189 subject_text, settings.hostname, local_user_view.person.name,
192 "<h1>{}</h1><br><div>{} - {}</div><br><a href={}/inbox>inbox</a>",
194 local_user_view.person.name,
196 settings.get_protocol_and_hostname()
201 &local_user_view.person.name,
206 Err(e) => error!("{}", e),
211 pub async fn is_mod_or_admin(
214 community_id: CommunityId,
215 ) -> Result<(), LemmyError> {
216 let is_mod_or_admin = blocking(pool, move |conn| {
217 CommunityView::is_mod_or_admin(conn, person_id, community_id)
220 if !is_mod_or_admin {
221 return Err(ApiError::err_plain("not_a_mod_or_admin").into());
226 pub fn is_admin(local_user_view: &LocalUserView) -> Result<(), LemmyError> {
227 if !local_user_view.person.admin {
228 return Err(ApiError::err_plain("not_an_admin").into());
233 pub async fn get_post(post_id: PostId, pool: &DbPool) -> Result<Post, LemmyError> {
234 blocking(pool, move |conn| Post::read(conn, post_id))
236 .map_err(|_| ApiError::err_plain("couldnt_find_post").into())
239 pub async fn mark_post_as_read(
243 ) -> Result<PostRead, LemmyError> {
244 let post_read_form = PostReadForm { post_id, person_id };
246 blocking(pool, move |conn| {
247 PostRead::mark_as_read(conn, &post_read_form)
250 .map_err(|_| ApiError::err_plain("couldnt_mark_post_as_read").into())
253 pub async fn get_local_user_view_from_jwt(
257 ) -> Result<LocalUserView, LemmyError> {
258 let claims = Claims::decode(jwt, &secret.jwt_secret)
259 .map_err(|e| ApiError::err("not_logged_in", e))?
261 let local_user_id = LocalUserId(claims.sub);
262 let local_user_view =
263 blocking(pool, move |conn| LocalUserView::read(conn, local_user_id)).await??;
264 // Check for a site ban
265 if local_user_view.person.banned {
266 return Err(ApiError::err_plain("site_ban").into());
269 // Check for user deletion
270 if local_user_view.person.deleted {
271 return Err(ApiError::err_plain("deleted").into());
274 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
279 /// Checks if user's token was issued before user's password reset.
280 pub fn check_validator_time(
281 validator_time: &chrono::NaiveDateTime,
283 ) -> Result<(), LemmyError> {
284 let user_validation_time = validator_time.timestamp();
285 if user_validation_time > claims.iat {
286 Err(ApiError::err_plain("not_logged_in").into())
292 pub async fn get_local_user_view_from_jwt_opt(
293 jwt: &Option<String>,
296 ) -> Result<Option<LocalUserView>, LemmyError> {
298 Some(jwt) => Ok(Some(get_local_user_view_from_jwt(jwt, pool, secret).await?)),
303 pub async fn get_local_user_settings_view_from_jwt(
307 ) -> Result<LocalUserSettingsView, LemmyError> {
308 let claims = Claims::decode(jwt, &secret.jwt_secret)
309 .map_err(|e| ApiError::err("not_logged_in", e))?
311 let local_user_id = LocalUserId(claims.sub);
312 let local_user_view = blocking(pool, move |conn| {
313 LocalUserSettingsView::read(conn, local_user_id)
316 // Check for a site ban
317 if local_user_view.person.banned {
318 return Err(ApiError::err_plain("site_ban").into());
321 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
326 pub async fn get_local_user_settings_view_from_jwt_opt(
327 jwt: &Option<String>,
330 ) -> Result<Option<LocalUserSettingsView>, LemmyError> {
332 Some(jwt) => Ok(Some(
333 get_local_user_settings_view_from_jwt(jwt, pool, secret).await?,
339 pub async fn check_community_ban(
341 community_id: CommunityId,
343 ) -> Result<(), LemmyError> {
345 move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
346 if blocking(pool, is_banned).await? {
347 Err(ApiError::err_plain("community_ban").into())
353 pub async fn check_community_deleted_or_removed(
354 community_id: CommunityId,
356 ) -> Result<(), LemmyError> {
357 let community = blocking(pool, move |conn| Community::read(conn, community_id))
359 .map_err(|e| ApiError::err("couldnt_find_community", e))?;
360 if community.deleted || community.removed {
361 Err(ApiError::err_plain("deleted").into())
367 pub fn check_post_deleted_or_removed(post: &Post) -> Result<(), LemmyError> {
368 if post.deleted || post.removed {
369 Err(ApiError::err_plain("deleted").into())
375 pub async fn check_person_block(
377 potential_blocker_id: PersonId,
379 ) -> Result<(), LemmyError> {
380 let is_blocked = move |conn: &'_ _| PersonBlock::read(conn, potential_blocker_id, my_id).is_ok();
381 if blocking(pool, is_blocked).await? {
382 Err(ApiError::err_plain("person_block").into())
388 pub async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> {
390 let site = blocking(pool, Site::read_simple).await??;
391 if !site.enable_downvotes {
392 return Err(ApiError::err_plain("downvotes_disabled").into());
398 pub async fn build_federated_instances(
400 federation_config: &FederationConfig,
402 ) -> Result<Option<FederatedInstances>, LemmyError> {
403 let federation = federation_config.to_owned();
404 if federation.enabled {
405 let distinct_communities = blocking(pool, move |conn| {
406 Community::distinct_federated_communities(conn)
410 let allowed = federation.allowed_instances;
411 let blocked = federation.blocked_instances;
413 let mut linked = distinct_communities
415 .map(|actor_id| Ok(Url::parse(actor_id)?.host_str().unwrap_or("").to_string()))
416 .collect::<Result<Vec<String>, LemmyError>>()?;
418 if let Some(allowed) = allowed.as_ref() {
419 linked.extend_from_slice(allowed);
422 if let Some(blocked) = blocked.as_ref() {
423 linked.retain(|a| !blocked.contains(a) && !a.eq(hostname));
426 // Sort and remove dupes
427 linked.sort_unstable();
430 Ok(Some(FederatedInstances {
440 /// Checks the password length
441 pub fn password_length_check(pass: &str) -> Result<(), LemmyError> {
442 if !(10..=60).contains(&pass.len()) {
443 Err(ApiError::err_plain("invalid_password").into())
449 /// Checks the site description length
450 pub fn site_description_length_check(description: &str) -> Result<(), LemmyError> {
451 if description.len() > 150 {
452 Err(ApiError::err_plain("site_description_length_overflow").into())
458 /// Checks for a honeypot. If this field is filled, fail the rest of the function
459 pub fn honeypot_check(honeypot: &Option<String>) -> Result<(), LemmyError> {
460 if honeypot.is_some() {
461 Err(ApiError::err_plain("honeypot_fail").into())