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},
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?;
348 title: group.inner.preferred_username().unwrap().to_string(),
349 // TODO: should be parsed as html and tags like <script> removed (or use markdown source)
350 // -> same for post.content etc
354 .map(|s| s.as_single_xsd_string().unwrap().into()),
355 category_id: group.ext_one.category.identifier.parse::<i32>()?,
356 creator_id: creator.id,
358 published: group.inner.published().map(|u| u.to_owned().naive_local()),
359 updated: group.inner.updated().map(|u| u.to_owned().naive_local()),
361 nsfw: group.ext_one.sensitive,
362 actor_id: group.inner.id_unchecked().unwrap().to_string(),
365 public_key: Some(group.ext_two.to_owned().public_key.public_key_pem),
366 last_refreshed_at: Some(naive_now()),
371 /// Return the community json over HTTP.
372 pub async fn get_apub_community_http(
373 info: web::Path<CommunityQuery>,
375 ) -> Result<HttpResponse<Body>, LemmyError> {
376 let community = blocking(&db, move |conn| {
377 Community::read_from_name(conn, &info.community_name)
381 if !community.deleted {
382 let apub = community.to_apub(&db).await?;
384 Ok(create_apub_response(&apub))
386 Ok(create_apub_tombstone_response(&community.to_tombstone()?))
390 /// Returns an empty followers collection, only populating the size (for privacy).
391 pub async fn get_apub_community_followers(
392 info: web::Path<CommunityQuery>,
394 ) -> Result<HttpResponse<Body>, LemmyError> {
395 let community = blocking(&db, move |conn| {
396 Community::read_from_name(&conn, &info.community_name)
400 let community_id = community.id;
401 let community_followers = blocking(&db, move |conn| {
402 CommunityFollowerView::for_community(&conn, community_id)
406 let mut collection = UnorderedCollection::new();
408 .set_context(context())
409 // TODO: this needs its own ID
410 .set_id(community.actor_id.parse()?)
411 .set_total_items(community_followers.len() as u64);
412 Ok(create_apub_response(&collection))
415 pub async fn get_apub_community_outbox(
416 info: web::Path<CommunityQuery>,
418 ) -> Result<HttpResponse<Body>, LemmyError> {
419 let community = blocking(&db, move |conn| {
420 Community::read_from_name(&conn, &info.community_name)
424 let community_id = community.id;
425 let posts = blocking(&db, move |conn| {
426 Post::list_for_community(conn, community_id)
430 let mut pages: Vec<AnyBase> = vec![];
432 pages.push(p.to_apub(&db).await?.into_any_base()?);
435 let len = pages.len();
436 let mut collection = OrderedCollection::new();
438 .set_many_items(pages)
439 .set_context(context())
440 .set_id(community.get_outbox_url()?)
441 .set_total_items(len as u64);
442 Ok(create_apub_response(&collection))
445 pub async fn do_announce(
447 community: &Community,
451 ) -> Result<(), LemmyError> {
452 let mut announce = Announce::new(community.actor_id.to_owned(), activity);
454 .set_context(context())
455 .set_id(generate_activity_id(AnnounceType::Announce)?)
457 .set_many_ccs(vec![community.get_followers_url()]);
459 insert_activity(community.creator_id, announce.clone(), true, pool).await?;
461 // dont send to the instance where the activity originally came from, because that would result
462 // in a database error (same data inserted twice)
463 let mut to = community.get_follower_inboxes(pool).await?;
465 // this seems to be the "easiest" stable alternative for remove_item()
466 to.retain(|x| *x != sender.get_shared_inbox_url());
468 send_activity(client, &announce.into_any_base()?, community, to).await?;