]> Untitled Git - lemmy.git/blob - crates/apub/src/activities/following/follow.rs
Merge pull request #1660 from LemmyNet/merge-apub-crates
[lemmy.git] / crates / apub / src / activities / following / follow.rs
1 use crate::{
2   activities::{verify_activity, verify_person},
3   fetcher::{community::get_or_fetch_and_upsert_community, person::get_or_fetch_and_upsert_person},
4   CommunityType,
5 };
6 use activitystreams::{
7   activity::{kind::FollowType, Follow},
8   base::{AnyBase, ExtendsExt},
9 };
10 use anyhow::Context;
11 use lemmy_api_common::blocking;
12 use lemmy_apub_lib::{verify_urls_match, ActivityCommonFields, ActivityHandler};
13 use lemmy_db_queries::Followable;
14 use lemmy_db_schema::source::community::{CommunityFollower, CommunityFollowerForm};
15 use lemmy_utils::{location_info, LemmyError};
16 use lemmy_websocket::LemmyContext;
17 use url::Url;
18
19 #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
20 #[serde(rename_all = "camelCase")]
21 pub struct FollowCommunity {
22   pub(in crate::activities::following) to: Url,
23   pub(in crate::activities::following) object: Url,
24   #[serde(rename = "type")]
25   kind: FollowType,
26   #[serde(flatten)]
27   pub(in crate::activities::following) common: ActivityCommonFields,
28 }
29
30 #[async_trait::async_trait(?Send)]
31 impl ActivityHandler for FollowCommunity {
32   async fn verify(
33     &self,
34     context: &LemmyContext,
35     request_counter: &mut i32,
36   ) -> Result<(), LemmyError> {
37     verify_activity(self.common())?;
38     verify_urls_match(&self.to, &self.object)?;
39     verify_person(&self.common.actor, context, request_counter).await?;
40     Ok(())
41   }
42
43   async fn receive(
44     &self,
45     context: &LemmyContext,
46     request_counter: &mut i32,
47   ) -> Result<(), LemmyError> {
48     let actor =
49       get_or_fetch_and_upsert_person(&self.common.actor, context, request_counter).await?;
50     let community =
51       get_or_fetch_and_upsert_community(&self.object, context, request_counter).await?;
52     let community_follower_form = CommunityFollowerForm {
53       community_id: community.id,
54       person_id: actor.id,
55       pending: false,
56     };
57
58     // This will fail if they're already a follower, but ignore the error.
59     blocking(context.pool(), move |conn| {
60       CommunityFollower::follow(conn, &community_follower_form).ok()
61     })
62     .await?;
63
64     // TODO: avoid the conversion and pass our own follow struct directly
65     let anybase = AnyBase::from_arbitrary_json(serde_json::to_string(self)?)?;
66     let anybase = Follow::from_any_base(anybase)?.context(location_info!())?;
67     community.send_accept_follow(anybase, context).await
68   }
69
70   fn common(&self) -> &ActivityCommonFields {
71     &self.common
72   }
73 }