2 check_is_apub_id_valid,
3 collections::{community_moderators::ApubCommunityModerators, CommunityContext},
4 generate_moderators_url,
7 objects::{group::Group, tombstone::Tombstone},
12 use activitystreams::{
13 actor::{kind::GroupType, Endpoints},
14 object::kind::ImageType,
16 use chrono::NaiveDateTime;
17 use itertools::Itertools;
18 use lemmy_api_common::blocking;
21 traits::{ActorType, ApubObject},
22 values::MediaTypeMarkdown,
24 use lemmy_db_schema::source::community::Community;
25 use lemmy_db_views_actor::community_follower_view::CommunityFollowerView;
27 utils::{convert_datetime, markdown_to_html},
30 use lemmy_websocket::LemmyContext;
35 #[derive(Clone, Debug)]
36 pub struct ApubCommunity(Community);
38 impl Deref for ApubCommunity {
39 type Target = Community;
40 fn deref(&self) -> &Self::Target {
45 impl From<Community> for ApubCommunity {
46 fn from(c: Community) -> Self {
47 ApubCommunity { 0: c }
51 #[async_trait::async_trait(?Send)]
52 impl ApubObject for ApubCommunity {
53 type DataType = LemmyContext;
54 type ApubType = Group;
55 type TombstoneType = Tombstone;
57 fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
58 Some(self.last_refreshed_at)
61 async fn read_from_apub_id(
63 context: &LemmyContext,
64 ) -> Result<Option<Self>, LemmyError> {
66 blocking(context.pool(), move |conn| {
67 Community::read_from_apub_id(conn, object_id)
74 async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
75 blocking(context.pool(), move |conn| {
76 Community::update_deleted(conn, self.id, true)
82 async fn to_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(|url| ImageObject {
88 kind: ImageType::Image,
91 let image = self.banner.clone().map(|url| ImageObject {
92 kind: ImageType::Image,
97 kind: GroupType::Group,
98 id: ObjectId::new(self.actor_id()),
99 preferred_username: self.name.clone(),
100 name: self.title.clone(),
101 summary: self.description.as_ref().map(|b| markdown_to_html(b)),
105 sensitive: Some(self.nsfw),
106 moderators: Some(ObjectId::<ApubCommunityModerators>::new(
107 generate_moderators_url(&self.actor_id)?,
109 inbox: self.inbox_url.clone().into(),
110 outbox: ObjectId::new(generate_outbox_url(&self.actor_id)?),
111 followers: self.followers_url.clone().into(),
112 endpoints: Endpoints {
113 shared_inbox: self.shared_inbox_url.clone().map(|s| s.into()),
116 public_key: self.get_public_key()?,
117 published: Some(convert_datetime(self.published)),
118 updated: self.updated.map(convert_datetime),
119 unparsed: Default::default(),
124 fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
127 self.updated.unwrap_or(self.published),
131 /// Converts a `Group` to `Community`, inserts it into the database and updates moderators.
134 context: &LemmyContext,
135 expected_domain: &Url,
136 request_counter: &mut i32,
137 ) -> Result<ApubCommunity, LemmyError> {
138 let form = Group::from_apub_to_form(group, expected_domain, &context.settings()).await?;
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, request_counter)
152 .map_err(|e| debug!("{}", e))
155 if let Some(moderators) = &group.moderators {
157 .dereference(&outbox_data, request_counter)
159 .map_err(|e| debug!("{}", e))
167 impl ActorType for ApubCommunity {
168 fn is_local(&self) -> bool {
171 fn actor_id(&self) -> Url {
172 self.actor_id.to_owned().into()
174 fn name(&self) -> String {
177 fn public_key(&self) -> Option<String> {
178 self.public_key.to_owned()
180 fn private_key(&self) -> Option<String> {
181 self.private_key.to_owned()
184 fn inbox_url(&self) -> Url {
185 self.inbox_url.clone().into()
188 fn shared_inbox_url(&self) -> Option<Url> {
189 self.shared_inbox_url.clone().map(|s| s.into())
194 /// For a given community, returns the inboxes of all followers.
195 pub(crate) async fn get_follower_inboxes(
197 additional_inboxes: Vec<Url>,
198 context: &LemmyContext,
199 ) -> Result<Vec<Url>, LemmyError> {
202 let follows = blocking(context.pool(), move |conn| {
203 CommunityFollowerView::for_community(conn, id)
206 let follower_inboxes: Vec<Url> = follows
208 .filter(|f| !f.follower.local)
212 .unwrap_or(f.follower.inbox_url)
216 let inboxes = vec![follower_inboxes, additional_inboxes]
220 .filter(|inbox| inbox.host_str() != Some(&context.settings().hostname))
221 // Don't send to blocked instances
222 .filter(|inbox| check_is_apub_id_valid(inbox, false, &context.settings()).is_ok())
230 pub(crate) mod tests {
232 use crate::objects::tests::{file_to_json_object, init_context};
233 use lemmy_db_schema::traits::Crud;
234 use serial_test::serial;
236 pub(crate) async fn parse_lemmy_community(context: &LemmyContext) -> ApubCommunity {
237 let mut json: Group = file_to_json_object("assets/lemmy/objects/group.json");
238 // change these links so they dont fetch over the network
239 json.moderators = None;
241 ObjectId::new(Url::parse("https://enterprise.lemmy.ml/c/tenforward/not_outbox").unwrap());
243 let url = Url::parse("https://enterprise.lemmy.ml/c/tenforward").unwrap();
244 let mut request_counter = 0;
245 let community = ApubCommunity::from_apub(&json, context, &url, &mut request_counter)
248 // this makes two requests to the (intentionally) broken outbox/moderators collections
249 assert_eq!(request_counter, 1);
255 async fn test_parse_lemmy_community() {
256 let context = init_context();
257 let community = parse_lemmy_community(&context).await;
259 assert_eq!(community.title, "Ten Forward");
260 assert!(community.public_key.is_some());
261 assert!(!community.local);
262 assert_eq!(community.description.as_ref().unwrap().len(), 132);
264 Community::delete(&*context.pool().get().unwrap(), community.id).unwrap();