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