2 check_apub_id_valid_with_strictness,
3 collections::{community_moderators::ApubCommunityModerators, CommunityContext},
4 generate_moderators_url,
7 objects::instance::fetch_instance_actor_for_object,
9 objects::{group::Group, Endpoints, LanguageTag},
15 use activitypub_federation::{
16 core::object_id::ObjectId,
17 traits::{Actor, ApubObject},
19 use activitystreams_kinds::actor::GroupType;
20 use chrono::NaiveDateTime;
21 use itertools::Itertools;
22 use lemmy_api_common::utils::blocking;
23 use lemmy_db_schema::{
24 source::{actor_language::CommunityLanguage, community::Community},
27 use lemmy_db_views_actor::structs::CommunityFollowerView;
30 utils::{convert_datetime, markdown_to_html},
32 use lemmy_websocket::LemmyContext;
37 #[derive(Clone, Debug)]
38 pub struct ApubCommunity(Community);
40 impl Deref for ApubCommunity {
41 type Target = Community;
42 fn deref(&self) -> &Self::Target {
47 impl From<Community> for ApubCommunity {
48 fn from(c: Community) -> Self {
53 #[async_trait::async_trait(?Send)]
54 impl ApubObject for ApubCommunity {
55 type DataType = LemmyContext;
56 type ApubType = Group;
57 type DbType = Community;
58 type Error = LemmyError;
60 fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
61 Some(self.last_refreshed_at)
64 #[tracing::instrument(skip_all)]
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.into())
78 #[tracing::instrument(skip_all)]
79 async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
80 blocking(context.pool(), move |conn| {
81 Community::update_deleted(conn, self.id, true)
87 #[tracing::instrument(skip_all)]
88 async fn into_apub(self, data: &LemmyContext) -> Result<Group, LemmyError> {
89 let community_id = self.id;
90 let langs = blocking(data.pool(), move |conn| {
91 CommunityLanguage::read(conn, community_id)
94 let language = LanguageTag::new_multiple(langs, data.pool()).await?;
97 kind: GroupType::Group,
98 id: ObjectId::new(self.actor_id()),
99 preferred_username: self.name.clone(),
100 name: Some(self.title.clone()),
101 summary: self.description.as_ref().map(|b| markdown_to_html(b)),
102 source: self.description.clone().map(Source::new),
103 icon: self.icon.clone().map(ImageObject::new),
104 image: self.banner.clone().map(ImageObject::new),
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: self.shared_inbox_url.clone().map(|s| Endpoints {
113 shared_inbox: s.into(),
115 public_key: self.get_public_key(),
117 published: Some(convert_datetime(self.published)),
118 updated: self.updated.map(convert_datetime),
119 posting_restricted_to_mods: Some(self.posting_restricted_to_mods),
124 #[tracing::instrument(skip_all)]
127 expected_domain: &Url,
128 context: &LemmyContext,
129 _request_counter: &mut i32,
130 ) -> Result<(), LemmyError> {
131 group.verify(expected_domain, context).await
134 /// Converts a `Group` to `Community`, inserts it into the database and updates moderators.
135 #[tracing::instrument(skip_all)]
138 context: &LemmyContext,
139 request_counter: &mut i32,
140 ) -> Result<ApubCommunity, LemmyError> {
141 let form = Group::into_form(group.clone());
142 let languages = LanguageTag::to_language_id_multiple(group.language, context.pool()).await?;
144 let community: ApubCommunity = blocking(context.pool(), move |conn| {
145 let community = Community::upsert(conn, &form)?;
146 CommunityLanguage::update(conn, languages, community.id)?;
147 Ok::<Community, diesel::result::Error>(community)
151 let outbox_data = CommunityContext(community.clone(), context.clone());
153 // Fetching mods and outbox is not necessary for Lemmy to work, so ignore errors. Besides,
154 // we need to ignore these errors so that tests can work entirely offline.
157 .dereference(&outbox_data, local_instance(context), request_counter)
159 .map_err(|e| debug!("{}", e))
162 if let Some(moderators) = &group.moderators {
164 .dereference(&outbox_data, local_instance(context), request_counter)
166 .map_err(|e| debug!("{}", e))
170 fetch_instance_actor_for_object(community.actor_id(), context, request_counter).await;
176 impl Actor for ApubCommunity {
177 fn public_key(&self) -> &str {
181 fn inbox(&self) -> Url {
182 self.inbox_url.clone().into()
185 fn shared_inbox(&self) -> Option<Url> {
186 self.shared_inbox_url.clone().map(|s| s.into())
190 impl ActorType for ApubCommunity {
191 fn actor_id(&self) -> Url {
192 self.actor_id.to_owned().into()
194 fn private_key(&self) -> Option<String> {
195 self.private_key.to_owned()
200 /// For a given community, returns the inboxes of all followers.
201 #[tracing::instrument(skip_all)]
202 pub(crate) async fn get_follower_inboxes(
204 context: &LemmyContext,
205 ) -> Result<Vec<Url>, LemmyError> {
208 let follows = blocking(context.pool(), move |conn| {
209 CommunityFollowerView::for_community(conn, id)
212 let inboxes: Vec<Url> = follows
214 .filter(|f| !f.follower.local)
218 .unwrap_or(f.follower.inbox_url)
222 .filter(|inbox: &Url| inbox.host_str() != Some(&context.settings().hostname))
223 // Don't send to blocked instances
224 .filter(|inbox| check_apub_id_valid_with_strictness(inbox, false, context.settings()).is_ok())
232 pub(crate) mod tests {
235 objects::{instance::tests::parse_lemmy_instance, tests::init_context},
236 protocol::tests::file_to_json_object,
238 use lemmy_db_schema::{source::site::Site, traits::Crud};
239 use serial_test::serial;
241 pub(crate) async fn parse_lemmy_community(context: &LemmyContext) -> ApubCommunity {
242 let mut json: Group = file_to_json_object("assets/lemmy/objects/group.json").unwrap();
243 // change these links so they dont fetch over the network
244 json.moderators = None;
246 ObjectId::new(Url::parse("https://enterprise.lemmy.ml/c/tenforward/not_outbox").unwrap());
248 let url = Url::parse("https://enterprise.lemmy.ml/c/tenforward").unwrap();
249 let mut request_counter = 0;
250 ApubCommunity::verify(&json, &url, context, &mut request_counter)
253 let community = ApubCommunity::from_apub(json, context, &mut request_counter)
256 // this makes one requests to the (intentionally broken) outbox collection
257 assert_eq!(request_counter, 1);
263 async fn test_parse_lemmy_community() {
264 let context = init_context();
265 let conn = &mut context.pool().get().unwrap();
266 let site = parse_lemmy_instance(&context).await;
267 let community = parse_lemmy_community(&context).await;
269 assert_eq!(community.title, "Ten Forward");
270 assert!(!community.local);
271 assert_eq!(community.description.as_ref().unwrap().len(), 132);
273 Community::delete(conn, community.id).unwrap();
274 Site::delete(conn, site.id).unwrap();