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