]> Untitled Git - lemmy.git/blob - crates/routes/src/webfinger.rs
Merge pull request #2593 from LemmyNet/refactor-notifications
[lemmy.git] / crates / routes / src / webfinger.rs
1 use actix_web::{web, web::Query, HttpResponse};
2 use anyhow::Context;
3 use lemmy_api_common::context::LemmyContext;
4 use lemmy_db_schema::{
5   source::{community::Community, person::Person},
6   traits::ApubActor,
7 };
8 use lemmy_utils::{error::LemmyError, location_info, WebfingerLink, WebfingerResponse};
9 use serde::Deserialize;
10 use url::Url;
11
12 #[derive(Deserialize)]
13 struct Params {
14   resource: String,
15 }
16
17 pub fn config(cfg: &mut web::ServiceConfig) {
18   cfg.route(
19     ".well-known/webfinger",
20     web::get().to(get_webfinger_response),
21   );
22 }
23
24 /// Responds to webfinger requests of the following format. There isn't any real documentation for
25 /// this, but it described in this blog post:
26 /// https://mastodon.social/.well-known/webfinger?resource=acct:gargron@mastodon.social
27 ///
28 /// You can also view the webfinger response that Mastodon sends:
29 /// https://radical.town/.well-known/webfinger?resource=acct:felix@radical.town
30 async fn get_webfinger_response(
31   info: Query<Params>,
32   context: web::Data<LemmyContext>,
33 ) -> Result<HttpResponse, LemmyError> {
34   let name = context
35     .settings()
36     .webfinger_regex()
37     .captures(&info.resource)
38     .and_then(|c| c.get(1))
39     .context(location_info!())?
40     .as_str()
41     .to_string();
42
43   let name_ = name.clone();
44   let user_id: Option<Url> = Person::read_from_name(context.pool(), &name_, false)
45     .await
46     .ok()
47     .map(|c| c.actor_id.into());
48   let community_id: Option<Url> = Community::read_from_name(context.pool(), &name, false)
49     .await
50     .ok()
51     .map(|c| c.actor_id.into());
52
53   // Mastodon seems to prioritize the last webfinger item in case of duplicates. Put
54   // community last so that it gets prioritized. For Lemmy the order doesnt matter.
55   let links = vec![
56     webfinger_link_for_actor(user_id),
57     webfinger_link_for_actor(community_id),
58   ]
59   .into_iter()
60   .flatten()
61   .collect();
62
63   let json = WebfingerResponse {
64     subject: info.resource.clone(),
65     links,
66   };
67
68   Ok(HttpResponse::Ok().json(json))
69 }
70
71 fn webfinger_link_for_actor(url: Option<Url>) -> Vec<WebfingerLink> {
72   if let Some(url) = url {
73     vec![
74       WebfingerLink {
75         rel: Some("http://webfinger.net/rel/profile-page".to_string()),
76         kind: Some("text/html".to_string()),
77         href: Some(url.clone()),
78       },
79       WebfingerLink {
80         rel: Some("self".to_string()),
81         kind: Some("application/activity+json".to_string()),
82         href: Some(url),
83       },
84     ]
85   } else {
86     vec![]
87   }
88 }