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