]> Untitled Git - lemmy.git/blob - server/src/apub/community.rs
3773b8fb4d5ab59faeb47961fa84ddfb75e0e4ce
[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::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     Ok(CommunityForm {
365       name,
366       title,
367       description,
368       category_id: group.ext_one.category.identifier.parse::<i32>()?,
369       creator_id: creator.id,
370       removed: None,
371       published: group.inner.published().map(|u| u.to_owned().naive_local()),
372       updated: group.inner.updated().map(|u| u.to_owned().naive_local()),
373       deleted: None,
374       nsfw: group.ext_one.sensitive,
375       actor_id: check_actor_domain(group, expected_domain)?,
376       local: false,
377       private_key: None,
378       public_key: Some(group.ext_two.to_owned().public_key.public_key_pem),
379       last_refreshed_at: Some(naive_now()),
380     })
381   }
382 }
383
384 /// Return the community json over HTTP.
385 pub async fn get_apub_community_http(
386   info: web::Path<CommunityQuery>,
387   db: DbPoolParam,
388 ) -> Result<HttpResponse<Body>, LemmyError> {
389   let community = blocking(&db, move |conn| {
390     Community::read_from_name(conn, &info.community_name)
391   })
392   .await??;
393
394   if !community.deleted {
395     let apub = community.to_apub(&db).await?;
396
397     Ok(create_apub_response(&apub))
398   } else {
399     Ok(create_apub_tombstone_response(&community.to_tombstone()?))
400   }
401 }
402
403 /// Returns an empty followers collection, only populating the size (for privacy).
404 pub async fn get_apub_community_followers(
405   info: web::Path<CommunityQuery>,
406   db: DbPoolParam,
407 ) -> Result<HttpResponse<Body>, LemmyError> {
408   let community = blocking(&db, move |conn| {
409     Community::read_from_name(&conn, &info.community_name)
410   })
411   .await??;
412
413   let community_id = community.id;
414   let community_followers = blocking(&db, move |conn| {
415     CommunityFollowerView::for_community(&conn, community_id)
416   })
417   .await??;
418
419   let mut collection = UnorderedCollection::new();
420   collection
421     .set_context(context())
422     // TODO: this needs its own ID
423     .set_id(community.actor_id.parse()?)
424     .set_total_items(community_followers.len() as u64);
425   Ok(create_apub_response(&collection))
426 }
427
428 pub async fn get_apub_community_outbox(
429   info: web::Path<CommunityQuery>,
430   db: DbPoolParam,
431 ) -> Result<HttpResponse<Body>, LemmyError> {
432   let community = blocking(&db, move |conn| {
433     Community::read_from_name(&conn, &info.community_name)
434   })
435   .await??;
436
437   let community_id = community.id;
438   let posts = blocking(&db, move |conn| {
439     Post::list_for_community(conn, community_id)
440   })
441   .await??;
442
443   let mut pages: Vec<AnyBase> = vec![];
444   for p in posts {
445     pages.push(p.to_apub(&db).await?.into_any_base()?);
446   }
447
448   let len = pages.len();
449   let mut collection = OrderedCollection::new();
450   collection
451     .set_many_items(pages)
452     .set_context(context())
453     .set_id(community.get_outbox_url()?)
454     .set_total_items(len as u64);
455   Ok(create_apub_response(&collection))
456 }
457
458 pub async fn do_announce(
459   activity: AnyBase,
460   community: &Community,
461   sender: &User_,
462   client: &Client,
463   pool: &DbPool,
464 ) -> Result<(), LemmyError> {
465   let mut announce = Announce::new(community.actor_id.to_owned(), activity);
466   announce
467     .set_context(context())
468     .set_id(generate_activity_id(AnnounceType::Announce)?)
469     .set_to(public())
470     .set_many_ccs(vec![community.get_followers_url()]);
471
472   insert_activity(community.creator_id, announce.clone(), true, pool).await?;
473
474   let mut to = community.get_follower_inboxes(pool).await?;
475
476   // dont send to the local instance, nor to the instance where the activity originally came from,
477   // because that would result in a database error (same data inserted twice)
478   // this seems to be the "easiest" stable alternative for remove_item()
479   to.retain(|x| *x != sender.get_shared_inbox_url());
480   to.retain(|x| *x != community.get_shared_inbox_url());
481
482   send_activity(client, &announce.into_any_base()?, community, to).await?;
483
484   Ok(())
485 }