]> Untitled Git - lemmy.git/blob - crates/api_common/src/lib.rs
c59bc500b98bac71eb521b2380ea9f041a7c0589
[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   Readable,
18 };
19 use lemmy_db_schema::{
20   source::{
21     comment::Comment,
22     community::{Community, CommunityModerator},
23     person::Person,
24     person_mention::{PersonMention, PersonMentionForm},
25     post::{Post, PostRead, PostReadForm},
26     site::Site,
27   },
28   CommunityId,
29   LocalUserId,
30   PersonId,
31   PostId,
32 };
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,
37 };
38 use lemmy_utils::{
39   claims::Claims,
40   email::send_email,
41   settings::structs::Settings,
42   utils::MentionData,
43   ApiError,
44   LemmyError,
45 };
46 use log::error;
47 use serde::{Deserialize, Serialize};
48 use url::Url;
49
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>,
58 }
59
60 #[derive(Serialize, Deserialize, Debug)]
61 pub struct WebFingerResponse {
62   pub subject: String,
63   pub aliases: Vec<Url>,
64   pub links: Vec<WebFingerLink>,
65 }
66
67 pub async fn blocking<F, T>(pool: &DbPool, f: F) -> Result<T, LemmyError>
68 where
69   F: FnOnce(&diesel::PgConnection) -> T + Send + 'static,
70   T: Send + 'static,
71 {
72   let pool = pool.clone();
73   let res = actix_web::web::block(move || {
74     let conn = pool.get()?;
75     let res = (f)(&conn);
76     Ok(res) as Result<_, LemmyError>
77   })
78   .await?;
79
80   Ok(res)
81 }
82
83 pub async fn send_local_notifs(
84   mentions: Vec<MentionData>,
85   comment: Comment,
86   person: Person,
87   post: Post,
88   pool: &DbPool,
89   do_send_email: bool,
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)
93   })
94   .await?;
95
96   Ok(ids)
97 }
98
99 fn do_send_local_notifs(
100   conn: &PgConnection,
101   mentions: &[MentionData],
102   comment: &Comment,
103   person: &Person,
104   post: &Post,
105   do_send_email: bool,
106 ) -> Vec<LocalUserId> {
107   let mut recipient_ids = Vec::new();
108
109   // Send the local mentions
110   for mention in mentions
111     .iter()
112     .filter(|m| m.is_local() && m.name.ne(&person.name))
113     .collect::<Vec<&MentionData>>()
114   {
115     if let Ok(mention_user_view) = LocalUserView::read_from_name(conn, &mention.name) {
116       // TODO
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);
120
121       let user_mention_form = PersonMentionForm {
122         recipient_id: mention_user_view.person.id,
123         comment_id: comment.id,
124         read: None,
125       };
126
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();
130
131       // Send an email to those local users that have notifications on
132       if do_send_email {
133         send_email_to_user(
134           &mention_user_view,
135           "Mentioned by",
136           "Person Mention",
137           &comment.content,
138         )
139       }
140     }
141   }
142
143   // Send notifs to the parent commenter / poster
144   match comment.parent_id {
145     Some(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)
151           {
152             recipient_ids.push(parent_user_view.local_user.id);
153
154             if do_send_email {
155               send_email_to_user(
156                 &parent_user_view,
157                 "Reply from",
158                 "Comment Reply",
159                 &comment.content,
160               )
161             }
162           }
163         }
164       }
165     }
166     // Its a post
167     None => {
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);
171
172           if do_send_email {
173             send_email_to_user(
174               &parent_user_view,
175               "Reply from",
176               "Post Reply",
177               &comment.content,
178             )
179           }
180         }
181       }
182     }
183   };
184   recipient_ids
185 }
186
187 pub fn send_email_to_user(
188   local_user_view: &LocalUserView,
189   subject_text: &str,
190   body_text: &str,
191   comment_content: &str,
192 ) {
193   if local_user_view.person.banned || !local_user_view.local_user.send_notifications_to_email {
194     return;
195   }
196
197   if let Some(user_email) = &local_user_view.local_user.email {
198     let subject = &format!(
199       "{} - {} {}",
200       subject_text,
201       Settings::get().hostname(),
202       local_user_view.person.name,
203     );
204     let html = &format!(
205       "<h1>{}</h1><br><div>{} - {}</div><br><a href={}/inbox>inbox</a>",
206       body_text,
207       local_user_view.person.name,
208       comment_content,
209       Settings::get().get_protocol_and_hostname()
210     );
211     match send_email(subject, user_email, &local_user_view.person.name, html) {
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("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("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("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("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 ) -> Result<LocalUserView, LemmyError> {
264   let claims = Claims::decode(jwt)
265     .map_err(|_| ApiError::err("not_logged_in"))?
266     .claims;
267   let local_user_id = LocalUserId(claims.sub);
268   let local_user_view =
269     blocking(pool, move |conn| LocalUserView::read(conn, local_user_id)).await??;
270   // Check for a site ban
271   if local_user_view.person.banned {
272     return Err(ApiError::err("site_ban").into());
273   }
274
275   check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
276
277   Ok(local_user_view)
278 }
279
280 /// Checks if user's token was issued before user's password reset.
281 pub fn check_validator_time(
282   validator_time: &chrono::NaiveDateTime,
283   claims: &Claims,
284 ) -> Result<(), LemmyError> {
285   let user_validation_time = validator_time.timestamp();
286   if user_validation_time > claims.iat {
287     Err(ApiError::err("not_logged_in").into())
288   } else {
289     Ok(())
290   }
291 }
292
293 pub async fn get_local_user_view_from_jwt_opt(
294   jwt: &Option<String>,
295   pool: &DbPool,
296 ) -> Result<Option<LocalUserView>, LemmyError> {
297   match jwt {
298     Some(jwt) => Ok(Some(get_local_user_view_from_jwt(jwt, pool).await?)),
299     None => Ok(None),
300   }
301 }
302
303 pub async fn get_local_user_settings_view_from_jwt(
304   jwt: &str,
305   pool: &DbPool,
306 ) -> Result<LocalUserSettingsView, LemmyError> {
307   let claims = Claims::decode(jwt)
308     .map_err(|_| ApiError::err("not_logged_in"))?
309     .claims;
310   let local_user_id = LocalUserId(claims.sub);
311   let local_user_view = blocking(pool, move |conn| {
312     LocalUserSettingsView::read(conn, local_user_id)
313   })
314   .await??;
315   // Check for a site ban
316   if local_user_view.person.banned {
317     return Err(ApiError::err("site_ban").into());
318   }
319
320   check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
321
322   Ok(local_user_view)
323 }
324
325 pub async fn get_local_user_settings_view_from_jwt_opt(
326   jwt: &Option<String>,
327   pool: &DbPool,
328 ) -> Result<Option<LocalUserSettingsView>, LemmyError> {
329   match jwt {
330     Some(jwt) => Ok(Some(
331       get_local_user_settings_view_from_jwt(jwt, pool).await?,
332     )),
333     None => Ok(None),
334   }
335 }
336
337 pub async fn check_community_ban(
338   person_id: PersonId,
339   community_id: CommunityId,
340   pool: &DbPool,
341 ) -> Result<(), LemmyError> {
342   let is_banned =
343     move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
344   if blocking(pool, is_banned).await? {
345     Err(ApiError::err("community_ban").into())
346   } else {
347     Ok(())
348   }
349 }
350
351 pub async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> {
352   if score == -1 {
353     let site = blocking(pool, move |conn| Site::read_simple(conn)).await??;
354     if !site.enable_downvotes {
355       return Err(ApiError::err("downvotes_disabled").into());
356     }
357   }
358   Ok(())
359 }
360
361 /// Returns a list of communities that the user moderates
362 /// or if a community_id is supplied validates the user is a moderator
363 /// of that community and returns the community id in a vec
364 ///
365 /// * `person_id` - the person id of the moderator
366 /// * `community_id` - optional community id to check for moderator privileges
367 /// * `pool` - the diesel db pool
368 pub async fn collect_moderated_communities(
369   person_id: PersonId,
370   community_id: Option<CommunityId>,
371   pool: &DbPool,
372 ) -> Result<Vec<CommunityId>, LemmyError> {
373   if let Some(community_id) = community_id {
374     // if the user provides a community_id, just check for mod/admin privileges
375     is_mod_or_admin(pool, person_id, community_id).await?;
376     Ok(vec![community_id])
377   } else {
378     let ids = blocking(pool, move |conn: &'_ _| {
379       CommunityModerator::get_person_moderated_communities(conn, person_id)
380     })
381     .await??;
382     Ok(ids)
383   }
384 }
385
386 pub async fn build_federated_instances(
387   pool: &DbPool,
388 ) -> Result<Option<FederatedInstances>, LemmyError> {
389   if Settings::get().federation().enabled {
390     let distinct_communities = blocking(pool, move |conn| {
391       Community::distinct_federated_communities(conn)
392     })
393     .await??;
394
395     let allowed = Settings::get().get_allowed_instances();
396     let blocked = Settings::get().get_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(&Settings::get().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 pass.len() > 60 {
428     Err(ApiError::err("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("site_description_length_overflow").into())
438   } else {
439     Ok(())
440   }
441 }