Compare commits

...
Author SHA1 Message Date
Reditus 593345fb1f fix: file manager overhaul, update removal, template auto-reload
File manager: inline split-pane layout, multi-pod selector, full filesystem access, upload permissions fix, download/delete buttons. Factory: TEMPLATES_AUTO_RELOAD to pick up template changes. Base: removed update banner, check button, polling, progress overlay, and all update JS/CSS.
2026-05-29 17:47:59 +01:00
5 changed files with 419 additions and 204 deletions

No files matched your search

+3 -2
View File
@@ -44,6 +44,7 @@ def create_app(settings_path=None):
static_url_path='/static'
)
app.config['SECRET_KEY'] = settings['dashboard']['secret_key']
app.config['TEMPLATES_AUTO_RELOAD'] = True # Pick up template changes without restart
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
app.config['PERMANENT_SESSION_LIFETIME'] = 28800 # 8 hours
@@ -305,8 +306,8 @@ def create_app(settings_path=None):
register_api_routes(app, services, settings)
register_websocket_handlers(socketio, settings)
# Start update checker
updater_svc.start_checker()
# Start update checker (disabled — being reworked)
# updater_svc.start_checker()
@app.teardown_appcontext
def cleanup_db(exc):
+100 -14
View File
@@ -800,35 +800,66 @@ def register_api_routes(app, services, settings):
FILEBROWSER_BASE_PATH = '/srv'
def _validate_fb_path(path):
"""Validate filebrowser path is within allowed directory."""
import posixpath
"""Validate filebrowser path — allow any path, block traversal."""
path_str = str(path or "").lstrip("/")
if '..' in path_str or '\x00' in path_str:
return False
normalized = posixpath.normpath("/" + path_str)
return normalized == FILEBROWSER_BASE_PATH or normalized.startswith(FILEBROWSER_BASE_PATH + "/")
return True
def _get_fb_pod():
"""Get the FileBrowser pod name dynamically."""
"""Get the default FileBrowser pod name dynamically."""
pod = k8s.find_pod_by_pattern('fb-deploy')
return pod
def _fb_exec(command, timeout=10):
"""Execute kubectl exec in the FileBrowser pod with correct namespace placement."""
pod = _get_fb_pod()
def _list_pods():
"""List all running pods available for file browsing, plus VM host."""
available = ['__VM__ (Host OS)']
pods = k8s.get_pods()
for p in pods:
if p.endswith('-sts-0') or '-deploy-' in p:
available.append(p)
return available
def _fb_exec(command, pod_name=None, timeout=10):
"""Execute a command on the VM host or in a K8s pod."""
if pod_name == '__VM__' or (pod_name and pod_name.startswith('__VM__')):
return k8s.ssh.run(command, timeout=timeout)
pod = pod_name or _get_fb_pod()
if not pod:
return '', 'FileBrowser pod not found', 1
return '', 'No pod specified or found', 1
full_cmd = f'sudo kubectl exec {pod} -n {k8s.namespace} -- {command}'
return k8s.ssh.run(full_cmd, timeout=timeout)
def _fb_write_file(content_b64, path, pod_name=None, timeout=30):
"""Write a file to the pod filesystem."""
import base64
cmd = f"echo '{content_b64}' | base64 -d > '{path}'"
return _fb_exec(f"sh -c {quote_remote(cmd)}", pod_name, timeout)
def _get_pod_from_request():
pod = request.form.get('pod', '') or request.args.get('pod', '') or request.get_json(silent=True)
if isinstance(pod, dict):
pod = pod.get('pod', '')
return pod or None
@app.route('/api/files/pods')
@auth_req
def api_files_pods():
try:
pods = _list_pods()
return jsonify({'success': True, 'pods': pods})
except Exception as e:
return jsonify({'success': False, 'error': str(e)})
@app.route('/api/files/list', methods=['POST'])
@auth_req
def api_files_list():
path = request.form.get('path', '/srv')
pod_name = _get_pod_from_request()
if not _validate_fb_path(path):
return jsonify({'success': False, 'error': 'Invalid path: access denied'})
safe_path = quote_remote(path)
out, err, rc = _fb_exec(f'ls -la {safe_path}', timeout=10)
out, err, rc = _fb_exec(f'ls -la {safe_path}', pod_name, timeout=10)
if rc != 0:
return jsonify({'success': False, 'error': err or 'Failed to list directory'})
@@ -855,12 +886,13 @@ def register_api_routes(app, services, settings):
@auth_req
def api_files_view():
path = request.args.get('path', '')
pod_name = _get_pod_from_request()
if not path:
return jsonify({'success': False, 'error': 'Missing path'})
if not _validate_fb_path(path):
return jsonify({'success': False, 'error': 'Invalid path: access denied'})
safe_path = quote_remote(path)
out, err, rc = _fb_exec(f'head -c 100000 {safe_path}', timeout=10)
out, err, rc = _fb_exec(f'head -c 100000 {safe_path}', pod_name, timeout=10)
if rc != 0:
return jsonify({'success': False, 'error': err or 'Failed to read file'})
return jsonify({'success': True, 'content': out, 'path': path})
@@ -871,19 +903,73 @@ def register_api_routes(app, services, settings):
def api_files_save():
path = request.form.get('path', '')
content = request.form.get('content', '')
pod_name = _get_pod_from_request()
if not path:
return jsonify({'success': False, 'error': 'Missing path'})
if not _validate_fb_path(path):
return jsonify({'success': False, 'error': 'Invalid path: access denied'})
import base64
content_b64 = base64.b64encode(content.encode()).decode()
safe_path = quote_remote(path)
save_script = quote_remote(f"base64 -d > {safe_path}")
out, err, rc = _fb_exec(f"sh -c {save_script}", timeout=15)
out, err, rc = _fb_write_file(content_b64, path, pod_name)
if rc != 0:
return jsonify({'success': False, 'error': err or 'Failed to save file'})
return jsonify({'success': True})
@app.route('/api/files/download', methods=['POST'])
@auth_req
def api_files_download():
path = request.form.get('path', '')
pod_name = _get_pod_from_request()
if not path:
return jsonify({'success': False, 'error': 'Missing path'})
if not _validate_fb_path(path):
return jsonify({'success': False, 'error': 'Invalid path: access denied'})
import base64
safe_path = quote_remote(path)
out, err, rc = _fb_exec(f'base64 {safe_path}', pod_name, timeout=30)
if rc != 0:
return jsonify({'success': False, 'error': err or 'Failed to read file'})
filename = path.rsplit('/', 1)[-1] if '/' in path else path
return jsonify({'success': True, 'content': out.strip(), 'filename': filename})
@app.route('/api/files/upload', methods=['POST'])
@auth_req
def api_files_upload():
target_path = request.form.get('path', '/srv')
uploaded = request.files.get('file')
pod_name = _get_pod_from_request()
if not uploaded:
return jsonify({'success': False, 'error': 'No file provided'})
if not _validate_fb_path(target_path):
return jsonify({'success': False, 'error': 'Invalid path: access denied'})
import base64
filename = uploaded.filename.rsplit('/', 1)[-1].rsplit('\\', 1)[-1] if uploaded.filename else 'uploaded_file'
dest = target_path.rstrip('/') + '/' + filename
if not _validate_fb_path(dest):
return jsonify({'success': False, 'error': 'Invalid destination path'})
content = uploaded.read()
content_b64 = base64.b64encode(content).decode()
out, err, rc = _fb_write_file(content_b64, dest, pod_name)
if rc != 0:
return jsonify({'success': False, 'error': err or 'Failed to upload file'})
return jsonify({'success': True, 'filename': filename})
@app.route('/api/files/delete', methods=['POST'])
@auth_req
def api_files_delete():
path = request.form.get('path', '')
pod_name = _get_pod_from_request()
if not path:
return jsonify({'success': False, 'error': 'Missing path'})
if not _validate_fb_path(path):
return jsonify({'success': False, 'error': 'Invalid path: access denied'})
safe_path = quote_remote(path)
out, err, rc = _fb_exec(f'rm -rf {safe_path}', pod_name, timeout=10)
if rc != 0:
return jsonify({'success': False, 'error': err or 'Failed to delete'})
return jsonify({'success': True})
director_svc = services.get('director')
director_port = settings.get('director', {}).get('port', 32479)
-59
View File
@@ -10,13 +10,6 @@
{% block head_extra %}{% endblock %}
</head>
<body>
<div id="update-banner" class="update-banner" style="display:none;">
<span>🔄 Update available for Dune Dashboard</span>
<div class="update-actions">
<button onclick="applyUpdate()" class="update-btn primary">Update Now</button>
<button onclick="dismissUpdate()" class="update-btn">Later</button>
</div>
</div>
<nav>
<div class="brand">DUNE DASHBOARD</div>
{% for href, label in nav_pages %}
@@ -104,7 +97,6 @@
<span class="conn-dot {% if conn_ok %}online{% else %}offline{% endif %}"></span>
{{ 'Connected' if conn_ok else 'Disconnected' }}
</span>
<button id="check-update-btn" onclick="manualCheckUpdate()" style="font-size:12px;color:var(--nav-text);background:none;border:none;cursor:pointer;padding:4px 8px;" title="Check for updates">🔄 Check Updates</button>
{% if current_user and current_user.is_authenticated %}
<a href="/logout" style="font-size:12px;color:var(--nav-text);">Logout</a>
{% endif %}
@@ -115,13 +107,6 @@
<footer class="site-footer">
<span>This is a fan-made project and is not affiliated with, endorsed by, or connected to Funcom, Legendary Entertainment, or any official Dune rights holders. All game assets, trademarks, and intellectual property belong to their respective owners.</span>
</footer>
<div id="update-progress" class="update-progress" style="display:none;">
<div class="update-progress-inner">
<h3>Updating Dashboard...</h3>
<p id="update-status-text">Checking for updates...</p>
<div class="update-spinner"></div>
</div>
</div>
<script>
const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
@@ -131,40 +116,6 @@
return fetch(url, options);
}
let updateDismissed = false;
async function checkForUpdate() {
if (updateDismissed) return;
try {
const resp = await fetch('/api/update/status');
const data = await resp.json();
if (data.available) {
document.getElementById('update-banner').style.display = 'flex';
}
} catch (e) {}
}
async function manualCheckUpdate() {
const progress = document.getElementById('update-progress');
const statusText = document.getElementById('update-status-text');
progress.style.display = 'flex';
statusText.textContent = 'The update system is being reworked for better reliability. Please check back soon.';
setTimeout(() => { progress.style.display = 'none'; }, 4000);
}
function dismissUpdate() {
updateDismissed = true;
document.getElementById('update-banner').style.display = 'none';
}
async function applyUpdate() {
const banner = document.getElementById('update-banner');
const progress = document.getElementById('update-progress');
const statusText = document.getElementById('update-status-text');
banner.style.display = 'none';
progress.style.display = 'flex';
statusText.textContent = 'The auto-update system is being reworked to be more reliable and robust. Manual updates from the launcher still work.';
setTimeout(() => { progress.style.display = 'none'; }, 5000);
}
setInterval(checkForUpdate, 60000);
checkForUpdate();
// Theme System
function setTheme(themeName) {
document.documentElement.setAttribute('data-theme', themeName);
@@ -188,16 +139,6 @@
</script>
{% block scripts %}{% endblock %}
<style>
.update-banner { background: var(--hover); border-bottom: 2px solid var(--accent); padding: 10px 20px; display: flex; justify-content: space-between; align-items: center; font-size: 13px; color: var(--text); }
.update-actions { display: flex; gap: 8px; }
.update-btn { padding: 4px 12px; border: 1px solid var(--border); border-radius: 4px; background: var(--bg-card); color: var(--text); cursor: pointer; font-size: 12px; }
.update-btn.primary { background: var(--accent); color: #fff; border-color: var(--accent); }
.update-progress { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.7); display: flex; align-items: center; justify-content: center; z-index: 9999; }
.update-progress-inner { background: var(--bg-card); padding: 30px 40px; border-radius: 8px; text-align: center; color: var(--text); max-width: 400px; }
.update-progress-inner h3 { margin: 0 0 10px; }
.update-progress-inner p { margin: 0 0 15px; color: var(--text-muted); font-size: 13px; }
.update-spinner { width: 30px; height: 30px; border: 3px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: spin 1s linear infinite; margin: 0 auto; }
@keyframes spin { to { transform: rotate(360deg); } }
.site-footer { text-align: center; padding: 16px 20px; font-size: 11px; color: var(--text-muted); border-top: 1px solid var(--border); margin-top: 24px; }
</style>
</body>
+49
View File
@@ -14,7 +14,9 @@
<span id="view-mode-badge" class="badge">View Mode</span>
</div>
<div class="view-actions">
<button id="dl-btn" class="view-btn" onclick="downloadFile()">Download</button>
<button id="edit-btn" class="view-btn" onclick="toggleEdit()">Edit</button>
<button id="delete-btn" class="view-btn danger" onclick="deleteViewFile()">Delete</button>
<button id="save-btn" class="view-btn primary" style="display:none;" onclick="saveFile()">Save</button>
<button id="cancel-btn" class="view-btn" style="display:none;" onclick="cancelEdit()">Cancel</button>
</div>
@@ -106,6 +108,53 @@ function cancelEdit() {
badge.classList.remove('edit');
}
async function deleteViewFile() {
const name = filePath.split('/').pop();
if (!confirm(`Delete "${name}"? This cannot be undone.`)) return;
try {
const form = new FormData();
form.append('path', filePath);
const resp = await csrfFetch('/api/files/delete', { method: 'POST', body: form });
const data = await resp.json();
if (data.success) {
window.close();
} else {
document.getElementById('view-error').textContent = 'Delete failed: ' + (data.error || 'Unknown');
document.getElementById('view-error').style.display = 'block';
}
} catch (e) {
document.getElementById('view-error').textContent = 'Delete failed: ' + e.message;
document.getElementById('view-error').style.display = 'block';
}
}
async function downloadFile() {
try {
const form = new FormData();
form.append('path', filePath);
const resp = await csrfFetch('/api/files/download', { method: 'POST', body: form });
const data = await resp.json();
if (!data.success) {
document.getElementById('view-error').textContent = 'Error: ' + (data.error || 'Download failed');
document.getElementById('view-error').style.display = 'block';
return;
}
const byteChars = atob(data.content);
const bytes = new Uint8Array(byteChars.length);
for (let i = 0; i < byteChars.length; i++) bytes[i] = byteChars.charCodeAt(i);
const blob = new Blob([bytes]);
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url; a.download = data.filename;
document.body.appendChild(a); a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
} catch (e) {
document.getElementById('view-error').textContent = 'Request failed: ' + e.message;
document.getElementById('view-error').style.display = 'block';
}
}
async function saveFile() {
const saveBtn = document.getElementById('save-btn');
const success = document.getElementById('view-success');
+267 -129
View File
@@ -3,49 +3,79 @@
{% block content %}
<div class="page-header">
<h1>File Browser</h1>
<p>Browse server files via SSH</p>
<h1>File Manager</h1>
<p>Browse, edit, upload, and download server files</p>
</div>
<div class="card">
<div class="card-body">
<div class="fb-toolbar">
<div class="fb-breadcrumb" id="fb-breadcrumb"></div>
<div class="fb-actions">
<button id="fb-refresh-btn" class="fb-btn">Refresh</button>
</div>
<div class="fm-layout">
<div class="fm-panel">
<div class="fm-toolbar">
<select id="fm-pod-select" onchange="selectPod()" style="padding:6px 8px;background:var(--bg-card);color:var(--text);border:1px solid var(--border);border-radius:4px;font-size:12px;max-width:180px;">
<option value="">Loading...</option>
</select>
<span style="flex:1;"></span>
<input type="file" id="fm-upload-input" style="display:none;" onchange="uploadFile()">
<button class="fm-btn" onclick="document.getElementById('fm-upload-input').click()">&#8682; Upload</button>
<button class="fm-btn" onclick="loadFiles(currentPath)">&#8635; Refresh</button>
</div>
<div id="fb-error" class="error-banner danger" style="display:none;"></div>
<div id="fb-file-list" class="fb-file-list"></div>
<div class="fm-breadcrumb" id="fm-breadcrumb"></div>
<div id="fm-error" class="error-banner danger" style="display:none;"></div>
<div id="fm-file-list" class="fm-file-list"></div>
</div>
<div class="fm-viewer" id="fm-viewer">
<div id="fm-viewer-empty" class="fm-viewer-empty">Select a file to view or edit</div>
<div id="fm-viewer-toolbar" class="fm-viewer-toolbar" style="display:none;">
<span id="fm-viewer-name" style="font-size:13px;color:var(--text);"></span>
<span style="flex:1;"></span>
<button class="fm-btn" onclick="toggleEdit()" id="fm-edit-btn">&#9998; Edit</button>
<button class="fm-btn" onclick="saveFile()" id="fm-save-btn" style="display:none;">&#128190; Save</button>
<button class="fm-btn" onclick="cancelEdit()" id="fm-cancel-btn" style="display:none;">Cancel</button>
<button class="fm-btn" onclick="downloadCurrent()">&#128229; Download</button>
<button class="fm-btn danger" onclick="deleteCurrent()">&#128465; Delete</button>
</div>
<pre id="fm-viewer-content" class="fm-viewer-content" style="display:none;"></pre>
<textarea id="fm-editor-content" class="fm-editor-content" style="display:none;" spellcheck="false"></textarea>
<div id="fm-viewer-status" class="error-banner success" style="display:none;"></div>
</div>
</div>
<style>
.fb-toolbar { display: flex; justify-content: space-between; align-items: center; padding: 12px; background: var(--bg-hover); border-radius: 6px; margin-bottom: 12px; }
.fb-breadcrumb { display: flex; gap: 4px; align-items: center; flex-wrap: wrap; }
.fb-breadcrumb span { cursor: pointer; color: var(--primary); font-family: monospace; font-size: 13px; }
.fb-breadcrumb span:hover { text-decoration: underline; }
.fb-breadcrumb .sep { color: var(--text-muted); cursor: default; font-size: 11px; }
.fb-breadcrumb .sep:hover { text-decoration: none; }
.fb-breadcrumb .current { color: var(--text); cursor: default; }
.fb-breadcrumb .current:hover { text-decoration: none; }
.fb-actions { display: flex; gap: 8px; }
.fb-btn { padding: 6px 14px; background: var(--bg-card); color: var(--text); border: 1px solid var(--border); border-radius: 4px; cursor: pointer; font-size: 13px; }
.fb-btn:hover { background: var(--bg-hover); }
.fb-file-list { }
.fb-item { display: flex; align-items: center; padding: 8px 12px; border-bottom: 1px solid var(--border); cursor: pointer; }
.fb-item:hover { background: var(--bg-hover); }
.fb-item:last-child { border-bottom: none; }
.fb-icon { width: 24px; text-align: center; margin-right: 8px; font-size: 16px; }
.fb-icon.dir { color: var(--accent); }
.fb-name { flex: 1; font-size: 13px; }
.fb-name.dir { color: var(--accent); font-weight: 500; cursor: pointer; }
.fb-name.file { cursor: pointer; }
.fb-name:hover { text-decoration: underline; }
.fb-size { color: var(--text-muted); font-size: 12px; margin-right: 12px; min-width: 70px; text-align: right; }
.fb-date { color: var(--text-muted); font-size: 12px; margin-right: 12px; min-width: 130px; }
.fb-perms { color: var(--text-muted); font-size: 11px; font-family: monospace; margin-right: 12px; min-width: 80px; }
.fb-empty { padding: 20px; text-align: center; color: var(--text-muted); }
.fm-layout { display: grid; grid-template-columns: 340px 1fr; gap: 16px; min-height: calc(100vh - 200px); }
.fm-panel { min-height: 0; display: flex; flex-direction: column; }
.fm-toolbar { display: flex; gap: 8px; margin-bottom: 10px; }
.fm-btn { padding: 6px 12px; background: var(--bg-card); color: var(--text); border: 1px solid var(--border); border-radius: 4px; cursor: pointer; font-size: 12px; white-space: nowrap; }
.fm-btn:hover { background: var(--bg-hover); }
.fm-btn.danger { color: var(--danger); border-color: var(--danger); }
.fm-breadcrumb { display: flex; gap: 4px; align-items: center; flex-wrap: wrap; font-size: 12px; margin-bottom: 8px; min-height: 20px; }
.fm-breadcrumb span { cursor: pointer; color: var(--primary); font-family: monospace; }
.fm-breadcrumb span:hover { text-decoration: underline; }
.fm-breadcrumb .sep { color: var(--text-muted); cursor: default; }
.fm-breadcrumb .sep:hover { text-decoration: none; }
.fm-breadcrumb .current { color: var(--text); cursor: default; }
.fm-breadcrumb .current:hover { text-decoration: none; }
.fm-file-list { flex: 1; overflow-y: auto; border: 1px solid var(--border); border-radius: 6px; }
.fm-item { display: flex; align-items: center; padding: 6px 10px; border-bottom: 1px solid var(--border); cursor: pointer; font-size: 12px; }
.fm-item:hover { background: var(--bg-hover); }
.fm-item.selected { background: var(--bg-hover); border-left: 3px solid var(--primary); }
.fm-item:last-child { border-bottom: none; }
.fm-icon { width: 20px; text-align: center; margin-right: 6px; font-size: 14px; flex-shrink: 0; }
.fm-icon.dir { color: var(--accent); }
.fm-fname { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.fm-fname.dir { color: var(--accent); font-weight: 500; }
.fm-fsize { color: var(--text-muted); font-size: 11px; margin-left: 8px; flex-shrink: 0; }
.fm-delete-btn { padding: 2px 6px; background: none; border: none; color: var(--danger); cursor: pointer; font-size: 13px; flex-shrink: 0; }
.fm-delete-btn:hover { background: var(--bg-hover); border-radius: 3px; }
.fm-empty { padding: 20px; text-align: center; color: var(--text-muted); font-size: 12px; }
.fm-viewer { display: flex; flex-direction: column; border: 1px solid var(--border); border-radius: 6px; min-height: 0; }
.fm-viewer-toolbar { display: flex; align-items: center; gap: 6px; padding: 8px 12px; border-bottom: 1px solid var(--border); background: var(--bg-hover); border-radius: 6px 6px 0 0; }
.fm-viewer-empty { flex: 1; display: flex; align-items: center; justify-content: center; color: var(--text-muted); font-size: 14px; }
.fm-viewer-content { flex: 1; margin: 0; padding: 12px; overflow: auto; font-family: 'Consolas','Courier New',monospace; font-size: 12px; line-height: 1.5; white-space: pre-wrap; word-break: break-all; background: var(--bg); color: var(--text); border: none; border-radius: 0 0 6px 6px; }
.fm-editor-content { flex: 1; padding: 12px; background: var(--bg); color: var(--text); border: none; font-family: 'Consolas','Courier New',monospace; font-size: 12px; line-height: 1.5; resize: none; outline: none; border-radius: 0 0 6px 6px; }
@media (max-width: 768px) {
.fm-layout { grid-template-columns: 1fr; grid-template-rows: auto 1fr; }
.fm-viewer { min-height: 300px; }
}
</style>
{% endblock %}
@@ -53,118 +83,226 @@
{% block scripts %}
<script>
let currentPath = '/srv';
let currentFile = null;
let currentPod = '';
let originalContent = '';
function formatSize(sizeStr) {
if (!sizeStr || sizeStr === '-') return '';
const bytes = parseInt(sizeStr);
if (isNaN(bytes)) return sizeStr;
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
let i = 0;
let size = bytes;
while (size >= 1024 && i < units.length - 1) { size /= 1024; i++; }
return size.toFixed(i === 0 ? 0 : 1) + ' ' + units[i];
async function loadPods() {
const sel = document.getElementById('fm-pod-select');
try {
const r = await csrfFetch('/api/files/pods');
const d = await r.json();
sel.innerHTML = '';
if (d.success && d.pods) {
d.pods.forEach(p => { const o = document.createElement('option'); o.value = p; o.textContent = p; sel.appendChild(o); });
}
// Default to fb-deploy pod if available
const fbOpt = Array.from(sel.options).find(o => o.value.includes('fb-deploy'));
if (fbOpt) { fbOpt.selected = true; currentPod = fbOpt.value; }
else if (sel.options.length) { sel.options[0].selected = true; currentPod = sel.options[0].value; }
} catch(e) { sel.innerHTML = '<option>Error loading pods</option>'; }
}
function selectPod() {
currentPod = document.getElementById('fm-pod-select').value;
currentFile = null;
hideViewer();
loadFiles(currentPath);
}
function buildForm(path) {
const f = new FormData();
f.append('path', path);
if (currentPod) f.append('pod', currentPod);
return f;
}
function formatSize(s) {
if (!s || s === '-') return '';
const b = parseInt(s); if (isNaN(b)) return s;
const u = ['B','KB','MB','GB','TB']; let i = 0, sz = b;
while (sz >= 1024 && i < u.length-1) { sz /= 1024; i++; }
return sz.toFixed(i===0?0:1) + ' ' + u[i];
}
function renderBreadcrumb(path) {
const parts = path.split('/').filter(Boolean);
let html = '<span onclick="loadFiles(\'/\')">&#128193; /</span>';
let buildPath = '';
for (let i = 0; i < parts.length; i++) {
buildPath += '/' + parts[i];
const isLast = i === parts.length - 1;
if (isLast) {
html += `<span class="sep">/</span><span class="current">${parts[i]}</span>`;
} else {
html += `<span class="sep">/</span><span onclick="loadFiles('${buildPath.replace(/'/g, "\\'")}')">${parts[i]}</span>`;
}
const p = path.split('/').filter(Boolean);
let h = '<span onclick="loadFiles(\'/\')">&#128193; /</span>';
let b = '';
for (let i=0;i<p.length;i++) {
b += '/'+p[i];
h += i===p.length-1
? '<span class="sep">/</span><span class="current">'+p[i]+'</span>'
: '<span class="sep">/</span><span onclick="loadFiles(\''+b.replace(/'/g,"\\'")+'\')">'+p[i]+'</span>';
}
return html;
return h;
}
function selectFile(path) { currentFile = path; }
async function loadFiles(path) {
currentPath = path;
const list = document.getElementById('fb-file-list');
const error = document.getElementById('fb-error');
const breadcrumb = document.getElementById('fb-breadcrumb');
error.style.display = 'none';
list.innerHTML = '<div class="fb-empty">Loading...</div>';
breadcrumb.innerHTML = renderBreadcrumb(path);
currentPath = path; currentFile = null;
document.getElementById('fm-error').style.display = 'none';
document.getElementById('fm-breadcrumb').innerHTML = renderBreadcrumb(path);
const list = document.getElementById('fm-file-list');
list.innerHTML = '<div class="fm-empty">Loading...</div>';
try {
const form = new FormData();
form.append('path', path);
const resp = await csrfFetch('/api/files/list', { method: 'POST', body: form });
const data = await resp.json();
if (!data.success) {
list.innerHTML = '';
error.textContent = 'Error: ' + (data.error || 'Failed to list directory');
error.style.display = 'block';
return;
}
const files = data.files || [];
if (files.length === 0) {
list.innerHTML = '<div class="fb-empty">Empty directory</div>';
return;
}
const sorted = files.sort((a, b) => {
if (a.is_dir !== b.is_dir) return a.is_dir ? -1 : 1;
return a.name.localeCompare(b.name);
});
let html = '';
for (const f of sorted) {
const icon = f.is_dir ? '&#128193;' : getFileIcon(f.name);
const iconClass = f.is_dir ? 'dir' : '';
const nameClass = f.is_dir ? 'dir' : 'file';
const fullPath = (path === '/' ? '' : path) + '/' + f.name;
const safePath = fullPath.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
const safeName = f.name.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
const clickAction = f.is_dir
? `loadFiles('${safePath}')`
: `viewFile('${safePath}', '${safeName}')`;
html += `<div class="fb-item" onclick="${clickAction}">
<span class="fb-icon ${iconClass}">${icon}</span>
<span class="fb-name ${nameClass}">${f.name}</span>
<span class="fb-perms">${f.perms || ''}</span>
<span class="fb-size">${formatSize(f.size)}</span>
<span class="fb-date">${f.date || ''}</span>
const f = buildForm(path);
const r = await csrfFetch('/api/files/list',{method:'POST',body:f});
const d = await r.json();
if (!d.success) { list.innerHTML = ''; showErr(d.error); return; }
const files = (d.files||[]).sort((a,b)=>a.is_dir!==b.is_dir?a.is_dir?-1:1:a.name.localeCompare(b.name));
if (!files.length) { list.innerHTML = '<div class="fm-empty">Empty directory</div>'; return; }
let h = '';
for (const x of files) {
const fp = (path==='/'?'':path)+'/'+x.name;
const sp = fp.replace(/\\/g,'\\\\').replace(/'/g,"\\'");
const sn = x.name.replace(/\\/g,'\\\\').replace(/'/g,"\\'");
const icon = x.is_dir ? '&#128193;' : getIcon(x.name);
const action = x.is_dir ? `loadFiles('${sp}')` : `openFile('${sp}','${sn}')`;
h += `<div class="fm-item" onclick="${action}">
<span class="fm-icon ${x.is_dir?'dir':''}">${icon}</span>
<span class="fm-fname ${x.is_dir?'dir':''}">${x.name}</span>
<span class="fm-fsize">${formatSize(x.size)}</span>
<button class="fm-delete-btn" onclick="event.stopPropagation();deleteFile('${sp}','${sn}')" title="Delete">&#128465;</button>
</div>`;
}
list.innerHTML = html;
} catch (e) {
list.innerHTML = '';
error.textContent = 'Request failed: ' + e.message;
error.style.display = 'block';
}
list.innerHTML = h;
} catch(e) { list.innerHTML = ''; showErr(e.message); }
}
function getFileIcon(name) {
function getIcon(name) {
const icons = {log:'&#128221;',txt:'&#128196;',ini:'&#9881;',cfg:'&#9881;',json:'&#123364;',xml:'&#128196;',yaml:'&#128196;',yml:'&#128196;',sh:'&#9881;',ps1:'&#9881;',bat:'&#9881;',cmd:'&#9881;',zip:'&#128230;',gz:'&#128230;',tar:'&#128230;',sql:'&#128451;',db:'&#128451;',png:'&#127748;',jpg:'&#127748;',jpeg:'&#127748;',gif:'&#127748;',svg:'&#127748;',pdf:'&#128214;',md:'&#128214;',html:'&#127760;',css:'&#127912;',js:'&#128220;',py:'&#128220;'};
return icons[name.split('.').pop().toLowerCase()] || '&#128196;';
}
const textExts = ['log','txt','ini','cfg','json','xml','yaml','yml','sh','ps1','bat','cmd','md','html','css','js','py','conf','env'];
function openFile(path, name) {
currentFile = path;
const ext = name.split('.').pop().toLowerCase();
const icons = {
log: '&#128221;', txt: '&#128196;', ini: '&#9881;', cfg: '&#9881;',
json: '&#123364;', xml: '&#128196;', yaml: '&#128196;', yml: '&#128196;',
sh: '&#9881;', ps1: '&#9881;', bat: '&#9881;', cmd: '&#9881;',
zip: '&#128230;', gz: '&#128230;', tar: '&#128230;',
sql: '&#128451;', db: '&#128451;', sqlite: '&#128451;',
png: '&#127748;', jpg: '&#127748;', jpeg: '&#127748;', gif: '&#127748;', svg: '&#127748;',
pdf: '&#128214;',
md: '&#128214;', html: '&#127760;', css: '&#127912;', js: '&#128220;',
py: '&#128220;',
};
return icons[ext] || '&#128196;';
if (!textExts.includes(ext)) { downloadFile(path); return; }
document.getElementById('fm-viewer-empty').style.display = 'none';
document.getElementById('fm-viewer-status').style.display = 'none';
document.getElementById('fm-viewer-content').style.display = 'block';
document.getElementById('fm-editor-content').style.display = 'none';
document.getElementById('fm-edit-btn').style.display = 'inline-block';
document.getElementById('fm-save-btn').style.display = 'none';
document.getElementById('fm-cancel-btn').style.display = 'none';
document.getElementById('fm-viewer-toolbar').style.display = 'flex';
document.getElementById('fm-viewer-name').textContent = name;
const content = document.getElementById('fm-viewer-content');
content.textContent = 'Loading...';
fetch('/api/files/view?path=' + encodeURIComponent(path) + '&pod=' + encodeURIComponent(currentPod))
.then(r=>r.json()).then(d=>{
if(!d.success){content.textContent='Error: '+(d.error||'Load failed');return;}
originalContent = d.content;
content.textContent = d.content;
}).catch(e=>{content.textContent='Error: '+e.message;});
// Highlight selected file
document.querySelectorAll('.fm-item').forEach(el=>el.classList.remove('selected'));
}
function viewFile(path, name) {
const ext = name.split('.').pop().toLowerCase();
const textExts = ['log', 'txt', 'ini', 'cfg', 'json', 'xml', 'yaml', 'yml', 'sh', 'ps1', 'bat', 'cmd', 'md', 'html', 'css', 'js', 'py', 'conf', 'env'];
if (textExts.includes(ext)) {
window.open(`/files/view?path=${encodeURIComponent(path)}`, '_blank');
} else {
alert('File preview is only available for text files. Download via SSH to view this file.');
}
function toggleEdit() {
document.getElementById('fm-viewer-content').style.display = 'none';
document.getElementById('fm-editor-content').style.display = 'block';
document.getElementById('fm-editor-content').value = originalContent;
document.getElementById('fm-editor-content').focus();
document.getElementById('fm-edit-btn').style.display = 'none';
document.getElementById('fm-save-btn').style.display = 'inline-block';
document.getElementById('fm-cancel-btn').style.display = 'inline-block';
}
document.getElementById('fb-refresh-btn')?.addEventListener('click', () => loadFiles(currentPath));
function cancelEdit() {
document.getElementById('fm-editor-content').style.display = 'none';
document.getElementById('fm-viewer-content').style.display = 'block';
document.getElementById('fm-edit-btn').style.display = 'inline-block';
document.getElementById('fm-save-btn').style.display = 'none';
document.getElementById('fm-cancel-btn').style.display = 'none';
}
async function saveFile() {
if (!currentFile) return;
const content = document.getElementById('fm-editor-content').value;
const btn = document.getElementById('fm-save-btn');
btn.textContent = 'Saving...'; btn.disabled = true;
try {
const f = buildForm(currentFile); f.append('content', content);
const r = await csrfFetch('/api/files/save',{method:'POST',body:f});
const d = await r.json();
if(!d.success){showErr(d.error);return;}
originalContent = content;
document.getElementById('fm-viewer-content').textContent = content;
cancelEdit();
document.getElementById('fm-viewer-status').textContent = 'Saved'; document.getElementById('fm-viewer-status').style.display='block';
setTimeout(()=>document.getElementById('fm-viewer-status').style.display='none',2000);
} catch(e) { showErr(e.message); }
btn.textContent = '💾 Save'; btn.disabled = false;
}
function downloadCurrent() {
if (!currentFile) return;
downloadFile(currentFile);
}
async function deleteCurrent() {
if (!currentFile) return;
const name = currentFile.split('/').pop();
if (!confirm('Delete "'+name+'"? This cannot be undone.')) return;
try {
const f = buildForm(currentFile);
const r = await csrfFetch('/api/files/delete',{method:'POST',body:f});
const d = await r.json();
if(d.success){currentFile=null;document.getElementById('fm-viewer-toolbar').style.display='none';document.getElementById('fm-viewer-content').style.display='none';document.getElementById('fm-viewer-empty').style.display='flex';loadFiles(currentPath);}
else showErr(d.error||'Delete failed');
} catch(e) { showErr(e.message); }
}
async function uploadFile() {
const input = document.getElementById('fm-upload-input');
const file = input.files[0]; if(!file)return;
const f = buildForm(currentPath); f.append('file',file);
try {
const r = await csrfFetch('/api/files/upload',{method:'POST',body:f});
const d = await r.json();
if(d.success){input.value='';loadFiles(currentPath);}
else showErr('Upload: '+(d.error||'Unknown'));
} catch(e) { showErr(e.message); }
}
async function downloadFile(path) {
try {
const f = buildForm(path);
const r = await csrfFetch('/api/files/download',{method:'POST',body:f});
const d = await r.json();
if(!d.success){alert('Download failed: '+(d.error||'Unknown'));return;}
const chars=atob(d.content); const bytes=new Uint8Array(chars.length);
for(let i=0;i<chars.length;i++)bytes[i]=chars.charCodeAt(i);
const blob=new Blob([bytes]),url=URL.createObjectURL(blob);
const a=document.createElement('a');a.href=url;a.download=d.filename;
document.body.appendChild(a);a.click();document.body.removeChild(a);URL.revokeObjectURL(url);
} catch(e) { alert('Download failed: '+e.message); }
}
async function deleteFile(path,name) {
if(!confirm('Delete "'+name+'"? This cannot be undone.'))return;
try {
const f = buildForm(path);
const r = await csrfFetch('/api/files/delete',{method:'POST',body:f});
const d = await r.json();
if(d.success){ if(currentFile===path){currentFile=null;document.getElementById('fm-viewer-toolbar').style.display='none';document.getElementById('fm-viewer-content').style.display='none';document.getElementById('fm-viewer-empty').style.display='flex';} loadFiles(currentPath); }
else showErr(d.error||'Delete failed');
} catch(e) { showErr(e.message); }
}
function showErr(msg) { const e=document.getElementById('fm-error');e.textContent='Error: '+msg;e.style.display='block'; }
function hideErr() { document.getElementById('fm-error').style.display='none'; }
function hideViewer() { document.getElementById('fm-viewer-toolbar').style.display='none'; document.getElementById('fm-viewer-content').style.display='none'; document.getElementById('fm-editor-content').style.display='none'; document.getElementById('fm-viewer-empty').style.display='flex'; }
loadPods();
loadFiles('/srv');
</script>
{% endblock %}