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