]> Untitled Git - lemmy.git/blob - crates/apub_receive/src/activities/following/undo.rs
Apub inbox rewrite (#1652)
[lemmy.git] / crates / apub_receive / src / activities / following / undo.rs
1 use crate::activities::{following::follow::FollowCommunity, verify_activity, verify_person};
2 use activitystreams::activity::kind::UndoType;
3 use lemmy_api_common::blocking;
4 use lemmy_apub::fetcher::{
5   community::get_or_fetch_and_upsert_community,
6   person::get_or_fetch_and_upsert_person,
7 };
8 use lemmy_apub_lib::{verify_urls_match, ActivityCommonFields, ActivityHandler};
9 use lemmy_db_queries::Followable;
10 use lemmy_db_schema::source::community::{CommunityFollower, CommunityFollowerForm};
11 use lemmy_utils::LemmyError;
12 use lemmy_websocket::LemmyContext;
13 use url::Url;
14
15 #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
16 #[serde(rename_all = "camelCase")]
17 pub struct UndoFollowCommunity {
18   to: Url,
19   object: FollowCommunity,
20   #[serde(rename = "type")]
21   kind: UndoType,
22   #[serde(flatten)]
23   common: ActivityCommonFields,
24 }
25
26 #[async_trait::async_trait(?Send)]
27 impl ActivityHandler for UndoFollowCommunity {
28   async fn verify(
29     &self,
30     context: &LemmyContext,
31     request_counter: &mut i32,
32   ) -> Result<(), LemmyError> {
33     verify_activity(self.common())?;
34     verify_urls_match(&self.to, &self.object.object)?;
35     verify_urls_match(&self.common.actor, &self.object.common.actor)?;
36     verify_person(&self.common.actor, context, request_counter).await?;
37     self.object.verify(context, request_counter).await?;
38     Ok(())
39   }
40
41   async fn receive(
42     &self,
43     context: &LemmyContext,
44     request_counter: &mut i32,
45   ) -> Result<(), LemmyError> {
46     let actor =
47       get_or_fetch_and_upsert_person(&self.common.actor, context, request_counter).await?;
48     let community = get_or_fetch_and_upsert_community(&self.to, context, request_counter).await?;
49
50     let community_follower_form = CommunityFollowerForm {
51       community_id: community.id,
52       person_id: actor.id,
53       pending: false,
54     };
55
56     // This will fail if they aren't a follower, but ignore the error.
57     blocking(context.pool(), move |conn| {
58       CommunityFollower::unfollow(conn, &community_follower_form).ok()
59     })
60     .await?;
61     Ok(())
62   }
63
64   fn common(&self) -> &ActivityCommonFields {
65     &self.common
66   }
67 }