]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/community.rs
When receiving activity, dont read community from cc (for pleroma compat and better...
[lemmy.git] / crates / apub / src / objects / community.rs
1 use crate::{
2   check_is_apub_id_valid,
3   collections::{
4     community_moderators::ApubCommunityModerators,
5     community_outbox::ApubCommunityOutbox,
6     CommunityContext,
7   },
8   context::lemmy_context,
9   fetcher::object_id::ObjectId,
10   generate_moderators_url,
11   generate_outbox_url,
12   objects::{get_summary_from_string_or_source, tombstone::Tombstone, ImageObject, Source},
13 };
14 use activitystreams::{
15   actor::{kind::GroupType, Endpoints},
16   base::AnyBase,
17   chrono::NaiveDateTime,
18   object::kind::ImageType,
19   primitives::OneOrMany,
20   unparsed::Unparsed,
21 };
22 use chrono::{DateTime, FixedOffset};
23 use itertools::Itertools;
24 use lemmy_api_common::blocking;
25 use lemmy_apub_lib::{
26   signatures::PublicKey,
27   traits::{ActorType, ApubObject},
28   values::MediaTypeMarkdown,
29   verify::verify_domains_match,
30 };
31 use lemmy_db_schema::{
32   naive_now,
33   source::community::{Community, CommunityForm},
34   DbPool,
35 };
36 use lemmy_db_views_actor::community_follower_view::CommunityFollowerView;
37 use lemmy_utils::{
38   settings::structs::Settings,
39   utils::{check_slurs, check_slurs_opt, convert_datetime, markdown_to_html},
40   LemmyError,
41 };
42 use lemmy_websocket::LemmyContext;
43 use log::debug;
44 use serde::{Deserialize, Serialize};
45 use serde_with::skip_serializing_none;
46 use std::ops::Deref;
47 use url::Url;
48
49 #[skip_serializing_none]
50 #[derive(Clone, Debug, Deserialize, Serialize)]
51 #[serde(rename_all = "camelCase")]
52 pub struct Group {
53   #[serde(rename = "@context")]
54   context: OneOrMany<AnyBase>,
55   #[serde(rename = "type")]
56   kind: GroupType,
57   pub(crate) id: Url,
58   /// username, set at account creation and can never be changed
59   preferred_username: String,
60   /// title (can be changed at any time)
61   name: String,
62   summary: Option<String>,
63   source: Option<Source>,
64   icon: Option<ImageObject>,
65   /// banner
66   image: Option<ImageObject>,
67   // lemmy extension
68   sensitive: Option<bool>,
69   // lemmy extension
70   pub(crate) moderators: Option<ObjectId<ApubCommunityModerators>>,
71   inbox: Url,
72   pub(crate) outbox: ObjectId<ApubCommunityOutbox>,
73   followers: Url,
74   endpoints: Endpoints<Url>,
75   public_key: PublicKey,
76   published: Option<DateTime<FixedOffset>>,
77   updated: Option<DateTime<FixedOffset>>,
78   #[serde(flatten)]
79   unparsed: Unparsed,
80 }
81
82 impl Group {
83   pub(crate) async fn from_apub_to_form(
84     group: &Group,
85     expected_domain: &Url,
86     settings: &Settings,
87   ) -> Result<CommunityForm, LemmyError> {
88     verify_domains_match(expected_domain, &group.id)?;
89     let name = group.preferred_username.clone();
90     let title = group.name.clone();
91     let description = get_summary_from_string_or_source(&group.summary, &group.source);
92     let shared_inbox = group.endpoints.shared_inbox.clone().map(|s| s.into());
93
94     let slur_regex = &settings.slur_regex();
95     check_slurs(&name, slur_regex)?;
96     check_slurs(&title, slur_regex)?;
97     check_slurs_opt(&description, slur_regex)?;
98
99     Ok(CommunityForm {
100       name,
101       title,
102       description,
103       removed: None,
104       published: group.published.map(|u| u.naive_local()),
105       updated: group.updated.map(|u| u.naive_local()),
106       deleted: None,
107       nsfw: Some(group.sensitive.unwrap_or(false)),
108       actor_id: Some(group.id.clone().into()),
109       local: Some(false),
110       private_key: None,
111       public_key: Some(group.public_key.public_key_pem.clone()),
112       last_refreshed_at: Some(naive_now()),
113       icon: Some(group.icon.clone().map(|i| i.url.into())),
114       banner: Some(group.image.clone().map(|i| i.url.into())),
115       followers_url: Some(group.followers.clone().into()),
116       inbox_url: Some(group.inbox.clone().into()),
117       shared_inbox_url: Some(shared_inbox),
118     })
119   }
120 }
121
122 #[derive(Clone, Debug)]
123 pub struct ApubCommunity(Community);
124
125 impl Deref for ApubCommunity {
126   type Target = Community;
127   fn deref(&self) -> &Self::Target {
128     &self.0
129   }
130 }
131
132 impl From<Community> for ApubCommunity {
133   fn from(c: Community) -> Self {
134     ApubCommunity { 0: c }
135   }
136 }
137
138 #[async_trait::async_trait(?Send)]
139 impl ApubObject for ApubCommunity {
140   type DataType = LemmyContext;
141   type ApubType = Group;
142   type TombstoneType = Tombstone;
143
144   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
145     Some(self.last_refreshed_at)
146   }
147
148   async fn read_from_apub_id(
149     object_id: Url,
150     context: &LemmyContext,
151   ) -> Result<Option<Self>, LemmyError> {
152     Ok(
153       blocking(context.pool(), move |conn| {
154         Community::read_from_apub_id(conn, object_id)
155       })
156       .await??
157       .map(Into::into),
158     )
159   }
160
161   async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
162     blocking(context.pool(), move |conn| {
163       Community::update_deleted(conn, self.id, true)
164     })
165     .await??;
166     Ok(())
167   }
168
169   async fn to_apub(&self, _context: &LemmyContext) -> Result<Group, LemmyError> {
170     let source = self.description.clone().map(|bio| Source {
171       content: bio,
172       media_type: MediaTypeMarkdown::Markdown,
173     });
174     let icon = self.icon.clone().map(|url| ImageObject {
175       kind: ImageType::Image,
176       url: url.into(),
177     });
178     let image = self.banner.clone().map(|url| ImageObject {
179       kind: ImageType::Image,
180       url: url.into(),
181     });
182
183     let group = Group {
184       context: lemmy_context(),
185       kind: GroupType::Group,
186       id: self.actor_id(),
187       preferred_username: self.name.clone(),
188       name: self.title.clone(),
189       summary: self.description.as_ref().map(|b| markdown_to_html(b)),
190       source,
191       icon,
192       image,
193       sensitive: Some(self.nsfw),
194       moderators: Some(ObjectId::<ApubCommunityModerators>::new(
195         generate_moderators_url(&self.actor_id)?.into_inner(),
196       )),
197       inbox: self.inbox_url.clone().into(),
198       outbox: ObjectId::new(generate_outbox_url(&self.actor_id)?),
199       followers: self.followers_url.clone().into(),
200       endpoints: Endpoints {
201         shared_inbox: self.shared_inbox_url.clone().map(|s| s.into()),
202         ..Default::default()
203       },
204       public_key: self.get_public_key()?,
205       published: Some(convert_datetime(self.published)),
206       updated: self.updated.map(convert_datetime),
207       unparsed: Default::default(),
208     };
209     Ok(group)
210   }
211
212   fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
213     Ok(Tombstone::new(
214       GroupType::Group,
215       self.updated.unwrap_or(self.published),
216     ))
217   }
218
219   /// Converts a `Group` to `Community`, inserts it into the database and updates moderators.
220   async fn from_apub(
221     group: &Group,
222     context: &LemmyContext,
223     expected_domain: &Url,
224     request_counter: &mut i32,
225   ) -> Result<ApubCommunity, LemmyError> {
226     let form = Group::from_apub_to_form(group, expected_domain, &context.settings()).await?;
227
228     // Fetching mods and outbox is not necessary for Lemmy to work, so ignore errors. Besides,
229     // we need to ignore these errors so that tests can work entirely offline.
230     let community: ApubCommunity =
231       blocking(context.pool(), move |conn| Community::upsert(conn, &form))
232         .await??
233         .into();
234     let outbox_data = CommunityContext(community.clone(), context.clone());
235
236     group
237       .outbox
238       .dereference(&outbox_data, request_counter)
239       .await
240       .map_err(|e| debug!("{}", e))
241       .ok();
242
243     if let Some(moderators) = &group.moderators {
244       moderators
245         .dereference(&outbox_data, request_counter)
246         .await
247         .map_err(|e| debug!("{}", e))
248         .ok();
249     }
250
251     Ok(community)
252   }
253 }
254
255 impl ActorType for ApubCommunity {
256   fn is_local(&self) -> bool {
257     self.local
258   }
259   fn actor_id(&self) -> Url {
260     self.actor_id.to_owned().into()
261   }
262   fn name(&self) -> String {
263     self.name.clone()
264   }
265   fn public_key(&self) -> Option<String> {
266     self.public_key.to_owned()
267   }
268   fn private_key(&self) -> Option<String> {
269     self.private_key.to_owned()
270   }
271
272   fn inbox_url(&self) -> Url {
273     self.inbox_url.clone().into()
274   }
275
276   fn shared_inbox_url(&self) -> Option<Url> {
277     self.shared_inbox_url.clone().map(|s| s.into_inner())
278   }
279 }
280
281 impl ApubCommunity {
282   /// For a given community, returns the inboxes of all followers.
283   pub(crate) async fn get_follower_inboxes(
284     &self,
285     pool: &DbPool,
286     settings: &Settings,
287   ) -> Result<Vec<Url>, LemmyError> {
288     let id = self.id;
289
290     let follows = blocking(pool, move |conn| {
291       CommunityFollowerView::for_community(conn, id)
292     })
293     .await??;
294     let inboxes = follows
295       .into_iter()
296       .filter(|f| !f.follower.local)
297       .map(|f| f.follower.shared_inbox_url.unwrap_or(f.follower.inbox_url))
298       .map(|i| i.into_inner())
299       .unique()
300       // Don't send to blocked instances
301       .filter(|inbox| check_is_apub_id_valid(inbox, false, settings).is_ok())
302       .collect();
303
304     Ok(inboxes)
305   }
306 }
307
308 #[cfg(test)]
309 mod tests {
310   use super::*;
311   use crate::objects::tests::{file_to_json_object, init_context};
312   use assert_json_diff::assert_json_include;
313   use lemmy_db_schema::traits::Crud;
314   use serial_test::serial;
315
316   #[actix_rt::test]
317   #[serial]
318   async fn test_parse_lemmy_community() {
319     let context = init_context();
320     let mut json: Group = file_to_json_object("assets/lemmy-community.json");
321     let json_orig = json.clone();
322     // change these links so they dont fetch over the network
323     json.moderators = Some(ObjectId::new(
324       Url::parse("https://enterprise.lemmy.ml/c/tenforward/not_moderators").unwrap(),
325     ));
326     json.outbox =
327       ObjectId::new(Url::parse("https://enterprise.lemmy.ml/c/tenforward/not_outbox").unwrap());
328
329     let url = Url::parse("https://enterprise.lemmy.ml/c/tenforward").unwrap();
330     let mut request_counter = 0;
331     let community = ApubCommunity::from_apub(&json, &context, &url, &mut request_counter)
332       .await
333       .unwrap();
334
335     assert_eq!(community.actor_id.clone().into_inner(), url);
336     assert_eq!(community.title, "Ten Forward");
337     assert!(community.public_key.is_some());
338     assert!(!community.local);
339     assert_eq!(community.description.as_ref().unwrap().len(), 132);
340     // this makes two requests to the (intentionally) broken outbox/moderators collections
341     assert_eq!(request_counter, 2);
342
343     let to_apub = community.to_apub(&context).await.unwrap();
344     assert_json_include!(actual: json_orig, expected: to_apub);
345
346     Community::delete(&*context.pool().get().unwrap(), community.id).unwrap();
347   }
348 }