2 check_apub_id_valid_with_strictness,
4 objects::instance::fetch_instance_actor_for_object,
6 objects::{group::Group, Endpoints, LanguageTag},
11 use activitypub_federation::{
13 kinds::actor::GroupType,
14 traits::{Actor, Object},
16 use chrono::NaiveDateTime;
17 use itertools::Itertools;
18 use lemmy_api_common::{
19 context::LemmyContext,
20 utils::{generate_featured_url, generate_moderators_url, generate_outbox_url},
22 use lemmy_db_schema::{
24 actor_language::CommunityLanguage,
25 community::{Community, CommunityUpdateForm},
27 traits::{ApubActor, Crud},
29 use lemmy_db_views_actor::structs::CommunityFollowerView;
32 utils::{markdown::markdown_to_html, time::convert_datetime},
38 #[derive(Clone, Debug)]
39 pub struct ApubCommunity(Community);
41 impl Deref for ApubCommunity {
42 type Target = Community;
43 fn deref(&self) -> &Self::Target {
48 impl From<Community> for ApubCommunity {
49 fn from(c: Community) -> Self {
54 #[async_trait::async_trait]
55 impl Object for ApubCommunity {
56 type DataType = LemmyContext;
58 type Error = LemmyError;
60 fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
61 Some(self.last_refreshed_at)
64 #[tracing::instrument(skip_all)]
65 async fn read_from_id(
67 context: &Data<Self::DataType>,
68 ) -> Result<Option<Self>, LemmyError> {
70 Community::read_from_apub_id(context.pool(), &object_id.into())
76 #[tracing::instrument(skip_all)]
77 async fn delete(self, context: &Data<Self::DataType>) -> Result<(), LemmyError> {
78 let form = CommunityUpdateForm::builder().deleted(Some(true)).build();
79 Community::update(context.pool(), self.id, &form).await?;
83 #[tracing::instrument(skip_all)]
84 async fn into_json(self, data: &Data<Self::DataType>) -> Result<Group, LemmyError> {
85 let community_id = self.id;
86 let langs = CommunityLanguage::read(data.pool(), community_id).await?;
87 let language = LanguageTag::new_multiple(langs, data.pool()).await?;
90 kind: GroupType::Group,
92 preferred_username: self.name.clone(),
93 name: Some(self.title.clone()),
94 summary: self.description.as_ref().map(|b| markdown_to_html(b)),
95 source: self.description.clone().map(Source::new),
96 icon: self.icon.clone().map(ImageObject::new),
97 image: self.banner.clone().map(ImageObject::new),
98 sensitive: Some(self.nsfw),
99 featured: Some(generate_featured_url(&self.actor_id)?.into()),
100 inbox: self.inbox_url.clone().into(),
101 outbox: generate_outbox_url(&self.actor_id)?.into(),
102 followers: self.followers_url.clone().into(),
103 endpoints: self.shared_inbox_url.clone().map(|s| Endpoints {
104 shared_inbox: s.into(),
106 public_key: self.public_key(),
108 published: Some(convert_datetime(self.published)),
109 updated: self.updated.map(convert_datetime),
110 posting_restricted_to_mods: Some(self.posting_restricted_to_mods),
111 attributed_to: Some(generate_moderators_url(&self.actor_id)?.into()),
116 #[tracing::instrument(skip_all)]
119 expected_domain: &Url,
120 context: &Data<Self::DataType>,
121 ) -> Result<(), LemmyError> {
122 group.verify(expected_domain, context).await
125 /// Converts a `Group` to `Community`, inserts it into the database and updates moderators.
126 #[tracing::instrument(skip_all)]
129 context: &Data<Self::DataType>,
130 ) -> Result<ApubCommunity, LemmyError> {
131 let instance_id = fetch_instance_actor_for_object(&group.id, context).await?;
133 let form = Group::into_insert_form(group.clone(), instance_id);
134 let languages = LanguageTag::to_language_id_multiple(group.language, context.pool()).await?;
136 let community = Community::create(context.pool(), &form).await?;
137 CommunityLanguage::update(context.pool(), languages, community.id).await?;
139 let community: ApubCommunity = community.into();
141 // Fetching mods and outbox is not necessary for Lemmy to work, so ignore errors. Besides,
142 // we need to ignore these errors so that tests can work entirely offline.
143 let fetch_outbox = group.outbox.dereference(&community, context);
145 if let Some(moderators) = group.attributed_to {
146 let fetch_moderators = moderators.dereference(&community, context);
147 // Fetch mods and outbox in parallel
148 let res = tokio::join!(fetch_outbox, fetch_moderators);
149 res.0.map_err(|e| debug!("{}", e)).ok();
150 res.1.map_err(|e| debug!("{}", e)).ok();
152 fetch_outbox.await.map_err(|e| debug!("{}", e)).ok();
159 impl Actor for ApubCommunity {
160 fn id(&self) -> Url {
161 self.actor_id.inner().clone()
164 fn public_key_pem(&self) -> &str {
168 fn private_key_pem(&self) -> Option<String> {
169 self.private_key.clone()
172 fn inbox(&self) -> Url {
173 self.inbox_url.clone().into()
176 fn shared_inbox(&self) -> Option<Url> {
177 self.shared_inbox_url.clone().map(Into::into)
182 /// For a given community, returns the inboxes of all followers.
183 #[tracing::instrument(skip_all)]
184 pub(crate) async fn get_follower_inboxes(
186 context: &LemmyContext,
187 ) -> Result<Vec<Url>, LemmyError> {
190 let local_site_data = fetch_local_site_data(context.pool()).await?;
191 let follows = CommunityFollowerView::for_community(context.pool(), id).await?;
192 let inboxes: Vec<Url> = follows
194 .filter(|f| !f.follower.local)
198 .unwrap_or(f.follower.inbox_url)
202 .filter(|inbox: &Url| inbox.host_str() != Some(&context.settings().hostname))
203 // Don't send to blocked instances
205 check_apub_id_valid_with_strictness(inbox, false, &local_site_data, context.settings())
215 pub(crate) mod tests {
218 objects::{instance::tests::parse_lemmy_instance, tests::init_context},
219 protocol::tests::file_to_json_object,
221 use activitypub_federation::fetch::collection_id::CollectionId;
222 use lemmy_db_schema::{source::site::Site, traits::Crud};
223 use serial_test::serial;
225 pub(crate) async fn parse_lemmy_community(context: &Data<LemmyContext>) -> ApubCommunity {
226 // use separate counter so this doesnt affect tests
227 let context2 = context.reset_request_count();
228 let mut json: Group = file_to_json_object("assets/lemmy/objects/group.json").unwrap();
229 // change these links so they dont fetch over the network
230 json.attributed_to = None;
232 CollectionId::parse("https://enterprise.lemmy.ml/c/tenforward/not_outbox").unwrap();
234 let url = Url::parse("https://enterprise.lemmy.ml/c/tenforward").unwrap();
235 ApubCommunity::verify(&json, &url, &context2).await.unwrap();
236 let community = ApubCommunity::from_json(json, &context2).await.unwrap();
237 // this makes one requests to the (intentionally broken) outbox collection
238 assert_eq!(context2.request_count(), 1);
244 async fn test_parse_lemmy_community() {
245 let context = init_context().await;
246 let site = parse_lemmy_instance(&context).await;
247 let community = parse_lemmy_community(&context).await;
249 assert_eq!(community.title, "Ten Forward");
250 assert!(!community.local);
251 assert_eq!(community.description.as_ref().unwrap().len(), 132);
253 Community::delete(context.pool(), community.id)
256 Site::delete(context.pool(), site.id).await.unwrap();