const fs = require("fs"); const path = require("path"); const SALIX_VERSION_HEADER = "Salix-version"; const CONFIG_FILENAME = "/config/salix.local.yml"; const i18n = { versionChanged: "La versión ha cambiado", deprecatedVersion: "La configuracion guardada está desactualizada", noDeprecatedVersion: "La configuración guardada no requiere actualización", erroFs: { noExists: "El archivo no existe", noWrite: "Error al escribir el archivo YAML:", noRead: "Error al leer el archivo YAML:", }, }; module.exports = class Salix { constructor() { this.conf = null; this._logInfo = []; this._salixVersion = null; this._salixConfig = null; this._token = null; } emit() {} subscribe(externalListenerFunction) { this.emit = externalListenerFunction; } 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; const salixFileConfig = await this.loadConfig(); try { // No exite fichero almacenado. Solicito config y version // else { this._salixConfig = salixFileConfig; //Obtengo la version await this.getSalixVersion(false); this.salixVersion && (await this.handleVersion(salixFileConfig)); if (!salixFileConfig) await this.salixLogInfo(); this._logInfo = salixFileConfig.log; // } } catch (error) {} 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() { // 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"); } // } catch (error) { // if (error.code === "ENOENT") { // console.error(i18n.erroFs.noExists); // } else { // console.error(i18n.erroFs.noRead, error); // } // return null; // } } async saveConfig(configValue) { const defaultConfig = { salixVersion: this.salixVersion, }; 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; } } parseVersion(value) { return value.split(".").map(Number); } async handleVersion(salixFileConfig) { const isDeprecated = this.compareVersion( this.salixVersion, 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; break; } 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; } async fetch(path) { try { // Configuración de la llamada fetch const fetchConfig = { method: "GET", headers: { "Content-Type": "application/json", Authorization: `${this.token}`, }, }; const salixCall = await fetch( `${this.conf.salix.url}/${path}`, fetchConfig ); if (salixCall.status !== 200) { throw new Error(response); } const responseText = await salixCall.text(); const response = JSON.parse(responseText); const newVersion = salixCall.headers.get(SALIX_VERSION_HEADER); if (!this.salixVersion) { this.salixVersion = newVersion; this.saveConfig(); await this.salixLogInfo(); } if (this.salixVersion !== newVersion) { const isDeprecated = this.compareVersion(newVersion, this.salixVersion); if (isDeprecated) { this.salixVersion = newVersion; console.info(i18n.versionChanged); await this.salixLogInfo(); } } return response; } catch (response) { const message = response?.error?.message ?? response.message; this.log(message, 'error'); } } async getSalixVersion() { this.log("CHECK VERSION"); await this.fetch(this.conf.salix.api.status); this.log("VERSION CHECKED"); } async salixLogInfo() { this.log("REQUEST LOGINFO"); await this.getToken(); let salixLogConfig = await this.fetch(this.conf.salix.api.logInfo); this._logInfo = salixLogConfig; this.saveConfig(salixLogConfig); this.log("LOGINFO REQUESTED"); } log(param, type = 'log') { const colors = { log: '\x1b[37m', error: '\x1b[31m', warn: '\x1b[33m' , } console[type](colors[type], `${Salix.name} - ${type} - ${param}`); } get logInfo() { return this._logInfo; } get token() { return this._token; } set token(token) { this._token = token; } get salixVersion() { return this._salixVersion; } set salixVersion(newVersion) { if (this._salixVersion && this._salixVersion !== newVersion) this.emit(newVersion); this._salixVersion = newVersion; } };