aboutsummaryrefslogtreecommitdiffhomepage
path: root/Digitigrade/Model/Actor.php
blob: 3ad0efef3bbc08c0c39a86d91d7118f3fd244e8f (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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
<?php
namespace Digitigrade\Model;

use Digitigrade\RpcException;
use Digitigrade\RpcReceiver;

class Actor extends PushableModel implements RpcReceiver {
    public ?int $id;
    public string $uri;
    public bool $isLocal = false;
    public \DateTimeImmutable $created;
    public ?\DateTimeImmutable $modified;
    public ?string $homepage;
    public string $handle;
    public string $displayName;
    public ?string $avatar;
    public ?string $bio;
    public ?string $pronouns;
    public bool $automated = false;
    public bool $requestToFollow = false;
    public ActorEndpoints $endpoints;
    public array $extensions = [];

    /**
     * Creates and saves a new local actor with the specified fields pre-set
     * @param string $handle handle local part
     * @param ?string $displayName display name (default = same as handle)
     * @param ?string $bio biography / description
     * @param bool $automated is this account automated? (e.g. a bot)
     * @param bool $requestToFollow does this account check follow requests manually?
     * @return self
     */
    public static function create(
        string $handle,
        ?string $displayName = null,
        ?string $bio = null,
        bool $automated = false,
        bool $requestToFollow = true // setting this true by default as i think it's better for privacy
    ): self {
        if (self::findLocalByHandle($handle) != null) {
            throw new \RuntimeException('an actor with that local handle already exists!');
        }
        $actor = new self();
        $actor->uri = path_to_uri("/actor/$handle");
        $actor->isLocal = true;
        $date = new \DateTimeImmutable();
        $actor->created = $date;
        $actor->modified = $date;
        // don't really need to set this as it's generated by the view at /actor/:handle
        $actor->homepage = path_to_uri("/@/$handle");
        $actor->handle = $handle;
        $actor->displayName = $displayName ?? $handle;
        $actor->bio = $bio;
        $actor->automated = $automated;
        $actor->requestToFollow = $requestToFollow;
        // don't actually need to set these either
        // just need to set the basicFeed since it's a required field
        $actor->endpoints = new ActorEndpoints();
        $actor->endpoints->basicFeed = path_to_uri("/actor/$handle/basicFeed");
        $actor->save();
        return $actor;
    }

    protected function getUpdateWhereClause(\PDO $db): ?string {
        if (self::findWhere('uri = ?', [$this->uri]) != null)
            return 'uri = ' . $db->quote($this->uri);
        if (self::findWhere('id = ?', [$this->id]) != null)
            return "id = $this->id";
        return null;
    }

    public static function findLocalByHandle(string $handle): ?self {
        return self::findWhere('is_local = true AND handle = ?', [$handle]);
    }

    public static function findByWebfinger(string $acct, bool $autoSave = true, bool $forceRefetch = false): ?self {
        // normalise uri
        if (!str_starts_with($acct, 'acct:')) {
            if (str_starts_with($acct, '@')) {
                $acct = substr($acct, 1);
            }
            $acct = "acct:$acct";
        }

        // fetch it
        return ActorWebfinger::findByAcct($acct, $autoSave, $forceRefetch)->actor;
    }

    public static function findByRequestHeaders(): ?self {
        $instance = Instance::findByRequestHeaders();
        if ($instance == null || !isset($_SERVER['HTTP_X_PAWPUB_ACTOR']))
            return null;
        $uri = $_SERVER['HTTP_X_PAWPUB_ACTOR'];
        if (hostname_from_uri($uri) != $instance->domain)
            return null;
        return self::findByUri($uri);
    }

    public function rpcCall(string $method, array $args) {
        // $args = [Actor $actingAs]
        if (!$this->isLocal) {
            // trigger the same action on the remote server
            $endpoint = $this->endpoints->{$method} ?? null;
            if (!isset($endpoint)) {
                throw new RpcException("Actor `$this->uri` has no $method endpoint");
            }
            $result = send_request_authenticated($endpoint, method: 'POST', actingAs: $args[0]);
            if (!str_contains($result->headers[0], ' 20')) {
                throw new RpcException('remote call did not indicate success: ' . $result->headers[0]);
            }
        }

        // the actual logic
        switch ($method) {
            case 'follow':
                $status = $this->requestToFollow ? FollowRelationStatus::PENDING : FollowRelationStatus::ACTIVE;
                FollowRelation::create($args[0], $this, $status);
                return $status;

            case 'unfollow':
                FollowRelation::findByActors($args[0], $this)->remove();
                return;

            case 'acceptedFollow':
                $rel = FollowRelation::findByActors($this, $args[0]);
                $rel->status = FollowRelationStatus::ACTIVE;
                $rel->save();
                return;

            case 'rejectedFollow':
                FollowRelation::findByActors($this, $args[0])->remove();
                return;

            default:
                throw new \RuntimeException("behaviour for actor rpc method $method not (yet?) implemented");
        }
    }

    /**
     * Tries to follow (or send a follow request to) another actor
     * @param Actor $target the actor to follow
     * @return FollowRelationStatus PENDING if a request was sent or ACTIVE if the follow went through immediately
     */
    public function follow(self $target): FollowRelationStatus {
        return $target->rpcCall('follow', [$this]);
    }

    public function unfollow(self $target) {
        $target->rpcCall('unfollow', [$this]);
    }

    public function acceptPendingFollowFrom(self $initiator) {
        $initiator->rpcCall('acceptedFollow', [$this]);
    }

    public function rejectPendingFollowFrom(self $initiator) {
        $initiator->rpcCall('rejectedFollow', [$this]);
    }

    /**
     * @return Actor[] a list of actors that follow this actor (does not include pending follows)
     */
    public function findFollowers(): array {
        $relations = FollowRelation::findAllWithObject($this);
        $relations = array_filter($relations, function (FollowRelation $rel) {
            return $rel->status == FollowRelationStatus::ACTIVE;
        });
        return array_map(function (FollowRelation $rel) {
            return $rel->subject;
        }, $relations);
    }

    /**
     * @return Actor[] a list of actors that are followed by this actor (does not include pending follows)
     */
    public function findFollowees(): array {
        $relations = FollowRelation::findAllWithSubject($this);
        $relations = array_filter($relations, function (FollowRelation $rel) {
            return $rel->status == FollowRelationStatus::ACTIVE;
        });
        return array_map(function (FollowRelation $rel) {
            return $rel->object;
        }, $relations);
    }

    /**
     * @return Actor[] a list of actors that both follow and are followed by this actor
     */
    public function findMutualFollows(): array {
        $followers = $this->findFollowers();
        $followees = $this->findFollowees();
        return array_intersect($followers, $followees);
    }

    public function findHomeInstance(): Instance {
        return Instance::findByHostname(hostname_from_uri($this->uri));
    }

    protected function getRelevantServers(): array {
        $actors = array_unique(array_merge($this->findFollowers(), $this->findFollowees()));
        $instances = array_unique(array_map(function (Actor $actor) {
            return Instance::findByHostname(hostname_from_uri($actor->uri));
        }, $actors));
        return $instances;
    }

    public function getFullHandle(): string {
        return $this->handle . ($this->isLocal ? '' : '@' . hostname_from_uri($this->uri));
    }

    public function jsonSerialize(): array {
        if ($this->deleted) {
            return [
                'type' => 'tombstone',
                'self' => path_to_uri("/actor/$this->handle"),
                'previousType' => 'actor'
            ];
        }
        return [
            'type' => 'actor',
            'self' => path_to_uri("/actor/$this->handle"),
            'created' => $this->created?->format('c'),
            'modified' => $this->modified?->format('c'),
            'homepage' => path_to_uri("/@/$this->handle"),
            'handle' => $this->handle,
            'displayName' => $this->displayName,
            'avatar' => $this->avatar,
            'bio' => $this->bio,
            'pronouns' => $this->pronouns,
            'automated' => $this->automated,
            'requestToFollow' => $this->requestToFollow,
            'endpoints' => [
                'basicFeed' => path_to_uri("/actor/$this->handle/basicFeed"),
                'fullFeed' => path_to_uri("/actor/$this->handle/fullFeed"),
                'follow' => path_to_uri("/actor/$this->handle/follow"),
                'unfollow' => path_to_uri("/actor/$this->handle/unfollow"),
                'acceptedFollow' => path_to_uri("/actor/$this->handle/acceptedFollow"),
                'rejectedFollow' => path_to_uri("/actor/$this->handle/rejectedFollow"),
            ]
        ];
    }

    public function hydrate() {
        $this->endpoints = ActorEndpoints::findWhere('actor_id = ?', [$this->id]);
    }
}