2 check_apub_id_valid_with_strictness,
3 collections::{community_moderators::ApubCommunityModerators, CommunityContext},
4 generate_moderators_url,
7 objects::instance::fetch_instance_actor_for_object,
9 objects::{group::Group, Endpoints},
15 use activitypub_federation::{
16 core::object_id::ObjectId,
17 traits::{Actor, ApubObject},
19 use activitystreams_kinds::actor::GroupType;
20 use chrono::NaiveDateTime;
21 use itertools::Itertools;
22 use lemmy_api_common::utils::blocking;
23 use lemmy_db_schema::{source::community::Community, traits::ApubActor};
24 use lemmy_db_views_actor::structs::CommunityFollowerView;
27 utils::{convert_datetime, markdown_to_html},
29 use lemmy_websocket::LemmyContext;
34 #[derive(Clone, Debug)]
35 pub struct ApubCommunity(Community);
37 impl Deref for ApubCommunity {
38 type Target = Community;
39 fn deref(&self) -> &Self::Target {
44 impl From<Community> for ApubCommunity {
45 fn from(c: Community) -> Self {
50 #[async_trait::async_trait(?Send)]
51 impl ApubObject for ApubCommunity {
52 type DataType = LemmyContext;
53 type ApubType = Group;
54 type DbType = Community;
55 type Error = LemmyError;
57 fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
58 Some(self.last_refreshed_at)
61 #[tracing::instrument(skip_all)]
62 async fn read_from_apub_id(
64 context: &LemmyContext,
65 ) -> Result<Option<Self>, LemmyError> {
67 blocking(context.pool(), move |conn| {
68 Community::read_from_apub_id(conn, &object_id.into())
75 #[tracing::instrument(skip_all)]
76 async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
77 blocking(context.pool(), move |conn| {
78 Community::update_deleted(conn, self.id, true)
84 #[tracing::instrument(skip_all)]
85 async fn into_apub(self, _context: &LemmyContext) -> Result<Group, LemmyError> {
87 kind: GroupType::Group,
88 id: ObjectId::new(self.actor_id()),
89 preferred_username: self.name.clone(),
90 name: Some(self.title.clone()),
91 summary: self.description.as_ref().map(|b| markdown_to_html(b)),
92 source: self.description.clone().map(Source::new),
93 icon: self.icon.clone().map(ImageObject::new),
94 image: self.banner.clone().map(ImageObject::new),
95 sensitive: Some(self.nsfw),
96 moderators: Some(ObjectId::<ApubCommunityModerators>::new(
97 generate_moderators_url(&self.actor_id)?,
99 inbox: self.inbox_url.clone().into(),
100 outbox: ObjectId::new(generate_outbox_url(&self.actor_id)?),
101 followers: self.followers_url.clone().into(),
102 endpoints: self.shared_inbox_url.clone().map(|s| Endpoints {
103 shared_inbox: s.into(),
105 public_key: self.get_public_key(),
106 published: Some(convert_datetime(self.published)),
107 updated: self.updated.map(convert_datetime),
108 posting_restricted_to_mods: Some(self.posting_restricted_to_mods),
113 #[tracing::instrument(skip_all)]
116 expected_domain: &Url,
117 context: &LemmyContext,
118 _request_counter: &mut i32,
119 ) -> Result<(), LemmyError> {
120 group.verify(expected_domain, context).await
123 /// Converts a `Group` to `Community`, inserts it into the database and updates moderators.
124 #[tracing::instrument(skip_all)]
127 context: &LemmyContext,
128 request_counter: &mut i32,
129 ) -> Result<ApubCommunity, LemmyError> {
130 let form = Group::into_form(group.clone());
132 // Fetching mods and outbox is not necessary for Lemmy to work, so ignore errors. Besides,
133 // we need to ignore these errors so that tests can work entirely offline.
134 let community: ApubCommunity =
135 blocking(context.pool(), move |conn| Community::upsert(conn, &form))
138 let outbox_data = CommunityContext(community.clone(), context.clone());
142 .dereference(&outbox_data, local_instance(context), request_counter)
144 .map_err(|e| debug!("{}", e))
147 if let Some(moderators) = &group.moderators {
149 .dereference(&outbox_data, local_instance(context), request_counter)
151 .map_err(|e| debug!("{}", e))
155 fetch_instance_actor_for_object(community.actor_id(), context, request_counter).await;
161 impl Actor for ApubCommunity {
162 fn public_key(&self) -> &str {
166 fn inbox(&self) -> Url {
167 self.inbox_url.clone().into()
170 fn shared_inbox(&self) -> Option<Url> {
171 self.shared_inbox_url.clone().map(|s| s.into())
175 impl ActorType for ApubCommunity {
176 fn actor_id(&self) -> Url {
177 self.actor_id.to_owned().into()
179 fn private_key(&self) -> Option<String> {
180 self.private_key.to_owned()
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 follows = blocking(context.pool(), move |conn| {
194 CommunityFollowerView::for_community(conn, id)
197 let inboxes: Vec<Url> = follows
199 .filter(|f| !f.follower.local)
203 .unwrap_or(f.follower.inbox_url)
207 .filter(|inbox: &Url| inbox.host_str() != Some(&context.settings().hostname))
208 // Don't send to blocked instances
209 .filter(|inbox| check_apub_id_valid_with_strictness(inbox, false, context.settings()).is_ok())
217 pub(crate) mod tests {
220 objects::{instance::tests::parse_lemmy_instance, tests::init_context},
221 protocol::tests::file_to_json_object,
223 use lemmy_db_schema::{source::site::Site, traits::Crud};
224 use serial_test::serial;
226 pub(crate) async fn parse_lemmy_community(context: &LemmyContext) -> ApubCommunity {
227 let mut json: Group = file_to_json_object("assets/lemmy/objects/group.json").unwrap();
228 // change these links so they dont fetch over the network
229 json.moderators = None;
231 ObjectId::new(Url::parse("https://enterprise.lemmy.ml/c/tenforward/not_outbox").unwrap());
233 let url = Url::parse("https://enterprise.lemmy.ml/c/tenforward").unwrap();
234 let mut request_counter = 0;
235 ApubCommunity::verify(&json, &url, context, &mut request_counter)
238 let community = ApubCommunity::from_apub(json, context, &mut request_counter)
241 // this makes one requests to the (intentionally broken) outbox collection
242 assert_eq!(request_counter, 1);
248 async fn test_parse_lemmy_community() {
249 let context = init_context();
250 let site = parse_lemmy_instance(&context).await;
251 let community = parse_lemmy_community(&context).await;
253 assert_eq!(community.title, "Ten Forward");
254 assert!(!community.local);
255 assert_eq!(community.description.as_ref().unwrap().len(), 132);
257 Community::delete(&*context.pool().get().unwrap(), community.id).unwrap();
258 Site::delete(&*context.pool().get().unwrap(), site.id).unwrap();