]> Untitled Git - lemmy.git/blob - crates/api_common/src/lib.rs
Clean up.
[lemmy.git] / crates / api_common / src / lib.rs
1 pub mod comment;
2 pub mod community;
3 pub mod person;
4 pub mod post;
5 pub mod site;
6 pub mod websocket;
7
8 use crate::site::FederatedInstances;
9 use diesel::PgConnection;
10 use lemmy_db_queries::{
11   source::{
12     community::{CommunityModerator_, Community_},
13     person_block::PersonBlock_,
14     site::Site_,
15   },
16   Crud,
17   DbPool,
18   Readable,
19 };
20 use lemmy_db_schema::{
21   source::{
22     comment::Comment,
23     community::{Community, CommunityModerator},
24     person::Person,
25     person_block::PersonBlock,
26     person_mention::{PersonMention, PersonMentionForm},
27     post::{Post, PostRead, PostReadForm},
28     site::Site,
29   },
30   CommunityId,
31   LocalUserId,
32   PersonId,
33   PostId,
34 };
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,
39 };
40 use lemmy_utils::{
41   claims::Claims,
42   email::send_email,
43   settings::structs::Settings,
44   utils::MentionData,
45   ApiError,
46   LemmyError,
47 };
48 use log::error;
49 use url::Url;
50
51 pub async fn blocking<F, T>(pool: &DbPool, f: F) -> Result<T, LemmyError>
52 where
53   F: FnOnce(&diesel::PgConnection) -> T + Send + 'static,
54   T: Send + 'static,
55 {
56   let pool = pool.clone();
57   let res = actix_web::web::block(move || {
58     let conn = pool.get()?;
59     let res = (f)(&conn);
60     Ok(res) as Result<T, LemmyError>
61   })
62   .await?;
63
64   res
65 }
66
67 pub async fn send_local_notifs(
68   mentions: Vec<MentionData>,
69   comment: Comment,
70   person: Person,
71   post: Post,
72   pool: &DbPool,
73   do_send_email: bool,
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)
77   })
78   .await?;
79
80   Ok(ids)
81 }
82
83 fn do_send_local_notifs(
84   conn: &PgConnection,
85   mentions: &[MentionData],
86   comment: &Comment,
87   person: &Person,
88   post: &Post,
89   do_send_email: bool,
90 ) -> Vec<LocalUserId> {
91   let mut recipient_ids = Vec::new();
92
93   // Send the local mentions
94   for mention in mentions
95     .iter()
96     .filter(|m| m.is_local() && m.name.ne(&person.name))
97     .collect::<Vec<&MentionData>>()
98   {
99     if let Ok(mention_user_view) = LocalUserView::read_from_name(conn, &mention.name) {
100       // TODO
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);
104
105       let user_mention_form = PersonMentionForm {
106         recipient_id: mention_user_view.person.id,
107         comment_id: comment.id,
108         read: None,
109       };
110
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();
114
115       // Send an email to those local users that have notifications on
116       if do_send_email {
117         send_email_to_user(
118           &mention_user_view,
119           "Mentioned by",
120           "Person Mention",
121           &comment.content,
122         )
123       }
124     }
125   }
126
127   // Send notifs to the parent commenter / poster
128   match comment.parent_id {
129     Some(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)
135           {
136             recipient_ids.push(parent_user_view.local_user.id);
137
138             if do_send_email {
139               send_email_to_user(
140                 &parent_user_view,
141                 "Reply from",
142                 "Comment Reply",
143                 &comment.content,
144               )
145             }
146           }
147         }
148       }
149     }
150     // Its a post
151     None => {
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);
155
156           if do_send_email {
157             send_email_to_user(
158               &parent_user_view,
159               "Reply from",
160               "Post Reply",
161               &comment.content,
162             )
163           }
164         }
165       }
166     }
167   };
168   recipient_ids
169 }
170
171 pub fn send_email_to_user(
172   local_user_view: &LocalUserView,
173   subject_text: &str,
174   body_text: &str,
175   comment_content: &str,
176 ) {
177   if local_user_view.person.banned || !local_user_view.local_user.send_notifications_to_email {
178     return;
179   }
180
181   if let Some(user_email) = &local_user_view.local_user.email {
182     let subject = &format!(
183       "{} - {} {}",
184       subject_text,
185       Settings::get().hostname,
186       local_user_view.person.name,
187     );
188     let html = &format!(
189       "<h1>{}</h1><br><div>{} - {}</div><br><a href={}/inbox>inbox</a>",
190       body_text,
191       local_user_view.person.name,
192       comment_content,
193       Settings::get().get_protocol_and_hostname()
194     );
195     match send_email(subject, user_email, &local_user_view.person.name, html) {
196       Ok(_o) => _o,
197       Err(e) => error!("{}", e),
198     };
199   }
200 }
201
202 pub async fn is_mod_or_admin(
203   pool: &DbPool,
204   person_id: PersonId,
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)
209   })
210   .await?;
211   if !is_mod_or_admin {
212     return Err(ApiError::err("not_a_mod_or_admin").into());
213   }
214   Ok(())
215 }
216
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());
220   }
221   Ok(())
222 }
223
224 pub async fn get_post(post_id: PostId, pool: &DbPool) -> Result<Post, LemmyError> {
225   blocking(pool, move |conn| Post::read(conn, post_id))
226     .await?
227     .map_err(|_| ApiError::err("couldnt_find_post").into())
228 }
229
230 pub async fn mark_post_as_read(
231   person_id: PersonId,
232   post_id: PostId,
233   pool: &DbPool,
234 ) -> Result<PostRead, LemmyError> {
235   let post_read_form = PostReadForm { post_id, person_id };
236
237   blocking(pool, move |conn| {
238     PostRead::mark_as_read(conn, &post_read_form)
239   })
240   .await?
241   .map_err(|_| ApiError::err("couldnt_mark_post_as_read").into())
242 }
243
244 pub async fn get_local_user_view_from_jwt(
245   jwt: &str,
246   pool: &DbPool,
247 ) -> Result<LocalUserView, LemmyError> {
248   let claims = Claims::decode(jwt)
249     .map_err(|_| ApiError::err("not_logged_in"))?
250     .claims;
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());
257   }
258
259   // Check for user deletion
260   if local_user_view.person.deleted {
261     return Err(ApiError::err("deleted").into());
262   }
263
264   check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
265
266   Ok(local_user_view)
267 }
268
269 /// Checks if user's token was issued before user's password reset.
270 pub fn check_validator_time(
271   validator_time: &chrono::NaiveDateTime,
272   claims: &Claims,
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())
277   } else {
278     Ok(())
279   }
280 }
281
282 pub async fn get_local_user_view_from_jwt_opt(
283   jwt: &Option<String>,
284   pool: &DbPool,
285 ) -> Result<Option<LocalUserView>, LemmyError> {
286   match jwt {
287     Some(jwt) => Ok(Some(get_local_user_view_from_jwt(jwt, pool).await?)),
288     None => Ok(None),
289   }
290 }
291
292 pub async fn get_local_user_settings_view_from_jwt(
293   jwt: &str,
294   pool: &DbPool,
295 ) -> Result<LocalUserSettingsView, LemmyError> {
296   let claims = Claims::decode(jwt)
297     .map_err(|_| ApiError::err("not_logged_in"))?
298     .claims;
299   let local_user_id = LocalUserId(claims.sub);
300   let local_user_view = blocking(pool, move |conn| {
301     LocalUserSettingsView::read(conn, local_user_id)
302   })
303   .await??;
304   // Check for a site ban
305   if local_user_view.person.banned {
306     return Err(ApiError::err("site_ban").into());
307   }
308
309   check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
310
311   Ok(local_user_view)
312 }
313
314 pub async fn get_local_user_settings_view_from_jwt_opt(
315   jwt: &Option<String>,
316   pool: &DbPool,
317 ) -> Result<Option<LocalUserSettingsView>, LemmyError> {
318   match jwt {
319     Some(jwt) => Ok(Some(
320       get_local_user_settings_view_from_jwt(jwt, pool).await?,
321     )),
322     None => Ok(None),
323   }
324 }
325
326 pub async fn check_community_ban(
327   person_id: PersonId,
328   community_id: CommunityId,
329   pool: &DbPool,
330 ) -> Result<(), LemmyError> {
331   let is_banned =
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())
335   } else {
336     Ok(())
337   }
338 }
339
340 pub async fn check_person_block(
341   my_id: PersonId,
342   potential_blocker_id: PersonId,
343   pool: &DbPool,
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())
348   } else {
349     Ok(())
350   }
351 }
352
353 pub async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> {
354   if score == -1 {
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());
358     }
359   }
360   Ok(())
361 }
362
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
366 ///
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(
371   person_id: PersonId,
372   community_id: Option<CommunityId>,
373   pool: &DbPool,
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])
379   } else {
380     let ids = blocking(pool, move |conn: &'_ _| {
381       CommunityModerator::get_person_moderated_communities(conn, person_id)
382     })
383     .await??;
384     Ok(ids)
385   }
386 }
387
388 pub async fn build_federated_instances(
389   pool: &DbPool,
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)
394     })
395     .await??;
396
397     let allowed = Settings::get().federation.allowed_instances;
398     let blocked = Settings::get().federation.blocked_instances;
399
400     let mut linked = distinct_communities
401       .iter()
402       .map(|actor_id| Ok(Url::parse(actor_id)?.host_str().unwrap_or("").to_string()))
403       .collect::<Result<Vec<String>, LemmyError>>()?;
404
405     if let Some(allowed) = allowed.as_ref() {
406       linked.extend_from_slice(allowed);
407     }
408
409     if let Some(blocked) = blocked.as_ref() {
410       linked.retain(|a| !blocked.contains(a) && !a.eq(&Settings::get().hostname));
411     }
412
413     // Sort and remove dupes
414     linked.sort_unstable();
415     linked.dedup();
416
417     Ok(Some(FederatedInstances {
418       linked,
419       allowed,
420       blocked,
421     }))
422   } else {
423     Ok(None)
424   }
425 }
426
427 /// Checks the password length
428 pub fn password_length_check(pass: &str) -> Result<(), LemmyError> {
429   if !(10..=60).contains(&pass.len()) {
430     Err(ApiError::err("invalid_password").into())
431   } else {
432     Ok(())
433   }
434 }
435
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())
440   } else {
441     Ok(())
442   }
443 }