/** * Sistema de Redirección Geográfica Automática * Friends Party Server SimRacing * * Redirige automáticamente a los usuarios según su ubicación: * - Paraguay: index.html (página principal) * - Argentina: assetto-corsa-argentina.html * - Resto de Sudamérica: assetto-corsa-sudamerica.html * - Otros países: index.html (página general) */ (function(window, document) { 'use strict'; const GeoRedirect = { // Configuración config: { services: [ 'https://ipapi.co/json/', 'https://ip-api.com/json/', 'https://ipinfo.io/json', 'https://geolocation-db.com/json/' ], delay: 2000, // Aumentado a 2 segundos debug: true, // Activar debug por defecto para diagnosis forceLog: true // Siempre mostrar logs principales }, // Mapeo de países a páginas countryMapping: { 'PY': 'index.html', // Paraguay - página principal 'AR': 'assetto-corsa-argentina.html', // Argentina - página específica // Resto de Sudamérica 'BR': 'assetto-corsa-sudamerica.html', // Brasil 'CL': 'assetto-corsa-sudamerica.html', // Chile 'UY': 'assetto-corsa-sudamerica.html', // Uruguay 'CO': 'assetto-corsa-sudamerica.html', // Colombia 'VE': 'assetto-corsa-sudamerica.html', // Venezuela 'EC': 'assetto-corsa-sudamerica.html', // Ecuador 'PE': 'assetto-corsa-sudamerica.html', // Perú 'BO': 'assetto-corsa-sudamerica.html', // Bolivia 'GY': 'assetto-corsa-sudamerica.html', // Guyana 'SR': 'assetto-corsa-sudamerica.html', // Suriname 'GF': 'assetto-corsa-sudamerica.html' // Guayana Francesa }, // Verificar si ya estamos en una página específica isSpecificPage: function() { const path = window.location.pathname; this.log('Verificando página actual:', path); return path.includes('assetto-corsa-argentina') || path.includes('assetto-corsa-sudamerica'); }, // Función de logging condicional log: function(message, data) { if (this.config.debug || this.config.forceLog || window.location.search.includes('geo-debug')) { console.log('🌍 [GeoRedirect]', message, data || ''); } }, // Detectar país usando múltiples servicios detectCountry: async function() { this.log('🔍 Iniciando detección de país...'); for (let i = 0; i < this.config.services.length; i++) { const service = this.config.services[i]; try { this.log('🌐 Probando servicio ' + (i + 1) + ':', service); const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), 8000); // 8 segundos timeout const response = await fetch(service, { signal: controller.signal, headers: { 'Accept': 'application/json', 'Cache-Control': 'no-cache' } }); clearTimeout(timeoutId); if (response.ok) { const data = await response.json(); this.log('📊 Respuesta del servicio ' + (i + 1) + ':', data); let countryCode = data.country_code || data.countryCode || data.country; const countryName = data.country_name || data.country || data.country_name || 'Desconocido'; if (countryCode) { countryCode = countryCode.toString().toUpperCase(); this.log('✅ País detectado:', { code: countryCode, name: countryName, service: service, serviceNumber: i + 1 }); return { code: countryCode, name: countryName, service: service }; } else { this.log('⚠️ Servicio ' + (i + 1) + ' no devolvió código de país válido'); } } else { this.log('❌ Servicio ' + (i + 1) + ' respondió con error:', response.status); } } catch (error) { this.log('💥 Error con servicio ' + (i + 1) + ':', error.message); } } this.log('🚫 No se pudo detectar el país con ningún servicio'); return null; }, // Realizar redirección redirect: function(countryData) { const targetPage = this.countryMapping[countryData.code]; const currentPath = window.location.pathname; this.log('🎯 Evaluando redirección:', { country: countryData.code + ' (' + countryData.name + ')', targetPage: targetPage, currentPath: currentPath }); if (targetPage) { // Verificar si ya estamos en la página correcta const currentPage = currentPath.split('/').pop() || 'index.html'; const targetFileName = targetPage.split('/').pop(); this.log('📄 Comparando páginas:', { actual: currentPage, objetivo: targetFileName }); if (currentPage !== targetFileName) { this.log('🚀 REDIRIGIENDO a:', targetPage); // Agregar parámetro para evitar loops infinitos const url = new URL(targetPage, window.location.origin); url.searchParams.set('geo-redirect', countryData.code.toLowerCase()); url.searchParams.set('from-country', countryData.name); this.log('🔗 URL final de redirección:', url.toString()); // Mostrar mensaje antes de redireccionar (para debug) console.log('🌍 REDIRECCIÓN DETECTADA: ' + countryData.code + ' → ' + targetPage); console.log('⏳ Redirigiendo en 2 segundos...'); setTimeout(() => { window.location.href = url.toString(); }, 2000); } else { this.log('✅ Ya en la página correcta'); } } else { // País no mapeado, mantener en página actual this.log('🗺️ País no mapeado (' + countryData.code + '), mantener en página actual'); } }, // Función principal init: function() { this.log('🚀 === INICIANDO SISTEMA DE REDIRECCIÓN GEOGRÁFICA ==='); this.log('📍 URL actual:', window.location.href); this.log('📱 User Agent:', navigator.userAgent.substring(0, 100) + '...'); // No redireccionar si ya estamos en una página específica if (this.isSpecificPage()) { this.log('📋 En página específica, no redireccionar'); return; } // No redireccionar si ya fuimos redirigidos (evitar loops) const urlParams = new URLSearchParams(window.location.search); if (urlParams.has('geo-redirect')) { this.log('🔄 Ya redirigido previamente (' + urlParams.get('geo-redirect') + '), evitando loop'); return; } this.log('⏲️ Iniciando detección en ' + (this.config.delay / 1000) + ' segundos...'); // Detectar país y redireccionar setTimeout(async () => { try { this.log('🔍 Ejecutando detección de país...'); const countryData = await this.detectCountry(); if (countryData) { this.redirect(countryData); } else { this.log('❌ No se pudo obtener información del país, mantener página actual'); } } catch (error) { this.log('💥 Error crítico en redirección:', error.message); } }, this.config.delay); }, // Función para testing manual testRedirect: function(countryCode) { this.log('🧪 MODO TEST: Simulando país ' + countryCode); this.redirect({ code: countryCode.toUpperCase(), name: 'Test Country', service: 'manual' }); } }; // Auto-inicializar cuando el DOM esté listo if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { console.log('🌍 DOM cargado, iniciando GeoRedirect...'); GeoRedirect.init(); }); } else { console.log('🌍 DOM ya listo, iniciando GeoRedirect inmediatamente...'); GeoRedirect.init(); } // Exponer para debugging y testing window.GeoRedirect = GeoRedirect; // Mensaje inicial console.log('🌍 === FRIENDS PARTY SERVER - SISTEMA DE REDIRECCIÓN GEOGRÁFICA CARGADO ==='); console.log('🧪 Para testing manual: GeoRedirect.testRedirect("AR") // Argentina'); console.log('🧪 Para testing manual: GeoRedirect.testRedirect("BR") // Brasil'); console.log('🔍 Para logs detallados: agrega ?geo-debug=1 a la URL'); })(window, document);