]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/community.rs
Merge pull request #1978 from LemmyNet/asonix/reqwest-middleware
[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   protocol::{
7     objects::{group::Group, tombstone::Tombstone, Endpoints},
8     ImageObject,
9     Source,
10   },
11 };
12 use activitystreams_kinds::actor::GroupType;
13 use chrono::NaiveDateTime;
14 use itertools::Itertools;
15 use lemmy_api_common::blocking;
16 use lemmy_apub_lib::{
17   object_id::ObjectId,
18   traits::{ActorType, ApubObject},
19   values::MediaTypeMarkdown,
20 };
21 use lemmy_db_schema::source::community::Community;
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 source = self.description.clone().map(|bio| Source {
84       content: bio,
85       media_type: MediaTypeMarkdown::Markdown,
86     });
87     let icon = self.icon.clone().map(ImageObject::new);
88     let image = self.banner.clone().map(ImageObject::new);
89
90     let group = Group {
91       kind: GroupType::Group,
92       id: ObjectId::new(self.actor_id()),
93       preferred_username: self.name.clone(),
94       name: self.title.clone(),
95       summary: self.description.as_ref().map(|b| markdown_to_html(b)),
96       source,
97       icon,
98       image,
99       sensitive: Some(self.nsfw),
100       moderators: Some(ObjectId::<ApubCommunityModerators>::new(
101         generate_moderators_url(&self.actor_id)?,
102       )),
103       inbox: self.inbox_url.clone().into(),
104       outbox: ObjectId::new(generate_outbox_url(&self.actor_id)?),
105       followers: self.followers_url.clone().into(),
106       endpoints: Endpoints {
107         shared_inbox: self.shared_inbox_url.clone().map(|s| s.into()),
108       },
109       public_key: self.get_public_key()?,
110       published: Some(convert_datetime(self.published)),
111       updated: self.updated.map(convert_datetime),
112       unparsed: Default::default(),
113     };
114     Ok(group)
115   }
116
117   fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
118     Ok(Tombstone::new(self.actor_id()))
119   }
120
121   #[tracing::instrument(skip_all)]
122   async fn verify(
123     group: &Group,
124     expected_domain: &Url,
125     context: &LemmyContext,
126     _request_counter: &mut i32,
127   ) -> Result<(), LemmyError> {
128     group.verify(expected_domain, context).await
129   }
130
131   /// Converts a `Group` to `Community`, inserts it into the database and updates moderators.
132   #[tracing::instrument(skip_all)]
133   async fn from_apub(
134     group: Group,
135     context: &LemmyContext,
136     request_counter: &mut i32,
137   ) -> Result<ApubCommunity, LemmyError> {
138     let form = Group::into_form(group.clone());
139
140     // Fetching mods and outbox is not necessary for Lemmy to work, so ignore errors. Besides,
141     // we need to ignore these errors so that tests can work entirely offline.
142     let community: ApubCommunity =
143       blocking(context.pool(), move |conn| Community::upsert(conn, &form))
144         .await??
145         .into();
146     let outbox_data = CommunityContext(community.clone(), context.clone());
147
148     group
149       .outbox
150       .dereference(&outbox_data, context.client(), request_counter)
151       .await
152       .map_err(|e| debug!("{}", e))
153       .ok();
154
155     if let Some(moderators) = &group.moderators {
156       moderators
157         .dereference(&outbox_data, context.client(), request_counter)
158         .await
159         .map_err(|e| debug!("{}", e))
160         .ok();
161     }
162
163     Ok(community)
164   }
165 }
166
167 impl ActorType for ApubCommunity {
168   fn actor_id(&self) -> Url {
169     self.actor_id.to_owned().into()
170   }
171   fn public_key(&self) -> String {
172     self.public_key.to_owned()
173   }
174   fn private_key(&self) -> Option<String> {
175     self.private_key.to_owned()
176   }
177
178   fn inbox_url(&self) -> Url {
179     self.inbox_url.clone().into()
180   }
181
182   fn shared_inbox_url(&self) -> Option<Url> {
183     self.shared_inbox_url.clone().map(|s| s.into())
184   }
185 }
186
187 impl ApubCommunity {
188   /// For a given community, returns the inboxes of all followers.
189   #[tracing::instrument(skip_all)]
190   pub(crate) async fn get_follower_inboxes(
191     &self,
192     context: &LemmyContext,
193   ) -> Result<Vec<Url>, LemmyError> {
194     let id = self.id;
195
196     let follows = blocking(context.pool(), move |conn| {
197       CommunityFollowerView::for_community(conn, id)
198     })
199     .await??;
200     let inboxes: Vec<Url> = follows
201       .into_iter()
202       .filter(|f| !f.follower.local)
203       .map(|f| {
204         f.follower
205           .shared_inbox_url
206           .unwrap_or(f.follower.inbox_url)
207           .into()
208       })
209       .unique()
210       .filter(|inbox: &Url| inbox.host_str() != Some(&context.settings().hostname))
211       // Don't send to blocked instances
212       .filter(|inbox| check_is_apub_id_valid(inbox, false, &context.settings()).is_ok())
213       .collect();
214
215     Ok(inboxes)
216   }
217 }
218
219 #[cfg(test)]
220 pub(crate) mod tests {
221   use super::*;
222   use crate::objects::tests::{file_to_json_object, init_context};
223   use lemmy_apub_lib::activity_queue::create_activity_queue;
224   use lemmy_db_schema::traits::Crud;
225   use serial_test::serial;
226
227   pub(crate) async fn parse_lemmy_community(context: &LemmyContext) -> ApubCommunity {
228     let mut json: Group = file_to_json_object("assets/lemmy/objects/group.json");
229     // change these links so they dont fetch over the network
230     json.moderators = None;
231     json.outbox =
232       ObjectId::new(Url::parse("https://enterprise.lemmy.ml/c/tenforward/not_outbox").unwrap());
233
234     let url = Url::parse("https://enterprise.lemmy.ml/c/tenforward").unwrap();
235     let mut request_counter = 0;
236     ApubCommunity::verify(&json, &url, context, &mut request_counter)
237       .await
238       .unwrap();
239     let community = ApubCommunity::from_apub(json, context, &mut request_counter)
240       .await
241       .unwrap();
242     // this makes two requests to the (intentionally) broken outbox/moderators collections
243     assert_eq!(request_counter, 1);
244     community
245   }
246
247   #[actix_rt::test]
248   #[serial]
249   async fn test_parse_lemmy_community() {
250     let client = reqwest::Client::new().into();
251     let manager = create_activity_queue(client);
252     let context = init_context(manager.queue_handle().clone());
253     let community = parse_lemmy_community(&context).await;
254
255     assert_eq!(community.title, "Ten Forward");
256     assert!(!community.local);
257     assert_eq!(community.description.as_ref().unwrap().len(), 132);
258
259     Community::delete(&*context.pool().get().unwrap(), community.id).unwrap();
260   }
261 }