3 local_site_data_cached,
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 lemmy_api_common::{
18 context::LemmyContext,
19 utils::{generate_featured_url, generate_moderators_url, generate_outbox_url},
21 use lemmy_db_schema::{
23 actor_language::CommunityLanguage,
24 community::{Community, CommunityUpdateForm},
26 traits::{ApubActor, Crud},
28 use lemmy_db_views_actor::structs::CommunityFollowerView;
31 utils::{markdown::markdown_to_html, time::convert_datetime},
37 #[derive(Clone, Debug)]
38 pub struct ApubCommunity(Community);
40 impl Deref for ApubCommunity {
41 type Target = Community;
42 fn deref(&self) -> &Self::Target {
47 impl From<Community> for ApubCommunity {
48 fn from(c: Community) -> Self {
53 #[async_trait::async_trait]
54 impl Object for ApubCommunity {
55 type DataType = LemmyContext;
57 type Error = LemmyError;
59 fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
60 Some(self.last_refreshed_at)
63 #[tracing::instrument(skip_all)]
64 async fn read_from_id(
66 context: &Data<Self::DataType>,
67 ) -> Result<Option<Self>, LemmyError> {
69 Community::read_from_apub_id(&mut context.pool(), &object_id.into())
75 #[tracing::instrument(skip_all)]
76 async fn delete(self, context: &Data<Self::DataType>) -> Result<(), LemmyError> {
77 let form = CommunityUpdateForm {
81 Community::update(&mut context.pool(), self.id, &form).await?;
85 #[tracing::instrument(skip_all)]
86 async fn into_json(self, data: &Data<Self::DataType>) -> Result<Group, LemmyError> {
87 let community_id = self.id;
88 let langs = CommunityLanguage::read(&mut data.pool(), community_id).await?;
89 let language = LanguageTag::new_multiple(langs, &mut data.pool()).await?;
92 kind: GroupType::Group,
94 preferred_username: self.name.clone(),
95 name: Some(self.title.clone()),
96 summary: self.description.as_ref().map(|b| markdown_to_html(b)),
97 source: self.description.clone().map(Source::new),
98 icon: self.icon.clone().map(ImageObject::new),
99 image: self.banner.clone().map(ImageObject::new),
100 sensitive: Some(self.nsfw),
101 featured: Some(generate_featured_url(&self.actor_id)?.into()),
102 inbox: self.inbox_url.clone().into(),
103 outbox: generate_outbox_url(&self.actor_id)?.into(),
104 followers: self.followers_url.clone().into(),
105 endpoints: self.shared_inbox_url.clone().map(|s| Endpoints {
106 shared_inbox: s.into(),
108 public_key: self.public_key(),
110 published: Some(convert_datetime(self.published)),
111 updated: self.updated.map(convert_datetime),
112 posting_restricted_to_mods: Some(self.posting_restricted_to_mods),
113 attributed_to: Some(generate_moderators_url(&self.actor_id)?.into()),
118 #[tracing::instrument(skip_all)]
121 expected_domain: &Url,
122 context: &Data<Self::DataType>,
123 ) -> Result<(), LemmyError> {
124 group.verify(expected_domain, context).await
127 /// Converts a `Group` to `Community`, inserts it into the database and updates moderators.
128 #[tracing::instrument(skip_all)]
131 context: &Data<Self::DataType>,
132 ) -> Result<ApubCommunity, LemmyError> {
133 let instance_id = fetch_instance_actor_for_object(&group.id, context).await?;
135 let form = Group::into_insert_form(group.clone(), instance_id);
137 LanguageTag::to_language_id_multiple(group.language, &mut context.pool()).await?;
139 let community = Community::create(&mut context.pool(), &form).await?;
140 CommunityLanguage::update(&mut context.pool(), languages, community.id).await?;
142 let community: ApubCommunity = community.into();
144 // Fetching mods and outbox is not necessary for Lemmy to work, so ignore errors. Besides,
145 // we need to ignore these errors so that tests can work entirely offline.
146 let fetch_outbox = group.outbox.dereference(&community, context);
148 if let Some(moderators) = group.attributed_to {
149 let fetch_moderators = moderators.dereference(&community, context);
150 // Fetch mods and outbox in parallel
151 let res = tokio::join!(fetch_outbox, fetch_moderators);
152 res.0.map_err(|e| debug!("{}", e)).ok();
153 res.1.map_err(|e| debug!("{}", e)).ok();
155 fetch_outbox.await.map_err(|e| debug!("{}", e)).ok();
162 impl Actor for ApubCommunity {
163 fn id(&self) -> Url {
164 self.actor_id.inner().clone()
167 fn public_key_pem(&self) -> &str {
171 fn private_key_pem(&self) -> Option<String> {
172 self.private_key.clone()
175 fn inbox(&self) -> Url {
176 self.inbox_url.clone().into()
179 fn shared_inbox(&self) -> Option<Url> {
180 self.shared_inbox_url.clone().map(Into::into)
185 /// For a given community, returns the inboxes of all followers.
186 #[tracing::instrument(skip_all)]
187 pub(crate) async fn get_follower_inboxes(
189 context: &LemmyContext,
190 ) -> Result<Vec<Url>, LemmyError> {
193 let local_site_data = local_site_data_cached(&mut context.pool()).await?;
195 CommunityFollowerView::get_community_follower_inboxes(&mut context.pool(), id).await?;
196 let inboxes: Vec<Url> = follows
199 .filter(|inbox: &Url| inbox.host_str() != Some(&context.settings().hostname))
200 // Don't send to blocked instances
201 .filter(|inbox| check_apub_id_valid(inbox, &local_site_data).is_ok())
209 pub(crate) mod tests {
210 #![allow(clippy::unwrap_used)]
211 #![allow(clippy::indexing_slicing)]
215 objects::{instance::tests::parse_lemmy_instance, tests::init_context},
216 protocol::tests::file_to_json_object,
218 use activitypub_federation::fetch::collection_id::CollectionId;
219 use lemmy_db_schema::{source::site::Site, traits::Crud};
220 use serial_test::serial;
222 pub(crate) async fn parse_lemmy_community(context: &Data<LemmyContext>) -> ApubCommunity {
223 // use separate counter so this doesnt affect tests
224 let context2 = context.reset_request_count();
225 let mut json: Group = file_to_json_object("assets/lemmy/objects/group.json").unwrap();
226 // change these links so they dont fetch over the network
227 json.attributed_to = None;
229 CollectionId::parse("https://enterprise.lemmy.ml/c/tenforward/not_outbox").unwrap();
231 let url = Url::parse("https://enterprise.lemmy.ml/c/tenforward").unwrap();
232 ApubCommunity::verify(&json, &url, &context2).await.unwrap();
233 let community = ApubCommunity::from_json(json, &context2).await.unwrap();
234 // this makes one requests to the (intentionally broken) outbox collection
235 assert_eq!(context2.request_count(), 1);
241 async fn test_parse_lemmy_community() {
242 let context = init_context().await;
243 let site = parse_lemmy_instance(&context).await;
244 let community = parse_lemmy_community(&context).await;
246 assert_eq!(community.title, "Ten Forward");
247 assert!(!community.local);
248 assert_eq!(community.description.as_ref().unwrap().len(), 132);
250 Community::delete(&mut context.pool(), community.id)
253 Site::delete(&mut context.pool(), site.id).await.unwrap();