]> Untitled Git - lemmy.git/blob - crates/apub/src/activities/create_or_update/post.rs
Extract Activitypub logic into separate library (#2288)
[lemmy.git] / crates / apub / src / activities / create_or_update / post.rs
1 use crate::{
2   activities::{
3     check_community_deleted_or_removed,
4     community::{announce::GetCommunity, send_activity_in_community},
5     generate_activity_id,
6     verify_is_public,
7     verify_mod_action,
8     verify_person_in_community,
9   },
10   activity_lists::AnnouncableActivities,
11   objects::{community::ApubCommunity, person::ApubPerson, post::ApubPost},
12   protocol::activities::{create_or_update::post::CreateOrUpdatePost, CreateOrUpdateType},
13   ActorType,
14 };
15 use activitypub_federation::{
16   core::object_id::ObjectId,
17   data::Data,
18   traits::{ActivityHandler, ApubObject},
19   utils::{verify_domains_match, verify_urls_match},
20 };
21 use activitystreams_kinds::public;
22 use lemmy_api_common::utils::blocking;
23 use lemmy_db_schema::{
24   source::{
25     community::Community,
26     post::{PostLike, PostLikeForm},
27   },
28   traits::{Crud, Likeable},
29 };
30 use lemmy_utils::error::LemmyError;
31 use lemmy_websocket::{send::send_post_ws_message, LemmyContext, UserOperationCrud};
32 use url::Url;
33
34 impl CreateOrUpdatePost {
35   pub(crate) async fn new(
36     post: ApubPost,
37     actor: &ApubPerson,
38     community: &ApubCommunity,
39     kind: CreateOrUpdateType,
40     context: &LemmyContext,
41   ) -> Result<CreateOrUpdatePost, LemmyError> {
42     let id = generate_activity_id(
43       kind.clone(),
44       &context.settings().get_protocol_and_hostname(),
45     )?;
46     Ok(CreateOrUpdatePost {
47       actor: ObjectId::new(actor.actor_id()),
48       to: vec![public()],
49       object: post.into_apub(context).await?,
50       cc: vec![community.actor_id()],
51       kind,
52       id: id.clone(),
53       unparsed: Default::default(),
54     })
55   }
56
57   #[tracing::instrument(skip_all)]
58   pub async fn send(
59     post: ApubPost,
60     actor: &ApubPerson,
61     kind: CreateOrUpdateType,
62     context: &LemmyContext,
63   ) -> Result<(), LemmyError> {
64     let community_id = post.community_id;
65     let community: ApubCommunity = blocking(context.pool(), move |conn| {
66       Community::read(conn, community_id)
67     })
68     .await??
69     .into();
70
71     let create_or_update = CreateOrUpdatePost::new(post, actor, &community, kind, context).await?;
72     let id = create_or_update.id.clone();
73     let activity = AnnouncableActivities::CreateOrUpdatePost(Box::new(create_or_update));
74     send_activity_in_community(activity, &id, actor, &community, vec![], context).await
75   }
76 }
77
78 #[async_trait::async_trait(?Send)]
79 impl ActivityHandler for CreateOrUpdatePost {
80   type DataType = LemmyContext;
81   type Error = LemmyError;
82
83   fn id(&self) -> &Url {
84     &self.id
85   }
86
87   fn actor(&self) -> &Url {
88     self.actor.inner()
89   }
90
91   #[tracing::instrument(skip_all)]
92   async fn verify(
93     &self,
94     context: &Data<LemmyContext>,
95     request_counter: &mut i32,
96   ) -> Result<(), LemmyError> {
97     verify_is_public(&self.to, &self.cc)?;
98     let community = self.get_community(context, request_counter).await?;
99     verify_person_in_community(&self.actor, &community, context, request_counter).await?;
100     check_community_deleted_or_removed(&community)?;
101
102     match self.kind {
103       CreateOrUpdateType::Create => {
104         verify_domains_match(self.actor.inner(), self.object.id.inner())?;
105         verify_urls_match(self.actor.inner(), self.object.creator()?.inner())?;
106         // Check that the post isnt locked or stickied, as that isnt possible for newly created posts.
107         // However, when fetching a remote post we generate a new create activity with the current
108         // locked/stickied value, so this check may fail. So only check if its a local community,
109         // because then we will definitely receive all create and update activities separately.
110         let is_stickied_or_locked =
111           self.object.stickied == Some(true) || self.object.comments_enabled == Some(false);
112         if community.local && is_stickied_or_locked {
113           return Err(LemmyError::from_message(
114             "New post cannot be stickied or locked",
115           ));
116         }
117       }
118       CreateOrUpdateType::Update => {
119         let is_mod_action = self.object.is_mod_action(context).await?;
120         if is_mod_action {
121           verify_mod_action(
122             &self.actor,
123             self.object.id.inner(),
124             &community,
125             context,
126             request_counter,
127           )
128           .await?;
129         } else {
130           verify_domains_match(self.actor.inner(), self.object.id.inner())?;
131           verify_urls_match(self.actor.inner(), self.object.creator()?.inner())?;
132         }
133       }
134     }
135     ApubPost::verify(&self.object, self.actor.inner(), context, request_counter).await?;
136     Ok(())
137   }
138
139   #[tracing::instrument(skip_all)]
140   async fn receive(
141     self,
142     context: &Data<LemmyContext>,
143     request_counter: &mut i32,
144   ) -> Result<(), LemmyError> {
145     let post = ApubPost::from_apub(self.object, context, request_counter).await?;
146
147     // author likes their own post by default
148     let like_form = PostLikeForm {
149       post_id: post.id,
150       person_id: post.creator_id,
151       score: 1,
152     };
153     blocking(context.pool(), move |conn: &'_ _| {
154       PostLike::like(conn, &like_form)
155     })
156     .await??;
157
158     let notif_type = match self.kind {
159       CreateOrUpdateType::Create => UserOperationCrud::CreatePost,
160       CreateOrUpdateType::Update => UserOperationCrud::EditPost,
161     };
162     send_post_ws_message(post.id, notif_type, None, None, context).await?;
163     Ok(())
164   }
165 }
166
167 #[async_trait::async_trait(?Send)]
168 impl GetCommunity for CreateOrUpdatePost {
169   #[tracing::instrument(skip_all)]
170   async fn get_community(
171     &self,
172     context: &LemmyContext,
173     request_counter: &mut i32,
174   ) -> Result<ApubCommunity, LemmyError> {
175     self
176       .object
177       .extract_community(context, request_counter)
178       .await
179   }
180 }