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