]> Untitled Git - lemmy.git/blob - crates/apub/src/api/list_comments.rs
Make functions work with both connection and pool (#3420)
[lemmy.git] / crates / apub / src / api / list_comments.rs
1 use crate::{
2   api::listing_type_with_default,
3   fetcher::resolve_actor_identifier,
4   objects::community::ApubCommunity,
5 };
6 use activitypub_federation::config::Data;
7 use actix_web::web::{Json, Query};
8 use lemmy_api_common::{
9   comment::{GetComments, GetCommentsResponse},
10   context::LemmyContext,
11   utils::{check_private_instance, local_user_view_from_jwt_opt},
12 };
13 use lemmy_db_schema::{
14   source::{comment::Comment, community::Community, local_site::LocalSite},
15   traits::Crud,
16 };
17 use lemmy_db_views::comment_view::CommentQuery;
18 use lemmy_utils::error::{LemmyError, LemmyErrorExt, LemmyErrorType};
19
20 #[tracing::instrument(skip(context))]
21 pub async fn list_comments(
22   data: Query<GetComments>,
23   context: Data<LemmyContext>,
24 ) -> Result<Json<GetCommentsResponse>, LemmyError> {
25   let local_user_view = local_user_view_from_jwt_opt(data.auth.as_ref(), &context).await;
26   let local_site = LocalSite::read(&mut context.pool()).await?;
27   check_private_instance(&local_user_view, &local_site)?;
28
29   let community_id = if let Some(name) = &data.community_name {
30     Some(resolve_actor_identifier::<ApubCommunity, Community>(name, &context, &None, true).await?)
31       .map(|c| c.id)
32   } else {
33     data.community_id
34   };
35   let sort = data.sort;
36   let max_depth = data.max_depth;
37   let saved_only = data.saved_only;
38   let page = data.page;
39   let limit = data.limit;
40   let parent_id = data.parent_id;
41
42   let listing_type = listing_type_with_default(data.type_, &local_site, community_id)?;
43
44   // If a parent_id is given, fetch the comment to get the path
45   let parent_path = if let Some(parent_id) = parent_id {
46     Some(Comment::read(&mut context.pool(), parent_id).await?.path)
47   } else {
48     None
49   };
50
51   let parent_path_cloned = parent_path.clone();
52   let post_id = data.post_id;
53   let local_user = local_user_view.map(|l| l.local_user);
54   let comments = CommentQuery::builder()
55     .pool(&mut context.pool())
56     .listing_type(Some(listing_type))
57     .sort(sort)
58     .max_depth(max_depth)
59     .saved_only(saved_only)
60     .community_id(community_id)
61     .parent_path(parent_path_cloned)
62     .post_id(post_id)
63     .local_user(local_user.as_ref())
64     .page(page)
65     .limit(limit)
66     .build()
67     .list()
68     .await
69     .with_lemmy_type(LemmyErrorType::CouldntGetComments)?;
70
71   Ok(Json(GetCommentsResponse { comments }))
72 }