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