Files
web-app-starter/lib/realtime.class.php

100 lines
2.8 KiB
PHP

<?php
class Realtime
{
static function enabled()
{
return (bool)cfg('realtime/enabled');
}
static function broker_url()
{
return rtrim((string)cfg('realtime/broker_url'), '/');
}
static function command_token()
{
return (string)cfg('realtime/command_token');
}
static function live_url($path = '/live/')
{
$path = '/'.ltrim((string)$path, '/');
$base = (string)cfg('realtime/live_url');
if($base !== '') return $base;
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'wss' : 'ws';
$host = first($_SERVER['HTTP_HOST'] ?? false, 'localhost');
return $scheme.'://'.$host.rtrim(url_root(), '/').$path;
}
static function command($commands)
{
if(!is_array($commands)) $commands = array($commands);
$url = self::broker_url();
if($url === '')
return array('result' => false, 'error' => 'realtime_broker_url_missing');
$payload = http_build_query(array(
'data' => json_encode(array_values($commands), JSON_UNESCAPED_SLASHES),
'token' => self::command_token(),
));
$headers = "Content-Type: application/x-www-form-urlencoded\r\n";
if(self::command_token() !== '')
$headers .= 'Authorization: Bearer '.self::command_token()."\r\n";
$context = stream_context_create(array('http' => array(
'method' => 'POST',
'header' => $headers,
'content' => $payload,
'timeout' => (float)first(cfg('realtime/timeout'), 2),
'ignore_errors' => true,
)));
$response = @file_get_contents($url, false, $context);
$status = self::response_status($http_response_header ?? array());
if($response === false)
return array('result' => false, 'error' => 'realtime_broker_unreachable', 'status' => $status);
$decoded = json_decode($response, true);
return array('result' => $status >= 200 && $status < 300, 'status' => $status, 'response' => $decoded, 'raw' => $response);
}
static function response_status($headers)
{
foreach((array)$headers as $header)
{
if(str_starts_with($header, 'HTTP/'))
{
$parts = explode(' ', $header);
return intval($parts[1] ?? 0);
}
}
return 0;
}
static function broadcast($message, $match = false)
{
$command = array('type' => 'send', 'message' => $message);
if($match) $command['match'] = $match;
return self::command(array($command));
}
static function session($data, $match = false)
{
$command = array('type' => 'session', 'data' => $data);
if($match) $command['match'] = $match;
return self::command(array($command));
}
static function close($match = false)
{
$command = array('type' => 'close');
if($match) $command['match'] = $match;
return self::command(array($command));
}
static function connections($match = false)
{
$command = array('type' => 'list');
if($match) $command['match'] = $match;
return self::command(array($command));
}
}