]> Untitled Git - lemmy.git/blob - crates/apub/src/collections/community_moderators.rs
Don't drop error context when adding a message to errors (#1958)
[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.dereference(&data.1, request_counter).await?;
114
115       if !current_moderators
116         .iter()
117         .map(|c| c.moderator.actor_id.clone())
118         .any(|x| x == mod_user.actor_id)
119       {
120         let community_moderator_form = CommunityModeratorForm {
121           community_id: data.0.id,
122           person_id: mod_user.id,
123         };
124         blocking(data.1.pool(), move |conn| {
125           CommunityModerator::join(conn, &community_moderator_form)
126         })
127         .await??;
128       }
129     }
130
131     // This return value is unused, so just set an empty vec
132     Ok(ApubCommunityModerators { 0: vec![] })
133   }
134 }
135
136 #[cfg(test)]
137 mod tests {
138   use super::*;
139   use crate::objects::{
140     community::tests::parse_lemmy_community,
141     person::tests::parse_lemmy_person,
142     tests::{file_to_json_object, init_context},
143   };
144   use lemmy_apub_lib::activity_queue::create_activity_queue;
145   use lemmy_db_schema::{
146     source::{
147       community::Community,
148       person::{Person, PersonForm},
149     },
150     traits::Crud,
151   };
152   use serial_test::serial;
153
154   #[actix_rt::test]
155   #[serial]
156   async fn test_parse_lemmy_community_moderators() {
157     let manager = create_activity_queue();
158     let context = init_context(manager.queue_handle().clone());
159     let community = parse_lemmy_community(&context).await;
160     let community_id = community.id;
161
162     let old_mod = PersonForm {
163       name: "holly".into(),
164       ..PersonForm::default()
165     };
166     let old_mod = Person::create(&context.pool().get().unwrap(), &old_mod).unwrap();
167     let community_moderator_form = CommunityModeratorForm {
168       community_id: community.id,
169       person_id: old_mod.id,
170     };
171
172     CommunityModerator::join(&context.pool().get().unwrap(), &community_moderator_form).unwrap();
173
174     let new_mod = parse_lemmy_person(&context).await;
175
176     let json: GroupModerators =
177       file_to_json_object("assets/lemmy/collections/group_moderators.json");
178     let url = Url::parse("https://enterprise.lemmy.ml/c/tenforward").unwrap();
179     let mut request_counter = 0;
180     let community_context = CommunityContext {
181       0: community,
182       1: context,
183     };
184     ApubCommunityModerators::verify(&json, &url, &community_context, &mut request_counter)
185       .await
186       .unwrap();
187     ApubCommunityModerators::from_apub(json, &community_context, &mut request_counter)
188       .await
189       .unwrap();
190     assert_eq!(request_counter, 0);
191
192     let current_moderators = blocking(community_context.1.pool(), move |conn| {
193       CommunityModeratorView::for_community(conn, community_id)
194     })
195     .await
196     .unwrap()
197     .unwrap();
198
199     assert_eq!(current_moderators.len(), 1);
200     assert_eq!(current_moderators[0].moderator.id, new_mod.id);
201
202     Person::delete(&*community_context.1.pool().get().unwrap(), old_mod.id).unwrap();
203     Person::delete(&*community_context.1.pool().get().unwrap(), new_mod.id).unwrap();
204     Community::delete(
205       &*community_context.1.pool().get().unwrap(),
206       community_context.0.id,
207     )
208     .unwrap();
209   }
210 }