]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/community.rs
Merge websocket crate into api_common
[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   generate_moderators_url,
6   generate_outbox_url,
7   local_instance,
8   objects::instance::fetch_instance_actor_for_object,
9   protocol::{
10     objects::{group::Group, Endpoints, LanguageTag},
11     ImageObject,
12     Source,
13   },
14   ActorType,
15 };
16 use activitypub_federation::{
17   core::object_id::ObjectId,
18   traits::{Actor, ApubObject},
19 };
20 use activitystreams_kinds::actor::GroupType;
21 use chrono::NaiveDateTime;
22 use itertools::Itertools;
23 use lemmy_api_common::LemmyContext;
24 use lemmy_db_schema::{
25   source::{
26     actor_language::CommunityLanguage,
27     community::{Community, CommunityUpdateForm},
28     instance::Instance,
29   },
30   traits::{ApubActor, Crud},
31 };
32 use lemmy_db_views_actor::structs::CommunityFollowerView;
33 use lemmy_utils::{
34   error::LemmyError,
35   utils::{convert_datetime, markdown_to_html},
36 };
37 use std::ops::Deref;
38 use tracing::debug;
39 use url::Url;
40
41 #[derive(Clone, Debug)]
42 pub struct ApubCommunity(Community);
43
44 impl Deref for ApubCommunity {
45   type Target = Community;
46   fn deref(&self) -> &Self::Target {
47     &self.0
48   }
49 }
50
51 impl From<Community> for ApubCommunity {
52   fn from(c: Community) -> Self {
53     ApubCommunity(c)
54   }
55 }
56
57 #[async_trait::async_trait(?Send)]
58 impl ApubObject for ApubCommunity {
59   type DataType = LemmyContext;
60   type ApubType = Group;
61   type DbType = Community;
62   type Error = LemmyError;
63
64   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
65     Some(self.last_refreshed_at)
66   }
67
68   #[tracing::instrument(skip_all)]
69   async fn read_from_apub_id(
70     object_id: Url,
71     context: &LemmyContext,
72   ) -> Result<Option<Self>, LemmyError> {
73     Ok(
74       Community::read_from_apub_id(context.pool(), &object_id.into())
75         .await?
76         .map(Into::into),
77     )
78   }
79
80   #[tracing::instrument(skip_all)]
81   async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
82     let form = CommunityUpdateForm::builder().deleted(Some(true)).build();
83     Community::update(context.pool(), self.id, &form).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 = CommunityLanguage::read(data.pool(), community_id).await?;
91     let language = LanguageTag::new_multiple(langs, data.pool()).await?;
92     let attributed_to = Some(ObjectId::<ApubCommunityModerators>::new(
93       generate_moderators_url(&self.actor_id)?,
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: 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: attributed_to.clone(),
107       inbox: self.inbox_url.clone().into(),
108       outbox: ObjectId::new(generate_outbox_url(&self.actor_id)?),
109       followers: self.followers_url.clone().into(),
110       endpoints: self.shared_inbox_url.clone().map(|s| Endpoints {
111         shared_inbox: s.into(),
112       }),
113       public_key: self.get_public_key(),
114       language,
115       published: Some(convert_datetime(self.published)),
116       updated: self.updated.map(convert_datetime),
117       posting_restricted_to_mods: Some(self.posting_restricted_to_mods),
118       attributed_to,
119     };
120     Ok(group)
121   }
122
123   #[tracing::instrument(skip_all)]
124   async fn verify(
125     group: &Group,
126     expected_domain: &Url,
127     context: &LemmyContext,
128     _request_counter: &mut i32,
129   ) -> Result<(), LemmyError> {
130     group.verify(expected_domain, context).await
131   }
132
133   /// Converts a `Group` to `Community`, inserts it into the database and updates moderators.
134   #[tracing::instrument(skip_all)]
135   async fn from_apub(
136     group: Group,
137     context: &LemmyContext,
138     request_counter: &mut i32,
139   ) -> Result<ApubCommunity, LemmyError> {
140     let apub_id = group.id.inner().clone();
141     let instance = Instance::create_from_actor_id(context.pool(), &apub_id).await?;
142
143     let form = Group::into_insert_form(group.clone(), instance.id);
144     let languages = LanguageTag::to_language_id_multiple(group.language, context.pool()).await?;
145
146     let community = Community::create(context.pool(), &form).await?;
147     CommunityLanguage::update(context.pool(), languages, community.id).await?;
148
149     let community: ApubCommunity = community.into();
150     let outbox_data = CommunityContext(community.clone(), context.clone());
151
152     // Fetching mods and outbox is not necessary for Lemmy to work, so ignore errors. Besides,
153     // we need to ignore these errors so that tests can work entirely offline.
154     group
155       .outbox
156       .dereference(&outbox_data, local_instance(context).await, request_counter)
157       .await
158       .map_err(|e| debug!("{}", e))
159       .ok();
160
161     if let Some(moderators) = group.attributed_to.or(group.moderators) {
162       moderators
163         .dereference(&outbox_data, local_instance(context).await, request_counter)
164         .await
165         .map_err(|e| debug!("{}", e))
166         .ok();
167     }
168
169     fetch_instance_actor_for_object(community.actor_id(), context, request_counter).await;
170
171     Ok(community)
172   }
173 }
174
175 impl Actor for ApubCommunity {
176   fn public_key(&self) -> &str {
177     &self.public_key
178   }
179
180   fn inbox(&self) -> Url {
181     self.inbox_url.clone().into()
182   }
183
184   fn shared_inbox(&self) -> Option<Url> {
185     self.shared_inbox_url.clone().map(Into::into)
186   }
187 }
188
189 impl ActorType for ApubCommunity {
190   fn actor_id(&self) -> Url {
191     self.actor_id.clone().into()
192   }
193   fn private_key(&self) -> Option<String> {
194     self.private_key.clone()
195   }
196 }
197
198 impl ApubCommunity {
199   /// For a given community, returns the inboxes of all followers.
200   #[tracing::instrument(skip_all)]
201   pub(crate) async fn get_follower_inboxes(
202     &self,
203     context: &LemmyContext,
204   ) -> Result<Vec<Url>, LemmyError> {
205     let id = self.id;
206
207     let local_site_data = fetch_local_site_data(context.pool()).await?;
208     let follows = CommunityFollowerView::for_community(context.pool(), id).await?;
209     let inboxes: Vec<Url> = follows
210       .into_iter()
211       .filter(|f| !f.follower.local)
212       .map(|f| {
213         f.follower
214           .shared_inbox_url
215           .unwrap_or(f.follower.inbox_url)
216           .into()
217       })
218       .unique()
219       .filter(|inbox: &Url| inbox.host_str() != Some(&context.settings().hostname))
220       // Don't send to blocked instances
221       .filter(|inbox| {
222         check_apub_id_valid_with_strictness(inbox, false, &local_site_data, context.settings())
223           .is_ok()
224       })
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.attributed_to = None;
246     json.outbox =
247       ObjectId::new(Url::parse("https://enterprise.lemmy.ml/c/tenforward/not_outbox").unwrap());
248
249     let url = Url::parse("https://enterprise.lemmy.ml/c/tenforward").unwrap();
250     let mut request_counter = 0;
251     ApubCommunity::verify(&json, &url, context, &mut request_counter)
252       .await
253       .unwrap();
254     let community = ApubCommunity::from_apub(json, context, &mut request_counter)
255       .await
256       .unwrap();
257     // this makes one requests to the (intentionally broken) outbox collection
258     assert_eq!(request_counter, 1);
259     community
260   }
261
262   #[actix_rt::test]
263   #[serial]
264   async fn test_parse_lemmy_community() {
265     let context = init_context().await;
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(context.pool(), community.id)
274       .await
275       .unwrap();
276     Site::delete(context.pool(), site.id).await.unwrap();
277   }
278 }