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