@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,289 @@
1
+ import { General } from "./common/General.mjs";
2
+ import { MyStore } from "./common/MyStore.mjs";
3
+ import { InstancesClient, ZoneOperationsClient } from '@google-cloud/compute'
4
+ import axios from "axios";
5
+ import MyDatesBack from "@ejfdelgado/ejflab-common/src/MyDatesBack.mjs";
6
+
7
+ const projectId = "ejfexperiments";
8
+ export const instancesMap = {
9
+ "imagiation-worker-1": {
10
+ name: "Entrenamiento de Detección de Imágenes - 4CPU virt (2 cores) 16G Mem",
11
+ zone: "us-central1-c",
12
+ workerType: 'predefined',
13
+ url: "http://34.16.94.71/",
14
+ state: null,// STOPPING -> TERMINATED -> PROVISIONING -> STAGING -> RUNNING
15
+ stateDetail: null,
16
+ log: [],
17
+ price: 0.134012
18
+ },
19
+ "imagiation-worker-2": {
20
+ name: "Entrenamiento de Detección de Imágenes - 8CPU virt (4 cores) 32G Mem",
21
+ zone: "us-central1-c",
22
+ workerType: 'paid1',
23
+ url: "http://104.198.166.155/",
24
+ state: null,// STOPPING -> TERMINATED -> PROVISIONING -> STAGING -> RUNNING
25
+ stateDetail: null,
26
+ log: [],
27
+ price: 0.28
28
+ },
29
+ "local": {
30
+ name: "Entrenamiento de Detección de Imágenes - Local",
31
+ zone: "local",
32
+ workerType: 'local',
33
+ url: "http://localhost:8080/",
34
+ state: "RUNNING",
35
+ stateDetail: null,
36
+ log: [],
37
+ price: 0
38
+ },
39
+ };
40
+
41
+ export class ComputeEngineSrv {
42
+ static async startJobExecution(instanceUrl, job) {
43
+ const url = `${instanceUrl}train_mock?job=${job.id}`;
44
+ const responseRequest = await new Promise((resolve, reject) => {
45
+ const options = {};
46
+ axios.get(url, options)
47
+ .then(res => { resolve(res) })
48
+ .catch(error => { reject(error) });
49
+ });
50
+ const response = responseRequest.data;
51
+ return response;
52
+ }
53
+ static async executeJobQueuee(instanceName, instancesClient = null) {
54
+ // Tomar el job más viejito en pending asociado a la instancia workerType que pasen por parámetro
55
+ // order by created asc, jobType == imagiation-worker-1 [0]
56
+ const ref = instancesMap[instanceName];
57
+ const localres = {
58
+ message: "",
59
+ };
60
+ if (ref) {
61
+ const estadoActualPromise = ComputeEngineSrv.getCurrentInstanceStatus(instanceName, instancesClient);
62
+ estadoActualPromise.catch(err => { });
63
+ const where = [
64
+ { key: "workerType", oper: "==", value: ref.workerType },
65
+ { key: "state", oper: "==", value: "pending" },
66
+ ];
67
+ const offset = 0;
68
+ const max = 1;
69
+ const jobs = await MyStore.paginate("imagiationjob", [{ name: "created", dir: 'asc' }], offset, max, where);
70
+ const tamanio = jobs.length;
71
+
72
+ // Leer el estado del job
73
+ try {
74
+ const estadoActual = await estadoActualPromise;
75
+ localres.health = estadoActual;
76
+ localres.message = "";
77
+ if (tamanio == 0) {
78
+ // Si no hay nada, leer el estado del job, si el job está sin tareas, terminar.
79
+ if (estadoActual.state == "RUNNING") {
80
+ if (estadoActual.stateDetail.state == "free" && estadoActual.stateDetail.currentJobs == 0) {
81
+ if (instanceName != "local") {
82
+ localres.message = `${instanceName} sin tareas pendientes por lanzar y sin ejecuciones en curso, DETENER!`;
83
+ }
84
+ await ComputeEngineSrv.stopInstanceRaw(instanceName, instancesClient);
85
+ } else {
86
+ //localres.message = `${instanceName} en ${estadoActual.state} y current running tasks ${estadoActual.stateDetail.currentJobs}`;
87
+ }
88
+ }
89
+ } else {
90
+ // Leer la instancia asociada a ese job
91
+ const job = jobs[0];
92
+ if (estadoActual.state == "RUNNING") {
93
+ const tieneCapacidad = (estadoActual.stateDetail.currentJobs < estadoActual.stateDetail.maxJobs);
94
+ if (tieneCapacidad) {
95
+ localres.message = `${instanceName} lanzando job ${job.id}`;
96
+ // Si es running y si tiene capacidad -> ejecutar job.id
97
+ await ComputeEngineSrv.startJobExecution(estadoActual.url, job);
98
+ } else {
99
+ // Si es running y no tiene capacidad -> ignorar
100
+ localres.message = `${instanceName} ejecutando ${estadoActual.stateDetail.currentJobs}/${estadoActual.stateDetail.maxJobs}`;
101
+ }
102
+ } else {
103
+ // Si es TERMINATED solo intentar lanzar y ya.
104
+ if (estadoActual.state == "TERMINATED") {
105
+ localres.message = `${instanceName} encendiendo!`;
106
+ await ComputeEngineSrv.startInstanceRaw(instanceName, instancesClient);
107
+ } else {
108
+ localres.message = `${instanceName} en ${estadoActual.state}`;
109
+ }
110
+ }
111
+ }
112
+ } catch (err) {
113
+ localres.message = err.message;
114
+ }
115
+ } else {
116
+ localres.message = `La cola de ejecución ${instanceName} no existe`;
117
+ }
118
+
119
+ // Se complementa con la fecha
120
+ if (localres.message.length > 0) {
121
+ localres.message = "[" + MyDatesBack.formatDateCompleto(new Date()) + "] " + localres.message;
122
+ ref.log.unshift(localres.message);
123
+ // Limit
124
+ const MAX_LINES = 50;
125
+ if (ref.log.length > MAX_LINES) {
126
+ ref.log.splice(MAX_LINES, 1);
127
+ }
128
+ }
129
+ return localres;
130
+ }
131
+ static async getCurrentInstanceStatus(instanceName, instancesClient = null) {
132
+ const ref = instancesMap[instanceName];
133
+ if (ref) {
134
+ if (instanceName != "local") {
135
+ if (!instancesClient) {
136
+ instancesClient = new InstancesClient();
137
+ }
138
+ const zone = ref.zone;
139
+ const [instance] = await instancesClient.get({
140
+ project: projectId,
141
+ zone,
142
+ instance: instanceName,
143
+ });
144
+ const status = instance.status;
145
+ ref.state = status;
146
+ }
147
+ let responseRequest = {};
148
+ if (ref.state == "RUNNING") {
149
+ // Ask server state
150
+ const url = `${ref.url}ping`;
151
+ responseRequest = await new Promise((resolve, reject) => {
152
+ const options = {};
153
+ axios.get(url, options)
154
+ .then(res => { resolve(res) })
155
+ .catch(error => { reject(error) });
156
+ });
157
+ const response = responseRequest.data;
158
+ ref.stateDetail = response;
159
+ } else {
160
+ ref.stateDetail = null;
161
+ }
162
+ return ref;
163
+ }
164
+ return null;
165
+ }
166
+ static async stopInstanceRaw(instanceName, instancesClient = null) {
167
+ if (instanceName == "local") {
168
+ return;
169
+ }
170
+ const ref = instancesMap[instanceName];
171
+ if (ref) {
172
+ if (!instancesClient) {
173
+ instancesClient = new InstancesClient();
174
+ }
175
+ const zone = ref.zone;
176
+ const [instance] = await instancesClient.get({
177
+ project: projectId,
178
+ zone,
179
+ instance: instanceName,
180
+ });
181
+ const status = instance.status;
182
+ if (status !== "RUNNING") {
183
+ throw new Error(`No se puede detener una instancia en estado diferente a RUNNING, actualmente es ${status}`);
184
+ }
185
+ const [response] = await instancesClient.stop({
186
+ project: projectId,
187
+ zone,
188
+ instance: instanceName,
189
+ });
190
+ let operation = response.latestResponse;
191
+ const operationsClient = new ZoneOperationsClient();
192
+ //console.log(`operation.status = ${operation.status}`);
193
+ // Wait for the operation to complete.
194
+ while (operation.status !== 'DONE') {
195
+ [operation] = await operationsClient.wait({
196
+ operation: operation.name,
197
+ project: projectId,
198
+ zone: operation.zone.split('/').pop(),
199
+ });
200
+ //console.log(`operation.status = ${operation.status}`);
201
+ }
202
+ }
203
+ }
204
+ static async startInstanceRaw(instanceName, instancesClient = null) {
205
+ if (instanceName == "local") {
206
+ return;
207
+ }
208
+ const ref = instancesMap[instanceName];
209
+ if (ref) {
210
+ if (!instancesClient) {
211
+ instancesClient = new InstancesClient();
212
+ }
213
+ const zone = ref.zone;
214
+ const [instance] = await instancesClient.get({
215
+ project: projectId,
216
+ zone,
217
+ instance: instanceName,
218
+ });
219
+ const status = instance.status;
220
+ if (status !== "TERMINATED") {
221
+ throw new Error(`No se puede iniciar una instancia en estado diferente a TERMINATED, actualmente es ${status}`);
222
+ }
223
+ const [response] = await instancesClient.start({
224
+ project: projectId,
225
+ zone,
226
+ instance: instanceName,
227
+ });
228
+ let operation = response.latestResponse;
229
+ const operationsClient = new ZoneOperationsClient();
230
+ //console.log(`operation.status = ${operation.status}`);
231
+ // Wait for the operation to complete.
232
+ while (operation.status !== 'DONE') {
233
+ [operation] = await operationsClient.wait({
234
+ operation: operation.name,
235
+ project: projectId,
236
+ zone: operation.zone.split('/').pop(),
237
+ });
238
+ //console.log(`operation.status = ${operation.status}`);
239
+ }
240
+ }
241
+ }
242
+ static async startInstance(req, res, next) {
243
+ const image = General.readParam(req, "name");
244
+ const instancesClient = new InstancesClient();
245
+ await ComputeEngineSrv.startInstanceRaw(image, instancesClient);
246
+ const response = {
247
+ status: "ok",
248
+ image
249
+ };
250
+ res.status(200).send(response);
251
+ }
252
+ static async stopInstance(req, res, next) {
253
+ const image = General.readParam(req, "name");
254
+ const instancesClient = new InstancesClient();
255
+ await ComputeEngineSrv.stopInstanceRaw(image, instancesClient);
256
+ const response = {
257
+ status: "ok",
258
+ image
259
+ };
260
+ res.status(200).send(response);
261
+ }
262
+ static async getStatus(req, res, next) {
263
+ const image = General.readParam(req, "name");
264
+ const instancesClient = new InstancesClient();
265
+ const status = await ComputeEngineSrv.getCurrentInstanceStatus(image, instancesClient);
266
+ const response = {
267
+ status: "ok",
268
+ status
269
+ };
270
+ res.status(200).send(response);
271
+ }
272
+ static async iterate(req, res, next) {
273
+ const image = General.readParam(req, "name");
274
+ const instancesClient = new InstancesClient();
275
+ const status = await ComputeEngineSrv.executeJobQueuee(image, instancesClient);
276
+ const response = {
277
+ status: "ok",
278
+ status
279
+ };
280
+ res.status(200).send(response);
281
+ }
282
+ static async readAllInstances(req, res, next) {
283
+ const response = {
284
+ status: "ok",
285
+ map: instancesMap,
286
+ };
287
+ res.status(200).send(response);
288
+ }
289
+ }
@@ -0,0 +1,54 @@
1
+ import sgMail from "@sendgrid/mail";
2
+ import { MyConstants } from "@ejfdelgado/ejflab-common/src/MyConstants.js";
3
+ import { MainHandler } from "./MainHandler.mjs";
4
+ import { MyTemplate } from "@ejfdelgado/ejflab-common/src/MyTemplate.js";
5
+ import { General } from "./common/General.mjs";
6
+ import MyDatesBack from "@ejfdelgado/ejflab-common/src/MyDatesBack.mjs";
7
+
8
+ export class EmailHandler {
9
+ static async send(req, res) {
10
+ const useDebug = false;
11
+ sgMail.setApiKey(
12
+ process.env.SEND_GRID_VARIABLE
13
+ );
14
+ const body = General.readParam(req, "body");
15
+ const contenido = await MainHandler.resolveLocalFile({
16
+ files: [body.template],
17
+ });
18
+ const renderer = new MyTemplate();
19
+ renderer.registerFunction("formatDate", (millis) => {
20
+ try {
21
+ return MyDatesBack.formatDateCompleto(new Date(millis));
22
+ } catch (err) {
23
+ return `${millis}`;
24
+ }
25
+ });
26
+ renderer.registerFunction("porcentaje1", (por) => {
27
+ return (100 * por).toFixed(1) + " %";
28
+ });
29
+ if (useDebug) {
30
+ console.log(JSON.stringify(body.params, null, 4));
31
+ }
32
+ const contenidoFinal = renderer.render(
33
+ contenido.data,//template
34
+ body.params//params
35
+ );
36
+ const msg = {
37
+ to: body.to,
38
+ from: MyConstants.EMAIL_SENDER,
39
+ subject: body.subject,
40
+ html: contenidoFinal,
41
+ };
42
+
43
+ //console.log(JSON.stringify(body.params, null, 4));
44
+ //console.log(JSON.stringify(contenidoFinal, null, 4));
45
+
46
+ if (useDebug) {
47
+ res.status(200).set({ 'content-type': 'text/html; charset=utf-8' }).send(contenidoFinal).end();
48
+ } else {
49
+ let answer = {};
50
+ answer = await sgMail.send(msg);
51
+ res.status(200).json(answer).end();
52
+ }
53
+ }
54
+ }
@@ -0,0 +1,101 @@
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 Image2MeshSrv {
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 = "img2mesh";
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
+ Image2MeshSrv.serializeImage(image1);
23
+ if (image1.id) {
24
+ await MyStore.updateById("imgtomeshimg", image1.id, image1);
25
+ } else {
26
+ image1.created = AHORA;
27
+ await MyStore.create("imgtomeshimg", image1);
28
+ }
29
+ Image2MeshSrv.deserializeImage(image1);
30
+ }
31
+ } else {
32
+ image.author = token.email;
33
+ image.updated = AHORA;
34
+ image.pg = pageId;
35
+ image.pageType = pageType;
36
+ Image2MeshSrv.serializeImage(image);
37
+ if (image.id) {
38
+ await MyStore.updateById("imgtomeshimg", image.id, image);
39
+ } else {
40
+ image.created = AHORA;
41
+ await MyStore.create("imgtomeshimg", image);
42
+ }
43
+ Image2MeshSrv.deserializeImage(image);
44
+ }
45
+
46
+ res.status(200).send({
47
+ status: "ok",
48
+ image
49
+ });
50
+ }
51
+ static serializeImage(image) {
52
+ //
53
+ }
54
+ static deserializeImage(image) {
55
+ //
56
+ }
57
+ static async read(req, res, next) {
58
+ const { max, offset } = General.readMaxOffset(req, MAX_READ_SIZE);
59
+ const max_date = parseInt(General.readParam(req, "max_date", 0));
60
+ const min_date = parseInt(General.readParam(req, "min_date", 0));
61
+ let response = [];
62
+ const pageId = req.params['pageId'];
63
+ // Se debe realizar la lectura como tal
64
+ const where = [
65
+ { key: "pg", oper: "==", value: pageId },
66
+ ];
67
+ if (!isNaN(max_date) && max_date > 0) {
68
+ where.push({ key: "created", oper: "<=", value: max_date });
69
+ }
70
+ if (!isNaN(min_date) && min_date > 0) {
71
+ where.push({ key: "created", oper: ">=", value: min_date });
72
+ }
73
+ response = await MyStore.paginate("imgtomeshimg", [{ name: "created", dir: 'desc' }], offset, max, where);
74
+ for (let i = 0; i < response.length; i++) {
75
+ const image = response[i];
76
+ Image2MeshSrv.deserializeImage(image);
77
+ }
78
+ res.status(200).send({
79
+ status: "ok",
80
+ images: response,
81
+ });
82
+ }
83
+ static async delete(req, res, next) {
84
+ const image = General.readParam(req, "image");
85
+
86
+ if (image instanceof Array) {
87
+ for (let i = 0; i < image.length; i++) {
88
+ if (image1.id) {
89
+ await MyStore.deleteById("imgtomeshimg", image1.id);
90
+ }
91
+ }
92
+ } else {
93
+ await MyStore.deleteById("imgtomeshimg", image.id);
94
+ }
95
+
96
+ res.status(200).send({
97
+ status: "ok",
98
+ image: []
99
+ });
100
+ }
101
+ }