доп фукнции апи
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class LauncherRealmService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly RealmStatusProbe $statusProbe,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, array<string, bool|float|int|string>>
|
||||
*/
|
||||
public function realms(): Collection
|
||||
{
|
||||
$cacheSeconds = max(0, (int) config('moonwell.launcher.realm_status_cache', 15));
|
||||
|
||||
if ($cacheSeconds === 0) {
|
||||
return $this->loadRealms();
|
||||
}
|
||||
|
||||
return Cache::remember(
|
||||
'launcher.realm-status',
|
||||
now()->addSeconds($cacheSeconds),
|
||||
fn (): Collection => $this->loadRealms(),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, array<string, bool|float|int|string>>
|
||||
*/
|
||||
private function loadRealms(): Collection
|
||||
{
|
||||
return DB::connection(config('moonwell.auth_connection'))
|
||||
->table('realmlist')
|
||||
->orderBy('id')
|
||||
->get([
|
||||
'id',
|
||||
'name',
|
||||
'address',
|
||||
'port',
|
||||
'icon',
|
||||
'flag',
|
||||
'timezone',
|
||||
'population',
|
||||
])
|
||||
->map(function (object $realm): array {
|
||||
$probeAddress = trim((string) config('moonwell.launcher.realm_status_host'));
|
||||
$online = $this->statusProbe->isOnline(
|
||||
$probeAddress !== '' ? $probeAddress : (string) $realm->address,
|
||||
(int) $realm->port,
|
||||
);
|
||||
|
||||
return [
|
||||
'id' => (int) $realm->id,
|
||||
'name' => (string) $realm->name,
|
||||
'address' => (string) $realm->address,
|
||||
'port' => (int) $realm->port,
|
||||
'icon' => (int) $realm->icon,
|
||||
'flag' => (int) $realm->flag,
|
||||
'timezone' => (int) $realm->timezone,
|
||||
'population' => (float) $realm->population,
|
||||
'online' => $online,
|
||||
'status' => $online ? 'online' : 'offline',
|
||||
];
|
||||
})
|
||||
->values();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
class RealmStatusProbe
|
||||
{
|
||||
public function isOnline(string $address, int $port): bool
|
||||
{
|
||||
if ($address === '' || $port < 1 || $port > 65535) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$host = str_contains($address, ':') && ! str_starts_with($address, '[')
|
||||
? '['.$address.']'
|
||||
: $address;
|
||||
$timeout = max(0.1, min(3.0, (float) config('moonwell.launcher.realm_status_timeout', 0.5)));
|
||||
$socket = @stream_socket_client(
|
||||
'tcp://'.$host.':'.$port,
|
||||
$errorCode,
|
||||
$errorMessage,
|
||||
$timeout,
|
||||
STREAM_CLIENT_CONNECT,
|
||||
);
|
||||
|
||||
if ($socket === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
fclose($socket);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user