Skip to content
Merged
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
6 changes: 6 additions & 0 deletions .github/workflows/status-heartbeat.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ on:
- 'src/Civ13/PortableProfile.php'
- 'src/Civ13/RegionRoster.php'
- 'tests/local/heartbeat*.php'
- 'src/Civ13/PlayerActivityTotals.php'
- 'src/Civ13/MessageCommand/Commands/Civ13GameServerActivity.php'
- 'tests/local/player-activity-totals.php'
- '.github/workflows/status-heartbeat.yml'

permissions:
Expand Down Expand Up @@ -43,5 +46,8 @@ jobs:
- run: php tests/local/heartbeat-playercount.php
- run: php -l src/Civ13/RegionRoster.php
- run: php tests/local/heartbeat-roster.php
- run: php -l src/Civ13/PlayerActivityTotals.php
- run: php -l src/Civ13/MessageCommand/Commands/Civ13GameServerActivity.php
- run: php tests/local/player-activity-totals.php
- run: php -l src/Civ13/ServerPlayLink.php
- run: php tests/local/play-link.php
5 changes: 5 additions & 0 deletions docs/shard-group.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ DreamDaemon itself.
| `<key>restart`, panel Restart, `/restart_server` | `restart --region=<id>`, announced in OOC first |
| `<key>update` | `update --region=<id>` |
| `<key>hoststatus` | `status --region=<id>`: region name, port, world ready, players, last action, map |
| `<key>activity` (Ambassador, Admin) | none: reads `<group root>/player-activity-weekly.json` from the server's `region_group` |

`<key>activity` shows the group's weekly player activity totals (active players,
new players, sessions, deaths, trips, hours per region). The Civ13 host writes the
file beside its activity database; it holds no player names, research or recipe ids.

start, stop, restart and update are accepted within seconds and finish in the
script's detached worker; `hoststatus` shows progress. The bot runs as the same
Expand Down
2 changes: 2 additions & 0 deletions src/Civ13/GameServer.php
Original file line number Diff line number Diff line change
Expand Up @@ -1111,6 +1111,8 @@ public function HostStatus(): PromiseInterface
$control = $this->gaiaHost;
return $control->request('status')->then(static fn (array $status): string => $control::describe($status));
}
/** The shard group file (Civ13 scripts/shard-group) this server heads, or '' when it has none. */
public function regionGroupFile(): string { return $this->regionGroupFile; }
public function hasGaiaHost(): bool { return $this->gaiaHost !== null; }
public function hasSystemdUnit(): bool { return $this->systemdUnit !== null; }
/** Accepted means systemd queued the job; hoststatus shows the unit's state. */
Expand Down
35 changes: 35 additions & 0 deletions src/Civ13/MessageCommand/Commands/Civ13GameServerActivity.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

declare(strict_types=1);

/*
* This file is a part of the Civilizationbot project.
*
* Copyright (c) 2021-present Valithor Obsidion <valithor@civ13.org>
*
* This file is subject to the MIT license that is bundled
* with this source code in the LICENSE.md file.
*/

namespace Civ13\MessageCommand\Commands;

use Civ13\MessageCommand\Civ13GameServerMessageCommand;
use Civ13\PlayerActivityTotals;
use Discord\Parts\Channel\Message;
use React\Promise\PromiseInterface;

/**
* Handles the "activity" command: the region group's weekly player activity totals (no player names).
*/
class Civ13GameServerActivity extends Civ13GameServerMessageCommand
{
/**
* @inheritDoc
*/
public function __invoke(Message $message, string $command, array $message_filtered): PromiseInterface
{
$totals = PlayerActivityTotals::read($this->gameserver->regionGroupFile(), $why);

return $this->civ13->reply($message, $totals === null ? 'No player activity: '.$why.'.' : PlayerActivityTotals::describe($totals));
}
}
1 change: 1 addition & 0 deletions src/Civ13/MessageServiceManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,7 @@ function (Message $message, string $command, array $message_filtered) use (&$gam
->offsetSet("{$gameserver->key}update", new Commands\Civ13GameServerUpdate($this->civ13, $gameserver), ['Ambassador'])
->offsetSet("{$gameserver->key}manage", new Commands\Civ13GameServerManage($this->civ13, $gameserver), ['Ambassador'])
->offsetSet("{$gameserver->key}hoststatus", new Commands\Civ13GameServerHostStatus($this->civ13, $gameserver), ['Ambassador'])
->offsetSet("{$gameserver->key}activity", new Commands\Civ13GameServerActivity($this->civ13, $gameserver), ['Ambassador', 'Admin'])
->offsetSet("{$gameserver->key}mapswap", new Commands\Civ13GameServerMapSwap($this->civ13, $gameserver), ['Ambassador'])
->offsetSet("{$gameserver->key}panic", new Commands\Civ13GameServerPanic($this->civ13, $gameserver), ['Ambassador'])
->offsetSet("{$gameserver->key}ban", new Commands\Civ13GameServerBan($this->civ13, $gameserver), ['Admin'])
Expand Down
111 changes: 111 additions & 0 deletions src/Civ13/PlayerActivityTotals.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
<?php

declare(strict_types=1);

/*
* This file is a part of the Civilizationbot project.
*
* Copyright (c) 2021-present Valithor Obsidion <valithor@civ13.org>
*
* This file is subject to the MIT license that is bundled
* with this source code in the LICENSE.md file.
*/

namespace Civ13;

/**
* Weekly player activity totals for a Civ13 region group (Civ13 docs/player-activity.md). The game host writes
* `<group root>/player-activity-weekly.json` beside its activity database; it holds totals only (no account
* names, research or recipe ids), so it is safe to show in Discord. Read-only: the bot never opens the database.
*/
final class PlayerActivityTotals
{
public const FILE = 'player-activity-weekly.json';
private const MAX_BYTES = 65536;

/** The totals for the group in this shard group file, or null with a reason in $why. */
public static function read(string $groupFile, ?string &$why = null): ?array
{
$why = null;
if ($groupFile === '') {
$why = 'this server has no region group';

return null;
}
$group = self::json($groupFile, 1048576);
if (! is_array($group) || ! is_string($group['root'] ?? null) || $group['root'] === '') {
$why = 'the region group file is unreadable';

return null;
}
$totals = self::json(rtrim($group['root'], '/\\').'/'.self::FILE, self::MAX_BYTES);
if (! is_array($totals)) {
$why = 'no activity totals yet (the recorder is off or the host has not read any yet)';

return null;
}

return self::clean($totals);
}

/** Keep only the expected totals, as whole numbers and plain region names. */
public static function clean(array $raw): array
{
$int = static fn (mixed $value): int => is_int($value) || (is_float($value) && is_finite($value)) ? max(0, (int) $value) : 0;
$num = static fn (mixed $value): float => is_int($value) || (is_float($value) && is_finite($value)) ? max(0.0, round((float) $value, 1)) : 0.0;
$active = is_array($raw['active'] ?? null) ? $raw['active'] : [];
$regions = [];
foreach (is_array($raw['hours_by_region'] ?? null) ? array_slice($raw['hours_by_region'], 0, 24) : [] as $row) {
if (is_array($row) && is_string($row['region'] ?? null) && preg_match('/^[A-Za-z0-9_-]{1,40}$/D', $row['region']) === 1) {
$regions[$row['region']] = $num($row['hours'] ?? 0);
}
}
$generated = is_string($raw['generated'] ?? null) && preg_match('/^[0-9: UTC-]{10,24}$/D', $raw['generated']) === 1 ? $raw['generated'] : '';

return [
'generated' => $generated,
'active' => ['day' => $int($active['day'] ?? 0), 'week' => $int($active['week'] ?? 0), 'month' => $int($active['month'] ?? 0)],
'new_this_week' => $int($raw['new_this_week'] ?? 0),
'sessions_this_week' => $int($raw['sessions_this_week'] ?? 0),
'session_minutes_median' => $num($raw['session_minutes_median'] ?? 0),
'deaths_this_week' => $int($raw['deaths_this_week'] ?? 0),
'trips_this_week' => $int($raw['trips_this_week'] ?? 0),
'hours_by_region' => $regions,
];
}

/** A short Discord message: totals only. */
public static function describe(array $totals): string
{
$a = $totals['active'];
$lines = [
'**Player activity**'.($totals['generated'] !== '' ? " ({$totals['generated']})" : ''),
"Active players: {$a['day']} today, {$a['week']} this week, {$a['month']} this month. New this week: {$totals['new_this_week']}.",
"Play sessions this week: {$totals['sessions_this_week']}, median {$totals['session_minutes_median']} minutes.",
"Deaths this week: {$totals['deaths_this_week']}. Trips between lands: {$totals['trips_this_week']}.",
];
if ($totals['hours_by_region']) {
$parts = [];
foreach ($totals['hours_by_region'] as $region => $hours) {
$parts[] = ucfirst($region).' '.$hours.' h';
}
$lines[] = 'Hours played this week: '.implode(', ', $parts).'.';
}

return implode("\n", $lines);
}

private static function json(string $path, int $limit): mixed
{
clearstatcache(true, $path);
$bytes = @is_file($path) ? @file_get_contents($path, false, null, 0, $limit + 1) : false;
if (! is_string($bytes) || strlen($bytes) > $limit) {
return null;
}
try {
return json_decode($bytes, true, 16, JSON_THROW_ON_ERROR);
} catch (\JsonException) {
return null;
}
}
}
52 changes: 52 additions & 0 deletions tests/local/player-activity-totals.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php

declare(strict_types=1);

// No Composer, Discord, game or bot bootstrap: the weekly player activity totals file only.
require __DIR__.'/../../src/Civ13/PlayerActivityTotals.php';

use Civ13\PlayerActivityTotals;

function check(bool $ok, string $message): void
{
if (! $ok) {
throw new RuntimeException($message);
}
}

$root = sys_get_temp_dir().'/civ13-activity-'.bin2hex(random_bytes(4));
mkdir($root);
$group = $root.'/group.json';
file_put_contents($group, json_encode(['root' => $root, 'regions' => [['id' => 'gaia']]]));

// Nothing written yet, and no group at all.
check(PlayerActivityTotals::read($group, $why) === null && str_contains($why, 'no activity totals yet'), 'A missing totals file was not reported');
check(PlayerActivityTotals::read('', $why) === null && $why === 'this server has no region group', 'A server without a group was not reported');
file_put_contents($root.'/'.PlayerActivityTotals::FILE, '{not json');
check(PlayerActivityTotals::read($group) === null, 'A broken totals file was read');

// Totals only: unexpected fields (names, ids) are dropped and bad values become zero.
file_put_contents($root.'/'.PlayerActivityTotals::FILE, json_encode([
'generated' => '2026-11-16 00:15 UTC',
'active' => ['day' => 3, 'week' => 9, 'month' => 20],
'new_this_week' => 2, 'sessions_this_week' => 14, 'session_minutes_median' => 37.25,
'deaths_this_week' => -5, 'trips_this_week' => 'many',
'hours_by_region' => [['region' => 'gaia', 'hours' => 12.5], ['region' => '<@everyone>', 'hours' => 1], ['region' => 'europe', 'hours' => 2]],
'churn' => [['account' => 'alice']],
]));
$totals = PlayerActivityTotals::read($group);
check(is_array($totals) && ! isset($totals['churn']), 'Unexpected fields were kept');
check($totals['deaths_this_week'] === 0 && $totals['trips_this_week'] === 0, 'Bad numbers were kept');
check($totals['hours_by_region'] === ['gaia' => 12.5, 'europe' => 2.0], 'Region names were not filtered');
$text = PlayerActivityTotals::describe($totals);
check(str_contains($text, 'Active players: 3 today, 9 this week, 20 this month. New this week: 2.'), 'Totals line changed: '.$text);
check(str_contains($text, 'median 37.3 minutes') && str_contains($text, 'Gaia 12.5 h, Europe 2 h'), 'Session or hours line changed: '.$text);
check(! str_contains($text, 'alice') && ! str_contains($text, '@'), 'A player name or mention reached the message');

// An oversized file is refused.
file_put_contents($root.'/'.PlayerActivityTotals::FILE, str_repeat(' ', 70000).'{}');
check(PlayerActivityTotals::read($group) === null, 'An oversized totals file was read');

array_map('unlink', glob($root.'/*'));
rmdir($root);
echo "PASS player activity totals\n";
Loading