| 1 | /* ========================================================= |
| 2 | FILE MANAGER — CLIENT SPA |
| 3 | ========================================================= |
| 4 | Architecture: |
| 5 | - RSA-OAEP + AES-256-GCM hybrid encryption via Web Crypto API |
| 6 | - No cookies / sessionStorage — token lives in module-scoped memory |
| 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 | |
| 34 | // ─────────────────────────────────────────────────────────────────────────── |
| 35 | // CRYPTO HELPERS (Web Crypto API) |
| 36 | // ─────────────────────────────────────────────────────────────────────────── |
| 37 | |
| 38 | async function generateClientKeyPair() { |
| 39 | const kp = await crypto.subtle.generateKey( |
| 40 | { name: 'RSA-OAEP', modulusLength: 2048, publicExponent: new Uint8Array([1,0,1]), hash: 'SHA-256' }, |
| 41 | true, |
| 42 | ['encrypt', 'decrypt'], |
| 43 | ); |
| 44 | STATE.clientPrivateKey = kp.privateKey; |
| 45 | STATE.clientPublicKeyJwk = await crypto.subtle.exportKey('jwk', kp.publicKey); |
| 46 | } |
| 47 | |
| 48 | /** |
| 49 | * Hybrid-encrypt a JS object using the server's RSA public key. |
| 50 | * Returns { encryptedKey, iv, ciphertext, tag } all as base64 strings. |
| 51 | */ |
| 52 | async function hybridEncryptForServer(obj) { |
| 53 | const serverPub = await crypto.subtle.importKey( |
| 54 | 'jwk', STATE.serverPublicKeyJwk, |
| 55 | { name: 'RSA-OAEP', hash: 'SHA-256' }, |
| 56 | false, ['encrypt'], |
| 57 | ); |
| 58 | |
| 59 | const plaintext = new TextEncoder().encode(JSON.stringify(obj)); |
| 60 | const aesKey = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt']); |
| 61 | const iv = crypto.getRandomValues(new Uint8Array(12)); |
| 62 | const gcmResult = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, aesKey, plaintext); |
| 63 | |
| 64 | // gcmResult = ciphertext || tag (last 16 bytes are auth tag) |
| 65 | const gcmBytes = new Uint8Array(gcmResult); |
| 66 | const ciphertext = gcmBytes.slice(0, gcmBytes.length - 16); |
| 67 | const tag = gcmBytes.slice(gcmBytes.length - 16); |
| 68 | |
| 69 | const rawAes = await crypto.subtle.exportKey('raw', aesKey); |
| 70 | const encryptedKey = await crypto.subtle.encrypt({ name: 'RSA-OAEP' }, serverPub, rawAes); |
| 71 | |
| 72 | return { |
| 73 | encryptedKey: b64(encryptedKey), |
| 74 | iv: b64(iv), |
| 75 | ciphertext: b64(ciphertext), |
| 76 | tag: b64(tag), |
| 77 | }; |
| 78 | } |
| 79 | |
| 80 | /** |
| 81 | * Hybrid-decrypt a payload encrypted by the server for us (using our public key). |
| 82 | */ |
| 83 | async function hybridDecryptFromServer(payload) { |
| 84 | const encryptedKey = unb64(payload.encryptedKey); |
| 85 | const iv = unb64(payload.iv); |
| 86 | const ciphertext = unb64(payload.ciphertext); |
| 87 | const tag = unb64(payload.tag); |
| 88 | |
| 89 | const rawAes = await crypto.subtle.decrypt( |
| 90 | { name: 'RSA-OAEP' }, STATE.clientPrivateKey, encryptedKey, |
| 91 | ); |
| 92 | |
| 93 | const aesKey = await crypto.subtle.importKey('raw', rawAes, { name: 'AES-GCM' }, false, ['decrypt']); |
| 94 | |
| 95 | // Recombine ciphertext + tag for AES-GCM |
| 96 | const combined = new Uint8Array(ciphertext.byteLength + tag.byteLength); |
| 97 | combined.set(new Uint8Array(ciphertext)); |
| 98 | combined.set(new Uint8Array(tag), ciphertext.byteLength); |
| 99 | |
| 100 | const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, aesKey, combined); |
| 101 | return new TextDecoder().decode(plain); |
| 102 | } |
| 103 | |
| 104 | // ─────────────────────────────────────────────────────────────────────────── |
| 105 | // UTIL |
| 106 | // ─────────────────────────────────────────────────────────────────────────── |
| 107 | |
| 108 | function b64(buf) { |
| 109 | return btoa(String.fromCharCode(...new Uint8Array(buf instanceof ArrayBuffer ? buf : buf.buffer))); |
| 110 | } |
| 111 | |
| 112 | function unb64(str) { |
| 113 | const binary = atob(str); |
| 114 | const buf = new Uint8Array(binary.length); |
| 115 | for (let i = 0; i < binary.length; i++) buf[i] = binary.charCodeAt(i); |
| 116 | return buf.buffer; |
| 117 | } |
| 118 | |
| 119 | /** Stable browser fingerprint (not stored, derived fresh each load) */ |
| 120 | function getFingerprint() { |
| 121 | const nav = navigator; |
| 122 | return [ |
| 123 | nav.language, |
| 124 | nav.platform || nav.userAgentData?.platform || '', |
| 125 | nav.hardwareConcurrency, |
| 126 | screen.colorDepth, |
| 127 | screen.width + 'x' + screen.height, |
| 128 | Intl.DateTimeFormat().resolvedOptions().timeZone, |
| 129 | ].join('|'); |
| 130 | } |
| 131 | |
| 132 | function formatBytes(bytes) { |
| 133 | if (bytes == null) return '—'; |
| 134 | if (bytes < 1024) return bytes + ' B'; |
| 135 | if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB'; |
| 136 | if (bytes < 1073741824) return (bytes / 1048576).toFixed(1) + ' MB'; |
| 137 | return (bytes / 1073741824).toFixed(2) + ' GB'; |
| 138 | } |
| 139 | |
| 140 | function extOf(name) { |
| 141 | const i = name.lastIndexOf('.'); |
| 142 | return i >= 0 ? name.slice(i + 1).toLowerCase() : ''; |
| 143 | } |
| 144 | |
| 145 | // ─────────────────────────────────────────────────────────────────────────── |
| 146 | // API |
| 147 | // ─────────────────────────────────────────────────────────────────────────── |
| 148 | |
| 149 | async function api(method, path, body, opts = {}) { |
| 150 | const headers = { 'Content-Type': 'application/json' }; |
| 151 | if (STATE.token) { |
| 152 | headers['Authorization'] = 'Bearer ' + STATE.token; |
| 153 | headers['X-Fp'] = getFingerprint(); |
| 154 | } |
| 155 | const res = await fetch('/api' + path, { |
| 156 | method, |
| 157 | headers, |
| 158 | body: body != null ? JSON.stringify(body) : undefined, |
| 159 | ...opts, |
| 160 | }); |
| 161 | if (!res.ok) { |
| 162 | const j = await res.json().catch(() => ({})); |
| 163 | // Session-expired → force re-login |
| 164 | if (res.status === 401) { logout(); return null; } |
| 165 | throw new Error(j.error || res.statusText); |
| 166 | } |
| 167 | return res.json(); |
| 168 | } |
| 169 | |
| 170 | // ─────────────────────────────────────────────────────────────────────────── |
| 171 | // TOAST |
| 172 | // ─────────────────────────────────────────────────────────────────────────── |
| 173 | |
| 174 | function toast(msg, type = '') { |
| 175 | const el = document.createElement('div'); |
| 176 | el.className = 'toast-msg' + (type ? ' ' + type : ''); |
| 177 | el.textContent = msg; |
| 178 | document.getElementById('toast').appendChild(el); |
| 179 | setTimeout(() => el.remove(), 3500); |
| 180 | } |
| 181 | |
| 182 | // ─────────────────────────────────────────────────────────────────────────── |
| 183 | // AUTH FLOW |
| 184 | // ─────────────────────────────────────────────────────────────────────────── |
| 185 | |
| 186 | function showAuthOverlay(setupMode = false) { |
| 187 | document.getElementById('app').classList.add('hidden'); |
| 188 | const overlay = document.getElementById('auth-overlay'); |
| 189 | overlay.classList.remove('hidden'); |
| 190 | document.getElementById('auth-title').textContent = setupMode ? 'Create Admin Account' : 'Sign In'; |
| 191 | document.getElementById('auth-subtitle').classList.toggle('hidden', !setupMode); |
| 192 | document.getElementById('auth-submit').textContent = setupMode ? 'Create Account' : 'Sign In'; |
| 193 | document.getElementById('auth-error').classList.add('hidden'); |
| 194 | document.getElementById('auth-username').value = ''; |
| 195 | document.getElementById('auth-password').value = ''; |
| 196 | document.getElementById('auth-username').focus(); |
| 197 | document.getElementById('auth-form').dataset.mode = setupMode ? 'setup' : 'login'; |
| 198 | } |
| 199 | |
| 200 | function showApp() { |
| 201 | document.getElementById('auth-overlay').classList.add('hidden'); |
| 202 | document.getElementById('app').classList.remove('hidden'); |
| 203 | document.getElementById('btn-admin').classList.toggle('hidden', !STATE.isAdmin); |
| 204 | } |
| 205 | |
| 206 | async function initAuth() { |
| 207 | // Always generate a fresh key pair so each page-load session is independent |
| 208 | await generateClientKeyPair(); |
| 209 | |
| 210 | // Fetch server public key |
| 211 | const { publicKey } = await api('GET', '/auth/server-key').catch(() => ({ publicKey: null })); |
| 212 | if (!publicKey) { toast('Could not reach server.', 'err'); return; } |
| 213 | STATE.serverPublicKeyJwk = publicKey; |
| 214 | |
| 215 | // Check whether first-run setup is needed |
| 216 | const { needed } = await api('GET', '/auth/setup-needed').catch(() => ({ needed: false })); |
| 217 | showAuthOverlay(needed); |
| 218 | } |
| 219 | |
| 220 | async function doLogin(username, password, isSetup) { |
| 221 | const encrypted = await hybridEncryptForServer({ username, password }); |
| 222 | const endpoint = isSetup ? '/auth/setup' : '/auth/login'; |
| 223 | |
| 224 | let data; |
| 225 | try { |
| 226 | data = await api('POST', endpoint, { |
| 227 | encrypted, |
| 228 | clientPublicKey: STATE.clientPublicKeyJwk, |
| 229 | fingerprint: getFingerprint(), |
| 230 | }); |
| 231 | } catch (err) { |
| 232 | return err.message; |
| 233 | } |
| 234 | |
| 235 | if (!data) return 'Login failed.'; |
| 236 | |
| 237 | // Decrypt the token sent back by the server |
| 238 | const token = await hybridDecryptFromServer(data.encrypted); |
| 239 | STATE.token = token; |
| 240 | |
| 241 | // Load user info |
| 242 | const me = await api('GET', '/auth/me'); |
| 243 | if (!me) return 'Session error.'; |
| 244 | |
| 245 | STATE.username = me.username; |
| 246 | STATE.isAdmin = me.isAdmin; |
| 247 | STATE.permissions = me.permissions; |
| 248 | |
| 249 | showApp(); |
| 250 | await loadRoots(); |
| 251 | return null; // no error |
| 252 | } |
| 253 | |
| 254 | function logout() { |
| 255 | STATE.token = null; |
| 256 | STATE.username = null; |
| 257 | STATE.isAdmin = false; |
| 258 | STATE.permissions = {}; |
| 259 | STATE.currentDir = null; |
| 260 | STATE.currentRoot = null; |
| 261 | STATE.items = []; |
| 262 | closeSidebar(); |
| 263 | initAuth(); |
| 264 | } |
| 265 | |
| 266 | // ─────────────────────────────────────────────────────────────────────────── |
| 267 | // NAVIGATION |
| 268 | // ─────────────────────────────────────────────────────────────────────────── |
| 269 | |
| 270 | async function loadRoots() { |
| 271 | const data = await api('GET', '/files/roots'); |
| 272 | if (!data) return; |
| 273 | STATE.roots = data.roots; |
| 274 | |
| 275 | if (STATE.roots.length === 1) { |
| 276 | // Single root → open it directly |
| 277 | await navigateTo(STATE.roots[0].path, STATE.roots[0]); |
| 278 | } else { |
| 279 | renderRootsView(); |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | function renderRootsView() { |
| 284 | STATE.currentDir = null; |
| 285 | STATE.currentRoot = null; |
| 286 | renderBreadcrumb(); |
| 287 | const grid = document.getElementById('file-grid'); |
| 288 | grid.innerHTML = ''; |
| 289 | document.getElementById('empty-notice').classList.add('hidden'); |
| 290 | closeSidebar(); |
| 291 | |
| 292 | for (const root of STATE.roots) { |
| 293 | const el = makeFileItem({ name: root.label, isDir: true, path: root.path, _root: root }); |
| 294 | grid.appendChild(el); |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | async function navigateTo(absPath, root) { |
| 299 | if (root) STATE.currentRoot = root; |
| 300 | STATE.currentDir = absPath; |
| 301 | |
| 302 | const data = await api('GET', `/files/list?dir=${encodeURIComponent(absPath)}`); |
| 303 | if (!data) return; |
| 304 | |
| 305 | STATE.items = data.items; |
| 306 | renderBreadcrumb(); |
| 307 | renderFileGrid(); |
| 308 | closeSidebar(); |
| 309 | } |
| 310 | |
| 311 | function renderBreadcrumb() { |
| 312 | const nav = document.getElementById('breadcrumb'); |
| 313 | nav.innerHTML = ''; |
| 314 | |
| 315 | // "Home" crumb |
| 316 | const home = document.createElement('span'); |
| 317 | home.className = 'crumb' + (STATE.currentDir == null ? ' active' : ''); |
| 318 | home.textContent = 'Home'; |
| 319 | home.addEventListener('click', () => { |
| 320 | if (STATE.roots.length === 1) { |
| 321 | navigateTo(STATE.roots[0].path, STATE.roots[0]); |
| 322 | } else { |
| 323 | renderRootsView(); |
| 324 | } |
| 325 | }); |
| 326 | nav.appendChild(home); |
| 327 | |
| 328 | if (!STATE.currentDir || !STATE.currentRoot) return; |
| 329 | |
| 330 | // Build path segments relative to the root |
| 331 | const rootPath = STATE.currentRoot.path; |
| 332 | const relative = STATE.currentDir === rootPath |
| 333 | ? '' |
| 334 | : STATE.currentDir.replace(rootPath, '').replace(/^[\\/]/, ''); |
| 335 | |
| 336 | const parts = [STATE.currentRoot.label, ...relative.split(/[\\/]/).filter(Boolean)]; |
| 337 | let accumulated = rootPath; |
| 338 | |
| 339 | for (let i = 0; i < parts.length; i++) { |
| 340 | const sep = document.createElement('span'); |
| 341 | sep.className = 'sep'; |
| 342 | sep.textContent = ' / '; |
| 343 | nav.appendChild(sep); |
| 344 | |
| 345 | const crumb = document.createElement('span'); |
| 346 | crumb.className = 'crumb' + (i === parts.length - 1 ? ' active' : ''); |
| 347 | crumb.textContent = parts[i]; |
| 348 | |
| 349 | // Capture the path for this crumb |
| 350 | const capturedPath = i === 0 ? rootPath : accumulated; |
| 351 | if (i < parts.length - 1) { |
| 352 | crumb.addEventListener('click', () => navigateTo(capturedPath, STATE.currentRoot)); |
| 353 | } |
| 354 | |
| 355 | nav.appendChild(crumb); |
| 356 | |
| 357 | // Advance accumulated path (skip for root label) |
| 358 | if (i > 0) accumulated = accumulated + '/' + parts[i]; |
| 359 | else if (i === 0 && parts.length > 1) { |
| 360 | // After root label, next crumb should append the next segment |
| 361 | accumulated = rootPath; |
| 362 | } |
| 363 | } |
| 364 | } |
| 365 | |
| 366 | // ─────────────────────────────────────────────────────────────────────────── |
| 367 | // FILE GRID RENDERING |
| 368 | // ─────────────────────────────────────────────────────────────────────────── |
| 369 | |
| 370 | function renderFileGrid() { |
| 371 | const grid = document.getElementById('file-grid'); |
| 372 | grid.innerHTML = ''; |
| 373 | const empty = document.getElementById('empty-notice'); |
| 374 | |
| 375 | const sorted = [...STATE.items].sort((a, b) => { |
| 376 | if (a.isDir !== b.isDir) return a.isDir ? -1 : 1; |
| 377 | return a.name.localeCompare(b.name); |
| 378 | }); |
| 379 | |
| 380 | empty.classList.toggle('hidden', sorted.length > 0); |
| 381 | |
| 382 | for (const item of sorted) { |
| 383 | grid.appendChild(makeFileItem(item)); |
| 384 | } |
| 385 | } |
| 386 | |
| 387 | function makeFileItem(item) { |
| 388 | const el = document.createElement('div'); |
| 389 | el.className = 'file-item'; |
| 390 | el.dataset.path = item.path; |
| 391 | |
| 392 | const icon = document.createElement('div'); |
| 393 | icon.className = 'icon'; |
| 394 | icon.innerHTML = item.isDir ? iconFolder() : iconFile(item.name); |
| 395 | el.appendChild(icon); |
| 396 | |
| 397 | const name = document.createElement('div'); |
| 398 | name.className = 'name'; |
| 399 | name.textContent = item.name; |
| 400 | el.appendChild(name); |
| 401 | |
| 402 | // Single-click: open sidebar |
| 403 | el.addEventListener('click', (e) => { |
| 404 | e.stopPropagation(); |
| 405 | if (item._root) { |
| 406 | // Clicking a root tile goes straight in |
| 407 | navigateTo(item.path, item._root); |
| 408 | return; |
| 409 | } |
| 410 | selectItem(el, item); |
| 411 | }); |
| 412 | |
| 413 | // Double-click: enter folder or view/download file |
| 414 | el.addEventListener('dblclick', (e) => { |
| 415 | e.stopPropagation(); |
| 416 | if (item.isDir) { |
| 417 | navigateTo(item.path, STATE.currentRoot); |
| 418 | } else { |
| 419 | downloadOrView(item); |
| 420 | } |
| 421 | }); |
| 422 | |
| 423 | return el; |
| 424 | } |
| 425 | |
| 426 | function selectItem(el, item) { |
| 427 | document.querySelectorAll('.file-item.selected').forEach(e => e.classList.remove('selected')); |
| 428 | el.classList.add('selected'); |
| 429 | STATE.selectedItem = item; |
| 430 | openSidebar(item); |
| 431 | } |
| 432 | |
| 433 | // ─────────────────────────────────────────────────────────────────────────── |
| 434 | // SIDEBAR |
| 435 | // ─────────────────────────────────────────────────────────────────────────── |
| 436 | |
| 437 | async function openSidebar(item) { |
| 438 | const sidebar = document.getElementById('sidebar'); |
| 439 | sidebar.classList.remove('hidden'); |
| 440 | document.getElementById('app').classList.add('sidebar-open'); |
| 441 | |
| 442 | document.getElementById('sidebar-icon').innerHTML = item.isDir ? iconFolder(64) : iconFile(item.name, 64); |
| 443 | document.getElementById('sidebar-name').textContent = item.name; |
| 444 | |
| 445 | // Load metadata |
| 446 | const dl = document.getElementById('sidebar-meta'); |
| 447 | dl.innerHTML = '<dt>Loading…</dt><dd></dd>'; |
| 448 | |
| 449 | const actions = document.getElementById('sidebar-actions'); |
| 450 | actions.innerHTML = ''; |
| 451 | |
| 452 | if (!item.isDir) { |
| 453 | const meta = await api('GET', `/files/meta?file=${encodeURIComponent(item.path)}`); |
| 454 | if (meta) { |
| 455 | dl.innerHTML = ` |
| 456 | <dt>Size</dt> <dd>${formatBytes(meta.size)}</dd> |
| 457 | <dt>Modified</dt> <dd>${new Date(meta.mtime).toLocaleString()}</dd> |
| 458 | <dt>Uploaded by</dt><dd>${meta.uploader || '—'}</dd> |
| 459 | <dt>Downloaded by</dt><dd>${meta.downloaders.join(', ') || '—'}</dd> |
| 460 | `; |
| 461 | } |
| 462 | |
| 463 | // View / download button |
| 464 | const btnDl = document.createElement('button'); |
| 465 | btnDl.textContent = 'View / Download'; |
| 466 | btnDl.addEventListener('click', () => downloadOrView(item)); |
| 467 | actions.appendChild(btnDl); |
| 468 | } else { |
| 469 | dl.innerHTML = `<dt>Type</dt><dd>Folder</dd>`; |
| 470 | const btnOpen = document.createElement('button'); |
| 471 | btnOpen.textContent = 'Open folder'; |
| 472 | btnOpen.addEventListener('click', () => navigateTo(item.path, STATE.currentRoot)); |
| 473 | actions.appendChild(btnOpen); |
| 474 | } |
| 475 | |
| 476 | // Rename button (write access required) |
| 477 | if (canWrite()) { |
| 478 | const btnRen = document.createElement('button'); |
| 479 | btnRen.textContent = 'Rename'; |
| 480 | btnRen.addEventListener('click', () => openRenameModal(item)); |
| 481 | actions.appendChild(btnRen); |
| 482 | |
| 483 | const btnDel = document.createElement('button'); |
| 484 | btnDel.textContent = 'Delete'; |
| 485 | btnDel.className = 'danger'; |
| 486 | btnDel.addEventListener('click', () => deleteItem(item)); |
| 487 | actions.appendChild(btnDel); |
| 488 | } |
| 489 | } |
| 490 | |
| 491 | function closeSidebar() { |
| 492 | document.getElementById('sidebar').classList.add('hidden'); |
| 493 | document.getElementById('app').classList.remove('sidebar-open'); |
| 494 | document.querySelectorAll('.file-item.selected').forEach(e => e.classList.remove('selected')); |
| 495 | STATE.selectedItem = null; |
| 496 | } |
| 497 | |
| 498 | // ─────────────────────────────────────────────────────────────────────────── |
| 499 | // DOWNLOAD / VIEW |
| 500 | // ─────────────────────────────────────────────────────────────────────────── |
| 501 | |
| 502 | function downloadOrView(item) { |
| 503 | const url = `/api/files/download?file=${encodeURIComponent(item.path)}`; |
| 504 | // Open in new tab — browser decides whether to display or download |
| 505 | const a = document.createElement('a'); |
| 506 | a.href = url; |
| 507 | a.target = '_blank'; |
| 508 | a.rel = 'noopener noreferrer'; |
| 509 | // We need to send the auth header; since <a> can't do that, we fetch and blob it |
| 510 | fetchAndServe(item, url); |
| 511 | } |
| 512 | |
| 513 | async function fetchAndServe(item, url) { |
| 514 | try { |
| 515 | const res = await fetch(url, { |
| 516 | headers: { |
| 517 | Authorization: 'Bearer ' + STATE.token, |
| 518 | 'X-Fp': getFingerprint(), |
| 519 | }, |
| 520 | }); |
| 521 | if (!res.ok) { toast('Download failed.', 'err'); return; } |
| 522 | const blob = await res.blob(); |
| 523 | const objUrl = URL.createObjectURL(blob); |
| 524 | const a = document.createElement('a'); |
| 525 | a.href = objUrl; |
| 526 | a.download = item.name; |
| 527 | // Try to open viewable types inline |
| 528 | const viewable = /^(image|video|audio|text|application\/pdf)/.test(blob.type); |
| 529 | if (viewable) { |
| 530 | window.open(objUrl, '_blank', 'noopener,noreferrer'); |
| 531 | } else { |
| 532 | a.click(); |
| 533 | } |
| 534 | setTimeout(() => URL.revokeObjectURL(objUrl), 60000); |
| 535 | } catch { |
| 536 | toast('Download failed.', 'err'); |
| 537 | } |
| 538 | } |
| 539 | |
| 540 | // ─────────────────────────────────────────────────────────────────────────── |
| 541 | // UPLOAD |
| 542 | // ─────────────────────────────────────────────────────────────────────────── |
| 543 | |
| 544 | function canWrite() { |
| 545 | if (STATE.isAdmin) return true; |
| 546 | if (!STATE.currentRoot) return false; |
| 547 | const p = STATE.permissions[STATE.currentRoot.label]; |
| 548 | return p && p.write; |
| 549 | } |
| 550 | |
| 551 | async function uploadFiles(fileList) { |
| 552 | if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; } |
| 553 | if (!canWrite()) { toast('No write access.', 'err'); return; } |
| 554 | |
| 555 | const formData = new FormData(); |
| 556 | for (const f of fileList) formData.append('files', f); |
| 557 | |
| 558 | // Show upload bar |
| 559 | const wrap = document.createElement('div'); |
| 560 | wrap.className = 'upload-bar-wrap'; |
| 561 | wrap.innerHTML = `<span>Uploading ${fileList.length} file(s)…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`; |
| 562 | document.body.appendChild(wrap); |
| 563 | |
| 564 | try { |
| 565 | const xhr = new XMLHttpRequest(); |
| 566 | xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(STATE.currentDir)}`); |
| 567 | xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token); |
| 568 | xhr.setRequestHeader('X-Fp', getFingerprint()); |
| 569 | |
| 570 | xhr.upload.addEventListener('progress', e => { |
| 571 | if (e.lengthComputable) { |
| 572 | wrap.querySelector('.upload-bar-fill').style.width = (e.loaded / e.total * 100) + '%'; |
| 573 | } |
| 574 | }); |
| 575 | |
| 576 | await new Promise((resolve, reject) => { |
| 577 | xhr.onload = () => { |
| 578 | if (xhr.status === 200) resolve(); |
| 579 | else reject(new Error(JSON.parse(xhr.responseText).error || 'Upload failed')); |
| 580 | }; |
| 581 | xhr.onerror = () => reject(new Error('Network error')); |
| 582 | xhr.send(formData); |
| 583 | }); |
| 584 | |
| 585 | toast(`Uploaded ${fileList.length} file(s).`, 'ok'); |
| 586 | await navigateTo(STATE.currentDir, STATE.currentRoot); |
| 587 | } catch (err) { |
| 588 | toast(err.message, 'err'); |
| 589 | } finally { |
| 590 | wrap.remove(); |
| 591 | } |
| 592 | } |
| 593 | |
| 594 | // ─────────────────────────────────────────────────────────────────────────── |
| 595 | // FOLDER DRAG-AND-DROP (recursive) |
| 596 | // ─────────────────────────────────────────────────────────────────────────── |
| 597 | |
| 598 | /** |
| 599 | * Reads all readEntries batches from a DirectoryReader (browsers may return |
| 600 | * results in chunks; we must keep calling until we get an empty array). |
| 601 | */ |
| 602 | function readAllEntries(reader) { |
| 603 | return new Promise((resolve, reject) => { |
| 604 | const all = []; |
| 605 | function next() { |
| 606 | reader.readEntries(batch => { |
| 607 | if (!batch.length) { resolve(all); return; } |
| 608 | all.push(...batch); |
| 609 | next(); |
| 610 | }, reject); |
| 611 | } |
| 612 | next(); |
| 613 | }); |
| 614 | } |
| 615 | |
| 616 | /** |
| 617 | * Recursively walk a FileSystemEntry tree, creating server-side directories |
| 618 | * on the fly and collecting { file, targetDir } pairs for upload. |
| 619 | */ |
| 620 | async function collectEntries(entry, serverDir, toUpload) { |
| 621 | if (entry.isFile) { |
| 622 | const file = await new Promise((res, rej) => entry.getFile(res, rej)); |
| 623 | toUpload.push({ file, targetDir: serverDir }); |
| 624 | } else if (entry.isDirectory) { |
| 625 | // Ask the server to create the directory; it returns the canonical path. |
| 626 | let newServerDir; |
| 627 | try { |
| 628 | const resp = await api('POST', '/files/mkdir', { dir: serverDir, name: entry.name }); |
| 629 | newServerDir = resp.path; |
| 630 | } catch { |
| 631 | // Directory may already exist — reconstruct path from what we know. |
| 632 | // The server always returns JSON with {error} on failure, so we can |
| 633 | // still continue by falling back to a best-effort path join. |
| 634 | // We rely on the fact that the server separator is consistent within |
| 635 | // a session (the list/browse API already returned paths in that format). |
| 636 | const sep = serverDir.includes('\\') ? '\\' : '/'; |
| 637 | newServerDir = serverDir + sep + entry.name; |
| 638 | } |
| 639 | const reader = entry.createReader(); |
| 640 | const subEntries = await readAllEntries(reader); |
| 641 | for (const sub of subEntries) { |
| 642 | await collectEntries(sub, newServerDir, toUpload); |
| 643 | } |
| 644 | } |
| 645 | } |
| 646 | |
| 647 | async function uploadEntries(entries) { |
| 648 | if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; } |
| 649 | if (!canWrite()) { toast('No write access.', 'err'); return; } |
| 650 | |
| 651 | const wrap = document.createElement('div'); |
| 652 | wrap.className = 'upload-bar-wrap'; |
| 653 | wrap.innerHTML = `<span>Scanning…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`; |
| 654 | document.body.appendChild(wrap); |
| 655 | |
| 656 | try { |
| 657 | const toUpload = []; |
| 658 | for (const entry of entries) { |
| 659 | await collectEntries(entry, STATE.currentDir, toUpload); |
| 660 | } |
| 661 | |
| 662 | if (!toUpload.length) { toast('No files found.', 'err'); return; } |
| 663 | |
| 664 | let done = 0; |
| 665 | const total = toUpload.length; |
| 666 | const updateBar = () => { |
| 667 | wrap.querySelector('span').textContent = `Uploading ${done} / ${total} file(s)…`; |
| 668 | wrap.querySelector('.upload-bar-fill').style.width = (done / total * 100) + '%'; |
| 669 | }; |
| 670 | updateBar(); |
| 671 | |
| 672 | for (const { file, targetDir } of toUpload) { |
| 673 | const formData = new FormData(); |
| 674 | formData.append('files', file); |
| 675 | await new Promise((resolve, reject) => { |
| 676 | const xhr = new XMLHttpRequest(); |
| 677 | xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(targetDir)}`); |
| 678 | xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token); |
| 679 | xhr.setRequestHeader('X-Fp', getFingerprint()); |
| 680 | xhr.onload = () => xhr.status === 200 |
| 681 | ? resolve() |
| 682 | : reject(new Error((JSON.parse(xhr.responseText) || {}).error || 'Upload failed')); |
| 683 | xhr.onerror = () => reject(new Error('Network error')); |
| 684 | xhr.send(formData); |
| 685 | }); |
| 686 | done++; |
| 687 | updateBar(); |
| 688 | } |
| 689 | |
| 690 | toast(`Uploaded ${total} file(s).`, 'ok'); |
| 691 | await navigateTo(STATE.currentDir, STATE.currentRoot); |
| 692 | } catch (err) { |
| 693 | toast(err.message, 'err'); |
| 694 | } finally { |
| 695 | wrap.remove(); |
| 696 | } |
| 697 | } |
| 698 | |
| 699 | // DRAG-AND-DROP |
| 700 | // ─────────────────────────────────────────────────────────────────────────── |
| 701 | |
| 702 | function initDragDrop() { |
| 703 | const main = document.getElementById('main-content'); |
| 704 | const dropOvl = document.getElementById('drop-overlay'); |
| 705 | let dragDepth = 0; |
| 706 | |
| 707 | main.addEventListener('dragenter', e => { |
| 708 | e.preventDefault(); |
| 709 | dragDepth++; |
| 710 | dropOvl.classList.remove('hidden'); |
| 711 | }); |
| 712 | main.addEventListener('dragleave', () => { |
| 713 | dragDepth--; |
| 714 | if (dragDepth <= 0) { dragDepth = 0; dropOvl.classList.add('hidden'); } |
| 715 | }); |
| 716 | main.addEventListener('dragover', e => e.preventDefault()); |
| 717 | main.addEventListener('drop', async e => { |
| 718 | e.preventDefault(); |
| 719 | dragDepth = 0; |
| 720 | dropOvl.classList.add('hidden'); |
| 721 | if (!canWrite()) { toast('No write access.', 'err'); return; } |
| 722 | |
| 723 | const items = Array.from(e.dataTransfer.items || []); |
| 724 | // Use the FileSystem Entry API when available so we can handle folders. |
| 725 | if (items.length && typeof items[0].webkitGetAsEntry === 'function') { |
| 726 | const entries = items.map(i => i.webkitGetAsEntry()).filter(Boolean); |
| 727 | if (entries.some(en => en.isDirectory)) { |
| 728 | await uploadEntries(entries); |
| 729 | return; |
| 730 | } |
| 731 | } |
| 732 | // Plain files only — use the fast batch path. |
| 733 | const files = e.dataTransfer.files; |
| 734 | if (files.length) await uploadFiles(files); |
| 735 | }); |
| 736 | } |
| 737 | |
| 738 | // ─────────────────────────────────────────────────────────────────────────── |
| 739 | // RENAME |
| 740 | // ─────────────────────────────────────────────────────────────────────────── |
| 741 | |
| 742 | function openRenameModal(item) { |
| 743 | const modal = document.getElementById('rename-modal'); |
| 744 | modal.classList.remove('hidden'); |
| 745 | const input = document.getElementById('rename-input'); |
| 746 | input.value = item.name; |
| 747 | input.focus(); |
| 748 | input.select(); |
| 749 | document.getElementById('rename-error').classList.add('hidden'); |
| 750 | document.getElementById('rename-form').onsubmit = async (e) => { |
| 751 | e.preventDefault(); |
| 752 | const newName = input.value.trim(); |
| 753 | if (!newName) return; |
| 754 | try { |
| 755 | await api('POST', '/files/rename', { from: item.path, to: newName }); |
| 756 | modal.classList.add('hidden'); |
| 757 | toast('Renamed.', 'ok'); |
| 758 | await navigateTo(STATE.currentDir, STATE.currentRoot); |
| 759 | } catch (err) { |
| 760 | document.getElementById('rename-error').textContent = err.message; |
| 761 | document.getElementById('rename-error').classList.remove('hidden'); |
| 762 | } |
| 763 | }; |
| 764 | } |
| 765 | |
| 766 | // ─────────────────────────────────────────────────────────────────────────── |
| 767 | // DELETE |
| 768 | // ─────────────────────────────────────────────────────────────────────────── |
| 769 | |
| 770 | async function deleteItem(item) { |
| 771 | if (!confirm(`Delete "${item.name}"? This cannot be undone.`)) return; |
| 772 | try { |
| 773 | await api('POST', '/files/delete', { path: item.path }); |
| 774 | toast('Deleted.', 'ok'); |
| 775 | closeSidebar(); |
| 776 | await navigateTo(STATE.currentDir, STATE.currentRoot); |
| 777 | } catch (err) { |
| 778 | toast(err.message, 'err'); |
| 779 | } |
| 780 | } |
| 781 | |
| 782 | // ─────────────────────────────────────────────────────────────────────────── |
| 783 | // ADMIN PANEL |
| 784 | // ─────────────────────────────────────────────────────────────────────────── |
| 785 | |
| 786 | async function openAdminModal() { |
| 787 | document.getElementById('admin-modal').classList.remove('hidden'); |
| 788 | await refreshAdminConfig(); |
| 789 | await refreshAdminUsers(); |
| 790 | } |
| 791 | |
| 792 | async function refreshAdminConfig() { |
| 793 | const data = await api('GET', '/admin/config'); |
| 794 | if (!data) return; |
| 795 | const container = document.getElementById('admin-paths'); |
| 796 | container.innerHTML = ''; |
| 797 | for (const p of data.paths) { |
| 798 | const row = document.createElement('div'); |
| 799 | row.className = 'path-row'; |
| 800 | row.innerHTML = `<span>${p}</span><button data-path="${p}" title="Remove">✕</button>`; |
| 801 | row.querySelector('button').addEventListener('click', () => { |
| 802 | row.remove(); |
| 803 | }); |
| 804 | container.appendChild(row); |
| 805 | } |
| 806 | } |
| 807 | |
| 808 | async function refreshAdminUsers() { |
| 809 | const data = await api('GET', '/admin/users'); |
| 810 | if (!data) return; |
| 811 | const container = document.getElementById('admin-users-list'); |
| 812 | container.innerHTML = ''; |
| 813 | |
| 814 | // Need paths for permission rows |
| 815 | const cfg = await api('GET', '/admin/config'); |
| 816 | const paths = cfg ? (cfg.effectivePaths || []) : []; |
| 817 | |
| 818 | for (const u of data.users) { |
| 819 | const row = document.createElement('div'); |
| 820 | row.className = 'user-row'; |
| 821 | row.innerHTML = ` |
| 822 | <span class="user-name">${u.username}</span> |
| 823 | ${u.isAdmin ? '<span class="user-admin-badge">Admin</span>' : ''} |
| 824 | <button data-id="${u.id}" data-action="edit">Edit</button> |
| 825 | <button data-id="${u.id}" data-action="delete" class="danger">Delete</button> |
| 826 | `; |
| 827 | row.querySelector('[data-action="edit"]').addEventListener('click', () => |
| 828 | openUserModal(u, paths)); |
| 829 | row.querySelector('[data-action="delete"]').addEventListener('click', async () => { |
| 830 | if (!confirm(`Delete user "${u.username}"?`)) return; |
| 831 | try { |
| 832 | await api('DELETE', `/admin/users/${u.id}`); |
| 833 | toast('User deleted.', 'ok'); |
| 834 | await refreshAdminUsers(); |
| 835 | } catch (err) { toast(err.message, 'err'); } |
| 836 | }); |
| 837 | container.appendChild(row); |
| 838 | } |
| 839 | } |
| 840 | |
| 841 | function openUserModal(user, paths) { |
| 842 | const modal = document.getElementById('user-modal'); |
| 843 | modal.classList.remove('hidden'); |
| 844 | document.getElementById('user-modal-title').textContent = user ? `Edit: ${user.username}` : 'New User'; |
| 845 | document.getElementById('user-error').classList.add('hidden'); |
| 846 | |
| 847 | const usernameInput = document.getElementById('user-username'); |
| 848 | usernameInput.value = user ? user.username : ''; |
| 849 | usernameInput.readOnly = !!user; |
| 850 | |
| 851 | document.getElementById('user-password').value = ''; |
| 852 | document.getElementById('user-is-admin').checked = user ? user.isAdmin : false; |
| 853 | |
| 854 | // Password placeholder |
| 855 | document.getElementById('user-password').placeholder = |
| 856 | user ? 'Leave blank to keep current' : 'Min 8 characters'; |
| 857 | |
| 858 | // Build permissions grid |
| 859 | const permDiv = document.getElementById('user-permissions'); |
| 860 | permDiv.innerHTML = ''; |
| 861 | if (paths.length) { |
| 862 | const heading = document.createElement('h4'); |
| 863 | heading.textContent = 'Path Permissions'; |
| 864 | permDiv.appendChild(heading); |
| 865 | |
| 866 | const isAdminUser = !!(user && user.isAdmin); |
| 867 | // Mirror the is-admin checkbox so toggling it live-updates the perm rows. |
| 868 | const adminChk = document.getElementById('user-is-admin'); |
| 869 | const rebuildPermRows = (admin) => { |
| 870 | permDiv.querySelectorAll('.perm-row').forEach(r => { |
| 871 | r.querySelectorAll('input[type=checkbox]').forEach(cb => { |
| 872 | cb.disabled = admin; |
| 873 | if (admin) cb.checked = true; |
| 874 | }); |
| 875 | r.title = admin ? 'Admins always have full access' : ''; |
| 876 | }); |
| 877 | }; |
| 878 | adminChk.addEventListener('change', () => rebuildPermRows(adminChk.checked)); |
| 879 | |
| 880 | for (const p of paths) { |
| 881 | const label = p.split(/[\\/]/).pop(); |
| 882 | const perms = user && user.permissions ? (user.permissions[label] || {}) : {}; |
| 883 | const row = document.createElement('div'); |
| 884 | row.className = 'perm-row'; |
| 885 | const readChecked = isAdminUser || perms.read; |
| 886 | const writeChecked = isAdminUser || perms.write; |
| 887 | row.innerHTML = ` |
| 888 | <span class="perm-label">${label}</span> |
| 889 | <label class="checkbox-label"><input type="checkbox" data-label="${label}" data-type="read" ${readChecked ? 'checked' : ''} ${isAdminUser ? 'disabled' : ''} /> Read</label> |
| 890 | <label class="checkbox-label"><input type="checkbox" data-label="${label}" data-type="write" ${writeChecked ? 'checked' : ''} ${isAdminUser ? 'disabled' : ''} /> Write</label> |
| 891 | `; |
| 892 | if (isAdminUser) row.title = 'Admins always have full access'; |
| 893 | permDiv.appendChild(row); |
| 894 | } |
| 895 | } |
| 896 | |
| 897 | document.getElementById('user-form').onsubmit = async (e) => { |
| 898 | e.preventDefault(); |
| 899 | const password = document.getElementById('user-password').value; |
| 900 | const isAdmin = document.getElementById('user-is-admin').checked; |
| 901 | const permissions = {}; |
| 902 | permDiv.querySelectorAll('input[data-label]').forEach(cb => { |
| 903 | const lbl = cb.dataset.label; |
| 904 | if (!permissions[lbl]) permissions[lbl] = {}; |
| 905 | permissions[lbl][cb.dataset.type] = cb.checked; |
| 906 | }); |
| 907 | |
| 908 | try { |
| 909 | if (user) { |
| 910 | const body = { isAdmin, permissions }; |
| 911 | if (password) body.password = password; |
| 912 | await api('PATCH', `/admin/users/${user.id}`, body); |
| 913 | } else { |
| 914 | const uname = document.getElementById('user-username').value.trim(); |
| 915 | await api('POST', '/admin/users', { username: uname, password, isAdmin, permissions }); |
| 916 | } |
| 917 | modal.classList.add('hidden'); |
| 918 | toast('User saved.', 'ok'); |
| 919 | await refreshAdminUsers(); |
| 920 | } catch (err) { |
| 921 | document.getElementById('user-error').textContent = err.message; |
| 922 | document.getElementById('user-error').classList.remove('hidden'); |
| 923 | } |
| 924 | }; |
| 925 | } |
| 926 | |
| 927 | // ─────────────────────────────────────────────────────────────────────────── |
| 928 | // SVG ICONS |
| 929 | // ─────────────────────────────────────────────────────────────────────────── |
| 930 | |
| 931 | const IMAGE_EXTS = new Set(['jpg','jpeg','png','gif','webp','svg','bmp','ico','avif']); |
| 932 | const VIDEO_EXTS = new Set(['mp4','webm','ogv','mov','avi','mkv']); |
| 933 | const AUDIO_EXTS = new Set(['mp3','ogg','wav','flac','aac','m4a']); |
| 934 | const DOC_EXTS = new Set(['pdf','doc','docx','xls','xlsx','ppt','pptx','odt','ods','odp']); |
| 935 | 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']); |
| 936 | const ARCHIVE_EXTS= new Set(['zip','tar','gz','bz2','xz','rar','7z']); |
| 937 | |
| 938 | function iconFolder(size = 52) { |
| 939 | return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" |
| 940 | stroke="#5b7fff" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"> |
| 941 | <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"/> |
| 942 | </svg>`; |
| 943 | } |
| 944 | |
| 945 | function iconFile(name, size = 52) { |
| 946 | const ext = extOf(name); |
| 947 | let color = '#7880a0'; |
| 948 | let symbol = ''; |
| 949 | |
| 950 | if (IMAGE_EXTS.has(ext)) color = '#3fcf8e'; |
| 951 | else if (VIDEO_EXTS.has(ext)) color = '#e05c6e'; |
| 952 | else if (AUDIO_EXTS.has(ext)) color = '#c084fc'; |
| 953 | else if (DOC_EXTS.has(ext)) color = '#f97316'; |
| 954 | else if (CODE_EXTS.has(ext)) color = '#38bdf8'; |
| 955 | else if (ARCHIVE_EXTS.has(ext))color = '#facc15'; |
| 956 | |
| 957 | return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" |
| 958 | stroke="${color}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"> |
| 959 | <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/> |
| 960 | <polyline points="14 2 14 8 20 8"/> |
| 961 | </svg>`; |
| 962 | } |
| 963 | |
| 964 | // ─────────────────────────────────────────────────────────────────────────── |
| 965 | // EVENT WIRING |
| 966 | // ─────────────────────────────────────────────────────────────────────────── |
| 967 | |
| 968 | function wireEvents() { |
| 969 | // Auth form |
| 970 | document.getElementById('auth-form').addEventListener('submit', async (e) => { |
| 971 | e.preventDefault(); |
| 972 | const username = document.getElementById('auth-username').value.trim(); |
| 973 | const password = document.getElementById('auth-password').value; |
| 974 | const isSetup = e.target.dataset.mode === 'setup'; |
| 975 | const errEl = document.getElementById('auth-error'); |
| 976 | const btn = document.getElementById('auth-submit'); |
| 977 | btn.disabled = true; |
| 978 | btn.textContent = 'Please wait…'; |
| 979 | const err = await doLogin(username, password, isSetup); |
| 980 | if (err) { |
| 981 | errEl.textContent = err; |
| 982 | errEl.classList.remove('hidden'); |
| 983 | btn.disabled = false; |
| 984 | btn.textContent = isSetup ? 'Create Account' : 'Sign In'; |
| 985 | } |
| 986 | }); |
| 987 | |
| 988 | // Logout |
| 989 | document.getElementById('btn-logout').addEventListener('click', logout); |
| 990 | |
| 991 | // Upload button |
| 992 | document.getElementById('btn-upload').addEventListener('click', () => { |
| 993 | if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; } |
| 994 | if (!canWrite()) { toast('No write access.', 'err'); return; } |
| 995 | document.getElementById('file-input').click(); |
| 996 | }); |
| 997 | |
| 998 | document.getElementById('file-input').addEventListener('change', async (e) => { |
| 999 | if (e.target.files.length) await uploadFiles(e.target.files); |
| 1000 | e.target.value = ''; |
| 1001 | }); |
| 1002 | |
| 1003 | // Sidebar close |
| 1004 | document.getElementById('sidebar-close').addEventListener('click', closeSidebar); |
| 1005 | |
| 1006 | // Click outside grid closes sidebar |
| 1007 | document.getElementById('main-content').addEventListener('click', (e) => { |
| 1008 | if (!e.target.closest('.file-item')) closeSidebar(); |
| 1009 | }); |
| 1010 | |
| 1011 | // Admin panel |
| 1012 | document.getElementById('btn-admin').addEventListener('click', openAdminModal); |
| 1013 | document.getElementById('admin-modal-close').addEventListener('click', () => |
| 1014 | document.getElementById('admin-modal').classList.add('hidden')); |
| 1015 | |
| 1016 | // Add path |
| 1017 | document.getElementById('admin-add-path').addEventListener('click', () => { |
| 1018 | const val = document.getElementById('admin-new-path').value.trim(); |
| 1019 | if (!val) return; |
| 1020 | const row = document.createElement('div'); |
| 1021 | row.className = 'path-row'; |
| 1022 | row.innerHTML = `<span>${val}</span><button title="Remove">✕</button>`; |
| 1023 | row.querySelector('button').addEventListener('click', () => row.remove()); |
| 1024 | document.getElementById('admin-paths').appendChild(row); |
| 1025 | document.getElementById('admin-new-path').value = ''; |
| 1026 | }); |
| 1027 | |
| 1028 | // Save paths |
| 1029 | document.getElementById('admin-save-paths').addEventListener('click', async () => { |
| 1030 | const rows = document.querySelectorAll('#admin-paths .path-row span'); |
| 1031 | const paths = [...rows].map(s => s.textContent.trim()).filter(Boolean); |
| 1032 | try { |
| 1033 | await api('PUT', '/admin/config', { paths }); |
| 1034 | toast('Paths saved.', 'ok'); |
| 1035 | await loadRoots(); |
| 1036 | } catch (err) { toast(err.message, 'err'); } |
| 1037 | }); |
| 1038 | |
| 1039 | // Shutdown server |
| 1040 | document.getElementById('admin-shutdown-btn').addEventListener('click', async () => { |
| 1041 | if (!confirm('Shut down the server? You will lose access until it is restarted manually.')) return; |
| 1042 | try { |
| 1043 | await api('POST', '/admin/shutdown'); |
| 1044 | toast('Server is shutting down…', 'ok'); |
| 1045 | document.getElementById('admin-modal').classList.add('hidden'); |
| 1046 | } catch { |
| 1047 | // Fetch may throw because the connection closes before a response arrives. |
| 1048 | toast('Server is shutting down…', 'ok'); |
| 1049 | document.getElementById('admin-modal').classList.add('hidden'); |
| 1050 | } |
| 1051 | }); |
| 1052 | |
| 1053 | // New user |
| 1054 | document.getElementById('admin-new-user-btn').addEventListener('click', async () => { |
| 1055 | const cfg = await api('GET', '/admin/config'); |
| 1056 | const paths = cfg ? (cfg.effectivePaths || []) : []; |
| 1057 | openUserModal(null, paths); |
| 1058 | }); |
| 1059 | |
| 1060 | // User modal close |
| 1061 | document.getElementById('user-modal-close').addEventListener('click', () => |
| 1062 | document.getElementById('user-modal').classList.add('hidden')); |
| 1063 | |
| 1064 | // Rename modal close |
| 1065 | document.getElementById('rename-modal-close').addEventListener('click', () => |
| 1066 | document.getElementById('rename-modal').classList.add('hidden')); |
| 1067 | |
| 1068 | // Close modals on backdrop click |
| 1069 | document.querySelectorAll('.modal-overlay').forEach(overlay => { |
| 1070 | overlay.addEventListener('click', e => { |
| 1071 | if (e.target === overlay) overlay.classList.add('hidden'); |
| 1072 | }); |
| 1073 | }); |
| 1074 | } |
| 1075 | |
| 1076 | // ─────────────────────────────────────────────────────────────────────────── |
| 1077 | // BOOT |
| 1078 | // ─────────────────────────────────────────────────────────────────────────── |
| 1079 | |
| 1080 | (async function boot() { |
| 1081 | wireEvents(); |
| 1082 | initDragDrop(); |
| 1083 | await initAuth(); |
| 1084 | })(); |