]> Untitled Git - lemmy.git/blob - crates/apub/src/activities/voting/vote.rs
Split activity table into sent and received parts (fixes #3103) (#3583)
[lemmy.git] / crates / apub / src / activities / voting / vote.rs
1 use crate::{
2   activities::{
3     generate_activity_id,
4     verify_person_in_community,
5     voting::{vote_comment, vote_post},
6   },
7   insert_received_activity,
8   objects::{community::ApubCommunity, person::ApubPerson},
9   protocol::{
10     activities::voting::vote::{Vote, VoteType},
11     InCommunity,
12   },
13   PostOrComment,
14 };
15 use activitypub_federation::{
16   config::Data,
17   fetch::object_id::ObjectId,
18   traits::{ActivityHandler, Actor},
19 };
20 use anyhow::anyhow;
21 use lemmy_api_common::context::LemmyContext;
22 use lemmy_db_schema::source::local_site::LocalSite;
23 use lemmy_utils::error::LemmyError;
24 use url::Url;
25
26 impl Vote {
27   pub(in crate::activities::voting) fn new(
28     object_id: ObjectId<PostOrComment>,
29     actor: &ApubPerson,
30     community: &ApubCommunity,
31     kind: VoteType,
32     context: &Data<LemmyContext>,
33   ) -> Result<Vote, LemmyError> {
34     Ok(Vote {
35       actor: actor.id().into(),
36       object: object_id,
37       kind: kind.clone(),
38       id: generate_activity_id(kind, &context.settings().get_protocol_and_hostname())?,
39       audience: Some(community.id().into()),
40     })
41   }
42 }
43
44 #[async_trait::async_trait]
45 impl ActivityHandler for Vote {
46   type DataType = LemmyContext;
47   type Error = LemmyError;
48
49   fn id(&self) -> &Url {
50     &self.id
51   }
52
53   fn actor(&self) -> &Url {
54     self.actor.inner()
55   }
56
57   #[tracing::instrument(skip_all)]
58   async fn verify(&self, context: &Data<LemmyContext>) -> Result<(), LemmyError> {
59     insert_received_activity(&self.id, context).await?;
60     let community = self.community(context).await?;
61     verify_person_in_community(&self.actor, &community, context).await?;
62     let enable_downvotes = LocalSite::read(&mut context.pool())
63       .await
64       .map(|l| l.enable_downvotes)
65       .unwrap_or(true);
66     if self.kind == VoteType::Dislike && !enable_downvotes {
67       return Err(anyhow!("Downvotes disabled").into());
68     }
69     Ok(())
70   }
71
72   #[tracing::instrument(skip_all)]
73   async fn receive(self, context: &Data<LemmyContext>) -> Result<(), LemmyError> {
74     let actor = self.actor.dereference(context).await?;
75     let object = self.object.dereference(context).await?;
76     match object {
77       PostOrComment::Post(p) => vote_post(&self.kind, actor, &p, context).await,
78       PostOrComment::Comment(c) => vote_comment(&self.kind, actor, &c, context).await,
79     }
80   }
81 }