]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/community.rs
Implement restricted community (only mods can post) (fixes #187) (#2235)
[lemmy.git] / crates / apub / src / objects / community.rs
1 use crate::{
2   check_is_apub_id_valid,
3   collections::{community_moderators::ApubCommunityModerators, CommunityContext},
4   generate_moderators_url,
5   generate_outbox_url,
6   objects::instance::fetch_instance_actor_for_object,
7   protocol::{
8     objects::{group::Group, tombstone::Tombstone, Endpoints},
9     ImageObject,
10     Source,
11   },
12 };
13 use activitystreams_kinds::actor::GroupType;
14 use chrono::NaiveDateTime;
15 use itertools::Itertools;
16 use lemmy_api_common::blocking;
17 use lemmy_apub_lib::{
18   object_id::ObjectId,
19   traits::{ActorType, ApubObject},
20 };
21 use lemmy_db_schema::{source::community::Community, traits::ApubActor};
22 use lemmy_db_views_actor::community_follower_view::CommunityFollowerView;
23 use lemmy_utils::{
24   utils::{convert_datetime, markdown_to_html},
25   LemmyError,
26 };
27 use lemmy_websocket::LemmyContext;
28 use std::ops::Deref;
29 use tracing::debug;
30 use url::Url;
31
32 #[derive(Clone, Debug)]
33 pub struct ApubCommunity(Community);
34
35 impl Deref for ApubCommunity {
36   type Target = Community;
37   fn deref(&self) -> &Self::Target {
38     &self.0
39   }
40 }
41
42 impl From<Community> for ApubCommunity {
43   fn from(c: Community) -> Self {
44     ApubCommunity(c)
45   }
46 }
47
48 #[async_trait::async_trait(?Send)]
49 impl ApubObject for ApubCommunity {
50   type DataType = LemmyContext;
51   type ApubType = Group;
52   type DbType = Community;
53   type TombstoneType = Tombstone;
54
55   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
56     Some(self.last_refreshed_at)
57   }
58
59   #[tracing::instrument(skip_all)]
60   async fn read_from_apub_id(
61     object_id: Url,
62     context: &LemmyContext,
63   ) -> Result<Option<Self>, LemmyError> {
64     Ok(
65       blocking(context.pool(), move |conn| {
66         Community::read_from_apub_id(conn, &object_id.into())
67       })
68       .await??
69       .map(Into::into),
70     )
71   }
72
73   #[tracing::instrument(skip_all)]
74   async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
75     blocking(context.pool(), move |conn| {
76       Community::update_deleted(conn, self.id, true)
77     })
78     .await??;
79     Ok(())
80   }
81
82   #[tracing::instrument(skip_all)]
83   async fn into_apub(self, _context: &LemmyContext) -> Result<Group, LemmyError> {
84     let group = Group {
85       kind: GroupType::Group,
86       id: ObjectId::new(self.actor_id()),
87       preferred_username: self.name.clone(),
88       name: Some(self.title.clone()),
89       summary: self.description.as_ref().map(|b| markdown_to_html(b)),
90       source: self.description.clone().map(Source::new),
91       icon: self.icon.clone().map(ImageObject::new),
92       image: self.banner.clone().map(ImageObject::new),
93       sensitive: Some(self.nsfw),
94       moderators: Some(ObjectId::<ApubCommunityModerators>::new(
95         generate_moderators_url(&self.actor_id)?,
96       )),
97       inbox: self.inbox_url.clone().into(),
98       outbox: ObjectId::new(generate_outbox_url(&self.actor_id)?),
99       followers: self.followers_url.clone().into(),
100       endpoints: self.shared_inbox_url.clone().map(|s| Endpoints {
101         shared_inbox: s.into(),
102       }),
103       public_key: self.get_public_key()?,
104       published: Some(convert_datetime(self.published)),
105       updated: self.updated.map(convert_datetime),
106       posting_restricted_to_mods: Some(self.posting_restricted_to_mods),
107     };
108     Ok(group)
109   }
110
111   fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
112     Ok(Tombstone::new(self.actor_id()))
113   }
114
115   #[tracing::instrument(skip_all)]
116   async fn verify(
117     group: &Group,
118     expected_domain: &Url,
119     context: &LemmyContext,
120     _request_counter: &mut i32,
121   ) -> Result<(), LemmyError> {
122     group.verify(expected_domain, context).await
123   }
124
125   /// Converts a `Group` to `Community`, inserts it into the database and updates moderators.
126   #[tracing::instrument(skip_all)]
127   async fn from_apub(
128     group: Group,
129     context: &LemmyContext,
130     request_counter: &mut i32,
131   ) -> Result<ApubCommunity, LemmyError> {
132     let form = Group::into_form(group.clone());
133
134     // Fetching mods and outbox is not necessary for Lemmy to work, so ignore errors. Besides,
135     // we need to ignore these errors so that tests can work entirely offline.
136     let community: ApubCommunity =
137       blocking(context.pool(), move |conn| Community::upsert(conn, &form))
138         .await??
139         .into();
140     let outbox_data = CommunityContext(community.clone(), context.clone());
141
142     group
143       .outbox
144       .dereference(&outbox_data, context.client(), request_counter)
145       .await
146       .map_err(|e| debug!("{}", e))
147       .ok();
148
149     if let Some(moderators) = &group.moderators {
150       moderators
151         .dereference(&outbox_data, context.client(), request_counter)
152         .await
153         .map_err(|e| debug!("{}", e))
154         .ok();
155     }
156
157     fetch_instance_actor_for_object(community.actor_id(), context, request_counter).await;
158
159     Ok(community)
160   }
161 }
162
163 impl ActorType for ApubCommunity {
164   fn actor_id(&self) -> Url {
165     self.actor_id.to_owned().into()
166   }
167   fn public_key(&self) -> String {
168     self.public_key.to_owned()
169   }
170   fn private_key(&self) -> Option<String> {
171     self.private_key.to_owned()
172   }
173
174   fn inbox_url(&self) -> Url {
175     self.inbox_url.clone().into()
176   }
177
178   fn shared_inbox_url(&self) -> Option<Url> {
179     self.shared_inbox_url.clone().map(|s| s.into())
180   }
181 }
182
183 impl ApubCommunity {
184   /// For a given community, returns the inboxes of all followers.
185   #[tracing::instrument(skip_all)]
186   pub(crate) async fn get_follower_inboxes(
187     &self,
188     context: &LemmyContext,
189   ) -> Result<Vec<Url>, LemmyError> {
190     let id = self.id;
191
192     let follows = blocking(context.pool(), move |conn| {
193       CommunityFollowerView::for_community(conn, id)
194     })
195     .await??;
196     let inboxes: Vec<Url> = follows
197       .into_iter()
198       .filter(|f| !f.follower.local)
199       .map(|f| {
200         f.follower
201           .shared_inbox_url
202           .unwrap_or(f.follower.inbox_url)
203           .into()
204       })
205       .unique()
206       .filter(|inbox: &Url| inbox.host_str() != Some(&context.settings().hostname))
207       // Don't send to blocked instances
208       .filter(|inbox| check_is_apub_id_valid(inbox, false, &context.settings()).is_ok())
209       .collect();
210
211     Ok(inboxes)
212   }
213 }
214
215 #[cfg(test)]
216 pub(crate) mod tests {
217   use super::*;
218   use crate::{
219     objects::{instance::tests::parse_lemmy_instance, tests::init_context},
220     protocol::tests::file_to_json_object,
221   };
222   use lemmy_db_schema::{source::site::Site, traits::Crud};
223   use serial_test::serial;
224
225   pub(crate) async fn parse_lemmy_community(context: &LemmyContext) -> ApubCommunity {
226     let mut json: Group = file_to_json_object("assets/lemmy/objects/group.json").unwrap();
227     // change these links so they dont fetch over the network
228     json.moderators = None;
229     json.outbox =
230       ObjectId::new(Url::parse("https://enterprise.lemmy.ml/c/tenforward/not_outbox").unwrap());
231
232     let url = Url::parse("https://enterprise.lemmy.ml/c/tenforward").unwrap();
233     let mut request_counter = 0;
234     ApubCommunity::verify(&json, &url, context, &mut request_counter)
235       .await
236       .unwrap();
237     let community = ApubCommunity::from_apub(json, context, &mut request_counter)
238       .await
239       .unwrap();
240     // this makes one requests to the (intentionally broken) outbox collection
241     assert_eq!(request_counter, 1);
242     community
243   }
244
245   #[actix_rt::test]
246   #[serial]
247   async fn test_parse_lemmy_community() {
248     let context = init_context();
249     let site = parse_lemmy_instance(&context).await;
250     let community = parse_lemmy_community(&context).await;
251
252     assert_eq!(community.title, "Ten Forward");
253     assert!(!community.local);
254     assert_eq!(community.description.as_ref().unwrap().len(), 132);
255
256     Community::delete(&*context.pool().get().unwrap(), community.id).unwrap();
257     Site::delete(&*context.pool().get().unwrap(), site.id).unwrap();
258   }
259 }