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