]> Untitled Git - lemmy.git/blob - crates/apub/src/collections/community_moderators.rs
Change to_apub and from_apub to take by value and avoid cloning
[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 from_apub(
70     apub: Self::ApubType,
71     data: &Self::DataType,
72     expected_domain: &Url,
73     request_counter: &mut i32,
74   ) -> Result<Self, LemmyError> {
75     verify_domains_match(expected_domain, &apub.id)?;
76     let community_id = data.0.id;
77     let current_moderators = blocking(data.1.pool(), move |conn| {
78       CommunityModeratorView::for_community(conn, community_id)
79     })
80     .await??;
81     // Remove old mods from database which arent in the moderators collection anymore
82     for mod_user in &current_moderators {
83       let mod_id = ObjectId::new(mod_user.moderator.actor_id.clone());
84       if !apub.ordered_items.contains(&mod_id) {
85         let community_moderator_form = CommunityModeratorForm {
86           community_id: mod_user.community.id,
87           person_id: mod_user.moderator.id,
88         };
89         blocking(data.1.pool(), move |conn| {
90           CommunityModerator::leave(conn, &community_moderator_form)
91         })
92         .await??;
93       }
94     }
95
96     // Add new mods to database which have been added to moderators collection
97     for mod_id in apub.ordered_items {
98       let mod_id = ObjectId::new(mod_id);
99       let mod_user: ApubPerson = mod_id.dereference(&data.1, request_counter).await?;
100
101       if !current_moderators
102         .iter()
103         .map(|c| c.moderator.actor_id.clone())
104         .any(|x| x == mod_user.actor_id)
105       {
106         let community_moderator_form = CommunityModeratorForm {
107           community_id: data.0.id,
108           person_id: mod_user.id,
109         };
110         blocking(data.1.pool(), move |conn| {
111           CommunityModerator::join(conn, &community_moderator_form)
112         })
113         .await??;
114       }
115     }
116
117     // This return value is unused, so just set an empty vec
118     Ok(ApubCommunityModerators { 0: vec![] })
119   }
120 }
121
122 #[cfg(test)]
123 mod tests {
124   use super::*;
125   use crate::objects::{
126     community::tests::parse_lemmy_community,
127     person::tests::parse_lemmy_person,
128     tests::{file_to_json_object, init_context},
129   };
130   use lemmy_db_schema::{
131     source::{
132       community::Community,
133       person::{Person, PersonForm},
134     },
135     traits::Crud,
136   };
137   use serial_test::serial;
138
139   #[actix_rt::test]
140   #[serial]
141   async fn test_parse_lemmy_community_moderators() {
142     let context = init_context();
143     let community = parse_lemmy_community(&context).await;
144     let community_id = community.id;
145
146     let old_mod = PersonForm {
147       name: "holly".into(),
148       ..PersonForm::default()
149     };
150     let old_mod = Person::create(&context.pool().get().unwrap(), &old_mod).unwrap();
151     let community_moderator_form = CommunityModeratorForm {
152       community_id: community.id,
153       person_id: old_mod.id,
154     };
155
156     CommunityModerator::join(&context.pool().get().unwrap(), &community_moderator_form).unwrap();
157
158     let new_mod = parse_lemmy_person(&context).await;
159
160     let json: GroupModerators =
161       file_to_json_object("assets/lemmy/collections/group_moderators.json");
162     let url = Url::parse("https://enterprise.lemmy.ml/c/tenforward").unwrap();
163     let mut request_counter = 0;
164     let community_context = CommunityContext {
165       0: community,
166       1: context,
167     };
168     ApubCommunityModerators::from_apub(json, &community_context, &url, &mut request_counter)
169       .await
170       .unwrap();
171     assert_eq!(request_counter, 0);
172
173     let current_moderators = blocking(community_context.1.pool(), move |conn| {
174       CommunityModeratorView::for_community(conn, community_id)
175     })
176     .await
177     .unwrap()
178     .unwrap();
179
180     assert_eq!(current_moderators.len(), 1);
181     assert_eq!(current_moderators[0].moderator.id, new_mod.id);
182
183     Person::delete(&*community_context.1.pool().get().unwrap(), old_mod.id).unwrap();
184     Person::delete(&*community_context.1.pool().get().unwrap(), new_mod.id).unwrap();
185     Community::delete(
186       &*community_context.1.pool().get().unwrap(),
187       community_context.0.id,
188     )
189     .unwrap();
190   }
191 }