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