✏️ Some code clean...

This commit is contained in:
SebClem 2021-01-07 16:37:30 +01:00
parent f34154a4f1
commit d85c04755e
6 changed files with 329 additions and 333 deletions

View File

@ -1,4 +1,3 @@
const appRoot = require("app-root-path");
const winston = require("winston");
const logger = winston.createLogger({

View File

@ -1,16 +1,12 @@
const settingsTools = require("./settingsTools");
const CronJob = require("cron").CronJob;
const settingsTools = require("./settingsTools");
const WebdavTools = require("./webdavTools");
const webdav = new WebdavTools().getInstance();
const hassioApiTools = require("./hassioApiTools");
const statusTools = require("./status");
const pathTools = require("./pathTools");
const CronJob = require("cron").CronJob;
const moment = require("moment");
const logger = require("../config/winston");
function startCron() {
@ -100,21 +96,26 @@ class CronContainer {
.then(() => {
webdav.uploadFile(id, webdav.getConf().back_dir + pathTools.auto + name + ".tar");
})
.catch(() => {});
.catch(() => {
});
})
.catch(() => {});
.catch(() => {
});
})
.catch(() => {});
.catch(() => {
});
}
_clean() {
let autoCleanlocal = settingsTools.getSettings().auto_clean_local;
if (autoCleanlocal != null && autoCleanlocal === "true") {
hassioApiTools.clean().catch(() => {});
hassioApiTools.clean().catch(() => {
});
}
let autoCleanCloud = settingsTools.getSettings().auto_clean_backup;
if (autoCleanCloud != null && autoCleanCloud === "true") {
webdav.clean().catch(() => {});
webdav.clean().catch(() => {
});
}
}
}

View File

@ -14,7 +14,6 @@ const logger = require("../config/winston");
const create_snap_timeout = 90 * 60 * 1000;
function getVersion() {
return new Promise((resolve, reject) => {
let token = process.env.HASSIO_TOKEN;
@ -64,19 +63,19 @@ function getAddonList() {
statusTools.setStatus(status);
}
let addons = result.body.data.addons;
let instaled = [];
let installed = [];
for (let index in addons) {
let current = addons[index];
if(current.installed == true){
instaled.push({slug:current.slug, name: current.name})
if (current.installed === true) {
installed.push({ slug: current.slug, name: current.name })
}
}
instaled.sort((a,b)=>{
var textA = a.name.toUpperCase();
var textB = b.name.toUpperCase();
installed.sort((a, b) => {
let textA = a.name.toUpperCase();
let textB = b.name.toUpperCase();
return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
});
resolve(instaled);
resolve(installed);
})
.catch((error) => {
status.status = "error";
@ -92,14 +91,16 @@ function getAddonList() {
function getAddonToBackup() {
return new Promise((resolve, reject) => {
let excluded_addon = settingsTools.getSettings().exclude_addon;
getAddonList().then((all_addon)=>{
getAddonList()
.then((all_addon) => {
let slugs = [];
for (let i in all_addon) {
if (!excluded_addon.includes(all_addon[i].slug))
slugs.push(all_addon[i].slug)
}
resolve(slugs)
}).catch(()=>reject());
})
.catch(() => reject());
});
}
@ -189,9 +190,10 @@ function downloadSnapshot(id) {
};
pipeline(
got.stream.get(`http://hassio/snapshots/${id}/download`, option).on("downloadProgress", (e) => {
got.stream.get(`http://hassio/snapshots/${id}/download`, option)
.on("downloadProgress", (e) => {
let percent = Math.round(e.percent * 100) / 100;
if (status.progress != percent) {
if (status.progress !== percent) {
status.progress = percent;
statusTools.setStatus(status);
}
@ -238,12 +240,8 @@ function dellSnap(id) {
};
got.post(`http://hassio/snapshots/${id}/remove`, option)
.then((result) => {
resolve();
})
.catch((error) => {
reject();
});
.then(() => resolve())
.catch(() => reject());
})
.catch(() => {
reject();
@ -264,9 +262,7 @@ function checkSnap(id) {
logger.debug(`Snapshot size: ${result.body.data.size}`);
resolve();
})
.catch((error) => {
reject();
});
.catch(() => reject());
});
}
@ -322,7 +318,8 @@ function clean() {
}
snaps.sort((a, b) => {
if (moment(a.date).isBefore(moment(b.date))) return 1;
else return -1;
else
return -1;
});
let toDel = snaps.slice(limit);
for (let i in toDel) {
@ -363,7 +360,7 @@ function uploadSnapshot(path) {
.post(`http://hassio/snapshots/new/upload`, options)
.on("uploadProgress", (e) => {
let percent = e.percent;
if (status.progress != percent) {
if (status.progress !== percent) {
status.progress = percent;
statusTools.setStatus(status);
}
@ -372,7 +369,7 @@ function uploadSnapshot(path) {
}
})
.on("response", (res) => {
if (res.statusCode != 200) {
if (res.statusCode !== 200) {
status.status = "error";
status.error_code = 4;
status.message = `Fail to upload backup to home assitant (Status code: ${res.statusCode})!`;

View File

@ -36,8 +36,7 @@ function check(conf, fallback = false){
conf.cron_hour = "00:00",
conf.cron_weekday = "0",
conf.cron_month_day = "1"
}
else {
} else {
logger.error("Bad value for cron settings")
return false;
}
@ -46,8 +45,7 @@ function check(conf, fallback = false){
if (fallback) {
logger.warn("Bad value for 'name_template', fallback to default ")
conf.name_template = "{type}-{ha_version}-{date}_{hour}"
}
else {
} else {
logger.error("Bad value for 'name_template'")
return false;
}
@ -57,8 +55,7 @@ function check(conf, fallback = false){
if (fallback) {
logger.warn("Bad value for 'auto_clean_local_keep', fallback to 5 ")
conf.auto_clean_local_keep = "5"
}
else {
} else {
logger.error("Bad value for 'auto_clean_local_keep'")
return false;
}
@ -67,8 +64,7 @@ function check(conf, fallback = false){
if (fallback) {
logger.warn("Bad value for 'auto_clean_backup_keep', fallback to 5 ")
conf.auto_clean_backup_keep = "5"
}
else {
} else {
logger.error("Bad value for 'auto_clean_backup_keep'")
return false;
}
@ -77,8 +73,7 @@ function check(conf, fallback = false){
if (fallback) {
logger.warn("Bad value for 'auto_clean_local', fallback to false ")
conf.auto_clean_local = "false"
}
else {
} else {
logger.error("Bad value for 'auto_clean_local'")
return false;
}
@ -87,8 +82,7 @@ function check(conf, fallback = false){
if (fallback) {
logger.warn("Bad value for 'auto_clean_backup', fallback to false ")
conf.auto_clean_backup = "false"
}
else {
} else {
logger.error("Bad value for 'auto_clean_backup'")
return false;
}
@ -97,8 +91,7 @@ function check(conf, fallback = false){
if (fallback) {
logger.warn("Bad value for 'exclude_addon', fallback to [] ")
conf.exclude_addon = []
}
else {
} else {
logger.error("Bad value for 'exclude_addon'")
return false;
}
@ -107,8 +100,7 @@ function check(conf, fallback = false){
if (fallback) {
logger.warn("Bad value for 'exclude_folder', fallback to [] ")
conf.exclude_folder = []
}
else {
} else {
logger.error("Bad value for 'exclude_folder'")
return false;
}

View File

@ -36,7 +36,11 @@ class WebdavTools {
this.password = password;
let agent_option = ssl === "true" ? { rejectUnauthorized: accept_selfsigned_cert === "false" } : {};
try {
this.client = createClient(this.baseUrl, { username: username, password: password, httpsAgent: new https.Agent(agent_option) });
this.client = createClient(this.baseUrl, {
username: username,
password: password,
httpsAgent: new https.Agent(agent_option)
});
this.client
.getDirectoryContents("/")
@ -72,6 +76,7 @@ class WebdavTools {
}
});
}
async __createRoot() {
let root_splited = this.getConf().back_dir.split("/").splice(1);
let path = "/";
@ -91,18 +96,17 @@ class WebdavTools {
initFolder() {
return new Promise((resolve) => {
this.__createRoot()
.catch((err) => {
this.__createRoot().catch((err) => {
logger.error(err);
}).then(() => {
this.client.createDirectory(this.getConf().back_dir + pathTools.auto)
.catch(() => {
})
.then(() => {
this.client
.createDirectory(this.getConf().back_dir + pathTools.auto)
.catch(() => {})
.then(() => {
this.client
.createDirectory(this.getConf().back_dir + pathTools.manual)
.catch(() => {})
.catch(() => {
})
.then(() => {
resolve();
});
@ -110,6 +114,7 @@ class WebdavTools {
});
});
}
/**
* Check if theh webdav config is valid, if yes, start init of webdav client
*/
@ -177,7 +182,8 @@ class WebdavTools {
if (fs.existsSync(configPath)) {
let content = JSON.parse(fs.readFileSync(configPath));
return content;
} else return null;
} else
return null;
}
setConf(conf) {
@ -194,7 +200,8 @@ class WebdavTools {
.catch((err) => {
reject(err);
});
} else this._startUpload(id, path);
} else
this._startUpload(id, path);
});
}
@ -237,7 +244,7 @@ class WebdavTools {
}
})
.on("response", (res) => {
if (res.statusCode != 201 && res.statusCode != 204) {
if (res.statusCode !== 201 && res.statusCode !== 204) {
status.status = "error";
status.error_code = 4;
status.message = `Fail to upload snapshot to nextcloud (Status code: ${res.statusCode})!`;
@ -255,11 +262,11 @@ class WebdavTools {
statusTools.setStatus(status);
cleanTempFolder();
let autoCleanCloud = settingsTools.getSettings().auto_clean_backup;
if (autoCleanCloud != null && autoCleanCloud == "true") {
if (autoCleanCloud != null && autoCleanCloud === "true") {
this.clean().catch();
}
let autoCleanlocal = settingsTools.getSettings().auto_clean_local;
if (autoCleanlocal != null && autoCleanlocal == "true") {
if (autoCleanlocal != null && autoCleanlocal === "true") {
hassioApiTools.clean();
}
resolve();
@ -296,6 +303,7 @@ class WebdavTools {
.catch(() => reject());
});
}
_startDownload(path) {
return new Promise((resolve, reject) => {
let status = statusTools.getStatus();
@ -321,23 +329,22 @@ class WebdavTools {
logger.debug(`...URI: ${encodeURI(this.baseUrl.replace(this.host, 'host.hiden') + path)}`);
logger.debug(`...rejectUnauthorized: ${options["https"]["rejectUnauthorized"]}`);
pipeline(
got.stream.get(encodeURI(this.baseUrl + path), options).on("downloadProgress", (e) => {
got.stream.get(encodeURI(this.baseUrl + path), options)
.on("downloadProgress", (e) => {
let percent = Math.round(e.percent * 100) / 100;
if (status.progress != percent) {
if (status.progress !== percent) {
status.progress = percent;
statusTools.setStatus(status);
}
}),
stream
)
.then((res) => {
).then((res) => {
logger.info("Download success !");
status.progress = 1;
statusTools.setStatus(status);
logger.debug("Backup dl size : " + fs.statSync(tmpFile).size / 1024 / 1024);
resolve(tmpFile);
})
.catch((err) => {
}).catch((err) => {
if (fs.existsSync(tmpFile)) fs.unlinkSync(tmpFile);
status.status = "error";
status.message = "Fail to download Hassio snapshot (" + err.message + ")";
@ -358,12 +365,8 @@ class WebdavTools {
}
this.client
.getDirectoryContents(path)
.then((contents) => {
resolve(contents);
})
.catch((error) => {
reject(error);
});
.then((contents) => resolve(contents))
.catch((error) => reject(error));
});
}
@ -378,8 +381,10 @@ class WebdavTools {
return;
}
contents.sort((a, b) => {
if (moment(a.lastmod).isBefore(moment(b.lastmod))) return 1;
else return -1;
if (moment(a.lastmod).isBefore(moment(b.lastmod)))
return 1;
else
return -1;
});
let toDel = contents.slice(limit);
@ -403,11 +408,13 @@ class WebdavTools {
function cleanTempFolder() {
fs.readdir("./temp/", (err, files) => {
if (err) throw err;
if (err)
throw err;
for (const file of files) {
fs.unlink(path.join("./temp/", file), (err) => {
if (err) throw err;
if (err)
throw err;
});
}
});