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