$lobbyId ?: null, 'host' => (string) config('teamspeak.host'), 'query_port' => (int) config('teamspeak.query_port', 9998), 'server_id' => (int) config('teamspeak.server_id'), 'parent_channel_id' => (int) config('teamspeak.parent_channel_id'), 'fallback_channel_id' => (int) config('teamspeak.fallback_channel_id'), ]; } /** * Localiza um canal existente pelo nome e pelo canal pai. * Necessário para recuperar canais que foram criados no TS3, mas ainda * não chegaram a ser persistidos em lobby_ts3_channels. */ private function findChannelIdByName(string $channelName, string|int $parentId): ?string { $parentId = (string) $parentId; for ($attempt = 1; $attempt <= 3; $attempt++) { $response = $this->command('channellist'); $matches = []; foreach ($this->parseChannelEntries($response) as $entry) { $cid = (string) ($entry['cid'] ?? ''); $pid = (string) ($entry['pid'] ?? '0'); $name = (string) ($entry['channel_name'] ?? ''); if ($cid === '' || $name !== $channelName || $pid !== $parentId) { continue; } $matches[] = $cid; } if (!empty($matches)) { // Em caso de duplicata antiga, usa o CID mais recente. usort($matches, fn ($a, $b) => (int) $b <=> (int) $a); return (string) $matches[0]; } usleep(90000); } return null; } /** * Fallback robusto: localiza pelo nome sem depender do PID. * Útil quando o TS3 cria o canal, mas o channellist ainda reporta o parent de forma tardia. */ private function findChannelIdByNameAnyParent(string $channelName): ?string { try { $response = $this->command('channellist'); $matches = []; foreach ($this->parseChannelEntries($response) as $entry) { $cid = (string) ($entry['cid'] ?? ''); $name = (string) ($entry['channel_name'] ?? ''); if ($cid !== '' && $name === $channelName) { $matches[] = $cid; } } if (!$matches) return null; usort($matches, fn ($a, $b) => (int) $b <=> (int) $a); return (string) $matches[0]; } catch (\Throwable $e) { Log::warning('TS3 fallback por nome falhou.', ['channel_name' => $channelName, 'error' => $e->getMessage()]); return null; } } /** * Procura canal via channelfind e confirma o pai com channelinfo. * Alguns hosts/proxies TS3 retornam somente "error id=0 msg=ok" * no channelcreate, sem o cid criado. */ private function findChannelIdViaChannelFind(string $channelName, string|int $parentId): ?string { $parentId = (string) $parentId; try { $response = $this->command('channelfind pattern=' . $this->escape($channelName)); $data = $this->extractResponseData($response); if ($data === '') { return null; } $candidates = []; foreach (explode('|', $data) as $rawEntry) { $rawEntry = trim($rawEntry); if ($rawEntry === '') { continue; } if (!preg_match('/(?:^|\s)cid=(\d+)/', $rawEntry, $m)) { continue; } $cid = (string) $m[1]; try { $infoRaw = $this->command('channelinfo cid=' . $cid); $info = $this->extractResponseData($infoRaw); $infoPid = null; $infoName = null; if (preg_match('/(?:^|\s)pid=(\d+)/', $info, $pm)) { $infoPid = (string) $pm[1]; } if (preg_match('/(?:^|\s)channel_name=([^\s]+)/', $info, $nm)) { $infoName = $this->unescape((string) $nm[1]); } if ($infoName === $channelName && ($infoPid === null || $infoPid === $parentId)) { return $cid; } if ($infoName === $channelName) { $candidates[] = $cid; } } catch (\Throwable $e) { // Se channelinfo for bloqueado pelo host, ainda preserva o CID achado. $candidates[] = $cid; } } if ($candidates) { usort($candidates, fn ($a, $b) => (int) $b <=> (int) $a); return (string) $candidates[0]; } } catch (\Throwable $e) { Log::warning('TS3 channelfind falhou ao recuperar CID.', [ 'channel_name' => $channelName, 'parent_id' => $parentId, 'error' => $e->getMessage(), ]); } return null; } /** * Retorna os canais atuais indexados por CID. */ private function channelSnapshot(): array { $response = $this->command('channellist'); $snapshot = []; foreach ($this->parseChannelEntries($response) as $entry) { $cid = (string) ($entry['cid'] ?? ''); if ($cid === '') { continue; } $snapshot[$cid] = $entry; } return $snapshot; } /** * Recupera o CID de um canal recém-criado. * Primeiro usa o retorno do channelcreate; depois procura pelo nome/pai; * por último compara o channellist de antes/depois e identifica o novo CID. */ private function recoverCreatedChannelId( string $createResponse, string $channelName, string|int $parentId, array $beforeSnapshot = [] ): ?string { $cid = $this->extractId($createResponse, 'cid'); if ($cid) { return (string) $cid; } $parentId = (string) $parentId; for ($attempt = 1; $attempt <= 12; $attempt++) { if ($attempt > 1) { usleep(100000); } $cid = $this->findChannelIdViaChannelFind($channelName, $parentId) ?: $this->findChannelIdByName($channelName, $parentId) ?: $this->findChannelIdByNameAnyParent($channelName); if ($cid) { return (string) $cid; } try { $afterSnapshot = $this->channelSnapshot(); $newIds = array_diff(array_keys($afterSnapshot), array_keys($beforeSnapshot)); // Como apenas um channelcreate é executado por vez, se apareceu // exatamente um CID novo ele é o canal recém-criado, mesmo que o // provedor normalize/oculte o channel_name na listagem. if (count($newIds) === 1) { return (string) array_values($newIds)[0]; } $candidates = []; foreach ($newIds as $newId) { $entry = $afterSnapshot[$newId] ?? []; $name = (string) ($entry['channel_name'] ?? ''); $pid = (string) ($entry['pid'] ?? '0'); // Prioriza correspondência exata de nome + pai. if ($name === $channelName && $pid === $parentId) { return (string) $newId; } // Alguns hosts demoram a atualizar o PID; guarda pelo nome. if ($name === $channelName) { $candidates[] = (string) $newId; } } if (!empty($candidates)) { usort($candidates, fn ($a, $b) => (int) $b <=> (int) $a); return (string) $candidates[0]; } } catch (\Throwable $e) { Log::warning('TS3 recuperação de CID por snapshot falhou.', [ 'channel_name' => $channelName, 'parent_id' => $parentId, 'error' => $e->getMessage(), ]); } } Log::error('TS3 não conseguiu recuperar CID após channelcreate.', [ 'channel_name' => $channelName, 'parent_id' => $parentId, 'create_response' => trim($createResponse), ]); return null; } private function channelExists(string|int $channelId): bool { $channelId = (string) $channelId; if ($channelId === '' || $channelId === '0') { return false; } try { $response = $this->command('channellist'); foreach ($this->parseChannelEntries($response) as $entry) { if ((string) ($entry['cid'] ?? '') === $channelId) { return true; } } return false; } catch (\Throwable $e) { Log::warning('TS3 não conseguiu validar parent channel antes da criação.', $this->baseDebugContext() + [ 'channel_id' => $channelId, 'error' => $e->getMessage(), ]); return false; } } private function normalizeUid(string $uid): string { $uid = trim($uid); $uid = str_replace('\/', '/', $uid); $uid = str_replace('\/', '/', $uid); $missingPadding = strlen($uid) % 4; if ($missingPadding !== 0) { $uid .= str_repeat('=', 4 - $missingPadding); } return $uid; } /** * Lista somente clientes reais conectados ao TS3, incluindo UID e IP. * O ServerQuery (client_type=1) nunca é retornado. */ public function getOnlineClients(): array { if (!$this->enabled()) { return []; } try { $this->connect(); $raw = $this->command('clientlist -uid -ip'); $clients = []; foreach ($this->parseClientEntries($raw) as $entry) { if (($entry['client_type'] ?? '0') !== '0') { continue; } $uid = trim((string) ($entry['client_unique_identifier'] ?? '')); if ($uid === '') { continue; } $clients[] = [ 'uid' => $uid, 'nickname' => (string) ($entry['client_nickname'] ?? ''), 'clid' => isset($entry['clid']) ? (int) $entry['clid'] : null, 'cid' => isset($entry['cid']) ? (int) $entry['cid'] : null, 'ip' => (string) ($entry['connection_client_ip'] ?? ''), ]; } return $clients; } catch (\Throwable $e) { Log::warning('Falha ao listar clientes TS3 para captura de UID', [ 'error' => $e->getMessage(), ]); return []; } finally { $this->disconnect(); } } /** * Captura o UID do cliente online usando o nickname da conta GIGAX. * Se $expectedIp for informado, exige também o mesmo IP para evitar * que outro usuário copie o nickname e se vincule à conta errada. */ public function captureUniqueIdByNickname(string $nickname, ?string $expectedIp = null): array { $nickname = trim($nickname); $expectedIp = trim((string) $expectedIp); if ($nickname === '') { return ['success' => false, 'message' => 'Nickname GIGAX vazio.']; } $matches = array_values(array_filter($this->getOnlineClients(), function (array $client) use ($nickname) { return mb_strtolower(trim((string) ($client['nickname'] ?? '')), 'UTF-8') === mb_strtolower($nickname, 'UTF-8'); })); if ($expectedIp !== '') { $ipMatches = array_values(array_filter($matches, function (array $client) use ($expectedIp) { return trim((string) ($client['ip'] ?? '')) === $expectedIp; })); if (!empty($ipMatches)) { $matches = $ipMatches; } else { // V11: IP é apenas evidência auxiliar. Proxy/CGNAT/IPv4/IPv6 podem fazer // o IP da sessão web divergir do IP visto pelo TeamSpeak ServerQuery. // A vinculação continua protegida por nickname online único + UID TS3 // único (a checagem de proprietário é feita no controller). Log::info('GIGAX TS3: IP divergente durante captura automática; seguindo por UID/nickname único', [ 'nickname' => $nickname, 'web_ip' => $expectedIp, 'ts3_ips' => array_values(array_unique(array_filter(array_map( fn (array $client) => trim((string) ($client['ip'] ?? '')), $matches )))), ]); } } if (count($matches) === 0) { return [ 'success' => false, 'message' => 'Entre no TeamSpeak usando exatamente o mesmo nickname da GIGAX Arena e tente novamente.', ]; } if (count($matches) > 1) { return [ 'success' => false, 'message' => 'Há mais de um cliente TS3 usando esse nickname. Feche as conexões duplicadas e tente novamente.', ]; } $client = $matches[0]; return [ 'success' => true, 'message' => 'UID capturado automaticamente pelo TeamSpeak.', 'uid' => (string) $client['uid'], 'nickname' => (string) $client['nickname'], 'clid' => $client['clid'], 'cid' => $client['cid'], 'ip' => $client['ip'], ]; } public function validateUniqueId(string $uid): array { $uid = trim($uid); if (!$this->enabled()) { return [ 'success' => false, 'message' => 'TS3 desabilitado no .env', 'diagnostic' => [ 'enabled' => false, ], ]; } $diagnostic = $this->diagnosticBase($uid); try { $this->connect(); $diagnostic['connected'] = true; $whoAmI = $this->extractResponseData($this->command('whoami')); $serverInfo = $this->extractResponseData($this->command('serverinfo')); $diagnostic['whoami'] = $whoAmI; $diagnostic['serverinfo'] = $serverInfo; $clientList = $this->command('clientlist -uid'); $entries = $this->parseClientEntries($clientList); $realClients = array_values(array_filter($entries, function (array $entry) { return ($entry['client_type'] ?? '0') === '0'; })); $diagnostic['online_total'] = count($realClients); $diagnostic['online_uids_sample'] = array_slice(array_values(array_filter(array_map(function (array $entry) { return $entry['client_unique_identifier'] ?? null; }, $realClients))), 0, 10); $diagnostic['online_nicknames_sample'] = array_slice(array_values(array_filter(array_map(function (array $entry) { return $entry['client_nickname'] ?? null; }, $realClients))), 0, 10); Log::debug('Comparando UID TS3', [ 'input_uid' => $uid, 'normalized_uid' => $this->normalizeUid($uid), 'online_uids_sample' => $diagnostic['online_uids_sample'] ?? [], 'online_nicknames_sample' => $diagnostic['online_nicknames_sample'] ?? [], ]); $entry = $this->findClientEntryByUid($clientList, $uid); if (!$entry) { $result = [ 'success' => false, 'message' => 'Falha ao validar TeamSpeak agora. Confira se o UID está online no TS3.', 'nickname' => null, 'diagnostic' => $diagnostic, ]; Log::warning('TS3 UID não encontrado online', $diagnostic); return $result; } $diagnostic['matched_entry'] = [ 'clid' => $entry['clid'] ?? null, 'cid' => $entry['cid'] ?? null, 'client_nickname' => $entry['client_nickname'] ?? null, 'client_unique_identifier' => $entry['client_unique_identifier'] ?? null, ]; $result = [ 'success' => true, 'message' => 'UID validado com sucesso.', 'nickname' => $entry['client_nickname'] ?? null, 'clid' => $entry['clid'] ?? null, 'cid' => $entry['cid'] ?? null, 'diagnostic' => $diagnostic, ]; Log::info('TS3 UID validado com sucesso', $diagnostic); return $result; } catch (\Throwable $e) { $diagnostic['exception'] = $e->getMessage(); Log::error('Erro ao validar UID no TeamSpeak', $diagnostic); return [ 'success' => false, 'message' => 'Falha ao validar TeamSpeak agora. Confira host, query, credenciais e se o UID está online no TS3.', 'nickname' => null, 'diagnostic' => $diagnostic, ]; } finally { $this->disconnect(); } } public function testConnection(): array { if (!$this->enabled()) { return ['success' => false, 'message' => 'TS3 desabilitado no .env']; } try { $this->connect(); $whoAmI = $this->command('whoami'); $serverInfo = $this->command('serverinfo'); $result = [ 'success' => true, 'message' => 'Conexão TS3 realizada com sucesso.', 'whoami' => trim($whoAmI), 'serverinfo' => trim($serverInfo), ]; $this->persistActionLog('test_connection', 0, $result); return $result; } catch (\Throwable $e) { Log::error('Erro TS3 ao testar conexão', ['error' => $e->getMessage()]); $result = [ 'success' => false, 'message' => $e->getMessage(), ]; $this->persistActionLog('test_connection_failed', 0, $result); return $result; } finally { $this->disconnect(); } } /** * Diagnóstico completo + criação real de salas de teste. * * Cria: * [GIGAX] TESTE * TIME A * TIME B * * As salas são SEMI-PERMANENT e NÃO são removidas automaticamente. */ public function runFullDiagnosticTest(): array { $steps = []; $diagnostic = $this->baseDebugContext(); if (!$this->enabled()) { return [ 'success' => false, 'message' => 'TS3 desabilitado no .env', 'steps' => ['TeamSpeak está desabilitado na configuração.'], 'diagnostic' => $diagnostic, ]; } try { $this->connect(); $steps[] = 'ServerQuery conectado e autenticado'; $diagnostic['whoami'] = $this->extractResponseData( $this->command('whoami') ); $diagnostic['serverinfo'] = $this->extractResponseData( $this->command('serverinfo') ); $serverId = (int) config('teamspeak.server_id'); $steps[] = 'Virtual Server selecionado: ' . $serverId; $parentId = (int) config('teamspeak.parent_channel_id'); $useParent = $parentId > 0 && $this->channelExists($parentId); if ($parentId > 0 && $useParent) { $steps[] = 'Canal pai localizado: ' . $parentId; } elseif ($parentId > 0) { $steps[] = 'Canal pai ' . $parentId . ' não localizado; criando teste na raiz.'; } else { $steps[] = 'Canal pai não configurado; criando teste na raiz.'; } $testName = '[GIGAX] TESTE ' . date('d-m-Y H-i-s'); $escapedTestName = $this->escape($testName); $rootCommand = sprintf( 'channelcreate channel_name=%s%s channel_flag_semi_permanent=1', $escapedTestName, $useParent ? ' cpid=' . $parentId : '' ); $effectiveParent = $useParent ? $parentId : 0; $beforeRoot = $this->channelSnapshot(); $rootResponse = $this->command($rootCommand); $rootId = $this->recoverCreatedChannelId( $rootResponse, $testName, $effectiveParent, $beforeRoot ); if (!$rootId) { throw new \RuntimeException( 'A sala principal de teste foi solicitada, mas não foi possível localizar seu CID.' ); } $steps[] = 'Sala principal criada: ' . $testName . ' (#' . $rootId . ')'; $beforeTeamA = $this->channelSnapshot(); $teamAResponse = $this->command(sprintf( 'channelcreate channel_name=%s cpid=%s channel_flag_semi_permanent=1', $this->escape('TIME A'), $rootId )); $teamAId = $this->recoverCreatedChannelId( $teamAResponse, 'TIME A', $rootId, $beforeTeamA ); if (!$teamAId) { throw new \RuntimeException('TIME A foi solicitada, mas o CID não foi localizado.'); } $steps[] = 'TIME A criada (#' . $teamAId . ')'; $beforeTeamB = $this->channelSnapshot(); $teamBResponse = $this->command(sprintf( 'channelcreate channel_name=%s cpid=%s channel_flag_semi_permanent=1', $this->escape('TIME B'), $rootId )); $teamBId = $this->recoverCreatedChannelId( $teamBResponse, 'TIME B', $rootId, $beforeTeamB ); if (!$teamBId) { throw new \RuntimeException('TIME B foi solicitada, mas o CID não foi localizado.'); } $steps[] = 'TIME B criada (#' . $teamBId . ')'; $rawClients = $this->command('clientlist -uid -ip'); $clients = array_values(array_filter( $this->parseClientEntries($rawClients), static fn (array $entry): bool => ($entry['client_type'] ?? '0') === '0' )); $diagnostic['online_clients'] = count($clients); $diagnostic['test_channels'] = [ 'root_channel_id' => (int) $rootId, 'root_channel_name' => $testName, 'team_a_channel_id' => (int) $teamAId, 'team_a_channel_name' => 'TIME A', 'team_b_channel_id' => (int) $teamBId, 'team_b_channel_name' => 'TIME B', ]; $steps[] = 'Clientes reais online detectados: ' . count($clients); $steps[] = 'Salas de teste mantidas no servidor até limpeza manual.'; $result = [ 'success' => true, 'message' => 'Diagnóstico concluído e salas de teste criadas com sucesso.', 'steps' => $steps, 'channels' => $diagnostic['test_channels'], 'diagnostic' => $diagnostic, ]; $this->persistActionLog('full_diagnostic_create_test_rooms', 0, $result); return $result; } catch (\Throwable $e) { $steps[] = 'ERRO: ' . $e->getMessage(); $diagnostic['exception'] = $e->getMessage(); $result = [ 'success' => false, 'message' => 'Falha no diagnóstico/criação das salas TS3: ' . $e->getMessage(), 'steps' => $steps, 'diagnostic' => $diagnostic, ]; Log::error('Erro no diagnóstico completo TS3 com criação de salas', $result); $this->persistActionLog('full_diagnostic_create_test_rooms_failed', 0, $result); return $result; } finally { $this->disconnect(); } } /** * Remove apenas as salas criadas pelo diagnóstico: * [GIGAX] TESTE ... * TIME A * TIME B * * Jogadores encontrados nessas salas são movidos para o fallback antes da exclusão. */ public function cleanupDiagnosticTestChannels(): array { if (!$this->enabled()) { return ['success' => false, 'message' => 'TS3 desabilitado no .env']; } $deleted = 0; $moved = 0; $roots = []; try { $this->connect(); $response = $this->command('channellist'); $entries = $this->parseChannelEntries($response); $byPid = []; $byCid = []; foreach ($entries as $entry) { $cid = (string) ($entry['cid'] ?? ''); $pid = (string) ($entry['pid'] ?? '0'); $name = (string) ($entry['channel_name'] ?? ''); if ($cid === '') { continue; } $byCid[$cid] = $entry; $byPid[$pid][] = $cid; if (str_starts_with($name, '[GIGAX] TESTE ')) { $roots[] = $cid; } } $roots = array_values(array_unique($roots)); if (!$roots) { return [ 'success' => true, 'deleted' => 0, 'moved' => 0, 'message' => 'Nenhuma sala de diagnóstico GIGAX encontrada.', ]; } $allIds = []; $collect = function (string $cid) use (&$collect, &$allIds, $byPid): void { if (isset($allIds[$cid])) { return; } $allIds[$cid] = true; foreach ($byPid[$cid] ?? [] as $childCid) { $collect((string) $childCid); } }; foreach ($roots as $rootCid) { $collect((string) $rootCid); } $channelIds = array_keys($allIds); $clientList = $this->command('clientlist -uid'); $clientIds = $this->findClientIdsByChannelIds($clientList, $channelIds); $fallbackId = (int) config('teamspeak.fallback_channel_id'); if ($fallbackId > 0) { foreach ($clientIds as $clid) { $this->command('clientmove clid=' . $clid . ' cid=' . $fallbackId); $moved++; } } // Filhos primeiro, raízes por último. $depth = function (string $cid) use ($byCid): int { $d = 0; $seen = []; while (isset($byCid[$cid])) { $pid = (string) ($byCid[$cid]['pid'] ?? '0'); if ($pid === '0' || isset($seen[$pid])) { break; } $seen[$pid] = true; $d++; $cid = $pid; } return $d; }; usort($channelIds, fn ($a, $b) => $depth((string) $b) <=> $depth((string) $a)); foreach ($channelIds as $cid) { if ($this->deleteChannelIfExists((string) $cid)) { $deleted++; } } $result = [ 'success' => true, 'deleted' => $deleted, 'moved' => $moved, 'message' => "{$deleted} sala(s) de diagnóstico removida(s); {$moved} jogador(es) movido(s) para o fallback.", ]; $this->persistActionLog('cleanup_diagnostic_test_channels', 0, $result); return $result; } catch (\Throwable $e) { $result = [ 'success' => false, 'deleted' => $deleted, 'moved' => $moved, 'message' => 'Falha ao limpar salas de diagnóstico TS3: ' . $e->getMessage(), ]; Log::error('Erro ao limpar salas de diagnóstico TS3', $result); $this->persistActionLog('cleanup_diagnostic_test_channels_failed', 0, $result); return $result; } finally { $this->disconnect(); } } public function getMatchChannelStatus(int $lobbyId): array { $channels = DB::table('lobby_ts3_channels')->where('training_match_id', $lobbyId)->first(); if (!$channels) { return [ 'success' => true, 'exists' => false, 'message' => 'Nenhuma sala temporária registrada para este lobby.', ]; } $players = DB::select( 'SELECT tp.user_id, tp.team, u.nickname, u.ts3_unique_id FROM mix_training_participants tp JOIN users u ON u.id = tp.user_id WHERE tp.training_match_id = ? AND tp.left_at IS NULL ORDER BY tp.team, u.nickname', [$lobbyId] ); $online = []; $offline = []; try { $this->connect(); $clientList = $this->command('clientlist -uid'); foreach ($players as $player) { if (empty($player->ts3_unique_id)) { $offline[] = [ 'nickname' => $player->nickname, 'team' => (int) $player->team, 'reason' => 'sem ts3_unique_id', ]; continue; } $entry = $this->findClientEntryByUid($clientList, (string) $player->ts3_unique_id); if (!$entry) { $offline[] = [ 'nickname' => $player->nickname, 'team' => (int) $player->team, 'reason' => 'offline no TS3', ]; continue; } $online[] = [ 'nickname' => $player->nickname, 'team' => (int) $player->team, 'clid' => $entry['clid'] ?? null, 'cid' => $entry['cid'] ?? null, 'client_nickname' => $entry['client_nickname'] ?? $player->nickname, ]; } 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, ], 'online_players' => $online, 'offline_players' => $offline, 'message' => 'Status TS3 carregado com sucesso.', ]; } catch (\Throwable $e) { Log::error('Erro TS3 ao buscar status do lobby', ['error' => $e->getMessage(), 'lobby_id' => $lobbyId]); return [ 'success' => false, 'exists' => true, 'message' => $e->getMessage(), ]; } finally { $this->disconnect(); } } public function provisionMatchChannels(int $lobbyId): array { if (!$this->enabled()) { return ['success' => false, 'message' => 'TS3 desabilitado no .env']; } $existing = DB::table('lobby_ts3_channels')->where('training_match_id', $lobbyId)->first(); $lobby = DB::selectOne('SELECT id, title, map_name, training_type FROM mix_training_matches WHERE id = ?', [$lobbyId]); if (!$lobby) { return ['success' => false, 'message' => 'Lobby não encontrado']; } // C1S é individual: uma única sala para todos, sem Time A / Time B. $trainingType = strtolower(trim((string) ($lobby->training_type ?? ''))); $isC1s = $trainingType === 'c1s'; try { $this->connect(); // Nunca confia cegamente nos CIDs gravados: canais temporários podem // desaparecer quando ficam vazios. Se todos ainda existem, reutiliza. // Se algum sumiu, remove o registro obsoleto e reconstrói o conjunto. if ($existing && $existing->root_channel_id) { $rootOk = $this->channelExists((int) $existing->root_channel_id); if ($isC1s) { // No C1S os três campos apontam para o MESMO CID por compatibilidade // com a tabela existente; fisicamente existe apenas uma sala. if ($rootOk) { return [ 'success' => true, 'channels' => (array) $existing, 'message' => 'Sala C1S TS3 já existia', ]; } } elseif ($existing->team_a_channel_id && $existing->team_b_channel_id) { $teamAOk = $this->channelExists((int) $existing->team_a_channel_id); $teamBOk = $this->channelExists((int) $existing->team_b_channel_id); if ($rootOk && $teamAOk && $teamBOk) { return ['success' => true, 'channels' => (array) $existing, 'message' => 'Salas TS3 já existiam']; } } DB::table('lobby_ts3_channels')->where('training_match_id', $lobbyId)->delete(); } $rootNameRaw = $this->matchRootName($lobby); $rootName = $this->escape($rootNameRaw); $parentChannelId = (int) config('teamspeak.parent_channel_id'); $useParentChannel = $parentChannelId > 0 && $this->channelExists($parentChannelId); $effectiveParentId = $useParentChannel ? $parentChannelId : 0; // Idempotência: se a sala foi criada numa tentativa anterior, reutiliza o CID. $rootId = $this->findChannelIdByName($rootNameRaw, $effectiveParentId) ?: $this->findChannelIdByNameAnyParent($rootNameRaw); $rootWasExisting = (bool) $rootId; $rootResponse = ''; if (!$rootId) { $rootCommand = sprintf( 'channelcreate channel_name=%s%s channel_flag_semi_permanent=1', $rootName, $useParentChannel ? ' cpid=' . $parentChannelId : '' ); try { $beforeRoot = $this->channelSnapshot(); $rootResponse = $this->command($rootCommand); $rootId = $this->recoverCreatedChannelId( $rootResponse, $rootNameRaw, $effectiveParentId, $beforeRoot ); } catch (\Throwable $e) { if (str_contains($e->getMessage(), 'error id=771')) { $rootId = $this->findChannelIdByName($rootNameRaw, $effectiveParentId) ?: $this->findChannelIdByNameAnyParent($rootNameRaw); } if (!$rootId) { throw $e; } } } if (!$rootId) { throw new \RuntimeException('Não foi possível obter o canal raiz da partida no TS3.'); } /* * C1S: a própria sala raiz É a sala da partida. * Não cria Time A nem Time B. * * Para preservar a estrutura atual de lobby_ts3_channels sem migration, * team_a_channel_id e team_b_channel_id recebem o mesmo CID da sala única. */ if ($isC1s) { DB::table('lobby_ts3_channels')->updateOrInsert( ['training_match_id' => $lobbyId], [ 'root_channel_id' => $rootId, 'root_channel_name' => $this->matchRootName($lobby), 'team_a_channel_id' => $rootId, 'team_a_channel_name' => 'C1S', 'team_b_channel_id' => $rootId, 'team_b_channel_name' => 'C1S', 'updated_at' => now(), 'created_at' => now(), ] ); DB::table('mix_training_matches') ->where('id', $lobbyId) ->update([ 'voice_status' => 'ready', 'voice_notes' => 'TeamSpeak 3 pronto', 'updated_at' => now(), ]); $result = [ 'success' => true, 'channels' => [ 'root_channel_id' => $rootId, 'team_a_channel_id' => $rootId, 'team_b_channel_id' => $rootId, ], 'single_channel' => true, 'message' => 'Sala única C1S criada com sucesso no TS3.', ]; $this->persistActionLog('provision', $lobbyId, $result); return $result; } $teamAId = $this->findChannelIdByName('Time A', $rootId); $teamBId = $this->findChannelIdByName('Time B', $rootId); // Se sobrou apenas parte de uma árvore TEMPORARY antiga (ex.: raiz // existe porque havia jogador nela, mas Time A/Time B sumiram vazios), // reconstrói tudo como SEMI-PERMANENT. Assim os canais permanecem // enquanto a partida estiver ativa e o cleanup final os apaga. if ($rootWasExisting && $rootId && (!$teamAId || !$teamBId)) { try { $staleIds = array_values(array_filter([$teamAId, $teamBId, $rootId])); $clientList = $this->command('clientlist -uid'); $clientIds = $this->findClientIdsByChannelIds($clientList, $staleIds); $fallbackId = (int) config('teamspeak.fallback_channel_id'); if ($fallbackId > 0) { foreach ($clientIds as $clid) { $this->command('clientmove clid=' . $clid . ' cid=' . $fallbackId); } } if ($teamAId) { $this->deleteChannelIfExists($teamAId); } if ($teamBId) { $this->deleteChannelIfExists($teamBId); } $this->deleteChannelIfExists($rootId); } catch (\Throwable $cleanupError) { Log::warning('TS3 não conseguiu limpar árvore temporária obsoleta antes de reconstruir.', $this->baseDebugContext($lobbyId) + ['error' => $cleanupError->getMessage()]); } $rootId = null; $teamAId = null; $teamBId = null; $rootCommand = sprintf( 'channelcreate channel_name=%s%s channel_flag_semi_permanent=1', $rootName, $useParentChannel ? ' cpid=' . $parentChannelId : '' ); $beforeRoot = $this->channelSnapshot(); $rootResponse = $this->command($rootCommand); $rootId = $this->recoverCreatedChannelId( $rootResponse, $rootNameRaw, $effectiveParentId, $beforeRoot ); } if (!$teamAId) { try { $beforeTeamA = $this->channelSnapshot(); $teamAResponse = $this->command(sprintf( 'channelcreate channel_name=%s cpid=%s channel_flag_semi_permanent=1', $this->escape('Time A'), $rootId )); $teamAId = $this->recoverCreatedChannelId( $teamAResponse, 'Time A', $rootId, $beforeTeamA ); } catch (\Throwable $e) { if (str_contains($e->getMessage(), 'error id=771')) { $teamAId = $this->findChannelIdByName('Time A', $rootId); } if (!$teamAId) { throw $e; } } } if (!$teamBId) { try { $beforeTeamB = $this->channelSnapshot(); $teamBResponse = $this->command(sprintf( 'channelcreate channel_name=%s cpid=%s channel_flag_semi_permanent=1', $this->escape('Time B'), $rootId )); $teamBId = $this->recoverCreatedChannelId( $teamBResponse, 'Time B', $rootId, $beforeTeamB ); } catch (\Throwable $e) { if (str_contains($e->getMessage(), 'error id=771')) { $teamBId = $this->findChannelIdByName('Time B', $rootId); } if (!$teamBId) { throw $e; } } } if (!$teamAId || !$teamBId) { throw new \RuntimeException('Não foi possível obter os canais dos times no TS3.'); } DB::table('lobby_ts3_channels')->updateOrInsert( ['training_match_id' => $lobbyId], [ 'root_channel_id' => $rootId, 'root_channel_name' => $this->matchRootName($lobby), 'team_a_channel_id' => $teamAId, 'team_a_channel_name' => 'Time A', 'team_b_channel_id' => $teamBId, 'team_b_channel_name' => 'Time B', 'updated_at' => now(), 'created_at' => now(), ] ); $result = [ 'success' => true, 'channels' => [ 'root_channel_id' => $rootId, 'team_a_channel_id' => $teamAId, 'team_b_channel_id' => $teamBId, ], 'message' => 'Salas da partida criadas com sucesso no TS3.', ]; DB::table('mix_training_matches') ->where('id', $lobbyId) ->update([ 'voice_status' => 'ready', 'voice_notes' => 'TeamSpeak 3 pronto', 'updated_at' => now(), ]); $this->persistActionLog('provision', $lobbyId, $result); return $result; } catch (\Throwable $e) { Log::error('Erro TS3 ao criar canais', $this->baseDebugContext($lobbyId) + ['error' => $e->getMessage()]); DB::table('mix_training_matches') ->where('id', $lobbyId) ->update([ 'voice_status' => 'error', 'voice_notes' => mb_substr($e->getMessage(), 0, 500), 'updated_at' => now(), ]); $result = ['success' => false, 'message' => $e->getMessage()]; $this->persistActionLog('provision_failed', $lobbyId, $result); return $result; } finally { $this->disconnect(); } } /** * GIGAX TS3 V162: movimenta somente para o CID real do time. * Valida a hierarquia do canal e confirma o CID após o movimento. */ public function moveMatchPlayers(int $lobbyId): array { if (!$this->enabled()) { return ['success' => false, 'message' => 'TS3 desabilitado no .env']; } $match = DB::table('mix_training_matches')->where('id', $lobbyId)->select('training_type')->first(); if (!$match) { return ['success' => false, 'message' => 'Partida não encontrada.']; } $isC1s = strtolower(trim((string) ($match->training_type ?? ''))) === 'c1s'; // Provisionar/revalidar CIDs mesmo quando o banco já possui registros antigos. $provision = $this->provisionMatchChannels($lobbyId); if (!($provision['success'] ?? false)) { return $provision; } $channels = DB::table('lobby_ts3_channels')->where('training_match_id', $lobbyId)->first(); if (!$channels) { return ['success' => false, 'message' => 'Canais não persistidos no banco.']; } $players = DB::select( 'SELECT tp.user_id, tp.team, u.nickname, u.ts3_unique_id FROM mix_training_participants tp JOIN users u ON u.id = tp.user_id WHERE tp.training_match_id = ? AND tp.left_at IS NULL', [$lobbyId] ); $moved = 0; $missing = []; $verified = []; try { $this->connect(); $rootId = (int) $channels->root_channel_id; $aId = (int) $channels->team_a_channel_id; $bId = (int) $channels->team_b_channel_id; $snapshot = $this->channelSnapshot(); if (!isset($snapshot[(string) $rootId])) { throw new \RuntimeException('CID raiz da partida não existe no TS3.'); } if (!$isC1s) { if ($aId <= 0 || $bId <= 0 || $aId === $bId || $aId === $rootId || $bId === $rootId) { throw new \RuntimeException('CIDs dos times inválidos ou apontando para a raiz.'); } foreach ([$aId => 'Time A', $bId => 'Time B'] as $cid => $name) { $entry = $snapshot[(string) $cid] ?? null; if (!$entry || (int) ($entry['pid'] ?? 0) !== $rootId || strcasecmp(trim((string) ($entry['channel_name'] ?? '')), $name) !== 0) { throw new \RuntimeException($name . ': CID não pertence à raiz desta partida.'); } } } $list = $this->command('clientlist -uid'); foreach ($players as $player) { $nick = (string) $player->nickname; if (empty($player->ts3_unique_id)) { $missing[] = $nick . ' (UID TS3 não vinculado)'; continue; } $entry = $this->findClientEntryByUid($list, (string) $player->ts3_unique_id); if (!$entry || empty($entry['clid'])) { $missing[] = $nick . ' (offline no TS3)'; continue; } $team = (int) $player->team; if (!$isC1s && !in_array($team, [1, 2], true)) { $missing[] = $nick . ' (time inválido: ' . $team . ')'; continue; } $target = $isC1s ? $rootId : ($team === 1 ? $aId : $bId); $clid = (int) $entry['clid']; if ((int) ($entry['cid'] ?? 0) !== $target) { try { $this->command('clientmove clid=' . $clid . ' cid=' . $target); } catch (\Throwable $moveError) { $missing[] = $nick . ' (falha no clientmove: ' . $moveError->getMessage() . ')'; continue; } } $confirmed = false; for ($check = 0; $check < 3; $check++) { if ($check > 0) usleep(100000); $current = $this->findClientEntryByUid( $this->command('clientlist -uid'), (string) $player->ts3_unique_id ); if ($current && (int) ($current['cid'] ?? 0) === $target) { $confirmed = true; break; } } if ($confirmed) { $moved++; $verified[] = ['nickname' => $nick, 'team' => $team, 'cid' => $target]; } else { $missing[] = $nick . ' (destino CID ' . $target . ' não confirmado)'; } } DB::table('lobby_ts3_channels')->where('training_match_id', $lobbyId)->update([ 'last_move_at' => now(), 'updated_at' => now(), ]); $complete = empty($missing); $result = [ 'success' => $complete, 'moved' => $moved, 'missing' => $missing, 'verified' => $verified, 'channels' => ['root' => $rootId, 'team_a' => $aId, 'team_b' => $bId], 'message' => $complete ? $moved . ' jogador(es) confirmados no canal correto.' : $moved . ' confirmado(s); ' . count($missing) . ' pendente(s).', ]; DB::table('mix_training_matches')->where('id', $lobbyId)->update([ 'voice_status' => $complete ? 'ready' : 'error', 'voice_notes' => mb_substr($result['message'], 0, 500), 'updated_at' => now(), ]); $this->persistActionLog('move_players_verified_v162', $lobbyId, $result); return $result; } catch (\Throwable $e) { Log::error('TS3 V162 falha ao mover jogadores', ['lobby_id' => $lobbyId, 'error' => $e->getMessage()]); $result = ['success' => false, 'moved' => $moved, 'missing' => $missing, 'message' => $e->getMessage()]; $this->persistActionLog('move_players_failed_v162', $lobbyId, $result); return $result; } finally { $this->disconnect(); } } public function moveMatchPlayersWithRetry(int $lobbyId, int $attempts = 8, int $delayMs = 80): array { $attempts = max(1, min(8, $attempts)); $delayMs = max(80, min(500, $delayMs)); $last = ['success' => false, 'moved' => 0, 'missing' => [], 'message' => 'Movimentação não executada.']; for ($attempt = 1; $attempt <= $attempts; $attempt++) { $last = $this->moveMatchPlayers($lobbyId); if (($last['success'] ?? false) && empty($last['missing'] ?? [])) { $last['attempt'] = $attempt; return $last; } if ($attempt < $attempts) usleep($delayMs * 1000); } $last['attempt'] = $attempts; return $last; } /** * GIGAX DRAFT V1 * Cria a árvore completa do Draft sem alterar o provisionamento normal de lobbies. * Estrutura: DRAFT -> FASE -> JOGO -> TIME A / TIME B. */ public function provisionDraftTree(int $draftId): array { if (!$this->enabled()) { return ['success' => false, 'message' => 'TS3 desabilitado no .env']; } if (!\Illuminate\Support\Facades\Schema::hasTable('gigax_drafts') || !\Illuminate\Support\Facades\Schema::hasTable('gigax_draft_ts3_channels')) { return ['success' => false, 'message' => 'Tabelas do GIGAX DRAFT ainda não existem.']; } $draft = DB::table('gigax_drafts')->where('id', $draftId)->first(); if (!$draft) { return ['success' => false, 'message' => 'Draft não encontrado.']; } $matches = DB::table('gigax_draft_matches') ->where('draft_id', $draftId) ->orderBy('round_number') ->orderBy('match_number') ->get(); try { $this->connect(); $configuredParent = (int) config('teamspeak.parent_channel_id'); $parentId = ($configuredParent > 0 && $this->channelExists($configuredParent)) ? $configuredParent : 0; $type = strtoupper((string) $draft->draft_type); $rootName = '[GIGAX] DRAFT #' . $draftId . ' - ' . $type; $rootId = $this->createDraftChannel($rootName, $parentId); $this->persistDraftChannel($draftId, null, 'root', $rootId, $rootName, $parentId); $roundParents = []; foreach ($matches->groupBy('round_number') as $round => $roundMatches) { $count = $roundMatches->count(); $teamsInRound = max(2, $count * 2); $phase = match ($teamsInRound) { 2 => 'FINAL', 4 => 'SEMIFINAIS', 8 => 'QUARTAS DE FINAL', 16 => 'OITAVAS DE FINAL', 32 => 'FASE DE 32', 64 => 'FASE DE 64', 128 => 'FASE DE 128', 256 => 'FASE DE 256', default => 'FASE ' . (int) $round, }; $phaseName = '⚔ ' . $phase; $phaseId = $this->createDraftChannel($phaseName, $rootId); $roundParents[(int) $round] = $phaseId; $this->persistDraftChannel($draftId, null, 'round_' . (int) $round, $phaseId, $phaseName, $rootId); foreach ($roundMatches as $match) { // Em chaves grandes (até 256 times), não cria centenas de salas // futuras vazias. A sala nasce assim que pelo menos um classificado // chega ao confronto; a 1ª fase já nasce completa normalmente. if (empty($match->entry_a_id) && empty($match->entry_b_id)) { continue; } $gameName = 'JOGO ' . str_pad((string) $match->match_number, 3, '0', STR_PAD_LEFT); $gameId = $this->createDraftChannel($gameName, $phaseId); $teamAId = $this->createDraftChannel('TIME A', $gameId); $teamBId = $this->createDraftChannel('TIME B', $gameId); $this->persistDraftChannel($draftId, (int) $match->id, 'match', $gameId, $gameName, $phaseId); $this->persistDraftChannel($draftId, (int) $match->id, 'team_a', $teamAId, 'TIME A', $gameId); $this->persistDraftChannel($draftId, (int) $match->id, 'team_b', $teamBId, 'TIME B', $gameId); } } return [ 'success' => true, 'draft_id' => $draftId, 'root_channel_id' => $rootId, 'matches' => $matches->count(), 'message' => 'Árvore do Draft preparada no TeamSpeak 3. Salas futuras são criadas conforme os vencedores avançam.', ]; } catch (\Throwable $e) { Log::error('GIGAX DRAFT: erro ao criar árvore TS3', ['draft_id' => $draftId, 'error' => $e->getMessage()]); return ['success' => false, 'message' => $e->getMessage()]; } finally { $this->disconnect(); } } private function createDraftChannel(string $name, string|int $parentId): string { $existing = $this->findChannelIdByName($name, $parentId); if ($existing) { return (string) $existing; } $before = $this->channelSnapshot(); $command = 'channelcreate channel_name=' . $this->escape($name) . ((int) $parentId > 0 ? ' cpid=' . (int) $parentId : '') . ' channel_flag_semi_permanent=1'; try { $response = $this->command($command); $id = $this->recoverCreatedChannelId($response, $name, $parentId, $before); } catch (\Throwable $e) { if (str_contains($e->getMessage(), 'error id=771')) { $id = $this->findChannelIdByName($name, $parentId); } else { throw $e; } } if (empty($id)) { throw new \RuntimeException('Não foi possível obter CID do canal DRAFT: ' . $name); } return (string) $id; } private function persistDraftChannel(int $draftId, ?int $draftMatchId, string $role, string|int $channelId, string $name, string|int $parentId): void { DB::table('gigax_draft_ts3_channels')->updateOrInsert( ['draft_id' => $draftId, 'draft_match_id' => $draftMatchId, 'channel_role' => $role], [ 'channel_id' => (string) $channelId, 'channel_name' => $name, 'parent_channel_id' => (string) $parentId, 'updated_at' => now(), 'created_at' => now(), ] ); } /** Vincula um lobby real às salas previamente criadas para o confronto do Draft. */ public function bindDraftMatchLobby(int $draftMatchId, int $lobbyId): array { $match = DB::table('gigax_draft_matches')->where('id', $draftMatchId)->first(); if (!$match) { return ['success' => false, 'message' => 'Confronto DRAFT não encontrado.']; } $rows = DB::table('gigax_draft_ts3_channels')->where('draft_match_id', $draftMatchId)->get()->keyBy('channel_role'); $root = $rows->get('match'); $a = $rows->get('team_a'); $b = $rows->get('team_b'); if (!$root || !$a || !$b) { $this->provisionDraftTree((int) $match->draft_id); $rows = DB::table('gigax_draft_ts3_channels')->where('draft_match_id', $draftMatchId)->get()->keyBy('channel_role'); $root = $rows->get('match'); $a = $rows->get('team_a'); $b = $rows->get('team_b'); } if (!$root || !$a || !$b) { return ['success' => false, 'message' => 'Salas do confronto DRAFT não foram encontradas.']; } DB::table('lobby_ts3_channels')->updateOrInsert( ['training_match_id' => $lobbyId], [ 'root_channel_id' => (string) $root->channel_id, 'root_channel_name' => (string) $root->channel_name, 'team_a_channel_id' => (string) $a->channel_id, 'team_a_channel_name' => (string) $a->channel_name, 'team_b_channel_id' => (string) $b->channel_id, 'team_b_channel_name' => (string) $b->channel_name, 'updated_at' => now(), 'created_at' => now(), ] ); return ['success' => true, 'root' => $root->channel_id, 'team_a' => $a->channel_id, 'team_b' => $b->channel_id]; } /** Move o vencedor imediatamente para o slot da próxima fase, mesmo antes do adversário ser definido. */ public function moveDraftEntryToSlot(int $draftMatchId, int $entryId, string $slot): array { if (!$this->enabled()) { return ['success' => false, 'message' => 'TS3 desabilitado no .env']; } $role = strtoupper($slot) === 'B' ? 'team_b' : 'team_a'; $channel = DB::table('gigax_draft_ts3_channels')->where('draft_match_id', $draftMatchId)->where('channel_role', $role)->first(); if (!$channel) { $draftId = (int) (DB::table('gigax_draft_matches')->where('id', $draftMatchId)->value('draft_id') ?? 0); if ($draftId > 0) { $this->provisionDraftTree($draftId); $channel = DB::table('gigax_draft_ts3_channels')->where('draft_match_id', $draftMatchId)->where('channel_role', $role)->first(); } } if (!$channel) { return ['success' => false, 'message' => 'Canal da próxima fase não encontrado.']; } $players = DB::table('gigax_draft_members as dm') ->join('users as u', 'u.id', '=', 'dm.user_id') ->where('dm.entry_id', $entryId) ->select('u.nickname', 'u.ts3_unique_id')->get(); try { $this->connect(); $clientList = $this->command('clientlist -uid'); $moved = 0; $missing = []; foreach ($players as $player) { if (empty($player->ts3_unique_id)) { $missing[] = $player->nickname . ' (sem UID)'; continue; } $clid = $this->findClientIdByUid($clientList, (string) $player->ts3_unique_id); if (!$clid) { $missing[] = $player->nickname . ' (offline)'; continue; } $this->command('clientmove clid=' . $clid . ' cid=' . (int) $channel->channel_id); $moved++; } return ['success' => true, 'moved' => $moved, 'missing' => $missing, 'channel_id' => $channel->channel_id]; } catch (\Throwable $e) { return ['success' => false, 'message' => $e->getMessage()]; } finally { $this->disconnect(); } } /** Limpa apenas a árvore do Draft; o restante do TS3 permanece intocado. */ public function cleanupDraftTree(int $draftId): array { if (!$this->enabled()) { return ['success' => false, 'message' => 'TS3 desabilitado no .env']; } $rows = DB::table('gigax_draft_ts3_channels')->where('draft_id', $draftId)->get(); if ($rows->isEmpty()) { return ['success' => true, 'deleted' => 0, 'message' => 'Árvore DRAFT já estava limpa.']; } try { $this->connect(); $ids = $rows->pluck('channel_id')->filter()->map(fn ($id) => (string) $id)->unique()->values()->all(); $clientList = $this->command('clientlist -uid'); $clients = $this->findClientIdsByChannelIds($clientList, $ids); $fallbackId = (int) config('teamspeak.fallback_channel_id'); foreach ($clients as $clid) { if ($fallbackId > 0) $this->command('clientmove clid=' . $clid . ' cid=' . $fallbackId); } $priority = ['team_a' => 1, 'team_b' => 1, 'match' => 2, 'root' => 9]; $ordered = $rows->sortBy(function ($row) use ($priority) { if (str_starts_with((string) $row->channel_role, 'round_')) return 5; return $priority[(string) $row->channel_role] ?? 4; }); $deleted = 0; foreach ($ordered as $row) { if ($this->deleteChannelIfExists((string) $row->channel_id)) $deleted++; } DB::table('gigax_draft_ts3_channels')->where('draft_id', $draftId)->delete(); return ['success' => true, 'deleted' => $deleted, 'moved' => count($clients), 'message' => 'Árvore DRAFT removida.']; } catch (\Throwable $e) { Log::warning('GIGAX DRAFT: cleanup TS3 falhou', ['draft_id' => $draftId, 'error' => $e->getMessage()]); return ['success' => false, 'message' => $e->getMessage()]; } finally { $this->disconnect(); } } /** * GIGAX V176 - cleanup resiliente de salas da partida. * * O registro em lobby_ts3_channels pode faltar mesmo com a sala ainda viva * no TeamSpeak (ex.: falha entre channelcreate e persistência). Neste caso * localizamos a árvore pelo prefixo único "Lobby # - " e limpamos * os canais físicos antes de remover qualquer vínculo restante no banco. */ public function cleanupMatchChannels(int $lobbyId): array { if (!$this->enabled()) { return ['success' => false, 'message' => 'TS3 desabilitado no .env']; } $registered = DB::table('lobby_ts3_channels') ->where('training_match_id', $lobbyId) ->first(); $lastError = null; // Ação administrativa: poucas tentativas curtas evitam deixar sala órfã // por uma queda momentânea do ServerQuery (ex.: errno 10053). for ($attempt = 1; $attempt <= 3; $attempt++) { try { $this->connect(); $tree = $this->discoverMatchChannelTree($lobbyId, $registered); $channelIds = $tree['channel_ids']; if (empty($channelIds)) { DB::table('lobby_ts3_channels') ->where('training_match_id', $lobbyId) ->delete(); $result = [ 'success' => true, 'moved' => 0, 'deleted' => 0, 'attempt' => $attempt, 'recovered_by_name' => (bool) $tree['recovered_by_name'], 'message' => 'Nenhuma sala TS3 física encontrada para o lobby; vínculo local limpo.', ]; $this->persistActionLog('cleanup', $lobbyId, $result); return $result; } $clientList = $this->command('clientlist -uid'); $clientIds = $this->findClientIdsByChannelIds($clientList, $channelIds); $fallbackId = (int) config('teamspeak.fallback_channel_id'); $moved = 0; if (!empty($clientIds) && $fallbackId <= 0) { throw new \RuntimeException('fallback_channel_id inválido; cleanup TS3 interrompido para não remover sala com jogadores dentro.'); } foreach ($clientIds as $clid) { $this->command('clientmove clid=' . $clid . ' cid=' . $fallbackId); $moved++; } // discoverMatchChannelTree já devolve filhos antes dos pais. $deleted = 0; foreach ($channelIds as $channelId) { if ($this->deleteChannelIfExists((string) $channelId)) { $deleted++; } } DB::table('lobby_ts3_channels') ->where('training_match_id', $lobbyId) ->delete(); $result = [ 'success' => true, 'moved' => $moved, 'deleted' => $deleted, 'attempt' => $attempt, 'recovered_by_name' => (bool) $tree['recovered_by_name'], 'channel_ids' => $channelIds, 'message' => "{$moved} jogador(es) movido(s) para a sala {$fallbackId} e {$deleted} sala(s) temporária(s) removida(s).", ]; $this->persistActionLog('cleanup', $lobbyId, $result); return $result; } catch (\Throwable $e) { $lastError = $e; Log::warning('GIGAX V176: tentativa de cleanup TS3 falhou', [ 'lobby_id' => $lobbyId, 'attempt' => $attempt, 'error' => $e->getMessage(), ]); if ($attempt < 3) { usleep(150000); } } finally { $this->disconnect(); } } $result = [ 'success' => false, 'moved' => 0, 'deleted' => 0, 'attempt' => 3, 'message' => $lastError?->getMessage() ?: 'Falha desconhecida ao limpar salas TS3.', ]; Log::error('Erro TS3 ao limpar canais após 3 tentativas', [ 'error' => $result['message'], 'lobby_id' => $lobbyId, ]); $this->persistActionLog('cleanup_failed', $lobbyId, $result); return $result; } /** * Retorna todos os CIDs pertencentes à partida, inclusive quando o registro * lobby_ts3_channels desapareceu. A ordem final é: filhos -> pais. */ private function discoverMatchChannelTree(int $lobbyId, ?object $registered = null): array { $entries = $this->parseChannelEntries($this->command('channellist')); $byCid = []; $childrenByPid = []; foreach ($entries as $entry) { $cid = (string) ($entry['cid'] ?? ''); if ($cid === '') { continue; } $pid = (string) ($entry['pid'] ?? '0'); $byCid[$cid] = $entry; $childrenByPid[$pid][] = $cid; } $seedIds = []; $rootIds = []; $recoveredByName = false; if ($registered) { foreach ([ (string) ($registered->root_channel_id ?? ''), (string) ($registered->team_a_channel_id ?? ''), (string) ($registered->team_b_channel_id ?? ''), ] as $cid) { if ($cid !== '' && isset($byCid[$cid])) { $seedIds[$cid] = true; } } $registeredRoot = (string) ($registered->root_channel_id ?? ''); if ($registeredRoot !== '' && isset($byCid[$registeredRoot])) { $rootIds[$registeredRoot] = true; } } // Fallback principal para órfãos: o nome físico sempre contém o ID único. $prefix = 'Lobby #' . $lobbyId . ' - '; foreach ($byCid as $cid => $entry) { $name = (string) ($entry['channel_name'] ?? ''); if (str_starts_with($name, $prefix)) { $rootIds[$cid] = true; $seedIds[$cid] = true; $recoveredByName = true; } } // Inclui toda a árvore descendente de cada raiz recuperada. $collect = function (string $cid) use (&$collect, &$seedIds, $childrenByPid): void { if ($cid === '') { return; } $seedIds[$cid] = true; foreach ($childrenByPid[$cid] ?? [] as $childCid) { $collect((string) $childCid); } }; foreach (array_keys($rootIds) as $rootCid) { $collect((string) $rootCid); } $channelIds = array_keys($seedIds); // Apaga sempre os canais mais profundos primeiro; a raiz fica por último. $depth = function (string $cid) use ($byCid): int { $level = 0; $seen = []; while (isset($byCid[$cid])) { $pid = (string) ($byCid[$cid]['pid'] ?? '0'); if ($pid === '0' || $pid === '' || isset($seen[$pid])) { break; } $seen[$pid] = true; $level++; $cid = $pid; } return $level; }; usort($channelIds, fn ($a, $b) => $depth((string) $b) <=> $depth((string) $a)); return [ 'channel_ids' => array_values(array_unique(array_map('strval', $channelIds))), 'recovered_by_name' => $recoveredByName, ]; } private function connect(): void { $host = (string) config('teamspeak.host'); $port = (int) config('teamspeak.query_port', 9998); Log::info('TS3 CONNECT DEBUG', [ 'host' => $host, 'port' => $port, ]); $timeout = max(1, min(3, (int) config('teamspeak.timeout', 3))); if ($host === '' || $port <= 0) { throw new \RuntimeException('Configuração TS3 inválida: host ou query_port ausente.'); } Log::info('TS3 CONNECT DEBUG', [ 'host' => $host, 'port' => $port, 'server_id' => (int) config('teamspeak.server_id'), 'username' => (string) config('teamspeak.username'), ]); $this->socket = fsockopen($host, $port, $errno, $errstr, $timeout); if (!$this->socket) { throw new \RuntimeException("Não foi possível conectar no TS3: {$errstr} ({$errno})"); } stream_set_timeout($this->socket, $timeout); $banner = $this->readBanner(); Log::debug('TS3 banner recebido', ['banner' => trim($banner)]); $loginUser = (string) config('teamspeak.username'); $serverId = (int) config('teamspeak.server_id'); Log::debug('TS3 iniciando autenticação e seleção do servidor', [ 'host' => $host, 'query_port' => $port, 'server_id' => $serverId, 'username' => $loginUser, ]); $this->command('login ' . $this->escape($loginUser) . ' ' . $this->escape((string) config('teamspeak.password'))); $this->command('use sid=' . $serverId); Log::debug('TS3 autenticação concluída', [ 'server_id' => $serverId, ]); } private function disconnect(): void { if (is_resource($this->socket)) { @fwrite($this->socket, "quit\n"); @fclose($this->socket); } $this->socket = null; } private function command(string $command): string { fwrite($this->socket, $command . "\n"); return $this->readUntilOk(); } private function readBanner(): string { $buffer = ''; while (!feof($this->socket)) { $line = fgets($this->socket, 4096); if ($line === false) { $meta = stream_get_meta_data($this->socket); if (!empty($meta['timed_out'])) { break; } break; } $buffer .= $line; if (trim($line) === '') { break; } } return $buffer; } private function readUntilOk(): string { $buffer = ''; $startedAt = microtime(true); while (!feof($this->socket)) { if ((microtime(true) - $startedAt) > 4.0) { throw new \RuntimeException('Timeout curto ao aguardar resposta do TeamSpeak.'); } $line = fgets($this->socket, 4096); if ($line === false) { $meta = stream_get_meta_data($this->socket); if (!empty($meta['timed_out'])) { throw new \RuntimeException('Timeout ao aguardar resposta do TeamSpeak.'); } break; } $buffer .= $line; if (preg_match('/^error id=(\d+) msg=(.*)$/', trim($line), $matches)) { if ((int) $matches[1] !== 0) { throw new \RuntimeException(trim($buffer)); } break; } } return $buffer; } private function extractResponseData(string $response): string { $lines = preg_split('/\r\n|\r|\n/', trim($response)); $dataLines = []; foreach ($lines as $line) { $line = trim($line); if ($line === '' || str_starts_with($line, 'error id=')) { continue; } $dataLines[] = $line; } return implode("\n", $dataLines); } private function extractId(string $response, string $field): ?string { $response = $this->extractResponseData($response); if (preg_match('/' . preg_quote($field, '/') . '=([0-9]+)/', $response, $matches)) { return $matches[1]; } return null; } private function diagnosticBase(string $uid): array { return [ 'uid' => $uid, 'host' => (string) config('teamspeak.host'), 'query_port' => (int) config('teamspeak.query_port', 9998), 'server_id' => (int) config('teamspeak.server_id'), 'username' => (string) config('teamspeak.username'), 'timeout' => (int) config('teamspeak.timeout', 10), 'connected' => false, ]; } private function findClientEntryByUid(string $clientList, string $uid): ?array { $inputUid = $this->normalizeUid($uid); foreach ($this->parseClientEntries($clientList) as $entry) { if (!is_array($entry)) { continue; } if (($entry['client_type'] ?? '0') !== '0') { continue; } if (!isset($entry['client_unique_identifier'])) { continue; } $entryUid = $this->normalizeUid((string) $entry['client_unique_identifier']); if ($entryUid === $inputUid) { return $entry; } } return null; } private function findClientIdByUid(string $clientList, string $uid): ?string { $entry = $this->findClientEntryByUid($clientList, $uid); return $entry['clid'] ?? null; } private function findClientIdsByChannelIds(string $clientList, array $channelIds): array { $channelIds = array_map('strval', $channelIds); $clientIds = []; foreach ($this->parseClientEntries($clientList) as $entry) { if (($entry['client_type'] ?? '0') !== '0') { continue; } if (in_array((string) ($entry['cid'] ?? ''), $channelIds, true) && !empty($entry['clid'])) { $clientIds[] = (string) $entry['clid']; } } return array_values(array_unique($clientIds)); } private function parseClientEntries(string $clientList): array { $clientList = $this->extractResponseData($clientList); $entries = []; foreach (explode('|', $clientList) as $rawEntry) { $rawEntry = trim($rawEntry); if ($rawEntry === '') { continue; } $pairs = preg_split('/\s+/', $rawEntry); $entry = []; foreach ($pairs as $pair) { if (!str_contains($pair, '=')) { continue; } [$key, $value] = explode('=', $pair, 2); $entry[$key] = $this->unescape($value); } $entries[] = $entry; } return $entries; } private function parseChannelEntries(string $channelList): array { $channelList = $this->extractResponseData($channelList); $entries = []; foreach (explode('|', $channelList) as $rawEntry) { $rawEntry = trim($rawEntry); if ($rawEntry === '') { continue; } $pairs = preg_split('/\s+/', $rawEntry); $entry = []; foreach ($pairs as $pair) { if (!str_contains($pair, '=')) { continue; } [$key, $value] = explode('=', $pair, 2); $entry[$key] = $this->unescape($value); } $entries[] = $entry; } return $entries; } private function deleteChannelIfExists(string $channelId): bool { try { $this->command('channeldelete cid=' . $channelId . ' force=1'); return true; } catch (\Throwable $e) { $message = $e->getMessage(); if (str_contains($message, 'invalid channelID') || str_contains($message, 'channel not found')) { return false; } throw $e; } } private function persistActionLog(string $action, int $lobbyId, array $result): void { try { if (!DB::getSchemaBuilder()->hasTable('ts3_action_logs')) { return; } DB::table('ts3_action_logs')->insert([ 'training_match_id' => $lobbyId, 'action' => $action, 'success' => !empty($result['success']) ? 1 : 0, 'message' => substr((string) ($result['message'] ?? ''), 0, 1000), 'payload_json' => json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'created_at' => now(), 'updated_at' => now(), ]); } catch (\Throwable $e) { Log::warning('Não foi possível salvar log TS3', [ 'error' => $e->getMessage(), 'lobby_id' => $lobbyId, 'action' => $action, ]); } } private function matchRootName(object $lobby): string { $mapName = trim((string) ($lobby->map_name ?? 'sem-mapa')); return 'Lobby #' . $lobby->id . ' - ' . $mapName; } private function escape(string $value): string { return strtr($value, [ '\\' => '\\\\', '/' => '\\/', ' ' => '\\s', '|' => '\\p', ]); } private function unescape(string $value): string { return strtr($value, [ '\\s' => ' ', '\\p' => '|', '\\/' => '/', '\\\\' => '\\', ]); } }