2 check_apub_id_valid_with_strictness,
3 collections::{community_moderators::ApubCommunityModerators, CommunityContext},
5 generate_moderators_url,
8 objects::instance::fetch_instance_actor_for_object,
10 objects::{group::Group, Endpoints, LanguageTag},
16 use activitypub_federation::{
17 core::object_id::ObjectId,
18 traits::{Actor, ApubObject},
20 use activitystreams_kinds::actor::GroupType;
21 use chrono::NaiveDateTime;
22 use itertools::Itertools;
23 use lemmy_db_schema::{
25 actor_language::CommunityLanguage,
26 community::{Community, CommunityUpdateForm},
29 traits::{ApubActor, Crud},
31 use lemmy_db_views_actor::structs::CommunityFollowerView;
34 utils::{convert_datetime, markdown_to_html},
36 use lemmy_websocket::LemmyContext;
41 #[derive(Clone, Debug)]
42 pub struct ApubCommunity(Community);
44 impl Deref for ApubCommunity {
45 type Target = Community;
46 fn deref(&self) -> &Self::Target {
51 impl From<Community> for ApubCommunity {
52 fn from(c: Community) -> Self {
57 #[async_trait::async_trait(?Send)]
58 impl ApubObject for ApubCommunity {
59 type DataType = LemmyContext;
60 type ApubType = Group;
61 type DbType = Community;
62 type Error = LemmyError;
64 fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
65 Some(self.last_refreshed_at)
68 #[tracing::instrument(skip_all)]
69 async fn read_from_apub_id(
71 context: &LemmyContext,
72 ) -> Result<Option<Self>, LemmyError> {
74 Community::read_from_apub_id(context.pool(), &object_id.into())
80 #[tracing::instrument(skip_all)]
81 async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
82 let form = CommunityUpdateForm::builder().deleted(Some(true)).build();
83 Community::update(context.pool(), self.id, &form).await?;
87 #[tracing::instrument(skip_all)]
88 async fn into_apub(self, data: &LemmyContext) -> Result<Group, LemmyError> {
89 let community_id = self.id;
90 let langs = CommunityLanguage::read(data.pool(), community_id).await?;
91 let language = LanguageTag::new_multiple(langs, data.pool()).await?;
92 let attributed_to = Some(ObjectId::<ApubCommunityModerators>::new(
93 generate_moderators_url(&self.actor_id)?,
97 kind: GroupType::Group,
98 id: ObjectId::new(self.actor_id()),
99 preferred_username: self.name.clone(),
100 name: Some(self.title.clone()),
101 summary: self.description.as_ref().map(|b| markdown_to_html(b)),
102 source: self.description.clone().map(Source::new),
103 icon: self.icon.clone().map(ImageObject::new),
104 image: self.banner.clone().map(ImageObject::new),
105 sensitive: Some(self.nsfw),
106 moderators: attributed_to.clone(),
107 inbox: self.inbox_url.clone().into(),
108 outbox: ObjectId::new(generate_outbox_url(&self.actor_id)?),
109 followers: self.followers_url.clone().into(),
110 endpoints: self.shared_inbox_url.clone().map(|s| Endpoints {
111 shared_inbox: s.into(),
113 public_key: self.get_public_key(),
115 published: Some(convert_datetime(self.published)),
116 updated: self.updated.map(convert_datetime),
117 posting_restricted_to_mods: Some(self.posting_restricted_to_mods),
123 #[tracing::instrument(skip_all)]
126 expected_domain: &Url,
127 context: &LemmyContext,
128 _request_counter: &mut i32,
129 ) -> Result<(), LemmyError> {
130 group.verify(expected_domain, context).await
133 /// Converts a `Group` to `Community`, inserts it into the database and updates moderators.
134 #[tracing::instrument(skip_all)]
137 context: &LemmyContext,
138 request_counter: &mut i32,
139 ) -> Result<ApubCommunity, LemmyError> {
140 let apub_id = group.id.inner().clone();
141 let instance = Instance::create_from_actor_id(context.pool(), &apub_id).await?;
143 let form = Group::into_insert_form(group.clone(), instance.id);
144 let languages = LanguageTag::to_language_id_multiple(group.language, context.pool()).await?;
146 let community = Community::create(context.pool(), &form).await?;
147 CommunityLanguage::update(context.pool(), languages, community.id).await?;
149 let community: ApubCommunity = community.into();
150 let outbox_data = CommunityContext(community.clone(), context.clone());
152 // Fetching mods and outbox is not necessary for Lemmy to work, so ignore errors. Besides,
153 // we need to ignore these errors so that tests can work entirely offline.
156 .dereference(&outbox_data, local_instance(context).await, request_counter)
158 .map_err(|e| debug!("{}", e))
161 if let Some(moderators) = group.attributed_to.or(group.moderators) {
163 .dereference(&outbox_data, local_instance(context).await, request_counter)
165 .map_err(|e| debug!("{}", e))
169 fetch_instance_actor_for_object(community.actor_id(), context, request_counter).await;
175 impl Actor for ApubCommunity {
176 fn public_key(&self) -> &str {
180 fn inbox(&self) -> Url {
181 self.inbox_url.clone().into()
184 fn shared_inbox(&self) -> Option<Url> {
185 self.shared_inbox_url.clone().map(Into::into)
189 impl ActorType for ApubCommunity {
190 fn actor_id(&self) -> Url {
191 self.actor_id.clone().into()
193 fn private_key(&self) -> Option<String> {
194 self.private_key.clone()
199 /// For a given community, returns the inboxes of all followers.
200 #[tracing::instrument(skip_all)]
201 pub(crate) async fn get_follower_inboxes(
203 context: &LemmyContext,
204 ) -> Result<Vec<Url>, LemmyError> {
207 let local_site_data = fetch_local_site_data(context.pool()).await?;
208 let follows = CommunityFollowerView::for_community(context.pool(), id).await?;
209 let inboxes: Vec<Url> = follows
211 .filter(|f| !f.follower.local)
215 .unwrap_or(f.follower.inbox_url)
219 .filter(|inbox: &Url| inbox.host_str() != Some(&context.settings().hostname))
220 // Don't send to blocked instances
222 check_apub_id_valid_with_strictness(inbox, false, &local_site_data, context.settings())
232 pub(crate) mod tests {
235 objects::{instance::tests::parse_lemmy_instance, tests::init_context},
236 protocol::tests::file_to_json_object,
238 use lemmy_db_schema::{source::site::Site, traits::Crud};
239 use serial_test::serial;
241 pub(crate) async fn parse_lemmy_community(context: &LemmyContext) -> ApubCommunity {
242 let mut json: Group = file_to_json_object("assets/lemmy/objects/group.json").unwrap();
243 // change these links so they dont fetch over the network
244 json.moderators = None;
245 json.attributed_to = None;
247 ObjectId::new(Url::parse("https://enterprise.lemmy.ml/c/tenforward/not_outbox").unwrap());
249 let url = Url::parse("https://enterprise.lemmy.ml/c/tenforward").unwrap();
250 let mut request_counter = 0;
251 ApubCommunity::verify(&json, &url, context, &mut request_counter)
254 let community = ApubCommunity::from_apub(json, context, &mut request_counter)
257 // this makes one requests to the (intentionally broken) outbox collection
258 assert_eq!(request_counter, 1);
264 async fn test_parse_lemmy_community() {
265 let context = init_context().await;
266 let site = parse_lemmy_instance(&context).await;
267 let community = parse_lemmy_community(&context).await;
269 assert_eq!(community.title, "Ten Forward");
270 assert!(!community.local);
271 assert_eq!(community.description.as_ref().unwrap().len(), 132);
273 Community::delete(context.pool(), community.id)
276 Site::delete(context.pool(), site.id).await.unwrap();