diff --git a/src/Channels/Channel.php b/src/Channels/Channel.php index 218baa0..7084b93 100644 --- a/src/Channels/Channel.php +++ b/src/Channels/Channel.php @@ -29,6 +29,13 @@ class Channel */ protected $connections = []; + /** + * The channel manager instance. + * + * @var \BlaxSoftware\LaravelWebSockets\Contracts\ChannelManager + */ + public $channelManager; + /** * Create a new instance. * diff --git a/src/Channels/OpenPresenceChannel.php b/src/Channels/OpenPresenceChannel.php new file mode 100644 index 0000000..01860a5 --- /dev/null +++ b/src/Channels/OpenPresenceChannel.php @@ -0,0 +1,98 @@ +channelManager + ->getLocalConnections() + ->then(function ($connections) use ($connection) { + $connection->send(json_encode([ + 'event' => 'presence.subscription_succeeded', + 'channel' => $this->getName(), + 'data' => [ + 'sockets' => collect($connections) + ->filter(fn($conn) => ($conn->remoteAddress && $conn->remoteAddress != '127.0.0.1')) + ->pluck('socketId')->toArray(), + 'count' => collect($connections) + ->filter(fn($conn) => ($conn->remoteAddress && $conn->remoteAddress != '127.0.0.1')) + ->count(), + ], + ])); + + $memberAddedPayload = [ + 'event' => 'presence.member_added', + 'channel' => $this->getName(), + 'data' => $connection->socketId, + ]; + + + if ($connection->remoteAddress && $connection->remoteAddress != '127.0.0.1') { + $this->broadcastToEveryoneExcept( + (object) $memberAddedPayload, + $connection->socketId, + $connection->app->id, + false + ); + } + }); + + return true; + } + + /** + * Unsubscribe connection from the channel. + * + * @param \Ratchet\ConnectionInterface $connection + * @return PromiseInterface + */ + public function unsubscribe(ConnectionInterface $connection): PromiseInterface + { + $truth = parent::unsubscribe($connection); + + + return $this->channelManager + ->getLocalConnections() + ->then(function ($connections) use ($connection) { + $memberRemovedPayload = [ + 'event' => 'presence:member_removed', + 'channel' => $this->getName(), + 'data' => [ + 'socket' => $connection->socketId, + ], + ]; + + if ($connection->remoteAddress && $connection->remoteAddress != '127.0.0.1') { + $this->broadcastToEveryoneExcept( + (object) $memberRemovedPayload, + $connection->socketId, + $connection->app->id, + false + ); + } + }) + ->then(function () use ($truth) { + return $truth; + }); + } +}