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