summaryrefslogtreecommitdiffstats
path: root/users/tasks/follow.py
blob: 0f802cf7430c8ed8bfe8bafe8a6108b608469888 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
from core.ld import canonicalise
from core.signatures import HttpSignature
from users.models import Follow


async def handle_follow_request(task_handler):
    """
    Request a follow from a remote server
    """
    follow = await Follow.objects.select_related(
        "source", "source__domain", "target"
    ).aget(pk=task_handler.subject)
    # Construct the request
    request = canonicalise(
        {
            "@context": "https://www.w3.org/ns/activitystreams",
            "id": follow.uri,
            "type": "Follow",
            "actor": follow.source.actor_uri,
            "object": follow.target.actor_uri,
        }
    )
    # Sign it and send it
    response = await HttpSignature.signed_request(
        follow.target.inbox_uri, request, follow.source
    )
    if response.status_code >= 400:
        raise ValueError(f"Request error: {response.status_code} {response.content}")
    await Follow.objects.filter(pk=follow.pk).aupdate(requested=True)


def send_follow_undo(id):
    """
    Request a follow from a remote server
    """
    follow = Follow.objects.select_related("source", "source__domain", "target").get(
        pk=id
    )
    # Construct the request
    request = canonicalise(
        {
            "@context": "https://www.w3.org/ns/activitystreams",
            "id": follow.uri + "#undo",
            "type": "Undo",
            "actor": follow.source.actor_uri,
            "object": {
                "id": follow.uri,
                "type": "Follow",
                "actor": follow.source.actor_uri,
                "object": follow.target.actor_uri,
            },
        }
    )
    # Sign it and send it
    from asgiref.sync import async_to_sync

    response = async_to_sync(HttpSignature.signed_request)(
        follow.target.inbox_uri, request, follow.source
    )
    if response.status_code >= 400:
        raise ValueError(f"Request error: {response.status_code} {response.content}")
    print(response)