8 use crate::site::FederatedInstances;
9 use diesel::PgConnection;
10 use lemmy_db_queries::{
12 community::{CommunityModerator_, Community_},
19 use lemmy_db_schema::{
22 community::{Community, CommunityModerator},
24 person_mention::{PersonMention, PersonMentionForm},
25 post::{Post, PostRead, PostReadForm},
33 use lemmy_db_views::local_user_view::{LocalUserSettingsView, LocalUserView};
34 use lemmy_db_views_actor::{
35 community_person_ban_view::CommunityPersonBanView,
36 community_view::CommunityView,
41 settings::structs::Settings,
47 use serde::{Deserialize, Serialize};
50 #[derive(Serialize, Deserialize, Debug)]
51 pub struct WebFingerLink {
52 pub rel: Option<String>,
53 #[serde(rename(serialize = "type", deserialize = "type"))]
54 pub type_: Option<String>,
55 pub href: Option<Url>,
56 #[serde(skip_serializing_if = "Option::is_none")]
57 pub template: Option<String>,
60 #[derive(Serialize, Deserialize, Debug)]
61 pub struct WebFingerResponse {
63 pub aliases: Vec<Url>,
64 pub links: Vec<WebFingerLink>,
67 pub async fn blocking<F, T>(pool: &DbPool, f: F) -> Result<T, LemmyError>
69 F: FnOnce(&diesel::PgConnection) -> T + Send + 'static,
72 let pool = pool.clone();
73 let res = actix_web::web::block(move || {
74 let conn = pool.get()?;
76 Ok(res) as Result<_, LemmyError>
83 pub async fn send_local_notifs(
84 mentions: Vec<MentionData>,
90 ) -> Result<Vec<LocalUserId>, LemmyError> {
91 let ids = blocking(pool, move |conn| {
92 do_send_local_notifs(conn, &mentions, &comment, &person, &post, do_send_email)
99 fn do_send_local_notifs(
101 mentions: &[MentionData],
106 ) -> Vec<LocalUserId> {
107 let mut recipient_ids = Vec::new();
109 // Send the local mentions
110 for mention in mentions
112 .filter(|m| m.is_local() && m.name.ne(&person.name))
113 .collect::<Vec<&MentionData>>()
115 if let Ok(mention_user_view) = LocalUserView::read_from_name(&conn, &mention.name) {
117 // At some point, make it so you can't tag the parent creator either
118 // This can cause two notifications, one for reply and the other for mention
119 recipient_ids.push(mention_user_view.local_user.id);
121 let user_mention_form = PersonMentionForm {
122 recipient_id: mention_user_view.person.id,
123 comment_id: comment.id,
127 // Allow this to fail softly, since comment edits might re-update or replace it
128 // Let the uniqueness handle this fail
129 PersonMention::create(&conn, &user_mention_form).ok();
131 // Send an email to those local users that have notifications on
143 // Send notifs to the parent commenter / poster
144 match comment.parent_id {
146 if let Ok(parent_comment) = Comment::read(&conn, parent_id) {
147 // Don't send a notif to yourself
148 if parent_comment.creator_id != person.id {
149 // Get the parent commenter local_user
150 if let Ok(parent_user_view) = LocalUserView::read_person(&conn, parent_comment.creator_id)
152 recipient_ids.push(parent_user_view.local_user.id);
168 if post.creator_id != person.id {
169 if let Ok(parent_user_view) = LocalUserView::read_person(&conn, post.creator_id) {
170 recipient_ids.push(parent_user_view.local_user.id);
187 pub fn send_email_to_user(
188 local_user_view: &LocalUserView,
191 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!(
201 Settings::get().hostname(),
202 local_user_view.person.name,
205 "<h1>{}</h1><br><div>{} - {}</div><br><a href={}/inbox>inbox</a>",
207 local_user_view.person.name,
209 Settings::get().get_protocol_and_hostname()
211 match send_email(subject, &user_email, &local_user_view.person.name, html) {
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("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("not_an_admin").into());
240 /// A helper method for showing the bot account
241 pub fn user_show_bot_accounts(local_user_view: &Option<LocalUserView>) -> bool {
242 match local_user_view {
243 Some(uv) => uv.to_owned().local_user.show_bot_accounts,
248 /// A helper method for showing nsfw
249 pub fn user_show_nsfw(local_user_view: &Option<LocalUserView>) -> bool {
250 match &local_user_view {
251 Some(uv) => uv.local_user.show_nsfw,
256 /// A helper method for showing read posts
257 pub fn user_show_read_posts(local_user_view: &Option<LocalUserView>) -> bool {
258 match local_user_view {
259 Some(uv) => uv.to_owned().local_user.show_read_posts,
264 pub async fn get_post(post_id: PostId, pool: &DbPool) -> Result<Post, LemmyError> {
265 blocking(pool, move |conn| Post::read(conn, post_id))
267 .map_err(|_| ApiError::err("couldnt_find_post").into())
270 pub async fn mark_post_as_read(
274 ) -> Result<PostRead, LemmyError> {
275 let post_read_form = PostReadForm { post_id, person_id };
277 blocking(pool, move |conn| {
278 PostRead::mark_as_read(conn, &post_read_form)
281 .map_err(|_| ApiError::err("couldnt_mark_post_as_read").into())
284 pub async fn get_local_user_view_from_jwt(
287 ) -> Result<LocalUserView, LemmyError> {
288 let claims = Claims::decode(&jwt)
289 .map_err(|_| ApiError::err("not_logged_in"))?
291 let local_user_id = LocalUserId(claims.sub);
292 let local_user_view =
293 blocking(pool, move |conn| LocalUserView::read(conn, local_user_id)).await??;
294 // Check for a site ban
295 if local_user_view.person.banned {
296 return Err(ApiError::err("site_ban").into());
299 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
304 /// Checks if user's token was issued before user's password reset.
305 pub fn check_validator_time(
306 validator_time: &chrono::NaiveDateTime,
308 ) -> Result<(), LemmyError> {
309 let user_validation_time = validator_time.timestamp();
310 if user_validation_time > claims.iat {
311 Err(ApiError::err("not_logged_in").into())
317 pub async fn get_local_user_view_from_jwt_opt(
318 jwt: &Option<String>,
320 ) -> Result<Option<LocalUserView>, LemmyError> {
322 Some(jwt) => Ok(Some(get_local_user_view_from_jwt(jwt, pool).await?)),
327 pub async fn get_local_user_settings_view_from_jwt(
330 ) -> Result<LocalUserSettingsView, LemmyError> {
331 let claims = Claims::decode(&jwt)
332 .map_err(|_| ApiError::err("not_logged_in"))?
334 let local_user_id = LocalUserId(claims.sub);
335 let local_user_view = blocking(pool, move |conn| {
336 LocalUserSettingsView::read(conn, local_user_id)
339 // Check for a site ban
340 if local_user_view.person.banned {
341 return Err(ApiError::err("site_ban").into());
344 check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
349 pub async fn get_local_user_settings_view_from_jwt_opt(
350 jwt: &Option<String>,
352 ) -> Result<Option<LocalUserSettingsView>, LemmyError> {
354 Some(jwt) => Ok(Some(
355 get_local_user_settings_view_from_jwt(jwt, pool).await?,
361 pub async fn check_community_ban(
363 community_id: CommunityId,
365 ) -> Result<(), LemmyError> {
367 move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
368 if blocking(pool, is_banned).await? {
369 Err(ApiError::err("community_ban").into())
375 pub async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> {
377 let site = blocking(pool, move |conn| Site::read_simple(conn)).await??;
378 if !site.enable_downvotes {
379 return Err(ApiError::err("downvotes_disabled").into());
385 /// Returns a list of communities that the user moderates
386 /// or if a community_id is supplied validates the user is a moderator
387 /// of that community and returns the community id in a vec
389 /// * `person_id` - the person id of the moderator
390 /// * `community_id` - optional community id to check for moderator privileges
391 /// * `pool` - the diesel db pool
392 pub async fn collect_moderated_communities(
394 community_id: Option<CommunityId>,
396 ) -> Result<Vec<CommunityId>, LemmyError> {
397 if let Some(community_id) = community_id {
398 // if the user provides a community_id, just check for mod/admin privileges
399 is_mod_or_admin(pool, person_id, community_id).await?;
400 Ok(vec![community_id])
402 let ids = blocking(pool, move |conn: &'_ _| {
403 CommunityModerator::get_person_moderated_communities(conn, person_id)
410 pub async fn build_federated_instances(
412 ) -> Result<Option<FederatedInstances>, LemmyError> {
413 if Settings::get().federation().enabled {
414 let distinct_communities = blocking(pool, move |conn| {
415 Community::distinct_federated_communities(conn)
419 let allowed = Settings::get().get_allowed_instances();
420 let blocked = Settings::get().get_blocked_instances();
422 let mut linked = distinct_communities
424 .map(|actor_id| Ok(Url::parse(actor_id)?.host_str().unwrap_or("").to_string()))
425 .collect::<Result<Vec<String>, LemmyError>>()?;
427 if let Some(allowed) = allowed.as_ref() {
428 linked.extend_from_slice(allowed);
431 if let Some(blocked) = blocked.as_ref() {
432 linked.retain(|a| !blocked.contains(a) && !a.eq(&Settings::get().hostname()));
435 // Sort and remove dupes
436 linked.sort_unstable();
439 Ok(Some(FederatedInstances {
449 /// Checks the password length
450 pub fn password_length_check(pass: &str) -> Result<(), LemmyError> {
452 Err(ApiError::err("invalid_password").into())
458 /// Checks the site description length
459 pub fn site_description_length_check(description: &str) -> Result<(), LemmyError> {
460 if description.len() > 150 {
461 Err(ApiError::err("site_description_length_overflow").into())