]> Untitled Git - lemmy.git/blob - crates/apub/src/activities/create_or_update/comment.rs
Split activity table into sent and received parts (fixes #3103) (#3583)
[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_received_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(&mut context.pool(), post_id).await?;
95     let community_id = post.community_id;
96     let person: ApubPerson = Person::read(&mut context.pool(), person_id).await?.into();
97     let community: ApubCommunity = Community::read(&mut context.pool(), community_id)
98       .await?
99       .into();
100
101     let id = generate_activity_id(
102       kind.clone(),
103       &context.settings().get_protocol_and_hostname(),
104     )?;
105     let note = ApubComment(comment.clone()).into_json(context).await?;
106
107     let create_or_update = CreateOrUpdateNote {
108       actor: person.id().into(),
109       to: vec![public()],
110       cc: note.cc.clone(),
111       tag: note.tag.clone(),
112       object: note,
113       kind,
114       id: id.clone(),
115       audience: Some(community.id().into()),
116     };
117
118     let tagged_users: Vec<ObjectId<ApubPerson>> = create_or_update
119       .tag
120       .iter()
121       .filter_map(|t| {
122         if let MentionOrValue::Mention(t) = t {
123           Some(t)
124         } else {
125           None
126         }
127       })
128       .map(|t| t.href.clone())
129       .map(ObjectId::from)
130       .collect();
131     let mut inboxes = vec![];
132     for t in tagged_users {
133       let person = t.dereference(context).await?;
134       inboxes.push(person.shared_inbox_or_inbox());
135     }
136
137     let activity = AnnouncableActivities::CreateOrUpdateComment(create_or_update);
138     send_activity_in_community(activity, &person, &community, inboxes, false, context).await
139   }
140 }
141
142 #[async_trait::async_trait]
143 impl ActivityHandler for CreateOrUpdateNote {
144   type DataType = LemmyContext;
145   type Error = LemmyError;
146
147   fn id(&self) -> &Url {
148     &self.id
149   }
150
151   fn actor(&self) -> &Url {
152     self.actor.inner()
153   }
154
155   #[tracing::instrument(skip_all)]
156   async fn verify(&self, context: &Data<Self::DataType>) -> Result<(), LemmyError> {
157     insert_received_activity(&self.id, context).await?;
158     verify_is_public(&self.to, &self.cc)?;
159     let post = self.object.get_parents(context).await?.0;
160     let community = self.community(context).await?;
161
162     verify_person_in_community(&self.actor, &community, context).await?;
163     verify_domains_match(self.actor.inner(), self.object.id.inner())?;
164     check_community_deleted_or_removed(&community)?;
165     check_post_deleted_or_removed(&post)?;
166
167     ApubComment::verify(&self.object, self.actor.inner(), context).await?;
168     Ok(())
169   }
170
171   #[tracing::instrument(skip_all)]
172   async fn receive(self, context: &Data<Self::DataType>) -> Result<(), LemmyError> {
173     // Need to do this check here instead of Note::from_json because we need the person who
174     // send the activity, not the comment author.
175     let existing_comment = self.object.id.dereference_local(context).await.ok();
176     if let (Some(distinguished), Some(existing_comment)) =
177       (self.object.distinguished, existing_comment)
178     {
179       if distinguished != existing_comment.distinguished {
180         let creator = self.actor.dereference(context).await?;
181         let (post, _) = self.object.get_parents(context).await?;
182         is_mod_or_admin(&mut context.pool(), creator.id, post.community_id).await?;
183       }
184     }
185
186     let comment = ApubComment::from_json(self.object, context).await?;
187
188     // author likes their own comment by default
189     let like_form = CommentLikeForm {
190       comment_id: comment.id,
191       post_id: comment.post_id,
192       person_id: comment.creator_id,
193       score: 1,
194     };
195     CommentLike::like(&mut context.pool(), &like_form).await?;
196
197     // Calculate initial hot_rank
198     CommentAggregates::update_hot_rank(&mut context.pool(), comment.id).await?;
199
200     let do_send_email = self.kind == CreateOrUpdateType::Create;
201     let post_id = comment.post_id;
202     let post = Post::read(&mut context.pool(), post_id).await?;
203     let actor = self.actor.dereference(context).await?;
204
205     // Note:
206     // Although mentions could be gotten from the post tags (they are included there), or the ccs,
207     // Its much easier to scrape them from the comment body, since the API has to do that
208     // anyway.
209     // TODO: for compatibility with other projects, it would be much better to read this from cc or tags
210     let mentions = scrape_text_for_mentions(&comment.content);
211     send_local_notifs(mentions, &comment.0, &actor, &post, do_send_email, context).await?;
212     Ok(())
213   }
214 }