3 activities::generate_activity_id,
4 activity_queue::send_activity,
7 create_apub_tombstone_response,
9 extensions::group_extensions::GroupExtension,
10 fetcher::{get_or_fetch_and_upsert_actor, get_or_fetch_and_upsert_user},
20 use activitystreams::{
22 kind::{AcceptType, AnnounceType, DeleteType, LikeType, RemoveType, UndoType},
30 actor::{kind::GroupType, ApActor, Endpoints, Group},
31 base::{AnyBase, BaseExt},
32 collection::{OrderedCollection, UnorderedCollection},
33 object::{Image, Tombstone},
37 use activitystreams_ext::Ext2;
38 use actix_web::{body::Body, web, HttpResponse};
40 use itertools::Itertools;
41 use lemmy_structs::blocking;
43 community::{Community, CommunityForm},
44 community_view::{CommunityFollowerView, CommunityModeratorView},
50 apub::get_apub_protocol_string,
52 utils::{check_slurs, check_slurs_opt, convert_datetime},
55 use serde::Deserialize;
58 #[derive(Deserialize)]
59 pub struct CommunityQuery {
60 community_name: String,
63 #[async_trait::async_trait(?Send)]
64 impl ToApub for Community {
65 type Response = GroupExt;
67 // Turn a Lemmy Community into an ActivityPub group that can be sent out over the network.
68 async fn to_apub(&self, pool: &DbPool) -> Result<GroupExt, LemmyError> {
69 // The attributed to, is an ordered vector with the creator actor_ids first,
70 // then the rest of the moderators
71 // TODO Technically the instance admins can mod the community, but lets
72 // ignore that for now
74 let moderators = blocking(pool, move |conn| {
75 CommunityModeratorView::for_community(&conn, id)
78 let moderators: Vec<String> = moderators.into_iter().map(|m| m.user_actor_id).collect();
80 let mut group = Group::new();
82 .set_context(activitystreams::context())
83 .set_id(Url::parse(&self.actor_id)?)
84 .set_name(self.name.to_owned())
85 .set_published(convert_datetime(self.published))
86 .set_many_attributed_tos(moderators);
88 if let Some(u) = self.updated.to_owned() {
89 group.set_updated(convert_datetime(u));
91 if let Some(d) = self.description.to_owned() {
92 // TODO: this should be html, also add source field with raw markdown
93 // -> same for post.content and others
97 if let Some(icon) = &self.icon {
98 let mut image = Image::new();
99 image.set_url(icon.to_owned());
100 group.set_icon(image.into_any_base()?);
103 if let Some(banner_url) = &self.banner {
104 let mut image = Image::new();
105 image.set_url(banner_url.to_owned());
106 group.set_image(image.into_any_base()?);
109 let mut ap_actor = ApActor::new(self.get_inbox_url()?, group);
111 .set_preferred_username(self.title.to_owned())
112 .set_outbox(self.get_outbox_url()?)
113 .set_followers(self.get_followers_url()?)
114 .set_following(self.get_following_url().parse()?)
115 .set_liked(self.get_liked_url().parse()?)
116 .set_endpoints(Endpoints {
117 shared_inbox: Some(self.get_shared_inbox_url()?),
121 let nsfw = self.nsfw;
122 let category_id = self.category_id;
123 let group_extension = blocking(pool, move |conn| {
124 GroupExtension::new(conn, category_id, nsfw)
131 self.get_public_key_ext()?,
135 fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
136 create_tombstone(self.deleted, &self.actor_id, self.updated, GroupType::Group)
140 #[async_trait::async_trait(?Send)]
141 impl ActorType for Community {
142 fn actor_id_str(&self) -> String {
143 self.actor_id.to_owned()
146 fn public_key(&self) -> Option<String> {
147 self.public_key.to_owned()
149 fn private_key(&self) -> Option<String> {
150 self.private_key.to_owned()
153 /// As a local community, accept the follow request from a remote user.
154 async fn send_accept_follow(
157 context: &LemmyContext,
158 ) -> Result<(), LemmyError> {
159 let actor_uri = follow
161 .as_single_xsd_any_uri()
162 .context(location_info!())?;
163 let actor = get_or_fetch_and_upsert_actor(actor_uri, context).await?;
165 let mut accept = Accept::new(self.actor_id.to_owned(), follow.into_any_base()?);
166 let to = actor.get_inbox_url()?;
168 .set_context(activitystreams::context())
169 .set_id(generate_activity_id(AcceptType::Accept)?)
172 insert_activity(self.creator_id, accept.clone(), true, context.pool()).await?;
174 send_activity(context.activity_queue(), accept, self, vec![to])?;
178 async fn send_delete(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError> {
179 let group = self.to_apub(context.pool()).await?;
181 let mut delete = Delete::new(creator.actor_id.to_owned(), group.into_any_base()?);
183 .set_context(activitystreams::context())
184 .set_id(generate_activity_id(DeleteType::Delete)?)
186 .set_many_ccs(vec![self.get_followers_url()?]);
188 insert_activity(self.creator_id, delete.clone(), true, context.pool()).await?;
190 let inboxes = self.get_follower_inboxes(context.pool()).await?;
192 // Note: For an accept, since it was automatic, no one pushed a button,
193 // the community was the actor.
194 // But for delete, the creator is the actor, and does the signing
195 send_activity(context.activity_queue(), delete, creator, inboxes)?;
199 async fn send_undo_delete(
202 context: &LemmyContext,
203 ) -> Result<(), LemmyError> {
204 let group = self.to_apub(context.pool()).await?;
206 let mut delete = Delete::new(creator.actor_id.to_owned(), group.into_any_base()?);
208 .set_context(activitystreams::context())
209 .set_id(generate_activity_id(DeleteType::Delete)?)
211 .set_many_ccs(vec![self.get_followers_url()?]);
213 let mut undo = Undo::new(creator.actor_id.to_owned(), delete.into_any_base()?);
215 .set_context(activitystreams::context())
216 .set_id(generate_activity_id(UndoType::Undo)?)
218 .set_many_ccs(vec![self.get_followers_url()?]);
220 insert_activity(self.creator_id, undo.clone(), true, context.pool()).await?;
222 let inboxes = self.get_follower_inboxes(context.pool()).await?;
224 // Note: For an accept, since it was automatic, no one pushed a button,
225 // the community was the actor.
226 // But for delete, the creator is the actor, and does the signing
227 send_activity(context.activity_queue(), undo, creator, inboxes)?;
231 async fn send_remove(&self, mod_: &User_, context: &LemmyContext) -> Result<(), LemmyError> {
232 let group = self.to_apub(context.pool()).await?;
234 let mut remove = Remove::new(mod_.actor_id.to_owned(), group.into_any_base()?);
236 .set_context(activitystreams::context())
237 .set_id(generate_activity_id(RemoveType::Remove)?)
239 .set_many_ccs(vec![self.get_followers_url()?]);
241 insert_activity(mod_.id, remove.clone(), true, context.pool()).await?;
243 let inboxes = self.get_follower_inboxes(context.pool()).await?;
245 // Note: For an accept, since it was automatic, no one pushed a button,
246 // the community was the actor.
247 // But for delete, the creator is the actor, and does the signing
248 send_activity(context.activity_queue(), remove, mod_, inboxes)?;
252 async fn send_undo_remove(&self, mod_: &User_, context: &LemmyContext) -> Result<(), LemmyError> {
253 let group = self.to_apub(context.pool()).await?;
255 let mut remove = Remove::new(mod_.actor_id.to_owned(), group.into_any_base()?);
257 .set_context(activitystreams::context())
258 .set_id(generate_activity_id(RemoveType::Remove)?)
260 .set_many_ccs(vec![self.get_followers_url()?]);
262 // Undo that fake activity
263 let mut undo = Undo::new(mod_.actor_id.to_owned(), remove.into_any_base()?);
265 .set_context(activitystreams::context())
266 .set_id(generate_activity_id(LikeType::Like)?)
268 .set_many_ccs(vec![self.get_followers_url()?]);
270 insert_activity(mod_.id, undo.clone(), true, context.pool()).await?;
272 let inboxes = self.get_follower_inboxes(context.pool()).await?;
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(context.activity_queue(), undo, mod_, inboxes)?;
281 /// For a given community, returns the inboxes of all followers.
283 /// TODO: this function is very badly implemented, we should just store shared_inbox_url in
284 /// CommunityFollowerView
285 async fn get_follower_inboxes(&self, pool: &DbPool) -> Result<Vec<Url>, LemmyError> {
288 let inboxes = blocking(pool, move |conn| {
289 CommunityFollowerView::for_community(conn, id)
292 let inboxes = inboxes
294 .map(|u| -> Result<Url, LemmyError> {
295 let url = Url::parse(&u.user_actor_id)?;
296 let domain = url.domain().context(location_info!())?;
297 let port = if let Some(port) = url.port() {
302 Ok(Url::parse(&format!(
304 get_apub_protocol_string(),
309 .filter_map(Result::ok)
316 async fn send_follow(
318 _follow_actor_id: &Url,
319 _context: &LemmyContext,
320 ) -> Result<(), LemmyError> {
324 async fn send_unfollow(
326 _follow_actor_id: &Url,
327 _context: &LemmyContext,
328 ) -> Result<(), LemmyError> {
332 fn user_id(&self) -> i32 {
337 #[async_trait::async_trait(?Send)]
338 impl FromApub for CommunityForm {
339 type ApubType = GroupExt;
341 /// Parse an ActivityPub group received from another instance into a Lemmy community.
344 context: &LemmyContext,
345 expected_domain: Option<Url>,
346 ) -> Result<Self, LemmyError> {
347 let creator_and_moderator_uris = group.inner.attributed_to().context(location_info!())?;
348 let creator_uri = creator_and_moderator_uris
350 .context(location_info!())?
353 .context(location_info!())?
355 .context(location_info!())?;
357 let creator = get_or_fetch_and_upsert_user(creator_uri, context).await?;
361 .context(location_info!())?
363 .context(location_info!())?
365 .context(location_info!())?
369 .preferred_username()
370 .context(location_info!())?
372 // TODO: should be parsed as html and tags like <script> removed (or use markdown source)
373 // -> same for post.content etc
374 let description = group
377 .map(|s| s.as_single_xsd_string())
379 .map(|s| s.to_string());
381 check_slurs(&title)?;
382 check_slurs_opt(&description)?;
384 let icon = match group.icon() {
385 Some(any_image) => Some(
386 Image::from_any_base(any_image.as_one().context(location_info!())?.clone())
387 .context(location_info!())?
388 .context(location_info!())?
390 .context(location_info!())?
391 .as_single_xsd_any_uri()
392 .map(|u| u.to_string()),
397 let banner = match group.image() {
398 Some(any_image) => Some(
399 Image::from_any_base(any_image.as_one().context(location_info!())?.clone())
400 .context(location_info!())?
401 .context(location_info!())?
403 .context(location_info!())?
404 .as_single_xsd_any_uri()
405 .map(|u| u.to_string()),
414 category_id: group.ext_one.category.identifier.parse::<i32>()?,
415 creator_id: creator.id,
417 published: group.inner.published().map(|u| u.to_owned().naive_local()),
418 updated: group.inner.updated().map(|u| u.to_owned().naive_local()),
420 nsfw: group.ext_one.sensitive,
421 actor_id: Some(check_actor_domain(group, expected_domain)?),
424 public_key: Some(group.ext_two.to_owned().public_key.public_key_pem),
425 last_refreshed_at: Some(naive_now()),
432 /// Return the community json over HTTP.
433 pub async fn get_apub_community_http(
434 info: web::Path<CommunityQuery>,
435 context: web::Data<LemmyContext>,
436 ) -> Result<HttpResponse<Body>, LemmyError> {
437 let community = blocking(context.pool(), move |conn| {
438 Community::read_from_name(conn, &info.community_name)
442 if !community.deleted {
443 let apub = community.to_apub(context.pool()).await?;
445 Ok(create_apub_response(&apub))
447 Ok(create_apub_tombstone_response(&community.to_tombstone()?))
451 /// Returns an empty followers collection, only populating the size (for privacy).
452 pub async fn get_apub_community_followers(
453 info: web::Path<CommunityQuery>,
454 context: web::Data<LemmyContext>,
455 ) -> Result<HttpResponse<Body>, LemmyError> {
456 let community = blocking(context.pool(), move |conn| {
457 Community::read_from_name(&conn, &info.community_name)
461 let community_id = community.id;
462 let community_followers = blocking(context.pool(), move |conn| {
463 CommunityFollowerView::for_community(&conn, community_id)
467 let mut collection = UnorderedCollection::new();
469 .set_context(activitystreams::context())
470 .set_id(community.get_followers_url()?)
471 .set_total_items(community_followers.len() as u64);
472 Ok(create_apub_response(&collection))
475 pub async fn get_apub_community_outbox(
476 info: web::Path<CommunityQuery>,
477 context: web::Data<LemmyContext>,
478 ) -> Result<HttpResponse<Body>, LemmyError> {
479 let community = blocking(context.pool(), move |conn| {
480 Community::read_from_name(&conn, &info.community_name)
484 let community_id = community.id;
485 let posts = blocking(context.pool(), move |conn| {
486 Post::list_for_community(conn, community_id)
490 let mut pages: Vec<AnyBase> = vec![];
492 pages.push(p.to_apub(context.pool()).await?.into_any_base()?);
495 let len = pages.len();
496 let mut collection = OrderedCollection::new();
498 .set_many_items(pages)
499 .set_context(activitystreams::context())
500 .set_id(community.get_outbox_url()?)
501 .set_total_items(len as u64);
502 Ok(create_apub_response(&collection))
505 pub async fn do_announce(
507 community: &Community,
509 context: &LemmyContext,
510 ) -> Result<(), LemmyError> {
511 let mut announce = Announce::new(community.actor_id.to_owned(), activity);
513 .set_context(activitystreams::context())
514 .set_id(generate_activity_id(AnnounceType::Announce)?)
516 .set_many_ccs(vec![community.get_followers_url()?]);
518 insert_activity(community.creator_id, announce.clone(), true, context.pool()).await?;
520 let mut to: Vec<Url> = community.get_follower_inboxes(context.pool()).await?;
522 // dont send to the local instance, nor to the instance where the activity originally came from,
523 // because that would result in a database error (same data inserted twice)
524 // this seems to be the "easiest" stable alternative for remove_item()
525 let sender_shared_inbox = sender.get_shared_inbox_url()?;
526 to.retain(|x| x != &sender_shared_inbox);
527 let community_shared_inbox = community.get_shared_inbox_url()?;
528 to.retain(|x| x != &community_shared_inbox);
530 send_activity(context.activity_queue(), announce, community, to)?;