]> Untitled Git - lemmy.git/blob - crates/apub/src/activities/comment/mod.rs
Rewrite delete activities (#1699)
[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, 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   LocalUserId,
13 };
14 use lemmy_utils::{
15   request::{retry, RecvError},
16   settings::structs::Settings,
17   utils::{scrape_text_for_mentions, MentionData},
18   LemmyError,
19 };
20 use lemmy_websocket::LemmyContext;
21 use log::debug;
22 use reqwest::Client;
23 use url::Url;
24
25 pub mod create_or_update;
26
27 async fn get_notif_recipients(
28   actor: &Url,
29   comment: &Comment,
30   context: &LemmyContext,
31   request_counter: &mut i32,
32 ) -> Result<Vec<LocalUserId>, LemmyError> {
33   let post_id = comment.post_id;
34   let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
35   let actor = get_or_fetch_and_upsert_person(actor, context, request_counter).await?;
36
37   // Note:
38   // Although mentions could be gotten from the post tags (they are included there), or the ccs,
39   // Its much easier to scrape them from the comment body, since the API has to do that
40   // anyway.
41   // TODO: for compatibility with other projects, it would be much better to read this from cc or tags
42   let mentions = scrape_text_for_mentions(&comment.content);
43   send_local_notifs(mentions, comment.clone(), actor, post, context.pool(), true).await
44 }
45
46 pub struct MentionsAndAddresses {
47   pub ccs: Vec<Url>,
48   pub inboxes: Vec<Url>,
49   pub tags: Vec<Mention>,
50 }
51
52 /// This takes a comment, and builds a list of to_addresses, inboxes,
53 /// and mention tags, so they know where to be sent to.
54 /// Addresses are the persons / addresses that go in the cc field.
55 pub async fn collect_non_local_mentions(
56   comment: &Comment,
57   community: &Community,
58   context: &LemmyContext,
59 ) -> Result<MentionsAndAddresses, LemmyError> {
60   let parent_creator = get_comment_parent_creator(context.pool(), comment).await?;
61   let mut addressed_ccs = vec![community.actor_id(), parent_creator.actor_id()];
62   // Note: dont include community inbox here, as we send to it separately with `send_to_community()`
63   let mut inboxes = vec![parent_creator.get_shared_inbox_or_inbox_url()];
64
65   // Add the mention tag
66   let mut tags = Vec::new();
67
68   // Get the person IDs for any mentions
69   let mentions = scrape_text_for_mentions(&comment.content)
70     .into_iter()
71     // Filter only the non-local ones
72     .filter(|m| !m.is_local())
73     .collect::<Vec<MentionData>>();
74
75   for mention in &mentions {
76     // TODO should it be fetching it every time?
77     if let Ok(actor_id) = fetch_webfinger_url(mention, context.client()).await {
78       debug!("mention actor_id: {}", actor_id);
79       addressed_ccs.push(actor_id.to_owned().to_string().parse()?);
80
81       let mention_person = get_or_fetch_and_upsert_person(&actor_id, context, &mut 0).await?;
82       inboxes.push(mention_person.get_shared_inbox_or_inbox_url());
83
84       let mut mention_tag = Mention::new();
85       mention_tag.set_href(actor_id).set_name(mention.full_name());
86       tags.push(mention_tag);
87     }
88   }
89
90   let inboxes = inboxes.into_iter().unique().collect();
91
92   Ok(MentionsAndAddresses {
93     ccs: addressed_ccs,
94     inboxes,
95     tags,
96   })
97 }
98
99 /// Returns the apub ID of the person this comment is responding to. Meaning, in case this is a
100 /// top-level comment, the creator of the post, otherwise the creator of the parent comment.
101 async fn get_comment_parent_creator(
102   pool: &DbPool,
103   comment: &Comment,
104 ) -> Result<Person, LemmyError> {
105   let parent_creator_id = if let Some(parent_comment_id) = comment.parent_id {
106     let parent_comment =
107       blocking(pool, move |conn| Comment::read(conn, parent_comment_id)).await??;
108     parent_comment.creator_id
109   } else {
110     let parent_post_id = comment.post_id;
111     let parent_post = blocking(pool, move |conn| Post::read(conn, parent_post_id)).await??;
112     parent_post.creator_id
113   };
114   Ok(blocking(pool, move |conn| Person::read(conn, parent_creator_id)).await??)
115 }
116
117 /// Turns a person id like `@name@example.com` into an apub ID, like `https://example.com/user/name`,
118 /// using webfinger.
119 async fn fetch_webfinger_url(mention: &MentionData, client: &Client) -> Result<Url, LemmyError> {
120   let fetch_url = format!(
121     "{}://{}/.well-known/webfinger?resource=acct:{}@{}",
122     Settings::get().get_protocol_string(),
123     mention.domain,
124     mention.name,
125     mention.domain
126   );
127   debug!("Fetching webfinger url: {}", &fetch_url);
128
129   let response = retry(|| client.get(&fetch_url).send()).await?;
130
131   let res: WebFingerResponse = response
132     .json()
133     .await
134     .map_err(|e| RecvError(e.to_string()))?;
135
136   let link = res
137     .links
138     .iter()
139     .find(|l| l.type_.eq(&Some("application/activity+json".to_string())))
140     .ok_or_else(|| anyhow!("No application/activity+json link found."))?;
141   link
142     .href
143     .to_owned()
144     .ok_or_else(|| anyhow!("No href found.").into())
145 }