Compare commits
8 Commits
v1.1.0
...
c4c08c64c3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c4c08c64c3 | ||
|
|
1ad4f46aa4 | ||
|
|
797780fc94 | ||
|
|
77194bd8f6 | ||
|
|
3ac48e50fb | ||
|
|
91da241423 | ||
|
|
1548309753 | ||
|
|
3d68eddb8b |
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "resistencia-client",
|
||||
"version": "1.1.0",
|
||||
"version": "1.1.2",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
|
||||
454
client/src/app/dashboard/page.tsx
Normal file
454
client/src/app/dashboard/page.tsx
Normal file
@@ -0,0 +1,454 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { motion, AnimatePresence } from 'framer-motion';
|
||||
import { useSocket } from '../../hooks/useSocket';
|
||||
import { Shield, Users, Gamepad2, LogOut, Clock, History, UserMinus, Key, ChevronDown } from 'lucide-react';
|
||||
|
||||
const ADMIN_PASSWORD = "admin123";
|
||||
|
||||
export default function Dashboard() {
|
||||
const { socket, isConnected } = useSocket();
|
||||
const [password, setPassword] = useState('');
|
||||
const [isAuthenticated, setIsAuthenticated] = useState(false);
|
||||
const [activeGames, setActiveGames] = useState<any[]>([]);
|
||||
const [gameHistory, setGameHistory] = useState<any[]>([]);
|
||||
const [error, setError] = useState('');
|
||||
const [expandedGames, setExpandedGames] = useState<Set<string>>(new Set());
|
||||
|
||||
// Comprobar sesión al cargar
|
||||
useEffect(() => {
|
||||
const savedSession = localStorage.getItem('resistencia_admin_session');
|
||||
if (savedSession === 'active') {
|
||||
setIsAuthenticated(true);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Cargar datos y escuchar actualizaciones en tiempo real
|
||||
useEffect(() => {
|
||||
if (isAuthenticated && socket) {
|
||||
// Solicitar datos iniciales
|
||||
socket.emit('admin_get_data');
|
||||
|
||||
// Escuchar actualizaciones (el servidor emite a admin-room)
|
||||
socket.on('admin_data', (data: any) => {
|
||||
console.log('[ADMIN] Datos recibidos:', data);
|
||||
setActiveGames(data.activeGames);
|
||||
setGameHistory(data.history);
|
||||
});
|
||||
|
||||
socket.on('admin_action_success', () => {
|
||||
console.log('[ADMIN] Acción realizada con éxito');
|
||||
socket.emit('admin_get_data');
|
||||
});
|
||||
|
||||
return () => {
|
||||
socket.off('admin_data');
|
||||
socket.off('admin_action_success');
|
||||
};
|
||||
}
|
||||
}, [isAuthenticated, socket]);
|
||||
|
||||
const handleLogin = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (password === ADMIN_PASSWORD) {
|
||||
setIsAuthenticated(true);
|
||||
localStorage.setItem('resistencia_admin_session', 'active');
|
||||
setError('');
|
||||
} else {
|
||||
setError('Acceso Denegado: Contraseña incorrecta');
|
||||
}
|
||||
};
|
||||
|
||||
const handleLogout = () => {
|
||||
localStorage.removeItem('resistencia_admin_session');
|
||||
setIsAuthenticated(false);
|
||||
setPassword('');
|
||||
};
|
||||
|
||||
const closeGame = (roomId: string) => {
|
||||
if (confirm('¿Seguro que quieres forzar el cierre de esta partida?')) {
|
||||
socket?.emit('admin_close_game', { roomId });
|
||||
}
|
||||
};
|
||||
|
||||
const kickPlayer = (roomId: string, socketId: string) => {
|
||||
if (confirm('¿Seguro que quieres expulsar a este jugador?')) {
|
||||
socket?.emit('admin_kick_player', { roomId, targetSocketId: socketId });
|
||||
}
|
||||
};
|
||||
|
||||
const toggleGame = (id: string) => {
|
||||
setExpandedGames(prev => {
|
||||
const newSet = new Set(prev);
|
||||
if (newSet.has(id)) newSet.delete(id);
|
||||
else newSet.add(id);
|
||||
return newSet;
|
||||
});
|
||||
};
|
||||
|
||||
if (!isAuthenticated) {
|
||||
return (
|
||||
<div className="min-h-screen bg-[#0a0a0c] flex items-center justify-center p-4 font-['Inter',sans-serif]">
|
||||
<motion.div
|
||||
initial={{ opacity: 0, scale: 0.95 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
className="bg-[#121216] border border-white/10 p-10 rounded-3xl w-full max-w-md shadow-[0_20px_50px_rgba(0,0,0,0.5)] relative overflow-hidden"
|
||||
>
|
||||
<div className="absolute top-0 left-0 w-full h-1 bg-gradient-to-r from-red-600 via-zinc-800 to-red-600"></div>
|
||||
|
||||
<div className="flex justify-center mb-8 relative">
|
||||
<div className="absolute inset-0 bg-red-500/20 blur-2xl rounded-full"></div>
|
||||
<Shield size={64} className="text-red-500 relative z-10" />
|
||||
</div>
|
||||
|
||||
<h1 className="text-3xl font-black text-white text-center mb-2 uppercase tracking-tight">Acceso Admin</h1>
|
||||
<p className="text-gray-400 text-center text-sm mb-10 font-medium">Panel de Control de La Resistencia</p>
|
||||
|
||||
<form onSubmit={handleLogin} className="space-y-6">
|
||||
<div className="relative">
|
||||
<Key size={18} className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-500" />
|
||||
<input
|
||||
type="password"
|
||||
autoFocus
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder="Introduce la contraseña"
|
||||
className="w-full bg-[#1a1a20] border border-white/5 rounded-2xl pl-12 pr-6 py-4 text-white focus:outline-none focus:ring-2 focus:ring-red-600/50 transition-all placeholder:text-gray-600 font-medium"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<motion.p
|
||||
initial={{ opacity: 0, y: -10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="text-red-500 text-xs font-bold text-center mt-2 flex items-center justify-center gap-2"
|
||||
>
|
||||
<span className="w-1.5 h-1.5 bg-red-500 rounded-full animate-pulse"></span>
|
||||
{error}
|
||||
</motion.p>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
className="w-full bg-red-600 hover:bg-red-500 text-white font-black py-4 rounded-2xl shadow-xl shadow-red-600/10 transition-all uppercase tracking-[0.2em] text-xs hover:scale-[1.02] active:scale-[0.98]"
|
||||
>
|
||||
Entrar en Sistema
|
||||
</button>
|
||||
</form>
|
||||
</motion.div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-[#0a0a0c] text-white p-4 md:p-10 font-['Inter',sans-serif]">
|
||||
{/* Header */}
|
||||
<header className="max-w-7xl mx-auto flex flex-col md:flex-row justify-between items-start md:items-center mb-12 gap-6">
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center gap-3 text-red-500">
|
||||
<div className="p-2 bg-red-500/10 rounded-lg">
|
||||
<Shield size={22} />
|
||||
</div>
|
||||
<span className="text-[10px] font-black uppercase tracking-[0.4em] opacity-80">Seguimiento de Operaciones</span>
|
||||
</div>
|
||||
<h1 className="text-5xl font-black tracking-tighter uppercase italic text-transparent bg-clip-text bg-gradient-to-r from-white via-white to-gray-500">Comandante</h1>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-6 bg-[#121216] border border-white/10 px-8 py-4 rounded-3xl shadow-xl">
|
||||
<div className="flex flex-col items-end">
|
||||
<span className="text-[10px] text-gray-500 uppercase font-black tracking-widest mb-1">Status Servidor</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className={`w-2.5 h-2.5 rounded-full ${isConnected ? 'bg-green-500 shadow-[0_0_15px_rgba(34,197,94,0.6)] animate-pulse' : 'bg-red-500'}`}></div>
|
||||
<span className="text-xs font-mono font-black tracking-widest">{isConnected ? 'OPERATIVO' : 'DESCONECTADO'}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="w-px h-8 bg-white/10 mx-2"></div>
|
||||
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
className="flex items-center gap-2 px-5 py-2.5 bg-zinc-800 hover:bg-red-600 text-gray-300 hover:text-white rounded-xl transition-all font-black text-[10px] uppercase tracking-widest group"
|
||||
>
|
||||
<LogOut size={16} className="group-hover:translate-x-1 transition-transform" />
|
||||
Desconectar
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main className="max-w-7xl mx-auto grid grid-cols-1 lg:grid-cols-12 gap-10">
|
||||
|
||||
{/* Panel Latino: Estadísticas Rápidas */}
|
||||
<div className="lg:col-span-12 grid grid-cols-2 md:grid-cols-4 gap-4 mb-2">
|
||||
{[
|
||||
{ label: 'Partidas Activas', value: activeGames.length, color: 'text-red-500', icon: Gamepad2 },
|
||||
{ label: 'Agentes Online', value: activeGames.reduce((acc, g) => acc + g.currentPlayers, 0), color: 'text-blue-400', icon: Users },
|
||||
{ label: 'Misiones Registradas', value: gameHistory.length, color: 'text-orange-400', icon: History },
|
||||
{ label: 'Uso de CPU', value: '4%', color: 'text-green-400', icon: Clock }
|
||||
].map((stat, i) => (
|
||||
<div key={i} className="bg-[#121216] border border-white/5 p-6 rounded-2xl flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-[10px] uppercase font-black tracking-widest text-gray-500 mb-1">{stat.label}</p>
|
||||
<p className={`text-2xl font-black ${stat.color}`}>{stat.value}</p>
|
||||
</div>
|
||||
<stat.icon className="opacity-10" size={32} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Columna Principal: Partidas Activas */}
|
||||
<div className="lg:col-span-8 space-y-8">
|
||||
<section>
|
||||
<div className="flex items-center gap-4 mb-8">
|
||||
<h2 className="text-xl font-black text-white uppercase tracking-tighter italic border-l-4 border-red-600 pl-4">Canales de Radio Activos</h2>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4">
|
||||
<AnimatePresence mode="popLayout">
|
||||
{activeGames.length === 0 ? (
|
||||
<motion.div
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
className="bg-[#121216]/40 border border-dashed border-white/10 rounded-3xl p-20 text-center"
|
||||
>
|
||||
<Clock size={48} className="mx-auto mb-6 text-gray-700" />
|
||||
<p className="text-lg font-bold text-gray-600 uppercase tracking-widest">Silencio Radioeléctrico</p>
|
||||
<p className="text-xs text-gray-700 font-medium">Buscando señales de misiones activas...</p>
|
||||
</motion.div>
|
||||
) : (
|
||||
activeGames.map((game: any) => (
|
||||
<motion.div
|
||||
key={game.id}
|
||||
layout
|
||||
initial={{ opacity: 0, x: -20 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
exit={{ opacity: 0, scale: 0.95 }}
|
||||
className="bg-[#121216] border border-white/10 rounded-3xl overflow-hidden hover:bg-[#16161c] transition-all group shadow-lg"
|
||||
>
|
||||
{/* Cabecera Compacta (Clickable) */}
|
||||
<div
|
||||
onClick={() => toggleGame(game.id)}
|
||||
className="flex flex-wrap items-center justify-between p-6 cursor-pointer gap-4"
|
||||
>
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="w-2 h-12 bg-red-600 rounded-full" />
|
||||
<div>
|
||||
<h3 className="text-xl font-black text-white italic uppercase tracking-tighter leading-none mb-1">{game.name}</h3>
|
||||
<div className="flex items-center gap-2 text-[10px] uppercase font-black tracking-widest text-gray-500">
|
||||
<span>ID: {game.id.slice(0, 6)}</span>
|
||||
<span className="text-gray-700">•</span>
|
||||
<span>{new Date(game.created_at || Date.now()).toLocaleTimeString()}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-6">
|
||||
<div className="flex items-center gap-2 bg-black/40 px-3 py-1.5 rounded-lg border border-white/5">
|
||||
<Users size={14} className="text-gray-400" />
|
||||
<span className="text-xs font-bold text-white">{game.currentPlayers} / {game.maxPlayers}</span>
|
||||
</div>
|
||||
<div className={`px-3 py-1 rounded text-[10px] font-black uppercase tracking-widest border ${game.status === 'WAITING' ? 'bg-orange-500/10 text-orange-500 border-orange-500/20' : 'bg-green-500/10 text-green-500 border-green-500/20'}`}>
|
||||
{game.status}
|
||||
</div>
|
||||
{game.currentRound > 0 && (
|
||||
<div className="bg-white/10 px-3 py-1 rounded text-[10px] font-black uppercase tracking-widest border border-white/10">
|
||||
Ronda {game.currentRound}
|
||||
</div>
|
||||
)}
|
||||
<ChevronDown
|
||||
size={20}
|
||||
className={`text-gray-500 transition-transform duration-300 ${expandedGames.has(game.id) ? 'rotate-180' : ''}`}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Contenido Expandible */}
|
||||
<AnimatePresence>
|
||||
{expandedGames.has(game.id) && (
|
||||
<motion.div
|
||||
initial={{ height: 0, opacity: 0 }}
|
||||
animate={{ height: 'auto', opacity: 1 }}
|
||||
exit={{ height: 0, opacity: 0 }}
|
||||
className="border-t border-white/5 bg-black/20"
|
||||
>
|
||||
<div className="p-6 pt-2">
|
||||
{/* Panel de Control */}
|
||||
<div className="flex justify-end mb-6">
|
||||
<button
|
||||
onClick={(e) => { e.stopPropagation(); closeGame(game.id); }}
|
||||
className="px-6 py-3 bg-zinc-900 hover:bg-red-900/40 text-gray-400 hover:text-red-400 rounded-2xl text-[10px] font-black uppercase tracking-[0.2em] transition-all border border-white/5 hover:border-red-500/30 active:scale-95 whitespace-nowrap flex items-center gap-2"
|
||||
>
|
||||
<LogOut size={14} />
|
||||
Abortar Misión
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Grid de Jugadores */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-3">
|
||||
{game.players.map((player: any) => (
|
||||
<div key={player.id} className="bg-[#0a0a0c] p-3 rounded-xl border border-white/5 flex items-center justify-between group/player hover:border-white/10 transition-all">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-8 h-8 rounded-lg bg-white/5 flex items-center justify-center font-black text-gray-400 text-xs border border-white/5 group-hover/player:text-white transition-all">
|
||||
{player.name[0].toUpperCase()}
|
||||
</div>
|
||||
<div className="overflow-hidden">
|
||||
<p className="text-xs font-bold text-gray-300 truncate">{player.name}</p>
|
||||
<p className="text-[9px] opacity-30 font-mono">AG-{player.id.slice(0, 4)}</p>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={(e) => { e.stopPropagation(); kickPlayer(game.id, player.id); }}
|
||||
className="p-2 text-gray-700 hover:text-red-500 hover:bg-red-500/10 rounded-lg transition-all opacity-0 group-hover/player:opacity-100"
|
||||
title="Expulsar"
|
||||
>
|
||||
<UserMinus size={14} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</motion.div>
|
||||
))
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
{/* Columna Lateral: Archivo Histórico */}
|
||||
<div className="lg:col-span-4 space-y-8">
|
||||
<section className="sticky top-10">
|
||||
<div className="flex items-center gap-4 mb-8">
|
||||
<h2 className="text-xl font-black text-white uppercase tracking-tighter italic border-l-4 border-gray-600 pl-4">Informe Forense</h2>
|
||||
</div>
|
||||
|
||||
<div className="bg-[#121216] border border-white/10 rounded-3xl overflow-hidden shadow-2xl">
|
||||
<div className="p-6 bg-white/5 border-b border-white/5 flex justify-between items-center">
|
||||
<p className="text-[10px] uppercase font-black tracking-widest text-gray-400">Archivos Recientes</p>
|
||||
<History size={14} className="text-gray-600" />
|
||||
</div>
|
||||
|
||||
<div className="max-h-[60vh] overflow-y-auto custom-scrollbar p-0">
|
||||
{gameHistory.length === 0 ? (
|
||||
<div className="text-center py-20 opacity-10">
|
||||
<p className="text-xs italic font-bold">Sin registros</p>
|
||||
</div>
|
||||
) : (
|
||||
gameHistory.map((entry: any) => (
|
||||
<div key={entry.id} className="border-b border-white/5 last:border-0 last:rounded-b-3xl">
|
||||
{/* Cabecera Historial */}
|
||||
<div
|
||||
onClick={() => toggleGame(entry.id)}
|
||||
className={`p-4 cursor-pointer hover:bg-white/5 transition-colors flex justify-between items-center group relative overflow-hidden ${expandedGames.has(entry.id) ? 'bg-white/[0.02]' : ''}`}
|
||||
>
|
||||
<div className={`absolute left-0 top-0 bottom-0 w-1 transition-all ${entry.winner === 'resistance' ? 'bg-blue-500' : entry.winner === 'spies' ? 'bg-red-500' : 'bg-gray-600'} ${expandedGames.has(entry.id) ? 'opacity-100' : 'opacity-40 group-hover:opacity-100'}`} />
|
||||
|
||||
<div className="pl-3">
|
||||
<h4 className="text-sm font-black text-gray-200 uppercase tracking-tight leading-none mb-1">{entry.room_name}</h4>
|
||||
<div className="flex items-center gap-2 text-[9px] text-gray-600 font-bold uppercase tracking-widest">
|
||||
<span>{entry.host_name}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<div className={`text-[9px] font-black uppercase px-2 py-1 rounded ${entry.winner === 'resistance' ? 'bg-blue-500/10 text-blue-500' :
|
||||
entry.winner === 'spies' ? 'bg-red-500/10 text-red-500' : 'bg-gray-700/20 text-gray-500'
|
||||
}`}>
|
||||
{entry.winner ? (entry.winner === 'resistance' ? 'ALIAD' : 'AXIS') : '??'}
|
||||
</div>
|
||||
<ChevronDown
|
||||
size={14}
|
||||
className={`text-gray-600 transition-transform ${expandedGames.has(entry.id) ? 'rotate-180' : ''}`}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Detalles Historial Expandido */}
|
||||
<AnimatePresence>
|
||||
{expandedGames.has(entry.id) && (
|
||||
<motion.div
|
||||
initial={{ height: 0, opacity: 0 }}
|
||||
animate={{ height: 'auto', opacity: 1 }}
|
||||
exit={{ height: 0, opacity: 0 }}
|
||||
className="bg-black/20"
|
||||
>
|
||||
<div className="p-4 pl-7 text-[10px] text-gray-400 space-y-2 font-mono border-t border-white/5">
|
||||
<div className="flex justify-between">
|
||||
<span>FECHA:</span>
|
||||
<span className="text-gray-300">{new Date(entry.created_at).toLocaleDateString()}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span>HORA:</span>
|
||||
<span className="text-gray-300">{new Date(entry.created_at).toLocaleTimeString()}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span>AGENTES:</span>
|
||||
<span className="text-gray-300">{entry.players.split(',').length}</span>
|
||||
</div>
|
||||
{entry.rounds_played > 0 && (
|
||||
<>
|
||||
<div className="flex justify-between">
|
||||
<span>RONDAS:</span>
|
||||
<span className="text-gray-300">{entry.rounds_played}</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center pt-2">
|
||||
<span>RESULTADOS:</span>
|
||||
<div className="flex gap-1">
|
||||
{entry.round_results && entry.round_results.split(',').map((res: string, idx: number) => (
|
||||
<div
|
||||
key={idx}
|
||||
className={`w-3 h-3 rounded-full ${res === 'true' ? 'bg-blue-500' : 'bg-red-500'}`}
|
||||
title={res === 'true' ? 'Victoria Resistencia' : 'Victoria Espías'}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{entry.players && (
|
||||
<div className="pt-2 border-t border-white/5 mt-2">
|
||||
<p className="mb-1 opacity-50">PARTICIPANTES:</p>
|
||||
<p className="text-gray-500 leading-relaxed">{entry.players.split(',').join(', ')}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<style jsx global>{`
|
||||
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;700;900&display=swap');
|
||||
|
||||
body {
|
||||
background-color: #0a0a0c;
|
||||
cursor: crosshair;
|
||||
}
|
||||
|
||||
.custom-scrollbar::-webkit-scrollbar {
|
||||
width: 3px;
|
||||
}
|
||||
.custom-scrollbar::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
.custom-scrollbar::-webkit-scrollbar-thumb {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border-radius: 10px;
|
||||
}
|
||||
.custom-scrollbar::-webkit-scrollbar-thumb:hover {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -65,10 +65,30 @@ export default function Home() {
|
||||
updateSession({ currentView: 'game', roomId: gameState.roomId });
|
||||
} else if (view === 'game' && !gameState) {
|
||||
// Si estábamos en juego y volvemos a null, volver al lobby
|
||||
setView('lobby');
|
||||
updateSession({ currentView: 'lobby', roomId: undefined });
|
||||
// Pero solo si no estamos esperando una reconexión inicial
|
||||
if (hasReconnected) {
|
||||
setView('lobby');
|
||||
updateSession({ currentView: 'lobby', roomId: undefined });
|
||||
}
|
||||
}
|
||||
}, [gameState]);
|
||||
}, [gameState, view, hasReconnected]);
|
||||
|
||||
// Listener para errores de socket que deben expulsar al lobby
|
||||
useEffect(() => {
|
||||
if (!socket) return;
|
||||
|
||||
const handleError = (msg: string) => {
|
||||
if (msg === 'La partida ya no existe' || msg === 'No se pudo reconectar a la partida') {
|
||||
setView('lobby');
|
||||
updateSession({ currentView: 'lobby', roomId: undefined });
|
||||
}
|
||||
};
|
||||
|
||||
socket.on('error', handleError);
|
||||
return () => {
|
||||
socket.off('error', handleError);
|
||||
};
|
||||
}, [socket, updateSession]);
|
||||
|
||||
const handleLogin = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
@@ -996,7 +996,7 @@ function VotingTimer() {
|
||||
}, [timeLeft]);
|
||||
|
||||
return (
|
||||
<div className="fixed top-5 left-5 bg-red-600/80 text-white w-16 h-16 rounded-full flex items-center justify-center border-4 border-red-400 animate-pulse text-2xl font-bold font-mono">
|
||||
<div className="mx-auto my-2 bg-gray-900/90 text-white w-20 h-20 rounded-full flex items-center justify-center border-4 border-gray-500 text-3xl font-bold font-mono shadow-xl relative z-20">
|
||||
{timeLeft}
|
||||
</div>
|
||||
);
|
||||
|
||||
1
client/tsconfig.tsbuildinfo
Normal file
1
client/tsconfig.tsbuildinfo
Normal file
File diff suppressed because one or more lines are too long
1960
server/package-lock.json
generated
Normal file
1960
server/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "resistencia-server",
|
||||
"version": "1.1.0",
|
||||
"version": "1.1.2",
|
||||
"description": "Backend para el juego La Resistencia",
|
||||
"main": "src/index.ts",
|
||||
"scripts": {
|
||||
@@ -12,9 +12,11 @@
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@types/pg": "^8.16.0",
|
||||
"cors": "^2.8.5",
|
||||
"dotenv": "^16.3.1",
|
||||
"express": "^4.18.2",
|
||||
"pg": "^8.16.3",
|
||||
"socket.io": "^4.7.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
100
server/src/db.ts
Normal file
100
server/src/db.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
import { Pool } from 'pg';
|
||||
import dotenv from 'dotenv';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const pool = new Pool({
|
||||
connectionString: process.env.DATABASE_URL || 'postgresql://postgres:password@db:5432/resistencia',
|
||||
});
|
||||
|
||||
// Inicializar base de datos
|
||||
export const initDb = async () => {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query(`
|
||||
CREATE TABLE IF NOT EXISTS game_logs (
|
||||
id SERIAL PRIMARY KEY,
|
||||
room_id UUID NOT NULL,
|
||||
room_name TEXT NOT NULL,
|
||||
host_name TEXT NOT NULL,
|
||||
players TEXT NOT NULL, -- Lista de nombres separada por comas
|
||||
max_players INTEGER NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
finished_at TIMESTAMP,
|
||||
winner TEXT, -- 'resistance' o 'spies'
|
||||
status TEXT DEFAULT 'active' -- 'active', 'finished', 'aborted'
|
||||
);
|
||||
`);
|
||||
|
||||
// Migration: Add new columns if they don't exist
|
||||
await client.query(`
|
||||
ALTER TABLE game_logs
|
||||
ADD COLUMN IF NOT EXISTS rounds_played INTEGER DEFAULT 0,
|
||||
ADD COLUMN IF NOT EXISTS round_results TEXT DEFAULT '';
|
||||
`);
|
||||
|
||||
console.log('[DB] Base de datos inicializada correctamente');
|
||||
} catch (err) {
|
||||
console.error('[DB] Error al inicializar base de datos:', err);
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
};
|
||||
|
||||
// Registrar inicio de partida
|
||||
export const logGameStart = async (roomId: string, roomName: string, hostName: string, maxPlayers: number) => {
|
||||
try {
|
||||
await pool.query(
|
||||
'INSERT INTO game_logs (room_id, room_name, host_name, players, max_players, status) VALUES ($1, $2, $3, $4, $5, $6)',
|
||||
[roomId, roomName, hostName, hostName, maxPlayers, 'active']
|
||||
);
|
||||
} catch (err) {
|
||||
console.error('[DB] Error al registrar inicio de partida:', err);
|
||||
}
|
||||
};
|
||||
|
||||
// Actualizar lista de jugadores en tiempo real (opcional, pero útil para el histórico final)
|
||||
export const updateGamePlayers = async (roomId: string, players: string[]) => {
|
||||
try {
|
||||
await pool.query(
|
||||
'UPDATE game_logs SET players = $1 WHERE room_id = $2 AND status = $3',
|
||||
[players.join(', '), roomId, 'active']
|
||||
);
|
||||
} catch (err) {
|
||||
console.error('[DB] Error al actualizar jugadores en log:', err);
|
||||
}
|
||||
};
|
||||
|
||||
// Registrar fin de partida
|
||||
export const logGameEnd = async (
|
||||
roomId: string,
|
||||
winner: string | null = null,
|
||||
aborted: boolean = false,
|
||||
roundsPlayed: number = 0,
|
||||
roundResults: boolean[] = []
|
||||
) => {
|
||||
try {
|
||||
// Convert boolean[] to string "true,false,true" or simplified "W,L,W"
|
||||
const resultsStr = roundResults.join(',');
|
||||
|
||||
await pool.query(
|
||||
'UPDATE game_logs SET finished_at = CURRENT_TIMESTAMP, winner = $1, status = $2, rounds_played = $3, round_results = $4 WHERE room_id = $5 AND status = $6',
|
||||
[winner, aborted ? 'aborted' : 'finished', roundsPlayed, resultsStr, roomId, 'active']
|
||||
);
|
||||
} catch (err) {
|
||||
console.error('[DB] Error al registrar fin de partida:', err);
|
||||
}
|
||||
};
|
||||
|
||||
// Obtener historial
|
||||
export const getGameHistory = async () => {
|
||||
try {
|
||||
const res = await pool.query('SELECT * FROM game_logs ORDER BY created_at DESC LIMIT 50');
|
||||
return res.rows;
|
||||
} catch (err) {
|
||||
console.error('[DB] Error al obtener historial:', err);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
export default pool;
|
||||
@@ -6,21 +6,38 @@ import dotenv from 'dotenv';
|
||||
import crypto from 'crypto';
|
||||
import { Game } from './models/Game';
|
||||
import { GamePhase } from '../../shared/types';
|
||||
import { initDb, logGameStart, logGameEnd, updateGamePlayers, getGameHistory } from './db';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
// Inicializar DB
|
||||
initDb();
|
||||
|
||||
const app = express();
|
||||
const port = process.env.PORT || 4000;
|
||||
|
||||
const allowedOrigins = [
|
||||
process.env.CORS_ORIGIN || "http://localhost:3000",
|
||||
"http://localhost:3000",
|
||||
"http://127.0.0.1:3000",
|
||||
"http://192.168.1.131:3000"
|
||||
];
|
||||
|
||||
app.use(cors({
|
||||
origin: process.env.CORS_ORIGIN || "http://localhost:3000",
|
||||
origin: (origin, callback) => {
|
||||
if (!origin || allowedOrigins.includes(origin)) {
|
||||
callback(null, true);
|
||||
} else {
|
||||
callback(new Error('Not allowed by CORS'));
|
||||
}
|
||||
},
|
||||
methods: ["GET", "POST"]
|
||||
}));
|
||||
|
||||
const server = http.createServer(app);
|
||||
const io = new Server(server, {
|
||||
cors: {
|
||||
origin: process.env.CORS_ORIGIN || "http://localhost:3000",
|
||||
origin: allowedOrigins,
|
||||
methods: ["GET", "POST"]
|
||||
}
|
||||
});
|
||||
@@ -66,6 +83,30 @@ const generateRoomName = () => {
|
||||
return `${MISSION_NAMES[idx]} #${suffix}`;
|
||||
};
|
||||
|
||||
const getAdminData = async () => {
|
||||
const activeGamesData = Object.values(games).map(g => ({
|
||||
id: g.state.roomId,
|
||||
name: g.roomName,
|
||||
status: g.state.phase,
|
||||
currentPlayers: g.state.players.length,
|
||||
maxPlayers: g.maxPlayers,
|
||||
currentRound: g.state.currentRound,
|
||||
players: g.state.players.map(p => ({ id: p.id, name: p.name }))
|
||||
}));
|
||||
|
||||
const history = await getGameHistory();
|
||||
|
||||
return {
|
||||
activeGames: activeGamesData,
|
||||
history: history
|
||||
};
|
||||
};
|
||||
|
||||
const broadcastAdminUpdate = async () => {
|
||||
const data = await getAdminData();
|
||||
io.to('admin-room').emit('admin_data', data);
|
||||
};
|
||||
|
||||
io.on('connection', (socket) => {
|
||||
console.log('Cliente conectado:', socket.id);
|
||||
|
||||
@@ -90,6 +131,10 @@ io.on('connection', (socket) => {
|
||||
|
||||
// Actualizar lista a todos
|
||||
io.emit('rooms_list', getRoomsList());
|
||||
|
||||
// LOG EN DB
|
||||
logGameStart(roomId, roomName, hostName, maxPlayers);
|
||||
broadcastAdminUpdate();
|
||||
});
|
||||
|
||||
// B. UNIRSE A SALA
|
||||
@@ -126,6 +171,10 @@ io.on('connection', (socket) => {
|
||||
|
||||
// Actualizar lista de salas (cambió contador de jugadores)
|
||||
io.emit('rooms_list', getRoomsList());
|
||||
|
||||
// ACTUALIZAR LOG EN DB
|
||||
updateGamePlayers(roomId, game.state.players.map(p => p.name));
|
||||
broadcastAdminUpdate();
|
||||
});
|
||||
|
||||
// C. REFRESCAR LISTA
|
||||
@@ -298,6 +347,10 @@ io.on('connection', (socket) => {
|
||||
|
||||
// Desconectar a todos los jugadores de la sala
|
||||
io.in(roomId).socketsLeave(roomId);
|
||||
|
||||
// LOG EN DB
|
||||
logGameEnd(roomId, game.state.winner, false, game.state.currentRound, game.state.questResults);
|
||||
broadcastAdminUpdate();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -328,6 +381,10 @@ io.on('connection', (socket) => {
|
||||
// Desconectar a todos de la sala
|
||||
io.in(roomId).socketsLeave(roomId);
|
||||
|
||||
// LOG EN DB COMO ABORTADA
|
||||
logGameEnd(roomId, null, true, game.state.currentRound, game.state.questResults);
|
||||
broadcastAdminUpdate();
|
||||
|
||||
console.log(`[LEAVE_GAME] ${playerName} abandonó la partida ${roomId}. Partida eliminada.`);
|
||||
}
|
||||
});
|
||||
@@ -387,7 +444,62 @@ io.on('connection', (socket) => {
|
||||
socket.on('disconnect', () => {
|
||||
// Buscar en qué partida estaba y sacarlo (opcional, por ahora solo notificamos)
|
||||
console.log('Desconectado:', socket.id);
|
||||
// TODO: Eliminar de la partida si está en LOBBY para liberar hueco
|
||||
});
|
||||
|
||||
// --- ADMIN COMMANDS ---
|
||||
|
||||
socket.on('admin_get_data', async () => {
|
||||
console.log('[ADMIN] Agente administrativo conectado');
|
||||
socket.join('admin-room');
|
||||
const data = await getAdminData();
|
||||
socket.emit('admin_data', data);
|
||||
});
|
||||
|
||||
socket.on('admin_close_game', async ({ roomId }) => {
|
||||
const game = games[roomId];
|
||||
if (game) {
|
||||
io.to(roomId).emit('game_finalized');
|
||||
delete games[roomId];
|
||||
|
||||
if (voteTimers[roomId]) {
|
||||
clearTimeout(voteTimers[roomId]);
|
||||
delete voteTimers[roomId];
|
||||
}
|
||||
|
||||
io.emit('rooms_list', getRoomsList());
|
||||
io.in(roomId).socketsLeave(roomId);
|
||||
|
||||
// Log como abortada por admin
|
||||
await logGameEnd(roomId, null, true, game.state.currentRound, game.state.questResults);
|
||||
socket.emit('admin_action_success');
|
||||
broadcastAdminUpdate();
|
||||
}
|
||||
});
|
||||
|
||||
socket.on('admin_kick_player', ({ roomId, targetSocketId }) => {
|
||||
const game = games[roomId];
|
||||
if (game) {
|
||||
const playerIndex = game.state.players.findIndex(p => p.id === targetSocketId);
|
||||
if (playerIndex !== -1) {
|
||||
const playerName = game.state.players[playerIndex].name;
|
||||
game.state.players.splice(playerIndex, 1);
|
||||
|
||||
// Notificar al jugador expulsado
|
||||
io.to(targetSocketId).emit('game_finalized');
|
||||
const targetSocket = io.sockets.sockets.get(targetSocketId);
|
||||
targetSocket?.leave(roomId);
|
||||
|
||||
// Notificar al resto
|
||||
io.to(roomId).emit('player_left_game', { playerName: `${playerName} (Expulsado)` });
|
||||
io.to(roomId).emit('game_state', game.state);
|
||||
|
||||
io.emit('rooms_list', getRoomsList());
|
||||
updateGamePlayers(roomId, game.state.players.map(p => p.name));
|
||||
|
||||
socket.emit('admin_action_success');
|
||||
broadcastAdminUpdate();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user