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