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