]> Untitled Git - lemmy.git/blob - crates/apub/src/activities/comment/mod.rs
Rewrite apub comment (de)serialization using structs (ref #1657)
[lemmy.git] / crates / apub / src / activities / comment / mod.rs
1 use crate::{fetcher::person::get_or_fetch_and_upsert_person, ActorType};
2 use activitystreams::{
3   base::BaseExt,
4   link::{LinkExt, Mention},
5 };
6 use anyhow::anyhow;
7 use itertools::Itertools;
8 use lemmy_api_common::{blocking, comment::CommentResponse, send_local_notifs, WebFingerResponse};
9 use lemmy_db_queries::{Crud, DbPool};
10 use lemmy_db_schema::{
11   source::{comment::Comment, community::Community, person::Person, post::Post},
12   CommentId,
13   LocalUserId,
14 };
15 use lemmy_db_views::comment_view::CommentView;
16 use lemmy_utils::{
17   request::{retry, RecvError},
18   settings::structs::Settings,
19   utils::{scrape_text_for_mentions, MentionData},
20   LemmyError,
21 };
22 use lemmy_websocket::{messages::SendComment, LemmyContext};
23 use log::debug;
24 use reqwest::Client;
25 use url::Url;
26
27 pub mod create;
28 pub mod update;
29
30 async fn get_notif_recipients(
31   actor: &Url,
32   comment: &Comment,
33   context: &LemmyContext,
34   request_counter: &mut i32,
35 ) -> Result<Vec<LocalUserId>, LemmyError> {
36   let post_id = comment.post_id;
37   let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
38   let actor = get_or_fetch_and_upsert_person(actor, context, request_counter).await?;
39
40   // Note:
41   // Although mentions could be gotten from the post tags (they are included there), or the ccs,
42   // Its much easier to scrape them from the comment body, since the API has to do that
43   // anyway.
44   // TODO: for compatibility with other projects, it would be much better to read this from cc or tags
45   let mentions = scrape_text_for_mentions(&comment.content);
46   send_local_notifs(mentions, comment.clone(), actor, post, context.pool(), true).await
47 }
48
49 // TODO: in many call sites we are setting an empty vec for recipient_ids, we should get the actual
50 //       recipient actors from somewhere
51 pub(crate) async fn send_websocket_message<
52   OP: ToString + Send + lemmy_websocket::OperationType + 'static,
53 >(
54   comment_id: CommentId,
55   recipient_ids: Vec<LocalUserId>,
56   op: OP,
57   context: &LemmyContext,
58 ) -> Result<(), LemmyError> {
59   // Refetch the view
60   let comment_view = blocking(context.pool(), move |conn| {
61     CommentView::read(conn, comment_id, None)
62   })
63   .await??;
64
65   let res = CommentResponse {
66     comment_view,
67     recipient_ids,
68     form_id: None,
69   };
70
71   context.chat_server().do_send(SendComment {
72     op,
73     comment: res,
74     websocket_id: None,
75   });
76
77   Ok(())
78 }
79
80 pub struct MentionsAndAddresses {
81   pub ccs: Vec<Url>,
82   pub inboxes: Vec<Url>,
83   pub tags: Vec<Mention>,
84 }
85
86 /// This takes a comment, and builds a list of to_addresses, inboxes,
87 /// and mention tags, so they know where to be sent to.
88 /// Addresses are the persons / addresses that go in the cc field.
89 pub async fn collect_non_local_mentions(
90   comment: &Comment,
91   community: &Community,
92   context: &LemmyContext,
93 ) -> Result<MentionsAndAddresses, LemmyError> {
94   let parent_creator = get_comment_parent_creator(context.pool(), comment).await?;
95   let mut addressed_ccs = vec![community.actor_id(), parent_creator.actor_id()];
96   // Note: dont include community inbox here, as we send to it separately with `send_to_community()`
97   let mut inboxes = vec![parent_creator.get_shared_inbox_or_inbox_url()];
98
99   // Add the mention tag
100   let mut tags = Vec::new();
101
102   // Get the person IDs for any mentions
103   let mentions = scrape_text_for_mentions(&comment.content)
104     .into_iter()
105     // Filter only the non-local ones
106     .filter(|m| !m.is_local())
107     .collect::<Vec<MentionData>>();
108
109   for mention in &mentions {
110     // TODO should it be fetching it every time?
111     if let Ok(actor_id) = fetch_webfinger_url(mention, context.client()).await {
112       debug!("mention actor_id: {}", actor_id);
113       addressed_ccs.push(actor_id.to_owned().to_string().parse()?);
114
115       let mention_person = get_or_fetch_and_upsert_person(&actor_id, context, &mut 0).await?;
116       inboxes.push(mention_person.get_shared_inbox_or_inbox_url());
117
118       let mut mention_tag = Mention::new();
119       mention_tag.set_href(actor_id).set_name(mention.full_name());
120       tags.push(mention_tag);
121     }
122   }
123
124   let inboxes = inboxes.into_iter().unique().collect();
125
126   Ok(MentionsAndAddresses {
127     ccs: addressed_ccs,
128     inboxes,
129     tags,
130   })
131 }
132
133 /// Returns the apub ID of the person this comment is responding to. Meaning, in case this is a
134 /// top-level comment, the creator of the post, otherwise the creator of the parent comment.
135 async fn get_comment_parent_creator(
136   pool: &DbPool,
137   comment: &Comment,
138 ) -> Result<Person, LemmyError> {
139   let parent_creator_id = if let Some(parent_comment_id) = comment.parent_id {
140     let parent_comment =
141       blocking(pool, move |conn| Comment::read(conn, parent_comment_id)).await??;
142     parent_comment.creator_id
143   } else {
144     let parent_post_id = comment.post_id;
145     let parent_post = blocking(pool, move |conn| Post::read(conn, parent_post_id)).await??;
146     parent_post.creator_id
147   };
148   Ok(blocking(pool, move |conn| Person::read(conn, parent_creator_id)).await??)
149 }
150
151 /// Turns a person id like `@name@example.com` into an apub ID, like `https://example.com/user/name`,
152 /// using webfinger.
153 async fn fetch_webfinger_url(mention: &MentionData, client: &Client) -> Result<Url, LemmyError> {
154   let fetch_url = format!(
155     "{}://{}/.well-known/webfinger?resource=acct:{}@{}",
156     Settings::get().get_protocol_string(),
157     mention.domain,
158     mention.name,
159     mention.domain
160   );
161   debug!("Fetching webfinger url: {}", &fetch_url);
162
163   let response = retry(|| client.get(&fetch_url).send()).await?;
164
165   let res: WebFingerResponse = response
166     .json()
167     .await
168     .map_err(|e| RecvError(e.to_string()))?;
169
170   let link = res
171     .links
172     .iter()
173     .find(|l| l.type_.eq(&Some("application/activity+json".to_string())))
174     .ok_or_else(|| anyhow!("No application/activity+json link found."))?;
175   link
176     .href
177     .to_owned()
178     .ok_or_else(|| anyhow!("No href found.").into())
179 }