2 check_apub_id_valid_with_strictness,
3 collections::{community_moderators::ApubCommunityModerators, CommunityContext},
6 objects::instance::fetch_instance_actor_for_object,
8 objects::{group::Group, Endpoints, LanguageTag},
14 use activitypub_federation::{
15 core::object_id::ObjectId,
16 traits::{Actor, ApubObject},
18 use activitystreams_kinds::actor::GroupType;
19 use chrono::NaiveDateTime;
20 use itertools::Itertools;
21 use lemmy_api_common::{
22 context::LemmyContext,
23 utils::{generate_moderators_url, generate_outbox_url},
25 use lemmy_db_schema::{
27 actor_language::CommunityLanguage,
28 community::{Community, CommunityUpdateForm},
31 traits::{ApubActor, Crud},
33 use lemmy_db_views_actor::structs::CommunityFollowerView;
36 utils::{convert_datetime, markdown_to_html},
42 #[derive(Clone, Debug)]
43 pub struct ApubCommunity(Community);
45 impl Deref for ApubCommunity {
46 type Target = Community;
47 fn deref(&self) -> &Self::Target {
52 impl From<Community> for ApubCommunity {
53 fn from(c: Community) -> Self {
58 #[async_trait::async_trait(?Send)]
59 impl ApubObject for ApubCommunity {
60 type DataType = LemmyContext;
61 type ApubType = Group;
62 type DbType = Community;
63 type Error = LemmyError;
65 fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
66 Some(self.last_refreshed_at)
69 #[tracing::instrument(skip_all)]
70 async fn read_from_apub_id(
72 context: &LemmyContext,
73 ) -> Result<Option<Self>, LemmyError> {
75 Community::read_from_apub_id(context.pool(), &object_id.into())
81 #[tracing::instrument(skip_all)]
82 async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
83 let form = CommunityUpdateForm::builder().deleted(Some(true)).build();
84 Community::update(context.pool(), self.id, &form).await?;
88 #[tracing::instrument(skip_all)]
89 async fn into_apub(self, data: &LemmyContext) -> Result<Group, LemmyError> {
90 let community_id = self.id;
91 let langs = CommunityLanguage::read(data.pool(), community_id).await?;
92 let language = LanguageTag::new_multiple(langs, data.pool()).await?;
93 let attributed_to = Some(ObjectId::<ApubCommunityModerators>::new(
94 generate_moderators_url(&self.actor_id)?,
98 kind: GroupType::Group,
99 id: ObjectId::new(self.actor_id()),
100 preferred_username: self.name.clone(),
101 name: Some(self.title.clone()),
102 summary: self.description.as_ref().map(|b| markdown_to_html(b)),
103 source: self.description.clone().map(Source::new),
104 icon: self.icon.clone().map(ImageObject::new),
105 image: self.banner.clone().map(ImageObject::new),
106 sensitive: Some(self.nsfw),
107 moderators: attributed_to.clone(),
108 inbox: self.inbox_url.clone().into(),
109 outbox: ObjectId::new(generate_outbox_url(&self.actor_id)?),
110 followers: self.followers_url.clone().into(),
111 endpoints: self.shared_inbox_url.clone().map(|s| Endpoints {
112 shared_inbox: s.into(),
114 public_key: self.get_public_key(),
116 published: Some(convert_datetime(self.published)),
117 updated: self.updated.map(convert_datetime),
118 posting_restricted_to_mods: Some(self.posting_restricted_to_mods),
124 #[tracing::instrument(skip_all)]
127 expected_domain: &Url,
128 context: &LemmyContext,
129 _request_counter: &mut i32,
130 ) -> Result<(), LemmyError> {
131 group.verify(expected_domain, context).await
134 /// Converts a `Group` to `Community`, inserts it into the database and updates moderators.
135 #[tracing::instrument(skip_all)]
138 context: &LemmyContext,
139 request_counter: &mut i32,
140 ) -> Result<ApubCommunity, LemmyError> {
141 let apub_id = group.id.inner().clone();
142 let instance = Instance::create_from_actor_id(context.pool(), &apub_id).await?;
144 let form = Group::into_insert_form(group.clone(), instance.id);
145 let languages = LanguageTag::to_language_id_multiple(group.language, context.pool()).await?;
147 let community = Community::create(context.pool(), &form).await?;
148 CommunityLanguage::update(context.pool(), languages, community.id).await?;
150 let community: ApubCommunity = community.into();
151 let outbox_data = CommunityContext(community.clone(), context.clone());
153 // Fetching mods and outbox is not necessary for Lemmy to work, so ignore errors. Besides,
154 // we need to ignore these errors so that tests can work entirely offline.
157 .dereference(&outbox_data, local_instance(context).await, request_counter)
159 .map_err(|e| debug!("{}", e))
162 if let Some(moderators) = group.attributed_to.or(group.moderators) {
164 .dereference(&outbox_data, local_instance(context).await, request_counter)
166 .map_err(|e| debug!("{}", e))
170 fetch_instance_actor_for_object(community.actor_id(), context, request_counter).await;
176 impl Actor for ApubCommunity {
177 fn public_key(&self) -> &str {
181 fn inbox(&self) -> Url {
182 self.inbox_url.clone().into()
185 fn shared_inbox(&self) -> Option<Url> {
186 self.shared_inbox_url.clone().map(Into::into)
190 impl ActorType for ApubCommunity {
191 fn actor_id(&self) -> Url {
192 self.actor_id.clone().into()
194 fn private_key(&self) -> Option<String> {
195 self.private_key.clone()
200 /// For a given community, returns the inboxes of all followers.
201 #[tracing::instrument(skip_all)]
202 pub(crate) async fn get_follower_inboxes(
204 context: &LemmyContext,
205 ) -> Result<Vec<Url>, LemmyError> {
208 let local_site_data = fetch_local_site_data(context.pool()).await?;
209 let follows = CommunityFollowerView::for_community(context.pool(), id).await?;
210 let inboxes: Vec<Url> = follows
212 .filter(|f| !f.follower.local)
216 .unwrap_or(f.follower.inbox_url)
220 .filter(|inbox: &Url| inbox.host_str() != Some(&context.settings().hostname))
221 // Don't send to blocked instances
223 check_apub_id_valid_with_strictness(inbox, false, &local_site_data, context.settings())
233 pub(crate) mod tests {
236 objects::{instance::tests::parse_lemmy_instance, tests::init_context},
237 protocol::tests::file_to_json_object,
239 use lemmy_db_schema::{source::site::Site, traits::Crud};
240 use serial_test::serial;
242 pub(crate) async fn parse_lemmy_community(context: &LemmyContext) -> ApubCommunity {
243 let mut json: Group = file_to_json_object("assets/lemmy/objects/group.json").unwrap();
244 // change these links so they dont fetch over the network
245 json.moderators = None;
246 json.attributed_to = None;
248 ObjectId::new(Url::parse("https://enterprise.lemmy.ml/c/tenforward/not_outbox").unwrap());
250 let url = Url::parse("https://enterprise.lemmy.ml/c/tenforward").unwrap();
251 let mut request_counter = 0;
252 ApubCommunity::verify(&json, &url, context, &mut request_counter)
255 let community = ApubCommunity::from_apub(json, context, &mut request_counter)
258 // this makes one requests to the (intentionally broken) outbox collection
259 assert_eq!(request_counter, 1);
265 async fn test_parse_lemmy_community() {
266 let context = init_context().await;
267 let site = parse_lemmy_instance(&context).await;
268 let community = parse_lemmy_community(&context).await;
270 assert_eq!(community.title, "Ten Forward");
271 assert!(!community.local);
272 assert_eq!(community.description.as_ref().unwrap().len(), 132);
274 Community::delete(context.pool(), community.id)
277 Site::delete(context.pool(), site.id).await.unwrap();