]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/community.rs
Add diesel_async, get rid of blocking function (#2510)
[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_db_schema::{
24   source::{
25     actor_language::CommunityLanguage,
26     community::{Community, CommunityUpdateForm},
27     instance::Instance,
28   },
29   traits::{ApubActor, Crud},
30 };
31 use lemmy_db_views_actor::structs::CommunityFollowerView;
32 use lemmy_utils::{
33   error::LemmyError,
34   utils::{convert_datetime, markdown_to_html},
35 };
36 use lemmy_websocket::LemmyContext;
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
93     let group = Group {
94       kind: GroupType::Group,
95       id: ObjectId::new(self.actor_id()),
96       preferred_username: self.name.clone(),
97       name: Some(self.title.clone()),
98       summary: self.description.as_ref().map(|b| markdown_to_html(b)),
99       source: self.description.clone().map(Source::new),
100       icon: self.icon.clone().map(ImageObject::new),
101       image: self.banner.clone().map(ImageObject::new),
102       sensitive: Some(self.nsfw),
103       moderators: Some(ObjectId::<ApubCommunityModerators>::new(
104         generate_moderators_url(&self.actor_id)?,
105       )),
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     };
118     Ok(group)
119   }
120
121   #[tracing::instrument(skip_all)]
122   async fn verify(
123     group: &Group,
124     expected_domain: &Url,
125     context: &LemmyContext,
126     _request_counter: &mut i32,
127   ) -> Result<(), LemmyError> {
128     group.verify(expected_domain, context).await
129   }
130
131   /// Converts a `Group` to `Community`, inserts it into the database and updates moderators.
132   #[tracing::instrument(skip_all)]
133   async fn from_apub(
134     group: Group,
135     context: &LemmyContext,
136     request_counter: &mut i32,
137   ) -> Result<ApubCommunity, LemmyError> {
138     let apub_id = group.id.inner().to_owned();
139     let instance = Instance::create_from_actor_id(context.pool(), &apub_id).await?;
140
141     let form = Group::into_insert_form(group.clone(), instance.id);
142     let languages = LanguageTag::to_language_id_multiple(group.language, context.pool()).await?;
143
144     let community = Community::create(context.pool(), &form).await?;
145     CommunityLanguage::update(context.pool(), languages, community.id).await?;
146
147     let community: ApubCommunity = community.into();
148     let outbox_data = CommunityContext(community.clone(), context.clone());
149
150     // Fetching mods and outbox is not necessary for Lemmy to work, so ignore errors. Besides,
151     // we need to ignore these errors so that tests can work entirely offline.
152     group
153       .outbox
154       .dereference(&outbox_data, local_instance(context).await, request_counter)
155       .await
156       .map_err(|e| debug!("{}", e))
157       .ok();
158
159     if let Some(moderators) = &group.moderators {
160       moderators
161         .dereference(&outbox_data, local_instance(context).await, request_counter)
162         .await
163         .map_err(|e| debug!("{}", e))
164         .ok();
165     }
166
167     fetch_instance_actor_for_object(community.actor_id(), context, request_counter).await;
168
169     Ok(community)
170   }
171 }
172
173 impl Actor for ApubCommunity {
174   fn public_key(&self) -> &str {
175     &self.public_key
176   }
177
178   fn inbox(&self) -> Url {
179     self.inbox_url.clone().into()
180   }
181
182   fn shared_inbox(&self) -> Option<Url> {
183     self.shared_inbox_url.clone().map(|s| s.into())
184   }
185 }
186
187 impl ActorType for ApubCommunity {
188   fn actor_id(&self) -> Url {
189     self.actor_id.to_owned().into()
190   }
191   fn private_key(&self) -> Option<String> {
192     self.private_key.to_owned()
193   }
194 }
195
196 impl ApubCommunity {
197   /// For a given community, returns the inboxes of all followers.
198   #[tracing::instrument(skip_all)]
199   pub(crate) async fn get_follower_inboxes(
200     &self,
201     context: &LemmyContext,
202   ) -> Result<Vec<Url>, LemmyError> {
203     let id = self.id;
204
205     let local_site_data = fetch_local_site_data(context.pool()).await?;
206     let follows = CommunityFollowerView::for_community(context.pool(), id).await?;
207     let inboxes: Vec<Url> = follows
208       .into_iter()
209       .filter(|f| !f.follower.local)
210       .map(|f| {
211         f.follower
212           .shared_inbox_url
213           .unwrap_or(f.follower.inbox_url)
214           .into()
215       })
216       .unique()
217       .filter(|inbox: &Url| inbox.host_str() != Some(&context.settings().hostname))
218       // Don't send to blocked instances
219       .filter(|inbox| {
220         check_apub_id_valid_with_strictness(inbox, false, &local_site_data, context.settings())
221           .is_ok()
222       })
223       .collect();
224
225     Ok(inboxes)
226   }
227 }
228
229 #[cfg(test)]
230 pub(crate) mod tests {
231   use super::*;
232   use crate::{
233     objects::{instance::tests::parse_lemmy_instance, tests::init_context},
234     protocol::tests::file_to_json_object,
235   };
236   use lemmy_db_schema::{source::site::Site, traits::Crud};
237   use serial_test::serial;
238
239   pub(crate) async fn parse_lemmy_community(context: &LemmyContext) -> ApubCommunity {
240     let mut json: Group = file_to_json_object("assets/lemmy/objects/group.json").unwrap();
241     // change these links so they dont fetch over the network
242     json.moderators = None;
243     json.outbox =
244       ObjectId::new(Url::parse("https://enterprise.lemmy.ml/c/tenforward/not_outbox").unwrap());
245
246     let url = Url::parse("https://enterprise.lemmy.ml/c/tenforward").unwrap();
247     let mut request_counter = 0;
248     ApubCommunity::verify(&json, &url, context, &mut request_counter)
249       .await
250       .unwrap();
251     let community = ApubCommunity::from_apub(json, context, &mut request_counter)
252       .await
253       .unwrap();
254     // this makes one requests to the (intentionally broken) outbox collection
255     assert_eq!(request_counter, 1);
256     community
257   }
258
259   #[actix_rt::test]
260   #[serial]
261   async fn test_parse_lemmy_community() {
262     let context = init_context().await;
263     let site = parse_lemmy_instance(&context).await;
264     let community = parse_lemmy_community(&context).await;
265
266     assert_eq!(community.title, "Ten Forward");
267     assert!(!community.local);
268     assert_eq!(community.description.as_ref().unwrap().len(), 132);
269
270     Community::delete(context.pool(), community.id)
271       .await
272       .unwrap();
273     Site::delete(context.pool(), site.id).await.unwrap();
274   }
275 }