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