` (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'); } }