2 check_apub_id_valid_with_strictness,
3 collections::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_featured_url, 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::{markdown::markdown_to_html, time::convert_datetime},
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?;
95 kind: GroupType::Group,
96 id: ObjectId::new(self.actor_id()),
97 preferred_username: self.name.clone(),
98 name: Some(self.title.clone()),
99 summary: self.description.as_ref().map(|b| markdown_to_html(b)),
100 source: self.description.clone().map(Source::new),
101 icon: self.icon.clone().map(ImageObject::new),
102 image: self.banner.clone().map(ImageObject::new),
103 sensitive: Some(self.nsfw),
104 moderators: Some(generate_moderators_url(&self.actor_id)?.into()),
105 featured: Some(generate_featured_url(&self.actor_id)?.into()),
106 inbox: self.inbox_url.clone().into(),
107 outbox: ObjectId::new(generate_outbox_url(&self.actor_id)?),
108 followers: self.followers_url.clone().into(),
109 endpoints: self.shared_inbox_url.clone().map(|s| Endpoints {
110 shared_inbox: s.into(),
112 public_key: self.get_public_key(),
114 published: Some(convert_datetime(self.published)),
115 updated: self.updated.map(convert_datetime),
116 posting_restricted_to_mods: Some(self.posting_restricted_to_mods),
117 attributed_to: Some(generate_moderators_url(&self.actor_id)?.into()),
122 #[tracing::instrument(skip_all)]
125 expected_domain: &Url,
126 context: &LemmyContext,
127 _request_counter: &mut i32,
128 ) -> Result<(), LemmyError> {
129 group.verify(expected_domain, context).await
132 /// Converts a `Group` to `Community`, inserts it into the database and updates moderators.
133 #[tracing::instrument(skip_all)]
136 context: &LemmyContext,
137 request_counter: &mut i32,
138 ) -> Result<ApubCommunity, LemmyError> {
139 let apub_id = group.id.inner().clone();
140 let instance = Instance::create_from_actor_id(context.pool(), &apub_id).await?;
142 let form = Group::into_insert_form(group.clone(), instance.id);
143 let languages = LanguageTag::to_language_id_multiple(group.language, context.pool()).await?;
145 let community = Community::create(context.pool(), &form).await?;
146 CommunityLanguage::update(context.pool(), languages, community.id).await?;
148 let community: ApubCommunity = community.into();
149 let outbox_data = CommunityContext(community.clone(), context.clone());
151 // Fetching mods and outbox is not necessary for Lemmy to work, so ignore errors. Besides,
152 // we need to ignore these errors so that tests can work entirely offline.
155 .dereference(&outbox_data, local_instance(context).await, request_counter)
157 .map_err(|e| debug!("{}", e))
160 if let Some(moderators) = group.attributed_to.or(group.moderators) {
162 .dereference(&outbox_data, local_instance(context).await, request_counter)
164 .map_err(|e| debug!("{}", e))
168 fetch_instance_actor_for_object(community.actor_id(), context, request_counter).await;
174 impl Actor for ApubCommunity {
175 fn public_key(&self) -> &str {
179 fn inbox(&self) -> Url {
180 self.inbox_url.clone().into()
183 fn shared_inbox(&self) -> Option<Url> {
184 self.shared_inbox_url.clone().map(Into::into)
188 impl ActorType for ApubCommunity {
189 fn actor_id(&self) -> Url {
190 self.actor_id.clone().into()
192 fn private_key(&self) -> Option<String> {
193 self.private_key.clone()
198 /// For a given community, returns the inboxes of all followers.
199 #[tracing::instrument(skip_all)]
200 pub(crate) async fn get_follower_inboxes(
202 context: &LemmyContext,
203 ) -> Result<Vec<Url>, LemmyError> {
206 let local_site_data = fetch_local_site_data(context.pool()).await?;
207 let follows = CommunityFollowerView::for_community(context.pool(), id).await?;
208 let inboxes: Vec<Url> = follows
210 .filter(|f| !f.follower.local)
214 .unwrap_or(f.follower.inbox_url)
218 .filter(|inbox: &Url| inbox.host_str() != Some(&context.settings().hostname))
219 // Don't send to blocked instances
221 check_apub_id_valid_with_strictness(inbox, false, &local_site_data, context.settings())
231 pub(crate) mod tests {
234 objects::{instance::tests::parse_lemmy_instance, tests::init_context},
235 protocol::tests::file_to_json_object,
237 use lemmy_db_schema::{source::site::Site, traits::Crud};
238 use serial_test::serial;
240 pub(crate) async fn parse_lemmy_community(context: &LemmyContext) -> ApubCommunity {
241 let mut json: Group = file_to_json_object("assets/lemmy/objects/group.json").unwrap();
242 // change these links so they dont fetch over the network
243 json.moderators = None;
244 json.attributed_to = None;
246 ObjectId::new(Url::parse("https://enterprise.lemmy.ml/c/tenforward/not_outbox").unwrap());
248 let url = Url::parse("https://enterprise.lemmy.ml/c/tenforward").unwrap();
249 let mut request_counter = 0;
250 ApubCommunity::verify(&json, &url, context, &mut request_counter)
253 let community = ApubCommunity::from_apub(json, context, &mut request_counter)
256 // this makes one requests to the (intentionally broken) outbox collection
257 assert_eq!(request_counter, 1);
263 async fn test_parse_lemmy_community() {
264 let context = init_context().await;
265 let site = parse_lemmy_instance(&context).await;
266 let community = parse_lemmy_community(&context).await;
268 assert_eq!(community.title, "Ten Forward");
269 assert!(!community.local);
270 assert_eq!(community.description.as_ref().unwrap().len(), 132);
272 Community::delete(context.pool(), community.id)
275 Site::delete(context.pool(), site.id).await.unwrap();