]> Untitled Git - lemmy.git/blob - crates/apub/src/collections/community_moderators.rs
Add method ApubObject.verify()
[lemmy.git] / crates / apub / src / collections / community_moderators.rs
1 use crate::{
2   collections::CommunityContext,
3   generate_moderators_url,
4   objects::person::ApubPerson,
5   protocol::collections::group_moderators::GroupModerators,
6 };
7 use activitystreams::{chrono::NaiveDateTime, collection::kind::OrderedCollectionType};
8 use lemmy_api_common::blocking;
9 use lemmy_apub_lib::{object_id::ObjectId, traits::ApubObject, verify::verify_domains_match};
10 use lemmy_db_schema::{
11   source::community::{CommunityModerator, CommunityModeratorForm},
12   traits::Joinable,
13 };
14 use lemmy_db_views_actor::community_moderator_view::CommunityModeratorView;
15 use lemmy_utils::LemmyError;
16 use url::Url;
17
18 #[derive(Clone, Debug)]
19 pub(crate) struct ApubCommunityModerators(pub(crate) Vec<CommunityModeratorView>);
20
21 #[async_trait::async_trait(?Send)]
22 impl ApubObject for ApubCommunityModerators {
23   type DataType = CommunityContext;
24   type TombstoneType = ();
25   type ApubType = GroupModerators;
26
27   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
28     None
29   }
30
31   async fn read_from_apub_id(
32     _object_id: Url,
33     data: &Self::DataType,
34   ) -> Result<Option<Self>, LemmyError> {
35     // Only read from database if its a local community, otherwise fetch over http
36     if data.0.local {
37       let cid = data.0.id;
38       let moderators = blocking(data.1.pool(), move |conn| {
39         CommunityModeratorView::for_community(conn, cid)
40       })
41       .await??;
42       Ok(Some(ApubCommunityModerators { 0: moderators }))
43     } else {
44       Ok(None)
45     }
46   }
47
48   async fn delete(self, _data: &Self::DataType) -> Result<(), LemmyError> {
49     unimplemented!()
50   }
51
52   async fn into_apub(self, data: &Self::DataType) -> Result<Self::ApubType, LemmyError> {
53     let ordered_items = self
54       .0
55       .into_iter()
56       .map(|m| ObjectId::<ApubPerson>::new(m.moderator.actor_id))
57       .collect();
58     Ok(GroupModerators {
59       r#type: OrderedCollectionType::OrderedCollection,
60       id: generate_moderators_url(&data.0.actor_id)?.into(),
61       ordered_items,
62     })
63   }
64
65   fn to_tombstone(&self) -> Result<Self::TombstoneType, LemmyError> {
66     unimplemented!()
67   }
68
69   async fn verify(
70     group_moderators: &GroupModerators,
71     expected_domain: &Url,
72     _context: &CommunityContext,
73     _request_counter: &mut i32,
74   ) -> Result<(), LemmyError> {
75     verify_domains_match(&group_moderators.id, expected_domain)?;
76     Ok(())
77   }
78
79   async fn from_apub(
80     apub: Self::ApubType,
81     data: &Self::DataType,
82     request_counter: &mut i32,
83   ) -> Result<Self, LemmyError> {
84     let community_id = data.0.id;
85     let current_moderators = blocking(data.1.pool(), move |conn| {
86       CommunityModeratorView::for_community(conn, community_id)
87     })
88     .await??;
89     // Remove old mods from database which arent in the moderators collection anymore
90     for mod_user in &current_moderators {
91       let mod_id = ObjectId::new(mod_user.moderator.actor_id.clone());
92       if !apub.ordered_items.contains(&mod_id) {
93         let community_moderator_form = CommunityModeratorForm {
94           community_id: mod_user.community.id,
95           person_id: mod_user.moderator.id,
96         };
97         blocking(data.1.pool(), move |conn| {
98           CommunityModerator::leave(conn, &community_moderator_form)
99         })
100         .await??;
101       }
102     }
103
104     // Add new mods to database which have been added to moderators collection
105     for mod_id in apub.ordered_items {
106       let mod_id = ObjectId::new(mod_id);
107       let mod_user: ApubPerson = mod_id.dereference(&data.1, request_counter).await?;
108
109       if !current_moderators
110         .iter()
111         .map(|c| c.moderator.actor_id.clone())
112         .any(|x| x == mod_user.actor_id)
113       {
114         let community_moderator_form = CommunityModeratorForm {
115           community_id: data.0.id,
116           person_id: mod_user.id,
117         };
118         blocking(data.1.pool(), move |conn| {
119           CommunityModerator::join(conn, &community_moderator_form)
120         })
121         .await??;
122       }
123     }
124
125     // This return value is unused, so just set an empty vec
126     Ok(ApubCommunityModerators { 0: vec![] })
127   }
128 }
129
130 #[cfg(test)]
131 mod tests {
132   use super::*;
133   use crate::objects::{
134     community::tests::parse_lemmy_community,
135     person::tests::parse_lemmy_person,
136     tests::{file_to_json_object, init_context},
137   };
138   use lemmy_db_schema::{
139     source::{
140       community::Community,
141       person::{Person, PersonForm},
142     },
143     traits::Crud,
144   };
145   use serial_test::serial;
146
147   #[actix_rt::test]
148   #[serial]
149   async fn test_parse_lemmy_community_moderators() {
150     let context = init_context();
151     let community = parse_lemmy_community(&context).await;
152     let community_id = community.id;
153
154     let old_mod = PersonForm {
155       name: "holly".into(),
156       ..PersonForm::default()
157     };
158     let old_mod = Person::create(&context.pool().get().unwrap(), &old_mod).unwrap();
159     let community_moderator_form = CommunityModeratorForm {
160       community_id: community.id,
161       person_id: old_mod.id,
162     };
163
164     CommunityModerator::join(&context.pool().get().unwrap(), &community_moderator_form).unwrap();
165
166     let new_mod = parse_lemmy_person(&context).await;
167
168     let json: GroupModerators =
169       file_to_json_object("assets/lemmy/collections/group_moderators.json");
170     let url = Url::parse("https://enterprise.lemmy.ml/c/tenforward").unwrap();
171     let mut request_counter = 0;
172     let community_context = CommunityContext {
173       0: community,
174       1: context,
175     };
176     ApubCommunityModerators::verify(&json, &url, &community_context, &mut request_counter)
177       .await
178       .unwrap();
179     ApubCommunityModerators::from_apub(json, &community_context, &mut request_counter)
180       .await
181       .unwrap();
182     assert_eq!(request_counter, 0);
183
184     let current_moderators = blocking(community_context.1.pool(), move |conn| {
185       CommunityModeratorView::for_community(conn, community_id)
186     })
187     .await
188     .unwrap()
189     .unwrap();
190
191     assert_eq!(current_moderators.len(), 1);
192     assert_eq!(current_moderators[0].moderator.id, new_mod.id);
193
194     Person::delete(&*community_context.1.pool().get().unwrap(), old_mod.id).unwrap();
195     Person::delete(&*community_context.1.pool().get().unwrap(), new_mod.id).unwrap();
196     Community::delete(
197       &*community_context.1.pool().get().unwrap(),
198       community_context.0.id,
199     )
200     .unwrap();
201   }
202 }