funquail/api/funkwhale_api/federation/webfinger.py

57 lines
1.7 KiB
Python
Raw Permalink Normal View History

2018-03-29 00:00:20 +02:00
from django import forms
from django.conf import settings
from funkwhale_api.common import session
2018-04-08 10:42:10 +02:00
2018-07-22 10:20:16 +00:00
from . import serializers
2018-06-09 15:36:16 +02:00
VALID_RESOURCE_TYPES = ["acct"]
2018-03-29 00:00:20 +02:00
def clean_resource(resource_string):
if not resource_string:
2018-06-09 15:36:16 +02:00
raise forms.ValidationError("Invalid resource string")
2018-03-29 00:00:20 +02:00
try:
2018-06-09 15:36:16 +02:00
resource_type, resource = resource_string.split(":", 1)
2018-03-29 00:00:20 +02:00
except ValueError:
2018-06-09 15:36:16 +02:00
raise forms.ValidationError("Missing webfinger resource type")
2018-03-29 00:00:20 +02:00
if resource_type not in VALID_RESOURCE_TYPES:
2018-06-09 15:36:16 +02:00
raise forms.ValidationError("Invalid webfinger resource type")
2018-03-29 00:00:20 +02:00
return resource_type, resource
2018-04-08 10:42:10 +02:00
def clean_acct(acct_string, ensure_local=True):
2018-03-29 00:00:20 +02:00
try:
2018-06-09 15:36:16 +02:00
username, hostname = acct_string.split("@")
2018-03-29 00:00:20 +02:00
except ValueError:
2018-06-09 15:36:16 +02:00
raise forms.ValidationError("Invalid format")
2018-03-29 00:00:20 +02:00
2018-04-08 10:42:10 +02:00
if ensure_local and hostname.lower() != settings.FEDERATION_HOSTNAME:
raise forms.ValidationError(f"Invalid hostname {hostname}")
2018-03-29 00:00:20 +02:00
return username, hostname
2018-04-08 10:42:10 +02:00
def get_resource(resource_string):
resource_type, resource = clean_resource(resource_string)
username, hostname = clean_acct(resource, ensure_local=False)
2018-06-09 15:36:16 +02:00
url = "https://{}/.well-known/webfinger?resource={}".format(
hostname, resource_string
)
2019-11-25 09:49:06 +01:00
response = session.get_session().get(url)
2018-04-08 10:42:10 +02:00
response.raise_for_status()
serializer = serializers.ActorWebfingerSerializer(data=response.json())
serializer.is_valid(raise_exception=True)
return serializer.validated_data
2020-03-02 17:23:03 +01:00
def get_ap_url(links):
for link in links:
if (
link.get("rel") == "self"
and link.get("type") == "application/activity+json"
):
return link["href"]