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