ogcore/src/Service/UDS/UDSClient.php

216 lines
7.8 KiB
PHP

<?php
namespace App\Service\UDS;
use AllowDynamicProperties;
use App\Entity\OrganizationalUnit;
use App\Model\ClientStatus;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpClient\Exception\TransportException;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
#[AllowDynamicProperties]
class UDSClient
{
private string $token;
private string $scrambler;
private string $udsAPIurl;
private string $udsAuthLogin;
private string $udsAuthUsername;
private string $udsAuthPassword;
public function __construct(
private HttpClientInterface $httpClient,
private readonly EntityManagerInterface $entityManager,
private readonly LoggerInterface $logger,
private readonly KernelInterface $kernel,
)
{
$envFile = $this->kernel->getProjectDir() . DIRECTORY_SEPARATOR . 'env.json';
if (!is_file($envFile)) {
throw new \RuntimeException('Configuration file not found: ' . $envFile);
}
$config = json_decode(file_get_contents($envFile), true);
$vars = $config['vars'] ?? [];
$this->udsAPIurl = $vars['UDS_URL'] ?? throw new \RuntimeException('UDS_URL not set in env.json');
$this->udsAuthLogin = $vars['UDS_AUTH_LOGIN'] ?? throw new \RuntimeException('UDS_AUTH_LOGIN not set in env.json');
$this->udsAuthUsername = $vars['UDS_AUTH_USERNAME'] ?? throw new \RuntimeException('UDS_AUTH_USERNAME not set in env.json');
$this->udsAuthPassword = $vars['UDS_AUTH_PASSWORD'] ?? throw new \RuntimeException('UDS_AUTH_PASSWORD not set in env.json');
}
/**
* @throws TransportExceptionInterface
*/
public function __invoke(): array
{
$this->login();
$servicePools = $this->getServicePools();
$results = [];
foreach ($servicePools as $servicePool) {
$servicePoolInfo = $this->getServicePool($servicePool['provider_id'], $servicePool['service_id']);
if (!$servicePoolInfo) {
continue;
}
$classroom = $servicePoolInfo['lab'];
$maxAvailableSeats = $this->getMaxAvailableSeats($classroom);
$servicePool['max_srvs'] = $maxAvailableSeats;
$servicePool['osmanager_id'] = null;
$response = $this->httpClient->request('PUT', $this->udsAPIurl . 'servicespools/' . $servicePool['id'], [
'verify_host' => false,
'headers' => [
'X-Auth-Token' => $this->token,
'Content-Type' => 'application/json',
'Scrambler' => $this->scrambler
],
'body' => json_encode($servicePool)
]);
$results[] = json_decode($response->getContent(false), true);
}
return $results;
}
/**
* @throws TransportExceptionInterface
*/
public function login(): void
{
try {
$response = $this->httpClient->request('POST', $this->udsAPIurl . 'auth/login', [
'verify_host' => false,
'headers' => [
'Content-Type' => 'application/json'
],
'json' => [
'auth' => $this->udsAuthLogin,
'username' => $this->udsAuthUsername,
'password' => $this->udsAuthPassword
]
]);
$statusCode = $response->getStatusCode();
$data = json_decode($response->getContent(false), true);
if ($statusCode !== 200 || empty($data['token'])) {
$this->logger->error('UDS login failed', [
'status_code' => $statusCode,
'response' => $data,
'uds_url' => $this->udsAPIurl,
'uds_auth' => $this->udsAuthLogin,
'uds_username' => $this->udsAuthUsername,
]);
throw new \RuntimeException('UDS login failed with status ' . $statusCode);
}
$this->token = $data['token'];
$this->scrambler = $data['scrambler'];
} catch (TransportExceptionInterface $e) {
$this->logger->error('UDS login transport error', [
'message' => $e->getMessage(),
'uds_url' => $this->udsAPIurl,
]);
throw new TransportException('Error while logging in to UDS: ' . $e->getMessage(), 0, $e);
} catch (ClientExceptionInterface|ServerExceptionInterface|RedirectionExceptionInterface $e) {
$this->logger->error('UDS login HTTP error', [
'message' => $e->getMessage(),
'uds_url' => $this->udsAPIurl,
]);
throw new \RuntimeException('UDS login HTTP error: ' . $e->getMessage(), 0, $e);
}
}
/**
* @throws TransportExceptionInterface
*/
public function getServicePools(): array
{
try {
$response = $this->httpClient->request('GET', $this->udsAPIurl . '/servicespools/overview', [
'verify_host' => false,
'headers' => [
'X-Auth-Token' => $this->token,
'Content-Type' => 'application/json',
'Scrambler' => $this->scrambler
]
]);
return json_decode($response->getContent(), true);
} catch (TransportExceptionInterface $e) {
throw new TransportException('Error while fetching service pools');
} catch (ClientExceptionInterface|ServerExceptionInterface|RedirectionExceptionInterface $e) {
}
}
/**
* @throws TransportExceptionInterface
*/
public function getServicePool(string $providerId, string $serviceId): ?array
{
try {
$response = $this->httpClient->request('GET', $this->udsAPIurl . 'providers/' . $providerId .'/services/'. $serviceId, [
'verify_host' => false,
'headers' => [
'X-Auth-Token' => $this->token,
'Content-Type' => 'application/json',
'Scrambler' => $this->scrambler
]
]);
return json_decode($response->getContent(), true);
} catch (TransportExceptionInterface $e) {
throw new TransportException('Error while fetching service pool');
} catch (ClientExceptionInterface|ServerExceptionInterface|RedirectionExceptionInterface $e) {
}
return null;
}
public function getMaxAvailableSeats(int $organizationalUnitId): int
{
$organizationalUnit = $this->entityManager->getRepository(OrganizationalUnit::class)->findOneBy(['id' => $organizationalUnitId]);
if (!$organizationalUnit) {
return 0;
}
$remoteCalendar = $organizationalUnit->getRemoteCalendar();
if (!$remoteCalendar || !$remoteCalendar->isAvailable()) {
return 0;
}
$totalAvailableClients = 0;
foreach ($organizationalUnit->getClients() as $client) {
if ($client->isMaintenance()) {
continue;
}
$status = $client->getStatus();
$clientAvailable = in_array($status, [ClientStatus::OG_LIVE, ClientStatus::WINDOWS, ClientStatus::LINUX]);
$totalAvailableClients += $clientAvailable ? 1 : 0;
}
return $totalAvailableClients;
}
}