8 use crate::site::FederatedInstances;
9 use diesel::PgConnection;
10 use lemmy_db_queries::{
11 source::{community::Community_, person_block::PersonBlock_, site::Site_},
16 use lemmy_db_schema::{
21 person_block::PersonBlock,
22 person_mention::{PersonMention, PersonMentionForm},
23 post::{Post, PostRead, PostReadForm},
32 use lemmy_db_views::local_user_view::{LocalUserSettingsView, LocalUserView};
33 use lemmy_db_views_actor::{
34 community_person_ban_view::CommunityPersonBanView,
35 community_view::CommunityView,
40 settings::structs::{FederationConfig, Settings},
48 pub async fn blocking<F, T>(pool: &DbPool, f: F) -> Result<T, LemmyError>
50 F: FnOnce(&diesel::PgConnection) -> T + Send + 'static,
53 let pool = pool.clone();
54 let res = actix_web::web::block(move || {
55 let conn = pool.get()?;
57 Ok(res) as Result<T, LemmyError>
64 pub async fn send_local_notifs(
65 mentions: Vec<MentionData>,
72 ) -> Result<Vec<LocalUserId>, LemmyError> {
73 let settings = settings.to_owned();
74 let ids = blocking(pool, move |conn| {
90 fn do_send_local_notifs(
92 mentions: &[MentionData],
98 ) -> Vec<LocalUserId> {
99 let mut recipient_ids = Vec::new();
101 // Send the local mentions
102 for mention in mentions
104 .filter(|m| m.is_local(&settings.hostname) && m.name.ne(&person.name))
105 .collect::<Vec<&MentionData>>()
107 if let Ok(mention_user_view) = LocalUserView::read_from_name(conn, &mention.name) {
109 // At some point, make it so you can't tag the parent creator either
110 // This can cause two notifications, one for reply and the other for mention
111 recipient_ids.push(mention_user_view.local_user.id);
113 let user_mention_form = PersonMentionForm {
114 recipient_id: mention_user_view.person.id,
115 comment_id: comment.id,
119 // Allow this to fail softly, since comment edits might re-update or replace it
120 // Let the uniqueness handle this fail
121 PersonMention::create(conn, &user_mention_form).ok();
123 // Send an email to those local users that have notifications on
136 // Send notifs to the parent commenter / poster
137 match comment.parent_id {
139 if let Ok(parent_comment) = Comment::read(conn, parent_id) {
140 // Don't send a notif to yourself
141 if parent_comment.creator_id != person.id {
142 // Get the parent commenter local_user
143 if let Ok(parent_user_view) = LocalUserView::read_person(conn, parent_comment.creator_id)
145 recipient_ids.push(parent_user_view.local_user.id);
162 if post.creator_id != person.id {
163 if let Ok(parent_user_view) = LocalUserView::read_person(conn, post.creator_id) {
164 recipient_ids.push(parent_user_view.local_user.id);
182 pub fn send_email_to_user(
183 local_user_view: &LocalUserView,
186 comment_content: &str,
189 if local_user_view.person.banned || !local_user_view.local_user.send_notifications_to_email {
193 if let Some(user_email) = &local_user_view.local_user.email {
194 let subject = &format!(
196 subject_text, settings.hostname, local_user_view.person.name,
199 "<h1>{}</h1><br><div>{} - {}</div><br><a href={}/inbox>inbox</a>",
201 local_user_view.person.name,
203 settings.get_protocol_and_hostname()
208 &local_user_view.person.name,
213 Err(e) => error!("{}", e),
218 pub async fn is_mod_or_admin(
221 community_id: CommunityId,
222 ) -> Result<(), LemmyError> {
223 let is_mod_or_admin = blocking(pool, move |conn| {
224 CommunityView::is_mod_or_admin(conn, person_id, community_id)
227 if !is_mod_or_admin {
228 return Err(ApiError::err_plain("not_a_mod_or_admin").into());
233 pub fn is_admin(local_user_view: &LocalUserView) -> Result<(), LemmyError> {
234 if !local_user_view.person.admin {
235 return Err(ApiError::err_plain("not_an_admin").into());
240 pub async fn get_post(post_id: PostId, pool: &DbPool) -> Result<Post, LemmyError> {
241 blocking(pool, move |conn| Post::read(conn, post_id))
243 .map_err(|_| ApiError::err_plain("couldnt_find_post").into())
246 pub async fn mark_post_as_read(
250 ) -> Result<PostRead, LemmyError> {
251 let post_read_form = PostReadForm { post_id, person_id };
253 blocking(pool, move |conn| {
254 PostRead::mark_as_read(conn, &post_read_form)
257 .map_err(|_| ApiError::err_plain("couldnt_mark_post_as_read").into())
260 pub async fn get_local_user_view_from_jwt(
264 ) -> Result<LocalUserView, LemmyError> {
265 let claims = Claims::decode(jwt, &secret.jwt_secret)
266 .map_err(|e| ApiError::err("not_logged_in", e))?
268 let local_user_id = LocalUserId(claims.sub);
269 let local_user_view =
270 blocking(pool, move |conn| LocalUserView::read(conn, local_user_id)).await??;
271 // Check for a site ban
272 if local_user_view.person.banned {
273 return Err(ApiError::err_plain("site_ban").into());
276 // Check for user deletion
277 if local_user_view.person.deleted {
278 return Err(ApiError::err_plain("deleted").into());
281 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
286 /// Checks if user's token was issued before user's password reset.
287 pub fn check_validator_time(
288 validator_time: &chrono::NaiveDateTime,
290 ) -> Result<(), LemmyError> {
291 let user_validation_time = validator_time.timestamp();
292 if user_validation_time > claims.iat {
293 Err(ApiError::err_plain("not_logged_in").into())
299 pub async fn get_local_user_view_from_jwt_opt(
300 jwt: &Option<String>,
303 ) -> Result<Option<LocalUserView>, LemmyError> {
305 Some(jwt) => Ok(Some(get_local_user_view_from_jwt(jwt, pool, secret).await?)),
310 pub async fn get_local_user_settings_view_from_jwt(
314 ) -> Result<LocalUserSettingsView, LemmyError> {
315 let claims = Claims::decode(jwt, &secret.jwt_secret)
316 .map_err(|e| ApiError::err("not_logged_in", e))?
318 let local_user_id = LocalUserId(claims.sub);
319 let local_user_view = blocking(pool, move |conn| {
320 LocalUserSettingsView::read(conn, local_user_id)
323 // Check for a site ban
324 if local_user_view.person.banned {
325 return Err(ApiError::err_plain("site_ban").into());
328 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
333 pub async fn get_local_user_settings_view_from_jwt_opt(
334 jwt: &Option<String>,
337 ) -> Result<Option<LocalUserSettingsView>, LemmyError> {
339 Some(jwt) => Ok(Some(
340 get_local_user_settings_view_from_jwt(jwt, pool, secret).await?,
346 pub async fn check_community_ban(
348 community_id: CommunityId,
350 ) -> Result<(), LemmyError> {
352 move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
353 if blocking(pool, is_banned).await? {
354 Err(ApiError::err_plain("community_ban").into())
360 pub async fn check_community_deleted_or_removed(
361 community_id: CommunityId,
363 ) -> Result<(), LemmyError> {
364 let community = blocking(pool, move |conn| Community::read(conn, community_id))
366 .map_err(|e| ApiError::err("couldnt_find_community", e))?;
367 if community.deleted || community.removed {
368 Err(ApiError::err_plain("deleted").into())
374 pub fn check_post_deleted_or_removed(post: &Post) -> Result<(), LemmyError> {
375 if post.deleted || post.removed {
376 Err(ApiError::err_plain("deleted").into())
382 pub async fn check_person_block(
384 potential_blocker_id: PersonId,
386 ) -> Result<(), LemmyError> {
387 let is_blocked = move |conn: &'_ _| PersonBlock::read(conn, potential_blocker_id, my_id).is_ok();
388 if blocking(pool, is_blocked).await? {
389 Err(ApiError::err_plain("person_block").into())
395 pub async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> {
397 let site = blocking(pool, move |conn| Site::read_simple(conn)).await??;
398 if !site.enable_downvotes {
399 return Err(ApiError::err_plain("downvotes_disabled").into());
405 pub async fn build_federated_instances(
407 federation_config: &FederationConfig,
409 ) -> Result<Option<FederatedInstances>, LemmyError> {
410 let federation = federation_config.to_owned();
411 if federation.enabled {
412 let distinct_communities = blocking(pool, move |conn| {
413 Community::distinct_federated_communities(conn)
417 let allowed = federation.allowed_instances;
418 let blocked = federation.blocked_instances;
420 let mut linked = distinct_communities
422 .map(|actor_id| Ok(Url::parse(actor_id)?.host_str().unwrap_or("").to_string()))
423 .collect::<Result<Vec<String>, LemmyError>>()?;
425 if let Some(allowed) = allowed.as_ref() {
426 linked.extend_from_slice(allowed);
429 if let Some(blocked) = blocked.as_ref() {
430 linked.retain(|a| !blocked.contains(a) && !a.eq(hostname));
433 // Sort and remove dupes
434 linked.sort_unstable();
437 Ok(Some(FederatedInstances {
447 /// Checks the password length
448 pub fn password_length_check(pass: &str) -> Result<(), LemmyError> {
449 if !(10..=60).contains(&pass.len()) {
450 Err(ApiError::err_plain("invalid_password").into())
456 /// Checks the site description length
457 pub fn site_description_length_check(description: &str) -> Result<(), LemmyError> {
458 if description.len() > 150 {
459 Err(ApiError::err_plain("site_description_length_overflow").into())
465 /// Checks for a honeypot. If this field is filled, fail the rest of the function
466 pub fn honeypot_check(honeypot: &Option<String>) -> Result<(), LemmyError> {
467 if honeypot.is_some() {
468 Err(ApiError::err_plain("honeypot_fail").into())