-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_utils.js
More file actions
458 lines (405 loc) · 14.3 KB
/
Copy pathbinary_utils.js
File metadata and controls
458 lines (405 loc) · 14.3 KB
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
/**
* Utilidades para manejo de archivos binarios en DBP2P
*/
/**
* Convierte un archivo a Base64
* @param {File|Blob} file - El archivo o blob a convertir
* @returns {Promise<string>} - Promesa que resuelve con el string en Base64
*/
function fileToBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
// Eliminar el prefijo "data:*/*;base64," para obtener solo el contenido Base64
const base64String = reader.result.split(",")[1];
resolve(base64String);
};
reader.onerror = (error) => reject(error);
});
}
/**
* Calcula el hash SHA-256 de un archivo o blob
* @param {File|Blob} file - El archivo o blob para calcular el hash
* @returns {Promise<string>} - Promesa que resuelve con el hash en formato hexadecimal
*/
async function calculateSHA256(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = async () => {
try {
// Usar la API Web Crypto para calcular el hash
const hashBuffer = await crypto.subtle.digest("SHA-256", reader.result);
// Convertir el ArrayBuffer a string hexadecimal
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
resolve(hashHex);
} catch (error) {
reject(error);
}
};
reader.onerror = (error) => reject(error);
});
}
/**
* Sube un archivo binario a una colección
* @param {string} collection - Nombre de la colección
* @param {File} file - Archivo a subir
* @param {Object} metadata - Metadatos adicionales para el archivo
* @param {Function} [progressCallback] - Función de callback para reportar progreso (0-100)
* @returns {Promise<Object>} - Promesa que resuelve con los metadatos del archivo creado
*/
async function uploadBinaryToCollection(
collection,
file,
metadata = {},
progressCallback = null
) {
try {
// Tamaño máximo de fragmento (2MB para mejor compatibilidad)
let CHUNK_SIZE = 2 * 1024 * 1024;
// Ajustar tamaño de fragmento según el tipo de archivo
if (file.type === "video/mp4") {
// Para archivos MP4, usar fragmentos más pequeños (1MB)
CHUNK_SIZE = 1 * 1024 * 1024;
console.log("Archivo MP4 detectado, usando fragmentos de 1MB");
}
// Verificar si el archivo es grande (>5MB)
const isLargeFile = file.size > 5 * 1024 * 1024;
// Calcular número óptimo de fragmentos basado en el tamaño y tipo de archivo
let totalChunks = Math.ceil(file.size / CHUNK_SIZE);
// Para archivos MP4 muy grandes, limitar el número de fragmentos
const MAX_CHUNKS = 200; // Límite máximo de fragmentos (aumentado para videos grandes)
if (file.type === "video/mp4" && totalChunks > MAX_CHUNKS) {
console.log(
`Archivo MP4 grande detectado (${totalChunks} fragmentos). Ajustando a ${MAX_CHUNKS} fragmentos.`
);
// Recalcular tamaño de fragmento para tener exactamente MAX_CHUNKS fragmentos
CHUNK_SIZE = Math.ceil(file.size / MAX_CHUNKS);
totalChunks = MAX_CHUNKS;
console.log(`Nuevo tamaño de fragmento: ${CHUNK_SIZE} bytes`);
}
// Para archivos extremadamente grandes, mostrar advertencia
if (file.size > 500 * 1024 * 1024) {
// 500MB
console.warn(
`Archivo muy grande detectado (${(file.size / (1024 * 1024)).toFixed(
2
)}MB). La subida puede tardar mucho tiempo.`
);
showAlert(
`Archivo muy grande (${(file.size / (1024 * 1024)).toFixed(
2
)}MB). La subida puede tardar mucho tiempo y consumir muchos recursos.`,
"warning"
);
}
// Para archivos pequeños, usar el método simple
if (!isLargeFile) {
// Convertir archivo a Base64
const base64Content = await fileToBase64(file);
// Crear documento con el contenido binario
const documentData = {
filename: file.name,
mimetype: file.type,
size: file.size,
binary: base64Content,
...metadata,
};
// Crear documento en la colección
const result = await makeApiRequest(
`${API_URL}/collections/${collection}`,
{
method: "POST",
body: JSON.stringify(documentData),
useCache: false,
}
);
return result;
}
// Para archivos grandes, usar streaming por fragmentos
// Crear un ID temporal para el archivo
const tempId = `temp_${Date.now()}_${Math.random()
.toString(36)
.substring(2, 15)}`;
// Crear documento inicial con metadatos pero sin contenido
const initialData = {
filename: file.name,
mimetype: file.type,
size: file.size,
chunks: totalChunks, // Usar el valor calculado anteriormente
tempId: tempId,
isMultipart: true,
chunkSize: CHUNK_SIZE,
completedChunks: 0,
...metadata,
};
// Crear documento inicial
const initialResult = await makeApiRequest(
`${API_URL}/collections/${collection}`,
{
method: "POST",
body: JSON.stringify(initialData),
useCache: false,
}
);
const docId = initialResult.id;
// Subir fragmentos
for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) {
const chunk = file.slice(
chunkIndex * CHUNK_SIZE,
(chunkIndex + 1) * CHUNK_SIZE
);
await fetch(
`${API_URL}/collections/${collection}/${docId}/chunk?chunkIndex=${chunkIndex}`,
{
method: "PUT",
headers: {
Authorization: `Bearer ${token}`,
},
body: chunk,
}
);
// Actualizar progreso
if (progressCallback) {
const progress = Math.round(((chunkIndex + 1) / totalChunks) * 100);
progressCallback(progress);
}
}
// Verificar que todos los fragmentos se hayan subido correctamente
try {
console.log("Verificando integridad de la subida...");
const verifyResponse = await fetch(
`${API_URL}/diagnostics/document/${collection}/${docId}`,
{
method: "GET",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
credentials: "include",
mode: "cors",
}
);
if (verifyResponse.ok) {
const verifyData = await verifyResponse.json();
console.log("Resultado de verificación:", verifyData);
// Si hay problemas, intentar reparar
if (!verifyData.success) {
console.log("Intentando reparar documento...");
const repairResponse = await fetch(
`${API_URL}/diagnostics/document/${collection}/${docId}/repair`,
{
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
credentials: "include",
mode: "cors",
}
);
if (repairResponse.ok) {
const repairData = await repairResponse.json();
console.log("Resultado de reparación:", repairData);
}
}
}
} catch (error) {
console.error("Error al verificar integridad:", error);
// No lanzar error aquí, continuar con la finalización
}
// Finalizar la subida
const finalizeData = {
isComplete: true,
tempId: tempId,
partCount: totalChunks,
fileSize: file.size,
chunkSize: CHUNK_SIZE,
mimeType: file.type,
fileName: file.name,
force: file.type === "video/mp4", // Forzar finalización para archivos MP4
};
console.log("Finalizando subida con datos:", finalizeData);
const finalResult = await makeApiRequest(
`${API_URL}/collections/${collection}/${docId}/finalize`,
{
method: "POST", // Cambiar a POST para evitar problemas de caché
body: JSON.stringify(finalizeData),
useCache: false,
}
);
return finalResult;
} catch (error) {
console.error("Error al subir archivo binario:", error);
throw error;
}
}
/**
* Descarga un archivo binario de una colección
* @param {string} collection - Nombre de la colección
* @param {string} id - ID del documento
* @param {Function} [progressCallback] - Función de callback para reportar progreso (0-100)
* @returns {Promise<Object>} - Promesa que resuelve con el objeto {blob, filename, mimetype}
*/
async function downloadBinaryFromCollection(
collection,
id,
progressCallback = null
) {
try {
// Obtener documento (metadatos)
const doc = await makeApiRequest(
`${API_URL}/collections/${collection}/${id}`
);
if (!doc || !doc.data) {
throw new Error("No se pudo obtener el documento");
}
// Verificar si es un archivo multipart (grande)
const isMultipart = doc.data.isMultipart === true;
// Para archivos pequeños, usar el método simple
if (!isMultipart) {
if (!doc.data.binary) {
throw new Error("El documento no contiene datos binarios");
}
// Convertir Base64 a Blob
const byteCharacters = atob(doc.data.binary);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += 512) {
const slice = byteCharacters.slice(offset, offset + 512);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
// Crear Blob con el tipo MIME correcto
const blob = new Blob(byteArrays, {
type: doc.data.mimetype || "application/octet-stream",
});
return {
blob,
filename: doc.data.filename || `file_${id}`,
mimetype: doc.data.mimetype || "application/octet-stream",
};
}
// Para archivos grandes, descargar por fragmentos
const totalChunks = doc.data.chunks || 0;
if (totalChunks <= 0) {
throw new Error("Información de fragmentos no válida");
}
// Array para almacenar todos los fragmentos
const chunks = [];
// Descargar cada fragmento
for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) {
const chunkUrl = `${API_URL}/collections/${collection}/${id}/chunk?chunkIndex=${chunkIndex}`;
// Solicitar fragmento
const chunkResponse = await makeApiRequest(chunkUrl, { useCache: false });
if (!chunkResponse || !chunkResponse.binary) {
console.error(
`Error al descargar fragmento ${chunkIndex} (${chunkUrl})`,
chunkResponse
);
showAlert(
`No se pudo descargar el fragmento ${chunkIndex}. Verifique que el archivo exista en el servidor.`,
"danger"
);
throw new Error(
`Error al descargar fragmento ${chunkIndex}: Fragmento no encontrado. Verifique que el archivo exista en el servidor.`
);
}
// Verificar checksum si está disponible
if (chunkResponse.checksum) {
const chunkData = atob(chunkResponse.binary);
const byteNumbers = new Array(chunkData.length);
for (let i = 0; i < chunkData.length; i++) {
byteNumbers[i] = chunkData.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
const blob = new Blob([byteArray]);
// Calcular checksum del fragmento recibido
const calculatedChecksum = await calculateSHA256(blob);
// Verificar integridad
if (calculatedChecksum !== chunkResponse.checksum) {
throw new Error(
`Error de integridad en fragmento ${chunkIndex}: checksum no coincide`
);
}
}
// Convertir Base64 a ArrayBuffer
const byteCharacters = atob(chunkResponse.binary);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
// Guardar fragmento
chunks.push(byteArray);
// Actualizar progreso
if (progressCallback) {
const progress = Math.round(((chunkIndex + 1) / totalChunks) * 100);
progressCallback(progress);
}
}
// Combinar todos los fragmentos en un solo Blob
const blob = new Blob(chunks, {
type: doc.data.mimetype || "application/octet-stream",
});
return {
blob,
filename: doc.data.filename || `file_${id}`,
mimetype: doc.data.mimetype || "application/octet-stream",
};
} catch (error) {
console.error("Error al descargar archivo binario:", error);
throw error;
}
}
/**
* Descarga y abre un archivo binario
* @param {string} collection - Nombre de la colección
* @param {string} id - ID del documento
* @param {boolean} [visualize=false] - Si es true, intenta abrir el archivo en el navegador; si es false, lo descarga
*/
async function openBinaryFile(collection, id, visualize = false) {
try {
const { blob, filename, mimetype } = await downloadBinaryFromCollection(
collection,
id
);
const url = URL.createObjectURL(blob);
// Permitir visualizar imágenes, textos, PDFs y videos
const canHandle =
mimetype &&
(mimetype.startsWith("image/") ||
mimetype.startsWith("text/") ||
mimetype.startsWith("video/") ||
mimetype === "application/pdf");
if (visualize && canHandle) {
window.open(url, "_blank");
} else {
const a = document.createElement("a");
a.href = url;
a.download = filename || "archivo";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
} catch (error) {
console.error("Error al abrir archivo:", error);
// Verificar si es un error de fragmento no encontrado
if (error.message && error.message.includes("Fragmento no encontrado")) {
showAlert(
"No se pudo abrir el archivo: Error fragmento no encontrado. Verifique que el archivo exista en el servidor y que no esté corrupto.",
"danger"
);
} else {
showAlert("No se pudo abrir el archivo: " + error, "danger");
}
}
}