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