3 activities::{generate_activity_id, send_activity},
5 create_apub_tombstone_response,
7 extensions::group_extensions::GroupExtension,
8 fetcher::get_or_fetch_and_upsert_user,
21 use activitystreams::{
23 kind::{AcceptType, AnnounceType, DeleteType, LikeType, RemoveType, UndoType},
31 actor::{kind::GroupType, ApActor, Endpoints, Group},
32 base::{AnyBase, BaseExt},
33 collection::{OrderedCollection, UnorderedCollection},
35 object::{Image, Tombstone},
39 use activitystreams_ext::Ext2;
40 use actix_web::{body::Body, client::Client, web, HttpResponse};
41 use itertools::Itertools;
43 community::{Community, CommunityForm},
44 community_view::{CommunityFollowerView, CommunityModeratorView},
49 use lemmy_utils::convert_datetime;
50 use serde::Deserialize;
53 #[derive(Deserialize)]
54 pub struct CommunityQuery {
55 community_name: String,
58 #[async_trait::async_trait(?Send)]
59 impl ToApub for Community {
60 type Response = GroupExt;
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
69 let moderators = blocking(pool, move |conn| {
70 CommunityModeratorView::for_community(&conn, id)
73 let moderators: Vec<String> = moderators.into_iter().map(|m| m.user_actor_id).collect();
75 let mut group = Group::new();
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);
83 if let Some(u) = self.updated.to_owned() {
84 group.set_updated(convert_datetime(u));
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
92 let mut ap_actor = ApActor::new(self.get_inbox_url()?, group);
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()?),
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)
114 self.get_public_key_ext(),
118 fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
119 create_tombstone(self.deleted, &self.actor_id, self.updated, GroupType::Group)
123 #[async_trait::async_trait(?Send)]
124 impl ActorType for Community {
125 fn actor_id_str(&self) -> String {
126 self.actor_id.to_owned()
129 fn public_key(&self) -> String {
130 self.public_key.to_owned().unwrap()
132 fn private_key(&self) -> String {
133 self.private_key.to_owned().unwrap()
136 /// As a local community, accept the follow request from a remote user.
137 async fn send_accept_follow(
142 ) -> Result<(), LemmyError> {
143 let actor_uri = follow.actor()?.as_single_xsd_any_uri().unwrap().to_string();
145 let mut accept = Accept::new(self.actor_id.to_owned(), follow.into_any_base()?);
146 let to = format!("{}/inbox", actor_uri);
148 .set_context(context())
149 .set_id(generate_activity_id(AcceptType::Accept)?)
152 insert_activity(self.creator_id, accept.clone(), true, pool).await?;
154 send_activity(client, &accept.into_any_base()?, self, vec![to]).await?;
158 async fn send_delete(
163 ) -> Result<(), LemmyError> {
164 let group = self.to_apub(pool).await?;
166 let mut delete = Delete::new(creator.actor_id.to_owned(), group.into_any_base()?);
168 .set_context(context())
169 .set_id(generate_activity_id(DeleteType::Delete)?)
171 .set_many_ccs(vec![self.get_followers_url()]);
173 insert_activity(self.creator_id, delete.clone(), true, pool).await?;
175 let inboxes = self.get_follower_inboxes(pool).await?;
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?;
184 async fn send_undo_delete(
189 ) -> Result<(), LemmyError> {
190 let group = self.to_apub(pool).await?;
192 let mut delete = Delete::new(creator.actor_id.to_owned(), group.into_any_base()?);
194 .set_context(context())
195 .set_id(generate_activity_id(DeleteType::Delete)?)
197 .set_many_ccs(vec![self.get_followers_url()]);
200 // Undo that fake activity
201 let mut undo = Undo::new(creator.actor_id.to_owned(), delete.into_any_base()?);
203 .set_context(context())
204 .set_id(generate_activity_id(UndoType::Undo)?)
206 .set_many_ccs(vec![self.get_followers_url()]);
208 insert_activity(self.creator_id, undo.clone(), true, pool).await?;
210 let inboxes = self.get_follower_inboxes(pool).await?;
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?;
219 async fn send_remove(
224 ) -> Result<(), LemmyError> {
225 let group = self.to_apub(pool).await?;
227 let mut remove = Remove::new(mod_.actor_id.to_owned(), group.into_any_base()?);
229 .set_context(context())
230 .set_id(generate_activity_id(RemoveType::Remove)?)
232 .set_many_ccs(vec![self.get_followers_url()]);
234 insert_activity(mod_.id, remove.clone(), true, pool).await?;
236 let inboxes = self.get_follower_inboxes(pool).await?;
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?;
245 async fn send_undo_remove(
250 ) -> Result<(), LemmyError> {
251 let group = self.to_apub(pool).await?;
253 let mut remove = Remove::new(mod_.actor_id.to_owned(), group.into_any_base()?);
255 .set_context(context())
256 .set_id(generate_activity_id(RemoveType::Remove)?)
258 .set_many_ccs(vec![self.get_followers_url()]);
260 // Undo that fake activity
261 let mut undo = Undo::new(mod_.actor_id.to_owned(), remove.into_any_base()?);
263 .set_context(context())
264 .set_id(generate_activity_id(LikeType::Like)?)
266 .set_many_ccs(vec![self.get_followers_url()]);
268 insert_activity(mod_.id, undo.clone(), true, pool).await?;
270 let inboxes = self.get_follower_inboxes(pool).await?;
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?;
279 /// For a given community, returns the inboxes of all followers.
280 async fn get_follower_inboxes(&self, pool: &DbPool) -> Result<Vec<String>, LemmyError> {
283 let inboxes = blocking(pool, move |conn| {
284 CommunityFollowerView::for_community(conn, id)
287 let inboxes = inboxes
289 .map(|c| get_shared_inbox(&Url::parse(&c.user_actor_id).unwrap()))
290 .filter(|s| !s.is_empty())
297 async fn send_follow(
299 _follow_actor_id: &str,
302 ) -> Result<(), LemmyError> {
306 async fn send_unfollow(
308 _follow_actor_id: &str,
311 ) -> Result<(), LemmyError> {
315 fn user_id(&self) -> i32 {
320 #[async_trait::async_trait(?Send)]
321 impl FromApub for CommunityForm {
322 type ApubType = GroupExt;
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
336 let creator = get_or_fetch_and_upsert_user(creator_uri, client, pool).await?;
338 let icon = match group.icon() {
339 Some(any_image) => Some(
340 Image::from_any_base(any_image.as_one().unwrap().clone())
345 .as_single_xsd_any_uri()
346 .map(|u| u.to_string()),
351 let banner = match group.image() {
352 Some(any_image) => Some(
353 Image::from_any_base(any_image.as_one().unwrap().clone())
358 .as_single_xsd_any_uri()
359 .map(|u| u.to_string()),
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
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,
384 published: group.inner.published().map(|u| u.to_owned().naive_local()),
385 updated: group.inner.updated().map(|u| u.to_owned().naive_local()),
387 nsfw: group.ext_one.sensitive,
388 actor_id: group.inner.id_unchecked().unwrap().to_string(),
391 public_key: Some(group.ext_two.to_owned().public_key.public_key_pem),
392 last_refreshed_at: Some(naive_now()),
399 /// Return the community json over HTTP.
400 pub async fn get_apub_community_http(
401 info: web::Path<CommunityQuery>,
403 ) -> Result<HttpResponse<Body>, LemmyError> {
404 let community = blocking(&db, move |conn| {
405 Community::read_from_name(conn, &info.community_name)
409 if !community.deleted {
410 let apub = community.to_apub(&db).await?;
412 Ok(create_apub_response(&apub))
414 Ok(create_apub_tombstone_response(&community.to_tombstone()?))
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>,
422 ) -> Result<HttpResponse<Body>, LemmyError> {
423 let community = blocking(&db, move |conn| {
424 Community::read_from_name(&conn, &info.community_name)
428 let community_id = community.id;
429 let community_followers = blocking(&db, move |conn| {
430 CommunityFollowerView::for_community(&conn, community_id)
434 let mut collection = UnorderedCollection::new();
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))
443 pub async fn get_apub_community_outbox(
444 info: web::Path<CommunityQuery>,
446 ) -> Result<HttpResponse<Body>, LemmyError> {
447 let community = blocking(&db, move |conn| {
448 Community::read_from_name(&conn, &info.community_name)
452 let community_id = community.id;
453 let posts = blocking(&db, move |conn| {
454 Post::list_for_community(conn, community_id)
458 let mut pages: Vec<AnyBase> = vec![];
460 pages.push(p.to_apub(&db).await?.into_any_base()?);
463 let len = pages.len();
464 let mut collection = OrderedCollection::new();
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))
473 pub async fn do_announce(
475 community: &Community,
479 ) -> Result<(), LemmyError> {
480 let mut announce = Announce::new(community.actor_id.to_owned(), activity);
482 .set_context(context())
483 .set_id(generate_activity_id(AnnounceType::Announce)?)
485 .set_many_ccs(vec![community.get_followers_url()]);
487 insert_activity(community.creator_id, announce.clone(), true, pool).await?;
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?;
493 // this seems to be the "easiest" stable alternative for remove_item()
494 to.retain(|x| *x != sender.get_shared_inbox_url());
496 send_activity(client, &announce.into_any_base()?, community, to).await?;