2 activities::generate_activity_id,
3 activity_queue::send_activity,
6 create_apub_tombstone_response,
8 extensions::group_extensions::GroupExtension,
9 fetcher::{get_or_fetch_and_upsert_actor, get_or_fetch_and_upsert_user},
16 use activitystreams::{
18 kind::{AcceptType, AnnounceType, DeleteType, LikeType, RemoveType, UndoType},
26 actor::{kind::GroupType, ApActor, Endpoints, Group},
27 base::{AnyBase, BaseExt},
28 collection::{OrderedCollection, UnorderedCollection},
29 object::{Image, Tombstone},
33 use activitystreams_ext::Ext2;
34 use actix_web::{body::Body, web, HttpResponse};
36 use itertools::Itertools;
38 community::{Community, CommunityForm},
39 community_view::{CommunityFollowerView, CommunityModeratorView},
45 use lemmy_structs::blocking;
47 apub::get_apub_protocol_string,
49 utils::{check_slurs, check_slurs_opt, convert_datetime},
52 use lemmy_websocket::LemmyContext;
53 use serde::Deserialize;
56 #[derive(Deserialize)]
57 pub struct CommunityQuery {
58 community_name: String,
61 #[async_trait::async_trait(?Send)]
62 impl ToApub for Community {
63 type Response = GroupExt;
65 // Turn a Lemmy Community into an ActivityPub group that can be sent out over the network.
66 async fn to_apub(&self, pool: &DbPool) -> Result<GroupExt, LemmyError> {
67 // The attributed to, is an ordered vector with the creator actor_ids first,
68 // then the rest of the moderators
69 // TODO Technically the instance admins can mod the community, but lets
70 // ignore that for now
72 let moderators = blocking(pool, move |conn| {
73 CommunityModeratorView::for_community(&conn, id)
76 let moderators: Vec<String> = moderators.into_iter().map(|m| m.user_actor_id).collect();
78 let mut group = Group::new();
80 .set_context(activitystreams::context())
81 .set_id(Url::parse(&self.actor_id)?)
82 .set_name(self.name.to_owned())
83 .set_published(convert_datetime(self.published))
84 .set_many_attributed_tos(moderators);
86 if let Some(u) = self.updated.to_owned() {
87 group.set_updated(convert_datetime(u));
89 if let Some(d) = self.description.to_owned() {
90 // TODO: this should be html, also add source field with raw markdown
91 // -> same for post.content and others
95 if let Some(icon) = &self.icon {
96 let mut image = Image::new();
97 image.set_url(icon.to_owned());
98 group.set_icon(image.into_any_base()?);
101 if let Some(banner_url) = &self.banner {
102 let mut image = Image::new();
103 image.set_url(banner_url.to_owned());
104 group.set_image(image.into_any_base()?);
107 let mut ap_actor = ApActor::new(self.get_inbox_url()?, group);
109 .set_preferred_username(self.title.to_owned())
110 .set_outbox(self.get_outbox_url()?)
111 .set_followers(self.get_followers_url()?)
112 .set_following(self.get_following_url().parse()?)
113 .set_liked(self.get_liked_url().parse()?)
114 .set_endpoints(Endpoints {
115 shared_inbox: Some(self.get_shared_inbox_url()?),
119 let nsfw = self.nsfw;
120 let category_id = self.category_id;
121 let group_extension = blocking(pool, move |conn| {
122 GroupExtension::new(conn, category_id, nsfw)
129 self.get_public_key_ext()?,
133 fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
134 create_tombstone(self.deleted, &self.actor_id, self.updated, GroupType::Group)
138 #[async_trait::async_trait(?Send)]
139 impl ActorType for Community {
140 fn actor_id_str(&self) -> String {
141 self.actor_id.to_owned()
144 fn public_key(&self) -> Option<String> {
145 self.public_key.to_owned()
147 fn private_key(&self) -> Option<String> {
148 self.private_key.to_owned()
151 /// As a local community, accept the follow request from a remote user.
152 async fn send_accept_follow(
155 context: &LemmyContext,
156 ) -> Result<(), LemmyError> {
157 let actor_uri = follow
159 .as_single_xsd_any_uri()
160 .context(location_info!())?;
161 let actor = get_or_fetch_and_upsert_actor(actor_uri, context).await?;
163 let mut accept = Accept::new(self.actor_id.to_owned(), follow.into_any_base()?);
164 let to = actor.get_inbox_url()?;
166 .set_context(activitystreams::context())
167 .set_id(generate_activity_id(AcceptType::Accept)?)
170 insert_activity(self.creator_id, accept.clone(), true, context.pool()).await?;
172 send_activity(context.activity_queue(), accept, self, vec![to])?;
176 async fn send_delete(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError> {
177 let group = self.to_apub(context.pool()).await?;
179 let mut delete = Delete::new(creator.actor_id.to_owned(), group.into_any_base()?);
181 .set_context(activitystreams::context())
182 .set_id(generate_activity_id(DeleteType::Delete)?)
184 .set_many_ccs(vec![self.get_followers_url()?]);
186 insert_activity(self.creator_id, delete.clone(), true, context.pool()).await?;
188 let inboxes = self.get_follower_inboxes(context.pool()).await?;
190 // Note: For an accept, since it was automatic, no one pushed a button,
191 // the community was the actor.
192 // But for delete, the creator is the actor, and does the signing
193 send_activity(context.activity_queue(), delete, creator, inboxes)?;
197 async fn send_undo_delete(
200 context: &LemmyContext,
201 ) -> Result<(), LemmyError> {
202 let group = self.to_apub(context.pool()).await?;
204 let mut delete = Delete::new(creator.actor_id.to_owned(), group.into_any_base()?);
206 .set_context(activitystreams::context())
207 .set_id(generate_activity_id(DeleteType::Delete)?)
209 .set_many_ccs(vec![self.get_followers_url()?]);
211 let mut undo = Undo::new(creator.actor_id.to_owned(), delete.into_any_base()?);
213 .set_context(activitystreams::context())
214 .set_id(generate_activity_id(UndoType::Undo)?)
216 .set_many_ccs(vec![self.get_followers_url()?]);
218 insert_activity(self.creator_id, undo.clone(), true, context.pool()).await?;
220 let inboxes = self.get_follower_inboxes(context.pool()).await?;
222 // Note: For an accept, since it was automatic, no one pushed a button,
223 // the community was the actor.
224 // But for delete, the creator is the actor, and does the signing
225 send_activity(context.activity_queue(), undo, creator, inboxes)?;
229 async fn send_remove(&self, mod_: &User_, context: &LemmyContext) -> Result<(), LemmyError> {
230 let group = self.to_apub(context.pool()).await?;
232 let mut remove = Remove::new(mod_.actor_id.to_owned(), group.into_any_base()?);
234 .set_context(activitystreams::context())
235 .set_id(generate_activity_id(RemoveType::Remove)?)
237 .set_many_ccs(vec![self.get_followers_url()?]);
239 insert_activity(mod_.id, remove.clone(), true, context.pool()).await?;
241 let inboxes = self.get_follower_inboxes(context.pool()).await?;
243 // Note: For an accept, since it was automatic, no one pushed a button,
244 // the community was the actor.
245 // But for delete, the creator is the actor, and does the signing
246 send_activity(context.activity_queue(), remove, mod_, inboxes)?;
250 async fn send_undo_remove(&self, mod_: &User_, context: &LemmyContext) -> Result<(), LemmyError> {
251 let group = self.to_apub(context.pool()).await?;
253 let mut remove = Remove::new(mod_.actor_id.to_owned(), group.into_any_base()?);
255 .set_context(activitystreams::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(activitystreams::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, context.pool()).await?;
270 let inboxes = self.get_follower_inboxes(context.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(context.activity_queue(), undo, mod_, inboxes)?;
279 /// For a given community, returns the inboxes of all followers.
281 /// TODO: this function is very badly implemented, we should just store shared_inbox_url in
282 /// CommunityFollowerView
283 async fn get_follower_inboxes(&self, pool: &DbPool) -> Result<Vec<Url>, LemmyError> {
286 let inboxes = blocking(pool, move |conn| {
287 CommunityFollowerView::for_community(conn, id)
290 let inboxes = inboxes
292 .map(|u| -> Result<Url, LemmyError> {
293 let url = Url::parse(&u.user_actor_id)?;
294 let domain = url.domain().context(location_info!())?;
295 let port = if let Some(port) = url.port() {
300 Ok(Url::parse(&format!(
302 get_apub_protocol_string(),
307 .filter_map(Result::ok)
314 async fn send_follow(
316 _follow_actor_id: &Url,
317 _context: &LemmyContext,
318 ) -> Result<(), LemmyError> {
322 async fn send_unfollow(
324 _follow_actor_id: &Url,
325 _context: &LemmyContext,
326 ) -> Result<(), LemmyError> {
330 fn user_id(&self) -> i32 {
335 #[async_trait::async_trait(?Send)]
336 impl FromApub for CommunityForm {
337 type ApubType = GroupExt;
339 /// Parse an ActivityPub group received from another instance into a Lemmy community.
342 context: &LemmyContext,
343 expected_domain: Option<Url>,
344 ) -> Result<Self, LemmyError> {
345 let creator_and_moderator_uris = group.inner.attributed_to().context(location_info!())?;
346 let creator_uri = creator_and_moderator_uris
348 .context(location_info!())?
351 .context(location_info!())?
353 .context(location_info!())?;
355 let creator = get_or_fetch_and_upsert_user(creator_uri, context).await?;
359 .context(location_info!())?
361 .context(location_info!())?
363 .context(location_info!())?
367 .preferred_username()
368 .context(location_info!())?
370 // TODO: should be parsed as html and tags like <script> removed (or use markdown source)
371 // -> same for post.content etc
372 let description = group
375 .map(|s| s.as_single_xsd_string())
377 .map(|s| s.to_string());
379 check_slurs(&title)?;
380 check_slurs_opt(&description)?;
382 let icon = match group.icon() {
383 Some(any_image) => Some(
384 Image::from_any_base(any_image.as_one().context(location_info!())?.clone())
385 .context(location_info!())?
386 .context(location_info!())?
388 .context(location_info!())?
389 .as_single_xsd_any_uri()
390 .map(|u| u.to_string()),
395 let banner = match group.image() {
396 Some(any_image) => Some(
397 Image::from_any_base(any_image.as_one().context(location_info!())?.clone())
398 .context(location_info!())?
399 .context(location_info!())?
401 .context(location_info!())?
402 .as_single_xsd_any_uri()
403 .map(|u| u.to_string()),
412 category_id: group.ext_one.category.identifier.parse::<i32>()?,
413 creator_id: creator.id,
415 published: group.inner.published().map(|u| u.to_owned().naive_local()),
416 updated: group.inner.updated().map(|u| u.to_owned().naive_local()),
418 nsfw: group.ext_one.sensitive,
419 actor_id: Some(check_actor_domain(group, expected_domain)?),
422 public_key: Some(group.ext_two.to_owned().public_key.public_key_pem),
423 last_refreshed_at: Some(naive_now()),
430 /// Return the community json over HTTP.
431 pub async fn get_apub_community_http(
432 info: web::Path<CommunityQuery>,
433 context: web::Data<LemmyContext>,
434 ) -> Result<HttpResponse<Body>, LemmyError> {
435 let community = blocking(context.pool(), move |conn| {
436 Community::read_from_name(conn, &info.community_name)
440 if !community.deleted {
441 let apub = community.to_apub(context.pool()).await?;
443 Ok(create_apub_response(&apub))
445 Ok(create_apub_tombstone_response(&community.to_tombstone()?))
449 /// Returns an empty followers collection, only populating the size (for privacy).
450 pub async fn get_apub_community_followers(
451 info: web::Path<CommunityQuery>,
452 context: web::Data<LemmyContext>,
453 ) -> Result<HttpResponse<Body>, LemmyError> {
454 let community = blocking(context.pool(), move |conn| {
455 Community::read_from_name(&conn, &info.community_name)
459 let community_id = community.id;
460 let community_followers = blocking(context.pool(), move |conn| {
461 CommunityFollowerView::for_community(&conn, community_id)
465 let mut collection = UnorderedCollection::new();
467 .set_context(activitystreams::context())
468 .set_id(community.get_followers_url()?)
469 .set_total_items(community_followers.len() as u64);
470 Ok(create_apub_response(&collection))
473 pub async fn get_apub_community_outbox(
474 info: web::Path<CommunityQuery>,
475 context: web::Data<LemmyContext>,
476 ) -> Result<HttpResponse<Body>, LemmyError> {
477 let community = blocking(context.pool(), move |conn| {
478 Community::read_from_name(&conn, &info.community_name)
482 let community_id = community.id;
483 let posts = blocking(context.pool(), move |conn| {
484 Post::list_for_community(conn, community_id)
488 let mut pages: Vec<AnyBase> = vec![];
490 pages.push(p.to_apub(context.pool()).await?.into_any_base()?);
493 let len = pages.len();
494 let mut collection = OrderedCollection::new();
496 .set_many_items(pages)
497 .set_context(activitystreams::context())
498 .set_id(community.get_outbox_url()?)
499 .set_total_items(len as u64);
500 Ok(create_apub_response(&collection))
503 pub async fn do_announce(
505 community: &Community,
507 context: &LemmyContext,
508 ) -> Result<(), LemmyError> {
509 let mut announce = Announce::new(community.actor_id.to_owned(), activity);
511 .set_context(activitystreams::context())
512 .set_id(generate_activity_id(AnnounceType::Announce)?)
514 .set_many_ccs(vec![community.get_followers_url()?]);
516 insert_activity(community.creator_id, announce.clone(), true, context.pool()).await?;
518 let mut to: Vec<Url> = community.get_follower_inboxes(context.pool()).await?;
520 // dont send to the local instance, nor to the instance where the activity originally came from,
521 // because that would result in a database error (same data inserted twice)
522 // this seems to be the "easiest" stable alternative for remove_item()
523 let sender_shared_inbox = sender.get_shared_inbox_url()?;
524 to.retain(|x| x != &sender_shared_inbox);
525 let community_shared_inbox = community.get_shared_inbox_url()?;
526 to.retain(|x| x != &community_shared_inbox);
528 send_activity(context.activity_queue(), announce, community, to)?;