]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/community.rs
6e2f409a6b839e347136b7be715858462e1b7ae1
[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   generate_moderators_url,
5   generate_outbox_url,
6   local_instance,
7   objects::instance::fetch_instance_actor_for_object,
8   protocol::{
9     objects::{group::Group, Endpoints},
10     ImageObject,
11     Source,
12   },
13   ActorType,
14 };
15 use activitypub_federation::{
16   core::object_id::ObjectId,
17   traits::{Actor, ApubObject},
18 };
19 use activitystreams_kinds::actor::GroupType;
20 use chrono::NaiveDateTime;
21 use itertools::Itertools;
22 use lemmy_api_common::utils::blocking;
23 use lemmy_db_schema::{source::community::Community, traits::ApubActor};
24 use lemmy_db_views_actor::structs::CommunityFollowerView;
25 use lemmy_utils::{
26   error::LemmyError,
27   utils::{convert_datetime, markdown_to_html},
28 };
29 use lemmy_websocket::LemmyContext;
30 use std::ops::Deref;
31 use tracing::debug;
32 use url::Url;
33
34 #[derive(Clone, Debug)]
35 pub struct ApubCommunity(Community);
36
37 impl Deref for ApubCommunity {
38   type Target = Community;
39   fn deref(&self) -> &Self::Target {
40     &self.0
41   }
42 }
43
44 impl From<Community> for ApubCommunity {
45   fn from(c: Community) -> Self {
46     ApubCommunity(c)
47   }
48 }
49
50 #[async_trait::async_trait(?Send)]
51 impl ApubObject for ApubCommunity {
52   type DataType = LemmyContext;
53   type ApubType = Group;
54   type DbType = Community;
55   type Error = LemmyError;
56
57   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
58     Some(self.last_refreshed_at)
59   }
60
61   #[tracing::instrument(skip_all)]
62   async fn read_from_apub_id(
63     object_id: Url,
64     context: &LemmyContext,
65   ) -> Result<Option<Self>, LemmyError> {
66     Ok(
67       blocking(context.pool(), move |conn| {
68         Community::read_from_apub_id(conn, &object_id.into())
69       })
70       .await??
71       .map(Into::into),
72     )
73   }
74
75   #[tracing::instrument(skip_all)]
76   async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
77     blocking(context.pool(), move |conn| {
78       Community::update_deleted(conn, self.id, true)
79     })
80     .await??;
81     Ok(())
82   }
83
84   #[tracing::instrument(skip_all)]
85   async fn into_apub(self, _context: &LemmyContext) -> Result<Group, LemmyError> {
86     let group = Group {
87       kind: GroupType::Group,
88       id: ObjectId::new(self.actor_id()),
89       preferred_username: self.name.clone(),
90       name: Some(self.title.clone()),
91       summary: self.description.as_ref().map(|b| markdown_to_html(b)),
92       source: self.description.clone().map(Source::new),
93       icon: self.icon.clone().map(ImageObject::new),
94       image: self.banner.clone().map(ImageObject::new),
95       sensitive: Some(self.nsfw),
96       moderators: Some(ObjectId::<ApubCommunityModerators>::new(
97         generate_moderators_url(&self.actor_id)?,
98       )),
99       inbox: self.inbox_url.clone().into(),
100       outbox: ObjectId::new(generate_outbox_url(&self.actor_id)?),
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.get_public_key(),
106       published: Some(convert_datetime(self.published)),
107       updated: self.updated.map(convert_datetime),
108       posting_restricted_to_mods: Some(self.posting_restricted_to_mods),
109     };
110     Ok(group)
111   }
112
113   #[tracing::instrument(skip_all)]
114   async fn verify(
115     group: &Group,
116     expected_domain: &Url,
117     context: &LemmyContext,
118     _request_counter: &mut i32,
119   ) -> Result<(), LemmyError> {
120     group.verify(expected_domain, context).await
121   }
122
123   /// Converts a `Group` to `Community`, inserts it into the database and updates moderators.
124   #[tracing::instrument(skip_all)]
125   async fn from_apub(
126     group: Group,
127     context: &LemmyContext,
128     request_counter: &mut i32,
129   ) -> Result<ApubCommunity, LemmyError> {
130     let form = Group::into_form(group.clone());
131
132     // Fetching mods and outbox is not necessary for Lemmy to work, so ignore errors. Besides,
133     // we need to ignore these errors so that tests can work entirely offline.
134     let community: ApubCommunity =
135       blocking(context.pool(), move |conn| Community::upsert(conn, &form))
136         .await??
137         .into();
138     let outbox_data = CommunityContext(community.clone(), context.clone());
139
140     group
141       .outbox
142       .dereference(&outbox_data, local_instance(context), request_counter)
143       .await
144       .map_err(|e| debug!("{}", e))
145       .ok();
146
147     if let Some(moderators) = &group.moderators {
148       moderators
149         .dereference(&outbox_data, local_instance(context), request_counter)
150         .await
151         .map_err(|e| debug!("{}", e))
152         .ok();
153     }
154
155     fetch_instance_actor_for_object(community.actor_id(), context, request_counter).await;
156
157     Ok(community)
158   }
159 }
160
161 impl Actor for ApubCommunity {
162   fn public_key(&self) -> &str {
163     &self.public_key
164   }
165
166   fn inbox(&self) -> Url {
167     self.inbox_url.clone().into()
168   }
169
170   fn shared_inbox(&self) -> Option<Url> {
171     self.shared_inbox_url.clone().map(|s| s.into())
172   }
173 }
174
175 impl ActorType for ApubCommunity {
176   fn actor_id(&self) -> Url {
177     self.actor_id.to_owned().into()
178   }
179   fn private_key(&self) -> Option<String> {
180     self.private_key.to_owned()
181   }
182 }
183
184 impl ApubCommunity {
185   /// For a given community, returns the inboxes of all followers.
186   #[tracing::instrument(skip_all)]
187   pub(crate) async fn get_follower_inboxes(
188     &self,
189     context: &LemmyContext,
190   ) -> Result<Vec<Url>, LemmyError> {
191     let id = self.id;
192
193     let follows = blocking(context.pool(), move |conn| {
194       CommunityFollowerView::for_community(conn, id)
195     })
196     .await??;
197     let inboxes: Vec<Url> = follows
198       .into_iter()
199       .filter(|f| !f.follower.local)
200       .map(|f| {
201         f.follower
202           .shared_inbox_url
203           .unwrap_or(f.follower.inbox_url)
204           .into()
205       })
206       .unique()
207       .filter(|inbox: &Url| inbox.host_str() != Some(&context.settings().hostname))
208       // Don't send to blocked instances
209       .filter(|inbox| check_apub_id_valid_with_strictness(inbox, false, context.settings()).is_ok())
210       .collect();
211
212     Ok(inboxes)
213   }
214 }
215
216 #[cfg(test)]
217 pub(crate) mod tests {
218   use super::*;
219   use crate::{
220     objects::{instance::tests::parse_lemmy_instance, tests::init_context},
221     protocol::tests::file_to_json_object,
222   };
223   use lemmy_db_schema::{source::site::Site, traits::Crud};
224   use serial_test::serial;
225
226   pub(crate) async fn parse_lemmy_community(context: &LemmyContext) -> ApubCommunity {
227     let mut json: Group = file_to_json_object("assets/lemmy/objects/group.json").unwrap();
228     // change these links so they dont fetch over the network
229     json.moderators = None;
230     json.outbox =
231       ObjectId::new(Url::parse("https://enterprise.lemmy.ml/c/tenforward/not_outbox").unwrap());
232
233     let url = Url::parse("https://enterprise.lemmy.ml/c/tenforward").unwrap();
234     let mut request_counter = 0;
235     ApubCommunity::verify(&json, &url, context, &mut request_counter)
236       .await
237       .unwrap();
238     let community = ApubCommunity::from_apub(json, context, &mut request_counter)
239       .await
240       .unwrap();
241     // this makes one requests to the (intentionally broken) outbox collection
242     assert_eq!(request_counter, 1);
243     community
244   }
245
246   #[actix_rt::test]
247   #[serial]
248   async fn test_parse_lemmy_community() {
249     let context = init_context();
250     let site = parse_lemmy_instance(&context).await;
251     let community = parse_lemmy_community(&context).await;
252
253     assert_eq!(community.title, "Ten Forward");
254     assert!(!community.local);
255     assert_eq!(community.description.as_ref().unwrap().len(), 132);
256
257     Community::delete(&*context.pool().get().unwrap(), community.id).unwrap();
258     Site::delete(&*context.pool().get().unwrap(), site.id).unwrap();
259   }
260 }