]> Untitled Git - lemmy.git/blob - crates/api_common/src/lib.rs
Merge remote-tracking branch 'yerba/split-api-crate' into test_merge_api_crates_reorg
[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   match blocking(pool, move |conn| Post::read(conn, post_id)).await? {
241     Ok(post) => Ok(post),
242     Err(_e) => Err(ApiError::err("couldnt_find_post").into()),
243   }
244 }
245
246 pub async fn get_local_user_view_from_jwt(
247   jwt: &str,
248   pool: &DbPool,
249 ) -> Result<LocalUserView, LemmyError> {
250   let claims = match Claims::decode(&jwt) {
251     Ok(claims) => claims.claims,
252     Err(_e) => return Err(ApiError::err("not_logged_in").into()),
253   };
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_validator_time(&local_user_view.local_user.validator_time, &claims)?;
263
264   Ok(local_user_view)
265 }
266
267 /// Checks if user's token was issued before user's password reset.
268 pub fn check_validator_time(
269   validator_time: &chrono::NaiveDateTime,
270   claims: &Claims,
271 ) -> Result<(), LemmyError> {
272   let user_validation_time = validator_time.timestamp();
273   if user_validation_time > claims.iat {
274     Err(ApiError::err("not_logged_in").into())
275   } else {
276     Ok(())
277   }
278 }
279
280 pub async fn get_local_user_view_from_jwt_opt(
281   jwt: &Option<String>,
282   pool: &DbPool,
283 ) -> Result<Option<LocalUserView>, LemmyError> {
284   match jwt {
285     Some(jwt) => Ok(Some(get_local_user_view_from_jwt(jwt, pool).await?)),
286     None => Ok(None),
287   }
288 }
289
290 pub async fn get_local_user_settings_view_from_jwt(
291   jwt: &str,
292   pool: &DbPool,
293 ) -> Result<LocalUserSettingsView, LemmyError> {
294   let claims = match Claims::decode(&jwt) {
295     Ok(claims) => claims.claims,
296     Err(_e) => return Err(ApiError::err("not_logged_in").into()),
297   };
298   let local_user_id = LocalUserId(claims.sub);
299   let local_user_view = blocking(pool, move |conn| {
300     LocalUserSettingsView::read(conn, local_user_id)
301   })
302   .await??;
303   // Check for a site ban
304   if local_user_view.person.banned {
305     return Err(ApiError::err("site_ban").into());
306   }
307
308   check_validator_time(&local_user_view.local_user.validator_time, &claims)?;
309
310   Ok(local_user_view)
311 }
312
313 pub async fn get_local_user_settings_view_from_jwt_opt(
314   jwt: &Option<String>,
315   pool: &DbPool,
316 ) -> Result<Option<LocalUserSettingsView>, LemmyError> {
317   match jwt {
318     Some(jwt) => Ok(Some(
319       get_local_user_settings_view_from_jwt(jwt, pool).await?,
320     )),
321     None => Ok(None),
322   }
323 }
324
325 pub async fn check_community_ban(
326   person_id: PersonId,
327   community_id: CommunityId,
328   pool: &DbPool,
329 ) -> Result<(), LemmyError> {
330   let is_banned =
331     move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
332   if blocking(pool, is_banned).await? {
333     Err(ApiError::err("community_ban").into())
334   } else {
335     Ok(())
336   }
337 }
338
339 pub async fn check_downvotes_enabled(score: i16, pool: &DbPool) -> Result<(), LemmyError> {
340   if score == -1 {
341     let site = blocking(pool, move |conn| Site::read_simple(conn)).await??;
342     if !site.enable_downvotes {
343       return Err(ApiError::err("downvotes_disabled").into());
344     }
345   }
346   Ok(())
347 }
348
349 /// Returns a list of communities that the user moderates
350 /// or if a community_id is supplied validates the user is a moderator
351 /// of that community and returns the community id in a vec
352 ///
353 /// * `person_id` - the person id of the moderator
354 /// * `community_id` - optional community id to check for moderator privileges
355 /// * `pool` - the diesel db pool
356 pub async fn collect_moderated_communities(
357   person_id: PersonId,
358   community_id: Option<CommunityId>,
359   pool: &DbPool,
360 ) -> Result<Vec<CommunityId>, LemmyError> {
361   if let Some(community_id) = community_id {
362     // if the user provides a community_id, just check for mod/admin privileges
363     is_mod_or_admin(pool, person_id, community_id).await?;
364     Ok(vec![community_id])
365   } else {
366     let ids = blocking(pool, move |conn: &'_ _| {
367       CommunityModerator::get_person_moderated_communities(conn, person_id)
368     })
369     .await??;
370     Ok(ids)
371   }
372 }
373
374 pub async fn build_federated_instances(
375   pool: &DbPool,
376 ) -> Result<Option<FederatedInstances>, LemmyError> {
377   if Settings::get().federation().enabled {
378     let distinct_communities = blocking(pool, move |conn| {
379       Community::distinct_federated_communities(conn)
380     })
381     .await??;
382
383     let allowed = Settings::get().get_allowed_instances();
384     let blocked = Settings::get().get_blocked_instances();
385
386     let mut linked = distinct_communities
387       .iter()
388       .map(|actor_id| Ok(Url::parse(actor_id)?.host_str().unwrap_or("").to_string()))
389       .collect::<Result<Vec<String>, LemmyError>>()?;
390
391     if let Some(allowed) = allowed.as_ref() {
392       linked.extend_from_slice(allowed);
393     }
394
395     if let Some(blocked) = blocked.as_ref() {
396       linked.retain(|a| !blocked.contains(a) && !a.eq(&Settings::get().hostname()));
397     }
398
399     // Sort and remove dupes
400     linked.sort_unstable();
401     linked.dedup();
402
403     Ok(Some(FederatedInstances {
404       linked,
405       allowed,
406       blocked,
407     }))
408   } else {
409     Ok(None)
410   }
411 }
412
413 /// Checks the password length
414 pub fn password_length_check(pass: &str) -> Result<(), LemmyError> {
415   if pass.len() > 60 {
416     Err(ApiError::err("invalid_password").into())
417   } else {
418     Ok(())
419   }
420 }