]> Untitled Git - lemmy.git/blob - crates/apub/src/activities/following/undo_follow.rs
Merge pull request #1897 from LemmyNet/mastodon-compat
[lemmy.git] / crates / apub / src / activities / following / undo_follow.rs
1 use crate::{
2   activities::{generate_activity_id, send_lemmy_activity, verify_activity, verify_person},
3   objects::{community::ApubCommunity, person::ApubPerson},
4   protocol::activities::following::{follow::FollowCommunity, undo_follow::UndoFollowCommunity},
5 };
6 use activitystreams::activity::kind::UndoType;
7 use lemmy_api_common::blocking;
8 use lemmy_apub_lib::{
9   data::Data,
10   object_id::ObjectId,
11   traits::{ActivityHandler, ActorType},
12   verify::verify_urls_match,
13 };
14 use lemmy_db_schema::{
15   source::community::{CommunityFollower, CommunityFollowerForm},
16   traits::Followable,
17 };
18 use lemmy_utils::LemmyError;
19 use lemmy_websocket::LemmyContext;
20
21 impl UndoFollowCommunity {
22   pub async fn send(
23     actor: &ApubPerson,
24     community: &ApubCommunity,
25     context: &LemmyContext,
26   ) -> Result<(), LemmyError> {
27     let object = FollowCommunity::new(actor, community, context)?;
28     let undo = UndoFollowCommunity {
29       actor: ObjectId::new(actor.actor_id()),
30       object,
31       kind: UndoType::Undo,
32       id: generate_activity_id(
33         UndoType::Undo,
34         &context.settings().get_protocol_and_hostname(),
35       )?,
36       unparsed: Default::default(),
37     };
38     let inbox = vec![community.shared_inbox_or_inbox_url()];
39     send_lemmy_activity(context, &undo, &undo.id, actor, inbox, true).await
40   }
41 }
42
43 #[async_trait::async_trait(?Send)]
44 impl ActivityHandler for UndoFollowCommunity {
45   type DataType = LemmyContext;
46   async fn verify(
47     &self,
48     context: &Data<LemmyContext>,
49     request_counter: &mut i32,
50   ) -> Result<(), LemmyError> {
51     verify_activity(&self.id, self.actor.inner(), &context.settings())?;
52     verify_urls_match(self.actor.inner(), self.object.actor.inner())?;
53     verify_person(&self.actor, context, request_counter).await?;
54     self.object.verify(context, request_counter).await?;
55     Ok(())
56   }
57
58   async fn receive(
59     self,
60     context: &Data<LemmyContext>,
61     request_counter: &mut i32,
62   ) -> Result<(), LemmyError> {
63     let person = self.actor.dereference(context, request_counter).await?;
64     let community = self
65       .object
66       .object
67       .dereference(context, request_counter)
68       .await?;
69
70     let community_follower_form = CommunityFollowerForm {
71       community_id: community.id,
72       person_id: person.id,
73       pending: false,
74     };
75
76     // This will fail if they aren't a follower, but ignore the error.
77     blocking(context.pool(), move |conn| {
78       CommunityFollower::unfollow(conn, &community_follower_form).ok()
79     })
80     .await?;
81     Ok(())
82   }
83 }