id(); $table->unsignedBigInteger('training_match_id')->unique(); $table->string('root_channel_id', 50)->nullable(); $table->string('root_channel_name', 255)->nullable(); $table->string('team_a_channel_id', 50)->nullable(); $table->string('team_a_channel_name', 255)->nullable(); $table->string('team_b_channel_id', 50)->nullable(); $table->string('team_b_channel_name', 255)->nullable(); $table->timestamp('last_move_at')->nullable(); $table->timestamps(); }); Log::info('GIGAX V23: tabela lobby_discord_channels criada automaticamente.'); } private const TYPE_CATEGORY = 4; private const PERM_VIEW_CHANNEL = 1024; private const PERM_CONNECT = 1048576; private const PERM_SPEAK = 2097152; private const PERM_STREAM = 512; private const PERM_MOVE_MEMBERS = 16777216; private const PERM_MANAGE_CHANNELS = 16; public function enabled(): bool { return (bool) config('discord.enabled') && filled(config('discord.bot_token')) && filled(config('discord.guild_id')); } public function matchIntegrationData(int $matchId, ?Collection $participants = null): array { $this->ensureStorageTable(); $match = DB::table('mix_training_matches')->where('id', $matchId)->first(); if ($participants === null) { $participants = $this->participants($matchId); } $channels = Schema::hasTable('lobby_discord_channels') ? DB::table('lobby_discord_channels')->where('training_match_id', $matchId)->first() : null; return [ 'provider' => 'discord', 'mode' => strtoupper((string) ($match->voice_mode ?? config('voice.default_mode', 'A'))), 'discord' => [ 'enabled' => $this->enabled(), 'invite_url' => config('discord.invite_url'), 'category_id' => config('discord.category_id'), 'default_room_id' => config('discord.default_room_id'), 'waiting_channel_id' => config('discord.waiting_channel_id'), 'root_channel_id' => $channels->root_channel_id ?? null, 'root_channel_name' => $channels->root_channel_name ?? null, 'team_a_channel_id' => $channels->team_a_channel_id ?? null, 'team_b_channel_id' => $channels->team_b_channel_id ?? null, 'team_a_channel_name' => $channels->team_a_channel_name ?? null, 'team_b_channel_name' => $channels->team_b_channel_name ?? null, 'players_with_discord' => $participants->filter(fn ($p) => !empty($p->discord_id ?? $p->discord_user_id ?? null))->count(), 'players_total' => $participants->count(), ], 'ts3' => [ 'enabled' => (bool) config('teamspeak.enabled'), ], ]; } public function getMatchChannelStatus(int $matchId): array { $this->ensureStorageTable(); $channels = DB::table('lobby_discord_channels')->where('training_match_id', $matchId)->first(); if (!$channels) { return ['success' => true, 'exists' => false, 'message' => 'Nenhuma sala Discord registrada para esta partida.']; } return [ 'success' => true, 'exists' => true, 'channels' => [ 'root_channel_id' => $channels->root_channel_id, 'root_channel_name' => $channels->root_channel_name, 'team_a_channel_id' => $channels->team_a_channel_id, 'team_a_channel_name' => $channels->team_a_channel_name, 'team_b_channel_id' => $channels->team_b_channel_id, 'team_b_channel_name' => $channels->team_b_channel_name, 'last_move_at' => $channels->last_move_at, 'updated_at' => $channels->updated_at, ], ]; } public function provisionMatchChannels(int $matchId): array { $this->ensureStorageTable(); if (!$this->enabled()) { return ['success' => false, 'message' => 'Discord desabilitado ou sem configuracao completa.']; } $existing = DB::table('lobby_discord_channels')->where('training_match_id', $matchId)->first(); if ($existing && $existing->team_a_channel_id && $existing->team_b_channel_id) { return ['success' => true, 'channels' => (array) $existing, 'message' => 'Salas Discord ja existiam.']; } $match = DB::table('mix_training_matches')->where('id', $matchId)->first(); if (!$match) { return ['success' => false, 'message' => 'Partida nao encontrada.']; } $players = $this->participants($matchId); $template = $this->fetchDefaultRoomTemplate(); $rootName = $this->rootChannelName($match); $rootPayload = [ 'name' => $rootName, 'type' => self::TYPE_CATEGORY, 'permission_overwrites' => $this->permissionOverwrites($players), ]; $rootChannel = $this->api('POST', '/guilds/' . config('discord.guild_id') . '/channels', $rootPayload); $rootId = data_get($rootChannel, 'id'); if (!$rootId) { return ['success' => false, 'message' => 'Nao foi possivel criar a categoria privada da partida no Discord.']; } $teamA = $this->createVoiceChannel($rootId, 'Time A', $template); $teamB = $this->createVoiceChannel($rootId, 'Time B', $template); if (!data_get($teamA, 'id') || !data_get($teamB, 'id')) { $this->safeDeleteChannel($rootId); return ['success' => false, 'message' => 'Nao foi possivel criar os canais privados de voz no Discord.']; } DB::table('lobby_discord_channels')->updateOrInsert( ['training_match_id' => $matchId], [ 'root_channel_id' => (string) data_get($rootChannel, 'id'), 'root_channel_name' => $rootName, 'team_a_channel_id' => (string) data_get($teamA, 'id'), 'team_a_channel_name' => (string) data_get($teamA, 'name', 'Time A'), 'team_b_channel_id' => (string) data_get($teamB, 'id'), 'team_b_channel_name' => (string) data_get($teamB, 'name', 'Time B'), 'last_move_at' => null, 'updated_at' => now(), 'created_at' => now(), ] ); $playerLines = $players->map(function ($player) { $team = (int) ($player->team ?? 1) === 1 ? 'Time A' : 'Time B'; return '• ' . ($player->nickname ?? 'Jogador') . ' — ' . $team; })->implode("\n"); $mapName = trim((string) ($match->map_name ?? '')) ?: 'A definir'; $this->notifyViaWebhook( "🎮 Partida #{$matchId} — salas privadas criadas\n" . "🗺️ Mapa: {$mapName}\n" . "🔒 Acesso: somente jogadores da partida e administradores\n\n" . $playerLines ); return [ 'success' => true, 'channels' => [ 'root_channel_id' => data_get($rootChannel, 'id'), 'team_a_channel_id' => data_get($teamA, 'id'), 'team_b_channel_id' => data_get($teamB, 'id'), ], 'message' => 'Salas privadas criadas com sucesso no Discord.', ]; } public function moveMatchPlayers(int $matchId): array { $this->ensureStorageTable(); if (!$this->enabled()) { return ['success' => false, 'message' => 'Discord desabilitado ou sem configuracao completa.']; } $channels = Schema::hasTable('lobby_discord_channels') ? DB::table('lobby_discord_channels')->where('training_match_id', $matchId)->first() : null; if (!$channels) { $provision = $this->provisionMatchChannels($matchId); if (!$provision['success']) { return $provision; } $channels = DB::table('lobby_discord_channels')->where('training_match_id', $matchId)->first(); } $players = $this->participants($matchId); $moved = 0; $pending = []; foreach ($players as $player) { $discordId = trim((string) ($player->discord_id ?? $player->discord_user_id ?? '')); if ($discordId === '') { $pending[] = $player->nickname . ' (sem discord_id vinculado)'; continue; } $targetChannel = (int) ($player->team ?? 1) === 1 ? $channels->team_a_channel_id : $channels->team_b_channel_id; try { $this->api('PATCH', '/guilds/' . config('discord.guild_id') . '/members/' . $discordId, [ 'channel_id' => (string) $targetChannel, ]); $moved++; } catch (\Throwable $e) { $pending[] = $player->nickname . ' (' . $e->getMessage() . ')'; } } DB::table('lobby_discord_channels') ->where('training_match_id', $matchId) ->update([ 'last_move_at' => now(), 'updated_at' => now(), ]); return [ 'success' => true, 'moved' => $moved, 'pending' => $pending, 'message' => $moved . ' jogador(es) enviados para as salas privadas do Discord.', ]; } /** * GIGAX V22: * Move jogadores logo após a criação das salas e repete por alguns segundos. * * O Discord só permite mover um membro que já esteja conectado em voz. * Portanto, se o jogador estiver entrando no Discord no mesmo instante do * ready-check, uma única tentativa pode falhar mesmo com tudo correto. */ public function moveMatchPlayersWithRetry( int $matchId, int $attempts = 8, int $delayMs = 900 ): array { $attempts = max(1, min(10, $attempts)); $delayMs = max(150, min(2000, $delayMs)); $last = [ 'success' => false, 'moved' => 0, 'pending' => [], 'message' => 'Movimentacao ainda nao executada.', ]; for ($attempt = 1; $attempt <= $attempts; $attempt++) { $last = $this->moveMatchPlayers($matchId); $last['attempt'] = $attempt; $last['attempts'] = $attempts; $pending = is_array($last['pending'] ?? null) ? $last['pending'] : []; if (($last['success'] ?? false) && empty($pending)) { Log::info('GIGAX V22: todos os jogadores movidos no Discord.', [ 'match_id' => $matchId, 'attempt' => $attempt, 'moved' => (int) ($last['moved'] ?? 0), ]); return $last; } if ($attempt < $attempts) { usleep($delayMs * 1000); } } Log::warning('GIGAX V22: alguns jogadores ainda nao foram movidos no Discord.', [ 'match_id' => $matchId, 'moved' => (int) ($last['moved'] ?? 0), 'pending' => $last['pending'] ?? [], 'attempts' => $attempts, ]); return $last; } /** * Move um único usuário da partida para a sala do time. * Útil para chamadas do bot/polling quando o membro entra em voz depois. */ public function moveUserToMatchChannel(int $matchId, int $userId): array { $this->ensureStorageTable(); $channels = DB::table('lobby_discord_channels') ->where('training_match_id', $matchId) ->first(); if (!$channels) { $provision = $this->provisionMatchChannels($matchId); if (!($provision['success'] ?? false)) { return $provision; } $channels = DB::table('lobby_discord_channels') ->where('training_match_id', $matchId) ->first(); } $player = $this->participants($matchId)->firstWhere('user_id', $userId); if (!$player) { return ['success' => false, 'message' => 'Jogador não pertence à partida.']; } $discordId = trim((string) ($player->discord_id ?? $player->discord_user_id ?? '')); if ($discordId === '') { return ['success' => false, 'message' => 'Jogador sem discord_id vinculado.']; } $targetChannel = (int) ($player->team ?? 1) === 1 ? (string) $channels->team_a_channel_id : (string) $channels->team_b_channel_id; try { $this->api( 'PATCH', '/guilds/' . config('discord.guild_id') . '/members/' . $discordId, ['channel_id' => $targetChannel] ); return [ 'success' => true, 'discord_id' => $discordId, 'team' => (int) ($player->team ?? 1), 'channel_id' => $targetChannel, 'message' => 'Jogador movido automaticamente para a sala do time.', ]; } catch (\Throwable $e) { return [ 'success' => false, 'discord_id' => $discordId, 'message' => $e->getMessage(), ]; } } public function cleanupMatchChannels(int $matchId): array { $this->ensureStorageTable(); $channels = DB::table('lobby_discord_channels')->where('training_match_id', $matchId)->first(); if (!$channels) { return ['success' => true, 'message' => 'Nao havia salas Discord registradas para a partida.']; } $players = $this->participants($matchId); $movedToWaiting = 0; $waiting = trim((string) config('discord.waiting_channel_id')); if ($waiting !== '') { foreach ($players as $player) { $discordId = trim((string) ($player->discord_id ?? $player->discord_user_id ?? '')); if ($discordId === '') { continue; } try { $this->api('PATCH', '/guilds/' . config('discord.guild_id') . '/members/' . $discordId, [ 'channel_id' => $waiting, ]); $movedToWaiting++; } catch (\Throwable $e) { Log::warning('Falha ao mover jogador para waiting room do Discord', [ 'match_id' => $matchId, 'discord_user_id' => $discordId, 'error' => $e->getMessage(), ]); } } } // GIGAX_DISCORD_CLEANUP_SAFE_V1 $failed = []; foreach ([ 'team_a_channel_id', 'team_b_channel_id', 'root_channel_id', ] as $field) { $channelId = trim((string) ($channels->{$field} ?? '')); if ($channelId === '') { continue; } try { $this->api('DELETE', '/channels/' . $channelId); } catch (\Throwable $e) { // 404 significa que o canal ja foi removido. if (!str_contains($e->getMessage(), 'HTTP 404')) { $failed[] = $field . ': ' . $e->getMessage(); } } } if ($failed) { Log::warning('GIGAX Discord: limpeza incompleta', [ 'match_id' => $matchId, 'errors' => $failed, ]); return [ 'success' => false, 'moved' => $movedToWaiting, 'message' => 'Limpeza incompleta. Registro preservado para nova tentativa.', 'errors' => $failed, ]; } DB::table('lobby_discord_channels') ->where('training_match_id', $matchId) ->delete(); $this->notifyViaWebhook("🏁 Partida #{$matchId} encerrou. Salas privadas do Discord foram removidas."); return [ 'success' => true, 'moved' => $movedToWaiting, 'message' => 'Limpeza das salas Discord concluida.', ]; } public function finishMatchChannels(int $matchId): array { return $this->cleanupMatchChannels($matchId); } public function describeForUser(int $matchId, int $userId): array { $this->ensureStorageTable(); $match = DB::table('mix_training_matches')->where('id', $matchId)->first(); $channels = Schema::hasTable('lobby_discord_channels') ? DB::table('lobby_discord_channels')->where('training_match_id', $matchId)->first() : null; $user = DB::table('users')->where('id', $userId)->first(); $team = (int) (DB::table('mix_training_participants') ->where('training_match_id', $matchId) ->where('user_id', $userId) ->whereNull('left_at') ->value('team') ?? 0); $teamChannelId = $team === 1 ? ($channels->team_a_channel_id ?? null) : ($team === 2 ? ($channels->team_b_channel_id ?? null) : null); $teamChannelName = $team === 1 ? ($channels->team_a_channel_name ?? 'Time A') : ($team === 2 ? ($channels->team_b_channel_name ?? 'Time B') : 'Aguardando time'); $joinUrl = null; $guildId = trim((string) config('discord.guild_id')); $teamChannelId = $teamChannelId ? (string) $teamChannelId : null; if ($guildId !== '' && !empty($teamChannelId)) { $joinUrl = 'https://discord.com/channels/' . $guildId . '/' . $teamChannelId; } elseif (!empty(config('discord.invite_url'))) { $joinUrl = (string) config('discord.invite_url'); } return [ 'enabled' => $this->enabled(), 'username' => $user->discord_username ?? null, 'discord_user_id' => $user->discord_id ?? $user->discord_user_id ?? null, 'invite_url' => config('discord.invite_url'), 'category_id' => config('discord.category_id'), 'default_room_id' => config('discord.default_room_id'), 'waiting_channel_id' => config('discord.waiting_channel_id'), 'root_channel_id' => $channels->root_channel_id ?? null, 'root_channel_name' => $channels->root_channel_name ?? null, 'team_a_channel_id' => $channels->team_a_channel_id ?? null, 'team_b_channel_id' => $channels->team_b_channel_id ?? null, 'team_a_channel_name' => $channels->team_a_channel_name ?? null, 'team_b_channel_name' => $channels->team_b_channel_name ?? null, 'team_room_id' => $teamChannelId, 'team_room_name' => $teamChannelName, 'join_url' => $joinUrl, 'access_notice' => $team ? 'Seu acesso já fica liberado para a sala privada do seu time. Admins podem entrar em todas.' : 'Seu time ainda não foi identificado para esta partida.', 'mode' => strtoupper((string) ($match->voice_mode ?? config('voice.default_mode', 'A'))), ]; } private function createVoiceChannel(string $parentId, string $name, array $template): array { $payload = [ 'name' => $name, 'type' => self::TYPE_VOICE, 'parent_id' => $parentId, ]; if (isset($template['bitrate'])) { $payload['bitrate'] = $template['bitrate']; } if (isset($template['user_limit'])) { $payload['user_limit'] = $template['user_limit']; } return $this->api('POST', '/guilds/' . config('discord.guild_id') . '/channels', $payload); } private function fetchDefaultRoomTemplate(): array { $defaultRoomId = trim((string) config('discord.default_room_id')); if ($defaultRoomId === '') { return []; } try { $channel = $this->api('GET', '/channels/' . $defaultRoomId); return array_filter([ 'bitrate' => data_get($channel, 'bitrate'), 'user_limit' => data_get($channel, 'user_limit'), ], fn ($value) => $value !== null && $value !== ''); } catch (\Throwable $e) { Log::warning('Nao foi possivel ler canal padrao do Discord', [ 'channel_id' => $defaultRoomId, 'error' => $e->getMessage(), ]); return []; } } private function permissionOverwrites(Collection $players): array { $overwrites = []; if ((bool) config('discord.private_rooms', true)) { $deny = (string) (self::PERM_VIEW_CHANNEL + self::PERM_CONNECT); $overwrites[] = [ 'id' => (string) config('discord.guild_id'), 'type' => 0, 'allow' => '0', 'deny' => $deny, ]; } $allowPlayer = (string) (self::PERM_VIEW_CHANNEL + self::PERM_CONNECT + self::PERM_SPEAK + self::PERM_STREAM); foreach ($players as $player) { $discordId = trim((string) ($player->discord_id ?? $player->discord_user_id ?? '')); if ($discordId === '') { continue; } $overwrites[] = [ 'id' => $discordId, 'type' => 1, 'allow' => $allowPlayer, 'deny' => '0', ]; } $allowAdmin = (string) (self::PERM_VIEW_CHANNEL + self::PERM_CONNECT + self::PERM_SPEAK + self::PERM_MOVE_MEMBERS + self::PERM_MANAGE_CHANNELS); foreach ((array) config('discord.admin_role_ids', []) as $roleId) { $roleId = trim((string) $roleId); if ($roleId === '') { continue; } $overwrites[] = [ 'id' => $roleId, 'type' => 0, 'allow' => $allowAdmin, 'deny' => '0', ]; } return $overwrites; } private function participants(int $matchId): Collection { $query = DB::table('mix_training_participants as tp') ->join('users as u', 'u.id', '=', 'tp.user_id') ->select( 'tp.user_id', 'tp.team', 'u.nickname' ) ->where('tp.training_match_id', $matchId) ->whereNull('tp.left_at'); // GIGAX V22: // O projeto histórico usa "discord_id"; algumas versões novas usam // "discord_user_id". Aceitamos ambos e exponemos uma identidade única. $hasDiscordId = Schema::hasColumn('users', 'discord_id'); $hasDiscordUserId = Schema::hasColumn('users', 'discord_user_id'); if ($hasDiscordId) { $query->addSelect('u.discord_id'); } else { $query->addSelect(DB::raw('NULL as discord_id')); } if ($hasDiscordUserId) { $query->addSelect('u.discord_user_id'); } else { $query->addSelect(DB::raw('NULL as discord_user_id')); } return $query->orderBy('tp.team')->orderBy('u.nickname')->get(); } private function rootChannelName(object $match): string { return 'Partida #' . $match->id . ' - ' . trim((string) ($match->title ?? 'GIGAX')); } private function safeDeleteChannel(string $channelId): void { if ($channelId === '') { return; } try { $this->api('DELETE', '/channels/' . $channelId); } catch (\Throwable $e) { Log::warning('Falha ao remover canal Discord', [ 'channel_id' => $channelId, 'error' => $e->getMessage(), ]); } } private function notifyViaWebhook(string $content): void { $webhook = trim((string) config('discord.webhook_url')); if ($webhook === '') { return; } try { Http::timeout((int) config('discord.request_timeout', 10)) ->post($webhook, ['content' => $content]); } catch (\Throwable $e) { Log::warning('Falha ao enviar webhook do Discord', ['error' => $e->getMessage()]); } } private function api(string $method, string $uri, array $payload = []): array { $token = trim((string) config('discord.bot_token')); $base = 'https://discord.com/api/v10'; // GIGAX V24: // Discord Bot API NÃO usa Bearer token. O header obrigatório é: // Authorization: Bot // Http::withToken() envia Bearer e causava HTTP 401 Unauthorized. if (str_starts_with(strtolower($token), 'bot ')) { $token = trim(substr($token, 4)); } if ($token === '') { throw new \RuntimeException('DISCORD_BOT_TOKEN não configurado.'); } $request = Http::timeout((int) config('discord.request_timeout', 10)) ->withHeaders([ 'Authorization' => 'Bot ' . $token, 'Content-Type' => 'application/json', ]) ->acceptJson(); $response = match (strtoupper($method)) { 'GET' => $request->get($base . $uri), 'POST' => $request->post($base . $uri, $payload), 'PATCH' => $request->patch($base . $uri, $payload), 'DELETE' => $request->delete($base . $uri), default => throw new \InvalidArgumentException('Metodo nao suportado: ' . $method), }; if ($response->failed()) { $body = $response->json(); $message = data_get($body, 'message') ?: $response->body(); throw new \RuntimeException('Discord API HTTP ' . $response->status() . ': ' . $message); } return $response->json() ?: []; } }