@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,169 @@
1
+
2
+ import { Firestore } from '@google-cloud/firestore'
3
+
4
+ const firestore = new Firestore();
5
+ firestore.settings({
6
+ ignoreUndefinedProperties: true
7
+ });
8
+
9
+ export class MyStore {
10
+ // https://www.npmjs.com/package/@google-cloud/firestore
11
+ static async runTransaction(theFunction) {
12
+ /**
13
+ * Con las bibliotecas cliente de Cloud Firestore, puede agrupar
14
+ * varias operaciones en una sola transacción. Las transacciones
15
+ * son útiles cuando desea actualizar el valor de un campo según
16
+ * su valor actual o el valor de algún otro campo. Una transacción
17
+ * consta de cualquier cantidad de operaciones get() seguidas de
18
+ * cualquier cantidad de operaciones de escritura, como set() ,
19
+ * update() o delete() . En el caso de una edición simultánea,
20
+ * Cloud Firestore vuelve a ejecutar toda la transacción.
21
+ * Por ejemplo, si una transacción lee documentos y otro cliente
22
+ * modifica cualquiera de esos documentos, Cloud Firestore vuelve
23
+ * a intentar la transacción. Esta función garantiza que la
24
+ * transacción se ejecute con datos actualizados y coherentes.
25
+ */
26
+ return await firestore.runTransaction(theFunction);
27
+ }
28
+
29
+ static getBatch() {
30
+ /**
31
+ * Si no necesita leer ningún documento en su conjunto de operaciones,
32
+ * puede ejecutar varias operaciones de escritura como un solo lote que
33
+ * contiene cualquier combinación de operaciones set() , update() o delete() .
34
+ * Un lote de escrituras se completa de forma atómica y puede escribir en
35
+ * varios documentos.
36
+ */
37
+ return firestore.batch();
38
+ }
39
+
40
+ static async readByIds(collection, ids, firestoreInstance = null) {
41
+ const lista = [];
42
+ const theJson = {};
43
+ if (ids.length == 0) {
44
+ return theJson;
45
+ }
46
+ for (let i = 0; i < ids.length; i++) {
47
+ const id = ids[i];
48
+ lista.push(firestore.doc(`${process.env.ENV ? process.env.ENV : "pro"}-${collection}/${id}`));
49
+ }
50
+ let response;
51
+ if (firestoreInstance == null) {
52
+ response = await firestore.getAll(...lista);
53
+ } else {
54
+ response = await firestoreInstance.getAll(...lista);
55
+ }
56
+ for (let j = 0; j < response.length; j++) {
57
+ const doc = response[j];
58
+ const data = doc.data();
59
+ if (data) {
60
+ data.id = doc.id;
61
+ theJson[data.id] = data;
62
+ }
63
+ }
64
+ return theJson;
65
+ }
66
+
67
+ // Si no encuentra retorna undefined
68
+ static async readById(collection, id, firestoreInstance = null) {
69
+ const document = firestore.doc(`${process.env.ENV ? process.env.ENV : "pro"}-${collection}/${id}`);
70
+ let doc;
71
+ if (firestoreInstance == null) {
72
+ doc = await document.get();
73
+ } else {
74
+ doc = await firestoreInstance.get(document);
75
+ }
76
+ const theJson = doc.data();
77
+ if (theJson) {
78
+ theJson.id = id;
79
+ }
80
+ return theJson;
81
+ }
82
+
83
+ static async create(collection, payload, firestoreInstance = null) {
84
+ const elDoc = await firestore.collection(`${process.env.ENV ? process.env.ENV : "pro"}-${collection}`).add(payload);
85
+ if (firestoreInstance == null) {
86
+ payload.id = elDoc.id;
87
+ return payload;
88
+ } else {
89
+ // Please check it later, could not work
90
+ firestoreInstance.add(elDoc, payload);
91
+ }
92
+ }
93
+
94
+ static async createById(collection, id, payload, firestoreInstance = null) {
95
+ const document = firestore.doc(`${process.env.ENV ? process.env.ENV : "pro"}-${collection}/${id}`);
96
+ if (firestoreInstance == null) {
97
+ await document.set(payload);
98
+ } else {
99
+ firestoreInstance.set(document, payload);// no retorna promesa, sino la misma instancia
100
+ }
101
+ return document;
102
+ }
103
+
104
+ static async updateOrCreateById(collection, id, payload, firestoreInstance = null) {
105
+ const localKey = `${process.env.ENV ? process.env.ENV : "pro"}-${collection}/${id}`;
106
+ const document = firestore.doc(localKey);
107
+ if (firestoreInstance == null) {
108
+ await document.set(payload, { merge: true });
109
+ } else {
110
+ firestoreInstance.set(document, payload, { merge: true });// no retorna promesa, sino la misma instancia
111
+ }
112
+ }
113
+
114
+ static async updateById(collection, id, payload, firestoreInstance = null) {
115
+ const document = firestore.doc(`${process.env.ENV ? process.env.ENV : "pro"}-${collection}/${id}`);
116
+ if (firestoreInstance == null) {
117
+ await document.update(payload);
118
+ } else {
119
+ firestoreInstance.update(document, payload);// no retorna promesa, sino la misma instancia
120
+ }
121
+ }
122
+
123
+ static async deleteById(collection, id, firestoreInstance = null) {
124
+ const document = firestore.doc(`${process.env.ENV ? process.env.ENV : "pro"}-${collection}/${id}`);
125
+ if (firestoreInstance == null) {
126
+ await document.delete();
127
+ } else {
128
+ firestoreInstance.delete(document);// no retorna promesa, sino la misma instancia
129
+ }
130
+ }
131
+
132
+ static async paginate(collection, orderColumns, offset = 0, pageSize = 20, where = [], firestoreInstance = null, select = []) {
133
+ const collectionReference = firestore.collection(`${process.env.ENV ? process.env.ENV : "pro"}-${collection}`);
134
+ let theQuery = collectionReference;
135
+ for (let i = 0; i < orderColumns.length; i++) {
136
+ const orderColumn = orderColumns[i];
137
+ theQuery = theQuery.orderBy(orderColumn.name, orderColumn.dir);
138
+ }
139
+
140
+ for (let i = 0; i < where.length; i++) {
141
+ const aWhere = where[i];
142
+ theQuery = theQuery.where(aWhere.key, aWhere.oper, aWhere.value)
143
+ }
144
+ let documents;
145
+
146
+ theQuery = theQuery
147
+ .offset(offset)
148
+ .limit(pageSize);
149
+
150
+ if (select.length > 0) {
151
+ theQuery = theQuery.select(...select);
152
+ }
153
+
154
+ if (firestoreInstance == null) {
155
+ documents = await theQuery.get();
156
+ } else {
157
+ documents = await firestoreInstance.get(theQuery);
158
+ }
159
+
160
+ const data = documents.docs.map((d) => {
161
+ const temp = d.data();
162
+ temp.id = d.id;
163
+ return temp;
164
+ });
165
+ return data;
166
+ }
167
+ }
168
+
169
+
@@ -0,0 +1,101 @@
1
+ import { MyUtilities } from "@ejfdelgado/ejflab-common/src/MyUtilities.js";
2
+ import { MyFileService } from "../MyFileService.mjs";
3
+ import { MyConstants } from "@ejfdelgado/ejflab-common/src/MyConstants.js";
4
+ import { MyStore } from "./MyStore.mjs";
5
+ import { General } from "./General.mjs";
6
+ import { MalaPeticionException } from "../MyError.mjs";
7
+
8
+ const USER_TYPE = "user";
9
+
10
+ export class Usuario {
11
+ metadatos = null;
12
+ id = null;
13
+ email = null;
14
+ phone = null;
15
+ constructor(token) {
16
+ this.metadatos = token;
17
+ if (this.metadatos != null) {
18
+ if (this.metadatos.email) {
19
+ this.email = this.metadatos.email;
20
+ }
21
+ const contenedor = this.metadatos["firebase"];
22
+ const identidades = contenedor["identities"];
23
+ if ("email" in identidades) {
24
+ this.id = identidades["email"][0];
25
+ this.email = this.id;
26
+ } else if ("phone" in identidades) {
27
+ this.id = identidades["phone"][0];
28
+ this.phone = this.id;
29
+ }
30
+ }
31
+ }
32
+ static async getCurrentUser(req, res, next) {
33
+ const user = res.locals.user;
34
+ const token = res.locals.token;
35
+ const sessionToken = res.locals.sessionToken;
36
+ if (sessionToken) {
37
+ res.cookie('yo', sessionToken, { maxAge: 1000 * 60 * 60 * 24, httpOnly: true });
38
+ }
39
+ // Debo buscar el usuario de base de datos
40
+ const response = await MyStore.readById(USER_TYPE, user.id);
41
+ if (response) {
42
+ res.status(200).send(response);
43
+ } else {
44
+ // Si no existe lo creo
45
+ const AHORA = new Date().getTime();
46
+ const email = user.email;
47
+ const prefijoEmail = /^[^@]+/.exec(email)[0]
48
+ const nuevo = {
49
+ email: email,
50
+ name: (token.name ? token.name : prefijoEmail),//El nombre será la primera parte del mail
51
+ phone: user.phone,
52
+ };
53
+ const q = `${nuevo.name ? nuevo.name : ""} ${prefijoEmail}`;
54
+ user.search = MyUtilities.partirTexto(q, true);
55
+ if (token.picture) {
56
+ nuevo.picture = await MyFileService.fetchUrl2Bucket(token.picture, token, MyConstants.USER.DEFAULT_FOLDER, MyConstants.USER.DEFAULT_FILE);
57
+ } else {
58
+ // Podría aquí hacerce un random
59
+ nuevo.picture = MyConstants.USER.DEFAULT_IMAGE;
60
+ }
61
+ nuevo.created = AHORA;
62
+ nuevo.updated = AHORA;
63
+ await MyStore.createById(USER_TYPE, user.id, nuevo);
64
+ nuevo.id = user.id;
65
+ res.status(200).send(nuevo);
66
+ }
67
+ }
68
+
69
+ static async saveMyUser(req, res, next) {
70
+ const user = res.locals.user;
71
+ const datos = General.readParam(req, "datos");
72
+ if (!datos || !(typeof datos == "object")) {
73
+ throw new MalaPeticionException("Falta datos");
74
+ }
75
+ const AHORA = new Date().getTime();
76
+ const updated = {
77
+ updated: AHORA,
78
+ };
79
+ const LLAVES = ["name", "email", "phone", "created"];
80
+ const LLAVES_SEARCH = ["name", "phone"];
81
+ let searchable = "";
82
+ for (let i = 0; i < LLAVES.length; i++) {
83
+ const llave = LLAVES[i];
84
+ const valor = datos[llave];
85
+ if (LLAVES_SEARCH.indexOf(llave) >= 0 && typeof valor == "string") {
86
+ searchable += valor + " ";
87
+ }
88
+ updated[llave] = valor;
89
+ }
90
+ updated.search = MyUtilities.partirTexto(searchable);
91
+ updated.search.push(user.id);
92
+ if (typeof datos.email == "string" && datos.email.length > 0) {
93
+ updated.search.push(datos.email);
94
+ }
95
+ await MyStore.updateById(USER_TYPE, user.id, updated);
96
+ updated.id = user.id;
97
+ updated.picture = datos.picture;
98
+ delete updated.search;
99
+ res.status(200).send(updated);
100
+ }
101
+ }
@@ -0,0 +1,43 @@
1
+
2
+ export class Utilidades {
3
+ static leerRefererPath(myrequest) {
4
+ let urlTotal = Utilidades.leerHeader(myrequest, [
5
+ //"referer",
6
+ "X-Referer",
7
+ ]);
8
+ let elhost = Utilidades.leerHeader(myrequest, [
9
+ //"host",
10
+ //"Host",
11
+ "X-Host",
12
+ ]);
13
+ if (urlTotal == null || elhost == null) {
14
+ return "";
15
+ }
16
+ urlTotal = urlTotal.replace(/^https?:\/\//ig, "");
17
+ elhost = elhost.replace(/^https?:\/\//ig, "");
18
+
19
+ let elreferer = urlTotal;
20
+ const elindice = elreferer.indexOf(elhost) + elhost.length;
21
+ let temp = urlTotal.substr(elindice);
22
+ let indiceQuery = temp.indexOf("?");
23
+ if (indiceQuery >= 0) {
24
+ temp = temp.substr(0, indiceQuery);
25
+ }
26
+ indiceQuery = temp.indexOf("#");
27
+ if (indiceQuery >= 0) {
28
+ temp = temp.substr(0, indiceQuery);
29
+ }
30
+ temp = temp.replace(/[\/]$/, "");
31
+ return temp;
32
+ }
33
+ static leerHeader(myrequest, lista) {
34
+ for (let i = 0; i < lista.length; i++) {
35
+ const a = lista[i];
36
+ const val = myrequest.header(a);
37
+ if (["", null, undefined].indexOf(val) < 0) {
38
+ return val;
39
+ }
40
+ return null;
41
+ }
42
+ }
43
+ }