]> Untitled Git - lemmy.git/blob - crates/apub/src/fetcher/mod.rs
Rewrite collections to use new fetcher (#1861)
[lemmy.git] / crates / apub / src / fetcher / mod.rs
1 pub mod object_id;
2 pub mod post_or_comment;
3 pub mod search;
4
5 use crate::{
6   fetcher::object_id::ObjectId,
7   objects::{community::ApubCommunity, person::ApubPerson},
8 };
9 use chrono::NaiveDateTime;
10 use lemmy_apub_lib::traits::ActorType;
11 use lemmy_db_schema::naive_now;
12 use lemmy_utils::LemmyError;
13 use lemmy_websocket::LemmyContext;
14 use url::Url;
15
16 static ACTOR_REFETCH_INTERVAL_SECONDS: i64 = 24 * 60 * 60;
17 static ACTOR_REFETCH_INTERVAL_SECONDS_DEBUG: i64 = 10;
18
19 /// Get a remote actor from its apub ID (either a person or a community). Thin wrapper around
20 /// `get_or_fetch_and_upsert_person()` and `get_or_fetch_and_upsert_community()`.
21 ///
22 /// If it exists locally and `!should_refetch_actor()`, it is returned directly from the database.
23 /// Otherwise it is fetched from the remote instance, stored and returned.
24 pub(crate) async fn get_or_fetch_and_upsert_actor(
25   apub_id: Url,
26   context: &LemmyContext,
27   recursion_counter: &mut i32,
28 ) -> Result<Box<dyn ActorType>, LemmyError> {
29   let community_id = ObjectId::<ApubCommunity>::new(apub_id.clone());
30   let community = community_id.dereference(context, recursion_counter).await;
31   let actor: Box<dyn ActorType> = match community {
32     Ok(c) => Box::new(c),
33     Err(_) => {
34       let person_id = ObjectId::new(apub_id);
35       let person: ApubPerson = person_id.dereference(context, recursion_counter).await?;
36       Box::new(person)
37     }
38   };
39   Ok(actor)
40 }
41
42 /// Determines when a remote actor should be refetched from its instance. In release builds, this is
43 /// `ACTOR_REFETCH_INTERVAL_SECONDS` after the last refetch, in debug builds
44 /// `ACTOR_REFETCH_INTERVAL_SECONDS_DEBUG`.
45 ///
46 /// TODO it won't pick up new avatars, summaries etc until a day after.
47 /// Actors need an "update" activity pushed to other servers to fix this.
48 fn should_refetch_object(last_refreshed: NaiveDateTime) -> bool {
49   let update_interval = if cfg!(debug_assertions) {
50     // avoid infinite loop when fetching community outbox
51     chrono::Duration::seconds(ACTOR_REFETCH_INTERVAL_SECONDS_DEBUG)
52   } else {
53     chrono::Duration::seconds(ACTOR_REFETCH_INTERVAL_SECONDS)
54   };
55   last_refreshed.lt(&(naive_now() - update_interval))
56 }