Files
pico/projects/tzpuPico/SD/default/webfs/js/filemanager.js
2026-03-29 22:05:52 +01:00

233 lines
8.2 KiB
JavaScript
Executable File
Vendored

var lastStatus = 0;
// Confirm delete with "Don't ask again" checkbox.
// Uses localStorage to persist the preference across sessions.
// To re-enable: localStorage.removeItem('skipDeleteConfirm') in browser console.
var _delPendingForm = null;
function confirmDelete(filename) {
if (localStorage.getItem('skipDeleteConfirm') === 'true') {
return true;
}
// Show a modal overlay with confirm + checkbox
var overlay = document.createElement('div');
overlay.id = 'delConfirmOverlay';
overlay.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;' +
'background:rgba(0,0,0,0.5);z-index:10000;display:flex;align-items:center;justify-content:center;';
overlay.innerHTML =
'<div style="background:#2c2c2c;border:1px solid #555;border-radius:8px;padding:20px 30px;' +
'max-width:400px;color:#eee;font-size:14px;text-align:center;">' +
'<p style="margin-bottom:15px;">Delete <b>"' + filename + '"</b>?</p>' +
'<label style="display:block;margin-bottom:15px;font-size:12px;cursor:pointer;">' +
'<input type="checkbox" id="delNoAsk" style="margin-right:6px;">Don\'t ask again</label>' +
'<button id="delOk" style="margin-right:10px;padding:6px 20px;cursor:pointer;' +
'background:#c33;color:#fff;border:1px solid #a22;border-radius:4px;">Delete</button>' +
'<button id="delCancel" style="padding:6px 20px;cursor:pointer;' +
'background:#555;color:#fff;border:1px solid #444;border-radius:4px;">Cancel</button></div>';
document.body.appendChild(overlay);
// Capture the form that triggered this
_delPendingForm = event.target.closest('form');
document.getElementById('delOk').onclick = function() {
if (document.getElementById('delNoAsk').checked) {
localStorage.setItem('skipDeleteConfirm', 'true');
}
document.body.removeChild(overlay);
if (_delPendingForm) _delPendingForm.submit();
};
document.getElementById('delCancel').onclick = function() {
document.body.removeChild(overlay);
};
return false; // Prevent the default form submit
}
// Method to display a message in a message field. The existing html is saved and replaced
// with the new html. After a timeout period the original html is restored.
//
$origMessage = null;
$origId = null;
$msgTimerId = null;
function showMessage(timeout, id, message)
{
// Is this a new message whilst one is active?
if($origMessage !== null)
{
// Cancel timer and restore original message.
clearTimeout($msgTimerId);
$('#' + $origId).html($origMessage);
}
// Store original message and Id so that on timer expiry it can be replaced..
$origMessage = $('#' + id).html();
$origId = id;
// Change HTML and set timer to restore it.
$('#' + id).html(message);
$msgTimerId = setTimeout(function(msgFieldId)
{
$('#' + msgFieldId).html($origMessage);
$origMessage = null;
}, timeout, id);
}
// Clear the file input array.
function clearFileInput(ctrl)
{
try {
ctrl.value = null;
} catch(ex) { }
if (ctrl.value) {
ctrl.parentNode.replaceChild(ctrl.cloneNode(true), ctrl);
}
}
function setpath() {
var default_path = document.getElementById("newfile").files[0].name;
document.getElementById("filepath").value = default_path;
}
function uploadFile() {
var filePath = document.getElementById("filepath").value;
var upload_path = "/data/upload/" + filePath;
var fileInput = document.getElementById("newfile").files;
var MAX_FILE_SIZE = 512*1024*1024;
var MAX_FILE_SIZE_STR = "512MB";
if (fileInput.length == 0)
{
alert("No file selected!");
} else if (filePath.length == 0)
{
alert("File path on server is not set!");
} else if (filePath.indexOf(' ') >= 0)
{
alert("File path on server cannot have spaces!");
} else if (filePath[filePath.length-1] == '/')
{
alert("File name not specified after path!");
} else if (fileInput[0].size > MAX_FILE_SIZE)
{
alert("File size must be less than "+MAX_FILE_SIZE_STR+"!");
} else
{
document.getElementById("newfile").disabled = true;
document.getElementById("filepath").disabled = true;
document.getElementById("upload").disabled = true;
//document.getElementById("download").disabled = true;
document.getElementById("mkdir").disabled = true;
var file = fileInput[0];
var xhttp;
if(window.XMLHttpRequest)
{
xhttp = new XMLHttpRequest();
} else
{
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4)
{
if (xhttp.status == 200)
{
document.open();
document.write(xhttp.responseText);
document.close();
alert("File upload successful!");
location.reload()
} else if (xhttp.status == 0)
{
alert("Upload failed, server closed the connection abruptly!");
location.reload()
} else
{
alert(xhttp.status + " Error!\n" + xhttp.responseText);
location.reload()
}
}
};
xhttp.open("POST", upload_path+window.location.search, true);
xhttp.send(fileInput[0]);
}
}
// Function to handle form submission for file download
function downloadFile(event) {
event.preventDefault(); // Prevent default form submission
const form = event.target.closest("form"); // Get the parent form
const filename = form.querySelector("input[name='name']").value; // Extract filename
const directory = form.querySelector("input[name='dir']").value; // Extract directory
// Send AJAX GET request to the server
const url = `/data/download/?name=${encodeURIComponent(filename)}&dir=${encodeURIComponent(directory)}`;
fetch(url, {
method: "GET",
headers: {
"Accept": "application/octet-stream"
}
})
.then(response => {
if (!response.ok) {
throw new Error("Failed to download file");
}
return response.blob(); // Get the file as a blob
})
.then(blob => {
// Create a temporary link to trigger download
const url = window.URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = filename; // Set the downloaded file's name
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(url); // Clean up
})
.catch(error => {
console.error("Download failed:", error);
alert("Failed to download the file.");
});
}
// Add event listeners to all download forms
document.addEventListener("DOMContentLoaded", () => {
const downloadForms = document.querySelectorAll("form[action='?cmd=download']");
downloadForms.forEach(form => {
form.addEventListener("submit", downloadFile); // Handle form submission
});
});
function mkdir() {
// Get the basepath from the hidden field and filepath from the input box
const basepath = document.getElementById('basepath').value;
const filepath = document.getElementById('filepath').value;
// Combine basepath and filepath, ensuring no double slashes
const fullpath = `${basepath.replace(/\/+$/, '')}/${filepath.replace(/^\/+/, '')}`;
// Construct the URL with the full path
const url = `/data/mkdir?dir=${encodeURIComponent(fullpath)}`;
// Make the GET request using fetch
fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
// Reload the page after successful request
location.reload();
})
.catch(error => {
console.error('Error:', error);
alert('Failed to create directory');
});
}