matchMode($matchId); if ($mode !== 'B') { return ['success' => true, 'mode' => $mode, 'skipped' => true]; } try { $provision = app(TeamSpeakService::class)->provisionMatchChannels($matchId); $result = [ 'mode' => 'B', 'ts3' => [ 'success' => (bool) ($provision['success'] ?? false), 'provision' => $provision, 'message' => $provision['message'] ?? 'Salas TeamSpeak 3 provisionadas.', ], 'discord' => null, ]; $this->updateMatchVoiceStatus($matchId, $result); return $result; } catch (\Throwable $e) { Log::warning('Falha TS3 no provisionForMatch', ['match_id' => $matchId, 'error' => $e->getMessage()]); return ['success' => false, 'mode' => 'B', 'message' => $e->getMessage()]; } } public function startForMatch(int $matchId): array { $mode = $this->matchMode($matchId); $result = ['mode' => $mode, 'ts3' => null, 'discord' => null]; // GIGAX_VOICE_START_SAFE_V1 // A = Discord | B = TeamSpeak 3. if ($mode === 'A') { $result['discord'] = [ 'success' => true, 'queued' => true, 'message' => 'Criando sala Discord pelo GIGAX Bot...', ]; if (Schema::hasColumn('mix_training_matches', 'voice_status')) { $update = [ 'voice_status' => 'creating', 'voice_notes' => 'Criando sala Discord pelo GIGAX Bot...', ]; if (Schema::hasColumn('mix_training_matches', 'updated_at')) { $update['updated_at'] = now(); } DB::table('mix_training_matches') ->where('id', $matchId) ->update($update); } return $result; } if ($mode === 'B') { try { $teamSpeakService = app(TeamSpeakService::class); // Este método já provisiona as salas quando necessário e faz retry. $move = $teamSpeakService->moveMatchPlayersWithRetry($matchId, 8, 80); $result['ts3'] = [ 'success' => (bool) ($move['success'] ?? false), 'move' => $move, 'message' => $move['message'] ?? 'TeamSpeak 3 processado.', ]; } catch (\Throwable $e) { $result['ts3'] = [ 'success' => false, 'message' => $e->getMessage(), ]; Log::warning('Falha TS3 no startForMatch', [ 'match_id' => $matchId, 'error' => $e->getMessage(), ]); } } $this->updateMatchVoiceStatus($matchId, $result); return $result; } public function finishForMatch(int $matchId): array { /* GIGAX_FINISH_MOVE_DELETE_V3 */ $mode = $this->matchMode($matchId); $result = ['mode' => $mode, 'ts3' => null, 'discord' => null]; /* GIGAX_DRAFT_V216_PRESERVE_VOICE */ $isDraftMap = false; if (Schema::hasTable('gigax_draft_series_games')) { $isDraftMap = DB::table('gigax_draft_series_games')->where('training_match_id', $matchId)->exists(); } if (!$isDraftMap && Schema::hasTable('gigax_draft_matches')) { $isDraftMap = DB::table('gigax_draft_matches')->where('training_match_id', $matchId)->exists(); } if ($isDraftMap) { // GigaxDraftService cria o próximo mapa ou move o vencedor antes da limpeza. return [ 'mode' => $mode, 'draft' => true, 'preserved' => true, 'ts3' => ['success' => true, 'message' => 'Salas do Draft preservadas até o fechamento da série.'], 'discord' => null, ]; } if ($mode === 'A') { try { $ok = app(\App\Services\GigaxDiscordEventService::class)->matchEnded($matchId); $result['discord'] = [ 'success' => $ok, 'message' => $ok ? 'Jogadores retirados e salas Discord removidas.' : 'Bot Discord nao confirmou a limpeza.', ]; } catch (\Throwable $e) { $result['discord'] = ['success' => false, 'message' => $e->getMessage()]; Log::warning('Falha Discord no finishForMatch', [ 'match_id' => $matchId, 'error' => $e->getMessage(), ]); } } if ($mode === 'B') { try { $result['ts3'] = app(TeamSpeakService::class)->cleanupMatchChannels($matchId); } catch (\Throwable $e) { $result['ts3'] = ['success' => false, 'message' => $e->getMessage()]; Log::warning('Falha TS3 no finishForMatch', [ 'match_id' => $matchId, 'error' => $e->getMessage(), ]); } } $this->updateMatchVoiceStatus($matchId, $result, true); return $result; } public function buildMatchIntegration(int $matchId, int $userId): array { $match = DB::table('mix_training_matches')->where('id', $matchId)->first(); $mode = $this->matchMode($matchId, $match); $trainingType = strtolower(trim((string) ($match->training_type ?? ''))); $isC1s = $trainingType === 'c1s'; $participants = DB::table('mix_training_participants') ->where('training_match_id', $matchId) ->whereNull('left_at') ->count(); $userTeam = (int) (DB::table('mix_training_participants') ->where('training_match_id', $matchId) ->where('user_id', $userId) ->whereNull('left_at') ->value('team') ?? 0); $isAdmin = in_array((string) (session('user_role') ?? ''), ['admin', 'moderator'], true) || in_array((string) (DB::table('users')->where('id', $userId)->value('role') ?? 'user'), ['admin', 'moderator'], true); $discord = app(DiscordVoiceService::class)->describeForUser($matchId, $userId); $ts3Status = app(TeamSpeakService::class)->getMatchChannelStatus($matchId); $ts3Join = $this->buildTs3Join($ts3Status, $userId, $userTeam, $isC1s); return [ // Contrato unico consumido pelo modal: A=Discord, B=TeamSpeak 3. 'voice_mode' => $mode, 'provider' => $mode === 'B' ? 'teamspeak' : 'discord', 'choice' => $mode, 'choice_label' => $this->label($mode), 'mode' => $mode, 'participants_ready' => $isC1s ? $participants >= 2 : $participants >= 10, 'admin_defined_mode' => $this->label($mode), 'user_team' => $userTeam, 'access_rules' => $isC1s ? 'C1S individual: todos os jogadores confirmados entram na mesma sala.' : 'Salas privadas por time. Cada jogador entra na sala do próprio time; admins entram em todas.', 'discord' => $discord + [ 'label' => $this->modeAllows($mode, 'A') ? 'Liberado' : 'Desativado para esta partida', ], 'ts3' => $ts3Join + [ 'label' => $this->modeAllows($mode, 'B') ? 'Liberado' : 'Desativado para esta partida', ], 'join' => $this->pickJoin($mode, $discord, $ts3Join), 'admins_have_full_access' => $isAdmin, 'status' => $match->voice_status ?? null, 'notes' => $match->voice_notes ?? null, ]; } public function matchMode(int $matchId, $match = null): string { // GIGAX_MATCH_MODE_FROM_MATCH_V1 $match = $match ?: DB::table('mix_training_matches') ->where('id', $matchId) ->first(); $raw = strtolower(trim((string) ($match->voice_mode ?? ''))); if (in_array($raw, ['b', 'teamspeak', 'teamspeak3', 'ts3'], true)) { return 'B'; } if (in_array($raw, ['a', 'discord'], true)) { return 'A'; } return app(GlobalVoiceProviderService::class)->legacyMode(); } private function pickJoin(string $mode, array $discord, array $ts3): array { if ($mode === 'B') { return [ 'platform' => 'TS3', 'url' => $ts3['join_url'] ?? null, 'text' => 'Entrar na sala TS3 do meu time', ]; } return [ 'platform' => 'Discord', 'url' => $discord['join_url'] ?? null, 'text' => 'Entrar na sala Discord do meu time', ]; } private function buildTs3Join(array $status, int $userId, int $userTeam, bool $isC1s = false): array { $teamKey = $userTeam === 1 ? 'team_a' : ($userTeam === 2 ? 'team_b' : null); $channelName = $isC1s ? data_get($status, 'channels.root_channel_name') : ($teamKey && !empty($status['channels'][$teamKey . '_channel_name']) ? (string) $status['channels'][$teamKey . '_channel_name'] : null); $channelId = $isC1s ? (int) data_get($status, 'channels.root_channel_id', 0) : ($teamKey ? (int) data_get($status, 'channels.' . $teamKey . '_channel_id', 0) : 0); $host = (string) config('teamspeak.host', env('TEAMSPEAK_HOST', env('TS3_HOST', ''))); $port = (int) config('teamspeak.server_port', env('TS3_SERVER_PORT', 9987)); $url = null; if ($host !== '' && $channelId > 0) { $url = sprintf('ts3server://%s?port=%d&cid=%d', $host, $port, $channelId); } elseif ($host !== '' && $channelName !== null && $channelName !== '') { $url = sprintf( 'ts3server://%s?port=%d&channel=%s', $host, $port, rawurlencode($channelName) ); } return [ 'enabled' => app(TeamSpeakService::class)->enabled(), 'host' => $host, 'server_port' => $port, 'nickname_uid' => DB::table('users')->where('id', $userId)->value('ts3_unique_id'), 'team_room_name' => $channelName, 'channel_id' => $channelId ?: null, 'single_room' => $isC1s, 'root_channel_name' => data_get($status, 'channels.root_channel_name'), 'team_a_channel_name' => data_get($status, 'channels.team_a_channel_name'), 'team_b_channel_name' => data_get($status, 'channels.team_b_channel_name'), 'join_url' => $url, 'access_notice' => $isC1s ? 'C1S individual: todos os confirmados usam a mesma sala.' : ($userTeam ? 'Seu acesso fica restrito à sala privada do seu time; administradores entram em todas.' : 'Aguardando definição do seu time.'), ]; } private function label(string $mode): string { return ['A' => 'Discord', 'B' => 'TS3'][$mode] ?? 'Discord'; } private function modeAllows(string $mode, string $platform): bool { return $mode === $platform; } private function updateMatchVoiceStatus(int $matchId, array $result, bool $finished = false): void { if (!Schema::hasColumn('mix_training_matches', 'voice_status')) { return; } $ts3Ok = (bool) data_get($result, 'ts3.success', false); $discordOk = (bool) data_get($result, 'discord.success', false); $status = $finished ? 'finished' : (($ts3Ok || $discordOk) ? 'ready' : 'error'); $notes = collect([ data_get($result, 'ts3.message'), data_get($result, 'discord.message'), ])->filter()->implode(' | '); $update = [ 'voice_status' => $status, 'voice_notes' => $notes !== '' ? mb_substr($notes, 0, 255) : null, ]; if (Schema::hasColumn('mix_training_matches', 'updated_at')) { $update['updated_at'] = now(); } DB::table('mix_training_matches')->where('id', $matchId)->update($update); } }