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