]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/community.rs
Merge pull request #1936 from LemmyNet/required_public_key
[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 log::debug;
29 use std::ops::Deref;
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   async fn read_from_apub_id(
59     object_id: Url,
60     context: &LemmyContext,
61   ) -> Result<Option<Self>, LemmyError> {
62     Ok(
63       blocking(context.pool(), move |conn| {
64         Community::read_from_apub_id(conn, object_id)
65       })
66       .await??
67       .map(Into::into),
68     )
69   }
70
71   async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
72     blocking(context.pool(), move |conn| {
73       Community::update_deleted(conn, self.id, true)
74     })
75     .await??;
76     Ok(())
77   }
78
79   async fn into_apub(self, _context: &LemmyContext) -> Result<Group, LemmyError> {
80     let source = self.description.clone().map(|bio| Source {
81       content: bio,
82       media_type: MediaTypeMarkdown::Markdown,
83     });
84     let icon = self.icon.clone().map(ImageObject::new);
85     let image = self.banner.clone().map(ImageObject::new);
86
87     let group = Group {
88       kind: GroupType::Group,
89       id: ObjectId::new(self.actor_id()),
90       preferred_username: self.name.clone(),
91       name: self.title.clone(),
92       summary: self.description.as_ref().map(|b| markdown_to_html(b)),
93       source,
94       icon,
95       image,
96       sensitive: Some(self.nsfw),
97       moderators: Some(ObjectId::<ApubCommunityModerators>::new(
98         generate_moderators_url(&self.actor_id)?,
99       )),
100       inbox: self.inbox_url.clone().into(),
101       outbox: ObjectId::new(generate_outbox_url(&self.actor_id)?),
102       followers: self.followers_url.clone().into(),
103       endpoints: Endpoints {
104         shared_inbox: self.shared_inbox_url.clone().map(|s| s.into()),
105       },
106       public_key: self.get_public_key()?,
107       published: Some(convert_datetime(self.published)),
108       updated: self.updated.map(convert_datetime),
109       unparsed: Default::default(),
110     };
111     Ok(group)
112   }
113
114   fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
115     Ok(Tombstone::new(self.actor_id()))
116   }
117
118   async fn verify(
119     group: &Group,
120     expected_domain: &Url,
121     context: &LemmyContext,
122     _request_counter: &mut i32,
123   ) -> Result<(), LemmyError> {
124     group.verify(expected_domain, context).await
125   }
126
127   /// Converts a `Group` to `Community`, inserts it into the database and updates moderators.
128   async fn from_apub(
129     group: Group,
130     context: &LemmyContext,
131     request_counter: &mut i32,
132   ) -> Result<ApubCommunity, LemmyError> {
133     let form = Group::into_form(group.clone());
134
135     // Fetching mods and outbox is not necessary for Lemmy to work, so ignore errors. Besides,
136     // we need to ignore these errors so that tests can work entirely offline.
137     let community: ApubCommunity =
138       blocking(context.pool(), move |conn| Community::upsert(conn, &form))
139         .await??
140         .into();
141     let outbox_data = CommunityContext(community.clone(), context.clone());
142
143     group
144       .outbox
145       .dereference(&outbox_data, request_counter)
146       .await
147       .map_err(|e| debug!("{}", e))
148       .ok();
149
150     if let Some(moderators) = &group.moderators {
151       moderators
152         .dereference(&outbox_data, request_counter)
153         .await
154         .map_err(|e| debug!("{}", e))
155         .ok();
156     }
157
158     Ok(community)
159   }
160 }
161
162 impl ActorType for ApubCommunity {
163   fn actor_id(&self) -> Url {
164     self.actor_id.to_owned().into()
165   }
166   fn public_key(&self) -> String {
167     self.public_key.to_owned()
168   }
169   fn private_key(&self) -> Option<String> {
170     self.private_key.to_owned()
171   }
172
173   fn inbox_url(&self) -> Url {
174     self.inbox_url.clone().into()
175   }
176
177   fn shared_inbox_url(&self) -> Option<Url> {
178     self.shared_inbox_url.clone().map(|s| s.into())
179   }
180 }
181
182 impl ApubCommunity {
183   /// For a given community, returns the inboxes of all followers.
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::objects::tests::{file_to_json_object, init_context};
217   use lemmy_db_schema::traits::Crud;
218   use serial_test::serial;
219
220   pub(crate) async fn parse_lemmy_community(context: &LemmyContext) -> ApubCommunity {
221     let mut json: Group = file_to_json_object("assets/lemmy/objects/group.json");
222     // change these links so they dont fetch over the network
223     json.moderators = None;
224     json.outbox =
225       ObjectId::new(Url::parse("https://enterprise.lemmy.ml/c/tenforward/not_outbox").unwrap());
226
227     let url = Url::parse("https://enterprise.lemmy.ml/c/tenforward").unwrap();
228     let mut request_counter = 0;
229     ApubCommunity::verify(&json, &url, context, &mut request_counter)
230       .await
231       .unwrap();
232     let community = ApubCommunity::from_apub(json, context, &mut request_counter)
233       .await
234       .unwrap();
235     // this makes two requests to the (intentionally) broken outbox/moderators collections
236     assert_eq!(request_counter, 1);
237     community
238   }
239
240   #[actix_rt::test]
241   #[serial]
242   async fn test_parse_lemmy_community() {
243     let context = init_context();
244     let community = parse_lemmy_community(&context).await;
245
246     assert_eq!(community.title, "Ten Forward");
247     assert!(!community.local);
248     assert_eq!(community.description.as_ref().unwrap().len(), 132);
249
250     Community::delete(&*context.pool().get().unwrap(), community.id).unwrap();
251   }
252 }