Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions src/Civ13/GameServer.php
Original file line number Diff line number Diff line change
Expand Up @@ -853,8 +853,9 @@ public function createCurrentRoundEmbedMessageBuilder(): ?MessageBuilder
$embed->addFieldValues('Season', $data[10], true);
}
$this->addRosterField($embed);
$players = PlayerEmbedKeys::withoutGuests(array_keys($round['players'] ?? []));
$embed->addFieldValues(
'Participating Players ('.count($players = array_keys($round['players'])).')',
'Participating Players ('.count($players).')',
$players
? (strlen($participating_players = implode(', ', $players)) <= 1024
? $participating_players
Expand Down Expand Up @@ -2237,7 +2238,7 @@ public function generateServerstatusEmbed(): ?Embed
$this->addRosterField($embed);
} elseif (isset($data['ckey_list'])) { // Player list
$players = explode('&', $data['ckey_list']);
$players = array_filter(array_map(fn ($player) => Civ13::sanitizeInput($player), $players));
$players = PlayerEmbedKeys::withoutGuests(array_filter(array_map(fn ($player) => Civ13::sanitizeInput($player), $players)));
if (! $players_list = implode(', ', $players)) {
$players_list = 'N/A';
}
Expand Down Expand Up @@ -2342,12 +2343,14 @@ public static function explodeServerdata(string $data): array
/** A short embed with this server's URL, host and current player list. */
public function toEmbed(): Embed
{
$players = PlayerEmbedKeys::withoutGuests($this->players);

return $this->civ13->createEmbed()
->setTitle($this->name)
->addFieldValues($this->engine === 'opendream' ? 'OpenDream gameplay endpoint' : 'Server URL', $this->engine === 'opendream' ? "{$this->ip}:{$this->port}" : "byond://{$this->ip}:{$this->port}", false)
->addFieldValues('Host', $this->displayHost(), true)
->addFieldValues('Health', 'Unknown (no local heartbeat evidence)', true)
->addFieldValues('Players (cached, unverified)', empty($this->players) ? 'N/A' : implode(', ', $this->players), true);
->addFieldValues('Players (cached, unverified)', $players ? implode(', ', $players) : 'N/A', true);
}
// Magic Methods
/**
Expand Down
14 changes: 8 additions & 6 deletions src/Civ13/MessageCommand/Commands/GetRound.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

use Civ13\Civ13;
use Civ13\MessageCommand\Civ13MessageCommand;
use Civ13\PlayerEmbedKeys;
use Discord\Builders\Components\ActionRow;
use Discord\Builders\Components\Button;
use Discord\Builders\MessageBuilder;
Expand Down Expand Up @@ -118,12 +119,13 @@ protected function createEmbed(string|int $server, array $round, bool $high_staf
->addFieldValues('Start', $round['start'] ?? 'Unknown', true)
->addFieldValues('End', $round['end'] ?? 'Ongoing/Unknown', true);
$round['players'] = is_array($round['players'] ?? null) ? $round['players'] : []; // A round recorded only as interrupted has no player list
if (($players = implode(', ', array_keys($round['players']))) && strlen($players) <= 1024) {
$embed->addFieldValues('Players ('.count($round['players']).')', $players);
} else {
$embed->addFieldValues('Players ('.count($round['players']).')', 'Either none or too many to list!');
}
if ($discord_ids = array_filter(array_map(fn ($c) => ($item = $this->civ13->verifier->get('ss13', $c)) ? "<@{$item['discord']}>" : null, array_keys($round['players'])))) {
$players = PlayerEmbedKeys::withoutGuests(array_keys($round['players']));
$players_list = implode(', ', $players);
$embed->addFieldValues(
'Players ('.count($players).')',
$players_list !== '' && strlen($players_list) <= 1024 ? $players_list : 'Either none or too many to list!'
);
if ($discord_ids = array_filter(array_map(fn ($c) => ($item = $this->civ13->verifier->get('ss13', $c)) ? "<@{$item['discord']}>" : null, $players))) {
if (strlen($verified_players = implode(', ', $discord_ids)) <= 1024) {
$embed->addFieldValues('Verified Players ('.count($discord_ids).')', $verified_players);
} else {
Expand Down
23 changes: 23 additions & 0 deletions src/Civ13/PlayerEmbedKeys.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

declare(strict_types=1);

namespace Civ13;

/** Filters BYOND guest identities at the embed boundary, not from player records. */
final class PlayerEmbedKeys
{
/**
* BYOND supplies Guest-123 or Guest-W123; canonical ckeys omit the hyphen.
* Keep names that merely start with "guest", such as GuestBuilder.
*
* @param array<array-key, string|int> $keys
* @return list<string|int>
*/
public static function withoutGuests(array $keys): array
{
return array_values(array_filter($keys, static fn (string|int $key): bool =>
preg_match('/\Aguest-?w?[0-9]+\z/i', trim((string) $key)) !== 1
));
}
}
12 changes: 7 additions & 5 deletions src/Civ13/RegionRoster.php
Original file line number Diff line number Diff line change
Expand Up @@ -114,15 +114,17 @@ public function total(): int
*/
public function field(bool $grouped): array
{
$title = 'Online Players ('.$this->total().')';
if (! $this->regions) {
// Leave observations and operational headcounts alone; hide only from the embed.
$regions = array_filter(array_map(PlayerEmbedKeys::withoutGuests(...), $this->regions));
$title = 'Online Players ('.array_sum(array_map('count', $regions)).')';
if (! $regions) {
return [$title, 'None'];
}
if (! $grouped && count($this->regions) === 1) {
return [$title, self::fit(implode(', ', reset($this->regions)))];
if (! $grouped && count($regions) === 1) {
return [$title, self::fit(implode(', ', reset($regions)))];
}
$lines = $counts = [];
foreach ($this->regions as $region => $ckeys) {
foreach ($regions as $region => $ckeys) {
$label = $region === self::TRANSIT ? '*'.self::TRANSIT.'*' : '**'.self::escape($region).'**';
$lines[] = $label.' ('.count($ckeys).'): '.implode(', ', $ckeys);
$counts[] = $label.' ('.count($ckeys).')';
Expand Down
12 changes: 12 additions & 0 deletions tests/local/command-fixes.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,11 @@ public function react($emoticon): PromiseInterface { $this->reactions[] = $emoti
final class CommandVerifier extends \Civ13\Verifier {
public array $items = [];
public array $joined = [];
public array $roundReads = [];
public function get(string $discrim, $key): mixed {
$this->roundReads[] = $key;
return $this->items[$key] ?? null;
}
public function getVerifiedItem(Member|User|array|string $input): ?array { return is_string($input) ? ($this->items[$input] ?? null) : ($input instanceof User ? ($this->items['author'] ?? null) : null); }
public function getVerified(bool $initialize = true): \Discord\Helpers\CollectionInterface { return $this->verified; }
public function joinRoles(Member $member, bool $send_welcome_message = true): ?PromiseInterface { $this->joined[] = $member->id; return null; }
Expand Down Expand Up @@ -167,6 +172,13 @@ function run(object $command, string $name, string $content, array $extra = []):
$command = new Commands\GetRound($bot);
$embed = (new ReflectionMethod($command, 'createEmbed'))->invoke($command, 'Fixture', ['interrupted' => true], true, 'someone');
check($embed->captured['Players (0)'] === 'Either none or too many to list!' && ! isset($embed->captured['Player Data (someone)']), 'Round without players was not handled');
$verifier->items['guestbuilder'] = ['discord' => '123'];
$verifier->items['guest3830181121'] = ['discord' => '456'];
$verifier->roundReads = [];
$round = ['players' => ['guest3830181121' => [], 'Guest-W97' => [], 'guestbuilder' => []]];
$embed = (new ReflectionMethod($command, 'createEmbed'))->invoke($command, 'Fixture', $round, false, null);
check(($embed->captured['Players (1)'] ?? null) === 'guestbuilder', 'Historical round lists or counts a guest');
check(($embed->captured['Verified Players (1)'] ?? null) === '<@123>' && $verifier->roundReads === ['guestbuilder'], 'Historical round resolved a guest to a Discord mention');
$embed = inert(CommandEmbed::class);
$builder = Civ13::createBuilder(true);
(new ReflectionMethod($command, 'addStaffDetails'))->invokeArgs($command, [&$embed, &$builder, ['server_key' => 'fixture']]);
Expand Down
25 changes: 25 additions & 0 deletions tests/local/heartbeat-integration.php
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,31 @@ function checkRoundStartTimestamps(): void {
$playWire = json_decode(json_encode($server->createCurrentRoundEmbedMessageBuilder(), JSON_THROW_ON_ERROR), true);
check($playWire['components'][0]['components'][0]['label'] === 'Log', 'Existing Log button lost');
check($playWire['components'][1]['components'][0]['url'] === 'https://join.example.org/nomads/play', 'Round Play button wrong');
$verifier = new class extends Civ13\Verifier {
public array $reads = [];
public function __construct() {}
public function get(string $discrim, $key): mixed {
$this->reads[] = $key;
return ['discord' => '123'];
}
};
$server->civ13->verifier = $verifier;
$server->rounds['fixture']['players'] = ['guest3830181121' => [], 'Guest-W987' => [], 'guestbuilder' => []];
$before = $server->rounds;
$roundWire = json_decode(json_encode($server->createCurrentRoundEmbedMessageBuilder(), JSON_THROW_ON_ERROR), true);
$roundFields = array_column($roundWire['embeds'][0]['fields'], 'value', 'name');
check(($roundFields['Participating Players (1)'] ?? null) === 'guestbuilder', 'Round participation displayed or counted guests');
check(($roundFields['Verified Players (1)'] ?? null) === '<@123>' && $verifier->reads === ['guestbuilder'], 'Round verified guests or queried the verifier for them');
check($server->rounds === $before, 'Filtering changed round records');
unset($server->rounds['fixture']['players']['guestbuilder']);
$roundWire = json_decode(json_encode($server->createCurrentRoundEmbedMessageBuilder(), JSON_THROW_ON_ERROR), true);
$roundFields = array_column($roundWire['embeds'][0]['fields'], 'value', 'name');
check(($roundFields['Participating Players (0)'] ?? null) === 'None' && $verifier->reads === ['guestbuilder'], 'Guests-only participation was not empty');
$server->rounds['fixture']['players'] = [];
file_put_contents($path, record('201', 'player&Guest-7', true));
$active = fields($server->generateServerstatusEmbed());
check(($active['Players (1)'] ?? null) === 'player' && $server->players === ['player', 'guest7'], 'Standalone embed did not exclude guests without altering cached observations');
check(fields($server->toEmbed())['Players (cached, unverified)'] === 'player', 'Cached status embed displayed guests');
$server->civ13->enabled_gameservers = [$server];
$server->civ13->civ14_enabled_gameservers = [];
$aggregate = json_decode(json_encode($server->civ13->createServerstatusEmbed(), JSON_THROW_ON_ERROR), true);
Expand Down
11 changes: 11 additions & 0 deletions tests/local/heartbeat-roster.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
require __DIR__.'/../../src/Civ13/ServerHeartbeat.php';
require __DIR__.'/../../src/Civ13/PlayercountChannel.php';
require __DIR__.'/../../src/Civ13/RegionRoster.php';
require __DIR__.'/../../src/Civ13/PlayerEmbedKeys.php';

use Civ13\PlayercountChannel;
use Civ13\RegionRoster;
Expand Down Expand Up @@ -66,4 +67,14 @@ function check(bool $ok, string $message): void
$many->observe([$up('Gaia', ...array_slice($names, 0, 40)), $up('Europe', ...array_slice($names, 40))], 0.0);
check($many->field(true) === ['Online Players (80)', "**Gaia** (40)\n**Europe** (40)"], 'Oversized roster was not reduced to counts');

// Guest sessions contribute to operational headcounts but never to an embed field.
$guests = new RegionRoster();
$worlds = $guests->observe([$up('Gaia', 'guest3830181121', 'guestbuilder'), $up('Europe', 'Guest-W42')], 0.0);
check($guests->field(true) === ['Online Players (1)', '**Gaia** (1): guestbuilder'], 'Group guest keys leaked or inflated the embed count');
check(PlayercountChannel::label($worlds) === '3' && $guests->total() === 3, 'Guest filtering changed operational counts');
$guests->observe([$up('Gaia', 'Guest-123')], 5.0); // Previous real player still in transit.
check($guests->field(true) === ['Online Players (1)', '*Between regions* (1): guestbuilder'], 'Guest keys leaked from the transit roster');
$guests->observe([$up('Gaia', 'Guest-123')], 45.0);
check($guests->field(false) === ['Online Players (0)', 'None'], 'A guests-only field was not empty');

echo "Region roster contracts passed\n";
Loading