4 actor::{kind::GroupType, Endpoints},
5 object::kind::ImageType,
7 use chrono::NaiveDateTime;
8 use itertools::Itertools;
12 use lemmy_api_common::blocking;
14 traits::{ActorType, ApubObject},
15 values::MediaTypeMarkdown,
17 use lemmy_db_schema::{source::community::Community, DbPool};
18 use lemmy_db_views_actor::community_follower_view::CommunityFollowerView;
20 settings::structs::Settings,
21 utils::{convert_datetime, markdown_to_html},
24 use lemmy_websocket::LemmyContext;
27 check_is_apub_id_valid,
28 collections::{community_moderators::ApubCommunityModerators, CommunityContext},
29 fetcher::object_id::ObjectId,
30 generate_moderators_url,
33 objects::{group::Group, tombstone::Tombstone},
39 #[derive(Clone, Debug)]
40 pub struct ApubCommunity(Community);
42 impl Deref for ApubCommunity {
43 type Target = Community;
44 fn deref(&self) -> &Self::Target {
49 impl From<Community> for ApubCommunity {
50 fn from(c: Community) -> Self {
51 ApubCommunity { 0: c }
55 #[async_trait::async_trait(?Send)]
56 impl ApubObject for ApubCommunity {
57 type DataType = LemmyContext;
58 type ApubType = Group;
59 type TombstoneType = Tombstone;
61 fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
62 Some(self.last_refreshed_at)
65 async fn read_from_apub_id(
67 context: &LemmyContext,
68 ) -> Result<Option<Self>, LemmyError> {
70 blocking(context.pool(), move |conn| {
71 Community::read_from_apub_id(conn, object_id)
78 async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
79 blocking(context.pool(), move |conn| {
80 Community::update_deleted(conn, self.id, true)
86 async fn to_apub(&self, _context: &LemmyContext) -> Result<Group, LemmyError> {
87 let source = self.description.clone().map(|bio| Source {
89 media_type: MediaTypeMarkdown::Markdown,
91 let icon = self.icon.clone().map(|url| ImageObject {
92 kind: ImageType::Image,
95 let image = self.banner.clone().map(|url| ImageObject {
96 kind: ImageType::Image,
101 kind: GroupType::Group,
103 preferred_username: self.name.clone(),
104 name: self.title.clone(),
105 summary: self.description.as_ref().map(|b| markdown_to_html(b)),
109 sensitive: Some(self.nsfw),
110 moderators: Some(ObjectId::<ApubCommunityModerators>::new(
111 generate_moderators_url(&self.actor_id)?.into_inner(),
113 inbox: self.inbox_url.clone().into(),
114 outbox: ObjectId::new(generate_outbox_url(&self.actor_id)?),
115 followers: self.followers_url.clone().into(),
116 endpoints: Endpoints {
117 shared_inbox: self.shared_inbox_url.clone().map(|s| s.into()),
120 public_key: self.get_public_key()?,
121 published: Some(convert_datetime(self.published)),
122 updated: self.updated.map(convert_datetime),
123 unparsed: Default::default(),
128 fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
131 self.updated.unwrap_or(self.published),
135 /// Converts a `Group` to `Community`, inserts it into the database and updates moderators.
138 context: &LemmyContext,
139 expected_domain: &Url,
140 request_counter: &mut i32,
141 ) -> Result<ApubCommunity, LemmyError> {
142 let form = Group::from_apub_to_form(group, expected_domain, &context.settings()).await?;
144 // Fetching mods and outbox is not necessary for Lemmy to work, so ignore errors. Besides,
145 // we need to ignore these errors so that tests can work entirely offline.
146 let community: ApubCommunity =
147 blocking(context.pool(), move |conn| Community::upsert(conn, &form))
150 let outbox_data = CommunityContext(community.clone(), context.clone());
154 .dereference(&outbox_data, request_counter)
156 .map_err(|e| debug!("{}", e))
159 if let Some(moderators) = &group.moderators {
161 .dereference(&outbox_data, request_counter)
163 .map_err(|e| debug!("{}", e))
171 impl ActorType for ApubCommunity {
172 fn is_local(&self) -> bool {
175 fn actor_id(&self) -> Url {
176 self.actor_id.to_owned().into()
178 fn name(&self) -> String {
181 fn public_key(&self) -> Option<String> {
182 self.public_key.to_owned()
184 fn private_key(&self) -> Option<String> {
185 self.private_key.to_owned()
188 fn inbox_url(&self) -> Url {
189 self.inbox_url.clone().into()
192 fn shared_inbox_url(&self) -> Option<Url> {
193 self.shared_inbox_url.clone().map(|s| s.into_inner())
198 /// For a given community, returns the inboxes of all followers.
199 pub(crate) async fn get_follower_inboxes(
203 ) -> Result<Vec<Url>, LemmyError> {
206 let follows = blocking(pool, move |conn| {
207 CommunityFollowerView::for_community(conn, id)
210 let inboxes = follows
212 .filter(|f| !f.follower.local)
213 .map(|f| f.follower.shared_inbox_url.unwrap_or(f.follower.inbox_url))
214 .map(|i| i.into_inner())
216 // Don't send to blocked instances
217 .filter(|inbox| check_is_apub_id_valid(inbox, false, settings).is_ok())
225 pub(crate) mod tests {
227 use crate::objects::tests::{file_to_json_object, init_context};
228 use lemmy_db_schema::traits::Crud;
229 use serial_test::serial;
231 pub(crate) async fn parse_lemmy_community(context: &LemmyContext) -> ApubCommunity {
232 let mut json: Group = file_to_json_object("assets/lemmy/objects/group.json");
233 // change these links so they dont fetch over the network
234 json.moderators = None;
236 ObjectId::new(Url::parse("https://enterprise.lemmy.ml/c/tenforward/not_outbox").unwrap());
238 let url = Url::parse("https://enterprise.lemmy.ml/c/tenforward").unwrap();
239 let mut request_counter = 0;
240 let community = ApubCommunity::from_apub(&json, context, &url, &mut request_counter)
243 // this makes two requests to the (intentionally) broken outbox/moderators collections
244 assert_eq!(request_counter, 1);
250 async fn test_parse_lemmy_community() {
251 let context = init_context();
252 let community = parse_lemmy_community(&context).await;
254 assert_eq!(community.title, "Ten Forward");
255 assert!(community.public_key.is_some());
256 assert!(!community.local);
257 assert_eq!(community.description.as_ref().unwrap().len(), 132);
259 Community::delete(&*context.pool().get().unwrap(), community.id).unwrap();