@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,205 @@
1
+ import path from "path";
2
+ import fs from "fs";
3
+ import { spawn } from "child_process";
4
+ import { General } from "./common/General.mjs";
5
+ import { InesperadoException } from "./MyError.mjs";
6
+ import { IdGen } from "@ejfdelgado/ejflab-common/src/IdGen.js";
7
+
8
+ export class ExecFolder {
9
+ constructor() {
10
+ // Debe crear una carpeta aleatoria
11
+ this.folderName = IdGen.num2ord(new Date().getTime());
12
+ this.folderPath = `/tmp/ejflabs/${this.folderName}/`;
13
+ fs.mkdirSync(this.folderPath, { recursive: true });
14
+ }
15
+ destroyFolder() {
16
+ fs.rmSync(this.folderPath, { recursive: true, force: true });
17
+ }
18
+ static async removeDir(path) {
19
+ return new Promise((resolve, reject) => {
20
+ try {
21
+ if (fs.existsSync(path)) {
22
+ const files = fs.readdirSync(path)
23
+ if (files.length > 0) {
24
+ files.forEach(function (filename) {
25
+ if (fs.statSync(path + "/" + filename).isDirectory()) {
26
+ removeDir(path + "/" + filename)
27
+ } else {
28
+ fs.unlinkSync(path + "/" + filename)
29
+ }
30
+ })
31
+ }
32
+ fs.rmdirSync(path);
33
+ }
34
+ resolve();
35
+ } catch (err) {
36
+ reject(err);
37
+ }
38
+ });
39
+ }
40
+ writeTextFile(fileName, content) {
41
+ const folderPath = this.folderPath;
42
+ return new Promise((resolve, reject) => {
43
+ try {
44
+ const path = `${folderPath}${fileName}`;
45
+ fs.writeFileSync(path, content);
46
+ resolve(path);
47
+ } catch (err) {
48
+ reject(err);
49
+ }
50
+ });
51
+ }
52
+ readTextFile(fileName) {
53
+ const folderPath = this.folderPath;
54
+ return new Promise((resolve, reject) => {
55
+ try {
56
+ const ruta = `${folderPath}${fileName}`;
57
+ const data = fs.readFileSync(ruta, 'utf8');
58
+ resolve(data);
59
+ } catch (err) {
60
+ reject(err);
61
+ }
62
+ });
63
+ }
64
+ static async copyDir(src, dest) {
65
+ return new Promise(async (resolve, reject) => {
66
+ const copy = async (copySrc, copyDest) => {
67
+ return new Promise(async (resolve2, reject2) => {
68
+ try {
69
+ const list = fs.readdirSync(copySrc);
70
+ const promesas = [];
71
+ list.forEach(async (item) => {
72
+ const ss = path.resolve(copySrc, item);
73
+ try {
74
+ const stat = fs.statSync(ss);
75
+ const curSrc = path.resolve(copySrc, item);
76
+ const curDest = path.resolve(copyDest, item);
77
+ if (stat.isFile()) {
78
+ promesas.push(new Promise((resolve3, reject3) => {
79
+ const stream = fs.createReadStream(curSrc)
80
+ .pipe(fs.createWriteStream(curDest));
81
+ stream.on('error', reject3);
82
+ stream.on('finish', resolve3);
83
+ }));
84
+ } else if (stat.isDirectory()) {
85
+ fs.mkdirSync(curDest, { recursive: true });
86
+ await copy(curSrc, curDest);
87
+ }
88
+ } catch (err2) {
89
+ reject2(err2);
90
+ }
91
+ });
92
+ try {
93
+ await Promise.all(promesas);
94
+ resolve2();
95
+ } catch (err3) {
96
+ reject2(err3);
97
+ }
98
+ } catch (err1) {
99
+ reject2(err1);
100
+ }
101
+ });
102
+ };
103
+
104
+ try {
105
+ await createFolderIfNotExists(dest);
106
+ await copy(src, dest);
107
+ resolve();
108
+ } catch (err0) {
109
+ reject(err0);
110
+ }
111
+ });
112
+ }
113
+ }
114
+
115
+ export class MyShell {
116
+
117
+ //http://localhost:8081/srv/shell?cmd=solvePnP&payload={"v2": [[282, 274], [397, 227], [577, 271], [462, 318], [270, 479], [450, 523], [566, 475]], "v3": [[0.5, 0.5, -0.5], [0.5, 0.5, 0.5], [-0.5, 0.5, 0.5], [-0.5, 0.5, -0.5], [0.5, -0.5, -0.5], [-0.5, -0.5, -0.5], [-0.5, -0.5, 0.5]]}
118
+ //http://localhost:8081/srv/shell?cmd=ls%20-la
119
+ static async run(req, res, next) {
120
+ const cmd = General.readParam(req, "cmd");
121
+ const payload = General.readParam(req, "payload");
122
+ const dato = await MyShell.runLocal(cmd, payload);
123
+ res.setHeader('content-type', 'text/plain');
124
+ res.end(dato);
125
+ }
126
+ static async runCommand(command, workingDirectory = "./") {
127
+ return new Promise((resolve, reject) => {
128
+ console.log(`Running ${command} at ${workingDirectory}`);
129
+ exec(command, {
130
+ cwd: workingDirectory
131
+ }, function (err, stdout, stderr) {
132
+ console.log(stdout);
133
+ if (err !== null) {
134
+ reject(err);
135
+ } else {
136
+ resolve();
137
+ }
138
+ });
139
+ });
140
+ }
141
+ static existsExecutable(execPath) {
142
+ try {
143
+ if (fs.lstatSync(execPath).isFile()) {
144
+ return true;
145
+ }
146
+ } catch (err) { }
147
+ return false;
148
+ }
149
+ //MyShell.getBinDir()
150
+ static getBinDir() {
151
+ const DIR = process.env.BIN_DIR || "bin-docker";
152
+ return DIR;
153
+ }
154
+ static async runLocal(command, payload = null) {
155
+ const args = command.split(/\s+/g);
156
+ const command1 = args.splice(0, 1)[0];
157
+ let execPath = path.join(process.cwd(), `/${MyShell.getBinDir()}/${command1}`);
158
+ if (!MyShell.existsExecutable(execPath)) {
159
+ execPath = command1;
160
+ }
161
+ if (payload !== null) {
162
+ args.push(payload);
163
+ }
164
+ const dirPath = path.join(process.cwd(), `/${MyShell.getBinDir()}/libs`);
165
+ const options = { env: { LD_LIBRARY_PATH: dirPath } };
166
+ const ls = spawn(execPath, args, options);
167
+
168
+ return new Promise((resolve, reject) => {
169
+ let total = "";
170
+ let isError = false;
171
+ ls.stdout.on("data", data => {
172
+ total += data.toString();
173
+ });
174
+
175
+ ls.stderr.on("data", data => {
176
+ //console.log(`stderr: ${data}`);
177
+ //reject(new Error(data));
178
+ total += data.toString();
179
+ isError = true;
180
+ });
181
+
182
+ ls.on('error', (error) => {
183
+ //console.log(`error: ${error.message}`);
184
+ reject(error);
185
+ });
186
+
187
+ ls.on("close", code => {
188
+ //console.log(`child process exited with code ${code}`);
189
+ if (isError) {
190
+ reject(total);
191
+ } else {
192
+ let parsed = {};
193
+ try {
194
+ parsed = JSON.parse(total);
195
+ } catch (err) { }
196
+ if (typeof parsed.error == "string") {
197
+ reject(new InesperadoException(parsed.error));
198
+ }
199
+ resolve(total);
200
+ }
201
+ });
202
+ });
203
+
204
+ }
205
+ }
@@ -0,0 +1,43 @@
1
+ import * as mysql from "mysql2/promise";
2
+
3
+ export class MySqlSrv {
4
+ connectionPromise = null;
5
+ connection = null;
6
+ constructor() {
7
+ }
8
+
9
+ getConnectionParams() {
10
+ const host = process.env.PMA_HOST || "localhost";
11
+ const port = parseInt(process.env.PMA_PORT || "6033");
12
+ const database = process.env.MYSQL_DATABASE || "policia_vr";
13
+ const user = process.env.MYSQL_ROOT_USER || "root";
14
+ const password = process.env.MYSQL_ROOT_PASSWORD || "p0l1c14";
15
+ return {
16
+ host,
17
+ port,
18
+ user,
19
+ database,
20
+ password,
21
+ waitForConnections: true,
22
+ connectionLimit: 10,
23
+ maxIdle: 10, // max idle connections, the default value is the same as `connectionLimit`
24
+ idleTimeout: 60000, // idle connections timeout, in milliseconds, the default value 60000
25
+ queueLimit: 0,
26
+ enableKeepAlive: true,
27
+ keepAliveInitialDelay: 0
28
+ };
29
+ }
30
+
31
+ async connect() {
32
+ this.connectionPromise = mysql.createPool(this.getConnectionParams());
33
+ this.connection = await this.connectionPromise;
34
+ }
35
+
36
+ async checkConnection() {
37
+ await this.connectionPromise;
38
+ }
39
+
40
+ async disconnect() {
41
+ this.connection.end();
42
+ }
43
+ }
@@ -0,0 +1,111 @@
1
+ import md5 from "md5";
2
+ import { Buffer } from "buffer";
3
+ import { MyError } from "./MyError.mjs";
4
+ import { MyUtilities } from "@ejfdelgado/ejflab-common/src/MyUtilities.js";
5
+
6
+ function stringify(circ) {
7
+ var cache = [];
8
+ const text = JSON.stringify(circ, (key, value) => {
9
+ if (typeof value === 'object' && value !== null) {
10
+ if (cache.includes(value)) return;
11
+ cache.push(value);
12
+ }
13
+ return value;
14
+ });
15
+ cache = null;
16
+ return text;
17
+ };
18
+
19
+ function cors(req, res, next) {
20
+ if (req.method == 'OPTIONS') {
21
+ res.setHeader('Access-Control-Allow-Origin', '*');
22
+ res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE');
23
+ res.setHeader('Access-Control-Allow-Headers', '*');
24
+ res.setHeader('Access-Control-Max-Age', '3600');
25
+ res.status(204).send('');
26
+ } else {
27
+ res.setHeader('Access-Control-Allow-Origin', '*');
28
+ next();
29
+ }
30
+ }
31
+
32
+ async function commonHeaders(req, res, next) {
33
+ res.setHeader('Content-Type', 'application/json');
34
+ await next();
35
+ }
36
+
37
+ function getVerifyKey(body, sometime) {
38
+ return md5(Buffer.from(md5(body) + sometime).toString("base64"));
39
+ }
40
+
41
+ async function verifyConstant(req, res, next) {
42
+ const verifyHeader = req.headers["x-constant"];
43
+ const someTimeHeader = req.headers["x-mytime"];
44
+ const reqBody = req.body;
45
+ const calculado = getVerifyKey(JSON.stringify(reqBody), someTimeHeader);
46
+ if (verifyHeader != calculado) {
47
+ res.status(403).send({ message: "Operación no permitida" });
48
+ } else {
49
+ await next();
50
+ }
51
+ }
52
+
53
+ function urlNorFound(req, res, next) {
54
+ res.status(404).send("Sorry can't find that!");
55
+ }
56
+
57
+ function getEnvVariables() {
58
+ return {
59
+ GAE_APPLICATION: process.env.GAE_APPLICATION,
60
+ GAE_DEPLOYMENT_ID: process.env.GAE_DEPLOYMENT_ID,
61
+ GAE_ENV: process.env.GAE_ENV,
62
+ GAE_INSTANCE: process.env.GAE_INSTANCE,
63
+ GAE_MEMORY_MB: process.env.GAE_MEMORY_MB,
64
+ GAE_RUNTIME: process.env.GAE_RUNTIME,
65
+ GAE_SERVICE: process.env.GAE_SERVICE,
66
+ GAE_VERSION: process.env.GAE_VERSION,
67
+ GOOGLE_CLOUD_PROJECT: process.env.GOOGLE_CLOUD_PROJECT,
68
+ NODE_ENV: process.env.NODE_ENV,
69
+ PORT: process.env.PORT,
70
+ ENV: process.env.ENV ? process.env.ENV : "pro",
71
+ };
72
+ }
73
+
74
+ function handleErrors(error, res) {
75
+ if (error instanceof MyError && typeof error.httpCode == "number") {
76
+ res.status(error.httpCode);
77
+ } else {
78
+ res.status(500);
79
+ }
80
+ const response = {
81
+ status: "error",
82
+ message: error.message,
83
+ };
84
+ res.send(response);
85
+ }
86
+
87
+ function handleErrorsDecorator(someFun) {
88
+ return async (req, res, next) => {
89
+ try {
90
+ await someFun(req, res, next);
91
+ } catch (error) {
92
+ console.log(error);
93
+ if (error.response && error.response.body) {
94
+ console.log(JSON.stringify(error.response.body));
95
+ }
96
+ res.locals.myerror = error;
97
+ handleErrors(error, res);
98
+ }
99
+ };
100
+ }
101
+
102
+ export {
103
+ cors,
104
+ getEnvVariables,
105
+ urlNorFound,
106
+ commonHeaders,
107
+ handleErrors,
108
+ handleErrorsDecorator,
109
+ verifyConstant,
110
+ stringify
111
+ }
@@ -0,0 +1,27 @@
1
+ import { General } from "./common/General.mjs";
2
+ import { ExecFolder, MyShell } from "./MyShell.mjs";
3
+
4
+ export class OpenCVSrv {
5
+ static async solvePnPLocal(payload) {
6
+ const cmd = "solvePnP";
7
+ const points3d = payload.points3d;
8
+ let folder = null;
9
+ if (points3d) {
10
+ folder = new ExecFolder();
11
+ payload.points3dPath = await folder.writeTextFile("points3d.json", JSON.stringify(points3d));
12
+ delete payload.points3d;
13
+ }
14
+ const payloadTxt = JSON.stringify(payload);
15
+ const dato = await MyShell.runLocal(cmd, payloadTxt);
16
+ if (folder) {
17
+ folder.destroyFolder();
18
+ }
19
+ return dato;
20
+ }
21
+ static async solvePnP(req, res, next) {
22
+ const payload = General.readParam(req, "payload");
23
+ const dato = await OpenCVSrv.solvePnPLocal(payload);
24
+ res.setHeader('content-type', 'text/json');
25
+ res.end(dato);
26
+ }
27
+ }
@@ -0,0 +1,234 @@
1
+ import { MyUtilities } from "@ejfdelgado/ejflab-common/src/MyUtilities.js";
2
+ import { MyRoutes } from "@ejfdelgado/ejflab-common/src/MyRoutes.js"
3
+ import { General } from "./common/General.mjs";
4
+ import { MyStore } from "./common/MyStore.mjs";
5
+ import { Utilidades } from "./common/Utilidades.mjs";
6
+ import { MalaPeticionException, NoExisteException } from "./MyError.mjs";
7
+ import { AuthorizationSrv } from "./AuthorizationSrv.mjs";
8
+ import { MyConstants } from "@ejfdelgado/ejflab-common/src/MyConstants.js";
9
+ import { ModuloDatoSeguroBack } from "@ejfdelgado/ejflab-common/src/ModuloDatoSeguroBack.mjs";
10
+
11
+
12
+
13
+ const PAGE_TYPE = "page";
14
+ const PAGE_DELETE_TYPE = "page-delete";
15
+ const MAX_READ_SIZE = 30;
16
+
17
+ export class PageSrv {
18
+ static async deletePage(req, res, next) {
19
+ let respuesta = {};
20
+ const pageId = req.params['pageId'];
21
+ const ahora = new Date().getTime();
22
+ // Crear una entidad como evidencia de que el borrado está en proceso
23
+ await MyStore.createById(PAGE_DELETE_TYPE, pageId, {
24
+ state: 0,
25
+ created: ahora,
26
+ updated: ahora,
27
+ });
28
+ // Se borra la página como tal
29
+ await MyStore.deleteById(PAGE_TYPE, pageId);
30
+ res.status(200).send(respuesta);
31
+ }
32
+ static async savePage(req, res, next) {
33
+ let respuesta = {};
34
+ const pageId = req.params['pageId'];
35
+ const datos = General.readParam(req, "datos");
36
+ if (!pageId) {
37
+ throw new MalaPeticionException("Falta el id");
38
+ }
39
+ if (!datos || !(typeof datos == "object")) {
40
+ throw new MalaPeticionException("Falta datos");
41
+ }
42
+ const response = await MyStore.readById(PAGE_TYPE, pageId);
43
+ if (response) {
44
+ const { tit, desc } = datos;
45
+ const q = MyUtilities.partirTexto(`${typeof tit == 'string' ? tit : ''} ${typeof desc == 'string' ? desc : ''}`, true);
46
+ //Se agrega al buscable el correo del autor
47
+ q.push(response.usr);
48
+ const updated = {
49
+ tit,
50
+ desc,
51
+ q,
52
+ };
53
+ if (res.locals && res.locals.uri) {
54
+ updated.img = res.locals.uri;
55
+ }
56
+ await MyStore.updateById(PAGE_TYPE, pageId, updated);
57
+ Object.assign(response, updated);
58
+ respuesta = response;
59
+ } else {
60
+ throw new NoExisteException(`Does not exists ${pageId}`);
61
+ }
62
+ PageSrv.cleanSecrets(respuesta);
63
+ res.status(200).send(respuesta);
64
+ }
65
+ static async createNewPage(req, res, next) {
66
+ const user = res.locals.user;
67
+ const elpath = Utilidades.leerRefererPath(req);
68
+ const partes = MyRoutes.splitPageData(elpath);
69
+ const elUsuario = user.metadatos.email;
70
+ const nueva = await PageSrv.commonCreateNewPage(elUsuario, partes.pageType);
71
+ PageSrv.cleanSecrets(nueva);
72
+ res.status(200).send(nueva);
73
+ }
74
+ static async getCurrentPage(req, res, next) {
75
+ const user = res.locals.user;
76
+ const elpath = Utilidades.leerRefererPath(req);
77
+ const partes = MyRoutes.splitPageData(elpath);
78
+ const respuesta = await PageSrv.loadCurrentPage(partes.pageType, partes.pageId, user);
79
+ PageSrv.cleanSecrets(respuesta);
80
+ res.status(200).send(respuesta);
81
+ }
82
+ // PageSrv.cleanSecrets(page)
83
+ static async cleanSecrets(page) {
84
+ if (page) {
85
+ delete page['private'];
86
+ delete page['private2'];
87
+ delete page['public2'];
88
+ delete page['pass'];
89
+ }
90
+ return page;
91
+ }
92
+ static async rotateSecret1(req, res, next) {
93
+ let respuesta = {};
94
+ const pageId = req.params['pageId'];
95
+ if (!pageId) {
96
+ throw new MalaPeticionException("Falta el id");
97
+ }
98
+ const actualizacion = { pass: ModuloDatoSeguroBack.generateKey(4) };
99
+ await MyStore.updateById(PAGE_TYPE, pageId, actualizacion);
100
+ res.status(200).send(respuesta);
101
+ }
102
+ static async rotateSecret2(req, res, next) {
103
+ let respuesta = {};
104
+ const pageId = req.params['pageId'];
105
+ if (!pageId) {
106
+ throw new MalaPeticionException("Falta el id");
107
+ }
108
+ const actualizacion = ModuloDatoSeguroBack.generateKeyPair();
109
+ await MyStore.updateById(PAGE_TYPE, pageId, actualizacion);
110
+ res.status(200).send(respuesta);
111
+ }
112
+ static async rotateSecret3(req, res, next) {
113
+ let respuesta = {};
114
+ const pageId = req.params['pageId'];
115
+ if (!pageId) {
116
+ throw new MalaPeticionException("Falta el id");
117
+ }
118
+ const par = ModuloDatoSeguroBack.generateKeyPair();
119
+ const actualizacion = {
120
+ public2: par.public,
121
+ private2: par.private,
122
+ };
123
+ await MyStore.updateById(PAGE_TYPE, pageId, actualizacion);
124
+ res.status(200).send(respuesta);
125
+ }
126
+ static async commonCreateNewPage(elUsuario, pageType) {
127
+ const AHORA = new Date().getTime() / 1000;
128
+ const nueva = {
129
+ usr: elUsuario,
130
+ path: pageType,
131
+ date: AHORA,
132
+ act: AHORA,
133
+ tit: "Título",
134
+ desc: "Descripción",
135
+ img: MyConstants.getDefaultPageImage(pageType),
136
+ kw: "",
137
+ };
138
+ try {
139
+ nueva.pass = ModuloDatoSeguroBack.generateKey(4);
140
+ const par = ModuloDatoSeguroBack.generateKeyPair();
141
+ const par2 = ModuloDatoSeguroBack.generateKeyPair();
142
+ nueva.public = par.public;
143
+ nueva.private = par.private;
144
+ nueva.public2 = par2.public;
145
+ nueva.private2 = par2.private;
146
+ } catch (err) { }
147
+ await MyStore.create(PAGE_TYPE, nueva);
148
+ // Se deben agregar los permisos
149
+ const promesasPermisos = [];
150
+ promesasPermisos.push(AuthorizationSrv.createPagePermision("owner", nueva.id, elUsuario));
151
+ const publicRole = MyConstants.getDefaultPublicPageRole(pageType);
152
+ if (publicRole != "none") {
153
+ promesasPermisos.push(AuthorizationSrv.createPagePermision(publicRole, nueva.id));
154
+ }
155
+ await Promise.all(promesasPermisos);
156
+ return nueva;
157
+ }
158
+ static async loadCurrentPage(pageType, pageId, usuario = null) {
159
+ const AHORA = new Date().getTime() / 1000;
160
+ if (usuario == null && pageId == null) {
161
+ return {};
162
+ }
163
+ if (typeof pageId == "string") {
164
+ // Si hay id se debe buscar con Id y listo
165
+ const response = await MyStore.readById(PAGE_TYPE, pageId);
166
+ if (response) {
167
+ return response;
168
+ } else {
169
+ throw new NoExisteException(`Does not exists ${pageId}`);
170
+ }
171
+ } else {
172
+ if (usuario) {
173
+ const elUsuario = usuario.metadatos.email;
174
+ const where = [
175
+ { key: "usr", oper: "==", value: elUsuario },
176
+ { key: "path", oper: "==", value: pageType },
177
+ ];
178
+ const max = 1;
179
+ // Si no hay id pero hay usuario logeado se debe buscar por aut y pageType
180
+ const response = await MyStore.paginate(PAGE_TYPE, [{ name: "act", dir: 'desc' }], 0, max, where);
181
+ if (response.length > 0) {
182
+ return response[0];
183
+ } else {
184
+ // Si no existe lo crea y devuelve el valor por defecto
185
+ const nueva = await PageSrv.commonCreateNewPage(elUsuario, pageType);
186
+ return nueva;
187
+ }
188
+ }
189
+ }
190
+ }
191
+ static async iterateMyPages(req, res, next) {
192
+ const token = res.locals.token;
193
+ const { max, offset } = General.readMaxOffset(req, MAX_READ_SIZE);
194
+ const q = General.readParam(req, "q");
195
+ const path = General.readParam(req, "path");
196
+ if (!path) {
197
+ throw new MalaPeticionException("Falta el path");
198
+ }
199
+ // Que sea mio
200
+ const where = [
201
+ { key: "usr", oper: "==", value: token.email },
202
+ { key: "path", oper: "==", value: path },
203
+ ];
204
+ if (typeof q == 'string' && q.trim().length > 0) {
205
+ const partes = MyUtilities.partirTexto(q, false, true);
206
+ where.push({
207
+ key: "q", oper: "array-contains-any", value: partes
208
+ });
209
+ }
210
+ const select = ["date", "path", "img", "act", "usr", "kw", "tit", "desc", "public"];
211
+ const response = await MyStore.paginate(PAGE_TYPE, [{ name: "act", dir: 'desc' }], offset, max, where, null, select);
212
+ res.status(200).send(response);
213
+ }
214
+ static async iterateAllPages(req, res, next) {
215
+ const { max, offset } = General.readMaxOffset(req, MAX_READ_SIZE);
216
+ const q = General.readParam(req, "q");
217
+ const path = General.readParam(req, "path");
218
+ if (!path) {
219
+ throw new MalaPeticionException("Falta el path");
220
+ }
221
+ const where = [
222
+ { key: "path", oper: "==", value: path },
223
+ ];
224
+ if (typeof q == 'string' && q.trim().length > 0) {
225
+ const partes = MyUtilities.partirTexto(q, false, true);
226
+ where.push({
227
+ key: "q", oper: "array-contains-any", value: partes
228
+ });
229
+ }
230
+ const select = ["date", "path", "img", "act", "usr", "kw", "tit", "desc", "public"];
231
+ const response = await MyStore.paginate(PAGE_TYPE, [{ name: "act", dir: 'desc' }], offset, max, where, null, select);
232
+ res.status(200).send(response);
233
+ }
234
+ }