2023-01-13 17:53:02 +00:00
|
|
|
import ssl
|
2022-11-26 02:33:46 +00:00
|
|
|
from functools import cached_property, partial
|
2023-07-22 17:46:35 +00:00
|
|
|
from typing import Literal, Optional
|
2022-11-06 20:48:04 +00:00
|
|
|
from urllib.parse import urlparse
|
2022-11-05 20:17:27 +00:00
|
|
|
|
2022-11-05 23:51:54 +00:00
|
|
|
import httpx
|
2022-11-05 20:17:27 +00:00
|
|
|
import urlman
|
2022-12-24 04:35:17 +00:00
|
|
|
from django.conf import settings
|
2022-11-21 15:31:14 +00:00
|
|
|
from django.db import IntegrityError, models
|
2022-11-05 20:17:27 +00:00
|
|
|
from django.utils import timezone
|
2022-11-26 02:33:46 +00:00
|
|
|
from django.utils.functional import lazy
|
2022-12-24 04:35:17 +00:00
|
|
|
from lxml import etree
|
2022-11-05 23:51:54 +00:00
|
|
|
|
2023-01-19 20:14:55 +00:00
|
|
|
from core.exceptions import ActorMismatchError, capture_message
|
2023-01-30 00:46:22 +00:00
|
|
|
from core.html import ContentRenderer, FediverseHtmlParser
|
2022-12-17 22:42:29 +00:00
|
|
|
from core.ld import (
|
|
|
|
canonicalise,
|
|
|
|
format_ld_date,
|
|
|
|
get_first_image_url,
|
|
|
|
get_list,
|
|
|
|
media_type_from_filename,
|
|
|
|
)
|
2022-11-26 02:33:46 +00:00
|
|
|
from core.models import Config
|
2022-11-21 01:32:55 +00:00
|
|
|
from core.signatures import HttpSignature, RsaKeys
|
2023-01-09 01:05:29 +00:00
|
|
|
from core.snowflake import Snowflake
|
2022-11-17 15:21:42 +00:00
|
|
|
from core.uploads import upload_namer
|
2022-12-28 18:57:54 +00:00
|
|
|
from core.uris import (
|
|
|
|
AutoAbsoluteUrl,
|
|
|
|
ProxyAbsoluteUrl,
|
|
|
|
RelativeAbsoluteUrl,
|
|
|
|
StaticAbsoluteUrl,
|
|
|
|
)
|
2022-11-10 05:29:33 +00:00
|
|
|
from stator.models import State, StateField, StateGraph, StatorModel
|
2022-11-06 20:48:04 +00:00
|
|
|
from users.models.domain import Domain
|
2022-11-21 01:29:19 +00:00
|
|
|
from users.models.system_actor import SystemActor
|
2022-11-05 20:17:27 +00:00
|
|
|
|
|
|
|
|
2022-11-10 05:29:33 +00:00
|
|
|
class IdentityStates(StateGraph):
|
2022-11-28 00:05:31 +00:00
|
|
|
"""
|
|
|
|
Identities sit in "updated" for up to system.identity_max_age, and then
|
|
|
|
go back to "outdated" for refetching.
|
2022-12-21 17:13:39 +00:00
|
|
|
|
|
|
|
When a local identity is "edited" or "deleted", it will fanout the change to
|
|
|
|
all followers and transition to "updated"
|
2022-11-28 00:05:31 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
outdated = State(try_interval=3600, force_initial=True)
|
2023-07-07 21:52:12 +00:00
|
|
|
updated = State(try_interval=86400 * 15, attempt_immediately=False)
|
2022-11-10 05:29:33 +00:00
|
|
|
|
2022-12-21 17:13:39 +00:00
|
|
|
edited = State(try_interval=300, attempt_immediately=True)
|
|
|
|
deleted = State(try_interval=300, attempt_immediately=True)
|
2023-01-08 19:43:32 +00:00
|
|
|
deleted_fanned_out = State(delete_after=86400 * 7)
|
2022-12-21 17:13:39 +00:00
|
|
|
|
2023-08-08 14:54:59 +00:00
|
|
|
moved = State(try_interval=300, attempt_immediately=True)
|
|
|
|
moved_fanned_out = State(externally_progressed=True)
|
|
|
|
|
2022-12-21 17:13:39 +00:00
|
|
|
deleted.transitions_to(deleted_fanned_out)
|
|
|
|
|
|
|
|
edited.transitions_to(updated)
|
|
|
|
updated.transitions_to(edited)
|
|
|
|
edited.transitions_to(deleted)
|
|
|
|
|
2022-11-10 06:48:31 +00:00
|
|
|
outdated.transitions_to(updated)
|
2022-11-28 00:05:31 +00:00
|
|
|
updated.transitions_to(outdated)
|
2022-11-10 06:48:31 +00:00
|
|
|
|
2023-08-08 14:54:59 +00:00
|
|
|
moved.transitions_to(moved_fanned_out)
|
|
|
|
|
2022-12-21 20:56:52 +00:00
|
|
|
@classmethod
|
|
|
|
def group_deleted(cls):
|
|
|
|
return [cls.deleted, cls.deleted_fanned_out]
|
|
|
|
|
2022-12-21 17:13:39 +00:00
|
|
|
@classmethod
|
2023-07-17 06:37:47 +00:00
|
|
|
def targets_fan_out(cls, identity: "Identity", type_: str) -> None:
|
2022-12-21 17:13:39 +00:00
|
|
|
from activities.models import FanOut
|
|
|
|
from users.models import Follow
|
|
|
|
|
|
|
|
# Fan out to each target
|
|
|
|
shared_inboxes = set()
|
2023-07-17 06:37:47 +00:00
|
|
|
for follower in Follow.objects.select_related("source", "target").filter(
|
2022-12-21 17:13:39 +00:00
|
|
|
target=identity
|
|
|
|
):
|
|
|
|
# Dedupe shared_inbox_uri
|
|
|
|
shared_uri = follower.source.shared_inbox_uri
|
|
|
|
if shared_uri and shared_uri in shared_inboxes:
|
|
|
|
continue
|
|
|
|
|
2023-07-17 06:37:47 +00:00
|
|
|
FanOut.objects.create(
|
2022-12-21 17:13:39 +00:00
|
|
|
identity=follower.source,
|
|
|
|
type=type_,
|
|
|
|
subject_identity=identity,
|
|
|
|
)
|
|
|
|
shared_inboxes.add(shared_uri)
|
|
|
|
|
|
|
|
@classmethod
|
2023-07-17 06:37:47 +00:00
|
|
|
def handle_edited(cls, instance: "Identity"):
|
2022-12-21 17:13:39 +00:00
|
|
|
from activities.models import FanOut
|
|
|
|
|
|
|
|
if not instance.local:
|
|
|
|
return cls.updated
|
|
|
|
|
2023-07-17 06:37:47 +00:00
|
|
|
cls.targets_fan_out(instance, FanOut.Types.identity_edited)
|
2022-12-21 17:13:39 +00:00
|
|
|
return cls.updated
|
|
|
|
|
2023-08-08 14:54:59 +00:00
|
|
|
@classmethod
|
|
|
|
def handle_moved(cls, instance: "Identity"):
|
|
|
|
from activities.models import FanOut
|
|
|
|
|
|
|
|
if not instance.local:
|
|
|
|
return cls.updated
|
|
|
|
|
|
|
|
cls.targets_fan_out(instance, FanOut.Types.identity_moved)
|
|
|
|
return cls.moved_fanned_out
|
|
|
|
|
2022-12-21 17:13:39 +00:00
|
|
|
@classmethod
|
2023-07-17 06:37:47 +00:00
|
|
|
def handle_deleted(cls, instance: "Identity"):
|
2022-12-21 17:13:39 +00:00
|
|
|
from activities.models import FanOut
|
|
|
|
|
|
|
|
if not instance.local:
|
|
|
|
return cls.updated
|
|
|
|
|
2023-07-17 06:37:47 +00:00
|
|
|
cls.targets_fan_out(instance, FanOut.Types.identity_deleted)
|
2022-12-21 17:13:39 +00:00
|
|
|
return cls.deleted_fanned_out
|
|
|
|
|
2022-11-10 06:48:31 +00:00
|
|
|
@classmethod
|
2023-07-17 06:37:47 +00:00
|
|
|
def handle_outdated(cls, identity: "Identity"):
|
2022-11-10 06:48:31 +00:00
|
|
|
# Local identities never need fetching
|
2022-11-10 05:29:33 +00:00
|
|
|
if identity.local:
|
2022-11-28 00:05:31 +00:00
|
|
|
return cls.updated
|
2022-11-10 06:48:31 +00:00
|
|
|
# Run the actor fetch and progress to updated if it succeeds
|
2023-07-17 06:37:47 +00:00
|
|
|
if identity.fetch_actor():
|
2022-11-28 00:05:31 +00:00
|
|
|
return cls.updated
|
|
|
|
|
|
|
|
@classmethod
|
2023-07-17 06:18:00 +00:00
|
|
|
def handle_updated(cls, instance: "Identity"):
|
2022-11-28 00:05:31 +00:00
|
|
|
if instance.state_age > Config.system.identity_max_age:
|
|
|
|
return cls.outdated
|
2022-11-10 05:29:33 +00:00
|
|
|
|
|
|
|
|
2022-12-21 17:13:39 +00:00
|
|
|
class IdentityQuerySet(models.QuerySet):
|
|
|
|
def not_deleted(self):
|
2022-12-21 20:56:52 +00:00
|
|
|
query = self.exclude(state__in=IdentityStates.group_deleted())
|
2022-12-21 17:13:39 +00:00
|
|
|
return query
|
|
|
|
|
|
|
|
|
|
|
|
class IdentityManager(models.Manager):
|
|
|
|
def get_queryset(self):
|
|
|
|
return IdentityQuerySet(self.model, using=self._db)
|
|
|
|
|
|
|
|
def not_deleted(self):
|
|
|
|
return self.get_queryset().not_deleted()
|
|
|
|
|
|
|
|
|
2022-11-10 05:29:33 +00:00
|
|
|
class Identity(StatorModel):
|
2022-11-05 20:17:27 +00:00
|
|
|
"""
|
|
|
|
Represents both local and remote Fediverse identities (actors)
|
|
|
|
"""
|
|
|
|
|
2022-12-17 02:42:48 +00:00
|
|
|
class Restriction(models.IntegerChoices):
|
|
|
|
none = 0
|
|
|
|
limited = 1
|
|
|
|
blocked = 2
|
|
|
|
|
2022-12-20 06:52:33 +00:00
|
|
|
ACTOR_TYPES = ["person", "service", "application", "group", "organization"]
|
|
|
|
|
2023-01-09 01:05:29 +00:00
|
|
|
id = models.BigIntegerField(primary_key=True, default=Snowflake.generate_identity)
|
|
|
|
|
2022-11-06 20:48:04 +00: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 04:30:07 +00:00
|
|
|
actor_uri = models.CharField(max_length=500, unique=True)
|
2022-11-06 20:48:04 +00:00
|
|
|
|
2022-11-10 05:29:33 +00:00
|
|
|
state = StateField(IdentityStates)
|
|
|
|
|
2023-07-07 21:14:06 +00:00
|
|
|
local = models.BooleanField(db_index=True)
|
2022-11-12 05:02:43 +00:00
|
|
|
users = models.ManyToManyField(
|
|
|
|
"users.User",
|
|
|
|
related_name="identities",
|
|
|
|
blank=True,
|
|
|
|
)
|
2022-11-06 20:48:04 +00: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 04:12:28 +00:00
|
|
|
related_name="identities",
|
2022-11-06 20:48:04 +00:00
|
|
|
)
|
|
|
|
|
2022-11-05 20:17:27 +00:00
|
|
|
name = models.CharField(max_length=500, blank=True, null=True)
|
2022-11-05 23:51:54 +00:00
|
|
|
summary = models.TextField(blank=True, null=True)
|
2022-11-06 20:48:04 +00:00
|
|
|
manually_approves_followers = models.BooleanField(blank=True, null=True)
|
2022-11-26 01:32:45 +00:00
|
|
|
discoverable = models.BooleanField(default=True)
|
2022-11-05 23:51:54 +00: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-27 23:43:20 +00:00
|
|
|
shared_inbox_uri = models.CharField(max_length=500, blank=True, null=True)
|
2022-11-05 23:51:54 +00: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-27 23:43:20 +00:00
|
|
|
followers_uri = models.CharField(max_length=500, blank=True, null=True)
|
|
|
|
following_uri = models.CharField(max_length=500, blank=True, null=True)
|
2023-05-13 16:01:27 +00:00
|
|
|
featured_collection_uri = models.CharField(max_length=500, blank=True, null=True)
|
2022-12-20 06:52:33 +00:00
|
|
|
actor_type = models.CharField(max_length=100, default="person")
|
2022-11-05 20:17:27 +00:00
|
|
|
|
2022-11-05 23:51:54 +00: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 20:17:27 +00:00
|
|
|
)
|
|
|
|
|
2022-11-27 23:43:20 +00: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)
|
|
|
|
|
2023-07-22 17:46:35 +00:00
|
|
|
# A list of other actor URIs - if this account was moved, should contain
|
|
|
|
# the one URI it was moved to.
|
|
|
|
aliases = models.JSONField(blank=True, null=True)
|
|
|
|
|
2022-12-17 02:42:48 +00:00
|
|
|
# Admin-only moderation fields
|
|
|
|
sensitive = models.BooleanField(default=False)
|
|
|
|
restriction = models.IntegerField(
|
2023-01-01 17:58:13 +00:00
|
|
|
choices=Restriction.choices, default=Restriction.none, db_index=True
|
2022-12-17 02:42:48 +00:00
|
|
|
)
|
|
|
|
admin_notes = models.TextField(null=True, blank=True)
|
|
|
|
|
2022-11-05 20:17:27 +00:00
|
|
|
private_key = models.TextField(null=True, blank=True)
|
|
|
|
public_key = models.TextField(null=True, blank=True)
|
2022-11-12 22:10:15 +00:00
|
|
|
public_key_id = models.TextField(null=True, blank=True)
|
2022-11-05 20:17:27 +00:00
|
|
|
|
|
|
|
created = models.DateTimeField(auto_now_add=True)
|
|
|
|
updated = models.DateTimeField(auto_now=True)
|
2022-11-05 23:51:54 +00:00
|
|
|
fetched = models.DateTimeField(null=True, blank=True)
|
2022-11-05 20:17:27 +00:00
|
|
|
deleted = models.DateTimeField(null=True, blank=True)
|
|
|
|
|
2022-12-21 17:13:39 +00:00
|
|
|
objects = IdentityManager()
|
|
|
|
|
2022-11-07 04:30:07 +00:00
|
|
|
### Model attributes ###
|
|
|
|
|
2022-11-06 06:07:38 +00:00
|
|
|
class Meta:
|
|
|
|
verbose_name_plural = "identities"
|
2022-11-06 20:48:04 +00:00
|
|
|
unique_together = [("username", "domain")]
|
2023-07-07 21:14:06 +00:00
|
|
|
indexes: list = [] # We need this so Stator can add its own
|
2022-11-06 06:07:38 +00:00
|
|
|
|
2022-11-07 04:30:07 +00:00
|
|
|
class urls(urlman.Urls):
|
|
|
|
view = "/@{self.username}@{self.domain_id}/"
|
2023-05-13 17:07:57 +00:00
|
|
|
replies = "{view}replies/"
|
2023-05-04 04:42:37 +00:00
|
|
|
settings = "{view}settings/"
|
2022-11-07 04:30:07 +00:00
|
|
|
action = "{view}action/"
|
2022-12-21 20:36:10 +00:00
|
|
|
followers = "{view}followers/"
|
|
|
|
following = "{view}following/"
|
2023-05-04 04:42:37 +00:00
|
|
|
search = "{view}search/"
|
2022-11-07 04:30:07 +00:00
|
|
|
activate = "{view}activate/"
|
2022-12-17 02:42:48 +00:00
|
|
|
admin = "/admin/identities/"
|
|
|
|
admin_edit = "{admin}{self.pk}/"
|
2022-12-30 08:01:03 +00:00
|
|
|
djadmin_edit = "/djadmin/users/identity/{self.id}/change/"
|
2022-11-07 04:30:07 +00: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 04:18:13 +00:00
|
|
|
def absolute_profile_uri(self):
|
2022-11-16 01:30:30 +00:00
|
|
|
"""
|
2022-11-22 04:18:13 +00:00
|
|
|
Returns a profile URI that is always absolute, for sending out to
|
|
|
|
other servers.
|
2022-11-16 01:30:30 +00:00
|
|
|
"""
|
|
|
|
if self.local:
|
|
|
|
return f"https://{self.domain.uri_domain}/@{self.username}/"
|
|
|
|
else:
|
2022-11-22 04:18:13 +00:00
|
|
|
return self.profile_uri
|
2022-11-16 01:30:30 +00:00
|
|
|
|
2022-12-22 20:51:39 +00:00
|
|
|
def all_absolute_profile_uris(self) -> list[str]:
|
|
|
|
"""
|
|
|
|
Returns alist of profile URIs that are always absolute. For local addresses,
|
|
|
|
this includes the short and long form URIs.
|
|
|
|
"""
|
|
|
|
if not self.local:
|
|
|
|
return [self.profile_uri]
|
|
|
|
return [
|
|
|
|
f"https://{self.domain.uri_domain}/@{self.username}/",
|
|
|
|
f"https://{self.domain.uri_domain}/@{self.username}@{self.domain_id}/",
|
|
|
|
]
|
|
|
|
|
2022-12-12 14:22:11 +00:00
|
|
|
def local_icon_url(self) -> RelativeAbsoluteUrl:
|
2022-11-17 15:21:42 +00:00
|
|
|
"""
|
2022-12-12 14:22:11 +00:00
|
|
|
Returns an icon for use by us, with fallbacks to a placeholder
|
2022-11-17 15:21:42 +00:00
|
|
|
"""
|
|
|
|
if self.icon:
|
2022-12-12 14:22:11 +00:00
|
|
|
return RelativeAbsoluteUrl(self.icon.url)
|
2022-11-17 15:21:42 +00:00
|
|
|
elif self.icon_uri:
|
2022-12-28 18:57:54 +00:00
|
|
|
return ProxyAbsoluteUrl(
|
|
|
|
f"/proxy/identity_icon/{self.pk}/",
|
|
|
|
remote_url=self.icon_uri,
|
2022-12-28 18:39:40 +00:00
|
|
|
)
|
2022-11-17 15:21:42 +00:00
|
|
|
else:
|
2022-12-12 14:32:35 +00:00
|
|
|
return StaticAbsoluteUrl("img/unknown-icon-128.png")
|
2022-11-17 15:21:42 +00:00
|
|
|
|
2022-12-12 14:22:11 +00:00
|
|
|
def local_image_url(self) -> RelativeAbsoluteUrl | None:
|
2022-11-17 15:21:42 +00:00
|
|
|
"""
|
|
|
|
Returns a background image for us, returning None if there isn't one
|
|
|
|
"""
|
|
|
|
if self.image:
|
2022-12-24 04:57:50 +00:00
|
|
|
return AutoAbsoluteUrl(self.image.url)
|
2022-11-17 15:21:42 +00:00
|
|
|
elif self.image_uri:
|
2022-12-28 18:57:54 +00:00
|
|
|
return ProxyAbsoluteUrl(
|
|
|
|
f"/proxy/identity_image/{self.pk}/",
|
|
|
|
remote_url=self.image_uri,
|
2022-12-28 18:39:40 +00:00
|
|
|
)
|
2022-12-12 14:22:11 +00:00
|
|
|
return None
|
2022-11-17 15:21:42 +00:00
|
|
|
|
2022-11-18 02:31:00 +00:00
|
|
|
@property
|
|
|
|
def safe_summary(self):
|
2022-12-22 01:10:25 +00:00
|
|
|
return ContentRenderer(local=True).render_identity_summary(self.summary, self)
|
2022-11-18 02:31:00 +00:00
|
|
|
|
2022-11-27 23:43:20 +00:00
|
|
|
@property
|
|
|
|
def safe_metadata(self):
|
2022-12-20 11:39:45 +00:00
|
|
|
renderer = ContentRenderer(local=True)
|
2022-12-15 07:50:54 +00:00
|
|
|
|
2022-11-27 23:43:20 +00:00
|
|
|
if not self.metadata:
|
|
|
|
return []
|
|
|
|
return [
|
|
|
|
{
|
2022-12-22 01:10:25 +00:00
|
|
|
"name": renderer.render_identity_data(data["name"], self, strip=True),
|
|
|
|
"value": renderer.render_identity_data(data["value"], self, strip=True),
|
2022-11-27 23:43:20 +00:00
|
|
|
}
|
|
|
|
for data in self.metadata
|
|
|
|
]
|
|
|
|
|
2023-07-22 16:38:22 +00:00
|
|
|
def ensure_uris(self):
|
|
|
|
"""
|
|
|
|
Ensures that local identities have all the URIs populated on their fields
|
|
|
|
(this lets us add new ones easily)
|
|
|
|
"""
|
|
|
|
if self.local:
|
|
|
|
self.inbox_uri = self.actor_uri + "inbox/"
|
|
|
|
self.outbox_uri = self.actor_uri + "outbox/"
|
|
|
|
self.featured_collection_uri = self.actor_uri + "collections/featured/"
|
|
|
|
self.followers_uri = self.actor_uri + "followers/"
|
|
|
|
self.following_uri = self.actor_uri + "following/"
|
|
|
|
self.shared_inbox_uri = f"https://{self.domain.uri_domain}/inbox/"
|
|
|
|
|
2023-07-22 17:46:35 +00:00
|
|
|
def add_alias(self, actor_uri: str):
|
|
|
|
self.aliases = (self.aliases or []) + [actor_uri]
|
|
|
|
self.save()
|
|
|
|
|
|
|
|
def remove_alias(self, actor_uri: str):
|
|
|
|
self.aliases = [x for x in (self.aliases or []) if x != actor_uri]
|
|
|
|
self.save()
|
|
|
|
|
2022-11-07 04:30:07 +00:00
|
|
|
### Alternate constructors/fetchers ###
|
|
|
|
|
2023-07-22 17:46:35 +00:00
|
|
|
@classmethod
|
|
|
|
def by_handle(cls, handle, fetch: bool = False) -> Optional["Identity"]:
|
|
|
|
username, domain = handle.lstrip("@").split("@", 1)
|
|
|
|
return cls.by_username_and_domain(username=username, domain=domain, fetch=fetch)
|
|
|
|
|
2022-11-06 04:49:25 +00:00
|
|
|
@classmethod
|
2022-12-28 17:52:39 +00:00
|
|
|
def by_username_and_domain(
|
|
|
|
cls,
|
|
|
|
username: str,
|
|
|
|
domain: str | Domain,
|
|
|
|
fetch: bool = False,
|
|
|
|
local: bool = False,
|
2023-07-22 17:46:35 +00:00
|
|
|
) -> Optional["Identity"]:
|
2022-12-28 17:52:39 +00:00
|
|
|
"""
|
|
|
|
Get an Identity by username and domain.
|
|
|
|
|
|
|
|
When fetch is True, a failed lookup will do a webfinger lookup to attempt to do
|
|
|
|
a lookup by actor_uri, creating an Identity record if one does not exist. When
|
|
|
|
local is True, lookups will be restricted to local domains.
|
|
|
|
|
|
|
|
If domain is a Domain, domain.local is used instead of passsed local.
|
|
|
|
|
|
|
|
"""
|
2022-11-07 07:19:00 +00:00
|
|
|
if username.startswith("@"):
|
|
|
|
raise ValueError("Username must not start with @")
|
2022-12-28 17:52:39 +00:00
|
|
|
|
|
|
|
domain_instance = None
|
|
|
|
|
|
|
|
if isinstance(domain, Domain):
|
|
|
|
domain_instance = domain
|
|
|
|
local = domain.local
|
|
|
|
domain = domain.domain
|
|
|
|
else:
|
|
|
|
domain = domain.lower()
|
2022-11-06 04:49:25 +00:00
|
|
|
try:
|
2022-11-06 20:48:04 +00:00
|
|
|
if local:
|
2022-12-17 02:42:48 +00:00
|
|
|
return cls.objects.get(
|
2022-12-21 21:39:56 +00:00
|
|
|
username__iexact=username,
|
2022-12-17 02:42:48 +00:00
|
|
|
domain_id=domain,
|
|
|
|
local=True,
|
|
|
|
)
|
2022-11-06 20:48:04 +00:00
|
|
|
else:
|
2022-12-17 02:42:48 +00:00
|
|
|
return cls.objects.get(
|
2022-12-21 21:39:56 +00:00
|
|
|
username__iexact=username,
|
2022-12-17 02:42:48 +00:00
|
|
|
domain_id=domain,
|
|
|
|
)
|
2022-11-06 04:49:25 +00:00
|
|
|
except cls.DoesNotExist:
|
2022-11-06 20:48:04 +00:00
|
|
|
if fetch and not local:
|
2023-07-17 06:37:47 +00:00
|
|
|
actor_uri, handle = cls.fetch_webfinger(f"{username}@{domain}")
|
2022-11-19 20:38:25 +00:00
|
|
|
if handle is None:
|
|
|
|
return None
|
2022-11-21 00:17:53 +00: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 04:30:07 +00:00
|
|
|
username, domain = handle.split("@")
|
2022-12-28 17:52:39 +00:00
|
|
|
if not domain_instance:
|
|
|
|
domain_instance = Domain.get_remote_domain(domain)
|
2022-11-07 04:30:07 +00:00
|
|
|
return cls.objects.create(
|
|
|
|
actor_uri=actor_uri,
|
|
|
|
username=username,
|
2022-12-28 17:52:39 +00:00
|
|
|
domain_id=domain_instance,
|
2022-11-07 04:30:07 +00:00
|
|
|
local=False,
|
|
|
|
)
|
2022-11-06 04:49:25 +00:00
|
|
|
return None
|
|
|
|
|
2022-11-06 06:07:38 +00:00
|
|
|
@classmethod
|
2022-11-20 21:20:28 +00:00
|
|
|
def by_actor_uri(cls, uri, create=False, transient=False) -> "Identity":
|
2022-11-06 06:07:38 +00:00
|
|
|
try:
|
2022-11-06 20:48:04 +00:00
|
|
|
return cls.objects.get(actor_uri=uri)
|
2022-11-06 06:07:38 +00:00
|
|
|
except cls.DoesNotExist:
|
2022-11-12 05:02:43 +00:00
|
|
|
if create:
|
2022-11-20 21:20:28 +00: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 05:02:43 +00:00
|
|
|
else:
|
2022-11-17 05:23:32 +00:00
|
|
|
raise cls.DoesNotExist(f"No identity found with actor_uri {uri}")
|
2022-11-06 21:14:08 +00:00
|
|
|
|
2022-11-07 04:30:07 +00:00
|
|
|
### Dynamic properties ###
|
|
|
|
|
|
|
|
@property
|
|
|
|
def name_or_handle(self):
|
|
|
|
return self.name or self.handle
|
|
|
|
|
2022-12-15 07:50:54 +00:00
|
|
|
@cached_property
|
|
|
|
def html_name_or_handle(self):
|
|
|
|
"""
|
|
|
|
Return the name_or_handle with any HTML substitutions made
|
|
|
|
"""
|
2022-12-22 01:10:25 +00:00
|
|
|
return ContentRenderer(local=True).render_identity_data(
|
2022-12-20 11:39:45 +00:00
|
|
|
self.name_or_handle, self, strip=True
|
|
|
|
)
|
2022-12-15 07:50:54 +00:00
|
|
|
|
2022-11-05 20:17:27 +00:00
|
|
|
@property
|
2022-11-06 20:48:04 +00:00
|
|
|
def handle(self):
|
2022-12-05 04:13:33 +00:00
|
|
|
if self.username is None:
|
|
|
|
return "(unknown user)"
|
2022-11-07 04:30:07 +00:00
|
|
|
if self.domain_id:
|
|
|
|
return f"{self.username}@{self.domain_id}"
|
2022-12-05 04:13:33 +00:00
|
|
|
return f"{self.username}@(unknown server)"
|
2022-11-05 20:17:27 +00:00
|
|
|
|
2022-11-06 04:49:25 +00: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 04:30:07 +00:00
|
|
|
@property
|
|
|
|
def outdated(self) -> bool:
|
|
|
|
# TODO: Setting
|
|
|
|
return self.data_age > 60 * 24 * 24
|
|
|
|
|
2022-12-17 02:42:48 +00: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 05:23:32 +00:00
|
|
|
### ActivityPub (outbound) ###
|
2022-11-16 01:30:30 +00:00
|
|
|
|
2022-12-22 20:51:39 +00:00
|
|
|
def to_webfinger(self):
|
2022-12-22 18:43:53 +00:00
|
|
|
aliases = [self.absolute_profile_uri()]
|
2022-12-22 20:51:39 +00:00
|
|
|
|
|
|
|
actor_links = []
|
|
|
|
|
|
|
|
if self.restriction != Identity.Restriction.blocked:
|
|
|
|
# Blocked users don't get a profile page
|
|
|
|
actor_links.append(
|
|
|
|
{
|
|
|
|
"rel": "http://webfinger.net/rel/profile-page",
|
|
|
|
"type": "text/html",
|
|
|
|
"href": self.absolute_profile_uri(),
|
|
|
|
},
|
|
|
|
)
|
|
|
|
|
|
|
|
# TODO: How to handle Restriction.limited and Restriction.blocked?
|
|
|
|
# Exposing the activity+json will allow migrating off server
|
|
|
|
actor_links.extend(
|
|
|
|
[
|
2022-12-22 18:43:53 +00:00
|
|
|
{
|
|
|
|
"rel": "self",
|
|
|
|
"type": "application/activity+json",
|
|
|
|
"href": self.actor_uri,
|
|
|
|
}
|
2022-12-22 20:51:39 +00:00
|
|
|
]
|
|
|
|
)
|
|
|
|
|
|
|
|
return {
|
|
|
|
"subject": f"acct:{self.handle}",
|
|
|
|
"aliases": aliases,
|
|
|
|
"links": actor_links,
|
|
|
|
}
|
|
|
|
|
2022-11-16 01:30:30 +00:00
|
|
|
def to_ap(self):
|
2023-01-28 18:00:48 +00:00
|
|
|
from activities.models import Emoji
|
|
|
|
|
2023-07-22 16:38:22 +00:00
|
|
|
self.ensure_uris()
|
2022-11-16 01:30:30 +00:00
|
|
|
response = {
|
|
|
|
"id": self.actor_uri,
|
2022-12-20 06:52:33 +00:00
|
|
|
"type": self.actor_type.title(),
|
2023-07-22 16:38:22 +00:00
|
|
|
"inbox": self.inbox_uri,
|
|
|
|
"outbox": self.outbox_uri,
|
|
|
|
"featured": self.featured_collection_uri,
|
|
|
|
"followers": self.followers_uri,
|
|
|
|
"following": self.following_uri,
|
2022-11-16 01:30:30 +00:00
|
|
|
"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 04:18:13 +00:00
|
|
|
"url": self.absolute_profile_uri(),
|
2022-12-17 02:45:39 +00:00
|
|
|
"toot:discoverable": self.discoverable,
|
2022-11-16 01:30:30 +00:00
|
|
|
}
|
|
|
|
if self.name:
|
|
|
|
response["name"] = self.name
|
|
|
|
if self.summary:
|
2022-12-24 19:49:59 +00:00
|
|
|
response["summary"] = self.summary
|
2022-11-18 02:31:00 +00:00
|
|
|
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,
|
|
|
|
}
|
2023-07-22 16:38:22 +00:00
|
|
|
if self.shared_inbox_uri:
|
2022-12-10 20:24:49 +00:00
|
|
|
response["endpoints"] = {
|
2023-07-22 16:38:22 +00:00
|
|
|
"sharedInbox": self.shared_inbox_uri,
|
2022-12-10 20:24:49 +00:00
|
|
|
}
|
2022-12-28 00:42:30 +00:00
|
|
|
if self.metadata:
|
|
|
|
response["attachment"] = [
|
|
|
|
{
|
2023-06-22 23:09:19 +00:00
|
|
|
"type": "PropertyValue",
|
2023-01-30 00:46:22 +00:00
|
|
|
"name": FediverseHtmlParser(item["name"]).plain_text,
|
|
|
|
"value": FediverseHtmlParser(item["value"]).html,
|
2022-12-28 00:42:30 +00:00
|
|
|
}
|
|
|
|
for item in self.metadata
|
|
|
|
]
|
2023-07-22 17:46:35 +00:00
|
|
|
if self.aliases:
|
|
|
|
response["alsoKnownAs"] = self.aliases
|
2023-01-28 18:00:48 +00:00
|
|
|
# Emoji
|
|
|
|
emojis = Emoji.emojis_from_content(
|
|
|
|
(self.name or "") + " " + (self.summary or ""), None
|
|
|
|
)
|
|
|
|
if emojis:
|
|
|
|
response["tag"] = []
|
|
|
|
for emoji in emojis:
|
|
|
|
response["tag"].append(emoji.to_ap_tag())
|
2022-11-16 01:30:30 +00:00
|
|
|
return response
|
|
|
|
|
2022-12-15 07:50:54 +00:00
|
|
|
def to_ap_tag(self):
|
|
|
|
"""
|
|
|
|
Return this Identity as an ActivityPub Tag
|
|
|
|
"""
|
|
|
|
return {
|
|
|
|
"href": self.actor_uri,
|
|
|
|
"name": "@" + self.handle,
|
|
|
|
"type": "Mention",
|
|
|
|
}
|
|
|
|
|
2022-12-21 17:13:39 +00:00
|
|
|
def to_update_ap(self):
|
|
|
|
"""
|
|
|
|
Returns the AP JSON to update this object
|
|
|
|
"""
|
|
|
|
object = self.to_ap()
|
|
|
|
return {
|
|
|
|
"type": "Update",
|
|
|
|
"id": self.actor_uri + "#update",
|
|
|
|
"actor": self.actor_uri,
|
|
|
|
"object": object,
|
|
|
|
}
|
|
|
|
|
|
|
|
def to_delete_ap(self):
|
|
|
|
"""
|
|
|
|
Returns the AP JSON to delete this object
|
|
|
|
"""
|
|
|
|
object = self.to_ap()
|
|
|
|
return {
|
|
|
|
"type": "Delete",
|
|
|
|
"id": self.actor_uri + "#delete",
|
|
|
|
"actor": self.actor_uri,
|
|
|
|
"object": object,
|
|
|
|
}
|
|
|
|
|
2022-11-17 05:23:32 +00: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 19:32:49 +00: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
|
|
|
|
|
2023-05-04 04:42:37 +00:00
|
|
|
### Deletion ###
|
|
|
|
|
|
|
|
def mark_deleted(self):
|
|
|
|
"""
|
|
|
|
Marks the identity and all of its related content as deleted.
|
|
|
|
"""
|
|
|
|
# Move all posts to deleted
|
|
|
|
from activities.models.post import Post, PostStates
|
|
|
|
|
|
|
|
Post.transition_perform_queryset(self.posts, PostStates.deleted)
|
|
|
|
# Remove all users from ourselves and mark deletion date
|
|
|
|
self.users.set([])
|
|
|
|
self.deleted = timezone.now()
|
|
|
|
self.save()
|
|
|
|
# Move ourselves to deleted
|
|
|
|
self.transition_perform(IdentityStates.deleted)
|
|
|
|
|
2022-11-07 04:30:07 +00:00
|
|
|
### Actor/Webfinger fetching ###
|
2022-11-05 20:17:27 +00:00
|
|
|
|
2022-11-06 20:48:04 +00:00
|
|
|
@classmethod
|
2023-07-17 06:37:47 +00:00
|
|
|
def fetch_webfinger_url(cls, domain: str):
|
2022-11-06 20:48:04 +00:00
|
|
|
"""
|
2022-12-31 18:13:51 +00:00
|
|
|
Given a domain (hostname), returns the correct webfinger URL to use
|
|
|
|
based on probing host-meta.
|
2022-11-06 20:48:04 +00:00
|
|
|
"""
|
2023-07-17 06:37:47 +00:00
|
|
|
with httpx.Client(
|
2022-12-27 23:50:39 +00:00
|
|
|
timeout=settings.SETUP.REMOTE_TIMEOUT,
|
|
|
|
headers={"User-Agent": settings.TAKAHE_USER_AGENT},
|
|
|
|
) as client:
|
|
|
|
try:
|
2023-07-17 06:37:47 +00:00
|
|
|
response = client.get(
|
2022-12-24 04:35:17 +00:00
|
|
|
f"https://{domain}/.well-known/host-meta",
|
|
|
|
follow_redirects=True,
|
2022-12-27 23:50:39 +00:00
|
|
|
headers={"Accept": "application/xml"},
|
2022-12-24 04:35:17 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
# In the case of anything other than a success, we'll still try
|
|
|
|
# hitting the webfinger URL on the domain we were given to handle
|
|
|
|
# incorrectly setup servers.
|
2022-12-24 17:56:49 +00:00
|
|
|
if response.status_code == 200 and response.content.strip():
|
2022-12-24 04:35:17 +00:00
|
|
|
tree = etree.fromstring(response.content)
|
|
|
|
template = tree.xpath(
|
2022-12-31 18:13:51 +00:00
|
|
|
"string(.//*[local-name() = 'Link' and @rel='lrdd' and (not(@type) or @type='application/jrd+json')]/@template)"
|
2022-12-24 04:35:17 +00:00
|
|
|
)
|
|
|
|
if template:
|
2022-12-31 18:13:51 +00:00
|
|
|
return template
|
2022-12-27 23:50:39 +00:00
|
|
|
except (httpx.RequestError, etree.ParseError):
|
|
|
|
pass
|
2022-12-24 04:35:17 +00:00
|
|
|
|
2022-12-31 18:13:51 +00:00
|
|
|
return f"https://{domain}/.well-known/webfinger?resource={{uri}}"
|
|
|
|
|
|
|
|
@classmethod
|
2023-07-17 06:37:47 +00:00
|
|
|
def fetch_webfinger(cls, handle: str) -> tuple[str | None, str | None]:
|
2022-12-31 18:13:51 +00:00
|
|
|
"""
|
|
|
|
Given a username@domain handle, returns a tuple of
|
|
|
|
(actor uri, canonical handle) or None, None if it does not resolve.
|
|
|
|
"""
|
|
|
|
domain = handle.split("@")[1].lower()
|
2023-01-13 17:53:02 +00:00
|
|
|
try:
|
2023-07-17 06:37:47 +00:00
|
|
|
webfinger_url = cls.fetch_webfinger_url(domain)
|
2023-01-13 17:53:02 +00:00
|
|
|
except ssl.SSLCertVerificationError:
|
|
|
|
return None, None
|
2022-12-31 18:13:51 +00:00
|
|
|
|
|
|
|
# Go make a Webfinger request
|
2023-07-17 06:37:47 +00:00
|
|
|
with httpx.Client(
|
2022-12-31 18:13:51 +00:00
|
|
|
timeout=settings.SETUP.REMOTE_TIMEOUT,
|
|
|
|
headers={"User-Agent": settings.TAKAHE_USER_AGENT},
|
|
|
|
) as client:
|
2022-12-27 23:50:39 +00:00
|
|
|
try:
|
2023-07-17 06:37:47 +00:00
|
|
|
response = client.get(
|
2022-12-27 23:50:39 +00:00
|
|
|
webfinger_url.format(uri=f"acct:{handle}"),
|
2022-12-18 21:00:28 +00:00
|
|
|
follow_redirects=True,
|
2022-12-27 23:50:39 +00:00
|
|
|
headers={"Accept": "application/json"},
|
2022-12-17 19:00:47 +00:00
|
|
|
)
|
2022-12-27 23:50:39 +00:00
|
|
|
response.raise_for_status()
|
2023-01-13 17:53:02 +00:00
|
|
|
except (httpx.HTTPError, ssl.SSLCertVerificationError) as ex:
|
2022-12-27 23:50:39 +00:00
|
|
|
response = getattr(ex, "response", None)
|
|
|
|
if (
|
|
|
|
response
|
|
|
|
and response.status_code < 500
|
2023-07-10 16:19:20 +00:00
|
|
|
and response.status_code not in [400, 401, 403, 404, 406, 410]
|
2022-12-27 23:50:39 +00:00
|
|
|
):
|
|
|
|
raise ValueError(
|
|
|
|
f"Client error fetching webfinger: {response.status_code}",
|
|
|
|
response.content,
|
|
|
|
)
|
|
|
|
return None, None
|
|
|
|
|
2022-12-18 21:00:28 +00:00
|
|
|
try:
|
|
|
|
data = response.json()
|
|
|
|
except ValueError:
|
2022-12-21 21:46:09 +00:00
|
|
|
# Some servers return these with a 200 status code!
|
|
|
|
if b"not found" in response.content.lower():
|
|
|
|
return None, None
|
2022-12-18 21:00:28 +00:00
|
|
|
raise ValueError(
|
|
|
|
"JSON parse error fetching webfinger",
|
|
|
|
response.content,
|
|
|
|
)
|
2023-01-14 21:19:47 +00:00
|
|
|
try:
|
|
|
|
if data["subject"].startswith("acct:"):
|
|
|
|
data["subject"] = data["subject"][5:]
|
|
|
|
for link in data["links"]:
|
|
|
|
if (
|
|
|
|
link.get("type") == "application/activity+json"
|
|
|
|
and link.get("rel") == "self"
|
|
|
|
):
|
|
|
|
return link["href"], data["subject"]
|
|
|
|
except KeyError:
|
|
|
|
# Server returning wrong payload structure
|
|
|
|
pass
|
2022-11-06 20:48:04 +00:00
|
|
|
return None, None
|
2022-11-05 23:51:54 +00:00
|
|
|
|
2023-05-13 16:01:27 +00:00
|
|
|
@classmethod
|
2023-07-17 06:37:47 +00:00
|
|
|
def fetch_pinned_post_uris(cls, uri: str) -> list[str]:
|
2023-05-13 16:01:27 +00:00
|
|
|
"""
|
|
|
|
Fetch an identity's featured collection.
|
|
|
|
"""
|
2023-07-17 06:37:47 +00:00
|
|
|
with httpx.Client(
|
2023-05-13 16:01:27 +00:00
|
|
|
timeout=settings.SETUP.REMOTE_TIMEOUT,
|
|
|
|
headers={"User-Agent": settings.TAKAHE_USER_AGENT},
|
|
|
|
) as client:
|
|
|
|
try:
|
2023-07-17 06:37:47 +00:00
|
|
|
response = client.get(
|
2023-05-13 16:01:27 +00:00
|
|
|
uri,
|
|
|
|
follow_redirects=True,
|
|
|
|
headers={"Accept": "application/activity+json"},
|
|
|
|
)
|
|
|
|
response.raise_for_status()
|
|
|
|
except (httpx.HTTPError, ssl.SSLCertVerificationError) as ex:
|
|
|
|
response = getattr(ex, "response", None)
|
|
|
|
if (
|
|
|
|
response
|
|
|
|
and response.status_code < 500
|
|
|
|
and response.status_code not in [401, 403, 404, 406, 410]
|
|
|
|
):
|
|
|
|
raise ValueError(
|
|
|
|
f"Client error fetching featured collection: {response.status_code}",
|
|
|
|
response.content,
|
|
|
|
)
|
|
|
|
return []
|
|
|
|
|
|
|
|
try:
|
|
|
|
data = canonicalise(response.json(), include_security=True)
|
2023-05-15 16:54:32 +00:00
|
|
|
items: list[dict | str] = []
|
2023-05-13 16:01:27 +00:00
|
|
|
if "orderedItems" in data:
|
2023-05-15 16:54:32 +00:00
|
|
|
items = list(reversed(data["orderedItems"]))
|
2023-05-13 16:01:27 +00:00
|
|
|
elif "items" in data:
|
2023-05-15 16:54:32 +00:00
|
|
|
items = list(data["items"])
|
|
|
|
|
|
|
|
ids = []
|
|
|
|
for item in items:
|
|
|
|
if not isinstance(item, dict):
|
|
|
|
continue
|
|
|
|
post_obj: dict | None = item
|
2023-05-15 17:36:33 +00:00
|
|
|
if item["type"] in ["Create", "Update"]:
|
2023-05-15 16:54:32 +00:00
|
|
|
post_obj = item.get("object")
|
|
|
|
if post_obj:
|
|
|
|
ids.append(post_obj["id"])
|
|
|
|
return ids
|
2023-05-13 16:01:27 +00:00
|
|
|
except ValueError:
|
|
|
|
# Some servers return these with a 200 status code!
|
|
|
|
if b"not found" in response.content.lower():
|
|
|
|
return []
|
|
|
|
raise ValueError(
|
|
|
|
"JSON parse error fetching featured collection",
|
|
|
|
response.content,
|
|
|
|
)
|
|
|
|
|
2023-07-17 06:37:47 +00:00
|
|
|
def fetch_actor(self) -> bool:
|
2022-11-06 20:48:04 +00:00
|
|
|
"""
|
|
|
|
Fetches the user's actor information, as well as their domain from
|
|
|
|
webfinger if it's available.
|
|
|
|
"""
|
2022-12-17 03:04:28 +00:00
|
|
|
from activities.models import Emoji
|
2023-05-13 16:01:27 +00:00
|
|
|
from users.services import IdentityService
|
2022-12-17 03:04:28 +00:00
|
|
|
|
2022-11-06 20:48:04 +00:00
|
|
|
if self.local:
|
|
|
|
raise ValueError("Cannot fetch local identities")
|
2022-11-21 01:29:19 +00:00
|
|
|
try:
|
2023-07-17 06:37:47 +00:00
|
|
|
response = SystemActor().signed_request(
|
2022-11-21 01:29:19 +00:00
|
|
|
method="get",
|
|
|
|
uri=self.actor_uri,
|
2022-11-06 06:07:38 +00:00
|
|
|
)
|
2023-01-13 17:53:02 +00:00
|
|
|
except (httpx.RequestError, ssl.SSLCertVerificationError):
|
2022-11-21 01:29:19 +00:00
|
|
|
return False
|
2022-12-24 18:05:07 +00:00
|
|
|
content_type = response.headers.get("content-type")
|
|
|
|
if content_type and "html" in content_type:
|
|
|
|
# Some servers don't properly handle "application/activity+json"
|
|
|
|
return False
|
2023-01-13 17:53:02 +00:00
|
|
|
status_code = response.status_code
|
|
|
|
if status_code >= 400:
|
|
|
|
if status_code == 410 and self.pk:
|
|
|
|
# Their account got deleted, so let's do the same.
|
2023-07-17 06:37:47 +00:00
|
|
|
Identity.objects.filter(pk=self.pk).delete()
|
2023-01-13 17:53:02 +00:00
|
|
|
|
2023-01-19 20:14:55 +00:00
|
|
|
if status_code < 500 and status_code not in [401, 403, 404, 406, 410]:
|
|
|
|
capture_message(
|
|
|
|
f"Client error fetching actor at {self.actor_uri}: {status_code}",
|
|
|
|
extras={
|
|
|
|
"identity": self.pk,
|
|
|
|
"domain": self.domain_id,
|
|
|
|
"content": response.content,
|
|
|
|
},
|
|
|
|
)
|
|
|
|
return False
|
2023-01-13 17:53:02 +00:00
|
|
|
|
2022-11-21 01:29:19 +00:00
|
|
|
document = canonicalise(response.json(), include_security=True)
|
2022-12-21 16:13:36 +00:00
|
|
|
if "type" not in document:
|
|
|
|
return False
|
2022-11-21 01:29:19 +00:00
|
|
|
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-27 23:43:20 +00:00
|
|
|
self.followers_uri = document.get("followers")
|
|
|
|
self.following_uri = document.get("following")
|
2023-05-13 16:01:27 +00:00
|
|
|
self.featured_collection_uri = document.get("featured")
|
2022-12-20 06:52:33 +00:00
|
|
|
self.actor_type = document["type"].lower()
|
2022-11-27 23:43:20 +00:00
|
|
|
self.shared_inbox_uri = document.get("endpoints", {}).get("sharedInbox")
|
2022-11-21 01:29:19 +00: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:
|
2022-12-21 21:39:56 +00:00
|
|
|
self.username = self.username
|
2022-12-16 23:38:52 +00:00
|
|
|
self.manually_approves_followers = document.get("manuallyApprovesFollowers")
|
2022-11-21 01:29:19 +00:00
|
|
|
self.public_key = document.get("publicKey", {}).get("publicKeyPem")
|
|
|
|
self.public_key_id = document.get("publicKey", {}).get("id")
|
2022-12-22 05:59:07 +00:00
|
|
|
# Sometimes the public key PEM is in a language construct?
|
|
|
|
if isinstance(self.public_key, dict):
|
|
|
|
self.public_key = self.public_key["@value"]
|
2022-12-17 22:42:29 +00:00
|
|
|
self.icon_uri = get_first_image_url(document.get("icon", None))
|
|
|
|
self.image_uri = get_first_image_url(document.get("image", None))
|
2022-12-17 02:45:39 +00:00
|
|
|
self.discoverable = document.get("toot:discoverable", True)
|
2022-11-27 23:43:20 +00:00
|
|
|
# Profile links/metadata
|
|
|
|
self.metadata = []
|
|
|
|
for attachment in get_list(document, "attachment"):
|
|
|
|
if (
|
2023-06-24 14:53:42 +00:00
|
|
|
attachment["type"] == "PropertyValue"
|
2022-11-27 23:43:20 +00:00
|
|
|
and "name" in attachment
|
2023-06-24 14:53:42 +00:00
|
|
|
and "value" in attachment
|
2022-11-27 23:43:20 +00:00
|
|
|
):
|
|
|
|
self.metadata.append(
|
|
|
|
{
|
2023-06-24 14:53:42 +00:00
|
|
|
"name": attachment["name"],
|
|
|
|
"value": FediverseHtmlParser(attachment["value"]).html,
|
2022-11-27 23:43:20 +00:00
|
|
|
}
|
|
|
|
)
|
2022-11-06 20:48:04 +00:00
|
|
|
# Now go do webfinger with that info to see if we can get a canonical domain
|
|
|
|
actor_url_parts = urlparse(self.actor_uri)
|
|
|
|
if self.username:
|
2023-07-17 06:37:47 +00:00
|
|
|
webfinger_actor, webfinger_handle = self.fetch_webfinger(
|
2022-11-06 20:48:04 +00:00
|
|
|
f"{self.username}@{actor_url_parts.hostname}"
|
|
|
|
)
|
|
|
|
if webfinger_handle:
|
|
|
|
webfinger_username, webfinger_domain = webfinger_handle.split("@")
|
2022-12-21 21:39:56 +00:00
|
|
|
self.username = webfinger_username
|
2023-07-17 06:37:47 +00:00
|
|
|
self.domain = Domain.get_remote_domain(webfinger_domain)
|
2022-11-06 20:48:04 +00:00
|
|
|
else:
|
2023-07-17 06:37:47 +00:00
|
|
|
self.domain = Domain.get_remote_domain(actor_url_parts.hostname)
|
2022-11-06 20:48:04 +00:00
|
|
|
else:
|
2023-07-17 06:37:47 +00:00
|
|
|
self.domain = Domain.get_remote_domain(actor_url_parts.hostname)
|
2022-12-17 03:04:28 +00:00
|
|
|
# Emojis (we need the domain so we do them here)
|
|
|
|
for tag in get_list(document, "tag"):
|
2023-01-12 00:07:59 +00:00
|
|
|
if tag["type"].lower() in ["toot:emoji", "emoji"]:
|
2023-07-17 06:37:47 +00:00
|
|
|
Emoji.by_ap_tag(self.domain, tag, create=True)
|
2022-12-17 03:04:28 +00:00
|
|
|
# Mark as fetched
|
2022-11-06 20:48:04 +00:00
|
|
|
self.fetched = timezone.now()
|
2022-11-21 15:31:14 +00:00
|
|
|
try:
|
2023-07-17 06:37:47 +00:00
|
|
|
self.save()
|
2022-11-21 15:31:14 +00:00
|
|
|
except IntegrityError as e:
|
|
|
|
# See if we can fetch a PK and save there
|
|
|
|
if self.pk is None:
|
|
|
|
try:
|
2023-07-17 06:37:47 +00:00
|
|
|
other_row = Identity.objects.get(actor_uri=self.actor_uri)
|
2022-11-21 15:31:14 +00:00
|
|
|
except Identity.DoesNotExist:
|
|
|
|
raise ValueError(
|
|
|
|
f"Could not save Identity at end of actor fetch: {e}"
|
|
|
|
)
|
2022-12-05 17:38:37 +00:00
|
|
|
self.pk: int | None = other_row.pk
|
2023-07-17 06:37:47 +00:00
|
|
|
self.save()
|
2023-05-13 16:01:27 +00:00
|
|
|
|
|
|
|
# Fetch pinned posts after identity has been fetched and saved
|
|
|
|
if self.featured_collection_uri:
|
2023-07-17 06:37:47 +00:00
|
|
|
featured = self.fetch_pinned_post_uris(self.featured_collection_uri)
|
2023-05-13 16:01:27 +00:00
|
|
|
service = IdentityService(self)
|
2023-07-17 06:37:47 +00:00
|
|
|
service.sync_pins(featured)
|
2023-05-13 16:01:27 +00:00
|
|
|
|
2022-11-06 06:07:38 +00:00
|
|
|
return True
|
|
|
|
|
2022-12-26 17:39:33 +00:00
|
|
|
### OpenGraph API ###
|
|
|
|
|
|
|
|
def to_opengraph_dict(self) -> dict:
|
|
|
|
return {
|
|
|
|
"og:title": f"{self.name} (@{self.handle})",
|
|
|
|
"og:type": "profile",
|
|
|
|
"og:description": self.summary,
|
|
|
|
"og:profile:username": self.handle,
|
|
|
|
"og:image:url": self.local_icon_url().absolute,
|
|
|
|
"og:image:height": 85,
|
|
|
|
"og:image:width": 85,
|
|
|
|
}
|
|
|
|
|
2022-12-11 07:25:48 +00:00
|
|
|
### Mastodon Client API ###
|
|
|
|
|
2023-01-06 05:51:02 +00:00
|
|
|
def to_mastodon_mention_json(self):
|
|
|
|
return {
|
|
|
|
"id": self.id,
|
|
|
|
"username": self.username or "",
|
|
|
|
"url": self.absolute_profile_uri() or "",
|
|
|
|
"acct": self.handle or "",
|
|
|
|
}
|
|
|
|
|
2023-01-15 23:15:57 +00:00
|
|
|
def to_mastodon_json(self, source=False, include_counts=True):
|
|
|
|
from activities.models import Emoji, Post
|
2022-12-15 07:50:54 +00:00
|
|
|
|
2022-12-12 14:22:11 +00:00
|
|
|
header_image = self.local_image_url()
|
2022-12-29 17:31:32 +00:00
|
|
|
missing = StaticAbsoluteUrl("img/missing.png").absolute
|
|
|
|
|
2022-12-15 07:50:54 +00: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
|
|
|
|
)
|
2023-01-12 05:04:03 +00:00
|
|
|
renderer = ContentRenderer(local=False)
|
2023-01-15 23:15:57 +00:00
|
|
|
result = {
|
2022-12-11 07:25:48 +00:00
|
|
|
"id": self.pk,
|
2022-12-16 01:59:04 +00:00
|
|
|
"username": self.username or "",
|
2023-01-19 23:34:49 +00:00
|
|
|
"acct": self.username if source else self.handle,
|
2022-12-16 02:10:50 +00:00
|
|
|
"url": self.absolute_profile_uri() or "",
|
2022-12-16 01:59:04 +00:00
|
|
|
"display_name": self.name or "",
|
2022-12-11 07:25:48 +00:00
|
|
|
"note": self.summary or "",
|
2022-12-12 14:22:11 +00:00
|
|
|
"avatar": self.local_icon_url().absolute,
|
|
|
|
"avatar_static": self.local_icon_url().absolute,
|
2022-12-29 17:31:32 +00:00
|
|
|
"header": header_image.absolute if header_image else missing,
|
|
|
|
"header_static": header_image.absolute if header_image else missing,
|
2022-12-11 07:25:48 +00:00
|
|
|
"locked": False,
|
|
|
|
"fields": (
|
|
|
|
[
|
2023-01-12 05:04:03 +00:00
|
|
|
{
|
|
|
|
"name": m["name"],
|
|
|
|
"value": renderer.render_identity_data(m["value"], self),
|
|
|
|
"verified_at": None,
|
|
|
|
}
|
2022-12-11 07:25:48 +00:00
|
|
|
for m in self.metadata
|
|
|
|
]
|
|
|
|
if self.metadata
|
|
|
|
else []
|
|
|
|
),
|
2022-12-15 07:50:54 +00:00
|
|
|
"emojis": [emoji.to_mastodon_json() for emoji in emojis],
|
2023-05-13 12:00:18 +00:00
|
|
|
"bot": self.actor_type.lower() in ["service", "application"],
|
|
|
|
"group": self.actor_type.lower() == "group",
|
2022-12-11 07:25:48 +00:00
|
|
|
"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
|
2023-01-09 01:05:29 +00:00
|
|
|
"statuses_count": self.posts.count() if include_counts else 0,
|
|
|
|
"followers_count": self.inbound_follows.count() if include_counts else 0,
|
|
|
|
"following_count": self.outbound_follows.count() if include_counts else 0,
|
2022-12-11 07:25:48 +00:00
|
|
|
}
|
2023-01-15 23:15:57 +00:00
|
|
|
if source:
|
|
|
|
privacy_map = {
|
|
|
|
Post.Visibilities.public: "public",
|
|
|
|
Post.Visibilities.unlisted: "unlisted",
|
|
|
|
Post.Visibilities.local_only: "unlisted",
|
|
|
|
Post.Visibilities.followers: "private",
|
|
|
|
Post.Visibilities.mentioned: "direct",
|
|
|
|
}
|
|
|
|
result["source"] = {
|
2023-01-30 00:46:22 +00:00
|
|
|
"note": FediverseHtmlParser(self.summary).plain_text
|
|
|
|
if self.summary
|
|
|
|
else "",
|
2023-01-19 17:30:26 +00:00
|
|
|
"fields": (
|
|
|
|
[
|
|
|
|
{
|
|
|
|
"name": m["name"],
|
2023-01-30 00:46:22 +00:00
|
|
|
"value": FediverseHtmlParser(m["value"]).plain_text,
|
2023-01-19 17:30:26 +00:00
|
|
|
"verified_at": None,
|
|
|
|
}
|
|
|
|
for m in self.metadata
|
|
|
|
]
|
|
|
|
if self.metadata
|
|
|
|
else []
|
|
|
|
),
|
2023-01-15 23:15:57 +00:00
|
|
|
"privacy": privacy_map[
|
|
|
|
Config.load_identity(self).default_post_visibility
|
|
|
|
],
|
|
|
|
"sensitive": False,
|
|
|
|
"language": "unk",
|
|
|
|
"follow_requests_count": 0,
|
|
|
|
}
|
|
|
|
return result
|
2022-12-11 07:25:48 +00:00
|
|
|
|
2022-11-07 04:30:07 +00:00
|
|
|
### Cryptography ###
|
|
|
|
|
2023-07-17 06:37:47 +00:00
|
|
|
def signed_request(
|
2022-11-21 01:32:55 +00:00
|
|
|
self,
|
|
|
|
method: Literal["get", "post"],
|
|
|
|
uri: str,
|
2022-12-05 17:38:37 +00:00
|
|
|
body: dict | None = None,
|
2022-11-21 01:32:55 +00:00
|
|
|
):
|
|
|
|
"""
|
|
|
|
Performs a signed request on behalf of the System Actor.
|
|
|
|
"""
|
2023-07-17 06:37:47 +00:00
|
|
|
return HttpSignature.signed_request(
|
2022-11-21 01:32:55 +00:00
|
|
|
method=method,
|
|
|
|
uri=uri,
|
|
|
|
body=body,
|
|
|
|
private_key=self.private_key,
|
|
|
|
key_id=self.public_key_id,
|
|
|
|
)
|
|
|
|
|
2022-11-07 04:30:07 +00:00
|
|
|
def generate_keypair(self):
|
|
|
|
if not self.local:
|
|
|
|
raise ValueError("Cannot generate keypair for remote user")
|
2022-11-21 01:29:19 +00:00
|
|
|
self.private_key, self.public_key = RsaKeys.generate_keypair()
|
2022-11-17 05:23:32 +00:00
|
|
|
self.public_key_id = self.actor_uri + "#main-key"
|
2022-11-07 04:30:07 +00:00
|
|
|
self.save()
|
2022-11-26 02:33:46 +00: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))
|