bot-functions 1.5.2 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/index.js +108 -2
  2. package/package.json +3 -1
package/index.js CHANGED
@@ -15,6 +15,10 @@ const { simpleParser } = require('mailparser');
15
15
  const xpath = require('xpath');
16
16
  const { JSDOM } = require('jsdom');
17
17
 
18
+ const { S3Client } = require("@aws-sdk/client-s3");
19
+ const { Upload } = require("@aws-sdk/lib-storage");
20
+
21
+ const separador = (os.type() === "Windows_NT") ? `\\` : "/";
18
22
 
19
23
  async function obtenerCorreos(email, password, subject) {
20
24
  const config = {
@@ -375,8 +379,6 @@ async function manageEmails(config, searchOptions) {
375
379
  }
376
380
  }
377
381
 
378
- let separador = (os.type() === "Windows_NT") ? `\\` : "/";
379
-
380
382
  async function* asyncGenerator(final) {
381
383
  var i = 0;
382
384
  while (i < final) {
@@ -903,6 +905,30 @@ const sendDataCH = async (params, dataJSON) => {
903
905
  });
904
906
  }
905
907
 
908
+ const sendDataClickHouse = async (params, dataJSON) => {
909
+ return new Promise(async function (resolve, reject) {
910
+ actualFunction = "sendDataClickHouse";
911
+ try {
912
+ const batchPromises = [];
913
+ const stringData = JSON.stringify(dataJSON);
914
+ const response = await axios({
915
+ method: 'post', url: process.env.INSERT_CLICKHOUSE, data: {params, dataJSON: stringData },
916
+ maxBodyLength: Infinity, headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }
917
+ });
918
+ batchPromises.push(response.status);
919
+ batchPromises.map(reg => log.info('Insert status', reg));
920
+ if (batchPromises.every(reg => reg == 200)) {
921
+ resolve({ status: "Packages inserted successfully", exit: 1 });
922
+ } else {
923
+ return reject(new Error('No se insertaron todos los paquetes'));
924
+ }
925
+ } catch (error) {
926
+ await insertLog(params, 107);
927
+ return reject(new Error(error.message));
928
+ }
929
+ });
930
+ }
931
+
906
932
  const waitFrame = (page, frame, framename, info, timeout, parent = null) => {
907
933
  return new Promise(async function (resolve, reject) {
908
934
  let counter = 0;
@@ -1374,6 +1400,84 @@ const uploadImageToS3 = async (filePath, key) => {
1374
1400
  return uploadFileResponse.data.data;
1375
1401
  }
1376
1402
 
1403
+ const sleepFile = (ms) => new Promise((r) => setTimeout(r, ms));
1404
+
1405
+ const validarZip = (zipPath) => {
1406
+ try {
1407
+ const zip = new AdmZip(zipPath);
1408
+ const entries = zip.getEntries();
1409
+
1410
+ if (entries.length === 0)
1411
+ throw new Error("El zip está vacío, no contiene archivos.");
1412
+
1413
+ // Verifica que cada entrada tenga contenido
1414
+ for (const entry of entries) {
1415
+ if (!entry.header || entry.header.size === 0)
1416
+ throw new Error(`La entrada "${entry.entryName}" está corrupta o vacía.`);
1417
+ }
1418
+ log.info(`[ZIP] Válido — ${entries.length} archivo(s) dentro.`);
1419
+ return true;
1420
+ } catch (error) {
1421
+ throw new Error(`[ZIP] Validación fallida: ${error.message}`);
1422
+ }
1423
+ };
1424
+
1425
+ const uploadEvidence = async (pathDownloads, params, reintentos = 3) => {
1426
+
1427
+ log.info(`[S3] Región: ${process.env.AWS_REGION_BUCKET} | Bucket: ${process.env.S3_BUCKET}`);
1428
+ const s3 = new S3Client({ region: process.env.AWS_REGION_BUCKET });
1429
+
1430
+ const zipPath = `${pathDownloads}/${params.reporte.filename}.zip`;
1431
+ const key = `${params.reporte.pathS3}/${params.reporte.filename}.zip`;
1432
+
1433
+ // Armar el zip
1434
+ const zip = new AdmZip();
1435
+ zip.addLocalFile(`${pathDownloads}/${params.reporte.filename}${process.env.EXTENSION_FILE}`);
1436
+ zip.writeZip(zipPath);
1437
+
1438
+ // Validar antes de intentar subir
1439
+ validarZip(zipPath);
1440
+
1441
+ let ultimoError;
1442
+
1443
+ for (let intento = 1; intento <= reintentos; intento++) {
1444
+ try {
1445
+ log.info(`[S3] Intento ${intento}/${reintentos} — subiendo ${key}`);
1446
+
1447
+ const upload = new Upload({
1448
+ client: s3,
1449
+ params: {
1450
+ Bucket: process.env.S3_BUCKET,
1451
+ Key: key,
1452
+ Body: fs.createReadStream(zipPath),
1453
+ ContentType: "application/zip",
1454
+ ACL: "public-read",
1455
+ },
1456
+ queueSize: 4,
1457
+ partSize: 10 * 1024 * 1024,
1458
+ });
1459
+
1460
+ await upload.done();
1461
+ const url = `https://${process.env.S3_BUCKET}.s3.${process.env.AWS_REGION_BUCKET}.amazonaws.com/${key}`;
1462
+ log.info(`[S3] Upload exitoso en intento ${intento} — ${key}`);
1463
+ await insertEvidenceCore(url, '', params.robot.baseHyperCube, params.robot.idgfc, process.env.PERIODO, params.reporte.date1, params.reporte.type);
1464
+ await insertLog2(params, 305);
1465
+ return key;
1466
+
1467
+ } catch (error) {
1468
+ ultimoError = error;
1469
+ log.error(`[S3] Intento ${intento} fallido: ${error.message}`);
1470
+
1471
+ if (intento < reintentos) {
1472
+ const espera = 2000 * intento;
1473
+ log.info(`[S3] Reintentando en ${espera / 1000}s...`);
1474
+ await sleepFile(espera);
1475
+ }
1476
+ }
1477
+ }
1478
+ throw new Error(`[S3] Upload fallido tras ${reintentos} intentos: ${ultimoError.message}`);
1479
+ };
1480
+
1377
1481
 
1378
1482
  module.exports = {
1379
1483
  waitNtype,
@@ -1430,4 +1534,6 @@ module.exports = {
1430
1534
  processDataDaily,
1431
1535
  uploadImageToS3,
1432
1536
  insertCatspecs,
1537
+ uploadEvidence,
1538
+ sendDataClickHouse
1433
1539
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bot-functions",
3
- "version": "1.5.2",
3
+ "version": "1.7.0",
4
4
  "description": "Bot functions",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -9,6 +9,8 @@
9
9
  "author": "Juan Monrroy Reyes",
10
10
  "license": "ISC",
11
11
  "dependencies": {
12
+ "@aws-sdk/client-s3": "^3.1022.0",
13
+ "@aws-sdk/lib-storage": "^3.1022.0",
12
14
  "adm-zip": "0.5.10",
13
15
  "axios": "0.21.1",
14
16
  "concat-stream": "2.0.0",