2 fetcher::{fetch::fetch_remote_object, is_deleted, should_refetch_actor},
7 use diesel::result::Error::NotFound;
8 use lemmy_api_structs::blocking;
9 use lemmy_db_queries::{source::user::User, ApubObject};
10 use lemmy_db_schema::source::user::User_;
11 use lemmy_utils::LemmyError;
12 use lemmy_websocket::LemmyContext;
16 /// Get a user from its apub ID.
18 /// If it exists locally and `!should_refetch_actor()`, it is returned directly from the database.
19 /// Otherwise it is fetched from the remote instance, stored and returned.
20 pub(crate) async fn get_or_fetch_and_upsert_user(
22 context: &LemmyContext,
23 recursion_counter: &mut i32,
24 ) -> Result<User_, LemmyError> {
25 let apub_id_owned = apub_id.to_owned();
26 let user = blocking(context.pool(), move |conn| {
27 User_::read_from_apub_id(conn, &apub_id_owned.into())
32 // If its older than a day, re-fetch it
33 Ok(u) if !u.local && should_refetch_actor(u.last_refreshed_at) => {
34 debug!("Fetching and updating from remote user: {}", apub_id);
36 fetch_remote_object::<PersonExt>(context.client(), apub_id, recursion_counter).await;
38 if is_deleted(&person) {
39 // TODO: use User_::update_deleted() once implemented
40 blocking(context.pool(), move |conn| {
41 User_::delete_account(conn, u.id)
44 return Err(anyhow!("User was deleted by remote instance").into());
45 } else if person.is_err() {
49 let user = User_::from_apub(&person?, context, apub_id.to_owned(), recursion_counter).await?;
51 let user_id = user.id;
52 blocking(context.pool(), move |conn| {
53 User_::mark_as_updated(conn, user_id)
61 debug!("Fetching and creating remote user: {}", apub_id);
63 fetch_remote_object::<PersonExt>(context.client(), apub_id, recursion_counter).await?;
65 let user = User_::from_apub(&person, context, apub_id.to_owned(), recursion_counter).await?;
69 Err(e) => Err(e.into()),