nie mam sił

This commit is contained in:
GitProtogen
2026-03-06 13:28:26 +01:00
parent 90254a43bb
commit 14359b9de1
+51 -11
View File
@@ -19,34 +19,74 @@ use \ComCen\Security\TokenHandler;
class WebSocketServer implements MessageComponentInterface
{
private array $connectedUsers = [];
private $connectionsData = [];
private function isSameConnection(ConnectionInterface $connection1, ConnectionInterface $connection2): bool
{
return $connection1->resourceId === $connection2->resourceId;
}
private function getConnectionIndex(ConnectionInterface $connection): int | null
{
foreach ($this->connectionsData as $i => $connectionData) {
if ($this->isSameConnection($connection, $connectionData["connection"])) {
return $i;
}
}
return null;
}
private function sendToAllAuthenticated(string $username, string $msg): void
{
foreach ($this->connectionsData as $connectionData) {
if ($connectionData["username"] !== $username) {
$connectionData["connection"]->send("{\"sender\": \"{$username}\",\"msg\": \"{$msg}\"");
}
}
}
private function deleteGivenId(int $id): void
{
foreach ($this->connectedUsers as $key => $conn) {
if ($conn->resourceId === $id) {
unset($this->connectedUsers[$key]);
foreach ($this->connectionsData as $i => $connectionData) {
if ($connectionData["connection"]->resourceId === $id) {
array_splice($this->connectionsData, $i, 1);
return;
}
}
}
public function onOpen(ConnectionInterface $conn): void
{
$this->connectedUsers[] = $conn;
$conn->send("Connected users: " . count($this->connectedUsers) . " (One is you)");
$this->connectionsData[] = [
"connection" => $conn,
"username" => null
];
echo "New connection: {$conn->resourceId}\n";
}
public function onMessage(ConnectionInterface $from, $msg): void
{
$decodedMsg = json_decode($msg, true);
if (!$decodedMsg) $from->send("not or empty json");
if (!TokenHandler::getTokenOwnership($decodedMsg['token'])) $from->send("invalid credentials");
foreach ($this->connectedUsers as $conn) {
$conn->send($decodedMsg["message"]);
if (!$decodedMsg) {
$from->send("not or empty json");
return;
}
$index = $this->getConnectionIndex($from);
if ($index === null) return;
$from->send("Message sent to others");
if ($this->connectionsData[$index]["username"]) {
$this->sendToAllAuthenticated($this->connectionsData[$index]["username"], $decodedMsg["message"]);
} else {
$token = $decodedMsg["token"] ?? null;
if ($token) {
$tokenUser = TokenHandler::getTokenOwnership($token);
if ($tokenUser) {
$this->connectionsData[$index]["username"] = $tokenUser;
$from->send("authenticated");
} else {
$from->send("invalid token");
}
} else {
$from->send("not authenticated");
}
}
}
public function onClose(ConnectionInterface $conn): void