From 9f2a89b49832dde53c67865e7b6bfecb33dae17b Mon Sep 17 00:00:00 2001 From: "Fabian @ Blax Software" Date: Fri, 30 Oct 2026 10:56:17 +0100 Subject: [PATCH] feat: chat on a world: world, tribe and direct channels with unread counts and live pushes Co-Authored-By: Claude Opus 5.5 (1M context) --- app/Actions/Chat.php | 193 ++++++++++++++++++ app/Models/ChatMessage.php | 25 +++ app/Websocket/Controllers/ChatController.php | 35 ++++ .../2026_10_31_180000_create_chat.php | 36 ++++ docs/architecture.md | 7 + docs/roadmap.md | 3 +- tests/Feature/ChatTest.php | 64 ++++++ 7 files changed, 362 insertions(+), 1 deletion(-) create mode 100644 app/Actions/Chat.php create mode 100644 app/Models/ChatMessage.php create mode 100644 app/Websocket/Controllers/ChatController.php create mode 100644 database/migrations/2026_10_31_180000_create_chat.php create mode 100644 tests/Feature/ChatTest.php diff --git a/app/Actions/Chat.php b/app/Actions/Chat.php new file mode 100644 index 0000000..bfd5d20 --- /dev/null +++ b/app/Actions/Chat.php @@ -0,0 +1,193 @@ +` (a conversation with that + * player); stored, they are `world`, `tribe:` and `dm::`. A new + * message is whispered as `chat:message` to every listener's sockets, in their naming. + */ +final class Chat +{ + public const MAX_LENGTH = 500; + + public const PAGE = 50; + + /** Every channel the player can read, with unread counts, last message first for direct ones. */ + public function channels(User $user, int $worldId): array + { + $me = $this->player($user, $worldId); + $channels = ['world' => 'world']; + if ($tribe = $me->tribeId()) { + $channels['tribe'] = "tribe:$tribe"; + } + $direct = ChatMessage::where('world_id', $worldId) + ->where(fn ($q) => $q->where('channel', 'like', "dm:{$me->id}:%")->orWhere('channel', 'like', "dm:%:{$me->id}")) + ->groupBy('channel')->selectRaw('channel, MAX(id) as last')->orderByDesc('last')->pluck('channel'); + $others = Player::whereIn('id', $direct->map(fn (string $c) => $this->other($c, $me->id)))->pluck('name', 'id'); + foreach ($direct as $stored) { + $channels['dm:'.$this->other($stored, $me->id)] = $stored; + } + $reads = DB::table('chat_reads')->where('player_id', $me->id)->pluck('last_id', 'channel'); + + return collect($channels)->map(function (string $stored, string $channel) use ($me, $reads, $others, $worldId) { + $other = str_starts_with($channel, 'dm:') ? (int) substr($channel, 3) : null; + + return [ + 'channel' => $channel, + 'with' => $other ? ['id' => $other, 'name' => $others[$other] ?? '?'] : null, + 'unread' => ChatMessage::where('world_id', $worldId)->where('channel', $stored)->where('player_id', '!=', $me->id)->where('id', '>', $reads[$stored] ?? 0)->count(), + ]; + })->values()->all(); + } + + /** The last messages of a channel (or those before an id), oldest first; reading marks them read. */ + public function history(User $user, int $worldId, string $channel, ?int $before = null): array + { + $me = $this->player($user, $worldId); + $stored = $this->stored($me, $channel); + $messages = ChatMessage::with('player:id,name')->where('world_id', $worldId)->where('channel', $stored) + ->when($before, fn ($q) => $q->where('id', '<', $before)) + ->orderByDesc('id')->limit(self::PAGE)->get()->reverse()->values(); + if (! $before && $messages->isNotEmpty()) { + $this->markRead($me, $stored, $messages->last()->id); + } + + return [ + 'channel' => $channel, + 'messages' => $messages->map(fn (ChatMessage $m) => self::present($m))->all(), + 'more' => $messages->count() === self::PAGE, + ]; + } + + /** Open a conversation with a player by name: the channel to write in. */ + public function open(User $user, int $worldId, string $name): array + { + $me = $this->player($user, $worldId); + $other = Player::where('world_id', $worldId)->where('name', trim($name))->first() + ?? throw new GameRuleViolation('no_player', 'No player of that name here.'); + if ($other->id === $me->id) { + throw new GameRuleViolation('no_player', 'That is you.'); + } + + return ['channel' => "dm:{$other->id}", 'with' => ['id' => $other->id, 'name' => $other->name], 'unread' => 0]; + } + + public function send(User $user, int $worldId, string $channel, string $body): array + { + $me = $this->player($user, $worldId); + $me->world->ensureOpen(); + $body = trim($body); + if ($body === '' || mb_strlen($body) > self::MAX_LENGTH) { + throw new GameRuleViolation('chat_length', 'Messages are 1 to 500 characters.'); + } + $stored = $this->stored($me, $channel); + // One message a second per player is plenty for talking. + if (! cache()->add("chat.{$me->id}", true, 1)) { + throw new GameRuleViolation('chat_slow', 'Slow down a little.'); + } + $message = ChatMessage::create(['world_id' => $worldId, 'channel' => $stored, 'player_id' => $me->id, 'body' => $body, 'created_at' => now()->toImmutable()]); + $message->setRelation('player', $me); + $this->markRead($me, $stored, $message->id); + $this->push($message, $me); + + return self::present($message); + } + + /** The player has seen a channel up to its newest message. */ + public function read(User $user, int $worldId, string $channel): array + { + $me = $this->player($user, $worldId); + $stored = $this->stored($me, $channel); + $last = ChatMessage::where('world_id', $worldId)->where('channel', $stored)->max('id'); + if ($last) { + $this->markRead($me, $stored, (int) $last); + } + + return ['channel' => $channel, 'unread' => 0]; + } + + /** The stored name of a channel the player may use. */ + private function stored(Player $me, string $channel): string + { + if ($channel === 'world') { + return 'world'; + } + if ($channel === 'tribe') { + return 'tribe:'.($me->tribeId() ?? throw new GameRuleViolation('no_tribe', 'You are not in a tribe.')); + } + if (preg_match('/^dm:(\d+)$/', $channel, $m) && (int) $m[1] !== $me->id && Player::where('world_id', $me->world_id)->whereKey((int) $m[1])->exists()) { + $ids = [$me->id, (int) $m[1]]; + sort($ids); + + return 'dm:'.implode(':', $ids); + } + + throw new GameRuleViolation('not_found', 'No such channel.'); + } + + private function other(string $stored, int $me): int + { + [, $a, $b] = explode(':', $stored); + + return (int) $a === $me ? (int) $b : (int) $a; + } + + /** Everyone who reads the channel hears of the message, in their own naming of it. */ + private function push(ChatMessage $message, Player $from): void + { + if (! ws_available()) { + return; + } + [$kind] = explode(':', $message->channel); + $listeners = match ($kind) { + 'world' => Player::where('world_id', $message->world_id)->get(['id', 'user_id']), + 'tribe' => Player::whereIn('id', DB::table('tribe_members')->where('tribe_id', (int) substr($message->channel, 6))->pluck('player_id'))->get(['id', 'user_id']), + default => Player::whereIn('id', array_map('intval', array_slice(explode(':', $message->channel), 1)))->get(['id', 'user_id']), + }; + foreach ($listeners as $listener) { + $channel = $kind === 'dm' ? 'dm:'.($listener->id === $from->id ? $this->other($message->channel, $from->id) : $from->id) : $kind; + try { + $sockets = WebsocketService::getUserSocketIds($listener->user_id); + if ($sockets) { + ws_whisper('chat:message', ['world_id' => $message->world_id, 'channel' => $channel, 'message' => self::present($message)], $sockets); + } + } catch (Throwable $e) { + // The message is stored; a missed push shows on the next look. + report($e); + } + } + } + + private function markRead(Player $me, string $stored, int $id): void + { + DB::table('chat_reads')->upsert([['player_id' => $me->id, 'channel' => $stored, 'last_id' => $id]], ['player_id', 'channel'], ['last_id']); + } + + private function player(User $user, int $worldId): Player + { + return Player::with(['world', 'membership'])->where('user_id', $user->id)->where('world_id', $worldId)->first() + ?? throw new GameRuleViolation('not_found', 'You have not joined this world.'); + } + + /** @return array{id: int, player: array{id: int, name: string}, body: string, at: string} */ + private static function present(ChatMessage $m): array + { + return ['id' => $m->id, 'player' => ['id' => $m->player->id, 'name' => $m->player->name], 'body' => $m->body, 'at' => self::iso($m->created_at)]; + } + + private static function iso(CarbonImmutable $at): string + { + return $at->utc()->format('Y-m-d\TH:i:s.v\Z'); + } +} diff --git a/app/Models/ChatMessage.php b/app/Models/ChatMessage.php new file mode 100644 index 0000000..214d827 --- /dev/null +++ b/app/Models/ChatMessage.php @@ -0,0 +1,25 @@ + 'immutable_datetime']; + } + + public function player(): BelongsTo + { + return $this->belongsTo(Player::class); + } +} diff --git a/app/Websocket/Controllers/ChatController.php b/app/Websocket/Controllers/ChatController.php new file mode 100644 index 0000000..ba1cb96 --- /dev/null +++ b/app/Websocket/Controllers/ChatController.php @@ -0,0 +1,35 @@ +. */ +class ChatController extends GameController +{ + public function channels() + { + return $this->play(fn () => app(Chat::class)->channels(auth()->user(), (int) request('world_id'))); + } + + public function history() + { + return $this->play(fn () => app(Chat::class)->history(auth()->user(), (int) request('world_id'), (string) request('channel'), request('before') ? (int) request('before') : null)); + } + + public function open() + { + return $this->play(fn () => app(Chat::class)->open(auth()->user(), (int) request('world_id'), (string) request('player'))); + } + + public function send() + { + return $this->play(fn () => app(Chat::class)->send(auth()->user(), (int) request('world_id'), (string) request('channel'), (string) request('body'))); + } + + public function read() + { + return $this->play(fn () => app(Chat::class)->read(auth()->user(), (int) request('world_id'), (string) request('channel'))); + } +} diff --git a/database/migrations/2026_10_31_180000_create_chat.php b/database/migrations/2026_10_31_180000_create_chat.php new file mode 100644 index 0000000..85f0330 --- /dev/null +++ b/database/migrations/2026_10_31_180000_create_chat.php @@ -0,0 +1,36 @@ +id(); + $table->foreignId('world_id')->constrained()->cascadeOnDelete(); + // world, tribe:, or dm:: + $table->string('channel', 40); + $table->foreignId('player_id')->constrained()->cascadeOnDelete(); + $table->text('body'); + $table->dateTime('created_at', 3); + $table->index(['world_id', 'channel', 'id']); + }); + Schema::create('chat_reads', function (Blueprint $table) { + $table->id(); + $table->foreignId('player_id')->constrained()->cascadeOnDelete(); + $table->string('channel', 40); + $table->unsignedBigInteger('last_id'); + $table->unique(['player_id', 'channel']); + }); + } + + public function down(): void + { + Schema::dropIfExists('chat_reads'); + Schema::dropIfExists('chat_messages'); + } +}; diff --git a/docs/architecture.md b/docs/architecture.md index 1013b89..4260f34 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -265,6 +265,13 @@ Players band together in tribes (`Tribes` action, `tribe.*` over WS, rules in `D - Members of one tribe, allies and NAP partners can't attack each other (`own_tribe`, `pact` at the rally point). Support goes to anyone, as before. - The tribe page (`tribe.show`) carries the members with points, the invites sent, the relations (holds, ending with `ends_at`, offered, incoming, enemy, hostile) and the last 30 events of its news; `tribe.list` every tribe with its size, points and relation. The village payload carries `tribe: {tribe, invites}` for the menu badge. The ranking has a tribe kind and tags players with their tribe. +## Chat + +Players talk on their world (`Chat` action, `chat.*` over WS). The client names channels from its own side: `world` (everyone on the world), `tribe` (the player's tribe) and `dm:` (a conversation with that player, opened by name with `chat.open`). Stored (`chat_messages`), they are `world`, `tribe:` and `dm::`, so a tribe's talk stays with the tribe even as members come and go. + +- `chat.send` takes 1 to 500 characters, one message a second per player, on open worlds only. Every reader of the channel gets `chat:message {world_id, channel, message}` whispered to their sockets, with the channel in their own naming. +- `chat.channels` lists the channels with unread counts (`chat_reads` keeps each player's last read message per channel; direct conversations newest first), `chat.history` the last 50 messages (or 50 before an id) and marks them read, `chat.read` marks a channel read. + ## Seasons A world is a season with a winner (`world.season`, rules in `Season`, rows in `Seasons`). diff --git a/docs/roadmap.md b/docs/roadmap.md index 191299d..ab2ca9d 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -58,7 +58,8 @@ What Die Stämme has at this stage that the game still lacks. - [x] Rename villages - [ ] Player and village profile pages (from the map, reports and movements) - [x] Ranking: players by points, villages by points, opponents defeated (attack and defence) -- [ ] Messages between players (inbox, threads) +- [x] Chat between players: the world, the tribe, and direct conversations, live +- [ ] Messages between players as letters (inbox, threads), if the chat isn't enough - [ ] Notebook and account settings (vacation mode later) ## M4.6: Game loop diff --git a/tests/Feature/ChatTest.php b/tests/Feature/ChatTest.php new file mode 100644 index 0000000..bef66bd --- /dev/null +++ b/tests/Feature/ChatTest.php @@ -0,0 +1,64 @@ + $this->travelTo(CarbonImmutable::parse('2026-10-29 12:00:00'))); + +function chat(): Chat +{ + return app(Chat::class); +} + +it('talks on the world channel and counts what is unread', function () { + $a = startVillage(); + $b = startVillage(); + $sent = chat()->send(owner($a), $a->world_id, 'world', ' Hello, neighbours! '); + expect($sent)->toMatchArray(['body' => 'Hello, neighbours!', 'player' => ['id' => $a->player_id, 'name' => $a->player->name]]); + + expect(chat()->channels(owner($b), $b->world_id))->toBe([['channel' => 'world', 'with' => null, 'unread' => 1]]) + ->and(chat()->channels(owner($a), $a->world_id)[0]['unread'])->toBe(0); + $history = chat()->history(owner($b), $b->world_id, 'world'); + expect($history['messages'])->toHaveCount(1)->and($history['more'])->toBeFalse() + ->and(chat()->channels(owner($b), $b->world_id)[0]['unread'])->toBe(0); +}); + +it('keeps tribe talk inside the tribe', function () { + $a = startVillage(); + $b = startVillage(); + expect(rule(fn () => chat()->send(owner($a), $a->world_id, 'tribe', 'Hi')))->toBe('no_tribe'); + + app(Tribes::class)->found(owner($a), $a->world_id, 'Dorfrat', 'DRF'); + chat()->send(owner($a), $a->world_id, 'tribe', 'Council at dawn'); + expect(collect(chat()->channels(owner($a), $a->world_id))->pluck('channel')->all())->toBe(['world', 'tribe']) + ->and(chat()->history(owner($a), $a->world_id, 'tribe')['messages'][0]['body'])->toBe('Council at dawn') + ->and(rule(fn () => chat()->history(owner($b), $b->world_id, 'tribe')))->toBe('no_tribe'); +}); + +it('opens a conversation between two players by name', function () { + $a = startVillage(); + $b = startVillage(); + $c = startVillage(); + $open = chat()->open(owner($a), $a->world_id, $b->player->name); + expect($open['channel'])->toBe("dm:{$b->player_id}"); + + chat()->send(owner($a), $a->world_id, $open['channel'], 'Truce?'); + $theirs = collect(chat()->channels(owner($b), $b->world_id))->firstWhere('channel', "dm:{$a->player_id}"); + expect($theirs)->toBe(['channel' => "dm:{$a->player_id}", 'with' => ['id' => $a->player_id, 'name' => $a->player->name], 'unread' => 1]) + ->and(chat()->history(owner($b), $b->world_id, "dm:{$a->player_id}")['messages'][0]['body'])->toBe('Truce?') + ->and(collect(chat()->channels(owner($c), $c->world_id))->pluck('channel')->all())->toBe(['world']) + ->and(rule(fn () => chat()->open(owner($a), $a->world_id, 'Nobody')))->toBe('no_player'); +}); + +it('refuses empty, long and too quick messages', function () { + $a = startVillage(); + expect(rule(fn () => chat()->send(owner($a), $a->world_id, 'world', ' ')))->toBe('chat_length') + ->and(rule(fn () => chat()->send(owner($a), $a->world_id, 'world', str_repeat('a', 501))))->toBe('chat_length'); + + chat()->send(owner($a), $a->world_id, 'world', 'one'); + expect(rule(fn () => chat()->send(owner($a), $a->world_id, 'world', 'two')))->toBe('chat_slow'); + $this->travel(2)->seconds(); + chat()->send(owner($a), $a->world_id, 'world', 'two'); + expect(chat()->history(owner($a), $a->world_id, 'world')['messages'])->toHaveCount(2); +});