const http = require('http'); const fs = require('fs'); const path = require('path'); const { initializeApp, cert } = require('firebase-admin/app'); const { getFirestore } = require('firebase-admin/firestore'); const PORT = 8080; const VOICES_FILE = path.join(__dirname, 'voices.json'); const IMAGES_DIR = path.join(__dirname, 'images'); const KEY_FILE = path.join(__dirname, 'firebase_key.json'); // INTERVALOS DE RESPALDO EN LA NUBE (FIREBASE) const CLOUD_SYNC_DEBOUNCE_MS = 5 * 60 * 1000; // Espera 5 minutos sin nuevas ediciones antes de subir const CLOUD_SYNC_MIN_INTERVAL_MS = 1 * 60 * 60 * 1000; // Máximo 1 subida cada hora como mínimo let lastCloudSyncTime = 0; let cloudSyncDebounceTimer = null; let hasPendingCloudSync = false; let latestDataToSync = null; if (!fs.existsSync(IMAGES_DIR)) { fs.mkdirSync(IMAGES_DIR, { recursive: true }); } // Inicializar Firebase Admin SDK para respaldo secundario en la nube let db = null; try { if (fs.existsSync(KEY_FILE)) { const serviceAccount = require(KEY_FILE); initializeApp({ credential: cert(serviceAccount) }); db = getFirestore(); console.log('[+] Conectado a Firebase Firestore (Modo: Respaldo Secundario Programado)'); } } catch (e) { console.warn('[-] Firebase no inicializado. El servidor funcionará 100% en modo Local.'); } function extractImagesFromVoices(data) { try { if (!data || !Array.isArray(data.voices)) return; data.voices.forEach(voice => { if (voice.coverImage && voice.coverImage.startsWith('data:image/')) { const matches = voice.coverImage.match(/^data:image\/([a-zA-Z+]+);base64,(.+)$/); if (matches && matches[2]) { const ext = matches[1] === 'jpeg' ? 'jpg' : 'png'; const fileName = `${voice.id}.${ext}`; const filePath = path.join(IMAGES_DIR, fileName); if (!fs.existsSync(filePath)) { fs.writeFile(filePath, Buffer.from(matches[2], 'base64'), (err) => { if (!err) console.log(`[+] Imagen guardada físicamente en: images/${fileName}`); }); } } } }); } catch (err) { console.error('[-] Error extrayendo imágenes:', err); } } // FUNCIONES LOCALES (FUENTE DE VERDAD PRIMARIA) function getLocalData() { if (fs.existsSync(VOICES_FILE)) { try { const raw = fs.readFileSync(VOICES_FILE, 'utf8'); return JSON.parse(raw); } catch (e) { console.error('[-] Error leyendo voices.json:', e.message); } } return { folders: [], voices: [] }; } function saveLocalData(data) { try { const cleanData = JSON.parse(JSON.stringify(data)); const folderMap = new Map(); (cleanData.folders || []).forEach(f => { if (f && f.id) folderMap.set(f.id, f.name); }); if (Array.isArray(cleanData.voices)) { cleanData.voices.forEach(v => { if (v) { const fId = v.folderId || 'f_sueltas'; v.folderName = folderMap.get(fId) || (fId === 'f_sueltas' ? 'Voces Sueltas' : fId === 'f_favorites' ? 'Favoritas' : fId === 'all' ? 'Todas' : 'Sin Carpeta'); } }); } fs.writeFileSync(VOICES_FILE, JSON.stringify(cleanData, null, 2), 'utf8'); console.log(`[+] [LOCAL ⚡] Guardado instantáneo en voices.json (${(cleanData.voices || []).length} voces, ${(cleanData.folders || []).length} carpetas)`); return true; } catch (e) { console.error('[-] Error guardando localmente en voices.json:', e.message); return false; } } // RESPALDO PROGRAMADO EN LA NUBE (FIREBASE FIRESTORE EN SEGUNDO PLANO) async function saveFirebaseData(data) { if (!db || !data) return false; try { console.log('[+] [NUBE ☁️] Iniciando sincronización programada con Firebase Firestore...'); const cleanFolders = JSON.parse(JSON.stringify(data.folders || [])); const cleanVoices = JSON.parse(JSON.stringify(data.voices || [])); const currentFolderIds = new Set(cleanFolders.map(f => f.id)); const snapFolders = await db.collection('folders').get(); let ops = []; snapFolders.forEach(doc => { if (!currentFolderIds.has(doc.id)) { ops.push({ type: 'delete', ref: doc.ref }); } }); cleanFolders.forEach(f => { if (f.id) { ops.push({ type: 'set', ref: db.collection('folders').doc(f.id), data: f }); } }); const currentVoiceIds = new Set(cleanVoices.map(v => v.id)); const snapVoices = await db.collection('voices').get(); snapVoices.forEach(doc => { if (!currentVoiceIds.has(doc.id)) { ops.push({ type: 'delete', ref: doc.ref }); } }); cleanVoices.forEach(v => { if (v.id) { ops.push({ type: 'set', ref: db.collection('voices').doc(v.id), data: v }); } }); const BATCH_SIZE = 50; for (let i = 0; i < ops.length; i += BATCH_SIZE) { const chunk = ops.slice(i, i + BATCH_SIZE); const batch = db.batch(); chunk.forEach(op => { if (op.type === 'delete') batch.delete(op.ref); else batch.set(op.ref, op.data, { merge: true }); }); await batch.commit(); } lastCloudSyncTime = Date.now(); hasPendingCloudSync = false; console.log(`[+] [NUBE ☁️] Respaldo completado exitosamente en Firebase! Próxima subida en al menos 1-5 horas.`); return true; } catch (e) { if (e.message && e.message.includes('Quota exceeded')) { console.warn('[!] [NUBE ☁️] Cuota diaria de Firebase alcanzada. Se reanudará automáticamente más tarde.'); } else { console.warn('[-] [NUBE ☁️] Respaldo no completado:', e.message); } return false; } } // PLANIFICADOR INTELIGENTE DE SINCRONIZACIÓN CON FIREBASE function scheduleSmartCloudSync(data) { if (!db) return; latestDataToSync = data; hasPendingCloudSync = true; if (cloudSyncDebounceTimer) { clearTimeout(cloudSyncDebounceTimer); } const timeSinceLastSync = Date.now() - lastCloudSyncTime; // Si ha pasado más de 1 hora desde la última sincronización, sincronizar en 5 minutos de calma const delay = Math.max(CLOUD_SYNC_DEBOUNCE_MS, CLOUD_SYNC_MIN_INTERVAL_MS - timeSinceLastSync); console.log(`[i] [PLANIFICADOR ⏱️] Cambio detectado. Respaldo en la nube programado para ejecutarse en ${Math.round(delay / 60000)} minutos.`); cloudSyncDebounceTimer = setTimeout(() => { if (hasPendingCloudSync && latestDataToSync) { saveFirebaseData(latestDataToSync); } }, delay); } // Sincronización inicial al arrancar el servidor (si han pasado más de 1 hora o primera vez) setTimeout(() => { if (db) { const initialData = getLocalData(); if (initialData && initialData.voices && initialData.voices.length > 0) { console.log('[+] [INICIO 🚀] Sincronización inicial al conectar servidor...'); saveFirebaseData(initialData); } } }, 5000); const server = http.createServer(async (req, res) => { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); res.setHeader('Access-Control-Allow-Headers', 'Content-Type'); if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; } if (req.url === '/ping' || req.url === '/api/ping') { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ status: 'ok', localFirst: true, firebase: !!db })); return; } // RESOLVER ENLACES DE AUDIO FRESCOS AL VUELO DESDE SERVIDORES DE FISH AUDIO if (req.method === 'GET' && req.url.startsWith('/api/resolve_audio')) { try { const parsedUrl = new URL(req.url, `http://localhost:${PORT}`); const modelId = parsedUrl.searchParams.get('modelId'); if (!modelId) { res.writeHead(400, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Falta parametro modelId' })); return; } const fishRes = await fetch(`https://api.fish.audio/model/${modelId}`); if (fishRes.ok) { const json = await fishRes.json(); let freshUrl = ''; if (json.samples && Array.isArray(json.samples) && json.samples.length > 0 && json.samples[0].audio) { freshUrl = json.samples[0].audio; } else if (json.audioUrl) { freshUrl = json.audioUrl; } else if (json.sampleAudio) { freshUrl = json.sampleAudio; } const cover = json.cover_image ? `https://public-platform.r2.fish.audio/${json.cover_image}` : ''; if (freshUrl) { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ success: true, audioUrl: freshUrl, title: json.title, coverImage: cover })); return; } } } catch (e) { console.warn('[-] Error resolviendo audio en servidor local:', e.message); } res.writeHead(404, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ success: false, error: 'No se pudo obtener el audio de muestra' })); return; } // LECTURA 100% LOCAL (INSTANTÁNEA) if (req.method === 'GET' && (req.url.startsWith('/voices.json') || req.url === '/')) { const localData = getLocalData(); extractImagesFromVoices(localData); res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' }); res.end(JSON.stringify(localData)); return; } // ESCRITURA: LOCAL PRIMERO (0 ms), FIREBASE PROGRAMADO EN SEGUNDO PLANO if (req.method === 'POST' && req.url === '/api/save') { let body = ''; req.on('data', chunk => { body += chunk.toString(); }); req.on('end', async () => { try { const parsed = JSON.parse(body); extractImagesFromVoices(parsed); // 1. GUARDADO LOCAL INMEDIATO EN DISCO (voices.json) - 0 MS DE LATENCIA saveLocalData(parsed); // Responder éxito de inmediato a la interfaz del usuario res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ success: true, storage: 'local_first' })); // 2. PROGRAMACIÓN INTELIGENTE EN SEGUNDO PLANO (CADA 5 HORAS O PERÍODOS DE CALMA) scheduleSmartCloudSync(parsed); } catch (e) { res.writeHead(400, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ success: false, error: e.message })); } }); return; } res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('Not found'); }); server.on('error', (e) => { if (e.code === 'EADDRINUSE') { console.log('==================================================='); console.log('[+] El Servidor Local-First YA ESTA ACTIVO en http://localhost:8080'); console.log('==================================================='); process.exit(0); } else { console.error('Error en el servidor:', e); } }); server.listen(PORT, () => { console.log(`===================================================`); console.log(` Servidor Fish Audio Vault en Ejecución (Local-First)!`); console.log(` Escuchando en http://localhost:${PORT}`); console.log(` Fuente Primaria: Disco Duro Local (voices.json) - Instantáneo`); console.log(` Respaldo en Nube (Firebase): Programado Inteligente (Debounce & Intervalos)`); console.log(`===================================================`); });