Add upload methods

This commit is contained in:
Sebastien Clement 2019-12-28 12:50:36 +01:00
parent 7ce157efec
commit a962827599
5 changed files with 85 additions and 27 deletions

View File

@ -79,13 +79,15 @@ router.get('/nextcloud-settings', function(req, res, next) {
router.post('/manual-backup', function(req, res, next) { router.post('/manual-backup', function(req, res, next) {
let id = req.query.id; let id = req.query.id;
hassioApiTools.downloadSnapshot(id) let name = req.query.name;
.then(() => { // hassioApiTools.downloadSnapshot(id)
// .then(() => {
webdav.uploadFile('8afb4728', '/Hassio Backup/Manual/' + '8afb4728' + '.tar');
res.send(200); res.send(200);
}) // })
.catch(() => { // .catch(() => {
res.send(500); // res.send(500);
}) // })
}); });

View File

@ -38,6 +38,7 @@ function getSnapshots() {
status.message = "Fail to fetch Hassio snapshot (" + error + ")"; status.message = "Fail to fetch Hassio snapshot (" + error + ")";
status.error_code = 1; status.error_code = 1;
statusTools.setStatus(status); statusTools.setStatus(status);
console.error(status.message);
reject(error); reject(error);
} }
}) })
@ -47,8 +48,10 @@ function getSnapshots() {
function downloadSnapshot(id) { function downloadSnapshot(id) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
console.log('Downloading snapshot ' + id + '...')
let stream = fs.createWriteStream('./' + id + '.tar'); if(!fs.existsSync('./temp/'))
fs.mkdirSync('./temp/');
let stream = fs.createWriteStream('./temp/' + id + '.tar');
let token = process.env.HASSIO_TOKEN; let token = process.env.HASSIO_TOKEN;
if (token == null) { if (token == null) {
token = fallbackToken token = fallbackToken
@ -64,27 +67,31 @@ function downloadSnapshot(id) {
} }
progress(request(option)) progress(request(option))
.on('progress', (state) => { .on('progress', (state) => {
// TODO Don't write progress to disk, preseve disk IO time
status.progress = state.percent; status.progress = state.percent;
statusTools.setStatus(status); statusTools.setStatus(status);
}) })
.on('error', (error) => { .on('error', (error) => {
status.status = "error"; status.status = "error";
status.message = "Fail to downloadw Hassio snapshot (" + error + ")"; status.message = "Fail to download Hassio snapshot (" + error + ")";
status.error_code = 4; status.error_code = 4;
statusTools.setStatus(status); statusTools.setStatus(status);
console.error(status.message);
reject(error); reject(error);
}) })
.on('end', () => { .on('end', () => {
console.log('end') console.log('Download success !')
status.progress = 1; status.progress = 1;
statusTools.setStatus(status); statusTools.setStatus(status);
resolve();
}) })
.pipe(stream); .pipe(stream);
}).catch(() => { }).catch(() => {
status.status = "error"; status.status = "error";
status.message = "Fail to downloadw Hassio snapshot"; status.message = "Fail to download Hassio snapshot. Not found ?";
status.error_code = 4; status.error_code = 4;
statusTools.setStatus(status); statusTools.setStatus(status);
console.error(status.message);
reject(); reject();
}); });

View File

@ -1,5 +1,6 @@
const { createClient } = require("webdav"); const { createClient } = require("webdav");
const fs = require("fs"); const fs = require("fs");
const statusTools = require('./status'); const statusTools = require('./status');
const endpoint = "/remote.php/webdav" const endpoint = "/remote.php/webdav"
const configPath = "./webdav_conf.json" const configPath = "./webdav_conf.json"
@ -16,6 +17,7 @@ class WebdavTools {
let url = (ssl ? "https" : "http") + "://" + host + endpoint; let url = (ssl ? "https" : "http") + "://" + host + endpoint;
try { try {
this.client = createClient(url, { username: username, password: password }); this.client = createClient(url, { username: username, password: password });
this.client.getDirectoryContents("/").then(() => { this.client.getDirectoryContents("/").then(() => {
if (status.error_code == 3) { if (status.error_code == 3) {
status.status = "idle"; status.status = "idle";
@ -87,6 +89,7 @@ class WebdavTools {
status.error_code = 2; status.error_code = 2;
status.message = "Nextcloud config invalid !" status.message = "Nextcloud config invalid !"
statusTools.setStatus(status); statusTools.setStatus(status);
console.error(status.message);
reject("Nextcloud config invalid !"); reject("Nextcloud config invalid !");
} }
} }
@ -95,6 +98,7 @@ class WebdavTools {
status.error_code = 2; status.error_code = 2;
status.message = "Nextcloud config not found !" status.message = "Nextcloud config not found !"
statusTools.setStatus(status); statusTools.setStatus(status);
console.error(status.message);
reject("Nextcloud config not found !"); reject("Nextcloud config not found !");
} }
@ -115,6 +119,48 @@ class WebdavTools {
} }
uploadFile(id, path) {
return new Promise((resolve, reject) => {
if (this.client == null) {
this.confIsValid().then(() => {
this._startUpload(id, path);
}).catch((err) => {
reject(err);
})
}
else
this._startUpload(id, path);
});
}
_startUpload(id, path) {
return new Promise((resolve, reject) => {
let status = statusTools.getStatus();
status.status = "upload";
status.progress = -1;
status.message = null;
status.error_code = null;
statusTools.setStatus(status);
console.log('Uploading snap...');
//TODO Change this, try with request (buid the webdav request manualy) to track progress (https://stackoverflow.com/questions/12098713/upload-progress-request)
this.client.putFileContents(path, fs.readFileSync('./temp/' + id + '.tar'), { maxContentLength: 1024 ** 3 }).then((result) => {
console.log("...Upload finish !");
status.status = "idle";
status.message = null;
status.error_code = null;
statusTools.setStatus(status);
resolve();
}).catch((err) => {
status.status = "error";
status.error_code = 4;
status.message = "Fail to upload snapshot to nextcloud (" + err + ") !"
statusTools.setStatus(status);
console.error(status.message);
reject(status.message);
});
});
}
} }

View File

@ -310,7 +310,8 @@
$('.manual-back-list').click(function(){ $('.manual-back-list').click(function(){
let id = this.getAttribute('data-id'); let id = this.getAttribute('data-id');
manualBackup(id); let name = this.getAttribute('data-name');
manualBackup(id, name);
}) })
}); });
@ -329,6 +330,8 @@
break; break;
case "download": case "download":
printStatusWithBar('Downloading Snapshot', data.progress); printStatusWithBar('Downloading Snapshot', data.progress);
case "upload":
printStatusWithBar('Uploading Snapshot', data.progress);
} }
} }
@ -408,8 +411,8 @@
}) })
} }
function manualBackup(id){ function manualBackup(id, name){
$.post('./api/manual-backup?id=' + id); $.post('./api/manual-backup?id=' + id + '&name=' + name);
} }

View File

@ -3,7 +3,7 @@
<% for(const index in snaps) { %> <% for(const index in snaps) { %>
<a class="collection-item local-snap-listener modal-trigger" href="#modal-<%=snaps[index].slug%>" <a class="collection-item local-snap-listener modal-trigger" href="#modal-<%=snaps[index].slug%>"
data-id="<%= snaps[index].slug %>"> data-id="<%= snaps[index].slug %>">
<div><%= snaps[index].name ? snaps[index].name : 'No name' %><div class="secondary-content"> <div><%= snaps[index].name ? snaps[index].name : snaps[index].slug %><div class="secondary-content">
<%= moment(snaps[index].date).format('lll') %></div> <%= moment(snaps[index].date).format('lll') %></div>
</div> </div>
</a> </a>
@ -22,7 +22,7 @@
<div class="row"> <div class="row">
<div class="input-field col s12"> <div class="input-field col s12">
<input disabled type="text" id="name-<%=snaps[index].slug%>" value="<%= snaps[index].name ? snaps[index].name : 'No name' %>" /> <input disabled type="text" id="name-<%=snaps[index].slug%>" value="<%= snaps[index].name ? snaps[index].name : snaps[index].slug %>" />
<label for="name-<%=snaps[index].slug%>" class="white-text active">Name</label> <label for="name-<%=snaps[index].slug%>" class="white-text active">Name</label>
</div> </div>
@ -46,7 +46,7 @@
</div> </div>
</div> </div>
<div class="modal-footer blue-grey darken-4"> <div class="modal-footer blue-grey darken-4">
<a href="#!" class="waves-effect waves-green btn light-blue accent-4 manual-back-list modal-close" data-id="<%=snaps[index].slug%>">Backup now</a> <a href="#!" class="waves-effect waves-green btn light-blue accent-4 manual-back-list modal-close" data-id="<%=snaps[index].slug%>" data-name='<%= snaps[index].name ? snaps[index].name : snaps[index].slug %>'</a>Backup now</a>
<a href="#!" class="modal-close waves-effect waves-green btn red">Close</a> <a href="#!" class="modal-close waves-effect waves-green btn red">Close</a>
</div> </div>