Implement backup upload and deletion functionality in eMMC provisioning dashboard: add API endpoints for uploading image files and deleting backups, enhance UI with upload button and delete options, and improve error handling for file operations. Update documentation to reflect new features.
This commit is contained in:
@@ -335,9 +335,44 @@ def api_backups():
|
||||
return jsonify({"backups": list_backups(), "backups_dir": str(BACKUPS_DIR)})
|
||||
|
||||
|
||||
@app.route("/api/backups/upload", methods=["POST"])
|
||||
def api_backups_upload():
|
||||
"""Upload an image file from the dashboard (multipart form)."""
|
||||
if "file" not in request.files and "image" not in request.files:
|
||||
return jsonify({"ok": False, "error": "no file in request (use field 'file' or 'image')"}), 400
|
||||
f = request.files.get("file") or request.files.get("image")
|
||||
if not f or not f.filename:
|
||||
return jsonify({"ok": False, "error": "no file selected"}), 400
|
||||
base = (f.filename.rsplit(".", 1)[0] if "." in f.filename else f.filename).strip() or "upload"
|
||||
safe_base = re.sub(r"[^\w\-.]", "_", base)[:80]
|
||||
if not safe_base:
|
||||
safe_base = "upload"
|
||||
ext = ""
|
||||
if f.filename.lower().endswith(".img.xz"):
|
||||
ext = ".img.xz"
|
||||
elif f.filename.lower().endswith(".img.gz"):
|
||||
ext = ".img.gz"
|
||||
elif f.filename.lower().endswith(".img"):
|
||||
ext = ".img"
|
||||
else:
|
||||
ext = ".img"
|
||||
name = f"{safe_base}-{int(time.time())}{ext}"
|
||||
if not _safe_backup_name(name):
|
||||
name = f"upload-{int(time.time())}.img"
|
||||
path = BACKUPS_DIR / name
|
||||
try:
|
||||
BACKUPS_DIR.mkdir(parents=True, exist_ok=True)
|
||||
f.save(str(path))
|
||||
return jsonify({"ok": True, "name": name, "message": f"Uploaded {name}"})
|
||||
except (OSError, IOError) as e:
|
||||
if path.exists():
|
||||
path.unlink(missing_ok=True)
|
||||
return jsonify({"ok": False, "error": str(e)}), 500
|
||||
|
||||
|
||||
@app.route("/api/backups/<path:name>/set-as-golden", methods=["POST"])
|
||||
def api_backup_set_as_golden(name):
|
||||
"""Copy this backup to golden.img so it becomes the image used for Deploy."""
|
||||
"""Use this backup as the golden image (symlink when in backups dir to avoid copying)."""
|
||||
if not _safe_backup_name(name):
|
||||
return jsonify({"ok": False, "error": "invalid backup name"}), 400
|
||||
path = BACKUPS_DIR / name
|
||||
@@ -345,7 +380,17 @@ def api_backup_set_as_golden(name):
|
||||
return jsonify({"ok": False, "error": "backup not found"}), 404
|
||||
try:
|
||||
BACKUPS_DIR.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(path, GOLDEN_IMAGE)
|
||||
GOLDEN_IMAGE.parent.mkdir(parents=True, exist_ok=True)
|
||||
if GOLDEN_IMAGE.exists():
|
||||
GOLDEN_IMAGE.unlink()
|
||||
# Symlink to the backup so we use the same file instead of duplicating
|
||||
path_resolved = path.resolve()
|
||||
try:
|
||||
path_resolved.relative_to(BACKUPS_DIR.resolve())
|
||||
os.symlink(path_resolved, GOLDEN_IMAGE)
|
||||
except ValueError:
|
||||
# Backup not under BACKUPS_DIR (shouldn't happen for list); fall back to copy
|
||||
shutil.copy2(path, GOLDEN_IMAGE)
|
||||
return jsonify({"ok": True, "message": f"Golden image set from {name}"})
|
||||
except (OSError, IOError) as e:
|
||||
return jsonify({"ok": False, "error": str(e)}), 500
|
||||
@@ -458,6 +503,30 @@ def api_backup_update(name):
|
||||
return jsonify({"ok": True, "name": name})
|
||||
|
||||
|
||||
@app.route("/api/backups/<path:name>", methods=["DELETE"])
|
||||
def api_backup_delete(name):
|
||||
"""Delete a backup file. If it is the current golden image (symlink), the golden link is removed."""
|
||||
if not _safe_backup_name(name):
|
||||
return jsonify({"ok": False, "error": "invalid backup name"}), 400
|
||||
path = BACKUPS_DIR / name
|
||||
if not path.is_file():
|
||||
return jsonify({"ok": False, "error": "backup not found"}), 404
|
||||
try:
|
||||
if GOLDEN_IMAGE.exists() and GOLDEN_IMAGE.is_symlink():
|
||||
try:
|
||||
if (GOLDEN_IMAGE.resolve() == path.resolve()):
|
||||
GOLDEN_IMAGE.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
path.unlink()
|
||||
meta = _load_backups_meta()
|
||||
meta.pop(name, None)
|
||||
_save_backups_meta(meta)
|
||||
return jsonify({"ok": True, "message": f"Deleted {name}"})
|
||||
except (OSError, IOError) as e:
|
||||
return jsonify({"ok": False, "error": str(e)}), 500
|
||||
|
||||
|
||||
@app.route("/api/backups/<path:name>", methods=["GET"])
|
||||
def api_backup_download(name):
|
||||
if not _safe_backup_name(name):
|
||||
|
||||
@@ -399,7 +399,11 @@
|
||||
|
||||
<!-- 3. Saved backups -->
|
||||
<section class="section">
|
||||
<h2 class="section-title">Saved backups <button type="button" class="btn btn-outline btn-sm" id="refreshBackupsBtn" title="Reload list">Refresh</button></h2>
|
||||
<h2 class="section-title">Saved backups
|
||||
<button type="button" class="btn btn-outline btn-sm" id="refreshBackupsBtn" title="Reload list">Refresh</button>
|
||||
<button type="button" class="btn btn-outline btn-sm" id="uploadImageBtn" title="Upload an image file">Upload image</button>
|
||||
<input type="file" id="uploadImageInput" accept=".img,.img.gz,.img.xz,image/*" style="display:none;" />
|
||||
</h2>
|
||||
<p id="goldenHint" class="backups-mono" style="margin-bottom:0.25rem;font-size:0.8rem;"></p>
|
||||
<p id="backupsDirHint" class="backups-mono" style="margin-bottom:0.75rem;font-size:0.75rem;color:var(--muted);"></p>
|
||||
<table class="backups-table" id="backupsTable">
|
||||
@@ -617,7 +621,8 @@
|
||||
compressBtn +
|
||||
'<button type="button" class="btn btn-primary btn-sm set-golden-btn" data-name="' + escapeHtml(b.name) + '">Set as golden</button> ' +
|
||||
'<button type="button" class="btn btn-outline btn-sm rename-file-btn" data-name="' + escapeHtml(b.name) + '" title="Rename file">Rename file</button> ' +
|
||||
'<a href="/api/backups/' + encodeURIComponent(b.name) + '" download class="btn btn-outline btn-sm download-link">Download</a>' +
|
||||
'<a href="/api/backups/' + encodeURIComponent(b.name) + '" download class="btn btn-outline btn-sm download-link">Download</a> ' +
|
||||
'<button type="button" class="btn btn-outline btn-sm delete-backup-btn" data-name="' + escapeHtml(b.name) + '" title="Delete this backup">Delete</button>' +
|
||||
'</td>';
|
||||
tbody.appendChild(tr);
|
||||
});
|
||||
@@ -626,6 +631,25 @@
|
||||
bindRenameFile();
|
||||
bindShrink();
|
||||
bindCompress();
|
||||
bindDeleteBackup();
|
||||
}
|
||||
|
||||
function bindDeleteBackup() {
|
||||
document.querySelectorAll('.delete-backup-btn').forEach(function(btn) {
|
||||
btn.onclick = function() {
|
||||
const name = btn.getAttribute('data-name');
|
||||
if (!confirm('Delete this backup? This cannot be undone.\n\n' + name)) return;
|
||||
btn.disabled = true;
|
||||
fetch('/api/backups/' + encodeURIComponent(name), { method: 'DELETE' })
|
||||
.then(function(r) { return r.json(); })
|
||||
.then(function(data) {
|
||||
if (data.ok) { fetchBackups(); fetchGoldenInfo(); }
|
||||
else alert(data.error || 'Failed');
|
||||
})
|
||||
.catch(function() { alert('Request failed'); })
|
||||
.finally(function() { btn.disabled = false; });
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function bindRenameFile() {
|
||||
@@ -901,6 +925,26 @@
|
||||
});
|
||||
var refreshBackupsBtn = document.getElementById('refreshBackupsBtn');
|
||||
if (refreshBackupsBtn) refreshBackupsBtn.onclick = function() { fetchBackups(); fetchGoldenInfo(); };
|
||||
var uploadImageBtn = document.getElementById('uploadImageBtn');
|
||||
var uploadImageInput = document.getElementById('uploadImageInput');
|
||||
if (uploadImageBtn && uploadImageInput) {
|
||||
uploadImageBtn.onclick = function() { uploadImageInput.click(); };
|
||||
uploadImageInput.onchange = function() {
|
||||
var file = uploadImageInput.files && uploadImageInput.files[0];
|
||||
if (!file) return;
|
||||
var fd = new FormData();
|
||||
fd.append('file', file);
|
||||
uploadImageBtn.disabled = true;
|
||||
fetch('/api/backups/upload', { method: 'POST', body: fd })
|
||||
.then(function(r) { return r.json(); })
|
||||
.then(function(d) {
|
||||
if (d.ok) { fetchBackups(); fetchGoldenInfo(); alert('Uploaded: ' + (d.name || file.name)); }
|
||||
else alert(d.error || 'Upload failed');
|
||||
})
|
||||
.catch(function() { alert('Upload failed'); })
|
||||
.finally(function() { uploadImageBtn.disabled = false; uploadImageInput.value = ''; });
|
||||
};
|
||||
}
|
||||
|
||||
fetchStatus();
|
||||
fetchLog();
|
||||
|
||||
Reference in New Issue
Block a user