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