]> Untitled Git - lemmy.git/blob - crates/apub/src/protocol/activities/voting/vote.rs
add enable_federated_downvotes site option
[lemmy.git] / crates / apub / src / protocol / activities / voting / vote.rs
1 use crate::{
2   activities::verify_community_matches,
3   fetcher::post_or_comment::PostOrComment,
4   objects::{community::ApubCommunity, person::ApubPerson},
5   protocol::InCommunity,
6 };
7 use activitypub_federation::{config::Data, fetch::object_id::ObjectId};
8 use lemmy_api_common::context::LemmyContext;
9 use lemmy_utils::error::{LemmyError, LemmyErrorType};
10 use serde::{Deserialize, Serialize};
11 use std::convert::TryFrom;
12 use strum_macros::Display;
13 use url::Url;
14
15 #[derive(Clone, Debug, Deserialize, Serialize)]
16 #[serde(rename_all = "camelCase")]
17 pub struct Vote {
18   pub(crate) actor: ObjectId<ApubPerson>,
19   pub(crate) object: ObjectId<PostOrComment>,
20   #[serde(rename = "type")]
21   pub(crate) kind: VoteType,
22   pub(crate) id: Url,
23   pub(crate) audience: Option<ObjectId<ApubCommunity>>,
24 }
25
26 #[derive(Clone, Debug, Display, Deserialize, Serialize, PartialEq, Eq)]
27 pub enum VoteType {
28   Like,
29   Dislike,
30 }
31
32 impl TryFrom<i16> for VoteType {
33   type Error = LemmyError;
34
35   fn try_from(value: i16) -> Result<Self, Self::Error> {
36     match value {
37       1 => Ok(VoteType::Like),
38       -1 => Ok(VoteType::Dislike),
39       _ => Err(LemmyErrorType::InvalidVoteValue.into()),
40     }
41   }
42 }
43
44 impl From<&VoteType> for i16 {
45   fn from(value: &VoteType) -> i16 {
46     match value {
47       VoteType::Like => 1,
48       VoteType::Dislike => -1,
49     }
50   }
51 }
52
53 #[async_trait::async_trait]
54 impl InCommunity for Vote {
55   async fn community(&self, context: &Data<LemmyContext>) -> Result<ApubCommunity, LemmyError> {
56     let community = self
57       .object
58       .dereference(context)
59       .await?
60       .community(context)
61       .await?;
62     if let Some(audience) = &self.audience {
63       verify_community_matches(audience, community.actor_id.clone())?;
64     }
65     Ok(community)
66   }
67 }