2 check_is_apub_id_valid,
4 community_moderators::ApubCommunityModerators,
5 community_outbox::ApubCommunityOutbox,
8 fetcher::object_id::ObjectId,
9 generate_moderators_url,
11 objects::{get_summary_from_string_or_source, tombstone::Tombstone, ImageObject, Source},
13 use activitystreams::{
14 actor::{kind::GroupType, Endpoints},
15 object::kind::ImageType,
18 use chrono::{DateTime, FixedOffset, NaiveDateTime};
19 use itertools::Itertools;
20 use lemmy_api_common::blocking;
22 signatures::PublicKey,
23 traits::{ActorType, ApubObject},
24 values::MediaTypeMarkdown,
25 verify::verify_domains_match,
27 use lemmy_db_schema::{
29 source::community::{Community, CommunityForm},
32 use lemmy_db_views_actor::community_follower_view::CommunityFollowerView;
34 settings::structs::Settings,
35 utils::{check_slurs, check_slurs_opt, convert_datetime, markdown_to_html},
38 use lemmy_websocket::LemmyContext;
40 use serde::{Deserialize, Serialize};
41 use serde_with::skip_serializing_none;
45 #[skip_serializing_none]
46 #[derive(Clone, Debug, Deserialize, Serialize)]
47 #[serde(rename_all = "camelCase")]
49 #[serde(rename = "type")]
52 /// username, set at account creation and can never be changed
53 preferred_username: String,
54 /// title (can be changed at any time)
56 summary: Option<String>,
57 source: Option<Source>,
58 icon: Option<ImageObject>,
60 image: Option<ImageObject>,
62 sensitive: Option<bool>,
64 pub(crate) moderators: Option<ObjectId<ApubCommunityModerators>>,
66 pub(crate) outbox: ObjectId<ApubCommunityOutbox>,
68 endpoints: Endpoints<Url>,
69 public_key: PublicKey,
70 published: Option<DateTime<FixedOffset>>,
71 updated: Option<DateTime<FixedOffset>>,
77 pub(crate) async fn from_apub_to_form(
79 expected_domain: &Url,
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());
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)?;
98 published: group.published.map(|u| u.naive_local()),
99 updated: group.updated.map(|u| u.naive_local()),
101 nsfw: Some(group.sensitive.unwrap_or(false)),
102 actor_id: Some(group.id.clone().into()),
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),
116 #[derive(Clone, Debug)]
117 pub struct ApubCommunity(Community);
119 impl Deref for ApubCommunity {
120 type Target = Community;
121 fn deref(&self) -> &Self::Target {
126 impl From<Community> for ApubCommunity {
127 fn from(c: Community) -> Self {
128 ApubCommunity { 0: c }
132 #[async_trait::async_trait(?Send)]
133 impl ApubObject for ApubCommunity {
134 type DataType = LemmyContext;
135 type ApubType = Group;
136 type TombstoneType = Tombstone;
138 fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
139 Some(self.last_refreshed_at)
142 async fn read_from_apub_id(
144 context: &LemmyContext,
145 ) -> Result<Option<Self>, LemmyError> {
147 blocking(context.pool(), move |conn| {
148 Community::read_from_apub_id(conn, object_id)
155 async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
156 blocking(context.pool(), move |conn| {
157 Community::update_deleted(conn, self.id, true)
163 async fn to_apub(&self, _context: &LemmyContext) -> Result<Group, LemmyError> {
164 let source = self.description.clone().map(|bio| Source {
166 media_type: MediaTypeMarkdown::Markdown,
168 let icon = self.icon.clone().map(|url| ImageObject {
169 kind: ImageType::Image,
172 let image = self.banner.clone().map(|url| ImageObject {
173 kind: ImageType::Image,
178 kind: GroupType::Group,
180 preferred_username: self.name.clone(),
181 name: self.title.clone(),
182 summary: self.description.as_ref().map(|b| markdown_to_html(b)),
186 sensitive: Some(self.nsfw),
187 moderators: Some(ObjectId::<ApubCommunityModerators>::new(
188 generate_moderators_url(&self.actor_id)?.into_inner(),
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()),
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(),
205 fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
208 self.updated.unwrap_or(self.published),
212 /// Converts a `Group` to `Community`, inserts it into the database and updates moderators.
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?;
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))
227 let outbox_data = CommunityContext(community.clone(), context.clone());
231 .dereference(&outbox_data, request_counter)
233 .map_err(|e| debug!("{}", e))
236 if let Some(moderators) = &group.moderators {
238 .dereference(&outbox_data, request_counter)
240 .map_err(|e| debug!("{}", e))
248 impl ActorType for ApubCommunity {
249 fn is_local(&self) -> bool {
252 fn actor_id(&self) -> Url {
253 self.actor_id.to_owned().into()
255 fn name(&self) -> String {
258 fn public_key(&self) -> Option<String> {
259 self.public_key.to_owned()
261 fn private_key(&self) -> Option<String> {
262 self.private_key.to_owned()
265 fn inbox_url(&self) -> Url {
266 self.inbox_url.clone().into()
269 fn shared_inbox_url(&self) -> Option<Url> {
270 self.shared_inbox_url.clone().map(|s| s.into_inner())
275 /// For a given community, returns the inboxes of all followers.
276 pub(crate) async fn get_follower_inboxes(
280 ) -> Result<Vec<Url>, LemmyError> {
283 let follows = blocking(pool, move |conn| {
284 CommunityFollowerView::for_community(conn, id)
287 let inboxes = follows
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())
293 // Don't send to blocked instances
294 .filter(|inbox| check_is_apub_id_valid(inbox, false, settings).is_ok())
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;
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(),
320 ObjectId::new(Url::parse("https://enterprise.lemmy.ml/c/tenforward/not_outbox").unwrap());
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)
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);
336 let to_apub = community.to_apub(&context).await.unwrap();
337 assert_json_include!(actual: json_orig, expected: to_apub);
339 Community::delete(&*context.pool().get().unwrap(), community.id).unwrap();