make more robust, add log (#1690)

Co-authored-by: CaCO3 <caco@ruinelli.ch>
This commit is contained in:
CaCO3
2022-12-27 00:04:29 +01:00
committed by GitHub
parent 9b8923c998
commit f11fadf14b

View File

@@ -32,16 +32,8 @@ input[type=number] {
<h2>Backup Configuration</h2> <h2>Backup Configuration</h2>
<p>With the following action the <a href="/fileserver/config/" target="_self">config</a> folder on the SD-card gets zipped and provided as a download.</p> <p>With the following action the <a href="/fileserver/config/" target="_self">config</a> folder on the SD-card gets zipped and provided as a download.</p>
<table border="0"> <button class="button" id="startBackup" type="button" onclick="startBackup()">Create Config backup</button>
</tr> <p id=progress></p>
<td>
<button class="button" id="doBackup" type="button" onclick="doBackup()">Create Config backup</button>
</td>
<td>
<p id=progress></p>
</td>
</tr>
</table>
<hr> <hr>
<h2>Restore Configuration</h2> <h2>Restore Configuration</h2>
<p>Use the <a href="/fileserver/config/" target="_self">File Server</a> to upload individual files.</p> <p>Use the <a href="/fileserver/config/" target="_self">File Server</a> to upload individual files.</p>
@@ -52,18 +44,21 @@ input[type=number] {
<script src="FileSaver.min.js"></script> <script src="FileSaver.min.js"></script>
<script> <script>
function doBackup() { var domain = "http://192.168.1.153";
document.getElementById("progress").innerHTML = "Creating backup..."; //var domain = "";
function startBackup() {
document.getElementById("progress").innerHTML = "Creating backup...<br>\n";
// Get hostname // Get hostname
try { try {
var xhttp = new XMLHttpRequest(); var xhttp = new XMLHttpRequest();
xhttp.open("GET", "/info?type=Hostname", false); xhttp.open("GET", domain + "/info?type=Hostname", false);
xhttp.send(); xhttp.send();
hostname = xhttp.responseText; hostname = xhttp.responseText;
} }
catch(err) { catch(err) {
alert("Failed to fetch hostname: " + err.message); setStatus("<span style=\"color: red\">Failed to fetch hostname: " + err.message + "!</span>");
return; return;
} }
@@ -74,15 +69,16 @@ function doBackup() {
console.log(zipFilename); console.log(zipFilename);
// Get files list // Get files list
setStatus("Fetching File List...");
try { try {
var xhttp = new XMLHttpRequest(); var xhttp = new XMLHttpRequest();
xhttp.open("GET", "/fileserver/config/", false); xhttp.open("GET", domain + "/fileserver/config/", false);
xhttp.send(); xhttp.send();
var parser = new DOMParser(); var parser = new DOMParser();
var content = parser.parseFromString(xhttp.responseText, 'text/html'); } var content = parser.parseFromString(xhttp.responseText, 'text/html'); }
catch(err) { catch(err) {
alert("Failed to fetch files list: " + err.message); setStatus("Failed to fetch files list: " + err.message);
return; return;
} }
@@ -92,49 +88,118 @@ function doBackup() {
for (a of list) { for (a of list) {
url = a.getAttribute("href"); url = a.getAttribute("href");
urls.push(url); urls.push(domain + url);
} }
// Pack as zip and download // Pack as zip and download
try { try {
saveZip(zipFilename, urls); backup(urls, zipFilename);
} }
catch(err) { catch(err) {
alert("Failed to zip files: " + err.message); setStatus("<span style=\"color: red\">Failed to zip files: " + err.message + "!</span>");
return; return;
} }
} }
const saveZip = (filename, urls) => { function fetchFiles(urls, filesData, index, retry, zipFilename) {
if(!urls) return; url = urls[index];
const zip = new JSZip(); // console.log(url + " started (" + index + "/" + urls.length + ")");
const folder = zip.folder(""); if (retry == 0) {
setStatus("&nbsp;- " + getFilenameFromUrl(urls[index]) + " (" + index + "/" + urls.length + ")...");
}
else {
setStatus("<span style=\"color: gray\">&nbsp;&nbsp;&nbsp;Retrying (" + retry + ")...</span>");
}
var i = 0; const xhr = new XMLHttpRequest();
urls.forEach((url) => { xhr.open('GET', url, true);
const blobPromise = fetch(url).then((r) => { xhr.responseType = "blob";
if (r.status === 200) return r.blob();
return Promise.reject(new Error(r.statusText)); if (retry == 0) { // Short timeout on first retry
}); xhr.timeout = 2000; // time in milliseconds
const name = url.substring(url.lastIndexOf("/") + 1); }
folder.file(name, blobPromise); else if (retry == 1) { // longer timeout
xhr.timeout = 5000; // time in milliseconds
}
else { // very long timeout
xhr.timeout = 20000; // time in milliseconds
}
xhr.onload = () => { // Request finished
//console.log(url + " done");
filesData[index] = xhr.response;
if (index == urls.length - 1) {
setStatus("Fetched all files");
generateZipFile(urls, filesData, zipFilename);
return;
}
else { // Next file
fetchFiles(urls, filesData, index+1, 0, zipFilename);
}
};
xhr.ontimeout = (e) => { // XMLHttpRequest timed out
console.log("Timeout on fetching " + url + "!");
if (retry > 5) {
setStatus("<span style=\"color: red\">Backup failed, please restart the device and try again!</span>");
}
else {
fetchFiles(urls, filesData, index, retry+1, zipFilename);
}
};
xhr.send(null);
}
function generateZipFile(urls, filesData, zipFilename) {
setStatus("Creating Zip File...");
var zip = new JSZip();
for (var i = 0; i < urls.length; i++) {
zip.file(getFilenameFromUrl(urls[i]), filesData[i]);
}
zip.generateAsync({type:"blob"})
.then(function(content) {
saveAs(content, zipFilename);
}); });
zip.generateAsync({ type: "blob" }, setStatus("Backup completed");
function updateCallback(metadata) { }
var msg = "Progress: " + metadata.percent.toFixed(0) + "%";
if(metadata.currentFile) {
msg += ", " + metadata.currentFile;
}
console.log(msg);
document.getElementById("progress").innerHTML = msg; const backup = (urls, zipFilename) => {
} if(!urls) return;
).then((blob) => saveAs(blob, filename));
/* Testing */
/*len = urls.length;
for (i = 0; i < len - 3; i++) {
urls.pop();
}*/
console.log(urls);
urlIndex = 0;
setStatus("Fetching files...");
fetchFiles(urls, [], 0, 0, zipFilename);
}; };
function setStatus(status) {
console.log(status);
document.getElementById("progress").innerHTML += status + "<br>\n";
}
function getFilenameFromUrl(url) {
return filename = url.substring(url.lastIndexOf('/')+1);
}
</script> </script>
</html> </html>