From d85c04755e71f3d63ed4d03b1b0f5d98cac689fe Mon Sep 17 00:00:00 2001 From: SebClem Date: Thu, 7 Jan 2021 16:37:30 +0100 Subject: [PATCH] :pencil2: Some code clean... --- .../opt/nextcloud_backup/config/winston.js | 3 +- .../opt/nextcloud_backup/tools/cronTools.js | 23 +- .../nextcloud_backup/tools/hassioApiTools.js | 425 +++++++++--------- .../opt/nextcloud_backup/tools/pathTools.js | 2 +- .../nextcloud_backup/tools/settingsTools.js | 86 ++-- .../opt/nextcloud_backup/tools/webdavTools.js | 123 ++--- 6 files changed, 329 insertions(+), 333 deletions(-) diff --git a/nextcloud_backup/rootfs/opt/nextcloud_backup/config/winston.js b/nextcloud_backup/rootfs/opt/nextcloud_backup/config/winston.js index f78f6f2..42e0547 100644 --- a/nextcloud_backup/rootfs/opt/nextcloud_backup/config/winston.js +++ b/nextcloud_backup/rootfs/opt/nextcloud_backup/config/winston.js @@ -1,8 +1,7 @@ -const appRoot = require("app-root-path"); const winston = require("winston"); const logger = winston.createLogger({ - level: process.env.LOG_LEVEL || 'info' , + level: process.env.LOG_LEVEL || 'info', format: winston.format.combine( winston.format.timestamp({ format: "YYYY-MM-DD HH:mm:ss", diff --git a/nextcloud_backup/rootfs/opt/nextcloud_backup/tools/cronTools.js b/nextcloud_backup/rootfs/opt/nextcloud_backup/tools/cronTools.js index 21d6179..9a30241 100644 --- a/nextcloud_backup/rootfs/opt/nextcloud_backup/tools/cronTools.js +++ b/nextcloud_backup/rootfs/opt/nextcloud_backup/tools/cronTools.js @@ -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(() => { + }); } } } diff --git a/nextcloud_backup/rootfs/opt/nextcloud_backup/tools/hassioApiTools.js b/nextcloud_backup/rootfs/opt/nextcloud_backup/tools/hassioApiTools.js index 85c3cb8..a4494a6 100644 --- a/nextcloud_backup/rootfs/opt/nextcloud_backup/tools/hassioApiTools.js +++ b/nextcloud_backup/rootfs/opt/nextcloud_backup/tools/hassioApiTools.js @@ -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; @@ -23,26 +22,26 @@ function getVersion() { headers: { "X-HASSIO-KEY": token }, responseType: "json", }; - + got("http://hassio/core/info", option) - .then((result) => { - if (status.error_code === 1) { - status.status = "idle"; - status.message = null; - status.error_code = null; + .then((result) => { + if (status.error_code === 1) { + status.status = "idle"; + status.message = null; + status.error_code = null; + statusTools.setStatus(status); + } + let version = result.body.data.version; + resolve(version); + }) + .catch((error) => { + status.status = "error"; + status.message = "Fail to fetch HA Version (" + error.message + ")"; + status.error_code = 1; statusTools.setStatus(status); - } - let version = result.body.data.version; - resolve(version); - }) - .catch((error) => { - status.status = "error"; - status.message = "Fail to fetch HA Version (" + error.message + ")"; - status.error_code = 1; - statusTools.setStatus(status); - logger.error(status.message); - reject(error.message); - }); + logger.error(status.message); + reject(error.message); + }); }); } @@ -54,61 +53,63 @@ function getAddonList() { headers: { "X-HASSIO-KEY": token }, responseType: "json", }; - + got("http://hassio/addons", option) - .then((result) => { - if (status.error_code === 1) { - status.status = "idle"; - status.message = null; - status.error_code = null; + .then((result) => { + if (status.error_code === 1) { + status.status = "idle"; + status.message = null; + status.error_code = null; + statusTools.setStatus(status); + } + let addons = result.body.data.addons; + let installed = []; + for (let index in addons) { + let current = addons[index]; + if (current.installed === true) { + installed.push({ slug: current.slug, name: current.name }) + } + } + installed.sort((a, b) => { + let textA = a.name.toUpperCase(); + let textB = b.name.toUpperCase(); + return (textA < textB) ? -1 : (textA > textB) ? 1 : 0; + }); + resolve(installed); + }) + .catch((error) => { + status.status = "error"; + status.message = "Fail to fetch addons list (" + error.message + ")"; + status.error_code = 1; statusTools.setStatus(status); - } - let addons = result.body.data.addons; - let instaled = []; - for(let index in addons){ - let current = addons[index]; - if(current.installed == true){ - instaled.push({slug:current.slug, name: current.name}) - } - } - instaled.sort((a,b)=>{ - var textA = a.name.toUpperCase(); - var textB = b.name.toUpperCase(); - return (textA < textB) ? -1 : (textA > textB) ? 1 : 0; + logger.error(status.message); + reject(error.message); }); - resolve(instaled); - }) - .catch((error) => { - status.status = "error"; - status.message = "Fail to fetch addons list (" + error.message + ")"; - status.error_code = 1; - statusTools.setStatus(status); - logger.error(status.message); - reject(error.message); - }); }); } -function getAddonToBackup(){ +function getAddonToBackup() { return new Promise((resolve, reject) => { let excluded_addon = settingsTools.getSettings().exclude_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()); - }); + 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()); + }); } -function getFolderList(){ +function getFolderList() { return [ { name: "Homme Assistant configuration", slug: "homeassistant" - + }, { name: "SSL", @@ -125,16 +126,16 @@ function getFolderList(){ { name: "Local add-ons", slug: "addons/local" - } + } ] } -function getFolderToBackup(){ +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)) + for (let i in all_folder) { + if (!excluded_folder.includes(all_folder[i].slug)) slugs.push(all_folder[i].slug) } return slugs; @@ -148,26 +149,26 @@ function getSnapshots() { headers: { "X-HASSIO-KEY": token }, responseType: "json", }; - + got("http://hassio/snapshots", option) - .then((result) => { - if (status.error_code === 1) { - status.status = "idle"; - status.message = null; - status.error_code = null; + .then((result) => { + if (status.error_code === 1) { + status.status = "idle"; + status.message = null; + status.error_code = null; + statusTools.setStatus(status); + } + let snaps = result.body.data.snapshots; + resolve(snaps); + }) + .catch((error) => { + status.status = "error"; + status.message = "Fail to fetch Hassio snapshots (" + error.message + ")"; + status.error_code = 1; statusTools.setStatus(status); - } - let snaps = result.body.data.snapshots; - resolve(snaps); - }) - .catch((error) => { - status.status = "error"; - status.message = "Fail to fetch Hassio snapshots (" + error.message + ")"; - status.error_code = 1; - statusTools.setStatus(status); - logger.error(status.message); - reject(error.message); - }); + logger.error(status.message); + reject(error.message); + }); }); } @@ -180,74 +181,71 @@ function downloadSnapshot(id) { let token = process.env.HASSIO_TOKEN; let status = statusTools.getStatus(); checkSnap(id) - .then(() => { - status.status = "download"; - status.progress = 0; - statusTools.setStatus(status); - let option = { - headers: { "X-HASSIO-KEY": token }, - }; - - pipeline( - got.stream.get(`http://hassio/snapshots/${id}/download`, option).on("downloadProgress", (e) => { - let percent = Math.round(e.percent * 100) / 100; - if (status.progress != percent) { - status.progress = percent; - statusTools.setStatus(status); - } - }), - stream - ) - .then((res) => { - logger.info("Download success !"); - status.progress = 1; + .then(() => { + status.status = "download"; + status.progress = 0; statusTools.setStatus(status); - logger.debug("Snapshot dl size : " + fs.statSync(tmp_file).size / 1024 / 1024); - resolve(); + let option = { + headers: { "X-HASSIO-KEY": token }, + }; + + pipeline( + got.stream.get(`http://hassio/snapshots/${id}/download`, option) + .on("downloadProgress", (e) => { + let percent = Math.round(e.percent * 100) / 100; + if (status.progress !== percent) { + status.progress = percent; + statusTools.setStatus(status); + } + }), + stream + ) + .then((res) => { + logger.info("Download success !"); + status.progress = 1; + statusTools.setStatus(status); + logger.debug("Snapshot dl size : " + fs.statSync(tmp_file).size / 1024 / 1024); + resolve(); + }) + .catch((err) => { + fs.unlinkSync(tmp_file); + status.status = "error"; + status.message = "Fail to download Hassio snapshot (" + err.message + ")"; + status.error_code = 7; + statusTools.setStatus(status); + logger.error(status.message); + reject(err.message); + }); }) .catch((err) => { - fs.unlinkSync(tmp_file); status.status = "error"; - status.message = "Fail to download Hassio snapshot (" + err.message + ")"; + status.message = "Fail to download Hassio snapshot. Not found ?"; status.error_code = 7; statusTools.setStatus(status); logger.error(status.message); - reject(err.message); + reject(); }); - }) - .catch((err) => { - status.status = "error"; - status.message = "Fail to download Hassio snapshot. Not found ?"; - status.error_code = 7; - statusTools.setStatus(status); - logger.error(status.message); - reject(); - }); }); } function dellSnap(id) { return new Promise((resolve, reject) => { checkSnap(id) - .then(() => { - let token = process.env.HASSIO_TOKEN; - - let option = { - headers: { "X-HASSIO-KEY": token }, - responseType: "json", - }; - - got.post(`http://hassio/snapshots/${id}/remove`, option) - .then((result) => { - resolve(); + .then(() => { + let token = process.env.HASSIO_TOKEN; + + let option = { + headers: { "X-HASSIO-KEY": token }, + responseType: "json", + }; + + got.post(`http://hassio/snapshots/${id}/remove`, option) + .then(() => resolve()) + .catch(() => reject()); }) - .catch((error) => { + .catch(() => { reject(); }); - }) - .catch(() => { - reject(); - }); }); } @@ -258,15 +256,13 @@ function checkSnap(id) { headers: { "X-HASSIO-KEY": token }, responseType: "json", }; - + got(`http://hassio/snapshots/${id}/info`, option) - .then((result) => { - logger.debug(`Snapshot size: ${result.body.data.size}`); - resolve(); - }) - .catch((error) => { - reject(); - }); + .then((result) => { + logger.debug(`Snapshot size: ${result.body.data.size}`); + resolve(); + }) + .catch(() => reject()); }); } @@ -278,35 +274,35 @@ function createNewBackup(name) { statusTools.setStatus(status); logger.info("Creating new snapshot..."); let token = process.env.HASSIO_TOKEN; - getAddonToBackup().then((addons)=>{ + getAddonToBackup().then((addons) => { let folders = getFolderToBackup(); let option = { headers: { "X-HASSIO-KEY": token }, responseType: "json", timeout: create_snap_timeout, - json: { + json: { name: name, addons: addons, folders: folders - }, + }, }; - + got.post(`http://hassio/snapshots/new/partial`, option) - .then((result) => { - logger.info(`Snapshot created with id ${result.body.data.slug}`); - resolve(result.body.data.slug); - }) - .catch((error) => { - status.status = "error"; - status.message = "Can't create new snapshot (" + error.message + ")"; - status.error_code = 5; - statusTools.setStatus(status); - logger.error(status.message); - reject(status.message); - }); - + .then((result) => { + logger.info(`Snapshot created with id ${result.body.data.slug}`); + resolve(result.body.data.slug); + }) + .catch((error) => { + status.status = "error"; + status.message = "Can't create new snapshot (" + error.message + ")"; + status.error_code = 5; + statusTools.setStatus(status); + logger.error(status.message); + reject(status.message); + }); + }).catch(reject); - + }); } @@ -315,25 +311,26 @@ function clean() { if (limit == null) limit = 5; return new Promise((resolve, reject) => { getSnapshots() - .then(async (snaps) => { - if (snaps.length < limit) { + .then(async (snaps) => { + if (snaps.length < limit) { + resolve(); + return; + } + snaps.sort((a, b) => { + if (moment(a.date).isBefore(moment(b.date))) return 1; + else + return -1; + }); + let toDel = snaps.slice(limit); + for (let i in toDel) { + await dellSnap(toDel[i].slug); + } + logger.info("Local clean done."); resolve(); - return; - } - snaps.sort((a, b) => { - if (moment(a.date).isBefore(moment(b.date))) return 1; - else return -1; + }) + .catch(() => { + reject(); }); - let toDel = snaps.slice(limit); - for (let i in toDel) { - await dellSnap(toDel[i].slug); - } - logger.info("Local clean done."); - resolve(); - }) - .catch(() => { - reject(); - }); }); } @@ -348,58 +345,58 @@ function uploadSnapshot(path) { logger.info("Uploading backup..."); let stream = fs.createReadStream(path); let token = process.env.HASSIO_TOKEN; - + let form = new FormData(); form.append("file", stream); - + let options = { body: form, username: this.username, password: this.password, headers: { "X-HASSIO-KEY": token }, }; - + got.stream - .post(`http://hassio/snapshots/new/upload`, options) - .on("uploadProgress", (e) => { - let percent = e.percent; - if (status.progress != percent) { - status.progress = percent; - statusTools.setStatus(status); - } - if (percent >= 1) { - logger.info("Upload done..."); - } - }) - .on("response", (res) => { - if (res.statusCode != 200) { + .post(`http://hassio/snapshots/new/upload`, options) + .on("uploadProgress", (e) => { + let percent = e.percent; + if (status.progress !== percent) { + status.progress = percent; + statusTools.setStatus(status); + } + if (percent >= 1) { + logger.info("Upload done..."); + } + }) + .on("response", (res) => { + if (res.statusCode !== 200) { + status.status = "error"; + status.error_code = 4; + status.message = `Fail to upload backup to home assitant (Status code: ${res.statusCode})!`; + statusTools.setStatus(status); + logger.error(status.message); + fs.unlinkSync(path); + reject(status.message); + } else { + logger.info(`...Upload finish ! (status: ${res.statusCode})`); + status.status = "idle"; + status.progress = -1; + status.message = null; + status.error_code = null; + statusTools.setStatus(status); + fs.unlinkSync(path); + resolve(); + } + }) + .on("error", (err) => { + fs.unlinkSync(path); 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 assitant (${err}) !`; statusTools.setStatus(status); logger.error(status.message); - fs.unlinkSync(path); reject(status.message); - } else { - logger.info(`...Upload finish ! (status: ${res.statusCode})`); - status.status = "idle"; - status.progress = -1; - status.message = null; - status.error_code = null; - statusTools.setStatus(status); - fs.unlinkSync(path); - resolve(); - } - }) - .on("error", (err) => { - fs.unlinkSync(path); - status.status = "error"; - status.error_code = 4; - status.message = `Fail to upload backup to home assitant (${err}) !`; - statusTools.setStatus(status); - logger.error(status.message); - reject(status.message); - }); + }); }); } diff --git a/nextcloud_backup/rootfs/opt/nextcloud_backup/tools/pathTools.js b/nextcloud_backup/rootfs/opt/nextcloud_backup/tools/pathTools.js index 7e227a9..83e5458 100644 --- a/nextcloud_backup/rootfs/opt/nextcloud_backup/tools/pathTools.js +++ b/nextcloud_backup/rootfs/opt/nextcloud_backup/tools/pathTools.js @@ -1,4 +1,4 @@ - let default_root = "/Hassio Backup/"; +let default_root = "/Hassio Backup/"; exports.default_root = default_root; exports.manual = "Manual/"; exports.auto = "Auto/"; diff --git a/nextcloud_backup/rootfs/opt/nextcloud_backup/tools/settingsTools.js b/nextcloud_backup/rootfs/opt/nextcloud_backup/tools/settingsTools.js index 2e11b77..c5c276b 100644 --- a/nextcloud_backup/rootfs/opt/nextcloud_backup/tools/settingsTools.js +++ b/nextcloud_backup/rootfs/opt/nextcloud_backup/tools/settingsTools.js @@ -4,135 +4,127 @@ const moment = require('moment') const settingsPath = "/data/backup_conf.json"; -function check_cron(conf){ +function check_cron(conf) { if (conf.cron_base != null) { if (conf.cron_base === "1" || conf.cron_base === "2" || conf.cron_base === "3") { if (conf.cron_hour != null && conf.cron_hour.match(/\d\d:\d\d/)) { if (conf.cron_base === "1") return true; } else return false; } - + if (conf.cron_base === "2") { return conf.cron_weekday != null && conf.cron_weekday >= 0 && conf.cron_weekday <= 6; } - + if (conf.cron_base === "3") { return conf.cron_month_day != null && conf.cron_month_day >= 1 && conf.cron_month_day <= 28; } - + if (conf.cron_base === "0") return true; } else return false; - + return false; } -function check(conf, fallback = false){ +function check(conf, fallback = false) { let needSave = false; - if(!check_cron(conf)){ - if(fallback){ + if (!check_cron(conf)) { + if (fallback) { logger.warn("Bad value for cron settings, fallback to default ") conf.cron_base = "0"; conf.cron_hour = "00:00", - conf.cron_weekday = "0", - conf.cron_month_day = "1" - } - else { + conf.cron_weekday = "0", + conf.cron_month_day = "1" + } else { logger.error("Bad value for cron settings") return false; } } - if(conf.name_template == null){ - if(fallback){ + if (conf.name_template == null) { + 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; } } - if(conf.auto_clean_local_keep == null || !/^\d+$/.test(conf.auto_clean_local_keep)){ - - if(fallback){ + if (conf.auto_clean_local_keep == null || !/^\d+$/.test(conf.auto_clean_local_keep)) { + + 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; } } - if(conf.auto_clean_backup_keep == null || !/^\d+$/.test(conf.auto_clean_backup_keep)){ - if(fallback){ + if (conf.auto_clean_backup_keep == null || !/^\d+$/.test(conf.auto_clean_backup_keep)) { + 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; } } - if(conf.auto_clean_local == null){ - if(fallback){ + if (conf.auto_clean_local == null) { + 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; } } - if(conf.auto_clean_backup == null){ - if(fallback){ + if (conf.auto_clean_backup == null) { + 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; } } - if(conf.exclude_addon == null){ - if(fallback){ + if (conf.exclude_addon == null) { + 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; } } - if(conf.exclude_folder == null){ - if(fallback){ + if (conf.exclude_folder == null) { + 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; } } - if(!Array.isArray(conf.exclude_folder)){ + if (!Array.isArray(conf.exclude_folder)) { logger.debug("exclude_folder is not array (Empty value), reset..."); conf.exclude_folder = [] needSave = true; } - if(!Array.isArray(conf.exclude_addon)){ + if (!Array.isArray(conf.exclude_addon)) { logger.debug("exclude_addon is not array (Empty value), reset..."); conf.exclude_addon = [] needSave = true; } - if(fallback || needSave){ + if (fallback || needSave) { setSettings(conf); } return true - + } -function getFormatedName(is_manual, ha_version){ +function getFormatedName(is_manual, ha_version) { let setting = getSettings(); let template = setting.name_template; template = template.replace('{type_low}', is_manual ? 'manual' : 'auto'); @@ -142,7 +134,7 @@ function getFormatedName(is_manual, ha_version){ template = template.replace('{hour_12}', mmt.format('hhmmA')); template = template.replace('{hour}', mmt.format('HHmm')); template = template.replace('{date}', mmt.format('YYYY-MM-DD')); - return template + return template } function getSettings() { diff --git a/nextcloud_backup/rootfs/opt/nextcloud_backup/tools/webdavTools.js b/nextcloud_backup/rootfs/opt/nextcloud_backup/tools/webdavTools.js index a9074cd..86f5891 100644 --- a/nextcloud_backup/rootfs/opt/nextcloud_backup/tools/webdavTools.js +++ b/nextcloud_backup/rootfs/opt/nextcloud_backup/tools/webdavTools.js @@ -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,25 +96,25 @@ class WebdavTools { initFolder() { return new Promise((resolve) => { - 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.manual) - .catch(() => {}) - .then(() => { - resolve(); - }); - }); - }); + 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.manual) + .catch(() => { + }) + .then(() => { + resolve(); + }); + }); + }); }); } + /** * 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,32 +329,31 @@ 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) => { - let percent = Math.round(e.percent * 100) / 100; - if (status.progress != percent) { - status.progress = percent; - statusTools.setStatus(status); - } - }), + got.stream.get(encodeURI(this.baseUrl + path), options) + .on("downloadProgress", (e) => { + let percent = Math.round(e.percent * 100) / 100; + if (status.progress !== percent) { + status.progress = percent; + statusTools.setStatus(status); + } + }), stream - ) - .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) => { - if (fs.existsSync(tmpFile)) fs.unlinkSync(tmpFile); - status.status = "error"; - status.message = "Fail to download Hassio snapshot (" + err.message + ")"; - status.error_code = 7; - statusTools.setStatus(status); - logger.error(status.message); - logger.error(err.stack); - reject(err.message); - }); + ).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) => { + if (fs.existsSync(tmpFile)) fs.unlinkSync(tmpFile); + status.status = "error"; + status.message = "Fail to download Hassio snapshot (" + err.message + ")"; + status.error_code = 7; + statusTools.setStatus(status); + logger.error(status.message); + logger.error(err.stack); + reject(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; }); } });