]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/community.rs
Add tests for parsing activities and collections
[lemmy.git] / crates / apub / src / objects / community.rs
1 use std::ops::Deref;
2
3 use activitystreams::{
4   actor::{kind::GroupType, Endpoints},
5   object::kind::ImageType,
6 };
7 use chrono::NaiveDateTime;
8 use itertools::Itertools;
9 use log::debug;
10 use url::Url;
11
12 use lemmy_api_common::blocking;
13 use lemmy_apub_lib::{
14   traits::{ActorType, ApubObject},
15   values::MediaTypeMarkdown,
16 };
17 use lemmy_db_schema::{source::community::Community, DbPool};
18 use lemmy_db_views_actor::community_follower_view::CommunityFollowerView;
19 use lemmy_utils::{
20   settings::structs::Settings,
21   utils::{convert_datetime, markdown_to_html},
22   LemmyError,
23 };
24 use lemmy_websocket::LemmyContext;
25
26 use crate::{
27   check_is_apub_id_valid,
28   collections::{community_moderators::ApubCommunityModerators, CommunityContext},
29   fetcher::object_id::ObjectId,
30   generate_moderators_url,
31   generate_outbox_url,
32   protocol::{
33     objects::{group::Group, tombstone::Tombstone},
34     ImageObject,
35     Source,
36   },
37 };
38
39 #[derive(Clone, Debug)]
40 pub struct ApubCommunity(Community);
41
42 impl Deref for ApubCommunity {
43   type Target = Community;
44   fn deref(&self) -> &Self::Target {
45     &self.0
46   }
47 }
48
49 impl From<Community> for ApubCommunity {
50   fn from(c: Community) -> Self {
51     ApubCommunity { 0: c }
52   }
53 }
54
55 #[async_trait::async_trait(?Send)]
56 impl ApubObject for ApubCommunity {
57   type DataType = LemmyContext;
58   type ApubType = Group;
59   type TombstoneType = Tombstone;
60
61   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
62     Some(self.last_refreshed_at)
63   }
64
65   async fn read_from_apub_id(
66     object_id: Url,
67     context: &LemmyContext,
68   ) -> Result<Option<Self>, LemmyError> {
69     Ok(
70       blocking(context.pool(), move |conn| {
71         Community::read_from_apub_id(conn, object_id)
72       })
73       .await??
74       .map(Into::into),
75     )
76   }
77
78   async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
79     blocking(context.pool(), move |conn| {
80       Community::update_deleted(conn, self.id, true)
81     })
82     .await??;
83     Ok(())
84   }
85
86   async fn to_apub(&self, _context: &LemmyContext) -> Result<Group, LemmyError> {
87     let source = self.description.clone().map(|bio| Source {
88       content: bio,
89       media_type: MediaTypeMarkdown::Markdown,
90     });
91     let icon = self.icon.clone().map(|url| ImageObject {
92       kind: ImageType::Image,
93       url: url.into(),
94     });
95     let image = self.banner.clone().map(|url| ImageObject {
96       kind: ImageType::Image,
97       url: url.into(),
98     });
99
100     let group = Group {
101       kind: GroupType::Group,
102       id: self.actor_id(),
103       preferred_username: self.name.clone(),
104       name: self.title.clone(),
105       summary: self.description.as_ref().map(|b| markdown_to_html(b)),
106       source,
107       icon,
108       image,
109       sensitive: Some(self.nsfw),
110       moderators: Some(ObjectId::<ApubCommunityModerators>::new(
111         generate_moderators_url(&self.actor_id)?.into_inner(),
112       )),
113       inbox: self.inbox_url.clone().into(),
114       outbox: ObjectId::new(generate_outbox_url(&self.actor_id)?),
115       followers: self.followers_url.clone().into(),
116       endpoints: Endpoints {
117         shared_inbox: self.shared_inbox_url.clone().map(|s| s.into()),
118         ..Default::default()
119       },
120       public_key: self.get_public_key()?,
121       published: Some(convert_datetime(self.published)),
122       updated: self.updated.map(convert_datetime),
123       unparsed: Default::default(),
124     };
125     Ok(group)
126   }
127
128   fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
129     Ok(Tombstone::new(
130       GroupType::Group,
131       self.updated.unwrap_or(self.published),
132     ))
133   }
134
135   /// Converts a `Group` to `Community`, inserts it into the database and updates moderators.
136   async fn from_apub(
137     group: &Group,
138     context: &LemmyContext,
139     expected_domain: &Url,
140     request_counter: &mut i32,
141   ) -> Result<ApubCommunity, LemmyError> {
142     let form = Group::from_apub_to_form(group, expected_domain, &context.settings()).await?;
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 is_local(&self) -> bool {
173     self.local
174   }
175   fn actor_id(&self) -> Url {
176     self.actor_id.to_owned().into()
177   }
178   fn name(&self) -> String {
179     self.name.clone()
180   }
181   fn public_key(&self) -> Option<String> {
182     self.public_key.to_owned()
183   }
184   fn private_key(&self) -> Option<String> {
185     self.private_key.to_owned()
186   }
187
188   fn inbox_url(&self) -> Url {
189     self.inbox_url.clone().into()
190   }
191
192   fn shared_inbox_url(&self) -> Option<Url> {
193     self.shared_inbox_url.clone().map(|s| s.into_inner())
194   }
195 }
196
197 impl ApubCommunity {
198   /// For a given community, returns the inboxes of all followers.
199   pub(crate) async fn get_follower_inboxes(
200     &self,
201     pool: &DbPool,
202     settings: &Settings,
203   ) -> Result<Vec<Url>, LemmyError> {
204     let id = self.id;
205
206     let follows = blocking(pool, move |conn| {
207       CommunityFollowerView::for_community(conn, id)
208     })
209     .await??;
210     let inboxes = follows
211       .into_iter()
212       .filter(|f| !f.follower.local)
213       .map(|f| f.follower.shared_inbox_url.unwrap_or(f.follower.inbox_url))
214       .map(|i| i.into_inner())
215       .unique()
216       // Don't send to blocked instances
217       .filter(|inbox| check_is_apub_id_valid(inbox, false, settings).is_ok())
218       .collect();
219
220     Ok(inboxes)
221   }
222 }
223
224 #[cfg(test)]
225 pub(crate) mod tests {
226   use super::*;
227   use crate::objects::tests::{file_to_json_object, init_context};
228   use lemmy_db_schema::traits::Crud;
229   use serial_test::serial;
230
231   pub(crate) async fn parse_lemmy_community(context: &LemmyContext) -> ApubCommunity {
232     let mut json: Group = file_to_json_object("assets/lemmy/objects/group.json");
233     // change these links so they dont fetch over the network
234     json.moderators = None;
235     json.outbox =
236       ObjectId::new(Url::parse("https://enterprise.lemmy.ml/c/tenforward/not_outbox").unwrap());
237
238     let url = Url::parse("https://enterprise.lemmy.ml/c/tenforward").unwrap();
239     let mut request_counter = 0;
240     let community = ApubCommunity::from_apub(&json, context, &url, &mut request_counter)
241       .await
242       .unwrap();
243     // this makes two requests to the (intentionally) broken outbox/moderators collections
244     assert_eq!(request_counter, 1);
245     community
246   }
247
248   #[actix_rt::test]
249   #[serial]
250   async fn test_parse_lemmy_community() {
251     let context = init_context();
252     let community = parse_lemmy_community(&context).await;
253
254     assert_eq!(community.title, "Ten Forward");
255     assert!(community.public_key.is_some());
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 }