]> Untitled Git - lemmy.git/blob - crates/apub/src/collections/community_moderators.rs
Merge pull request #2178 from LemmyNet/fix_ban_expires
[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(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(Vec::new()))
135   }
136
137   type DbType = ();
138 }
139
140 #[cfg(test)]
141 mod tests {
142   use super::*;
143   use crate::{
144     objects::{
145       community::tests::parse_lemmy_community,
146       person::tests::parse_lemmy_person,
147       tests::init_context,
148     },
149     protocol::tests::file_to_json_object,
150   };
151   use lemmy_db_schema::{
152     source::{
153       community::Community,
154       person::{Person, PersonForm},
155       site::Site,
156     },
157     traits::Crud,
158   };
159   use serial_test::serial;
160
161   #[actix_rt::test]
162   #[serial]
163   async fn test_parse_lemmy_community_moderators() {
164     let context = init_context();
165     let (new_mod, site) = parse_lemmy_person(&context).await;
166     let community = parse_lemmy_community(&context).await;
167     let community_id = community.id;
168
169     let old_mod = PersonForm {
170       name: "holly".into(),
171       ..PersonForm::default()
172     };
173     let old_mod = Person::create(&context.pool().get().unwrap(), &old_mod).unwrap();
174     let community_moderator_form = CommunityModeratorForm {
175       community_id: community.id,
176       person_id: old_mod.id,
177     };
178
179     CommunityModerator::join(&context.pool().get().unwrap(), &community_moderator_form).unwrap();
180
181     assert_eq!(site.actor_id.to_string(), "https://enterprise.lemmy.ml/");
182
183     let json: GroupModerators =
184       file_to_json_object("assets/lemmy/collections/group_moderators.json").unwrap();
185     let url = Url::parse("https://enterprise.lemmy.ml/c/tenforward").unwrap();
186     let mut request_counter = 0;
187     let community_context = CommunityContext {
188       0: community,
189       1: context,
190     };
191     ApubCommunityModerators::verify(&json, &url, &community_context, &mut request_counter)
192       .await
193       .unwrap();
194     ApubCommunityModerators::from_apub(json, &community_context, &mut request_counter)
195       .await
196       .unwrap();
197     assert_eq!(request_counter, 0);
198
199     let current_moderators = blocking(community_context.1.pool(), move |conn| {
200       CommunityModeratorView::for_community(conn, community_id)
201     })
202     .await
203     .unwrap()
204     .unwrap();
205
206     assert_eq!(current_moderators.len(), 1);
207     assert_eq!(current_moderators[0].moderator.id, new_mod.id);
208
209     Person::delete(&*community_context.1.pool().get().unwrap(), old_mod.id).unwrap();
210     Person::delete(&*community_context.1.pool().get().unwrap(), new_mod.id).unwrap();
211     Community::delete(
212       &*community_context.1.pool().get().unwrap(),
213       community_context.0.id,
214     )
215     .unwrap();
216     Site::delete(&*community_context.1.pool().get().unwrap(), site.id).unwrap();
217   }
218 }