]> Untitled Git - lemmy.git/blob - server/src/apub/community.rs
Merge branch 'main' into federation-authorisation
[lemmy.git] / server / src / apub / community.rs
1 use crate::{
2   api::{check_slurs, check_slurs_opt},
3   apub::{
4     activities::{generate_activity_id, send_activity},
5     check_actor_domain,
6     create_apub_response,
7     create_apub_tombstone_response,
8     create_tombstone,
9     extensions::group_extensions::GroupExtension,
10     fetcher::get_or_fetch_and_upsert_user,
11     get_shared_inbox,
12     insert_activity,
13     ActorType,
14     FromApub,
15     GroupExt,
16     ToApub,
17   },
18   blocking,
19   routes::DbPoolParam,
20   DbPool,
21   LemmyError,
22 };
23 use activitystreams::{
24   activity::{
25     kind::{AcceptType, AnnounceType, DeleteType, LikeType, RemoveType, UndoType},
26     Accept,
27     Announce,
28     Delete,
29     Follow,
30     Remove,
31     Undo,
32   },
33   actor::{kind::GroupType, ApActor, Endpoints, Group},
34   base::{AnyBase, BaseExt},
35   collection::{OrderedCollection, UnorderedCollection},
36   context,
37   object::{Image, Tombstone},
38   prelude::*,
39   public,
40 };
41 use activitystreams_ext::Ext2;
42 use actix_web::{body::Body, client::Client, web, HttpResponse};
43 use itertools::Itertools;
44 use lemmy_db::{
45   community::{Community, CommunityForm},
46   community_view::{CommunityFollowerView, CommunityModeratorView},
47   naive_now,
48   post::Post,
49   user::User_,
50 };
51 use lemmy_utils::convert_datetime;
52 use serde::Deserialize;
53 use url::Url;
54
55 #[derive(Deserialize)]
56 pub struct CommunityQuery {
57   community_name: String,
58 }
59
60 #[async_trait::async_trait(?Send)]
61 impl ToApub for Community {
62   type Response = GroupExt;
63
64   // Turn a Lemmy Community into an ActivityPub group that can be sent out over the network.
65   async fn to_apub(&self, pool: &DbPool) -> Result<GroupExt, LemmyError> {
66     // The attributed to, is an ordered vector with the creator actor_ids first,
67     // then the rest of the moderators
68     // TODO Technically the instance admins can mod the community, but lets
69     // ignore that for now
70     let id = self.id;
71     let moderators = blocking(pool, move |conn| {
72       CommunityModeratorView::for_community(&conn, id)
73     })
74     .await??;
75     let moderators: Vec<String> = moderators.into_iter().map(|m| m.user_actor_id).collect();
76
77     let mut group = Group::new();
78     group
79       .set_context(context())
80       .set_id(Url::parse(&self.actor_id)?)
81       .set_name(self.name.to_owned())
82       .set_published(convert_datetime(self.published))
83       .set_many_attributed_tos(moderators);
84
85     if let Some(u) = self.updated.to_owned() {
86       group.set_updated(convert_datetime(u));
87     }
88     if let Some(d) = self.description.to_owned() {
89       // TODO: this should be html, also add source field with raw markdown
90       //       -> same for post.content and others
91       group.set_content(d);
92     }
93
94     let mut ap_actor = ApActor::new(self.get_inbox_url()?, group);
95     ap_actor
96       .set_preferred_username(self.title.to_owned())
97       .set_outbox(self.get_outbox_url()?)
98       .set_followers(self.get_followers_url().parse()?)
99       .set_following(self.get_following_url().parse()?)
100       .set_liked(self.get_liked_url().parse()?)
101       .set_endpoints(Endpoints {
102         shared_inbox: Some(self.get_shared_inbox_url().parse()?),
103         ..Default::default()
104       });
105
106     let nsfw = self.nsfw;
107     let category_id = self.category_id;
108     let group_extension = blocking(pool, move |conn| {
109       GroupExtension::new(conn, category_id, nsfw)
110     })
111     .await??;
112
113     Ok(Ext2::new(
114       ap_actor,
115       group_extension,
116       self.get_public_key_ext(),
117     ))
118   }
119
120   fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
121     create_tombstone(self.deleted, &self.actor_id, self.updated, GroupType::Group)
122   }
123 }
124
125 #[async_trait::async_trait(?Send)]
126 impl ActorType for Community {
127   fn actor_id_str(&self) -> String {
128     self.actor_id.to_owned()
129   }
130
131   fn public_key(&self) -> String {
132     self.public_key.to_owned().unwrap()
133   }
134   fn private_key(&self) -> String {
135     self.private_key.to_owned().unwrap()
136   }
137
138   /// As a local community, accept the follow request from a remote user.
139   async fn send_accept_follow(
140     &self,
141     follow: Follow,
142     client: &Client,
143     pool: &DbPool,
144   ) -> Result<(), LemmyError> {
145     let actor_uri = follow.actor()?.as_single_xsd_any_uri().unwrap().to_string();
146
147     let mut accept = Accept::new(self.actor_id.to_owned(), follow.into_any_base()?);
148     let to = format!("{}/inbox", actor_uri);
149     accept
150       .set_context(context())
151       .set_id(generate_activity_id(AcceptType::Accept)?)
152       .set_to(to.clone());
153
154     insert_activity(self.creator_id, accept.clone(), true, pool).await?;
155
156     send_activity(client, &accept.into_any_base()?, self, vec![to]).await?;
157     Ok(())
158   }
159
160   async fn send_delete(
161     &self,
162     creator: &User_,
163     client: &Client,
164     pool: &DbPool,
165   ) -> Result<(), LemmyError> {
166     let group = self.to_apub(pool).await?;
167
168     let mut delete = Delete::new(creator.actor_id.to_owned(), group.into_any_base()?);
169     delete
170       .set_context(context())
171       .set_id(generate_activity_id(DeleteType::Delete)?)
172       .set_to(public())
173       .set_many_ccs(vec![self.get_followers_url()]);
174
175     insert_activity(self.creator_id, delete.clone(), true, pool).await?;
176
177     let inboxes = self.get_follower_inboxes(pool).await?;
178
179     // Note: For an accept, since it was automatic, no one pushed a button,
180     // the community was the actor.
181     // But for delete, the creator is the actor, and does the signing
182     send_activity(client, &delete.into_any_base()?, creator, inboxes).await?;
183     Ok(())
184   }
185
186   async fn send_undo_delete(
187     &self,
188     creator: &User_,
189     client: &Client,
190     pool: &DbPool,
191   ) -> Result<(), LemmyError> {
192     let group = self.to_apub(pool).await?;
193
194     let mut delete = Delete::new(creator.actor_id.to_owned(), group.into_any_base()?);
195     delete
196       .set_context(context())
197       .set_id(generate_activity_id(DeleteType::Delete)?)
198       .set_to(public())
199       .set_many_ccs(vec![self.get_followers_url()]);
200
201     // TODO
202     // Undo that fake activity
203     let mut undo = Undo::new(creator.actor_id.to_owned(), delete.into_any_base()?);
204     undo
205       .set_context(context())
206       .set_id(generate_activity_id(UndoType::Undo)?)
207       .set_to(public())
208       .set_many_ccs(vec![self.get_followers_url()]);
209
210     insert_activity(self.creator_id, undo.clone(), true, pool).await?;
211
212     let inboxes = self.get_follower_inboxes(pool).await?;
213
214     // Note: For an accept, since it was automatic, no one pushed a button,
215     // the community was the actor.
216     // But for delete, the creator is the actor, and does the signing
217     send_activity(client, &undo.into_any_base()?, creator, inboxes).await?;
218     Ok(())
219   }
220
221   async fn send_remove(
222     &self,
223     mod_: &User_,
224     client: &Client,
225     pool: &DbPool,
226   ) -> Result<(), LemmyError> {
227     let group = self.to_apub(pool).await?;
228
229     let mut remove = Remove::new(mod_.actor_id.to_owned(), group.into_any_base()?);
230     remove
231       .set_context(context())
232       .set_id(generate_activity_id(RemoveType::Remove)?)
233       .set_to(public())
234       .set_many_ccs(vec![self.get_followers_url()]);
235
236     insert_activity(mod_.id, remove.clone(), true, pool).await?;
237
238     let inboxes = self.get_follower_inboxes(pool).await?;
239
240     // Note: For an accept, since it was automatic, no one pushed a button,
241     // the community was the actor.
242     // But for delete, the creator is the actor, and does the signing
243     send_activity(client, &remove.into_any_base()?, mod_, inboxes).await?;
244     Ok(())
245   }
246
247   async fn send_undo_remove(
248     &self,
249     mod_: &User_,
250     client: &Client,
251     pool: &DbPool,
252   ) -> Result<(), LemmyError> {
253     let group = self.to_apub(pool).await?;
254
255     let mut remove = Remove::new(mod_.actor_id.to_owned(), group.into_any_base()?);
256     remove
257       .set_context(context())
258       .set_id(generate_activity_id(RemoveType::Remove)?)
259       .set_to(public())
260       .set_many_ccs(vec![self.get_followers_url()]);
261
262     // Undo that fake activity
263     let mut undo = Undo::new(mod_.actor_id.to_owned(), remove.into_any_base()?);
264     undo
265       .set_context(context())
266       .set_id(generate_activity_id(LikeType::Like)?)
267       .set_to(public())
268       .set_many_ccs(vec![self.get_followers_url()]);
269
270     insert_activity(mod_.id, undo.clone(), true, pool).await?;
271
272     let inboxes = self.get_follower_inboxes(pool).await?;
273
274     // Note: For an accept, since it was automatic, no one pushed a button,
275     // the community was the actor.
276     // But for remove , the creator is the actor, and does the signing
277     send_activity(client, &undo.into_any_base()?, mod_, inboxes).await?;
278     Ok(())
279   }
280
281   /// For a given community, returns the inboxes of all followers.
282   async fn get_follower_inboxes(&self, pool: &DbPool) -> Result<Vec<String>, LemmyError> {
283     let id = self.id;
284
285     let inboxes = blocking(pool, move |conn| {
286       CommunityFollowerView::for_community(conn, id)
287     })
288     .await??;
289     let inboxes = inboxes
290       .into_iter()
291       .map(|c| get_shared_inbox(&Url::parse(&c.user_actor_id).unwrap()))
292       .filter(|s| !s.is_empty())
293       .unique()
294       .collect();
295
296     Ok(inboxes)
297   }
298
299   async fn send_follow(
300     &self,
301     _follow_actor_id: &str,
302     _client: &Client,
303     _pool: &DbPool,
304   ) -> Result<(), LemmyError> {
305     unimplemented!()
306   }
307
308   async fn send_unfollow(
309     &self,
310     _follow_actor_id: &str,
311     _client: &Client,
312     _pool: &DbPool,
313   ) -> Result<(), LemmyError> {
314     unimplemented!()
315   }
316
317   fn user_id(&self) -> i32 {
318     self.creator_id
319   }
320 }
321
322 #[async_trait::async_trait(?Send)]
323 impl FromApub for CommunityForm {
324   type ApubType = GroupExt;
325
326   /// Parse an ActivityPub group received from another instance into a Lemmy community.
327   async fn from_apub(
328     group: &GroupExt,
329     client: &Client,
330     pool: &DbPool,
331     expected_domain: Option<Url>,
332   ) -> Result<Self, LemmyError> {
333     let creator_and_moderator_uris = group.inner.attributed_to().unwrap();
334     let creator_uri = creator_and_moderator_uris
335       .as_many()
336       .unwrap()
337       .iter()
338       .next()
339       .unwrap()
340       .as_xsd_any_uri()
341       .unwrap();
342
343     let creator = get_or_fetch_and_upsert_user(creator_uri, client, pool).await?;
344     let name = group
345       .inner
346       .name()
347       .unwrap()
348       .as_one()
349       .unwrap()
350       .as_xsd_string()
351       .unwrap()
352       .to_string();
353     let title = group.inner.preferred_username().unwrap().to_string();
354     // TODO: should be parsed as html and tags like <script> removed (or use markdown source)
355     //       -> same for post.content etc
356     let description = group
357       .inner
358       .content()
359       .map(|s| s.as_single_xsd_string().unwrap().into());
360     check_slurs(&name)?;
361     check_slurs(&title)?;
362     check_slurs_opt(&description)?;
363
364     let icon = match group.icon() {
365       Some(any_image) => Some(
366         Image::from_any_base(any_image.as_one().unwrap().clone())
367           .unwrap()
368           .unwrap()
369           .url()
370           .unwrap()
371           .as_single_xsd_any_uri()
372           .map(|u| u.to_string()),
373       ),
374       None => None,
375     };
376
377     let banner = match group.image() {
378       Some(any_image) => Some(
379         Image::from_any_base(any_image.as_one().unwrap().clone())
380           .unwrap()
381           .unwrap()
382           .url()
383           .unwrap()
384           .as_single_xsd_any_uri()
385           .map(|u| u.to_string()),
386       ),
387       None => None,
388     };
389
390     Ok(CommunityForm {
391       name,
392       title,
393       description,
394       category_id: group.ext_one.category.identifier.parse::<i32>()?,
395       creator_id: creator.id,
396       removed: None,
397       published: group.inner.published().map(|u| u.to_owned().naive_local()),
398       updated: group.inner.updated().map(|u| u.to_owned().naive_local()),
399       deleted: None,
400       nsfw: group.ext_one.sensitive,
401       actor_id: check_actor_domain(group, expected_domain)?,
402       local: false,
403       private_key: None,
404       public_key: Some(group.ext_two.to_owned().public_key.public_key_pem),
405       last_refreshed_at: Some(naive_now()),
406       icon,
407       banner,
408     })
409   }
410 }
411
412 /// Return the community json over HTTP.
413 pub async fn get_apub_community_http(
414   info: web::Path<CommunityQuery>,
415   db: DbPoolParam,
416 ) -> Result<HttpResponse<Body>, LemmyError> {
417   let community = blocking(&db, move |conn| {
418     Community::read_from_name(conn, &info.community_name)
419   })
420   .await??;
421
422   if !community.deleted {
423     let apub = community.to_apub(&db).await?;
424
425     Ok(create_apub_response(&apub))
426   } else {
427     Ok(create_apub_tombstone_response(&community.to_tombstone()?))
428   }
429 }
430
431 /// Returns an empty followers collection, only populating the size (for privacy).
432 pub async fn get_apub_community_followers(
433   info: web::Path<CommunityQuery>,
434   db: DbPoolParam,
435 ) -> Result<HttpResponse<Body>, LemmyError> {
436   let community = blocking(&db, move |conn| {
437     Community::read_from_name(&conn, &info.community_name)
438   })
439   .await??;
440
441   let community_id = community.id;
442   let community_followers = blocking(&db, move |conn| {
443     CommunityFollowerView::for_community(&conn, community_id)
444   })
445   .await??;
446
447   let mut collection = UnorderedCollection::new();
448   collection
449     .set_context(context())
450     // TODO: this needs its own ID
451     .set_id(community.actor_id.parse()?)
452     .set_total_items(community_followers.len() as u64);
453   Ok(create_apub_response(&collection))
454 }
455
456 pub async fn get_apub_community_outbox(
457   info: web::Path<CommunityQuery>,
458   db: DbPoolParam,
459 ) -> Result<HttpResponse<Body>, LemmyError> {
460   let community = blocking(&db, move |conn| {
461     Community::read_from_name(&conn, &info.community_name)
462   })
463   .await??;
464
465   let community_id = community.id;
466   let posts = blocking(&db, move |conn| {
467     Post::list_for_community(conn, community_id)
468   })
469   .await??;
470
471   let mut pages: Vec<AnyBase> = vec![];
472   for p in posts {
473     pages.push(p.to_apub(&db).await?.into_any_base()?);
474   }
475
476   let len = pages.len();
477   let mut collection = OrderedCollection::new();
478   collection
479     .set_many_items(pages)
480     .set_context(context())
481     .set_id(community.get_outbox_url()?)
482     .set_total_items(len as u64);
483   Ok(create_apub_response(&collection))
484 }
485
486 pub async fn do_announce(
487   activity: AnyBase,
488   community: &Community,
489   sender: &User_,
490   client: &Client,
491   pool: &DbPool,
492 ) -> Result<(), LemmyError> {
493   let mut announce = Announce::new(community.actor_id.to_owned(), activity);
494   announce
495     .set_context(context())
496     .set_id(generate_activity_id(AnnounceType::Announce)?)
497     .set_to(public())
498     .set_many_ccs(vec![community.get_followers_url()]);
499
500   insert_activity(community.creator_id, announce.clone(), true, pool).await?;
501
502   let mut to = community.get_follower_inboxes(pool).await?;
503
504   // dont send to the local instance, nor to the instance where the activity originally came from,
505   // because that would result in a database error (same data inserted twice)
506   // this seems to be the "easiest" stable alternative for remove_item()
507   to.retain(|x| *x != sender.get_shared_inbox_url());
508   to.retain(|x| *x != community.get_shared_inbox_url());
509
510   send_activity(client, &announce.into_any_base()?, community, to).await?;
511
512   Ok(())
513 }