2022-11-26 03:33:46 +01:00
|
|
|
from functools import cached_property, partial
|
2022-12-05 18:38:37 +01:00
|
|
|
from typing import Literal
|
2022-11-06 21:48:04 +01:00
|
|
|
from urllib.parse import urlparse
|
2022-11-05 21:17:27 +01:00
|
|
|
|
2022-11-06 00:51:54 +01:00
|
|
|
import httpx
|
2022-11-05 21:17:27 +01:00
|
|
|
import urlman
|
2022-11-07 05:30:07 +01:00
|
|
|
from asgiref.sync import async_to_sync, sync_to_async
|
2022-11-21 16:31:14 +01:00
|
|
|
from django.db import IntegrityError, models
|
2022-11-18 03:31:00 +01:00
|
|
|
from django.template.defaultfilters import linebreaks_filter
|
2022-11-05 21:17:27 +01:00
|
|
|
from django.utils import timezone
|
2022-11-26 03:33:46 +01:00
|
|
|
from django.utils.functional import lazy
|
2022-11-06 00:51:54 +01:00
|
|
|
|
2022-11-20 20:32:49 +01:00
|
|
|
from core.exceptions import ActorMismatchError
|
2022-11-28 00:43:20 +01:00
|
|
|
from core.html import sanitize_post, strip_html
|
2022-12-11 08:25:48 +01:00
|
|
|
from core.ld import canonicalise, format_ld_date, get_list, media_type_from_filename
|
2022-11-26 03:33:46 +01:00
|
|
|
from core.models import Config
|
2022-11-21 02:32:55 +01:00
|
|
|
from core.signatures import HttpSignature, RsaKeys
|
2022-11-17 16:21:42 +01:00
|
|
|
from core.uploads import upload_namer
|
2022-12-12 15:32:35 +01:00
|
|
|
from core.uris import AutoAbsoluteUrl, RelativeAbsoluteUrl, StaticAbsoluteUrl
|
2022-11-10 06:29:33 +01:00
|
|
|
from stator.models import State, StateField, StateGraph, StatorModel
|
2022-11-06 21:48:04 +01:00
|
|
|
from users.models.domain import Domain
|
2022-11-21 02:29:19 +01:00
|
|
|
from users.models.system_actor import SystemActor
|
2022-11-05 21:17:27 +01:00
|
|
|
|
|
|
|
|
2022-11-10 06:29:33 +01:00
|
|
|
class IdentityStates(StateGraph):
|
2022-11-28 01:05:31 +01:00
|
|
|
"""
|
|
|
|
There are only two states in a cycle.
|
|
|
|
Identities sit in "updated" for up to system.identity_max_age, and then
|
|
|
|
go back to "outdated" for refetching.
|
|
|
|
"""
|
|
|
|
|
|
|
|
outdated = State(try_interval=3600, force_initial=True)
|
2022-12-04 18:46:59 +01:00
|
|
|
updated = State(try_interval=86400 * 7, attempt_immediately=False)
|
2022-11-10 06:29:33 +01:00
|
|
|
|
2022-11-10 07:48:31 +01:00
|
|
|
outdated.transitions_to(updated)
|
2022-11-28 01:05:31 +01:00
|
|
|
updated.transitions_to(outdated)
|
2022-11-10 07:48:31 +01:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
async def handle_outdated(cls, identity: "Identity"):
|
|
|
|
# Local identities never need fetching
|
2022-11-10 06:29:33 +01:00
|
|
|
if identity.local:
|
2022-11-28 01:05:31 +01:00
|
|
|
return cls.updated
|
2022-11-10 07:48:31 +01:00
|
|
|
# Run the actor fetch and progress to updated if it succeeds
|
|
|
|
if await identity.fetch_actor():
|
2022-11-28 01:05:31 +01:00
|
|
|
return cls.updated
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
async def handle_updated(cls, instance: "Identity"):
|
|
|
|
if instance.state_age > Config.system.identity_max_age:
|
|
|
|
return cls.outdated
|
2022-11-10 06:29:33 +01:00
|
|
|
|
|
|
|
|
|
|
|
class Identity(StatorModel):
|
2022-11-05 21:17:27 +01:00
|
|
|
"""
|
|
|
|
Represents both local and remote Fediverse identities (actors)
|
|
|
|
"""
|
|
|
|
|
2022-12-17 03:42:48 +01:00
|
|
|
class Restriction(models.IntegerChoices):
|
|
|
|
none = 0
|
|
|
|
limited = 1
|
|
|
|
blocked = 2
|
|
|
|
|
2022-11-06 21:48:04 +01:00
|
|
|
# The Actor URI is essentially also a PK - we keep the default numeric
|
|
|
|
# one around as well for making nice URLs etc.
|
2022-11-07 05:30:07 +01:00
|
|
|
actor_uri = models.CharField(max_length=500, unique=True)
|
2022-11-06 21:48:04 +01:00
|
|
|
|
2022-11-10 06:29:33 +01:00
|
|
|
state = StateField(IdentityStates)
|
|
|
|
|
2022-11-06 21:48:04 +01:00
|
|
|
local = models.BooleanField()
|
2022-11-12 06:02:43 +01:00
|
|
|
users = models.ManyToManyField(
|
|
|
|
"users.User",
|
|
|
|
related_name="identities",
|
|
|
|
blank=True,
|
|
|
|
)
|
2022-11-06 21:48:04 +01:00
|
|
|
|
|
|
|
username = models.CharField(max_length=500, blank=True, null=True)
|
|
|
|
# Must be a display domain if present
|
|
|
|
domain = models.ForeignKey(
|
|
|
|
"users.Domain",
|
|
|
|
blank=True,
|
|
|
|
null=True,
|
|
|
|
on_delete=models.PROTECT,
|
2022-11-17 05:12:28 +01:00
|
|
|
related_name="identities",
|
2022-11-06 21:48:04 +01:00
|
|
|
)
|
|
|
|
|
2022-11-05 21:17:27 +01:00
|
|
|
name = models.CharField(max_length=500, blank=True, null=True)
|
2022-11-06 00:51:54 +01:00
|
|
|
summary = models.TextField(blank=True, null=True)
|
2022-11-06 21:48:04 +01:00
|
|
|
manually_approves_followers = models.BooleanField(blank=True, null=True)
|
2022-11-26 02:32:45 +01:00
|
|
|
discoverable = models.BooleanField(default=True)
|
2022-11-06 00:51:54 +01:00
|
|
|
|
|
|
|
profile_uri = models.CharField(max_length=500, blank=True, null=True)
|
|
|
|
inbox_uri = models.CharField(max_length=500, blank=True, null=True)
|
2022-11-28 00:43:20 +01:00
|
|
|
shared_inbox_uri = models.CharField(max_length=500, blank=True, null=True)
|
2022-11-06 00:51:54 +01:00
|
|
|
outbox_uri = models.CharField(max_length=500, blank=True, null=True)
|
|
|
|
icon_uri = models.CharField(max_length=500, blank=True, null=True)
|
|
|
|
image_uri = models.CharField(max_length=500, blank=True, null=True)
|
2022-11-28 00:43:20 +01:00
|
|
|
followers_uri = models.CharField(max_length=500, blank=True, null=True)
|
|
|
|
following_uri = models.CharField(max_length=500, blank=True, null=True)
|
2022-11-05 21:17:27 +01:00
|
|
|
|
2022-11-06 00:51:54 +01:00
|
|
|
icon = models.ImageField(
|
|
|
|
upload_to=partial(upload_namer, "profile_images"), blank=True, null=True
|
|
|
|
)
|
|
|
|
image = models.ImageField(
|
|
|
|
upload_to=partial(upload_namer, "background_images"), blank=True, null=True
|
2022-11-05 21:17:27 +01:00
|
|
|
)
|
|
|
|
|
2022-11-28 00:43:20 +01:00
|
|
|
# Should be a list of {"name":..., "value":...} dicts
|
|
|
|
metadata = models.JSONField(blank=True, null=True)
|
|
|
|
|
|
|
|
# Should be a list of object URIs (we don't want a full M2M here)
|
|
|
|
pinned = models.JSONField(blank=True, null=True)
|
|
|
|
|
2022-12-17 03:42:48 +01:00
|
|
|
# Admin-only moderation fields
|
|
|
|
sensitive = models.BooleanField(default=False)
|
|
|
|
restriction = models.IntegerField(
|
|
|
|
choices=Restriction.choices, default=Restriction.none
|
|
|
|
)
|
|
|
|
admin_notes = models.TextField(null=True, blank=True)
|
|
|
|
|
2022-11-05 21:17:27 +01:00
|
|
|
private_key = models.TextField(null=True, blank=True)
|
|
|
|
public_key = models.TextField(null=True, blank=True)
|
2022-11-12 23:10:15 +01:00
|
|
|
public_key_id = models.TextField(null=True, blank=True)
|
2022-11-05 21:17:27 +01:00
|
|
|
|
|
|
|
created = models.DateTimeField(auto_now_add=True)
|
|
|
|
updated = models.DateTimeField(auto_now=True)
|
2022-11-06 00:51:54 +01:00
|
|
|
fetched = models.DateTimeField(null=True, blank=True)
|
2022-11-05 21:17:27 +01:00
|
|
|
deleted = models.DateTimeField(null=True, blank=True)
|
|
|
|
|
2022-11-07 05:30:07 +01:00
|
|
|
### Model attributes ###
|
|
|
|
|
2022-11-06 07:07:38 +01:00
|
|
|
class Meta:
|
|
|
|
verbose_name_plural = "identities"
|
2022-11-06 21:48:04 +01:00
|
|
|
unique_together = [("username", "domain")]
|
2022-11-06 07:07:38 +01:00
|
|
|
|
2022-11-07 05:30:07 +01:00
|
|
|
class urls(urlman.Urls):
|
|
|
|
view = "/@{self.username}@{self.domain_id}/"
|
|
|
|
action = "{view}action/"
|
|
|
|
activate = "{view}activate/"
|
2022-12-17 03:42:48 +01:00
|
|
|
admin = "/admin/identities/"
|
|
|
|
admin_edit = "{admin}{self.pk}/"
|
2022-11-07 05:30:07 +01:00
|
|
|
|
|
|
|
def get_scheme(self, url):
|
|
|
|
return "https"
|
|
|
|
|
|
|
|
def get_hostname(self, url):
|
|
|
|
return self.instance.domain.uri_domain
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
if self.username and self.domain_id:
|
|
|
|
return self.handle
|
|
|
|
return self.actor_uri
|
|
|
|
|
2022-11-22 05:18:13 +01:00
|
|
|
def absolute_profile_uri(self):
|
2022-11-16 02:30:30 +01:00
|
|
|
"""
|
2022-11-22 05:18:13 +01:00
|
|
|
Returns a profile URI that is always absolute, for sending out to
|
|
|
|
other servers.
|
2022-11-16 02:30:30 +01:00
|
|
|
"""
|
|
|
|
if self.local:
|
|
|
|
return f"https://{self.domain.uri_domain}/@{self.username}/"
|
|
|
|
else:
|
2022-11-22 05:18:13 +01:00
|
|
|
return self.profile_uri
|
2022-11-16 02:30:30 +01:00
|
|
|
|
2022-12-12 15:22:11 +01:00
|
|
|
def local_icon_url(self) -> RelativeAbsoluteUrl:
|
2022-11-17 16:21:42 +01:00
|
|
|
"""
|
2022-12-12 15:22:11 +01:00
|
|
|
Returns an icon for use by us, with fallbacks to a placeholder
|
2022-11-17 16:21:42 +01:00
|
|
|
"""
|
|
|
|
if self.icon:
|
2022-12-12 15:22:11 +01:00
|
|
|
return RelativeAbsoluteUrl(self.icon.url)
|
2022-11-17 16:21:42 +01:00
|
|
|
elif self.icon_uri:
|
2022-12-12 15:22:11 +01:00
|
|
|
return AutoAbsoluteUrl(f"/proxy/identity_icon/{self.pk}/")
|
2022-11-17 16:21:42 +01:00
|
|
|
else:
|
2022-12-12 15:32:35 +01:00
|
|
|
return StaticAbsoluteUrl("img/unknown-icon-128.png")
|
2022-11-17 16:21:42 +01:00
|
|
|
|
2022-12-12 15:22:11 +01:00
|
|
|
def local_image_url(self) -> RelativeAbsoluteUrl | None:
|
2022-11-17 16:21:42 +01:00
|
|
|
"""
|
|
|
|
Returns a background image for us, returning None if there isn't one
|
|
|
|
"""
|
|
|
|
if self.image:
|
2022-12-12 15:22:11 +01:00
|
|
|
return RelativeAbsoluteUrl(self.image.url)
|
2022-11-17 16:21:42 +01:00
|
|
|
elif self.image_uri:
|
2022-12-12 15:22:11 +01:00
|
|
|
return AutoAbsoluteUrl(f"/proxy/identity_image/{self.pk}/")
|
|
|
|
return None
|
2022-11-17 16:21:42 +01:00
|
|
|
|
2022-11-18 03:31:00 +01:00
|
|
|
@property
|
|
|
|
def safe_summary(self):
|
2022-12-15 08:50:54 +01:00
|
|
|
from activities.templatetags.emoji_tags import imageify_emojis
|
|
|
|
|
|
|
|
return imageify_emojis(sanitize_post(self.summary), self.domain)
|
2022-11-18 03:31:00 +01:00
|
|
|
|
2022-11-28 00:43:20 +01:00
|
|
|
@property
|
|
|
|
def safe_metadata(self):
|
2022-12-15 08:50:54 +01:00
|
|
|
from activities.templatetags.emoji_tags import imageify_emojis
|
|
|
|
|
2022-11-28 00:43:20 +01:00
|
|
|
if not self.metadata:
|
|
|
|
return []
|
|
|
|
return [
|
|
|
|
{
|
|
|
|
"name": data["name"],
|
2022-12-15 08:50:54 +01:00
|
|
|
"value": imageify_emojis(strip_html(data["value"]), self.domain),
|
2022-11-28 00:43:20 +01:00
|
|
|
}
|
|
|
|
for data in self.metadata
|
|
|
|
]
|
|
|
|
|
2022-11-07 05:30:07 +01:00
|
|
|
### Alternate constructors/fetchers ###
|
|
|
|
|
2022-11-06 05:49:25 +01:00
|
|
|
@classmethod
|
2022-11-07 08:19:00 +01:00
|
|
|
def by_username_and_domain(cls, username, domain, fetch=False, local=False):
|
|
|
|
if username.startswith("@"):
|
|
|
|
raise ValueError("Username must not start with @")
|
2022-11-17 07:10:55 +01:00
|
|
|
username = username.lower()
|
2022-11-25 00:27:21 +01:00
|
|
|
domain = domain.lower()
|
2022-11-06 05:49:25 +01:00
|
|
|
try:
|
2022-11-06 21:48:04 +01:00
|
|
|
if local:
|
2022-12-17 03:42:48 +01:00
|
|
|
return cls.objects.get(
|
|
|
|
username=username,
|
|
|
|
domain_id=domain,
|
|
|
|
local=True,
|
|
|
|
)
|
2022-11-06 21:48:04 +01:00
|
|
|
else:
|
2022-12-17 03:42:48 +01:00
|
|
|
return cls.objects.get(
|
|
|
|
username=username,
|
|
|
|
domain_id=domain,
|
|
|
|
)
|
2022-11-06 05:49:25 +01:00
|
|
|
except cls.DoesNotExist:
|
2022-11-06 21:48:04 +01:00
|
|
|
if fetch and not local:
|
2022-11-07 08:19:00 +01:00
|
|
|
actor_uri, handle = async_to_sync(cls.fetch_webfinger)(
|
|
|
|
f"{username}@{domain}"
|
|
|
|
)
|
2022-11-19 21:38:25 +01:00
|
|
|
if handle is None:
|
|
|
|
return None
|
2022-11-21 01:17:53 +01:00
|
|
|
# See if this actually does match an existing actor
|
|
|
|
try:
|
|
|
|
return cls.objects.get(actor_uri=actor_uri)
|
|
|
|
except cls.DoesNotExist:
|
|
|
|
pass
|
|
|
|
# OK, make one
|
2022-11-07 05:30:07 +01:00
|
|
|
username, domain = handle.split("@")
|
|
|
|
domain = Domain.get_remote_domain(domain)
|
|
|
|
return cls.objects.create(
|
|
|
|
actor_uri=actor_uri,
|
|
|
|
username=username,
|
|
|
|
domain_id=domain,
|
|
|
|
local=False,
|
|
|
|
)
|
2022-11-06 05:49:25 +01:00
|
|
|
return None
|
|
|
|
|
2022-11-06 07:07:38 +01:00
|
|
|
@classmethod
|
2022-11-20 22:20:28 +01:00
|
|
|
def by_actor_uri(cls, uri, create=False, transient=False) -> "Identity":
|
2022-11-06 07:07:38 +01:00
|
|
|
try:
|
2022-11-06 21:48:04 +01:00
|
|
|
return cls.objects.get(actor_uri=uri)
|
2022-11-06 07:07:38 +01:00
|
|
|
except cls.DoesNotExist:
|
2022-11-12 06:02:43 +01:00
|
|
|
if create:
|
2022-11-20 22:20:28 +01:00
|
|
|
if transient:
|
|
|
|
# Some code (like inbox fetching) doesn't need this saved
|
|
|
|
# to the DB until the fetch succeeds
|
|
|
|
return cls(actor_uri=uri, local=False)
|
|
|
|
else:
|
|
|
|
return cls.objects.create(actor_uri=uri, local=False)
|
2022-11-12 06:02:43 +01:00
|
|
|
else:
|
2022-11-17 06:23:32 +01:00
|
|
|
raise cls.DoesNotExist(f"No identity found with actor_uri {uri}")
|
2022-11-06 22:14:08 +01:00
|
|
|
|
2022-11-07 05:30:07 +01:00
|
|
|
### Dynamic properties ###
|
|
|
|
|
|
|
|
@property
|
|
|
|
def name_or_handle(self):
|
|
|
|
return self.name or self.handle
|
|
|
|
|
2022-12-15 08:50:54 +01:00
|
|
|
@cached_property
|
|
|
|
def html_name_or_handle(self):
|
|
|
|
"""
|
|
|
|
Return the name_or_handle with any HTML substitutions made
|
|
|
|
"""
|
|
|
|
from activities.templatetags.emoji_tags import imageify_emojis
|
|
|
|
|
|
|
|
return imageify_emojis(self.name_or_handle, self.domain)
|
|
|
|
|
2022-11-05 21:17:27 +01:00
|
|
|
@property
|
2022-11-06 21:48:04 +01:00
|
|
|
def handle(self):
|
2022-12-05 05:13:33 +01:00
|
|
|
if self.username is None:
|
|
|
|
return "(unknown user)"
|
2022-11-07 05:30:07 +01:00
|
|
|
if self.domain_id:
|
|
|
|
return f"{self.username}@{self.domain_id}"
|
2022-12-05 05:13:33 +01:00
|
|
|
return f"{self.username}@(unknown server)"
|
2022-11-05 21:17:27 +01:00
|
|
|
|
2022-11-06 05:49:25 +01:00
|
|
|
@property
|
|
|
|
def data_age(self) -> float:
|
|
|
|
"""
|
|
|
|
How old our copy of this data is, in seconds
|
|
|
|
"""
|
|
|
|
if self.local:
|
|
|
|
return 0
|
|
|
|
if self.fetched is None:
|
|
|
|
return 10000000000
|
|
|
|
return (timezone.now() - self.fetched).total_seconds()
|
|
|
|
|
2022-11-07 05:30:07 +01:00
|
|
|
@property
|
|
|
|
def outdated(self) -> bool:
|
|
|
|
# TODO: Setting
|
|
|
|
return self.data_age > 60 * 24 * 24
|
|
|
|
|
2022-12-17 03:42:48 +01:00
|
|
|
@property
|
|
|
|
def blocked(self) -> bool:
|
|
|
|
return self.restriction == self.Restriction.blocked
|
|
|
|
|
|
|
|
@property
|
|
|
|
def limited(self) -> bool:
|
|
|
|
return self.restriction == self.Restriction.limited
|
|
|
|
|
2022-11-17 06:23:32 +01:00
|
|
|
### ActivityPub (outbound) ###
|
2022-11-16 02:30:30 +01:00
|
|
|
|
|
|
|
def to_ap(self):
|
|
|
|
response = {
|
|
|
|
"id": self.actor_uri,
|
|
|
|
"type": "Person",
|
|
|
|
"inbox": self.actor_uri + "inbox/",
|
|
|
|
"preferredUsername": self.username,
|
|
|
|
"publicKey": {
|
|
|
|
"id": self.public_key_id,
|
|
|
|
"owner": self.actor_uri,
|
|
|
|
"publicKeyPem": self.public_key,
|
|
|
|
},
|
|
|
|
"published": self.created.strftime("%Y-%m-%dT%H:%M:%SZ"),
|
2022-11-22 05:18:13 +01:00
|
|
|
"url": self.absolute_profile_uri(),
|
2022-11-26 02:32:45 +01:00
|
|
|
"http://joinmastodon.org/ns#discoverable": self.discoverable,
|
2022-11-16 02:30:30 +01:00
|
|
|
}
|
|
|
|
if self.name:
|
|
|
|
response["name"] = self.name
|
|
|
|
if self.summary:
|
2022-11-18 03:31:00 +01:00
|
|
|
response["summary"] = str(linebreaks_filter(self.summary))
|
|
|
|
if self.icon:
|
|
|
|
response["icon"] = {
|
|
|
|
"type": "Image",
|
|
|
|
"mediaType": media_type_from_filename(self.icon.name),
|
|
|
|
"url": self.icon.url,
|
|
|
|
}
|
|
|
|
if self.image:
|
|
|
|
response["image"] = {
|
|
|
|
"type": "Image",
|
|
|
|
"mediaType": media_type_from_filename(self.image.name),
|
|
|
|
"url": self.image.url,
|
|
|
|
}
|
2022-12-10 21:24:49 +01:00
|
|
|
if self.local:
|
|
|
|
response["endpoints"] = {
|
|
|
|
"sharedInbox": f"https://{self.domain.uri_domain}/inbox/",
|
|
|
|
}
|
2022-11-16 02:30:30 +01:00
|
|
|
return response
|
|
|
|
|
2022-12-15 08:50:54 +01:00
|
|
|
def to_ap_tag(self):
|
|
|
|
"""
|
|
|
|
Return this Identity as an ActivityPub Tag
|
|
|
|
http://joinmastodon.org/ns#Mention
|
|
|
|
"""
|
|
|
|
return {
|
|
|
|
"href": self.actor_uri,
|
|
|
|
"name": "@" + self.handle,
|
|
|
|
"type": "Mention",
|
|
|
|
}
|
|
|
|
|
2022-11-17 06:23:32 +01:00
|
|
|
### ActivityPub (inbound) ###
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def handle_update_ap(cls, data):
|
|
|
|
"""
|
|
|
|
Takes an incoming update.person message and just forces us to add it
|
|
|
|
to our fetch queue (don't want to bother with two load paths right now)
|
|
|
|
"""
|
|
|
|
# Find by actor
|
|
|
|
try:
|
|
|
|
actor = cls.by_actor_uri(data["actor"])
|
|
|
|
actor.transition_perform(IdentityStates.outdated)
|
|
|
|
except cls.DoesNotExist:
|
|
|
|
pass
|
|
|
|
|
2022-11-20 20:32:49 +01:00
|
|
|
@classmethod
|
|
|
|
def handle_delete_ap(cls, data):
|
|
|
|
"""
|
|
|
|
Takes an incoming update.person message and just forces us to add it
|
|
|
|
to our fetch queue (don't want to bother with two load paths right now)
|
|
|
|
"""
|
|
|
|
# Assert that the actor matches the object
|
|
|
|
if data["actor"] != data["object"]:
|
|
|
|
raise ActorMismatchError(
|
|
|
|
f"Actor {data['actor']} trying to delete identity {data['object']}"
|
|
|
|
)
|
|
|
|
# Find by actor
|
|
|
|
try:
|
|
|
|
actor = cls.by_actor_uri(data["actor"])
|
|
|
|
actor.delete()
|
|
|
|
except cls.DoesNotExist:
|
|
|
|
pass
|
|
|
|
|
2022-11-07 05:30:07 +01:00
|
|
|
### Actor/Webfinger fetching ###
|
2022-11-05 21:17:27 +01:00
|
|
|
|
2022-11-06 21:48:04 +01:00
|
|
|
@classmethod
|
2022-12-05 18:38:37 +01:00
|
|
|
async def fetch_webfinger(cls, handle: str) -> tuple[str | None, str | None]:
|
2022-11-06 21:48:04 +01:00
|
|
|
"""
|
|
|
|
Given a username@domain handle, returns a tuple of
|
|
|
|
(actor uri, canonical handle) or None, None if it does not resolve.
|
|
|
|
"""
|
2022-11-25 00:27:21 +01:00
|
|
|
domain = handle.split("@")[1].lower()
|
2022-11-20 20:02:38 +01:00
|
|
|
try:
|
2022-11-21 02:29:19 +01:00
|
|
|
response = await SystemActor().signed_request(
|
|
|
|
method="get",
|
|
|
|
uri=f"https://{domain}/.well-known/webfinger?resource=acct:{handle}",
|
|
|
|
)
|
2022-11-21 16:57:00 +01:00
|
|
|
except (httpx.RequestError, httpx.ConnectError):
|
2022-11-20 20:02:38 +01:00
|
|
|
return None, None
|
2022-11-21 02:45:28 +01:00
|
|
|
if response.status_code in [404, 410]:
|
2022-11-21 02:29:19 +01:00
|
|
|
return None, None
|
|
|
|
if response.status_code >= 500:
|
2022-11-06 21:48:04 +01:00
|
|
|
return None, None
|
2022-11-21 02:45:28 +01:00
|
|
|
if response.status_code >= 400:
|
|
|
|
raise ValueError(
|
|
|
|
f"Client error fetching webfinger: {response.status_code}",
|
|
|
|
response.content,
|
|
|
|
)
|
2022-11-06 00:51:54 +01:00
|
|
|
data = response.json()
|
2022-11-06 21:48:04 +01:00
|
|
|
if data["subject"].startswith("acct:"):
|
|
|
|
data["subject"] = data["subject"][5:]
|
2022-11-06 00:51:54 +01:00
|
|
|
for link in data["links"]:
|
|
|
|
if (
|
|
|
|
link.get("type") == "application/activity+json"
|
|
|
|
and link.get("rel") == "self"
|
|
|
|
):
|
2022-11-06 21:48:04 +01:00
|
|
|
return link["href"], data["subject"]
|
|
|
|
return None, None
|
2022-11-06 00:51:54 +01:00
|
|
|
|
|
|
|
async def fetch_actor(self) -> bool:
|
2022-11-06 21:48:04 +01:00
|
|
|
"""
|
|
|
|
Fetches the user's actor information, as well as their domain from
|
|
|
|
webfinger if it's available.
|
|
|
|
"""
|
|
|
|
if self.local:
|
|
|
|
raise ValueError("Cannot fetch local identities")
|
2022-11-21 02:29:19 +01:00
|
|
|
try:
|
|
|
|
response = await SystemActor().signed_request(
|
|
|
|
method="get",
|
|
|
|
uri=self.actor_uri,
|
2022-11-06 07:07:38 +01:00
|
|
|
)
|
2022-11-21 16:57:00 +01:00
|
|
|
except (httpx.ConnectError, httpx.RequestError):
|
2022-11-21 02:29:19 +01:00
|
|
|
return False
|
|
|
|
if response.status_code == 410:
|
|
|
|
# Their account got deleted, so let's do the same.
|
|
|
|
if self.pk:
|
|
|
|
await Identity.objects.filter(pk=self.pk).adelete()
|
|
|
|
return False
|
|
|
|
if response.status_code == 404:
|
|
|
|
# We don't trust this as much as 410 Gone, but skip for now
|
|
|
|
return False
|
|
|
|
if response.status_code >= 500:
|
|
|
|
return False
|
2022-11-21 02:45:28 +01:00
|
|
|
if response.status_code >= 400:
|
|
|
|
raise ValueError(
|
|
|
|
f"Client error fetching actor: {response.status_code}", response.content
|
|
|
|
)
|
2022-11-21 02:29:19 +01:00
|
|
|
document = canonicalise(response.json(), include_security=True)
|
|
|
|
self.name = document.get("name")
|
|
|
|
self.profile_uri = document.get("url")
|
|
|
|
self.inbox_uri = document.get("inbox")
|
|
|
|
self.outbox_uri = document.get("outbox")
|
2022-11-28 00:43:20 +01:00
|
|
|
self.followers_uri = document.get("followers")
|
|
|
|
self.following_uri = document.get("following")
|
|
|
|
self.shared_inbox_uri = document.get("endpoints", {}).get("sharedInbox")
|
2022-11-21 02:29:19 +01:00
|
|
|
self.summary = document.get("summary")
|
|
|
|
self.username = document.get("preferredUsername")
|
|
|
|
if self.username and "@value" in self.username:
|
|
|
|
self.username = self.username["@value"]
|
|
|
|
if self.username:
|
|
|
|
self.username = self.username.lower()
|
2022-12-17 00:38:52 +01:00
|
|
|
self.manually_approves_followers = document.get("manuallyApprovesFollowers")
|
2022-11-21 02:29:19 +01:00
|
|
|
self.public_key = document.get("publicKey", {}).get("publicKeyPem")
|
|
|
|
self.public_key_id = document.get("publicKey", {}).get("id")
|
|
|
|
self.icon_uri = document.get("icon", {}).get("url")
|
|
|
|
self.image_uri = document.get("image", {}).get("url")
|
2022-11-26 02:32:45 +01:00
|
|
|
self.discoverable = document.get(
|
|
|
|
"http://joinmastodon.org/ns#discoverable", True
|
|
|
|
)
|
2022-11-28 00:43:20 +01:00
|
|
|
# Profile links/metadata
|
|
|
|
self.metadata = []
|
|
|
|
for attachment in get_list(document, "attachment"):
|
|
|
|
if (
|
|
|
|
attachment["type"] == "http://schema.org#PropertyValue"
|
|
|
|
and "name" in attachment
|
|
|
|
and "http://schema.org#value" in attachment
|
|
|
|
):
|
|
|
|
self.metadata.append(
|
|
|
|
{
|
|
|
|
"name": attachment.get("name"),
|
|
|
|
"value": strip_html(attachment.get("http://schema.org#value")),
|
|
|
|
}
|
|
|
|
)
|
2022-11-06 21:48:04 +01:00
|
|
|
# Now go do webfinger with that info to see if we can get a canonical domain
|
|
|
|
actor_url_parts = urlparse(self.actor_uri)
|
|
|
|
get_domain = sync_to_async(Domain.get_remote_domain)
|
|
|
|
if self.username:
|
|
|
|
webfinger_actor, webfinger_handle = await self.fetch_webfinger(
|
|
|
|
f"{self.username}@{actor_url_parts.hostname}"
|
|
|
|
)
|
|
|
|
if webfinger_handle:
|
|
|
|
webfinger_username, webfinger_domain = webfinger_handle.split("@")
|
2022-11-25 00:27:21 +01:00
|
|
|
self.username = webfinger_username.lower()
|
2022-11-06 21:48:04 +01:00
|
|
|
self.domain = await get_domain(webfinger_domain)
|
|
|
|
else:
|
|
|
|
self.domain = await get_domain(actor_url_parts.hostname)
|
|
|
|
else:
|
|
|
|
self.domain = await get_domain(actor_url_parts.hostname)
|
|
|
|
self.fetched = timezone.now()
|
2022-11-21 16:31:14 +01:00
|
|
|
try:
|
|
|
|
await sync_to_async(self.save)()
|
|
|
|
except IntegrityError as e:
|
|
|
|
# See if we can fetch a PK and save there
|
|
|
|
if self.pk is None:
|
|
|
|
try:
|
|
|
|
other_row = await Identity.objects.aget(actor_uri=self.actor_uri)
|
|
|
|
except Identity.DoesNotExist:
|
|
|
|
raise ValueError(
|
|
|
|
f"Could not save Identity at end of actor fetch: {e}"
|
|
|
|
)
|
2022-12-05 18:38:37 +01:00
|
|
|
self.pk: int | None = other_row.pk
|
2022-11-21 16:31:14 +01:00
|
|
|
await sync_to_async(self.save)()
|
2022-11-06 07:07:38 +01:00
|
|
|
return True
|
|
|
|
|
2022-12-11 08:25:48 +01:00
|
|
|
### Mastodon Client API ###
|
|
|
|
|
|
|
|
def to_mastodon_json(self):
|
2022-12-15 08:50:54 +01:00
|
|
|
from activities.models import Emoji
|
|
|
|
|
2022-12-12 15:22:11 +01:00
|
|
|
header_image = self.local_image_url()
|
2022-12-15 08:50:54 +01:00
|
|
|
metadata_value_text = (
|
|
|
|
" ".join([m["value"] for m in self.metadata]) if self.metadata else ""
|
|
|
|
)
|
|
|
|
emojis = Emoji.emojis_from_content(
|
|
|
|
f"{self.name} {self.summary} {metadata_value_text}", self.domain
|
|
|
|
)
|
2022-12-11 08:25:48 +01:00
|
|
|
return {
|
|
|
|
"id": self.pk,
|
2022-12-16 02:59:04 +01:00
|
|
|
"username": self.username or "",
|
2022-12-11 08:25:48 +01:00
|
|
|
"acct": self.username if self.local else self.handle,
|
2022-12-16 03:10:50 +01:00
|
|
|
"url": self.absolute_profile_uri() or "",
|
2022-12-16 02:59:04 +01:00
|
|
|
"display_name": self.name or "",
|
2022-12-11 08:25:48 +01:00
|
|
|
"note": self.summary or "",
|
2022-12-12 15:22:11 +01:00
|
|
|
"avatar": self.local_icon_url().absolute,
|
|
|
|
"avatar_static": self.local_icon_url().absolute,
|
|
|
|
"header": header_image.absolute if header_image else None,
|
|
|
|
"header_static": header_image.absolute if header_image else None,
|
2022-12-11 08:25:48 +01:00
|
|
|
"locked": False,
|
|
|
|
"fields": (
|
|
|
|
[
|
|
|
|
{"name": m["name"], "value": m["value"], "verified_at": None}
|
|
|
|
for m in self.metadata
|
|
|
|
]
|
|
|
|
if self.metadata
|
|
|
|
else []
|
|
|
|
),
|
2022-12-15 08:50:54 +01:00
|
|
|
"emojis": [emoji.to_mastodon_json() for emoji in emojis],
|
2022-12-11 08:25:48 +01:00
|
|
|
"bot": False,
|
|
|
|
"group": False,
|
|
|
|
"discoverable": self.discoverable,
|
|
|
|
"suspended": False,
|
|
|
|
"limited": False,
|
|
|
|
"created_at": format_ld_date(
|
|
|
|
self.created.replace(hour=0, minute=0, second=0, microsecond=0)
|
|
|
|
),
|
|
|
|
"last_status_at": None, # TODO: populate
|
|
|
|
"statuses_count": self.posts.count(),
|
|
|
|
"followers_count": self.inbound_follows.count(),
|
|
|
|
"following_count": self.outbound_follows.count(),
|
|
|
|
}
|
|
|
|
|
2022-11-07 05:30:07 +01:00
|
|
|
### Cryptography ###
|
|
|
|
|
2022-11-21 02:32:55 +01:00
|
|
|
async def signed_request(
|
|
|
|
self,
|
|
|
|
method: Literal["get", "post"],
|
|
|
|
uri: str,
|
2022-12-05 18:38:37 +01:00
|
|
|
body: dict | None = None,
|
2022-11-21 02:32:55 +01:00
|
|
|
):
|
|
|
|
"""
|
|
|
|
Performs a signed request on behalf of the System Actor.
|
|
|
|
"""
|
|
|
|
return await HttpSignature.signed_request(
|
|
|
|
method=method,
|
|
|
|
uri=uri,
|
|
|
|
body=body,
|
|
|
|
private_key=self.private_key,
|
|
|
|
key_id=self.public_key_id,
|
|
|
|
)
|
|
|
|
|
2022-11-07 05:30:07 +01:00
|
|
|
def generate_keypair(self):
|
|
|
|
if not self.local:
|
|
|
|
raise ValueError("Cannot generate keypair for remote user")
|
2022-11-21 02:29:19 +01:00
|
|
|
self.private_key, self.public_key = RsaKeys.generate_keypair()
|
2022-11-17 06:23:32 +01:00
|
|
|
self.public_key_id = self.actor_uri + "#main-key"
|
2022-11-07 05:30:07 +01:00
|
|
|
self.save()
|
2022-11-26 03:33:46 +01:00
|
|
|
|
|
|
|
### Config ###
|
|
|
|
|
|
|
|
@cached_property
|
|
|
|
def config_identity(self) -> Config.IdentityOptions:
|
|
|
|
return Config.load_identity(self)
|
|
|
|
|
|
|
|
def lazy_config_value(self, key: str):
|
|
|
|
"""
|
|
|
|
Lazily load a config value for this Identity
|
|
|
|
"""
|
|
|
|
if key not in Config.IdentityOptions.__fields__:
|
|
|
|
raise KeyError(f"Undefined IdentityOption for {key}")
|
|
|
|
return lazy(lambda: getattr(self.config_identity, key))
|