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::{actor::kind::GroupType, object::kind::ImageType};
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 async fn read_from_apub_id(
60 context: &LemmyContext,
61 ) -> Result<Option<Self>, LemmyError> {
63 blocking(context.pool(), move |conn| {
64 Community::read_from_apub_id(conn, object_id)
71 async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
72 blocking(context.pool(), move |conn| {
73 Community::update_deleted(conn, self.id, true)
79 async fn into_apub(self, _context: &LemmyContext) -> Result<Group, LemmyError> {
80 let source = self.description.clone().map(|bio| Source {
82 media_type: MediaTypeMarkdown::Markdown,
84 let icon = self.icon.clone().map(|url| ImageObject {
85 kind: ImageType::Image,
88 let image = self.banner.clone().map(|url| ImageObject {
89 kind: ImageType::Image,
94 kind: GroupType::Group,
95 id: ObjectId::new(self.actor_id()),
96 preferred_username: self.name.clone(),
97 name: self.title.clone(),
98 summary: self.description.as_ref().map(|b| markdown_to_html(b)),
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: Endpoints {
110 shared_inbox: self.shared_inbox_url.clone().map(|s| s.into()),
112 public_key: self.get_public_key()?,
113 published: Some(convert_datetime(self.published)),
114 updated: self.updated.map(convert_datetime),
115 unparsed: Default::default(),
120 fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
123 self.updated.unwrap_or(self.published),
127 /// Converts a `Group` to `Community`, inserts it into the database and updates moderators.
130 context: &LemmyContext,
131 expected_domain: &Url,
132 request_counter: &mut i32,
133 ) -> Result<ApubCommunity, LemmyError> {
134 let form = Group::into_form(group.clone(), expected_domain, &context.settings()).await?;
136 // Fetching mods and outbox is not necessary for Lemmy to work, so ignore errors. Besides,
137 // we need to ignore these errors so that tests can work entirely offline.
138 let community: ApubCommunity =
139 blocking(context.pool(), move |conn| Community::upsert(conn, &form))
142 let outbox_data = CommunityContext(community.clone(), context.clone());
146 .dereference(&outbox_data, request_counter)
148 .map_err(|e| debug!("{}", e))
151 if let Some(moderators) = &group.moderators {
153 .dereference(&outbox_data, request_counter)
155 .map_err(|e| debug!("{}", e))
163 impl ActorType for ApubCommunity {
164 fn is_local(&self) -> bool {
167 fn actor_id(&self) -> Url {
168 self.actor_id.to_owned().into()
170 fn name(&self) -> String {
173 fn public_key(&self) -> Option<String> {
174 self.public_key.to_owned()
176 fn private_key(&self) -> Option<String> {
177 self.private_key.to_owned()
180 fn inbox_url(&self) -> Url {
181 self.inbox_url.clone().into()
184 fn shared_inbox_url(&self) -> Option<Url> {
185 self.shared_inbox_url.clone().map(|s| s.into())
190 /// For a given community, returns the inboxes of all followers.
191 pub(crate) async fn get_follower_inboxes(
193 additional_inboxes: Vec<Url>,
194 context: &LemmyContext,
195 ) -> Result<Vec<Url>, LemmyError> {
198 let follows = blocking(context.pool(), move |conn| {
199 CommunityFollowerView::for_community(conn, id)
202 let follower_inboxes: Vec<Url> = follows
204 .filter(|f| !f.follower.local)
208 .unwrap_or(f.follower.inbox_url)
212 let inboxes = vec![follower_inboxes, additional_inboxes]
216 .filter(|inbox| inbox.host_str() != Some(&context.settings().hostname))
217 // Don't send to blocked instances
218 .filter(|inbox| check_is_apub_id_valid(inbox, false, &context.settings()).is_ok())
226 pub(crate) mod tests {
228 use crate::objects::tests::{file_to_json_object, init_context};
229 use lemmy_db_schema::traits::Crud;
230 use serial_test::serial;
232 pub(crate) async fn parse_lemmy_community(context: &LemmyContext) -> ApubCommunity {
233 let mut json: Group = file_to_json_object("assets/lemmy/objects/group.json");
234 // change these links so they dont fetch over the network
235 json.moderators = None;
237 ObjectId::new(Url::parse("https://enterprise.lemmy.ml/c/tenforward/not_outbox").unwrap());
239 let url = Url::parse("https://enterprise.lemmy.ml/c/tenforward").unwrap();
240 let mut request_counter = 0;
241 let community = ApubCommunity::from_apub(json, context, &url, &mut request_counter)
244 // this makes two requests to the (intentionally) broken outbox/moderators collections
245 assert_eq!(request_counter, 1);
251 async fn test_parse_lemmy_community() {
252 let context = init_context();
253 let community = parse_lemmy_community(&context).await;
255 assert_eq!(community.title, "Ten Forward");
256 assert!(community.public_key.is_some());
257 assert!(!community.local);
258 assert_eq!(community.description.as_ref().unwrap().len(), 132);
260 Community::delete(&*context.pool().get().unwrap(), community.id).unwrap();