aboutsummaryrefslogtreecommitdiffhomepage
path: root/Digitigrade/Model/Interaction.php
blob: dd977fd1f22bc96652ba6a10b072eb7d465b7ea2 (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
<?php
namespace Digitigrade\Model;

use Digitigrade\Db;
use Digitigrade\Model\HomeTimelineItem;
use Digitigrade\Notification\Notifyable;
use Digitigrade\Timeline\ReasonReshared;
use Digitigrade\Timeline\TimelineItem;

class Interaction extends PushableModel implements Notifyable {
    public ?int $id;
    public string $uri;
    public \DateTimeImmutable $created;
    public ?\DateTimeImmutable $modified;
    public Actor $author;
    public InteractionKind $kind;
    public Note $target;
    public array $extensions = [];

    public static function create(Actor $author, InteractionKind $kind, Note $target) {
        $inter = new self();
        $inter->uri = "UNKNOWN";
        $inter->created = new \DateTimeImmutable();
        $inter->author = $author;
        $inter->kind = $kind;
        $inter->target = $target;

        $inter->save();
        $inter->uri = path_to_uri("/interaction/$inter->id");
        $inter->save();

        return $inter;
    }

    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;
    }

    protected function validate(): bool {
        // author has to be from the same instance as the interaction itself
        return hostname_from_uri($this->author->uri) == hostname_from_uri($this->uri);
    }

    protected function hydrate() {
        $this->extensions = $this->findExtensions();
    }

    protected function dehydrate() {
        $this->saveExtensions();
    }

    private function findExtensions() {
        $pdo = Db::getInstance()->getPdo();
        $stmt = $pdo->prepare('SELECT uri, data FROM interaction_extension WHERE interaction_id = ?');
        $stmt->execute([$this->id]);
        $items = [];
        while ($row = $stmt->fetch()) {
            $items[$row['uri']] = json_decode($row['data']);
        }
        return $items;
    }

    private function saveExtensions() {
        $pdo = Db::getInstance()->getPdo();
        foreach ($this->extensions as $uri => $obj) {
            $stmt = $pdo->prepare(
                'INSERT INTO interaction_extension(interaction_id, uri, data) VALUES (?, ?, ?) ' .
                'ON CONFLICT (interaction_id, uri) DO UPDATE SET data = EXCLUDED.data'
            );
            $stmt->execute([$this->id, $uri, json_encode($obj)]);
        }
    }

    public static function findAllWithAuthor(Actor $author): array {
        return self::findAllWhere('author = ?', [$author->id]);
    }

    public static function findAllWithTarget(Note $target): array {
        return self::findAllWhere('target = ?', [$target->id]);
    }

    protected function getRelevantServers(): array {
        $instances = array_map(
            fn(Actor $actor) => $actor->isLocal ? null : $actor->findHomeInstance(),
            $this->author->findFollowers()
        );
        if (!$this->target->author->isLocal)
            $instances[] = $this->target->author->findHomeInstance();
        return array_unique($instances);
    }

    public function getNotificationTitle(): string {
        return sprintf(__('notifications.interaction.' . $this->kind->value . '.title'), $this->author->displayName);
    }
    public function getNotificationTitleLink(): ?string {
        return $this->target->getLocalUiHref();
    }
    public function getNotificationBody(): ?string {
        return isset($this->target->summary) ? ('[' . $this->target->summary . ']') : $this->target->plainContent;
    }
    public function getNotificationImageUrl(): ?string {
        return $this->author->avatar ?? '/static/default-avatar.png';
    }
    public function getNotificationImageLink(): ?string {
        return $this->author->getLocalUiHref();
    }

    public function toJsonReference(): mixed {
        return $this->id;
    }

    public static function fromJsonReference(mixed $reference): ?self {
        return self::find($reference);
    }

    public function processTimelineAdditions() {
        // basically, if this is a reshare, we need to put a home timeline item
        // for all followers who can see the shared note
        if ($this->kind != InteractionKind::RESHARE)
            return;
        $reason = new ReasonReshared($this->author);
        $item = new TimelineItem($this->target, $reason);

        foreach (array_merge($this->author->findFollowers(), [$this->author]) as $actor) {
            if (!$actor->isLocal)
                return;
            $user = UserAccount::findByLinkedActor($actor);
            if (!$this->target->isViewableBy($user))
                return;

            HomeTimelineItem::fromTimelineItem($item, $user)->save();
        }
    }

    public function processNotifications() {
        if (!$this->target->author->isLocal || $this->author == $this->target->author) {
            return;
        }
        $recipient = UserAccount::findByLinkedActor($this->target->author);
        Notification::fromNotifyable($this, $recipient)->send();
    }

    public function jsonSerialize(): array {
        if ($this->deleted) {
            return [
                'type' => 'tombstone',
                'self' => path_to_uri("/interaction/$this->id"),
                'previousType' => 'interaction'
            ];
        }
        return [
            'type' => 'interaction',
            'self' => path_to_uri("/interaction/$this->id"),
            'created' => $this->created->format('c'),
            'modified' => $this->modified?->format('c'),
            'author' => $this->author->uri,
            'kind' => $this->kind->value,
            'target' => $this->target->uri,
            //'extensions' => []
        ];
    }
}