]> Untitled Git - lemmy.git/blob - crates/apub/src/collections/community_outbox.rs
a16fbd02bba8ad75d3b3b1769600b34e167c1ffd
[lemmy.git] / crates / apub / src / collections / community_outbox.rs
1 use crate::{
2   activity_lists::AnnouncableActivities,
3   collections::CommunityContext,
4   objects::post::ApubPost,
5   protocol::{
6     activities::{
7       community::announce::AnnounceActivity,
8       create_or_update::page::CreateOrUpdatePage,
9       CreateOrUpdateType,
10     },
11     collections::group_outbox::GroupOutbox,
12   },
13 };
14 use activitypub_federation::{
15   data::Data,
16   traits::{ActivityHandler, ApubObject},
17   utils::verify_domains_match,
18 };
19 use activitystreams_kinds::collection::OrderedCollectionType;
20 use chrono::NaiveDateTime;
21 use futures::future::join_all;
22 use lemmy_api_common::utils::generate_outbox_url;
23 use lemmy_db_schema::{
24   source::{person::Person, post::Post},
25   traits::Crud,
26 };
27 use lemmy_utils::error::LemmyError;
28 use url::Url;
29
30 #[derive(Clone, Debug)]
31 pub(crate) struct ApubCommunityOutbox(Vec<ApubPost>);
32
33 #[async_trait::async_trait(?Send)]
34 impl ApubObject for ApubCommunityOutbox {
35   type DataType = CommunityContext;
36   type ApubType = GroupOutbox;
37   type Error = LemmyError;
38
39   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
40     None
41   }
42
43   #[tracing::instrument(skip_all)]
44   async fn read_from_apub_id(
45     _object_id: Url,
46     data: &Self::DataType,
47   ) -> Result<Option<Self>, LemmyError> {
48     // Only read from database if its a local community, otherwise fetch over http
49     if data.0.local {
50       let community_id = data.0.id;
51       let post_list: Vec<ApubPost> = Post::list_for_community(data.1.pool(), community_id)
52         .await?
53         .into_iter()
54         .map(Into::into)
55         .collect();
56       Ok(Some(ApubCommunityOutbox(post_list)))
57     } else {
58       Ok(None)
59     }
60   }
61
62   async fn delete(self, _data: &Self::DataType) -> Result<(), LemmyError> {
63     // do nothing (it gets deleted automatically with the community)
64     Ok(())
65   }
66
67   #[tracing::instrument(skip_all)]
68   async fn into_apub(self, data: &Self::DataType) -> Result<Self::ApubType, LemmyError> {
69     let mut ordered_items = vec![];
70     for post in self.0 {
71       let person = Person::read(data.1.pool(), post.creator_id).await?.into();
72       let create =
73         CreateOrUpdatePage::new(post, &person, &data.0, CreateOrUpdateType::Create, &data.1)
74           .await?;
75       let announcable = AnnouncableActivities::CreateOrUpdatePost(create);
76       let announce = AnnounceActivity::new(announcable.try_into()?, &data.0, &data.1)?;
77       ordered_items.push(announce);
78     }
79
80     Ok(GroupOutbox {
81       r#type: OrderedCollectionType::OrderedCollection,
82       id: generate_outbox_url(&data.0.actor_id)?.into(),
83       total_items: ordered_items.len() as i32,
84       ordered_items,
85     })
86   }
87
88   #[tracing::instrument(skip_all)]
89   async fn verify(
90     group_outbox: &GroupOutbox,
91     expected_domain: &Url,
92     _context: &CommunityContext,
93     _request_counter: &mut i32,
94   ) -> Result<(), LemmyError> {
95     verify_domains_match(expected_domain, &group_outbox.id)?;
96     Ok(())
97   }
98
99   #[tracing::instrument(skip_all)]
100   async fn from_apub(
101     apub: Self::ApubType,
102     data: &Self::DataType,
103     _request_counter: &mut i32,
104   ) -> Result<Self, LemmyError> {
105     let mut outbox_activities = apub.ordered_items;
106     if outbox_activities.len() > 20 {
107       outbox_activities = outbox_activities[0..20].to_vec();
108     }
109
110     // We intentionally ignore errors here. This is because the outbox might contain posts from old
111     // Lemmy versions, or from other software which we cant parse. In that case, we simply skip the
112     // item and only parse the ones that work.
113     let data = Data::new(data.1.clone());
114     // process items in parallel, to avoid long delay from fetch_site_metadata() and other processing
115     join_all(outbox_activities.into_iter().map(|activity| {
116       async {
117         // use separate request counter for each item, otherwise there will be problems with
118         // parallel processing
119         let request_counter = &mut 0;
120         let verify = activity.verify(&data, request_counter).await;
121         if verify.is_ok() {
122           activity.receive(&data, request_counter).await.ok();
123         }
124       }
125     }))
126     .await;
127
128     // This return value is unused, so just set an empty vec
129     Ok(ApubCommunityOutbox(Vec::new()))
130   }
131
132   type DbType = ();
133 }