microblog.pub/app/webfinger.py

156 lines
4.8 KiB
Python
Raw Normal View History

2022-12-15 15:14:24 -06:00
import xml.etree.ElementTree as ET
2022-06-22 13:11:22 -05:00
from typing import Any
from urllib.parse import urlparse
import httpx
from loguru import logger
2022-06-26 03:01:26 -05:00
from app import config
2022-07-15 13:50:27 -05:00
from app.utils.url import check_url
2022-06-22 13:11:22 -05:00
2022-12-15 15:14:24 -06:00
async def get_webfinger_via_host_meta(host: str) -> str | None:
resp: httpx.Response | None = None
is_404 = False
async with httpx.AsyncClient() as client:
for i, proto in enumerate({"http", "https"}):
try:
url = f"{proto}://{host}/.well-known/host-meta"
check_url(url)
resp = await client.get(
url,
headers={
"User-Agent": config.USER_AGENT,
},
follow_redirects=True,
)
resp.raise_for_status()
break
except httpx.HTTPStatusError as http_error:
logger.exception("HTTP error")
if http_error.response.status_code in [403, 404, 410]:
is_404 = True
continue
raise
except httpx.HTTPError:
logger.exception("req failed")
# If we tried https first and the domain is "http only"
if i == 0:
continue
break
if is_404:
return None
if resp:
tree = ET.fromstring(resp.text)
maybe_link = tree.find(
"./{http://docs.oasis-open.org/ns/xri/xrd-1.0}Link[@rel='lrdd']"
)
if maybe_link is not None:
return maybe_link.attrib.get("template")
return None
2022-06-29 17:28:07 -05:00
async def webfinger(
2022-06-22 13:11:22 -05:00
resource: str,
2022-12-15 15:14:24 -06:00
webfinger_url: str | None = None,
2022-06-22 13:11:22 -05:00
) -> dict[str, Any] | None: # noqa: C901
"""Mastodon-like WebFinger resolution to retrieve the activity stream Actor URL."""
2022-11-11 08:25:55 -06:00
resource = resource.strip()
2022-06-22 13:11:22 -05:00
logger.info(f"performing webfinger resolution for {resource}")
2022-12-15 15:14:24 -06:00
urls = []
host = None
if webfinger_url:
urls = [webfinger_url]
2022-06-22 13:11:22 -05:00
else:
2022-12-15 15:14:24 -06:00
if resource.startswith("http://"):
host = urlparse(resource).netloc
url = f"http://{host}/.well-known/webfinger"
elif resource.startswith("https://"):
host = urlparse(resource).netloc
url = f"https://{host}/.well-known/webfinger"
else:
protos = ["https", "http"]
_, host = resource.split("@", 1)
urls = [f"{proto}://{host}/.well-known/webfinger" for proto in protos]
if resource.startswith("acct:"):
resource = resource[5:]
if resource.startswith("@"):
resource = resource[1:]
resource = "acct:" + resource
2022-06-22 13:11:22 -05:00
is_404 = False
resp: httpx.Response | None = None
2022-06-29 17:28:07 -05:00
async with httpx.AsyncClient() as client:
2022-12-15 15:14:24 -06:00
for i, url in enumerate(urls):
2022-06-29 17:28:07 -05:00
try:
2022-07-15 13:50:27 -05:00
check_url(url)
2022-06-29 17:28:07 -05:00
resp = await client.get(
url,
params={"resource": resource},
headers={
"User-Agent": config.USER_AGENT,
},
2022-07-08 05:10:20 -05:00
follow_redirects=True,
2022-06-29 17:28:07 -05:00
)
2022-07-08 05:10:20 -05:00
resp.raise_for_status()
2022-06-29 17:28:07 -05:00
break
except httpx.HTTPStatusError as http_error:
logger.exception("HTTP error")
if http_error.response.status_code in [403, 404, 410]:
is_404 = True
continue
raise
except httpx.HTTPError:
logger.exception("req failed")
# If we tried https first and the domain is "http only"
if i == 0:
continue
break
2022-12-15 15:14:24 -06:00
2022-06-22 13:11:22 -05:00
if is_404:
2022-12-15 15:14:24 -06:00
if not webfinger_url and host:
if webfinger_url := (await get_webfinger_via_host_meta(host)):
return await webfinger(
resource,
webfinger_url=webfinger_url,
)
2022-06-22 13:11:22 -05:00
return None
if resp:
return resp.json()
else:
return None
2022-06-22 13:11:22 -05:00
2022-06-29 17:28:07 -05:00
async def get_remote_follow_template(resource: str) -> str | None:
data = await webfinger(resource)
2022-06-22 13:11:22 -05:00
if data is None:
return None
for link in data["links"]:
if link.get("rel") == "http://ostatus.org/schema/1.0/subscribe":
return link.get("template")
return None
2022-06-29 17:28:07 -05:00
async def get_actor_url(resource: str) -> str | None:
2022-06-22 13:11:22 -05:00
"""Mastodon-like WebFinger resolution to retrieve the activity stream Actor URL.
Returns:
the Actor URL or None if the resolution failed.
"""
2022-06-29 17:28:07 -05:00
data = await webfinger(resource)
2022-06-22 13:11:22 -05:00
if data is None:
return None
for link in data["links"]:
if (
link.get("rel") == "self"
and link.get("type") == "application/activity+json"
):
return link.get("href")
return None