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?;
94 kind: GroupType::Group,
95 id: ObjectId::new(self.actor_id()),
96 preferred_username: self.name.clone(),
97 name: Some(self.title.clone()),
98 summary: self.description.as_ref().map(|b| markdown_to_html(b)),
99 source: self.description.clone().map(Source::new),
100 icon: self.icon.clone().map(ImageObject::new),
101 image: self.banner.clone().map(ImageObject::new),
102 sensitive: Some(self.nsfw),
103 moderators: Some(ObjectId::<ApubCommunityModerators>::new(
104 generate_moderators_url(&self.actor_id)?,
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),
121 #[tracing::instrument(skip_all)]
124 expected_domain: &Url,
125 context: &LemmyContext,
126 _request_counter: &mut i32,
127 ) -> Result<(), LemmyError> {
128 group.verify(expected_domain, context).await
131 /// Converts a `Group` to `Community`, inserts it into the database and updates moderators.
132 #[tracing::instrument(skip_all)]
135 context: &LemmyContext,
136 request_counter: &mut i32,
137 ) -> Result<ApubCommunity, LemmyError> {
138 let apub_id = group.id.inner().to_owned();
139 let instance = Instance::create_from_actor_id(context.pool(), &apub_id).await?;
141 let form = Group::into_insert_form(group.clone(), instance.id);
142 let languages = LanguageTag::to_language_id_multiple(group.language, context.pool()).await?;
144 let community = Community::create(context.pool(), &form).await?;
145 CommunityLanguage::update(context.pool(), languages, community.id).await?;
147 let community: ApubCommunity = community.into();
148 let outbox_data = CommunityContext(community.clone(), context.clone());
150 // Fetching mods and outbox is not necessary for Lemmy to work, so ignore errors. Besides,
151 // we need to ignore these errors so that tests can work entirely offline.
154 .dereference(&outbox_data, local_instance(context).await, request_counter)
156 .map_err(|e| debug!("{}", e))
159 if let Some(moderators) = &group.moderators {
161 .dereference(&outbox_data, local_instance(context).await, request_counter)
163 .map_err(|e| debug!("{}", e))
167 fetch_instance_actor_for_object(community.actor_id(), context, request_counter).await;
173 impl Actor for ApubCommunity {
174 fn public_key(&self) -> &str {
178 fn inbox(&self) -> Url {
179 self.inbox_url.clone().into()
182 fn shared_inbox(&self) -> Option<Url> {
183 self.shared_inbox_url.clone().map(|s| s.into())
187 impl ActorType for ApubCommunity {
188 fn actor_id(&self) -> Url {
189 self.actor_id.to_owned().into()
191 fn private_key(&self) -> Option<String> {
192 self.private_key.to_owned()
197 /// For a given community, returns the inboxes of all followers.
198 #[tracing::instrument(skip_all)]
199 pub(crate) async fn get_follower_inboxes(
201 context: &LemmyContext,
202 ) -> Result<Vec<Url>, LemmyError> {
205 let local_site_data = fetch_local_site_data(context.pool()).await?;
206 let follows = CommunityFollowerView::for_community(context.pool(), id).await?;
207 let inboxes: Vec<Url> = follows
209 .filter(|f| !f.follower.local)
213 .unwrap_or(f.follower.inbox_url)
217 .filter(|inbox: &Url| inbox.host_str() != Some(&context.settings().hostname))
218 // Don't send to blocked instances
220 check_apub_id_valid_with_strictness(inbox, false, &local_site_data, context.settings())
230 pub(crate) mod tests {
233 objects::{instance::tests::parse_lemmy_instance, tests::init_context},
234 protocol::tests::file_to_json_object,
236 use lemmy_db_schema::{source::site::Site, traits::Crud};
237 use serial_test::serial;
239 pub(crate) async fn parse_lemmy_community(context: &LemmyContext) -> ApubCommunity {
240 let mut json: Group = file_to_json_object("assets/lemmy/objects/group.json").unwrap();
241 // change these links so they dont fetch over the network
242 json.moderators = None;
244 ObjectId::new(Url::parse("https://enterprise.lemmy.ml/c/tenforward/not_outbox").unwrap());
246 let url = Url::parse("https://enterprise.lemmy.ml/c/tenforward").unwrap();
247 let mut request_counter = 0;
248 ApubCommunity::verify(&json, &url, context, &mut request_counter)
251 let community = ApubCommunity::from_apub(json, context, &mut request_counter)
254 // this makes one requests to the (intentionally broken) outbox collection
255 assert_eq!(request_counter, 1);
261 async fn test_parse_lemmy_community() {
262 let context = init_context().await;
263 let site = parse_lemmy_instance(&context).await;
264 let community = parse_lemmy_community(&context).await;
266 assert_eq!(community.title, "Ten Forward");
267 assert!(!community.local);
268 assert_eq!(community.description.as_ref().unwrap().len(), 132);
270 Community::delete(context.pool(), community.id)
273 Site::delete(context.pool(), site.id).await.unwrap();