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