| 1 | /* ========================================================= |
| 2 | FILE MANAGER — CLIENT SPA |
| 3 | ========================================================= |
| 4 | Architecture: |
| 5 | - RSA-OAEP + AES-256-GCM hybrid encryption via Web Crypto API |
| 6 | - Token is stored in localStorage to survive full page refresh |
| 7 | - Token is sent as Bearer header on every API call |
| 8 | - Fingerprint (derived from navigator info) locks the token to this browser |
| 9 | ========================================================= */ |
| 10 | 'use strict'; |
| 11 | |
| 12 | // ─────────────────────────────────────────────────────────────────────────── |
| 13 | // STATE |
| 14 | // ─────────────────────────────────────────────────────────────────────────── |
| 15 | const STATE = { |
| 16 | token: null, // decrypted JWT string |
| 17 | username: null, |
| 18 | isAdmin: false, |
| 19 | permissions: {}, |
| 20 | roots: [], // [{ label, path }] |
| 21 | currentDir: null, // absolute path currently shown (null = roots view) |
| 22 | currentRoot: null, // { label, path } of the active root |
| 23 | items: [], // current directory listing |
| 24 | selectedItem: null, // item object selected in sidebar |
| 25 | |
| 26 | // Ephemeral key pair per session (client-side) |
| 27 | clientPrivateKey: null, |
| 28 | clientPublicKeyJwk: null, |
| 29 | |
| 30 | // Server public key for encrypting login |
| 31 | serverPublicKeyJwk: null, |
| 32 | |
| 33 | // Stable per-browser binding id used in fingerprint derivation |
| 34 | clientBindingId: null, |
| 35 | |
| 36 | // Persisted view state |
| 37 | restoreDir: null, |
| 38 | restoreRootPath: null, |
| 39 | lastOperationAt: null, |
| 40 | |
| 41 | // Background refresh state |
| 42 | autoRefreshTimer: null, |
| 43 | uploadInProgress: false, |
| 44 | }; |
| 45 | |
| 46 | const SESSION_KEY = 'filemanager.session.v1'; |
| 47 | const SESSION_IDLE_TIMEOUT_MS = 60 * 60 * 1000; // 1 hour |
| 48 | const CLIENT_BINDING_KEY = 'filemanager.client-binding-id.v1'; |
| 49 | |
| 50 | // ─────────────────────────────────────────────────────────────────────────── |
| 51 | // CRYPTO HELPERS (Web Crypto API) |
| 52 | // ─────────────────────────────────────────────────────────────────────────── |
| 53 | |
| 54 | async function generateClientKeyPair() { |
| 55 | if (!hasWebCrypto()) return; |
| 56 | const kp = await crypto.subtle.generateKey( |
| 57 | { name: 'RSA-OAEP', modulusLength: 2048, publicExponent: new Uint8Array([1,0,1]), hash: 'SHA-256' }, |
| 58 | true, |
| 59 | ['encrypt', 'decrypt'], |
| 60 | ); |
| 61 | STATE.clientPrivateKey = kp.privateKey; |
| 62 | STATE.clientPublicKeyJwk = await crypto.subtle.exportKey('jwk', kp.publicKey); |
| 63 | } |
| 64 | |
| 65 | /** |
| 66 | * Hybrid-encrypt a JS object using the server's RSA public key. |
| 67 | * Returns { encryptedKey, iv, ciphertext, tag } all as base64 strings. |
| 68 | */ |
| 69 | async function hybridEncryptForServer(obj) { |
| 70 | if (!hasWebCrypto() || !STATE.serverPublicKeyJwk) { |
| 71 | return { plaintext: obj }; |
| 72 | } |
| 73 | |
| 74 | const serverPub = await crypto.subtle.importKey( |
| 75 | 'jwk', STATE.serverPublicKeyJwk, |
| 76 | { name: 'RSA-OAEP', hash: 'SHA-256' }, |
| 77 | false, ['encrypt'], |
| 78 | ); |
| 79 | |
| 80 | const plaintext = new TextEncoder().encode(JSON.stringify(obj)); |
| 81 | const aesKey = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt']); |
| 82 | const iv = crypto.getRandomValues(new Uint8Array(12)); |
| 83 | const gcmResult = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, aesKey, plaintext); |
| 84 | |
| 85 | // gcmResult = ciphertext || tag (last 16 bytes are auth tag) |
| 86 | const gcmBytes = new Uint8Array(gcmResult); |
| 87 | const ciphertext = gcmBytes.slice(0, gcmBytes.length - 16); |
| 88 | const tag = gcmBytes.slice(gcmBytes.length - 16); |
| 89 | |
| 90 | const rawAes = await crypto.subtle.exportKey('raw', aesKey); |
| 91 | const encryptedKey = await crypto.subtle.encrypt({ name: 'RSA-OAEP' }, serverPub, rawAes); |
| 92 | |
| 93 | return { |
| 94 | encryptedKey: b64(encryptedKey), |
| 95 | iv: b64(iv), |
| 96 | ciphertext: b64(ciphertext), |
| 97 | tag: b64(tag), |
| 98 | }; |
| 99 | } |
| 100 | |
| 101 | /** |
| 102 | * Hybrid-decrypt a payload encrypted by the server for us (using our public key). |
| 103 | */ |
| 104 | async function hybridDecryptFromServer(payload) { |
| 105 | if (!payload) return null; |
| 106 | if (payload.token) return payload.token; |
| 107 | if (!hasWebCrypto()) return null; |
| 108 | |
| 109 | const encryptedKey = unb64(payload.encryptedKey); |
| 110 | const iv = unb64(payload.iv); |
| 111 | const ciphertext = unb64(payload.ciphertext); |
| 112 | const tag = unb64(payload.tag); |
| 113 | |
| 114 | const rawAes = await crypto.subtle.decrypt( |
| 115 | { name: 'RSA-OAEP' }, STATE.clientPrivateKey, encryptedKey, |
| 116 | ); |
| 117 | |
| 118 | const aesKey = await crypto.subtle.importKey('raw', rawAes, { name: 'AES-GCM' }, false, ['decrypt']); |
| 119 | |
| 120 | // Recombine ciphertext + tag for AES-GCM |
| 121 | const combined = new Uint8Array(ciphertext.byteLength + tag.byteLength); |
| 122 | combined.set(new Uint8Array(ciphertext)); |
| 123 | combined.set(new Uint8Array(tag), ciphertext.byteLength); |
| 124 | |
| 125 | const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, aesKey, combined); |
| 126 | return new TextDecoder().decode(plain); |
| 127 | } |
| 128 | |
| 129 | // ─────────────────────────────────────────────────────────────────────────── |
| 130 | // UTIL |
| 131 | // ─────────────────────────────────────────────────────────────────────────── |
| 132 | |
| 133 | function b64(buf) { |
| 134 | return btoa(String.fromCharCode(...new Uint8Array(buf instanceof ArrayBuffer ? buf : buf.buffer))); |
| 135 | } |
| 136 | |
| 137 | function hasWebCrypto() { |
| 138 | return !!(window.crypto && window.crypto.subtle); |
| 139 | } |
| 140 | |
| 141 | function unb64(str) { |
| 142 | const binary = atob(str); |
| 143 | const buf = new Uint8Array(binary.length); |
| 144 | for (let i = 0; i < binary.length; i++) buf[i] = binary.charCodeAt(i); |
| 145 | return buf.buffer; |
| 146 | } |
| 147 | |
| 148 | /** Stable browser fingerprint (not stored, derived fresh each load) */ |
| 149 | function getFingerprint() { |
| 150 | const binding = getOrCreateClientBindingId(); |
| 151 | const nav = navigator; |
| 152 | |
| 153 | // Keep this stable: avoid viewport/screen metrics that can change when |
| 154 | // devtools opens, orientation changes, or window state changes. |
| 155 | return [ |
| 156 | binding, |
| 157 | nav.userAgent || '', |
| 158 | nav.language, |
| 159 | nav.platform || nav.userAgentData?.platform || '', |
| 160 | Intl.DateTimeFormat().resolvedOptions().timeZone, |
| 161 | ].join('|'); |
| 162 | } |
| 163 | |
| 164 | function randomIdHex(bytes = 16) { |
| 165 | const arr = new Uint8Array(bytes); |
| 166 | if (window.crypto && typeof window.crypto.getRandomValues === 'function') { |
| 167 | window.crypto.getRandomValues(arr); |
| 168 | } else { |
| 169 | for (let i = 0; i < arr.length; i++) arr[i] = Math.floor(Math.random() * 256); |
| 170 | } |
| 171 | return Array.from(arr).map(n => n.toString(16).padStart(2, '0')).join(''); |
| 172 | } |
| 173 | |
| 174 | function getOrCreateClientBindingId() { |
| 175 | if (STATE.clientBindingId) return STATE.clientBindingId; |
| 176 | |
| 177 | try { |
| 178 | const existing = localStorage.getItem(CLIENT_BINDING_KEY); |
| 179 | if (existing && typeof existing === 'string') { |
| 180 | STATE.clientBindingId = existing; |
| 181 | return existing; |
| 182 | } |
| 183 | } catch { |
| 184 | // Ignore storage read errors. |
| 185 | } |
| 186 | |
| 187 | const created = randomIdHex(16); |
| 188 | STATE.clientBindingId = created; |
| 189 | |
| 190 | try { |
| 191 | localStorage.setItem(CLIENT_BINDING_KEY, created); |
| 192 | } catch { |
| 193 | // Ignore storage write errors; in-memory fallback still keeps this stable |
| 194 | // for the current page session. |
| 195 | } |
| 196 | |
| 197 | return created; |
| 198 | } |
| 199 | |
| 200 | function formatBytes(bytes) { |
| 201 | if (bytes == null) return '—'; |
| 202 | if (bytes < 1024) return bytes + ' B'; |
| 203 | if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB'; |
| 204 | if (bytes < 1073741824) return (bytes / 1048576).toFixed(1) + ' MB'; |
| 205 | return (bytes / 1073741824).toFixed(2) + ' GB'; |
| 206 | } |
| 207 | |
| 208 | function extOf(name) { |
| 209 | const i = name.lastIndexOf('.'); |
| 210 | return i >= 0 ? name.slice(i + 1).toLowerCase() : ''; |
| 211 | } |
| 212 | |
| 213 | function getPathSep(basePath) { |
| 214 | return basePath && basePath.includes('\\') ? '\\' : '/'; |
| 215 | } |
| 216 | |
| 217 | function joinServerPath(basePath, segment) { |
| 218 | const sep = getPathSep(basePath); |
| 219 | const base = String(basePath || '').replace(/[\\/]+$/, ''); |
| 220 | return base + sep + segment; |
| 221 | } |
| 222 | |
| 223 | function samePath(a, b) { |
| 224 | if (!a || !b) return false; |
| 225 | return String(a).toLowerCase() === String(b).toLowerCase(); |
| 226 | } |
| 227 | |
| 228 | function pathInside(child, root) { |
| 229 | if (!child || !root) return false; |
| 230 | if (samePath(child, root)) return true; |
| 231 | const sep = getPathSep(root); |
| 232 | return String(child).toLowerCase().startsWith((String(root) + sep).toLowerCase()); |
| 233 | } |
| 234 | |
| 235 | function saveSessionState() { |
| 236 | if (!STATE.token) return; |
| 237 | const now = Date.now(); |
| 238 | STATE.lastOperationAt = now; |
| 239 | const payload = { |
| 240 | token: STATE.token, |
| 241 | dir: STATE.currentDir || null, |
| 242 | rootPath: STATE.currentRoot ? STATE.currentRoot.path : null, |
| 243 | lastOperationAt: STATE.lastOperationAt, |
| 244 | }; |
| 245 | try { |
| 246 | localStorage.setItem(SESSION_KEY, JSON.stringify(payload)); |
| 247 | } catch { |
| 248 | // Ignore storage errors (private mode/full quota). |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | function loadSessionState() { |
| 253 | try { |
| 254 | const raw = localStorage.getItem(SESSION_KEY); |
| 255 | if (!raw) return null; |
| 256 | const parsed = JSON.parse(raw); |
| 257 | if (!parsed || typeof parsed.token !== 'string') return null; |
| 258 | if (!Number.isFinite(parsed.lastOperationAt)) return null; |
| 259 | |
| 260 | if (Date.now() - parsed.lastOperationAt > SESSION_IDLE_TIMEOUT_MS) { |
| 261 | clearSessionState(); |
| 262 | return null; |
| 263 | } |
| 264 | |
| 265 | return parsed; |
| 266 | } catch { |
| 267 | return null; |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | function clearSessionState() { |
| 272 | try { localStorage.removeItem(SESSION_KEY); } catch { /* ignore */ } |
| 273 | } |
| 274 | |
| 275 | // ─────────────────────────────────────────────────────────────────────────── |
| 276 | // API |
| 277 | // ─────────────────────────────────────────────────────────────────────────── |
| 278 | |
| 279 | async function api(method, path, body, opts = {}) { |
| 280 | const headers = { 'Content-Type': 'application/json' }; |
| 281 | const noAutoLogout = !!opts.noAutoLogout; |
| 282 | if (STATE.token) { |
| 283 | headers['Authorization'] = 'Bearer ' + STATE.token; |
| 284 | headers['X-Fp'] = getFingerprint(); |
| 285 | } |
| 286 | const fetchOpts = { ...opts }; |
| 287 | delete fetchOpts.noAutoLogout; |
| 288 | const res = await fetch('/api' + path, { |
| 289 | method, |
| 290 | headers, |
| 291 | body: body != null ? JSON.stringify(body) : undefined, |
| 292 | ...fetchOpts, |
| 293 | }); |
| 294 | if (!res.ok) { |
| 295 | const j = await res.json().catch(() => ({})); |
| 296 | // Session-expired → force re-login |
| 297 | if (res.status === 401) { |
| 298 | if (!noAutoLogout) logout(); |
| 299 | return null; |
| 300 | } |
| 301 | throw new Error(j.error || res.statusText); |
| 302 | } |
| 303 | if (STATE.token && !path.startsWith('/auth/server-key') && !path.startsWith('/auth/setup-needed')) { |
| 304 | saveSessionState(); |
| 305 | } |
| 306 | return res.json(); |
| 307 | } |
| 308 | |
| 309 | // ─────────────────────────────────────────────────────────────────────────── |
| 310 | // TOAST |
| 311 | // ─────────────────────────────────────────────────────────────────────────── |
| 312 | |
| 313 | function toast(msg, type = '') { |
| 314 | const el = document.createElement('div'); |
| 315 | el.className = 'toast-msg' + (type ? ' ' + type : ''); |
| 316 | el.textContent = msg; |
| 317 | document.getElementById('toast').appendChild(el); |
| 318 | setTimeout(() => el.remove(), 3500); |
| 319 | } |
| 320 | |
| 321 | // ─────────────────────────────────────────────────────────────────────────── |
| 322 | // DIALOG MODALS — centralised replacements for alert / confirm / prompt |
| 323 | // ─────────────────────────────────────────────────────────────────────────── |
| 324 | |
| 325 | /** |
| 326 | * Show a confirmation dialog. |
| 327 | * @param {string} title |
| 328 | * @param {string} message |
| 329 | * @returns {Promise<boolean>} true = OK, false = Cancel |
| 330 | */ |
| 331 | function showConfirm(title, message) { |
| 332 | return new Promise((resolve) => { |
| 333 | const overlay = document.getElementById('confirm-modal'); |
| 334 | document.getElementById('confirm-modal-title').textContent = title; |
| 335 | document.getElementById('confirm-modal-message').textContent = message; |
| 336 | overlay.classList.remove('hidden'); |
| 337 | |
| 338 | const ok = document.getElementById('confirm-modal-ok'); |
| 339 | const cancel = document.getElementById('confirm-modal-cancel'); |
| 340 | |
| 341 | function finish(result) { |
| 342 | overlay.classList.add('hidden'); |
| 343 | ok.removeEventListener('click', onOk); |
| 344 | cancel.removeEventListener('click', onCancel); |
| 345 | resolve(result); |
| 346 | } |
| 347 | function onOk() { finish(true); } |
| 348 | function onCancel() { finish(false); } |
| 349 | |
| 350 | ok.addEventListener('click', onOk); |
| 351 | cancel.addEventListener('click', onCancel); |
| 352 | ok.focus(); |
| 353 | }); |
| 354 | } |
| 355 | |
| 356 | /** |
| 357 | * Show a text-input dialog. |
| 358 | * @param {string} title |
| 359 | * @param {string} [message] — optional helper text shown above the input |
| 360 | * @param {string} [defaultValue] — pre-filled value |
| 361 | * @returns {Promise<string|null>} string = submitted value, null = cancelled |
| 362 | */ |
| 363 | function showPrompt(title, message = '', defaultValue = '') { |
| 364 | return new Promise((resolve) => { |
| 365 | const overlay = document.getElementById('prompt-modal'); |
| 366 | const msgEl = document.getElementById('prompt-modal-message'); |
| 367 | const input = document.getElementById('prompt-modal-input'); |
| 368 | const errorEl = document.getElementById('prompt-modal-error'); |
| 369 | const form = document.getElementById('prompt-modal-form'); |
| 370 | const cancel = document.getElementById('prompt-modal-cancel'); |
| 371 | |
| 372 | document.getElementById('prompt-modal-title').textContent = title; |
| 373 | msgEl.textContent = message; |
| 374 | msgEl.classList.toggle('hidden', !message); |
| 375 | input.value = defaultValue; |
| 376 | errorEl.classList.add('hidden'); |
| 377 | overlay.classList.remove('hidden'); |
| 378 | input.focus(); |
| 379 | input.select(); |
| 380 | |
| 381 | function finish(result) { |
| 382 | overlay.classList.add('hidden'); |
| 383 | form.removeEventListener('submit', onSubmit); |
| 384 | cancel.removeEventListener('click', onCancel); |
| 385 | resolve(result); |
| 386 | } |
| 387 | function onSubmit(e) { |
| 388 | e.preventDefault(); |
| 389 | finish(input.value); |
| 390 | } |
| 391 | function onCancel() { finish(null); } |
| 392 | |
| 393 | form.addEventListener('submit', onSubmit); |
| 394 | cancel.addEventListener('click', onCancel); |
| 395 | }); |
| 396 | } |
| 397 | |
| 398 | /** |
| 399 | * Show an overwrite-decision dialog for a single file conflict. |
| 400 | * @param {string} filename |
| 401 | * @returns {Promise<'yes'|'no'|'all'|'none'>} |
| 402 | */ |
| 403 | function showOverwrite(filename) { |
| 404 | return new Promise((resolve) => { |
| 405 | const overlay = document.getElementById('overwrite-modal'); |
| 406 | document.getElementById('overwrite-modal-filename').textContent = filename; |
| 407 | overlay.classList.remove('hidden'); |
| 408 | |
| 409 | const btnYes = document.getElementById('overwrite-modal-yes'); |
| 410 | const btnNo = document.getElementById('overwrite-modal-no'); |
| 411 | const btnAll = document.getElementById('overwrite-modal-all'); |
| 412 | const btnSkipAll = document.getElementById('overwrite-modal-skip-all'); |
| 413 | |
| 414 | function finish(result) { |
| 415 | overlay.classList.add('hidden'); |
| 416 | btnYes.removeEventListener('click', onYes); |
| 417 | btnNo.removeEventListener('click', onNo); |
| 418 | btnAll.removeEventListener('click', onAll); |
| 419 | btnSkipAll.removeEventListener('click', onSkipAll); |
| 420 | resolve(result); |
| 421 | } |
| 422 | function onYes() { finish('yes'); } |
| 423 | function onNo() { finish('no'); } |
| 424 | function onAll() { finish('all'); } |
| 425 | function onSkipAll() { finish('none'); } |
| 426 | |
| 427 | btnYes.addEventListener('click', onYes); |
| 428 | btnNo.addEventListener('click', onNo); |
| 429 | btnAll.addEventListener('click', onAll); |
| 430 | btnSkipAll.addEventListener('click', onSkipAll); |
| 431 | btnNo.focus(); |
| 432 | }); |
| 433 | } |
| 434 | |
| 435 | // ─────────────────────────────────────────────────────────────────────────── |
| 436 | // AUTH FLOW |
| 437 | // ─────────────────────────────────────────────────────────────────────────── |
| 438 | |
| 439 | function showAuthOverlay(setupMode = false) { |
| 440 | document.getElementById('app').classList.add('hidden'); |
| 441 | const overlay = document.getElementById('auth-overlay'); |
| 442 | overlay.classList.remove('hidden'); |
| 443 | document.getElementById('auth-title').textContent = setupMode ? 'Create Admin Account' : 'Sign In'; |
| 444 | document.getElementById('auth-subtitle').classList.toggle('hidden', !setupMode); |
| 445 | const submitBtn = document.getElementById('auth-submit'); |
| 446 | submitBtn.disabled = false; |
| 447 | submitBtn.textContent = setupMode ? 'Create Account' : 'Sign In'; |
| 448 | document.getElementById('auth-error').classList.add('hidden'); |
| 449 | document.getElementById('auth-username').value = ''; |
| 450 | document.getElementById('auth-password').value = ''; |
| 451 | document.getElementById('auth-username').focus(); |
| 452 | document.getElementById('auth-form').dataset.mode = setupMode ? 'setup' : 'login'; |
| 453 | } |
| 454 | |
| 455 | function showApp() { |
| 456 | document.getElementById('auth-overlay').classList.add('hidden'); |
| 457 | document.getElementById('app').classList.remove('hidden'); |
| 458 | document.getElementById('btn-admin').classList.toggle('hidden', !STATE.isAdmin); |
| 459 | startAutoRefresh(); |
| 460 | } |
| 461 | |
| 462 | async function initAuth() { |
| 463 | // Always generate a fresh key pair so each page-load session is independent |
| 464 | await generateClientKeyPair().catch(() => { |
| 465 | toast('Secure crypto unavailable in this browser context; using compatibility login mode.', 'err'); |
| 466 | }); |
| 467 | |
| 468 | // Fetch server public key |
| 469 | const { publicKey } = await api('GET', '/auth/server-key').catch(() => ({ publicKey: null })); |
| 470 | if (publicKey) STATE.serverPublicKeyJwk = publicKey; |
| 471 | if (!publicKey && hasWebCrypto()) { toast('Could not reach server.', 'err'); return; } |
| 472 | STATE.serverPublicKeyJwk = publicKey; |
| 473 | |
| 474 | // Check whether first-run setup is needed |
| 475 | const { needed } = await api('GET', '/auth/setup-needed').catch(() => ({ needed: false })); |
| 476 | |
| 477 | if (!needed) { |
| 478 | const saved = loadSessionState(); |
| 479 | if (saved && saved.token) { |
| 480 | STATE.token = saved.token; |
| 481 | STATE.restoreDir = saved.dir || null; |
| 482 | STATE.restoreRootPath = saved.rootPath || null; |
| 483 | STATE.lastOperationAt = saved.lastOperationAt; |
| 484 | |
| 485 | const me = await api('GET', '/auth/me', null, { noAutoLogout: true }).catch(() => null); |
| 486 | if (me) { |
| 487 | STATE.username = me.username; |
| 488 | STATE.isAdmin = me.isAdmin; |
| 489 | STATE.permissions = me.permissions; |
| 490 | showApp(); |
| 491 | await loadRoots({ |
| 492 | preferredDir: STATE.restoreDir, |
| 493 | preferredRootPath: STATE.restoreRootPath, |
| 494 | }); |
| 495 | return; |
| 496 | } |
| 497 | |
| 498 | STATE.token = null; |
| 499 | clearSessionState(); |
| 500 | } |
| 501 | } |
| 502 | |
| 503 | showAuthOverlay(needed); |
| 504 | } |
| 505 | |
| 506 | async function doLogin(username, password, isSetup) { |
| 507 | const encrypted = await hybridEncryptForServer({ username, password }); |
| 508 | const endpoint = isSetup ? '/auth/setup' : '/auth/login'; |
| 509 | |
| 510 | let data; |
| 511 | try { |
| 512 | data = await api('POST', endpoint, { |
| 513 | encrypted, |
| 514 | clientPublicKey: STATE.clientPublicKeyJwk, |
| 515 | fingerprint: getFingerprint(), |
| 516 | }); |
| 517 | } catch (err) { |
| 518 | return err.message; |
| 519 | } |
| 520 | |
| 521 | if (!data) return 'Login failed.'; |
| 522 | |
| 523 | // Decrypt the token sent back by the server |
| 524 | const token = await hybridDecryptFromServer(data.encrypted || data); |
| 525 | if (!token) return 'Login failed.'; |
| 526 | STATE.token = token; |
| 527 | |
| 528 | // Load user info |
| 529 | const me = await api('GET', '/auth/me'); |
| 530 | if (!me) return 'Session error.'; |
| 531 | |
| 532 | STATE.username = me.username; |
| 533 | STATE.isAdmin = me.isAdmin; |
| 534 | STATE.permissions = me.permissions; |
| 535 | |
| 536 | saveSessionState(); |
| 537 | showApp(); |
| 538 | await loadRoots(); |
| 539 | return null; // no error |
| 540 | } |
| 541 | |
| 542 | function logout() { |
| 543 | void performLogout(); |
| 544 | } |
| 545 | |
| 546 | async function performLogout() { |
| 547 | const tokenAtStart = STATE.token; |
| 548 | stopAutoRefresh(); |
| 549 | |
| 550 | if (tokenAtStart) { |
| 551 | try { |
| 552 | await api('POST', '/auth/logout', {}, { noAutoLogout: true }); |
| 553 | } catch { |
| 554 | // Ignore network errors while logging out locally. |
| 555 | } |
| 556 | } |
| 557 | |
| 558 | STATE.token = null; |
| 559 | STATE.username = null; |
| 560 | STATE.isAdmin = false; |
| 561 | STATE.permissions = {}; |
| 562 | STATE.currentDir = null; |
| 563 | STATE.currentRoot = null; |
| 564 | STATE.items = []; |
| 565 | STATE.restoreDir = null; |
| 566 | STATE.restoreRootPath = null; |
| 567 | STATE.lastOperationAt = null; |
| 568 | clearSessionState(); |
| 569 | closeSidebar(); |
| 570 | await initAuth(); |
| 571 | } |
| 572 | |
| 573 | // ─────────────────────────────────────────────────────────────────────────── |
| 574 | // NAVIGATION |
| 575 | // ─────────────────────────────────────────────────────────────────────────── |
| 576 | |
| 577 | async function loadRoots(opts = {}) { |
| 578 | const data = await api('GET', '/files/roots'); |
| 579 | if (!data) return; |
| 580 | STATE.roots = data.roots; |
| 581 | |
| 582 | const preferredDir = opts.preferredDir || null; |
| 583 | const preferredRootPath = opts.preferredRootPath || null; |
| 584 | |
| 585 | if (preferredDir && preferredRootPath) { |
| 586 | const preferredRoot = STATE.roots.find(r => samePath(r.path, preferredRootPath)); |
| 587 | if (preferredRoot && pathInside(preferredDir, preferredRoot.path)) { |
| 588 | try { |
| 589 | await navigateTo(preferredDir, preferredRoot, { keepSidebar: true }); |
| 590 | return; |
| 591 | } catch { |
| 592 | // Fall back to default root behavior. |
| 593 | } |
| 594 | } |
| 595 | } |
| 596 | |
| 597 | if (STATE.roots.length === 1) { |
| 598 | // Single root → open it directly |
| 599 | await navigateTo(STATE.roots[0].path, STATE.roots[0]); |
| 600 | } else { |
| 601 | renderRootsView(); |
| 602 | } |
| 603 | } |
| 604 | |
| 605 | function renderRootsView() { |
| 606 | STATE.currentDir = null; |
| 607 | STATE.currentRoot = null; |
| 608 | saveSessionState(); |
| 609 | renderBreadcrumb(); |
| 610 | const grid = document.getElementById('file-grid'); |
| 611 | grid.innerHTML = ''; |
| 612 | document.getElementById('empty-notice').classList.add('hidden'); |
| 613 | document.getElementById('folder-stats').classList.add('hidden'); |
| 614 | closeSidebar(); |
| 615 | |
| 616 | for (const root of STATE.roots) { |
| 617 | const el = makeFileItem({ name: root.label, isDir: true, path: root.path, _root: root }); |
| 618 | grid.appendChild(el); |
| 619 | } |
| 620 | } |
| 621 | |
| 622 | async function navigateTo(absPath, root, opts = {}) { |
| 623 | if (root) STATE.currentRoot = root; |
| 624 | STATE.currentDir = absPath; |
| 625 | |
| 626 | const data = await api('GET', `/files/list?dir=${encodeURIComponent(absPath)}`); |
| 627 | if (!data) return; |
| 628 | |
| 629 | STATE.items = data.items; |
| 630 | saveSessionState(); |
| 631 | renderBreadcrumb(); |
| 632 | renderFileGrid(); |
| 633 | await refreshFolderStats(); |
| 634 | if (!opts.keepSidebar) closeSidebar(); |
| 635 | } |
| 636 | |
| 637 | function renderBreadcrumb() { |
| 638 | const nav = document.getElementById('breadcrumb'); |
| 639 | nav.innerHTML = ''; |
| 640 | |
| 641 | // "Home" crumb |
| 642 | const home = document.createElement('span'); |
| 643 | home.className = 'crumb' + (STATE.currentDir == null ? ' active' : ''); |
| 644 | home.textContent = 'Home'; |
| 645 | home.addEventListener('click', () => { |
| 646 | if (STATE.roots.length === 1) { |
| 647 | navigateTo(STATE.roots[0].path, STATE.roots[0]); |
| 648 | } else { |
| 649 | renderRootsView(); |
| 650 | } |
| 651 | }); |
| 652 | nav.appendChild(home); |
| 653 | |
| 654 | if (!STATE.currentDir || !STATE.currentRoot) return; |
| 655 | |
| 656 | // Build path segments relative to the root |
| 657 | const rootPath = STATE.currentRoot.path; |
| 658 | const relative = STATE.currentDir === rootPath |
| 659 | ? '' |
| 660 | : STATE.currentDir.replace(rootPath, '').replace(/^[\\/]/, ''); |
| 661 | |
| 662 | const parts = [STATE.currentRoot.label, ...relative.split(/[\\/]/).filter(Boolean)]; |
| 663 | let accumulated = rootPath; |
| 664 | |
| 665 | for (let i = 0; i < parts.length; i++) { |
| 666 | const sep = document.createElement('span'); |
| 667 | sep.className = 'sep'; |
| 668 | sep.textContent = ' / '; |
| 669 | nav.appendChild(sep); |
| 670 | |
| 671 | const crumb = document.createElement('span'); |
| 672 | crumb.className = 'crumb' + (i === parts.length - 1 ? ' active' : ''); |
| 673 | crumb.textContent = parts[i]; |
| 674 | |
| 675 | // Capture the path for this crumb |
| 676 | const capturedPath = i === 0 ? rootPath : accumulated; |
| 677 | if (i < parts.length - 1) { |
| 678 | crumb.addEventListener('click', () => navigateTo(capturedPath, STATE.currentRoot)); |
| 679 | } |
| 680 | |
| 681 | nav.appendChild(crumb); |
| 682 | |
| 683 | // Advance accumulated path (skip for root label) |
| 684 | if (i > 0) accumulated = accumulated + '/' + parts[i]; |
| 685 | else if (i === 0 && parts.length > 1) { |
| 686 | // After root label, next crumb should append the next segment |
| 687 | accumulated = rootPath; |
| 688 | } |
| 689 | } |
| 690 | } |
| 691 | |
| 692 | async function refreshFolderStats() { |
| 693 | const el = document.getElementById('folder-stats'); |
| 694 | if (!STATE.currentDir) { |
| 695 | el.classList.add('hidden'); |
| 696 | return; |
| 697 | } |
| 698 | |
| 699 | const data = await api('GET', `/files/space?dir=${encodeURIComponent(STATE.currentDir)}`).catch(() => null); |
| 700 | if (!data) { |
| 701 | el.classList.add('hidden'); |
| 702 | return; |
| 703 | } |
| 704 | |
| 705 | const used = formatBytes(data.usedBytes); |
| 706 | const free = data.freeBytes == null ? 'unknown' : formatBytes(data.freeBytes); |
| 707 | el.textContent = `Folder usage (recursive): ${used} | Free on root: ${free}`; |
| 708 | el.classList.remove('hidden'); |
| 709 | } |
| 710 | |
| 711 | function itemsSignature(items) { |
| 712 | return JSON.stringify( |
| 713 | (items || []).map(it => [it.path, it.mtime, it.size, it.isDir]) |
| 714 | .sort((a, b) => String(a[0]).localeCompare(String(b[0]))), |
| 715 | ); |
| 716 | } |
| 717 | |
| 718 | async function incrementalRefreshCurrentDir() { |
| 719 | if (!STATE.currentDir || STATE.uploadInProgress) return; |
| 720 | const data = await api('GET', `/files/list?dir=${encodeURIComponent(STATE.currentDir)}`).catch(() => null); |
| 721 | if (!data) return; |
| 722 | |
| 723 | const oldSig = itemsSignature(STATE.items); |
| 724 | const newSig = itemsSignature(data.items); |
| 725 | if (oldSig !== newSig) { |
| 726 | const selectedPath = STATE.selectedItem ? STATE.selectedItem.path : null; |
| 727 | STATE.items = data.items; |
| 728 | renderFileGrid(); |
| 729 | |
| 730 | if (selectedPath) { |
| 731 | const match = STATE.items.find(i => i.path === selectedPath); |
| 732 | if (match) { |
| 733 | const selectedEl = Array.from(document.querySelectorAll('.file-item')) |
| 734 | .find(el => el.dataset.path === selectedPath); |
| 735 | if (selectedEl) selectItem(selectedEl, match); |
| 736 | } else { |
| 737 | closeSidebar(); |
| 738 | } |
| 739 | } |
| 740 | } |
| 741 | |
| 742 | await refreshFolderStats(); |
| 743 | } |
| 744 | |
| 745 | function startAutoRefresh() { |
| 746 | stopAutoRefresh(); |
| 747 | STATE.autoRefreshTimer = setInterval(() => { |
| 748 | if (document.hidden) return; |
| 749 | incrementalRefreshCurrentDir(); |
| 750 | }, 5000); |
| 751 | } |
| 752 | |
| 753 | function stopAutoRefresh() { |
| 754 | if (STATE.autoRefreshTimer) { |
| 755 | clearInterval(STATE.autoRefreshTimer); |
| 756 | STATE.autoRefreshTimer = null; |
| 757 | } |
| 758 | } |
| 759 | |
| 760 | // ─────────────────────────────────────────────────────────────────────────── |
| 761 | // FILE GRID RENDERING |
| 762 | // ─────────────────────────────────────────────────────────────────────────── |
| 763 | |
| 764 | function renderFileGrid() { |
| 765 | const grid = document.getElementById('file-grid'); |
| 766 | grid.innerHTML = ''; |
| 767 | const empty = document.getElementById('empty-notice'); |
| 768 | |
| 769 | const sorted = [...STATE.items].sort((a, b) => { |
| 770 | if (a.isDir !== b.isDir) return a.isDir ? -1 : 1; |
| 771 | return a.name.localeCompare(b.name); |
| 772 | }); |
| 773 | |
| 774 | empty.classList.toggle('hidden', sorted.length > 0); |
| 775 | |
| 776 | for (const item of sorted) { |
| 777 | grid.appendChild(makeFileItem(item)); |
| 778 | } |
| 779 | } |
| 780 | |
| 781 | function makeFileItem(item) { |
| 782 | const el = document.createElement('div'); |
| 783 | el.className = 'file-item'; |
| 784 | el.dataset.path = item.path; |
| 785 | |
| 786 | const icon = document.createElement('div'); |
| 787 | icon.className = 'icon'; |
| 788 | icon.innerHTML = item.isDir ? iconFolder() : iconFile(item.name); |
| 789 | el.appendChild(icon); |
| 790 | |
| 791 | const name = document.createElement('div'); |
| 792 | name.className = 'name'; |
| 793 | name.textContent = item.name; |
| 794 | el.appendChild(name); |
| 795 | |
| 796 | // Single-click: open sidebar |
| 797 | el.addEventListener('click', (e) => { |
| 798 | e.stopPropagation(); |
| 799 | if (item._root) { |
| 800 | // Clicking a root tile goes straight in |
| 801 | navigateTo(item.path, item._root); |
| 802 | return; |
| 803 | } |
| 804 | selectItem(el, item); |
| 805 | }); |
| 806 | |
| 807 | // Double-click: enter folder or view/download file |
| 808 | el.addEventListener('dblclick', (e) => { |
| 809 | e.stopPropagation(); |
| 810 | if (item.isDir) { |
| 811 | navigateTo(item.path, STATE.currentRoot); |
| 812 | } else { |
| 813 | downloadOrView(item); |
| 814 | } |
| 815 | }); |
| 816 | |
| 817 | return el; |
| 818 | } |
| 819 | |
| 820 | function selectItem(el, item) { |
| 821 | document.querySelectorAll('.file-item.selected').forEach(e => e.classList.remove('selected')); |
| 822 | el.classList.add('selected'); |
| 823 | STATE.selectedItem = item; |
| 824 | openSidebar(item); |
| 825 | } |
| 826 | |
| 827 | // ─────────────────────────────────────────────────────────────────────────── |
| 828 | // SIDEBAR |
| 829 | // ─────────────────────────────────────────────────────────────────────────── |
| 830 | |
| 831 | async function openSidebar(item) { |
| 832 | const sidebar = document.getElementById('sidebar'); |
| 833 | sidebar.classList.remove('hidden'); |
| 834 | document.getElementById('app').classList.add('sidebar-open'); |
| 835 | |
| 836 | document.getElementById('sidebar-icon').innerHTML = item.isDir ? iconFolder(64) : iconFile(item.name, 64); |
| 837 | document.getElementById('sidebar-name').textContent = item.name; |
| 838 | |
| 839 | // Load metadata |
| 840 | const dl = document.getElementById('sidebar-meta'); |
| 841 | dl.innerHTML = '<dt>Loading…</dt><dd></dd>'; |
| 842 | |
| 843 | const actions = document.getElementById('sidebar-actions'); |
| 844 | actions.innerHTML = ''; |
| 845 | |
| 846 | if (!item.isDir) { |
| 847 | const meta = await api('GET', `/files/meta?file=${encodeURIComponent(item.path)}`); |
| 848 | if (meta) { |
| 849 | dl.innerHTML = ` |
| 850 | <dt>Size</dt> <dd>${formatBytes(meta.size)}</dd> |
| 851 | <dt>Modified</dt> <dd>${new Date(meta.mtime).toLocaleString()}</dd> |
| 852 | <dt>Uploaded by</dt><dd>${meta.uploader || '—'}</dd> |
| 853 | <dt>Downloaded by</dt><dd>${meta.downloaders.join(', ') || '—'}</dd> |
| 854 | `; |
| 855 | } |
| 856 | |
| 857 | // View / download button |
| 858 | const btnDl = document.createElement('button'); |
| 859 | btnDl.textContent = 'View / Download'; |
| 860 | btnDl.addEventListener('click', () => downloadOrView(item)); |
| 861 | actions.appendChild(btnDl); |
| 862 | } else { |
| 863 | dl.innerHTML = `<dt>Type</dt><dd>Folder</dd>`; |
| 864 | const btnOpen = document.createElement('button'); |
| 865 | btnOpen.textContent = 'Open folder'; |
| 866 | btnOpen.addEventListener('click', () => navigateTo(item.path, STATE.currentRoot)); |
| 867 | actions.appendChild(btnOpen); |
| 868 | } |
| 869 | |
| 870 | // Rename button (write access required) |
| 871 | if (canWrite()) { |
| 872 | const btnRen = document.createElement('button'); |
| 873 | btnRen.textContent = 'Rename'; |
| 874 | btnRen.addEventListener('click', () => openRenameModal(item)); |
| 875 | actions.appendChild(btnRen); |
| 876 | |
| 877 | const btnDel = document.createElement('button'); |
| 878 | btnDel.textContent = 'Delete'; |
| 879 | btnDel.className = 'danger'; |
| 880 | btnDel.addEventListener('click', () => deleteItem(item)); |
| 881 | actions.appendChild(btnDel); |
| 882 | } |
| 883 | } |
| 884 | |
| 885 | function closeSidebar() { |
| 886 | document.getElementById('sidebar').classList.add('hidden'); |
| 887 | document.getElementById('app').classList.remove('sidebar-open'); |
| 888 | document.querySelectorAll('.file-item.selected').forEach(e => e.classList.remove('selected')); |
| 889 | STATE.selectedItem = null; |
| 890 | } |
| 891 | |
| 892 | // ─────────────────────────────────────────────────────────────────────────── |
| 893 | // DOWNLOAD / VIEW |
| 894 | // ─────────────────────────────────────────────────────────────────────────── |
| 895 | |
| 896 | function downloadOrView(item) { |
| 897 | const url = `/api/files/download?file=${encodeURIComponent(item.path)}`; |
| 898 | // Open in new tab — browser decides whether to display or download |
| 899 | const a = document.createElement('a'); |
| 900 | a.href = url; |
| 901 | a.target = '_blank'; |
| 902 | a.rel = 'noopener noreferrer'; |
| 903 | // We need to send the auth header; since <a> can't do that, we fetch and blob it |
| 904 | fetchAndServe(item, url); |
| 905 | } |
| 906 | |
| 907 | async function fetchAndServe(item, url) { |
| 908 | try { |
| 909 | const res = await fetch(url, { |
| 910 | headers: { |
| 911 | Authorization: 'Bearer ' + STATE.token, |
| 912 | 'X-Fp': getFingerprint(), |
| 913 | }, |
| 914 | }); |
| 915 | if (!res.ok) { toast('Download failed.', 'err'); return; } |
| 916 | const blob = await res.blob(); |
| 917 | const objUrl = URL.createObjectURL(blob); |
| 918 | const a = document.createElement('a'); |
| 919 | a.href = objUrl; |
| 920 | a.download = item.name; |
| 921 | // Try to open viewable types inline |
| 922 | const viewable = /^(image|video|audio|text|application\/pdf)/.test(blob.type); |
| 923 | if (viewable) { |
| 924 | window.open(objUrl, '_blank', 'noopener,noreferrer'); |
| 925 | } else { |
| 926 | a.click(); |
| 927 | } |
| 928 | setTimeout(() => URL.revokeObjectURL(objUrl), 60000); |
| 929 | } catch { |
| 930 | toast('Download failed.', 'err'); |
| 931 | } |
| 932 | } |
| 933 | |
| 934 | // ─────────────────────────────────────────────────────────────────────────── |
| 935 | // UPLOAD |
| 936 | // ─────────────────────────────────────────────────────────────────────────── |
| 937 | |
| 938 | function canWrite() { |
| 939 | if (STATE.isAdmin) return true; |
| 940 | if (!STATE.currentRoot) return false; |
| 941 | const p = STATE.permissions[STATE.currentRoot.label]; |
| 942 | return p && p.write; |
| 943 | } |
| 944 | |
| 945 | async function uploadFiles(fileList) { |
| 946 | if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; } |
| 947 | if (!canWrite()) { toast('No write access.', 'err'); return; } |
| 948 | |
| 949 | const totalSize = Array.from(fileList).reduce((sum, f) => sum + (f.size || 0), 0); |
| 950 | const formData = new FormData(); |
| 951 | for (const f of fileList) formData.append('files', f); |
| 952 | |
| 953 | // Show upload bar |
| 954 | const wrap = document.createElement('div'); |
| 955 | wrap.className = 'upload-bar-wrap'; |
| 956 | wrap.innerHTML = `<span>Uploading ${fileList.length} file(s)…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`; |
| 957 | document.body.appendChild(wrap); |
| 958 | STATE.uploadInProgress = true; |
| 959 | |
| 960 | try { |
| 961 | const xhr = new XMLHttpRequest(); |
| 962 | xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(STATE.currentDir)}`); |
| 963 | xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token); |
| 964 | xhr.setRequestHeader('X-Fp', getFingerprint()); |
| 965 | xhr.setRequestHeader('X-Upload-Size', String(totalSize)); |
| 966 | |
| 967 | xhr.upload.addEventListener('progress', e => { |
| 968 | if (e.lengthComputable) { |
| 969 | wrap.querySelector('.upload-bar-fill').style.width = (e.loaded / e.total * 100) + '%'; |
| 970 | } |
| 971 | }); |
| 972 | |
| 973 | await new Promise((resolve, reject) => { |
| 974 | xhr.onload = () => { |
| 975 | if (xhr.status === 200) resolve(); |
| 976 | else reject(new Error(JSON.parse(xhr.responseText).error || 'Upload failed')); |
| 977 | }; |
| 978 | xhr.onerror = () => reject(new Error('Network error')); |
| 979 | xhr.send(formData); |
| 980 | }); |
| 981 | |
| 982 | toast(`Uploaded ${fileList.length} file(s).`, 'ok'); |
| 983 | await navigateTo(STATE.currentDir, STATE.currentRoot); |
| 984 | } catch (err) { |
| 985 | toast(err.message, 'err'); |
| 986 | } finally { |
| 987 | STATE.uploadInProgress = false; |
| 988 | wrap.remove(); |
| 989 | } |
| 990 | } |
| 991 | |
| 992 | async function uploadSingleFile(file, targetDir) { |
| 993 | const formData = new FormData(); |
| 994 | formData.append('files', file); |
| 995 | |
| 996 | await new Promise((resolve, reject) => { |
| 997 | const xhr = new XMLHttpRequest(); |
| 998 | xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(targetDir)}`); |
| 999 | xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token); |
| 1000 | xhr.setRequestHeader('X-Fp', getFingerprint()); |
| 1001 | xhr.setRequestHeader('X-Upload-Size', String(file.size || 0)); |
| 1002 | xhr.onload = () => xhr.status === 200 |
| 1003 | ? resolve() |
| 1004 | : reject(new Error((JSON.parse(xhr.responseText) || {}).error || 'Upload failed')); |
| 1005 | xhr.onerror = () => reject(new Error('Network error')); |
| 1006 | xhr.send(formData); |
| 1007 | }); |
| 1008 | } |
| 1009 | |
| 1010 | async function ensureServerDir(baseDir, relativeDir) { |
| 1011 | const parts = String(relativeDir || '').split(/[\\/]/).filter(Boolean); |
| 1012 | let current = baseDir; |
| 1013 | for (const part of parts) { |
| 1014 | try { |
| 1015 | const resp = await api('POST', '/files/mkdir', { dir: current, name: part }); |
| 1016 | current = resp && resp.path ? resp.path : joinServerPath(current, part); |
| 1017 | } catch (err) { |
| 1018 | if (!/exist|EEXIST/i.test(err.message || '')) throw err; |
| 1019 | current = joinServerPath(current, part); |
| 1020 | } |
| 1021 | } |
| 1022 | return current; |
| 1023 | } |
| 1024 | |
| 1025 | async function uploadFolderInputFiles(fileList) { |
| 1026 | if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; } |
| 1027 | if (!canWrite()) { toast('No write access.', 'err'); return; } |
| 1028 | if (!fileList || !fileList.length) return; |
| 1029 | |
| 1030 | const files = Array.from(fileList); |
| 1031 | const total = files.length; |
| 1032 | let done = 0; |
| 1033 | |
| 1034 | const wrap = document.createElement('div'); |
| 1035 | wrap.className = 'upload-bar-wrap'; |
| 1036 | wrap.innerHTML = `<span>Preparing folder upload…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`; |
| 1037 | document.body.appendChild(wrap); |
| 1038 | STATE.uploadInProgress = true; |
| 1039 | |
| 1040 | try { |
| 1041 | const dirCache = new Map(); |
| 1042 | dirCache.set('', STATE.currentDir); |
| 1043 | |
| 1044 | for (const file of files) { |
| 1045 | const rel = file.webkitRelativePath || file.name; |
| 1046 | const relParts = rel.split(/[\\/]/).filter(Boolean); |
| 1047 | const relDir = relParts.slice(0, -1).join('/'); |
| 1048 | |
| 1049 | if (!dirCache.has(relDir)) { |
| 1050 | const parentRel = relParts.slice(0, -2).join('/'); |
| 1051 | const parentAbs = dirCache.get(parentRel) || await ensureServerDir(STATE.currentDir, parentRel); |
| 1052 | const thisName = relParts[relParts.length - 2]; |
| 1053 | |
| 1054 | try { |
| 1055 | const created = await api('POST', '/files/mkdir', { dir: parentAbs, name: thisName }); |
| 1056 | dirCache.set(relDir, created.path || joinServerPath(parentAbs, thisName)); |
| 1057 | } catch (err) { |
| 1058 | if (!/exist|EEXIST/i.test(err.message || '')) throw err; |
| 1059 | dirCache.set(relDir, joinServerPath(parentAbs, thisName)); |
| 1060 | } |
| 1061 | } |
| 1062 | |
| 1063 | const targetDir = dirCache.get(relDir) || STATE.currentDir; |
| 1064 | await uploadSingleFile(file, targetDir); |
| 1065 | done++; |
| 1066 | wrap.querySelector('span').textContent = `Uploading ${done} / ${total} file(s)…`; |
| 1067 | wrap.querySelector('.upload-bar-fill').style.width = (done / total * 100) + '%'; |
| 1068 | } |
| 1069 | |
| 1070 | toast(`Uploaded ${total} file(s).`, 'ok'); |
| 1071 | await navigateTo(STATE.currentDir, STATE.currentRoot); |
| 1072 | } catch (err) { |
| 1073 | toast(err.message, 'err'); |
| 1074 | } finally { |
| 1075 | STATE.uploadInProgress = false; |
| 1076 | wrap.remove(); |
| 1077 | } |
| 1078 | } |
| 1079 | |
| 1080 | // ─────────────────────────────────────────────────────────────────────────── |
| 1081 | // FOLDER DRAG-AND-DROP (recursive) |
| 1082 | // ─────────────────────────────────────────────────────────────────────────── |
| 1083 | |
| 1084 | /** |
| 1085 | * Reads all readEntries batches from a DirectoryReader (browsers may return |
| 1086 | * results in chunks; we must keep calling until we get an empty array). |
| 1087 | */ |
| 1088 | function readAllEntries(reader) { |
| 1089 | return new Promise((resolve, reject) => { |
| 1090 | const all = []; |
| 1091 | function next() { |
| 1092 | reader.readEntries(batch => { |
| 1093 | if (!batch.length) { resolve(all); return; } |
| 1094 | all.push(...batch); |
| 1095 | next(); |
| 1096 | }, reject); |
| 1097 | } |
| 1098 | next(); |
| 1099 | }); |
| 1100 | } |
| 1101 | |
| 1102 | /** |
| 1103 | * Recursively walk a FileSystemEntry tree, creating server-side directories |
| 1104 | * on the fly and collecting { file, targetDir } pairs for upload. |
| 1105 | */ |
| 1106 | async function collectEntries(entry, serverDir, toUpload) { |
| 1107 | if (entry.isFile) { |
| 1108 | const file = await new Promise((res, rej) => entry.file(res, rej)); |
| 1109 | toUpload.push({ file, targetDir: serverDir }); |
| 1110 | } else if (entry.isDirectory) { |
| 1111 | // Ask the server to create the directory; it returns the canonical path. |
| 1112 | let newServerDir; |
| 1113 | try { |
| 1114 | const resp = await api('POST', '/files/mkdir', { dir: serverDir, name: entry.name }); |
| 1115 | newServerDir = resp.path; |
| 1116 | } catch { |
| 1117 | // Directory may already exist — reconstruct path from what we know. |
| 1118 | // The server always returns JSON with {error} on failure, so we can |
| 1119 | // still continue by falling back to a best-effort path join. |
| 1120 | // We rely on the fact that the server separator is consistent within |
| 1121 | // a session (the list/browse API already returned paths in that format). |
| 1122 | const sep = serverDir.includes('\\') ? '\\' : '/'; |
| 1123 | newServerDir = serverDir + sep + entry.name; |
| 1124 | } |
| 1125 | const reader = entry.createReader(); |
| 1126 | const subEntries = await readAllEntries(reader); |
| 1127 | for (const sub of subEntries) { |
| 1128 | await collectEntries(sub, newServerDir, toUpload); |
| 1129 | } |
| 1130 | } |
| 1131 | } |
| 1132 | |
| 1133 | async function uploadEntries(entries) { |
| 1134 | if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; } |
| 1135 | if (!canWrite()) { toast('No write access.', 'err'); return; } |
| 1136 | |
| 1137 | const wrap = document.createElement('div'); |
| 1138 | wrap.className = 'upload-bar-wrap'; |
| 1139 | wrap.innerHTML = `<span>Scanning…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`; |
| 1140 | document.body.appendChild(wrap); |
| 1141 | STATE.uploadInProgress = true; |
| 1142 | |
| 1143 | try { |
| 1144 | const toUpload = []; |
| 1145 | for (const entry of entries) { |
| 1146 | await collectEntries(entry, STATE.currentDir, toUpload); |
| 1147 | } |
| 1148 | |
| 1149 | if (!toUpload.length) { toast('No files found.', 'err'); return; } |
| 1150 | |
| 1151 | let done = 0; |
| 1152 | const total = toUpload.length; |
| 1153 | const updateBar = () => { |
| 1154 | wrap.querySelector('span').textContent = `Uploading ${done} / ${total} file(s)…`; |
| 1155 | wrap.querySelector('.upload-bar-fill').style.width = (done / total * 100) + '%'; |
| 1156 | }; |
| 1157 | updateBar(); |
| 1158 | |
| 1159 | for (const { file, targetDir } of toUpload) { |
| 1160 | await uploadSingleFile(file, targetDir); |
| 1161 | done++; |
| 1162 | updateBar(); |
| 1163 | } |
| 1164 | |
| 1165 | toast(`Uploaded ${total} file(s).`, 'ok'); |
| 1166 | await navigateTo(STATE.currentDir, STATE.currentRoot); |
| 1167 | } catch (err) { |
| 1168 | toast(err.message, 'err'); |
| 1169 | } finally { |
| 1170 | STATE.uploadInProgress = false; |
| 1171 | wrap.remove(); |
| 1172 | } |
| 1173 | } |
| 1174 | |
| 1175 | // DRAG-AND-DROP |
| 1176 | // ─────────────────────────────────────────────────────────────────────────── |
| 1177 | |
| 1178 | function initDragDrop() { |
| 1179 | const main = document.getElementById('main-content'); |
| 1180 | const dropOvl = document.getElementById('drop-overlay'); |
| 1181 | let dragDepth = 0; |
| 1182 | |
| 1183 | main.addEventListener('dragenter', e => { |
| 1184 | e.preventDefault(); |
| 1185 | dragDepth++; |
| 1186 | dropOvl.classList.remove('hidden'); |
| 1187 | }); |
| 1188 | main.addEventListener('dragleave', () => { |
| 1189 | dragDepth--; |
| 1190 | if (dragDepth <= 0) { dragDepth = 0; dropOvl.classList.add('hidden'); } |
| 1191 | }); |
| 1192 | main.addEventListener('dragover', e => e.preventDefault()); |
| 1193 | main.addEventListener('drop', async e => { |
| 1194 | e.preventDefault(); |
| 1195 | dragDepth = 0; |
| 1196 | dropOvl.classList.add('hidden'); |
| 1197 | if (!canWrite()) { toast('No write access.', 'err'); return; } |
| 1198 | |
| 1199 | const items = Array.from(e.dataTransfer.items || []); |
| 1200 | // Use the FileSystem Entry API when available so we can handle folders. |
| 1201 | if (items.length && typeof items[0].webkitGetAsEntry === 'function') { |
| 1202 | const entries = items.map(i => i.webkitGetAsEntry()).filter(Boolean); |
| 1203 | if (entries.some(en => en.isDirectory)) { |
| 1204 | await uploadEntries(entries); |
| 1205 | return; |
| 1206 | } |
| 1207 | } |
| 1208 | // Plain files only — use the fast batch path. |
| 1209 | const files = e.dataTransfer.files; |
| 1210 | if (files.length) await uploadFiles(files); |
| 1211 | }); |
| 1212 | } |
| 1213 | |
| 1214 | // ─────────────────────────────────────────────────────────────────────────── |
| 1215 | // RENAME |
| 1216 | // ─────────────────────────────────────────────────────────────────────────── |
| 1217 | |
| 1218 | function openRenameModal(item) { |
| 1219 | const modal = document.getElementById('rename-modal'); |
| 1220 | modal.classList.remove('hidden'); |
| 1221 | const input = document.getElementById('rename-input'); |
| 1222 | input.value = item.name; |
| 1223 | input.focus(); |
| 1224 | input.select(); |
| 1225 | document.getElementById('rename-error').classList.add('hidden'); |
| 1226 | document.getElementById('rename-form').onsubmit = async (e) => { |
| 1227 | e.preventDefault(); |
| 1228 | const newName = input.value.trim(); |
| 1229 | if (!newName) return; |
| 1230 | try { |
| 1231 | await api('POST', '/files/rename', { from: item.path, to: newName }); |
| 1232 | modal.classList.add('hidden'); |
| 1233 | toast('Renamed.', 'ok'); |
| 1234 | await navigateTo(STATE.currentDir, STATE.currentRoot); |
| 1235 | } catch (err) { |
| 1236 | document.getElementById('rename-error').textContent = err.message; |
| 1237 | document.getElementById('rename-error').classList.remove('hidden'); |
| 1238 | } |
| 1239 | }; |
| 1240 | } |
| 1241 | |
| 1242 | // ─────────────────────────────────────────────────────────────────────────── |
| 1243 | // DELETE |
| 1244 | // ─────────────────────────────────────────────────────────────────────────── |
| 1245 | |
| 1246 | async function deleteItem(item) { |
| 1247 | if (!await showConfirm('Delete item', `Delete "${item.name}"? This cannot be undone.`)) return; |
| 1248 | try { |
| 1249 | await api('POST', '/files/delete', { path: item.path }); |
| 1250 | toast('Deleted.', 'ok'); |
| 1251 | closeSidebar(); |
| 1252 | await navigateTo(STATE.currentDir, STATE.currentRoot); |
| 1253 | } catch (err) { |
| 1254 | toast(err.message, 'err'); |
| 1255 | } |
| 1256 | } |
| 1257 | |
| 1258 | // ─────────────────────────────────────────────────────────────────────────── |
| 1259 | // ADMIN PANEL |
| 1260 | // ─────────────────────────────────────────────────────────────────────────── |
| 1261 | |
| 1262 | async function openAdminModal() { |
| 1263 | document.getElementById('admin-modal').classList.remove('hidden'); |
| 1264 | await refreshAdminConfig(); |
| 1265 | await refreshAdminUsers(); |
| 1266 | } |
| 1267 | |
| 1268 | async function refreshAdminConfig() { |
| 1269 | const data = await api('GET', '/admin/config'); |
| 1270 | if (!data) return; |
| 1271 | const container = document.getElementById('admin-paths'); |
| 1272 | container.innerHTML = ''; |
| 1273 | for (const p of data.paths) { |
| 1274 | const row = document.createElement('div'); |
| 1275 | row.className = 'path-row'; |
| 1276 | row.innerHTML = `<span>${p}</span><button data-path="${p}" title="Remove">✕</button>`; |
| 1277 | row.querySelector('button').addEventListener('click', () => { |
| 1278 | row.remove(); |
| 1279 | }); |
| 1280 | container.appendChild(row); |
| 1281 | } |
| 1282 | } |
| 1283 | |
| 1284 | async function refreshAdminUsers() { |
| 1285 | const data = await api('GET', '/admin/users'); |
| 1286 | if (!data) return; |
| 1287 | const container = document.getElementById('admin-users-list'); |
| 1288 | container.innerHTML = ''; |
| 1289 | |
| 1290 | // Need paths for permission rows |
| 1291 | const cfg = await api('GET', '/admin/config'); |
| 1292 | const paths = cfg ? (cfg.effectivePaths || []) : []; |
| 1293 | |
| 1294 | for (const u of data.users) { |
| 1295 | const row = document.createElement('div'); |
| 1296 | row.className = 'user-row'; |
| 1297 | row.innerHTML = ` |
| 1298 | <span class="user-name">${u.username}</span> |
| 1299 | ${u.isAdmin ? '<span class="user-admin-badge">Admin</span>' : ''} |
| 1300 | <button data-id="${u.id}" data-action="edit">Edit</button> |
| 1301 | <button data-id="${u.id}" data-action="delete" class="danger">Delete</button> |
| 1302 | `; |
| 1303 | row.querySelector('[data-action="edit"]').addEventListener('click', () => |
| 1304 | openUserModal(u, paths)); |
| 1305 | row.querySelector('[data-action="delete"]').addEventListener('click', async () => { |
| 1306 | if (!await showConfirm('Delete user', `Delete user "${u.username}"? This cannot be undone.`)) return; |
| 1307 | try { |
| 1308 | await api('DELETE', `/admin/users/${u.id}`); |
| 1309 | toast('User deleted.', 'ok'); |
| 1310 | await refreshAdminUsers(); |
| 1311 | } catch (err) { toast(err.message, 'err'); } |
| 1312 | }); |
| 1313 | container.appendChild(row); |
| 1314 | } |
| 1315 | } |
| 1316 | |
| 1317 | function openUserModal(user, paths) { |
| 1318 | const modal = document.getElementById('user-modal'); |
| 1319 | modal.classList.remove('hidden'); |
| 1320 | document.getElementById('user-modal-title').textContent = user ? `Edit: ${user.username}` : 'New User'; |
| 1321 | document.getElementById('user-error').classList.add('hidden'); |
| 1322 | |
| 1323 | const usernameInput = document.getElementById('user-username'); |
| 1324 | usernameInput.value = user ? user.username : ''; |
| 1325 | usernameInput.readOnly = !!user; |
| 1326 | |
| 1327 | document.getElementById('user-password').value = ''; |
| 1328 | document.getElementById('user-is-admin').checked = user ? user.isAdmin : false; |
| 1329 | |
| 1330 | // Password placeholder |
| 1331 | document.getElementById('user-password').placeholder = |
| 1332 | user ? 'Leave blank to keep current' : 'Min 8 characters'; |
| 1333 | |
| 1334 | // Build permissions grid |
| 1335 | const permDiv = document.getElementById('user-permissions'); |
| 1336 | permDiv.innerHTML = ''; |
| 1337 | if (paths.length) { |
| 1338 | const heading = document.createElement('h4'); |
| 1339 | heading.textContent = 'Path Permissions'; |
| 1340 | permDiv.appendChild(heading); |
| 1341 | |
| 1342 | const isAdminUser = !!(user && user.isAdmin); |
| 1343 | // Mirror the is-admin checkbox so toggling it live-updates the perm rows. |
| 1344 | const adminChk = document.getElementById('user-is-admin'); |
| 1345 | const rebuildPermRows = (admin) => { |
| 1346 | permDiv.querySelectorAll('.perm-row').forEach(r => { |
| 1347 | r.querySelectorAll('input[type=checkbox]').forEach(cb => { |
| 1348 | cb.disabled = admin; |
| 1349 | if (admin) cb.checked = true; |
| 1350 | }); |
| 1351 | r.title = admin ? 'Admins always have full access' : ''; |
| 1352 | }); |
| 1353 | }; |
| 1354 | adminChk.addEventListener('change', () => rebuildPermRows(adminChk.checked)); |
| 1355 | |
| 1356 | for (const p of paths) { |
| 1357 | const label = p.split(/[\\/]/).pop(); |
| 1358 | const perms = user && user.permissions ? (user.permissions[label] || {}) : {}; |
| 1359 | const row = document.createElement('div'); |
| 1360 | row.className = 'perm-row'; |
| 1361 | const readChecked = isAdminUser || perms.read; |
| 1362 | const writeChecked = isAdminUser || perms.write; |
| 1363 | row.innerHTML = ` |
| 1364 | <span class="perm-label">${label}</span> |
| 1365 | <label class="checkbox-label"><input type="checkbox" data-label="${label}" data-type="read" ${readChecked ? 'checked' : ''} ${isAdminUser ? 'disabled' : ''} /> Read</label> |
| 1366 | <label class="checkbox-label"><input type="checkbox" data-label="${label}" data-type="write" ${writeChecked ? 'checked' : ''} ${isAdminUser ? 'disabled' : ''} /> Write</label> |
| 1367 | `; |
| 1368 | if (isAdminUser) row.title = 'Admins always have full access'; |
| 1369 | permDiv.appendChild(row); |
| 1370 | } |
| 1371 | } |
| 1372 | |
| 1373 | document.getElementById('user-form').onsubmit = async (e) => { |
| 1374 | e.preventDefault(); |
| 1375 | const password = document.getElementById('user-password').value; |
| 1376 | const isAdmin = document.getElementById('user-is-admin').checked; |
| 1377 | const permissions = {}; |
| 1378 | permDiv.querySelectorAll('input[data-label]').forEach(cb => { |
| 1379 | const lbl = cb.dataset.label; |
| 1380 | if (!permissions[lbl]) permissions[lbl] = {}; |
| 1381 | permissions[lbl][cb.dataset.type] = cb.checked; |
| 1382 | }); |
| 1383 | |
| 1384 | try { |
| 1385 | if (user) { |
| 1386 | const body = { isAdmin, permissions }; |
| 1387 | if (password) body.password = password; |
| 1388 | await api('PATCH', `/admin/users/${user.id}`, body); |
| 1389 | } else { |
| 1390 | const uname = document.getElementById('user-username').value.trim(); |
| 1391 | await api('POST', '/admin/users', { username: uname, password, isAdmin, permissions }); |
| 1392 | } |
| 1393 | modal.classList.add('hidden'); |
| 1394 | toast('User saved.', 'ok'); |
| 1395 | await refreshAdminUsers(); |
| 1396 | } catch (err) { |
| 1397 | document.getElementById('user-error').textContent = err.message; |
| 1398 | document.getElementById('user-error').classList.remove('hidden'); |
| 1399 | } |
| 1400 | }; |
| 1401 | } |
| 1402 | |
| 1403 | // ─────────────────────────────────────────────────────────────────────────── |
| 1404 | // SVG ICONS |
| 1405 | // ─────────────────────────────────────────────────────────────────────────── |
| 1406 | |
| 1407 | const IMAGE_EXTS = new Set(['jpg','jpeg','png','gif','webp','svg','bmp','ico','avif']); |
| 1408 | const VIDEO_EXTS = new Set(['mp4','webm','ogv','mov','avi','mkv']); |
| 1409 | const AUDIO_EXTS = new Set(['mp3','ogg','wav','flac','aac','m4a']); |
| 1410 | const DOC_EXTS = new Set(['pdf','doc','docx','xls','xlsx','ppt','pptx','odt','ods','odp']); |
| 1411 | const CODE_EXTS = new Set(['js','ts','py','rb','go','rs','c','cpp','h','cs','java','php','html','css','json','xml','yaml','yml','sh','bash','md','txt']); |
| 1412 | const ARCHIVE_EXTS= new Set(['zip','tar','gz','bz2','xz','rar','7z']); |
| 1413 | |
| 1414 | function iconFolder(size = 52) { |
| 1415 | return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" |
| 1416 | stroke="#5b7fff" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"> |
| 1417 | <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/> |
| 1418 | </svg>`; |
| 1419 | } |
| 1420 | |
| 1421 | function iconFile(name, size = 52) { |
| 1422 | const ext = extOf(name); |
| 1423 | let color = '#7880a0'; |
| 1424 | let symbol = ''; |
| 1425 | |
| 1426 | if (IMAGE_EXTS.has(ext)) color = '#3fcf8e'; |
| 1427 | else if (VIDEO_EXTS.has(ext)) color = '#e05c6e'; |
| 1428 | else if (AUDIO_EXTS.has(ext)) color = '#c084fc'; |
| 1429 | else if (DOC_EXTS.has(ext)) color = '#f97316'; |
| 1430 | else if (CODE_EXTS.has(ext)) color = '#38bdf8'; |
| 1431 | else if (ARCHIVE_EXTS.has(ext))color = '#facc15'; |
| 1432 | |
| 1433 | return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" |
| 1434 | stroke="${color}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"> |
| 1435 | <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/> |
| 1436 | <polyline points="14 2 14 8 20 8"/> |
| 1437 | </svg>`; |
| 1438 | } |
| 1439 | |
| 1440 | // ─────────────────────────────────────────────────────────────────────────── |
| 1441 | // EVENT WIRING |
| 1442 | // ─────────────────────────────────────────────────────────────────────────── |
| 1443 | |
| 1444 | function wireEvents() { |
| 1445 | // Auth form |
| 1446 | document.getElementById('auth-form').addEventListener('submit', async (e) => { |
| 1447 | e.preventDefault(); |
| 1448 | const username = document.getElementById('auth-username').value.trim(); |
| 1449 | const password = document.getElementById('auth-password').value; |
| 1450 | const isSetup = e.target.dataset.mode === 'setup'; |
| 1451 | const errEl = document.getElementById('auth-error'); |
| 1452 | const btn = document.getElementById('auth-submit'); |
| 1453 | btn.disabled = true; |
| 1454 | btn.textContent = 'Please wait…'; |
| 1455 | const err = await doLogin(username, password, isSetup); |
| 1456 | if (err) { |
| 1457 | errEl.textContent = err; |
| 1458 | errEl.classList.remove('hidden'); |
| 1459 | btn.disabled = false; |
| 1460 | btn.textContent = isSetup ? 'Create Account' : 'Sign In'; |
| 1461 | } |
| 1462 | }); |
| 1463 | |
| 1464 | // Logout |
| 1465 | document.getElementById('btn-logout').addEventListener('click', logout); |
| 1466 | |
| 1467 | // Hard refresh while keeping auth/session state. |
| 1468 | document.getElementById('btn-refresh').addEventListener('click', () => { |
| 1469 | saveSessionState(); |
| 1470 | location.reload(); |
| 1471 | }); |
| 1472 | |
| 1473 | // Upload button |
| 1474 | document.getElementById('btn-upload').addEventListener('click', () => { |
| 1475 | if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; } |
| 1476 | if (!canWrite()) { toast('No write access.', 'err'); return; } |
| 1477 | document.getElementById('file-input').click(); |
| 1478 | }); |
| 1479 | |
| 1480 | document.getElementById('file-input').addEventListener('change', async (e) => { |
| 1481 | if (e.target.files.length) await uploadFiles(e.target.files); |
| 1482 | e.target.value = ''; |
| 1483 | }); |
| 1484 | |
| 1485 | document.getElementById('btn-upload-folder').addEventListener('click', () => { |
| 1486 | if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; } |
| 1487 | if (!canWrite()) { toast('No write access.', 'err'); return; } |
| 1488 | document.getElementById('folder-input').click(); |
| 1489 | }); |
| 1490 | |
| 1491 | document.getElementById('folder-input').addEventListener('change', async (e) => { |
| 1492 | if (e.target.files.length) await uploadFolderInputFiles(e.target.files); |
| 1493 | e.target.value = ''; |
| 1494 | }); |
| 1495 | |
| 1496 | document.getElementById('btn-new-folder').addEventListener('click', async () => { |
| 1497 | if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; } |
| 1498 | if (!canWrite()) { toast('No write access.', 'err'); return; } |
| 1499 | |
| 1500 | const name = await showPrompt('New Folder', 'Enter a name for the new folder:'); |
| 1501 | if (name == null) return; |
| 1502 | const folderName = name.trim(); |
| 1503 | if (!folderName) { |
| 1504 | toast('Folder name is required.', 'err'); |
| 1505 | return; |
| 1506 | } |
| 1507 | |
| 1508 | try { |
| 1509 | await api('POST', '/files/mkdir', { dir: STATE.currentDir, name: folderName }); |
| 1510 | toast('Folder created.', 'ok'); |
| 1511 | await navigateTo(STATE.currentDir, STATE.currentRoot); |
| 1512 | } catch (err) { |
| 1513 | toast(err.message, 'err'); |
| 1514 | } |
| 1515 | }); |
| 1516 | |
| 1517 | // Sidebar close |
| 1518 | document.getElementById('sidebar-close').addEventListener('click', closeSidebar); |
| 1519 | |
| 1520 | // Click outside grid closes sidebar |
| 1521 | document.getElementById('main-content').addEventListener('click', (e) => { |
| 1522 | if (!e.target.closest('.file-item')) closeSidebar(); |
| 1523 | }); |
| 1524 | |
| 1525 | // Admin panel |
| 1526 | document.getElementById('btn-admin').addEventListener('click', openAdminModal); |
| 1527 | document.getElementById('admin-modal-close').addEventListener('click', () => |
| 1528 | document.getElementById('admin-modal').classList.add('hidden')); |
| 1529 | |
| 1530 | // Add path |
| 1531 | document.getElementById('admin-add-path').addEventListener('click', () => { |
| 1532 | const val = document.getElementById('admin-new-path').value.trim(); |
| 1533 | if (!val) return; |
| 1534 | const row = document.createElement('div'); |
| 1535 | row.className = 'path-row'; |
| 1536 | row.innerHTML = `<span>${val}</span><button title="Remove">✕</button>`; |
| 1537 | row.querySelector('button').addEventListener('click', () => row.remove()); |
| 1538 | document.getElementById('admin-paths').appendChild(row); |
| 1539 | document.getElementById('admin-new-path').value = ''; |
| 1540 | }); |
| 1541 | |
| 1542 | // Save paths |
| 1543 | document.getElementById('admin-save-paths').addEventListener('click', async () => { |
| 1544 | const rows = document.querySelectorAll('#admin-paths .path-row span'); |
| 1545 | const paths = [...rows].map(s => s.textContent.trim()).filter(Boolean); |
| 1546 | try { |
| 1547 | await api('PUT', '/admin/config', { paths }); |
| 1548 | toast('Paths saved.', 'ok'); |
| 1549 | await loadRoots(); |
| 1550 | } catch (err) { toast(err.message, 'err'); } |
| 1551 | }); |
| 1552 | |
| 1553 | // Shutdown server |
| 1554 | document.getElementById('admin-shutdown-btn').addEventListener('click', async () => { |
| 1555 | if (!await showConfirm('Shut down server', 'Shut down the server? You will lose access until it is restarted manually.')) return; |
| 1556 | try { |
| 1557 | await api('POST', '/admin/shutdown'); |
| 1558 | toast('Server is shutting down…', 'ok'); |
| 1559 | document.getElementById('admin-modal').classList.add('hidden'); |
| 1560 | } catch { |
| 1561 | // Fetch may throw because the connection closes before a response arrives. |
| 1562 | toast('Server is shutting down…', 'ok'); |
| 1563 | document.getElementById('admin-modal').classList.add('hidden'); |
| 1564 | } |
| 1565 | }); |
| 1566 | |
| 1567 | // New user |
| 1568 | document.getElementById('admin-new-user-btn').addEventListener('click', async () => { |
| 1569 | const cfg = await api('GET', '/admin/config'); |
| 1570 | const paths = cfg ? (cfg.effectivePaths || []) : []; |
| 1571 | openUserModal(null, paths); |
| 1572 | }); |
| 1573 | |
| 1574 | // User modal close |
| 1575 | document.getElementById('user-modal-close').addEventListener('click', () => |
| 1576 | document.getElementById('user-modal').classList.add('hidden')); |
| 1577 | |
| 1578 | // Rename modal close |
| 1579 | document.getElementById('rename-modal-close').addEventListener('click', () => |
| 1580 | document.getElementById('rename-modal').classList.add('hidden')); |
| 1581 | |
| 1582 | // Close modals on backdrop click |
| 1583 | document.querySelectorAll('.modal-overlay').forEach(overlay => { |
| 1584 | overlay.addEventListener('click', e => { |
| 1585 | if (e.target === overlay) overlay.classList.add('hidden'); |
| 1586 | }); |
| 1587 | }); |
| 1588 | } |
| 1589 | |
| 1590 | // ─────────────────────────────────────────────────────────────────────────── |
| 1591 | // BOOT |
| 1592 | // ─────────────────────────────────────────────────────────────────────────── |
| 1593 | |
| 1594 | (async function boot() { |
| 1595 | wireEvents(); |
| 1596 | initDragDrop(); |
| 1597 | window.addEventListener('beforeunload', saveSessionState); |
| 1598 | await initAuth(); |
| 1599 | })(); |