]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/community.rs
Merge pull request #2593 from LemmyNet/refactor-notifications
[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   fetch_local_site_data,
5   local_instance,
6   objects::instance::fetch_instance_actor_for_object,
7   protocol::{
8     objects::{group::Group, Endpoints, LanguageTag},
9     ImageObject,
10     Source,
11   },
12   ActorType,
13 };
14 use activitypub_federation::{
15   core::object_id::ObjectId,
16   traits::{Actor, ApubObject},
17 };
18 use activitystreams_kinds::actor::GroupType;
19 use chrono::NaiveDateTime;
20 use itertools::Itertools;
21 use lemmy_api_common::{
22   context::LemmyContext,
23   utils::{generate_moderators_url, generate_outbox_url},
24 };
25 use lemmy_db_schema::{
26   source::{
27     actor_language::CommunityLanguage,
28     community::{Community, CommunityUpdateForm},
29     instance::Instance,
30   },
31   traits::{ApubActor, Crud},
32 };
33 use lemmy_db_views_actor::structs::CommunityFollowerView;
34 use lemmy_utils::{
35   error::LemmyError,
36   utils::{convert_datetime, markdown_to_html},
37 };
38 use std::ops::Deref;
39 use tracing::debug;
40 use url::Url;
41
42 #[derive(Clone, Debug)]
43 pub struct ApubCommunity(Community);
44
45 impl Deref for ApubCommunity {
46   type Target = Community;
47   fn deref(&self) -> &Self::Target {
48     &self.0
49   }
50 }
51
52 impl From<Community> for ApubCommunity {
53   fn from(c: Community) -> Self {
54     ApubCommunity(c)
55   }
56 }
57
58 #[async_trait::async_trait(?Send)]
59 impl ApubObject for ApubCommunity {
60   type DataType = LemmyContext;
61   type ApubType = Group;
62   type DbType = Community;
63   type Error = LemmyError;
64
65   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
66     Some(self.last_refreshed_at)
67   }
68
69   #[tracing::instrument(skip_all)]
70   async fn read_from_apub_id(
71     object_id: Url,
72     context: &LemmyContext,
73   ) -> Result<Option<Self>, LemmyError> {
74     Ok(
75       Community::read_from_apub_id(context.pool(), &object_id.into())
76         .await?
77         .map(Into::into),
78     )
79   }
80
81   #[tracing::instrument(skip_all)]
82   async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
83     let form = CommunityUpdateForm::builder().deleted(Some(true)).build();
84     Community::update(context.pool(), self.id, &form).await?;
85     Ok(())
86   }
87
88   #[tracing::instrument(skip_all)]
89   async fn into_apub(self, data: &LemmyContext) -> Result<Group, LemmyError> {
90     let community_id = self.id;
91     let langs = CommunityLanguage::read(data.pool(), community_id).await?;
92     let language = LanguageTag::new_multiple(langs, data.pool()).await?;
93     let attributed_to = Some(ObjectId::<ApubCommunityModerators>::new(
94       generate_moderators_url(&self.actor_id)?,
95     ));
96
97     let group = Group {
98       kind: GroupType::Group,
99       id: ObjectId::new(self.actor_id()),
100       preferred_username: self.name.clone(),
101       name: Some(self.title.clone()),
102       summary: self.description.as_ref().map(|b| markdown_to_html(b)),
103       source: self.description.clone().map(Source::new),
104       icon: self.icon.clone().map(ImageObject::new),
105       image: self.banner.clone().map(ImageObject::new),
106       sensitive: Some(self.nsfw),
107       moderators: attributed_to.clone(),
108       inbox: self.inbox_url.clone().into(),
109       outbox: ObjectId::new(generate_outbox_url(&self.actor_id)?),
110       followers: self.followers_url.clone().into(),
111       endpoints: self.shared_inbox_url.clone().map(|s| Endpoints {
112         shared_inbox: s.into(),
113       }),
114       public_key: self.get_public_key(),
115       language,
116       published: Some(convert_datetime(self.published)),
117       updated: self.updated.map(convert_datetime),
118       posting_restricted_to_mods: Some(self.posting_restricted_to_mods),
119       attributed_to,
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 apub_id = group.id.inner().clone();
142     let instance = Instance::create_from_actor_id(context.pool(), &apub_id).await?;
143
144     let form = Group::into_insert_form(group.clone(), instance.id);
145     let languages = LanguageTag::to_language_id_multiple(group.language, context.pool()).await?;
146
147     let community = Community::create(context.pool(), &form).await?;
148     CommunityLanguage::update(context.pool(), languages, community.id).await?;
149
150     let community: ApubCommunity = community.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).await, request_counter)
158       .await
159       .map_err(|e| debug!("{}", e))
160       .ok();
161
162     if let Some(moderators) = group.attributed_to.or(group.moderators) {
163       moderators
164         .dereference(&outbox_data, local_instance(context).await, 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(Into::into)
187   }
188 }
189
190 impl ActorType for ApubCommunity {
191   fn actor_id(&self) -> Url {
192     self.actor_id.clone().into()
193   }
194   fn private_key(&self) -> Option<String> {
195     self.private_key.clone()
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 local_site_data = fetch_local_site_data(context.pool()).await?;
209     let follows = CommunityFollowerView::for_community(context.pool(), id).await?;
210     let inboxes: Vec<Url> = follows
211       .into_iter()
212       .filter(|f| !f.follower.local)
213       .map(|f| {
214         f.follower
215           .shared_inbox_url
216           .unwrap_or(f.follower.inbox_url)
217           .into()
218       })
219       .unique()
220       .filter(|inbox: &Url| inbox.host_str() != Some(&context.settings().hostname))
221       // Don't send to blocked instances
222       .filter(|inbox| {
223         check_apub_id_valid_with_strictness(inbox, false, &local_site_data, context.settings())
224           .is_ok()
225       })
226       .collect();
227
228     Ok(inboxes)
229   }
230 }
231
232 #[cfg(test)]
233 pub(crate) mod tests {
234   use super::*;
235   use crate::{
236     objects::{instance::tests::parse_lemmy_instance, tests::init_context},
237     protocol::tests::file_to_json_object,
238   };
239   use lemmy_db_schema::{source::site::Site, traits::Crud};
240   use serial_test::serial;
241
242   pub(crate) async fn parse_lemmy_community(context: &LemmyContext) -> ApubCommunity {
243     let mut json: Group = file_to_json_object("assets/lemmy/objects/group.json").unwrap();
244     // change these links so they dont fetch over the network
245     json.moderators = None;
246     json.attributed_to = None;
247     json.outbox =
248       ObjectId::new(Url::parse("https://enterprise.lemmy.ml/c/tenforward/not_outbox").unwrap());
249
250     let url = Url::parse("https://enterprise.lemmy.ml/c/tenforward").unwrap();
251     let mut request_counter = 0;
252     ApubCommunity::verify(&json, &url, context, &mut request_counter)
253       .await
254       .unwrap();
255     let community = ApubCommunity::from_apub(json, context, &mut request_counter)
256       .await
257       .unwrap();
258     // this makes one requests to the (intentionally broken) outbox collection
259     assert_eq!(request_counter, 1);
260     community
261   }
262
263   #[actix_rt::test]
264   #[serial]
265   async fn test_parse_lemmy_community() {
266     let context = init_context().await;
267     let site = parse_lemmy_instance(&context).await;
268     let community = parse_lemmy_community(&context).await;
269
270     assert_eq!(community.title, "Ten Forward");
271     assert!(!community.local);
272     assert_eq!(community.description.as_ref().unwrap().len(), 132);
273
274     Community::delete(context.pool(), community.id)
275       .await
276       .unwrap();
277     Site::delete(context.pool(), site.id).await.unwrap();
278   }
279 }