]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/private_message.rs
c986e576e818d959d203eb8af270a625e2f1f6c2
[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   use super::*;
140   use crate::{
141     objects::{
142       instance::{tests::parse_lemmy_instance, ApubSite},
143       person::ApubPerson,
144       tests::init_context,
145     },
146     protocol::tests::file_to_json_object,
147   };
148   use assert_json_diff::assert_json_include;
149   use lemmy_db_schema::source::site::Site;
150   use serial_test::serial;
151
152   async fn prepare_comment_test(
153     url: &Url,
154     context: &Data<LemmyContext>,
155   ) -> (ApubPerson, ApubPerson, ApubSite) {
156     let context2 = context.reset_request_count();
157     let lemmy_person = file_to_json_object("assets/lemmy/objects/person.json").unwrap();
158     let site = parse_lemmy_instance(&context2).await;
159     ApubPerson::verify(&lemmy_person, url, &context2)
160       .await
161       .unwrap();
162     let person1 = ApubPerson::from_json(lemmy_person, &context2)
163       .await
164       .unwrap();
165     let pleroma_person = file_to_json_object("assets/pleroma/objects/person.json").unwrap();
166     let pleroma_url = Url::parse("https://queer.hacktivis.me/users/lanodan").unwrap();
167     ApubPerson::verify(&pleroma_person, &pleroma_url, &context2)
168       .await
169       .unwrap();
170     let person2 = ApubPerson::from_json(pleroma_person, &context2)
171       .await
172       .unwrap();
173     (person1, person2, site)
174   }
175
176   async fn cleanup(data: (ApubPerson, ApubPerson, ApubSite), context: &Data<LemmyContext>) {
177     Person::delete(&mut context.pool(), data.0.id)
178       .await
179       .unwrap();
180     Person::delete(&mut context.pool(), data.1.id)
181       .await
182       .unwrap();
183     Site::delete(&mut context.pool(), data.2.id).await.unwrap();
184   }
185
186   #[tokio::test]
187   #[serial]
188   async fn test_parse_lemmy_pm() {
189     let context = init_context().await;
190     let url = Url::parse("https://enterprise.lemmy.ml/private_message/1621").unwrap();
191     let data = prepare_comment_test(&url, &context).await;
192     let json: ChatMessage = file_to_json_object("assets/lemmy/objects/chat_message.json").unwrap();
193     ApubPrivateMessage::verify(&json, &url, &context)
194       .await
195       .unwrap();
196     let pm = ApubPrivateMessage::from_json(json.clone(), &context)
197       .await
198       .unwrap();
199
200     assert_eq!(pm.ap_id.clone(), url.into());
201     assert_eq!(pm.content.len(), 20);
202     assert_eq!(context.request_count(), 0);
203
204     let pm_id = pm.id;
205     let to_apub = pm.into_json(&context).await.unwrap();
206     assert_json_include!(actual: json, expected: to_apub);
207
208     PrivateMessage::delete(&mut context.pool(), pm_id)
209       .await
210       .unwrap();
211     cleanup(data, &context).await;
212   }
213
214   #[tokio::test]
215   #[serial]
216   async fn test_parse_pleroma_pm() {
217     let context = init_context().await;
218     let url = Url::parse("https://enterprise.lemmy.ml/private_message/1621").unwrap();
219     let data = prepare_comment_test(&url, &context).await;
220     let pleroma_url = Url::parse("https://queer.hacktivis.me/objects/2").unwrap();
221     let json = file_to_json_object("assets/pleroma/objects/chat_message.json").unwrap();
222     ApubPrivateMessage::verify(&json, &pleroma_url, &context)
223       .await
224       .unwrap();
225     let pm = ApubPrivateMessage::from_json(json, &context).await.unwrap();
226
227     assert_eq!(pm.ap_id, pleroma_url.into());
228     assert_eq!(pm.content.len(), 3);
229     assert_eq!(context.request_count(), 0);
230
231     PrivateMessage::delete(&mut context.pool(), pm.id)
232       .await
233       .unwrap();
234     cleanup(data, &context).await;
235   }
236 }