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