2 check_is_apub_id_valid,
3 collections::{community_moderators::ApubCommunityModerators, CommunityContext},
4 generate_moderators_url,
7 objects::{group::Group, tombstone::Tombstone, Endpoints},
12 use activitystreams_kinds::actor::GroupType;
13 use chrono::NaiveDateTime;
14 use itertools::Itertools;
15 use lemmy_api_common::blocking;
18 traits::{ActorType, ApubObject},
19 values::MediaTypeMarkdown,
21 use lemmy_db_schema::source::community::Community;
22 use lemmy_db_views_actor::community_follower_view::CommunityFollowerView;
24 utils::{convert_datetime, markdown_to_html},
27 use lemmy_websocket::LemmyContext;
32 #[derive(Clone, Debug)]
33 pub struct ApubCommunity(Community);
35 impl Deref for ApubCommunity {
36 type Target = Community;
37 fn deref(&self) -> &Self::Target {
42 impl From<Community> for ApubCommunity {
43 fn from(c: Community) -> Self {
44 ApubCommunity { 0: c }
48 #[async_trait::async_trait(?Send)]
49 impl ApubObject for ApubCommunity {
50 type DataType = LemmyContext;
51 type ApubType = Group;
52 type TombstoneType = Tombstone;
54 fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
55 Some(self.last_refreshed_at)
58 #[tracing::instrument(skip_all)]
59 async fn read_from_apub_id(
61 context: &LemmyContext,
62 ) -> Result<Option<Self>, LemmyError> {
64 blocking(context.pool(), move |conn| {
65 Community::read_from_apub_id(conn, object_id)
72 #[tracing::instrument(skip_all)]
73 async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
74 blocking(context.pool(), move |conn| {
75 Community::update_deleted(conn, self.id, true)
81 #[tracing::instrument(skip_all)]
82 async fn into_apub(self, _context: &LemmyContext) -> Result<Group, LemmyError> {
83 let source = self.description.clone().map(|bio| Source {
85 media_type: MediaTypeMarkdown::Markdown,
87 let icon = self.icon.clone().map(ImageObject::new);
88 let image = self.banner.clone().map(ImageObject::new);
91 kind: GroupType::Group,
92 id: ObjectId::new(self.actor_id()),
93 preferred_username: self.name.clone(),
94 name: self.title.clone(),
95 summary: self.description.as_ref().map(|b| markdown_to_html(b)),
99 sensitive: Some(self.nsfw),
100 moderators: Some(ObjectId::<ApubCommunityModerators>::new(
101 generate_moderators_url(&self.actor_id)?,
103 inbox: self.inbox_url.clone().into(),
104 outbox: ObjectId::new(generate_outbox_url(&self.actor_id)?),
105 followers: self.followers_url.clone().into(),
106 endpoints: self.shared_inbox_url.clone().map(|s| Endpoints {
107 shared_inbox: s.into(),
109 public_key: self.get_public_key()?,
110 published: Some(convert_datetime(self.published)),
111 updated: self.updated.map(convert_datetime),
112 unparsed: Default::default(),
117 fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
118 Ok(Tombstone::new(self.actor_id()))
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 form = Group::into_form(group.clone());
140 // Fetching mods and outbox is not necessary for Lemmy to work, so ignore errors. Besides,
141 // we need to ignore these errors so that tests can work entirely offline.
142 let community: ApubCommunity =
143 blocking(context.pool(), move |conn| Community::upsert(conn, &form))
146 let outbox_data = CommunityContext(community.clone(), context.clone());
150 .dereference(&outbox_data, context.client(), request_counter)
152 .map_err(|e| debug!("{}", e))
155 if let Some(moderators) = &group.moderators {
157 .dereference(&outbox_data, context.client(), request_counter)
159 .map_err(|e| debug!("{}", e))
167 impl ActorType for ApubCommunity {
168 fn actor_id(&self) -> Url {
169 self.actor_id.to_owned().into()
171 fn public_key(&self) -> String {
172 self.public_key.to_owned()
174 fn private_key(&self) -> Option<String> {
175 self.private_key.to_owned()
178 fn inbox_url(&self) -> Url {
179 self.inbox_url.clone().into()
182 fn shared_inbox_url(&self) -> Option<Url> {
183 self.shared_inbox_url.clone().map(|s| s.into())
188 /// For a given community, returns the inboxes of all followers.
189 #[tracing::instrument(skip_all)]
190 pub(crate) async fn get_follower_inboxes(
192 context: &LemmyContext,
193 ) -> Result<Vec<Url>, LemmyError> {
196 let follows = blocking(context.pool(), move |conn| {
197 CommunityFollowerView::for_community(conn, id)
200 let inboxes: Vec<Url> = follows
202 .filter(|f| !f.follower.local)
206 .unwrap_or(f.follower.inbox_url)
210 .filter(|inbox: &Url| inbox.host_str() != Some(&context.settings().hostname))
211 // Don't send to blocked instances
212 .filter(|inbox| check_is_apub_id_valid(inbox, false, &context.settings()).is_ok())
220 pub(crate) mod tests {
222 use crate::objects::tests::{file_to_json_object, init_context};
223 use lemmy_apub_lib::activity_queue::create_activity_queue;
224 use lemmy_db_schema::traits::Crud;
225 use serial_test::serial;
227 pub(crate) async fn parse_lemmy_community(context: &LemmyContext) -> ApubCommunity {
228 let mut json: Group = file_to_json_object("assets/lemmy/objects/group.json").unwrap();
229 // change these links so they dont fetch over the network
230 json.moderators = None;
232 ObjectId::new(Url::parse("https://enterprise.lemmy.ml/c/tenforward/not_outbox").unwrap());
234 let url = Url::parse("https://enterprise.lemmy.ml/c/tenforward").unwrap();
235 let mut request_counter = 0;
236 ApubCommunity::verify(&json, &url, context, &mut request_counter)
239 let community = ApubCommunity::from_apub(json, context, &mut request_counter)
242 // this makes two requests to the (intentionally) broken outbox/moderators collections
243 assert_eq!(request_counter, 1);
249 async fn test_parse_lemmy_community() {
250 let client = reqwest::Client::new().into();
251 let manager = create_activity_queue(client);
252 let context = init_context(manager.queue_handle().clone());
253 let community = parse_lemmy_community(&context).await;
255 assert_eq!(community.title, "Ten Forward");
256 assert!(!community.local);
257 assert_eq!(community.description.as_ref().unwrap().len(), 132);
259 Community::delete(&*context.pool().get().unwrap(), community.id).unwrap();