]> Untitled Git - lemmy.git/blob - crates/apub/src/activities/voting/vote.rs
Move @context out of object/activity definitions
[lemmy.git] / crates / apub / src / activities / voting / vote.rs
1 use crate::{
2   activities::{
3     community::{
4       announce::{AnnouncableActivities, GetCommunity},
5       send_to_community,
6     },
7     generate_activity_id,
8     verify_activity,
9     verify_is_public,
10     verify_person_in_community,
11     voting::{vote_comment, vote_post},
12   },
13   fetcher::object_id::ObjectId,
14   objects::{community::ApubCommunity, person::ApubPerson},
15   PostOrComment,
16 };
17 use activitystreams::{public, unparsed::Unparsed};
18 use anyhow::anyhow;
19 use lemmy_api_common::blocking;
20 use lemmy_apub_lib::{
21   data::Data,
22   traits::{ActivityFields, ActivityHandler, ActorType},
23 };
24 use lemmy_db_schema::{
25   newtypes::CommunityId,
26   source::{community::Community, post::Post},
27   traits::Crud,
28 };
29 use lemmy_utils::LemmyError;
30 use lemmy_websocket::LemmyContext;
31 use serde::{Deserialize, Serialize};
32 use std::{convert::TryFrom, ops::Deref};
33 use strum_macros::ToString;
34 use url::Url;
35
36 #[derive(Clone, Debug, ToString, Deserialize, Serialize)]
37 pub enum VoteType {
38   Like,
39   Dislike,
40 }
41
42 impl TryFrom<i16> for VoteType {
43   type Error = LemmyError;
44
45   fn try_from(value: i16) -> Result<Self, Self::Error> {
46     match value {
47       1 => Ok(VoteType::Like),
48       -1 => Ok(VoteType::Dislike),
49       _ => Err(anyhow!("invalid vote value").into()),
50     }
51   }
52 }
53
54 impl From<&VoteType> for i16 {
55   fn from(value: &VoteType) -> i16 {
56     match value {
57       VoteType::Like => 1,
58       VoteType::Dislike => -1,
59     }
60   }
61 }
62
63 #[derive(Clone, Debug, Deserialize, Serialize, ActivityFields)]
64 #[serde(rename_all = "camelCase")]
65 pub struct Vote {
66   actor: ObjectId<ApubPerson>,
67   to: Vec<Url>,
68   pub(in crate::activities::voting) object: ObjectId<PostOrComment>,
69   cc: Vec<Url>,
70   #[serde(rename = "type")]
71   pub(in crate::activities::voting) kind: VoteType,
72   id: Url,
73   #[serde(flatten)]
74   unparsed: Unparsed,
75 }
76
77 impl Vote {
78   pub(in crate::activities::voting) fn new(
79     object: &PostOrComment,
80     actor: &ApubPerson,
81     community: &ApubCommunity,
82     kind: VoteType,
83     context: &LemmyContext,
84   ) -> Result<Vote, LemmyError> {
85     Ok(Vote {
86       actor: ObjectId::new(actor.actor_id()),
87       to: vec![public()],
88       object: ObjectId::new(object.ap_id()),
89       cc: vec![community.actor_id()],
90       kind: kind.clone(),
91       id: generate_activity_id(kind, &context.settings().get_protocol_and_hostname())?,
92       unparsed: Default::default(),
93     })
94   }
95
96   pub async fn send(
97     object: &PostOrComment,
98     actor: &ApubPerson,
99     community_id: CommunityId,
100     kind: VoteType,
101     context: &LemmyContext,
102   ) -> Result<(), LemmyError> {
103     let community = blocking(context.pool(), move |conn| {
104       Community::read(conn, community_id)
105     })
106     .await??
107     .into();
108     let vote = Vote::new(object, actor, &community, kind, context)?;
109     let vote_id = vote.id.clone();
110
111     let activity = AnnouncableActivities::Vote(vote);
112     send_to_community(activity, &vote_id, actor, &community, vec![], context).await
113   }
114 }
115
116 #[async_trait::async_trait(?Send)]
117 impl ActivityHandler for Vote {
118   type DataType = LemmyContext;
119   async fn verify(
120     &self,
121     context: &Data<LemmyContext>,
122     request_counter: &mut i32,
123   ) -> Result<(), LemmyError> {
124     verify_is_public(&self.to)?;
125     verify_activity(self, &context.settings())?;
126     let community = self.get_community(context, request_counter).await?;
127     verify_person_in_community(&self.actor, &community, context, request_counter).await?;
128     Ok(())
129   }
130
131   async fn receive(
132     self,
133     context: &Data<LemmyContext>,
134     request_counter: &mut i32,
135   ) -> Result<(), LemmyError> {
136     let actor = self.actor.dereference(context, request_counter).await?;
137     let object = self.object.dereference(context, request_counter).await?;
138     match object {
139       PostOrComment::Post(p) => vote_post(&self.kind, actor, p.deref(), context).await,
140       PostOrComment::Comment(c) => vote_comment(&self.kind, actor, &c, context).await,
141     }
142   }
143 }
144
145 #[async_trait::async_trait(?Send)]
146 impl GetCommunity for Vote {
147   async fn get_community(
148     &self,
149     context: &LemmyContext,
150     request_counter: &mut i32,
151   ) -> Result<ApubCommunity, LemmyError> {
152     let object = self.object.dereference(context, request_counter).await?;
153     let cid = match object {
154       PostOrComment::Post(p) => p.community_id,
155       PostOrComment::Comment(c) => {
156         blocking(context.pool(), move |conn| Post::read(conn, c.post_id))
157           .await??
158           .community_id
159       }
160     };
161     let community = blocking(context.pool(), move |conn| Community::read(conn, cid)).await??;
162     Ok(community.into())
163   }
164 }