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