]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/community.rs
9793c4fd4ef43f24b281511ad95ad5f34176cadd
[lemmy.git] / crates / apub / src / objects / community.rs
1 use crate::{
2   check_apub_id_valid_with_strictness,
3   collections::{community_moderators::ApubCommunityModerators, CommunityContext},
4   generate_moderators_url,
5   generate_outbox_url,
6   local_instance,
7   objects::instance::fetch_instance_actor_for_object,
8   protocol::{
9     objects::{group::Group, Endpoints, LanguageTag},
10     ImageObject,
11     Source,
12   },
13   ActorType,
14 };
15 use activitypub_federation::{
16   core::object_id::ObjectId,
17   traits::{Actor, ApubObject},
18 };
19 use activitystreams_kinds::actor::GroupType;
20 use chrono::NaiveDateTime;
21 use itertools::Itertools;
22 use lemmy_api_common::utils::blocking;
23 use lemmy_db_schema::{
24   source::{actor_language::CommunityLanguage, community::Community},
25   traits::ApubActor,
26 };
27 use lemmy_db_views_actor::structs::CommunityFollowerView;
28 use lemmy_utils::{
29   error::LemmyError,
30   utils::{convert_datetime, markdown_to_html},
31 };
32 use lemmy_websocket::LemmyContext;
33 use std::ops::Deref;
34 use tracing::debug;
35 use url::Url;
36
37 #[derive(Clone, Debug)]
38 pub struct ApubCommunity(Community);
39
40 impl Deref for ApubCommunity {
41   type Target = Community;
42   fn deref(&self) -> &Self::Target {
43     &self.0
44   }
45 }
46
47 impl From<Community> for ApubCommunity {
48   fn from(c: Community) -> Self {
49     ApubCommunity(c)
50   }
51 }
52
53 #[async_trait::async_trait(?Send)]
54 impl ApubObject for ApubCommunity {
55   type DataType = LemmyContext;
56   type ApubType = Group;
57   type DbType = Community;
58   type Error = LemmyError;
59
60   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
61     Some(self.last_refreshed_at)
62   }
63
64   #[tracing::instrument(skip_all)]
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.into())
72       })
73       .await??
74       .map(Into::into),
75     )
76   }
77
78   #[tracing::instrument(skip_all)]
79   async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
80     blocking(context.pool(), move |conn| {
81       Community::update_deleted(conn, self.id, true)
82     })
83     .await??;
84     Ok(())
85   }
86
87   #[tracing::instrument(skip_all)]
88   async fn into_apub(self, data: &LemmyContext) -> Result<Group, LemmyError> {
89     let community_id = self.id;
90     let langs = blocking(data.pool(), move |conn| {
91       CommunityLanguage::read(conn, community_id)
92     })
93     .await??;
94     let language = LanguageTag::new_multiple(langs, data.pool()).await?;
95
96     let group = Group {
97       kind: GroupType::Group,
98       id: ObjectId::new(self.actor_id()),
99       preferred_username: self.name.clone(),
100       name: Some(self.title.clone()),
101       summary: self.description.as_ref().map(|b| markdown_to_html(b)),
102       source: self.description.clone().map(Source::new),
103       icon: self.icon.clone().map(ImageObject::new),
104       image: self.banner.clone().map(ImageObject::new),
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: self.shared_inbox_url.clone().map(|s| Endpoints {
113         shared_inbox: s.into(),
114       }),
115       public_key: self.get_public_key(),
116       language,
117       published: Some(convert_datetime(self.published)),
118       updated: self.updated.map(convert_datetime),
119       posting_restricted_to_mods: Some(self.posting_restricted_to_mods),
120     };
121     Ok(group)
122   }
123
124   #[tracing::instrument(skip_all)]
125   async fn verify(
126     group: &Group,
127     expected_domain: &Url,
128     context: &LemmyContext,
129     _request_counter: &mut i32,
130   ) -> Result<(), LemmyError> {
131     group.verify(expected_domain, context).await
132   }
133
134   /// Converts a `Group` to `Community`, inserts it into the database and updates moderators.
135   #[tracing::instrument(skip_all)]
136   async fn from_apub(
137     group: Group,
138     context: &LemmyContext,
139     request_counter: &mut i32,
140   ) -> Result<ApubCommunity, LemmyError> {
141     let form = Group::into_form(group.clone());
142     let languages = LanguageTag::to_language_id_multiple(group.language, context.pool()).await?;
143
144     let community: ApubCommunity = blocking(context.pool(), move |conn| {
145       let community = Community::upsert(conn, &form)?;
146       CommunityLanguage::update(conn, languages, community.id)?;
147       Ok::<Community, diesel::result::Error>(community)
148     })
149     .await??
150     .into();
151     let outbox_data = CommunityContext(community.clone(), context.clone());
152
153     // Fetching mods and outbox is not necessary for Lemmy to work, so ignore errors. Besides,
154     // we need to ignore these errors so that tests can work entirely offline.
155     group
156       .outbox
157       .dereference(&outbox_data, local_instance(context), request_counter)
158       .await
159       .map_err(|e| debug!("{}", e))
160       .ok();
161
162     if let Some(moderators) = &group.moderators {
163       moderators
164         .dereference(&outbox_data, local_instance(context), request_counter)
165         .await
166         .map_err(|e| debug!("{}", e))
167         .ok();
168     }
169
170     fetch_instance_actor_for_object(community.actor_id(), context, request_counter).await;
171
172     Ok(community)
173   }
174 }
175
176 impl Actor for ApubCommunity {
177   fn public_key(&self) -> &str {
178     &self.public_key
179   }
180
181   fn inbox(&self) -> Url {
182     self.inbox_url.clone().into()
183   }
184
185   fn shared_inbox(&self) -> Option<Url> {
186     self.shared_inbox_url.clone().map(|s| s.into())
187   }
188 }
189
190 impl ActorType for ApubCommunity {
191   fn actor_id(&self) -> Url {
192     self.actor_id.to_owned().into()
193   }
194   fn private_key(&self) -> Option<String> {
195     self.private_key.to_owned()
196   }
197 }
198
199 impl ApubCommunity {
200   /// For a given community, returns the inboxes of all followers.
201   #[tracing::instrument(skip_all)]
202   pub(crate) async fn get_follower_inboxes(
203     &self,
204     context: &LemmyContext,
205   ) -> Result<Vec<Url>, LemmyError> {
206     let id = self.id;
207
208     let follows = blocking(context.pool(), move |conn| {
209       CommunityFollowerView::for_community(conn, id)
210     })
211     .await??;
212     let inboxes: Vec<Url> = follows
213       .into_iter()
214       .filter(|f| !f.follower.local)
215       .map(|f| {
216         f.follower
217           .shared_inbox_url
218           .unwrap_or(f.follower.inbox_url)
219           .into()
220       })
221       .unique()
222       .filter(|inbox: &Url| inbox.host_str() != Some(&context.settings().hostname))
223       // Don't send to blocked instances
224       .filter(|inbox| check_apub_id_valid_with_strictness(inbox, false, context.settings()).is_ok())
225       .collect();
226
227     Ok(inboxes)
228   }
229 }
230
231 #[cfg(test)]
232 pub(crate) mod tests {
233   use super::*;
234   use crate::{
235     objects::{instance::tests::parse_lemmy_instance, tests::init_context},
236     protocol::tests::file_to_json_object,
237   };
238   use lemmy_db_schema::{source::site::Site, traits::Crud};
239   use serial_test::serial;
240
241   pub(crate) async fn parse_lemmy_community(context: &LemmyContext) -> ApubCommunity {
242     let mut json: Group = file_to_json_object("assets/lemmy/objects/group.json").unwrap();
243     // change these links so they dont fetch over the network
244     json.moderators = None;
245     json.outbox =
246       ObjectId::new(Url::parse("https://enterprise.lemmy.ml/c/tenforward/not_outbox").unwrap());
247
248     let url = Url::parse("https://enterprise.lemmy.ml/c/tenforward").unwrap();
249     let mut request_counter = 0;
250     ApubCommunity::verify(&json, &url, context, &mut request_counter)
251       .await
252       .unwrap();
253     let community = ApubCommunity::from_apub(json, context, &mut request_counter)
254       .await
255       .unwrap();
256     // this makes one requests to the (intentionally broken) outbox collection
257     assert_eq!(request_counter, 1);
258     community
259   }
260
261   #[actix_rt::test]
262   #[serial]
263   async fn test_parse_lemmy_community() {
264     let context = init_context();
265     let conn = &mut context.pool().get().unwrap();
266     let site = parse_lemmy_instance(&context).await;
267     let community = parse_lemmy_community(&context).await;
268
269     assert_eq!(community.title, "Ten Forward");
270     assert!(!community.local);
271     assert_eq!(community.description.as_ref().unwrap().len(), 132);
272
273     Community::delete(conn, community.id).unwrap();
274     Site::delete(conn, site.id).unwrap();
275   }
276 }