mylogger/lib/salix.js

243 lines
6.4 KiB
JavaScript
Raw Normal View History

2024-05-06 11:44:55 +00:00
const fs = require("fs");
const path = require("path");
const SALIX_VERSION_HEADER = "Salix-version";
2024-05-06 12:12:33 +00:00
const CONFIG_FILENAME = "/config/salix.local.yml";
2024-05-06 11:44:55 +00:00
const i18n = {
versionChanged: "La versión ha cambiado",
deprecatedVersion: "La configuracion guardada está desactualizada",
noDeprecatedVersion: "La configuración guardada no requiere actualización",
2024-05-06 12:12:33 +00:00
erroFs: {
noExists: "El archivo no existe",
noWrite: "Error al escribir el archivo YAML:",
noRead: "Error al leer el archivo YAML:",
},
2024-05-06 11:44:55 +00:00
};
module.exports = class Salix {
constructor() {
this.conf = null;
this._logInfo = [];
this._salixVersion = null;
2024-05-06 11:44:55 +00:00
this._salixConfig = null;
2025-01-17 22:34:57 +00:00
this._token = null;
}
2024-05-10 20:11:24 +00:00
emit() {}
subscribe(externalListenerFunction) {
this.emit = externalListenerFunction;
2024-05-06 12:12:33 +00:00
}
2025-01-17 22:34:57 +00:00
async getToken() {
const { url: path, user, password } = this.conf.salix.api.login;
let response;
try {
response = await fetch(`${this.conf.salix.url}/${path}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify({
user,
password,
}),
});
response = await response.json();
} catch (error) {
console.error(error);
}
this.token = response.token;
}
async init(logger) {
this.conf = logger.conf;
2024-05-06 11:44:55 +00:00
const salixFileConfig = await this.loadConfig();
try {
// No exite fichero almacenado. Solicito config y version
2025-01-17 22:34:57 +00:00
// else {
this._salixConfig = salixFileConfig;
//Obtengo la version
await this.getSalixVersion(false);
this.salixVersion && (await this.handleVersion(salixFileConfig));
2024-05-06 11:44:55 +00:00
if (!salixFileConfig) await this.salixLogInfo();
2025-01-17 22:34:57 +00:00
this._logInfo = salixFileConfig.log;
// }
2024-05-06 12:12:33 +00:00
} catch (error) {}
2024-05-06 11:44:55 +00:00
setInterval(
() => this.getSalixVersion(),
this.conf.salix.renewInterval * 1000
);
}
get filePath() {
// Leer el contenido del archivo YAML
const configDir = path.join(__dirname, "..");
return `${configDir}${CONFIG_FILENAME}`;
}
async loadConfig() {
2025-01-17 22:34:57 +00:00
// try {
if (fs.existsSync(this.filePath)) {
const contenidoYAML = require(this.filePath);
return Object.assign({}, contenidoYAML);
} else {
new Error(`No existe el archivo de configuración`);
this.log("Creando archivo de configuración");
fs.writeFileSync(this.filePath, require("js-yaml").dump({}), "utf-8");
this.log("Archivo de configuración creado");
2024-05-06 11:44:55 +00:00
}
2025-01-17 22:34:57 +00:00
// } catch (error) {
// if (error.code === "ENOENT") {
// console.error(i18n.erroFs.noExists);
// } else {
// console.error(i18n.erroFs.noRead, error);
// }
// return null;
// }
2024-05-06 11:44:55 +00:00
}
async saveConfig(configValue) {
const defaultConfig = {
2024-05-06 12:12:33 +00:00
salixVersion: this.salixVersion,
2024-05-06 11:44:55 +00:00
};
try {
const contenidoYAML = fs.writeFileSync(
this.filePath,
require("js-yaml").dump(
Object.assign(defaultConfig, { log: configValue })
),
"utf-8"
);
return Object.assign({}, contenidoYAML);
} catch (error) {
if (error.code === "ENOENT") {
console.error(i18n.erroFs.noExists);
} else {
console.error(i18n.erroFs.noWrite, error);
}
return null;
}
}
2024-05-06 11:44:55 +00:00
parseVersion(value) {
return value.split(".").map(Number);
}
async handleVersion(salixFileConfig) {
const isDeprecated = this.compareVersion(
2024-05-06 12:12:33 +00:00
this.salixVersion,
2024-05-06 11:44:55 +00:00
salixFileConfig.salixVersion
);
isDeprecated && (await this.salixLogInfo());
}
compareVersion(v1, v2) {
let deprecatedConfig = false;
const version1 = this.parseVersion(v1);
const version2 = this.parseVersion(v2);
for (let i = 0; i < 3; i++) {
if (version1[i] > version2[i]) {
console.log(
// `La versión ${v1} es mayor que la versión ${v2}`
i18n.deprecatedVersion
);
deprecatedConfig = true;
2024-05-06 12:12:33 +00:00
break;
2024-05-06 11:44:55 +00:00
} else if (version1[i] < version2[i]) {
console.log(
// `La versión ${v1} es menor que la versión ${v2}`
i18n.noDeprecatedVersion
);
deprecatedConfig = false;
}
}
return deprecatedConfig;
2024-04-25 05:34:32 +00:00
}
2024-04-25 05:34:32 +00:00
async fetch(path) {
2024-04-25 06:19:28 +00:00
try {
2025-01-17 22:34:57 +00:00
// Configuración de la llamada fetch
const fetchConfig = {
2024-04-25 06:19:28 +00:00
method: "GET",
2025-01-17 22:34:57 +00:00
headers: {
"Content-Type": "application/json",
Authorization: `${this.token}`,
},
};
const salixCall = await fetch(
`${this.conf.salix.url}/${path}`,
fetchConfig
);
2024-04-25 06:19:28 +00:00
if (salixCall.status !== 200) {
2025-01-17 22:34:57 +00:00
throw new Error(response);
2024-04-25 06:19:28 +00:00
}
2025-01-17 22:34:57 +00:00
const responseText = await salixCall.text();
const response = JSON.parse(responseText);
2024-05-06 11:44:55 +00:00
const newVersion = salixCall.headers.get(SALIX_VERSION_HEADER);
2025-01-17 22:34:57 +00:00
if (!this.salixVersion) {
this.salixVersion = newVersion;
this.saveConfig();
await this.salixLogInfo();
}
if (this.salixVersion !== newVersion) {
const isDeprecated = this.compareVersion(newVersion, this.salixVersion);
2024-05-06 11:44:55 +00:00
if (isDeprecated) {
2024-05-06 12:12:33 +00:00
this.salixVersion = newVersion;
2024-05-06 11:44:55 +00:00
console.info(i18n.versionChanged);
await this.salixLogInfo();
}
2025-01-17 22:34:57 +00:00
}
2024-04-25 06:19:28 +00:00
return response;
2025-01-17 22:34:57 +00:00
} catch (response) {
const message = response?.error?.message ?? response.message;
this.log(message, 'error');
2024-04-25 05:34:32 +00:00
}
}
async getSalixVersion() {
2024-04-25 06:19:28 +00:00
this.log("CHECK VERSION");
2024-04-25 05:34:32 +00:00
2024-05-06 11:44:55 +00:00
await this.fetch(this.conf.salix.api.status);
2024-04-25 05:34:32 +00:00
2024-04-25 06:19:28 +00:00
this.log("VERSION CHECKED");
2024-04-25 05:34:32 +00:00
}
async salixLogInfo() {
2024-05-06 11:44:55 +00:00
this.log("REQUEST LOGINFO");
2025-01-17 22:34:57 +00:00
await this.getToken();
2024-05-06 11:44:55 +00:00
let salixLogConfig = await this.fetch(this.conf.salix.api.logInfo);
2024-04-25 05:34:32 +00:00
2024-04-25 06:19:28 +00:00
this._logInfo = salixLogConfig;
2024-05-06 11:44:55 +00:00
this.saveConfig(salixLogConfig);
2024-04-25 06:19:28 +00:00
this.log("LOGINFO REQUESTED");
2024-04-25 05:34:32 +00:00
}
2025-01-17 22:34:57 +00:00
log(param, type = 'log') {
const colors = {
log: '\x1b[37m',
error: '\x1b[31m',
warn: '\x1b[33m' ,
}
console[type](colors[type], `${Salix.name} - ${type} - ${param}`);
}
2024-04-25 05:34:32 +00:00
get logInfo() {
return this._logInfo;
}
2025-01-17 22:34:57 +00:00
get token() {
return this._token;
}
set token(token) {
this._token = token;
}
2024-04-25 05:34:32 +00:00
get salixVersion() {
return this._salixVersion;
}
2024-05-06 12:12:33 +00:00
set salixVersion(newVersion) {
2025-01-17 22:34:57 +00:00
if (this._salixVersion && this._salixVersion !== newVersion)
this.emit(newVersion);
2024-05-06 12:12:33 +00:00
this._salixVersion = newVersion;
}
};