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