]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/community.rs
Move @context out of object/activity definitions
[lemmy.git] / crates / apub / src / objects / community.rs
1 use crate::{
2   check_is_apub_id_valid,
3   collections::{
4     community_moderators::ApubCommunityModerators,
5     community_outbox::ApubCommunityOutbox,
6     CommunityContext,
7   },
8   fetcher::object_id::ObjectId,
9   generate_moderators_url,
10   generate_outbox_url,
11   objects::{get_summary_from_string_or_source, tombstone::Tombstone, ImageObject, Source},
12 };
13 use activitystreams::{
14   actor::{kind::GroupType, Endpoints},
15   object::kind::ImageType,
16   unparsed::Unparsed,
17 };
18 use chrono::{DateTime, FixedOffset, NaiveDateTime};
19 use itertools::Itertools;
20 use lemmy_api_common::blocking;
21 use lemmy_apub_lib::{
22   signatures::PublicKey,
23   traits::{ActorType, ApubObject},
24   values::MediaTypeMarkdown,
25   verify::verify_domains_match,
26 };
27 use lemmy_db_schema::{
28   naive_now,
29   source::community::{Community, CommunityForm},
30   DbPool,
31 };
32 use lemmy_db_views_actor::community_follower_view::CommunityFollowerView;
33 use lemmy_utils::{
34   settings::structs::Settings,
35   utils::{check_slurs, check_slurs_opt, convert_datetime, markdown_to_html},
36   LemmyError,
37 };
38 use lemmy_websocket::LemmyContext;
39 use log::debug;
40 use serde::{Deserialize, Serialize};
41 use serde_with::skip_serializing_none;
42 use std::ops::Deref;
43 use url::Url;
44
45 #[skip_serializing_none]
46 #[derive(Clone, Debug, Deserialize, Serialize)]
47 #[serde(rename_all = "camelCase")]
48 pub struct Group {
49   #[serde(rename = "type")]
50   kind: GroupType,
51   pub(crate) id: Url,
52   /// username, set at account creation and can never be changed
53   preferred_username: String,
54   /// title (can be changed at any time)
55   name: String,
56   summary: Option<String>,
57   source: Option<Source>,
58   icon: Option<ImageObject>,
59   /// banner
60   image: Option<ImageObject>,
61   // lemmy extension
62   sensitive: Option<bool>,
63   // lemmy extension
64   pub(crate) moderators: Option<ObjectId<ApubCommunityModerators>>,
65   inbox: Url,
66   pub(crate) outbox: ObjectId<ApubCommunityOutbox>,
67   followers: Url,
68   endpoints: Endpoints<Url>,
69   public_key: PublicKey,
70   published: Option<DateTime<FixedOffset>>,
71   updated: Option<DateTime<FixedOffset>>,
72   #[serde(flatten)]
73   unparsed: Unparsed,
74 }
75
76 impl Group {
77   pub(crate) async fn from_apub_to_form(
78     group: &Group,
79     expected_domain: &Url,
80     settings: &Settings,
81   ) -> Result<CommunityForm, LemmyError> {
82     verify_domains_match(expected_domain, &group.id)?;
83     let name = group.preferred_username.clone();
84     let title = group.name.clone();
85     let description = get_summary_from_string_or_source(&group.summary, &group.source);
86     let shared_inbox = group.endpoints.shared_inbox.clone().map(|s| s.into());
87
88     let slur_regex = &settings.slur_regex();
89     check_slurs(&name, slur_regex)?;
90     check_slurs(&title, slur_regex)?;
91     check_slurs_opt(&description, slur_regex)?;
92
93     Ok(CommunityForm {
94       name,
95       title,
96       description,
97       removed: None,
98       published: group.published.map(|u| u.naive_local()),
99       updated: group.updated.map(|u| u.naive_local()),
100       deleted: None,
101       nsfw: Some(group.sensitive.unwrap_or(false)),
102       actor_id: Some(group.id.clone().into()),
103       local: Some(false),
104       private_key: None,
105       public_key: Some(group.public_key.public_key_pem.clone()),
106       last_refreshed_at: Some(naive_now()),
107       icon: Some(group.icon.clone().map(|i| i.url.into())),
108       banner: Some(group.image.clone().map(|i| i.url.into())),
109       followers_url: Some(group.followers.clone().into()),
110       inbox_url: Some(group.inbox.clone().into()),
111       shared_inbox_url: Some(shared_inbox),
112     })
113   }
114 }
115
116 #[derive(Clone, Debug)]
117 pub struct ApubCommunity(Community);
118
119 impl Deref for ApubCommunity {
120   type Target = Community;
121   fn deref(&self) -> &Self::Target {
122     &self.0
123   }
124 }
125
126 impl From<Community> for ApubCommunity {
127   fn from(c: Community) -> Self {
128     ApubCommunity { 0: c }
129   }
130 }
131
132 #[async_trait::async_trait(?Send)]
133 impl ApubObject for ApubCommunity {
134   type DataType = LemmyContext;
135   type ApubType = Group;
136   type TombstoneType = Tombstone;
137
138   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
139     Some(self.last_refreshed_at)
140   }
141
142   async fn read_from_apub_id(
143     object_id: Url,
144     context: &LemmyContext,
145   ) -> Result<Option<Self>, LemmyError> {
146     Ok(
147       blocking(context.pool(), move |conn| {
148         Community::read_from_apub_id(conn, object_id)
149       })
150       .await??
151       .map(Into::into),
152     )
153   }
154
155   async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
156     blocking(context.pool(), move |conn| {
157       Community::update_deleted(conn, self.id, true)
158     })
159     .await??;
160     Ok(())
161   }
162
163   async fn to_apub(&self, _context: &LemmyContext) -> Result<Group, LemmyError> {
164     let source = self.description.clone().map(|bio| Source {
165       content: bio,
166       media_type: MediaTypeMarkdown::Markdown,
167     });
168     let icon = self.icon.clone().map(|url| ImageObject {
169       kind: ImageType::Image,
170       url: url.into(),
171     });
172     let image = self.banner.clone().map(|url| ImageObject {
173       kind: ImageType::Image,
174       url: url.into(),
175     });
176
177     let group = Group {
178       kind: GroupType::Group,
179       id: self.actor_id(),
180       preferred_username: self.name.clone(),
181       name: self.title.clone(),
182       summary: self.description.as_ref().map(|b| markdown_to_html(b)),
183       source,
184       icon,
185       image,
186       sensitive: Some(self.nsfw),
187       moderators: Some(ObjectId::<ApubCommunityModerators>::new(
188         generate_moderators_url(&self.actor_id)?.into_inner(),
189       )),
190       inbox: self.inbox_url.clone().into(),
191       outbox: ObjectId::new(generate_outbox_url(&self.actor_id)?),
192       followers: self.followers_url.clone().into(),
193       endpoints: Endpoints {
194         shared_inbox: self.shared_inbox_url.clone().map(|s| s.into()),
195         ..Default::default()
196       },
197       public_key: self.get_public_key()?,
198       published: Some(convert_datetime(self.published)),
199       updated: self.updated.map(convert_datetime),
200       unparsed: Default::default(),
201     };
202     Ok(group)
203   }
204
205   fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
206     Ok(Tombstone::new(
207       GroupType::Group,
208       self.updated.unwrap_or(self.published),
209     ))
210   }
211
212   /// Converts a `Group` to `Community`, inserts it into the database and updates moderators.
213   async fn from_apub(
214     group: &Group,
215     context: &LemmyContext,
216     expected_domain: &Url,
217     request_counter: &mut i32,
218   ) -> Result<ApubCommunity, LemmyError> {
219     let form = Group::from_apub_to_form(group, expected_domain, &context.settings()).await?;
220
221     // Fetching mods and outbox is not necessary for Lemmy to work, so ignore errors. Besides,
222     // we need to ignore these errors so that tests can work entirely offline.
223     let community: ApubCommunity =
224       blocking(context.pool(), move |conn| Community::upsert(conn, &form))
225         .await??
226         .into();
227     let outbox_data = CommunityContext(community.clone(), context.clone());
228
229     group
230       .outbox
231       .dereference(&outbox_data, request_counter)
232       .await
233       .map_err(|e| debug!("{}", e))
234       .ok();
235
236     if let Some(moderators) = &group.moderators {
237       moderators
238         .dereference(&outbox_data, request_counter)
239         .await
240         .map_err(|e| debug!("{}", e))
241         .ok();
242     }
243
244     Ok(community)
245   }
246 }
247
248 impl ActorType for ApubCommunity {
249   fn is_local(&self) -> bool {
250     self.local
251   }
252   fn actor_id(&self) -> Url {
253     self.actor_id.to_owned().into()
254   }
255   fn name(&self) -> String {
256     self.name.clone()
257   }
258   fn public_key(&self) -> Option<String> {
259     self.public_key.to_owned()
260   }
261   fn private_key(&self) -> Option<String> {
262     self.private_key.to_owned()
263   }
264
265   fn inbox_url(&self) -> Url {
266     self.inbox_url.clone().into()
267   }
268
269   fn shared_inbox_url(&self) -> Option<Url> {
270     self.shared_inbox_url.clone().map(|s| s.into_inner())
271   }
272 }
273
274 impl ApubCommunity {
275   /// For a given community, returns the inboxes of all followers.
276   pub(crate) async fn get_follower_inboxes(
277     &self,
278     pool: &DbPool,
279     settings: &Settings,
280   ) -> Result<Vec<Url>, LemmyError> {
281     let id = self.id;
282
283     let follows = blocking(pool, move |conn| {
284       CommunityFollowerView::for_community(conn, id)
285     })
286     .await??;
287     let inboxes = follows
288       .into_iter()
289       .filter(|f| !f.follower.local)
290       .map(|f| f.follower.shared_inbox_url.unwrap_or(f.follower.inbox_url))
291       .map(|i| i.into_inner())
292       .unique()
293       // Don't send to blocked instances
294       .filter(|inbox| check_is_apub_id_valid(inbox, false, settings).is_ok())
295       .collect();
296
297     Ok(inboxes)
298   }
299 }
300
301 #[cfg(test)]
302 mod tests {
303   use super::*;
304   use crate::objects::tests::{file_to_json_object, init_context};
305   use assert_json_diff::assert_json_include;
306   use lemmy_db_schema::traits::Crud;
307   use serial_test::serial;
308
309   #[actix_rt::test]
310   #[serial]
311   async fn test_parse_lemmy_community() {
312     let context = init_context();
313     let mut json: Group = file_to_json_object("assets/lemmy-community.json");
314     let json_orig = json.clone();
315     // change these links so they dont fetch over the network
316     json.moderators = Some(ObjectId::new(
317       Url::parse("https://enterprise.lemmy.ml/c/tenforward/not_moderators").unwrap(),
318     ));
319     json.outbox =
320       ObjectId::new(Url::parse("https://enterprise.lemmy.ml/c/tenforward/not_outbox").unwrap());
321
322     let url = Url::parse("https://enterprise.lemmy.ml/c/tenforward").unwrap();
323     let mut request_counter = 0;
324     let community = ApubCommunity::from_apub(&json, &context, &url, &mut request_counter)
325       .await
326       .unwrap();
327
328     assert_eq!(community.actor_id.clone().into_inner(), url);
329     assert_eq!(community.title, "Ten Forward");
330     assert!(community.public_key.is_some());
331     assert!(!community.local);
332     assert_eq!(community.description.as_ref().unwrap().len(), 132);
333     // this makes two requests to the (intentionally) broken outbox/moderators collections
334     assert_eq!(request_counter, 2);
335
336     let to_apub = community.to_apub(&context).await.unwrap();
337     assert_json_include!(actual: json_orig, expected: to_apub);
338
339     Community::delete(&*context.pool().get().unwrap(), community.id).unwrap();
340   }
341 }