]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/community.rs
Implement separate mod activities for feature, lock post (#2716)
[lemmy.git] / crates / apub / src / objects / community.rs
1 use crate::{
2   check_apub_id_valid_with_strictness,
3   collections::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_featured_url, 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::{markdown::markdown_to_html, time::convert_datetime},
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
94     let group = Group {
95       kind: GroupType::Group,
96       id: ObjectId::new(self.actor_id()),
97       preferred_username: self.name.clone(),
98       name: Some(self.title.clone()),
99       summary: self.description.as_ref().map(|b| markdown_to_html(b)),
100       source: self.description.clone().map(Source::new),
101       icon: self.icon.clone().map(ImageObject::new),
102       image: self.banner.clone().map(ImageObject::new),
103       sensitive: Some(self.nsfw),
104       moderators: Some(generate_moderators_url(&self.actor_id)?.into()),
105       featured: Some(generate_featured_url(&self.actor_id)?.into()),
106       inbox: self.inbox_url.clone().into(),
107       outbox: ObjectId::new(generate_outbox_url(&self.actor_id)?),
108       followers: self.followers_url.clone().into(),
109       endpoints: self.shared_inbox_url.clone().map(|s| Endpoints {
110         shared_inbox: s.into(),
111       }),
112       public_key: self.get_public_key(),
113       language,
114       published: Some(convert_datetime(self.published)),
115       updated: self.updated.map(convert_datetime),
116       posting_restricted_to_mods: Some(self.posting_restricted_to_mods),
117       attributed_to: Some(generate_moderators_url(&self.actor_id)?.into()),
118     };
119     Ok(group)
120   }
121
122   #[tracing::instrument(skip_all)]
123   async fn verify(
124     group: &Group,
125     expected_domain: &Url,
126     context: &LemmyContext,
127     _request_counter: &mut i32,
128   ) -> Result<(), LemmyError> {
129     group.verify(expected_domain, context).await
130   }
131
132   /// Converts a `Group` to `Community`, inserts it into the database and updates moderators.
133   #[tracing::instrument(skip_all)]
134   async fn from_apub(
135     group: Group,
136     context: &LemmyContext,
137     request_counter: &mut i32,
138   ) -> Result<ApubCommunity, LemmyError> {
139     let apub_id = group.id.inner().clone();
140     let instance = Instance::create_from_actor_id(context.pool(), &apub_id).await?;
141
142     let form = Group::into_insert_form(group.clone(), instance.id);
143     let languages = LanguageTag::to_language_id_multiple(group.language, context.pool()).await?;
144
145     let community = Community::create(context.pool(), &form).await?;
146     CommunityLanguage::update(context.pool(), languages, community.id).await?;
147
148     let community: ApubCommunity = community.into();
149     let outbox_data = CommunityContext(community.clone(), context.clone());
150
151     // Fetching mods and outbox is not necessary for Lemmy to work, so ignore errors. Besides,
152     // we need to ignore these errors so that tests can work entirely offline.
153     group
154       .outbox
155       .dereference(&outbox_data, local_instance(context).await, request_counter)
156       .await
157       .map_err(|e| debug!("{}", e))
158       .ok();
159
160     if let Some(moderators) = group.attributed_to.or(group.moderators) {
161       moderators
162         .dereference(&outbox_data, local_instance(context).await, request_counter)
163         .await
164         .map_err(|e| debug!("{}", e))
165         .ok();
166     }
167
168     fetch_instance_actor_for_object(community.actor_id(), context, request_counter).await;
169
170     Ok(community)
171   }
172 }
173
174 impl Actor for ApubCommunity {
175   fn public_key(&self) -> &str {
176     &self.public_key
177   }
178
179   fn inbox(&self) -> Url {
180     self.inbox_url.clone().into()
181   }
182
183   fn shared_inbox(&self) -> Option<Url> {
184     self.shared_inbox_url.clone().map(Into::into)
185   }
186 }
187
188 impl ActorType for ApubCommunity {
189   fn actor_id(&self) -> Url {
190     self.actor_id.clone().into()
191   }
192   fn private_key(&self) -> Option<String> {
193     self.private_key.clone()
194   }
195 }
196
197 impl ApubCommunity {
198   /// For a given community, returns the inboxes of all followers.
199   #[tracing::instrument(skip_all)]
200   pub(crate) async fn get_follower_inboxes(
201     &self,
202     context: &LemmyContext,
203   ) -> Result<Vec<Url>, LemmyError> {
204     let id = self.id;
205
206     let local_site_data = fetch_local_site_data(context.pool()).await?;
207     let follows = CommunityFollowerView::for_community(context.pool(), id).await?;
208     let inboxes: Vec<Url> = follows
209       .into_iter()
210       .filter(|f| !f.follower.local)
211       .map(|f| {
212         f.follower
213           .shared_inbox_url
214           .unwrap_or(f.follower.inbox_url)
215           .into()
216       })
217       .unique()
218       .filter(|inbox: &Url| inbox.host_str() != Some(&context.settings().hostname))
219       // Don't send to blocked instances
220       .filter(|inbox| {
221         check_apub_id_valid_with_strictness(inbox, false, &local_site_data, context.settings())
222           .is_ok()
223       })
224       .collect();
225
226     Ok(inboxes)
227   }
228 }
229
230 #[cfg(test)]
231 pub(crate) mod tests {
232   use super::*;
233   use crate::{
234     objects::{instance::tests::parse_lemmy_instance, tests::init_context},
235     protocol::tests::file_to_json_object,
236   };
237   use lemmy_db_schema::{source::site::Site, traits::Crud};
238   use serial_test::serial;
239
240   pub(crate) async fn parse_lemmy_community(context: &LemmyContext) -> ApubCommunity {
241     let mut json: Group = file_to_json_object("assets/lemmy/objects/group.json").unwrap();
242     // change these links so they dont fetch over the network
243     json.moderators = None;
244     json.attributed_to = 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().await;
265     let site = parse_lemmy_instance(&context).await;
266     let community = parse_lemmy_community(&context).await;
267
268     assert_eq!(community.title, "Ten Forward");
269     assert!(!community.local);
270     assert_eq!(community.description.as_ref().unwrap().len(), 132);
271
272     Community::delete(context.pool(), community.id)
273       .await
274       .unwrap();
275     Site::delete(context.pool(), site.id).await.unwrap();
276   }
277 }