:pecil2: NodeJs code clean and refractory

This commit is contained in:
SebClem 2021-01-09 17:09:44 +01:00
parent 8e01daf953
commit f4e62a4a14
7 changed files with 179 additions and 188 deletions

View File

@ -36,7 +36,6 @@ app.use("/api", apiRouter);
// Boootstrap JS Files
app.use('/js/bootstrap.min.js', express.static(path.join(__dirname, '/node_modules/bootstrap/dist/js/bootstrap.min.js')))
// Fontawesome Files
app.use('/css/fa-all.min.css', express.static(path.join(__dirname, '/node_modules/@fortawesome/fontawesome-free/css/all.min.css')))
app.use('/webfonts/', express.static(path.join(__dirname, '/node_modules/@fortawesome/fontawesome-free/webfonts')))
@ -104,4 +103,6 @@ settingTool.check(settingTool.getSettings(), true);
const cronTools = require("./tools/cronTools");
cronTools.startCron();
module.exports = app;

View File

@ -12,7 +12,6 @@ const humanFileSize = require("../tools/toolbox").humanFileSize;
const cronTools = require("../tools/cronTools");
const logger = require("../config/winston");
const { add } = require("../config/winston");
router.get("/status", (req, res, next) => {
cronTools.updatetNextDate();
@ -21,8 +20,8 @@ router.get("/status", (req, res, next) => {
});
router.get("/formated-local-snap", function (req, res, next) {
hassioApiTools.getSnapshots().then(
(snaps) => {
hassioApiTools.getSnapshots()
.then((snaps) => {
snaps.sort((a, b) => {
if (moment(a.date).isBefore(moment(b.date))) {
return 1;
@ -32,21 +31,21 @@ router.get("/formated-local-snap", function (req, res, next) {
});
res.render("localSnaps", { snaps: snaps, moment: moment });
},
(err) => {
logger.error(err);
res.status(500);
res.send("");
}
})
.catch((err) => {
logger.error(err);
res.status(500);
res.send("");
}
);
});
router.get("/formated-backup-manual", function (req, res, next) {
if(webdav.getConf() == null){
res.send("");
return;
}
webdav
});
router.get("/formated-backup-manual", function (req, res, next) {
if (webdav.getConf() == null) {
res.send("");
return;
}
webdav
.getFolderContent(webdav.getConf().back_dir + pathTools.manual)
.then((contents) => {
contents.sort((a, b) => {
@ -54,7 +53,7 @@ router.get("/formated-local-snap", function (req, res, next) {
else return -1;
});
//TODO Remove this when bug is fixed, etag contain '"' at start and end ?
for(let backup of contents){
for (let backup of contents) {
backup.etag = backup.etag.replace(/"/g, '');
}
res.render("backupSnaps", { backups: contents, moment: moment, humanFileSize: humanFileSize });
@ -62,15 +61,15 @@ router.get("/formated-local-snap", function (req, res, next) {
.catch(() => {
res.send("");
});
});
router.get("/formated-backup-auto", function (req, res, next) {
if(webdav.getConf() == null){
res.send("");
return;
}
let url = webdav.getConf().back_dir + pathTools.auto;
webdav
});
router.get("/formated-backup-auto", function (req, res, next) {
if (webdav.getConf() == null) {
res.send("");
return;
}
let url = webdav.getConf().back_dir + pathTools.auto;
webdav
.getFolderContent(url)
.then((contents) => {
contents.sort((a, b) => {
@ -78,7 +77,7 @@ router.get("/formated-local-snap", function (req, res, next) {
else return -1;
});
//TODO Remove this when bug is fixed, etag contain '"' at start and end ?
for(let backup of contents){
for (let backup of contents) {
backup.etag = backup.etag.replace(/"/g, '');
}
res.render("backupSnaps", { backups: contents, moment: moment, humanFileSize: humanFileSize });
@ -86,13 +85,13 @@ router.get("/formated-local-snap", function (req, res, next) {
.catch(() => {
res.send("");
});
});
router.post("/nextcloud-settings", function (req, res, next) {
let settings = req.body;
if (settings.ssl != null && settings.host != null && settings.host != "" && settings.username != null && settings.password != null) {
webdav.setConf(settings);
webdav
});
router.post("/nextcloud-settings", function (req, res, next) {
let settings = req.body;
if (settings.ssl != null && settings.host != null && settings.host !== "" && settings.username != null && settings.password != null) {
webdav.setConf(settings);
webdav
.confIsValid()
.then(() => {
res.status(201);
@ -102,36 +101,36 @@ router.get("/formated-local-snap", function (req, res, next) {
res.status(406);
res.json({ message: err });
});
} else {
res.status(400);
res.send();
}
});
router.get("/nextcloud-settings", function (req, res, next) {
let conf = webdav.getConf();
if (conf == null) {
res.status(404);
res.send();
} else {
res.json(conf);
}
});
router.post("/manual-backup", function (req, res, next) {
let id = req.query.id;
let name = req.query.name;
let status = statusTools.getStatus();
if (status.status == "creating" && status.status == "upload" && status.status == "download") {
res.status(503);
res.send();
return;
}
hassioApiTools
} else {
res.status(400);
res.send();
}
});
router.get("/nextcloud-settings", function (req, res, next) {
let conf = webdav.getConf();
if (conf == null) {
res.status(404);
res.send();
} else {
res.json(conf);
}
});
router.post("/manual-backup", function (req, res, next) {
let id = req.query.id;
let name = req.query.name;
let status = statusTools.getStatus();
if (status.status === "creating" && status.status === "upload" && status.status === "download") {
res.status(503);
res.send();
return;
}
hassioApiTools
.downloadSnapshot(id)
.then(() => {
webdav.uploadFile(id, webdav.getConf().back_dir + pathTools.manual + name + ".tar");
webdav.uploadFile(id, webdav.getConf().back_dir + pathTools.manual + name + ".tar").catch();
res.status(201);
res.send();
})
@ -139,61 +138,64 @@ router.get("/formated-local-snap", function (req, res, next) {
res.status(500);
res.send();
});
});
router.post("/new-backup", function (req, res, next) {
let status = statusTools.getStatus();
if (status.status === "creating" && status.status === "upload" && status.status === "download") {
res.status(503);
res.send();
return;
}
hassioApiTools
});
router.post("/new-backup", function (req, res, next) {
let status = statusTools.getStatus();
if (status.status === "creating" && status.status === "upload" && status.status === "download") {
res.status(503);
res.send();
return;
}
hassioApiTools
.getVersion()
.then((version) => {
let name = settingsTools.getFormatedName(true, version);
hassioApiTools
.createNewBackup(name)
.then((id) => {
hassioApiTools
.downloadSnapshot(id)
.then(() => {
webdav.uploadFile(id, webdav.getConf().back_dir + pathTools.manual + name + ".tar");
.createNewBackup(name)
.then((id) => {
hassioApiTools
.downloadSnapshot(id)
.then(() => {
webdav.uploadFile(id, webdav.getConf().back_dir + pathTools.manual + name + ".tar").catch();
})
.catch(() => {
});
})
.catch(() => {});
})
.catch(() => {});
.catch(() => {
});
})
.catch(() => {});
res.status(201);
.catch(() => {
});
res.status(201);
res.send();
});
router.get("/backup-settings", function (req, res, next) {
hassioApiTools.getAddonList().then((addonList) => {
let data = {};
data['folders'] = hassioApiTools.getFolderList();
data['addonList'] = addonList;
data['settings'] = settingsTools.getSettings();
res.send(data);
})
});
router.post("/backup-settings", function (req, res, next) {
if (settingsTools.check(req.body)) {
settingsTools.setSettings(req.body);
cronTools.startCron();
res.send();
});
router.get("/backup-settings", function (req, res, next) {
hassioApiTools.getAddonList().then((addonList)=>{
let data = {};
data['folders'] = hassioApiTools.getFolderList();
data['addonList'] = addonList;
data['settings'] = settingsTools.getSettings();
res.send(data);
})
});
router.post("/backup-settings", function (req, res, next) {
if (settingsTools.check(req.body)) {
settingsTools.setSettings(req.body);
cronTools.startCron();
res.send();
} else {
res.status(400);
res.send();
}
});
router.post("/clean-now", function (req, res, next) {
webdav
} else {
res.status(400);
res.send();
}
});
router.post("/clean-now", function (req, res, next) {
webdav
.clean()
.then(() => {
hassioApiTools.clean().catch();
@ -201,22 +203,22 @@ router.get("/formated-local-snap", function (req, res, next) {
.catch(() => {
hassioApiTools.clean().catch();
});
res.status(201);
res.status(201);
res.send();
});
router.post("/restore", function (req, res, next) {
if (req.body["path"] != null) {
webdav.downloadFile(req.body["path"]).then((path) => {
hassioApiTools.uploadSnapshot(path).catch();
});
res.status(200);
res.send();
});
router.post("/restore", function (req, res, next) {
if (req.body["path"] != null) {
webdav.downloadFile(req.body["path"]).then((path) => {
hassioApiTools.uploadSnapshot(path);
});
res.status(200);
res.send();
} else {
res.status(400);
res.send();
}
});
module.exports = router;
} else {
res.status(400);
res.send();
}
});
module.exports = router;

View File

@ -16,7 +16,7 @@ function startCron() {
function updatetNextDate() {
let cronContainer = new Singleton().getInstance();
cronContainer.updatetNextDate();
cronContainer.updateNextDate();
}
class CronContainer {
@ -34,7 +34,7 @@ class CronContainer {
this.cronClean.start();
}
if (this.cronJob != null) {
logger.info("Stoping Cron...");
logger.info("Stopping Cron...");
this.cronJob.stop();
this.cronJob = null;
}
@ -68,10 +68,10 @@ class CronContainer {
logger.info("Starting Cron...");
this.cronJob = new CronJob(cronStr, this._createBackup, null, false, Intl.DateTimeFormat().resolvedOptions().timeZone);
this.cronJob.start();
this.updatetNextDate();
this.updateNextDate();
}
updatetNextDate() {
updateNextDate() {
let date;
if (this.cronJob == null) date = "Not configured";
else date = this.cronJob.nextDate().format("MMM D, YYYY HH:mm");
@ -94,28 +94,20 @@ class CronContainer {
hassioApiTools
.downloadSnapshot(id)
.then(() => {
webdav.uploadFile(id, webdav.getConf().back_dir + pathTools.auto + name + ".tar");
})
.catch(() => {
});
})
.catch(() => {
});
})
.catch(() => {
});
webdav.uploadFile(id, webdav.getConf().back_dir + pathTools.auto + name + ".tar").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

@ -64,8 +64,7 @@ function getAddonList() {
}
let addons = result.body.data.addons;
let installed = [];
for (let index in addons) {
let current = addons[index];
for (let current of addons) {
if (current.installed === true) {
installed.push({ slug: current.slug, name: current.name })
}
@ -94,9 +93,9 @@ function getAddonToBackup() {
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)
for (let addon of all_addon) {
if (!excluded_addon.includes(addon.slug))
slugs.push(addon.slug)
}
resolve(slugs)
})
@ -109,7 +108,6 @@ function getFolderList() {
{
name: "Home Assistant configuration",
slug: "homeassistant"
},
{
name: "SSL",
@ -134,9 +132,9 @@ function getFolderToBackup() {
let excluded_folder = settingsTools.getSettings().exclude_folder;
let all_folder = getFolderList()
let slugs = [];
for (let i in all_folder) {
if (!excluded_folder.includes(all_folder[i].slug))
slugs.push(all_folder[i].slug)
for (let folder of all_folder) {
if (!excluded_folder.includes(folder.slug))
slugs.push(folder.slug)
}
return slugs;
}
@ -322,8 +320,8 @@ function clean() {
return -1;
});
let toDel = snaps.slice(limit);
for (let i in toDel) {
await dellSnap(toDel[i].slug);
for (let i of toDel) {
await dellSnap(i.slug);
}
logger.info("Local clean done.");
resolve();
@ -372,7 +370,7 @@ function uploadSnapshot(path) {
if (res.statusCode !== 200) {
status.status = "error";
status.error_code = 4;
status.message = `Fail to upload backup to home assitant (Status code: ${res.statusCode})!`;
status.message = `Fail to upload backup to home assistant (Status code: ${res.statusCode})!`;
statusTools.setStatus(status);
logger.error(status.message);
fs.unlinkSync(path);

View File

@ -141,8 +141,7 @@ function getSettings() {
if (!fs.existsSync(settingsPath)) {
return {};
} else {
let rawSettings = fs.readFileSync(settingsPath);
return JSON.parse(rawSettings);
return JSON.parse(fs.readFileSync(settingsPath).toString());
}
}

View File

@ -25,9 +25,7 @@ function getStatus() {
if (!fs.existsSync(statusPath)) {
fs.writeFileSync(statusPath, JSON.stringify(baseStatus));
}
let content = fs.readFileSync(statusPath);
return JSON.parse(content);
return JSON.parse(fs.readFileSync(statusPath).toString());
}
function setStatus(state) {

View File

@ -30,7 +30,7 @@ class WebdavTools {
return new Promise((resolve, reject) => {
this.host = host;
let status = statusTools.getStatus();
logger.info("Initilizing and checking webdav client...");
logger.info("Initializing and checking webdav client...");
this.baseUrl = (ssl === "true" ? "https" : "http") + "://" + host + endpoint;
this.username = username;
this.password = password;
@ -45,7 +45,7 @@ class WebdavTools {
this.client
.getDirectoryContents("/")
.then(() => {
if (status.error_code == 3) {
if (status.error_code === 3) {
status.status = "idle";
status.message = null;
status.error_code = null;
@ -57,37 +57,37 @@ class WebdavTools {
});
})
.catch((error) => {
status.status = "error";
status.error_code = 3;
status.message = "Can't connect to Nextcloud (" + error + ") !";
statusTools.setStatus(status);
this.__cant_connect_status(error);
this.client = null;
logger.error("Can't connect to Nextcloud (" + error + ") !");
reject("Can't connect to Nextcloud (" + error + ") !");
});
} catch (err) {
status.status = "error";
status.error_code = 3;
status.message = "Can't connect to Nextcloud (" + err + ") !";
statusTools.setStatus(status);
this.__cant_connect_status(err);
this.client = null;
logger.error("Can't connect to Nextcloud (" + err + ") !");
reject("Can't connect to Nextcloud (" + err + ") !");
}
});
}
__cant_connect_status(err){
let status = statusTools.getStatus();
status.status = "error";
status.error_code = 3;
status.message = "Can't connect to Nextcloud (" + err + ") !";
statusTools.setStatus(status);
logger.error("Can't connect to Nextcloud (" + err + ") !");
}
async __createRoot() {
let root_splited = this.getConf().back_dir.split("/").splice(1);
let path = "/";
for (let elem of root_splited) {
if (elem != "") {
if (elem !== "") {
path = path + elem + "/";
try {
await this.client.createDirectory(path);
logger.debug(`Path ${path} created.`);
} catch (error) {
if (error.response.status == 405) logger.debug(`Path ${path} already exist.`);
if (error.response.status === 405) logger.debug(`Path ${path} already exist.`);
else logger.error(error);
}
}
@ -124,14 +124,14 @@ class WebdavTools {
let conf = this.getConf();
if (conf !== null) {
if (conf.ssl !== null && conf.host !== null && conf.username !== null && conf.password !== null) {
if (status.error_code == 2) {
if (status.error_code === 2) {
status.status = "idle";
status.message = null;
status.error_code = null;
statusTools.setStatus(status);
}
// Check if self_signed option exist
if (conf.self_signed == null || conf.self_signed == "") {
if (conf.self_signed == null || conf.self_signed === "") {
conf.self_signed = "false";
this.setConf(conf);
}
@ -151,7 +151,7 @@ class WebdavTools {
reject("Nextcloud config invalid !");
}
if (conf.back_dir == null || conf.back_dir == "") {
if (conf.back_dir == null || conf.back_dir === "") {
logger.info("Backup dir is null, initializing it.");
conf.back_dir = pathTools.default_root;
this.setConf(conf);
@ -180,8 +180,7 @@ class WebdavTools {
getConf() {
if (fs.existsSync(configPath)) {
let content = JSON.parse(fs.readFileSync(configPath));
return content;
return JSON.parse(fs.readFileSync(configPath).toString());
} else
return null;
}
@ -195,13 +194,13 @@ class WebdavTools {
if (this.client == null) {
this.confIsValid()
.then(() => {
this._startUpload(id, path);
this._startUpload(id, path).catch((err) => reject(err));
})
.catch((err) => {
reject(err);
});
} else
this._startUpload(id, path);
this._startUpload(id, path).catch((err) => reject(err));
});
}
@ -235,7 +234,7 @@ class WebdavTools {
.put(encodeURI(this.baseUrl + path), options)
.on("uploadProgress", (e) => {
let percent = e.percent;
if (status.progress != percent) {
if (status.progress !== percent) {
status.progress = percent;
statusTools.setStatus(status);
}
@ -267,7 +266,7 @@ class WebdavTools {
}
let autoCleanlocal = settingsTools.getSettings().auto_clean_local;
if (autoCleanlocal != null && autoCleanlocal === "true") {
hassioApiTools.clean();
hassioApiTools.clean().catch();
}
resolve();
}
@ -314,7 +313,8 @@ class WebdavTools {
statusTools.setStatus(status);
logger.info("Downloading backup...");
if (!fs.existsSync("./temp/")) fs.mkdirSync("./temp/");
if (!fs.existsSync("./temp/"))
fs.mkdirSync("./temp/");
let tmpFile = `./temp/restore_${moment().format("MMM-DD-YYYY_HH_mm")}.tar`;
let stream = fs.createWriteStream(tmpFile);
let conf = this.getConf();
@ -395,6 +395,7 @@ class WebdavTools {
resolve();
})
.catch((error) => {
let status = statusTools.getStatus();
status.status = "error";
status.error_code = 6;
status.message = "Fail to clean Nexcloud (" + error + ") !";