]> Untitled Git - lemmy.git/blob - crates/apub/src/collections/community_outbox.rs
Rewrite community outbox to use new fetcher
[lemmy.git] / crates / apub / src / collections / community_outbox.rs
1 use crate::{
2   activities::{post::create_or_update::CreateOrUpdatePost, CreateOrUpdateType},
3   collections::CommunityContext,
4   context::lemmy_context,
5   generate_outbox_url,
6   objects::{person::ApubPerson, post::ApubPost},
7 };
8 use activitystreams::{
9   base::AnyBase,
10   chrono::NaiveDateTime,
11   collection::kind::OrderedCollectionType,
12   object::Tombstone,
13   primitives::OneOrMany,
14   url::Url,
15 };
16 use lemmy_api_common::blocking;
17 use lemmy_apub_lib::{
18   data::Data,
19   traits::{ActivityHandler, ApubObject},
20   verify::verify_domains_match,
21 };
22 use lemmy_db_schema::{
23   source::{person::Person, post::Post},
24   traits::Crud,
25 };
26 use lemmy_utils::LemmyError;
27 use serde::{Deserialize, Serialize};
28 use serde_with::skip_serializing_none;
29
30 #[skip_serializing_none]
31 #[derive(Clone, Debug, Deserialize, Serialize)]
32 #[serde(rename_all = "camelCase")]
33 pub struct GroupOutbox {
34   #[serde(rename = "@context")]
35   context: OneOrMany<AnyBase>,
36   r#type: OrderedCollectionType,
37   id: Url,
38   ordered_items: Vec<CreateOrUpdatePost>,
39 }
40
41 #[derive(Clone, Debug)]
42 pub(crate) struct ApubCommunityOutbox(Vec<ApubPost>);
43
44 #[async_trait::async_trait(?Send)]
45 impl ApubObject for ApubCommunityOutbox {
46   type DataType = CommunityContext;
47   type TombstoneType = Tombstone;
48   type ApubType = GroupOutbox;
49
50   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
51     None
52   }
53
54   async fn read_from_apub_id(
55     _object_id: Url,
56     data: &Self::DataType,
57   ) -> Result<Option<Self>, LemmyError> {
58     // Only read from database if its a local community, otherwise fetch over http
59     if data.0.local {
60       let community_id = data.0.id;
61       let post_list: Vec<ApubPost> = blocking(data.1.pool(), move |conn| {
62         Post::list_for_community(conn, community_id)
63       })
64       .await??
65       .into_iter()
66       .map(Into::into)
67       .collect();
68       Ok(Some(ApubCommunityOutbox(post_list)))
69     } else {
70       Ok(None)
71     }
72   }
73
74   async fn delete(self, _data: &Self::DataType) -> Result<(), LemmyError> {
75     // do nothing (it gets deleted automatically with the community)
76     Ok(())
77   }
78
79   async fn to_apub(&self, data: &Self::DataType) -> Result<Self::ApubType, LemmyError> {
80     let mut ordered_items = vec![];
81     for post in &self.0 {
82       let actor = post.creator_id;
83       let actor: ApubPerson = blocking(data.1.pool(), move |conn| Person::read(conn, actor))
84         .await??
85         .into();
86       let a =
87         CreateOrUpdatePost::new(post, &actor, &data.0, CreateOrUpdateType::Create, &data.1).await?;
88       ordered_items.push(a);
89     }
90
91     Ok(GroupOutbox {
92       context: lemmy_context(),
93       r#type: OrderedCollectionType::OrderedCollection,
94       id: generate_outbox_url(&data.0.actor_id)?.into(),
95       ordered_items,
96     })
97   }
98
99   fn to_tombstone(&self) -> Result<Self::TombstoneType, LemmyError> {
100     // no tombstone for this, there is only a tombstone for the community
101     unimplemented!()
102   }
103
104   async fn from_apub(
105     apub: &Self::ApubType,
106     data: &Self::DataType,
107     expected_domain: &Url,
108     request_counter: &mut i32,
109   ) -> Result<Self, LemmyError> {
110     verify_domains_match(expected_domain, &apub.id)?;
111     let mut outbox_activities = apub.ordered_items.clone();
112     if outbox_activities.len() > 20 {
113       outbox_activities = outbox_activities[0..20].to_vec();
114     }
115
116     // We intentionally ignore errors here. This is because the outbox might contain posts from old
117     // Lemmy versions, or from other software which we cant parse. In that case, we simply skip the
118     // item and only parse the ones that work.
119     for activity in outbox_activities {
120       activity
121         .receive(&Data::new(data.1.clone()), request_counter)
122         .await
123         .ok();
124     }
125
126     // This return value is unused, so just set an empty vec
127     Ok(ApubCommunityOutbox { 0: vec![] })
128   }
129 }