]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/private_message.rs
Add person name to PersonIsBannedFromSite error (#3786) (#3855)
[lemmy.git] / crates / apub / src / objects / private_message.rs
1 use crate::{
2   check_apub_id_valid_with_strictness,
3   objects::read_from_string_or_source,
4   protocol::{
5     objects::chat_message::{ChatMessage, ChatMessageType},
6     Source,
7   },
8 };
9 use activitypub_federation::{
10   config::Data,
11   protocol::{values::MediaTypeHtml, verification::verify_domains_match},
12   traits::Object,
13 };
14 use chrono::NaiveDateTime;
15 use lemmy_api_common::{
16   context::LemmyContext,
17   utils::{check_person_block, sanitize_html},
18 };
19 use lemmy_db_schema::{
20   source::{
21     person::Person,
22     private_message::{PrivateMessage, PrivateMessageInsertForm},
23   },
24   traits::Crud,
25 };
26 use lemmy_utils::{
27   error::{LemmyError, LemmyErrorType},
28   utils::{markdown::markdown_to_html, time::convert_datetime},
29 };
30 use std::ops::Deref;
31 use url::Url;
32
33 #[derive(Clone, Debug)]
34 pub struct ApubPrivateMessage(pub(crate) PrivateMessage);
35
36 impl Deref for ApubPrivateMessage {
37   type Target = PrivateMessage;
38   fn deref(&self) -> &Self::Target {
39     &self.0
40   }
41 }
42
43 impl From<PrivateMessage> for ApubPrivateMessage {
44   fn from(pm: PrivateMessage) -> Self {
45     ApubPrivateMessage(pm)
46   }
47 }
48
49 #[async_trait::async_trait]
50 impl Object for ApubPrivateMessage {
51   type DataType = LemmyContext;
52   type Kind = ChatMessage;
53   type Error = LemmyError;
54
55   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
56     None
57   }
58
59   #[tracing::instrument(skip_all)]
60   async fn read_from_id(
61     object_id: Url,
62     context: &Data<Self::DataType>,
63   ) -> Result<Option<Self>, LemmyError> {
64     Ok(
65       PrivateMessage::read_from_apub_id(&mut context.pool(), object_id)
66         .await?
67         .map(Into::into),
68     )
69   }
70
71   async fn delete(self, _context: &Data<Self::DataType>) -> Result<(), LemmyError> {
72     // do nothing, because pm can't be fetched over http
73     unimplemented!()
74   }
75
76   #[tracing::instrument(skip_all)]
77   async fn into_json(self, context: &Data<Self::DataType>) -> Result<ChatMessage, LemmyError> {
78     let creator_id = self.creator_id;
79     let creator = Person::read(&mut context.pool(), creator_id).await?;
80
81     let recipient_id = self.recipient_id;
82     let recipient = Person::read(&mut context.pool(), recipient_id).await?;
83
84     let note = ChatMessage {
85       r#type: ChatMessageType::ChatMessage,
86       id: self.ap_id.clone().into(),
87       attributed_to: creator.actor_id.into(),
88       to: [recipient.actor_id.into()],
89       content: markdown_to_html(&self.content),
90       media_type: Some(MediaTypeHtml::Html),
91       source: Some(Source::new(self.content.clone())),
92       published: Some(convert_datetime(self.published)),
93       updated: self.updated.map(convert_datetime),
94     };
95     Ok(note)
96   }
97
98   #[tracing::instrument(skip_all)]
99   async fn verify(
100     note: &ChatMessage,
101     expected_domain: &Url,
102     context: &Data<Self::DataType>,
103   ) -> Result<(), LemmyError> {
104     verify_domains_match(note.id.inner(), expected_domain)?;
105     verify_domains_match(note.attributed_to.inner(), note.id.inner())?;
106
107     check_apub_id_valid_with_strictness(note.id.inner(), false, context).await?;
108     let person = note.attributed_to.dereference(context).await?;
109     if person.banned {
110       return Err(LemmyErrorType::PersonIsBannedFromSite(
111         person.actor_id.to_string(),
112       ))?;
113     }
114     Ok(())
115   }
116
117   #[tracing::instrument(skip_all)]
118   async fn from_json(
119     note: ChatMessage,
120     context: &Data<Self::DataType>,
121   ) -> Result<ApubPrivateMessage, LemmyError> {
122     let creator = note.attributed_to.dereference(context).await?;
123     let recipient = note.to[0].dereference(context).await?;
124     check_person_block(creator.id, recipient.id, &mut context.pool()).await?;
125
126     let content = read_from_string_or_source(&note.content, &None, &note.source);
127     let content = sanitize_html(&content);
128
129     let form = PrivateMessageInsertForm {
130       creator_id: creator.id,
131       recipient_id: recipient.id,
132       content,
133       published: note.published.map(|u| u.naive_local()),
134       updated: note.updated.map(|u| u.naive_local()),
135       deleted: Some(false),
136       read: None,
137       ap_id: Some(note.id.into()),
138       local: Some(false),
139     };
140     let pm = PrivateMessage::create(&mut context.pool(), &form).await?;
141     Ok(pm.into())
142   }
143 }
144
145 #[cfg(test)]
146 mod tests {
147   #![allow(clippy::unwrap_used)]
148   #![allow(clippy::indexing_slicing)]
149
150   use super::*;
151   use crate::{
152     objects::{
153       instance::{tests::parse_lemmy_instance, ApubSite},
154       person::ApubPerson,
155       tests::init_context,
156     },
157     protocol::tests::file_to_json_object,
158   };
159   use assert_json_diff::assert_json_include;
160   use lemmy_db_schema::source::site::Site;
161   use serial_test::serial;
162
163   async fn prepare_comment_test(
164     url: &Url,
165     context: &Data<LemmyContext>,
166   ) -> (ApubPerson, ApubPerson, ApubSite) {
167     let context2 = context.reset_request_count();
168     let lemmy_person = file_to_json_object("assets/lemmy/objects/person.json").unwrap();
169     let site = parse_lemmy_instance(&context2).await;
170     ApubPerson::verify(&lemmy_person, url, &context2)
171       .await
172       .unwrap();
173     let person1 = ApubPerson::from_json(lemmy_person, &context2)
174       .await
175       .unwrap();
176     let pleroma_person = file_to_json_object("assets/pleroma/objects/person.json").unwrap();
177     let pleroma_url = Url::parse("https://queer.hacktivis.me/users/lanodan").unwrap();
178     ApubPerson::verify(&pleroma_person, &pleroma_url, &context2)
179       .await
180       .unwrap();
181     let person2 = ApubPerson::from_json(pleroma_person, &context2)
182       .await
183       .unwrap();
184     (person1, person2, site)
185   }
186
187   async fn cleanup(data: (ApubPerson, ApubPerson, ApubSite), context: &Data<LemmyContext>) {
188     Person::delete(&mut context.pool(), data.0.id)
189       .await
190       .unwrap();
191     Person::delete(&mut context.pool(), data.1.id)
192       .await
193       .unwrap();
194     Site::delete(&mut context.pool(), data.2.id).await.unwrap();
195   }
196
197   #[tokio::test]
198   #[serial]
199   async fn test_parse_lemmy_pm() {
200     let context = init_context().await;
201     let url = Url::parse("https://enterprise.lemmy.ml/private_message/1621").unwrap();
202     let data = prepare_comment_test(&url, &context).await;
203     let json: ChatMessage = file_to_json_object("assets/lemmy/objects/chat_message.json").unwrap();
204     ApubPrivateMessage::verify(&json, &url, &context)
205       .await
206       .unwrap();
207     let pm = ApubPrivateMessage::from_json(json.clone(), &context)
208       .await
209       .unwrap();
210
211     assert_eq!(pm.ap_id.clone(), url.into());
212     assert_eq!(pm.content.len(), 20);
213     assert_eq!(context.request_count(), 0);
214
215     let pm_id = pm.id;
216     let to_apub = pm.into_json(&context).await.unwrap();
217     assert_json_include!(actual: json, expected: to_apub);
218
219     PrivateMessage::delete(&mut context.pool(), pm_id)
220       .await
221       .unwrap();
222     cleanup(data, &context).await;
223   }
224
225   #[tokio::test]
226   #[serial]
227   async fn test_parse_pleroma_pm() {
228     let context = init_context().await;
229     let url = Url::parse("https://enterprise.lemmy.ml/private_message/1621").unwrap();
230     let data = prepare_comment_test(&url, &context).await;
231     let pleroma_url = Url::parse("https://queer.hacktivis.me/objects/2").unwrap();
232     let json = file_to_json_object("assets/pleroma/objects/chat_message.json").unwrap();
233     ApubPrivateMessage::verify(&json, &pleroma_url, &context)
234       .await
235       .unwrap();
236     let pm = ApubPrivateMessage::from_json(json, &context).await.unwrap();
237
238     assert_eq!(pm.ap_id, pleroma_url.into());
239     assert_eq!(pm.content.len(), 3);
240     assert_eq!(context.request_count(), 0);
241
242     PrivateMessage::delete(&mut context.pool(), pm.id)
243       .await
244       .unwrap();
245     cleanup(data, &context).await;
246   }
247 }