Initial commit: KiraTV IPTV proxy server

Full-stack IPTV management system with Xtream Codes API compatibility,
multi-account provider fan-out, Jellyfin local library integration,
real-time dashboard, EPG support, and A/V-sync-safe stream recovery.
This commit is contained in:
joaquin
2026-05-17 23:22:05 +02:00
commit f5d6745ed0
62 changed files with 8567 additions and 0 deletions
+439
View File
@@ -0,0 +1,439 @@
import { useEffect, useState } from 'react'
import { Plus, Trash2, Edit2, List, Star, Server, Search } from 'lucide-react'
import api from '../lib/api'
interface User { id: number; username: string; max_connections: number; expiry_date: string | null; is_active: boolean; is_priority: boolean; created_at: string }
interface GroupedCategory { name: string; type: string; category_ids: number[]; provider_count: number }
interface CatalogEntry { id: number; category_id: number; category_name: string; type: string }
interface ProviderPref { id: number; provider_account_id: number; provider_name: string; priority: number }
interface Provider { id: number; name: string }
interface CustomCat { id: number; name: string; type: string }
const TYPE_LABELS: Record<string, string> = { live: 'Canales en directo', movie: 'Películas', series: 'Series' }
export default function Users() {
const [users, setUsers] = useState<User[]>([])
const [showForm, setShowForm] = useState(false)
const [editUser, setEditUser] = useState<User | null>(null)
const [catalogUser, setCatalogUser] = useState<User | null>(null)
const [providerUser, setProviderUser] = useState<User | null>(null)
const [allCategories, setAllCategories] = useState<GroupedCategory[]>([])
const [selectedCats, setSelectedCats] = useState<Set<number>>(new Set())
const [allCustomCats, setAllCustomCats] = useState<CustomCat[]>([])
const [selectedCustomCats, setSelectedCustomCats] = useState<Set<number>>(new Set())
const [catSearch, setCatSearch] = useState('')
const [allProviders, setAllProviders] = useState<Provider[]>([])
const [userProviderPrefs, setUserProviderPrefs] = useState<ProviderPref[]>([])
const [form, setForm] = useState({ username: '', password: '', max_connections: 1, expiry_date: '', is_active: true, is_priority: false })
async function load() {
const { data } = await api.get('/users/')
setUsers(data)
}
useEffect(() => { load() }, [])
async function submit(e: React.FormEvent) {
e.preventDefault()
const payload = { ...form, expiry_date: form.expiry_date || null }
if (editUser) {
await api.put(`/users/${editUser.id}`, payload)
} else {
await api.post('/users/', payload)
}
resetForm()
load()
}
function resetForm() {
setForm({ username: '', password: '', max_connections: 1, expiry_date: '', is_active: true, is_priority: false })
setShowForm(false)
setEditUser(null)
}
function startEdit(u: User) {
setForm({ username: u.username, password: '', max_connections: u.max_connections, expiry_date: u.expiry_date?.split('T')[0] || '', is_active: u.is_active, is_priority: u.is_priority })
setEditUser(u)
setShowForm(true)
}
async function del(id: number) {
if (!confirm('¿Eliminar usuario?')) return
await api.delete(`/users/${id}`)
load()
}
async function togglePriority(u: User) {
await api.put(`/users/${u.id}`, { is_priority: !u.is_priority })
load()
}
async function openCatalog(u: User) {
setCatalogUser(u)
setCatSearch('')
const [grouped, catalog, customCats, userCustomCatalog] = await Promise.all([
api.get('/catalogs/grouped').then(r => r.data as GroupedCategory[]),
api.get(`/users/${u.id}/catalog`).then(r => r.data as CatalogEntry[]),
api.get('/custom-categories/').then(r => r.data as CustomCat[]),
api.get(`/users/${u.id}/custom-catalog`).then(r => r.data as number[]),
])
setAllCategories(grouped)
setSelectedCats(new Set(catalog.map((c: CatalogEntry) => c.category_id)))
setAllCustomCats(customCats)
setSelectedCustomCats(new Set(userCustomCatalog))
}
function isGroupSelected(g: GroupedCategory): boolean {
return g.category_ids.some(id => selectedCats.has(id))
}
function toggleGroup(g: GroupedCategory, checked: boolean) {
setSelectedCats(prev => {
const n = new Set(prev)
if (checked) {
g.category_ids.forEach(id => n.add(id))
} else {
g.category_ids.forEach(id => n.delete(id))
}
return n
})
}
function selectAllFiltered(cats: GroupedCategory[]) {
setSelectedCats(prev => {
const n = new Set(prev)
cats.forEach((g: GroupedCategory) => g.category_ids.forEach((id: number) => n.add(id)))
return n
})
// Also select all filtered custom cats
const filteredCC = allCustomCats.filter(c => !catSearch || c.name.toLowerCase().includes(catSearch.toLowerCase()))
setSelectedCustomCats(prev => {
const n = new Set(prev)
filteredCC.forEach(c => n.add(c.id))
return n
})
}
function selectNoneFiltered(cats: GroupedCategory[]) {
setSelectedCats(prev => {
const n = new Set(prev)
cats.forEach((g: GroupedCategory) => g.category_ids.forEach((id: number) => n.delete(id)))
return n
})
const filteredCC = allCustomCats.filter(c => !catSearch || c.name.toLowerCase().includes(catSearch.toLowerCase()))
setSelectedCustomCats(prev => {
const n = new Set(prev)
filteredCC.forEach(c => n.delete(c.id))
return n
})
}
async function saveCatalog() {
if (!catalogUser) return
await Promise.all([
api.post(`/users/${catalogUser.id}/catalog`, Array.from(selectedCats)),
api.post(`/users/${catalogUser.id}/custom-catalog`, Array.from(selectedCustomCats)),
])
setCatalogUser(null)
}
async function openProviderPrefs(u: User) {
setProviderUser(u)
const [providers, prefs] = await Promise.all([
api.get('/providers/').then(r => r.data as Provider[]),
api.get(`/users/${u.id}/providers`).then(r => r.data as ProviderPref[]),
])
setAllProviders(providers)
setUserProviderPrefs(prefs)
}
async function addProviderPref(providerId: number) {
if (!providerUser) return
await api.post(`/users/${providerUser.id}/providers`, { provider_account_id: providerId, priority: userProviderPrefs.length })
const { data } = await api.get(`/users/${providerUser.id}/providers`)
setUserProviderPrefs(data)
}
async function removeProviderPref(providerId: number) {
if (!providerUser) return
await api.delete(`/users/${providerUser.id}/providers/${providerId}`)
const { data } = await api.get(`/users/${providerUser.id}/providers`)
setUserProviderPrefs(data)
}
const prefProviderIds = new Set(userProviderPrefs.map(p => p.provider_account_id))
// Catalog modal filtered + grouped by type
const filteredCats = allCategories.filter(c =>
!catSearch || c.name.toLowerCase().includes(catSearch.toLowerCase())
)
const filteredCustomCats = allCustomCats.filter(c =>
!catSearch || c.name.toLowerCase().includes(catSearch.toLowerCase())
)
const selectedGroupCount = allCategories.filter(g => isGroupSelected(g)).length + selectedCustomCats.size
return (
<div className="p-6 space-y-5">
<div className="flex items-center justify-between">
<h1 className="text-xl font-bold">Usuarios</h1>
<button onClick={() => setShowForm(v => !v)} className="flex items-center gap-2 bg-primary-500 hover:bg-primary-600 px-4 py-2 rounded-lg text-sm font-medium transition-colors">
<Plus size={16} /> Nuevo usuario
</button>
</div>
{showForm && (
<form onSubmit={submit} className="bg-dark-800 border border-dark-700 rounded-xl p-5 space-y-3">
<h3 className="font-semibold text-sm">{editUser ? 'Editar usuario' : 'Nuevo usuario'}</h3>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-xs text-gray-500 mb-1">Usuario</label>
<input value={form.username} onChange={e => setForm(f => ({ ...f, username: e.target.value }))} required disabled={!!editUser}
className="w-full bg-dark-700 border border-dark-600 rounded-lg px-3 py-2 text-sm" />
</div>
<div>
<label className="block text-xs text-gray-500 mb-1">Contraseña {editUser && '(dejar vacío para no cambiar)'}</label>
<input type="password" value={form.password} onChange={e => setForm(f => ({ ...f, password: e.target.value }))} required={!editUser}
className="w-full bg-dark-700 border border-dark-600 rounded-lg px-3 py-2 text-sm" />
</div>
<div>
<label className="block text-xs text-gray-500 mb-1">Max. conexiones simultáneas</label>
<input type="number" min={1} value={form.max_connections} onChange={e => setForm(f => ({ ...f, max_connections: +e.target.value }))}
className="w-full bg-dark-700 border border-dark-600 rounded-lg px-3 py-2 text-sm" />
</div>
<div>
<label className="block text-xs text-gray-500 mb-1">Fecha expiración</label>
<input type="date" value={form.expiry_date} onChange={e => setForm(f => ({ ...f, expiry_date: e.target.value }))}
className="w-full bg-dark-700 border border-dark-600 rounded-lg px-3 py-2 text-sm" />
</div>
<div className="flex items-center gap-4 col-span-2">
<label className="flex items-center gap-2 text-sm cursor-pointer">
<input type="checkbox" checked={form.is_active} onChange={e => setForm(f => ({ ...f, is_active: e.target.checked }))} />
Activo
</label>
<label className="flex items-center gap-2 text-sm cursor-pointer">
<input type="checkbox" checked={form.is_priority} onChange={e => setForm(f => ({ ...f, is_priority: e.target.checked }))} />
<Star size={13} className="text-yellow-400" />
Usuario prioritario
</label>
</div>
</div>
<div className="flex gap-2">
<button type="submit" className="bg-primary-500 hover:bg-primary-600 px-4 py-2 rounded-lg text-sm font-medium">Guardar</button>
<button type="button" onClick={resetForm} className="bg-dark-700 hover:bg-dark-600 px-4 py-2 rounded-lg text-sm">Cancelar</button>
</div>
</form>
)}
{/* Catalog assignment modal */}
{catalogUser && (
<div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4">
<div className="bg-dark-800 rounded-xl border border-dark-700 w-full max-w-2xl max-h-[85vh] flex flex-col">
<div className="p-4 border-b border-dark-700 flex items-center justify-between shrink-0">
<div>
<h2 className="font-semibold">Catálogo de <span className="text-primary-400">{catalogUser.username}</span></h2>
<p className="text-xs text-gray-500 mt-0.5">{selectedGroupCount} de {allCategories.length + allCustomCats.length} categorías seleccionadas</p>
</div>
<button onClick={() => setCatalogUser(null)} className="text-gray-500 hover:text-white">✕</button>
</div>
{/* Search + bulk actions */}
<div className="p-3 border-b border-dark-700 shrink-0 space-y-2">
<div className="relative">
<Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500" />
<input
value={catSearch}
onChange={e => setCatSearch(e.target.value)}
placeholder="Buscar categoría..."
className="w-full bg-dark-700 border border-dark-600 rounded-lg pl-9 pr-3 py-2 text-sm focus:outline-none focus:border-primary-500"
/>
</div>
<div className="flex gap-2">
<button
onClick={() => selectAllFiltered(filteredCats)}
className="text-xs px-3 py-1 rounded-lg bg-primary-900/40 hover:bg-primary-900/70 text-primary-300 border border-primary-800 transition-colors"
>
Seleccionar todo
</button>
<button
onClick={() => selectNoneFiltered(filteredCats)}
className="text-xs px-3 py-1 rounded-lg bg-dark-700 hover:bg-dark-600 text-gray-400 border border-dark-600 transition-colors"
>
Ninguna
</button>
</div>
</div>
<div className="overflow-y-auto flex-1 p-4 space-y-4">
{(['live', 'movie', 'series'] as const).map(type => {
const cats = filteredCats.filter(c => c.type === type)
if (!cats.length) return null
return (
<div key={type}>
<h3 className="text-xs text-gray-500 uppercase tracking-wider mb-2 flex items-center justify-between">
<span>{TYPE_LABELS[type]}</span>
<span className="normal-case text-gray-600">{cats.filter(g => isGroupSelected(g)).length}/{cats.length}</span>
</h3>
<div className="grid grid-cols-2 gap-1">
{cats.map(cat => (
<label
key={cat.name}
className={`flex items-center gap-2 text-sm p-2 rounded-lg cursor-pointer transition-colors ${isGroupSelected(cat) ? 'bg-primary-900/20 hover:bg-primary-900/30' : 'hover:bg-dark-700'}`}
>
<input
type="checkbox"
checked={isGroupSelected(cat)}
onChange={e => toggleGroup(cat, e.target.checked)}
className="shrink-0"
/>
<span className="truncate">{cat.name}</span>
{cat.provider_count > 0 && (
<span className={`shrink-0 text-xs px-1.5 py-0.5 rounded ml-auto font-medium ${cat.provider_count > 1 ? 'bg-green-900/50 text-green-400' : 'bg-dark-600 text-gray-500'}`}>
{cat.provider_count}p
</span>
)}
</label>
))}
</div>
</div>
)
})}
{filteredCats.length === 0 && filteredCustomCats.length === 0 && (
<div className="text-center text-gray-500 text-sm py-8">Sin resultados</div>
)}
{/* Custom categories section */}
{filteredCustomCats.length > 0 && (
<div>
<h3 className="text-xs text-gray-500 uppercase tracking-wider mb-2 flex items-center gap-2">
<Star size={11} className="text-yellow-400" />
<span>Categorías personalizadas</span>
<span className="normal-case text-gray-600">{filteredCustomCats.filter(c => selectedCustomCats.has(c.id)).length}/{filteredCustomCats.length}</span>
</h3>
<div className="grid grid-cols-2 gap-1">
{filteredCustomCats.map(cat => (
<label
key={cat.id}
className={`flex items-center gap-2 text-sm p-2 rounded-lg cursor-pointer transition-colors ${selectedCustomCats.has(cat.id) ? 'bg-yellow-900/20 hover:bg-yellow-900/30' : 'hover:bg-dark-700'}`}
>
<input
type="checkbox"
checked={selectedCustomCats.has(cat.id)}
onChange={e => {
setSelectedCustomCats(prev => {
const n = new Set(prev)
e.target.checked ? n.add(cat.id) : n.delete(cat.id)
return n
})
}}
className="shrink-0"
/>
<span className="truncate">{cat.name}</span>
<Star size={10} className="shrink-0 text-yellow-500 ml-auto" />
</label>
))}
</div>
</div>
)}
</div>
<div className="p-4 border-t border-dark-700 flex gap-2 justify-end shrink-0">
<button onClick={() => setCatalogUser(null)} className="bg-dark-700 px-4 py-2 rounded-lg text-sm">Cancelar</button>
<button onClick={saveCatalog} className="bg-primary-500 hover:bg-primary-600 px-4 py-2 rounded-lg text-sm font-medium">Guardar catálogo</button>
</div>
</div>
</div>
)}
{/* Provider preferences modal */}
{providerUser && (
<div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4">
<div className="bg-dark-800 rounded-xl border border-dark-700 w-full max-w-md flex flex-col">
<div className="p-4 border-b border-dark-700 flex items-center justify-between">
<h2 className="font-semibold">Proveedores preferidos — <span className="text-primary-400">{providerUser.username}</span></h2>
<button onClick={() => setProviderUser(null)} className="text-gray-500 hover:text-white">✕</button>
</div>
<div className="p-4 space-y-2">
<p className="text-xs text-gray-500 mb-3">Los proveedores marcados se intentan primero al asignar un slot. Si ninguno está disponible, se usa cualquiera con slot libre.</p>
{allProviders.map(p => {
const isPref = prefProviderIds.has(p.id)
return (
<div key={p.id} className={`flex items-center justify-between p-3 rounded-lg border ${isPref ? 'border-primary-700 bg-primary-900/20' : 'border-dark-600 bg-dark-700'}`}>
<span className="text-sm">{p.name}</span>
<button
onClick={() => isPref ? removeProviderPref(p.id) : addProviderPref(p.id)}
className={`text-xs px-3 py-1 rounded-lg font-medium transition-colors ${isPref ? 'bg-primary-600 hover:bg-red-700 text-white' : 'bg-dark-600 hover:bg-primary-700 text-gray-300 hover:text-white'}`}
>
{isPref ? 'Quitar' : 'Preferido'}
</button>
</div>
)
})}
{allProviders.length === 0 && (
<div className="text-center text-gray-500 text-sm py-4">No hay proveedores configurados</div>
)}
</div>
<div className="p-4 border-t border-dark-700 flex justify-end">
<button onClick={() => setProviderUser(null)} className="bg-dark-700 px-4 py-2 rounded-lg text-sm">Cerrar</button>
</div>
</div>
</div>
)}
<div className="bg-dark-800 border border-dark-700 rounded-xl overflow-hidden">
<table className="w-full text-sm">
<thead className="border-b border-dark-700 text-xs text-gray-500">
<tr>
<th className="text-left px-4 py-3">Usuario</th>
<th className="text-left px-4 py-3">Conexiones</th>
<th className="text-left px-4 py-3">Expiración</th>
<th className="text-left px-4 py-3">Estado</th>
<th className="text-left px-4 py-3">Acciones</th>
</tr>
</thead>
<tbody>
{users.map(u => (
<tr key={u.id} className="border-b border-dark-700 hover:bg-dark-700/30">
<td className="px-4 py-3">
<div className="flex items-center gap-1.5">
{u.is_priority && <Star size={12} className="text-yellow-400 shrink-0" />}
<span className="font-mono">{u.username}</span>
</div>
</td>
<td className="px-4 py-3">{u.max_connections}</td>
<td className="px-4 py-3 text-gray-400">{u.expiry_date ? new Date(u.expiry_date).toLocaleDateString('es-ES') : '—'}</td>
<td className="px-4 py-3">
<span className={`text-xs px-2 py-0.5 rounded-full ${u.is_active ? 'bg-green-900/40 text-green-400' : 'bg-red-900/40 text-red-400'}`}>
{u.is_active ? 'Activo' : 'Inactivo'}
</span>
</td>
<td className="px-4 py-3">
<div className="flex items-center gap-1">
<button onClick={() => openCatalog(u)} title="Asignar catálogo" className="p-1.5 rounded hover:bg-dark-600 text-gray-400 hover:text-blue-400">
<List size={14} />
</button>
<button onClick={() => openProviderPrefs(u)} title="Proveedores preferidos" className="p-1.5 rounded hover:bg-dark-600 text-gray-400 hover:text-purple-400">
<Server size={14} />
</button>
<button onClick={() => togglePriority(u)} title={u.is_priority ? 'Quitar prioridad' : 'Hacer prioritario'} className={`p-1.5 rounded hover:bg-dark-600 transition-colors ${u.is_priority ? 'text-yellow-400' : 'text-gray-400 hover:text-yellow-400'}`}>
<Star size={14} />
</button>
<button onClick={() => startEdit(u)} title="Editar" className="p-1.5 rounded hover:bg-dark-600 text-gray-400 hover:text-yellow-400">
<Edit2 size={14} />
</button>
<button onClick={() => del(u.id)} title="Eliminar" className="p-1.5 rounded hover:bg-dark-600 text-gray-400 hover:text-red-400">
<Trash2 size={14} />
</button>
</div>
</td>
</tr>
))}
{users.length === 0 && (
<tr><td colSpan={5} className="px-4 py-8 text-center text-gray-500">No hay usuarios</td></tr>
)}
</tbody>
</table>
</div>
</div>
)
}