appwrite/src/Appwrite/Event/Realtime.php

106 lines
2.5 KiB
PHP
Raw Normal View History

2024-11-04 15:05:54 +00:00
<?php
namespace Appwrite\Event;
use Appwrite\Messaging\Adapter\Realtime as RealtimeAdapter;
use Utopia\Database\Document;
class Realtime extends Event
{
2025-02-27 07:23:13 +00:00
protected array $subscribers = [];
2025-02-18 14:04:59 +00:00
2024-11-04 15:05:54 +00:00
public function __construct()
{
}
2025-02-18 14:04:59 +00:00
/**
* Get Realtime payload for this event.
*
* @return array
*/
2024-11-04 15:05:54 +00:00
public function getRealtimePayload(): array
{
$payload = [];
foreach ($this->payload as $key => $value) {
if (!isset($this->sensitive[$key])) {
$payload[$key] = $value;
}
}
return $payload;
}
2025-02-18 14:04:59 +00:00
/**
2025-02-27 07:23:13 +00:00
* Set subscribers for this realtime event.
2025-02-18 14:04:59 +00:00
*
2025-02-27 07:23:13 +00:00
* @param array $subscribers
2025-02-18 14:04:59 +00:00
* @return array
*/
2025-02-27 07:23:13 +00:00
public function setSubscribers(array $subscribers): self
2025-02-18 14:04:59 +00:00
{
2025-02-27 07:23:13 +00:00
$this->subscribers = $subscribers;
2025-02-18 14:04:59 +00:00
return $this;
}
/**
2025-02-27 07:23:13 +00:00
* Get subscribers for this realtime event.
2025-02-18 14:04:59 +00:00
*
* @return array
*/
2025-02-27 07:23:13 +00:00
public function getSubscribers(): array
2025-02-18 14:04:59 +00:00
{
2025-02-27 07:23:13 +00:00
return $this->subscribers;
2025-02-18 14:04:59 +00:00
}
2024-11-04 15:05:54 +00:00
/**
* Execute Event.
*
* @return string|bool
* @throws InvalidArgumentException
*/
public function trigger(): string|bool
{
2024-11-08 20:55:53 +00:00
if ($this->paused || empty($this->event)) {
2024-11-04 15:05:54 +00:00
return false;
}
$allEvents = Event::generateEvents($this->getEvent(), $this->getParams());
$payload = new Document($this->getPayload());
$db = $this->getContext('database');
$collection = $this->getContext('collection');
$bucket = $this->getContext('bucket');
$target = RealtimeAdapter::fromPayload(
// Pass first, most verbose event pattern
event: $allEvents[0],
payload: $payload,
project: $this->getProject(),
database: $db,
collection: $collection,
bucket: $bucket,
);
2025-02-27 07:23:13 +00:00
$projectIds = !empty($this->getSubscribers())
? $this->getSubscribers()
2025-02-26 16:24:05 +00:00
: [$target['projectId'] ?? $this->getProject()->getId()];
2025-02-26 16:50:12 +00:00
foreach ($projectIds as $projectId) {
RealtimeAdapter::send(
projectId: $projectId,
payload: $this->getRealtimePayload(),
events: $allEvents,
channels: $target['channels'],
roles: $target['roles'],
options: [
'permissionsChanged' => $target['permissionsChanged'],
'userId' => $this->getParam('userId')
]
);
}
2024-11-04 15:05:54 +00:00
return true;
}
}