2 fetcher::fetch::fetch_remote_object,
3 objects::{comment::Note, post::Page, FromApub},
7 use diesel::result::Error::NotFound;
8 use lemmy_api_common::blocking;
9 use lemmy_db_queries::{ApubObject, Crud};
10 use lemmy_db_schema::source::{comment::Comment, post::Post};
11 use lemmy_utils::LemmyError;
12 use lemmy_websocket::LemmyContext;
16 /// Gets a post by its apub ID. If it exists locally, it is returned directly. Otherwise it is
17 /// pulled from its apub ID, inserted and returned.
19 /// The parent community is also pulled if necessary. Comments are not pulled.
20 pub async fn get_or_fetch_and_insert_post(
22 context: &LemmyContext,
23 recursion_counter: &mut i32,
24 ) -> Result<Post, LemmyError> {
25 let post_ap_id_owned = post_ap_id.to_owned();
26 let post = blocking(context.pool(), move |conn| {
27 Post::read_from_apub_id(conn, &post_ap_id_owned.into())
34 debug!("Fetching and creating remote post: {}", post_ap_id);
36 fetch_remote_object::<Page>(context.client(), post_ap_id, recursion_counter).await?;
37 let post = Post::from_apub(&page, context, post_ap_id, recursion_counter).await?;
41 Err(e) => Err(e.into()),
45 /// Gets a comment by its apub ID. If it exists locally, it is returned directly. Otherwise it is
46 /// pulled from its apub ID, inserted and returned.
48 /// The parent community, post and comment are also pulled if necessary.
49 pub async fn get_or_fetch_and_insert_comment(
51 context: &LemmyContext,
52 recursion_counter: &mut i32,
53 ) -> Result<Comment, LemmyError> {
54 let comment_ap_id_owned = comment_ap_id.to_owned();
55 let comment = blocking(context.pool(), move |conn| {
56 Comment::read_from_apub_id(conn, &comment_ap_id_owned.into())
64 "Fetching and creating remote comment and its parents: {}",
68 fetch_remote_object::<Note>(context.client(), comment_ap_id, recursion_counter).await?;
69 let comment = Comment::from_apub(&comment, context, comment_ap_id, recursion_counter).await?;
71 let post_id = comment.post_id;
72 let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
74 return Err(anyhow!("Post is locked").into());
79 Err(e) => Err(e.into()),
83 pub async fn get_or_fetch_and_insert_post_or_comment(
85 context: &LemmyContext,
86 recursion_counter: &mut i32,
87 ) -> Result<PostOrComment, LemmyError> {
89 match get_or_fetch_and_insert_post(ap_id, context, recursion_counter).await {
90 Ok(p) => PostOrComment::Post(Box::new(p)),
92 let c = get_or_fetch_and_insert_comment(ap_id, context, recursion_counter).await?;
93 PostOrComment::Comment(Box::new(c))