Files
boursecu_server/app/Services/WebsocketBroadcastService.php
T

107 lines
3.0 KiB
PHP
Raw Normal View History

2026-06-17 12:12:35 +03:30
<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class WebsocketBroadcastService
{
private const DEFAULT_TRIGGER_PATH = '/prc/api/trigger-update';
public function triggerBaseUrl(): ?string
{
2026-06-17 21:26:08 +03:30
$config = app(ConfigService::class);
$port = $config->getInt('wss_http_port', 0);
if ($port > 0) {
$host = trim($config->getString('wss_trigger_host', '127.0.0.1'));
if ($host === '') {
$host = '127.0.0.1';
}
$scheme = trim($config->getString('wss_trigger_scheme', 'http'));
if ($scheme === '') {
$scheme = 'http';
}
return rtrim("{$scheme}://{$host}:{$port}", '/');
2026-06-17 12:12:35 +03:30
}
2026-06-17 21:26:08 +03:30
// سازگاری با دیپلوی‌های قدیمی (wss_link کامل)
$legacyLink = trim($config->getString('wss_link', ''));
if ($legacyLink !== '') {
return rtrim($legacyLink, '/');
2026-06-17 12:12:35 +03:30
}
return null;
}
2026-06-17 21:26:08 +03:30
/** پورت WebSocket داخلی — برای دیپلوی لایت‌اسپید/docker (همان پروژه) */
public function socketPort(): int
{
return app(ConfigService::class)->getInt('wss_socket_port', 0);
}
2026-06-17 12:12:35 +03:30
public function triggerPath(): string
{
$path = trim((string) app(ConfigService::class)->getString('wss_trigger_path', ''));
return $path !== '' ? $path : self::DEFAULT_TRIGGER_PATH;
}
public function isEnabled(): bool
{
if (! app(ConfigService::class)->getBool('wss_enabled', true)) {
return false;
}
return $this->triggerBaseUrl() !== null;
}
/**
* @param array<string, mixed> $payload
*/
public function sendEvent(string $trigger, array $payload = []): void
{
if (! $this->isEnabled()) {
return;
}
$baseUrl = $this->triggerBaseUrl();
if ($baseUrl === null) {
return;
}
$body = array_merge($payload, ['trigger' => $trigger]);
2026-07-21 13:25:18 +03:30
$host = app(ConfigService::class)->resolvePublicHost();
2026-06-17 12:12:35 +03:30
if ($host !== '') {
$body['host'] = $host;
}
$url = $baseUrl.$this->triggerPath();
try {
2026-06-18 15:25:49 +03:30
$response = Http::timeout(3)
2026-06-17 12:12:35 +03:30
->withHeaders(['Content-Type' => 'application/json'])
2026-06-23 22:05:47 +03:30
->withOptions(\App\Http\Controllers\Controller::httpClientOptions())
2026-06-17 12:12:35 +03:30
->post($url, $body);
2026-06-18 15:25:49 +03:30
if (! $response->successful()) {
Log::warning('Websocket broadcast rejected', [
'trigger' => $trigger,
'url' => $url,
'status' => $response->status(),
'body' => $response->body(),
]);
}
2026-06-17 12:12:35 +03:30
} catch (\Throwable $e) {
Log::warning('Websocket broadcast failed', [
'trigger' => $trigger,
'url' => $url,
'message' => $e->getMessage(),
]);
}
}
}