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