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