File size: 11,283 Bytes
eefe2da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
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(`===================================================`);
});