@ejfdelgado/ejflab-back 1.1.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 (64) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +2 -0
  3. package/package.json +57 -0
  4. package/srv/AudIASrv.mjs +218 -0
  5. package/srv/AuthorizationSrv.mjs +213 -0
  6. package/srv/ComputeEngineSrv.mjs +289 -0
  7. package/srv/EmailHandler.mjs +54 -0
  8. package/srv/Image2MeshSrv.mjs +101 -0
  9. package/srv/ImagiationSrv.mjs +408 -0
  10. package/srv/KeysSrv.mjs +104 -0
  11. package/srv/MainHandler.mjs +140 -0
  12. package/srv/MainReplacer.mjs +77 -0
  13. package/srv/MfaSrv.mjs +266 -0
  14. package/srv/MilvusSrv.mjs +152 -0
  15. package/srv/MinioSrv.mjs +154 -0
  16. package/srv/MongoSrv.mjs +320 -0
  17. package/srv/MyError.mjs +48 -0
  18. package/srv/MyFileService.mjs +392 -0
  19. package/srv/MyFileServiceLocal.mjs +177 -0
  20. package/srv/MyPdf.mjs +37 -0
  21. package/srv/MyShell.mjs +205 -0
  22. package/srv/MySqlSrv.mjs +43 -0
  23. package/srv/Network.mjs +111 -0
  24. package/srv/OpenCVSrv.mjs +27 -0
  25. package/srv/PageSrv.mjs +234 -0
  26. package/srv/PayUSrv.mjs +186 -0
  27. package/srv/PayUSrvConstants.mjs +46 -0
  28. package/srv/PostgresSrv.mjs +109 -0
  29. package/srv/SecretsSrv.mjs +126 -0
  30. package/srv/SocketIOCall.mjs +494 -0
  31. package/srv/TupleSrv.mjs +141 -0
  32. package/srv/UtilesSrv.mjs +8 -0
  33. package/srv/callprocessors/AskIceServersProcessor.mjs +14 -0
  34. package/srv/callprocessors/AskRoomProcessor.mjs +15 -0
  35. package/srv/callprocessors/CallUserProcessor.mjs +17 -0
  36. package/srv/callprocessors/ChatSetSawProcessor.mjs +42 -0
  37. package/srv/callprocessors/CheckSrcResponseProcessor.mjs +28 -0
  38. package/srv/callprocessors/ClientChangeProcessor.mjs +19 -0
  39. package/srv/callprocessors/CloseVideoChatProcessor.mjs +16 -0
  40. package/srv/callprocessors/DestroyModelProcessor.mjs +16 -0
  41. package/srv/callprocessors/DisconnectProcessor.mjs +53 -0
  42. package/srv/callprocessors/GenericProcessor.mjs +7 -0
  43. package/srv/callprocessors/GetModelProcessor.mjs +11 -0
  44. package/srv/callprocessors/IncludeOtherPeersProcessor.mjs +12 -0
  45. package/srv/callprocessors/LoadFlowChartProcessor.mjs +103 -0
  46. package/srv/callprocessors/MakeAnswerProcessor.mjs +17 -0
  47. package/srv/callprocessors/OnIceCandidateProcessor.mjs +13 -0
  48. package/srv/callprocessors/OpenVideoChatProcessor.mjs +17 -0
  49. package/srv/callprocessors/PauseFlowChartProcessor.mjs +16 -0
  50. package/srv/callprocessors/ProcessResponseProcessor.mjs +123 -0
  51. package/srv/callprocessors/ReadSrcResponseProcessor.mjs +30 -0
  52. package/srv/callprocessors/RegisterProcessorProcessor.mjs +23 -0
  53. package/srv/callprocessors/RegisterSourceProcessor.mjs +22 -0
  54. package/srv/callprocessors/SendChatProcessor.mjs +71 -0
  55. package/srv/callprocessors/StartFlowChartProcessor.mjs +48 -0
  56. package/srv/callprocessors/StopFlowChartProcessor.mjs +16 -0
  57. package/srv/callprocessors/SubscribemeProcessor.mjs +13 -0
  58. package/srv/callprocessors/UpdateMyInformationProcessor.mjs +30 -0
  59. package/srv/common/FirebasConfig.mjs +160 -0
  60. package/srv/common/General.mjs +69 -0
  61. package/srv/common/MimeTypeMap.mjs +142 -0
  62. package/srv/common/MyStore.mjs +169 -0
  63. package/srv/common/Usuario.mjs +101 -0
  64. package/srv/common/Utilidades.mjs +43 -0
@@ -0,0 +1,408 @@
1
+ import { MyStore } from "./common/MyStore.mjs";
2
+ import { General } from "./common/General.mjs";
3
+ import axios from "axios";
4
+
5
+ const MAX_READ_SIZE = 60;
6
+
7
+ export class ImagiationSrv {
8
+ static async save(req, res, next) {
9
+ const token = res.locals.token;
10
+ const AHORA = new Date().getTime();
11
+ const image = General.readParam(req, "image");
12
+ const pageId = req.params['pageId'];
13
+ const pageType = "imagiation";
14
+
15
+ if (image instanceof Array) {
16
+ for (let i = 0; i < image.length; i++) {
17
+ const image1 = image[i];
18
+ image1.author = token.email;
19
+ image1.updated = AHORA;
20
+ image1.pg = pageId;
21
+ image1.pageType = pageType;
22
+ ImagiationSrv.serializeImage(image1);
23
+ if (image1.id) {
24
+ await MyStore.updateById("imagiationimg", image1.id, image1);
25
+ } else {
26
+ image1.created = AHORA;
27
+ await MyStore.create("imagiationimg", image1);
28
+ }
29
+ ImagiationSrv.deserializeImage(image1);
30
+ }
31
+ } else {
32
+ image.author = token.email;
33
+ image.updated = AHORA;
34
+ image.pg = pageId;
35
+ image.pageType = pageType;
36
+ ImagiationSrv.serializeImage(image);
37
+ if (image.id) {
38
+ await MyStore.updateById("imagiationimg", image.id, image);
39
+ } else {
40
+ image.created = AHORA;
41
+ await MyStore.create("imagiationimg", image);
42
+ }
43
+ ImagiationSrv.deserializeImage(image);
44
+ }
45
+
46
+ res.status(200).send({
47
+ status: "ok",
48
+ image
49
+ });
50
+ }
51
+ static serializeImage(image) {
52
+ const tags = image.tags;
53
+ const nuevo = [];
54
+ for (let i = 0; i < tags.length; i++) {
55
+ const tag = tags[i];
56
+ for (let j = 0; j < tag.length; j++) {
57
+ nuevo.push(tag[j]);
58
+ }
59
+ }
60
+ image.tags = nuevo;
61
+ }
62
+ static deserializeImage(image) {
63
+ const tags = image.tags;
64
+ const nuevo = [];
65
+ const total = Math.floor(tags.length / 5);
66
+ for (let i = 0; i < total; i++) {
67
+ nuevo.push([tags[5 * i], tags[5 * i + 1], tags[5 * i + 2], tags[5 * i + 3], tags[5 * i + 4]]);
68
+ }
69
+ image.tags = nuevo;
70
+ }
71
+ static async read(req, res, next) {
72
+ const { max, offset } = General.readMaxOffset(req, MAX_READ_SIZE);
73
+ const max_date = parseInt(General.readParam(req, "max_date", 0));
74
+ const min_date = parseInt(General.readParam(req, "min_date", 0));
75
+ let response = [];
76
+ const pageId = req.params['pageId'];
77
+ // Se debe realizar la lectura como tal
78
+ const where = [
79
+ { key: "pg", oper: "==", value: pageId },
80
+ ];
81
+ if (!isNaN(max_date) && max_date > 0) {
82
+ where.push({ key: "created", oper: "<=", value: max_date });
83
+ }
84
+ if (!isNaN(min_date) && min_date > 0) {
85
+ where.push({ key: "created", oper: ">=", value: min_date });
86
+ }
87
+ response = await MyStore.paginate("imagiationimg", [{ name: "created", dir: 'desc' }], offset, max, where);
88
+ for (let i = 0; i < response.length; i++) {
89
+ const image = response[i];
90
+ ImagiationSrv.deserializeImage(image);
91
+ }
92
+ res.status(200).send({
93
+ status: "ok",
94
+ images: response,
95
+ });
96
+ }
97
+ static async delete(req, res, next) {
98
+ const image = General.readParam(req, "image");
99
+
100
+ if (image instanceof Array) {
101
+ for (let i = 0; i < image.length; i++) {
102
+ if (image1.id) {
103
+ await MyStore.deleteById("imagiationimg", image1.id);
104
+ }
105
+ }
106
+ } else {
107
+ await MyStore.deleteById("imagiationimg", image.id);
108
+ }
109
+
110
+ res.status(200).send({
111
+ status: "ok",
112
+ image: []
113
+ });
114
+ }
115
+
116
+ static async tagsSave(req, res, next) {
117
+ const pageId = req.params['pageId'];
118
+ const tag = General.readParam(req, "tag");
119
+ await MyStore.updateOrCreateById("imagiationtag", pageId, { txt: JSON.stringify(tag) });
120
+ res.status(200).send({
121
+ status: "ok",
122
+ });
123
+ }
124
+
125
+ static async tagsRead(req, res, next) {
126
+ const pageId = req.params['pageId'];
127
+ let existente = await MyStore.readById("imagiationtag", pageId);
128
+ if (!existente) {
129
+ existente = { txt: "{}" };
130
+ await MyStore.createById("imagiationtag", pageId, existente);
131
+ }
132
+ // Se tumba el id si está
133
+ delete existente.id;
134
+
135
+ const actual = JSON.parse(existente.txt);
136
+ const keys = Object.keys(actual);
137
+ for (let i = 0; i < keys.length; i++) {
138
+ const key = keys[i];
139
+ const val = actual[key];
140
+ if (typeof val == "string") {
141
+ actual[key] = { txt: val, ref: null };
142
+ }
143
+ }
144
+ res.status(200).send({
145
+ status: "ok",
146
+ tag: actual,
147
+ });
148
+ }
149
+
150
+ static async jobsSave(req, res, next) {
151
+ const token = res.locals.token;
152
+ const AHORA = new Date().getTime();
153
+ const pageId = req.params['pageId'];
154
+ const pageType = req.params['pageType'];
155
+ const job = General.readParam(req, "job");
156
+ if (job.id) {
157
+ // Primero se lee el estado
158
+ const old = await MyStore.readById("imagiationjob", job.id);
159
+ if (old.state != 'pending') {
160
+ throw new Error("No se puede hacer la modificación");
161
+ }
162
+ job.pageType = pageType;
163
+ job.updated = AHORA;
164
+ await MyStore.updateById("imagiationjob", job.id, job);
165
+ } else {
166
+ job.pageType = pageType;
167
+ job.pg = pageId;
168
+ job.created = AHORA;
169
+ job.updated = AHORA;
170
+ job.state = 'pending';
171
+ job.progress = 0;
172
+ job.owner = token.email;
173
+ if (!job.workerType) {
174
+ job.workerType = 'predefined';
175
+ }
176
+ job.started = 0;
177
+ await MyStore.create("imagiationjob", job);
178
+ }
179
+
180
+ res.status(200).send({
181
+ status: "ok",
182
+ jobs: [job],
183
+ });
184
+ }
185
+
186
+ static async jobsRead(req, res, next) {
187
+ const { max, offset } = General.readMaxOffset(req, MAX_READ_SIZE);
188
+ let response = [];
189
+ const pageId = req.params['pageId'];
190
+ // Se debe realizar la lectura como tal
191
+ const where = [
192
+ { key: "pg", oper: "==", value: pageId },
193
+ ];
194
+ response = await MyStore.paginate("imagiationjob", [{ name: "created", dir: 'desc' }], offset, max, where);
195
+ res.status(200).send({
196
+ status: "ok",
197
+ jobs: response,
198
+ });
199
+ }
200
+
201
+ static async jobRead(req, res, next) {
202
+ const jobId = General.readParam(req, "jobId");
203
+ const response = await MyStore.readById("imagiationjob", jobId);
204
+ const jobs = [];
205
+ if (response) {
206
+ jobs.push(response);
207
+ }
208
+ res.status(200).send({
209
+ status: "ok",
210
+ jobs,
211
+ });
212
+ }
213
+
214
+ static serializeModel(model) {
215
+ const configs = model.configs;
216
+ if (configs) {
217
+ for (let i = 0; i < configs.length; i++) {
218
+ configs[i] = JSON.stringify(configs[i]);
219
+ }
220
+ } else {
221
+ model.configs = [];
222
+ }
223
+ return model;
224
+ }
225
+
226
+ static deserializeModel(model) {
227
+ const configs = model.configs;
228
+ if (configs) {
229
+ for (let i = 0; i < configs.length; i++) {
230
+ configs[i] = JSON.parse(configs[i]);
231
+ }
232
+ } else {
233
+ model.configs = [];
234
+ }
235
+ return model;
236
+ }
237
+
238
+ static async confSave(req, res, next) {
239
+ const token = res.locals.token;
240
+ const AHORA = new Date().getTime();
241
+ const pageId = req.params['pageId'];
242
+ const pageType = req.params['pageType'];
243
+ let conf = General.readParam(req, "conf");
244
+ conf = ImagiationSrv.serializeModel(conf);
245
+ if (conf.id) {
246
+ conf.pageType = pageType;
247
+ conf.updated = AHORA;
248
+ await MyStore.updateById("imagiationconf", conf.id, conf);
249
+ } else {
250
+ // No existe
251
+ conf.pageType = pageType;
252
+ conf.pg = pageId;
253
+ conf.created = AHORA;
254
+ conf.updated = AHORA;
255
+ conf.owner = token.email;
256
+ await MyStore.create("imagiationconf", conf);
257
+ }
258
+
259
+ res.status(200).send({
260
+ status: "ok",
261
+ confs: [ImagiationSrv.deserializeModel(conf)],
262
+ });
263
+ }
264
+
265
+ static async confsRead(req, res, next) {
266
+ const { max, offset } = General.readMaxOffset(req, MAX_READ_SIZE);
267
+ let response = [];
268
+ const pageId = req.params['pageId'];
269
+ // Se debe realizar la lectura como tal
270
+ const where = [
271
+ { key: "pg", oper: "==", value: pageId },
272
+ ];
273
+ response = await MyStore.paginate("imagiationconf", [{ name: "created", dir: 'desc' }], offset, max, where);
274
+ response = response.map((elem) => {
275
+ return ImagiationSrv.deserializeModel(elem);
276
+ });
277
+ res.status(200).send({
278
+ status: "ok",
279
+ confs: response,
280
+ });
281
+ }
282
+
283
+ static async confRead(req, res, next) {
284
+ const confId = General.readParam(req, "confId");
285
+ const response = await MyStore.readById("imagiationconf", confId);
286
+ const confs = [];
287
+ if (response) {
288
+ confs.push(ImagiationSrv.deserializeModel(response));
289
+ }
290
+ res.status(200).send({
291
+ status: "ok",
292
+ confs,
293
+ });
294
+ }
295
+
296
+ static async confDelete(req, res, next) {
297
+ const confId = General.readParam(req, "confId");
298
+ const response = await MyStore.deleteById("imagiationconf", confId);
299
+ res.status(200).send({
300
+ status: "ok",
301
+ });
302
+ }
303
+
304
+ static serializeStatistic(stat) {
305
+ const respuesta = {
306
+ founds: []
307
+ };
308
+ for (let i = 0; i < stat.length; i++) {
309
+ const valor = stat[i];
310
+ const name = `count_${valor.name}`;
311
+ if (!(name in respuesta)) {
312
+ respuesta[name] = 1;
313
+ respuesta.founds.push(valor.name);
314
+ } else {
315
+ respuesta[name] += 1;
316
+ }
317
+ }
318
+ return respuesta;
319
+ }
320
+
321
+ static deserializeStatistic(stat) {
322
+ const founds = stat.founds;
323
+ const mapa = {};
324
+ for (let i = 0; i < founds.length; i++) {
325
+ const name = founds[i];
326
+ if (!(name in mapa)) {
327
+ mapa[name] = { count: 0 };
328
+ }
329
+ const conteoActual = stat[`count_${name}`];
330
+ mapa[name].count += conteoActual;
331
+ }
332
+ stat.founds = mapa;
333
+ }
334
+
335
+ static async storeStatistic(req, res, next) {
336
+ const AHORA = new Date().getTime();
337
+ const confId = General.readParam(req, "confId");
338
+ const pageId = req.params['pageId'];
339
+ const data = General.readParam(req, "data");
340
+
341
+ // De la configuración saco el nombre
342
+ const conf = await MyStore.readById("imagiationconf", confId);
343
+ if (!conf) {
344
+ throw Error("No conf");
345
+ }
346
+ const stat = ImagiationSrv.serializeStatistic(data.list);
347
+ const statExtra = {
348
+ t: AHORA,
349
+ pg: pageId,
350
+ confId,
351
+ confName: conf.name,
352
+ lat: data.lat,
353
+ lon: data.lon,
354
+ geohashs: data.geohashs,
355
+ geohash7: data.geohash7,
356
+ geohash8: data.geohash8,
357
+ big: data.uri,
358
+ thumb: data.uri.replace(/^(.*)\.([^\.]+)/, "$1_xs.$2")
359
+ };
360
+ // Eventualmente la lat y lon de la configuración si no vienen
361
+ if (!(statExtra.lat) && !(statExtra.lat)) {
362
+ statExtra.lat = conf.lat;
363
+ statExtra.lon = conf.lon;
364
+ }
365
+ Object.assign(stat, statExtra);
366
+ await MyStore.create("imagiationstat", stat);
367
+ res.status(200).send({
368
+ status: "ok",
369
+ });
370
+ }
371
+
372
+ static async pageStatistics(req, res, next) {
373
+ const { max, offset } = General.readMaxOffset(req, MAX_READ_SIZE);
374
+ const max_date = parseInt(General.readParam(req, "max_date", 0));
375
+ const min_date = parseInt(General.readParam(req, "min_date", 0));
376
+ let response = [];
377
+ const pageId = req.params['pageId'];
378
+ // Se debe realizar la lectura como tal
379
+ const where = [
380
+ { key: "pg", oper: "==", value: pageId },
381
+ ];
382
+ if (!isNaN(max_date) && max_date > 0) {
383
+ where.push({ key: "t", oper: "<=", value: max_date });
384
+ }
385
+ if (!isNaN(min_date) && min_date > 0) {
386
+ where.push({ key: "t", oper: ">=", value: min_date });
387
+ }
388
+ response = await MyStore.paginate("imagiationstat", [{ name: "t", dir: 'desc' }], offset, max, where);
389
+ /*
390
+ for (let i = 0; i < response.length; i++) {
391
+ const image = response[i];
392
+ ImagiationSrv.deserializeStatistic(image);
393
+ }
394
+ */
395
+ res.status(200).send({
396
+ status: "ok",
397
+ images: response,
398
+ });
399
+ }
400
+
401
+ static async statDelete(req, res, next) {
402
+ const statId = General.readParam(req, "statId");
403
+ const response = await MyStore.deleteById("imagiationstat", statId);
404
+ res.status(200).send({
405
+ status: "ok",
406
+ });
407
+ }
408
+ }
@@ -0,0 +1,104 @@
1
+
2
+ import { MyDates } from "@ejfdelgado/ejflab-common/src/MyDates.js";
3
+ import { ModuloDatoSeguro } from "@ejfdelgado/ejflab-common/src/ModuloDatoSeguro.js";
4
+ import { General } from "./common/General.mjs";
5
+ import { MyStore } from "./common/MyStore.mjs";
6
+ import { ModuloDatoSeguroBack } from "@ejfdelgado/ejflab-common/src/ModuloDatoSeguroBack.mjs";
7
+
8
+ const KEYS_TYPE = "page-key";
9
+ const DEFAULT_KEY_SIZE = 10;
10
+
11
+ export class KeysSrv {
12
+ static async getOrGeneratePageKeys(pageId) {
13
+ // Cada página debe tener algo como esto:
14
+ const {
15
+ actual,
16
+ siguiente,
17
+ anterior,
18
+ } = MyDates.getDates();
19
+
20
+ // Busco el registro por pageId
21
+ const response = await MyStore.readById(KEYS_TYPE, pageId);
22
+ const payload = {};
23
+ if (!response) {
24
+ // Toca crearlo desde ceros todo
25
+ payload[actual] = ModuloDatoSeguro.generateKey(DEFAULT_KEY_SIZE);
26
+ payload[siguiente] = ModuloDatoSeguro.generateKey(DEFAULT_KEY_SIZE);
27
+ payload[anterior] = ModuloDatoSeguro.generateKey(DEFAULT_KEY_SIZE);
28
+ await MyStore.createById(KEYS_TYPE, pageId, payload);
29
+ } else {
30
+ payload[actual] = response[actual];
31
+ payload[siguiente] = response[siguiente];
32
+ payload[anterior] = response[anterior];
33
+ let modificado = false;
34
+ if (!(actual in payload) || !payload[actual]) {
35
+ payload[actual] = ModuloDatoSeguro.generateKey(DEFAULT_KEY_SIZE);
36
+ modificado = true;
37
+ }
38
+ if (!(siguiente in payload) || !payload[siguiente]) {
39
+ payload[siguiente] = ModuloDatoSeguro.generateKey(DEFAULT_KEY_SIZE);
40
+ modificado = true;
41
+ }
42
+ if (!(anterior in payload) || !payload[anterior]) {
43
+ payload[anterior] = ModuloDatoSeguro.generateKey(DEFAULT_KEY_SIZE);
44
+ modificado = true;
45
+ }
46
+ if (modificado) {
47
+ await MyStore.updateById(KEYS_TYPE, pageId, payload);
48
+ }
49
+ }
50
+ return payload;
51
+ }
52
+
53
+ static async cifrar(objeto, pageId) {
54
+ const llavero = await KeysSrv.getOrGeneratePageKeys(pageId);
55
+ const actual = MyDates.getDayAsContinuosNumber(new Date());
56
+ const pass = llavero[actual];
57
+ const resultado = ModuloDatoSeguroBack.cifrarSimple(objeto, pass);
58
+ return resultado;
59
+ }
60
+
61
+ static async decifrar(texto, pageId) {
62
+ const llavero = await KeysSrv.getOrGeneratePageKeys(pageId);
63
+ const {
64
+ actual,
65
+ siguiente,
66
+ anterior,
67
+ } = MyDates.getDates();
68
+ let resultado = undefined;
69
+ const llaves = [];
70
+ llaves.push(llavero[actual]);
71
+ llaves.push(llavero[anterior]);
72
+ llaves.push(llavero[siguiente]);
73
+ for (let i = 0; i < llaves.length; i++) {
74
+ const llave = llaves[i];
75
+ try {
76
+ resultado = ModuloDatoSeguroBack.decifrarSimple(texto, llave);
77
+ } catch (e) {
78
+
79
+ }
80
+ }
81
+ return resultado;
82
+ }
83
+
84
+ static async getPageKeys(req, res, next) {
85
+ const pageId = req.params['pageId'];
86
+ const llavero = await KeysSrv.getOrGeneratePageKeys(pageId);
87
+ res.status(200).send(llavero);
88
+ }
89
+
90
+ static async cifrarWeb(req, res, next) {
91
+ const key = General.readParam(req, "key");
92
+ const payload = General.readParam(req, "payload");
93
+ const resultado = ModuloDatoSeguroBack.cifrarSimple(payload, key);
94
+ console.log(resultado);
95
+ res.status(200).send(resultado);
96
+ }
97
+
98
+ static async decifrarWeb(req, res, next) {
99
+ const key = General.readParam(req, "key");
100
+ const payload = General.readParam(req, "payload");
101
+ const resultado = ModuloDatoSeguroBack.decifrarSimple(payload, key);
102
+ res.status(200).send(resultado);
103
+ }
104
+ }
@@ -0,0 +1,140 @@
1
+ import url from "url";
2
+ import fs from "fs";
3
+ import path from "path";
4
+ import { guessMimeType } from "./common/MimeTypeMap.mjs";
5
+ import { MainReplacer } from "./MainReplacer.mjs";
6
+ import { MyRoutes } from "@ejfdelgado/ejflab-common/src/MyRoutes.js";
7
+ import { PageSrv } from "./PageSrv.mjs";
8
+ import { ModuloDatoSeguro } from "@ejfdelgado/ejflab-common/src/ModuloDatoSeguro.js";
9
+ import { ModuloDatoSeguroBack } from "@ejfdelgado/ejflab-common/src/ModuloDatoSeguroBack.mjs";
10
+ import { MyConstants } from "@ejfdelgado/ejflab-common/src/MyConstants.js";
11
+
12
+ export class MainHandler {
13
+ static LOCAL_FOLDER = path.resolve() + "/dist/bundle";
14
+ static async handle(req, res, next) {
15
+ const originalUrl = req.getUrl();
16
+ const theUrl = url.parse(originalUrl);
17
+ if (theUrl.pathname == "/socket.io/") {
18
+ return next();
19
+ }
20
+ const rutas = MainHandler.decodeUrl(theUrl);
21
+ const encoding = req.query.encoding;
22
+ const rta = await MainHandler.resolveLocalFile(rutas, encoding);
23
+ if (
24
+ rta != null &&
25
+ typeof rta.data == "string" &&
26
+ rta.metadata.filename == "index.html"
27
+ ) {
28
+ const partes = MyRoutes.splitPageData(theUrl.path);
29
+ if (MyConstants.NO_AUTO_PAGE_NAVITATION.indexOf(partes.pageType) >= 0) {
30
+ partes.pageId = null;
31
+ }
32
+ const replaces = await PageSrv.loadCurrentPage(partes.pageType, partes.pageId);
33
+ const firebaseJson = await MainHandler.resolveLocalFileSingle(MyConstants.FIREBASE_CONFIG_FILE, "utf8", path.resolve());
34
+ // Acá se debe inyectar el password y el json se lee de local y se cifra
35
+ replaces.time = "" + new Date().getTime();
36
+ replaces.pass = ModuloDatoSeguro.generateKey();
37
+ replaces.firebase = ModuloDatoSeguroBack.cifrarSimple(JSON.parse(firebaseJson), replaces.pass);
38
+ MainReplacer.replace(rta, replaces, theUrl);
39
+ }
40
+ MainHandler.makeResponse(rta, req, res);
41
+ }
42
+
43
+ static decodeUrl(localPath) {
44
+ const respuestas = [];
45
+ respuestas.push(localPath.pathname);
46
+ respuestas.push("/index.html");
47
+ const ans = {
48
+ files: respuestas,
49
+ pageType: null,
50
+ pageId: null,
51
+ };
52
+ return ans;
53
+ }
54
+
55
+ static makeResponse(rta, req, res) {
56
+ const downloadFlag = (req.query && req.query.download);
57
+ if (rta != null) {
58
+ if (rta.redirect) {
59
+ res.redirect(rta.redirect);
60
+ } else {
61
+ res.writeHead(200, {
62
+ "Content-Type": rta.metadata.contentType,
63
+ "Content-disposition":
64
+ downloadFlag ? "attachment;filename=" + rta.metadata.filename : "inline",
65
+ });
66
+ res.end(rta.data);
67
+ }
68
+ } else {
69
+ res.status(202).end();
70
+ }
71
+ }
72
+
73
+ static async resolveLocalFile(localPath, encoding = "utf8") {
74
+ for (let i = 0; i < localPath.files.length; i++) {
75
+ const filename = localPath.files[i];
76
+ const contentType = guessMimeType(filename);
77
+ let contenido;
78
+ if (["text/html"].indexOf(contentType) >= 0) {
79
+ contenido = await MainHandler.resolveLocalFileSingle(
80
+ filename,
81
+ encoding
82
+ );
83
+ } else {
84
+ contenido = await MainHandler.resolveLocalFileSingle(filename);
85
+ }
86
+ if (contenido != null) {
87
+ return {
88
+ data: contenido,
89
+ metadata: {
90
+ contentType: contentType,
91
+ filename: /[^/]*$/.exec(filename)[0],
92
+ fullPath: filename,
93
+ },
94
+ };
95
+ }
96
+ }
97
+ return null;
98
+ }
99
+
100
+ static async resolveLocalFileSingle(filename, encoding, rootFolder = MainHandler.LOCAL_FOLDER) {
101
+ return new Promise((resolve, reject) => {
102
+ const somePath = path.join(rootFolder, filename);
103
+
104
+ fs.access(somePath, (err) => {
105
+ if (err) {
106
+ resolve(null);
107
+ } else {
108
+ if (!fs.lstatSync(somePath).isFile()) {
109
+ resolve(null);
110
+ return;
111
+ }
112
+ if (typeof encoding == "string") {
113
+ fs.readFile(somePath, encoding, function (err, data) {
114
+ if (err) {
115
+ reject(err);
116
+ return;
117
+ }
118
+ resolve(data);
119
+ });
120
+ } else {
121
+ fs.readFile(somePath, function (err, data) {
122
+ if (err) {
123
+ reject(err);
124
+ return;
125
+ }
126
+ resolve(data);
127
+ });
128
+ }
129
+ }
130
+ });
131
+ });
132
+ }
133
+
134
+ static addGetUrl(req, res, next) {
135
+ req.getUrl = function () {
136
+ return req.protocol + "://" + req.get("host") + req.originalUrl;
137
+ };
138
+ return next();
139
+ }
140
+ }