]> Untitled Git - lemmy.git/blob - crates/apub/src/activities/create_or_update/comment.rs
e9e5673355510f1fb4b08c5c759627f651ceb95a
[lemmy.git] / crates / apub / src / activities / create_or_update / comment.rs
1 use crate::{
2   activities::{
3     check_community_deleted_or_removed,
4     community::send_activity_in_community,
5     generate_activity_id,
6     verify_is_public,
7     verify_person_in_community,
8   },
9   activity_lists::AnnouncableActivities,
10   insert_activity,
11   mentions::MentionOrValue,
12   objects::{comment::ApubComment, community::ApubCommunity, person::ApubPerson},
13   protocol::{
14     activities::{create_or_update::note::CreateOrUpdateNote, CreateOrUpdateType},
15     InCommunity,
16   },
17   SendActivity,
18 };
19 use activitypub_federation::{
20   config::Data,
21   fetch::object_id::ObjectId,
22   kinds::public,
23   protocol::verification::verify_domains_match,
24   traits::{ActivityHandler, Actor, Object},
25 };
26 use lemmy_api_common::{
27   build_response::send_local_notifs,
28   comment::{CommentResponse, CreateComment, EditComment},
29   context::LemmyContext,
30   utils::{check_post_deleted_or_removed, is_mod_or_admin},
31 };
32 use lemmy_db_schema::{
33   aggregates::structs::CommentAggregates,
34   newtypes::PersonId,
35   source::{
36     comment::{Comment, CommentLike, CommentLikeForm},
37     community::Community,
38     person::Person,
39     post::Post,
40   },
41   traits::{Crud, Likeable},
42 };
43 use lemmy_utils::{error::LemmyError, utils::mention::scrape_text_for_mentions};
44 use url::Url;
45
46 #[async_trait::async_trait]
47 impl SendActivity for CreateComment {
48   type Response = CommentResponse;
49
50   async fn send_activity(
51     _request: &Self,
52     response: &Self::Response,
53     context: &Data<LemmyContext>,
54   ) -> Result<(), LemmyError> {
55     CreateOrUpdateNote::send(
56       &response.comment_view.comment,
57       response.comment_view.creator.id,
58       CreateOrUpdateType::Create,
59       context,
60     )
61     .await
62   }
63 }
64
65 #[async_trait::async_trait]
66 impl SendActivity for EditComment {
67   type Response = CommentResponse;
68
69   async fn send_activity(
70     _request: &Self,
71     response: &Self::Response,
72     context: &Data<LemmyContext>,
73   ) -> Result<(), LemmyError> {
74     CreateOrUpdateNote::send(
75       &response.comment_view.comment,
76       response.comment_view.creator.id,
77       CreateOrUpdateType::Update,
78       context,
79     )
80     .await
81   }
82 }
83
84 impl CreateOrUpdateNote {
85   #[tracing::instrument(skip(comment, person_id, kind, context))]
86   async fn send(
87     comment: &Comment,
88     person_id: PersonId,
89     kind: CreateOrUpdateType,
90     context: &Data<LemmyContext>,
91   ) -> Result<(), LemmyError> {
92     // TODO: might be helpful to add a comment method to retrieve community directly
93     let post_id = comment.post_id;
94     let post = Post::read(context.pool(), post_id).await?;
95     let community_id = post.community_id;
96     let person: ApubPerson = Person::read(context.pool(), person_id).await?.into();
97     let community: ApubCommunity = Community::read(context.pool(), community_id).await?.into();
98
99     let id = generate_activity_id(
100       kind.clone(),
101       &context.settings().get_protocol_and_hostname(),
102     )?;
103     let note = ApubComment(comment.clone()).into_json(context).await?;
104
105     let create_or_update = CreateOrUpdateNote {
106       actor: person.id().into(),
107       to: vec![public()],
108       cc: note.cc.clone(),
109       tag: note.tag.clone(),
110       object: note,
111       kind,
112       id: id.clone(),
113       audience: Some(community.id().into()),
114     };
115
116     let tagged_users: Vec<ObjectId<ApubPerson>> = create_or_update
117       .tag
118       .iter()
119       .filter_map(|t| {
120         if let MentionOrValue::Mention(t) = t {
121           Some(t)
122         } else {
123           None
124         }
125       })
126       .map(|t| t.href.clone())
127       .map(ObjectId::from)
128       .collect();
129     let mut inboxes = vec![];
130     for t in tagged_users {
131       let person = t.dereference(context).await?;
132       inboxes.push(person.shared_inbox_or_inbox());
133     }
134
135     let activity = AnnouncableActivities::CreateOrUpdateComment(create_or_update);
136     send_activity_in_community(activity, &person, &community, inboxes, false, context).await
137   }
138 }
139
140 #[async_trait::async_trait]
141 impl ActivityHandler for CreateOrUpdateNote {
142   type DataType = LemmyContext;
143   type Error = LemmyError;
144
145   fn id(&self) -> &Url {
146     &self.id
147   }
148
149   fn actor(&self) -> &Url {
150     self.actor.inner()
151   }
152
153   #[tracing::instrument(skip_all)]
154   async fn verify(&self, context: &Data<Self::DataType>) -> Result<(), LemmyError> {
155     verify_is_public(&self.to, &self.cc)?;
156     let post = self.object.get_parents(context).await?.0;
157     let community = self.community(context).await?;
158
159     verify_person_in_community(&self.actor, &community, context).await?;
160     verify_domains_match(self.actor.inner(), self.object.id.inner())?;
161     check_community_deleted_or_removed(&community)?;
162     check_post_deleted_or_removed(&post)?;
163
164     ApubComment::verify(&self.object, self.actor.inner(), context).await?;
165     Ok(())
166   }
167
168   #[tracing::instrument(skip_all)]
169   async fn receive(self, context: &Data<Self::DataType>) -> Result<(), LemmyError> {
170     insert_activity(&self.id, &self, false, false, context).await?;
171     // Need to do this check here instead of Note::from_json because we need the person who
172     // send the activity, not the comment author.
173     let existing_comment = self.object.id.dereference_local(context).await.ok();
174     if let (Some(distinguished), Some(existing_comment)) =
175       (self.object.distinguished, existing_comment)
176     {
177       if distinguished != existing_comment.distinguished {
178         let creator = self.actor.dereference(context).await?;
179         let (post, _) = self.object.get_parents(context).await?;
180         is_mod_or_admin(context.pool(), creator.id, post.community_id).await?;
181       }
182     }
183
184     let comment = ApubComment::from_json(self.object, context).await?;
185
186     // author likes their own comment by default
187     let like_form = CommentLikeForm {
188       comment_id: comment.id,
189       post_id: comment.post_id,
190       person_id: comment.creator_id,
191       score: 1,
192     };
193     CommentLike::like(context.pool(), &like_form).await?;
194
195     // Calculate initial hot_rank
196     CommentAggregates::update_hot_rank(context.pool(), comment.id).await?;
197
198     let do_send_email = self.kind == CreateOrUpdateType::Create;
199     let post_id = comment.post_id;
200     let post = Post::read(context.pool(), post_id).await?;
201     let actor = self.actor.dereference(context).await?;
202
203     // Note:
204     // Although mentions could be gotten from the post tags (they are included there), or the ccs,
205     // Its much easier to scrape them from the comment body, since the API has to do that
206     // anyway.
207     // TODO: for compatibility with other projects, it would be much better to read this from cc or tags
208     let mentions = scrape_text_for_mentions(&comment.content);
209     send_local_notifs(mentions, &comment.0, &actor, &post, do_send_email, context).await?;
210     Ok(())
211   }
212 }