json([ 'ok' => true, 'matches' => [], 'count' => 0, ]); } /* * GIGAX_PENDING_VOICE_ROBUSTO_V2 * * Evita filtros SQL complexos que podem variar no SQL Server. * Busca partidas abertas e aplica os filtros de voz em PHP. * * voice_mode: * A = Discord no fluxo oficial da GIGAX * discord = compatibilidade com registros textuais antigos */ $rows = DB::table('mix_training_matches') ->whereNull('ended_at') ->orderBy('id') ->limit(100) ->get(); $finishedStatuses = [ 'finished', 'ended', 'completed', 'cancelled', 'canceled', 'finalizada', 'finalizado', 'encerrada', 'encerrado', ]; $alreadyProvisioned = [ 'created', 'ready', 'active', 'deleted', 'removed', ]; foreach ($rows as $row) { /* * GIGAX_READY_GATE_FINAL * * Nao cria Discord enquanto o ready-check nao estiver * completamente aceito. * * Depois que todos confirmarem: * ready_status = accepted * ready_check_status = accepted * * Entao pending-voice libera a partida para o bot. */ $readyStatus = strtolower(trim((string) ($row->ready_status ?? ''))); $readyCheckStatus = strtolower(trim((string) ($row->ready_check_status ?? ''))); if ( $readyStatus !== 'accepted' || $readyCheckStatus !== 'accepted' ) { continue; } $status = strtolower(trim((string) ($row->status ?? ''))); if (in_array($status, $finishedStatuses, true)) { continue; } $voiceMode = strtolower(trim((string) ($row->voice_mode ?? ''))); if (!in_array($voiceMode, ['', 'discord', 'a'], true)) { continue; } $voiceStatus = strtolower(trim((string) ($row->voice_status ?? ''))); if (in_array($voiceStatus, $alreadyProvisioned, true)) { continue; } $roomName = trim((string) ($row->discord_room_name ?? '')); if ($roomName !== '') { continue; } $payload = $this->buildPendingVoicePayload( (int) $row->id, (array) $row ); if ($payload !== null) { $matches[(int) $row->id] = $payload; } } } catch (\Throwable $e) { Log::warning('GIGAX Bot: falha pending-voice robusto', [ 'error' => $e->getMessage(), ]); } /* * Compatibilidade com mix_active_matches. * Mantida apenas quando ainda nao existe uma partida com mesmo ID. */ try { if (Schema::hasTable('mix_active_matches')) { $rows = DB::table('mix_active_matches') ->whereNull('ended_at') ->orderBy('id') ->limit(100) ->get(); foreach ($rows as $row) { $matchId = (int) $row->id; if (isset($matches[$matchId])) { continue; } $payload = $this->buildPendingVoicePayload( $matchId, (array) $row ); if ($payload !== null) { $matches[$matchId] = $payload; } } } } catch (\Throwable $e) { Log::warning('GIGAX Bot: falha pending-voice active matches', [ 'error' => $e->getMessage(), ]); } return response()->json([ 'ok' => true, 'matches' => array_values($matches), 'count' => count($matches), ]); } public function cleanupVoice(Request $request) { $ids = []; try { if (!Schema::hasTable('mix_training_matches')) { return response()->json(['ok' => true, 'matches' => [], 'count' => 0]); } $columns = Schema::getColumnListing('mix_training_matches'); $query = DB::table('mix_training_matches'); // Somente partidas realmente encerradas. $query->where(function ($q) use ($columns) { $has = false; if (in_array('ended_at', $columns, true)) { $q->whereNotNull('ended_at'); $has = true; } if (in_array('status', $columns, true)) { $statuses = [ 'finished', 'ended', 'completed', 'cancelled', 'canceled', 'finalizada', 'finalizado', 'encerrada', 'encerrado' ]; if ($has) { $q->orWhereIn(DB::raw('LOWER(status)'), $statuses); } else { $q->whereIn(DB::raw('LOWER(status)'), $statuses); } } }); // Somente Discord. if (in_array('voice_mode', $columns, true)) { $query->whereRaw("LOWER(COALESCE(voice_mode, '')) IN (?, ?)", ['discord', 'a']); } // Nunca reenviar depois que voice-deleted marcou como deleted/removed. if (in_array('voice_status', $columns, true)) { $query->where(function ($q) { $q->whereNull('voice_status') ->orWhereNotIn(DB::raw('LOWER(voice_status)'), ['deleted', 'removed']); }); } // A partida só entra no cleanup se o Laravel ainda tiver evidência de sala Discord. $hasRoomColumn = in_array('discord_room_name', $columns, true); $hasInviteColumn = in_array('discord_invite_url', $columns, true); if ($hasRoomColumn || $hasInviteColumn) { $query->where(function ($q) use ($hasRoomColumn, $hasInviteColumn) { if ($hasRoomColumn) { $q->where(function ($qq) { $qq->whereNotNull('discord_room_name') ->where('discord_room_name', '<>', ''); }); } if ($hasInviteColumn) { $method = $hasRoomColumn ? 'orWhere' : 'where'; $q->{$method}(function ($qq) { $qq->whereNotNull('discord_invite_url') ->where('discord_invite_url', '<>', ''); }); } }); } else { // Sem coluna de evidência, não arriscamos enviar históricos infinitamente. return response()->json(['ok' => true, 'matches' => [], 'count' => 0]); } foreach ($query->select('id')->orderByDesc('id')->limit(100)->get() as $row) { $ids[] = (int) $row->id; } } catch (\Throwable $e) { Log::warning('GIGAX Bot: falha buscando cleanup-voice', [ 'error' => $e->getMessage(), ]); } return response()->json([ 'ok' => true, 'matches' => array_map(static fn ($id) => ['match_id' => $id], $ids), 'count' => count($ids), ]); } public function voiceCreated(Request $request, int $matchId) { $payload = $request->all(); $this->syncVoiceState($matchId, true, $payload); Log::info('GIGAX Bot: canal de voz criado', [ 'match_id' => $matchId, 'payload' => $payload, 'ip' => $request->ip(), ]); return response()->json([ 'ok' => true, 'match_id' => $matchId, 'voice_created' => true, 'message' => 'Canal de voz registrado.', ]); } public function voiceDeleted(Request $request, int $matchId) { $payload = $request->all(); $this->syncVoiceState($matchId, false, $payload); Log::info('GIGAX Bot: canal de voz removido', [ 'match_id' => $matchId, 'payload' => $payload, 'ip' => $request->ip(), ]); return response()->json([ 'ok' => true, 'match_id' => $matchId, 'voice_deleted' => true, 'message' => 'Canal de voz removido.', ]); } private function buildPendingVoicePayload(int $matchId, array $match): ?array { if (!Schema::hasTable('users')) { return null; } $players = collect(); // Partidas MIX tradicionais. if (Schema::hasTable('mix_match_players')) { try { $players = DB::table('mix_match_players as mp') ->join('users as u', 'u.id', '=', 'mp.user_id') ->where('mp.match_id', $matchId) ->whereIn('mp.team', [1, 2]) ->select( 'mp.user_id', 'mp.team', 'u.discord_id', 'u.discord_user_id' ) ->get(); } catch (\Throwable $e) { Log::warning('GIGAX Bot: falha lendo mix_match_players', [ 'match_id' => $matchId, 'error' => $e->getMessage(), ]); } } // Salas personalizadas / training lobby: // no fluxo atual os jogadores estao em mix_training_participants. if ($players->isEmpty() && Schema::hasTable('mix_training_participants')) { try { $players = DB::table('mix_training_participants as tp') ->join('users as u', 'u.id', '=', 'tp.user_id') ->where('tp.training_match_id', $matchId) ->whereNull('tp.left_at') ->whereIn('tp.team', [1, 2]) ->select( 'tp.user_id', 'tp.team', 'u.discord_id', 'u.discord_user_id' ) ->get(); } catch (\Throwable $e) { Log::warning('GIGAX Bot: falha lendo mix_training_participants', [ 'match_id' => $matchId, 'error' => $e->getMessage(), ]); } } $teamA = []; $teamB = []; foreach ($players as $player) { $discordId = trim((string) ($player->discord_user_id ?: $player->discord_id ?: '')); if ($discordId === '' || !ctype_digit($discordId)) { continue; } if ((int) $player->team === 1) { $teamA[] = $discordId; } elseif ((int) $player->team === 2) { $teamB[] = $discordId; } } // Nao cria sala sem nenhum jogador Discord identificavel. if ($teamA === [] && $teamB === []) { return null; } return [ 'match_id' => $matchId, 'display_mode' => $this->gigaxDisplayMode($match), 'map_name' => $match['map_name'] ?? null, 'status' => $match['status'] ?? null, 'voice_mode' => 'discord', 'team_a_discord_ids' => array_values(array_unique($teamA)), 'team_b_discord_ids' => array_values(array_unique($teamB)), ]; } private function gigaxDisplayMode(array $match): string { // Nunca inventar modalidade quando o registro nao a informa. $raw = strtolower(trim((string) ($match['mode'] ?? $match['game_mode'] ?? $match['match_mode'] ?? ''))); $type = strtolower(trim((string) ($match['type'] ?? $match['match_type'] ?? $match['category'] ?? ''))); $combined = $type.' '.$raw; if (str_contains($combined, 'times')) return 'OPEN - TIMES'; if (str_contains($combined, 'mix') || str_contains($combined, 'pug')) return 'OPEN - MIX'; if (str_contains($combined, '5l')) return '5L - 5V5'; $prefix = str_contains($combined, '4f') ? '4F' : (str_contains($combined, 'open') ? 'OPEN' : ''); if (preg_match('/\bx\s*([1-8])\b/', $combined, $m)) return trim($prefix.' - X'.$m[1], ' -'); if (str_contains($combined, '5v5')) return trim(($prefix ?: '5L').' - 5V5'); return 'PARTIDA'; } private function syncVoiceState(int $matchId, bool $created, array $payload): void { /* * Compatibilidade segura: * não exige migration e não presume uma tabela específica. * Atualiza somente tabelas/colunas que já existirem. */ $candidateTables = [ 'mix_active_matches', 'mix_match_history', 'mix_training_matches', 'active_matches', ]; foreach ($candidateTables as $table) { try { if (!Schema::hasTable($table)) { continue; } $columns = Schema::getColumnListing($table); $matchColumn = null; foreach (['id', 'match_id'] as $candidate) { if (in_array($candidate, $columns, true)) { $matchColumn = $candidate; break; } } if (!$matchColumn) { continue; } $update = []; $boolFields = [ 'discord_voice_created', 'voice_created', 'discord_voice_active', 'voice_active', ]; foreach ($boolFields as $field) { if (in_array($field, $columns, true)) { $update[$field] = $created ? 1 : 0; } } if (in_array('voice_status', $columns, true)) { $update['voice_status'] = $created ? 'created' : 'deleted'; } if (in_array('discord_room_name', $columns, true)) { $update['discord_room_name'] = $created ? ($payload['discord_room_name'] ?? $payload['channel_name'] ?? $payload['voice_channel_name'] ?? null) : null; } if (in_array('discord_invite_url', $columns, true)) { $update['discord_invite_url'] = $created ? ($payload['discord_invite_url'] ?? null) : null; } if (in_array('discord_voice_channel_id', $columns, true)) { $update['discord_voice_channel_id'] = $created ? ($payload['channel_id'] ?? $payload['voice_channel_id'] ?? $payload['discord_team_a_voice_id'] ?? null) : null; } if (in_array('discord_voice_channel_name', $columns, true)) { $update['discord_voice_channel_name'] = $created ? ($payload['channel_name'] ?? $payload['voice_channel_name'] ?? $payload['discord_room_name'] ?? null) : null; } if (in_array('discord_guild_id', $columns, true) && $created) { $update['discord_guild_id'] = $payload['guild_id'] ?? null; } if (in_array('voice_created_at', $columns, true)) { $update['voice_created_at'] = $created ? now() : null; } if (in_array('voice_deleted_at', $columns, true) && !$created) { $update['voice_deleted_at'] = now(); } if (in_array('updated_at', $columns, true)) { $update['updated_at'] = now(); } if ($update !== []) { DB::table($table) ->where($matchColumn, $matchId) ->update($update); } } catch (\Throwable $e) { Log::warning('GIGAX Bot: falha ao sincronizar estado de voz', [ 'table' => $table, 'match_id' => $matchId, 'created' => $created, 'error' => $e->getMessage(), ]); } } } }