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