]> Untitled Git - lemmy.git/blob - crates/api_structs/src/lib.rs
e0fab6b24d368ba9b236cbdecf7a4d79ee79b5a2
[lemmy.git] / crates / api_structs / 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 diesel::PgConnection;
9 use lemmy_db_queries::{Crud, DbPool};
10 use lemmy_db_schema::source::{
11   comment::Comment,
12   person::Person,
13   person_mention::{PersonMention, PersonMentionForm},
14   post::Post,
15 };
16 use lemmy_db_views::local_user_view::LocalUserView;
17 use lemmy_utils::{email::send_email, settings::structs::Settings, utils::MentionData, LemmyError};
18 use log::error;
19 use serde::{Deserialize, Serialize};
20 use url::Url;
21
22 #[derive(Serialize, Deserialize, Debug)]
23 pub struct WebFingerLink {
24   pub rel: Option<String>,
25   #[serde(rename(serialize = "type", deserialize = "type"))]
26   pub type_: Option<String>,
27   pub href: Option<Url>,
28   #[serde(skip_serializing_if = "Option::is_none")]
29   pub template: Option<String>,
30 }
31
32 #[derive(Serialize, Deserialize, Debug)]
33 pub struct WebFingerResponse {
34   pub subject: String,
35   pub aliases: Vec<Url>,
36   pub links: Vec<WebFingerLink>,
37 }
38
39 pub async fn blocking<F, T>(pool: &DbPool, f: F) -> Result<T, LemmyError>
40 where
41   F: FnOnce(&diesel::PgConnection) -> T + Send + 'static,
42   T: Send + 'static,
43 {
44   let pool = pool.clone();
45   let res = actix_web::web::block(move || {
46     let conn = pool.get()?;
47     let res = (f)(&conn);
48     Ok(res) as Result<_, LemmyError>
49   })
50   .await?;
51
52   Ok(res)
53 }
54
55 pub async fn send_local_notifs(
56   mentions: Vec<MentionData>,
57   comment: Comment,
58   person: Person,
59   post: Post,
60   pool: &DbPool,
61   do_send_email: bool,
62 ) -> Result<Vec<i32>, LemmyError> {
63   let ids = blocking(pool, move |conn| {
64     do_send_local_notifs(conn, &mentions, &comment, &person, &post, do_send_email)
65   })
66   .await?;
67
68   Ok(ids)
69 }
70
71 // TODO should this really use person_ids as recipient ids? or local_user_ids ?
72 fn do_send_local_notifs(
73   conn: &PgConnection,
74   mentions: &[MentionData],
75   comment: &Comment,
76   person: &Person,
77   post: &Post,
78   do_send_email: bool,
79 ) -> Vec<i32> {
80   let mut recipient_ids = Vec::new();
81
82   // Send the local mentions
83   for mention in mentions
84     .iter()
85     .filter(|m| m.is_local() && m.name.ne(&person.name))
86     .collect::<Vec<&MentionData>>()
87   {
88     // TODO do a local user fetch
89     if let Ok(mention_user_view) = LocalUserView::read_from_name(&conn, &mention.name) {
90       // TODO
91       // At some point, make it so you can't tag the parent creator either
92       // This can cause two notifications, one for reply and the other for mention
93       recipient_ids.push(mention_user_view.local_user.id);
94
95       let user_mention_form = PersonMentionForm {
96         recipient_id: mention_user_view.person.id,
97         comment_id: comment.id,
98         read: None,
99       };
100
101       // Allow this to fail softly, since comment edits might re-update or replace it
102       // Let the uniqueness handle this fail
103       PersonMention::create(&conn, &user_mention_form).ok();
104
105       // Send an email to those local users that have notifications on
106       if do_send_email && mention_user_view.local_user.send_notifications_to_email {
107         send_email_to_user(
108           &mention_user_view,
109           "Mentioned by",
110           "Person Mention",
111           &comment.content,
112         )
113       }
114     }
115   }
116
117   // Send notifs to the parent commenter / poster
118   match comment.parent_id {
119     Some(parent_id) => {
120       if let Ok(parent_comment) = Comment::read(&conn, parent_id) {
121         if parent_comment.creator_id != person.id {
122           if let Ok(parent_user_view) = LocalUserView::read_person(&conn, parent_comment.creator_id)
123           {
124             recipient_ids.push(parent_user_view.local_user.id);
125
126             if do_send_email && parent_user_view.local_user.send_notifications_to_email {
127               send_email_to_user(
128                 &parent_user_view,
129                 "Reply from",
130                 "Comment Reply",
131                 &comment.content,
132               )
133             }
134           }
135         }
136       }
137     }
138     // Its a post
139     None => {
140       if post.creator_id != person.id {
141         if let Ok(parent_user_view) = LocalUserView::read_person(&conn, post.creator_id) {
142           recipient_ids.push(parent_user_view.local_user.id);
143
144           if do_send_email && parent_user_view.local_user.send_notifications_to_email {
145             send_email_to_user(
146               &parent_user_view,
147               "Reply from",
148               "Post Reply",
149               &comment.content,
150             )
151           }
152         }
153       }
154     }
155   };
156   recipient_ids
157 }
158
159 pub fn send_email_to_user(
160   local_user_view: &LocalUserView,
161   subject_text: &str,
162   body_text: &str,
163   comment_content: &str,
164 ) {
165   if local_user_view.person.banned {
166     return;
167   }
168
169   if let Some(user_email) = &local_user_view.local_user.email {
170     let subject = &format!(
171       "{} - {} {}",
172       subject_text,
173       Settings::get().hostname(),
174       local_user_view.person.name,
175     );
176     let html = &format!(
177       "<h1>{}</h1><br><div>{} - {}</div><br><a href={}/inbox>inbox</a>",
178       body_text,
179       local_user_view.person.name,
180       comment_content,
181       Settings::get().get_protocol_and_hostname()
182     );
183     match send_email(subject, &user_email, &local_user_view.person.name, html) {
184       Ok(_o) => _o,
185       Err(e) => error!("{}", e),
186     };
187   }
188 }