]> Untitled Git - lemmy.git/blob - crates/api_common/src/lib.rs
068bd253f5bc69b9de042f5a9e529017068c220f
[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     secret::SecretSingleton,
15     site::Site_,
16   },
17   Crud,
18   DbPool,
19   Readable,
20 };
21 use lemmy_db_schema::{
22   source::{
23     comment::Comment,
24     community::{Community, CommunityModerator},
25     person::Person,
26     person_block::PersonBlock,
27     person_mention::{PersonMention, PersonMentionForm},
28     post::{Post, PostRead, PostReadForm},
29     secret::Secret,
30     site::Site,
31   },
32   CommunityId,
33   LocalUserId,
34   PersonId,
35   PostId,
36 };
37 use lemmy_db_views::local_user_view::{LocalUserSettingsView, LocalUserView};
38 use lemmy_db_views_actor::{
39   community_person_ban_view::CommunityPersonBanView,
40   community_view::CommunityView,
41 };
42 use lemmy_utils::{
43   claims::Claims,
44   email::send_email,
45   settings::structs::Settings,
46   utils::MentionData,
47   ApiError,
48   LemmyError,
49 };
50 use log::error;
51 use url::Url;
52
53 pub async fn blocking<F, T>(pool: &DbPool, f: F) -> Result<T, LemmyError>
54 where
55   F: FnOnce(&diesel::PgConnection) -> T + Send + 'static,
56   T: Send + 'static,
57 {
58   let pool = pool.clone();
59   let res = actix_web::web::block(move || {
60     let conn = pool.get()?;
61     let res = (f)(&conn);
62     Ok(res) as Result<T, LemmyError>
63   })
64   .await?;
65
66   res
67 }
68
69 pub async fn send_local_notifs(
70   mentions: Vec<MentionData>,
71   comment: Comment,
72   person: Person,
73   post: Post,
74   pool: &DbPool,
75   do_send_email: bool,
76 ) -> Result<Vec<LocalUserId>, LemmyError> {
77   let ids = blocking(pool, move |conn| {
78     do_send_local_notifs(conn, &mentions, &comment, &person, &post, do_send_email)
79   })
80   .await?;
81
82   Ok(ids)
83 }
84
85 fn do_send_local_notifs(
86   conn: &PgConnection,
87   mentions: &[MentionData],
88   comment: &Comment,
89   person: &Person,
90   post: &Post,
91   do_send_email: bool,
92 ) -> Vec<LocalUserId> {
93   let mut recipient_ids = Vec::new();
94
95   // Send the local mentions
96   for mention in mentions
97     .iter()
98     .filter(|m| m.is_local() && m.name.ne(&person.name))
99     .collect::<Vec<&MentionData>>()
100   {
101     if let Ok(mention_user_view) = LocalUserView::read_from_name(conn, &mention.name) {
102       // TODO
103       // At some point, make it so you can't tag the parent creator either
104       // This can cause two notifications, one for reply and the other for mention
105       recipient_ids.push(mention_user_view.local_user.id);
106
107       let user_mention_form = PersonMentionForm {
108         recipient_id: mention_user_view.person.id,
109         comment_id: comment.id,
110         read: None,
111       };
112
113       // Allow this to fail softly, since comment edits might re-update or replace it
114       // Let the uniqueness handle this fail
115       PersonMention::create(conn, &user_mention_form).ok();
116
117       // Send an email to those local users that have notifications on
118       if do_send_email {
119         send_email_to_user(
120           &mention_user_view,
121           "Mentioned by",
122           "Person Mention",
123           &comment.content,
124         )
125       }
126     }
127   }
128
129   // Send notifs to the parent commenter / poster
130   match comment.parent_id {
131     Some(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)
137           {
138             recipient_ids.push(parent_user_view.local_user.id);
139
140             if do_send_email {
141               send_email_to_user(
142                 &parent_user_view,
143                 "Reply from",
144                 "Comment Reply",
145                 &comment.content,
146               )
147             }
148           }
149         }
150       }
151     }
152     // Its a post
153     None => {
154       if post.creator_id != person.id {
155         if let Ok(parent_user_view) = LocalUserView::read_person(conn, post.creator_id) {
156           recipient_ids.push(parent_user_view.local_user.id);
157
158           if do_send_email {
159             send_email_to_user(
160               &parent_user_view,
161               "Reply from",
162               "Post Reply",
163               &comment.content,
164             )
165           }
166         }
167       }
168     }
169   };
170   recipient_ids
171 }
172
173 pub fn send_email_to_user(
174   local_user_view: &LocalUserView,
175   subject_text: &str,
176   body_text: &str,
177   comment_content: &str,
178 ) {
179   if local_user_view.person.banned || !local_user_view.local_user.send_notifications_to_email {
180     return;
181   }
182
183   if let Some(user_email) = &local_user_view.local_user.email {
184     let subject = &format!(
185       "{} - {} {}",
186       subject_text,
187       Settings::get().hostname,
188       local_user_view.person.name,
189     );
190     let html = &format!(
191       "<h1>{}</h1><br><div>{} - {}</div><br><a href={}/inbox>inbox</a>",
192       body_text,
193       local_user_view.person.name,
194       comment_content,
195       Settings::get().get_protocol_and_hostname()
196     );
197     match send_email(subject, user_email, &local_user_view.person.name, html) {
198       Ok(_o) => _o,
199       Err(e) => error!("{}", e),
200     };
201   }
202 }
203
204 pub async fn is_mod_or_admin(
205   pool: &DbPool,
206   person_id: PersonId,
207   community_id: CommunityId,
208 ) -> Result<(), LemmyError> {
209   let is_mod_or_admin = blocking(pool, move |conn| {
210     CommunityView::is_mod_or_admin(conn, person_id, community_id)
211   })
212   .await?;
213   if !is_mod_or_admin {
214     return Err(ApiError::err("not_a_mod_or_admin").into());
215   }
216   Ok(())
217 }
218
219 pub fn is_admin(local_user_view: &LocalUserView) -> Result<(), LemmyError> {
220   if !local_user_view.person.admin {
221     return Err(ApiError::err("not_an_admin").into());
222   }
223   Ok(())
224 }
225
226 pub async fn get_post(post_id: PostId, pool: &DbPool) -> Result<Post, LemmyError> {
227   blocking(pool, move |conn| Post::read(conn, post_id))
228     .await?
229     .map_err(|_| ApiError::err("couldnt_find_post").into())
230 }
231
232 pub async fn mark_post_as_read(
233   person_id: PersonId,
234   post_id: PostId,
235   pool: &DbPool,
236 ) -> Result<PostRead, LemmyError> {
237   let post_read_form = PostReadForm { post_id, person_id };
238
239   blocking(pool, move |conn| {
240     PostRead::mark_as_read(conn, &post_read_form)
241   })
242   .await?
243   .map_err(|_| ApiError::err("couldnt_mark_post_as_read").into())
244 }
245
246 pub async fn get_local_user_view_from_jwt(
247   jwt: &str,
248   pool: &DbPool,
249 ) -> Result<LocalUserView, LemmyError> {
250   let jwt_secret = Secret::get().jwt_secret;
251   let claims = Claims::decode(jwt, &jwt_secret)
252     .map_err(|_| ApiError::err("not_logged_in"))?
253     .claims;
254   let local_user_id = LocalUserId(claims.sub);
255   let local_user_view =
256     blocking(pool, move |conn| LocalUserView::read(conn, local_user_id)).await??;
257   // Check for a site ban
258   if local_user_view.person.banned {
259     return Err(ApiError::err("site_ban").into());
260   }
261
262   // Check for user deletion
263   if local_user_view.person.deleted {
264     return Err(ApiError::err("deleted").into());
265   }
266
267   check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
268
269   Ok(local_user_view)
270 }
271
272 /// Checks if user's token was issued before user's password reset.
273 pub fn check_validator_time(
274   validator_time: &chrono::NaiveDateTime,
275   claims: &Claims,
276 ) -> Result<(), LemmyError> {
277   let user_validation_time = validator_time.timestamp();
278   if user_validation_time > claims.iat {
279     Err(ApiError::err("not_logged_in").into())
280   } else {
281     Ok(())
282   }
283 }
284
285 pub async fn get_local_user_view_from_jwt_opt(
286   jwt: &Option<String>,
287   pool: &DbPool,
288 ) -> Result<Option<LocalUserView>, LemmyError> {
289   match jwt {
290     Some(jwt) => Ok(Some(get_local_user_view_from_jwt(jwt, pool).await?)),
291     None => Ok(None),
292   }
293 }
294
295 pub async fn get_local_user_settings_view_from_jwt(
296   jwt: &str,
297   pool: &DbPool,
298 ) -> Result<LocalUserSettingsView, LemmyError> {
299   let jwt_secret = Secret::get().jwt_secret;
300   let claims = Claims::decode(jwt, &jwt_secret)
301     .map_err(|_| ApiError::err("not_logged_in"))?
302     .claims;
303   let local_user_id = LocalUserId(claims.sub);
304   let local_user_view = blocking(pool, move |conn| {
305     LocalUserSettingsView::read(conn, local_user_id)
306   })
307   .await??;
308   // Check for a site ban
309   if local_user_view.person.banned {
310     return Err(ApiError::err("site_ban").into());
311   }
312
313   check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
314
315   Ok(local_user_view)
316 }
317
318 pub async fn get_local_user_settings_view_from_jwt_opt(
319   jwt: &Option<String>,
320   pool: &DbPool,
321 ) -> Result<Option<LocalUserSettingsView>, LemmyError> {
322   match jwt {
323     Some(jwt) => Ok(Some(
324       get_local_user_settings_view_from_jwt(jwt, pool).await?,
325     )),
326     None => Ok(None),
327   }
328 }
329
330 pub async fn check_community_ban(
331   person_id: PersonId,
332   community_id: CommunityId,
333   pool: &DbPool,
334 ) -> Result<(), LemmyError> {
335   let is_banned =
336     move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
337   if blocking(pool, is_banned).await? {
338     Err(ApiError::err("community_ban").into())
339   } else {
340     Ok(())
341   }
342 }
343
344 pub async fn check_person_block(
345   my_id: PersonId,
346   potential_blocker_id: PersonId,
347   pool: &DbPool,
348 ) -> Result<(), LemmyError> {
349   let is_blocked = move |conn: &'_ _| PersonBlock::read(conn, potential_blocker_id, my_id).is_ok();
350   if blocking(pool, is_blocked).await? {
351     Err(ApiError::err("person_block").into())
352   } else {
353     Ok(())
354   }
355 }
356
357 pub async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> {
358   if score == -1 {
359     let site = blocking(pool, move |conn| Site::read_simple(conn)).await??;
360     if !site.enable_downvotes {
361       return Err(ApiError::err("downvotes_disabled").into());
362     }
363   }
364   Ok(())
365 }
366
367 /// Returns a list of communities that the user moderates
368 /// or if a community_id is supplied validates the user is a moderator
369 /// of that community and returns the community id in a vec
370 ///
371 /// * `person_id` - the person id of the moderator
372 /// * `community_id` - optional community id to check for moderator privileges
373 /// * `pool` - the diesel db pool
374 pub async fn collect_moderated_communities(
375   person_id: PersonId,
376   community_id: Option<CommunityId>,
377   pool: &DbPool,
378 ) -> Result<Vec<CommunityId>, LemmyError> {
379   if let Some(community_id) = community_id {
380     // if the user provides a community_id, just check for mod/admin privileges
381     is_mod_or_admin(pool, person_id, community_id).await?;
382     Ok(vec![community_id])
383   } else {
384     let ids = blocking(pool, move |conn: &'_ _| {
385       CommunityModerator::get_person_moderated_communities(conn, person_id)
386     })
387     .await??;
388     Ok(ids)
389   }
390 }
391
392 pub async fn build_federated_instances(
393   pool: &DbPool,
394 ) -> Result<Option<FederatedInstances>, LemmyError> {
395   if Settings::get().federation.enabled {
396     let distinct_communities = blocking(pool, move |conn| {
397       Community::distinct_federated_communities(conn)
398     })
399     .await??;
400
401     let allowed = Settings::get().federation.allowed_instances;
402     let blocked = Settings::get().federation.blocked_instances;
403
404     let mut linked = distinct_communities
405       .iter()
406       .map(|actor_id| Ok(Url::parse(actor_id)?.host_str().unwrap_or("").to_string()))
407       .collect::<Result<Vec<String>, LemmyError>>()?;
408
409     if let Some(allowed) = allowed.as_ref() {
410       linked.extend_from_slice(allowed);
411     }
412
413     if let Some(blocked) = blocked.as_ref() {
414       linked.retain(|a| !blocked.contains(a) && !a.eq(&Settings::get().hostname));
415     }
416
417     // Sort and remove dupes
418     linked.sort_unstable();
419     linked.dedup();
420
421     Ok(Some(FederatedInstances {
422       linked,
423       allowed,
424       blocked,
425     }))
426   } else {
427     Ok(None)
428   }
429 }
430
431 /// Checks the password length
432 pub fn password_length_check(pass: &str) -> Result<(), LemmyError> {
433   if !(10..=60).contains(&pass.len()) {
434     Err(ApiError::err("invalid_password").into())
435   } else {
436     Ok(())
437   }
438 }
439
440 /// Checks the site description length
441 pub fn site_description_length_check(description: &str) -> Result<(), LemmyError> {
442   if description.len() > 150 {
443     Err(ApiError::err("site_description_length_overflow").into())
444   } else {
445     Ok(())
446   }
447 }