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; } fooListener(val) {} registerNewListener(externalListenerFunction) { this.fooListener = externalListenerFunction; } async init(logger) { this.conf = logger.conf; const salixFileConfig = await this.loadConfig(); try { // No exite fichero almacenado. Solicito config y version if (!salixFileConfig) await this.salixLogInfo(); else { this._salixConfig = salixFileConfig; //Obtengo la version await this.getSalixVersion(false); this.salixVersion && this.handleVersion(salixFileConfig); 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); } } 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 { let salixCall = await fetch(`${this.conf.salix.url}/${path}`, { method: "GET", }); const response = JSON.parse(await salixCall.text()); if (salixCall.status !== 200) { console.error(response.error); throw new Error(response.error.message); } const newVersion = salixCall.headers.get(SALIX_VERSION_HEADER); if(!this.salixVersion) this.salixVersion = newVersion; 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 ({ message }) { console.error(message); if (!this._salixConfig) throw new Error(message); } } async getSalixVersion() { this.log("CHECK VERSION"); await this.fetch(this.conf.salix.api.status); this.log("VERSION CHECKED"); } async salixLogInfo() { this.log("REQUEST LOGINFO"); let salixLogConfig = await this.fetch(this.conf.salix.api.logInfo); this._logInfo = salixLogConfig; this.saveConfig(salixLogConfig); this.log("LOGINFO REQUESTED"); } log(param) { console.log(`${Salix.name} - ${param}`); } get logInfo() { return this._logInfo; } get salixVersion() { return this._salixVersion; } set salixVersion(newVersion) { if(this._salixVersion) this.fooListener(newVersion); this._salixVersion = newVersion; } };