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