]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/community.rs
Merge branch 'main' into move_matrix_and_admin_to_person
[lemmy.git] / crates / apub / src / objects / community.rs
1 use crate::{
2   extensions::{context::lemmy_context, group_extensions::GroupExtension},
3   fetcher::person::get_or_fetch_and_upsert_person,
4   objects::{
5     check_object_domain,
6     create_tombstone,
7     get_object_from_apub,
8     get_source_markdown_value,
9     set_content_and_source,
10     FromApub,
11     FromApubToForm,
12     ToApub,
13   },
14   ActorType,
15   GroupExt,
16 };
17 use activitystreams::{
18   actor::{kind::GroupType, ApActor, Endpoints, Group},
19   base::BaseExt,
20   object::{ApObject, Image, Tombstone},
21   prelude::*,
22 };
23 use activitystreams_ext::Ext2;
24 use anyhow::Context;
25 use lemmy_api_structs::blocking;
26 use lemmy_db_queries::DbPool;
27 use lemmy_db_schema::{
28   naive_now,
29   source::community::{Community, CommunityForm},
30 };
31 use lemmy_db_views_actor::community_moderator_view::CommunityModeratorView;
32 use lemmy_utils::{
33   location_info,
34   utils::{check_slurs, check_slurs_opt, convert_datetime},
35   LemmyError,
36 };
37 use lemmy_websocket::LemmyContext;
38 use url::Url;
39
40 #[async_trait::async_trait(?Send)]
41 impl ToApub for Community {
42   type ApubType = GroupExt;
43
44   async fn to_apub(&self, pool: &DbPool) -> Result<GroupExt, LemmyError> {
45     // The attributed to, is an ordered vector with the creator actor_ids first,
46     // then the rest of the moderators
47     // TODO Technically the instance admins can mod the community, but lets
48     // ignore that for now
49     let id = self.id;
50     let moderators = blocking(pool, move |conn| {
51       CommunityModeratorView::for_community(&conn, id)
52     })
53     .await??;
54     let moderators: Vec<Url> = moderators
55       .into_iter()
56       .map(|m| m.moderator.actor_id.into_inner())
57       .collect();
58
59     let mut group = ApObject::new(Group::new());
60     group
61       .set_many_contexts(lemmy_context()?)
62       .set_id(self.actor_id.to_owned().into())
63       .set_name(self.title.to_owned())
64       .set_published(convert_datetime(self.published))
65       .set_many_attributed_tos(moderators);
66
67     if let Some(u) = self.updated.to_owned() {
68       group.set_updated(convert_datetime(u));
69     }
70     if let Some(d) = self.description.to_owned() {
71       set_content_and_source(&mut group, &d)?;
72     }
73
74     if let Some(icon_url) = &self.icon {
75       let mut image = Image::new();
76       image.set_url::<Url>(icon_url.to_owned().into());
77       group.set_icon(image.into_any_base()?);
78     }
79
80     if let Some(banner_url) = &self.banner {
81       let mut image = Image::new();
82       image.set_url::<Url>(banner_url.to_owned().into());
83       group.set_image(image.into_any_base()?);
84     }
85
86     let mut ap_actor = ApActor::new(self.inbox_url.clone().into(), group);
87     ap_actor
88       .set_preferred_username(self.name.to_owned())
89       .set_outbox(self.get_outbox_url()?)
90       .set_followers(self.followers_url.clone().into())
91       .set_endpoints(Endpoints {
92         shared_inbox: Some(self.get_shared_inbox_or_inbox_url()),
93         ..Default::default()
94       });
95
96     Ok(Ext2::new(
97       ap_actor,
98       GroupExtension::new(self.nsfw)?,
99       self.get_public_key_ext()?,
100     ))
101   }
102
103   fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
104     create_tombstone(
105       self.deleted,
106       self.actor_id.to_owned().into(),
107       self.updated,
108       GroupType::Group,
109     )
110   }
111 }
112
113 #[async_trait::async_trait(?Send)]
114 impl FromApub for Community {
115   type ApubType = GroupExt;
116
117   /// Converts a `Group` to `Community`.
118   async fn from_apub(
119     group: &GroupExt,
120     context: &LemmyContext,
121     expected_domain: Url,
122     request_counter: &mut i32,
123   ) -> Result<Community, LemmyError> {
124     get_object_from_apub(group, context, expected_domain, request_counter).await
125   }
126 }
127
128 #[async_trait::async_trait(?Send)]
129 impl FromApubToForm<GroupExt> for CommunityForm {
130   async fn from_apub(
131     group: &GroupExt,
132     context: &LemmyContext,
133     expected_domain: Url,
134     request_counter: &mut i32,
135   ) -> Result<Self, LemmyError> {
136     let creator_and_moderator_uris = group.inner.attributed_to().context(location_info!())?;
137     let creator_uri = creator_and_moderator_uris
138       .as_many()
139       .context(location_info!())?
140       .iter()
141       .next()
142       .context(location_info!())?
143       .as_xsd_any_uri()
144       .context(location_info!())?;
145
146     let creator = get_or_fetch_and_upsert_person(creator_uri, context, request_counter).await?;
147     let name = group
148       .inner
149       .preferred_username()
150       .context(location_info!())?
151       .to_string();
152     let title = group
153       .inner
154       .name()
155       .context(location_info!())?
156       .as_one()
157       .context(location_info!())?
158       .as_xsd_string()
159       .context(location_info!())?
160       .to_string();
161
162     let description = get_source_markdown_value(group)?;
163
164     check_slurs(&name)?;
165     check_slurs(&title)?;
166     check_slurs_opt(&description)?;
167
168     let icon = match group.icon() {
169       Some(any_image) => Some(
170         Image::from_any_base(any_image.as_one().context(location_info!())?.clone())
171           .context(location_info!())?
172           .context(location_info!())?
173           .url()
174           .context(location_info!())?
175           .as_single_xsd_any_uri()
176           .map(|u| u.to_owned().into()),
177       ),
178       None => None,
179     };
180     let banner = match group.image() {
181       Some(any_image) => Some(
182         Image::from_any_base(any_image.as_one().context(location_info!())?.clone())
183           .context(location_info!())?
184           .context(location_info!())?
185           .url()
186           .context(location_info!())?
187           .as_single_xsd_any_uri()
188           .map(|u| u.to_owned().into()),
189       ),
190       None => None,
191     };
192     let shared_inbox = group
193       .inner
194       .endpoints()?
195       .map(|e| e.shared_inbox)
196       .flatten()
197       .map(|s| s.to_owned().into());
198
199     Ok(CommunityForm {
200       name,
201       title,
202       description,
203       creator_id: creator.id,
204       removed: None,
205       published: group.inner.published().map(|u| u.to_owned().naive_local()),
206       updated: group.inner.updated().map(|u| u.to_owned().naive_local()),
207       deleted: None,
208       nsfw: Some(group.ext_one.sensitive.unwrap_or(false)),
209       actor_id: Some(check_object_domain(group, expected_domain)?),
210       local: Some(false),
211       private_key: None,
212       public_key: Some(group.ext_two.to_owned().public_key.public_key_pem),
213       last_refreshed_at: Some(naive_now()),
214       icon,
215       banner,
216       followers_url: Some(
217         group
218           .inner
219           .followers()?
220           .context(location_info!())?
221           .to_owned()
222           .into(),
223       ),
224       inbox_url: Some(group.inner.inbox()?.to_owned().into()),
225       shared_inbox_url: Some(shared_inbox),
226     })
227   }
228 }