]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/comment.rs
Creating default DB forms. Fixes #1511
[lemmy.git] / crates / apub / src / objects / comment.rs
1 use crate::{
2   extensions::context::lemmy_context,
3   fetcher::objects::{get_or_fetch_and_insert_comment, get_or_fetch_and_insert_post},
4   objects::{
5     check_object_domain,
6     check_object_for_community_or_site_ban,
7     create_tombstone,
8     get_object_from_apub,
9     get_or_fetch_and_upsert_person,
10     get_source_markdown_value,
11     set_content_and_source,
12     FromApub,
13     FromApubToForm,
14     ToApub,
15   },
16   NoteExt,
17 };
18 use activitystreams::{
19   object::{kind::NoteType, ApObject, Note, Tombstone},
20   prelude::*,
21   public,
22 };
23 use anyhow::{anyhow, Context};
24 use lemmy_api_structs::blocking;
25 use lemmy_db_queries::{Crud, DbPool};
26 use lemmy_db_schema::{
27   source::{
28     comment::{Comment, CommentForm},
29     person::Person,
30     post::Post,
31   },
32   CommentId,
33 };
34 use lemmy_utils::{
35   location_info,
36   utils::{convert_datetime, remove_slurs},
37   LemmyError,
38 };
39 use lemmy_websocket::LemmyContext;
40 use url::Url;
41
42 #[async_trait::async_trait(?Send)]
43 impl ToApub for Comment {
44   type ApubType = NoteExt;
45
46   async fn to_apub(&self, pool: &DbPool) -> Result<NoteExt, LemmyError> {
47     let mut comment = ApObject::new(Note::new());
48
49     let creator_id = self.creator_id;
50     let creator = blocking(pool, move |conn| Person::read(conn, creator_id)).await??;
51
52     let post_id = self.post_id;
53     let post = blocking(pool, move |conn| Post::read(conn, post_id)).await??;
54
55     // Add a vector containing some important info to the "in_reply_to" field
56     // [post_ap_id, Option(parent_comment_ap_id)]
57     let mut in_reply_to_vec = vec![post.ap_id.into_inner()];
58
59     if let Some(parent_id) = self.parent_id {
60       let parent_comment = blocking(pool, move |conn| Comment::read(conn, parent_id)).await??;
61
62       in_reply_to_vec.push(parent_comment.ap_id.into_inner());
63     }
64
65     comment
66       // Not needed when the Post is embedded in a collection (like for community outbox)
67       .set_many_contexts(lemmy_context()?)
68       .set_id(self.ap_id.to_owned().into_inner())
69       .set_published(convert_datetime(self.published))
70       .set_to(public())
71       .set_many_in_reply_tos(in_reply_to_vec)
72       .set_attributed_to(creator.actor_id.into_inner());
73
74     set_content_and_source(&mut comment, &self.content)?;
75
76     if let Some(u) = self.updated {
77       comment.set_updated(convert_datetime(u));
78     }
79
80     Ok(comment)
81   }
82
83   fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
84     create_tombstone(
85       self.deleted,
86       self.ap_id.to_owned().into(),
87       self.updated,
88       NoteType::Note,
89     )
90   }
91 }
92
93 #[async_trait::async_trait(?Send)]
94 impl FromApub for Comment {
95   type ApubType = NoteExt;
96
97   /// Converts a `Note` to `Comment`.
98   ///
99   /// If the parent community, post and comment(s) are not known locally, these are also fetched.
100   async fn from_apub(
101     note: &NoteExt,
102     context: &LemmyContext,
103     expected_domain: Url,
104     request_counter: &mut i32,
105   ) -> Result<Comment, LemmyError> {
106     let comment: Comment =
107       get_object_from_apub(note, context, expected_domain, request_counter).await?;
108
109     let post_id = comment.post_id;
110     let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
111     check_object_for_community_or_site_ban(note, post.community_id, context, request_counter)
112       .await?;
113     if post.locked {
114       // This is not very efficient because a comment gets inserted just to be deleted right
115       // afterwards, but it seems to be the easiest way to implement it.
116       blocking(context.pool(), move |conn| {
117         Comment::delete(conn, comment.id)
118       })
119       .await??;
120       Err(anyhow!("Post is locked").into())
121     } else {
122       Ok(comment)
123     }
124   }
125 }
126
127 #[async_trait::async_trait(?Send)]
128 impl FromApubToForm<NoteExt> for CommentForm {
129   async fn from_apub(
130     note: &NoteExt,
131     context: &LemmyContext,
132     expected_domain: Url,
133     request_counter: &mut i32,
134   ) -> Result<CommentForm, LemmyError> {
135     let creator_actor_id = &note
136       .attributed_to()
137       .context(location_info!())?
138       .as_single_xsd_any_uri()
139       .context(location_info!())?;
140
141     let creator =
142       get_or_fetch_and_upsert_person(creator_actor_id, context, request_counter).await?;
143
144     let mut in_reply_tos = note
145       .in_reply_to()
146       .as_ref()
147       .context(location_info!())?
148       .as_many()
149       .context(location_info!())?
150       .iter()
151       .map(|i| i.as_xsd_any_uri().context(""));
152     let post_ap_id = in_reply_tos.next().context(location_info!())??;
153
154     // This post, or the parent comment might not yet exist on this server yet, fetch them.
155     let post = get_or_fetch_and_insert_post(&post_ap_id, context, request_counter).await?;
156
157     // The 2nd item, if it exists, is the parent comment apub_id
158     // For deeply nested comments, FromApub automatically gets called recursively
159     let parent_id: Option<CommentId> = match in_reply_tos.next() {
160       Some(parent_comment_uri) => {
161         let parent_comment_ap_id = &parent_comment_uri?;
162         let parent_comment =
163           get_or_fetch_and_insert_comment(&parent_comment_ap_id, context, request_counter).await?;
164
165         Some(parent_comment.id)
166       }
167       None => None,
168     };
169
170     let content = get_source_markdown_value(note)?.context(location_info!())?;
171     let content_slurs_removed = remove_slurs(&content);
172
173     Ok(CommentForm {
174       creator_id: creator.id,
175       post_id: post.id,
176       parent_id,
177       content: content_slurs_removed,
178       removed: None,
179       read: None,
180       published: note.published().map(|u| u.to_owned().naive_local()),
181       updated: note.updated().map(|u| u.to_owned().naive_local()),
182       deleted: None,
183       ap_id: Some(check_object_domain(note, expected_domain)?),
184       local: Some(false),
185     })
186   }
187 }