1 use crate::{fetcher::person::get_or_fetch_and_upsert_person, ActorType};
4 link::{LinkExt, Mention},
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},
15 use lemmy_db_views::comment_view::CommentView;
17 request::{retry, RecvError},
18 settings::structs::Settings,
19 utils::{scrape_text_for_mentions, MentionData},
22 use lemmy_websocket::{messages::SendComment, LemmyContext};
30 async fn get_notif_recipients(
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?;
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
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
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,
54 comment_id: CommentId,
55 recipient_ids: Vec<LocalUserId>,
57 context: &LemmyContext,
58 ) -> Result<(), LemmyError> {
60 let comment_view = blocking(context.pool(), move |conn| {
61 CommentView::read(conn, comment_id, None)
65 let res = CommentResponse {
71 context.chat_server().do_send(SendComment {
80 pub struct MentionsAndAddresses {
82 pub inboxes: Vec<Url>,
83 pub tags: Vec<Mention>,
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(
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()];
99 // Add the mention tag
100 let mut tags = Vec::new();
102 // Get the person IDs for any mentions
103 let mentions = scrape_text_for_mentions(&comment.content)
105 // Filter only the non-local ones
106 .filter(|m| !m.is_local())
107 .collect::<Vec<MentionData>>();
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()?);
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());
118 let mut mention_tag = Mention::new();
119 mention_tag.set_href(actor_id).set_name(mention.full_name());
120 tags.push(mention_tag);
124 let inboxes = inboxes.into_iter().unique().collect();
126 Ok(MentionsAndAddresses {
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(
138 ) -> Result<Person, LemmyError> {
139 let parent_creator_id = if let Some(parent_comment_id) = comment.parent_id {
141 blocking(pool, move |conn| Comment::read(conn, parent_comment_id)).await??;
142 parent_comment.creator_id
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
148 Ok(blocking(pool, move |conn| Person::read(conn, parent_creator_id)).await??)
151 /// Turns a person id like `@name@example.com` into an apub ID, like `https://example.com/user/name`,
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(),
161 debug!("Fetching webfinger url: {}", &fetch_url);
163 let response = retry(|| client.get(&fetch_url).send()).await?;
165 let res: WebFingerResponse = response
168 .map_err(|e| RecvError(e.to_string()))?;
173 .find(|l| l.type_.eq(&Some("application/activity+json".to_string())))
174 .ok_or_else(|| anyhow!("No application/activity+json link found."))?;
178 .ok_or_else(|| anyhow!("No href found.").into())