2022-11-07 04:30:07 +00:00
|
|
|
from typing import Optional
|
|
|
|
|
2022-12-17 19:29:48 +00:00
|
|
|
import httpx
|
2022-11-18 01:52:00 +00:00
|
|
|
from django.db import models, transaction
|
2022-11-05 23:51:54 +00:00
|
|
|
|
2022-11-11 06:42:43 +00:00
|
|
|
from core.ld import canonicalise
|
2022-11-09 06:06:29 +00:00
|
|
|
from stator.models import State, StateField, StateGraph, StatorModel
|
2022-11-12 05:02:43 +00:00
|
|
|
from users.models.identity import Identity
|
2022-11-07 04:30:07 +00:00
|
|
|
|
2022-11-05 23:51:54 +00:00
|
|
|
|
2022-11-09 06:06:29 +00:00
|
|
|
class FollowStates(StateGraph):
|
2022-11-12 05:02:43 +00:00
|
|
|
unrequested = State(try_interval=300)
|
2022-11-11 06:42:43 +00:00
|
|
|
local_requested = State(try_interval=24 * 60 * 60)
|
|
|
|
remote_requested = State(try_interval=24 * 60 * 60)
|
|
|
|
accepted = State(externally_progressed=True)
|
2022-11-17 05:23:32 +00:00
|
|
|
undone = State(try_interval=60 * 60)
|
2022-11-11 06:42:43 +00:00
|
|
|
undone_remotely = State()
|
|
|
|
|
|
|
|
unrequested.transitions_to(local_requested)
|
|
|
|
unrequested.transitions_to(remote_requested)
|
|
|
|
local_requested.transitions_to(accepted)
|
|
|
|
remote_requested.transitions_to(accepted)
|
2022-11-17 05:23:32 +00:00
|
|
|
accepted.transitions_to(undone)
|
|
|
|
undone.transitions_to(undone_remotely)
|
2022-11-10 06:48:31 +00:00
|
|
|
|
2022-11-18 03:04:01 +00:00
|
|
|
@classmethod
|
|
|
|
def group_active(cls):
|
|
|
|
return [cls.unrequested, cls.local_requested, cls.accepted]
|
|
|
|
|
2022-11-10 06:48:31 +00:00
|
|
|
@classmethod
|
|
|
|
async def handle_unrequested(cls, instance: "Follow"):
|
2022-11-12 05:02:43 +00:00
|
|
|
"""
|
|
|
|
Follows that are unrequested need us to deliver the Follow object
|
|
|
|
to the target server.
|
|
|
|
"""
|
|
|
|
follow = await instance.afetch_full()
|
2022-11-11 06:42:43 +00:00
|
|
|
# Remote follows should not be here
|
|
|
|
if not follow.source.local:
|
|
|
|
return cls.remote_requested
|
|
|
|
# Sign it and send it
|
2022-12-17 19:29:48 +00:00
|
|
|
try:
|
|
|
|
await follow.source.signed_request(
|
|
|
|
method="post",
|
|
|
|
uri=follow.target.inbox_uri,
|
|
|
|
body=canonicalise(follow.to_ap()),
|
|
|
|
)
|
|
|
|
except httpx.RequestError:
|
|
|
|
return
|
2022-11-11 06:42:43 +00:00
|
|
|
return cls.local_requested
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
async def handle_local_requested(cls, instance: "Follow"):
|
|
|
|
# TODO: Resend follow requests occasionally
|
|
|
|
pass
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
async def handle_remote_requested(cls, instance: "Follow"):
|
2022-11-12 05:02:43 +00:00
|
|
|
"""
|
|
|
|
Items in remote_requested need us to send an Accept object to the
|
|
|
|
source server.
|
|
|
|
"""
|
|
|
|
follow = await instance.afetch_full()
|
2022-12-17 19:29:48 +00:00
|
|
|
try:
|
|
|
|
await follow.target.signed_request(
|
|
|
|
method="post",
|
|
|
|
uri=follow.source.inbox_uri,
|
|
|
|
body=canonicalise(follow.to_accept_ap()),
|
|
|
|
)
|
|
|
|
except httpx.RequestError:
|
|
|
|
return
|
2022-11-11 06:42:43 +00:00
|
|
|
return cls.accepted
|
2022-11-09 06:06:29 +00:00
|
|
|
|
2022-11-10 06:48:31 +00:00
|
|
|
@classmethod
|
2022-11-17 05:23:32 +00:00
|
|
|
async def handle_undone(cls, instance: "Follow"):
|
2022-11-12 05:02:43 +00:00
|
|
|
"""
|
|
|
|
Delivers the Undo object to the target server
|
|
|
|
"""
|
|
|
|
follow = await instance.afetch_full()
|
2022-12-17 19:29:48 +00:00
|
|
|
try:
|
|
|
|
await follow.source.signed_request(
|
|
|
|
method="post",
|
|
|
|
uri=follow.target.inbox_uri,
|
|
|
|
body=canonicalise(follow.to_undo_ap()),
|
|
|
|
)
|
|
|
|
except httpx.RequestError:
|
|
|
|
return
|
2022-11-11 06:42:43 +00:00
|
|
|
return cls.undone_remotely
|
2022-11-09 06:06:29 +00:00
|
|
|
|
|
|
|
|
|
|
|
class Follow(StatorModel):
|
2022-11-05 23:51:54 +00:00
|
|
|
"""
|
2022-11-06 20:48:04 +00:00
|
|
|
When one user (the source) follows other (the target)
|
2022-11-05 23:51:54 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
source = models.ForeignKey(
|
|
|
|
"users.Identity",
|
|
|
|
on_delete=models.CASCADE,
|
|
|
|
related_name="outbound_follows",
|
|
|
|
)
|
|
|
|
target = models.ForeignKey(
|
|
|
|
"users.Identity",
|
|
|
|
on_delete=models.CASCADE,
|
|
|
|
related_name="inbound_follows",
|
|
|
|
)
|
|
|
|
|
2022-11-07 04:30:07 +00:00
|
|
|
uri = models.CharField(blank=True, null=True, max_length=500)
|
2022-11-05 23:51:54 +00:00
|
|
|
note = models.TextField(blank=True, null=True)
|
|
|
|
|
2022-11-09 06:06:29 +00:00
|
|
|
state = StateField(FollowStates)
|
2022-11-07 04:30:07 +00:00
|
|
|
|
2022-11-05 23:51:54 +00:00
|
|
|
created = models.DateTimeField(auto_now_add=True)
|
|
|
|
updated = models.DateTimeField(auto_now=True)
|
2022-11-07 04:30:07 +00:00
|
|
|
|
|
|
|
class Meta:
|
|
|
|
unique_together = [("source", "target")]
|
|
|
|
|
2022-11-12 05:02:43 +00:00
|
|
|
def __str__(self):
|
|
|
|
return f"#{self.id}: {self.source} → {self.target}"
|
|
|
|
|
|
|
|
### Alternate fetchers/constructors ###
|
|
|
|
|
2022-11-07 04:30:07 +00:00
|
|
|
@classmethod
|
|
|
|
def maybe_get(cls, source, target) -> Optional["Follow"]:
|
|
|
|
"""
|
|
|
|
Returns a follow if it exists between source and target
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
return Follow.objects.get(source=source, target=target)
|
|
|
|
except Follow.DoesNotExist:
|
|
|
|
return None
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def create_local(cls, source, target):
|
|
|
|
"""
|
|
|
|
Creates a Follow from a local Identity to the target
|
|
|
|
(which can be local or remote).
|
|
|
|
"""
|
|
|
|
if not source.local:
|
2022-11-09 06:06:29 +00:00
|
|
|
raise ValueError("You cannot initiate follows from a remote Identity")
|
2022-11-07 04:30:07 +00:00
|
|
|
try:
|
|
|
|
follow = Follow.objects.get(source=source, target=target)
|
|
|
|
except Follow.DoesNotExist:
|
|
|
|
follow = Follow.objects.create(source=source, target=target, uri="")
|
|
|
|
follow.uri = source.actor_uri + f"follow/{follow.pk}/"
|
2022-11-09 06:06:29 +00:00
|
|
|
# TODO: Local follow approvals
|
2022-11-07 04:30:07 +00:00
|
|
|
if target.local:
|
2022-11-09 06:06:29 +00:00
|
|
|
follow.state = FollowStates.accepted
|
2022-11-07 04:30:07 +00:00
|
|
|
follow.save()
|
|
|
|
return follow
|
2022-11-10 06:48:31 +00:00
|
|
|
|
2022-11-12 05:02:43 +00:00
|
|
|
### Async helpers ###
|
|
|
|
|
|
|
|
async def afetch_full(self):
|
|
|
|
"""
|
|
|
|
Returns a version of the object with all relations pre-loaded
|
|
|
|
"""
|
|
|
|
return await Follow.objects.select_related(
|
|
|
|
"source", "source__domain", "target"
|
|
|
|
).aget(pk=self.pk)
|
|
|
|
|
|
|
|
### ActivityPub (outbound) ###
|
|
|
|
|
|
|
|
def to_ap(self):
|
|
|
|
"""
|
|
|
|
Returns the AP JSON for this object
|
|
|
|
"""
|
|
|
|
return {
|
|
|
|
"type": "Follow",
|
|
|
|
"id": self.uri,
|
|
|
|
"actor": self.source.actor_uri,
|
|
|
|
"object": self.target.actor_uri,
|
|
|
|
}
|
|
|
|
|
|
|
|
def to_accept_ap(self):
|
|
|
|
"""
|
|
|
|
Returns the AP JSON for this objects' accept.
|
|
|
|
"""
|
|
|
|
return {
|
|
|
|
"type": "Accept",
|
|
|
|
"id": self.uri + "#accept",
|
|
|
|
"actor": self.target.actor_uri,
|
|
|
|
"object": self.to_ap(),
|
|
|
|
}
|
|
|
|
|
|
|
|
def to_undo_ap(self):
|
|
|
|
"""
|
|
|
|
Returns the AP JSON for this objects' undo.
|
|
|
|
"""
|
|
|
|
return {
|
|
|
|
"type": "Undo",
|
|
|
|
"id": self.uri + "#undo",
|
|
|
|
"actor": self.source.actor_uri,
|
|
|
|
"object": self.to_ap(),
|
|
|
|
}
|
|
|
|
|
|
|
|
### ActivityPub (inbound) ###
|
|
|
|
|
2022-11-10 06:48:31 +00:00
|
|
|
@classmethod
|
2022-11-12 05:02:43 +00:00
|
|
|
def by_ap(cls, data, create=False) -> "Follow":
|
|
|
|
"""
|
|
|
|
Retrieves a Follow instance by its ActivityPub JSON object.
|
|
|
|
|
|
|
|
Optionally creates one if it's not present.
|
|
|
|
Raises KeyError if it's not found and create is False.
|
|
|
|
"""
|
|
|
|
# Resolve source and target and see if a Follow exists
|
|
|
|
source = Identity.by_actor_uri(data["actor"], create=create)
|
|
|
|
target = Identity.by_actor_uri(data["object"])
|
2022-11-10 06:48:31 +00:00
|
|
|
follow = cls.maybe_get(source=source, target=target)
|
2022-11-12 05:02:43 +00:00
|
|
|
# If it doesn't exist, create one in the remote_requested state
|
2022-11-10 06:48:31 +00:00
|
|
|
if follow is None:
|
2022-11-12 05:02:43 +00:00
|
|
|
if create:
|
|
|
|
return cls.objects.create(
|
|
|
|
source=source,
|
|
|
|
target=target,
|
|
|
|
uri=data["id"],
|
|
|
|
state=FollowStates.remote_requested,
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
raise KeyError(
|
|
|
|
f"No follow with source {source} and target {target}", data
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
return follow
|
2022-11-10 06:48:31 +00:00
|
|
|
|
|
|
|
@classmethod
|
2022-11-12 05:02:43 +00:00
|
|
|
def handle_request_ap(cls, data):
|
|
|
|
"""
|
|
|
|
Handles an incoming follow request
|
|
|
|
"""
|
2022-11-18 01:52:00 +00:00
|
|
|
from activities.models import TimelineEvent
|
|
|
|
|
|
|
|
with transaction.atomic():
|
|
|
|
follow = cls.by_ap(data, create=True)
|
|
|
|
# Force it into remote_requested so we send an accept
|
|
|
|
follow.transition_perform(FollowStates.remote_requested)
|
|
|
|
# Add a timeline event
|
|
|
|
TimelineEvent.add_follow(follow.target, follow.source)
|
2022-11-12 05:02:43 +00:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def handle_accept_ap(cls, data):
|
|
|
|
"""
|
|
|
|
Handles an incoming Follow Accept for one of our follows
|
|
|
|
"""
|
|
|
|
# Ensure the Accept actor is the Follow's object
|
|
|
|
if data["actor"] != data["object"]["object"]:
|
|
|
|
raise ValueError("Accept actor does not match its Follow object", data)
|
|
|
|
# Resolve source and target and see if a Follow exists (it really should)
|
|
|
|
try:
|
|
|
|
follow = cls.by_ap(data["object"])
|
|
|
|
except KeyError:
|
|
|
|
raise ValueError("No Follow locally for incoming Accept", data)
|
|
|
|
# If the follow was waiting to be accepted, transition it
|
2022-11-11 06:42:43 +00:00
|
|
|
if follow and follow.state in [
|
|
|
|
FollowStates.unrequested,
|
|
|
|
FollowStates.local_requested,
|
|
|
|
]:
|
2022-11-10 06:48:31 +00:00
|
|
|
follow.transition_perform(FollowStates.accepted)
|
2022-11-12 05:02:43 +00:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def handle_undo_ap(cls, data):
|
|
|
|
"""
|
|
|
|
Handles an incoming Follow Undo for one of our follows
|
|
|
|
"""
|
|
|
|
# Ensure the Undo actor is the Follow's actor
|
|
|
|
if data["actor"] != data["object"]["actor"]:
|
|
|
|
raise ValueError("Undo actor does not match its Follow object", data)
|
|
|
|
# Resolve source and target and see if a Follow exists (it hopefully does)
|
|
|
|
try:
|
|
|
|
follow = cls.by_ap(data["object"])
|
|
|
|
except KeyError:
|
|
|
|
raise ValueError("No Follow locally for incoming Undo", data)
|
|
|
|
# Delete the follow
|
|
|
|
follow.delete()
|