]> Untitled Git - lemmy.git/blob - crates/apub/src/fetcher/user.rs
Use Url type for ap_id fields in database (fixes #1364) (#1371)
[lemmy.git] / crates / apub / src / fetcher / user.rs
1 use crate::{
2   fetcher::{fetch::fetch_remote_object, is_deleted, should_refetch_actor},
3   objects::FromApub,
4   PersonExt,
5 };
6 use anyhow::anyhow;
7 use diesel::result::Error::NotFound;
8 use lemmy_db_queries::{source::user::User, ApubObject};
9 use lemmy_db_schema::source::user::User_;
10 use lemmy_structs::blocking;
11 use lemmy_utils::LemmyError;
12 use lemmy_websocket::LemmyContext;
13 use log::debug;
14 use url::Url;
15
16 /// Get a user from its apub ID.
17 ///
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(
21   apub_id: &Url,
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())
28   })
29   .await?;
30
31   match user {
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);
35       let person =
36         fetch_remote_object::<PersonExt>(context.client(), apub_id, recursion_counter).await;
37
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)
42         })
43         .await??;
44         return Err(anyhow!("User was deleted by remote instance").into());
45       } else if person.is_err() {
46         return Ok(u);
47       }
48
49       let user = User_::from_apub(&person?, context, apub_id.to_owned(), recursion_counter).await?;
50
51       let user_id = user.id;
52       blocking(context.pool(), move |conn| {
53         User_::mark_as_updated(conn, user_id)
54       })
55       .await??;
56
57       Ok(user)
58     }
59     Ok(u) => Ok(u),
60     Err(NotFound {}) => {
61       debug!("Fetching and creating remote user: {}", apub_id);
62       let person =
63         fetch_remote_object::<PersonExt>(context.client(), apub_id, recursion_counter).await?;
64
65       let user = User_::from_apub(&person, context, apub_id.to_owned(), recursion_counter).await?;
66
67       Ok(user)
68     }
69     Err(e) => Err(e.into()),
70   }
71 }