]> Untitled Git - lemmy.git/blob - crates/apub/src/fetcher/community.rs
Use collection for moderators, instead of `attributedTo` (ref #1061)
[lemmy.git] / crates / apub / src / fetcher / community.rs
1 use crate::{
2   fetcher::{fetch::fetch_remote_object, is_deleted, should_refetch_actor},
3   inbox::user_inbox::receive_announce,
4   objects::FromApub,
5   GroupExt,
6 };
7 use activitystreams::{
8   actor::ApActorExt,
9   collection::{CollectionExt, OrderedCollection},
10 };
11 use anyhow::Context;
12 use diesel::result::Error::NotFound;
13 use lemmy_api_structs::blocking;
14 use lemmy_db_queries::{source::community::Community_, ApubObject};
15 use lemmy_db_schema::source::community::Community;
16 use lemmy_utils::{location_info, LemmyError};
17 use lemmy_websocket::LemmyContext;
18 use log::debug;
19 use url::Url;
20
21 /// Get a community from its apub ID.
22 ///
23 /// If it exists locally and `!should_refetch_actor()`, it is returned directly from the database.
24 /// Otherwise it is fetched from the remote instance, stored and returned.
25 pub(crate) async fn get_or_fetch_and_upsert_community(
26   apub_id: &Url,
27   context: &LemmyContext,
28   recursion_counter: &mut i32,
29 ) -> Result<Community, LemmyError> {
30   let apub_id_owned = apub_id.to_owned();
31   let community = blocking(context.pool(), move |conn| {
32     Community::read_from_apub_id(conn, &apub_id_owned.into())
33   })
34   .await?;
35
36   match community {
37     Ok(c) if !c.local && should_refetch_actor(c.last_refreshed_at) => {
38       debug!("Fetching and updating from remote community: {}", apub_id);
39       fetch_remote_community(apub_id, context, Some(c), recursion_counter).await
40     }
41     Ok(c) => Ok(c),
42     Err(NotFound {}) => {
43       debug!("Fetching and creating remote community: {}", apub_id);
44       fetch_remote_community(apub_id, context, None, recursion_counter).await
45     }
46     Err(e) => Err(e.into()),
47   }
48 }
49
50 /// Request a community by apub ID from a remote instance, including moderators. If `old_community`,
51 /// is set, this is an update for a community which is already known locally. If not, we don't know
52 /// the community yet and also pull the outbox, to get some initial posts.
53 async fn fetch_remote_community(
54   apub_id: &Url,
55   context: &LemmyContext,
56   old_community: Option<Community>,
57   recursion_counter: &mut i32,
58 ) -> Result<Community, LemmyError> {
59   let group = fetch_remote_object::<GroupExt>(context.client(), apub_id, recursion_counter).await;
60
61   if let Some(c) = old_community.to_owned() {
62     if is_deleted(&group) {
63       blocking(context.pool(), move |conn| {
64         Community::update_deleted(conn, c.id, true)
65       })
66       .await??;
67     } else if group.is_err() {
68       // If fetching failed, return the existing data.
69       return Ok(c);
70     }
71   }
72
73   let group = group?;
74   let community =
75     Community::from_apub(&group, context, apub_id.to_owned(), recursion_counter).await?;
76
77   // only fetch outbox for new communities, otherwise this can create an infinite loop
78   if old_community.is_none() {
79     let outbox = group.inner.outbox()?.context(location_info!())?;
80     fetch_community_outbox(context, outbox, &community, recursion_counter).await?
81   }
82
83   Ok(community)
84 }
85
86 async fn fetch_community_outbox(
87   context: &LemmyContext,
88   outbox: &Url,
89   community: &Community,
90   recursion_counter: &mut i32,
91 ) -> Result<(), LemmyError> {
92   let outbox =
93     fetch_remote_object::<OrderedCollection>(context.client(), outbox, recursion_counter).await?;
94   let outbox_activities = outbox.items().context(location_info!())?.clone();
95   let mut outbox_activities = outbox_activities.many().context(location_info!())?;
96   if outbox_activities.len() > 20 {
97     outbox_activities = outbox_activities[0..20].to_vec();
98   }
99
100   for activity in outbox_activities {
101     receive_announce(context, activity, community, recursion_counter).await?;
102   }
103
104   Ok(())
105 }