]> Untitled Git - lemmy.git/blob - crates/apub/src/fetcher/community.rs
Merge branch 'main' into federated-moderation
[lemmy.git] / crates / apub / src / fetcher / community.rs
1 use crate::{
2   fetcher::{fetch::fetch_remote_object, is_deleted, should_refetch_actor},
3   inbox::person_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 = Community::from_apub(
75     &group,
76     context,
77     apub_id.to_owned(),
78     recursion_counter,
79     false,
80   )
81   .await?;
82
83   // only fetch outbox for new communities, otherwise this can create an infinite loop
84   if old_community.is_none() {
85     let outbox = group.inner.outbox()?.context(location_info!())?;
86     fetch_community_outbox(context, outbox, &community, recursion_counter).await?
87   }
88
89   Ok(community)
90 }
91
92 async fn fetch_community_outbox(
93   context: &LemmyContext,
94   outbox: &Url,
95   community: &Community,
96   recursion_counter: &mut i32,
97 ) -> Result<(), LemmyError> {
98   let outbox =
99     fetch_remote_object::<OrderedCollection>(context.client(), outbox, recursion_counter).await?;
100   let outbox_activities = outbox.items().context(location_info!())?.clone();
101   let mut outbox_activities = outbox_activities.many().context(location_info!())?;
102   if outbox_activities.len() > 20 {
103     outbox_activities = outbox_activities[0..20].to_vec();
104   }
105
106   for activity in outbox_activities {
107     receive_announce(context, activity, community, recursion_counter).await?;
108   }
109
110   Ok(())
111 }
112
113 pub(crate) async fn fetch_community_mods(
114   context: &LemmyContext,
115   group: &GroupExt,
116   recursion_counter: &mut i32,
117 ) -> Result<Vec<Url>, LemmyError> {
118   if let Some(mods_url) = &group.ext_one.moderators {
119     let mods =
120       fetch_remote_object::<OrderedCollection>(context.client(), mods_url, recursion_counter)
121         .await?;
122     let mods = mods
123       .items()
124       .map(|i| i.as_many())
125       .flatten()
126       .context(location_info!())?
127       .iter()
128       .filter_map(|i| i.as_xsd_any_uri())
129       .map(|u| u.to_owned())
130       .collect();
131     Ok(mods)
132   } else {
133     Ok(vec![])
134   }
135 }