| 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 | // Blob URLs for thumbnail previews — revoked on each grid rebuild |
| 45 | thumbnailUrls: [], |
| 46 | thumbnailObserver: null, |
| 47 | folderIconObserver: null, |
| 48 | |
| 49 | // Preview overlay state |
| 50 | previewObjectUrl: null, |
| 51 | previewCleanup: null, |
| 52 | previewDownloadAction: null, |
| 53 | previewVideoStreamSessionId: null, |
| 54 | previewSourceEl: null, // SVG element that triggered the preview |
| 55 | previewClosing: false, // guard to prevent double-close during animation |
| 56 | previewExpandState: null, // in-place expanded tile preview state |
| 57 | movePicker: null, |
| 58 | }; |
| 59 | |
| 60 | const SESSION_KEY = 'filemanager.session.v1'; |
| 61 | const SESSION_IDLE_TIMEOUT_MS = 60 * 60 * 1000; // 1 hour |
| 62 | const CLIENT_BINDING_KEY = 'filemanager.client-binding-id.v1'; |
| 63 | const MOBILE_BREAKPOINT_QUERY = '(max-width: 600px)'; |
| 64 | const MOBILE_LONG_PRESS_MS = 420; |
| 65 | const MOBILE_LONG_PRESS_MOVE_THRESHOLD = 10; |
| 66 | const THUMB_OBSERVER_ROOT_MARGIN = '120px'; |
| 67 | const VIDEO_PREFS_KEY_PREFIX = 'filemanager.video-prefs.v1.'; |
| 68 | const VIDEO_TEXT_TRACK_SETTINGS_KEY = 'vjs-text-track-settings'; |
| 69 | const VIDEO_TEXT_TRACK_OVERRIDE_SETTINGS_RAW = JSON.stringify({ |
| 70 | backgroundOpacity: '0', |
| 71 | edgeStyle: 'uniform', |
| 72 | }); |
| 73 | const VIDEO_FORWARD_BUFFER_SECONDS = 60 * 60; |
| 74 | const VIDEO_FORWARD_BUFFER_OVERRIDE_ENABLED = false; |
| 75 | let videoJsLoaderPromise = null; |
| 76 | |
| 77 | // ─────────────────────────────────────────────────────────────────────────── |
| 78 | // CRYPTO HELPERS (Web Crypto API) |
| 79 | // ─────────────────────────────────────────────────────────────────────────── |
| 80 | |
| 81 | async function generateClientKeyPair () |
| 82 | { |
| 83 | if (!hasWebCrypto()) return; |
| 84 | const kp = await crypto.subtle.generateKey( |
| 85 | { name: 'RSA-OAEP', modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256' }, |
| 86 | true, |
| 87 | ['encrypt', 'decrypt'], |
| 88 | ); |
| 89 | STATE.clientPrivateKey = kp.privateKey; |
| 90 | STATE.clientPublicKeyJwk = await crypto.subtle.exportKey('jwk', kp.publicKey); |
| 91 | } |
| 92 | |
| 93 | /** |
| 94 | * Hybrid-encrypt a JS object using the server's RSA public key. |
| 95 | * Returns { encryptedKey, iv, ciphertext, tag } all as base64 strings. |
| 96 | */ |
| 97 | async function hybridEncryptForServer (obj) |
| 98 | { |
| 99 | if (!hasWebCrypto() || !STATE.serverPublicKeyJwk) |
| 100 | { |
| 101 | return { plaintext: obj }; |
| 102 | } |
| 103 | |
| 104 | const serverPub = await crypto.subtle.importKey( |
| 105 | 'jwk', STATE.serverPublicKeyJwk, |
| 106 | { name: 'RSA-OAEP', hash: 'SHA-256' }, |
| 107 | false, ['encrypt'], |
| 108 | ); |
| 109 | |
| 110 | const plaintext = new TextEncoder().encode(JSON.stringify(obj)); |
| 111 | const aesKey = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt']); |
| 112 | const iv = crypto.getRandomValues(new Uint8Array(12)); |
| 113 | const gcmResult = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, aesKey, plaintext); |
| 114 | |
| 115 | // gcmResult = ciphertext || tag (last 16 bytes are auth tag) |
| 116 | const gcmBytes = new Uint8Array(gcmResult); |
| 117 | const ciphertext = gcmBytes.slice(0, gcmBytes.length - 16); |
| 118 | const tag = gcmBytes.slice(gcmBytes.length - 16); |
| 119 | |
| 120 | const rawAes = await crypto.subtle.exportKey('raw', aesKey); |
| 121 | const encryptedKey = await crypto.subtle.encrypt({ name: 'RSA-OAEP' }, serverPub, rawAes); |
| 122 | |
| 123 | return { |
| 124 | encryptedKey: b64(encryptedKey), |
| 125 | iv: b64(iv), |
| 126 | ciphertext: b64(ciphertext), |
| 127 | tag: b64(tag), |
| 128 | }; |
| 129 | } |
| 130 | |
| 131 | /** |
| 132 | * Hybrid-decrypt a payload encrypted by the server for us (using our public key). |
| 133 | */ |
| 134 | async function hybridDecryptFromServer (payload) |
| 135 | { |
| 136 | if (!payload) return null; |
| 137 | if (payload.token) return payload.token; |
| 138 | if (!hasWebCrypto()) return null; |
| 139 | |
| 140 | const encryptedKey = unb64(payload.encryptedKey); |
| 141 | const iv = unb64(payload.iv); |
| 142 | const ciphertext = unb64(payload.ciphertext); |
| 143 | const tag = unb64(payload.tag); |
| 144 | |
| 145 | const rawAes = await crypto.subtle.decrypt( |
| 146 | { name: 'RSA-OAEP' }, STATE.clientPrivateKey, encryptedKey, |
| 147 | ); |
| 148 | |
| 149 | const aesKey = await crypto.subtle.importKey('raw', rawAes, { name: 'AES-GCM' }, false, ['decrypt']); |
| 150 | |
| 151 | // Recombine ciphertext + tag for AES-GCM |
| 152 | const combined = new Uint8Array(ciphertext.byteLength + tag.byteLength); |
| 153 | combined.set(new Uint8Array(ciphertext)); |
| 154 | combined.set(new Uint8Array(tag), ciphertext.byteLength); |
| 155 | |
| 156 | const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, aesKey, combined); |
| 157 | return new TextDecoder().decode(plain); |
| 158 | } |
| 159 | |
| 160 | // ─────────────────────────────────────────────────────────────────────────── |
| 161 | // UTIL |
| 162 | // ─────────────────────────────────────────────────────────────────────────── |
| 163 | |
| 164 | function b64 (buf) |
| 165 | { |
| 166 | return btoa(String.fromCharCode(...new Uint8Array(buf instanceof ArrayBuffer ? buf : buf.buffer))); |
| 167 | } |
| 168 | |
| 169 | function hasWebCrypto () |
| 170 | { |
| 171 | return !!(window.crypto && window.crypto.subtle); |
| 172 | } |
| 173 | |
| 174 | function unb64 (str) |
| 175 | { |
| 176 | const binary = atob(str); |
| 177 | const buf = new Uint8Array(binary.length); |
| 178 | for (let i = 0; i < binary.length; i++) buf[i] = binary.charCodeAt(i); |
| 179 | return buf.buffer; |
| 180 | } |
| 181 | |
| 182 | /** Stable browser fingerprint (not stored, derived fresh each load) */ |
| 183 | function getFingerprint () |
| 184 | { |
| 185 | const binding = getOrCreateClientBindingId(); |
| 186 | const nav = navigator; |
| 187 | |
| 188 | // Keep this stable: avoid viewport/screen metrics that can change when |
| 189 | // devtools opens, orientation changes, or window state changes. |
| 190 | return [ |
| 191 | binding, |
| 192 | nav.userAgent || '', |
| 193 | nav.language, |
| 194 | nav.platform || nav.userAgentData?.platform || '', |
| 195 | Intl.DateTimeFormat().resolvedOptions().timeZone, |
| 196 | ].join('|'); |
| 197 | } |
| 198 | |
| 199 | function randomIdHex (bytes = 16) |
| 200 | { |
| 201 | const arr = new Uint8Array(bytes); |
| 202 | if (window.crypto && typeof window.crypto.getRandomValues === 'function') |
| 203 | { |
| 204 | window.crypto.getRandomValues(arr); |
| 205 | } else |
| 206 | { |
| 207 | for (let i = 0; i < arr.length; i++) arr[i] = Math.floor(Math.random() * 256); |
| 208 | } |
| 209 | return Array.from(arr).map(n => n.toString(16).padStart(2, '0')).join(''); |
| 210 | } |
| 211 | |
| 212 | function userVideoPrefsKey () |
| 213 | { |
| 214 | const name = String(STATE.username || 'anonymous').trim().toLowerCase() || 'anonymous'; |
| 215 | return VIDEO_PREFS_KEY_PREFIX + name; |
| 216 | } |
| 217 | |
| 218 | function loadUserVideoPrefs () |
| 219 | { |
| 220 | try |
| 221 | { |
| 222 | const raw = localStorage.getItem(userVideoPrefsKey()); |
| 223 | const parsed = raw ? JSON.parse(raw) : {}; |
| 224 | if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {}; |
| 225 | return parsed; |
| 226 | } catch |
| 227 | { |
| 228 | return {}; |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | function saveUserVideoPrefs (patch) |
| 233 | { |
| 234 | try |
| 235 | { |
| 236 | const current = loadUserVideoPrefs(); |
| 237 | localStorage.setItem(userVideoPrefsKey(), JSON.stringify({ ...current, ...(patch || {}) })); |
| 238 | } catch |
| 239 | { |
| 240 | // Ignore localStorage failures. |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | function applyUserVideoTextTrackPrefs () |
| 245 | { |
| 246 | try |
| 247 | { |
| 248 | // Only override the two requested defaults and leave other settings at Video.js defaults. |
| 249 | localStorage.setItem(VIDEO_TEXT_TRACK_SETTINGS_KEY, VIDEO_TEXT_TRACK_OVERRIDE_SETTINGS_RAW); |
| 250 | } catch |
| 251 | { |
| 252 | // Ignore localStorage failures. |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | function normaliseTrackName (name) |
| 257 | { |
| 258 | return String(name || '').trim().toLowerCase(); |
| 259 | } |
| 260 | |
| 261 | function getTrackName (track) |
| 262 | { |
| 263 | if (!track || typeof track !== 'object') return ''; |
| 264 | const label = String(track.label || '').trim(); |
| 265 | if (label) return label; |
| 266 | const name = String(track.name || '').trim(); |
| 267 | if (name) return name; |
| 268 | const language = String(track.language || '').trim(); |
| 269 | if (language) return language; |
| 270 | const id = String(track.id || '').trim(); |
| 271 | if (id) return id; |
| 272 | return ''; |
| 273 | } |
| 274 | |
| 275 | function trackListToArray (trackList) |
| 276 | { |
| 277 | if (!trackList || typeof trackList.length !== 'number') return []; |
| 278 | const out = []; |
| 279 | for (let i = 0; i < trackList.length; i++) |
| 280 | { |
| 281 | const track = trackList[i] || (typeof trackList.item === 'function' ? trackList.item(i) : null); |
| 282 | if (track) out.push(track); |
| 283 | } |
| 284 | return out; |
| 285 | } |
| 286 | |
| 287 | function subtitleTracksFromPlayer (player) |
| 288 | { |
| 289 | if (!player || typeof player.textTracks !== 'function') return []; |
| 290 | return trackListToArray(player.textTracks()).filter((track) => |
| 291 | { |
| 292 | const kind = String(track.kind || '').toLowerCase(); |
| 293 | return kind === 'subtitles' || kind === 'captions'; |
| 294 | }); |
| 295 | } |
| 296 | |
| 297 | function audioTracksFromPlayer (player) |
| 298 | { |
| 299 | if (!player || typeof player.audioTracks !== 'function') return []; |
| 300 | return trackListToArray(player.audioTracks()); |
| 301 | } |
| 302 | |
| 303 | function applySavedSubtitleTrack (player, savedName) |
| 304 | { |
| 305 | if (typeof savedName !== 'string') return; |
| 306 | const tracks = subtitleTracksFromPlayer(player); |
| 307 | if (!tracks.length) return; |
| 308 | |
| 309 | const wanted = normaliseTrackName(savedName); |
| 310 | if (!wanted) |
| 311 | { |
| 312 | for (const track of tracks) track.mode = 'disabled'; |
| 313 | return; |
| 314 | } |
| 315 | |
| 316 | const match = tracks.find((track) => normaliseTrackName(getTrackName(track)) === wanted); |
| 317 | if (!match) return; |
| 318 | |
| 319 | for (const track of tracks) |
| 320 | { |
| 321 | track.mode = track === match ? 'showing' : 'disabled'; |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | function applySavedAudioTrack (player, savedName) |
| 326 | { |
| 327 | if (typeof savedName !== 'string') return; |
| 328 | const tracks = audioTracksFromPlayer(player); |
| 329 | if (!tracks.length) return; |
| 330 | |
| 331 | const wanted = normaliseTrackName(savedName); |
| 332 | if (!wanted) return; |
| 333 | |
| 334 | const match = tracks.find((track) => normaliseTrackName(getTrackName(track)) === wanted); |
| 335 | if (!match) return; |
| 336 | |
| 337 | for (const track of tracks) |
| 338 | { |
| 339 | track.enabled = track === match; |
| 340 | } |
| 341 | } |
| 342 | |
| 343 | function getSelectedSubtitleTrackName (player) |
| 344 | { |
| 345 | const tracks = subtitleTracksFromPlayer(player); |
| 346 | if (!tracks.length) return null; |
| 347 | const active = tracks.find((track) => String(track.mode || '').toLowerCase() === 'showing'); |
| 348 | return active ? getTrackName(active) : ''; |
| 349 | } |
| 350 | |
| 351 | function getSelectedAudioTrackName (player) |
| 352 | { |
| 353 | const tracks = audioTracksFromPlayer(player); |
| 354 | if (!tracks.length) return null; |
| 355 | const active = tracks.find((track) => !!track.enabled); |
| 356 | return active ? getTrackName(active) : ''; |
| 357 | } |
| 358 | |
| 359 | function bindUserVideoTrackPrefs (player, prefs) |
| 360 | { |
| 361 | const applySavedTracks = () => |
| 362 | { |
| 363 | applySavedSubtitleTrack(player, prefs.subtitleTrackName); |
| 364 | applySavedAudioTrack(player, prefs.audioTrackName); |
| 365 | }; |
| 366 | |
| 367 | const captureSelectedTracks = () => |
| 368 | { |
| 369 | const subtitleTrackName = getSelectedSubtitleTrackName(player); |
| 370 | const audioTrackName = getSelectedAudioTrackName(player); |
| 371 | const patch = {}; |
| 372 | |
| 373 | if (subtitleTrackName !== null) patch.subtitleTrackName = subtitleTrackName; |
| 374 | if (audioTrackName !== null) patch.audioTrackName = audioTrackName; |
| 375 | |
| 376 | if (Object.keys(patch).length) saveUserVideoPrefs(patch); |
| 377 | }; |
| 378 | |
| 379 | const textTrackList = typeof player.textTracks === 'function' ? player.textTracks() : null; |
| 380 | const audioTrackList = typeof player.audioTracks === 'function' ? player.audioTracks() : null; |
| 381 | const onTrackListChange = () => captureSelectedTracks(); |
| 382 | |
| 383 | if (textTrackList && typeof textTrackList.addEventListener === 'function') |
| 384 | { |
| 385 | textTrackList.addEventListener('change', onTrackListChange); |
| 386 | } |
| 387 | |
| 388 | if (audioTrackList && typeof audioTrackList.addEventListener === 'function') |
| 389 | { |
| 390 | audioTrackList.addEventListener('change', onTrackListChange); |
| 391 | } |
| 392 | |
| 393 | return { |
| 394 | applySavedTracks, |
| 395 | captureSelectedTracks, |
| 396 | detach: () => |
| 397 | { |
| 398 | if (textTrackList && typeof textTrackList.removeEventListener === 'function') |
| 399 | { |
| 400 | textTrackList.removeEventListener('change', onTrackListChange); |
| 401 | } |
| 402 | if (audioTrackList && typeof audioTrackList.removeEventListener === 'function') |
| 403 | { |
| 404 | audioTrackList.removeEventListener('change', onTrackListChange); |
| 405 | } |
| 406 | }, |
| 407 | }; |
| 408 | } |
| 409 | |
| 410 | function normaliseVideoDuration (player, durationSeconds) |
| 411 | { |
| 412 | const duration = Number(durationSeconds); |
| 413 | if (!player || !Number.isFinite(duration) || duration <= 0) return; |
| 414 | |
| 415 | let originalDuration = null; |
| 416 | let durationWasChanged = false; |
| 417 | try |
| 418 | { |
| 419 | originalDuration = typeof player.duration === 'function' ? player.duration.bind(player) : null; |
| 420 | installDurationFallback(player, originalDuration, duration); |
| 421 | if (player.__filemanagerDurationApplied) return; |
| 422 | |
| 423 | const current = originalDuration ? Number(originalDuration()) : NaN; |
| 424 | const withinTolerance = Number.isFinite(current) && current >= duration * 0.95; |
| 425 | console.log(`Current duration: ${formatDurationForDebug(current)}, Target time: ${formatDurationForDebug(duration)}, within 95%? ${withinTolerance ? 'yes' : 'no'}`); |
| 426 | if (withinTolerance) |
| 427 | { |
| 428 | player.__filemanagerDurationApplied = true; |
| 429 | return; |
| 430 | } |
| 431 | |
| 432 | if (originalDuration) |
| 433 | { |
| 434 | durationWasChanged = true; |
| 435 | originalDuration(duration); |
| 436 | } |
| 437 | } catch |
| 438 | { |
| 439 | // Ignore players that do not support setting duration. |
| 440 | } |
| 441 | |
| 442 | try |
| 443 | { |
| 444 | const updated = originalDuration ? Number(originalDuration()) : NaN; |
| 445 | if (Number.isFinite(updated) && updated >= duration * 0.95) |
| 446 | { |
| 447 | player.__filemanagerDurationApplied = true; |
| 448 | if (durationWasChanged && typeof player.trigger === 'function') player.trigger('durationchange'); |
| 449 | return; |
| 450 | } |
| 451 | |
| 452 | player.__filemanagerDurationApplied = true; |
| 453 | if (typeof player.trigger === 'function') player.trigger('durationchange'); |
| 454 | } catch |
| 455 | { |
| 456 | // Ignore duration fallback failures. |
| 457 | } |
| 458 | } |
| 459 | |
| 460 | function installDurationFallback (player, originalDuration, duration) |
| 461 | { |
| 462 | if (!player || !originalDuration || player.__filemanagerDurationFallback) return; |
| 463 | |
| 464 | player.__filemanagerDurationFallback = true; |
| 465 | player.duration = function durationWithFallback (...args) |
| 466 | { |
| 467 | if (args.length) return originalDuration(...args); |
| 468 | const current = Number(originalDuration()); |
| 469 | return Number.isFinite(current) && current >= duration * 0.95 ? current : duration; |
| 470 | }; |
| 471 | } |
| 472 | |
| 473 | function formatDurationForDebug (seconds) |
| 474 | { |
| 475 | const value = Number(seconds); |
| 476 | if (!Number.isFinite(value) || value < 0) return 'unknown'; |
| 477 | |
| 478 | const totalSeconds = Math.floor(value); |
| 479 | const hh = String(Math.floor(totalSeconds / 3600)).padStart(2, '0'); |
| 480 | const mm = String(Math.floor((totalSeconds % 3600) / 60)).padStart(2, '0'); |
| 481 | const ss = String(totalSeconds % 60).padStart(2, '0'); |
| 482 | return `${hh}:${mm}:${ss}`; |
| 483 | } |
| 484 | |
| 485 | function ensureVideoPlaybackUi (player, durationSeconds) |
| 486 | { |
| 487 | if (!player || typeof player.on !== 'function') return; |
| 488 | |
| 489 | const forceVodUi = () => |
| 490 | { |
| 491 | normaliseVideoDuration(player, durationSeconds); |
| 492 | |
| 493 | try |
| 494 | { |
| 495 | if (player.liveTracker && typeof player.liveTracker.stopTracking === 'function') |
| 496 | { |
| 497 | player.liveTracker.stopTracking(); |
| 498 | } |
| 499 | } catch |
| 500 | { |
| 501 | // Ignore live tracker availability issues. |
| 502 | } |
| 503 | |
| 504 | try |
| 505 | { |
| 506 | if (typeof player.removeClass === 'function') |
| 507 | { |
| 508 | player.removeClass('vjs-live'); |
| 509 | } |
| 510 | } catch |
| 511 | { |
| 512 | // Ignore class update failures. |
| 513 | } |
| 514 | |
| 515 | try |
| 516 | { |
| 517 | const display = player.el() && player.el().querySelector('.vjs-live-display'); |
| 518 | if (display) display.style.display = 'none'; |
| 519 | } catch |
| 520 | { |
| 521 | // Ignore missing DOM. |
| 522 | } |
| 523 | }; |
| 524 | |
| 525 | player.ready(forceVodUi); |
| 526 | player.on('loadedmetadata', forceVodUi); |
| 527 | player.on('durationchange', forceVodUi); |
| 528 | player.on('loadedplaylist', forceVodUi); |
| 529 | } |
| 530 | |
| 531 | async function reportWatchProgress (filePath, progress) |
| 532 | { |
| 533 | if (!filePath || !Number.isFinite(progress)) return; |
| 534 | await api('POST', '/files/watch-progress', { |
| 535 | filePath, |
| 536 | progress, |
| 537 | }).catch(() => null); |
| 538 | } |
| 539 | |
| 540 | function getOrCreateClientBindingId () |
| 541 | { |
| 542 | if (STATE.clientBindingId) return STATE.clientBindingId; |
| 543 | |
| 544 | try |
| 545 | { |
| 546 | const existing = localStorage.getItem(CLIENT_BINDING_KEY); |
| 547 | if (existing && typeof existing === 'string') |
| 548 | { |
| 549 | STATE.clientBindingId = existing; |
| 550 | return existing; |
| 551 | } |
| 552 | } catch |
| 553 | { |
| 554 | // Ignore storage read errors. |
| 555 | } |
| 556 | |
| 557 | const created = randomIdHex(16); |
| 558 | STATE.clientBindingId = created; |
| 559 | |
| 560 | try |
| 561 | { |
| 562 | localStorage.setItem(CLIENT_BINDING_KEY, created); |
| 563 | } catch |
| 564 | { |
| 565 | // Ignore storage write errors; in-memory fallback still keeps this stable |
| 566 | // for the current page session. |
| 567 | } |
| 568 | |
| 569 | return created; |
| 570 | } |
| 571 | |
| 572 | function formatBytes (bytes) |
| 573 | { |
| 574 | if (bytes == null) return '—'; |
| 575 | if (bytes < 1024) return bytes + ' B'; |
| 576 | if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB'; |
| 577 | if (bytes < 1073741824) return (bytes / 1048576).toFixed(1) + ' MB'; |
| 578 | return (bytes / 1073741824).toFixed(2) + ' GB'; |
| 579 | } |
| 580 | |
| 581 | function extOf (name) |
| 582 | { |
| 583 | const i = name.lastIndexOf('.'); |
| 584 | return i >= 0 ? name.slice(i + 1).toLowerCase() : ''; |
| 585 | } |
| 586 | |
| 587 | function getPathSep (basePath) |
| 588 | { |
| 589 | return basePath && basePath.includes('\\') ? '\\' : '/'; |
| 590 | } |
| 591 | |
| 592 | function joinServerPath (basePath, segment) |
| 593 | { |
| 594 | const sep = getPathSep(basePath); |
| 595 | const base = String(basePath || '').replace(/[\\/]+$/, ''); |
| 596 | return base + sep + segment; |
| 597 | } |
| 598 | |
| 599 | function samePath (a, b) |
| 600 | { |
| 601 | if (!a || !b) return false; |
| 602 | return String(a).toLowerCase() === String(b).toLowerCase(); |
| 603 | } |
| 604 | |
| 605 | function pathInside (child, root) |
| 606 | { |
| 607 | if (!child || !root) return false; |
| 608 | if (samePath(child, root)) return true; |
| 609 | const sep = getPathSep(root); |
| 610 | return String(child).toLowerCase().startsWith((String(root) + sep).toLowerCase()); |
| 611 | } |
| 612 | |
| 613 | function splitNameExt (name) |
| 614 | { |
| 615 | const dot = String(name || '').lastIndexOf('.'); |
| 616 | if (dot <= 0) return { stem: String(name || ''), ext: '' }; |
| 617 | return { |
| 618 | stem: String(name).slice(0, dot), |
| 619 | ext: String(name).slice(dot), |
| 620 | }; |
| 621 | } |
| 622 | |
| 623 | function nextAvailableName (requestedName, existingNames) |
| 624 | { |
| 625 | const set = existingNames instanceof Set ? existingNames : new Set(existingNames || []); |
| 626 | if (!set.has(requestedName)) return requestedName; |
| 627 | |
| 628 | const { stem, ext } = splitNameExt(requestedName); |
| 629 | let n = 1; |
| 630 | while (n <= 10000) |
| 631 | { |
| 632 | const candidate = `${stem || 'file'} (${n})${ext}`; |
| 633 | if (!set.has(candidate)) return candidate; |
| 634 | n++; |
| 635 | } |
| 636 | |
| 637 | return requestedName; |
| 638 | } |
| 639 | |
| 640 | async function listDirNameSet (dir) |
| 641 | { |
| 642 | const data = await api('GET', `/files/list?dir=${encodeURIComponent(dir)}`); |
| 643 | const names = new Set(); |
| 644 | for (const it of ((data && data.items) || [])) names.add(it.name); |
| 645 | return names; |
| 646 | } |
| 647 | |
| 648 | function cloneFileWithName (file, newName) |
| 649 | { |
| 650 | return new File([file], newName, { |
| 651 | type: file.type, |
| 652 | lastModified: file.lastModified, |
| 653 | }); |
| 654 | } |
| 655 | |
| 656 | function saveSessionState () |
| 657 | { |
| 658 | if (!STATE.token) return; |
| 659 | const now = Date.now(); |
| 660 | STATE.lastOperationAt = now; |
| 661 | const payload = { |
| 662 | token: STATE.token, |
| 663 | dir: STATE.currentDir || null, |
| 664 | rootPath: STATE.currentRoot ? STATE.currentRoot.path : null, |
| 665 | lastOperationAt: STATE.lastOperationAt, |
| 666 | }; |
| 667 | try |
| 668 | { |
| 669 | localStorage.setItem(SESSION_KEY, JSON.stringify(payload)); |
| 670 | } catch |
| 671 | { |
| 672 | // Ignore storage errors (private mode/full quota). |
| 673 | } |
| 674 | } |
| 675 | |
| 676 | function loadSessionState () |
| 677 | { |
| 678 | try |
| 679 | { |
| 680 | const raw = localStorage.getItem(SESSION_KEY); |
| 681 | if (!raw) return null; |
| 682 | const parsed = JSON.parse(raw); |
| 683 | if (!parsed || typeof parsed.token !== 'string') return null; |
| 684 | if (!Number.isFinite(parsed.lastOperationAt)) return null; |
| 685 | |
| 686 | if (Date.now() - parsed.lastOperationAt > SESSION_IDLE_TIMEOUT_MS) |
| 687 | { |
| 688 | clearSessionState(); |
| 689 | return null; |
| 690 | } |
| 691 | |
| 692 | return parsed; |
| 693 | } catch |
| 694 | { |
| 695 | return null; |
| 696 | } |
| 697 | } |
| 698 | |
| 699 | function clearSessionState () |
| 700 | { |
| 701 | try { localStorage.removeItem(SESSION_KEY); } catch { /* ignore */ } |
| 702 | } |
| 703 | |
| 704 | // ─────────────────────────────────────────────────────────────────────────── |
| 705 | // API |
| 706 | // ─────────────────────────────────────────────────────────────────────────── |
| 707 | |
| 708 | async function api (method, path, body, opts = {}) |
| 709 | { |
| 710 | const headers = { 'Content-Type': 'application/json' }; |
| 711 | const noAutoLogout = !!opts.noAutoLogout; |
| 712 | if (STATE.token) |
| 713 | { |
| 714 | headers['Authorization'] = 'Bearer ' + STATE.token; |
| 715 | try |
| 716 | { |
| 717 | const fp = getFingerprint(); |
| 718 | if (fp) headers['X-Fp'] = fp; |
| 719 | } catch |
| 720 | { |
| 721 | // Continue without a fingerprint header in constrained test/runtime contexts. |
| 722 | } |
| 723 | } |
| 724 | const fetchOpts = { ...opts }; |
| 725 | delete fetchOpts.noAutoLogout; |
| 726 | const res = await fetch('/api' + path, { |
| 727 | method, |
| 728 | headers, |
| 729 | body: body != null ? JSON.stringify(body) : undefined, |
| 730 | ...fetchOpts, |
| 731 | }); |
| 732 | if (!res.ok) |
| 733 | { |
| 734 | const j = await res.json().catch(() => ({})); |
| 735 | // Session-expired → force re-login |
| 736 | if (res.status === 401) |
| 737 | { |
| 738 | if (!noAutoLogout) logout(); |
| 739 | return null; |
| 740 | } |
| 741 | throw new Error(j.error || res.statusText); |
| 742 | } |
| 743 | if (STATE.token && !path.startsWith('/auth/server-key') && !path.startsWith('/auth/setup-needed')) |
| 744 | { |
| 745 | saveSessionState(); |
| 746 | } |
| 747 | return res.json(); |
| 748 | } |
| 749 | |
| 750 | // ─────────────────────────────────────────────────────────────────────────── |
| 751 | // TOAST |
| 752 | // ─────────────────────────────────────────────────────────────────────────── |
| 753 | |
| 754 | function toast (msg, type = '') |
| 755 | { |
| 756 | const el = document.createElement('div'); |
| 757 | el.className = 'toast-msg' + (type ? ' ' + type : ''); |
| 758 | el.textContent = msg; |
| 759 | document.getElementById('toast').appendChild(el); |
| 760 | setTimeout(() => el.remove(), 3500); |
| 761 | } |
| 762 | |
| 763 | // ─────────────────────────────────────────────────────────────────────────── |
| 764 | // DIALOG MODALS — centralised replacements for alert / confirm / prompt |
| 765 | // ─────────────────────────────────────────────────────────────────────────── |
| 766 | |
| 767 | /** |
| 768 | * Show a confirmation dialog. |
| 769 | * @param {string} title |
| 770 | * @param {string} message |
| 771 | * @returns {Promise<boolean>} true = OK, false = Cancel |
| 772 | */ |
| 773 | function showConfirm (title, message, { html = false, okLabel = null } = {}) |
| 774 | { |
| 775 | return new Promise((resolve) => |
| 776 | { |
| 777 | const overlay = document.getElementById('confirm-modal'); |
| 778 | document.getElementById('confirm-modal-title').textContent = title; |
| 779 | const msgEl = document.getElementById('confirm-modal-message'); |
| 780 | if (html) msgEl.innerHTML = message; |
| 781 | else msgEl.textContent = message; |
| 782 | overlay.classList.remove('hidden'); |
| 783 | |
| 784 | const ok = document.getElementById('confirm-modal-ok'); |
| 785 | const prevOkLabel = ok.textContent; |
| 786 | if (okLabel != null) ok.textContent = okLabel; |
| 787 | |
| 788 | const cancel = document.getElementById('confirm-modal-cancel'); |
| 789 | |
| 790 | function finish (result) |
| 791 | { |
| 792 | overlay.classList.add('hidden'); |
| 793 | ok.textContent = prevOkLabel; |
| 794 | ok.removeEventListener('click', onOk); |
| 795 | cancel.removeEventListener('click', onCancel); |
| 796 | resolve(result); |
| 797 | } |
| 798 | function onOk () { finish(true); } |
| 799 | function onCancel () { finish(false); } |
| 800 | |
| 801 | ok.addEventListener('click', onOk); |
| 802 | cancel.addEventListener('click', onCancel); |
| 803 | ok.focus(); |
| 804 | }); |
| 805 | } |
| 806 | |
| 807 | function escHtml (s) |
| 808 | { |
| 809 | return String(s || '') |
| 810 | .replace(/&/g, '&') |
| 811 | .replace(/</g, '<') |
| 812 | .replace(/>/g, '>') |
| 813 | .replace(/"/g, '"'); |
| 814 | } |
| 815 | |
| 816 | /** |
| 817 | * Show a text-input dialog. |
| 818 | * @param {string} title |
| 819 | * @param {string} [message] — optional helper text shown above the input |
| 820 | * @param {string} [defaultValue] — pre-filled value |
| 821 | * @returns {Promise<string|null>} string = submitted value, null = cancelled |
| 822 | */ |
| 823 | function showPrompt (title, message = '', defaultValue = '') |
| 824 | { |
| 825 | return new Promise((resolve) => |
| 826 | { |
| 827 | const overlay = document.getElementById('prompt-modal'); |
| 828 | const msgEl = document.getElementById('prompt-modal-message'); |
| 829 | const input = document.getElementById('prompt-modal-input'); |
| 830 | const errorEl = document.getElementById('prompt-modal-error'); |
| 831 | const form = document.getElementById('prompt-modal-form'); |
| 832 | const cancel = document.getElementById('prompt-modal-cancel'); |
| 833 | |
| 834 | document.getElementById('prompt-modal-title').textContent = title; |
| 835 | msgEl.textContent = message; |
| 836 | msgEl.classList.toggle('hidden', !message); |
| 837 | input.value = defaultValue; |
| 838 | errorEl.classList.add('hidden'); |
| 839 | overlay.classList.remove('hidden'); |
| 840 | input.focus(); |
| 841 | input.select(); |
| 842 | |
| 843 | function finish (result) |
| 844 | { |
| 845 | overlay.classList.add('hidden'); |
| 846 | form.removeEventListener('submit', onSubmit); |
| 847 | cancel.removeEventListener('click', onCancel); |
| 848 | resolve(result); |
| 849 | } |
| 850 | function onSubmit (e) |
| 851 | { |
| 852 | e.preventDefault(); |
| 853 | finish(input.value); |
| 854 | } |
| 855 | function onCancel () { finish(null); } |
| 856 | |
| 857 | form.addEventListener('submit', onSubmit); |
| 858 | cancel.addEventListener('click', onCancel); |
| 859 | }); |
| 860 | } |
| 861 | |
| 862 | /** |
| 863 | * Show an overwrite-decision dialog for a single file conflict. |
| 864 | * @param {string} filename |
| 865 | * @returns {Promise<'yes'|'no'|'all'|'none'>} |
| 866 | */ |
| 867 | function showOverwrite (filename) |
| 868 | { |
| 869 | return new Promise((resolve) => |
| 870 | { |
| 871 | const overlay = document.getElementById('overwrite-modal'); |
| 872 | document.getElementById('overwrite-modal-filename').textContent = filename; |
| 873 | overlay.classList.remove('hidden'); |
| 874 | |
| 875 | const btnYes = document.getElementById('overwrite-modal-yes'); |
| 876 | const btnNo = document.getElementById('overwrite-modal-no'); |
| 877 | const btnAll = document.getElementById('overwrite-modal-all'); |
| 878 | const btnSkipAll = document.getElementById('overwrite-modal-skip-all'); |
| 879 | |
| 880 | function finish (result) |
| 881 | { |
| 882 | overlay.classList.add('hidden'); |
| 883 | btnYes.removeEventListener('click', onYes); |
| 884 | btnNo.removeEventListener('click', onNo); |
| 885 | btnAll.removeEventListener('click', onAll); |
| 886 | btnSkipAll.removeEventListener('click', onSkipAll); |
| 887 | resolve(result); |
| 888 | } |
| 889 | function onYes () { finish('yes'); } |
| 890 | function onNo () { finish('no'); } |
| 891 | function onAll () { finish('all'); } |
| 892 | function onSkipAll () { finish('none'); } |
| 893 | |
| 894 | btnYes.addEventListener('click', onYes); |
| 895 | btnNo.addEventListener('click', onNo); |
| 896 | btnAll.addEventListener('click', onAll); |
| 897 | btnSkipAll.addEventListener('click', onSkipAll); |
| 898 | btnNo.focus(); |
| 899 | }); |
| 900 | } |
| 901 | |
| 902 | /** |
| 903 | * Show single-file conflict options. |
| 904 | * @param {string} filename |
| 905 | * @param {string} renameTo |
| 906 | * @param {string} mode - upload|move |
| 907 | * @returns {Promise<'overwrite'|'rename'|'cancel'>} |
| 908 | */ |
| 909 | function showFileConflictChoice (filename, renameTo, mode = 'upload') |
| 910 | { |
| 911 | return new Promise((resolve) => |
| 912 | { |
| 913 | const overlay = document.getElementById('file-conflict-modal'); |
| 914 | const title = document.getElementById('file-conflict-title'); |
| 915 | const fileEl = document.getElementById('file-conflict-filename'); |
| 916 | const renameEl = document.getElementById('file-conflict-rename'); |
| 917 | const btnOverwrite = document.getElementById('file-conflict-overwrite'); |
| 918 | const btnRename = document.getElementById('file-conflict-rename-btn'); |
| 919 | const btnCancel = document.getElementById('file-conflict-cancel'); |
| 920 | |
| 921 | title.textContent = mode === 'move' ? 'Move file' : 'Upload file'; |
| 922 | fileEl.textContent = filename; |
| 923 | renameEl.textContent = renameTo; |
| 924 | btnRename.textContent = `Rename (${renameTo})`; |
| 925 | |
| 926 | overlay.classList.remove('hidden'); |
| 927 | |
| 928 | function finish (result) |
| 929 | { |
| 930 | overlay.classList.add('hidden'); |
| 931 | btnOverwrite.removeEventListener('click', onOverwrite); |
| 932 | btnRename.removeEventListener('click', onRename); |
| 933 | btnCancel.removeEventListener('click', onCancel); |
| 934 | resolve(result); |
| 935 | } |
| 936 | |
| 937 | function onOverwrite () { finish('overwrite'); } |
| 938 | function onRename () { finish('rename'); } |
| 939 | function onCancel () { finish('cancel'); } |
| 940 | |
| 941 | btnOverwrite.addEventListener('click', onOverwrite); |
| 942 | btnRename.addEventListener('click', onRename); |
| 943 | btnCancel.addEventListener('click', onCancel); |
| 944 | btnCancel.focus(); |
| 945 | }); |
| 946 | } |
| 947 | |
| 948 | // ─────────────────────────────────────────────────────────────────────────── |
| 949 | // SHARE MODAL |
| 950 | // ─────────────────────────────────────────────────────────────────────────── |
| 951 | |
| 952 | async function openShareModal (item) |
| 953 | { |
| 954 | const overlay = document.getElementById('share-modal'); |
| 955 | const urlInput = document.getElementById('share-url-input'); |
| 956 | const copyBtn = document.getElementById('share-copy-btn'); |
| 957 | const okBtn = document.getElementById('share-modal-ok'); |
| 958 | const closeBtn = document.getElementById('share-modal-close'); |
| 959 | const msgEl = document.getElementById('share-modal-msg'); |
| 960 | |
| 961 | urlInput.value = 'Creating link...'; |
| 962 | copyBtn.disabled = true; |
| 963 | msgEl.textContent = 'This link is valid for 24 hours.'; |
| 964 | overlay.classList.remove('hidden'); |
| 965 | |
| 966 | let data; |
| 967 | try |
| 968 | { |
| 969 | data = await api('POST', '/share/create', { filePath: item.path }); |
| 970 | } catch (err) |
| 971 | { |
| 972 | msgEl.textContent = 'Error: ' + (err.message || 'Could not create link.'); |
| 973 | urlInput.value = ''; |
| 974 | return; |
| 975 | } |
| 976 | |
| 977 | if (!data || !data.token) |
| 978 | { |
| 979 | msgEl.textContent = 'Unknown error while creating link.'; |
| 980 | urlInput.value = ''; |
| 981 | return; |
| 982 | } |
| 983 | |
| 984 | const shareUrl = `${location.origin}/share/${data.token}`; |
| 985 | urlInput.value = shareUrl; |
| 986 | copyBtn.disabled = false; |
| 987 | |
| 988 | function close () |
| 989 | { |
| 990 | overlay.classList.add('hidden'); |
| 991 | okBtn.removeEventListener('click', close); |
| 992 | closeBtn.removeEventListener('click', close); |
| 993 | copyBtn.removeEventListener('click', onCopy); |
| 994 | } |
| 995 | |
| 996 | function onCopy () |
| 997 | { |
| 998 | navigator.clipboard.writeText(shareUrl).then(() => |
| 999 | { |
| 1000 | const orig = copyBtn.textContent; |
| 1001 | copyBtn.textContent = 'Copied!'; |
| 1002 | setTimeout(() => { copyBtn.textContent = orig; }, 1500); |
| 1003 | }).catch(() => |
| 1004 | { |
| 1005 | // Fallback: select the text |
| 1006 | urlInput.select(); |
| 1007 | }); |
| 1008 | } |
| 1009 | |
| 1010 | okBtn.addEventListener('click', close); |
| 1011 | closeBtn.addEventListener('click', close); |
| 1012 | copyBtn.addEventListener('click', onCopy); |
| 1013 | okBtn.focus(); |
| 1014 | } |
| 1015 | |
| 1016 | // ─────────────────────────────────────────────────────────────────────────── |
| 1017 | // AUTH FLOW |
| 1018 | // ─────────────────────────────────────────────────────────────────────────── |
| 1019 | |
| 1020 | function showAuthOverlay (setupMode = false) |
| 1021 | { |
| 1022 | if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return; |
| 1023 | document.getElementById('app').classList.add('hidden'); |
| 1024 | const overlay = document.getElementById('auth-overlay'); |
| 1025 | const usernameInput = document.getElementById('auth-username'); |
| 1026 | const passwordInput = document.getElementById('auth-password'); |
| 1027 | overlay.classList.remove('hidden'); |
| 1028 | document.getElementById('auth-title').textContent = setupMode ? 'Create Admin Account' : 'Sign In'; |
| 1029 | document.getElementById('auth-subtitle').classList.toggle('hidden', !setupMode); |
| 1030 | const submitBtn = document.getElementById('auth-submit'); |
| 1031 | submitBtn.disabled = false; |
| 1032 | submitBtn.textContent = setupMode ? 'Create Account' : 'Sign In'; |
| 1033 | document.getElementById('auth-error').classList.add('hidden'); |
| 1034 | usernameInput.value = ''; |
| 1035 | passwordInput.value = ''; |
| 1036 | usernameInput.autocomplete = 'username'; |
| 1037 | passwordInput.autocomplete = setupMode ? 'new-password' : 'current-password'; |
| 1038 | usernameInput.focus(); |
| 1039 | document.getElementById('auth-form').dataset.mode = setupMode ? 'setup' : 'login'; |
| 1040 | } |
| 1041 | |
| 1042 | function showApp () |
| 1043 | { |
| 1044 | if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return; |
| 1045 | document.getElementById('auth-overlay').classList.add('hidden'); |
| 1046 | document.getElementById('app').classList.remove('hidden'); |
| 1047 | if (isMobileViewport()) |
| 1048 | { |
| 1049 | hideSidebarPanel(); |
| 1050 | } else |
| 1051 | { |
| 1052 | openFolderSidebar(); |
| 1053 | } |
| 1054 | document.getElementById('btn-admin').classList.toggle('hidden', !STATE.isAdmin); |
| 1055 | startAutoRefresh(); |
| 1056 | } |
| 1057 | |
| 1058 | async function initAuth () |
| 1059 | { |
| 1060 | // Generate a fresh key pair in the background; login falls back gracefully |
| 1061 | // while this is still in progress. |
| 1062 | generateClientKeyPair().catch(() => |
| 1063 | { |
| 1064 | toast('Secure crypto unavailable in this browser context; using compatibility login mode.', 'err'); |
| 1065 | }); |
| 1066 | |
| 1067 | // Fetch server public key |
| 1068 | const { publicKey } = await api('GET', '/auth/server-key').catch(() => ({ publicKey: null })); |
| 1069 | if (publicKey) STATE.serverPublicKeyJwk = publicKey; |
| 1070 | if (!publicKey && hasWebCrypto()) { toast('Could not reach server.', 'err'); return; } |
| 1071 | STATE.serverPublicKeyJwk = publicKey; |
| 1072 | |
| 1073 | // Check whether first-run setup is needed |
| 1074 | const { needed } = await api('GET', '/auth/setup-needed').catch(() => ({ needed: false })); |
| 1075 | |
| 1076 | if (!needed) |
| 1077 | { |
| 1078 | const saved = loadSessionState(); |
| 1079 | if (saved && saved.token) |
| 1080 | { |
| 1081 | STATE.token = saved.token; |
| 1082 | STATE.restoreDir = saved.dir || null; |
| 1083 | STATE.restoreRootPath = saved.rootPath || null; |
| 1084 | STATE.lastOperationAt = saved.lastOperationAt; |
| 1085 | |
| 1086 | const me = await api('GET', '/auth/me', null, { noAutoLogout: true }).catch(() => null); |
| 1087 | if (me) |
| 1088 | { |
| 1089 | STATE.username = me.username; |
| 1090 | STATE.isAdmin = me.isAdmin; |
| 1091 | STATE.permissions = me.permissions; |
| 1092 | showApp(); |
| 1093 | await loadRoots({ |
| 1094 | preferredDir: STATE.restoreDir, |
| 1095 | preferredRootPath: STATE.restoreRootPath, |
| 1096 | }); |
| 1097 | return; |
| 1098 | } |
| 1099 | |
| 1100 | STATE.token = null; |
| 1101 | clearSessionState(); |
| 1102 | } |
| 1103 | } |
| 1104 | |
| 1105 | showAuthOverlay(needed); |
| 1106 | } |
| 1107 | |
| 1108 | async function doLogin (username, password, isSetup) |
| 1109 | { |
| 1110 | const encrypted = await hybridEncryptForServer({ username, password }); |
| 1111 | const endpoint = isSetup ? '/auth/setup' : '/auth/login'; |
| 1112 | |
| 1113 | let data; |
| 1114 | try |
| 1115 | { |
| 1116 | data = await api('POST', endpoint, { |
| 1117 | encrypted, |
| 1118 | clientPublicKey: STATE.clientPublicKeyJwk, |
| 1119 | fingerprint: getFingerprint(), |
| 1120 | }); |
| 1121 | } catch (err) |
| 1122 | { |
| 1123 | return err.message; |
| 1124 | } |
| 1125 | |
| 1126 | if (!data) return 'Login failed.'; |
| 1127 | |
| 1128 | // Decrypt the token sent back by the server |
| 1129 | const token = await hybridDecryptFromServer(data.encrypted || data); |
| 1130 | if (!token) return 'Login failed.'; |
| 1131 | STATE.token = token; |
| 1132 | |
| 1133 | // Load user info |
| 1134 | const me = await api('GET', '/auth/me'); |
| 1135 | if (!me) return 'Session error.'; |
| 1136 | |
| 1137 | STATE.username = me.username; |
| 1138 | STATE.isAdmin = me.isAdmin; |
| 1139 | STATE.permissions = me.permissions; |
| 1140 | |
| 1141 | saveSessionState(); |
| 1142 | showApp(); |
| 1143 | await loadRoots(); |
| 1144 | return null; // no error |
| 1145 | } |
| 1146 | |
| 1147 | function logout () |
| 1148 | { |
| 1149 | void performLogout(); |
| 1150 | } |
| 1151 | |
| 1152 | async function performLogout () |
| 1153 | { |
| 1154 | const tokenAtStart = STATE.token; |
| 1155 | stopAutoRefresh(); |
| 1156 | |
| 1157 | if (tokenAtStart) |
| 1158 | { |
| 1159 | try |
| 1160 | { |
| 1161 | await api('POST', '/auth/logout', {}, { noAutoLogout: true }); |
| 1162 | } catch |
| 1163 | { |
| 1164 | // Ignore network errors while logging out locally. |
| 1165 | } |
| 1166 | } |
| 1167 | |
| 1168 | STATE.token = null; |
| 1169 | STATE.username = null; |
| 1170 | STATE.isAdmin = false; |
| 1171 | STATE.permissions = {}; |
| 1172 | STATE.currentDir = null; |
| 1173 | STATE.currentRoot = null; |
| 1174 | STATE.items = []; |
| 1175 | STATE.restoreDir = null; |
| 1176 | STATE.restoreRootPath = null; |
| 1177 | STATE.lastOperationAt = null; |
| 1178 | clearSessionState(); |
| 1179 | closePreview({ force: true }); |
| 1180 | closeSidebar(); |
| 1181 | await initAuth(); |
| 1182 | } |
| 1183 | |
| 1184 | // ─────────────────────────────────────────────────────────────────────────── |
| 1185 | // NAVIGATION |
| 1186 | // ─────────────────────────────────────────────────────────────────────────── |
| 1187 | |
| 1188 | async function loadRoots (opts = {}) |
| 1189 | { |
| 1190 | const data = await api('GET', '/files/roots'); |
| 1191 | if (!data) return; |
| 1192 | STATE.roots = data.roots; |
| 1193 | |
| 1194 | const preferredDir = opts.preferredDir || null; |
| 1195 | const preferredRootPath = opts.preferredRootPath || null; |
| 1196 | |
| 1197 | if (preferredDir && preferredRootPath) |
| 1198 | { |
| 1199 | const preferredRoot = STATE.roots.find(r => samePath(r.path, preferredRootPath)); |
| 1200 | if (preferredRoot && pathInside(preferredDir, preferredRoot.path)) |
| 1201 | { |
| 1202 | try |
| 1203 | { |
| 1204 | await navigateTo(preferredDir, preferredRoot, { keepSidebar: true }); |
| 1205 | return; |
| 1206 | } catch |
| 1207 | { |
| 1208 | // Fall back to default root behavior. |
| 1209 | } |
| 1210 | } |
| 1211 | } |
| 1212 | |
| 1213 | if (STATE.roots.length === 1) |
| 1214 | { |
| 1215 | // Single root → open it directly |
| 1216 | await navigateTo(STATE.roots[0].path, STATE.roots[0]); |
| 1217 | } else |
| 1218 | { |
| 1219 | renderRootsView(); |
| 1220 | } |
| 1221 | } |
| 1222 | |
| 1223 | function renderRootsView () |
| 1224 | { |
| 1225 | if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return; |
| 1226 | disconnectThumbnailObserver(); |
| 1227 | disconnectFolderIconObserver(); |
| 1228 | revokeThumbnails(); |
| 1229 | |
| 1230 | STATE.currentDir = null; |
| 1231 | STATE.currentRoot = null; |
| 1232 | saveSessionState(); |
| 1233 | renderBreadcrumb(); |
| 1234 | const grid = document.getElementById('file-grid'); |
| 1235 | grid.innerHTML = ''; |
| 1236 | document.getElementById('empty-notice').classList.add('hidden'); |
| 1237 | document.getElementById('folder-stats').classList.add('hidden'); |
| 1238 | closeSidebar(); |
| 1239 | |
| 1240 | for (const root of STATE.roots) |
| 1241 | { |
| 1242 | const el = makeFileItem({ name: root.label, isDir: true, path: root.path, _root: root }); |
| 1243 | grid.appendChild(el); |
| 1244 | } |
| 1245 | |
| 1246 | loadThumbnails(); |
| 1247 | } |
| 1248 | |
| 1249 | async function navigateTo (absPath, root, opts = {}) |
| 1250 | { |
| 1251 | if (root) STATE.currentRoot = root; |
| 1252 | STATE.currentDir = absPath; |
| 1253 | |
| 1254 | const data = await api('GET', `/files/list?dir=${encodeURIComponent(absPath)}`); |
| 1255 | if (!data) return; |
| 1256 | |
| 1257 | STATE.items = data.items; |
| 1258 | saveSessionState(); |
| 1259 | renderBreadcrumb(); |
| 1260 | renderFileGrid(); |
| 1261 | await refreshFolderStats(); |
| 1262 | closeSidebar(); |
| 1263 | } |
| 1264 | |
| 1265 | function renderBreadcrumb () |
| 1266 | { |
| 1267 | if (typeof document === 'undefined') return; |
| 1268 | const nav = document.getElementById('breadcrumb'); |
| 1269 | if (!nav) return; |
| 1270 | nav.innerHTML = ''; |
| 1271 | |
| 1272 | // "Home" crumb |
| 1273 | const home = document.createElement('span'); |
| 1274 | home.className = 'crumb' + (STATE.currentDir == null ? ' active' : ''); |
| 1275 | home.textContent = 'Home'; |
| 1276 | home.addEventListener('click', () => |
| 1277 | { |
| 1278 | if (STATE.roots.length === 1) |
| 1279 | { |
| 1280 | navigateTo(STATE.roots[0].path, STATE.roots[0]); |
| 1281 | } else |
| 1282 | { |
| 1283 | renderRootsView(); |
| 1284 | } |
| 1285 | }); |
| 1286 | nav.appendChild(home); |
| 1287 | |
| 1288 | if (!STATE.currentDir || !STATE.currentRoot) return; |
| 1289 | |
| 1290 | // Build path segments relative to the root |
| 1291 | const rootPath = STATE.currentRoot.path; |
| 1292 | const relative = STATE.currentDir === rootPath |
| 1293 | ? '' |
| 1294 | : STATE.currentDir.replace(rootPath, '').replace(/^[\\/]/, ''); |
| 1295 | |
| 1296 | const parts = [STATE.currentRoot.label, ...relative.split(/[\\/]/).filter(Boolean)]; |
| 1297 | let accumulated = rootPath; |
| 1298 | |
| 1299 | for (let i = 0; i < parts.length; i++) |
| 1300 | { |
| 1301 | const sep = document.createElement('span'); |
| 1302 | sep.className = 'sep'; |
| 1303 | sep.textContent = ' / '; |
| 1304 | nav.appendChild(sep); |
| 1305 | |
| 1306 | const crumb = document.createElement('span'); |
| 1307 | crumb.className = 'crumb' + (i === parts.length - 1 ? ' active' : ''); |
| 1308 | crumb.textContent = parts[i]; |
| 1309 | |
| 1310 | // Capture the path for this crumb |
| 1311 | const capturedPath = i === 0 ? rootPath : accumulated; |
| 1312 | crumb.classList.add('crumb-drop-target'); |
| 1313 | crumb.dataset.path = capturedPath; |
| 1314 | if (i < parts.length - 1) |
| 1315 | { |
| 1316 | crumb.addEventListener('click', () => navigateTo(capturedPath, STATE.currentRoot)); |
| 1317 | } |
| 1318 | |
| 1319 | nav.appendChild(crumb); |
| 1320 | |
| 1321 | // Advance accumulated path (skip for root label) |
| 1322 | if (i > 0) accumulated = accumulated + '/' + parts[i]; |
| 1323 | else if (i === 0 && parts.length > 1) |
| 1324 | { |
| 1325 | // After root label, next crumb should append the next segment |
| 1326 | accumulated = rootPath; |
| 1327 | } |
| 1328 | } |
| 1329 | } |
| 1330 | |
| 1331 | async function refreshFolderStats () |
| 1332 | { |
| 1333 | if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return; |
| 1334 | const el = document.getElementById('folder-stats'); |
| 1335 | if (!STATE.currentDir) |
| 1336 | { |
| 1337 | el.classList.add('hidden'); |
| 1338 | return; |
| 1339 | } |
| 1340 | |
| 1341 | const data = await api('GET', `/files/space?dir=${encodeURIComponent(STATE.currentDir)}`).catch(() => null); |
| 1342 | if (!data) |
| 1343 | { |
| 1344 | el.classList.add('hidden'); |
| 1345 | return; |
| 1346 | } |
| 1347 | |
| 1348 | const used = formatBytes(data.usedBytes); |
| 1349 | const free = data.freeBytes == null ? 'unknown' : formatBytes(data.freeBytes); |
| 1350 | el.textContent = `Folder usage: ${used} | Free on disk: ${free}`; |
| 1351 | el.classList.remove('hidden'); |
| 1352 | } |
| 1353 | |
| 1354 | function itemsSignature (items) |
| 1355 | { |
| 1356 | return JSON.stringify( |
| 1357 | (items || []).map(it => [it.path, it.mtime, it.size, it.isDir]) |
| 1358 | .sort((a, b) => String(a[0]).localeCompare(String(b[0]))), |
| 1359 | ); |
| 1360 | } |
| 1361 | |
| 1362 | async function incrementalRefreshCurrentDir () |
| 1363 | { |
| 1364 | if (STATE.previewExpandState) return; |
| 1365 | if (!STATE.currentDir || STATE.uploadInProgress) return; |
| 1366 | |
| 1367 | const data = await api('GET', `/files/list?dir=${encodeURIComponent(STATE.currentDir)}`).catch(() => null); |
| 1368 | if (!data) return; |
| 1369 | |
| 1370 | const oldSig = itemsSignature(STATE.items); |
| 1371 | const newSig = itemsSignature(data.items); |
| 1372 | if (oldSig !== newSig) |
| 1373 | { |
| 1374 | const selectedPath = STATE.selectedItem ? STATE.selectedItem.path : null; |
| 1375 | STATE.items = data.items; |
| 1376 | renderFileGrid(); |
| 1377 | |
| 1378 | if (selectedPath) |
| 1379 | { |
| 1380 | const match = STATE.items.find(i => i.path === selectedPath); |
| 1381 | if (match) |
| 1382 | { |
| 1383 | const selectedEl = Array.from(document.querySelectorAll('.file-item')) |
| 1384 | .find(el => el.dataset.path === selectedPath); |
| 1385 | if (selectedEl) selectItem(selectedEl, match); |
| 1386 | } else |
| 1387 | { |
| 1388 | closeSidebar(); |
| 1389 | } |
| 1390 | } |
| 1391 | } |
| 1392 | else |
| 1393 | { |
| 1394 | loadThumbnails(); |
| 1395 | } |
| 1396 | |
| 1397 | await refreshFolderStats(); |
| 1398 | } |
| 1399 | |
| 1400 | function startAutoRefresh () |
| 1401 | { |
| 1402 | stopAutoRefresh(); |
| 1403 | STATE.autoRefreshTimer = setInterval(() => |
| 1404 | { |
| 1405 | if (document.hidden) return; |
| 1406 | incrementalRefreshCurrentDir(); |
| 1407 | }, 5000); |
| 1408 | } |
| 1409 | |
| 1410 | function stopAutoRefresh () |
| 1411 | { |
| 1412 | if (STATE.autoRefreshTimer) |
| 1413 | { |
| 1414 | clearInterval(STATE.autoRefreshTimer); |
| 1415 | STATE.autoRefreshTimer = null; |
| 1416 | } |
| 1417 | } |
| 1418 | |
| 1419 | // ─────────────────────────────────────────────────────────────────────────── |
| 1420 | // FILE GRID RENDERING |
| 1421 | // ─────────────────────────────────────────────────────────────────────────── |
| 1422 | |
| 1423 | function renderFileGrid () |
| 1424 | { |
| 1425 | if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return; |
| 1426 | disconnectThumbnailObserver(); |
| 1427 | disconnectFolderIconObserver(); |
| 1428 | revokeThumbnails(); |
| 1429 | const grid = document.getElementById('file-grid'); |
| 1430 | grid.innerHTML = ''; |
| 1431 | const empty = document.getElementById('empty-notice'); |
| 1432 | |
| 1433 | const sorted = [...STATE.items].sort((a, b) => |
| 1434 | { |
| 1435 | if (a.isDir !== b.isDir) return a.isDir ? -1 : 1; |
| 1436 | return a.name.localeCompare(b.name); |
| 1437 | }); |
| 1438 | |
| 1439 | empty.classList.toggle('hidden', sorted.length > 0); |
| 1440 | |
| 1441 | for (const item of sorted) |
| 1442 | { |
| 1443 | grid.appendChild(makeFileItem(item)); |
| 1444 | } |
| 1445 | |
| 1446 | loadThumbnails(); |
| 1447 | } |
| 1448 | |
| 1449 | function makeFileItem (item) |
| 1450 | { |
| 1451 | const el = document.createElement('div'); |
| 1452 | el.className = 'file-item'; |
| 1453 | el.dataset.path = item.path; |
| 1454 | if (item.isDir) el.dataset.isdir = '1'; |
| 1455 | |
| 1456 | const icon = document.createElement('div'); |
| 1457 | icon.className = 'icon'; |
| 1458 | icon.innerHTML = item.isDir ? iconFolder() : iconFile(item.name); |
| 1459 | if (!item.isDir) |
| 1460 | { |
| 1461 | icon.dataset.previewPath = item.path; |
| 1462 | } else |
| 1463 | { |
| 1464 | icon.dataset.folderPath = item.path; |
| 1465 | } |
| 1466 | el.appendChild(icon); |
| 1467 | |
| 1468 | const name = document.createElement('div'); |
| 1469 | name.className = 'name'; |
| 1470 | name.textContent = item.name; |
| 1471 | el.appendChild(name); |
| 1472 | |
| 1473 | if (!item._root) makeDraggable(el, item); |
| 1474 | attachMobileLongPress(el, item); |
| 1475 | |
| 1476 | el.addEventListener('contextmenu', (e) => |
| 1477 | { |
| 1478 | if (!isMobileViewport()) return; |
| 1479 | e.preventDefault(); |
| 1480 | e.stopPropagation(); |
| 1481 | }); |
| 1482 | |
| 1483 | // Single-click: open sidebar |
| 1484 | el.addEventListener('click', (e) => |
| 1485 | { |
| 1486 | e.stopPropagation(); |
| 1487 | if (isMobileViewport()) |
| 1488 | { |
| 1489 | if (el.dataset.longPressTriggered === '1') |
| 1490 | { |
| 1491 | el.dataset.longPressTriggered = '0'; |
| 1492 | return; |
| 1493 | } |
| 1494 | |
| 1495 | if (item.isDir) |
| 1496 | { |
| 1497 | navigateTo(item.path, item._root || STATE.currentRoot); |
| 1498 | } else |
| 1499 | { |
| 1500 | downloadOrView(item, icon.querySelector('svg')); |
| 1501 | } |
| 1502 | return; |
| 1503 | } |
| 1504 | |
| 1505 | selectItem(el, item); |
| 1506 | }); |
| 1507 | |
| 1508 | // Double-click: enter folder or view/download file |
| 1509 | el.addEventListener('dblclick', (e) => |
| 1510 | { |
| 1511 | e.stopPropagation(); |
| 1512 | if (item.isDir) |
| 1513 | { |
| 1514 | navigateTo(item.path, item._root || STATE.currentRoot); |
| 1515 | } else |
| 1516 | { |
| 1517 | downloadOrView(item, icon.querySelector('svg')); |
| 1518 | } |
| 1519 | }); |
| 1520 | |
| 1521 | return el; |
| 1522 | } |
| 1523 | |
| 1524 | function attachMobileLongPress (el, item) |
| 1525 | { |
| 1526 | if (item._root) return; |
| 1527 | |
| 1528 | let pressTimer = null; |
| 1529 | let startX = 0; |
| 1530 | let startY = 0; |
| 1531 | |
| 1532 | function clearPress () |
| 1533 | { |
| 1534 | if (!pressTimer) return; |
| 1535 | clearTimeout(pressTimer); |
| 1536 | pressTimer = null; |
| 1537 | } |
| 1538 | |
| 1539 | function cancelPress () |
| 1540 | { |
| 1541 | clearPress(); |
| 1542 | } |
| 1543 | |
| 1544 | el.addEventListener('pointerdown', (e) => |
| 1545 | { |
| 1546 | if (!isMobileViewport()) return; |
| 1547 | if (e.button !== undefined && e.button !== 0) return; |
| 1548 | if (e.pointerType && e.pointerType === 'mouse') return; |
| 1549 | |
| 1550 | startX = e.clientX; |
| 1551 | startY = e.clientY; |
| 1552 | clearPress(); |
| 1553 | |
| 1554 | pressTimer = setTimeout(() => |
| 1555 | { |
| 1556 | pressTimer = null; |
| 1557 | el.dataset.longPressTriggered = '1'; |
| 1558 | selectItem(el, item); |
| 1559 | }, MOBILE_LONG_PRESS_MS); |
| 1560 | }); |
| 1561 | |
| 1562 | el.addEventListener('pointermove', (e) => |
| 1563 | { |
| 1564 | if (!pressTimer) return; |
| 1565 | if (Math.hypot(e.clientX - startX, e.clientY - startY) > MOBILE_LONG_PRESS_MOVE_THRESHOLD) |
| 1566 | { |
| 1567 | clearPress(); |
| 1568 | } |
| 1569 | }); |
| 1570 | |
| 1571 | el.addEventListener('pointerup', cancelPress); |
| 1572 | el.addEventListener('pointercancel', cancelPress); |
| 1573 | el.addEventListener('pointerleave', cancelPress); |
| 1574 | } |
| 1575 | |
| 1576 | function selectItem (el, item) |
| 1577 | { |
| 1578 | document.querySelectorAll('.file-item.selected').forEach(e => e.classList.remove('selected')); |
| 1579 | el.classList.add('selected'); |
| 1580 | STATE.selectedItem = item; |
| 1581 | openSidebar(item); |
| 1582 | } |
| 1583 | |
| 1584 | // ─────────────────────────────────────────────────────────────────────────── |
| 1585 | // SIDEBAR |
| 1586 | // ─────────────────────────────────────────────────────────────────────────── |
| 1587 | |
| 1588 | async function openSidebar (item) |
| 1589 | { |
| 1590 | const sidebar = document.getElementById('sidebar'); |
| 1591 | sidebar.classList.remove('hidden'); |
| 1592 | document.getElementById('app').classList.add('sidebar-open'); |
| 1593 | |
| 1594 | document.getElementById('sidebar-icon').innerHTML = item.isDir ? iconFolder(64) : iconFile(item.name, 64); |
| 1595 | if (item.isDir) |
| 1596 | { |
| 1597 | document.getElementById('sidebar-icon').dataset.folderPath = item.path; |
| 1598 | } else |
| 1599 | { |
| 1600 | delete document.getElementById('sidebar-icon').dataset.folderPath; |
| 1601 | } |
| 1602 | document.getElementById('sidebar-name').textContent = item.name; |
| 1603 | |
| 1604 | // Load metadata |
| 1605 | const dl = document.getElementById('sidebar-meta'); |
| 1606 | dl.innerHTML = '<dt>Loading…</dt><dd></dd>'; |
| 1607 | |
| 1608 | const actions = document.getElementById('sidebar-actions'); |
| 1609 | actions.innerHTML = ''; |
| 1610 | |
| 1611 | if (!item.isDir) |
| 1612 | { |
| 1613 | const meta = await api('GET', `/files/meta?file=${encodeURIComponent(item.path)}`); |
| 1614 | if (meta) |
| 1615 | { |
| 1616 | const watchedBy = VIDEO_EXTS.has(extOf(item.name)) |
| 1617 | ? Object.entries(meta.watchedBy || {}) |
| 1618 | .map(([user, status]) => `${String(user)}: ${String(status)}`) |
| 1619 | .sort((a, b) => a.localeCompare(b)) |
| 1620 | : []; |
| 1621 | |
| 1622 | dl.innerHTML = ` |
| 1623 | <dt>Size</dt> <dd>${formatBytes(meta.size)}</dd> |
| 1624 | <dt>Modified</dt> <dd>${new Date(meta.mtime).toLocaleString()}</dd> |
| 1625 | <dt>Uploaded by</dt><dd>${meta.uploader || '—'}</dd> |
| 1626 | <dt>Downloaded by</dt><dd>${meta.downloaders.join(', ') || '—'}</dd> |
| 1627 | ${VIDEO_EXTS.has(extOf(item.name)) ? `<dt>Watched by</dt><dd>${watchedBy.join(', ') || '—'}</dd>` : ''} |
| 1628 | `; |
| 1629 | } |
| 1630 | |
| 1631 | // View / download button |
| 1632 | const btnDl = document.createElement('button'); |
| 1633 | btnDl.textContent = 'View / Download'; |
| 1634 | btnDl.addEventListener('click', () => |
| 1635 | { |
| 1636 | const tile = Array.from(document.querySelectorAll('.file-item')).find(node => node.dataset.path === item.path); |
| 1637 | const source = (tile ? tile.querySelector('.icon svg') : null) || document.querySelector('#sidebar-icon svg'); |
| 1638 | downloadOrView(item, source); |
| 1639 | }); |
| 1640 | actions.appendChild(btnDl); |
| 1641 | |
| 1642 | // Share button (file) |
| 1643 | const btnShareFile = document.createElement('button'); |
| 1644 | btnShareFile.textContent = 'Share'; |
| 1645 | btnShareFile.addEventListener('click', () => openShareModal(item)); |
| 1646 | actions.appendChild(btnShareFile); |
| 1647 | } else |
| 1648 | { |
| 1649 | dl.innerHTML = `<dt>Type</dt><dd>${item._root ? 'Root folder' : 'Folder'}</dd>`; |
| 1650 | |
| 1651 | if (item._root) |
| 1652 | { |
| 1653 | dl.innerHTML += ` |
| 1654 | <dt>Alias</dt><dd>${item.name}</dd> |
| 1655 | <dt>Original name</dt><dd>${item._root.originalName || basenameOfPath(item.path)}</dd> |
| 1656 | `; |
| 1657 | |
| 1658 | const space = await api('GET', `/files/space?dir=${encodeURIComponent(item.path)}`).catch(() => null); |
| 1659 | if (space) |
| 1660 | { |
| 1661 | const used = formatBytes(space.usedBytes); |
| 1662 | const free = space.freeBytes == null ? 'unknown' : formatBytes(space.freeBytes); |
| 1663 | dl.innerHTML += ` |
| 1664 | <dt>Used</dt><dd>${used}</dd> |
| 1665 | <dt>Remaining</dt><dd>${free}</dd> |
| 1666 | `; |
| 1667 | } |
| 1668 | |
| 1669 | const accessUsers = await fetchRootAccessList(item.path); |
| 1670 | if (accessUsers) |
| 1671 | { |
| 1672 | dl.innerHTML += ` |
| 1673 | <dt>Access</dt><dd>${formatRootAccessList(accessUsers)}</dd> |
| 1674 | `; |
| 1675 | } |
| 1676 | } |
| 1677 | |
| 1678 | const btnOpen = document.createElement('button'); |
| 1679 | btnOpen.textContent = 'Open folder'; |
| 1680 | btnOpen.addEventListener('click', () => navigateTo(item.path, item._root || STATE.currentRoot)); |
| 1681 | actions.appendChild(btnOpen); |
| 1682 | |
| 1683 | // Download as zip button (folder) |
| 1684 | const btnZip = document.createElement('button'); |
| 1685 | btnZip.textContent = 'Download as zip'; |
| 1686 | btnZip.addEventListener('click', () => |
| 1687 | { |
| 1688 | btnZip.disabled = true; |
| 1689 | btnZip.textContent = 'Working...'; |
| 1690 | const url = `/api/files/download-zip?dir=${encodeURIComponent(item.path)}`; |
| 1691 | const headers = { |
| 1692 | Authorization: 'Bearer ' + STATE.token, |
| 1693 | 'X-Fp': getFingerprint(), |
| 1694 | }; |
| 1695 | fetch(url, { headers }) |
| 1696 | .then(res => |
| 1697 | { |
| 1698 | if (!res.ok) throw new Error('Download mislukt'); |
| 1699 | return res.blob(); |
| 1700 | }) |
| 1701 | .then(blob => |
| 1702 | { |
| 1703 | const blobUrl = URL.createObjectURL(blob); |
| 1704 | const a = document.createElement('a'); |
| 1705 | a.href = blobUrl; |
| 1706 | a.download = item.name + '.zip'; |
| 1707 | a.click(); |
| 1708 | setTimeout(() => URL.revokeObjectURL(blobUrl), 10000); |
| 1709 | }) |
| 1710 | .catch((err) => toast(err.message || 'Download mislukt', 'err')) |
| 1711 | .finally(() => |
| 1712 | { |
| 1713 | btnZip.disabled = false; |
| 1714 | btnZip.textContent = 'Download as zip'; |
| 1715 | }); |
| 1716 | }); |
| 1717 | actions.appendChild(btnZip); |
| 1718 | |
| 1719 | // Share button (folder) |
| 1720 | const btnShareFolder = document.createElement('button'); |
| 1721 | btnShareFolder.textContent = 'Share'; |
| 1722 | btnShareFolder.addEventListener('click', () => openShareModal(item)); |
| 1723 | actions.appendChild(btnShareFolder); |
| 1724 | |
| 1725 | // Load folder icon thumbnail into the sidebar icon element. |
| 1726 | void loadOneFolderIcon(document.getElementById('sidebar-icon')); |
| 1727 | } |
| 1728 | |
| 1729 | // Rename button (write access required) |
| 1730 | if (canWrite(item)) |
| 1731 | { |
| 1732 | if (item.isDir) |
| 1733 | { |
| 1734 | const btnSetIcon = document.createElement('button'); |
| 1735 | btnSetIcon.textContent = 'Set icon'; |
| 1736 | btnSetIcon.addEventListener('click', () => openFolderIconPicker(item)); |
| 1737 | actions.appendChild(btnSetIcon); |
| 1738 | } |
| 1739 | |
| 1740 | if (!item._root) |
| 1741 | { |
| 1742 | const btnMove = document.createElement('button'); |
| 1743 | btnMove.textContent = 'Move to'; |
| 1744 | btnMove.addEventListener('click', () => openMovePicker(item)); |
| 1745 | actions.appendChild(btnMove); |
| 1746 | } |
| 1747 | |
| 1748 | const btnRen = document.createElement('button'); |
| 1749 | btnRen.textContent = 'Rename'; |
| 1750 | btnRen.addEventListener('click', () => openRenameModal(item)); |
| 1751 | actions.appendChild(btnRen); |
| 1752 | |
| 1753 | if (!item._root) |
| 1754 | { |
| 1755 | const btnDel = document.createElement('button'); |
| 1756 | btnDel.textContent = 'Delete'; |
| 1757 | btnDel.className = 'danger'; |
| 1758 | btnDel.addEventListener('click', () => deleteItem(item)); |
| 1759 | actions.appendChild(btnDel); |
| 1760 | } |
| 1761 | } |
| 1762 | } |
| 1763 | |
| 1764 | function openFolderSidebar () |
| 1765 | { |
| 1766 | const sidebar = document.getElementById('sidebar'); |
| 1767 | sidebar.classList.remove('hidden'); |
| 1768 | document.getElementById('app').classList.add('sidebar-open'); |
| 1769 | |
| 1770 | document.getElementById('sidebar-icon').innerHTML = iconFolder(64); |
| 1771 | |
| 1772 | const nameEl = document.getElementById('sidebar-name'); |
| 1773 | const dl = document.getElementById('sidebar-meta'); |
| 1774 | const actions = document.getElementById('sidebar-actions'); |
| 1775 | actions.innerHTML = ''; |
| 1776 | |
| 1777 | if (!STATE.currentDir || !STATE.currentRoot) |
| 1778 | { |
| 1779 | nameEl.textContent = 'Storage Roots'; |
| 1780 | dl.innerHTML = ` |
| 1781 | <dt>Type</dt><dd>Root overview</dd> |
| 1782 | <dt>Roots</dt><dd>${STATE.roots.length}</dd> |
| 1783 | `; |
| 1784 | return; |
| 1785 | } |
| 1786 | |
| 1787 | const parts = String(STATE.currentDir).split(/[\\/]/).filter(Boolean); |
| 1788 | const fallback = STATE.currentRoot.label || 'Folder'; |
| 1789 | nameEl.textContent = parts.length ? parts[parts.length - 1] : fallback; |
| 1790 | |
| 1791 | const dirs = STATE.items.filter(i => i.isDir).length; |
| 1792 | const files = STATE.items.length - dirs; |
| 1793 | const baseDetails = ` |
| 1794 | <dt>Path</dt><dd>${STATE.currentDir}</dd> |
| 1795 | <dt>Folders</dt><dd>${dirs}</dd> |
| 1796 | <dt>Files</dt><dd>${files}</dd> |
| 1797 | `; |
| 1798 | dl.innerHTML = baseDetails; |
| 1799 | |
| 1800 | if (samePath(STATE.currentDir, STATE.currentRoot.path)) |
| 1801 | { |
| 1802 | dl.innerHTML += '<dt>Access</dt><dd>Loading…</dd>'; |
| 1803 | const currentDirAtStart = STATE.currentDir; |
| 1804 | const currentRootPathAtStart = STATE.currentRoot.path; |
| 1805 | void fetchRootAccessList(currentRootPathAtStart).then((accessUsers) => |
| 1806 | { |
| 1807 | if (!accessUsers) return; |
| 1808 | if (!STATE.currentRoot) return; |
| 1809 | if (!samePath(STATE.currentDir, currentDirAtStart)) return; |
| 1810 | if (!samePath(STATE.currentRoot.path, currentRootPathAtStart)) return; |
| 1811 | dl.innerHTML = `${baseDetails}<dt>Access</dt><dd>${formatRootAccessList(accessUsers)}</dd>`; |
| 1812 | }); |
| 1813 | } |
| 1814 | } |
| 1815 | |
| 1816 | function closeSidebar () |
| 1817 | { |
| 1818 | if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') return; |
| 1819 | document.querySelectorAll('.file-item.selected').forEach(e => e.classList.remove('selected')); |
| 1820 | STATE.selectedItem = null; |
| 1821 | |
| 1822 | if (isMobileViewport()) |
| 1823 | { |
| 1824 | hideSidebarPanel(); |
| 1825 | return; |
| 1826 | } |
| 1827 | |
| 1828 | openFolderSidebar(); |
| 1829 | } |
| 1830 | |
| 1831 | function isMobileViewport () |
| 1832 | { |
| 1833 | return window.matchMedia(MOBILE_BREAKPOINT_QUERY).matches; |
| 1834 | } |
| 1835 | |
| 1836 | function hideSidebarPanel () |
| 1837 | { |
| 1838 | const sidebar = document.getElementById('sidebar'); |
| 1839 | const app = document.getElementById('app'); |
| 1840 | sidebar.classList.add('hidden'); |
| 1841 | app.classList.remove('sidebar-open'); |
| 1842 | } |
| 1843 | |
| 1844 | function basenameOfPath (p) |
| 1845 | { |
| 1846 | const parts = String(p || '').split(/[\\/]/).filter(Boolean); |
| 1847 | return parts.length ? parts[parts.length - 1] : String(p || ''); |
| 1848 | } |
| 1849 | |
| 1850 | async function fetchRootAccessList (rootPath) |
| 1851 | { |
| 1852 | if (!rootPath) return null; |
| 1853 | const data = await api('GET', `/files/root-access?rootPath=${encodeURIComponent(rootPath)}`).catch(() => null); |
| 1854 | if (!data || !Array.isArray(data.users)) return null; |
| 1855 | return data.users; |
| 1856 | } |
| 1857 | |
| 1858 | function formatRootAccessList (users) |
| 1859 | { |
| 1860 | if (!Array.isArray(users) || users.length === 0) return 'No users'; |
| 1861 | |
| 1862 | const sorted = [...users].sort((a, b) => |
| 1863 | { |
| 1864 | const modeRank = (mode) => mode === 'R+W' ? 0 : 1; |
| 1865 | const byMode = modeRank(a.mode) - modeRank(b.mode); |
| 1866 | if (byMode !== 0) return byMode; |
| 1867 | return String(a.username).localeCompare(String(b.username)); |
| 1868 | }); |
| 1869 | |
| 1870 | const items = sorted |
| 1871 | .map((u) => `<li>${escapeHtml(String(u.username || ''))} ${escapeHtml(String(u.mode || 'R'))}</li>`) |
| 1872 | .join(''); |
| 1873 | return `<ul class="root-access-list">${items}</ul>`; |
| 1874 | } |
| 1875 | |
| 1876 | function rootPermissionLabel (root) |
| 1877 | { |
| 1878 | return (root && (root.originalName || root.label)) || ''; |
| 1879 | } |
| 1880 | |
| 1881 | function resolveRootForPath (targetPath) |
| 1882 | { |
| 1883 | if (!targetPath) return null; |
| 1884 | return STATE.roots.find((r) => samePath(targetPath, r.path) || pathInside(targetPath, r.path)) || null; |
| 1885 | } |
| 1886 | |
| 1887 | function writableRoots () |
| 1888 | { |
| 1889 | if (STATE.isAdmin) return STATE.roots.slice(); |
| 1890 | return STATE.roots.filter((r) => |
| 1891 | { |
| 1892 | const perm = STATE.permissions[rootPermissionLabel(r)]; |
| 1893 | return !!(perm && perm.write); |
| 1894 | }); |
| 1895 | } |
| 1896 | |
| 1897 | async function moveWithConflictResolution (item, targetDir) |
| 1898 | { |
| 1899 | try |
| 1900 | { |
| 1901 | return await api('POST', '/files/move', { from: item.path, toDir: targetDir }); |
| 1902 | } |
| 1903 | catch (err) |
| 1904 | { |
| 1905 | if (!/already exists/i.test(err.message || '')) throw err; |
| 1906 | |
| 1907 | const existingNames = await listDirNameSet(targetDir); |
| 1908 | const desiredName = item.name || basenameOfPath(item.path) || 'file'; |
| 1909 | const suggestedName = nextAvailableName(desiredName, existingNames); |
| 1910 | const decision = await showFileConflictChoice(desiredName, suggestedName, 'move'); |
| 1911 | if (decision === 'cancel') return null; |
| 1912 | |
| 1913 | if (decision === 'overwrite') |
| 1914 | { |
| 1915 | return api('POST', '/files/move', { |
| 1916 | from: item.path, |
| 1917 | toDir: targetDir, |
| 1918 | conflict: 'overwrite', |
| 1919 | }); |
| 1920 | } |
| 1921 | |
| 1922 | return api('POST', '/files/move', { |
| 1923 | from: item.path, |
| 1924 | toDir: targetDir, |
| 1925 | conflict: 'rename', |
| 1926 | targetName: suggestedName, |
| 1927 | }); |
| 1928 | } |
| 1929 | } |
| 1930 | |
| 1931 | function ensureMoveModal () |
| 1932 | { |
| 1933 | let overlay = document.getElementById('move-modal'); |
| 1934 | if (overlay) return overlay; |
| 1935 | |
| 1936 | overlay = document.createElement('div'); |
| 1937 | overlay.id = 'move-modal'; |
| 1938 | overlay.className = 'modal-overlay hidden'; |
| 1939 | overlay.innerHTML = ` |
| 1940 | <div class="modal move-modal"> |
| 1941 | <button class="modal-close" id="move-modal-close" aria-label="Close">✕</button> |
| 1942 | <h2>Move To</h2> |
| 1943 | <p id="move-modal-caption" class="muted"></p> |
| 1944 | <div id="move-tree" class="move-tree"></div> |
| 1945 | <p id="move-selected" class="muted"></p> |
| 1946 | <div class="dialog-actions"> |
| 1947 | <button id="move-modal-cancel">Cancel</button> |
| 1948 | <button id="move-modal-confirm" class="primary">Move</button> |
| 1949 | </div> |
| 1950 | </div> |
| 1951 | `; |
| 1952 | document.body.appendChild(overlay); |
| 1953 | |
| 1954 | const closeBtn = overlay.querySelector('#move-modal-close'); |
| 1955 | const cancelBtn = overlay.querySelector('#move-modal-cancel'); |
| 1956 | const confirmBtn = overlay.querySelector('#move-modal-confirm'); |
| 1957 | |
| 1958 | function hide () |
| 1959 | { |
| 1960 | overlay.classList.add('hidden'); |
| 1961 | STATE.movePicker = null; |
| 1962 | } |
| 1963 | |
| 1964 | closeBtn.addEventListener('click', hide); |
| 1965 | cancelBtn.addEventListener('click', hide); |
| 1966 | overlay.addEventListener('click', (e) => |
| 1967 | { |
| 1968 | if (e.target === overlay) hide(); |
| 1969 | }); |
| 1970 | |
| 1971 | confirmBtn.addEventListener('click', async () => |
| 1972 | { |
| 1973 | const st = STATE.movePicker; |
| 1974 | if (!st || !st.item || !st.selectedPath) |
| 1975 | { |
| 1976 | toast('Select a destination folder first.', 'err'); |
| 1977 | return; |
| 1978 | } |
| 1979 | |
| 1980 | try |
| 1981 | { |
| 1982 | const moved = await moveWithConflictResolution(st.item, st.selectedPath); |
| 1983 | if (!moved) return; |
| 1984 | } |
| 1985 | catch (err) |
| 1986 | { |
| 1987 | toast('Move failed: ' + err.message, 'err'); |
| 1988 | return; |
| 1989 | } |
| 1990 | |
| 1991 | hide(); |
| 1992 | if (STATE.selectedItem && STATE.selectedItem.path === st.item.path) closeSidebar(); |
| 1993 | navigateTo(STATE.currentDir, STATE.currentRoot); |
| 1994 | }); |
| 1995 | |
| 1996 | return overlay; |
| 1997 | } |
| 1998 | |
| 1999 | function setMoveSelection (path, buttonEl) |
| 2000 | { |
| 2001 | if (!STATE.movePicker) return; |
| 2002 | STATE.movePicker.selectedPath = path; |
| 2003 | |
| 2004 | document.querySelectorAll('.move-node-label.selected').forEach((el) => el.classList.remove('selected')); |
| 2005 | if (buttonEl) buttonEl.classList.add('selected'); |
| 2006 | |
| 2007 | const selectedEl = document.getElementById('move-selected'); |
| 2008 | selectedEl.textContent = path ? `Destination: ${path}` : 'Destination: none'; |
| 2009 | } |
| 2010 | |
| 2011 | async function loadMoveChildren (containerEl, dirPath) |
| 2012 | { |
| 2013 | if (containerEl.dataset.loaded === '1') return; |
| 2014 | containerEl.dataset.loaded = '1'; |
| 2015 | |
| 2016 | const data = await api('GET', `/files/list?dir=${encodeURIComponent(dirPath)}`).catch(() => null); |
| 2017 | const folders = data ? data.items.filter((it) => it.isDir).sort((a, b) => a.name.localeCompare(b.name)) : []; |
| 2018 | |
| 2019 | if (!folders.length) |
| 2020 | { |
| 2021 | const empty = document.createElement('div'); |
| 2022 | empty.className = 'move-empty'; |
| 2023 | empty.textContent = 'No subfolders'; |
| 2024 | containerEl.appendChild(empty); |
| 2025 | return; |
| 2026 | } |
| 2027 | |
| 2028 | for (const child of folders) |
| 2029 | { |
| 2030 | containerEl.appendChild(createMoveNode(child.path, child.name)); |
| 2031 | } |
| 2032 | } |
| 2033 | |
| 2034 | function createMoveNode (folderPath, label) |
| 2035 | { |
| 2036 | const node = document.createElement('div'); |
| 2037 | node.className = 'move-node'; |
| 2038 | |
| 2039 | const row = document.createElement('div'); |
| 2040 | row.className = 'move-node-row'; |
| 2041 | |
| 2042 | const toggle = document.createElement('button'); |
| 2043 | toggle.type = 'button'; |
| 2044 | toggle.className = 'move-toggle'; |
| 2045 | toggle.textContent = '▸'; |
| 2046 | |
| 2047 | const selectBtn = document.createElement('button'); |
| 2048 | selectBtn.type = 'button'; |
| 2049 | selectBtn.className = 'move-node-label'; |
| 2050 | selectBtn.textContent = label; |
| 2051 | selectBtn.addEventListener('click', () => setMoveSelection(folderPath, selectBtn)); |
| 2052 | |
| 2053 | const children = document.createElement('div'); |
| 2054 | children.className = 'move-children hidden'; |
| 2055 | |
| 2056 | toggle.addEventListener('click', async () => |
| 2057 | { |
| 2058 | if (children.classList.contains('hidden')) |
| 2059 | { |
| 2060 | await loadMoveChildren(children, folderPath); |
| 2061 | children.classList.remove('hidden'); |
| 2062 | toggle.textContent = '▾'; |
| 2063 | } else |
| 2064 | { |
| 2065 | children.classList.add('hidden'); |
| 2066 | toggle.textContent = '▸'; |
| 2067 | } |
| 2068 | }); |
| 2069 | |
| 2070 | row.appendChild(toggle); |
| 2071 | row.appendChild(selectBtn); |
| 2072 | node.appendChild(row); |
| 2073 | node.appendChild(children); |
| 2074 | return node; |
| 2075 | } |
| 2076 | |
| 2077 | function openMovePicker (item) |
| 2078 | { |
| 2079 | if (!canWrite()) |
| 2080 | { |
| 2081 | toast('No write access.', 'err'); |
| 2082 | return; |
| 2083 | } |
| 2084 | |
| 2085 | const roots = writableRoots(); |
| 2086 | if (!roots.length) |
| 2087 | { |
| 2088 | toast('No writable destination roots available.', 'err'); |
| 2089 | return; |
| 2090 | } |
| 2091 | |
| 2092 | const overlay = ensureMoveModal(); |
| 2093 | const tree = overlay.querySelector('#move-tree'); |
| 2094 | const caption = overlay.querySelector('#move-modal-caption'); |
| 2095 | |
| 2096 | STATE.movePicker = { item, selectedPath: null }; |
| 2097 | caption.textContent = `Select destination folder for: ${item.name}`; |
| 2098 | tree.innerHTML = ''; |
| 2099 | |
| 2100 | for (const root of roots) |
| 2101 | { |
| 2102 | tree.appendChild(createMoveNode(root.path, root.label)); |
| 2103 | } |
| 2104 | |
| 2105 | setMoveSelection(null, null); |
| 2106 | overlay.classList.remove('hidden'); |
| 2107 | } |
| 2108 | |
| 2109 | // ─────────────────────────────────────────────────────────────────────────── |
| 2110 | // FOLDER ICON PICKER |
| 2111 | // ─────────────────────────────────────────────────────────────────────────── |
| 2112 | |
| 2113 | async function openFolderIconPicker (item) |
| 2114 | { |
| 2115 | if (!canWrite(item)) |
| 2116 | { |
| 2117 | toast('No write access.', 'err'); |
| 2118 | return; |
| 2119 | } |
| 2120 | |
| 2121 | // Fetch the list of available images (only those with cached thumbnails). |
| 2122 | const data = await api('GET', `/files/folder-images?dir=${encodeURIComponent(item.path)}`).catch(() => null); |
| 2123 | const images = data ? data.images : []; |
| 2124 | |
| 2125 | let existingIconOverlay = document.getElementById('folder-icon-picker'); |
| 2126 | if (existingIconOverlay) existingIconOverlay.remove(); |
| 2127 | |
| 2128 | const overlay = document.createElement('div'); |
| 2129 | overlay.id = 'folder-icon-picker'; |
| 2130 | overlay.className = 'modal-overlay'; |
| 2131 | |
| 2132 | const modal = document.createElement('div'); |
| 2133 | modal.className = 'modal folder-icon-modal'; |
| 2134 | |
| 2135 | const closeBtn = document.createElement('button'); |
| 2136 | closeBtn.className = 'modal-close'; |
| 2137 | closeBtn.setAttribute('aria-label', 'Close'); |
| 2138 | closeBtn.textContent = '✕'; |
| 2139 | |
| 2140 | const title = document.createElement('h2'); |
| 2141 | title.textContent = 'Set folder icon'; |
| 2142 | |
| 2143 | const subtitle = document.createElement('p'); |
| 2144 | subtitle.className = 'muted'; |
| 2145 | |
| 2146 | const grid = document.createElement('div'); |
| 2147 | grid.className = 'folder-icon-grid'; |
| 2148 | |
| 2149 | if (!images.length) |
| 2150 | { |
| 2151 | subtitle.textContent = 'No images with cached thumbnails were found inside this folder.'; |
| 2152 | } else |
| 2153 | { |
| 2154 | subtitle.textContent = 'Select an image to use as the folder icon.'; |
| 2155 | |
| 2156 | for (const { filePath } of images) |
| 2157 | { |
| 2158 | const cell = document.createElement('div'); |
| 2159 | cell.className = 'folder-icon-cell'; |
| 2160 | cell.dataset.path = filePath; |
| 2161 | |
| 2162 | const imgEl = document.createElement('img'); |
| 2163 | imgEl.alt = filePath.split('/').pop(); |
| 2164 | imgEl.className = 'folder-icon-thumb'; |
| 2165 | // Lazy-load via IntersectionObserver on the cell. |
| 2166 | imgEl.dataset.src = filePath; |
| 2167 | |
| 2168 | const label = document.createElement('div'); |
| 2169 | label.className = 'folder-icon-label'; |
| 2170 | label.textContent = filePath.split('/').pop(); |
| 2171 | |
| 2172 | cell.appendChild(imgEl); |
| 2173 | cell.appendChild(label); |
| 2174 | |
| 2175 | cell.addEventListener('click', () => |
| 2176 | { |
| 2177 | grid.querySelectorAll('.folder-icon-cell.selected').forEach(el => el.classList.remove('selected')); |
| 2178 | cell.classList.add('selected'); |
| 2179 | confirmBtn.disabled = false; |
| 2180 | }); |
| 2181 | |
| 2182 | grid.appendChild(cell); |
| 2183 | } |
| 2184 | } |
| 2185 | |
| 2186 | const dialogActions = document.createElement('div'); |
| 2187 | dialogActions.className = 'dialog-actions'; |
| 2188 | |
| 2189 | const clearBtn = document.createElement('button'); |
| 2190 | clearBtn.textContent = 'Clear icon'; |
| 2191 | clearBtn.addEventListener('click', async () => |
| 2192 | { |
| 2193 | try |
| 2194 | { |
| 2195 | await api('POST', '/files/folder-icon', { folderPath: item.path, imagePath: null }); |
| 2196 | } catch (err) |
| 2197 | { |
| 2198 | toast('Failed to clear icon: ' + err.message, 'err'); |
| 2199 | return; |
| 2200 | } |
| 2201 | hide(); |
| 2202 | refreshAfterIconChange(item); |
| 2203 | }); |
| 2204 | |
| 2205 | const cancelBtn = document.createElement('button'); |
| 2206 | cancelBtn.textContent = 'Cancel'; |
| 2207 | cancelBtn.addEventListener('click', () => hide()); |
| 2208 | |
| 2209 | const confirmBtn = document.createElement('button'); |
| 2210 | confirmBtn.className = 'primary'; |
| 2211 | confirmBtn.textContent = 'Set icon'; |
| 2212 | confirmBtn.disabled = true; |
| 2213 | confirmBtn.addEventListener('click', async () => |
| 2214 | { |
| 2215 | const selected = grid.querySelector('.folder-icon-cell.selected'); |
| 2216 | if (!selected) return; |
| 2217 | const imagePath = selected.dataset.path; |
| 2218 | try |
| 2219 | { |
| 2220 | await api('POST', '/files/folder-icon', { folderPath: item.path, imagePath }); |
| 2221 | } catch (err) |
| 2222 | { |
| 2223 | toast('Failed to set icon: ' + err.message, 'err'); |
| 2224 | return; |
| 2225 | } |
| 2226 | hide(); |
| 2227 | refreshAfterIconChange(item); |
| 2228 | }); |
| 2229 | |
| 2230 | dialogActions.appendChild(clearBtn); |
| 2231 | dialogActions.appendChild(cancelBtn); |
| 2232 | dialogActions.appendChild(confirmBtn); |
| 2233 | |
| 2234 | modal.appendChild(closeBtn); |
| 2235 | modal.appendChild(title); |
| 2236 | modal.appendChild(subtitle); |
| 2237 | modal.appendChild(grid); |
| 2238 | modal.appendChild(dialogActions); |
| 2239 | overlay.appendChild(modal); |
| 2240 | document.body.appendChild(overlay); |
| 2241 | |
| 2242 | function hide () |
| 2243 | { |
| 2244 | overlay.remove(); |
| 2245 | // Revoke any blob URLs we created for the picker thumbnails. |
| 2246 | grid.querySelectorAll('.folder-icon-thumb[src^="blob:"]').forEach(img => |
| 2247 | { |
| 2248 | URL.revokeObjectURL(img.src); |
| 2249 | }); |
| 2250 | } |
| 2251 | |
| 2252 | closeBtn.addEventListener('click', hide); |
| 2253 | overlay.addEventListener('click', (e) => { if (e.target === overlay) hide(); }); |
| 2254 | |
| 2255 | // Eagerly load thumbnails for all cells (picker is small, fetch all). |
| 2256 | for (const cell of grid.querySelectorAll('.folder-icon-cell')) |
| 2257 | { |
| 2258 | const imgEl = cell.querySelector('.folder-icon-thumb'); |
| 2259 | const filePath = imgEl.dataset.src; |
| 2260 | void fetch(`/api/files/thumbnail?file=${encodeURIComponent(filePath)}`, { |
| 2261 | headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() }, |
| 2262 | }).then(async (r) => |
| 2263 | { |
| 2264 | if (!r.ok || !overlay.isConnected) return; |
| 2265 | const blob = await r.blob(); |
| 2266 | const url = URL.createObjectURL(blob); |
| 2267 | imgEl.src = url; |
| 2268 | }).catch(() => {}); |
| 2269 | } |
| 2270 | } |
| 2271 | |
| 2272 | function refreshAfterIconChange (item) |
| 2273 | { |
| 2274 | // Reset and reload icon in grid tiles. |
| 2275 | const gridTile = Array.from(document.querySelectorAll('.icon[data-folder-path]')) |
| 2276 | .find(el => el.dataset.folderPath === item.path); |
| 2277 | if (gridTile) |
| 2278 | { |
| 2279 | const svg = gridTile.querySelector('svg'); |
| 2280 | if (svg) |
| 2281 | { |
| 2282 | // Rebuild to plain folder SVG, then reload. |
| 2283 | gridTile.innerHTML = iconFolder(); |
| 2284 | delete gridTile.dataset.thumbReady; |
| 2285 | gridTile.dataset.folderPath = item.path; |
| 2286 | void loadOneFolderIcon(gridTile); |
| 2287 | } |
| 2288 | } |
| 2289 | |
| 2290 | // Also reset the sidebar icon if it's showing the same folder. |
| 2291 | const sidebarIcon = document.getElementById('sidebar-icon'); |
| 2292 | if (sidebarIcon && sidebarIcon.dataset.folderPath === item.path) |
| 2293 | { |
| 2294 | sidebarIcon.innerHTML = iconFolder(64); |
| 2295 | delete sidebarIcon.dataset.thumbReady; |
| 2296 | void loadOneFolderIcon(sidebarIcon); |
| 2297 | } |
| 2298 | } |
| 2299 | |
| 2300 | // ─────────────────────────────────────────────────────────────────────────── |
| 2301 | // DOWNLOAD / VIEW |
| 2302 | // ─────────────────────────────────────────────────────────────────────────── |
| 2303 | |
| 2304 | function isInlinePreviewableBlob (blob, name) |
| 2305 | { |
| 2306 | const mime = String(blob.type || '').toLowerCase(); |
| 2307 | if (/^(image|video|audio)\//.test(mime)) return true; |
| 2308 | if (/^text\//.test(mime)) return true; |
| 2309 | if (mime === 'application/pdf') return true; |
| 2310 | if (mime === 'application/json') return true; |
| 2311 | if (mime === 'application/xml') return true; |
| 2312 | if (mime === 'application/javascript') return true; |
| 2313 | |
| 2314 | // Fallback by extension when MIME is missing or generic. |
| 2315 | const ext = extOf(name || ''); |
| 2316 | if (IMAGE_EXTS.has(ext) || VIDEO_EXTS.has(ext) || AUDIO_EXTS.has(ext)) return true; |
| 2317 | if (CODE_EXTS.has(ext)) return true; |
| 2318 | return false; |
| 2319 | } |
| 2320 | |
| 2321 | function isTextLikeBlob (blob, name) |
| 2322 | { |
| 2323 | const mime = String(blob.type || '').toLowerCase(); |
| 2324 | if (/^text\//.test(mime)) return true; |
| 2325 | if (mime === 'application/json' || mime === 'application/xml' || mime === 'application/javascript') return true; |
| 2326 | const ext = extOf(name || ''); |
| 2327 | return CODE_EXTS.has(ext); |
| 2328 | } |
| 2329 | |
| 2330 | function detectCodeLanguage (name, mime) |
| 2331 | { |
| 2332 | const ext = extOf(name || ''); |
| 2333 | const m = String(mime || '').toLowerCase(); |
| 2334 | if (m.includes('json') || ext === 'json') return 'json'; |
| 2335 | if (m.includes('xml') || ext === 'xml') return 'xml'; |
| 2336 | if (m.includes('html') || ext === 'html' || ext === 'htm') return 'html'; |
| 2337 | if (m.includes('css') || ext === 'css') return 'css'; |
| 2338 | if (m.includes('javascript') || ['js', 'jsx', 'mjs', 'cjs'].includes(ext)) return 'js'; |
| 2339 | if (m.includes('typescript') || ['ts', 'tsx'].includes(ext)) return 'ts'; |
| 2340 | if (['sh', 'bash', 'zsh'].includes(ext)) return 'sh'; |
| 2341 | if (['md', 'txt', 'log', 'ini', 'toml', 'yaml', 'yml'].includes(ext)) return 'plain'; |
| 2342 | return CODE_EXTS.has(ext) ? 'js' : 'plain'; |
| 2343 | } |
| 2344 | |
| 2345 | function prettyPrintMarkup (raw) |
| 2346 | { |
| 2347 | const src = String(raw || '') |
| 2348 | .replace(/>\s+</g, '><') |
| 2349 | .replace(/\r\n/g, '\n'); |
| 2350 | |
| 2351 | const lines = src.replace(/></g, '>\n<').split('\n'); |
| 2352 | let indent = 0; |
| 2353 | const out = []; |
| 2354 | |
| 2355 | for (const ln of lines) |
| 2356 | { |
| 2357 | const line = ln.trim(); |
| 2358 | if (!line) continue; |
| 2359 | const isClose = /^<\//.test(line); |
| 2360 | const isSelf = /\/>$/.test(line) || /^<[^!?][^>]*>[^<]*<\/[^>]+>$/.test(line); |
| 2361 | const isOpen = /^<[^!?/][^>]*>$/.test(line); |
| 2362 | |
| 2363 | if (isClose) indent = Math.max(0, indent - 1); |
| 2364 | out.push(' '.repeat(indent) + line); |
| 2365 | if (isOpen && !isSelf) indent += 1; |
| 2366 | } |
| 2367 | |
| 2368 | return out.join('\n'); |
| 2369 | } |
| 2370 | |
| 2371 | function prettyPrintBraces (raw) |
| 2372 | { |
| 2373 | const lines = String(raw || '') |
| 2374 | .replace(/\r\n/g, '\n') |
| 2375 | .split('\n'); |
| 2376 | let indent = 0; |
| 2377 | const out = []; |
| 2378 | |
| 2379 | for (const ln of lines) |
| 2380 | { |
| 2381 | const line = ln.trim(); |
| 2382 | if (!line) |
| 2383 | { |
| 2384 | out.push(''); |
| 2385 | continue; |
| 2386 | } |
| 2387 | if (/^[}\])]/.test(line)) indent = Math.max(0, indent - 1); |
| 2388 | out.push(' '.repeat(indent) + line); |
| 2389 | if (/[{[(]$/.test(line) || /[{[(]\s*(\/\/.*)?$/.test(line)) indent += 1; |
| 2390 | } |
| 2391 | return out.join('\n'); |
| 2392 | } |
| 2393 | |
| 2394 | function prettyPrintCode (raw, lang) |
| 2395 | { |
| 2396 | const text = String(raw || '').replace(/\r\n/g, '\n'); |
| 2397 | if (lang === 'json') |
| 2398 | { |
| 2399 | try { return JSON.stringify(JSON.parse(text), null, 2); } catch { return text; } |
| 2400 | } |
| 2401 | if (lang === 'xml' || lang === 'html') return prettyPrintMarkup(text); |
| 2402 | if (lang === 'js' || lang === 'ts' || lang === 'css') return prettyPrintBraces(text); |
| 2403 | return text; |
| 2404 | } |
| 2405 | |
| 2406 | function escapeHtml (s) |
| 2407 | { |
| 2408 | return String(s) |
| 2409 | .replace(/&/g, '&') |
| 2410 | .replace(/</g, '<') |
| 2411 | .replace(/>/g, '>'); |
| 2412 | } |
| 2413 | |
| 2414 | function highlightCode (raw, lang) |
| 2415 | { |
| 2416 | if (lang === 'plain') return escapeHtml(raw); |
| 2417 | |
| 2418 | let html = escapeHtml(raw); |
| 2419 | const stash = []; |
| 2420 | const keep = (regex, cls) => |
| 2421 | { |
| 2422 | html = html.replace(regex, (m) => |
| 2423 | { |
| 2424 | const idx = stash.push(`<span class="tok-${cls}">${m}</span>`) - 1; |
| 2425 | return `@@TOK${idx}@@`; |
| 2426 | }); |
| 2427 | }; |
| 2428 | |
| 2429 | if (lang === 'json') |
| 2430 | { |
| 2431 | html = html |
| 2432 | .replace(/("(?:\\.|[^"\\])*")\s*:/g, '<span class="tok-key">$1</span>:') |
| 2433 | .replace(/: ("(?:\\.|[^"\\])*")/g, ': <span class="tok-string">$1</span>') |
| 2434 | .replace(/\b(true|false|null)\b/g, '<span class="tok-keyword">$1</span>') |
| 2435 | .replace(/\b(-?\d+(?:\.\d+)?(?:e[+\-]?\d+)?)\b/gi, '<span class="tok-number">$1</span>'); |
| 2436 | return html; |
| 2437 | } |
| 2438 | |
| 2439 | if (lang === 'xml' || lang === 'html') |
| 2440 | { |
| 2441 | html = html |
| 2442 | .replace(/(<\/?)([a-zA-Z0-9:_-]+)/g, '$1<span class="tok-keyword">$2</span>') |
| 2443 | .replace(/([a-zA-Z0-9:_-]+)=("[^&]*"|"[^"]*")/g, '<span class="tok-key">$1</span>=<span class="tok-string">$2</span>'); |
| 2444 | return html; |
| 2445 | } |
| 2446 | |
| 2447 | if (lang === 'sh') keep(/(^|\s)#.*$/gm, 'comment'); |
| 2448 | else keep(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, 'comment'); |
| 2449 | keep(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`/g, 'string'); |
| 2450 | |
| 2451 | html = html |
| 2452 | .replace(/\b(function|return|if|else|for|while|switch|case|break|continue|const|let|var|class|new|import|from|export|default|try|catch|finally|throw|await|async|true|false|null|undefined)\b/g, '<span class="tok-keyword">$1</span>') |
| 2453 | .replace(/\b(-?\d+(?:\.\d+)?(?:e[+\-]?\d+)?)\b/gi, '<span class="tok-number">$1</span>'); |
| 2454 | |
| 2455 | html = html.replace(/@@TOK(\d+)@@/g, (_, idx) => stash[Number(idx)] || ''); |
| 2456 | return html; |
| 2457 | } |
| 2458 | |
| 2459 | function clearPreviewObjectUrl () |
| 2460 | { |
| 2461 | if (typeof STATE.previewCleanup === 'function') |
| 2462 | { |
| 2463 | try { STATE.previewCleanup(); } catch { /* ignore */ } |
| 2464 | } |
| 2465 | STATE.previewCleanup = null; |
| 2466 | STATE.previewDownloadAction = null; |
| 2467 | if (!STATE.previewObjectUrl) return; |
| 2468 | if (String(STATE.previewObjectUrl).startsWith('blob:')) |
| 2469 | { |
| 2470 | URL.revokeObjectURL(STATE.previewObjectUrl); |
| 2471 | } |
| 2472 | STATE.previewObjectUrl = null; |
| 2473 | } |
| 2474 | |
| 2475 | function ensureStylesheet (id, href) |
| 2476 | { |
| 2477 | let link = document.getElementById(id); |
| 2478 | if (link) return Promise.resolve(link); |
| 2479 | |
| 2480 | link = document.createElement('link'); |
| 2481 | link.id = id; |
| 2482 | link.rel = 'stylesheet'; |
| 2483 | link.href = href; |
| 2484 | |
| 2485 | return new Promise((resolve, reject) => |
| 2486 | { |
| 2487 | link.addEventListener('load', () => resolve(link), { once: true }); |
| 2488 | link.addEventListener('error', () => reject(new Error('Failed to load video player styles.')), { once: true }); |
| 2489 | document.head.appendChild(link); |
| 2490 | }); |
| 2491 | } |
| 2492 | |
| 2493 | function ensureScript (id, src) |
| 2494 | { |
| 2495 | let script = document.getElementById(id); |
| 2496 | if (script && window.videojs) return Promise.resolve(window.videojs); |
| 2497 | |
| 2498 | if (!script) |
| 2499 | { |
| 2500 | script = document.createElement('script'); |
| 2501 | script.id = id; |
| 2502 | script.src = src; |
| 2503 | } |
| 2504 | |
| 2505 | return new Promise((resolve, reject) => |
| 2506 | { |
| 2507 | script.addEventListener('load', () => resolve(window.videojs), { once: true }); |
| 2508 | script.addEventListener('error', () => reject(new Error('Failed to load video player script.')), { once: true }); |
| 2509 | if (!script.isConnected) document.head.appendChild(script); |
| 2510 | }); |
| 2511 | } |
| 2512 | |
| 2513 | async function ensureVideoJsLoaded () |
| 2514 | { |
| 2515 | if (window.videojs) |
| 2516 | { |
| 2517 | configureVideoJsBuffering(window.videojs); |
| 2518 | return window.videojs; |
| 2519 | } |
| 2520 | if (!videoJsLoaderPromise) |
| 2521 | { |
| 2522 | videoJsLoaderPromise = Promise.all([ |
| 2523 | ensureStylesheet('videojs-styles', '/vendor/video.js/video-js.css'), |
| 2524 | ensureScript('videojs-script', '/vendor/video.js/video.min.js'), |
| 2525 | ]).then(() => |
| 2526 | { |
| 2527 | configureVideoJsBuffering(window.videojs); |
| 2528 | return window.videojs; |
| 2529 | }); |
| 2530 | } |
| 2531 | return videoJsLoaderPromise; |
| 2532 | } |
| 2533 | |
| 2534 | function configureVideoJsBuffering (videojs) |
| 2535 | { |
| 2536 | if (! VIDEO_FORWARD_BUFFER_OVERRIDE_ENABLED) |
| 2537 | return; |
| 2538 | |
| 2539 | if (!videojs || !videojs.Vhs || videojs.__filemanagerBufferingConfigured) return; |
| 2540 | videojs.__filemanagerBufferingConfigured = true; |
| 2541 | |
| 2542 | try |
| 2543 | { |
| 2544 | videojs.Vhs.GOAL_BUFFER_LENGTH = VIDEO_FORWARD_BUFFER_SECONDS; |
| 2545 | videojs.Vhs.MAX_GOAL_BUFFER_LENGTH = VIDEO_FORWARD_BUFFER_SECONDS; |
| 2546 | } catch |
| 2547 | { |
| 2548 | // Ignore builds that do not expose VHS buffer configuration. |
| 2549 | } |
| 2550 | } |
| 2551 | |
| 2552 | async function createVideoStreamSessionForItem (item) |
| 2553 | { |
| 2554 | return api('POST', '/files/video-stream', { filePath: item.path }); |
| 2555 | } |
| 2556 | |
| 2557 | async function releaseVideoStreamSession (sessionId, opts = {}) |
| 2558 | { |
| 2559 | const id = String(sessionId || '').trim(); |
| 2560 | if (!id) return; |
| 2561 | |
| 2562 | await api('DELETE', `/files/video-stream/${encodeURIComponent(id)}`, null, { |
| 2563 | keepalive: !!opts.keepalive, |
| 2564 | noAutoLogout: true, |
| 2565 | }).catch(() => null); |
| 2566 | } |
| 2567 | |
| 2568 | function releaseActivePreviewVideoStreamSession (opts = {}) |
| 2569 | { |
| 2570 | const sessionId = String(STATE.previewVideoStreamSessionId || '').trim(); |
| 2571 | if (!sessionId) return; |
| 2572 | STATE.previewVideoStreamSessionId = null; |
| 2573 | void releaseVideoStreamSession(sessionId, opts); |
| 2574 | } |
| 2575 | |
| 2576 | async function preparePreviewDownload (item) |
| 2577 | { |
| 2578 | const blob = await fetchFileBlob(item); |
| 2579 | if (!blob) |
| 2580 | { |
| 2581 | toast('Download failed.', 'err'); |
| 2582 | return; |
| 2583 | } |
| 2584 | |
| 2585 | const objectUrl = URL.createObjectURL(blob); |
| 2586 | triggerDownload(item.name, objectUrl); |
| 2587 | setTimeout(() => URL.revokeObjectURL(objectUrl), 60 * 1000); |
| 2588 | } |
| 2589 | |
| 2590 | async function renderStreamedVideoPreview (item, targetEl) |
| 2591 | { |
| 2592 | const videojs = await ensureVideoJsLoaded(); |
| 2593 | const session = await createVideoStreamSessionForItem(item); |
| 2594 | STATE.previewVideoStreamSessionId = String(session.sessionId || '').trim() || null; |
| 2595 | const prefs = loadUserVideoPrefs(); |
| 2596 | applyUserVideoTextTrackPrefs(); |
| 2597 | |
| 2598 | if ((session.subtitleSummary && session.subtitleSummary.total > 0) && !(session.subtitleTracks || []).length) |
| 2599 | { |
| 2600 | toast('This video has subtitle tracks, but none are compatible with web playback.', 'err'); |
| 2601 | } |
| 2602 | |
| 2603 | STATE.previewDownloadAction = () => preparePreviewDownload(item); |
| 2604 | |
| 2605 | const video = document.createElement('video'); |
| 2606 | video.className = 'video-js vjs-big-play-centered preview-media preview-video-js'; |
| 2607 | video.controls = true; |
| 2608 | video.preload = 'auto'; |
| 2609 | video.playsInline = true; |
| 2610 | targetEl.classList.add('preview-expand-content--video'); |
| 2611 | targetEl.appendChild(video); |
| 2612 | |
| 2613 | const player = videojs(video, { |
| 2614 | controls: true, |
| 2615 | fluid: false, |
| 2616 | fill: true, |
| 2617 | responsive: false, |
| 2618 | preload: 'auto', |
| 2619 | controlBar: { |
| 2620 | currentTimeDisplay: true, |
| 2621 | timeDivider: true, |
| 2622 | durationDisplay: true, |
| 2623 | remainingTimeDisplay: false, |
| 2624 | }, |
| 2625 | sources: [{ src: session.playlistUrl, type: 'application/x-mpegURL' }], |
| 2626 | tracks: (session.subtitleTracks || []).map((track) => ({ |
| 2627 | kind: 'subtitles', |
| 2628 | src: track.src, |
| 2629 | srclang: track.language || 'und', |
| 2630 | label: track.label, |
| 2631 | default: !!track.default, |
| 2632 | })), |
| 2633 | }); |
| 2634 | |
| 2635 | const trackPrefs = bindUserVideoTrackPrefs(player, prefs); |
| 2636 | |
| 2637 | ensureVideoPlaybackUi(player, session.durationSeconds); |
| 2638 | |
| 2639 | let sentPartway = false; |
| 2640 | let sentFully = false; |
| 2641 | const markWatch = async () => |
| 2642 | { |
| 2643 | let ratio = 0; |
| 2644 | try |
| 2645 | { |
| 2646 | const duration = Number(player.duration()); |
| 2647 | const current = Number(player.currentTime()); |
| 2648 | if (Number.isFinite(duration) && duration > 0 && Number.isFinite(current)) |
| 2649 | { |
| 2650 | ratio = current / duration; |
| 2651 | } |
| 2652 | } catch |
| 2653 | { |
| 2654 | return; |
| 2655 | } |
| 2656 | |
| 2657 | if (ratio >= 0.7) |
| 2658 | { |
| 2659 | if (sentFully) return; |
| 2660 | sentPartway = true; |
| 2661 | sentFully = true; |
| 2662 | void reportWatchProgress(item.path, ratio); |
| 2663 | return; |
| 2664 | } |
| 2665 | |
| 2666 | if (ratio >= 0.05) |
| 2667 | { |
| 2668 | if (sentPartway) return; |
| 2669 | sentPartway = true; |
| 2670 | void reportWatchProgress(item.path, ratio); |
| 2671 | } |
| 2672 | }; |
| 2673 | |
| 2674 | player.ready(() => |
| 2675 | { |
| 2676 | const volume = Number(prefs.volume); |
| 2677 | if (Number.isFinite(volume)) |
| 2678 | { |
| 2679 | player.volume(Math.max(0, Math.min(1, volume))); |
| 2680 | } |
| 2681 | trackPrefs.applySavedTracks(); |
| 2682 | }); |
| 2683 | |
| 2684 | player.on('loadedmetadata', trackPrefs.applySavedTracks); |
| 2685 | player.on('loadedplaylist', trackPrefs.applySavedTracks); |
| 2686 | |
| 2687 | player.on('timeupdate', markWatch); |
| 2688 | player.on('ended', () => |
| 2689 | { |
| 2690 | sentPartway = true; |
| 2691 | sentFully = true; |
| 2692 | void reportWatchProgress(item.path, 1); |
| 2693 | }); |
| 2694 | player.on('volumechange', () => |
| 2695 | { |
| 2696 | const v = Number(player.volume()); |
| 2697 | if (Number.isFinite(v)) saveUserVideoPrefs({ volume: v }); |
| 2698 | }); |
| 2699 | |
| 2700 | STATE.previewCleanup = () => |
| 2701 | { |
| 2702 | releaseActivePreviewVideoStreamSession(); |
| 2703 | try { markWatch(); } catch { /* ignore */ } |
| 2704 | try { trackPrefs.captureSelectedTracks(); } catch { /* ignore */ } |
| 2705 | try { trackPrefs.detach(); } catch { /* ignore */ } |
| 2706 | try { player.dispose(); } catch { /* ignore */ } |
| 2707 | }; |
| 2708 | } |
| 2709 | |
| 2710 | function fileAccentColor (name) |
| 2711 | { |
| 2712 | const ext = extOf(name || ''); |
| 2713 | if (IMAGE_EXTS.has(ext)) return '#3fcf8e'; |
| 2714 | if (VIDEO_EXTS.has(ext)) return '#e05c6e'; |
| 2715 | if (AUDIO_EXTS.has(ext)) return '#c084fc'; |
| 2716 | if (DOC_EXTS.has(ext)) return '#f97316'; |
| 2717 | if (CODE_EXTS.has(ext)) return '#38bdf8'; |
| 2718 | if (ARCHIVE_EXTS.has(ext)) return '#facc15'; |
| 2719 | return '#7880a0'; |
| 2720 | } |
| 2721 | |
| 2722 | function animateRect (el, fromRect, toRect, opts = {}) |
| 2723 | { |
| 2724 | const duration = opts.duration == null ? 260 : opts.duration; |
| 2725 | const easeOut = (t) => 1 - Math.pow(1 - t, 3); |
| 2726 | |
| 2727 | el.style.left = `${fromRect.left}px`; |
| 2728 | el.style.top = `${fromRect.top}px`; |
| 2729 | el.style.width = `${fromRect.width}px`; |
| 2730 | el.style.height = `${fromRect.height}px`; |
| 2731 | |
| 2732 | return new Promise((resolve) => |
| 2733 | { |
| 2734 | const t0 = performance.now(); |
| 2735 | |
| 2736 | function frame (now) |
| 2737 | { |
| 2738 | const raw = Math.min((now - t0) / duration, 1); |
| 2739 | const t = easeOut(raw); |
| 2740 | |
| 2741 | const left = fromRect.left + (toRect.left - fromRect.left) * t; |
| 2742 | const top = fromRect.top + (toRect.top - fromRect.top) * t; |
| 2743 | const width = fromRect.width + (toRect.width - fromRect.width) * t; |
| 2744 | const height = fromRect.height + (toRect.height - fromRect.height) * t; |
| 2745 | |
| 2746 | el.style.left = `${left}px`; |
| 2747 | el.style.top = `${top}px`; |
| 2748 | el.style.width = `${width}px`; |
| 2749 | el.style.height = `${height}px`; |
| 2750 | |
| 2751 | if (raw < 1) |
| 2752 | { |
| 2753 | requestAnimationFrame(frame); |
| 2754 | } else |
| 2755 | { |
| 2756 | resolve(); |
| 2757 | } |
| 2758 | } |
| 2759 | |
| 2760 | requestAnimationFrame(frame); |
| 2761 | }); |
| 2762 | } |
| 2763 | |
| 2764 | async function openExpandedTilePreview (item, tileEl, sourceSvgEl, loadPreviewContent) |
| 2765 | { |
| 2766 | if (!tileEl || !sourceSvgEl) return false; |
| 2767 | |
| 2768 | if (STATE.previewExpandState) |
| 2769 | { |
| 2770 | await closeExpandedTilePreview(); |
| 2771 | } |
| 2772 | |
| 2773 | const iconEl = tileEl.querySelector('.icon'); |
| 2774 | const nameEl = tileEl.querySelector('.name'); |
| 2775 | if (!iconEl) return false; |
| 2776 | |
| 2777 | const startRect = tileEl.getBoundingClientRect(); |
| 2778 | const targetW = Math.min(window.innerWidth * 0.94, 1100); |
| 2779 | const targetH = Math.min(window.innerHeight * 0.9, 860); |
| 2780 | const targetRect = { |
| 2781 | left: (window.innerWidth - targetW) / 2, |
| 2782 | top: (window.innerHeight - targetH) / 2, |
| 2783 | width: targetW, |
| 2784 | height: targetH, |
| 2785 | }; |
| 2786 | |
| 2787 | const backdrop = document.createElement('div'); |
| 2788 | backdrop.className = 'preview-backdrop'; |
| 2789 | document.body.appendChild(backdrop); |
| 2790 | |
| 2791 | const parent = tileEl.parentNode; |
| 2792 | const nextSibling = tileEl.nextSibling; |
| 2793 | const iconHtml = iconEl.innerHTML; |
| 2794 | const originalIconSvg = iconEl.querySelector('svg'); |
| 2795 | |
| 2796 | tileEl.remove(); |
| 2797 | document.body.appendChild(tileEl); |
| 2798 | tileEl.classList.add('file-item--preview'); |
| 2799 | tileEl.style.setProperty('--preview-accent', fileAccentColor(item.name)); |
| 2800 | tileEl.style.position = 'fixed'; |
| 2801 | tileEl.style.left = `${startRect.left}px`; |
| 2802 | tileEl.style.top = `${startRect.top}px`; |
| 2803 | tileEl.style.width = `${startRect.width}px`; |
| 2804 | tileEl.style.height = `${startRect.height}px`; |
| 2805 | tileEl.style.margin = '0'; |
| 2806 | tileEl.style.zIndex = '10000'; |
| 2807 | |
| 2808 | if (nameEl) nameEl.style.display = 'none'; |
| 2809 | |
| 2810 | const titleEl = document.createElement('div'); |
| 2811 | titleEl.className = 'preview-expand-title'; |
| 2812 | titleEl.textContent = item.name; |
| 2813 | |
| 2814 | const closeBtn = document.createElement('button'); |
| 2815 | closeBtn.className = 'preview-expand-close'; |
| 2816 | closeBtn.type = 'button'; |
| 2817 | closeBtn.textContent = '×'; |
| 2818 | closeBtn.setAttribute('aria-label', 'Close preview'); |
| 2819 | |
| 2820 | const dlBtn = document.createElement('button'); |
| 2821 | dlBtn.className = 'preview-expand-download'; |
| 2822 | dlBtn.type = 'button'; |
| 2823 | dlBtn.textContent = 'Download'; |
| 2824 | dlBtn.addEventListener('click', async (e) => |
| 2825 | { |
| 2826 | e.stopPropagation(); |
| 2827 | if (STATE.previewDownloadAction) |
| 2828 | { |
| 2829 | await STATE.previewDownloadAction(); |
| 2830 | return; |
| 2831 | } |
| 2832 | if (!STATE.previewObjectUrl) |
| 2833 | { |
| 2834 | toast('Preview still loading.', 'err'); |
| 2835 | return; |
| 2836 | } |
| 2837 | triggerDownload(item.name, STATE.previewObjectUrl); |
| 2838 | }); |
| 2839 | |
| 2840 | const shareBtn = document.createElement('button'); |
| 2841 | shareBtn.className = 'preview-expand-share'; |
| 2842 | shareBtn.type = 'button'; |
| 2843 | shareBtn.textContent = 'Share'; |
| 2844 | shareBtn.addEventListener('click', (e) => |
| 2845 | { |
| 2846 | e.stopPropagation(); |
| 2847 | openShareModal(item); |
| 2848 | }); |
| 2849 | |
| 2850 | const actionsEl = document.createElement('div'); |
| 2851 | actionsEl.className = 'preview-expand-actions'; |
| 2852 | actionsEl.appendChild(shareBtn); |
| 2853 | actionsEl.appendChild(dlBtn); |
| 2854 | |
| 2855 | iconEl.innerHTML = ''; |
| 2856 | |
| 2857 | if (originalIconSvg) |
| 2858 | { |
| 2859 | const outline = originalIconSvg.cloneNode(true); |
| 2860 | outline.classList.add('preview-expand-outline'); |
| 2861 | iconEl.appendChild(outline); |
| 2862 | } |
| 2863 | |
| 2864 | const previewMount = document.createElement('div'); |
| 2865 | previewMount.className = 'preview-expand-content'; |
| 2866 | iconEl.appendChild(previewMount); |
| 2867 | |
| 2868 | // Show spinner during expansion animation; content loads after it finishes |
| 2869 | const spinner = document.createElement('div'); |
| 2870 | spinner.className = 'preview-loading-spinner'; |
| 2871 | previewMount.appendChild(spinner); |
| 2872 | |
| 2873 | tileEl.insertBefore(titleEl, tileEl.firstChild); |
| 2874 | tileEl.appendChild(closeBtn); |
| 2875 | tileEl.appendChild(actionsEl); |
| 2876 | |
| 2877 | STATE.previewExpandState = { |
| 2878 | item, |
| 2879 | requireExplicitClose: VIDEO_EXTS.has(extOf(item.name)), |
| 2880 | tileEl, |
| 2881 | sourceSvgEl, |
| 2882 | parent, |
| 2883 | nextSibling, |
| 2884 | iconEl, |
| 2885 | iconHtml, |
| 2886 | nameEl, |
| 2887 | backdrop, |
| 2888 | closeBtn, |
| 2889 | dlBtn, |
| 2890 | shareBtn, |
| 2891 | actionsEl, |
| 2892 | titleEl, |
| 2893 | previewMount, |
| 2894 | startRect, |
| 2895 | }; |
| 2896 | |
| 2897 | const onBackdrop = (e) => |
| 2898 | { |
| 2899 | if (e.target === backdrop) closePreview(); |
| 2900 | }; |
| 2901 | const onClose = () => closePreview({ force: true }); |
| 2902 | backdrop.addEventListener('click', onBackdrop); |
| 2903 | closeBtn.addEventListener('click', onClose); |
| 2904 | STATE.previewExpandState.onBackdrop = onBackdrop; |
| 2905 | STATE.previewExpandState.onClose = onClose; |
| 2906 | |
| 2907 | requestAnimationFrame(() => backdrop.classList.add('visible')); |
| 2908 | await animateRect(tileEl, startRect, targetRect); |
| 2909 | |
| 2910 | tileEl.style.left = `${targetRect.left}px`; |
| 2911 | tileEl.style.top = `${targetRect.top}px`; |
| 2912 | tileEl.style.width = `${targetRect.width}px`; |
| 2913 | tileEl.style.height = `${targetRect.height}px`; |
| 2914 | |
| 2915 | try |
| 2916 | { |
| 2917 | await loadPreviewContent(previewMount); |
| 2918 | } catch |
| 2919 | { |
| 2920 | if (previewMount.isConnected) |
| 2921 | { |
| 2922 | previewMount.innerHTML = ''; |
| 2923 | const msg = document.createElement('p'); |
| 2924 | msg.className = 'preview-unsupported'; |
| 2925 | msg.textContent = 'Preview failed to load. You can try again.'; |
| 2926 | previewMount.appendChild(msg); |
| 2927 | } |
| 2928 | } |
| 2929 | |
| 2930 | return true; |
| 2931 | } |
| 2932 | |
| 2933 | async function closeExpandedTilePreview () |
| 2934 | { |
| 2935 | const st = STATE.previewExpandState; |
| 2936 | if (!st) return; |
| 2937 | |
| 2938 | st.backdrop.classList.remove('visible'); |
| 2939 | if (st.backdrop && st.onBackdrop) st.backdrop.removeEventListener('click', st.onBackdrop); |
| 2940 | if (st.closeBtn && st.onClose) st.closeBtn.removeEventListener('click', st.onClose); |
| 2941 | |
| 2942 | const fromRect = st.tileEl.getBoundingClientRect(); |
| 2943 | await animateRect(st.tileEl, fromRect, st.startRect, { duration: 220 }); |
| 2944 | |
| 2945 | st.tileEl.classList.remove('file-item--preview'); |
| 2946 | st.tileEl.style.position = ''; |
| 2947 | st.tileEl.style.left = ''; |
| 2948 | st.tileEl.style.top = ''; |
| 2949 | st.tileEl.style.width = ''; |
| 2950 | st.tileEl.style.height = ''; |
| 2951 | st.tileEl.style.margin = ''; |
| 2952 | st.tileEl.style.zIndex = ''; |
| 2953 | |
| 2954 | if (st.titleEl) st.titleEl.remove(); |
| 2955 | if (st.closeBtn) st.closeBtn.remove(); |
| 2956 | if (st.actionsEl) st.actionsEl.remove(); |
| 2957 | if (st.iconEl) st.iconEl.innerHTML = st.iconHtml; |
| 2958 | if (st.nameEl) st.nameEl.style.display = ''; |
| 2959 | |
| 2960 | if (st.parent) |
| 2961 | { |
| 2962 | if (st.nextSibling && st.nextSibling.parentNode === st.parent) |
| 2963 | { |
| 2964 | st.parent.insertBefore(st.tileEl, st.nextSibling); |
| 2965 | } else |
| 2966 | { |
| 2967 | st.parent.appendChild(st.tileEl); |
| 2968 | } |
| 2969 | } |
| 2970 | |
| 2971 | if (st.backdrop) st.backdrop.remove(); |
| 2972 | STATE.previewExpandState = null; |
| 2973 | } |
| 2974 | |
| 2975 | async function closePreview (opts = {}) |
| 2976 | { |
| 2977 | if (STATE.previewClosing) return; |
| 2978 | if (STATE.previewExpandState) |
| 2979 | { |
| 2980 | if (STATE.previewExpandState.requireExplicitClose && !opts.force) |
| 2981 | { |
| 2982 | return; |
| 2983 | } |
| 2984 | |
| 2985 | STATE.previewClosing = true; |
| 2986 | clearPreviewObjectUrl(); |
| 2987 | try |
| 2988 | { |
| 2989 | await closeExpandedTilePreview(); |
| 2990 | STATE.previewSourceEl = null; |
| 2991 | } finally |
| 2992 | { |
| 2993 | STATE.previewClosing = false; |
| 2994 | } |
| 2995 | } |
| 2996 | } |
| 2997 | |
| 2998 | async function fetchFileBlob (item) |
| 2999 | { |
| 3000 | const url = `/api/files/download?file=${encodeURIComponent(item.path)}`; |
| 3001 | try |
| 3002 | { |
| 3003 | const res = await fetch(url, { |
| 3004 | headers: { |
| 3005 | Authorization: 'Bearer ' + STATE.token, |
| 3006 | 'X-Fp': getFingerprint(), |
| 3007 | }, |
| 3008 | }); |
| 3009 | if (!res.ok) throw new Error('Download failed.'); |
| 3010 | return await res.blob(); |
| 3011 | } catch |
| 3012 | { |
| 3013 | return null; |
| 3014 | } |
| 3015 | } |
| 3016 | |
| 3017 | function triggerDownload (filename, objectUrl) |
| 3018 | { |
| 3019 | const a = document.createElement('a'); |
| 3020 | a.href = objectUrl; |
| 3021 | a.download = filename; |
| 3022 | a.click(); |
| 3023 | } |
| 3024 | |
| 3025 | async function renderPreviewBody (item, blob, objectUrl, targetEl = null) |
| 3026 | { |
| 3027 | const body = targetEl || document.getElementById('preview-body'); |
| 3028 | body.innerHTML = ''; |
| 3029 | |
| 3030 | const mime = String(blob.type || '').toLowerCase(); |
| 3031 | const previewable = isInlinePreviewableBlob(blob, item.name); |
| 3032 | |
| 3033 | if (!previewable) |
| 3034 | { |
| 3035 | const msg = document.createElement('p'); |
| 3036 | msg.className = 'preview-unsupported'; |
| 3037 | msg.textContent = 'This file cannot be previewed, but you can download it with the button below.'; |
| 3038 | body.appendChild(msg); |
| 3039 | return; |
| 3040 | } |
| 3041 | |
| 3042 | if (/^image\//.test(mime) || IMAGE_EXTS.has(extOf(item.name))) |
| 3043 | { |
| 3044 | const img = document.createElement('img'); |
| 3045 | img.className = 'preview-media'; |
| 3046 | img.src = objectUrl; |
| 3047 | img.alt = item.name; |
| 3048 | body.appendChild(img); |
| 3049 | return; |
| 3050 | } |
| 3051 | |
| 3052 | if (/^video\//.test(mime) || VIDEO_EXTS.has(extOf(item.name))) |
| 3053 | { |
| 3054 | const video = document.createElement('video'); |
| 3055 | video.className = 'preview-media'; |
| 3056 | video.src = objectUrl; |
| 3057 | video.controls = true; |
| 3058 | video.preload = 'metadata'; |
| 3059 | body.appendChild(video); |
| 3060 | return; |
| 3061 | } |
| 3062 | |
| 3063 | if (/^audio\//.test(mime) || AUDIO_EXTS.has(extOf(item.name))) |
| 3064 | { |
| 3065 | const audio = document.createElement('audio'); |
| 3066 | audio.className = 'preview-audio'; |
| 3067 | audio.src = objectUrl; |
| 3068 | audio.controls = true; |
| 3069 | body.appendChild(audio); |
| 3070 | return; |
| 3071 | } |
| 3072 | |
| 3073 | if (mime === 'application/pdf') |
| 3074 | { |
| 3075 | const frame = document.createElement('iframe'); |
| 3076 | frame.className = 'preview-frame'; |
| 3077 | frame.src = objectUrl; |
| 3078 | frame.title = item.name; |
| 3079 | body.appendChild(frame); |
| 3080 | return; |
| 3081 | } |
| 3082 | |
| 3083 | if (isTextLikeBlob(blob, item.name)) |
| 3084 | { |
| 3085 | const text = await blob.text(); |
| 3086 | const lang = detectCodeLanguage(item.name, mime); |
| 3087 | const formatted = prettyPrintCode(text, lang); |
| 3088 | const pre = document.createElement('pre'); |
| 3089 | pre.className = 'preview-text preview-code'; |
| 3090 | pre.innerHTML = highlightCode(formatted, lang); |
| 3091 | body.appendChild(pre); |
| 3092 | return; |
| 3093 | } |
| 3094 | |
| 3095 | const msg = document.createElement('p'); |
| 3096 | msg.className = 'preview-unsupported'; |
| 3097 | msg.textContent = 'This file cannot be previewed, but you can download it with the button below.'; |
| 3098 | body.appendChild(msg); |
| 3099 | } |
| 3100 | |
| 3101 | async function downloadOrView (item, sourceSvgEl = null) |
| 3102 | { |
| 3103 | if (STATE.previewExpandState) |
| 3104 | { |
| 3105 | await closePreview({ force: true }); |
| 3106 | } |
| 3107 | |
| 3108 | const sourceTileEl = sourceSvgEl ? sourceSvgEl.closest('.file-item') : null; |
| 3109 | if (sourceTileEl) |
| 3110 | { |
| 3111 | STATE.previewSourceEl = sourceSvgEl; |
| 3112 | const expanded = await openExpandedTilePreview(item, sourceTileEl, sourceSvgEl, async (previewMount) => |
| 3113 | { |
| 3114 | if (VIDEO_EXTS.has(extOf(item.name))) |
| 3115 | { |
| 3116 | clearPreviewObjectUrl(); |
| 3117 | previewMount.innerHTML = ''; |
| 3118 | await renderStreamedVideoPreview(item, previewMount); |
| 3119 | return; |
| 3120 | } |
| 3121 | |
| 3122 | const blob = await fetchFileBlob(item); |
| 3123 | if (!blob) throw new Error('Download failed'); |
| 3124 | |
| 3125 | clearPreviewObjectUrl(); |
| 3126 | const objectUrl = URL.createObjectURL(blob); |
| 3127 | STATE.previewObjectUrl = objectUrl; |
| 3128 | |
| 3129 | if (!previewMount.isConnected) return; |
| 3130 | |
| 3131 | previewMount.innerHTML = ''; |
| 3132 | await renderPreviewBody(item, blob, objectUrl, previewMount); |
| 3133 | }); |
| 3134 | if (expanded) return; |
| 3135 | } |
| 3136 | |
| 3137 | toast('Preview unavailable — no source tile found.', 'err'); |
| 3138 | } |
| 3139 | |
| 3140 | // ─────────────────────────────────────────────────────────────────────────── |
| 3141 | // UPLOAD |
| 3142 | // ─────────────────────────────────────────────────────────────────────────── |
| 3143 | |
| 3144 | function canWrite (item = null) |
| 3145 | { |
| 3146 | if (STATE.isAdmin) return true; |
| 3147 | const root = item && item._root |
| 3148 | ? item._root |
| 3149 | : (STATE.currentRoot || (item ? resolveRootForPath(item.path) : null)); |
| 3150 | if (!root) return false; |
| 3151 | const p = STATE.permissions[rootPermissionLabel(root)]; |
| 3152 | return p && p.write; |
| 3153 | } |
| 3154 | |
| 3155 | async function uploadFiles (fileList) |
| 3156 | { |
| 3157 | if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; } |
| 3158 | if (!canWrite()) { toast('No write access.', 'err'); return; } |
| 3159 | |
| 3160 | const files = Array.from(fileList || []); |
| 3161 | if (!files.length) return; |
| 3162 | |
| 3163 | // Show upload bar |
| 3164 | const wrap = document.createElement('div'); |
| 3165 | wrap.className = 'upload-bar-wrap'; |
| 3166 | wrap.innerHTML = `<span>Preparing upload…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`; |
| 3167 | document.body.appendChild(wrap); |
| 3168 | STATE.uploadInProgress = true; |
| 3169 | |
| 3170 | try |
| 3171 | { |
| 3172 | const existingNames = await listDirNameSet(STATE.currentDir); |
| 3173 | let done = 0; |
| 3174 | let uploaded = 0; |
| 3175 | |
| 3176 | for (const original of files) |
| 3177 | { |
| 3178 | let fileToUpload = original; |
| 3179 | |
| 3180 | if (existingNames.has(original.name)) |
| 3181 | { |
| 3182 | const suggested = nextAvailableName(original.name, existingNames); |
| 3183 | const decision = await showFileConflictChoice(original.name, suggested, 'upload'); |
| 3184 | if (decision === 'cancel') |
| 3185 | { |
| 3186 | done++; |
| 3187 | wrap.querySelector('span').textContent = `Uploading ${done} / ${files.length} file(s)…`; |
| 3188 | wrap.querySelector('.upload-bar-fill').style.width = (done / files.length * 100) + '%'; |
| 3189 | continue; |
| 3190 | } |
| 3191 | |
| 3192 | if (decision === 'rename') |
| 3193 | { |
| 3194 | fileToUpload = cloneFileWithName(original, suggested); |
| 3195 | } |
| 3196 | } |
| 3197 | |
| 3198 | await uploadSingleFile(fileToUpload, STATE.currentDir); |
| 3199 | existingNames.add(fileToUpload.name); |
| 3200 | done++; |
| 3201 | uploaded++; |
| 3202 | wrap.querySelector('span').textContent = `Uploading ${done} / ${files.length} file(s)…`; |
| 3203 | wrap.querySelector('.upload-bar-fill').style.width = (done / files.length * 100) + '%'; |
| 3204 | } |
| 3205 | |
| 3206 | toast(`Uploaded ${uploaded} file(s).`, 'ok'); |
| 3207 | await navigateTo(STATE.currentDir, STATE.currentRoot); |
| 3208 | } catch (err) |
| 3209 | { |
| 3210 | toast(err.message, 'err'); |
| 3211 | } finally |
| 3212 | { |
| 3213 | STATE.uploadInProgress = false; |
| 3214 | wrap.remove(); |
| 3215 | } |
| 3216 | } |
| 3217 | |
| 3218 | async function uploadSingleFile (file, targetDir) |
| 3219 | { |
| 3220 | const formData = new FormData(); |
| 3221 | formData.append('files', file); |
| 3222 | |
| 3223 | await new Promise((resolve, reject) => |
| 3224 | { |
| 3225 | const xhr = new XMLHttpRequest(); |
| 3226 | xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(targetDir)}`); |
| 3227 | xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token); |
| 3228 | xhr.setRequestHeader('X-Fp', getFingerprint()); |
| 3229 | xhr.setRequestHeader('X-Upload-Size', String(file.size || 0)); |
| 3230 | xhr.onload = () => xhr.status === 200 |
| 3231 | ? resolve() |
| 3232 | : reject(new Error((JSON.parse(xhr.responseText) || {}).error || 'Upload failed')); |
| 3233 | xhr.onerror = () => reject(new Error('Network error')); |
| 3234 | xhr.send(formData); |
| 3235 | }); |
| 3236 | } |
| 3237 | |
| 3238 | async function ensureServerDir (baseDir, relativeDir) |
| 3239 | { |
| 3240 | const parts = String(relativeDir || '').split(/[\\/]/).filter(Boolean); |
| 3241 | let current = baseDir; |
| 3242 | for (const part of parts) |
| 3243 | { |
| 3244 | try |
| 3245 | { |
| 3246 | const resp = await api('POST', '/files/mkdir', { dir: current, name: part }); |
| 3247 | current = resp && resp.path ? resp.path : joinServerPath(current, part); |
| 3248 | } catch (err) |
| 3249 | { |
| 3250 | if (!/exist|EEXIST/i.test(err.message || '')) throw err; |
| 3251 | current = joinServerPath(current, part); |
| 3252 | } |
| 3253 | } |
| 3254 | return current; |
| 3255 | } |
| 3256 | |
| 3257 | async function uploadFolderInputFiles (fileList) |
| 3258 | { |
| 3259 | if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; } |
| 3260 | if (!canWrite()) { toast('No write access.', 'err'); return; } |
| 3261 | if (!fileList || !fileList.length) return; |
| 3262 | |
| 3263 | const files = Array.from(fileList); |
| 3264 | const total = files.length; |
| 3265 | let done = 0; |
| 3266 | |
| 3267 | const wrap = document.createElement('div'); |
| 3268 | wrap.className = 'upload-bar-wrap'; |
| 3269 | wrap.innerHTML = `<span>Preparing folder upload…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`; |
| 3270 | document.body.appendChild(wrap); |
| 3271 | STATE.uploadInProgress = true; |
| 3272 | |
| 3273 | try |
| 3274 | { |
| 3275 | const dirCache = new Map(); |
| 3276 | dirCache.set('', STATE.currentDir); |
| 3277 | |
| 3278 | for (const file of files) |
| 3279 | { |
| 3280 | const rel = file.webkitRelativePath || file.name; |
| 3281 | const relParts = rel.split(/[\\/]/).filter(Boolean); |
| 3282 | const relDir = relParts.slice(0, -1).join('/'); |
| 3283 | |
| 3284 | if (!dirCache.has(relDir)) |
| 3285 | { |
| 3286 | const parentRel = relParts.slice(0, -2).join('/'); |
| 3287 | const parentAbs = dirCache.get(parentRel) || await ensureServerDir(STATE.currentDir, parentRel); |
| 3288 | const thisName = relParts[relParts.length - 2]; |
| 3289 | |
| 3290 | try |
| 3291 | { |
| 3292 | const created = await api('POST', '/files/mkdir', { dir: parentAbs, name: thisName }); |
| 3293 | dirCache.set(relDir, created.path || joinServerPath(parentAbs, thisName)); |
| 3294 | } catch (err) |
| 3295 | { |
| 3296 | if (!/exist|EEXIST/i.test(err.message || '')) throw err; |
| 3297 | dirCache.set(relDir, joinServerPath(parentAbs, thisName)); |
| 3298 | } |
| 3299 | } |
| 3300 | |
| 3301 | const targetDir = dirCache.get(relDir) || STATE.currentDir; |
| 3302 | await uploadSingleFile(file, targetDir); |
| 3303 | done++; |
| 3304 | wrap.querySelector('span').textContent = `Uploading ${done} / ${total} file(s)…`; |
| 3305 | wrap.querySelector('.upload-bar-fill').style.width = (done / total * 100) + '%'; |
| 3306 | } |
| 3307 | |
| 3308 | toast(`Uploaded ${total} file(s).`, 'ok'); |
| 3309 | await navigateTo(STATE.currentDir, STATE.currentRoot); |
| 3310 | } catch (err) |
| 3311 | { |
| 3312 | toast(err.message, 'err'); |
| 3313 | } finally |
| 3314 | { |
| 3315 | STATE.uploadInProgress = false; |
| 3316 | wrap.remove(); |
| 3317 | } |
| 3318 | } |
| 3319 | |
| 3320 | // ─────────────────────────────────────────────────────────────────────────── |
| 3321 | // FOLDER DRAG-AND-DROP (recursive) |
| 3322 | // ─────────────────────────────────────────────────────────────────────────── |
| 3323 | |
| 3324 | /** |
| 3325 | * Reads all readEntries batches from a DirectoryReader (browsers may return |
| 3326 | * results in chunks; we must keep calling until we get an empty array). |
| 3327 | */ |
| 3328 | function readAllEntries (reader) |
| 3329 | { |
| 3330 | return new Promise((resolve, reject) => |
| 3331 | { |
| 3332 | const all = []; |
| 3333 | function next () |
| 3334 | { |
| 3335 | reader.readEntries(batch => |
| 3336 | { |
| 3337 | if (!batch.length) { resolve(all); return; } |
| 3338 | all.push(...batch); |
| 3339 | next(); |
| 3340 | }, reject); |
| 3341 | } |
| 3342 | next(); |
| 3343 | }); |
| 3344 | } |
| 3345 | |
| 3346 | /** |
| 3347 | * Recursively walk a FileSystemEntry tree, creating server-side directories |
| 3348 | * on the fly and collecting { file, targetDir } pairs for upload. |
| 3349 | */ |
| 3350 | async function collectEntries (entry, serverDir, toUpload) |
| 3351 | { |
| 3352 | if (entry.isFile) |
| 3353 | { |
| 3354 | const file = await new Promise((res, rej) => entry.file(res, rej)); |
| 3355 | toUpload.push({ file, targetDir: serverDir }); |
| 3356 | } else if (entry.isDirectory) |
| 3357 | { |
| 3358 | // Ask the server to create the directory; it returns the canonical path. |
| 3359 | let newServerDir; |
| 3360 | try |
| 3361 | { |
| 3362 | const resp = await api('POST', '/files/mkdir', { dir: serverDir, name: entry.name }); |
| 3363 | newServerDir = resp.path; |
| 3364 | } catch |
| 3365 | { |
| 3366 | // Directory may already exist — reconstruct path from what we know. |
| 3367 | // The server always returns JSON with {error} on failure, so we can |
| 3368 | // still continue by falling back to a best-effort path join. |
| 3369 | // We rely on the fact that the server separator is consistent within |
| 3370 | // a session (the list/browse API already returned paths in that format). |
| 3371 | const sep = serverDir.includes('\\') ? '\\' : '/'; |
| 3372 | newServerDir = serverDir + sep + entry.name; |
| 3373 | } |
| 3374 | const reader = entry.createReader(); |
| 3375 | const subEntries = await readAllEntries(reader); |
| 3376 | for (const sub of subEntries) |
| 3377 | { |
| 3378 | await collectEntries(sub, newServerDir, toUpload); |
| 3379 | } |
| 3380 | } |
| 3381 | } |
| 3382 | |
| 3383 | async function uploadEntries (entries) |
| 3384 | { |
| 3385 | if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; } |
| 3386 | if (!canWrite()) { toast('No write access.', 'err'); return; } |
| 3387 | |
| 3388 | const wrap = document.createElement('div'); |
| 3389 | wrap.className = 'upload-bar-wrap'; |
| 3390 | wrap.innerHTML = `<span>Scanning…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`; |
| 3391 | document.body.appendChild(wrap); |
| 3392 | STATE.uploadInProgress = true; |
| 3393 | |
| 3394 | try |
| 3395 | { |
| 3396 | const toUpload = []; |
| 3397 | for (const entry of entries) |
| 3398 | { |
| 3399 | await collectEntries(entry, STATE.currentDir, toUpload); |
| 3400 | } |
| 3401 | |
| 3402 | if (!toUpload.length) { toast('No files found.', 'err'); return; } |
| 3403 | |
| 3404 | let done = 0; |
| 3405 | const total = toUpload.length; |
| 3406 | const updateBar = () => |
| 3407 | { |
| 3408 | wrap.querySelector('span').textContent = `Uploading ${done} / ${total} file(s)…`; |
| 3409 | wrap.querySelector('.upload-bar-fill').style.width = (done / total * 100) + '%'; |
| 3410 | }; |
| 3411 | updateBar(); |
| 3412 | |
| 3413 | for (const { file, targetDir } of toUpload) |
| 3414 | { |
| 3415 | await uploadSingleFile(file, targetDir); |
| 3416 | done++; |
| 3417 | updateBar(); |
| 3418 | } |
| 3419 | |
| 3420 | toast(`Uploaded ${total} file(s).`, 'ok'); |
| 3421 | await navigateTo(STATE.currentDir, STATE.currentRoot); |
| 3422 | } catch (err) |
| 3423 | { |
| 3424 | toast(err.message, 'err'); |
| 3425 | } finally |
| 3426 | { |
| 3427 | STATE.uploadInProgress = false; |
| 3428 | wrap.remove(); |
| 3429 | } |
| 3430 | } |
| 3431 | |
| 3432 | // DRAG-AND-DROP |
| 3433 | // ─────────────────────────────────────────────────────────────────────────── |
| 3434 | |
| 3435 | function initDragDrop () |
| 3436 | { |
| 3437 | const main = document.getElementById('main-content'); |
| 3438 | const dropOvl = document.getElementById('drop-overlay'); |
| 3439 | let dragDepth = 0; |
| 3440 | |
| 3441 | main.addEventListener('dragenter', e => |
| 3442 | { |
| 3443 | e.preventDefault(); |
| 3444 | dragDepth++; |
| 3445 | dropOvl.classList.remove('hidden'); |
| 3446 | }); |
| 3447 | main.addEventListener('dragleave', () => |
| 3448 | { |
| 3449 | dragDepth--; |
| 3450 | if (dragDepth <= 0) { dragDepth = 0; dropOvl.classList.add('hidden'); } |
| 3451 | }); |
| 3452 | main.addEventListener('dragover', e => e.preventDefault()); |
| 3453 | main.addEventListener('drop', async e => |
| 3454 | { |
| 3455 | e.preventDefault(); |
| 3456 | dragDepth = 0; |
| 3457 | dropOvl.classList.add('hidden'); |
| 3458 | if (!canWrite()) { toast('No write access.', 'err'); return; } |
| 3459 | |
| 3460 | const items = Array.from(e.dataTransfer.items || []); |
| 3461 | // Use the FileSystem Entry API when available so we can handle folders. |
| 3462 | if (items.length && typeof items[0].webkitGetAsEntry === 'function') |
| 3463 | { |
| 3464 | const entries = items.map(i => i.webkitGetAsEntry()).filter(Boolean); |
| 3465 | if (entries.some(en => en.isDirectory)) |
| 3466 | { |
| 3467 | await uploadEntries(entries); |
| 3468 | return; |
| 3469 | } |
| 3470 | } |
| 3471 | // Plain files only — use the fast batch path. |
| 3472 | const files = e.dataTransfer.files; |
| 3473 | if (files.length) await uploadFiles(files); |
| 3474 | }); |
| 3475 | } |
| 3476 | |
| 3477 | // ─────────────────────────────────────────────────────────────────────────── |
| 3478 | // RENAME |
| 3479 | // ─────────────────────────────────────────────────────────────────────────── |
| 3480 | |
| 3481 | function openRenameModal (item) |
| 3482 | { |
| 3483 | const modal = document.getElementById('rename-modal'); |
| 3484 | modal.classList.remove('hidden'); |
| 3485 | const input = document.getElementById('rename-input'); |
| 3486 | input.value = item.name; |
| 3487 | input.focus(); |
| 3488 | input.select(); |
| 3489 | document.getElementById('rename-error').classList.add('hidden'); |
| 3490 | document.getElementById('rename-form').onsubmit = async (e) => |
| 3491 | { |
| 3492 | e.preventDefault(); |
| 3493 | const newName = input.value.trim(); |
| 3494 | if (!newName) return; |
| 3495 | try |
| 3496 | { |
| 3497 | if (item._root) |
| 3498 | { |
| 3499 | await api('POST', '/files/root-alias', { rootPath: item.path, alias: newName }); |
| 3500 | } else |
| 3501 | { |
| 3502 | await api('POST', '/files/rename', { from: item.path, to: newName }); |
| 3503 | } |
| 3504 | modal.classList.add('hidden'); |
| 3505 | toast(item._root ? 'Alias updated.' : 'Renamed.', 'ok'); |
| 3506 | if (item._root) |
| 3507 | { |
| 3508 | await loadRoots({ |
| 3509 | preferredDir: STATE.currentDir, |
| 3510 | preferredRootPath: (STATE.currentRoot && STATE.currentRoot.path) || item.path, |
| 3511 | }); |
| 3512 | } else |
| 3513 | { |
| 3514 | await navigateTo(STATE.currentDir, STATE.currentRoot); |
| 3515 | } |
| 3516 | } catch (err) |
| 3517 | { |
| 3518 | document.getElementById('rename-error').textContent = err.message; |
| 3519 | document.getElementById('rename-error').classList.remove('hidden'); |
| 3520 | } |
| 3521 | }; |
| 3522 | } |
| 3523 | |
| 3524 | // ─────────────────────────────────────────────────────────────────────────── |
| 3525 | // DELETE |
| 3526 | // ─────────────────────────────────────────────────────────────────────────── |
| 3527 | |
| 3528 | async function deleteItem (item) |
| 3529 | { |
| 3530 | if (!await showConfirm('Delete item', `Delete "${item.name}"? This cannot be undone.`)) return; |
| 3531 | try |
| 3532 | { |
| 3533 | await api('POST', '/files/delete', { path: item.path }); |
| 3534 | toast('Deleted.', 'ok'); |
| 3535 | closeSidebar(); |
| 3536 | await navigateTo(STATE.currentDir, STATE.currentRoot); |
| 3537 | } catch (err) |
| 3538 | { |
| 3539 | toast(err.message, 'err'); |
| 3540 | } |
| 3541 | } |
| 3542 | |
| 3543 | // ─────────────────────────────────────────────────────────────────────────── |
| 3544 | // ADMIN PANEL |
| 3545 | // ─────────────────────────────────────────────────────────────────────────── |
| 3546 | |
| 3547 | let _adminUpdateStatus = null; |
| 3548 | |
| 3549 | async function openAdminModal () |
| 3550 | { |
| 3551 | document.getElementById('admin-modal').classList.remove('hidden'); |
| 3552 | await refreshAdminConfig(); |
| 3553 | await refreshAdminUsers(); |
| 3554 | void refreshAdminUpdateStatus(); |
| 3555 | } |
| 3556 | |
| 3557 | async function refreshAdminConfig () |
| 3558 | { |
| 3559 | const data = await api('GET', '/admin/config'); |
| 3560 | if (!data) return; |
| 3561 | const container = document.getElementById('admin-paths'); |
| 3562 | container.innerHTML = ''; |
| 3563 | for (const p of data.paths) |
| 3564 | { |
| 3565 | const row = document.createElement('div'); |
| 3566 | row.className = 'path-row'; |
| 3567 | row.innerHTML = `<span>${p}</span><button data-path="${p}" title="Remove">✕</button>`; |
| 3568 | row.querySelector('button').addEventListener('click', () => |
| 3569 | { |
| 3570 | row.remove(); |
| 3571 | }); |
| 3572 | container.appendChild(row); |
| 3573 | } |
| 3574 | } |
| 3575 | |
| 3576 | async function refreshAdminUsers () |
| 3577 | { |
| 3578 | const data = await api('GET', '/admin/users'); |
| 3579 | if (!data) return; |
| 3580 | const container = document.getElementById('admin-users-list'); |
| 3581 | container.innerHTML = ''; |
| 3582 | |
| 3583 | // Need paths for permission rows |
| 3584 | const cfg = await api('GET', '/admin/config'); |
| 3585 | const paths = cfg ? (cfg.effectivePaths || []) : []; |
| 3586 | |
| 3587 | for (const u of data.users) |
| 3588 | { |
| 3589 | const row = document.createElement('div'); |
| 3590 | row.className = 'user-row'; |
| 3591 | row.innerHTML = ` |
| 3592 | <span class="user-name">${u.username}</span> |
| 3593 | ${u.isAdmin ? '<span class="user-admin-badge">Admin</span>' : ''} |
| 3594 | <button data-id="${u.id}" data-action="edit">Edit</button> |
| 3595 | ${u.username === STATE.username ? '' : `<button data-id="${u.id}" data-action="delete" class="danger">Delete</button>`} |
| 3596 | `; |
| 3597 | row.querySelector('[data-action="edit"]').addEventListener('click', () => |
| 3598 | openUserModal(u, paths)); |
| 3599 | const deleteBtn = row.querySelector('[data-action="delete"]'); |
| 3600 | if (deleteBtn) deleteBtn.addEventListener('click', async () => |
| 3601 | { |
| 3602 | if (!await showConfirm('Delete user', `Delete user "${u.username}"? This cannot be undone.`)) return; |
| 3603 | try |
| 3604 | { |
| 3605 | await api('DELETE', `/admin/users/${u.id}`); |
| 3606 | toast('User deleted.', 'ok'); |
| 3607 | await refreshAdminUsers(); |
| 3608 | } catch (err) { toast(err.message, 'err'); } |
| 3609 | }); |
| 3610 | container.appendChild(row); |
| 3611 | } |
| 3612 | } |
| 3613 | |
| 3614 | async function refreshAdminUpdateStatus () |
| 3615 | { |
| 3616 | const btn = document.getElementById('admin-shutdown-btn'); |
| 3617 | _adminUpdateStatus = null; |
| 3618 | btn.textContent = 'Shut down server'; |
| 3619 | |
| 3620 | try |
| 3621 | { |
| 3622 | const data = await api('GET', '/admin/update-status'); |
| 3623 | if (!data) return; |
| 3624 | _adminUpdateStatus = data; |
| 3625 | |
| 3626 | if (!data.underSystemd) |
| 3627 | { |
| 3628 | btn.textContent = 'Shut down server'; |
| 3629 | } |
| 3630 | else if (data.commitsAhead.length === 0) |
| 3631 | { |
| 3632 | btn.textContent = 'Restart Server'; |
| 3633 | } |
| 3634 | else |
| 3635 | { |
| 3636 | btn.textContent = 'Restart & Update'; |
| 3637 | } |
| 3638 | } |
| 3639 | catch |
| 3640 | { |
| 3641 | // Not critical; button stays as "Shut down server". |
| 3642 | } |
| 3643 | } |
| 3644 | |
| 3645 | function openUserModal (user, paths) |
| 3646 | { |
| 3647 | const modal = document.getElementById('user-modal'); |
| 3648 | modal.classList.remove('hidden'); |
| 3649 | document.getElementById('user-modal-title').textContent = user ? `Edit: ${user.username}` : 'New User'; |
| 3650 | document.getElementById('user-error').classList.add('hidden'); |
| 3651 | |
| 3652 | const usernameInput = document.getElementById('user-username'); |
| 3653 | usernameInput.value = user ? user.username : ''; |
| 3654 | usernameInput.readOnly = !!user; |
| 3655 | |
| 3656 | document.getElementById('user-password').value = ''; |
| 3657 | document.getElementById('user-is-admin').checked = user ? user.isAdmin : false; |
| 3658 | |
| 3659 | // Password placeholder |
| 3660 | document.getElementById('user-password').placeholder = |
| 3661 | user ? 'Leave blank to keep current' : 'Min 8 characters'; |
| 3662 | |
| 3663 | // Build permissions grid |
| 3664 | const permDiv = document.getElementById('user-permissions'); |
| 3665 | permDiv.innerHTML = ''; |
| 3666 | if (paths.length) |
| 3667 | { |
| 3668 | const heading = document.createElement('h4'); |
| 3669 | heading.textContent = 'Path Permissions'; |
| 3670 | permDiv.appendChild(heading); |
| 3671 | |
| 3672 | const isAdminUser = !!(user && user.isAdmin); |
| 3673 | // Mirror the is-admin checkbox so toggling it live-updates the perm rows. |
| 3674 | const adminChk = document.getElementById('user-is-admin'); |
| 3675 | const rebuildPermRows = (admin) => |
| 3676 | { |
| 3677 | permDiv.querySelectorAll('.perm-row').forEach(r => |
| 3678 | { |
| 3679 | r.querySelectorAll('input[type=checkbox]').forEach(cb => |
| 3680 | { |
| 3681 | cb.disabled = admin; |
| 3682 | if (admin) cb.checked = true; |
| 3683 | }); |
| 3684 | r.title = admin ? 'Admins always have full access' : ''; |
| 3685 | }); |
| 3686 | }; |
| 3687 | adminChk.addEventListener('change', () => rebuildPermRows(adminChk.checked)); |
| 3688 | |
| 3689 | const syncReadWriteConstraints = (row, admin = false) => |
| 3690 | { |
| 3691 | const readCb = row.querySelector('input[data-type="read"]'); |
| 3692 | const writeCb = row.querySelector('input[data-type="write"]'); |
| 3693 | if (!readCb || !writeCb) return; |
| 3694 | |
| 3695 | if (admin) |
| 3696 | { |
| 3697 | readCb.checked = true; |
| 3698 | writeCb.checked = true; |
| 3699 | readCb.disabled = true; |
| 3700 | writeCb.disabled = true; |
| 3701 | return; |
| 3702 | } |
| 3703 | |
| 3704 | readCb.disabled = false; |
| 3705 | if (!readCb.checked) |
| 3706 | { |
| 3707 | writeCb.checked = false; |
| 3708 | writeCb.disabled = true; |
| 3709 | } |
| 3710 | else |
| 3711 | { |
| 3712 | writeCb.disabled = false; |
| 3713 | } |
| 3714 | }; |
| 3715 | |
| 3716 | const syncAllReadWriteConstraints = () => |
| 3717 | { |
| 3718 | const admin = adminChk.checked; |
| 3719 | permDiv.querySelectorAll('.perm-row').forEach((row) => |
| 3720 | { |
| 3721 | syncReadWriteConstraints(row, admin); |
| 3722 | }); |
| 3723 | }; |
| 3724 | |
| 3725 | for (const p of paths) |
| 3726 | { |
| 3727 | const label = p.split(/[\\/]/).pop(); |
| 3728 | const perms = user && user.permissions ? (user.permissions[label] || {}) : {}; |
| 3729 | const row = document.createElement('div'); |
| 3730 | row.className = 'perm-row'; |
| 3731 | const readChecked = isAdminUser || perms.read; |
| 3732 | const writeChecked = isAdminUser || perms.write; |
| 3733 | row.innerHTML = ` |
| 3734 | <span class="perm-label">${label}</span> |
| 3735 | <label class="checkbox-label"><input type="checkbox" data-label="${label}" data-type="read" ${readChecked ? 'checked' : ''} ${isAdminUser ? 'disabled' : ''} /> Read</label> |
| 3736 | <label class="checkbox-label"><input type="checkbox" data-label="${label}" data-type="write" ${writeChecked ? 'checked' : ''} ${isAdminUser ? 'disabled' : ''} /> Write</label> |
| 3737 | `; |
| 3738 | if (isAdminUser) row.title = 'Admins always have full access'; |
| 3739 | const readCb = row.querySelector('input[data-type="read"]'); |
| 3740 | if (readCb) |
| 3741 | { |
| 3742 | readCb.addEventListener('change', () => |
| 3743 | { |
| 3744 | syncReadWriteConstraints(row, adminChk.checked); |
| 3745 | }); |
| 3746 | } |
| 3747 | permDiv.appendChild(row); |
| 3748 | } |
| 3749 | |
| 3750 | syncAllReadWriteConstraints(); |
| 3751 | adminChk.addEventListener('change', syncAllReadWriteConstraints); |
| 3752 | } |
| 3753 | |
| 3754 | document.getElementById('user-form').onsubmit = async (e) => |
| 3755 | { |
| 3756 | e.preventDefault(); |
| 3757 | const password = document.getElementById('user-password').value; |
| 3758 | const isAdmin = document.getElementById('user-is-admin').checked; |
| 3759 | const permissions = {}; |
| 3760 | permDiv.querySelectorAll('input[data-label]').forEach(cb => |
| 3761 | { |
| 3762 | const lbl = cb.dataset.label; |
| 3763 | if (!permissions[lbl]) permissions[lbl] = {}; |
| 3764 | permissions[lbl][cb.dataset.type] = cb.checked; |
| 3765 | }); |
| 3766 | |
| 3767 | try |
| 3768 | { |
| 3769 | if (user) |
| 3770 | { |
| 3771 | const body = { isAdmin, permissions }; |
| 3772 | if (password) body.password = password; |
| 3773 | await api('PATCH', `/admin/users/${user.id}`, body); |
| 3774 | } else |
| 3775 | { |
| 3776 | const uname = document.getElementById('user-username').value.trim(); |
| 3777 | await api('POST', '/admin/users', { username: uname, password, isAdmin, permissions }); |
| 3778 | } |
| 3779 | modal.classList.add('hidden'); |
| 3780 | toast('User saved.', 'ok'); |
| 3781 | await refreshAdminUsers(); |
| 3782 | } catch (err) |
| 3783 | { |
| 3784 | document.getElementById('user-error').textContent = err.message; |
| 3785 | document.getElementById('user-error').classList.remove('hidden'); |
| 3786 | } |
| 3787 | }; |
| 3788 | } |
| 3789 | |
| 3790 | // ─────────────────────────────────────────────────────────────────────────── |
| 3791 | // SVG ICONS |
| 3792 | // ─────────────────────────────────────────────────────────────────────────── |
| 3793 | |
| 3794 | const IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'ico', 'avif']); |
| 3795 | const VIDEO_EXTS = new Set(['mp4', 'webm', 'ogv', 'mov', 'avi', 'mkv']); |
| 3796 | const AUDIO_EXTS = new Set(['mp3', 'ogg', 'wav', 'flac', 'aac', 'm4a']); |
| 3797 | const DOC_EXTS = new Set(['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'ods', 'odp']); |
| 3798 | 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']); |
| 3799 | const ARCHIVE_EXTS = new Set(['zip', 'tar', 'gz', 'bz2', 'xz', 'rar', '7z']); |
| 3800 | const MAX_DIRECT_SVG_THUMB_BYTES = 1024 * 1024; |
| 3801 | |
| 3802 | function iconFolder (size = 52) |
| 3803 | { |
| 3804 | return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" |
| 3805 | stroke="#5b7fff" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"> |
| 3806 | <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"/> |
| 3807 | </svg>`; |
| 3808 | } |
| 3809 | |
| 3810 | function iconFile (name, size = 52) |
| 3811 | { |
| 3812 | const color = fileAccentColor(name); |
| 3813 | let symbol = ''; |
| 3814 | |
| 3815 | return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" |
| 3816 | stroke="${color}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"> |
| 3817 | <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/> |
| 3818 | <polyline points="14 2 14 8 20 8"/> |
| 3819 | </svg>`; |
| 3820 | } |
| 3821 | |
| 3822 | // ─────────────────────────────────────────────────────────────────────────── |
| 3823 | // EVENT WIRING |
| 3824 | // ─────────────────────────────────────────────────────────────────────────── |
| 3825 | |
| 3826 | // ─────────────────────────────────────────────────────────────────────────── |
| 3827 | // THUMBNAIL PREVIEWS |
| 3828 | // ─────────────────────────────────────────────────────────────────────────── |
| 3829 | |
| 3830 | function revokeThumbnails () |
| 3831 | { |
| 3832 | STATE.thumbnailUrls.forEach(u => URL.revokeObjectURL(u)); |
| 3833 | STATE.thumbnailUrls = []; |
| 3834 | } |
| 3835 | |
| 3836 | function disconnectThumbnailObserver () |
| 3837 | { |
| 3838 | if (!STATE.thumbnailObserver) return; |
| 3839 | STATE.thumbnailObserver.disconnect(); |
| 3840 | STATE.thumbnailObserver = null; |
| 3841 | } |
| 3842 | |
| 3843 | function disconnectFolderIconObserver () |
| 3844 | { |
| 3845 | if (!STATE.folderIconObserver) return; |
| 3846 | STATE.folderIconObserver.disconnect(); |
| 3847 | STATE.folderIconObserver = null; |
| 3848 | } |
| 3849 | |
| 3850 | function setThumbnailPending (iconEl, pending) |
| 3851 | { |
| 3852 | if (!iconEl) return; |
| 3853 | if (pending) |
| 3854 | { |
| 3855 | iconEl.classList.add('thumb-pending'); |
| 3856 | iconEl.dataset.thumbPending = '1'; |
| 3857 | return; |
| 3858 | } |
| 3859 | |
| 3860 | iconEl.classList.remove('thumb-pending'); |
| 3861 | delete iconEl.dataset.thumbPending; |
| 3862 | } |
| 3863 | |
| 3864 | function getThumbnailKind (name) |
| 3865 | { |
| 3866 | const ext = extOf(name || ''); |
| 3867 | if (IMAGE_EXTS.has(ext)) return 'image'; |
| 3868 | if (CODE_EXTS.has(ext)) return 'text'; |
| 3869 | return 'badge'; |
| 3870 | } |
| 3871 | |
| 3872 | function maxThumbBytesForKind (kind) |
| 3873 | { |
| 3874 | if (kind === 'image') return 15 * 1024 * 1024; |
| 3875 | if (kind === 'text') return 1024 * 1024; |
| 3876 | return 0; |
| 3877 | } |
| 3878 | |
| 3879 | function drawTokenizedLine (ctx, line, x, y) |
| 3880 | { |
| 3881 | const tokenRe = /(\/\/.*$|\/\*[\s\S]*?\*\/|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`|\b(?:function|return|if|else|for|while|switch|case|break|continue|const|let|var|class|new|import|from|export|default|try|catch|finally|throw|await|async|true|false|null|undefined)\b|\b\d+(?:\.\d+)?\b)/g; |
| 3882 | let last = 0; |
| 3883 | let cursor = x; |
| 3884 | for (const m of line.matchAll(tokenRe)) |
| 3885 | { |
| 3886 | const i = m.index == null ? 0 : m.index; |
| 3887 | if (i > last) |
| 3888 | { |
| 3889 | const plain = line.slice(last, i); |
| 3890 | ctx.fillStyle = '#dce4ff'; |
| 3891 | ctx.fillText(plain, cursor, y); |
| 3892 | cursor += ctx.measureText(plain).width; |
| 3893 | } |
| 3894 | |
| 3895 | const tok = m[0]; |
| 3896 | if (/^\/\//.test(tok) || /^\/\*/.test(tok)) ctx.fillStyle = '#6f7f9a'; |
| 3897 | else if (/^['"`]/.test(tok)) ctx.fillStyle = '#9ee37d'; |
| 3898 | else if (/^\d/.test(tok)) ctx.fillStyle = '#f8c46a'; |
| 3899 | else ctx.fillStyle = '#8bb4ff'; |
| 3900 | |
| 3901 | ctx.fillText(tok, cursor, y); |
| 3902 | cursor += ctx.measureText(tok).width; |
| 3903 | last = i + tok.length; |
| 3904 | } |
| 3905 | |
| 3906 | if (last < line.length) |
| 3907 | { |
| 3908 | const tail = line.slice(last); |
| 3909 | ctx.fillStyle = '#dce4ff'; |
| 3910 | ctx.fillText(tail, cursor, y); |
| 3911 | } |
| 3912 | } |
| 3913 | |
| 3914 | function textThumbnailDataUrl (text) |
| 3915 | { |
| 3916 | const canvas = document.createElement('canvas'); |
| 3917 | canvas.width = 160; |
| 3918 | canvas.height = 200; |
| 3919 | const ctx = canvas.getContext('2d'); |
| 3920 | if (!ctx) return null; |
| 3921 | |
| 3922 | ctx.fillStyle = '#0d111a'; |
| 3923 | ctx.fillRect(0, 0, canvas.width, canvas.height); |
| 3924 | ctx.font = '8px ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace'; |
| 3925 | ctx.textBaseline = 'top'; |
| 3926 | |
| 3927 | const lines = String(text || '') |
| 3928 | .replace(/\r\n/g, '\n') |
| 3929 | .split('\n') |
| 3930 | .slice(0, 17); |
| 3931 | |
| 3932 | let y = 8; |
| 3933 | for (const line of lines) |
| 3934 | { |
| 3935 | drawTokenizedLine(ctx, line.slice(0, 42), 6, y); |
| 3936 | y += 11; |
| 3937 | if (y > 190) break; |
| 3938 | } |
| 3939 | return canvas.toDataURL('image/png'); |
| 3940 | } |
| 3941 | |
| 3942 | function badgeThumbnailDataUrl (name, kind) |
| 3943 | { |
| 3944 | const canvas = document.createElement('canvas'); |
| 3945 | canvas.width = 160; |
| 3946 | canvas.height = 200; |
| 3947 | const ctx = canvas.getContext('2d'); |
| 3948 | if (!ctx) return null; |
| 3949 | |
| 3950 | const ext = (extOf(name || '') || 'file').toUpperCase().slice(0, 5); |
| 3951 | const color = '#5b7fff'; |
| 3952 | |
| 3953 | ctx.fillStyle = '#111826'; |
| 3954 | ctx.fillRect(0, 0, 160, 200); |
| 3955 | ctx.fillStyle = color; |
| 3956 | ctx.fillRect(0, 0, 160, 28); |
| 3957 | ctx.fillStyle = '#ffffff'; |
| 3958 | ctx.font = 'bold 12px sans-serif'; |
| 3959 | ctx.textAlign = 'center'; |
| 3960 | ctx.fillText(ext, 80, 8); |
| 3961 | ctx.textAlign = 'left'; |
| 3962 | ctx.fillStyle = '#9fb1d8'; |
| 3963 | ctx.font = '10px sans-serif'; |
| 3964 | ctx.fillText('Preview', 8, 48); |
| 3965 | ctx.fillStyle = '#dce4ff'; |
| 3966 | ctx.font = 'bold 11px sans-serif'; |
| 3967 | ctx.fillText(ext, 8, 66); |
| 3968 | return canvas.toDataURL('image/png'); |
| 3969 | } |
| 3970 | |
| 3971 | async function buildThumbnailSource (item, blob, kind) |
| 3972 | { |
| 3973 | if (kind === 'text') return textThumbnailDataUrl(await blob.text()); |
| 3974 | return badgeThumbnailDataUrl(item.name, kind); |
| 3975 | } |
| 3976 | |
| 3977 | function observeThumbnailIcon (iconEl) |
| 3978 | { |
| 3979 | if (!iconEl || !iconEl.isConnected) return; |
| 3980 | if (iconEl.dataset.thumbReady === '1') return; |
| 3981 | |
| 3982 | if (!('IntersectionObserver' in window)) |
| 3983 | { |
| 3984 | void loadOneThumbnail(iconEl); |
| 3985 | return; |
| 3986 | } |
| 3987 | |
| 3988 | if (!STATE.thumbnailObserver) |
| 3989 | { |
| 3990 | STATE.thumbnailObserver = new IntersectionObserver((entries) => |
| 3991 | { |
| 3992 | for (const entry of entries) |
| 3993 | { |
| 3994 | if (!entry.isIntersecting) continue; |
| 3995 | const icon = entry.target; |
| 3996 | STATE.thumbnailObserver.unobserve(icon); |
| 3997 | void loadOneThumbnail(icon); |
| 3998 | } |
| 3999 | }, { root: null, rootMargin: THUMB_OBSERVER_ROOT_MARGIN, threshold: 0.01 }); |
| 4000 | } |
| 4001 | |
| 4002 | STATE.thumbnailObserver.observe(iconEl); |
| 4003 | } |
| 4004 | |
| 4005 | async function loadThumbnails () |
| 4006 | { |
| 4007 | const icons = Array.from(document.querySelectorAll('.icon[data-preview-path]')); |
| 4008 | for (const icon of icons) |
| 4009 | { |
| 4010 | observeThumbnailIcon(icon); |
| 4011 | } |
| 4012 | |
| 4013 | const folderIcons = Array.from(document.querySelectorAll('.icon[data-folder-path]')); |
| 4014 | for (const icon of folderIcons) |
| 4015 | { |
| 4016 | observeFolderIcon(icon); |
| 4017 | } |
| 4018 | } |
| 4019 | |
| 4020 | async function loadOneThumbnail (iconEl) |
| 4021 | { |
| 4022 | if (!iconEl.isConnected || !STATE.token) return; |
| 4023 | if (iconEl.dataset.thumbReady === '1') return; |
| 4024 | const filePath = iconEl.dataset.previewPath; |
| 4025 | const item = STATE.items.find(i => i.path === filePath); |
| 4026 | if (!item) return; |
| 4027 | |
| 4028 | const kind = getThumbnailKind(item.name); |
| 4029 | let srcUrl = null; |
| 4030 | |
| 4031 | if (kind === 'badge') |
| 4032 | { |
| 4033 | setThumbnailPending(iconEl, false); |
| 4034 | srcUrl = badgeThumbnailDataUrl(item.name, kind); |
| 4035 | } |
| 4036 | else if (kind === 'image') |
| 4037 | { |
| 4038 | const ext = extOf(item.name || ''); |
| 4039 | const useDirectSource = |
| 4040 | ext === 'ico' || |
| 4041 | ( |
| 4042 | ext === 'svg' && |
| 4043 | typeof item.size === 'number' && |
| 4044 | item.size > 0 && |
| 4045 | item.size <= MAX_DIRECT_SVG_THUMB_BYTES |
| 4046 | ); |
| 4047 | |
| 4048 | const url = useDirectSource |
| 4049 | ? `/api/files/download?file=${encodeURIComponent(filePath)}` |
| 4050 | : `/api/files/thumbnail?file=${encodeURIComponent(filePath)}`; |
| 4051 | |
| 4052 | let res; |
| 4053 | try |
| 4054 | { |
| 4055 | res = await fetch(url, { |
| 4056 | headers: { |
| 4057 | Authorization: `Bearer ${STATE.token}`, |
| 4058 | 'X-Fp': getFingerprint(), |
| 4059 | }, |
| 4060 | }); |
| 4061 | } catch |
| 4062 | { |
| 4063 | return; |
| 4064 | } |
| 4065 | |
| 4066 | if (!useDirectSource && res.status === 404) |
| 4067 | { |
| 4068 | setThumbnailPending(iconEl, true); |
| 4069 | return; |
| 4070 | } |
| 4071 | |
| 4072 | if (!res.ok || !iconEl.isConnected) return; |
| 4073 | setThumbnailPending(iconEl, false); |
| 4074 | |
| 4075 | const blob = await res.blob(); |
| 4076 | srcUrl = URL.createObjectURL(blob); |
| 4077 | STATE.thumbnailUrls.push(srcUrl); |
| 4078 | } |
| 4079 | else |
| 4080 | { |
| 4081 | setThumbnailPending(iconEl, false); |
| 4082 | const maxBytes = maxThumbBytesForKind(kind); |
| 4083 | if (maxBytes > 0 && typeof item.size === 'number' && item.size > maxBytes) |
| 4084 | { |
| 4085 | srcUrl = badgeThumbnailDataUrl(item.name, kind); |
| 4086 | } else |
| 4087 | { |
| 4088 | const url = `/api/files/download?file=${encodeURIComponent(filePath)}`; |
| 4089 | |
| 4090 | let res; |
| 4091 | try |
| 4092 | { |
| 4093 | res = await fetch(url, { |
| 4094 | headers: { |
| 4095 | Authorization: `Bearer ${STATE.token}`, |
| 4096 | 'X-Fp': getFingerprint(), |
| 4097 | }, |
| 4098 | }); |
| 4099 | } catch { return; } |
| 4100 | if (!res.ok || !iconEl.isConnected) return; |
| 4101 | |
| 4102 | const blob = await res.blob(); |
| 4103 | srcUrl = await buildThumbnailSource(item, blob, kind); |
| 4104 | } |
| 4105 | } |
| 4106 | if (!srcUrl || !iconEl.isConnected) return; |
| 4107 | |
| 4108 | const svg = iconEl.querySelector('svg'); |
| 4109 | if (!svg) |
| 4110 | { |
| 4111 | if (srcUrl.startsWith('blob:')) URL.revokeObjectURL(srcUrl); |
| 4112 | return; |
| 4113 | } |
| 4114 | |
| 4115 | const NS = 'http://www.w3.org/2000/svg'; |
| 4116 | const id = `fcp-${Math.random().toString(36).slice(2, 9)}`; |
| 4117 | |
| 4118 | // clipPath matches the main file body outline exactly (viewBox 0 0 24 24) |
| 4119 | const defs = document.createElementNS(NS, 'defs'); |
| 4120 | const clipPath = document.createElementNS(NS, 'clipPath'); |
| 4121 | clipPath.setAttribute('id', id); |
| 4122 | clipPath.setAttribute('clipPathUnits', 'userSpaceOnUse'); |
| 4123 | const clipShape = document.createElementNS(NS, 'path'); |
| 4124 | clipShape.setAttribute('d', 'M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z'); |
| 4125 | clipPath.appendChild(clipShape); |
| 4126 | defs.appendChild(clipPath); |
| 4127 | |
| 4128 | // Image fills the file bounding box; clip keeps it inside the outline |
| 4129 | const img = document.createElementNS(NS, 'image'); |
| 4130 | img.setAttribute('href', srcUrl); |
| 4131 | img.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', srcUrl); |
| 4132 | img.setAttribute('x', '4'); |
| 4133 | img.setAttribute('y', '2'); |
| 4134 | img.setAttribute('width', '16'); |
| 4135 | img.setAttribute('height', '20'); |
| 4136 | img.setAttribute('clip-path', `url(#${id})`); |
| 4137 | img.setAttribute('preserveAspectRatio', 'xMidYMid slice'); |
| 4138 | |
| 4139 | // Prepend so existing path/polyline elements (the outline) render on top |
| 4140 | svg.prepend(img); |
| 4141 | svg.prepend(defs); |
| 4142 | iconEl.dataset.thumbReady = '1'; |
| 4143 | } |
| 4144 | |
| 4145 | // ─────────────────────────────────────────────────────────────────────────── |
| 4146 | // FOLDER ICON THUMBNAILS |
| 4147 | // ─────────────────────────────────────────────────────────────────────────── |
| 4148 | |
| 4149 | function observeFolderIcon (iconEl) |
| 4150 | { |
| 4151 | if (!iconEl || !iconEl.isConnected) return; |
| 4152 | if (iconEl.dataset.thumbReady === '1') return; |
| 4153 | |
| 4154 | if (!('IntersectionObserver' in window)) |
| 4155 | { |
| 4156 | void loadOneFolderIcon(iconEl); |
| 4157 | return; |
| 4158 | } |
| 4159 | |
| 4160 | if (!STATE.folderIconObserver) |
| 4161 | { |
| 4162 | STATE.folderIconObserver = new IntersectionObserver((entries) => |
| 4163 | { |
| 4164 | for (const entry of entries) |
| 4165 | { |
| 4166 | if (!entry.isIntersecting) continue; |
| 4167 | const icon = entry.target; |
| 4168 | STATE.folderIconObserver.unobserve(icon); |
| 4169 | void loadOneFolderIcon(icon); |
| 4170 | } |
| 4171 | }, { root: null, rootMargin: THUMB_OBSERVER_ROOT_MARGIN, threshold: 0.01 }); |
| 4172 | } |
| 4173 | |
| 4174 | STATE.folderIconObserver.observe(iconEl); |
| 4175 | } |
| 4176 | |
| 4177 | async function loadOneFolderIcon (iconEl) |
| 4178 | { |
| 4179 | if (!iconEl.isConnected || !STATE.token) return; |
| 4180 | if (iconEl.dataset.thumbReady === '1') return; |
| 4181 | |
| 4182 | const folderPath = iconEl.dataset.folderPath; |
| 4183 | if (!folderPath) return; |
| 4184 | |
| 4185 | let res; |
| 4186 | try |
| 4187 | { |
| 4188 | res = await fetch(`/api/files/folder-icon?dir=${encodeURIComponent(folderPath)}`, { |
| 4189 | headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() }, |
| 4190 | }); |
| 4191 | } catch { return; } |
| 4192 | |
| 4193 | if (!res.ok || !iconEl.isConnected) return; |
| 4194 | |
| 4195 | const data = await res.json(); |
| 4196 | if (!data.icon) return; // No icon available — keep plain folder SVG. |
| 4197 | |
| 4198 | // Fetch the thumbnail through the auth-gated endpoint. |
| 4199 | let thumbRes; |
| 4200 | try |
| 4201 | { |
| 4202 | thumbRes = await fetch( |
| 4203 | `/api/files/thumbnail?file=${encodeURIComponent(data.icon.filePath)}`, |
| 4204 | { headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() } }, |
| 4205 | ); |
| 4206 | } catch { return; } |
| 4207 | |
| 4208 | if (!thumbRes.ok || !iconEl.isConnected) return; |
| 4209 | |
| 4210 | const blob = await thumbRes.blob(); |
| 4211 | const srcUrl = URL.createObjectURL(blob); |
| 4212 | STATE.thumbnailUrls.push(srcUrl); |
| 4213 | |
| 4214 | applyFolderThumbnail(iconEl, srcUrl); |
| 4215 | } |
| 4216 | |
| 4217 | /** |
| 4218 | * Overlays a thumbnail image inside the folder SVG outline. |
| 4219 | * The folder viewBox is 0 0 24 24; the folder body covers roughly x=2,y=5 to x=22,y=21. |
| 4220 | */ |
| 4221 | function applyFolderThumbnail (iconEl, srcUrl) |
| 4222 | { |
| 4223 | if (!iconEl.isConnected) return; |
| 4224 | const svg = iconEl.querySelector('svg'); |
| 4225 | if (!svg) |
| 4226 | { |
| 4227 | if (srcUrl.startsWith('blob:')) URL.revokeObjectURL(srcUrl); |
| 4228 | return; |
| 4229 | } |
| 4230 | |
| 4231 | const NS = 'http://www.w3.org/2000/svg'; |
| 4232 | const id = `fcp-${Math.random().toString(36).slice(2, 9)}`; |
| 4233 | |
| 4234 | const defs = document.createElementNS(NS, 'defs'); |
| 4235 | const clipPath = document.createElementNS(NS, 'clipPath'); |
| 4236 | clipPath.setAttribute('id', id); |
| 4237 | clipPath.setAttribute('clipPathUnits', 'userSpaceOnUse'); |
| 4238 | const clipShape = document.createElementNS(NS, 'path'); |
| 4239 | // Folder outline path (same as iconFolder SVG path) |
| 4240 | clipShape.setAttribute('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'); |
| 4241 | clipPath.appendChild(clipShape); |
| 4242 | defs.appendChild(clipPath); |
| 4243 | |
| 4244 | // Image covers the folder body area; clip keeps it inside the outline. |
| 4245 | const img = document.createElementNS(NS, 'image'); |
| 4246 | img.setAttribute('href', srcUrl); |
| 4247 | img.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', srcUrl); |
| 4248 | img.setAttribute('x', '2'); |
| 4249 | img.setAttribute('y', '3'); |
| 4250 | img.setAttribute('width', '20'); |
| 4251 | img.setAttribute('height', '18'); |
| 4252 | img.setAttribute('clip-path', `url(#${id})`); |
| 4253 | img.setAttribute('preserveAspectRatio', 'xMidYMid slice'); |
| 4254 | |
| 4255 | // Prepend so the folder outline strokes render on top. |
| 4256 | svg.prepend(img); |
| 4257 | svg.prepend(defs); |
| 4258 | iconEl.dataset.thumbReady = '1'; |
| 4259 | } |
| 4260 | |
| 4261 | function wireEvents () |
| 4262 | { |
| 4263 | // Auth form |
| 4264 | document.getElementById('auth-form').addEventListener('submit', async (e) => |
| 4265 | { |
| 4266 | e.preventDefault(); |
| 4267 | const username = document.getElementById('auth-username').value.trim(); |
| 4268 | const password = document.getElementById('auth-password').value; |
| 4269 | const isSetup = e.target.dataset.mode === 'setup'; |
| 4270 | const errEl = document.getElementById('auth-error'); |
| 4271 | const btn = document.getElementById('auth-submit'); |
| 4272 | btn.disabled = true; |
| 4273 | btn.textContent = 'Please wait…'; |
| 4274 | const err = await doLogin(username, password, isSetup); |
| 4275 | if (err) |
| 4276 | { |
| 4277 | errEl.textContent = err; |
| 4278 | errEl.classList.remove('hidden'); |
| 4279 | btn.disabled = false; |
| 4280 | btn.textContent = isSetup ? 'Create Account' : 'Sign In'; |
| 4281 | } |
| 4282 | }); |
| 4283 | |
| 4284 | // Logout |
| 4285 | document.getElementById('btn-logout').addEventListener('click', logout); |
| 4286 | |
| 4287 | // Hard refresh while keeping auth/session state. |
| 4288 | document.getElementById('btn-refresh').addEventListener('click', () => |
| 4289 | { |
| 4290 | saveSessionState(); |
| 4291 | location.reload(); |
| 4292 | }); |
| 4293 | |
| 4294 | // Upload button |
| 4295 | document.getElementById('btn-upload').addEventListener('click', () => |
| 4296 | { |
| 4297 | if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; } |
| 4298 | if (!canWrite()) { toast('No write access.', 'err'); return; } |
| 4299 | document.getElementById('file-input').click(); |
| 4300 | }); |
| 4301 | |
| 4302 | document.getElementById('file-input').addEventListener('change', async (e) => |
| 4303 | { |
| 4304 | if (e.target.files.length) await uploadFiles(e.target.files); |
| 4305 | e.target.value = ''; |
| 4306 | }); |
| 4307 | |
| 4308 | document.getElementById('btn-upload-folder').addEventListener('click', () => |
| 4309 | { |
| 4310 | if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; } |
| 4311 | if (!canWrite()) { toast('No write access.', 'err'); return; } |
| 4312 | document.getElementById('folder-input').click(); |
| 4313 | }); |
| 4314 | |
| 4315 | document.getElementById('folder-input').addEventListener('change', async (e) => |
| 4316 | { |
| 4317 | if (e.target.files.length) await uploadFolderInputFiles(e.target.files); |
| 4318 | e.target.value = ''; |
| 4319 | }); |
| 4320 | |
| 4321 | document.getElementById('btn-new-folder').addEventListener('click', async () => |
| 4322 | { |
| 4323 | if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; } |
| 4324 | if (!canWrite()) { toast('No write access.', 'err'); return; } |
| 4325 | |
| 4326 | const name = await showPrompt('New Folder', 'Enter a name for the new folder:'); |
| 4327 | if (name == null) return; |
| 4328 | const folderName = name.trim(); |
| 4329 | if (!folderName) |
| 4330 | { |
| 4331 | toast('Folder name is required.', 'err'); |
| 4332 | return; |
| 4333 | } |
| 4334 | |
| 4335 | try |
| 4336 | { |
| 4337 | await api('POST', '/files/mkdir', { dir: STATE.currentDir, name: folderName }); |
| 4338 | toast('Folder created.', 'ok'); |
| 4339 | await navigateTo(STATE.currentDir, STATE.currentRoot); |
| 4340 | } catch (err) |
| 4341 | { |
| 4342 | toast(err.message, 'err'); |
| 4343 | } |
| 4344 | }); |
| 4345 | |
| 4346 | document.getElementById('sidebar-close').addEventListener('click', (e) => |
| 4347 | { |
| 4348 | e.stopPropagation(); |
| 4349 | hideSidebarPanel(); |
| 4350 | }); |
| 4351 | |
| 4352 | const mobileQuery = window.matchMedia(MOBILE_BREAKPOINT_QUERY); |
| 4353 | const syncSidebarForViewport = () => |
| 4354 | { |
| 4355 | if (isMobileViewport()) |
| 4356 | { |
| 4357 | hideSidebarPanel(); |
| 4358 | return; |
| 4359 | } |
| 4360 | |
| 4361 | if (!STATE.selectedItem) openFolderSidebar(); |
| 4362 | }; |
| 4363 | |
| 4364 | if (typeof mobileQuery.addEventListener === 'function') |
| 4365 | { |
| 4366 | mobileQuery.addEventListener('change', syncSidebarForViewport); |
| 4367 | } else if (typeof mobileQuery.addListener === 'function') |
| 4368 | { |
| 4369 | mobileQuery.addListener(syncSidebarForViewport); |
| 4370 | } |
| 4371 | |
| 4372 | // Click outside grid clears selection and returns to folder sidebar info. |
| 4373 | document.getElementById('main-content').addEventListener('click', (e) => |
| 4374 | { |
| 4375 | if (!e.target.closest('.file-item')) closeSidebar(); |
| 4376 | }); |
| 4377 | |
| 4378 | // Admin panel |
| 4379 | document.getElementById('btn-admin').addEventListener('click', openAdminModal); |
| 4380 | document.getElementById('admin-modal-close').addEventListener('click', () => |
| 4381 | document.getElementById('admin-modal').classList.add('hidden')); |
| 4382 | |
| 4383 | // Add path |
| 4384 | document.getElementById('admin-add-path').addEventListener('click', () => |
| 4385 | { |
| 4386 | const val = document.getElementById('admin-new-path').value.trim(); |
| 4387 | if (!val) return; |
| 4388 | const row = document.createElement('div'); |
| 4389 | row.className = 'path-row'; |
| 4390 | row.innerHTML = `<span>${val}</span><button title="Remove">✕</button>`; |
| 4391 | row.querySelector('button').addEventListener('click', () => row.remove()); |
| 4392 | document.getElementById('admin-paths').appendChild(row); |
| 4393 | document.getElementById('admin-new-path').value = ''; |
| 4394 | }); |
| 4395 | |
| 4396 | // Save paths |
| 4397 | document.getElementById('admin-save-paths').addEventListener('click', async () => |
| 4398 | { |
| 4399 | const rows = document.querySelectorAll('#admin-paths .path-row span'); |
| 4400 | const paths = [...rows].map(s => s.textContent.trim()).filter(Boolean); |
| 4401 | try |
| 4402 | { |
| 4403 | await api('PUT', '/admin/config', { paths }); |
| 4404 | toast('Paths saved.', 'ok'); |
| 4405 | await loadRoots(); |
| 4406 | } catch (err) { toast(err.message, 'err'); } |
| 4407 | }); |
| 4408 | |
| 4409 | // Shutdown / restart server |
| 4410 | document.getElementById('admin-shutdown-btn').addEventListener('click', async () => |
| 4411 | { |
| 4412 | const status = _adminUpdateStatus; |
| 4413 | |
| 4414 | if (!status || !status.underSystemd) |
| 4415 | { |
| 4416 | // Not running under systemd — plain shutdown (manual restart required). |
| 4417 | if (!await showConfirm('Shut down server', 'Shut down the server? You will lose access until it is restarted manually.')) return; |
| 4418 | } |
| 4419 | else if (status.commitsAhead.length === 0) |
| 4420 | { |
| 4421 | // Under systemd, no updates — restart only. |
| 4422 | if (!await showConfirm('Restart server', 'No update available. Would you like to restart?', { okLabel: 'Restart' })) return; |
| 4423 | } |
| 4424 | else |
| 4425 | { |
| 4426 | // Under systemd, updates available. |
| 4427 | const commitList = status.commitsAhead.map(c => escHtml(c)).join('<br/>'); |
| 4428 | const msg = `Updates available:<br/><br/>${commitList}<br/><br/>Update now?`; |
| 4429 | if (!await showConfirm('Restart & Update', msg, { html: true, okLabel: 'Update now' })) return; |
| 4430 | } |
| 4431 | |
| 4432 | try |
| 4433 | { |
| 4434 | await api('POST', '/admin/shutdown'); |
| 4435 | const toastMsg = (!status || !status.underSystemd) |
| 4436 | ? 'Server is shutting down\u2026' |
| 4437 | : status.commitsAhead.length > 0 |
| 4438 | ? 'Server is updating and restarting\u2026' |
| 4439 | : 'Server is restarting\u2026'; |
| 4440 | toast(toastMsg, 'ok'); |
| 4441 | document.getElementById('admin-modal').classList.add('hidden'); |
| 4442 | } catch |
| 4443 | { |
| 4444 | // Fetch may throw because the connection closes before a response arrives. |
| 4445 | const toastMsg = (!status || !status.underSystemd) |
| 4446 | ? 'Server is shutting down\u2026' |
| 4447 | : status.commitsAhead.length > 0 |
| 4448 | ? 'Server is updating and restarting\u2026' |
| 4449 | : 'Server is restarting\u2026'; |
| 4450 | toast(toastMsg, 'ok'); |
| 4451 | document.getElementById('admin-modal').classList.add('hidden'); |
| 4452 | } |
| 4453 | setTimeout(() => location.reload(), 3000); |
| 4454 | }); |
| 4455 | |
| 4456 | // New user |
| 4457 | document.getElementById('admin-new-user-btn').addEventListener('click', async () => |
| 4458 | { |
| 4459 | const cfg = await api('GET', '/admin/config'); |
| 4460 | const paths = cfg ? (cfg.effectivePaths || []) : []; |
| 4461 | openUserModal(null, paths); |
| 4462 | }); |
| 4463 | |
| 4464 | // User modal close |
| 4465 | document.getElementById('user-modal-close').addEventListener('click', () => |
| 4466 | document.getElementById('user-modal').classList.add('hidden')); |
| 4467 | |
| 4468 | // Rename modal close |
| 4469 | document.getElementById('rename-modal-close').addEventListener('click', () => |
| 4470 | document.getElementById('rename-modal').classList.add('hidden')); |
| 4471 | |
| 4472 | // Close modals on backdrop click |
| 4473 | document.querySelectorAll('.modal-overlay').forEach(overlay => |
| 4474 | { |
| 4475 | overlay.addEventListener('click', e => |
| 4476 | { |
| 4477 | if (e.target === overlay) overlay.classList.add('hidden'); |
| 4478 | }); |
| 4479 | }); |
| 4480 | } |
| 4481 | |
| 4482 | // ─────────────────────────────────────────────────────────────────────────── |
| 4483 | // BOOT |
| 4484 | // ─────────────────────────────────────────────────────────────────────────── |
| 4485 | |
| 4486 | (async function boot () |
| 4487 | { |
| 4488 | wireEvents(); |
| 4489 | initDragDrop(); |
| 4490 | window.addEventListener('beforeunload', () => |
| 4491 | { |
| 4492 | saveSessionState(); |
| 4493 | releaseActivePreviewVideoStreamSession({ keepalive: true }); |
| 4494 | }); |
| 4495 | window.addEventListener('pagehide', () => |
| 4496 | { |
| 4497 | releaseActivePreviewVideoStreamSession({ keepalive: true }); |
| 4498 | }); |
| 4499 | await initAuth(); |
| 4500 | })(); |