| 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 | // Sidebar async loading guard to prevent stale updates on rapid selection changes. |
| 60 | sidebarLoadId: 0, |
| 61 | sidebarAbortController: null, |
| 62 | |
| 63 | // Watched overlays are resolved asynchronously from /files/meta responses. |
| 64 | watchedStatusByPath: {}, |
| 65 | watchedLoadId: 0, |
| 66 | |
| 67 | // Cross-root file search mode (null = regular folder browsing). |
| 68 | searchQuery: null, |
| 69 | |
| 70 | // Bust cache when favicon changes. |
| 71 | faviconVersion: Date.now(), |
| 72 | }; |
| 73 | |
| 74 | const SESSION_KEY = 'filemanager.session.v1'; |
| 75 | const SESSION_IDLE_TIMEOUT_MS = 60 * 60 * 1000; // 1 hour |
| 76 | const CLIENT_BINDING_KEY = 'filemanager.client-binding-id.v1'; |
| 77 | const MOBILE_BREAKPOINT_QUERY = '(max-width: 600px)'; |
| 78 | const MOBILE_LONG_PRESS_MS = 420; |
| 79 | const MOBILE_LONG_PRESS_MOVE_THRESHOLD = 10; |
| 80 | const THUMB_OBSERVER_ROOT_MARGIN = '120px'; |
| 81 | const VIDEO_PREFS_KEY_PREFIX = 'filemanager.video-prefs.v1.'; |
| 82 | const FOLDER_VIEW_PREFS_KEY_PREFIX = 'filemanager.folder-view-prefs.v1.'; |
| 83 | const VIDEO_TEXT_TRACK_SETTINGS_KEY = 'vjs-text-track-settings'; |
| 84 | const VIDEO_TEXT_TRACK_OVERRIDE_SETTINGS_RAW = JSON.stringify({ |
| 85 | backgroundOpacity: '0', |
| 86 | edgeStyle: 'uniform', |
| 87 | }); |
| 88 | const DEFAULT_FOLDER_VIEW_PREFS = { |
| 89 | sortBy: 'alphabetical', |
| 90 | groupBy: 'none', |
| 91 | foldersFirst: true, |
| 92 | ascending: true, |
| 93 | }; |
| 94 | const VIDEO_FORWARD_BUFFER_SECONDS = 60 * 60; |
| 95 | const VIDEO_FORWARD_BUFFER_OVERRIDE_ENABLED = false; |
| 96 | let videoJsLoaderPromise = null; |
| 97 | let threePreviewModulesPromise = null; |
| 98 | |
| 99 | // ─────────────────────────────────────────────────────────────────────────── |
| 100 | // CRYPTO HELPERS (Web Crypto API) |
| 101 | // ─────────────────────────────────────────────────────────────────────────── |
| 102 | |
| 103 | async function generateClientKeyPair () |
| 104 | { |
| 105 | if (!hasWebCrypto()) return; |
| 106 | const kp = await crypto.subtle.generateKey( |
| 107 | { name: 'RSA-OAEP', modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256' }, |
| 108 | true, |
| 109 | ['encrypt', 'decrypt'], |
| 110 | ); |
| 111 | STATE.clientPrivateKey = kp.privateKey; |
| 112 | STATE.clientPublicKeyJwk = await crypto.subtle.exportKey('jwk', kp.publicKey); |
| 113 | } |
| 114 | |
| 115 | /** |
| 116 | * Hybrid-encrypt a JS object using the server's RSA public key. |
| 117 | * Returns { encryptedKey, iv, ciphertext, tag } all as base64 strings. |
| 118 | */ |
| 119 | async function hybridEncryptForServer (obj) |
| 120 | { |
| 121 | if (!hasWebCrypto() || !STATE.serverPublicKeyJwk) |
| 122 | { |
| 123 | return { plaintext: obj }; |
| 124 | } |
| 125 | |
| 126 | const serverPub = await crypto.subtle.importKey( |
| 127 | 'jwk', STATE.serverPublicKeyJwk, |
| 128 | { name: 'RSA-OAEP', hash: 'SHA-256' }, |
| 129 | false, ['encrypt'], |
| 130 | ); |
| 131 | |
| 132 | const plaintext = new TextEncoder().encode(JSON.stringify(obj)); |
| 133 | const aesKey = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt']); |
| 134 | const iv = crypto.getRandomValues(new Uint8Array(12)); |
| 135 | const gcmResult = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, aesKey, plaintext); |
| 136 | |
| 137 | // gcmResult = ciphertext || tag (last 16 bytes are auth tag) |
| 138 | const gcmBytes = new Uint8Array(gcmResult); |
| 139 | const ciphertext = gcmBytes.slice(0, gcmBytes.length - 16); |
| 140 | const tag = gcmBytes.slice(gcmBytes.length - 16); |
| 141 | |
| 142 | const rawAes = await crypto.subtle.exportKey('raw', aesKey); |
| 143 | const encryptedKey = await crypto.subtle.encrypt({ name: 'RSA-OAEP' }, serverPub, rawAes); |
| 144 | |
| 145 | return { |
| 146 | encryptedKey: b64(encryptedKey), |
| 147 | iv: b64(iv), |
| 148 | ciphertext: b64(ciphertext), |
| 149 | tag: b64(tag), |
| 150 | }; |
| 151 | } |
| 152 | |
| 153 | /** |
| 154 | * Hybrid-decrypt a payload encrypted by the server for us (using our public key). |
| 155 | */ |
| 156 | async function hybridDecryptFromServer (payload) |
| 157 | { |
| 158 | if (!payload) return null; |
| 159 | if (payload.token) return payload.token; |
| 160 | if (!hasWebCrypto()) return null; |
| 161 | |
| 162 | const encryptedKey = unb64(payload.encryptedKey); |
| 163 | const iv = unb64(payload.iv); |
| 164 | const ciphertext = unb64(payload.ciphertext); |
| 165 | const tag = unb64(payload.tag); |
| 166 | |
| 167 | const rawAes = await crypto.subtle.decrypt( |
| 168 | { name: 'RSA-OAEP' }, STATE.clientPrivateKey, encryptedKey, |
| 169 | ); |
| 170 | |
| 171 | const aesKey = await crypto.subtle.importKey('raw', rawAes, { name: 'AES-GCM' }, false, ['decrypt']); |
| 172 | |
| 173 | // Recombine ciphertext + tag for AES-GCM |
| 174 | const combined = new Uint8Array(ciphertext.byteLength + tag.byteLength); |
| 175 | combined.set(new Uint8Array(ciphertext)); |
| 176 | combined.set(new Uint8Array(tag), ciphertext.byteLength); |
| 177 | |
| 178 | const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, aesKey, combined); |
| 179 | return new TextDecoder().decode(plain); |
| 180 | } |
| 181 | |
| 182 | // ─────────────────────────────────────────────────────────────────────────── |
| 183 | // UTIL |
| 184 | // ─────────────────────────────────────────────────────────────────────────── |
| 185 | |
| 186 | function b64 (buf) |
| 187 | { |
| 188 | return btoa(String.fromCharCode(...new Uint8Array(buf instanceof ArrayBuffer ? buf : buf.buffer))); |
| 189 | } |
| 190 | |
| 191 | function hasWebCrypto () |
| 192 | { |
| 193 | return !!(window.crypto && window.crypto.subtle); |
| 194 | } |
| 195 | |
| 196 | function unb64 (str) |
| 197 | { |
| 198 | const binary = atob(str); |
| 199 | const buf = new Uint8Array(binary.length); |
| 200 | for (let i = 0; i < binary.length; i++) buf[i] = binary.charCodeAt(i); |
| 201 | return buf.buffer; |
| 202 | } |
| 203 | |
| 204 | /** Stable browser fingerprint (not stored, derived fresh each load) */ |
| 205 | function getFingerprint () |
| 206 | { |
| 207 | const binding = getOrCreateClientBindingId(); |
| 208 | const nav = navigator; |
| 209 | |
| 210 | // Keep this stable: avoid viewport/screen metrics that can change when |
| 211 | // devtools opens, orientation changes, or window state changes. |
| 212 | return [ |
| 213 | binding, |
| 214 | nav.userAgent || '', |
| 215 | nav.language, |
| 216 | nav.platform || nav.userAgentData?.platform || '', |
| 217 | Intl.DateTimeFormat().resolvedOptions().timeZone, |
| 218 | ].join('|'); |
| 219 | } |
| 220 | |
| 221 | function randomIdHex (bytes = 16) |
| 222 | { |
| 223 | const arr = new Uint8Array(bytes); |
| 224 | if (window.crypto && typeof window.crypto.getRandomValues === 'function') |
| 225 | { |
| 226 | window.crypto.getRandomValues(arr); |
| 227 | } else |
| 228 | { |
| 229 | for (let i = 0; i < arr.length; i++) arr[i] = Math.floor(Math.random() * 256); |
| 230 | } |
| 231 | return Array.from(arr).map(n => n.toString(16).padStart(2, '0')).join(''); |
| 232 | } |
| 233 | |
| 234 | function userVideoPrefsKey () |
| 235 | { |
| 236 | const name = String(STATE.username || 'anonymous').trim().toLowerCase() || 'anonymous'; |
| 237 | return VIDEO_PREFS_KEY_PREFIX + name; |
| 238 | } |
| 239 | |
| 240 | function loadUserVideoPrefs () |
| 241 | { |
| 242 | try |
| 243 | { |
| 244 | const raw = localStorage.getItem(userVideoPrefsKey()); |
| 245 | const parsed = raw ? JSON.parse(raw) : {}; |
| 246 | if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {}; |
| 247 | return parsed; |
| 248 | } catch |
| 249 | { |
| 250 | return {}; |
| 251 | } |
| 252 | } |
| 253 | |
| 254 | function saveUserVideoPrefs (patch) |
| 255 | { |
| 256 | try |
| 257 | { |
| 258 | const current = loadUserVideoPrefs(); |
| 259 | localStorage.setItem(userVideoPrefsKey(), JSON.stringify({ ...current, ...(patch || {}) })); |
| 260 | } catch |
| 261 | { |
| 262 | // Ignore localStorage failures. |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | function userFolderViewPrefsKey () |
| 267 | { |
| 268 | const name = String(STATE.username || 'anonymous').trim().toLowerCase() || 'anonymous'; |
| 269 | return FOLDER_VIEW_PREFS_KEY_PREFIX + name; |
| 270 | } |
| 271 | |
| 272 | function normaliseFolderViewPrefs (value) |
| 273 | { |
| 274 | const input = value && typeof value === 'object' ? value : {}; |
| 275 | const sortBy = ['alphabetical', 'fileType', 'lastChanged', 'timeUploaded', 'size'].includes(input.sortBy) |
| 276 | ? input.sortBy |
| 277 | : DEFAULT_FOLDER_VIEW_PREFS.sortBy; |
| 278 | const groupBy = ['none', 'alphabetical', 'fileType', 'lastChangedDate', 'timeUploadedDate', 'size'].includes(input.groupBy) |
| 279 | ? input.groupBy |
| 280 | : DEFAULT_FOLDER_VIEW_PREFS.groupBy; |
| 281 | |
| 282 | return { |
| 283 | sortBy, |
| 284 | groupBy, |
| 285 | foldersFirst: input.foldersFirst !== undefined ? !!input.foldersFirst : DEFAULT_FOLDER_VIEW_PREFS.foldersFirst, |
| 286 | ascending: input.ascending !== undefined ? !!input.ascending : DEFAULT_FOLDER_VIEW_PREFS.ascending, |
| 287 | }; |
| 288 | } |
| 289 | |
| 290 | function loadFolderViewPrefsMap () |
| 291 | { |
| 292 | try |
| 293 | { |
| 294 | const raw = localStorage.getItem(userFolderViewPrefsKey()); |
| 295 | const parsed = raw ? JSON.parse(raw) : {}; |
| 296 | if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {}; |
| 297 | |
| 298 | const out = {}; |
| 299 | for (const [dirPath, prefs] of Object.entries(parsed)) |
| 300 | { |
| 301 | out[String(dirPath)] = normaliseFolderViewPrefs(prefs); |
| 302 | } |
| 303 | return out; |
| 304 | } catch |
| 305 | { |
| 306 | return {}; |
| 307 | } |
| 308 | } |
| 309 | |
| 310 | function saveFolderViewPrefsMap (prefsByPath) |
| 311 | { |
| 312 | try |
| 313 | { |
| 314 | localStorage.setItem(userFolderViewPrefsKey(), JSON.stringify(prefsByPath || {})); |
| 315 | } catch |
| 316 | { |
| 317 | // Ignore localStorage failures. |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | function folderViewPrefsForDir (dirPath) |
| 322 | { |
| 323 | if (!dirPath) return { ...DEFAULT_FOLDER_VIEW_PREFS }; |
| 324 | const prefsByPath = loadFolderViewPrefsMap(); |
| 325 | return normaliseFolderViewPrefs(prefsByPath[String(dirPath)] || DEFAULT_FOLDER_VIEW_PREFS); |
| 326 | } |
| 327 | |
| 328 | function saveFolderViewPrefsForDir (dirPath, patch) |
| 329 | { |
| 330 | if (!dirPath) return; |
| 331 | const key = String(dirPath); |
| 332 | const prefsByPath = loadFolderViewPrefsMap(); |
| 333 | const current = normaliseFolderViewPrefs(prefsByPath[key] || DEFAULT_FOLDER_VIEW_PREFS); |
| 334 | prefsByPath[key] = normaliseFolderViewPrefs({ ...current, ...(patch || {}) }); |
| 335 | saveFolderViewPrefsMap(prefsByPath); |
| 336 | } |
| 337 | |
| 338 | function buildAuthHeaders () |
| 339 | { |
| 340 | const headers = {}; |
| 341 | if (STATE.token) |
| 342 | { |
| 343 | headers.Authorization = 'Bearer ' + STATE.token; |
| 344 | try |
| 345 | { |
| 346 | const fp = getFingerprint(); |
| 347 | if (fp) headers['X-Fp'] = fp; |
| 348 | } catch |
| 349 | { |
| 350 | // Continue without a fingerprint header in constrained test/runtime contexts. |
| 351 | } |
| 352 | } |
| 353 | return headers; |
| 354 | } |
| 355 | |
| 356 | function applyUserVideoTextTrackPrefs () |
| 357 | { |
| 358 | try |
| 359 | { |
| 360 | // Only override the two requested defaults and leave other settings at Video.js defaults. |
| 361 | localStorage.setItem(VIDEO_TEXT_TRACK_SETTINGS_KEY, VIDEO_TEXT_TRACK_OVERRIDE_SETTINGS_RAW); |
| 362 | } catch |
| 363 | { |
| 364 | // Ignore localStorage failures. |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | function normaliseTrackName (name) |
| 369 | { |
| 370 | return String(name || '').trim().toLowerCase(); |
| 371 | } |
| 372 | |
| 373 | function getTrackName (track) |
| 374 | { |
| 375 | if (!track || typeof track !== 'object') return ''; |
| 376 | const label = String(track.label || '').trim(); |
| 377 | if (label) return label; |
| 378 | const name = String(track.name || '').trim(); |
| 379 | if (name) return name; |
| 380 | const language = String(track.language || '').trim(); |
| 381 | if (language) return language; |
| 382 | const id = String(track.id || '').trim(); |
| 383 | if (id) return id; |
| 384 | return ''; |
| 385 | } |
| 386 | |
| 387 | function trackListToArray (trackList) |
| 388 | { |
| 389 | if (!trackList || typeof trackList.length !== 'number') return []; |
| 390 | const out = []; |
| 391 | for (let i = 0; i < trackList.length; i++) |
| 392 | { |
| 393 | const track = trackList[i] || (typeof trackList.item === 'function' ? trackList.item(i) : null); |
| 394 | if (track) out.push(track); |
| 395 | } |
| 396 | return out; |
| 397 | } |
| 398 | |
| 399 | function subtitleTracksFromPlayer (player) |
| 400 | { |
| 401 | if (!player || typeof player.textTracks !== 'function') return []; |
| 402 | return trackListToArray(player.textTracks()).filter((track) => |
| 403 | { |
| 404 | const kind = String(track.kind || '').toLowerCase(); |
| 405 | return kind === 'subtitles' || kind === 'captions'; |
| 406 | }); |
| 407 | } |
| 408 | |
| 409 | function audioTracksFromPlayer (player) |
| 410 | { |
| 411 | if (!player || typeof player.audioTracks !== 'function') return []; |
| 412 | return trackListToArray(player.audioTracks()); |
| 413 | } |
| 414 | |
| 415 | function applySavedSubtitleTrack (player, savedName) |
| 416 | { |
| 417 | if (typeof savedName !== 'string') return; |
| 418 | const tracks = subtitleTracksFromPlayer(player); |
| 419 | if (!tracks.length) return; |
| 420 | |
| 421 | const wanted = normaliseTrackName(savedName); |
| 422 | if (!wanted) |
| 423 | { |
| 424 | for (const track of tracks) track.mode = 'disabled'; |
| 425 | return; |
| 426 | } |
| 427 | |
| 428 | const match = tracks.find((track) => normaliseTrackName(getTrackName(track)) === wanted); |
| 429 | if (!match) return; |
| 430 | |
| 431 | for (const track of tracks) |
| 432 | { |
| 433 | track.mode = track === match ? 'showing' : 'disabled'; |
| 434 | } |
| 435 | } |
| 436 | |
| 437 | function applySavedAudioTrack (player, savedName) |
| 438 | { |
| 439 | if (typeof savedName !== 'string') return; |
| 440 | const tracks = audioTracksFromPlayer(player); |
| 441 | if (!tracks.length) return; |
| 442 | |
| 443 | const wanted = normaliseTrackName(savedName); |
| 444 | if (!wanted) return; |
| 445 | |
| 446 | const match = tracks.find((track) => normaliseTrackName(getTrackName(track)) === wanted); |
| 447 | if (!match) return; |
| 448 | |
| 449 | for (const track of tracks) |
| 450 | { |
| 451 | track.enabled = track === match; |
| 452 | } |
| 453 | } |
| 454 | |
| 455 | function getSelectedSubtitleTrackName (player) |
| 456 | { |
| 457 | const tracks = subtitleTracksFromPlayer(player); |
| 458 | if (!tracks.length) return null; |
| 459 | const active = tracks.find((track) => String(track.mode || '').toLowerCase() === 'showing'); |
| 460 | return active ? getTrackName(active) : ''; |
| 461 | } |
| 462 | |
| 463 | function getSelectedAudioTrackName (player) |
| 464 | { |
| 465 | const tracks = audioTracksFromPlayer(player); |
| 466 | if (!tracks.length) return null; |
| 467 | const active = tracks.find((track) => !!track.enabled); |
| 468 | return active ? getTrackName(active) : ''; |
| 469 | } |
| 470 | |
| 471 | function bindUserVideoTrackPrefs (player, prefs) |
| 472 | { |
| 473 | const applySavedTracks = () => |
| 474 | { |
| 475 | applySavedSubtitleTrack(player, prefs.subtitleTrackName); |
| 476 | applySavedAudioTrack(player, prefs.audioTrackName); |
| 477 | }; |
| 478 | |
| 479 | const captureSelectedTracks = () => |
| 480 | { |
| 481 | const subtitleTrackName = getSelectedSubtitleTrackName(player); |
| 482 | const audioTrackName = getSelectedAudioTrackName(player); |
| 483 | const patch = {}; |
| 484 | |
| 485 | if (subtitleTrackName !== null) patch.subtitleTrackName = subtitleTrackName; |
| 486 | if (audioTrackName !== null) patch.audioTrackName = audioTrackName; |
| 487 | |
| 488 | if (Object.keys(patch).length) saveUserVideoPrefs(patch); |
| 489 | }; |
| 490 | |
| 491 | const textTrackList = typeof player.textTracks === 'function' ? player.textTracks() : null; |
| 492 | const audioTrackList = typeof player.audioTracks === 'function' ? player.audioTracks() : null; |
| 493 | const onTrackListChange = () => captureSelectedTracks(); |
| 494 | |
| 495 | if (textTrackList && typeof textTrackList.addEventListener === 'function') |
| 496 | { |
| 497 | textTrackList.addEventListener('change', onTrackListChange); |
| 498 | } |
| 499 | |
| 500 | if (audioTrackList && typeof audioTrackList.addEventListener === 'function') |
| 501 | { |
| 502 | audioTrackList.addEventListener('change', onTrackListChange); |
| 503 | } |
| 504 | |
| 505 | return { |
| 506 | applySavedTracks, |
| 507 | captureSelectedTracks, |
| 508 | detach: () => |
| 509 | { |
| 510 | if (textTrackList && typeof textTrackList.removeEventListener === 'function') |
| 511 | { |
| 512 | textTrackList.removeEventListener('change', onTrackListChange); |
| 513 | } |
| 514 | if (audioTrackList && typeof audioTrackList.removeEventListener === 'function') |
| 515 | { |
| 516 | audioTrackList.removeEventListener('change', onTrackListChange); |
| 517 | } |
| 518 | }, |
| 519 | }; |
| 520 | } |
| 521 | |
| 522 | function bindImageSubtitleOverlay (player, videojs, prefs, session, item) |
| 523 | { |
| 524 | const imageTracks = Array.isArray(session.imageSubtitleTracks) |
| 525 | ? session.imageSubtitleTracks.map((track) => ({ |
| 526 | label: String(track.label || '').trim() || `Subtitle ${Number(track.streamIndex || 0) + 1}`, |
| 527 | language: String(track.language || '').trim(), |
| 528 | isDefault: !!track.default, |
| 529 | streamIndex: Number(track.streamIndex), |
| 530 | })).filter((track) => Number.isInteger(track.streamIndex) && track.streamIndex >= 0) |
| 531 | : []; |
| 532 | |
| 533 | if (!imageTracks.length) return null; |
| 534 | |
| 535 | const trackByStreamIndex = new Map(imageTracks.map((track) => [track.streamIndex, track])); |
| 536 | let selectedStreamIndex = null; |
| 537 | let menuOpen = false; |
| 538 | let requestToken = 0; |
| 539 | let activeBucket = -1; |
| 540 | let activeObjectUrl = null; |
| 541 | let overlayEl = null; |
| 542 | let overlayImgEl = null; |
| 543 | let menuEl = null; |
| 544 | let buttonEl = null; |
| 545 | let trackDisabled = false; |
| 546 | let failureNotified = false; |
| 547 | |
| 548 | const closeObjectUrl = () => |
| 549 | { |
| 550 | if (activeObjectUrl) |
| 551 | { |
| 552 | URL.revokeObjectURL(activeObjectUrl); |
| 553 | activeObjectUrl = null; |
| 554 | } |
| 555 | }; |
| 556 | |
| 557 | const hideOverlay = () => |
| 558 | { |
| 559 | if (overlayEl) overlayEl.style.display = 'none'; |
| 560 | if (overlayImgEl) overlayImgEl.removeAttribute('src'); |
| 561 | closeObjectUrl(); |
| 562 | }; |
| 563 | |
| 564 | const updateButtonState = () => |
| 565 | { |
| 566 | if (!buttonEl) return; |
| 567 | const track = selectedStreamIndex === null ? null : trackByStreamIndex.get(selectedStreamIndex) || null; |
| 568 | buttonEl.setAttribute('title', track ? `Image subtitles: ${track.label}` : 'Image subtitles'); |
| 569 | buttonEl.setAttribute('aria-pressed', selectedStreamIndex === null ? 'false' : 'true'); |
| 570 | }; |
| 571 | |
| 572 | const updateMenuState = () => |
| 573 | { |
| 574 | if (!menuEl) return; |
| 575 | const items = menuEl.querySelectorAll('[data-image-subtitle-stream-index]'); |
| 576 | for (const itemEl of items) |
| 577 | { |
| 578 | const value = itemEl.getAttribute('data-image-subtitle-stream-index'); |
| 579 | const isSelected = value === (selectedStreamIndex === null ? 'off' : String(selectedStreamIndex)); |
| 580 | itemEl.classList.toggle('is-selected', isSelected); |
| 581 | itemEl.setAttribute('aria-checked', isSelected ? 'true' : 'false'); |
| 582 | itemEl.style.background = isSelected ? 'rgba(90, 196, 255, 0.28)' : 'transparent'; |
| 583 | itemEl.style.fontWeight = isSelected ? '600' : '400'; |
| 584 | itemEl.style.boxShadow = isSelected ? 'inset 0 0 0 1px rgba(90, 196, 255, 0.55)' : 'none'; |
| 585 | } |
| 586 | }; |
| 587 | |
| 588 | const closeMenu = () => |
| 589 | { |
| 590 | menuOpen = false; |
| 591 | if (menuEl) menuEl.style.display = 'none'; |
| 592 | }; |
| 593 | |
| 594 | const openMenu = () => |
| 595 | { |
| 596 | menuOpen = true; |
| 597 | if (menuEl) |
| 598 | { |
| 599 | updateMenuState(); |
| 600 | menuEl.style.display = 'block'; |
| 601 | } |
| 602 | }; |
| 603 | |
| 604 | const toggleMenu = () => |
| 605 | { |
| 606 | if (menuOpen) closeMenu(); |
| 607 | else openMenu(); |
| 608 | }; |
| 609 | |
| 610 | const saveSelection = () => |
| 611 | { |
| 612 | const selectedTrack = selectedStreamIndex === null ? null : trackByStreamIndex.get(selectedStreamIndex) || null; |
| 613 | saveUserVideoPrefs({ |
| 614 | imageSubtitleTrackStreamIndex: selectedStreamIndex, |
| 615 | imageSubtitleTrackName: selectedTrack ? selectedTrack.label : null, |
| 616 | }); |
| 617 | }; |
| 618 | |
| 619 | const disableTrack = () => |
| 620 | { |
| 621 | trackDisabled = true; |
| 622 | selectedStreamIndex = null; |
| 623 | activeBucket = -1; |
| 624 | hideOverlay(); |
| 625 | updateButtonState(); |
| 626 | updateMenuState(); |
| 627 | saveSelection(); |
| 628 | |
| 629 | if (!failureNotified) |
| 630 | { |
| 631 | failureNotified = true; |
| 632 | toast('Image subtitles could not be rendered for this file.', 'err'); |
| 633 | } |
| 634 | }; |
| 635 | |
| 636 | const setSelectedStreamIndex = (streamIndex, { persist = true } = {}) => |
| 637 | { |
| 638 | const nextStreamIndex = Number.isInteger(streamIndex) ? streamIndex : null; |
| 639 | if (nextStreamIndex !== null && !trackByStreamIndex.has(nextStreamIndex)) return; |
| 640 | |
| 641 | trackDisabled = false; |
| 642 | failureNotified = false; |
| 643 | selectedStreamIndex = nextStreamIndex; |
| 644 | activeBucket = -1; |
| 645 | hideOverlay(); |
| 646 | updateButtonState(); |
| 647 | updateMenuState(); |
| 648 | if (persist) saveSelection(); |
| 649 | |
| 650 | if (selectedStreamIndex !== null) |
| 651 | { |
| 652 | void refreshFrame(true); |
| 653 | } |
| 654 | }; |
| 655 | |
| 656 | const refreshFrame = async (force = false) => |
| 657 | { |
| 658 | if (selectedStreamIndex === null) return; |
| 659 | if (!overlayEl || !overlayImgEl) return; |
| 660 | if (trackDisabled) return; |
| 661 | |
| 662 | const currentTime = Number(player.currentTime()); |
| 663 | if (!Number.isFinite(currentTime) || currentTime < 0) return; |
| 664 | |
| 665 | const bucket = Math.floor(currentTime * 4); |
| 666 | if (!force && bucket === activeBucket) return; |
| 667 | activeBucket = bucket; |
| 668 | |
| 669 | const token = ++requestToken; |
| 670 | const headers = buildAuthHeaders(); |
| 671 | const url = `/api/files/video-stream-subtitle-frame?filePath=${encodeURIComponent(item.path)}&streamIndex=${selectedStreamIndex}&timeSeconds=${encodeURIComponent(String(currentTime))}&videoWidth=${encodeURIComponent(String(session.videoWidth || ''))}&videoHeight=${encodeURIComponent(String(session.videoHeight || ''))}`; |
| 672 | |
| 673 | try |
| 674 | { |
| 675 | const res = await fetch(url, { |
| 676 | method: 'GET', |
| 677 | headers, |
| 678 | credentials: 'same-origin', |
| 679 | }); |
| 680 | |
| 681 | if (token !== requestToken) return; |
| 682 | |
| 683 | if (res.status === 204) |
| 684 | { |
| 685 | const frameStatus = String(res.headers.get('X-Subtitle-Frame-Status') || '').toLowerCase(); |
| 686 | hideOverlay(); |
| 687 | if (frameStatus === 'error') disableTrack(); |
| 688 | return; |
| 689 | } |
| 690 | |
| 691 | if (!res.ok) |
| 692 | { |
| 693 | disableTrack(); |
| 694 | return; |
| 695 | } |
| 696 | |
| 697 | const blob = await res.blob(); |
| 698 | if (token !== requestToken) return; |
| 699 | |
| 700 | if (!blob || blob.size === 0) |
| 701 | { |
| 702 | disableTrack(); |
| 703 | return; |
| 704 | } |
| 705 | |
| 706 | closeObjectUrl(); |
| 707 | activeObjectUrl = URL.createObjectURL(blob); |
| 708 | overlayImgEl.src = activeObjectUrl; |
| 709 | overlayEl.style.display = 'block'; |
| 710 | overlayImgEl.style.display = 'block'; |
| 711 | } catch |
| 712 | { |
| 713 | if (token === requestToken) disableTrack(); |
| 714 | } |
| 715 | }; |
| 716 | |
| 717 | const dispose = () => |
| 718 | { |
| 719 | requestToken++; |
| 720 | closeMenu(); |
| 721 | hideOverlay(); |
| 722 | if (overlayEl) overlayEl.remove(); |
| 723 | if (menuEl) menuEl.remove(); |
| 724 | player.imageSubtitleOverlayController = null; |
| 725 | buttonEl = null; |
| 726 | }; |
| 727 | |
| 728 | overlayEl = document.createElement('div'); |
| 729 | overlayEl.className = 'video-subtitle-overlay'; |
| 730 | overlayEl.style.position = 'absolute'; |
| 731 | overlayEl.style.left = '0'; |
| 732 | overlayEl.style.right = '0'; |
| 733 | overlayEl.style.bottom = '3rem'; |
| 734 | overlayEl.style.display = 'none'; |
| 735 | overlayEl.style.zIndex = '3'; |
| 736 | overlayEl.style.pointerEvents = 'none'; |
| 737 | overlayEl.style.textAlign = 'center'; |
| 738 | overlayEl.style.padding = '0 0.75rem'; |
| 739 | |
| 740 | overlayImgEl = document.createElement('img'); |
| 741 | overlayImgEl.alt = 'Image subtitles'; |
| 742 | overlayImgEl.style.display = 'none'; |
| 743 | overlayImgEl.style.maxWidth = '100%'; |
| 744 | overlayImgEl.style.maxHeight = '35%'; |
| 745 | overlayImgEl.style.margin = '0 auto'; |
| 746 | overlayImgEl.style.objectFit = 'contain'; |
| 747 | overlayImgEl.style.filter = 'drop-shadow(0 2px 2px rgba(0, 0, 0, 0.7))'; |
| 748 | overlayEl.appendChild(overlayImgEl); |
| 749 | |
| 750 | menuEl = document.createElement('div'); |
| 751 | menuEl.className = 'video-subtitle-overlay-menu'; |
| 752 | menuEl.style.position = 'absolute'; |
| 753 | menuEl.style.right = '0.75rem'; |
| 754 | menuEl.style.bottom = 'calc(3rem + 0.5rem)'; |
| 755 | menuEl.style.minWidth = '14rem'; |
| 756 | menuEl.style.maxWidth = '20rem'; |
| 757 | menuEl.style.background = 'rgba(12, 12, 12, 0.96)'; |
| 758 | menuEl.style.border = '1px solid rgba(255, 255, 255, 0.15)'; |
| 759 | menuEl.style.borderRadius = '0.5rem'; |
| 760 | menuEl.style.boxShadow = '0 12px 28px rgba(0, 0, 0, 0.35)'; |
| 761 | menuEl.style.padding = '0.35rem'; |
| 762 | menuEl.style.display = 'none'; |
| 763 | menuEl.style.zIndex = '4'; |
| 764 | |
| 765 | const buildMenuItem = (label, streamIndex, isSelected) => |
| 766 | { |
| 767 | const itemEl = document.createElement('button'); |
| 768 | itemEl.type = 'button'; |
| 769 | itemEl.className = 'video-subtitle-overlay-menu-item'; |
| 770 | itemEl.setAttribute('data-image-subtitle-stream-index', streamIndex === null ? 'off' : String(streamIndex)); |
| 771 | itemEl.setAttribute('aria-checked', isSelected ? 'true' : 'false'); |
| 772 | itemEl.style.display = 'block'; |
| 773 | itemEl.style.width = '100%'; |
| 774 | itemEl.style.margin = '0'; |
| 775 | itemEl.style.padding = '0.5rem 0.75rem'; |
| 776 | itemEl.style.border = '0'; |
| 777 | itemEl.style.borderRadius = '0.35rem'; |
| 778 | itemEl.style.background = isSelected ? 'rgba(255, 255, 255, 0.18)' : 'transparent'; |
| 779 | itemEl.style.color = '#fff'; |
| 780 | itemEl.style.textAlign = 'left'; |
| 781 | itemEl.style.cursor = 'pointer'; |
| 782 | itemEl.textContent = label; |
| 783 | itemEl.addEventListener('click', () => |
| 784 | { |
| 785 | setSelectedStreamIndex(streamIndex); |
| 786 | closeMenu(); |
| 787 | }); |
| 788 | return itemEl; |
| 789 | }; |
| 790 | |
| 791 | menuEl.appendChild(buildMenuItem('Off', null, false)); |
| 792 | for (const track of imageTracks) |
| 793 | { |
| 794 | menuEl.appendChild(buildMenuItem(track.label, track.streamIndex, false)); |
| 795 | } |
| 796 | |
| 797 | const registerButton = () => |
| 798 | { |
| 799 | if (!videojs || typeof videojs.getComponent !== 'function' || typeof videojs.registerComponent !== 'function') return; |
| 800 | if (videojs.getComponent('ImageSubtitleButton')) return; |
| 801 | |
| 802 | const Button = videojs.getComponent('Button'); |
| 803 | class ImageSubtitleButton extends Button |
| 804 | { |
| 805 | buildCSSClass () |
| 806 | { |
| 807 | return `${super.buildCSSClass()} vjs-image-subtitle-button`; |
| 808 | } |
| 809 | |
| 810 | createEl () |
| 811 | { |
| 812 | const el = super.createEl(); |
| 813 | el.type = 'button'; |
| 814 | el.setAttribute('title', 'Image subtitles'); |
| 815 | el.setAttribute('aria-label', 'Image subtitles'); |
| 816 | el.innerHTML = '<span aria-hidden="true">IM</span>'; |
| 817 | return el; |
| 818 | } |
| 819 | |
| 820 | handleClick () |
| 821 | { |
| 822 | const controller = this.player().imageSubtitleOverlayController; |
| 823 | if (controller) controller.toggleMenu(); |
| 824 | } |
| 825 | } |
| 826 | |
| 827 | videojs.registerComponent('ImageSubtitleButton', ImageSubtitleButton); |
| 828 | }; |
| 829 | |
| 830 | const attachUi = () => |
| 831 | { |
| 832 | if (!player.el()) return; |
| 833 | registerButton(); |
| 834 | if (overlayEl.parentElement !== player.el()) player.el().appendChild(overlayEl); |
| 835 | if (menuEl.parentElement !== player.el()) player.el().appendChild(menuEl); |
| 836 | const controlBar = typeof player.getChild === 'function' ? player.getChild('controlBar') : null; |
| 837 | if (controlBar && typeof controlBar.addChild === 'function' && !buttonEl) |
| 838 | { |
| 839 | const button = controlBar.addChild('ImageSubtitleButton', {}); |
| 840 | buttonEl = button && typeof button.el === 'function' ? button.el() : null; |
| 841 | updateButtonState(); |
| 842 | } |
| 843 | }; |
| 844 | |
| 845 | const applySavedTracks = () => |
| 846 | { |
| 847 | const savedName = normaliseTrackName(prefs.imageSubtitleTrackName); |
| 848 | if (savedName) |
| 849 | { |
| 850 | const savedByName = imageTracks.find((track) => normaliseTrackName(track.label) === savedName) || null; |
| 851 | if (savedByName) |
| 852 | { |
| 853 | setSelectedStreamIndex(savedByName.streamIndex, { persist: false }); |
| 854 | return; |
| 855 | } |
| 856 | } |
| 857 | |
| 858 | const savedIndex = Number(prefs.imageSubtitleTrackStreamIndex); |
| 859 | if (Number.isInteger(savedIndex) && trackByStreamIndex.has(savedIndex)) |
| 860 | { |
| 861 | setSelectedStreamIndex(savedIndex, { persist: false }); |
| 862 | return; |
| 863 | } |
| 864 | |
| 865 | const defaultTrack = imageTracks.find((track) => track.isDefault) || null; |
| 866 | if (defaultTrack) |
| 867 | { |
| 868 | setSelectedStreamIndex(defaultTrack.streamIndex, { persist: false }); |
| 869 | return; |
| 870 | } |
| 871 | |
| 872 | setSelectedStreamIndex(null, { persist: false }); |
| 873 | }; |
| 874 | |
| 875 | player.imageSubtitleOverlayController = { |
| 876 | toggleMenu, |
| 877 | closeMenu, |
| 878 | applySavedTracks, |
| 879 | captureSelectedTracks: saveSelection, |
| 880 | detach: dispose, |
| 881 | }; |
| 882 | |
| 883 | player.on('timeupdate', () => { void refreshFrame(); }); |
| 884 | player.on('seeking', () => { void refreshFrame(true); }); |
| 885 | player.on('play', () => { void refreshFrame(true); }); |
| 886 | player.on('fullscreenchange', () => { closeMenu(); void refreshFrame(true); }); |
| 887 | player.on('dispose', dispose); |
| 888 | player.ready(() => |
| 889 | { |
| 890 | attachUi(); |
| 891 | updateMenuState(); |
| 892 | updateButtonState(); |
| 893 | applySavedTracks(); |
| 894 | if (menuOpen) openMenu(); |
| 895 | }); |
| 896 | |
| 897 | return player.imageSubtitleOverlayController; |
| 898 | } |
| 899 | |
| 900 | function normaliseVideoDuration (player, durationSeconds) |
| 901 | { |
| 902 | const duration = Number(durationSeconds); |
| 903 | if (!player || !Number.isFinite(duration) || duration <= 0) return; |
| 904 | |
| 905 | let originalDuration = null; |
| 906 | let durationWasChanged = false; |
| 907 | try |
| 908 | { |
| 909 | originalDuration = typeof player.duration === 'function' ? player.duration.bind(player) : null; |
| 910 | installDurationFallback(player, originalDuration, duration); |
| 911 | if (player.__filemanagerDurationApplied) return; |
| 912 | |
| 913 | const current = originalDuration ? Number(originalDuration()) : NaN; |
| 914 | const withinTolerance = Number.isFinite(current) && current >= duration * 0.95; |
| 915 | console.log(`Current duration: ${formatDurationForDebug(current)}, Target time: ${formatDurationForDebug(duration)}, within 95%? ${withinTolerance ? 'yes' : 'no'}`); |
| 916 | if (withinTolerance) |
| 917 | { |
| 918 | player.__filemanagerDurationApplied = true; |
| 919 | return; |
| 920 | } |
| 921 | |
| 922 | if (originalDuration) |
| 923 | { |
| 924 | durationWasChanged = true; |
| 925 | originalDuration(duration); |
| 926 | } |
| 927 | } catch |
| 928 | { |
| 929 | // Ignore players that do not support setting duration. |
| 930 | } |
| 931 | |
| 932 | try |
| 933 | { |
| 934 | const updated = originalDuration ? Number(originalDuration()) : NaN; |
| 935 | if (Number.isFinite(updated) && updated >= duration * 0.95) |
| 936 | { |
| 937 | player.__filemanagerDurationApplied = true; |
| 938 | if (durationWasChanged && typeof player.trigger === 'function') player.trigger('durationchange'); |
| 939 | return; |
| 940 | } |
| 941 | |
| 942 | player.__filemanagerDurationApplied = true; |
| 943 | if (typeof player.trigger === 'function') player.trigger('durationchange'); |
| 944 | } catch |
| 945 | { |
| 946 | // Ignore duration fallback failures. |
| 947 | } |
| 948 | } |
| 949 | |
| 950 | function installDurationFallback (player, originalDuration, duration) |
| 951 | { |
| 952 | if (!player || !originalDuration || player.__filemanagerDurationFallback) return; |
| 953 | |
| 954 | player.__filemanagerDurationFallback = true; |
| 955 | player.duration = function durationWithFallback (...args) |
| 956 | { |
| 957 | if (args.length) return originalDuration(...args); |
| 958 | const current = Number(originalDuration()); |
| 959 | return Number.isFinite(current) && current >= duration * 0.95 ? current : duration; |
| 960 | }; |
| 961 | } |
| 962 | |
| 963 | function formatDurationForDebug (seconds) |
| 964 | { |
| 965 | const value = Number(seconds); |
| 966 | if (!Number.isFinite(value) || value < 0) return 'unknown'; |
| 967 | |
| 968 | const totalSeconds = Math.floor(value); |
| 969 | const hh = String(Math.floor(totalSeconds / 3600)).padStart(2, '0'); |
| 970 | const mm = String(Math.floor((totalSeconds % 3600) / 60)).padStart(2, '0'); |
| 971 | const ss = String(totalSeconds % 60).padStart(2, '0'); |
| 972 | return `${hh}:${mm}:${ss}`; |
| 973 | } |
| 974 | |
| 975 | function ensureVideoPlaybackUi (player, durationSeconds) |
| 976 | { |
| 977 | if (!player || typeof player.on !== 'function') return; |
| 978 | |
| 979 | const forceVodUi = () => |
| 980 | { |
| 981 | normaliseVideoDuration(player, durationSeconds); |
| 982 | |
| 983 | try |
| 984 | { |
| 985 | if (player.liveTracker && typeof player.liveTracker.stopTracking === 'function') |
| 986 | { |
| 987 | player.liveTracker.stopTracking(); |
| 988 | } |
| 989 | } catch |
| 990 | { |
| 991 | // Ignore live tracker availability issues. |
| 992 | } |
| 993 | |
| 994 | try |
| 995 | { |
| 996 | if (typeof player.removeClass === 'function') |
| 997 | { |
| 998 | player.removeClass('vjs-live'); |
| 999 | } |
| 1000 | } catch |
| 1001 | { |
| 1002 | // Ignore class update failures. |
| 1003 | } |
| 1004 | |
| 1005 | try |
| 1006 | { |
| 1007 | const display = player.el() && player.el().querySelector('.vjs-live-display'); |
| 1008 | if (display) display.style.display = 'none'; |
| 1009 | } catch |
| 1010 | { |
| 1011 | // Ignore missing DOM. |
| 1012 | } |
| 1013 | }; |
| 1014 | |
| 1015 | player.ready(forceVodUi); |
| 1016 | player.on('loadedmetadata', forceVodUi); |
| 1017 | player.on('durationchange', forceVodUi); |
| 1018 | player.on('loadedplaylist', forceVodUi); |
| 1019 | } |
| 1020 | |
| 1021 | async function reportWatchProgress (filePath, progress) |
| 1022 | { |
| 1023 | if (!filePath || !Number.isFinite(progress)) return; |
| 1024 | await api('POST', '/files/watch-progress', { |
| 1025 | filePath, |
| 1026 | progress, |
| 1027 | }).catch(() => null); |
| 1028 | |
| 1029 | const nextStatus = progress >= 0.7 ? 'fully' : progress >= 0.1 ? 'partway' : null; |
| 1030 | if (!nextStatus) return; |
| 1031 | |
| 1032 | const prev = STATE.watchedStatusByPath[filePath]; |
| 1033 | if (prev === 'fully') return; |
| 1034 | STATE.watchedStatusByPath[filePath] = nextStatus; |
| 1035 | |
| 1036 | const iconEl = findTileIconByPath(filePath); |
| 1037 | renderWatchedOverlayOnIcon(iconEl, nextStatus); |
| 1038 | } |
| 1039 | |
| 1040 | function getOrCreateClientBindingId () |
| 1041 | { |
| 1042 | if (STATE.clientBindingId) return STATE.clientBindingId; |
| 1043 | |
| 1044 | try |
| 1045 | { |
| 1046 | const existing = localStorage.getItem(CLIENT_BINDING_KEY); |
| 1047 | if (existing && typeof existing === 'string') |
| 1048 | { |
| 1049 | STATE.clientBindingId = existing; |
| 1050 | return existing; |
| 1051 | } |
| 1052 | } catch |
| 1053 | { |
| 1054 | // Ignore storage read errors. |
| 1055 | } |
| 1056 | |
| 1057 | const created = randomIdHex(16); |
| 1058 | STATE.clientBindingId = created; |
| 1059 | |
| 1060 | try |
| 1061 | { |
| 1062 | localStorage.setItem(CLIENT_BINDING_KEY, created); |
| 1063 | } catch |
| 1064 | { |
| 1065 | // Ignore storage write errors; in-memory fallback still keeps this stable |
| 1066 | // for the current page session. |
| 1067 | } |
| 1068 | |
| 1069 | return created; |
| 1070 | } |
| 1071 | |
| 1072 | function formatBytes (bytes) |
| 1073 | { |
| 1074 | if (bytes == null) return '—'; |
| 1075 | if (bytes < 1024) return bytes + ' B'; |
| 1076 | if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB'; |
| 1077 | if (bytes < 1073741824) return (bytes / 1048576).toFixed(1) + ' MB'; |
| 1078 | return (bytes / 1073741824).toFixed(2) + ' GB'; |
| 1079 | } |
| 1080 | |
| 1081 | function parseHumanSize (input) |
| 1082 | { |
| 1083 | const raw = String(input || '').trim(); |
| 1084 | if (!raw) return null; |
| 1085 | |
| 1086 | const m = raw.match(/^(\d+(?:\.\d+)?)\s*([kmgt]?)(?:i?b)?$/i); |
| 1087 | if (!m) return null; |
| 1088 | |
| 1089 | const value = Number(m[1]); |
| 1090 | if (!Number.isFinite(value) || value <= 0) return null; |
| 1091 | |
| 1092 | const unit = String(m[2] || '').toLowerCase(); |
| 1093 | const multipliers = { |
| 1094 | '': 1, |
| 1095 | k: 1024, |
| 1096 | m: 1024 * 1024, |
| 1097 | g: 1024 * 1024 * 1024, |
| 1098 | t: 1024 * 1024 * 1024 * 1024, |
| 1099 | }; |
| 1100 | return Math.floor(value * (multipliers[unit] || 1)); |
| 1101 | } |
| 1102 | |
| 1103 | function updateAdminSizeFeedback (rawValue) |
| 1104 | { |
| 1105 | const feedback = document.getElementById('admin-user-size-feedback'); |
| 1106 | if (!feedback) return { bytes: null, valid: true }; |
| 1107 | |
| 1108 | const trimmed = String(rawValue || '').trim(); |
| 1109 | if (!trimmed) |
| 1110 | { |
| 1111 | feedback.textContent = ''; |
| 1112 | feedback.classList.add('hidden'); |
| 1113 | feedback.classList.remove('ok', 'err'); |
| 1114 | return { bytes: null, valid: true }; |
| 1115 | } |
| 1116 | |
| 1117 | const bytes = parseHumanSize(trimmed); |
| 1118 | feedback.classList.remove('hidden', 'ok', 'err'); |
| 1119 | if (bytes == null) |
| 1120 | { |
| 1121 | feedback.textContent = 'Invalid size. Use formats like 25 MB, 1 GB, or 500 KB.'; |
| 1122 | feedback.classList.add('err'); |
| 1123 | return { bytes: null, valid: false }; |
| 1124 | } |
| 1125 | |
| 1126 | feedback.textContent = `Valid size: ${formatBytes(bytes)}`; |
| 1127 | feedback.classList.add('ok'); |
| 1128 | return { bytes, valid: true }; |
| 1129 | } |
| 1130 | |
| 1131 | function extOf (name) |
| 1132 | { |
| 1133 | const i = name.lastIndexOf('.'); |
| 1134 | return i >= 0 ? name.slice(i + 1).toLowerCase() : ''; |
| 1135 | } |
| 1136 | |
| 1137 | function getPathSep (basePath) |
| 1138 | { |
| 1139 | return basePath && basePath.includes('\\') ? '\\' : '/'; |
| 1140 | } |
| 1141 | |
| 1142 | function joinServerPath (basePath, segment) |
| 1143 | { |
| 1144 | const sep = getPathSep(basePath); |
| 1145 | const base = String(basePath || '').replace(/[\\/]+$/, ''); |
| 1146 | return base + sep + segment; |
| 1147 | } |
| 1148 | |
| 1149 | function samePath (a, b) |
| 1150 | { |
| 1151 | if (!a || !b) return false; |
| 1152 | return String(a).toLowerCase() === String(b).toLowerCase(); |
| 1153 | } |
| 1154 | |
| 1155 | function pathInside (child, root) |
| 1156 | { |
| 1157 | if (!child || !root) return false; |
| 1158 | if (samePath(child, root)) return true; |
| 1159 | const sep = getPathSep(root); |
| 1160 | return String(child).toLowerCase().startsWith((String(root) + sep).toLowerCase()); |
| 1161 | } |
| 1162 | |
| 1163 | function relativePathFromRoot (targetPath, rootPath) |
| 1164 | { |
| 1165 | if (!targetPath || !rootPath) return String(targetPath || ''); |
| 1166 | if (samePath(targetPath, rootPath)) return '.'; |
| 1167 | |
| 1168 | const prefix = String(rootPath).replace(/[\\/]+$/, ''); |
| 1169 | const rel = String(targetPath).slice(prefix.length).replace(/^[\\/]+/, ''); |
| 1170 | if (!rel) return '.'; |
| 1171 | return rel; |
| 1172 | } |
| 1173 | |
| 1174 | function displayPathWithRootLabel (targetPath, rootPath, rootLabel) |
| 1175 | { |
| 1176 | const rel = relativePathFromRoot(targetPath, rootPath); |
| 1177 | const safeRoot = String(rootLabel || '').replace(/^\/+|\/+$/g, ''); |
| 1178 | if (!safeRoot) return '/'; |
| 1179 | if (rel === '.') return `/${safeRoot}`; |
| 1180 | return `/${safeRoot}/${String(rel).replace(/\\/g, '/')}`; |
| 1181 | } |
| 1182 | |
| 1183 | function splitNameExt (name) |
| 1184 | { |
| 1185 | const dot = String(name || '').lastIndexOf('.'); |
| 1186 | if (dot <= 0) return { stem: String(name || ''), ext: '' }; |
| 1187 | return { |
| 1188 | stem: String(name).slice(0, dot), |
| 1189 | ext: String(name).slice(dot), |
| 1190 | }; |
| 1191 | } |
| 1192 | |
| 1193 | function nextAvailableName (requestedName, existingNames) |
| 1194 | { |
| 1195 | const set = existingNames instanceof Set ? existingNames : new Set(existingNames || []); |
| 1196 | if (!set.has(requestedName)) return requestedName; |
| 1197 | |
| 1198 | const { stem, ext } = splitNameExt(requestedName); |
| 1199 | let n = 1; |
| 1200 | while (n <= 10000) |
| 1201 | { |
| 1202 | const candidate = `${stem || 'file'} (${n})${ext}`; |
| 1203 | if (!set.has(candidate)) return candidate; |
| 1204 | n++; |
| 1205 | } |
| 1206 | |
| 1207 | return requestedName; |
| 1208 | } |
| 1209 | |
| 1210 | async function listDirNameSet (dir) |
| 1211 | { |
| 1212 | const data = await api('GET', `/files/list?dir=${encodeURIComponent(dir)}`); |
| 1213 | const names = new Set(); |
| 1214 | for (const it of ((data && data.items) || [])) names.add(it.name); |
| 1215 | return names; |
| 1216 | } |
| 1217 | |
| 1218 | function cloneFileWithName (file, newName) |
| 1219 | { |
| 1220 | return new File([file], newName, { |
| 1221 | type: file.type, |
| 1222 | lastModified: file.lastModified, |
| 1223 | }); |
| 1224 | } |
| 1225 | |
| 1226 | function saveSessionState () |
| 1227 | { |
| 1228 | if (!STATE.token) return; |
| 1229 | const now = Date.now(); |
| 1230 | STATE.lastOperationAt = now; |
| 1231 | const payload = { |
| 1232 | token: STATE.token, |
| 1233 | dir: STATE.currentDir || null, |
| 1234 | rootPath: STATE.currentRoot ? STATE.currentRoot.path : null, |
| 1235 | lastOperationAt: STATE.lastOperationAt, |
| 1236 | }; |
| 1237 | try |
| 1238 | { |
| 1239 | localStorage.setItem(SESSION_KEY, JSON.stringify(payload)); |
| 1240 | } catch |
| 1241 | { |
| 1242 | // Ignore storage errors (private mode/full quota). |
| 1243 | } |
| 1244 | } |
| 1245 | |
| 1246 | function loadSessionState () |
| 1247 | { |
| 1248 | try |
| 1249 | { |
| 1250 | const raw = localStorage.getItem(SESSION_KEY); |
| 1251 | if (!raw) return null; |
| 1252 | const parsed = JSON.parse(raw); |
| 1253 | if (!parsed || typeof parsed.token !== 'string') return null; |
| 1254 | if (!Number.isFinite(parsed.lastOperationAt)) return null; |
| 1255 | |
| 1256 | if (Date.now() - parsed.lastOperationAt > SESSION_IDLE_TIMEOUT_MS) |
| 1257 | { |
| 1258 | clearSessionState(); |
| 1259 | return null; |
| 1260 | } |
| 1261 | |
| 1262 | return parsed; |
| 1263 | } catch |
| 1264 | { |
| 1265 | return null; |
| 1266 | } |
| 1267 | } |
| 1268 | |
| 1269 | function clearSessionState () |
| 1270 | { |
| 1271 | try { localStorage.removeItem(SESSION_KEY); } catch { /* ignore */ } |
| 1272 | } |
| 1273 | |
| 1274 | // ─────────────────────────────────────────────────────────────────────────── |
| 1275 | // API |
| 1276 | // ─────────────────────────────────────────────────────────────────────────── |
| 1277 | |
| 1278 | async function api (method, path, body, opts = {}) |
| 1279 | { |
| 1280 | const headers = { 'Content-Type': 'application/json' }; |
| 1281 | const noAutoLogout = !!opts.noAutoLogout; |
| 1282 | if (STATE.token) |
| 1283 | { |
| 1284 | headers['Authorization'] = 'Bearer ' + STATE.token; |
| 1285 | try |
| 1286 | { |
| 1287 | const fp = getFingerprint(); |
| 1288 | if (fp) headers['X-Fp'] = fp; |
| 1289 | } catch |
| 1290 | { |
| 1291 | // Continue without a fingerprint header in constrained test/runtime contexts. |
| 1292 | } |
| 1293 | } |
| 1294 | const fetchOpts = { ...opts }; |
| 1295 | delete fetchOpts.noAutoLogout; |
| 1296 | const res = await fetch('/api' + path, { |
| 1297 | method, |
| 1298 | headers, |
| 1299 | body: body != null ? JSON.stringify(body) : undefined, |
| 1300 | ...fetchOpts, |
| 1301 | }); |
| 1302 | if (!res.ok) |
| 1303 | { |
| 1304 | const j = await res.json().catch(() => ({})); |
| 1305 | // Session-expired → force re-login |
| 1306 | if (res.status === 401) |
| 1307 | { |
| 1308 | if (!noAutoLogout) logout(); |
| 1309 | return null; |
| 1310 | } |
| 1311 | throw new Error(j.error || res.statusText); |
| 1312 | } |
| 1313 | if (STATE.token && !path.startsWith('/auth/server-key') && !path.startsWith('/auth/setup-needed')) |
| 1314 | { |
| 1315 | saveSessionState(); |
| 1316 | } |
| 1317 | return res.json(); |
| 1318 | } |
| 1319 | |
| 1320 | // ─────────────────────────────────────────────────────────────────────────── |
| 1321 | // TOAST |
| 1322 | // ─────────────────────────────────────────────────────────────────────────── |
| 1323 | |
| 1324 | function toast (msg, type = '') |
| 1325 | { |
| 1326 | const el = document.createElement('div'); |
| 1327 | el.className = 'toast-msg' + (type ? ' ' + type : ''); |
| 1328 | el.textContent = msg; |
| 1329 | document.getElementById('toast').appendChild(el); |
| 1330 | setTimeout(() => el.remove(), 3500); |
| 1331 | } |
| 1332 | |
| 1333 | // ─────────────────────────────────────────────────────────────────────────── |
| 1334 | // DIALOG MODALS — centralised replacements for alert / confirm / prompt |
| 1335 | // ─────────────────────────────────────────────────────────────────────────── |
| 1336 | |
| 1337 | /** |
| 1338 | * Show a confirmation dialog. |
| 1339 | * @param {string} title |
| 1340 | * @param {string} message |
| 1341 | * @returns {Promise<boolean>} true = OK, false = Cancel |
| 1342 | */ |
| 1343 | function showConfirm (title, message, { html = false, okLabel = null } = {}) |
| 1344 | { |
| 1345 | return new Promise((resolve) => |
| 1346 | { |
| 1347 | const overlay = document.getElementById('confirm-modal'); |
| 1348 | document.getElementById('confirm-modal-title').textContent = title; |
| 1349 | const msgEl = document.getElementById('confirm-modal-message'); |
| 1350 | if (html) msgEl.innerHTML = message; |
| 1351 | else msgEl.textContent = message; |
| 1352 | overlay.classList.remove('hidden'); |
| 1353 | |
| 1354 | const ok = document.getElementById('confirm-modal-ok'); |
| 1355 | const prevOkLabel = ok.textContent; |
| 1356 | if (okLabel != null) ok.textContent = okLabel; |
| 1357 | |
| 1358 | const cancel = document.getElementById('confirm-modal-cancel'); |
| 1359 | |
| 1360 | function finish (result) |
| 1361 | { |
| 1362 | overlay.classList.add('hidden'); |
| 1363 | ok.textContent = prevOkLabel; |
| 1364 | ok.removeEventListener('click', onOk); |
| 1365 | cancel.removeEventListener('click', onCancel); |
| 1366 | resolve(result); |
| 1367 | } |
| 1368 | function onOk () { finish(true); } |
| 1369 | function onCancel () { finish(false); } |
| 1370 | |
| 1371 | ok.addEventListener('click', onOk); |
| 1372 | cancel.addEventListener('click', onCancel); |
| 1373 | ok.focus(); |
| 1374 | }); |
| 1375 | } |
| 1376 | |
| 1377 | function escHtml (s) |
| 1378 | { |
| 1379 | return String(s || '') |
| 1380 | .replace(/&/g, '&') |
| 1381 | .replace(/</g, '<') |
| 1382 | .replace(/>/g, '>') |
| 1383 | .replace(/"/g, '"'); |
| 1384 | } |
| 1385 | |
| 1386 | /** |
| 1387 | * Show a text-input dialog. |
| 1388 | * @param {string} title |
| 1389 | * @param {string} [message] — optional helper text shown above the input |
| 1390 | * @param {string} [defaultValue] — pre-filled value |
| 1391 | * @returns {Promise<string|null>} string = submitted value, null = cancelled |
| 1392 | */ |
| 1393 | function showPrompt (title, message = '', defaultValue = '') |
| 1394 | { |
| 1395 | return new Promise((resolve) => |
| 1396 | { |
| 1397 | const overlay = document.getElementById('prompt-modal'); |
| 1398 | const msgEl = document.getElementById('prompt-modal-message'); |
| 1399 | const input = document.getElementById('prompt-modal-input'); |
| 1400 | const errorEl = document.getElementById('prompt-modal-error'); |
| 1401 | const form = document.getElementById('prompt-modal-form'); |
| 1402 | const cancel = document.getElementById('prompt-modal-cancel'); |
| 1403 | |
| 1404 | document.getElementById('prompt-modal-title').textContent = title; |
| 1405 | msgEl.textContent = message; |
| 1406 | msgEl.classList.toggle('hidden', !message); |
| 1407 | input.value = defaultValue; |
| 1408 | errorEl.classList.add('hidden'); |
| 1409 | overlay.classList.remove('hidden'); |
| 1410 | input.focus(); |
| 1411 | input.select(); |
| 1412 | |
| 1413 | function finish (result) |
| 1414 | { |
| 1415 | overlay.classList.add('hidden'); |
| 1416 | form.removeEventListener('submit', onSubmit); |
| 1417 | cancel.removeEventListener('click', onCancel); |
| 1418 | resolve(result); |
| 1419 | } |
| 1420 | function onSubmit (e) |
| 1421 | { |
| 1422 | e.preventDefault(); |
| 1423 | finish(input.value); |
| 1424 | } |
| 1425 | function onCancel () { finish(null); } |
| 1426 | |
| 1427 | form.addEventListener('submit', onSubmit); |
| 1428 | cancel.addEventListener('click', onCancel); |
| 1429 | }); |
| 1430 | } |
| 1431 | |
| 1432 | /** |
| 1433 | * Show an overwrite-decision dialog for a single file conflict. |
| 1434 | * @param {string} filename |
| 1435 | * @returns {Promise<'yes'|'no'|'all'|'none'>} |
| 1436 | */ |
| 1437 | function showOverwrite (filename) |
| 1438 | { |
| 1439 | return new Promise((resolve) => |
| 1440 | { |
| 1441 | const overlay = document.getElementById('overwrite-modal'); |
| 1442 | document.getElementById('overwrite-modal-filename').textContent = filename; |
| 1443 | overlay.classList.remove('hidden'); |
| 1444 | |
| 1445 | const btnYes = document.getElementById('overwrite-modal-yes'); |
| 1446 | const btnNo = document.getElementById('overwrite-modal-no'); |
| 1447 | const btnAll = document.getElementById('overwrite-modal-all'); |
| 1448 | const btnSkipAll = document.getElementById('overwrite-modal-skip-all'); |
| 1449 | |
| 1450 | function finish (result) |
| 1451 | { |
| 1452 | overlay.classList.add('hidden'); |
| 1453 | btnYes.removeEventListener('click', onYes); |
| 1454 | btnNo.removeEventListener('click', onNo); |
| 1455 | btnAll.removeEventListener('click', onAll); |
| 1456 | btnSkipAll.removeEventListener('click', onSkipAll); |
| 1457 | resolve(result); |
| 1458 | } |
| 1459 | function onYes () { finish('yes'); } |
| 1460 | function onNo () { finish('no'); } |
| 1461 | function onAll () { finish('all'); } |
| 1462 | function onSkipAll () { finish('none'); } |
| 1463 | |
| 1464 | btnYes.addEventListener('click', onYes); |
| 1465 | btnNo.addEventListener('click', onNo); |
| 1466 | btnAll.addEventListener('click', onAll); |
| 1467 | btnSkipAll.addEventListener('click', onSkipAll); |
| 1468 | btnNo.focus(); |
| 1469 | }); |
| 1470 | } |
| 1471 | |
| 1472 | /** |
| 1473 | * Show single-file conflict options. |
| 1474 | * @param {string} filename |
| 1475 | * @param {string} renameTo |
| 1476 | * @param {string} mode - upload|move |
| 1477 | * @returns {Promise<'overwrite'|'rename'|'cancel'>} |
| 1478 | */ |
| 1479 | function showFileConflictChoice (filename, renameTo, mode = 'upload') |
| 1480 | { |
| 1481 | return new Promise((resolve) => |
| 1482 | { |
| 1483 | const overlay = document.getElementById('file-conflict-modal'); |
| 1484 | const title = document.getElementById('file-conflict-title'); |
| 1485 | const fileEl = document.getElementById('file-conflict-filename'); |
| 1486 | const renameEl = document.getElementById('file-conflict-rename'); |
| 1487 | const btnOverwrite = document.getElementById('file-conflict-overwrite'); |
| 1488 | const btnRename = document.getElementById('file-conflict-rename-btn'); |
| 1489 | const btnCancel = document.getElementById('file-conflict-cancel'); |
| 1490 | |
| 1491 | title.textContent = mode === 'move' ? 'Move file' : 'Upload file'; |
| 1492 | fileEl.textContent = filename; |
| 1493 | renameEl.textContent = renameTo; |
| 1494 | btnRename.textContent = `Rename (${renameTo})`; |
| 1495 | |
| 1496 | overlay.classList.remove('hidden'); |
| 1497 | |
| 1498 | function finish (result) |
| 1499 | { |
| 1500 | overlay.classList.add('hidden'); |
| 1501 | btnOverwrite.removeEventListener('click', onOverwrite); |
| 1502 | btnRename.removeEventListener('click', onRename); |
| 1503 | btnCancel.removeEventListener('click', onCancel); |
| 1504 | resolve(result); |
| 1505 | } |
| 1506 | |
| 1507 | function onOverwrite () { finish('overwrite'); } |
| 1508 | function onRename () { finish('rename'); } |
| 1509 | function onCancel () { finish('cancel'); } |
| 1510 | |
| 1511 | btnOverwrite.addEventListener('click', onOverwrite); |
| 1512 | btnRename.addEventListener('click', onRename); |
| 1513 | btnCancel.addEventListener('click', onCancel); |
| 1514 | btnCancel.focus(); |
| 1515 | }); |
| 1516 | } |
| 1517 | |
| 1518 | // ─────────────────────────────────────────────────────────────────────────── |
| 1519 | // SHARE MODAL |
| 1520 | // ─────────────────────────────────────────────────────────────────────────── |
| 1521 | |
| 1522 | async function openShareModal (item) |
| 1523 | { |
| 1524 | const overlay = document.getElementById('share-modal'); |
| 1525 | const urlInput = document.getElementById('share-url-input'); |
| 1526 | const copyBtn = document.getElementById('share-copy-btn'); |
| 1527 | const okBtn = document.getElementById('share-modal-ok'); |
| 1528 | const closeBtn = document.getElementById('share-modal-close'); |
| 1529 | const msgEl = document.getElementById('share-modal-msg'); |
| 1530 | |
| 1531 | urlInput.value = 'Creating link...'; |
| 1532 | copyBtn.disabled = true; |
| 1533 | msgEl.textContent = 'This link is valid for 24 hours.'; |
| 1534 | overlay.classList.remove('hidden'); |
| 1535 | |
| 1536 | let data; |
| 1537 | try |
| 1538 | { |
| 1539 | data = await api('POST', '/share/create', { filePath: item.path }); |
| 1540 | } catch (err) |
| 1541 | { |
| 1542 | msgEl.textContent = 'Error: ' + (err.message || 'Could not create link.'); |
| 1543 | urlInput.value = ''; |
| 1544 | return; |
| 1545 | } |
| 1546 | |
| 1547 | if (!data || !data.token) |
| 1548 | { |
| 1549 | msgEl.textContent = 'Unknown error while creating link.'; |
| 1550 | urlInput.value = ''; |
| 1551 | return; |
| 1552 | } |
| 1553 | |
| 1554 | const shareUrl = `${location.origin}/share/${data.token}`; |
| 1555 | urlInput.value = shareUrl; |
| 1556 | copyBtn.disabled = false; |
| 1557 | |
| 1558 | function close () |
| 1559 | { |
| 1560 | overlay.classList.add('hidden'); |
| 1561 | okBtn.removeEventListener('click', close); |
| 1562 | closeBtn.removeEventListener('click', close); |
| 1563 | copyBtn.removeEventListener('click', onCopy); |
| 1564 | } |
| 1565 | |
| 1566 | function onCopy () |
| 1567 | { |
| 1568 | navigator.clipboard.writeText(shareUrl).then(() => |
| 1569 | { |
| 1570 | const orig = copyBtn.textContent; |
| 1571 | copyBtn.textContent = 'Copied!'; |
| 1572 | setTimeout(() => { copyBtn.textContent = orig; }, 1500); |
| 1573 | }).catch(() => |
| 1574 | { |
| 1575 | // Fallback: select the text |
| 1576 | urlInput.select(); |
| 1577 | }); |
| 1578 | } |
| 1579 | |
| 1580 | okBtn.addEventListener('click', close); |
| 1581 | closeBtn.addEventListener('click', close); |
| 1582 | copyBtn.addEventListener('click', onCopy); |
| 1583 | okBtn.focus(); |
| 1584 | } |
| 1585 | |
| 1586 | // ─────────────────────────────────────────────────────────────────────────── |
| 1587 | // AUTH FLOW |
| 1588 | // ─────────────────────────────────────────────────────────────────────────── |
| 1589 | |
| 1590 | function showAuthOverlay (setupMode = false) |
| 1591 | { |
| 1592 | if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return; |
| 1593 | document.getElementById('app').classList.add('hidden'); |
| 1594 | const overlay = document.getElementById('auth-overlay'); |
| 1595 | const usernameInput = document.getElementById('auth-username'); |
| 1596 | const passwordInput = document.getElementById('auth-password'); |
| 1597 | overlay.classList.remove('hidden'); |
| 1598 | document.getElementById('auth-title').textContent = setupMode ? 'Create Admin Account' : 'Sign In'; |
| 1599 | document.getElementById('auth-subtitle').classList.toggle('hidden', !setupMode); |
| 1600 | const submitBtn = document.getElementById('auth-submit'); |
| 1601 | submitBtn.disabled = false; |
| 1602 | submitBtn.textContent = setupMode ? 'Create Account' : 'Sign In'; |
| 1603 | document.getElementById('auth-error').classList.add('hidden'); |
| 1604 | usernameInput.value = ''; |
| 1605 | passwordInput.value = ''; |
| 1606 | usernameInput.autocomplete = 'username'; |
| 1607 | passwordInput.autocomplete = setupMode ? 'new-password' : 'current-password'; |
| 1608 | usernameInput.focus(); |
| 1609 | document.getElementById('auth-form').dataset.mode = setupMode ? 'setup' : 'login'; |
| 1610 | } |
| 1611 | |
| 1612 | function showApp () |
| 1613 | { |
| 1614 | if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return; |
| 1615 | document.getElementById('auth-overlay').classList.add('hidden'); |
| 1616 | document.getElementById('app').classList.remove('hidden'); |
| 1617 | if (isMobileViewport()) |
| 1618 | { |
| 1619 | hideSidebarPanel(); |
| 1620 | } else |
| 1621 | { |
| 1622 | openFolderSidebar(); |
| 1623 | } |
| 1624 | document.getElementById('btn-admin').classList.toggle('hidden', !STATE.isAdmin); |
| 1625 | const userLabel = document.getElementById('user-menu-label'); |
| 1626 | if (userLabel) userLabel.textContent = STATE.username || 'User'; |
| 1627 | void refreshGlobalFavicon(); |
| 1628 | if (STATE.isAdmin) |
| 1629 | { |
| 1630 | void refreshAdminUpdateStatus(); |
| 1631 | } |
| 1632 | else |
| 1633 | { |
| 1634 | setAdminUpdateBadge(0); |
| 1635 | } |
| 1636 | startAutoRefresh(); |
| 1637 | } |
| 1638 | |
| 1639 | async function initAuth () |
| 1640 | { |
| 1641 | // Generate a fresh key pair in the background; login falls back gracefully |
| 1642 | // while this is still in progress. |
| 1643 | generateClientKeyPair().catch(() => |
| 1644 | { |
| 1645 | toast('Secure crypto unavailable in this browser context; using compatibility login mode.', 'err'); |
| 1646 | }); |
| 1647 | |
| 1648 | // Fetch server public key |
| 1649 | const { publicKey } = await api('GET', '/auth/server-key').catch(() => ({ publicKey: null })); |
| 1650 | if (publicKey) STATE.serverPublicKeyJwk = publicKey; |
| 1651 | if (!publicKey && hasWebCrypto()) { toast('Could not reach server.', 'err'); return; } |
| 1652 | STATE.serverPublicKeyJwk = publicKey; |
| 1653 | |
| 1654 | // Check whether first-run setup is needed |
| 1655 | const { needed } = await api('GET', '/auth/setup-needed').catch(() => ({ needed: false })); |
| 1656 | |
| 1657 | if (!needed) |
| 1658 | { |
| 1659 | const saved = loadSessionState(); |
| 1660 | if (saved && saved.token) |
| 1661 | { |
| 1662 | STATE.token = saved.token; |
| 1663 | STATE.restoreDir = saved.dir || null; |
| 1664 | STATE.restoreRootPath = saved.rootPath || null; |
| 1665 | STATE.lastOperationAt = saved.lastOperationAt; |
| 1666 | |
| 1667 | const me = await api('GET', '/auth/me', null, { noAutoLogout: true }).catch(() => null); |
| 1668 | if (me) |
| 1669 | { |
| 1670 | STATE.username = me.username; |
| 1671 | STATE.isAdmin = me.isAdmin; |
| 1672 | STATE.permissions = me.permissions; |
| 1673 | showApp(); |
| 1674 | await loadRoots({ |
| 1675 | preferredDir: STATE.restoreDir, |
| 1676 | preferredRootPath: STATE.restoreRootPath, |
| 1677 | }); |
| 1678 | return; |
| 1679 | } |
| 1680 | |
| 1681 | STATE.token = null; |
| 1682 | clearSessionState(); |
| 1683 | } |
| 1684 | } |
| 1685 | |
| 1686 | showAuthOverlay(needed); |
| 1687 | } |
| 1688 | |
| 1689 | async function doLogin (username, password, isSetup) |
| 1690 | { |
| 1691 | const encrypted = await hybridEncryptForServer({ username, password }); |
| 1692 | const endpoint = isSetup ? '/auth/setup' : '/auth/login'; |
| 1693 | |
| 1694 | let data; |
| 1695 | try |
| 1696 | { |
| 1697 | data = await api('POST', endpoint, { |
| 1698 | encrypted, |
| 1699 | clientPublicKey: STATE.clientPublicKeyJwk, |
| 1700 | fingerprint: getFingerprint(), |
| 1701 | }); |
| 1702 | } catch (err) |
| 1703 | { |
| 1704 | return err.message; |
| 1705 | } |
| 1706 | |
| 1707 | if (!data) return 'Login failed.'; |
| 1708 | |
| 1709 | // Decrypt the token sent back by the server |
| 1710 | const token = await hybridDecryptFromServer(data.encrypted || data); |
| 1711 | if (!token) return 'Login failed.'; |
| 1712 | STATE.token = token; |
| 1713 | |
| 1714 | // Load user info |
| 1715 | const me = await api('GET', '/auth/me'); |
| 1716 | if (!me) return 'Session error.'; |
| 1717 | |
| 1718 | STATE.username = me.username; |
| 1719 | STATE.isAdmin = me.isAdmin; |
| 1720 | STATE.permissions = me.permissions; |
| 1721 | |
| 1722 | saveSessionState(); |
| 1723 | showApp(); |
| 1724 | await loadRoots(); |
| 1725 | return null; // no error |
| 1726 | } |
| 1727 | |
| 1728 | function logout () |
| 1729 | { |
| 1730 | void performLogout(); |
| 1731 | } |
| 1732 | |
| 1733 | async function performLogout () |
| 1734 | { |
| 1735 | const tokenAtStart = STATE.token; |
| 1736 | stopAutoRefresh(); |
| 1737 | |
| 1738 | if (tokenAtStart) |
| 1739 | { |
| 1740 | try |
| 1741 | { |
| 1742 | await api('POST', '/auth/logout', {}, { noAutoLogout: true }); |
| 1743 | } catch |
| 1744 | { |
| 1745 | // Ignore network errors while logging out locally. |
| 1746 | } |
| 1747 | } |
| 1748 | |
| 1749 | STATE.token = null; |
| 1750 | STATE.username = null; |
| 1751 | STATE.isAdmin = false; |
| 1752 | STATE.permissions = {}; |
| 1753 | STATE.currentDir = null; |
| 1754 | STATE.currentRoot = null; |
| 1755 | STATE.items = []; |
| 1756 | STATE.restoreDir = null; |
| 1757 | STATE.restoreRootPath = null; |
| 1758 | STATE.lastOperationAt = null; |
| 1759 | _adminUpdateStatus = null; |
| 1760 | setAdminUpdateBadge(0); |
| 1761 | clearSessionState(); |
| 1762 | closePreview({ force: true }); |
| 1763 | closeSidebar(); |
| 1764 | await initAuth(); |
| 1765 | } |
| 1766 | |
| 1767 | // ─────────────────────────────────────────────────────────────────────────── |
| 1768 | // NAVIGATION |
| 1769 | // ─────────────────────────────────────────────────────────────────────────── |
| 1770 | |
| 1771 | async function loadRoots (opts = {}) |
| 1772 | { |
| 1773 | const data = await api('GET', '/files/roots'); |
| 1774 | if (!data) return; |
| 1775 | STATE.roots = data.roots; |
| 1776 | |
| 1777 | const preferredDir = opts.preferredDir || null; |
| 1778 | const preferredRootPath = opts.preferredRootPath || null; |
| 1779 | |
| 1780 | if (preferredDir && preferredRootPath) |
| 1781 | { |
| 1782 | const preferredRoot = STATE.roots.find(r => samePath(r.path, preferredRootPath)); |
| 1783 | if (preferredRoot && pathInside(preferredDir, preferredRoot.path)) |
| 1784 | { |
| 1785 | try |
| 1786 | { |
| 1787 | await navigateTo(preferredDir, preferredRoot, { keepSidebar: true }); |
| 1788 | return; |
| 1789 | } catch |
| 1790 | { |
| 1791 | // Fall back to default root behavior. |
| 1792 | } |
| 1793 | } |
| 1794 | } |
| 1795 | |
| 1796 | if (STATE.roots.length === 1) |
| 1797 | { |
| 1798 | // Single root → open it directly |
| 1799 | await navigateTo(STATE.roots[0].path, STATE.roots[0]); |
| 1800 | } else |
| 1801 | { |
| 1802 | renderRootsView(); |
| 1803 | } |
| 1804 | } |
| 1805 | |
| 1806 | function renderRootsView () |
| 1807 | { |
| 1808 | if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return; |
| 1809 | disconnectThumbnailObserver(); |
| 1810 | disconnectFolderIconObserver(); |
| 1811 | revokeThumbnails(); |
| 1812 | |
| 1813 | STATE.currentDir = null; |
| 1814 | STATE.currentRoot = null; |
| 1815 | STATE.searchQuery = null; |
| 1816 | saveSessionState(); |
| 1817 | renderBreadcrumb(); |
| 1818 | const grid = document.getElementById('file-grid'); |
| 1819 | grid.innerHTML = ''; |
| 1820 | document.getElementById('empty-notice').classList.add('hidden'); |
| 1821 | document.getElementById('folder-stats').classList.add('hidden'); |
| 1822 | closeSidebar(); |
| 1823 | |
| 1824 | for (const root of STATE.roots) |
| 1825 | { |
| 1826 | const el = makeFileItem({ name: root.label, isDir: true, path: root.path, _root: root }); |
| 1827 | grid.appendChild(el); |
| 1828 | } |
| 1829 | |
| 1830 | loadThumbnails(); |
| 1831 | } |
| 1832 | |
| 1833 | async function navigateTo (absPath, root, opts = {}) |
| 1834 | { |
| 1835 | STATE.searchQuery = null; |
| 1836 | if (root) STATE.currentRoot = root; |
| 1837 | STATE.currentDir = absPath; |
| 1838 | |
| 1839 | const data = await api('GET', `/files/list?dir=${encodeURIComponent(absPath)}`); |
| 1840 | if (!data) return; |
| 1841 | |
| 1842 | STATE.items = data.items; |
| 1843 | saveSessionState(); |
| 1844 | renderBreadcrumb(); |
| 1845 | renderFileGrid(); |
| 1846 | await refreshFolderStats(); |
| 1847 | closeSidebar(); |
| 1848 | } |
| 1849 | |
| 1850 | async function runGlobalFileSearch () |
| 1851 | { |
| 1852 | const input = document.getElementById('top-search-input'); |
| 1853 | if (!input) return; |
| 1854 | |
| 1855 | const query = String(input.value || '').trim(); |
| 1856 | if (!query) |
| 1857 | { |
| 1858 | toast('Enter a search term first.', 'err'); |
| 1859 | return; |
| 1860 | } |
| 1861 | |
| 1862 | let data; |
| 1863 | try |
| 1864 | { |
| 1865 | data = await api('GET', `/files/search?query=${encodeURIComponent(query)}&limit=250`); |
| 1866 | } |
| 1867 | catch (err) |
| 1868 | { |
| 1869 | toast('Search failed: ' + err.message, 'err'); |
| 1870 | return; |
| 1871 | } |
| 1872 | |
| 1873 | STATE.searchQuery = query; |
| 1874 | STATE.currentDir = null; |
| 1875 | STATE.currentRoot = null; |
| 1876 | STATE.items = Array.isArray(data && data.results) |
| 1877 | ? data.results.map((it) => ({ |
| 1878 | name: it.name, |
| 1879 | path: it.path, |
| 1880 | dir: it.dir, |
| 1881 | isDir: false, |
| 1882 | size: it.size, |
| 1883 | mtime: it.mtime, |
| 1884 | })) |
| 1885 | : []; |
| 1886 | |
| 1887 | renderBreadcrumb(); |
| 1888 | renderFileGrid(); |
| 1889 | closeSidebar(); |
| 1890 | |
| 1891 | const stats = document.getElementById('folder-stats'); |
| 1892 | if (stats) |
| 1893 | { |
| 1894 | const n = STATE.items.length; |
| 1895 | stats.textContent = n === 1 |
| 1896 | ? `1 file found for "${query}".` |
| 1897 | : `${n} files found for "${query}".`; |
| 1898 | stats.classList.remove('hidden'); |
| 1899 | } |
| 1900 | } |
| 1901 | |
| 1902 | function renderBreadcrumb () |
| 1903 | { |
| 1904 | if (typeof document === 'undefined') return; |
| 1905 | const nav = document.getElementById('breadcrumb'); |
| 1906 | if (!nav) return; |
| 1907 | nav.innerHTML = ''; |
| 1908 | |
| 1909 | // "Home" crumb |
| 1910 | const home = document.createElement('span'); |
| 1911 | home.className = 'crumb' + (STATE.currentDir == null ? ' active' : ''); |
| 1912 | home.textContent = 'Home'; |
| 1913 | home.addEventListener('click', () => |
| 1914 | { |
| 1915 | if (STATE.roots.length === 1) |
| 1916 | { |
| 1917 | navigateTo(STATE.roots[0].path, STATE.roots[0]); |
| 1918 | } else |
| 1919 | { |
| 1920 | renderRootsView(); |
| 1921 | } |
| 1922 | }); |
| 1923 | nav.appendChild(home); |
| 1924 | |
| 1925 | if (STATE.searchQuery) |
| 1926 | { |
| 1927 | const sep = document.createElement('span'); |
| 1928 | sep.className = 'sep'; |
| 1929 | sep.textContent = ' / '; |
| 1930 | nav.appendChild(sep); |
| 1931 | |
| 1932 | const searchCrumb = document.createElement('span'); |
| 1933 | searchCrumb.className = 'crumb active'; |
| 1934 | searchCrumb.textContent = `Search: ${STATE.searchQuery}`; |
| 1935 | nav.appendChild(searchCrumb); |
| 1936 | return; |
| 1937 | } |
| 1938 | |
| 1939 | if (!STATE.currentDir || !STATE.currentRoot) return; |
| 1940 | |
| 1941 | // Build path segments relative to the root. |
| 1942 | const rootPath = STATE.currentRoot.path; |
| 1943 | const relative = relativePathFromRoot(STATE.currentDir, rootPath); |
| 1944 | const segments = relative === '.' ? [] : relative.split(/[\\/]/).filter(Boolean); |
| 1945 | const parts = [STATE.currentRoot.label, ...segments]; |
| 1946 | |
| 1947 | for (let i = 0; i < parts.length; i++) |
| 1948 | { |
| 1949 | const sep = document.createElement('span'); |
| 1950 | sep.className = 'sep'; |
| 1951 | sep.textContent = ' / '; |
| 1952 | nav.appendChild(sep); |
| 1953 | |
| 1954 | const crumb = document.createElement('span'); |
| 1955 | crumb.className = 'crumb' + (i === parts.length - 1 ? ' active' : ''); |
| 1956 | crumb.textContent = parts[i]; |
| 1957 | |
| 1958 | // Root crumb points to rootPath; segment crumbs point to their folder. |
| 1959 | const capturedPath = i === 0 |
| 1960 | ? rootPath |
| 1961 | : joinServerPath(rootPath, segments.slice(0, i).join('/')); |
| 1962 | crumb.classList.add('crumb-drop-target'); |
| 1963 | crumb.dataset.path = capturedPath; |
| 1964 | if (i < parts.length - 1) |
| 1965 | { |
| 1966 | crumb.addEventListener('click', () => navigateTo(capturedPath, STATE.currentRoot)); |
| 1967 | } |
| 1968 | |
| 1969 | nav.appendChild(crumb); |
| 1970 | } |
| 1971 | } |
| 1972 | |
| 1973 | async function refreshFolderStats () |
| 1974 | { |
| 1975 | if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return; |
| 1976 | const el = document.getElementById('folder-stats'); |
| 1977 | if (!STATE.currentDir || STATE.searchQuery) |
| 1978 | { |
| 1979 | el.classList.add('hidden'); |
| 1980 | return; |
| 1981 | } |
| 1982 | |
| 1983 | const data = await api('GET', `/files/space?dir=${encodeURIComponent(STATE.currentDir)}`).catch(() => null); |
| 1984 | if (!data) |
| 1985 | { |
| 1986 | el.classList.add('hidden'); |
| 1987 | return; |
| 1988 | } |
| 1989 | |
| 1990 | const used = formatBytes(data.usedBytes); |
| 1991 | if (data.userFreeBytes != null) |
| 1992 | { |
| 1993 | el.textContent = `Folder usage: ${used} | Free space remaining: ${formatBytes(data.userFreeBytes)}`; |
| 1994 | } else |
| 1995 | { |
| 1996 | const free = data.freeBytes == null ? 'unknown' : formatBytes(data.freeBytes); |
| 1997 | el.textContent = `Folder usage: ${used} | Free on disk: ${free}`; |
| 1998 | } |
| 1999 | el.classList.remove('hidden'); |
| 2000 | } |
| 2001 | |
| 2002 | function itemsSignature (items) |
| 2003 | { |
| 2004 | return JSON.stringify( |
| 2005 | (items || []).map(it => [it.path, it.mtime, it.uploadedAt, it.size, it.isDir]) |
| 2006 | .sort((a, b) => String(a[0]).localeCompare(String(b[0]))), |
| 2007 | ); |
| 2008 | } |
| 2009 | |
| 2010 | async function incrementalRefreshCurrentDir () |
| 2011 | { |
| 2012 | if (STATE.previewExpandState) return; |
| 2013 | if (STATE.searchQuery) return; |
| 2014 | if (!STATE.currentDir || STATE.uploadInProgress) return; |
| 2015 | |
| 2016 | const data = await api('GET', `/files/list?dir=${encodeURIComponent(STATE.currentDir)}`).catch(() => null); |
| 2017 | if (!data) return; |
| 2018 | |
| 2019 | const oldSig = itemsSignature(STATE.items); |
| 2020 | const newSig = itemsSignature(data.items); |
| 2021 | if (oldSig !== newSig) |
| 2022 | { |
| 2023 | const selectedPath = STATE.selectedItem ? STATE.selectedItem.path : null; |
| 2024 | STATE.items = data.items; |
| 2025 | renderFileGrid(); |
| 2026 | |
| 2027 | if (selectedPath) |
| 2028 | { |
| 2029 | const match = STATE.items.find(i => i.path === selectedPath); |
| 2030 | if (match) |
| 2031 | { |
| 2032 | const selectedEl = Array.from(document.querySelectorAll('.file-item')) |
| 2033 | .find(el => el.dataset.path === selectedPath); |
| 2034 | if (selectedEl) selectItem(selectedEl, match); |
| 2035 | } else |
| 2036 | { |
| 2037 | closeSidebar(); |
| 2038 | } |
| 2039 | } |
| 2040 | } |
| 2041 | else |
| 2042 | { |
| 2043 | loadThumbnails(); |
| 2044 | void loadWatchedStatusesForCurrentDir(); |
| 2045 | } |
| 2046 | |
| 2047 | await refreshFolderStats(); |
| 2048 | } |
| 2049 | |
| 2050 | function startAutoRefresh () |
| 2051 | { |
| 2052 | stopAutoRefresh(); |
| 2053 | STATE.autoRefreshTimer = setInterval(() => |
| 2054 | { |
| 2055 | if (document.hidden) return; |
| 2056 | incrementalRefreshCurrentDir(); |
| 2057 | }, 5000); |
| 2058 | } |
| 2059 | |
| 2060 | function stopAutoRefresh () |
| 2061 | { |
| 2062 | if (STATE.autoRefreshTimer) |
| 2063 | { |
| 2064 | clearInterval(STATE.autoRefreshTimer); |
| 2065 | STATE.autoRefreshTimer = null; |
| 2066 | } |
| 2067 | } |
| 2068 | |
| 2069 | // ─────────────────────────────────────────────────────────────────────────── |
| 2070 | // FILE GRID RENDERING |
| 2071 | // ─────────────────────────────────────────────────────────────────────────── |
| 2072 | |
| 2073 | function parseItemTimestampMs (value) |
| 2074 | { |
| 2075 | if (value == null || value === '') return null; |
| 2076 | const asNumber = Number(value); |
| 2077 | if (Number.isFinite(asNumber) && asNumber > 0) return asNumber; |
| 2078 | const asDate = Date.parse(String(value)); |
| 2079 | return Number.isFinite(asDate) ? asDate : null; |
| 2080 | } |
| 2081 | |
| 2082 | function dayStartMsFromTimestamp (value) |
| 2083 | { |
| 2084 | const ts = parseItemTimestampMs(value); |
| 2085 | if (!Number.isFinite(ts)) return null; |
| 2086 | const d = new Date(ts); |
| 2087 | return new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime(); |
| 2088 | } |
| 2089 | |
| 2090 | function dayCountWord (count) |
| 2091 | { |
| 2092 | const words = { |
| 2093 | 2: 'two', |
| 2094 | 3: 'three', |
| 2095 | 4: 'four', |
| 2096 | 5: 'five', |
| 2097 | 6: 'six', |
| 2098 | }; |
| 2099 | return words[count] || String(count); |
| 2100 | } |
| 2101 | |
| 2102 | function groupDateLabel (dayStartMs) |
| 2103 | { |
| 2104 | if (!Number.isFinite(dayStartMs)) return 'Unknown date'; |
| 2105 | |
| 2106 | const now = new Date(); |
| 2107 | const todayStartMs = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime(); |
| 2108 | const diffDays = Math.floor((todayStartMs - dayStartMs) / (24 * 60 * 60 * 1000)); |
| 2109 | |
| 2110 | if (diffDays === 0) return 'today'; |
| 2111 | if (diffDays === 1) return 'yesterday'; |
| 2112 | if (diffDays >= 2 && diffDays <= 6) return `${dayCountWord(diffDays)} days ago`; |
| 2113 | if (diffDays === 7) return 'one week ago'; |
| 2114 | |
| 2115 | return new Date(dayStartMs).toLocaleDateString('en-GB', { |
| 2116 | day: '2-digit', |
| 2117 | month: 'short', |
| 2118 | year: 'numeric', |
| 2119 | }); |
| 2120 | } |
| 2121 | |
| 2122 | function itemFileTypeLabel (item) |
| 2123 | { |
| 2124 | if (item.isDir) return 'Folder'; |
| 2125 | const ext = extOf(item.name); |
| 2126 | return ext ? `.${ext}` : 'No extension'; |
| 2127 | } |
| 2128 | |
| 2129 | function itemAlphabeticalGroupLabel (item) |
| 2130 | { |
| 2131 | const first = String(item.name || '').trim().charAt(0).toUpperCase(); |
| 2132 | if (!first) return '#'; |
| 2133 | return /[A-Z0-9]/.test(first) ? first : '#'; |
| 2134 | } |
| 2135 | |
| 2136 | function itemSizeGroupInfo (item) |
| 2137 | { |
| 2138 | if (item.isDir) return { id: 'folder', label: 'Folder', rank: -1 }; |
| 2139 | const size = Number(item.size); |
| 2140 | if (!Number.isFinite(size) || size < 0) return { id: 'unknown', label: 'Unknown size', rank: 999 }; |
| 2141 | if (size === 0) return { id: 'empty', label: 'Empty', rank: 0 }; |
| 2142 | if (size < (1024 * 1024)) return { id: 'small', label: 'Smaller than 1 MB', rank: 1 }; |
| 2143 | if (size < (100 * 1024 * 1024)) return { id: 'medium', label: '1 MB to 100 MB', rank: 2 }; |
| 2144 | if (size < (1024 * 1024 * 1024)) return { id: 'large', label: '100 MB to 1 GB', rank: 3 }; |
| 2145 | return { id: 'huge', label: 'Larger than 1 GB', rank: 4 }; |
| 2146 | } |
| 2147 | |
| 2148 | function itemGroupInfo (item, groupBy) |
| 2149 | { |
| 2150 | if (groupBy === 'alphabetical') |
| 2151 | { |
| 2152 | const label = itemAlphabeticalGroupLabel(item); |
| 2153 | return { id: `alpha:${label}`, label, rank: label.charCodeAt(0) || 999 }; |
| 2154 | } |
| 2155 | |
| 2156 | if (groupBy === 'fileType') |
| 2157 | { |
| 2158 | const label = itemFileTypeLabel(item); |
| 2159 | return { id: `type:${label.toLowerCase()}`, label, rank: 0 }; |
| 2160 | } |
| 2161 | |
| 2162 | if (groupBy === 'lastChangedDate') |
| 2163 | { |
| 2164 | const dayStart = dayStartMsFromTimestamp(item.mtime); |
| 2165 | return { |
| 2166 | id: `mtime:${dayStart == null ? 'unknown' : dayStart}`, |
| 2167 | label: groupDateLabel(dayStart), |
| 2168 | rank: dayStart == null ? Number.NEGATIVE_INFINITY : dayStart, |
| 2169 | }; |
| 2170 | } |
| 2171 | |
| 2172 | if (groupBy === 'timeUploadedDate') |
| 2173 | { |
| 2174 | const dayStart = dayStartMsFromTimestamp(item.uploadedAt != null ? item.uploadedAt : item.mtime); |
| 2175 | return { |
| 2176 | id: `uploaded:${dayStart == null ? 'unknown' : dayStart}`, |
| 2177 | label: groupDateLabel(dayStart), |
| 2178 | rank: dayStart == null ? Number.NEGATIVE_INFINITY : dayStart, |
| 2179 | }; |
| 2180 | } |
| 2181 | |
| 2182 | if (groupBy === 'size') |
| 2183 | { |
| 2184 | const sizeGroup = itemSizeGroupInfo(item); |
| 2185 | return { |
| 2186 | id: `size:${sizeGroup.id}`, |
| 2187 | label: sizeGroup.label, |
| 2188 | rank: sizeGroup.rank, |
| 2189 | }; |
| 2190 | } |
| 2191 | |
| 2192 | return { id: 'none', label: '', rank: 0 }; |
| 2193 | } |
| 2194 | |
| 2195 | function compareText (a, b) |
| 2196 | { |
| 2197 | return String(a || '').localeCompare(String(b || ''), undefined, { numeric: true, sensitivity: 'base' }); |
| 2198 | } |
| 2199 | |
| 2200 | function compareNullableNumber (a, b, ascending) |
| 2201 | { |
| 2202 | const hasA = Number.isFinite(a); |
| 2203 | const hasB = Number.isFinite(b); |
| 2204 | if (!hasA && !hasB) return 0; |
| 2205 | if (!hasA) return 1; |
| 2206 | if (!hasB) return -1; |
| 2207 | const diff = a - b; |
| 2208 | return ascending ? diff : -diff; |
| 2209 | } |
| 2210 | |
| 2211 | function compareBySortMode (a, b, sortBy, ascending) |
| 2212 | { |
| 2213 | if (sortBy === 'fileType') |
| 2214 | { |
| 2215 | const extA = itemFileTypeLabel(a.item).toLowerCase(); |
| 2216 | const extB = itemFileTypeLabel(b.item).toLowerCase(); |
| 2217 | const byType = compareText(extA, extB); |
| 2218 | if (byType !== 0) return ascending ? byType : -byType; |
| 2219 | const byName = compareText(a.item.name, b.item.name); |
| 2220 | return ascending ? byName : -byName; |
| 2221 | } |
| 2222 | |
| 2223 | if (sortBy === 'lastChanged') |
| 2224 | { |
| 2225 | return compareNullableNumber(parseItemTimestampMs(a.item.mtime), parseItemTimestampMs(b.item.mtime), ascending); |
| 2226 | } |
| 2227 | |
| 2228 | if (sortBy === 'timeUploaded') |
| 2229 | { |
| 2230 | const uploadedA = parseItemTimestampMs(a.item.uploadedAt != null ? a.item.uploadedAt : a.item.mtime); |
| 2231 | const uploadedB = parseItemTimestampMs(b.item.uploadedAt != null ? b.item.uploadedAt : b.item.mtime); |
| 2232 | return compareNullableNumber(uploadedA, uploadedB, ascending); |
| 2233 | } |
| 2234 | |
| 2235 | if (sortBy === 'size') |
| 2236 | { |
| 2237 | const sizeA = Number.isFinite(Number(a.item.size)) ? Number(a.item.size) : null; |
| 2238 | const sizeB = Number.isFinite(Number(b.item.size)) ? Number(b.item.size) : null; |
| 2239 | return compareNullableNumber(sizeA, sizeB, ascending); |
| 2240 | } |
| 2241 | |
| 2242 | const byName = compareText(a.item.name, b.item.name); |
| 2243 | return ascending ? byName : -byName; |
| 2244 | } |
| 2245 | |
| 2246 | function buildFileGridRows (items, prefs) |
| 2247 | { |
| 2248 | const list = Array.isArray(items) ? items : []; |
| 2249 | const groupBy = prefs.groupBy || 'none'; |
| 2250 | const sortBy = prefs.sortBy || 'alphabetical'; |
| 2251 | const descriptors = list.map((item) => ({ |
| 2252 | item, |
| 2253 | group: itemGroupInfo(item, groupBy), |
| 2254 | })); |
| 2255 | |
| 2256 | descriptors.sort((a, b) => |
| 2257 | { |
| 2258 | if (groupBy !== 'none') |
| 2259 | { |
| 2260 | const dateGrouping = groupBy === 'lastChangedDate' || groupBy === 'timeUploadedDate'; |
| 2261 | if (a.group.rank !== b.group.rank) |
| 2262 | { |
| 2263 | const byRank = dateGrouping ? (b.group.rank - a.group.rank) : (a.group.rank - b.group.rank); |
| 2264 | if (byRank !== 0) return byRank; |
| 2265 | } |
| 2266 | const byGroupLabel = compareText(a.group.label, b.group.label); |
| 2267 | if (byGroupLabel !== 0) return dateGrouping ? byGroupLabel : (prefs.ascending ? byGroupLabel : -byGroupLabel); |
| 2268 | } |
| 2269 | |
| 2270 | if (prefs.foldersFirst && a.item.isDir !== b.item.isDir) |
| 2271 | { |
| 2272 | return a.item.isDir ? -1 : 1; |
| 2273 | } |
| 2274 | |
| 2275 | const bySort = compareBySortMode(a, b, sortBy, !!prefs.ascending); |
| 2276 | if (bySort !== 0) return bySort; |
| 2277 | |
| 2278 | return compareText(a.item.name, b.item.name); |
| 2279 | }); |
| 2280 | |
| 2281 | const rows = []; |
| 2282 | let previousGroupId = null; |
| 2283 | for (const descriptor of descriptors) |
| 2284 | { |
| 2285 | if (groupBy !== 'none' && descriptor.group.id !== previousGroupId) |
| 2286 | { |
| 2287 | rows.push({ type: 'group', label: descriptor.group.label }); |
| 2288 | previousGroupId = descriptor.group.id; |
| 2289 | } |
| 2290 | rows.push({ type: 'item', item: descriptor.item }); |
| 2291 | } |
| 2292 | |
| 2293 | return rows; |
| 2294 | } |
| 2295 | |
| 2296 | function makeGroupSeparator (label) |
| 2297 | { |
| 2298 | const el = document.createElement('div'); |
| 2299 | el.className = 'file-group-separator'; |
| 2300 | |
| 2301 | const text = document.createElement('span'); |
| 2302 | text.textContent = String(label || 'Other'); |
| 2303 | el.appendChild(text); |
| 2304 | return el; |
| 2305 | } |
| 2306 | |
| 2307 | function renderFileItemName (targetEl, fileName) |
| 2308 | { |
| 2309 | if (!targetEl) return; |
| 2310 | |
| 2311 | const rawName = String(fileName || ''); |
| 2312 | targetEl.textContent = ''; |
| 2313 | if (!rawName) return; |
| 2314 | |
| 2315 | const segments = rawName.split(/([\-.,])/); |
| 2316 | for (const segment of segments) |
| 2317 | { |
| 2318 | if (!segment) continue; |
| 2319 | targetEl.appendChild(document.createTextNode(segment)); |
| 2320 | |
| 2321 | if (segment === '-' || segment === ',' || segment === '.') |
| 2322 | { |
| 2323 | targetEl.appendChild(document.createElement('wbr')); |
| 2324 | } |
| 2325 | } |
| 2326 | } |
| 2327 | |
| 2328 | function renderFileGrid () |
| 2329 | { |
| 2330 | if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return; |
| 2331 | disconnectThumbnailObserver(); |
| 2332 | disconnectFolderIconObserver(); |
| 2333 | revokeThumbnails(); |
| 2334 | const grid = document.getElementById('file-grid'); |
| 2335 | grid.innerHTML = ''; |
| 2336 | const empty = document.getElementById('empty-notice'); |
| 2337 | |
| 2338 | const prefs = (!STATE.searchQuery && STATE.currentDir) |
| 2339 | ? folderViewPrefsForDir(STATE.currentDir) |
| 2340 | : { ...DEFAULT_FOLDER_VIEW_PREFS }; |
| 2341 | const rows = buildFileGridRows(STATE.items, prefs); |
| 2342 | |
| 2343 | empty.classList.toggle('hidden', STATE.items.length > 0); |
| 2344 | |
| 2345 | for (const row of rows) |
| 2346 | { |
| 2347 | if (row.type === 'group') |
| 2348 | { |
| 2349 | grid.appendChild(makeGroupSeparator(row.label)); |
| 2350 | continue; |
| 2351 | } |
| 2352 | grid.appendChild(makeFileItem(row.item)); |
| 2353 | } |
| 2354 | |
| 2355 | loadThumbnails(); |
| 2356 | void loadWatchedStatusesForCurrentDir(); |
| 2357 | } |
| 2358 | |
| 2359 | function makeFileItem (item) |
| 2360 | { |
| 2361 | const el = document.createElement('div'); |
| 2362 | el.className = 'file-item'; |
| 2363 | el.dataset.path = item.path; |
| 2364 | if (item.isDir) el.dataset.isdir = '1'; |
| 2365 | |
| 2366 | const icon = document.createElement('div'); |
| 2367 | icon.className = 'icon'; |
| 2368 | icon.innerHTML = item.isDir ? iconFolder() : iconFile(item.name); |
| 2369 | if (!item.isDir) |
| 2370 | { |
| 2371 | icon.dataset.previewPath = item.path; |
| 2372 | renderWatchedOverlayOnIcon(icon, watchStatusForTile(item)); |
| 2373 | } else |
| 2374 | { |
| 2375 | icon.dataset.folderPath = item.path; |
| 2376 | } |
| 2377 | el.appendChild(icon); |
| 2378 | |
| 2379 | const name = document.createElement('div'); |
| 2380 | name.className = 'name'; |
| 2381 | renderFileItemName(name, item.name); |
| 2382 | el.appendChild(name); |
| 2383 | |
| 2384 | if (!item._root) makeDraggable(el, item); |
| 2385 | attachMobileLongPress(el, item); |
| 2386 | |
| 2387 | el.addEventListener('contextmenu', (e) => |
| 2388 | { |
| 2389 | if (!isMobileViewport()) return; |
| 2390 | e.preventDefault(); |
| 2391 | e.stopPropagation(); |
| 2392 | }); |
| 2393 | |
| 2394 | // Single-click: open sidebar |
| 2395 | el.addEventListener('click', (e) => |
| 2396 | { |
| 2397 | e.stopPropagation(); |
| 2398 | if (el.classList.contains('file-item--preview')) return; |
| 2399 | if (isMobileViewport()) |
| 2400 | { |
| 2401 | if (el.dataset.longPressTriggered === '1') |
| 2402 | { |
| 2403 | el.dataset.longPressTriggered = '0'; |
| 2404 | return; |
| 2405 | } |
| 2406 | |
| 2407 | if (item.isDir) |
| 2408 | { |
| 2409 | navigateTo(item.path, item._root || STATE.currentRoot); |
| 2410 | } else |
| 2411 | { |
| 2412 | downloadOrView(item, icon.querySelector('svg')); |
| 2413 | } |
| 2414 | return; |
| 2415 | } |
| 2416 | |
| 2417 | selectItem(el, item); |
| 2418 | }); |
| 2419 | |
| 2420 | // Double-click: enter folder or view/download file |
| 2421 | el.addEventListener('dblclick', (e) => |
| 2422 | { |
| 2423 | e.stopPropagation(); |
| 2424 | if (el.classList.contains('file-item--preview')) return; |
| 2425 | if (item.isDir) |
| 2426 | { |
| 2427 | navigateTo(item.path, item._root || STATE.currentRoot); |
| 2428 | } else |
| 2429 | { |
| 2430 | downloadOrView(item, icon.querySelector('svg')); |
| 2431 | } |
| 2432 | }); |
| 2433 | |
| 2434 | return el; |
| 2435 | } |
| 2436 | |
| 2437 | function attachMobileLongPress (el, item) |
| 2438 | { |
| 2439 | if (item._root) return; |
| 2440 | |
| 2441 | let pressTimer = null; |
| 2442 | let startX = 0; |
| 2443 | let startY = 0; |
| 2444 | |
| 2445 | function clearPress () |
| 2446 | { |
| 2447 | if (!pressTimer) return; |
| 2448 | clearTimeout(pressTimer); |
| 2449 | pressTimer = null; |
| 2450 | } |
| 2451 | |
| 2452 | function cancelPress () |
| 2453 | { |
| 2454 | clearPress(); |
| 2455 | } |
| 2456 | |
| 2457 | el.addEventListener('pointerdown', (e) => |
| 2458 | { |
| 2459 | if (!isMobileViewport()) return; |
| 2460 | if (e.button !== undefined && e.button !== 0) return; |
| 2461 | if (e.pointerType && e.pointerType === 'mouse') return; |
| 2462 | |
| 2463 | startX = e.clientX; |
| 2464 | startY = e.clientY; |
| 2465 | clearPress(); |
| 2466 | |
| 2467 | pressTimer = setTimeout(() => |
| 2468 | { |
| 2469 | pressTimer = null; |
| 2470 | el.dataset.longPressTriggered = '1'; |
| 2471 | selectItem(el, item); |
| 2472 | }, MOBILE_LONG_PRESS_MS); |
| 2473 | }); |
| 2474 | |
| 2475 | el.addEventListener('pointermove', (e) => |
| 2476 | { |
| 2477 | if (!pressTimer) return; |
| 2478 | if (Math.hypot(e.clientX - startX, e.clientY - startY) > MOBILE_LONG_PRESS_MOVE_THRESHOLD) |
| 2479 | { |
| 2480 | clearPress(); |
| 2481 | } |
| 2482 | }); |
| 2483 | |
| 2484 | el.addEventListener('pointerup', cancelPress); |
| 2485 | el.addEventListener('pointercancel', cancelPress); |
| 2486 | el.addEventListener('pointerleave', cancelPress); |
| 2487 | } |
| 2488 | |
| 2489 | function selectItem (el, item) |
| 2490 | { |
| 2491 | document.querySelectorAll('.file-item.selected').forEach(e => e.classList.remove('selected')); |
| 2492 | el.classList.add('selected'); |
| 2493 | STATE.selectedItem = item; |
| 2494 | openSidebar(item); |
| 2495 | } |
| 2496 | |
| 2497 | function isAbortError (err) |
| 2498 | { |
| 2499 | if (!err) return false; |
| 2500 | return err.name === 'AbortError' || /abort/i.test(String(err.message || '')); |
| 2501 | } |
| 2502 | |
| 2503 | function beginSidebarLoad () |
| 2504 | { |
| 2505 | if (STATE.sidebarAbortController && typeof STATE.sidebarAbortController.abort === 'function') |
| 2506 | { |
| 2507 | try { STATE.sidebarAbortController.abort(); } catch { /* ignore */ } |
| 2508 | } |
| 2509 | |
| 2510 | STATE.sidebarLoadId += 1; |
| 2511 | STATE.sidebarAbortController = null; |
| 2512 | |
| 2513 | return { |
| 2514 | id: STATE.sidebarLoadId, |
| 2515 | }; |
| 2516 | } |
| 2517 | |
| 2518 | function isSidebarLoadStale (item, sidebarLoadId) |
| 2519 | { |
| 2520 | if (sidebarLoadId !== STATE.sidebarLoadId) return true; |
| 2521 | if (!STATE.selectedItem) return true; |
| 2522 | return STATE.selectedItem !== item && STATE.selectedItem.path !== item.path; |
| 2523 | } |
| 2524 | |
| 2525 | // ─────────────────────────────────────────────────────────────────────────── |
| 2526 | // SIDEBAR |
| 2527 | // ─────────────────────────────────────────────────────────────────────────── |
| 2528 | |
| 2529 | /** |
| 2530 | * Renders (or clears) the duplicates panel at the bottom of the sidebar. |
| 2531 | * @param {object|null} item — the item whose duplicates are shown; null = clear |
| 2532 | * @param {Array|null} duplicates — array of {path, name, dir, relativePath}; null = loading state |
| 2533 | */ |
| 2534 | function renderSidebarDuplicates (item, duplicates) |
| 2535 | { |
| 2536 | if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return; |
| 2537 | const panel = document.getElementById('sidebar-duplicates'); |
| 2538 | if (!panel) return; |
| 2539 | |
| 2540 | // Clear / hide when no item or no duplicates. |
| 2541 | if (!item || (Array.isArray(duplicates) && duplicates.length === 0)) |
| 2542 | { |
| 2543 | panel.classList.add('hidden'); |
| 2544 | panel.innerHTML = ''; |
| 2545 | return; |
| 2546 | } |
| 2547 | |
| 2548 | // Loading state. |
| 2549 | if (duplicates === null) |
| 2550 | { |
| 2551 | panel.classList.add('hidden'); |
| 2552 | panel.innerHTML = ''; |
| 2553 | return; |
| 2554 | } |
| 2555 | |
| 2556 | panel.innerHTML = ''; |
| 2557 | const heading = document.createElement('p'); |
| 2558 | heading.className = 'sidebar-duplicates-heading'; |
| 2559 | heading.textContent = `Duplicates (${duplicates.length})`; |
| 2560 | panel.appendChild(heading); |
| 2561 | |
| 2562 | const list = document.createElement('ul'); |
| 2563 | list.className = 'sidebar-duplicates-list'; |
| 2564 | |
| 2565 | for (const dup of duplicates) |
| 2566 | { |
| 2567 | const li = document.createElement('li'); |
| 2568 | const btn = document.createElement('button'); |
| 2569 | btn.className = 'sidebar-duplicate-entry'; |
| 2570 | btn.title = dup.path; |
| 2571 | // Show path relative to its root; keep absolute path in the tooltip. |
| 2572 | btn.textContent = dup.relativePath || dup.path; |
| 2573 | btn.addEventListener('click', () => navigateToDuplicate(dup)); |
| 2574 | li.appendChild(btn); |
| 2575 | list.appendChild(li); |
| 2576 | } |
| 2577 | |
| 2578 | panel.appendChild(list); |
| 2579 | panel.classList.remove('hidden'); |
| 2580 | } |
| 2581 | |
| 2582 | /** |
| 2583 | * Navigates to the folder containing a duplicate file and then auto-opens it. |
| 2584 | * @param {{ path: string, name: string, dir: string }} dup |
| 2585 | */ |
| 2586 | async function navigateToDuplicate (dup) |
| 2587 | { |
| 2588 | // If the duplicate lives in the folder already shown, just select it. |
| 2589 | if (STATE.currentDir && samePath(dup.dir, STATE.currentDir)) |
| 2590 | { |
| 2591 | const tile = Array.from(document.querySelectorAll('.file-item')) |
| 2592 | .find((el) => el.dataset.path === dup.path); |
| 2593 | const dupItem = STATE.items.find((i) => i.path === dup.path); |
| 2594 | if (tile && dupItem) |
| 2595 | { |
| 2596 | selectItem(tile, dupItem); |
| 2597 | } |
| 2598 | return; |
| 2599 | } |
| 2600 | |
| 2601 | // Find the root that contains the duplicate. |
| 2602 | const root = STATE.roots.find( |
| 2603 | (r) => dup.dir === r.path || dup.dir.startsWith(r.path + '/') || dup.dir.startsWith(r.path + '\\'), |
| 2604 | ); |
| 2605 | if (!root) |
| 2606 | { |
| 2607 | toast('Cannot navigate to duplicate: root not accessible.', 'err'); |
| 2608 | return; |
| 2609 | } |
| 2610 | |
| 2611 | await navigateTo(dup.dir, root); |
| 2612 | |
| 2613 | // After navigation, find and select the file tile to open it. |
| 2614 | const tile = Array.from(document.querySelectorAll('.file-item')) |
| 2615 | .find((el) => el.dataset.path === dup.path); |
| 2616 | const dupItem = STATE.items.find((i) => i.path === dup.path); |
| 2617 | |
| 2618 | if (tile && dupItem) |
| 2619 | { |
| 2620 | selectItem(tile, dupItem); |
| 2621 | } |
| 2622 | } |
| 2623 | // ─────────────────────────────────────────────────────────────────────────── |
| 2624 | |
| 2625 | async function openSidebar (item) |
| 2626 | { |
| 2627 | const sidebarLoad = beginSidebarLoad(); |
| 2628 | |
| 2629 | const sidebar = document.getElementById('sidebar'); |
| 2630 | sidebar.classList.remove('hidden'); |
| 2631 | document.getElementById('app').classList.add('sidebar-open'); |
| 2632 | |
| 2633 | document.getElementById('sidebar-icon').innerHTML = item.isDir ? iconFolder(64) : iconFile(item.name, 64); |
| 2634 | if (item.isDir) |
| 2635 | { |
| 2636 | document.getElementById('sidebar-icon').dataset.folderPath = item.path; |
| 2637 | } else |
| 2638 | { |
| 2639 | delete document.getElementById('sidebar-icon').dataset.folderPath; |
| 2640 | } |
| 2641 | document.getElementById('sidebar-name').textContent = item.name; |
| 2642 | |
| 2643 | // Load metadata |
| 2644 | const dl = document.getElementById('sidebar-meta'); |
| 2645 | dl.innerHTML = '<dt>Loading…</dt><dd></dd>'; |
| 2646 | |
| 2647 | const actions = document.getElementById('sidebar-actions'); |
| 2648 | actions.innerHTML = ''; |
| 2649 | |
| 2650 | // Reset duplicates panel whenever a new item is opened. |
| 2651 | renderSidebarDuplicates(null, null); |
| 2652 | |
| 2653 | if (!item.isDir) |
| 2654 | { |
| 2655 | const meta = await api('GET', `/files/meta?file=${encodeURIComponent(item.path)}`).catch((err) => |
| 2656 | { |
| 2657 | if (isAbortError(err)) return null; |
| 2658 | throw err; |
| 2659 | }); |
| 2660 | if (isSidebarLoadStale(item, sidebarLoad.id)) return; |
| 2661 | |
| 2662 | if (meta) |
| 2663 | { |
| 2664 | const watchedBy = VIDEO_EXTS.has(extOf(item.name)) |
| 2665 | ? Object.entries(meta.watchedBy || {}) |
| 2666 | .map(([user, status]) => `${String(user)}: ${String(status)}`) |
| 2667 | .sort((a, b) => a.localeCompare(b)) |
| 2668 | : []; |
| 2669 | |
| 2670 | dl.innerHTML = ` |
| 2671 | <dt>Size</dt> <dd>${formatBytes(meta.size)}</dd> |
| 2672 | <dt>Modified</dt> <dd>${new Date(meta.mtime).toLocaleString()}</dd> |
| 2673 | <dt>Uploaded by</dt><dd>${meta.uploader || '—'}</dd> |
| 2674 | <dt>Downloaded by</dt><dd>${meta.downloaders.join(', ') || '—'}</dd> |
| 2675 | ${VIDEO_EXTS.has(extOf(item.name)) ? `<dt>Watched by</dt><dd>${watchedBy.join(', ') || '—'}</dd>` : ''} |
| 2676 | `; |
| 2677 | } |
| 2678 | |
| 2679 | // Fetch and render duplicate files. |
| 2680 | renderSidebarDuplicates(item, null); // show loading state |
| 2681 | const selectedPathAtRequest = item.path; |
| 2682 | api('GET', `/files/duplicates?file=${encodeURIComponent(item.path)}`) |
| 2683 | .then((data) => |
| 2684 | { |
| 2685 | if (isSidebarLoadStale(item, sidebarLoad.id)) return; |
| 2686 | if (!STATE.selectedItem || STATE.selectedItem.path !== selectedPathAtRequest) return; |
| 2687 | renderSidebarDuplicates(item, data ? data.duplicates : []); |
| 2688 | }) |
| 2689 | .catch((err) => |
| 2690 | { |
| 2691 | if (isAbortError(err)) return; |
| 2692 | if (isSidebarLoadStale(item, sidebarLoad.id)) return; |
| 2693 | if (!STATE.selectedItem || STATE.selectedItem.path !== selectedPathAtRequest) return; |
| 2694 | renderSidebarDuplicates(item, []); |
| 2695 | }); |
| 2696 | |
| 2697 | // View / download button |
| 2698 | const btnDl = document.createElement('button'); |
| 2699 | btnDl.textContent = 'View / Download'; |
| 2700 | btnDl.addEventListener('click', () => |
| 2701 | { |
| 2702 | const tile = Array.from(document.querySelectorAll('.file-item')).find(node => node.dataset.path === item.path); |
| 2703 | const source = (tile ? tile.querySelector('.icon svg') : null) || document.querySelector('#sidebar-icon svg'); |
| 2704 | downloadOrView(item, source); |
| 2705 | }); |
| 2706 | actions.appendChild(btnDl); |
| 2707 | |
| 2708 | // Share button (file) |
| 2709 | const btnShareFile = document.createElement('button'); |
| 2710 | btnShareFile.textContent = 'Share'; |
| 2711 | btnShareFile.addEventListener('click', () => openShareModal(item)); |
| 2712 | actions.appendChild(btnShareFile); |
| 2713 | } else |
| 2714 | { |
| 2715 | dl.innerHTML = `<dt>Type</dt><dd>${item._root ? 'Root folder' : 'Folder'}</dd>`; |
| 2716 | |
| 2717 | if (item._root) |
| 2718 | { |
| 2719 | dl.innerHTML += ` |
| 2720 | <dt>Alias</dt><dd>${item.name}</dd> |
| 2721 | <dt>Original name</dt><dd>${item._root.originalName || basenameOfPath(item.path)}</dd> |
| 2722 | `; |
| 2723 | |
| 2724 | const space = await api('GET', `/files/space?dir=${encodeURIComponent(item.path)}`).catch((err) => |
| 2725 | { |
| 2726 | if (isAbortError(err)) return null; |
| 2727 | return null; |
| 2728 | }); |
| 2729 | if (isSidebarLoadStale(item, sidebarLoad.id)) return; |
| 2730 | |
| 2731 | if (space) |
| 2732 | { |
| 2733 | const used = formatBytes(space.usedBytes); |
| 2734 | const free = space.userFreeBytes != null |
| 2735 | ? formatBytes(space.userFreeBytes) |
| 2736 | : (space.freeBytes == null ? 'unknown' : formatBytes(space.freeBytes)); |
| 2737 | const freeLabel = space.userFreeBytes != null ? 'Free space remaining' : 'Remaining'; |
| 2738 | dl.innerHTML += ` |
| 2739 | <dt>Used</dt><dd>${used}</dd> |
| 2740 | <dt>${freeLabel}</dt><dd>${free}</dd> |
| 2741 | `; |
| 2742 | } |
| 2743 | |
| 2744 | if (item._root.isUserFolder) |
| 2745 | { |
| 2746 | dl.innerHTML += ` |
| 2747 | <dt>Access</dt><dd>Private (your folder)</dd> |
| 2748 | `; |
| 2749 | } else |
| 2750 | { |
| 2751 | const accessUsers = await fetchRootAccessList(item.path); |
| 2752 | if (isSidebarLoadStale(item, sidebarLoad.id)) return; |
| 2753 | if (accessUsers) |
| 2754 | { |
| 2755 | dl.innerHTML += ` |
| 2756 | <dt>Access</dt><dd>${formatRootAccessList(accessUsers)}</dd> |
| 2757 | `; |
| 2758 | } |
| 2759 | } |
| 2760 | } |
| 2761 | |
| 2762 | const btnOpen = document.createElement('button'); |
| 2763 | btnOpen.textContent = 'Open folder'; |
| 2764 | btnOpen.addEventListener('click', () => navigateTo(item.path, item._root || STATE.currentRoot)); |
| 2765 | actions.appendChild(btnOpen); |
| 2766 | |
| 2767 | // Download as zip button (folder) |
| 2768 | const btnZip = document.createElement('button'); |
| 2769 | btnZip.textContent = 'Download as zip'; |
| 2770 | btnZip.addEventListener('click', () => |
| 2771 | { |
| 2772 | btnZip.disabled = true; |
| 2773 | btnZip.textContent = 'Working...'; |
| 2774 | const url = `/api/files/download-zip?dir=${encodeURIComponent(item.path)}`; |
| 2775 | const headers = { |
| 2776 | Authorization: 'Bearer ' + STATE.token, |
| 2777 | 'X-Fp': getFingerprint(), |
| 2778 | }; |
| 2779 | fetch(url, { headers }) |
| 2780 | .then(res => |
| 2781 | { |
| 2782 | if (!res.ok) throw new Error('Download mislukt'); |
| 2783 | return res.blob(); |
| 2784 | }) |
| 2785 | .then(blob => |
| 2786 | { |
| 2787 | const blobUrl = URL.createObjectURL(blob); |
| 2788 | const a = document.createElement('a'); |
| 2789 | a.href = blobUrl; |
| 2790 | a.download = item.name + '.zip'; |
| 2791 | a.click(); |
| 2792 | setTimeout(() => URL.revokeObjectURL(blobUrl), 10000); |
| 2793 | }) |
| 2794 | .catch((err) => toast(err.message || 'Download mislukt', 'err')) |
| 2795 | .finally(() => |
| 2796 | { |
| 2797 | btnZip.disabled = false; |
| 2798 | btnZip.textContent = 'Download as zip'; |
| 2799 | }); |
| 2800 | }); |
| 2801 | actions.appendChild(btnZip); |
| 2802 | |
| 2803 | // Share button (folder) |
| 2804 | const btnShareFolder = document.createElement('button'); |
| 2805 | btnShareFolder.textContent = 'Share'; |
| 2806 | btnShareFolder.addEventListener('click', () => openShareModal(item)); |
| 2807 | actions.appendChild(btnShareFolder); |
| 2808 | |
| 2809 | // Load folder icon thumbnail into the sidebar icon element. |
| 2810 | void loadOneFolderIcon(document.getElementById('sidebar-icon')); |
| 2811 | } |
| 2812 | |
| 2813 | // Rename button (write access required) |
| 2814 | if (canWrite(item)) |
| 2815 | { |
| 2816 | if (item.isDir) |
| 2817 | { |
| 2818 | const btnSetIcon = document.createElement('button'); |
| 2819 | btnSetIcon.textContent = 'Set icon'; |
| 2820 | btnSetIcon.addEventListener('click', () => openFolderIconPicker(item)); |
| 2821 | actions.appendChild(btnSetIcon); |
| 2822 | } |
| 2823 | |
| 2824 | if (!item._root) |
| 2825 | { |
| 2826 | const btnMove = document.createElement('button'); |
| 2827 | btnMove.textContent = 'Move to'; |
| 2828 | btnMove.addEventListener('click', () => openMovePicker(item)); |
| 2829 | actions.appendChild(btnMove); |
| 2830 | |
| 2831 | if (!item.isDir) |
| 2832 | { |
| 2833 | const btnCopy = document.createElement('button'); |
| 2834 | btnCopy.textContent = 'Copy to'; |
| 2835 | btnCopy.addEventListener('click', () => openCopyPicker(item)); |
| 2836 | actions.appendChild(btnCopy); |
| 2837 | } |
| 2838 | } |
| 2839 | |
| 2840 | const btnRen = document.createElement('button'); |
| 2841 | btnRen.textContent = 'Rename'; |
| 2842 | btnRen.addEventListener('click', () => openRenameModal(item)); |
| 2843 | actions.appendChild(btnRen); |
| 2844 | |
| 2845 | if (!item._root) |
| 2846 | { |
| 2847 | const btnDel = document.createElement('button'); |
| 2848 | btnDel.textContent = 'Delete'; |
| 2849 | btnDel.className = 'danger'; |
| 2850 | btnDel.addEventListener('click', () => deleteItem(item)); |
| 2851 | actions.appendChild(btnDel); |
| 2852 | } |
| 2853 | } |
| 2854 | } |
| 2855 | |
| 2856 | function openFolderSidebar () |
| 2857 | { |
| 2858 | beginSidebarLoad(); |
| 2859 | |
| 2860 | const sidebar = document.getElementById('sidebar'); |
| 2861 | sidebar.classList.remove('hidden'); |
| 2862 | document.getElementById('app').classList.add('sidebar-open'); |
| 2863 | |
| 2864 | document.getElementById('sidebar-icon').innerHTML = iconFolder(64); |
| 2865 | |
| 2866 | const nameEl = document.getElementById('sidebar-name'); |
| 2867 | const dl = document.getElementById('sidebar-meta'); |
| 2868 | const actions = document.getElementById('sidebar-actions'); |
| 2869 | actions.innerHTML = ''; |
| 2870 | renderSidebarDuplicates(null, null); |
| 2871 | |
| 2872 | if (!STATE.currentDir || !STATE.currentRoot) |
| 2873 | { |
| 2874 | nameEl.textContent = 'Storage Roots'; |
| 2875 | dl.innerHTML = ` |
| 2876 | <dt>Type</dt><dd>Root overview</dd> |
| 2877 | <dt>Roots</dt><dd>${STATE.roots.length}</dd> |
| 2878 | `; |
| 2879 | return; |
| 2880 | } |
| 2881 | |
| 2882 | const parts = String(STATE.currentDir).split(/[\\/]/).filter(Boolean); |
| 2883 | const fallback = STATE.currentRoot.label || 'Folder'; |
| 2884 | nameEl.textContent = parts.length ? parts[parts.length - 1] : fallback; |
| 2885 | |
| 2886 | const dirs = STATE.items.filter(i => i.isDir).length; |
| 2887 | const files = STATE.items.length - dirs; |
| 2888 | const displayPath = displayPathWithRootLabel(STATE.currentDir, STATE.currentRoot.path, STATE.currentRoot.label); |
| 2889 | const baseDetails = ` |
| 2890 | <dt>Path</dt><dd>${displayPath}</dd> |
| 2891 | <dt>Folders</dt><dd>${dirs}</dd> |
| 2892 | <dt>Files</dt><dd>${files}</dd> |
| 2893 | `; |
| 2894 | dl.innerHTML = baseDetails; |
| 2895 | renderFolderViewControls(actions, STATE.currentDir); |
| 2896 | |
| 2897 | if (samePath(STATE.currentDir, STATE.currentRoot.path)) |
| 2898 | { |
| 2899 | if (STATE.currentRoot.isUserFolder) |
| 2900 | { |
| 2901 | dl.innerHTML += '<dt>Access</dt><dd>Private (your folder)</dd>'; |
| 2902 | return; |
| 2903 | } |
| 2904 | |
| 2905 | dl.innerHTML += '<dt>Access</dt><dd>Loading…</dd>'; |
| 2906 | const currentDirAtStart = STATE.currentDir; |
| 2907 | const currentRootPathAtStart = STATE.currentRoot.path; |
| 2908 | void fetchRootAccessList(currentRootPathAtStart).then((accessUsers) => |
| 2909 | { |
| 2910 | if (!accessUsers) return; |
| 2911 | if (!STATE.currentRoot) return; |
| 2912 | if (!samePath(STATE.currentDir, currentDirAtStart)) return; |
| 2913 | if (!samePath(STATE.currentRoot.path, currentRootPathAtStart)) return; |
| 2914 | dl.innerHTML = `${baseDetails}<dt>Access</dt><dd>${formatRootAccessList(accessUsers)}</dd>`; |
| 2915 | }); |
| 2916 | } |
| 2917 | } |
| 2918 | |
| 2919 | function renderFolderViewControls (actions, dirPath) |
| 2920 | { |
| 2921 | if (!actions || !dirPath) return; |
| 2922 | |
| 2923 | const prefs = folderViewPrefsForDir(dirPath); |
| 2924 | |
| 2925 | const section = document.createElement('section'); |
| 2926 | section.className = 'sidebar-view-options'; |
| 2927 | |
| 2928 | const heading = document.createElement('h3'); |
| 2929 | heading.textContent = 'View options'; |
| 2930 | section.appendChild(heading); |
| 2931 | |
| 2932 | const sortLabel = document.createElement('label'); |
| 2933 | sortLabel.className = 'sidebar-view-option-label'; |
| 2934 | sortLabel.textContent = 'Sort by'; |
| 2935 | const sortSelect = document.createElement('select'); |
| 2936 | sortSelect.className = 'sidebar-view-option-control'; |
| 2937 | sortSelect.dataset.viewOption = 'sort'; |
| 2938 | const sortOptions = [ |
| 2939 | { value: 'alphabetical', label: 'Alphabetically' }, |
| 2940 | { value: 'fileType', label: 'File type' }, |
| 2941 | { value: 'lastChanged', label: 'Last changed' }, |
| 2942 | { value: 'timeUploaded', label: 'Time uploaded' }, |
| 2943 | { value: 'size', label: 'Size' }, |
| 2944 | ]; |
| 2945 | for (const option of sortOptions) |
| 2946 | { |
| 2947 | const optEl = document.createElement('option'); |
| 2948 | optEl.value = option.value; |
| 2949 | optEl.textContent = option.label; |
| 2950 | sortSelect.appendChild(optEl); |
| 2951 | } |
| 2952 | sortSelect.value = prefs.sortBy; |
| 2953 | sortSelect.addEventListener('change', () => |
| 2954 | { |
| 2955 | saveFolderViewPrefsForDir(dirPath, { sortBy: sortSelect.value }); |
| 2956 | renderFileGrid(); |
| 2957 | }); |
| 2958 | sortLabel.appendChild(sortSelect); |
| 2959 | section.appendChild(sortLabel); |
| 2960 | |
| 2961 | const groupLabel = document.createElement('label'); |
| 2962 | groupLabel.className = 'sidebar-view-option-label'; |
| 2963 | groupLabel.textContent = 'Group by'; |
| 2964 | const groupSelect = document.createElement('select'); |
| 2965 | groupSelect.className = 'sidebar-view-option-control'; |
| 2966 | groupSelect.dataset.viewOption = 'group'; |
| 2967 | const groupOptions = [ |
| 2968 | { value: 'none', label: 'None' }, |
| 2969 | { value: 'alphabetical', label: 'Alphabetically' }, |
| 2970 | { value: 'fileType', label: 'File type' }, |
| 2971 | { value: 'lastChangedDate', label: 'Last changed date' }, |
| 2972 | { value: 'timeUploadedDate', label: 'Upload date' }, |
| 2973 | { value: 'size', label: 'Size' }, |
| 2974 | ]; |
| 2975 | for (const option of groupOptions) |
| 2976 | { |
| 2977 | const optEl = document.createElement('option'); |
| 2978 | optEl.value = option.value; |
| 2979 | optEl.textContent = option.label; |
| 2980 | groupSelect.appendChild(optEl); |
| 2981 | } |
| 2982 | groupSelect.value = prefs.groupBy; |
| 2983 | groupSelect.addEventListener('change', () => |
| 2984 | { |
| 2985 | saveFolderViewPrefsForDir(dirPath, { groupBy: groupSelect.value }); |
| 2986 | renderFileGrid(); |
| 2987 | }); |
| 2988 | groupLabel.appendChild(groupSelect); |
| 2989 | section.appendChild(groupLabel); |
| 2990 | |
| 2991 | const foldersTopLabel = document.createElement('label'); |
| 2992 | foldersTopLabel.className = 'sidebar-view-toggle'; |
| 2993 | const foldersTopInput = document.createElement('input'); |
| 2994 | foldersTopInput.type = 'checkbox'; |
| 2995 | foldersTopInput.dataset.viewOption = 'folders-first'; |
| 2996 | foldersTopInput.checked = !!prefs.foldersFirst; |
| 2997 | foldersTopInput.addEventListener('change', () => |
| 2998 | { |
| 2999 | saveFolderViewPrefsForDir(dirPath, { foldersFirst: foldersTopInput.checked }); |
| 3000 | renderFileGrid(); |
| 3001 | }); |
| 3002 | const foldersTopText = document.createElement('span'); |
| 3003 | foldersTopText.textContent = 'Always keep folders at the top'; |
| 3004 | foldersTopLabel.appendChild(foldersTopInput); |
| 3005 | foldersTopLabel.appendChild(foldersTopText); |
| 3006 | section.appendChild(foldersTopLabel); |
| 3007 | |
| 3008 | const ascLabel = document.createElement('label'); |
| 3009 | ascLabel.className = 'sidebar-view-toggle'; |
| 3010 | const ascInput = document.createElement('input'); |
| 3011 | ascInput.type = 'checkbox'; |
| 3012 | ascInput.dataset.viewOption = 'ascending'; |
| 3013 | ascInput.checked = !!prefs.ascending; |
| 3014 | ascInput.addEventListener('change', () => |
| 3015 | { |
| 3016 | saveFolderViewPrefsForDir(dirPath, { ascending: ascInput.checked }); |
| 3017 | renderFileGrid(); |
| 3018 | }); |
| 3019 | const ascText = document.createElement('span'); |
| 3020 | ascText.textContent = ascInput.checked ? 'Ascending' : 'Descending'; |
| 3021 | ascInput.addEventListener('change', () => |
| 3022 | { |
| 3023 | ascText.textContent = ascInput.checked ? 'Ascending' : 'Descending'; |
| 3024 | }); |
| 3025 | ascLabel.appendChild(ascInput); |
| 3026 | ascLabel.appendChild(ascText); |
| 3027 | section.appendChild(ascLabel); |
| 3028 | |
| 3029 | actions.appendChild(section); |
| 3030 | } |
| 3031 | |
| 3032 | function closeSidebar () |
| 3033 | { |
| 3034 | if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') return; |
| 3035 | beginSidebarLoad(); |
| 3036 | document.querySelectorAll('.file-item.selected').forEach(e => e.classList.remove('selected')); |
| 3037 | STATE.selectedItem = null; |
| 3038 | |
| 3039 | if (isMobileViewport()) |
| 3040 | { |
| 3041 | hideSidebarPanel(); |
| 3042 | return; |
| 3043 | } |
| 3044 | |
| 3045 | openFolderSidebar(); |
| 3046 | } |
| 3047 | |
| 3048 | function isMobileViewport () |
| 3049 | { |
| 3050 | return window.matchMedia(MOBILE_BREAKPOINT_QUERY).matches; |
| 3051 | } |
| 3052 | |
| 3053 | function hideSidebarPanel () |
| 3054 | { |
| 3055 | const sidebar = document.getElementById('sidebar'); |
| 3056 | const app = document.getElementById('app'); |
| 3057 | sidebar.classList.add('hidden'); |
| 3058 | app.classList.remove('sidebar-open'); |
| 3059 | } |
| 3060 | |
| 3061 | function basenameOfPath (p) |
| 3062 | { |
| 3063 | const parts = String(p || '').split(/[\\/]/).filter(Boolean); |
| 3064 | return parts.length ? parts[parts.length - 1] : String(p || ''); |
| 3065 | } |
| 3066 | |
| 3067 | async function fetchRootAccessList (rootPath) |
| 3068 | { |
| 3069 | if (!rootPath) return null; |
| 3070 | const data = await api('GET', `/files/root-access?rootPath=${encodeURIComponent(rootPath)}`).catch((err) => |
| 3071 | { |
| 3072 | if (isAbortError(err)) return null; |
| 3073 | return null; |
| 3074 | }); |
| 3075 | if (!data || !Array.isArray(data.users)) return null; |
| 3076 | return data.users; |
| 3077 | } |
| 3078 | |
| 3079 | function formatRootAccessList (users) |
| 3080 | { |
| 3081 | if (!Array.isArray(users) || users.length === 0) return 'No users'; |
| 3082 | |
| 3083 | const sorted = [...users].sort((a, b) => |
| 3084 | { |
| 3085 | const modeRank = (mode) => mode === 'R+W' ? 0 : 1; |
| 3086 | const byMode = modeRank(a.mode) - modeRank(b.mode); |
| 3087 | if (byMode !== 0) return byMode; |
| 3088 | return String(a.username).localeCompare(String(b.username)); |
| 3089 | }); |
| 3090 | |
| 3091 | const items = sorted |
| 3092 | .map((u) => `<li>${escapeHtml(String(u.username || ''))} ${escapeHtml(String(u.mode || 'R'))}</li>`) |
| 3093 | .join(''); |
| 3094 | return `<ul class="root-access-list">${items}</ul>`; |
| 3095 | } |
| 3096 | |
| 3097 | function rootPermissionLabel (root) |
| 3098 | { |
| 3099 | if (root && root.isUserFolder) return 'My Folder'; |
| 3100 | return (root && (root.originalName || root.label)) || ''; |
| 3101 | } |
| 3102 | |
| 3103 | function resolveRootForPath (targetPath) |
| 3104 | { |
| 3105 | if (!targetPath) return null; |
| 3106 | return STATE.roots.find((r) => samePath(targetPath, r.path) || pathInside(targetPath, r.path)) || null; |
| 3107 | } |
| 3108 | |
| 3109 | function writableRoots () |
| 3110 | { |
| 3111 | if (STATE.isAdmin) return STATE.roots.slice(); |
| 3112 | return STATE.roots.filter((r) => |
| 3113 | { |
| 3114 | if (r.isUserFolder) return true; |
| 3115 | const perm = STATE.permissions[rootPermissionLabel(r)]; |
| 3116 | return !!(perm && perm.write); |
| 3117 | }); |
| 3118 | } |
| 3119 | |
| 3120 | async function moveWithConflictResolution (item, targetDir) |
| 3121 | { |
| 3122 | try |
| 3123 | { |
| 3124 | return await api('POST', '/files/move', { from: item.path, toDir: targetDir }); |
| 3125 | } |
| 3126 | catch (err) |
| 3127 | { |
| 3128 | if (!/already exists/i.test(err.message || '')) throw err; |
| 3129 | |
| 3130 | const existingNames = await listDirNameSet(targetDir); |
| 3131 | const desiredName = item.name || basenameOfPath(item.path) || 'file'; |
| 3132 | const suggestedName = nextAvailableName(desiredName, existingNames); |
| 3133 | const decision = await showFileConflictChoice(desiredName, suggestedName, 'move'); |
| 3134 | if (decision === 'cancel') return null; |
| 3135 | |
| 3136 | if (decision === 'overwrite') |
| 3137 | { |
| 3138 | return api('POST', '/files/move', { |
| 3139 | from: item.path, |
| 3140 | toDir: targetDir, |
| 3141 | conflict: 'overwrite', |
| 3142 | }); |
| 3143 | } |
| 3144 | |
| 3145 | return api('POST', '/files/move', { |
| 3146 | from: item.path, |
| 3147 | toDir: targetDir, |
| 3148 | conflict: 'rename', |
| 3149 | targetName: suggestedName, |
| 3150 | }); |
| 3151 | } |
| 3152 | } |
| 3153 | |
| 3154 | async function copyWithConflictResolution (item, targetDir) |
| 3155 | { |
| 3156 | try |
| 3157 | { |
| 3158 | return await api('POST', '/files/copy', { from: item.path, toDir: targetDir }); |
| 3159 | } |
| 3160 | catch (err) |
| 3161 | { |
| 3162 | if (!/already exists/i.test(err.message || '')) throw err; |
| 3163 | |
| 3164 | const existingNames = await listDirNameSet(targetDir); |
| 3165 | const desiredName = item.name || basenameOfPath(item.path) || 'file'; |
| 3166 | const suggestedName = nextAvailableName(desiredName, existingNames); |
| 3167 | const decision = await showFileConflictChoice(desiredName, suggestedName, 'copy'); |
| 3168 | if (decision === 'cancel') return null; |
| 3169 | |
| 3170 | if (decision === 'overwrite') |
| 3171 | { |
| 3172 | return api('POST', '/files/copy', { |
| 3173 | from: item.path, |
| 3174 | toDir: targetDir, |
| 3175 | conflict: 'overwrite', |
| 3176 | }); |
| 3177 | } |
| 3178 | |
| 3179 | return api('POST', '/files/copy', { |
| 3180 | from: item.path, |
| 3181 | toDir: targetDir, |
| 3182 | conflict: 'rename', |
| 3183 | targetName: suggestedName, |
| 3184 | }); |
| 3185 | } |
| 3186 | } |
| 3187 | |
| 3188 | function ensureMoveModal () |
| 3189 | { |
| 3190 | let overlay = document.getElementById('move-modal'); |
| 3191 | if (overlay) return overlay; |
| 3192 | |
| 3193 | overlay = document.createElement('div'); |
| 3194 | overlay.id = 'move-modal'; |
| 3195 | overlay.className = 'modal-overlay hidden'; |
| 3196 | overlay.innerHTML = ` |
| 3197 | <div class="modal move-modal"> |
| 3198 | <button class="modal-close" id="move-modal-close" aria-label="Close">✕</button> |
| 3199 | <h2>Move To</h2> |
| 3200 | <p id="move-modal-caption" class="muted"></p> |
| 3201 | <div id="move-tree" class="move-tree"></div> |
| 3202 | <p id="move-selected" class="muted"></p> |
| 3203 | <div class="dialog-actions"> |
| 3204 | <button id="move-modal-cancel">Cancel</button> |
| 3205 | <button id="move-modal-confirm" class="primary">Move</button> |
| 3206 | </div> |
| 3207 | </div> |
| 3208 | `; |
| 3209 | document.body.appendChild(overlay); |
| 3210 | |
| 3211 | const closeBtn = overlay.querySelector('#move-modal-close'); |
| 3212 | const cancelBtn = overlay.querySelector('#move-modal-cancel'); |
| 3213 | const confirmBtn = overlay.querySelector('#move-modal-confirm'); |
| 3214 | |
| 3215 | function hide () |
| 3216 | { |
| 3217 | overlay.classList.add('hidden'); |
| 3218 | STATE.movePicker = null; |
| 3219 | } |
| 3220 | |
| 3221 | closeBtn.addEventListener('click', hide); |
| 3222 | cancelBtn.addEventListener('click', hide); |
| 3223 | overlay.addEventListener('click', (e) => |
| 3224 | { |
| 3225 | if (e.target === overlay) hide(); |
| 3226 | }); |
| 3227 | |
| 3228 | confirmBtn.addEventListener('click', async () => |
| 3229 | { |
| 3230 | const st = STATE.movePicker; |
| 3231 | if (!st || !st.item || !st.selectedPath) |
| 3232 | { |
| 3233 | toast('Select a destination folder first.', 'err'); |
| 3234 | return; |
| 3235 | } |
| 3236 | |
| 3237 | try |
| 3238 | { |
| 3239 | if (st.mode === 'copy') |
| 3240 | { |
| 3241 | const copied = await copyWithConflictResolution(st.item, st.selectedPath); |
| 3242 | if (!copied) return; |
| 3243 | } |
| 3244 | else |
| 3245 | { |
| 3246 | const moved = await moveWithConflictResolution(st.item, st.selectedPath); |
| 3247 | if (!moved) return; |
| 3248 | } |
| 3249 | } |
| 3250 | catch (err) |
| 3251 | { |
| 3252 | const action = st.mode === 'copy' ? 'Copy' : 'Move'; |
| 3253 | toast(`${action} failed: ${err.message}`, 'err'); |
| 3254 | return; |
| 3255 | } |
| 3256 | |
| 3257 | hide(); |
| 3258 | if (st.mode !== 'copy' && STATE.selectedItem && STATE.selectedItem.path === st.item.path) closeSidebar(); |
| 3259 | navigateTo(STATE.currentDir, STATE.currentRoot); |
| 3260 | }); |
| 3261 | |
| 3262 | return overlay; |
| 3263 | } |
| 3264 | |
| 3265 | function setMoveSelection (path, buttonEl) |
| 3266 | { |
| 3267 | if (!STATE.movePicker) return; |
| 3268 | STATE.movePicker.selectedPath = path; |
| 3269 | |
| 3270 | document.querySelectorAll('.move-node-label.selected').forEach((el) => el.classList.remove('selected')); |
| 3271 | if (buttonEl) buttonEl.classList.add('selected'); |
| 3272 | |
| 3273 | const selectedEl = document.getElementById('move-selected'); |
| 3274 | selectedEl.textContent = path ? `Destination: ${path}` : 'Destination: none'; |
| 3275 | } |
| 3276 | |
| 3277 | async function loadMoveChildren (containerEl, dirPath) |
| 3278 | { |
| 3279 | if (containerEl.dataset.loaded === '1') return; |
| 3280 | containerEl.dataset.loaded = '1'; |
| 3281 | |
| 3282 | const data = await api('GET', `/files/list?dir=${encodeURIComponent(dirPath)}`).catch(() => null); |
| 3283 | const folders = data ? data.items.filter((it) => it.isDir).sort((a, b) => a.name.localeCompare(b.name)) : []; |
| 3284 | |
| 3285 | if (!folders.length) |
| 3286 | { |
| 3287 | const empty = document.createElement('div'); |
| 3288 | empty.className = 'move-empty'; |
| 3289 | empty.textContent = 'No subfolders'; |
| 3290 | containerEl.appendChild(empty); |
| 3291 | return; |
| 3292 | } |
| 3293 | |
| 3294 | for (const child of folders) |
| 3295 | { |
| 3296 | containerEl.appendChild(createMoveNode(child.path, child.name)); |
| 3297 | } |
| 3298 | } |
| 3299 | |
| 3300 | function createMoveNode (folderPath, label) |
| 3301 | { |
| 3302 | const node = document.createElement('div'); |
| 3303 | node.className = 'move-node'; |
| 3304 | |
| 3305 | const row = document.createElement('div'); |
| 3306 | row.className = 'move-node-row'; |
| 3307 | |
| 3308 | const toggle = document.createElement('button'); |
| 3309 | toggle.type = 'button'; |
| 3310 | toggle.className = 'move-toggle'; |
| 3311 | toggle.textContent = '▸'; |
| 3312 | |
| 3313 | const selectBtn = document.createElement('button'); |
| 3314 | selectBtn.type = 'button'; |
| 3315 | selectBtn.className = 'move-node-label'; |
| 3316 | selectBtn.textContent = label; |
| 3317 | selectBtn.addEventListener('click', () => setMoveSelection(folderPath, selectBtn)); |
| 3318 | |
| 3319 | const children = document.createElement('div'); |
| 3320 | children.className = 'move-children hidden'; |
| 3321 | |
| 3322 | toggle.addEventListener('click', async () => |
| 3323 | { |
| 3324 | if (children.classList.contains('hidden')) |
| 3325 | { |
| 3326 | await loadMoveChildren(children, folderPath); |
| 3327 | children.classList.remove('hidden'); |
| 3328 | toggle.textContent = '▾'; |
| 3329 | } else |
| 3330 | { |
| 3331 | children.classList.add('hidden'); |
| 3332 | toggle.textContent = '▸'; |
| 3333 | } |
| 3334 | }); |
| 3335 | |
| 3336 | row.appendChild(toggle); |
| 3337 | row.appendChild(selectBtn); |
| 3338 | node.appendChild(row); |
| 3339 | node.appendChild(children); |
| 3340 | return node; |
| 3341 | } |
| 3342 | |
| 3343 | function openDestinationPicker (item, mode) |
| 3344 | { |
| 3345 | if (!canWrite()) |
| 3346 | { |
| 3347 | toast('No write access.', 'err'); |
| 3348 | return; |
| 3349 | } |
| 3350 | |
| 3351 | const roots = writableRoots(); |
| 3352 | if (!roots.length) |
| 3353 | { |
| 3354 | toast('No writable destination roots available.', 'err'); |
| 3355 | return; |
| 3356 | } |
| 3357 | |
| 3358 | const overlay = ensureMoveModal(); |
| 3359 | const tree = overlay.querySelector('#move-tree'); |
| 3360 | const caption = overlay.querySelector('#move-modal-caption'); |
| 3361 | const titleEl = overlay.querySelector('h2'); |
| 3362 | const confirmBtn = overlay.querySelector('#move-modal-confirm'); |
| 3363 | |
| 3364 | const op = mode === 'copy' ? 'copy' : 'move'; |
| 3365 | STATE.movePicker = { item, selectedPath: null, mode: op }; |
| 3366 | titleEl.textContent = op === 'copy' ? 'Copy To' : 'Move To'; |
| 3367 | confirmBtn.textContent = op === 'copy' ? 'Copy' : 'Move'; |
| 3368 | caption.textContent = `Select destination folder for: ${item.name}`; |
| 3369 | tree.innerHTML = ''; |
| 3370 | |
| 3371 | for (const root of roots) |
| 3372 | { |
| 3373 | tree.appendChild(createMoveNode(root.path, root.label)); |
| 3374 | } |
| 3375 | |
| 3376 | setMoveSelection(null, null); |
| 3377 | overlay.classList.remove('hidden'); |
| 3378 | } |
| 3379 | |
| 3380 | function openMovePicker (item) |
| 3381 | { |
| 3382 | openDestinationPicker(item, 'move'); |
| 3383 | } |
| 3384 | |
| 3385 | function openCopyPicker (item) |
| 3386 | { |
| 3387 | openDestinationPicker(item, 'copy'); |
| 3388 | } |
| 3389 | |
| 3390 | // ─────────────────────────────────────────────────────────────────────────── |
| 3391 | // FOLDER ICON PICKER |
| 3392 | // ─────────────────────────────────────────────────────────────────────────── |
| 3393 | |
| 3394 | function globalFaviconFallbackMarkup () |
| 3395 | { |
| 3396 | return iconFile('favicon.png', 18); |
| 3397 | } |
| 3398 | |
| 3399 | function applyGlobalFaviconPreview (hasFavicon) |
| 3400 | { |
| 3401 | if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return; |
| 3402 | const preview = document.getElementById('global-favicon-preview'); |
| 3403 | if (!preview) return; |
| 3404 | |
| 3405 | if (!hasFavicon) |
| 3406 | { |
| 3407 | preview.innerHTML = globalFaviconFallbackMarkup(); |
| 3408 | return; |
| 3409 | } |
| 3410 | |
| 3411 | const img = document.createElement('img'); |
| 3412 | img.alt = 'Current favicon'; |
| 3413 | img.src = `/api/files/global-favicon-image?v=${STATE.faviconVersion}`; |
| 3414 | img.addEventListener('error', () => |
| 3415 | { |
| 3416 | preview.innerHTML = globalFaviconFallbackMarkup(); |
| 3417 | }, { once: true }); |
| 3418 | preview.innerHTML = ''; |
| 3419 | preview.appendChild(img); |
| 3420 | } |
| 3421 | |
| 3422 | function applyGlobalFaviconLink (hasFavicon) |
| 3423 | { |
| 3424 | if (typeof document === 'undefined' || typeof document.getElementById !== 'function' || !document.head) return; |
| 3425 | let link = document.getElementById('global-favicon-link'); |
| 3426 | if (!link) |
| 3427 | { |
| 3428 | link = document.createElement('link'); |
| 3429 | link.id = 'global-favicon-link'; |
| 3430 | link.rel = 'icon'; |
| 3431 | document.head.appendChild(link); |
| 3432 | } |
| 3433 | |
| 3434 | if (!hasFavicon) |
| 3435 | { |
| 3436 | link.removeAttribute('href'); |
| 3437 | return; |
| 3438 | } |
| 3439 | |
| 3440 | link.href = `/api/files/global-favicon-image?v=${STATE.faviconVersion}`; |
| 3441 | } |
| 3442 | |
| 3443 | async function refreshGlobalFavicon () |
| 3444 | { |
| 3445 | const data = await api('GET', '/files/global-favicon').catch(() => null); |
| 3446 | const hasFavicon = !!(data && data.favicon && data.favicon.filePath); |
| 3447 | applyGlobalFaviconPreview(hasFavicon); |
| 3448 | applyGlobalFaviconLink(hasFavicon); |
| 3449 | } |
| 3450 | |
| 3451 | async function openIconPickerModal ({ |
| 3452 | dirPath, |
| 3453 | titleText, |
| 3454 | subtitleText, |
| 3455 | emptyText, |
| 3456 | confirmLabel, |
| 3457 | clearLabel, |
| 3458 | onSelect, |
| 3459 | onClear, |
| 3460 | }) |
| 3461 | { |
| 3462 | if (!dirPath) |
| 3463 | { |
| 3464 | toast('Open a folder first.', 'err'); |
| 3465 | return; |
| 3466 | } |
| 3467 | |
| 3468 | const data = await api('GET', `/files/folder-images?dir=${encodeURIComponent(dirPath)}`).catch(() => null); |
| 3469 | const images = data ? data.images : []; |
| 3470 | |
| 3471 | const existingIconOverlay = document.getElementById('folder-icon-picker'); |
| 3472 | if (existingIconOverlay) existingIconOverlay.remove(); |
| 3473 | |
| 3474 | const overlay = document.createElement('div'); |
| 3475 | overlay.id = 'folder-icon-picker'; |
| 3476 | overlay.className = 'modal-overlay'; |
| 3477 | |
| 3478 | const modal = document.createElement('div'); |
| 3479 | modal.className = 'modal folder-icon-modal'; |
| 3480 | |
| 3481 | const closeBtn = document.createElement('button'); |
| 3482 | closeBtn.className = 'modal-close'; |
| 3483 | closeBtn.setAttribute('aria-label', 'Close'); |
| 3484 | closeBtn.textContent = '✕'; |
| 3485 | |
| 3486 | const title = document.createElement('h2'); |
| 3487 | title.textContent = titleText; |
| 3488 | |
| 3489 | const filterInput = document.createElement('input'); |
| 3490 | filterInput.type = 'text'; |
| 3491 | filterInput.className = 'folder-icon-filter'; |
| 3492 | filterInput.placeholder = 'Search icons'; |
| 3493 | filterInput.setAttribute('aria-label', 'Search icons'); |
| 3494 | |
| 3495 | const subtitle = document.createElement('p'); |
| 3496 | subtitle.className = 'muted'; |
| 3497 | subtitle.textContent = images.length ? subtitleText : emptyText; |
| 3498 | |
| 3499 | const grid = document.createElement('div'); |
| 3500 | grid.className = 'folder-icon-grid'; |
| 3501 | |
| 3502 | for (const { filePath } of images) |
| 3503 | { |
| 3504 | const name = filePath.split('/').pop(); |
| 3505 | const cell = document.createElement('div'); |
| 3506 | cell.className = 'folder-icon-cell'; |
| 3507 | cell.dataset.path = filePath; |
| 3508 | cell.dataset.name = String(name || '').toLowerCase(); |
| 3509 | |
| 3510 | const imgEl = document.createElement('img'); |
| 3511 | imgEl.alt = name; |
| 3512 | imgEl.className = 'folder-icon-thumb'; |
| 3513 | imgEl.dataset.src = filePath; |
| 3514 | |
| 3515 | const label = document.createElement('div'); |
| 3516 | label.className = 'folder-icon-label'; |
| 3517 | label.textContent = name; |
| 3518 | |
| 3519 | cell.appendChild(imgEl); |
| 3520 | cell.appendChild(label); |
| 3521 | |
| 3522 | cell.addEventListener('click', () => |
| 3523 | { |
| 3524 | grid.querySelectorAll('.folder-icon-cell.selected').forEach(el => el.classList.remove('selected')); |
| 3525 | cell.classList.add('selected'); |
| 3526 | confirmBtn.disabled = false; |
| 3527 | }); |
| 3528 | |
| 3529 | grid.appendChild(cell); |
| 3530 | } |
| 3531 | |
| 3532 | function applyFilter () |
| 3533 | { |
| 3534 | const needle = String(filterInput.value || '').trim().toLowerCase(); |
| 3535 | let visible = 0; |
| 3536 | for (const cell of grid.querySelectorAll('.folder-icon-cell')) |
| 3537 | { |
| 3538 | const name = cell.dataset.name || ''; |
| 3539 | const show = !needle || name.includes(needle); |
| 3540 | cell.classList.toggle('hidden', !show); |
| 3541 | if (show) visible += 1; |
| 3542 | } |
| 3543 | subtitle.textContent = visible |
| 3544 | ? subtitleText |
| 3545 | : 'No matching thumbnails were found.'; |
| 3546 | } |
| 3547 | |
| 3548 | filterInput.addEventListener('input', applyFilter); |
| 3549 | |
| 3550 | const dialogActions = document.createElement('div'); |
| 3551 | dialogActions.className = 'dialog-actions'; |
| 3552 | |
| 3553 | const clearBtn = document.createElement('button'); |
| 3554 | clearBtn.textContent = clearLabel; |
| 3555 | clearBtn.addEventListener('click', async () => |
| 3556 | { |
| 3557 | try |
| 3558 | { |
| 3559 | await onClear(); |
| 3560 | } |
| 3561 | catch (err) |
| 3562 | { |
| 3563 | toast('Failed to clear icon: ' + err.message, 'err'); |
| 3564 | return; |
| 3565 | } |
| 3566 | hide(); |
| 3567 | }); |
| 3568 | |
| 3569 | const cancelBtn = document.createElement('button'); |
| 3570 | cancelBtn.textContent = 'Cancel'; |
| 3571 | cancelBtn.addEventListener('click', () => hide()); |
| 3572 | |
| 3573 | const confirmBtn = document.createElement('button'); |
| 3574 | confirmBtn.className = 'primary'; |
| 3575 | confirmBtn.textContent = confirmLabel; |
| 3576 | confirmBtn.disabled = true; |
| 3577 | confirmBtn.addEventListener('click', async () => |
| 3578 | { |
| 3579 | const selected = grid.querySelector('.folder-icon-cell.selected'); |
| 3580 | if (!selected) return; |
| 3581 | |
| 3582 | try |
| 3583 | { |
| 3584 | await onSelect(selected.dataset.path); |
| 3585 | } |
| 3586 | catch (err) |
| 3587 | { |
| 3588 | toast('Failed to set icon: ' + err.message, 'err'); |
| 3589 | return; |
| 3590 | } |
| 3591 | |
| 3592 | hide(); |
| 3593 | }); |
| 3594 | |
| 3595 | dialogActions.appendChild(clearBtn); |
| 3596 | dialogActions.appendChild(cancelBtn); |
| 3597 | dialogActions.appendChild(confirmBtn); |
| 3598 | |
| 3599 | modal.appendChild(closeBtn); |
| 3600 | modal.appendChild(title); |
| 3601 | modal.appendChild(filterInput); |
| 3602 | modal.appendChild(subtitle); |
| 3603 | modal.appendChild(grid); |
| 3604 | modal.appendChild(dialogActions); |
| 3605 | overlay.appendChild(modal); |
| 3606 | document.body.appendChild(overlay); |
| 3607 | |
| 3608 | function hide () |
| 3609 | { |
| 3610 | overlay.remove(); |
| 3611 | grid.querySelectorAll('.folder-icon-thumb[src^="blob:"]').forEach((img) => |
| 3612 | { |
| 3613 | URL.revokeObjectURL(img.src); |
| 3614 | }); |
| 3615 | } |
| 3616 | |
| 3617 | closeBtn.addEventListener('click', hide); |
| 3618 | overlay.addEventListener('click', (e) => { if (e.target === overlay) hide(); }); |
| 3619 | |
| 3620 | for (const cell of grid.querySelectorAll('.folder-icon-cell')) |
| 3621 | { |
| 3622 | const imgEl = cell.querySelector('.folder-icon-thumb'); |
| 3623 | const filePath = imgEl.dataset.src; |
| 3624 | void fetch(`/api/files/thumbnail?file=${encodeURIComponent(filePath)}`, { |
| 3625 | headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() }, |
| 3626 | }).then(async (r) => |
| 3627 | { |
| 3628 | if (!r.ok || !overlay.isConnected) return; |
| 3629 | const blob = await r.blob(); |
| 3630 | const url = URL.createObjectURL(blob); |
| 3631 | imgEl.src = url; |
| 3632 | }).catch(() => { }); |
| 3633 | } |
| 3634 | |
| 3635 | filterInput.focus(); |
| 3636 | } |
| 3637 | |
| 3638 | async function openFolderIconPicker (item) |
| 3639 | { |
| 3640 | if (!canWrite(item)) |
| 3641 | { |
| 3642 | toast('No write access.', 'err'); |
| 3643 | return; |
| 3644 | } |
| 3645 | |
| 3646 | await openIconPickerModal({ |
| 3647 | dirPath: item.path, |
| 3648 | titleText: 'Set folder icon', |
| 3649 | subtitleText: 'Select a file thumbnail to use as the folder icon.', |
| 3650 | emptyText: 'No files with cached thumbnails were found inside this folder.', |
| 3651 | confirmLabel: 'Set icon', |
| 3652 | clearLabel: 'Clear icon', |
| 3653 | onSelect: async (imagePath) => |
| 3654 | { |
| 3655 | await api('POST', '/files/folder-icon', { folderPath: item.path, imagePath }); |
| 3656 | refreshAfterIconChange(item); |
| 3657 | }, |
| 3658 | onClear: async () => |
| 3659 | { |
| 3660 | await api('POST', '/files/folder-icon', { folderPath: item.path, imagePath: null }); |
| 3661 | refreshAfterIconChange(item); |
| 3662 | }, |
| 3663 | }); |
| 3664 | } |
| 3665 | |
| 3666 | async function openGlobalFaviconPicker () |
| 3667 | { |
| 3668 | if (!STATE.isAdmin) |
| 3669 | { |
| 3670 | toast('Admin access required.', 'err'); |
| 3671 | return; |
| 3672 | } |
| 3673 | |
| 3674 | const existingIconOverlay = document.getElementById('folder-icon-picker'); |
| 3675 | if (existingIconOverlay) existingIconOverlay.remove(); |
| 3676 | |
| 3677 | const overlay = document.createElement('div'); |
| 3678 | overlay.id = 'folder-icon-picker'; |
| 3679 | overlay.className = 'modal-overlay'; |
| 3680 | |
| 3681 | const modal = document.createElement('div'); |
| 3682 | modal.className = 'modal folder-icon-modal'; |
| 3683 | |
| 3684 | const closeBtn = document.createElement('button'); |
| 3685 | closeBtn.className = 'modal-close'; |
| 3686 | closeBtn.setAttribute('aria-label', 'Close'); |
| 3687 | closeBtn.textContent = '✕'; |
| 3688 | |
| 3689 | const title = document.createElement('h2'); |
| 3690 | title.textContent = 'Set global favicon'; |
| 3691 | |
| 3692 | const filterInput = document.createElement('input'); |
| 3693 | filterInput.type = 'text'; |
| 3694 | filterInput.className = 'folder-icon-filter'; |
| 3695 | filterInput.placeholder = 'Search images across all folders'; |
| 3696 | filterInput.setAttribute('aria-label', 'Search images'); |
| 3697 | |
| 3698 | const subtitle = document.createElement('p'); |
| 3699 | subtitle.className = 'muted'; |
| 3700 | subtitle.textContent = 'Type at least 2 characters to search accessible images.'; |
| 3701 | |
| 3702 | const grid = document.createElement('div'); |
| 3703 | grid.className = 'folder-icon-grid'; |
| 3704 | |
| 3705 | const dialogActions = document.createElement('div'); |
| 3706 | dialogActions.className = 'dialog-actions'; |
| 3707 | |
| 3708 | const clearBtn = document.createElement('button'); |
| 3709 | clearBtn.textContent = 'Clear favicon'; |
| 3710 | clearBtn.addEventListener('click', async () => |
| 3711 | { |
| 3712 | try |
| 3713 | { |
| 3714 | await api('POST', '/files/global-favicon', { imagePath: null }); |
| 3715 | STATE.faviconVersion = Date.now(); |
| 3716 | await refreshGlobalFavicon(); |
| 3717 | } |
| 3718 | catch (err) |
| 3719 | { |
| 3720 | toast('Failed to clear icon: ' + err.message, 'err'); |
| 3721 | return; |
| 3722 | } |
| 3723 | hide(); |
| 3724 | }); |
| 3725 | |
| 3726 | const cancelBtn = document.createElement('button'); |
| 3727 | cancelBtn.textContent = 'Cancel'; |
| 3728 | cancelBtn.addEventListener('click', () => hide()); |
| 3729 | |
| 3730 | const confirmBtn = document.createElement('button'); |
| 3731 | confirmBtn.className = 'primary'; |
| 3732 | confirmBtn.textContent = 'Set favicon'; |
| 3733 | confirmBtn.disabled = true; |
| 3734 | |
| 3735 | let selectedPath = null; |
| 3736 | let searchToken = 0; |
| 3737 | let searchTimer = null; |
| 3738 | |
| 3739 | confirmBtn.addEventListener('click', async () => |
| 3740 | { |
| 3741 | if (!selectedPath) return; |
| 3742 | try |
| 3743 | { |
| 3744 | await api('POST', '/files/global-favicon', { imagePath: selectedPath }); |
| 3745 | STATE.faviconVersion = Date.now(); |
| 3746 | await refreshGlobalFavicon(); |
| 3747 | } |
| 3748 | catch (err) |
| 3749 | { |
| 3750 | toast('Failed to set icon: ' + err.message, 'err'); |
| 3751 | return; |
| 3752 | } |
| 3753 | hide(); |
| 3754 | }); |
| 3755 | |
| 3756 | function revokeCellThumbs () |
| 3757 | { |
| 3758 | grid.querySelectorAll('.folder-icon-thumb[src^="blob:"]').forEach((img) => |
| 3759 | { |
| 3760 | URL.revokeObjectURL(img.src); |
| 3761 | }); |
| 3762 | } |
| 3763 | |
| 3764 | function renderResults (items) |
| 3765 | { |
| 3766 | selectedPath = null; |
| 3767 | confirmBtn.disabled = true; |
| 3768 | revokeCellThumbs(); |
| 3769 | grid.innerHTML = ''; |
| 3770 | |
| 3771 | for (const { path: filePath, name } of (items || [])) |
| 3772 | { |
| 3773 | const cell = document.createElement('div'); |
| 3774 | cell.className = 'folder-icon-cell'; |
| 3775 | cell.dataset.path = filePath; |
| 3776 | |
| 3777 | const imgEl = document.createElement('img'); |
| 3778 | imgEl.alt = name; |
| 3779 | imgEl.className = 'folder-icon-thumb'; |
| 3780 | |
| 3781 | const label = document.createElement('div'); |
| 3782 | label.className = 'folder-icon-label'; |
| 3783 | label.textContent = name; |
| 3784 | |
| 3785 | cell.appendChild(imgEl); |
| 3786 | cell.appendChild(label); |
| 3787 | |
| 3788 | cell.addEventListener('click', () => |
| 3789 | { |
| 3790 | grid.querySelectorAll('.folder-icon-cell.selected').forEach(el => el.classList.remove('selected')); |
| 3791 | cell.classList.add('selected'); |
| 3792 | selectedPath = filePath; |
| 3793 | confirmBtn.disabled = false; |
| 3794 | }); |
| 3795 | |
| 3796 | grid.appendChild(cell); |
| 3797 | |
| 3798 | void fetch(`/api/files/thumbnail?file=${encodeURIComponent(filePath)}`, { |
| 3799 | headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() }, |
| 3800 | }).then(async (r) => |
| 3801 | { |
| 3802 | if (!r.ok || !overlay.isConnected) return; |
| 3803 | const blob = await r.blob(); |
| 3804 | const url = URL.createObjectURL(blob); |
| 3805 | imgEl.src = url; |
| 3806 | }).catch(() => { }); |
| 3807 | } |
| 3808 | } |
| 3809 | |
| 3810 | async function runSearchNow () |
| 3811 | { |
| 3812 | const query = String(filterInput.value || '').trim(); |
| 3813 | searchToken += 1; |
| 3814 | const token = searchToken; |
| 3815 | |
| 3816 | if (query.length < 2) |
| 3817 | { |
| 3818 | subtitle.textContent = 'Type at least 2 characters to search accessible images.'; |
| 3819 | renderResults([]); |
| 3820 | return; |
| 3821 | } |
| 3822 | |
| 3823 | subtitle.textContent = 'Searching…'; |
| 3824 | const data = await api('GET', `/files/search-images?query=${encodeURIComponent(query)}&limit=80`).catch(() => null); |
| 3825 | if (!overlay.isConnected || token !== searchToken) return; |
| 3826 | |
| 3827 | const results = Array.isArray(data && data.results) ? data.results : []; |
| 3828 | renderResults(results); |
| 3829 | |
| 3830 | if (!results.length) |
| 3831 | { |
| 3832 | subtitle.textContent = 'No matching thumbnails were found.'; |
| 3833 | return; |
| 3834 | } |
| 3835 | |
| 3836 | const suffix = data && data.truncated |
| 3837 | ? ` Scanned first ${Number(data.scannedFiles) || 0} files; refine your search for more.` |
| 3838 | : ''; |
| 3839 | subtitle.textContent = `${results.length} matching image${results.length === 1 ? '' : 's'} found.${suffix}`; |
| 3840 | } |
| 3841 | |
| 3842 | filterInput.addEventListener('input', () => |
| 3843 | { |
| 3844 | if (searchTimer) clearTimeout(searchTimer); |
| 3845 | searchTimer = setTimeout(() => |
| 3846 | { |
| 3847 | void runSearchNow(); |
| 3848 | }, 240); |
| 3849 | }); |
| 3850 | |
| 3851 | dialogActions.appendChild(clearBtn); |
| 3852 | dialogActions.appendChild(cancelBtn); |
| 3853 | dialogActions.appendChild(confirmBtn); |
| 3854 | |
| 3855 | modal.appendChild(closeBtn); |
| 3856 | modal.appendChild(title); |
| 3857 | modal.appendChild(filterInput); |
| 3858 | modal.appendChild(subtitle); |
| 3859 | modal.appendChild(grid); |
| 3860 | modal.appendChild(dialogActions); |
| 3861 | overlay.appendChild(modal); |
| 3862 | document.body.appendChild(overlay); |
| 3863 | |
| 3864 | function hide () |
| 3865 | { |
| 3866 | if (searchTimer) clearTimeout(searchTimer); |
| 3867 | overlay.remove(); |
| 3868 | revokeCellThumbs(); |
| 3869 | } |
| 3870 | |
| 3871 | closeBtn.addEventListener('click', hide); |
| 3872 | overlay.addEventListener('click', (e) => { if (e.target === overlay) hide(); }); |
| 3873 | filterInput.focus(); |
| 3874 | } |
| 3875 | |
| 3876 | function refreshAfterIconChange (item) |
| 3877 | { |
| 3878 | // Reset and reload icon in grid tiles. |
| 3879 | const gridTile = Array.from(document.querySelectorAll('.icon[data-folder-path]')) |
| 3880 | .find(el => el.dataset.folderPath === item.path); |
| 3881 | if (gridTile) |
| 3882 | { |
| 3883 | const svg = gridTile.querySelector('svg'); |
| 3884 | if (svg) |
| 3885 | { |
| 3886 | // Rebuild to plain folder SVG, then reload. |
| 3887 | gridTile.innerHTML = iconFolder(); |
| 3888 | delete gridTile.dataset.thumbReady; |
| 3889 | gridTile.dataset.folderPath = item.path; |
| 3890 | void loadOneFolderIcon(gridTile); |
| 3891 | } |
| 3892 | } |
| 3893 | |
| 3894 | // Also reset the sidebar icon if it's showing the same folder. |
| 3895 | const sidebarIcon = document.getElementById('sidebar-icon'); |
| 3896 | if (sidebarIcon && sidebarIcon.dataset.folderPath === item.path) |
| 3897 | { |
| 3898 | sidebarIcon.innerHTML = iconFolder(64); |
| 3899 | delete sidebarIcon.dataset.thumbReady; |
| 3900 | void loadOneFolderIcon(sidebarIcon); |
| 3901 | } |
| 3902 | } |
| 3903 | |
| 3904 | // ─────────────────────────────────────────────────────────────────────────── |
| 3905 | // DOWNLOAD / VIEW |
| 3906 | // ─────────────────────────────────────────────────────────────────────────── |
| 3907 | |
| 3908 | function isInlinePreviewableBlob (blob, name) |
| 3909 | { |
| 3910 | const mime = String(blob.type || '').toLowerCase(); |
| 3911 | if (/^(image|video|audio)\//.test(mime)) return true; |
| 3912 | if (/^text\//.test(mime)) return true; |
| 3913 | if (mime === 'application/pdf') return true; |
| 3914 | if (mime === 'application/json') return true; |
| 3915 | if (mime === 'application/xml') return true; |
| 3916 | if (mime === 'application/javascript') return true; |
| 3917 | |
| 3918 | // Fallback by extension when MIME is missing or generic. |
| 3919 | const ext = extOf(name || ''); |
| 3920 | if (IMAGE_EXTS.has(ext) || VIDEO_EXTS.has(ext) || AUDIO_EXTS.has(ext)) return true; |
| 3921 | if (MODEL_EXTS.has(ext)) return true; |
| 3922 | if (MODEL_EXTS.has(ext)) return true; |
| 3923 | if (CODE_EXTS.has(ext)) return true; |
| 3924 | return false; |
| 3925 | } |
| 3926 | |
| 3927 | function isTextLikeBlob (blob, name) |
| 3928 | { |
| 3929 | const mime = String(blob.type || '').toLowerCase(); |
| 3930 | if (/^text\//.test(mime)) return true; |
| 3931 | if (mime === 'application/json' || mime === 'application/xml' || mime === 'application/javascript') return true; |
| 3932 | const ext = extOf(name || ''); |
| 3933 | return CODE_EXTS.has(ext); |
| 3934 | } |
| 3935 | |
| 3936 | function detectCodeLanguage (name, mime) |
| 3937 | { |
| 3938 | const ext = extOf(name || ''); |
| 3939 | const m = String(mime || '').toLowerCase(); |
| 3940 | if (m.includes('json') || ext === 'json') return 'json'; |
| 3941 | if (m.includes('xml') || ext === 'xml') return 'xml'; |
| 3942 | if (m.includes('html') || ext === 'html' || ext === 'htm') return 'html'; |
| 3943 | if (m.includes('css') || ext === 'css') return 'css'; |
| 3944 | if (m.includes('javascript') || ['js', 'jsx', 'mjs', 'cjs'].includes(ext)) return 'js'; |
| 3945 | if (m.includes('typescript') || ['ts', 'tsx'].includes(ext)) return 'ts'; |
| 3946 | if (['sh', 'bash', 'zsh'].includes(ext)) return 'sh'; |
| 3947 | if (['md', 'txt', 'log', 'ini', 'toml', 'yaml', 'yml'].includes(ext)) return 'plain'; |
| 3948 | return CODE_EXTS.has(ext) ? 'js' : 'plain'; |
| 3949 | } |
| 3950 | |
| 3951 | function prettyPrintMarkup (raw) |
| 3952 | { |
| 3953 | const src = String(raw || '') |
| 3954 | .replace(/>\s+</g, '><') |
| 3955 | .replace(/\r\n/g, '\n'); |
| 3956 | |
| 3957 | const lines = src.replace(/></g, '>\n<').split('\n'); |
| 3958 | let indent = 0; |
| 3959 | const out = []; |
| 3960 | |
| 3961 | for (const ln of lines) |
| 3962 | { |
| 3963 | const line = ln.trim(); |
| 3964 | if (!line) continue; |
| 3965 | const isClose = /^<\//.test(line); |
| 3966 | const isSelf = /\/>$/.test(line) || /^<[^!?][^>]*>[^<]*<\/[^>]+>$/.test(line); |
| 3967 | const isOpen = /^<[^!?/][^>]*>$/.test(line); |
| 3968 | |
| 3969 | if (isClose) indent = Math.max(0, indent - 1); |
| 3970 | out.push(' '.repeat(indent) + line); |
| 3971 | if (isOpen && !isSelf) indent += 1; |
| 3972 | } |
| 3973 | |
| 3974 | return out.join('\n'); |
| 3975 | } |
| 3976 | |
| 3977 | function prettyPrintBraces (raw) |
| 3978 | { |
| 3979 | const lines = String(raw || '') |
| 3980 | .replace(/\r\n/g, '\n') |
| 3981 | .split('\n'); |
| 3982 | let indent = 0; |
| 3983 | const out = []; |
| 3984 | |
| 3985 | for (const ln of lines) |
| 3986 | { |
| 3987 | const line = ln.trim(); |
| 3988 | if (!line) |
| 3989 | { |
| 3990 | out.push(''); |
| 3991 | continue; |
| 3992 | } |
| 3993 | if (/^[}\])]/.test(line)) indent = Math.max(0, indent - 1); |
| 3994 | out.push(' '.repeat(indent) + line); |
| 3995 | if (/[{[(]$/.test(line) || /[{[(]\s*(\/\/.*)?$/.test(line)) indent += 1; |
| 3996 | } |
| 3997 | return out.join('\n'); |
| 3998 | } |
| 3999 | |
| 4000 | function prettyPrintCode (raw, lang) |
| 4001 | { |
| 4002 | const text = String(raw || '').replace(/\r\n/g, '\n'); |
| 4003 | if (lang === 'json') |
| 4004 | { |
| 4005 | try { return JSON.stringify(JSON.parse(text), null, 2); } catch { return text; } |
| 4006 | } |
| 4007 | if (lang === 'xml' || lang === 'html') return prettyPrintMarkup(text); |
| 4008 | if (lang === 'js' || lang === 'ts' || lang === 'css') return prettyPrintBraces(text); |
| 4009 | return text; |
| 4010 | } |
| 4011 | |
| 4012 | function escapeHtml (s) |
| 4013 | { |
| 4014 | return String(s) |
| 4015 | .replace(/&/g, '&') |
| 4016 | .replace(/</g, '<') |
| 4017 | .replace(/>/g, '>'); |
| 4018 | } |
| 4019 | |
| 4020 | function highlightCode (raw, lang) |
| 4021 | { |
| 4022 | if (lang === 'plain') return escapeHtml(raw); |
| 4023 | |
| 4024 | let html = escapeHtml(raw); |
| 4025 | const stash = []; |
| 4026 | const keep = (regex, cls) => |
| 4027 | { |
| 4028 | html = html.replace(regex, (m) => |
| 4029 | { |
| 4030 | const idx = stash.push(`<span class="tok-${cls}">${m}</span>`) - 1; |
| 4031 | return `@@TOK${idx}@@`; |
| 4032 | }); |
| 4033 | }; |
| 4034 | |
| 4035 | if (lang === 'json') |
| 4036 | { |
| 4037 | html = html |
| 4038 | .replace(/("(?:\\.|[^"\\])*")\s*:/g, '<span class="tok-key">$1</span>:') |
| 4039 | .replace(/: ("(?:\\.|[^"\\])*")/g, ': <span class="tok-string">$1</span>') |
| 4040 | .replace(/\b(true|false|null)\b/g, '<span class="tok-keyword">$1</span>') |
| 4041 | .replace(/\b(-?\d+(?:\.\d+)?(?:e[+\-]?\d+)?)\b/gi, '<span class="tok-number">$1</span>'); |
| 4042 | return html; |
| 4043 | } |
| 4044 | |
| 4045 | if (lang === 'xml' || lang === 'html') |
| 4046 | { |
| 4047 | html = html |
| 4048 | .replace(/(<\/?)([a-zA-Z0-9:_-]+)/g, '$1<span class="tok-keyword">$2</span>') |
| 4049 | .replace(/([a-zA-Z0-9:_-]+)=("[^&]*"|"[^"]*")/g, '<span class="tok-key">$1</span>=<span class="tok-string">$2</span>'); |
| 4050 | return html; |
| 4051 | } |
| 4052 | |
| 4053 | if (lang === 'sh') keep(/(^|\s)#.*$/gm, 'comment'); |
| 4054 | else keep(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, 'comment'); |
| 4055 | keep(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`/g, 'string'); |
| 4056 | |
| 4057 | html = html |
| 4058 | .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>') |
| 4059 | .replace(/\b(-?\d+(?:\.\d+)?(?:e[+\-]?\d+)?)\b/gi, '<span class="tok-number">$1</span>'); |
| 4060 | |
| 4061 | html = html.replace(/@@TOK(\d+)@@/g, (_, idx) => stash[Number(idx)] || ''); |
| 4062 | return html; |
| 4063 | } |
| 4064 | |
| 4065 | function clearPreviewObjectUrl () |
| 4066 | { |
| 4067 | if (typeof STATE.previewCleanup === 'function') |
| 4068 | { |
| 4069 | try { STATE.previewCleanup(); } catch { /* ignore */ } |
| 4070 | } |
| 4071 | STATE.previewCleanup = null; |
| 4072 | STATE.previewDownloadAction = null; |
| 4073 | if (!STATE.previewObjectUrl) return; |
| 4074 | if (String(STATE.previewObjectUrl).startsWith('blob:')) |
| 4075 | { |
| 4076 | URL.revokeObjectURL(STATE.previewObjectUrl); |
| 4077 | } |
| 4078 | STATE.previewObjectUrl = null; |
| 4079 | } |
| 4080 | |
| 4081 | function ensureStylesheet (id, href) |
| 4082 | { |
| 4083 | let link = document.getElementById(id); |
| 4084 | if (link) return Promise.resolve(link); |
| 4085 | |
| 4086 | link = document.createElement('link'); |
| 4087 | link.id = id; |
| 4088 | link.rel = 'stylesheet'; |
| 4089 | link.href = href; |
| 4090 | |
| 4091 | return new Promise((resolve, reject) => |
| 4092 | { |
| 4093 | link.addEventListener('load', () => resolve(link), { once: true }); |
| 4094 | link.addEventListener('error', () => reject(new Error('Failed to load video player styles.')), { once: true }); |
| 4095 | document.head.appendChild(link); |
| 4096 | }); |
| 4097 | } |
| 4098 | |
| 4099 | function ensureScript (id, src) |
| 4100 | { |
| 4101 | let script = document.getElementById(id); |
| 4102 | if (script && window.videojs) return Promise.resolve(window.videojs); |
| 4103 | |
| 4104 | if (!script) |
| 4105 | { |
| 4106 | script = document.createElement('script'); |
| 4107 | script.id = id; |
| 4108 | script.src = src; |
| 4109 | } |
| 4110 | |
| 4111 | return new Promise((resolve, reject) => |
| 4112 | { |
| 4113 | script.addEventListener('load', () => resolve(window.videojs), { once: true }); |
| 4114 | script.addEventListener('error', () => reject(new Error('Failed to load video player script.')), { once: true }); |
| 4115 | if (!script.isConnected) document.head.appendChild(script); |
| 4116 | }); |
| 4117 | } |
| 4118 | |
| 4119 | async function ensureVideoJsLoaded () |
| 4120 | { |
| 4121 | if (window.videojs) |
| 4122 | { |
| 4123 | configureVideoJsBuffering(window.videojs); |
| 4124 | return window.videojs; |
| 4125 | } |
| 4126 | if (!videoJsLoaderPromise) |
| 4127 | { |
| 4128 | videoJsLoaderPromise = Promise.all([ |
| 4129 | ensureStylesheet('videojs-styles', '/vendor/video.js/video-js.css'), |
| 4130 | ensureScript('videojs-script', '/vendor/video.js/video.min.js'), |
| 4131 | ]).then(() => |
| 4132 | { |
| 4133 | configureVideoJsBuffering(window.videojs); |
| 4134 | return window.videojs; |
| 4135 | }); |
| 4136 | } |
| 4137 | return videoJsLoaderPromise; |
| 4138 | } |
| 4139 | |
| 4140 | function configureVideoJsBuffering (videojs) |
| 4141 | { |
| 4142 | if (!VIDEO_FORWARD_BUFFER_OVERRIDE_ENABLED) |
| 4143 | return; |
| 4144 | |
| 4145 | if (!videojs || !videojs.Vhs || videojs.__filemanagerBufferingConfigured) return; |
| 4146 | videojs.__filemanagerBufferingConfigured = true; |
| 4147 | |
| 4148 | try |
| 4149 | { |
| 4150 | videojs.Vhs.GOAL_BUFFER_LENGTH = VIDEO_FORWARD_BUFFER_SECONDS; |
| 4151 | videojs.Vhs.MAX_GOAL_BUFFER_LENGTH = VIDEO_FORWARD_BUFFER_SECONDS; |
| 4152 | } catch |
| 4153 | { |
| 4154 | // Ignore builds that do not expose VHS buffer configuration. |
| 4155 | } |
| 4156 | } |
| 4157 | |
| 4158 | async function createVideoStreamSessionForItem (item) |
| 4159 | { |
| 4160 | return api('POST', '/files/video-stream', { filePath: item.path }); |
| 4161 | } |
| 4162 | |
| 4163 | async function releaseVideoStreamSession (sessionId, opts = {}) |
| 4164 | { |
| 4165 | const id = String(sessionId || '').trim(); |
| 4166 | if (!id) return; |
| 4167 | |
| 4168 | await api('DELETE', `/files/video-stream/${encodeURIComponent(id)}`, null, { |
| 4169 | keepalive: !!opts.keepalive, |
| 4170 | noAutoLogout: true, |
| 4171 | }).catch(() => null); |
| 4172 | } |
| 4173 | |
| 4174 | function releaseActivePreviewVideoStreamSession (opts = {}) |
| 4175 | { |
| 4176 | const sessionId = String(STATE.previewVideoStreamSessionId || '').trim(); |
| 4177 | if (!sessionId) return; |
| 4178 | STATE.previewVideoStreamSessionId = null; |
| 4179 | void releaseVideoStreamSession(sessionId, opts); |
| 4180 | } |
| 4181 | |
| 4182 | async function preparePreviewDownload (item) |
| 4183 | { |
| 4184 | const blob = await fetchFileBlob(item); |
| 4185 | if (!blob) |
| 4186 | { |
| 4187 | toast('Download failed.', 'err'); |
| 4188 | return; |
| 4189 | } |
| 4190 | |
| 4191 | const objectUrl = URL.createObjectURL(blob); |
| 4192 | triggerDownload(item.name, objectUrl); |
| 4193 | setTimeout(() => URL.revokeObjectURL(objectUrl), 60 * 1000); |
| 4194 | } |
| 4195 | |
| 4196 | async function renderStreamedVideoPreview (item, targetEl) |
| 4197 | { |
| 4198 | const videojs = await ensureVideoJsLoaded(); |
| 4199 | const session = await createVideoStreamSessionForItem(item); |
| 4200 | STATE.previewVideoStreamSessionId = String(session.sessionId || '').trim() || null; |
| 4201 | const prefs = loadUserVideoPrefs(); |
| 4202 | applyUserVideoTextTrackPrefs(); |
| 4203 | |
| 4204 | if ((session.subtitleSummary && session.subtitleSummary.skipped > 0)) |
| 4205 | { |
| 4206 | toast('Some subtitle tracks could not be converted for web playback.', 'err'); |
| 4207 | } |
| 4208 | |
| 4209 | STATE.previewDownloadAction = () => preparePreviewDownload(item); |
| 4210 | |
| 4211 | const video = document.createElement('video'); |
| 4212 | video.className = 'video-js vjs-big-play-centered preview-media preview-video-js'; |
| 4213 | video.controls = true; |
| 4214 | video.preload = 'auto'; |
| 4215 | video.playsInline = true; |
| 4216 | targetEl.classList.add('preview-expand-content--video'); |
| 4217 | targetEl.appendChild(video); |
| 4218 | |
| 4219 | const player = videojs(video, { |
| 4220 | controls: true, |
| 4221 | fluid: false, |
| 4222 | fill: true, |
| 4223 | responsive: false, |
| 4224 | preload: 'auto', |
| 4225 | controlBar: { |
| 4226 | currentTimeDisplay: true, |
| 4227 | timeDivider: true, |
| 4228 | durationDisplay: true, |
| 4229 | remainingTimeDisplay: false, |
| 4230 | }, |
| 4231 | sources: [{ src: session.playlistUrl, type: 'application/x-mpegURL' }], |
| 4232 | tracks: (session.subtitleTracks || []).map((track) => ({ |
| 4233 | kind: 'subtitles', |
| 4234 | src: track.src, |
| 4235 | srclang: track.language || 'und', |
| 4236 | label: track.label, |
| 4237 | default: !!track.default, |
| 4238 | })), |
| 4239 | }); |
| 4240 | |
| 4241 | const trackPrefs = bindUserVideoTrackPrefs(player, prefs); |
| 4242 | |
| 4243 | ensureVideoPlaybackUi(player, session.durationSeconds); |
| 4244 | const imageSubtitleController = bindImageSubtitleOverlay(player, videojs, prefs, session, item); |
| 4245 | |
| 4246 | // ------------------------------------------------------------------------- |
| 4247 | |
| 4248 | let sentPartway = false; |
| 4249 | let sentFully = false; |
| 4250 | const markWatch = async () => |
| 4251 | { |
| 4252 | let ratio = 0; |
| 4253 | try |
| 4254 | { |
| 4255 | const duration = Number(player.duration()); |
| 4256 | const current = Number(player.currentTime()); |
| 4257 | if (Number.isFinite(duration) && duration > 0 && Number.isFinite(current)) |
| 4258 | { |
| 4259 | ratio = current / duration; |
| 4260 | } |
| 4261 | } catch |
| 4262 | { |
| 4263 | return; |
| 4264 | } |
| 4265 | |
| 4266 | if (ratio >= 0.7) |
| 4267 | { |
| 4268 | if (sentFully) return; |
| 4269 | sentPartway = true; |
| 4270 | sentFully = true; |
| 4271 | void reportWatchProgress(item.path, ratio); |
| 4272 | return; |
| 4273 | } |
| 4274 | |
| 4275 | if (ratio >= 0.05) |
| 4276 | { |
| 4277 | if (sentPartway) return; |
| 4278 | sentPartway = true; |
| 4279 | void reportWatchProgress(item.path, ratio); |
| 4280 | } |
| 4281 | }; |
| 4282 | |
| 4283 | player.ready(() => |
| 4284 | { |
| 4285 | const volume = Number(prefs.volume); |
| 4286 | if (Number.isFinite(volume)) |
| 4287 | { |
| 4288 | player.volume(Math.max(0, Math.min(1, volume))); |
| 4289 | } |
| 4290 | |
| 4291 | const settings = player && player.textTrackSettings; |
| 4292 | if (settings && typeof settings.setValues === 'function' && typeof settings.updateDisplay === 'function') |
| 4293 | { |
| 4294 | settings.setValues({ |
| 4295 | backgroundColor: '#000', |
| 4296 | backgroundOpacity: '0', |
| 4297 | edgeStyle: 'uniform', |
| 4298 | }); |
| 4299 | settings.updateDisplay(); |
| 4300 | } |
| 4301 | |
| 4302 | trackPrefs.applySavedTracks(); |
| 4303 | }); |
| 4304 | |
| 4305 | player.on('loadedmetadata', trackPrefs.applySavedTracks); |
| 4306 | player.on('loadedplaylist', trackPrefs.applySavedTracks); |
| 4307 | player.on('timeupdate', markWatch); |
| 4308 | player.on('ended', () => |
| 4309 | { |
| 4310 | sentPartway = true; |
| 4311 | sentFully = true; |
| 4312 | void reportWatchProgress(item.path, 1); |
| 4313 | }); |
| 4314 | player.on('volumechange', () => |
| 4315 | { |
| 4316 | const v = Number(player.volume()); |
| 4317 | if (Number.isFinite(v)) saveUserVideoPrefs({ volume: v }); |
| 4318 | }); |
| 4319 | |
| 4320 | STATE.previewCleanup = () => |
| 4321 | { |
| 4322 | if (imageSubtitleController) |
| 4323 | { |
| 4324 | try { imageSubtitleController.captureSelectedTracks(); } catch { /* ignore */ } |
| 4325 | try { imageSubtitleController.detach(); } catch { /* ignore */ } |
| 4326 | } |
| 4327 | releaseActivePreviewVideoStreamSession(); |
| 4328 | try { markWatch(); } catch { /* ignore */ } |
| 4329 | try { trackPrefs.captureSelectedTracks(); } catch { /* ignore */ } |
| 4330 | try { trackPrefs.detach(); } catch { /* ignore */ } |
| 4331 | try { player.dispose(); } catch { /* ignore */ } |
| 4332 | }; |
| 4333 | } |
| 4334 | |
| 4335 | function fileAccentColor (name) |
| 4336 | { |
| 4337 | const ext = extOf(name || ''); |
| 4338 | if (IMAGE_EXTS.has(ext)) return '#3fcf8e'; |
| 4339 | if (VIDEO_EXTS.has(ext)) return '#e05c6e'; |
| 4340 | if (AUDIO_EXTS.has(ext)) return '#c084fc'; |
| 4341 | if (MODEL_EXTS.has(ext)) return '#2f6dff'; |
| 4342 | if (DOC_EXTS.has(ext)) return '#f97316'; |
| 4343 | if (CODE_EXTS.has(ext)) return '#38bdf8'; |
| 4344 | if (ARCHIVE_EXTS.has(ext)) return '#facc15'; |
| 4345 | return '#7880a0'; |
| 4346 | } |
| 4347 | |
| 4348 | function animateRect (el, fromRect, toRect, opts = {}) |
| 4349 | { |
| 4350 | const duration = opts.duration == null ? 260 : opts.duration; |
| 4351 | const easeOut = (t) => 1 - Math.pow(1 - t, 3); |
| 4352 | |
| 4353 | el.style.left = `${fromRect.left}px`; |
| 4354 | el.style.top = `${fromRect.top}px`; |
| 4355 | el.style.width = `${fromRect.width}px`; |
| 4356 | el.style.height = `${fromRect.height}px`; |
| 4357 | |
| 4358 | return new Promise((resolve) => |
| 4359 | { |
| 4360 | const t0 = performance.now(); |
| 4361 | |
| 4362 | function frame (now) |
| 4363 | { |
| 4364 | const raw = Math.min((now - t0) / duration, 1); |
| 4365 | const t = easeOut(raw); |
| 4366 | |
| 4367 | const left = fromRect.left + (toRect.left - fromRect.left) * t; |
| 4368 | const top = fromRect.top + (toRect.top - fromRect.top) * t; |
| 4369 | const width = fromRect.width + (toRect.width - fromRect.width) * t; |
| 4370 | const height = fromRect.height + (toRect.height - fromRect.height) * t; |
| 4371 | |
| 4372 | el.style.left = `${left}px`; |
| 4373 | el.style.top = `${top}px`; |
| 4374 | el.style.width = `${width}px`; |
| 4375 | el.style.height = `${height}px`; |
| 4376 | |
| 4377 | if (raw < 1) |
| 4378 | { |
| 4379 | requestAnimationFrame(frame); |
| 4380 | } else |
| 4381 | { |
| 4382 | resolve(); |
| 4383 | } |
| 4384 | } |
| 4385 | |
| 4386 | requestAnimationFrame(frame); |
| 4387 | }); |
| 4388 | } |
| 4389 | |
| 4390 | async function openExpandedTilePreview (item, tileEl, sourceSvgEl, loadPreviewContent) |
| 4391 | { |
| 4392 | if (!tileEl || !sourceSvgEl) return false; |
| 4393 | |
| 4394 | if (STATE.previewExpandState) |
| 4395 | { |
| 4396 | await closeExpandedTilePreview(); |
| 4397 | } |
| 4398 | |
| 4399 | const iconEl = tileEl.querySelector('.icon'); |
| 4400 | const nameEl = tileEl.querySelector('.name'); |
| 4401 | if (!iconEl) return false; |
| 4402 | |
| 4403 | const startRect = tileEl.getBoundingClientRect(); |
| 4404 | const targetW = Math.min(window.innerWidth * 0.94, 1100); |
| 4405 | const targetH = Math.min(window.innerHeight * 0.9, 860); |
| 4406 | const targetRect = { |
| 4407 | left: (window.innerWidth - targetW) / 2, |
| 4408 | top: (window.innerHeight - targetH) / 2, |
| 4409 | width: targetW, |
| 4410 | height: targetH, |
| 4411 | }; |
| 4412 | |
| 4413 | const backdrop = document.createElement('div'); |
| 4414 | backdrop.className = 'preview-backdrop'; |
| 4415 | document.body.appendChild(backdrop); |
| 4416 | |
| 4417 | const parent = tileEl.parentNode; |
| 4418 | const nextSibling = tileEl.nextSibling; |
| 4419 | const iconHtml = iconEl.innerHTML; |
| 4420 | const originalIconSvg = iconEl.querySelector('svg'); |
| 4421 | const placeholder = document.createElement('div'); |
| 4422 | placeholder.className = 'file-item file-item--preview-placeholder'; |
| 4423 | placeholder.style.width = `${startRect.width}px`; |
| 4424 | placeholder.style.height = `${startRect.height}px`; |
| 4425 | |
| 4426 | if (parent) |
| 4427 | { |
| 4428 | parent.insertBefore(placeholder, tileEl); |
| 4429 | } |
| 4430 | |
| 4431 | tileEl.remove(); |
| 4432 | document.body.appendChild(tileEl); |
| 4433 | tileEl.classList.add('file-item--preview'); |
| 4434 | tileEl.style.setProperty('--preview-accent', fileAccentColor(item.name)); |
| 4435 | tileEl.style.position = 'fixed'; |
| 4436 | tileEl.style.left = `${startRect.left}px`; |
| 4437 | tileEl.style.top = `${startRect.top}px`; |
| 4438 | tileEl.style.width = `${startRect.width}px`; |
| 4439 | tileEl.style.height = `${startRect.height}px`; |
| 4440 | tileEl.style.margin = '0'; |
| 4441 | tileEl.style.zIndex = '10000'; |
| 4442 | |
| 4443 | if (nameEl) nameEl.style.display = 'none'; |
| 4444 | |
| 4445 | const titleEl = document.createElement('div'); |
| 4446 | titleEl.className = 'preview-expand-title'; |
| 4447 | titleEl.textContent = item.name; |
| 4448 | |
| 4449 | const closeBtn = document.createElement('button'); |
| 4450 | closeBtn.className = 'preview-expand-close'; |
| 4451 | closeBtn.type = 'button'; |
| 4452 | closeBtn.textContent = '×'; |
| 4453 | closeBtn.setAttribute('aria-label', 'Close preview'); |
| 4454 | |
| 4455 | const dlBtn = document.createElement('button'); |
| 4456 | dlBtn.className = 'preview-expand-download'; |
| 4457 | dlBtn.type = 'button'; |
| 4458 | dlBtn.textContent = 'Download'; |
| 4459 | dlBtn.addEventListener('click', async (e) => |
| 4460 | { |
| 4461 | e.stopPropagation(); |
| 4462 | if (STATE.previewDownloadAction) |
| 4463 | { |
| 4464 | await STATE.previewDownloadAction(); |
| 4465 | return; |
| 4466 | } |
| 4467 | if (!STATE.previewObjectUrl) |
| 4468 | { |
| 4469 | toast('Preview still loading.', 'err'); |
| 4470 | return; |
| 4471 | } |
| 4472 | triggerDownload(item.name, STATE.previewObjectUrl); |
| 4473 | }); |
| 4474 | |
| 4475 | const shareBtn = document.createElement('button'); |
| 4476 | shareBtn.className = 'preview-expand-share'; |
| 4477 | shareBtn.type = 'button'; |
| 4478 | shareBtn.textContent = 'Share'; |
| 4479 | shareBtn.addEventListener('click', (e) => |
| 4480 | { |
| 4481 | e.stopPropagation(); |
| 4482 | openShareModal(item); |
| 4483 | }); |
| 4484 | |
| 4485 | const actionsEl = document.createElement('div'); |
| 4486 | actionsEl.className = 'preview-expand-actions'; |
| 4487 | actionsEl.appendChild(shareBtn); |
| 4488 | actionsEl.appendChild(dlBtn); |
| 4489 | |
| 4490 | iconEl.innerHTML = ''; |
| 4491 | |
| 4492 | if (originalIconSvg) |
| 4493 | { |
| 4494 | const outline = originalIconSvg.cloneNode(true); |
| 4495 | outline.classList.add('preview-expand-outline'); |
| 4496 | iconEl.appendChild(outline); |
| 4497 | } |
| 4498 | |
| 4499 | const previewMount = document.createElement('div'); |
| 4500 | previewMount.className = 'preview-expand-content'; |
| 4501 | iconEl.appendChild(previewMount); |
| 4502 | |
| 4503 | // Show spinner during expansion animation; content loads after it finishes |
| 4504 | const spinner = document.createElement('div'); |
| 4505 | spinner.className = 'preview-loading-spinner'; |
| 4506 | previewMount.appendChild(spinner); |
| 4507 | |
| 4508 | tileEl.insertBefore(titleEl, tileEl.firstChild); |
| 4509 | tileEl.appendChild(closeBtn); |
| 4510 | tileEl.appendChild(actionsEl); |
| 4511 | |
| 4512 | STATE.previewExpandState = { |
| 4513 | item, |
| 4514 | requireExplicitClose: VIDEO_EXTS.has(extOf(item.name)), |
| 4515 | tileEl, |
| 4516 | sourceSvgEl, |
| 4517 | parent, |
| 4518 | nextSibling, |
| 4519 | iconEl, |
| 4520 | iconHtml, |
| 4521 | nameEl, |
| 4522 | backdrop, |
| 4523 | placeholder, |
| 4524 | closeBtn, |
| 4525 | dlBtn, |
| 4526 | shareBtn, |
| 4527 | actionsEl, |
| 4528 | titleEl, |
| 4529 | previewMount, |
| 4530 | startRect, |
| 4531 | }; |
| 4532 | |
| 4533 | const onBackdrop = (e) => |
| 4534 | { |
| 4535 | if (e.target === backdrop) closePreview(); |
| 4536 | }; |
| 4537 | const onClose = () => closePreview({ force: true }); |
| 4538 | backdrop.addEventListener('click', onBackdrop); |
| 4539 | closeBtn.addEventListener('click', onClose); |
| 4540 | STATE.previewExpandState.onBackdrop = onBackdrop; |
| 4541 | STATE.previewExpandState.onClose = onClose; |
| 4542 | |
| 4543 | requestAnimationFrame(() => backdrop.classList.add('visible')); |
| 4544 | await animateRect(tileEl, startRect, targetRect); |
| 4545 | |
| 4546 | tileEl.style.left = `${targetRect.left}px`; |
| 4547 | tileEl.style.top = `${targetRect.top}px`; |
| 4548 | tileEl.style.width = `${targetRect.width}px`; |
| 4549 | tileEl.style.height = `${targetRect.height}px`; |
| 4550 | |
| 4551 | try |
| 4552 | { |
| 4553 | await loadPreviewContent(previewMount); |
| 4554 | } catch |
| 4555 | { |
| 4556 | if (previewMount.isConnected) |
| 4557 | { |
| 4558 | previewMount.innerHTML = ''; |
| 4559 | const msg = document.createElement('p'); |
| 4560 | msg.className = 'preview-unsupported'; |
| 4561 | msg.textContent = 'Preview failed to load. You can try again.'; |
| 4562 | previewMount.appendChild(msg); |
| 4563 | } |
| 4564 | } |
| 4565 | |
| 4566 | return true; |
| 4567 | } |
| 4568 | |
| 4569 | async function closeExpandedTilePreview () |
| 4570 | { |
| 4571 | const st = STATE.previewExpandState; |
| 4572 | if (!st) return; |
| 4573 | |
| 4574 | st.backdrop.classList.remove('visible'); |
| 4575 | if (st.backdrop && st.onBackdrop) st.backdrop.removeEventListener('click', st.onBackdrop); |
| 4576 | if (st.closeBtn && st.onClose) st.closeBtn.removeEventListener('click', st.onClose); |
| 4577 | |
| 4578 | const fromRect = st.tileEl.getBoundingClientRect(); |
| 4579 | await animateRect(st.tileEl, fromRect, st.startRect, { duration: 220 }); |
| 4580 | |
| 4581 | st.tileEl.classList.remove('file-item--preview'); |
| 4582 | st.tileEl.style.position = ''; |
| 4583 | st.tileEl.style.left = ''; |
| 4584 | st.tileEl.style.top = ''; |
| 4585 | st.tileEl.style.width = ''; |
| 4586 | st.tileEl.style.height = ''; |
| 4587 | st.tileEl.style.margin = ''; |
| 4588 | st.tileEl.style.zIndex = ''; |
| 4589 | |
| 4590 | if (st.titleEl) st.titleEl.remove(); |
| 4591 | if (st.closeBtn) st.closeBtn.remove(); |
| 4592 | if (st.actionsEl) st.actionsEl.remove(); |
| 4593 | if (st.iconEl) st.iconEl.innerHTML = st.iconHtml; |
| 4594 | if (st.nameEl) st.nameEl.style.display = ''; |
| 4595 | |
| 4596 | if (st.placeholder && st.placeholder.parentNode) |
| 4597 | { |
| 4598 | st.placeholder.parentNode.insertBefore(st.tileEl, st.placeholder); |
| 4599 | st.placeholder.remove(); |
| 4600 | } else if (st.parent) |
| 4601 | { |
| 4602 | if (st.nextSibling && st.nextSibling.parentNode === st.parent) |
| 4603 | { |
| 4604 | st.parent.insertBefore(st.tileEl, st.nextSibling); |
| 4605 | } else |
| 4606 | { |
| 4607 | st.parent.appendChild(st.tileEl); |
| 4608 | } |
| 4609 | } |
| 4610 | |
| 4611 | if (st.backdrop) st.backdrop.remove(); |
| 4612 | STATE.previewExpandState = null; |
| 4613 | } |
| 4614 | |
| 4615 | async function closePreview (opts = {}) |
| 4616 | { |
| 4617 | if (STATE.previewClosing) return; |
| 4618 | if (STATE.previewExpandState) |
| 4619 | { |
| 4620 | if (STATE.previewExpandState.requireExplicitClose && !opts.force) |
| 4621 | { |
| 4622 | return; |
| 4623 | } |
| 4624 | |
| 4625 | STATE.previewClosing = true; |
| 4626 | clearPreviewObjectUrl(); |
| 4627 | try |
| 4628 | { |
| 4629 | await closeExpandedTilePreview(); |
| 4630 | STATE.previewSourceEl = null; |
| 4631 | } finally |
| 4632 | { |
| 4633 | STATE.previewClosing = false; |
| 4634 | } |
| 4635 | } |
| 4636 | } |
| 4637 | |
| 4638 | async function fetchFileBlob (item) |
| 4639 | { |
| 4640 | const url = `/api/files/download?file=${encodeURIComponent(item.path)}`; |
| 4641 | try |
| 4642 | { |
| 4643 | const res = await fetch(url, { |
| 4644 | headers: { |
| 4645 | Authorization: 'Bearer ' + STATE.token, |
| 4646 | 'X-Fp': getFingerprint(), |
| 4647 | }, |
| 4648 | }); |
| 4649 | if (!res.ok) throw new Error('Download failed.'); |
| 4650 | return await res.blob(); |
| 4651 | } catch |
| 4652 | { |
| 4653 | return null; |
| 4654 | } |
| 4655 | } |
| 4656 | |
| 4657 | function triggerDownload (filename, objectUrl) |
| 4658 | { |
| 4659 | const a = document.createElement('a'); |
| 4660 | a.href = objectUrl; |
| 4661 | a.download = filename; |
| 4662 | a.click(); |
| 4663 | } |
| 4664 | |
| 4665 | function modelPreviewType (name) |
| 4666 | { |
| 4667 | const ext = extOf(name || ''); |
| 4668 | if (MODEL_EXTS.has(ext)) return ext; |
| 4669 | return null; |
| 4670 | } |
| 4671 | |
| 4672 | async function loadThreePreviewModules () |
| 4673 | { |
| 4674 | if (!threePreviewModulesPromise) |
| 4675 | { |
| 4676 | threePreviewModulesPromise = Promise.all([ |
| 4677 | import('/vendor/three/three.module.js'), |
| 4678 | import('/vendor/three/addons/controls/OrbitControls.js'), |
| 4679 | import('/vendor/three/addons/loaders/STLLoader.js'), |
| 4680 | import('/vendor/three/addons/loaders/OBJLoader.js'), |
| 4681 | ]).then(([THREE, controlsMod, stlMod, objMod]) => |
| 4682 | { |
| 4683 | return { |
| 4684 | THREE, |
| 4685 | OrbitControls: controlsMod.OrbitControls, |
| 4686 | STLLoader: stlMod.STLLoader, |
| 4687 | OBJLoader: objMod.OBJLoader, |
| 4688 | }; |
| 4689 | }); |
| 4690 | } |
| 4691 | |
| 4692 | return threePreviewModulesPromise; |
| 4693 | } |
| 4694 | |
| 4695 | function disposeObject3D (root) |
| 4696 | { |
| 4697 | if (!root || typeof root.traverse !== 'function') return; |
| 4698 | root.traverse((node) => |
| 4699 | { |
| 4700 | if (node.geometry && typeof node.geometry.dispose === 'function') |
| 4701 | { |
| 4702 | node.geometry.dispose(); |
| 4703 | } |
| 4704 | |
| 4705 | if (!node.material) return; |
| 4706 | if (Array.isArray(node.material)) |
| 4707 | { |
| 4708 | node.material.forEach((material) => |
| 4709 | { |
| 4710 | if (material && typeof material.dispose === 'function') material.dispose(); |
| 4711 | }); |
| 4712 | return; |
| 4713 | } |
| 4714 | |
| 4715 | if (typeof node.material.dispose === 'function') node.material.dispose(); |
| 4716 | }); |
| 4717 | } |
| 4718 | |
| 4719 | async function buildModelObjectFromBlob (blob, type, modules) |
| 4720 | { |
| 4721 | const { THREE, STLLoader, OBJLoader } = modules; |
| 4722 | const sharedMaterial = new THREE.MeshStandardMaterial({ |
| 4723 | color: 0x2f6dff, |
| 4724 | metalness: 0.08, |
| 4725 | roughness: 0.72, |
| 4726 | }); |
| 4727 | |
| 4728 | if (type === 'stl') |
| 4729 | { |
| 4730 | const arr = await blob.arrayBuffer(); |
| 4731 | const geometry = new STLLoader().parse(arr); |
| 4732 | geometry.computeVertexNormals(); |
| 4733 | return new THREE.Mesh(geometry, sharedMaterial); |
| 4734 | } |
| 4735 | |
| 4736 | if (type === 'obj') |
| 4737 | { |
| 4738 | const text = await blob.text(); |
| 4739 | const obj = new OBJLoader().parse(text); |
| 4740 | obj.traverse((node) => |
| 4741 | { |
| 4742 | if (!node || !node.isMesh) return; |
| 4743 | node.material = sharedMaterial.clone(); |
| 4744 | }); |
| 4745 | sharedMaterial.dispose(); |
| 4746 | return obj; |
| 4747 | } |
| 4748 | |
| 4749 | throw new Error('Unsupported 3D model format.'); |
| 4750 | } |
| 4751 | |
| 4752 | function setModelPreviewMessage (wrap, text) |
| 4753 | { |
| 4754 | wrap.innerHTML = ''; |
| 4755 | const msg = document.createElement('p'); |
| 4756 | msg.className = 'preview-unsupported'; |
| 4757 | msg.textContent = text; |
| 4758 | wrap.appendChild(msg); |
| 4759 | } |
| 4760 | |
| 4761 | async function renderModelPreview (item, blob, targetEl) |
| 4762 | { |
| 4763 | const type = modelPreviewType(item && item.name); |
| 4764 | if (!type) |
| 4765 | { |
| 4766 | const msg = document.createElement('p'); |
| 4767 | msg.className = 'preview-unsupported'; |
| 4768 | msg.textContent = 'This 3D file type is not supported yet.'; |
| 4769 | targetEl.appendChild(msg); |
| 4770 | return; |
| 4771 | } |
| 4772 | |
| 4773 | const wrap = document.createElement('div'); |
| 4774 | wrap.className = 'preview-model-wrap'; |
| 4775 | targetEl.appendChild(wrap); |
| 4776 | |
| 4777 | const canvas = document.createElement('canvas'); |
| 4778 | canvas.className = 'preview-model-canvas'; |
| 4779 | canvas.style.touchAction = 'none'; |
| 4780 | wrap.appendChild(canvas); |
| 4781 | |
| 4782 | const hint = document.createElement('p'); |
| 4783 | hint.className = 'preview-model-hint'; |
| 4784 | hint.textContent = 'Drag to rotate. Use the scroll wheel to zoom.'; |
| 4785 | wrap.appendChild(hint); |
| 4786 | |
| 4787 | const gl = |
| 4788 | canvas.getContext('webgl2', { antialias: true, alpha: true }) || |
| 4789 | canvas.getContext('webgl', { antialias: true, alpha: true }); |
| 4790 | if (!gl) |
| 4791 | { |
| 4792 | setModelPreviewMessage(wrap, '3D preview is not available in this browser. You can still download this file.'); |
| 4793 | return; |
| 4794 | } |
| 4795 | |
| 4796 | let modules; |
| 4797 | try |
| 4798 | { |
| 4799 | modules = await loadThreePreviewModules(); |
| 4800 | } catch |
| 4801 | { |
| 4802 | setModelPreviewMessage(wrap, '3D preview dependencies failed to load. You can still download this file.'); |
| 4803 | return; |
| 4804 | } |
| 4805 | |
| 4806 | if (!wrap.isConnected) return; |
| 4807 | |
| 4808 | const { THREE, OrbitControls } = modules; |
| 4809 | const scene = new THREE.Scene(); |
| 4810 | scene.background = new THREE.Color(0x0d111a); |
| 4811 | |
| 4812 | const camera = new THREE.PerspectiveCamera(50, 1, 0.01, 5000); |
| 4813 | const renderer = new THREE.WebGLRenderer({ canvas, context: gl, antialias: true, alpha: true }); |
| 4814 | renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2)); |
| 4815 | |
| 4816 | const ambient = new THREE.AmbientLight(0xffffff, 0.9); |
| 4817 | const key = new THREE.DirectionalLight(0xffffff, 0.95); |
| 4818 | key.position.set(1.2, 1.6, 1.1); |
| 4819 | scene.add(ambient); |
| 4820 | scene.add(key); |
| 4821 | |
| 4822 | let modelRoot; |
| 4823 | try |
| 4824 | { |
| 4825 | modelRoot = await buildModelObjectFromBlob(blob, type, modules); |
| 4826 | } catch |
| 4827 | { |
| 4828 | renderer.dispose(); |
| 4829 | setModelPreviewMessage(wrap, 'This 3D file could not be parsed. You can still download it.'); |
| 4830 | return; |
| 4831 | } |
| 4832 | |
| 4833 | if (!wrap.isConnected) |
| 4834 | { |
| 4835 | disposeObject3D(modelRoot); |
| 4836 | renderer.dispose(); |
| 4837 | return; |
| 4838 | } |
| 4839 | |
| 4840 | scene.add(modelRoot); |
| 4841 | |
| 4842 | const box = new THREE.Box3().setFromObject(modelRoot); |
| 4843 | if (box.isEmpty()) |
| 4844 | { |
| 4845 | disposeObject3D(modelRoot); |
| 4846 | renderer.dispose(); |
| 4847 | setModelPreviewMessage(wrap, 'This 3D file has no visible geometry to preview.'); |
| 4848 | return; |
| 4849 | } |
| 4850 | |
| 4851 | const size = new THREE.Vector3(); |
| 4852 | const center = new THREE.Vector3(); |
| 4853 | box.getSize(size); |
| 4854 | box.getCenter(center); |
| 4855 | modelRoot.position.sub(center); |
| 4856 | |
| 4857 | const maxDim = Math.max(size.x, size.y, size.z) || 1; |
| 4858 | const camDistance = maxDim * 1.8; |
| 4859 | camera.position.set(camDistance, camDistance * 0.75, camDistance); |
| 4860 | camera.near = Math.max(0.001, maxDim / 2000); |
| 4861 | camera.far = Math.max(1000, maxDim * 2000); |
| 4862 | camera.updateProjectionMatrix(); |
| 4863 | |
| 4864 | const controls = new OrbitControls(camera, renderer.domElement); |
| 4865 | controls.enableDamping = true; |
| 4866 | controls.dampingFactor = 0.08; |
| 4867 | controls.target.set(0, 0, 0); |
| 4868 | controls.minDistance = maxDim * 0.2; |
| 4869 | controls.maxDistance = maxDim * 25; |
| 4870 | controls.update(); |
| 4871 | |
| 4872 | const resize = () => |
| 4873 | { |
| 4874 | const w = Math.max(160, Math.floor(wrap.clientWidth || 0)); |
| 4875 | const h = Math.max(160, Math.floor((wrap.clientHeight || 0) - (hint.offsetHeight || 0) - 6)); |
| 4876 | renderer.setSize(w, h, false); |
| 4877 | camera.aspect = w / h; |
| 4878 | camera.updateProjectionMatrix(); |
| 4879 | }; |
| 4880 | resize(); |
| 4881 | |
| 4882 | let stop = false; |
| 4883 | let rafId = 0; |
| 4884 | const frame = () => |
| 4885 | { |
| 4886 | if (stop) return; |
| 4887 | controls.update(); |
| 4888 | renderer.render(scene, camera); |
| 4889 | rafId = requestAnimationFrame(frame); |
| 4890 | }; |
| 4891 | frame(); |
| 4892 | |
| 4893 | const resizeObserver = typeof ResizeObserver === 'function' |
| 4894 | ? new ResizeObserver(() => resize()) |
| 4895 | : null; |
| 4896 | if (resizeObserver) resizeObserver.observe(wrap); |
| 4897 | |
| 4898 | STATE.previewCleanup = () => |
| 4899 | { |
| 4900 | stop = true; |
| 4901 | if (rafId) cancelAnimationFrame(rafId); |
| 4902 | if (resizeObserver) resizeObserver.disconnect(); |
| 4903 | try { controls.dispose(); } catch { /* ignore */ } |
| 4904 | try { disposeObject3D(modelRoot); } catch { /* ignore */ } |
| 4905 | try { renderer.dispose(); } catch { /* ignore */ } |
| 4906 | }; |
| 4907 | } |
| 4908 | |
| 4909 | async function renderPreviewBody (item, blob, objectUrl, targetEl = null) |
| 4910 | { |
| 4911 | const body = targetEl || document.getElementById('preview-body'); |
| 4912 | body.innerHTML = ''; |
| 4913 | |
| 4914 | const mime = String(blob.type || '').toLowerCase(); |
| 4915 | const previewable = isInlinePreviewableBlob(blob, item.name); |
| 4916 | |
| 4917 | if (!previewable) |
| 4918 | { |
| 4919 | const msg = document.createElement('p'); |
| 4920 | msg.className = 'preview-unsupported'; |
| 4921 | msg.textContent = 'This file cannot be previewed, but you can download it with the button below.'; |
| 4922 | body.appendChild(msg); |
| 4923 | return; |
| 4924 | } |
| 4925 | |
| 4926 | if (/^image\//.test(mime) || IMAGE_EXTS.has(extOf(item.name))) |
| 4927 | { |
| 4928 | const img = document.createElement('img'); |
| 4929 | img.className = 'preview-media'; |
| 4930 | img.src = objectUrl; |
| 4931 | img.alt = item.name; |
| 4932 | body.appendChild(img); |
| 4933 | return; |
| 4934 | } |
| 4935 | |
| 4936 | if (/^video\//.test(mime) || VIDEO_EXTS.has(extOf(item.name))) |
| 4937 | { |
| 4938 | const video = document.createElement('video'); |
| 4939 | video.className = 'preview-media'; |
| 4940 | video.src = objectUrl; |
| 4941 | video.controls = true; |
| 4942 | video.preload = 'metadata'; |
| 4943 | body.appendChild(video); |
| 4944 | return; |
| 4945 | } |
| 4946 | |
| 4947 | if (/^audio\//.test(mime) || AUDIO_EXTS.has(extOf(item.name))) |
| 4948 | { |
| 4949 | const audio = document.createElement('audio'); |
| 4950 | audio.className = 'preview-audio'; |
| 4951 | audio.src = objectUrl; |
| 4952 | audio.controls = true; |
| 4953 | body.appendChild(audio); |
| 4954 | return; |
| 4955 | } |
| 4956 | |
| 4957 | if (modelPreviewType(item.name)) |
| 4958 | { |
| 4959 | await renderModelPreview(item, blob, body); |
| 4960 | return; |
| 4961 | } |
| 4962 | |
| 4963 | if (mime === 'application/pdf') |
| 4964 | { |
| 4965 | const frame = document.createElement('iframe'); |
| 4966 | frame.className = 'preview-frame'; |
| 4967 | frame.src = objectUrl; |
| 4968 | frame.title = item.name; |
| 4969 | body.appendChild(frame); |
| 4970 | return; |
| 4971 | } |
| 4972 | |
| 4973 | if (isTextLikeBlob(blob, item.name)) |
| 4974 | { |
| 4975 | const text = await blob.text(); |
| 4976 | const lang = detectCodeLanguage(item.name, mime); |
| 4977 | const formatted = prettyPrintCode(text, lang); |
| 4978 | const pre = document.createElement('pre'); |
| 4979 | pre.className = 'preview-text preview-code'; |
| 4980 | pre.innerHTML = highlightCode(formatted, lang); |
| 4981 | body.appendChild(pre); |
| 4982 | return; |
| 4983 | } |
| 4984 | |
| 4985 | const msg = document.createElement('p'); |
| 4986 | msg.className = 'preview-unsupported'; |
| 4987 | msg.textContent = 'This file cannot be previewed, but you can download it with the button below.'; |
| 4988 | body.appendChild(msg); |
| 4989 | } |
| 4990 | |
| 4991 | async function downloadOrView (item, sourceSvgEl = null) |
| 4992 | { |
| 4993 | if (STATE.previewExpandState) |
| 4994 | { |
| 4995 | await closePreview({ force: true }); |
| 4996 | } |
| 4997 | |
| 4998 | const sourceTileEl = sourceSvgEl ? sourceSvgEl.closest('.file-item') : null; |
| 4999 | if (sourceTileEl) |
| 5000 | { |
| 5001 | STATE.previewSourceEl = sourceSvgEl; |
| 5002 | const expanded = await openExpandedTilePreview(item, sourceTileEl, sourceSvgEl, async (previewMount) => |
| 5003 | { |
| 5004 | if (VIDEO_EXTS.has(extOf(item.name))) |
| 5005 | { |
| 5006 | clearPreviewObjectUrl(); |
| 5007 | previewMount.innerHTML = ''; |
| 5008 | await renderStreamedVideoPreview(item, previewMount); |
| 5009 | return; |
| 5010 | } |
| 5011 | |
| 5012 | const blob = await fetchFileBlob(item); |
| 5013 | if (!blob) throw new Error('Download failed'); |
| 5014 | |
| 5015 | clearPreviewObjectUrl(); |
| 5016 | const objectUrl = URL.createObjectURL(blob); |
| 5017 | STATE.previewObjectUrl = objectUrl; |
| 5018 | |
| 5019 | if (!previewMount.isConnected) return; |
| 5020 | |
| 5021 | previewMount.innerHTML = ''; |
| 5022 | await renderPreviewBody(item, blob, objectUrl, previewMount); |
| 5023 | }); |
| 5024 | if (expanded) return; |
| 5025 | } |
| 5026 | |
| 5027 | toast('Preview unavailable — no source tile found.', 'err'); |
| 5028 | } |
| 5029 | |
| 5030 | // ─────────────────────────────────────────────────────────────────────────── |
| 5031 | // UPLOAD |
| 5032 | // ─────────────────────────────────────────────────────────────────────────── |
| 5033 | |
| 5034 | function canWrite (item = null) |
| 5035 | { |
| 5036 | if (STATE.isAdmin) return true; |
| 5037 | const root = item && item._root |
| 5038 | ? item._root |
| 5039 | : (STATE.currentRoot || (item ? resolveRootForPath(item.path) : null)); |
| 5040 | if (!root) return false; |
| 5041 | if (root.isUserFolder) return true; |
| 5042 | const p = STATE.permissions[rootPermissionLabel(root)]; |
| 5043 | return p && p.write; |
| 5044 | } |
| 5045 | |
| 5046 | async function uploadFiles (fileList) |
| 5047 | { |
| 5048 | if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; } |
| 5049 | if (!canWrite()) { toast('No write access.', 'err'); return; } |
| 5050 | |
| 5051 | const files = Array.from(fileList || []); |
| 5052 | if (!files.length) return; |
| 5053 | |
| 5054 | // Show upload bar |
| 5055 | const wrap = document.createElement('div'); |
| 5056 | wrap.className = 'upload-bar-wrap'; |
| 5057 | wrap.innerHTML = `<span>Preparing upload…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`; |
| 5058 | document.body.appendChild(wrap); |
| 5059 | STATE.uploadInProgress = true; |
| 5060 | |
| 5061 | try |
| 5062 | { |
| 5063 | const existingNames = await listDirNameSet(STATE.currentDir); |
| 5064 | let done = 0; |
| 5065 | let uploaded = 0; |
| 5066 | |
| 5067 | for (const original of files) |
| 5068 | { |
| 5069 | let fileToUpload = original; |
| 5070 | |
| 5071 | if (existingNames.has(original.name)) |
| 5072 | { |
| 5073 | const suggested = nextAvailableName(original.name, existingNames); |
| 5074 | const decision = await showFileConflictChoice(original.name, suggested, 'upload'); |
| 5075 | if (decision === 'cancel') |
| 5076 | { |
| 5077 | done++; |
| 5078 | wrap.querySelector('span').textContent = `Uploading ${done} / ${files.length} file(s)…`; |
| 5079 | wrap.querySelector('.upload-bar-fill').style.width = (done / files.length * 100) + '%'; |
| 5080 | continue; |
| 5081 | } |
| 5082 | |
| 5083 | if (decision === 'rename') |
| 5084 | { |
| 5085 | fileToUpload = cloneFileWithName(original, suggested); |
| 5086 | } |
| 5087 | } |
| 5088 | |
| 5089 | await uploadSingleFile(fileToUpload, STATE.currentDir); |
| 5090 | existingNames.add(fileToUpload.name); |
| 5091 | done++; |
| 5092 | uploaded++; |
| 5093 | wrap.querySelector('span').textContent = `Uploading ${done} / ${files.length} file(s)…`; |
| 5094 | wrap.querySelector('.upload-bar-fill').style.width = (done / files.length * 100) + '%'; |
| 5095 | } |
| 5096 | |
| 5097 | toast(`Uploaded ${uploaded} file(s).`, 'ok'); |
| 5098 | await navigateTo(STATE.currentDir, STATE.currentRoot); |
| 5099 | } catch (err) |
| 5100 | { |
| 5101 | toast(err.message, 'err'); |
| 5102 | } finally |
| 5103 | { |
| 5104 | STATE.uploadInProgress = false; |
| 5105 | wrap.remove(); |
| 5106 | } |
| 5107 | } |
| 5108 | |
| 5109 | async function uploadSingleFile (file, targetDir) |
| 5110 | { |
| 5111 | const formData = new FormData(); |
| 5112 | formData.append('files', file); |
| 5113 | |
| 5114 | await new Promise((resolve, reject) => |
| 5115 | { |
| 5116 | const xhr = new XMLHttpRequest(); |
| 5117 | xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(targetDir)}`); |
| 5118 | xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token); |
| 5119 | xhr.setRequestHeader('X-Fp', getFingerprint()); |
| 5120 | xhr.setRequestHeader('X-Upload-Size', String(file.size || 0)); |
| 5121 | xhr.onload = () => xhr.status === 200 |
| 5122 | ? resolve() |
| 5123 | : reject(new Error((JSON.parse(xhr.responseText) || {}).error || 'Upload failed')); |
| 5124 | xhr.onerror = () => reject(new Error('Network error')); |
| 5125 | xhr.send(formData); |
| 5126 | }); |
| 5127 | } |
| 5128 | |
| 5129 | async function ensureServerDir (baseDir, relativeDir) |
| 5130 | { |
| 5131 | const parts = String(relativeDir || '').split(/[\\/]/).filter(Boolean); |
| 5132 | let current = baseDir; |
| 5133 | for (const part of parts) |
| 5134 | { |
| 5135 | try |
| 5136 | { |
| 5137 | const resp = await api('POST', '/files/mkdir', { dir: current, name: part }); |
| 5138 | current = resp && resp.path ? resp.path : joinServerPath(current, part); |
| 5139 | } catch (err) |
| 5140 | { |
| 5141 | if (!/exist|EEXIST/i.test(err.message || '')) throw err; |
| 5142 | current = joinServerPath(current, part); |
| 5143 | } |
| 5144 | } |
| 5145 | return current; |
| 5146 | } |
| 5147 | |
| 5148 | async function uploadFolderInputFiles (fileList) |
| 5149 | { |
| 5150 | if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; } |
| 5151 | if (!canWrite()) { toast('No write access.', 'err'); return; } |
| 5152 | if (!fileList || !fileList.length) return; |
| 5153 | |
| 5154 | const files = Array.from(fileList); |
| 5155 | const total = files.length; |
| 5156 | let done = 0; |
| 5157 | |
| 5158 | const wrap = document.createElement('div'); |
| 5159 | wrap.className = 'upload-bar-wrap'; |
| 5160 | wrap.innerHTML = `<span>Preparing folder upload…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`; |
| 5161 | document.body.appendChild(wrap); |
| 5162 | STATE.uploadInProgress = true; |
| 5163 | |
| 5164 | try |
| 5165 | { |
| 5166 | const dirCache = new Map(); |
| 5167 | dirCache.set('', STATE.currentDir); |
| 5168 | |
| 5169 | for (const file of files) |
| 5170 | { |
| 5171 | const rel = file.webkitRelativePath || file.name; |
| 5172 | const relParts = rel.split(/[\\/]/).filter(Boolean); |
| 5173 | const relDir = relParts.slice(0, -1).join('/'); |
| 5174 | |
| 5175 | if (!dirCache.has(relDir)) |
| 5176 | { |
| 5177 | const parentRel = relParts.slice(0, -2).join('/'); |
| 5178 | const parentAbs = dirCache.get(parentRel) || await ensureServerDir(STATE.currentDir, parentRel); |
| 5179 | const thisName = relParts[relParts.length - 2]; |
| 5180 | |
| 5181 | try |
| 5182 | { |
| 5183 | const created = await api('POST', '/files/mkdir', { dir: parentAbs, name: thisName }); |
| 5184 | dirCache.set(relDir, created.path || joinServerPath(parentAbs, thisName)); |
| 5185 | } catch (err) |
| 5186 | { |
| 5187 | if (!/exist|EEXIST/i.test(err.message || '')) throw err; |
| 5188 | dirCache.set(relDir, joinServerPath(parentAbs, thisName)); |
| 5189 | } |
| 5190 | } |
| 5191 | |
| 5192 | const targetDir = dirCache.get(relDir) || STATE.currentDir; |
| 5193 | await uploadSingleFile(file, targetDir); |
| 5194 | done++; |
| 5195 | wrap.querySelector('span').textContent = `Uploading ${done} / ${total} file(s)…`; |
| 5196 | wrap.querySelector('.upload-bar-fill').style.width = (done / total * 100) + '%'; |
| 5197 | } |
| 5198 | |
| 5199 | toast(`Uploaded ${total} file(s).`, 'ok'); |
| 5200 | await navigateTo(STATE.currentDir, STATE.currentRoot); |
| 5201 | } catch (err) |
| 5202 | { |
| 5203 | toast(err.message, 'err'); |
| 5204 | } finally |
| 5205 | { |
| 5206 | STATE.uploadInProgress = false; |
| 5207 | wrap.remove(); |
| 5208 | } |
| 5209 | } |
| 5210 | |
| 5211 | // ─────────────────────────────────────────────────────────────────────────── |
| 5212 | // FOLDER DRAG-AND-DROP (recursive) |
| 5213 | // ─────────────────────────────────────────────────────────────────────────── |
| 5214 | |
| 5215 | /** |
| 5216 | * Reads all readEntries batches from a DirectoryReader (browsers may return |
| 5217 | * results in chunks; we must keep calling until we get an empty array). |
| 5218 | */ |
| 5219 | function readAllEntries (reader) |
| 5220 | { |
| 5221 | return new Promise((resolve, reject) => |
| 5222 | { |
| 5223 | const all = []; |
| 5224 | function next () |
| 5225 | { |
| 5226 | reader.readEntries(batch => |
| 5227 | { |
| 5228 | if (!batch.length) { resolve(all); return; } |
| 5229 | all.push(...batch); |
| 5230 | next(); |
| 5231 | }, reject); |
| 5232 | } |
| 5233 | next(); |
| 5234 | }); |
| 5235 | } |
| 5236 | |
| 5237 | /** |
| 5238 | * Recursively walk a FileSystemEntry tree, creating server-side directories |
| 5239 | * on the fly and collecting { file, targetDir } pairs for upload. |
| 5240 | */ |
| 5241 | async function collectEntries (entry, serverDir, toUpload) |
| 5242 | { |
| 5243 | if (entry.isFile) |
| 5244 | { |
| 5245 | const file = await new Promise((res, rej) => entry.file(res, rej)); |
| 5246 | toUpload.push({ file, targetDir: serverDir }); |
| 5247 | } else if (entry.isDirectory) |
| 5248 | { |
| 5249 | // Ask the server to create the directory; it returns the canonical path. |
| 5250 | let newServerDir; |
| 5251 | try |
| 5252 | { |
| 5253 | const resp = await api('POST', '/files/mkdir', { dir: serverDir, name: entry.name }); |
| 5254 | newServerDir = resp.path; |
| 5255 | } catch |
| 5256 | { |
| 5257 | // Directory may already exist — reconstruct path from what we know. |
| 5258 | // The server always returns JSON with {error} on failure, so we can |
| 5259 | // still continue by falling back to a best-effort path join. |
| 5260 | // We rely on the fact that the server separator is consistent within |
| 5261 | // a session (the list/browse API already returned paths in that format). |
| 5262 | const sep = serverDir.includes('\\') ? '\\' : '/'; |
| 5263 | newServerDir = serverDir + sep + entry.name; |
| 5264 | } |
| 5265 | const reader = entry.createReader(); |
| 5266 | const subEntries = await readAllEntries(reader); |
| 5267 | for (const sub of subEntries) |
| 5268 | { |
| 5269 | await collectEntries(sub, newServerDir, toUpload); |
| 5270 | } |
| 5271 | } |
| 5272 | } |
| 5273 | |
| 5274 | async function uploadEntries (entries) |
| 5275 | { |
| 5276 | if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; } |
| 5277 | if (!canWrite()) { toast('No write access.', 'err'); return; } |
| 5278 | |
| 5279 | const wrap = document.createElement('div'); |
| 5280 | wrap.className = 'upload-bar-wrap'; |
| 5281 | wrap.innerHTML = `<span>Scanning…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`; |
| 5282 | document.body.appendChild(wrap); |
| 5283 | STATE.uploadInProgress = true; |
| 5284 | |
| 5285 | try |
| 5286 | { |
| 5287 | const toUpload = []; |
| 5288 | for (const entry of entries) |
| 5289 | { |
| 5290 | await collectEntries(entry, STATE.currentDir, toUpload); |
| 5291 | } |
| 5292 | |
| 5293 | if (!toUpload.length) { toast('No files found.', 'err'); return; } |
| 5294 | |
| 5295 | let done = 0; |
| 5296 | const total = toUpload.length; |
| 5297 | const updateBar = () => |
| 5298 | { |
| 5299 | wrap.querySelector('span').textContent = `Uploading ${done} / ${total} file(s)…`; |
| 5300 | wrap.querySelector('.upload-bar-fill').style.width = (done / total * 100) + '%'; |
| 5301 | }; |
| 5302 | updateBar(); |
| 5303 | |
| 5304 | for (const { file, targetDir } of toUpload) |
| 5305 | { |
| 5306 | await uploadSingleFile(file, targetDir); |
| 5307 | done++; |
| 5308 | updateBar(); |
| 5309 | } |
| 5310 | |
| 5311 | toast(`Uploaded ${total} file(s).`, 'ok'); |
| 5312 | await navigateTo(STATE.currentDir, STATE.currentRoot); |
| 5313 | } catch (err) |
| 5314 | { |
| 5315 | toast(err.message, 'err'); |
| 5316 | } finally |
| 5317 | { |
| 5318 | STATE.uploadInProgress = false; |
| 5319 | wrap.remove(); |
| 5320 | } |
| 5321 | } |
| 5322 | |
| 5323 | // DRAG-AND-DROP |
| 5324 | // ─────────────────────────────────────────────────────────────────────────── |
| 5325 | |
| 5326 | function initDragDrop () |
| 5327 | { |
| 5328 | const main = document.getElementById('main-content'); |
| 5329 | const dropOvl = document.getElementById('drop-overlay'); |
| 5330 | let dragDepth = 0; |
| 5331 | |
| 5332 | main.addEventListener('dragenter', e => |
| 5333 | { |
| 5334 | e.preventDefault(); |
| 5335 | dragDepth++; |
| 5336 | dropOvl.classList.remove('hidden'); |
| 5337 | }); |
| 5338 | main.addEventListener('dragleave', () => |
| 5339 | { |
| 5340 | dragDepth--; |
| 5341 | if (dragDepth <= 0) { dragDepth = 0; dropOvl.classList.add('hidden'); } |
| 5342 | }); |
| 5343 | main.addEventListener('dragover', e => e.preventDefault()); |
| 5344 | main.addEventListener('drop', async e => |
| 5345 | { |
| 5346 | e.preventDefault(); |
| 5347 | dragDepth = 0; |
| 5348 | dropOvl.classList.add('hidden'); |
| 5349 | if (!canWrite()) { toast('No write access.', 'err'); return; } |
| 5350 | |
| 5351 | const items = Array.from(e.dataTransfer.items || []); |
| 5352 | // Use the FileSystem Entry API when available so we can handle folders. |
| 5353 | if (items.length && typeof items[0].webkitGetAsEntry === 'function') |
| 5354 | { |
| 5355 | const entries = items.map(i => i.webkitGetAsEntry()).filter(Boolean); |
| 5356 | if (entries.some(en => en.isDirectory)) |
| 5357 | { |
| 5358 | await uploadEntries(entries); |
| 5359 | return; |
| 5360 | } |
| 5361 | } |
| 5362 | // Plain files only — use the fast batch path. |
| 5363 | const files = e.dataTransfer.files; |
| 5364 | if (files.length) await uploadFiles(files); |
| 5365 | }); |
| 5366 | } |
| 5367 | |
| 5368 | // ─────────────────────────────────────────────────────────────────────────── |
| 5369 | // RENAME |
| 5370 | // ─────────────────────────────────────────────────────────────────────────── |
| 5371 | |
| 5372 | function openRenameModal (item) |
| 5373 | { |
| 5374 | const modal = document.getElementById('rename-modal'); |
| 5375 | modal.classList.remove('hidden'); |
| 5376 | const input = document.getElementById('rename-input'); |
| 5377 | input.value = item.name; |
| 5378 | input.focus(); |
| 5379 | input.select(); |
| 5380 | document.getElementById('rename-error').classList.add('hidden'); |
| 5381 | document.getElementById('rename-form').onsubmit = async (e) => |
| 5382 | { |
| 5383 | e.preventDefault(); |
| 5384 | const newName = input.value.trim(); |
| 5385 | if (!newName) return; |
| 5386 | try |
| 5387 | { |
| 5388 | if (item._root) |
| 5389 | { |
| 5390 | await api('POST', '/files/root-alias', { rootPath: item.path, alias: newName }); |
| 5391 | } else |
| 5392 | { |
| 5393 | await api('POST', '/files/rename', { from: item.path, to: newName }); |
| 5394 | } |
| 5395 | modal.classList.add('hidden'); |
| 5396 | toast(item._root ? 'Alias updated.' : 'Renamed.', 'ok'); |
| 5397 | if (item._root) |
| 5398 | { |
| 5399 | await loadRoots({ |
| 5400 | preferredDir: STATE.currentDir, |
| 5401 | preferredRootPath: (STATE.currentRoot && STATE.currentRoot.path) || item.path, |
| 5402 | }); |
| 5403 | } else |
| 5404 | { |
| 5405 | await navigateTo(STATE.currentDir, STATE.currentRoot); |
| 5406 | } |
| 5407 | } catch (err) |
| 5408 | { |
| 5409 | document.getElementById('rename-error').textContent = err.message; |
| 5410 | document.getElementById('rename-error').classList.remove('hidden'); |
| 5411 | } |
| 5412 | }; |
| 5413 | } |
| 5414 | |
| 5415 | // ─────────────────────────────────────────────────────────────────────────── |
| 5416 | // DELETE |
| 5417 | // ─────────────────────────────────────────────────────────────────────────── |
| 5418 | |
| 5419 | async function deleteItem (item) |
| 5420 | { |
| 5421 | if (!await showConfirm('Delete item', `Delete "${item.name}"? This cannot be undone.`)) return; |
| 5422 | try |
| 5423 | { |
| 5424 | await api('POST', '/files/delete', { path: item.path }); |
| 5425 | toast('Deleted.', 'ok'); |
| 5426 | closeSidebar(); |
| 5427 | await navigateTo(STATE.currentDir, STATE.currentRoot); |
| 5428 | } catch (err) |
| 5429 | { |
| 5430 | toast(err.message, 'err'); |
| 5431 | } |
| 5432 | } |
| 5433 | |
| 5434 | // ─────────────────────────────────────────────────────────────────────────── |
| 5435 | // ADMIN PANEL |
| 5436 | // ─────────────────────────────────────────────────────────────────────────── |
| 5437 | |
| 5438 | let _adminUpdateStatus = null; |
| 5439 | |
| 5440 | function animateBadgeToTarget (targetEl) |
| 5441 | { |
| 5442 | const badge = document.getElementById('admin-update-badge'); |
| 5443 | if (!badge || !targetEl) return; |
| 5444 | if (badge.parentElement === targetEl) return; |
| 5445 | |
| 5446 | const from = badge.getBoundingClientRect(); |
| 5447 | targetEl.appendChild(badge); |
| 5448 | const to = badge.getBoundingClientRect(); |
| 5449 | |
| 5450 | const dx = from.left - to.left; |
| 5451 | const dy = from.top - to.top; |
| 5452 | |
| 5453 | badge.style.transition = 'none'; |
| 5454 | badge.style.transform = `translate(${dx}px, ${dy}px)`; |
| 5455 | badge.style.willChange = 'transform'; |
| 5456 | |
| 5457 | requestAnimationFrame(() => |
| 5458 | { |
| 5459 | badge.style.transition = 'transform 240ms cubic-bezier(0.22, 1, 0.36, 1)'; |
| 5460 | badge.style.transform = 'translate(0, 0)'; |
| 5461 | }); |
| 5462 | |
| 5463 | const cleanup = () => |
| 5464 | { |
| 5465 | badge.style.transition = ''; |
| 5466 | badge.style.transform = ''; |
| 5467 | badge.style.willChange = ''; |
| 5468 | badge.removeEventListener('transitionend', cleanup); |
| 5469 | }; |
| 5470 | badge.addEventListener('transitionend', cleanup); |
| 5471 | } |
| 5472 | |
| 5473 | function moveBadgeToTarget (targetEl) |
| 5474 | { |
| 5475 | const badge = document.getElementById('admin-update-badge'); |
| 5476 | if (!badge || !targetEl) return; |
| 5477 | if (badge.parentElement === targetEl) return; |
| 5478 | |
| 5479 | badge.style.transition = ''; |
| 5480 | badge.style.transform = ''; |
| 5481 | badge.style.willChange = ''; |
| 5482 | targetEl.appendChild(badge); |
| 5483 | } |
| 5484 | |
| 5485 | function syncAdminUpdateBadgeAnchor ({ animate = true, forceUserAnchor = false } = {}) |
| 5486 | { |
| 5487 | const badge = document.getElementById('admin-update-badge'); |
| 5488 | const userMenuBtn = document.getElementById('btn-user-menu'); |
| 5489 | const adminBtn = document.getElementById('btn-admin'); |
| 5490 | if (!badge || !userMenuBtn || !adminBtn) return; |
| 5491 | |
| 5492 | const userDropdown = userMenuBtn.closest('.topbar-dropdown'); |
| 5493 | const userMenuOpen = !!(userDropdown && userDropdown.classList.contains('open')); |
| 5494 | const target = forceUserAnchor ? userMenuBtn : (userMenuOpen ? adminBtn : userMenuBtn); |
| 5495 | |
| 5496 | if (badge.classList.contains('hidden')) |
| 5497 | { |
| 5498 | moveBadgeToTarget(userMenuBtn); |
| 5499 | return; |
| 5500 | } |
| 5501 | |
| 5502 | if (animate) animateBadgeToTarget(target); |
| 5503 | else moveBadgeToTarget(target); |
| 5504 | } |
| 5505 | |
| 5506 | function setAdminUpdateBadge (count) |
| 5507 | { |
| 5508 | const badge = document.getElementById('admin-update-badge'); |
| 5509 | const userMenuBtn = document.getElementById('btn-user-menu'); |
| 5510 | if (!badge || !userMenuBtn) return; |
| 5511 | |
| 5512 | if (!STATE.isAdmin || !Number.isFinite(count) || count <= 0) |
| 5513 | { |
| 5514 | badge.classList.add('hidden'); |
| 5515 | badge.textContent = ''; |
| 5516 | if (badge.parentElement !== userMenuBtn) userMenuBtn.appendChild(badge); |
| 5517 | userMenuBtn.removeAttribute('data-update-count'); |
| 5518 | return; |
| 5519 | } |
| 5520 | |
| 5521 | const whole = Math.floor(count); |
| 5522 | const capped = Math.min(whole, 99); |
| 5523 | badge.textContent = capped >= 99 ? '99+' : String(capped); |
| 5524 | badge.classList.remove('hidden'); |
| 5525 | userMenuBtn.dataset.updateCount = String(whole); |
| 5526 | syncAdminUpdateBadgeAnchor(); |
| 5527 | } |
| 5528 | |
| 5529 | function pulseAdminUpdateButton () |
| 5530 | { |
| 5531 | const btn = document.getElementById('admin-shutdown-btn'); |
| 5532 | if (!btn) return; |
| 5533 | |
| 5534 | if (typeof btn.scrollIntoView === 'function') |
| 5535 | { |
| 5536 | btn.scrollIntoView({ behavior: 'smooth', block: 'center' }); |
| 5537 | } |
| 5538 | |
| 5539 | btn.classList.remove('admin-update-highlight'); |
| 5540 | // Force reflow so repeated openings can replay the pulse animation. |
| 5541 | void btn.offsetWidth; |
| 5542 | btn.classList.add('admin-update-highlight'); |
| 5543 | |
| 5544 | setTimeout(() => |
| 5545 | { |
| 5546 | btn.classList.remove('admin-update-highlight'); |
| 5547 | }, 1800); |
| 5548 | } |
| 5549 | |
| 5550 | async function openAdminModal () |
| 5551 | { |
| 5552 | document.getElementById('admin-modal').classList.remove('hidden'); |
| 5553 | await refreshGlobalFavicon(); |
| 5554 | await refreshAdminConfig(); |
| 5555 | await refreshAdminUsers(); |
| 5556 | await refreshAdminUpdateStatus({ pulseIfUpdateAvailable: true }); |
| 5557 | } |
| 5558 | |
| 5559 | async function refreshAdminConfig () |
| 5560 | { |
| 5561 | const data = await api('GET', '/admin/config'); |
| 5562 | if (!data) return; |
| 5563 | |
| 5564 | const userPathInput = document.getElementById('admin-user-path'); |
| 5565 | const sizeInput = document.getElementById('admin-user-size-limit'); |
| 5566 | if (userPathInput) userPathInput.value = data.userPath || ''; |
| 5567 | if (sizeInput) |
| 5568 | { |
| 5569 | sizeInput.value = data.userFolderSizeLimit ? formatBytes(data.userFolderSizeLimit) : ''; |
| 5570 | updateAdminSizeFeedback(sizeInput.value); |
| 5571 | } |
| 5572 | |
| 5573 | const container = document.getElementById('admin-paths'); |
| 5574 | container.innerHTML = ''; |
| 5575 | for (const p of data.paths) |
| 5576 | { |
| 5577 | const row = document.createElement('div'); |
| 5578 | row.className = 'path-row'; |
| 5579 | row.innerHTML = `<span>${p}</span><button data-path="${p}" title="Remove">✕</button>`; |
| 5580 | row.querySelector('button').addEventListener('click', () => |
| 5581 | { |
| 5582 | row.remove(); |
| 5583 | }); |
| 5584 | container.appendChild(row); |
| 5585 | } |
| 5586 | } |
| 5587 | |
| 5588 | async function refreshAdminUsers () |
| 5589 | { |
| 5590 | const data = await api('GET', '/admin/users'); |
| 5591 | if (!data) return; |
| 5592 | const container = document.getElementById('admin-users-list'); |
| 5593 | container.innerHTML = ''; |
| 5594 | |
| 5595 | // Need paths for permission rows |
| 5596 | const cfg = await api('GET', '/admin/config'); |
| 5597 | const paths = cfg ? (cfg.effectivePaths || []) : []; |
| 5598 | |
| 5599 | for (const u of data.users) |
| 5600 | { |
| 5601 | const row = document.createElement('div'); |
| 5602 | row.className = 'user-row'; |
| 5603 | row.innerHTML = ` |
| 5604 | <span class="user-name">${u.username}</span> |
| 5605 | ${u.isAdmin ? '<span class="user-admin-badge">Admin</span>' : ''} |
| 5606 | <button data-id="${u.id}" data-action="edit">Edit</button> |
| 5607 | ${u.username === STATE.username ? '' : `<button data-id="${u.id}" data-action="delete" class="danger">Delete</button>`} |
| 5608 | `; |
| 5609 | row.querySelector('[data-action="edit"]').addEventListener('click', () => |
| 5610 | openUserModal(u, paths)); |
| 5611 | const deleteBtn = row.querySelector('[data-action="delete"]'); |
| 5612 | if (deleteBtn) deleteBtn.addEventListener('click', async () => |
| 5613 | { |
| 5614 | if (!await showConfirm('Delete user', `Delete user "${u.username}"? This cannot be undone.`)) return; |
| 5615 | try |
| 5616 | { |
| 5617 | await api('DELETE', `/admin/users/${u.id}`); |
| 5618 | toast('User deleted.', 'ok'); |
| 5619 | await refreshAdminUsers(); |
| 5620 | } catch (err) { toast(err.message, 'err'); } |
| 5621 | }); |
| 5622 | container.appendChild(row); |
| 5623 | } |
| 5624 | |
| 5625 | await refreshAdminOrphanUserFolders(); |
| 5626 | } |
| 5627 | |
| 5628 | async function refreshAdminOrphanUserFolders () |
| 5629 | { |
| 5630 | const section = document.getElementById('admin-orphan-userfolders-section'); |
| 5631 | const list = document.getElementById('admin-orphan-userfolders-list'); |
| 5632 | if (!section || !list) return; |
| 5633 | |
| 5634 | let data = null; |
| 5635 | try |
| 5636 | { |
| 5637 | data = await api('GET', '/admin/orphan-userfolders'); |
| 5638 | } catch |
| 5639 | { |
| 5640 | section.classList.add('hidden'); |
| 5641 | list.innerHTML = ''; |
| 5642 | return; |
| 5643 | } |
| 5644 | |
| 5645 | const folders = Array.isArray(data && data.folders) ? data.folders : []; |
| 5646 | if (!folders.length) |
| 5647 | { |
| 5648 | section.classList.add('hidden'); |
| 5649 | list.innerHTML = ''; |
| 5650 | return; |
| 5651 | } |
| 5652 | |
| 5653 | section.classList.remove('hidden'); |
| 5654 | list.innerHTML = ''; |
| 5655 | |
| 5656 | for (const folder of folders) |
| 5657 | { |
| 5658 | const row = document.createElement('div'); |
| 5659 | row.className = 'user-row orphan-folder-row'; |
| 5660 | |
| 5661 | const name = document.createElement('span'); |
| 5662 | name.className = 'user-name'; |
| 5663 | name.textContent = folder.folderName || 'Unknown folder'; |
| 5664 | |
| 5665 | const info = document.createElement('span'); |
| 5666 | info.className = 'orphan-folder-meta'; |
| 5667 | const itemCount = Number(folder.itemCount) || 0; |
| 5668 | info.textContent = `${itemCount} item${itemCount === 1 ? '' : 's'}`; |
| 5669 | |
| 5670 | const openBtn = document.createElement('button'); |
| 5671 | openBtn.dataset.action = 'open-orphan-folder'; |
| 5672 | openBtn.textContent = 'Open folder'; |
| 5673 | openBtn.addEventListener('click', async () => |
| 5674 | { |
| 5675 | const targetPath = String(folder.path || '').trim(); |
| 5676 | if (!targetPath) return; |
| 5677 | |
| 5678 | try |
| 5679 | { |
| 5680 | const syntheticRoot = { |
| 5681 | label: name.textContent, |
| 5682 | originalName: name.textContent, |
| 5683 | alias: null, |
| 5684 | path: targetPath, |
| 5685 | isUserFolder: true, |
| 5686 | isOrphanUserFolder: true, |
| 5687 | }; |
| 5688 | await navigateTo(targetPath, syntheticRoot); |
| 5689 | document.getElementById('admin-modal').classList.add('hidden'); |
| 5690 | } catch (err) |
| 5691 | { |
| 5692 | toast(err.message || 'Failed to open folder.', 'err'); |
| 5693 | } |
| 5694 | }); |
| 5695 | |
| 5696 | row.appendChild(name); |
| 5697 | row.appendChild(info); |
| 5698 | row.appendChild(openBtn); |
| 5699 | list.appendChild(row); |
| 5700 | } |
| 5701 | } |
| 5702 | |
| 5703 | async function refreshAdminUpdateStatus (opts = {}) |
| 5704 | { |
| 5705 | const pulseIfUpdateAvailable = !!opts.pulseIfUpdateAvailable; |
| 5706 | const btn = document.getElementById('admin-shutdown-btn'); |
| 5707 | _adminUpdateStatus = null; |
| 5708 | btn.textContent = 'Shut down server'; |
| 5709 | setAdminUpdateBadge(0); |
| 5710 | |
| 5711 | try |
| 5712 | { |
| 5713 | const data = await api('GET', '/admin/update-status'); |
| 5714 | if (!data) return; |
| 5715 | _adminUpdateStatus = data; |
| 5716 | |
| 5717 | const updateCount = (data.underSystemd && Array.isArray(data.commitsAhead)) |
| 5718 | ? data.commitsAhead.length |
| 5719 | : 0; |
| 5720 | setAdminUpdateBadge(updateCount); |
| 5721 | |
| 5722 | if (!data.underSystemd) |
| 5723 | { |
| 5724 | btn.textContent = 'Shut down server'; |
| 5725 | } |
| 5726 | else if (data.commitsAhead.length === 0) |
| 5727 | { |
| 5728 | btn.textContent = 'Restart Server'; |
| 5729 | } |
| 5730 | else |
| 5731 | { |
| 5732 | btn.textContent = 'Restart & Update'; |
| 5733 | if (pulseIfUpdateAvailable) pulseAdminUpdateButton(); |
| 5734 | } |
| 5735 | } |
| 5736 | catch |
| 5737 | { |
| 5738 | // Not critical; button stays as "Shut down server". |
| 5739 | } |
| 5740 | } |
| 5741 | |
| 5742 | function openUserModal (user, paths) |
| 5743 | { |
| 5744 | const modal = document.getElementById('user-modal'); |
| 5745 | modal.classList.remove('hidden'); |
| 5746 | document.getElementById('user-modal-title').textContent = user ? `Edit: ${user.username}` : 'New User'; |
| 5747 | document.getElementById('user-error').classList.add('hidden'); |
| 5748 | |
| 5749 | const usernameInput = document.getElementById('user-username'); |
| 5750 | usernameInput.value = user ? user.username : ''; |
| 5751 | usernameInput.readOnly = !!user; |
| 5752 | |
| 5753 | document.getElementById('user-password').value = ''; |
| 5754 | const adminChk = document.getElementById('user-is-admin'); |
| 5755 | const editingOwnAccount = !!(user |
| 5756 | && String(user.username || '').toLowerCase() === String(STATE.username || '').toLowerCase()); |
| 5757 | adminChk.checked = user ? user.isAdmin : false; |
| 5758 | adminChk.disabled = editingOwnAccount; |
| 5759 | adminChk.title = editingOwnAccount |
| 5760 | ? 'You cannot remove admin privileges from your own account.' |
| 5761 | : ''; |
| 5762 | |
| 5763 | // Password placeholder |
| 5764 | document.getElementById('user-password').placeholder = |
| 5765 | user ? 'Leave blank to keep current' : 'Min 8 characters'; |
| 5766 | |
| 5767 | // Build permissions grid |
| 5768 | const permDiv = document.getElementById('user-permissions'); |
| 5769 | permDiv.innerHTML = ''; |
| 5770 | if (paths.length) |
| 5771 | { |
| 5772 | const heading = document.createElement('h4'); |
| 5773 | heading.textContent = 'Path Permissions'; |
| 5774 | permDiv.appendChild(heading); |
| 5775 | |
| 5776 | const isAdminUser = !!(user && user.isAdmin); |
| 5777 | // Mirror the is-admin checkbox so toggling it live-updates the perm rows. |
| 5778 | const rebuildPermRows = (admin) => |
| 5779 | { |
| 5780 | permDiv.querySelectorAll('.perm-row').forEach(r => |
| 5781 | { |
| 5782 | r.querySelectorAll('input[type=checkbox]').forEach(cb => |
| 5783 | { |
| 5784 | cb.disabled = admin; |
| 5785 | if (admin) cb.checked = true; |
| 5786 | }); |
| 5787 | r.title = admin ? 'Admins always have full access' : ''; |
| 5788 | }); |
| 5789 | }; |
| 5790 | adminChk.addEventListener('change', () => rebuildPermRows(adminChk.checked)); |
| 5791 | |
| 5792 | const syncReadWriteConstraints = (row, admin = false) => |
| 5793 | { |
| 5794 | const readCb = row.querySelector('input[data-type="read"]'); |
| 5795 | const writeCb = row.querySelector('input[data-type="write"]'); |
| 5796 | if (!readCb || !writeCb) return; |
| 5797 | |
| 5798 | if (admin) |
| 5799 | { |
| 5800 | readCb.checked = true; |
| 5801 | writeCb.checked = true; |
| 5802 | readCb.disabled = true; |
| 5803 | writeCb.disabled = true; |
| 5804 | return; |
| 5805 | } |
| 5806 | |
| 5807 | readCb.disabled = false; |
| 5808 | if (!readCb.checked) |
| 5809 | { |
| 5810 | writeCb.checked = false; |
| 5811 | writeCb.disabled = true; |
| 5812 | } |
| 5813 | else |
| 5814 | { |
| 5815 | writeCb.disabled = false; |
| 5816 | } |
| 5817 | }; |
| 5818 | |
| 5819 | const syncAllReadWriteConstraints = () => |
| 5820 | { |
| 5821 | const admin = adminChk.checked; |
| 5822 | permDiv.querySelectorAll('.perm-row').forEach((row) => |
| 5823 | { |
| 5824 | syncReadWriteConstraints(row, admin); |
| 5825 | }); |
| 5826 | }; |
| 5827 | |
| 5828 | for (const p of paths) |
| 5829 | { |
| 5830 | const label = p.split(/[\\/]/).pop(); |
| 5831 | const perms = user && user.permissions ? (user.permissions[label] || {}) : {}; |
| 5832 | const row = document.createElement('div'); |
| 5833 | row.className = 'perm-row'; |
| 5834 | const readChecked = isAdminUser || perms.read; |
| 5835 | const writeChecked = isAdminUser || perms.write; |
| 5836 | row.innerHTML = ` |
| 5837 | <span class="perm-label">${label}</span> |
| 5838 | <label class="checkbox-label"><input type="checkbox" data-label="${label}" data-type="read" ${readChecked ? 'checked' : ''} ${isAdminUser ? 'disabled' : ''} /> Read</label> |
| 5839 | <label class="checkbox-label"><input type="checkbox" data-label="${label}" data-type="write" ${writeChecked ? 'checked' : ''} ${isAdminUser ? 'disabled' : ''} /> Write</label> |
| 5840 | `; |
| 5841 | if (isAdminUser) row.title = 'Admins always have full access'; |
| 5842 | const readCb = row.querySelector('input[data-type="read"]'); |
| 5843 | if (readCb) |
| 5844 | { |
| 5845 | readCb.addEventListener('change', () => |
| 5846 | { |
| 5847 | syncReadWriteConstraints(row, adminChk.checked); |
| 5848 | }); |
| 5849 | } |
| 5850 | permDiv.appendChild(row); |
| 5851 | } |
| 5852 | |
| 5853 | syncAllReadWriteConstraints(); |
| 5854 | adminChk.addEventListener('change', syncAllReadWriteConstraints); |
| 5855 | } |
| 5856 | |
| 5857 | document.getElementById('user-form').onsubmit = async (e) => |
| 5858 | { |
| 5859 | e.preventDefault(); |
| 5860 | const password = document.getElementById('user-password').value; |
| 5861 | const isAdmin = document.getElementById('user-is-admin').checked; |
| 5862 | const permissions = {}; |
| 5863 | permDiv.querySelectorAll('input[data-label]').forEach(cb => |
| 5864 | { |
| 5865 | const lbl = cb.dataset.label; |
| 5866 | if (!permissions[lbl]) permissions[lbl] = {}; |
| 5867 | permissions[lbl][cb.dataset.type] = cb.checked; |
| 5868 | }); |
| 5869 | |
| 5870 | try |
| 5871 | { |
| 5872 | if (user) |
| 5873 | { |
| 5874 | const body = { isAdmin, permissions }; |
| 5875 | if (password) body.password = password; |
| 5876 | await api('PATCH', `/admin/users/${user.id}`, body); |
| 5877 | } else |
| 5878 | { |
| 5879 | const uname = document.getElementById('user-username').value.trim(); |
| 5880 | await api('POST', '/admin/users', { username: uname, password, isAdmin, permissions }); |
| 5881 | } |
| 5882 | modal.classList.add('hidden'); |
| 5883 | toast('User saved.', 'ok'); |
| 5884 | await refreshAdminUsers(); |
| 5885 | } catch (err) |
| 5886 | { |
| 5887 | document.getElementById('user-error').textContent = err.message; |
| 5888 | document.getElementById('user-error').classList.remove('hidden'); |
| 5889 | } |
| 5890 | }; |
| 5891 | } |
| 5892 | |
| 5893 | // ─────────────────────────────────────────────────────────────────────────── |
| 5894 | // SVG ICONS |
| 5895 | // ─────────────────────────────────────────────────────────────────────────── |
| 5896 | |
| 5897 | const IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'ico', 'avif']); |
| 5898 | const VIDEO_EXTS = new Set(['mp4', 'webm', 'ogv', 'mov', 'avi', 'mkv']); |
| 5899 | const AUDIO_EXTS = new Set(['mp3', 'ogg', 'wav', 'flac', 'aac', 'm4a']); |
| 5900 | const MODEL_EXTS = new Set(['stl', 'obj']); |
| 5901 | const DOC_EXTS = new Set(['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'ods', 'odp']); |
| 5902 | 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']); |
| 5903 | const ARCHIVE_EXTS = new Set(['zip', 'tar', 'gz', 'bz2', 'xz', 'rar', '7z']); |
| 5904 | const MAX_DIRECT_SVG_THUMB_BYTES = 1024 * 1024; |
| 5905 | |
| 5906 | function iconFolder (size = 52) |
| 5907 | { |
| 5908 | return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" |
| 5909 | stroke="#5b7fff" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"> |
| 5910 | <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"/> |
| 5911 | </svg>`; |
| 5912 | } |
| 5913 | |
| 5914 | function iconFile (name, size = 52) |
| 5915 | { |
| 5916 | const color = fileAccentColor(name); |
| 5917 | let symbol = ''; |
| 5918 | |
| 5919 | return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" |
| 5920 | stroke="${color}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"> |
| 5921 | <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/> |
| 5922 | <polyline points="14 2 14 8 20 8"/> |
| 5923 | </svg>`; |
| 5924 | } |
| 5925 | |
| 5926 | function watchStatusForTile (item) |
| 5927 | { |
| 5928 | if (!item || item.isDir) return null; |
| 5929 | if (!VIDEO_EXTS.has(extOf(item.name || ''))) return null; |
| 5930 | |
| 5931 | const cached = STATE.watchedStatusByPath[item.path]; |
| 5932 | if (cached === 'fully' || cached === 'partway') return cached; |
| 5933 | |
| 5934 | const currentUser = String(STATE.username || '').trim(); |
| 5935 | if (!currentUser) return null; |
| 5936 | |
| 5937 | const watchedBy = item.watchedBy && typeof item.watchedBy === 'object' ? item.watchedBy : {}; |
| 5938 | const statusRaw = watchedBy[currentUser]; |
| 5939 | const status = String(statusRaw || '').toLowerCase(); |
| 5940 | if (status === 'fully' || status === 'partway') return status; |
| 5941 | return null; |
| 5942 | } |
| 5943 | |
| 5944 | function renderWatchedOverlayOnIcon (iconEl, watchStatus) |
| 5945 | { |
| 5946 | if (!iconEl) return; |
| 5947 | |
| 5948 | const existing = iconEl.querySelector('.watched-overlay'); |
| 5949 | if (existing) existing.remove(); |
| 5950 | if (watchStatus !== 'fully' && watchStatus !== 'partway') return; |
| 5951 | |
| 5952 | const overlay = document.createElement('div'); |
| 5953 | overlay.className = `watched-overlay watched-overlay--${watchStatus}`; |
| 5954 | overlay.innerHTML = watchedEyeFilledSvg(); |
| 5955 | iconEl.appendChild(overlay); |
| 5956 | } |
| 5957 | |
| 5958 | function findTileIconByPath (filePath) |
| 5959 | { |
| 5960 | if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') return null; |
| 5961 | const tile = Array.from(document.querySelectorAll('.file-item')).find((el) => el.dataset.path === filePath); |
| 5962 | if (!tile) return null; |
| 5963 | return tile.querySelector('.icon'); |
| 5964 | } |
| 5965 | |
| 5966 | function watchStatusFromWatchedBy (watchedBy) |
| 5967 | { |
| 5968 | const currentUser = String(STATE.username || '').trim(); |
| 5969 | if (!currentUser) return null; |
| 5970 | |
| 5971 | const map = watchedBy && typeof watchedBy === 'object' ? watchedBy : {}; |
| 5972 | const statusRaw = map[currentUser]; |
| 5973 | const status = String(statusRaw || '').toLowerCase(); |
| 5974 | if (status === 'fully' || status === 'partway') return status; |
| 5975 | return null; |
| 5976 | } |
| 5977 | |
| 5978 | async function loadWatchedStatusesForCurrentDir () |
| 5979 | { |
| 5980 | const dirAtStart = STATE.currentDir; |
| 5981 | if (!dirAtStart) return; |
| 5982 | |
| 5983 | const videoItems = (STATE.items || []).filter((item) => |
| 5984 | item && !item.isDir && VIDEO_EXTS.has(extOf(item.name || '')) |
| 5985 | ); |
| 5986 | if (!videoItems.length) return; |
| 5987 | |
| 5988 | const loadId = ++STATE.watchedLoadId; |
| 5989 | |
| 5990 | let statusMap = null; |
| 5991 | const filePaths = videoItems.map((item) => item.path); |
| 5992 | |
| 5993 | const bulk = await api('POST', '/files/watched-statuses', { filePaths }).catch(() => null); |
| 5994 | if (bulk && bulk.statuses && typeof bulk.statuses === 'object') |
| 5995 | { |
| 5996 | statusMap = {}; |
| 5997 | for (const item of videoItems) |
| 5998 | { |
| 5999 | const status = String(bulk.statuses[item.path] || '').toLowerCase(); |
| 6000 | statusMap[item.path] = status === 'fully' || status === 'partway' ? status : null; |
| 6001 | } |
| 6002 | } |
| 6003 | |
| 6004 | // Compatibility fallback for older servers that do not expose bulk statuses yet. |
| 6005 | if (!statusMap) |
| 6006 | { |
| 6007 | statusMap = {}; |
| 6008 | const statuses = await Promise.all(videoItems.map(async (item) => |
| 6009 | { |
| 6010 | const meta = await api('GET', `/files/meta?file=${encodeURIComponent(item.path)}`).catch(() => null); |
| 6011 | return { |
| 6012 | path: item.path, |
| 6013 | status: watchStatusFromWatchedBy(meta && meta.watchedBy), |
| 6014 | }; |
| 6015 | })); |
| 6016 | |
| 6017 | for (const entry of statuses) |
| 6018 | { |
| 6019 | statusMap[entry.path] = entry.status; |
| 6020 | } |
| 6021 | } |
| 6022 | |
| 6023 | if (loadId !== STATE.watchedLoadId) return; |
| 6024 | if (!samePath(STATE.currentDir, dirAtStart)) return; |
| 6025 | if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') return; |
| 6026 | |
| 6027 | for (const item of videoItems) |
| 6028 | { |
| 6029 | const status = statusMap[item.path] || null; |
| 6030 | if (status) STATE.watchedStatusByPath[item.path] = status; |
| 6031 | else delete STATE.watchedStatusByPath[item.path]; |
| 6032 | |
| 6033 | const iconEl = findTileIconByPath(item.path); |
| 6034 | renderWatchedOverlayOnIcon(iconEl, status); |
| 6035 | } |
| 6036 | } |
| 6037 | |
| 6038 | function watchedEyeFilledSvg () |
| 6039 | { |
| 6040 | return `<svg class="watched-overlay-svg" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"><path fill="#ffffff" d="M651.669528 512c0-14.5903-2.084475-28.290323-6.251378-41.395806-11.019984 24.423249-35.143405 41.395806-63.733557 41.395806l-7.440459-0.593518-5.957689 0.593518c-30.973432 0-56.285934-25.607214-56.285934-56.882522l0.297782-5.952572-0.297782-7.447623c0-28.290323 16.97665-52.709479 41.097-63.727417-13.104459-4.172019-26.802436-6.252401-41.097-6.252401-77.132728 0-139.67311 62.834071-139.67311 140.263557 0 77.428464 62.540382 139.971915 139.67311 139.971915S651.669528 589.428464 651.669528 512L651.669528 512zM958.70846 512c0 0-153.36904-297.80564-448.198905-297.80564-293.63669 0-445.219037 297.80564-445.219037 297.80564s164.385954 297.804616 447.306582 297.804616C805.038568 809.80564 958.70846 512 958.70846 512L958.70846 512zM304.725748 512c0-114.954125 92.619444-208.164017 207.27374-208.164017 114.657366 0 207.27067 93.209892 207.27067 208.164017 0 114.953102-92.613304 208.167087-207.27067 208.167087C397.345192 720.167087 304.725748 626.953102 304.725748 512L304.725748 512zM304.725748 512"/></svg>`; |
| 6041 | } |
| 6042 | |
| 6043 | // ─────────────────────────────────────────────────────────────────────────── |
| 6044 | // EVENT WIRING |
| 6045 | // ─────────────────────────────────────────────────────────────────────────── |
| 6046 | |
| 6047 | // ─────────────────────────────────────────────────────────────────────────── |
| 6048 | // THUMBNAIL PREVIEWS |
| 6049 | // ─────────────────────────────────────────────────────────────────────────── |
| 6050 | |
| 6051 | function revokeThumbnails () |
| 6052 | { |
| 6053 | STATE.thumbnailUrls.forEach(u => URL.revokeObjectURL(u)); |
| 6054 | STATE.thumbnailUrls = []; |
| 6055 | } |
| 6056 | |
| 6057 | function disconnectThumbnailObserver () |
| 6058 | { |
| 6059 | if (!STATE.thumbnailObserver) return; |
| 6060 | STATE.thumbnailObserver.disconnect(); |
| 6061 | STATE.thumbnailObserver = null; |
| 6062 | } |
| 6063 | |
| 6064 | function disconnectFolderIconObserver () |
| 6065 | { |
| 6066 | if (!STATE.folderIconObserver) return; |
| 6067 | STATE.folderIconObserver.disconnect(); |
| 6068 | STATE.folderIconObserver = null; |
| 6069 | } |
| 6070 | |
| 6071 | function setThumbnailPending (iconEl, pending) |
| 6072 | { |
| 6073 | if (!iconEl) return; |
| 6074 | if (pending) |
| 6075 | { |
| 6076 | iconEl.classList.add('thumb-pending'); |
| 6077 | iconEl.dataset.thumbPending = '1'; |
| 6078 | return; |
| 6079 | } |
| 6080 | |
| 6081 | iconEl.classList.remove('thumb-pending'); |
| 6082 | delete iconEl.dataset.thumbPending; |
| 6083 | } |
| 6084 | |
| 6085 | function getThumbnailKind (name) |
| 6086 | { |
| 6087 | const ext = extOf(name || ''); |
| 6088 | if (IMAGE_EXTS.has(ext) || VIDEO_EXTS.has(ext) || MODEL_EXTS.has(ext)) return 'image'; |
| 6089 | if (CODE_EXTS.has(ext)) return 'text'; |
| 6090 | return 'badge'; |
| 6091 | } |
| 6092 | |
| 6093 | function maxThumbBytesForKind (kind) |
| 6094 | { |
| 6095 | if (kind === 'image') return 15 * 1024 * 1024; |
| 6096 | if (kind === 'text') return 1024 * 1024; |
| 6097 | return 0; |
| 6098 | } |
| 6099 | |
| 6100 | function drawTokenizedLine (ctx, line, x, y) |
| 6101 | { |
| 6102 | 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; |
| 6103 | let last = 0; |
| 6104 | let cursor = x; |
| 6105 | for (const m of line.matchAll(tokenRe)) |
| 6106 | { |
| 6107 | const i = m.index == null ? 0 : m.index; |
| 6108 | if (i > last) |
| 6109 | { |
| 6110 | const plain = line.slice(last, i); |
| 6111 | ctx.fillStyle = '#dce4ff'; |
| 6112 | ctx.fillText(plain, cursor, y); |
| 6113 | cursor += ctx.measureText(plain).width; |
| 6114 | } |
| 6115 | |
| 6116 | const tok = m[0]; |
| 6117 | if (/^\/\//.test(tok) || /^\/\*/.test(tok)) ctx.fillStyle = '#6f7f9a'; |
| 6118 | else if (/^['"`]/.test(tok)) ctx.fillStyle = '#9ee37d'; |
| 6119 | else if (/^\d/.test(tok)) ctx.fillStyle = '#f8c46a'; |
| 6120 | else ctx.fillStyle = '#8bb4ff'; |
| 6121 | |
| 6122 | ctx.fillText(tok, cursor, y); |
| 6123 | cursor += ctx.measureText(tok).width; |
| 6124 | last = i + tok.length; |
| 6125 | } |
| 6126 | |
| 6127 | if (last < line.length) |
| 6128 | { |
| 6129 | const tail = line.slice(last); |
| 6130 | ctx.fillStyle = '#dce4ff'; |
| 6131 | ctx.fillText(tail, cursor, y); |
| 6132 | } |
| 6133 | } |
| 6134 | |
| 6135 | function textThumbnailDataUrl (text) |
| 6136 | { |
| 6137 | const canvas = document.createElement('canvas'); |
| 6138 | canvas.width = 160; |
| 6139 | canvas.height = 200; |
| 6140 | const ctx = canvas.getContext('2d'); |
| 6141 | if (!ctx) return null; |
| 6142 | |
| 6143 | ctx.fillStyle = '#0d111a'; |
| 6144 | ctx.fillRect(0, 0, canvas.width, canvas.height); |
| 6145 | ctx.font = '8px ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace'; |
| 6146 | ctx.textBaseline = 'top'; |
| 6147 | |
| 6148 | const lines = String(text || '') |
| 6149 | .replace(/\r\n/g, '\n') |
| 6150 | .split('\n') |
| 6151 | .slice(0, 17); |
| 6152 | |
| 6153 | let y = 8; |
| 6154 | for (const line of lines) |
| 6155 | { |
| 6156 | drawTokenizedLine(ctx, line.slice(0, 42), 6, y); |
| 6157 | y += 11; |
| 6158 | if (y > 190) break; |
| 6159 | } |
| 6160 | return canvas.toDataURL('image/png'); |
| 6161 | } |
| 6162 | |
| 6163 | function badgeThumbnailDataUrl (name, kind) |
| 6164 | { |
| 6165 | const canvas = document.createElement('canvas'); |
| 6166 | canvas.width = 160; |
| 6167 | canvas.height = 200; |
| 6168 | const ctx = canvas.getContext('2d'); |
| 6169 | if (!ctx) return null; |
| 6170 | |
| 6171 | const ext = (extOf(name || '') || 'file').toUpperCase().slice(0, 5); |
| 6172 | const color = '#5b7fff'; |
| 6173 | |
| 6174 | ctx.fillStyle = '#111826'; |
| 6175 | ctx.fillRect(0, 0, 160, 200); |
| 6176 | ctx.fillStyle = color; |
| 6177 | ctx.fillRect(0, 0, 160, 28); |
| 6178 | ctx.fillStyle = '#ffffff'; |
| 6179 | ctx.font = 'bold 12px sans-serif'; |
| 6180 | ctx.textAlign = 'center'; |
| 6181 | ctx.fillText(ext, 80, 8); |
| 6182 | ctx.textAlign = 'left'; |
| 6183 | ctx.fillStyle = '#9fb1d8'; |
| 6184 | ctx.font = '10px sans-serif'; |
| 6185 | ctx.fillText('Preview', 8, 48); |
| 6186 | ctx.fillStyle = '#dce4ff'; |
| 6187 | ctx.font = 'bold 11px sans-serif'; |
| 6188 | ctx.fillText(ext, 8, 66); |
| 6189 | return canvas.toDataURL('image/png'); |
| 6190 | } |
| 6191 | |
| 6192 | async function buildThumbnailSource (item, blob, kind) |
| 6193 | { |
| 6194 | if (kind === 'text') return textThumbnailDataUrl(await blob.text()); |
| 6195 | return badgeThumbnailDataUrl(item.name, kind); |
| 6196 | } |
| 6197 | |
| 6198 | function observeThumbnailIcon (iconEl) |
| 6199 | { |
| 6200 | if (!iconEl || !iconEl.isConnected) return; |
| 6201 | if (iconEl.dataset.thumbReady === '1') return; |
| 6202 | |
| 6203 | if (!('IntersectionObserver' in window)) |
| 6204 | { |
| 6205 | void loadOneThumbnail(iconEl); |
| 6206 | return; |
| 6207 | } |
| 6208 | |
| 6209 | if (!STATE.thumbnailObserver) |
| 6210 | { |
| 6211 | STATE.thumbnailObserver = new IntersectionObserver((entries) => |
| 6212 | { |
| 6213 | for (const entry of entries) |
| 6214 | { |
| 6215 | if (!entry.isIntersecting) continue; |
| 6216 | const icon = entry.target; |
| 6217 | STATE.thumbnailObserver.unobserve(icon); |
| 6218 | void loadOneThumbnail(icon); |
| 6219 | } |
| 6220 | }, { root: null, rootMargin: THUMB_OBSERVER_ROOT_MARGIN, threshold: 0.01 }); |
| 6221 | } |
| 6222 | |
| 6223 | STATE.thumbnailObserver.observe(iconEl); |
| 6224 | } |
| 6225 | |
| 6226 | async function loadThumbnails () |
| 6227 | { |
| 6228 | const icons = Array.from(document.querySelectorAll('.icon[data-preview-path]')); |
| 6229 | for (const icon of icons) |
| 6230 | { |
| 6231 | observeThumbnailIcon(icon); |
| 6232 | } |
| 6233 | |
| 6234 | const folderIcons = Array.from(document.querySelectorAll('.icon[data-folder-path]')); |
| 6235 | for (const icon of folderIcons) |
| 6236 | { |
| 6237 | observeFolderIcon(icon); |
| 6238 | } |
| 6239 | } |
| 6240 | |
| 6241 | async function loadOneThumbnail (iconEl) |
| 6242 | { |
| 6243 | if (!iconEl.isConnected || !STATE.token) return; |
| 6244 | if (iconEl.dataset.thumbReady === '1') return; |
| 6245 | const filePath = iconEl.dataset.previewPath; |
| 6246 | const item = STATE.items.find(i => i.path === filePath); |
| 6247 | if (!item) return; |
| 6248 | |
| 6249 | const kind = getThumbnailKind(item.name); |
| 6250 | let srcUrl = null; |
| 6251 | |
| 6252 | if (kind === 'badge') |
| 6253 | { |
| 6254 | setThumbnailPending(iconEl, false); |
| 6255 | srcUrl = badgeThumbnailDataUrl(item.name, kind); |
| 6256 | } |
| 6257 | else if (kind === 'image') |
| 6258 | { |
| 6259 | const ext = extOf(item.name || ''); |
| 6260 | const useDirectSource = |
| 6261 | ext === 'ico' || |
| 6262 | ( |
| 6263 | ext === 'svg' && |
| 6264 | typeof item.size === 'number' && |
| 6265 | item.size > 0 && |
| 6266 | item.size <= MAX_DIRECT_SVG_THUMB_BYTES |
| 6267 | ); |
| 6268 | |
| 6269 | const url = useDirectSource |
| 6270 | ? `/api/files/download?file=${encodeURIComponent(filePath)}` |
| 6271 | : `/api/files/thumbnail?file=${encodeURIComponent(filePath)}`; |
| 6272 | |
| 6273 | let res; |
| 6274 | try |
| 6275 | { |
| 6276 | res = await fetch(url, { |
| 6277 | headers: { |
| 6278 | Authorization: `Bearer ${STATE.token}`, |
| 6279 | 'X-Fp': getFingerprint(), |
| 6280 | }, |
| 6281 | }); |
| 6282 | } catch |
| 6283 | { |
| 6284 | return; |
| 6285 | } |
| 6286 | |
| 6287 | if (!useDirectSource && res.status === 404) |
| 6288 | { |
| 6289 | setThumbnailPending(iconEl, true); |
| 6290 | return; |
| 6291 | } |
| 6292 | |
| 6293 | if (!res.ok || !iconEl.isConnected) return; |
| 6294 | setThumbnailPending(iconEl, false); |
| 6295 | |
| 6296 | const blob = await res.blob(); |
| 6297 | srcUrl = URL.createObjectURL(blob); |
| 6298 | STATE.thumbnailUrls.push(srcUrl); |
| 6299 | } |
| 6300 | else |
| 6301 | { |
| 6302 | setThumbnailPending(iconEl, false); |
| 6303 | const maxBytes = maxThumbBytesForKind(kind); |
| 6304 | if (maxBytes > 0 && typeof item.size === 'number' && item.size > maxBytes) |
| 6305 | { |
| 6306 | srcUrl = badgeThumbnailDataUrl(item.name, kind); |
| 6307 | } else |
| 6308 | { |
| 6309 | const url = `/api/files/download?file=${encodeURIComponent(filePath)}`; |
| 6310 | |
| 6311 | let res; |
| 6312 | try |
| 6313 | { |
| 6314 | res = await fetch(url, { |
| 6315 | headers: { |
| 6316 | Authorization: `Bearer ${STATE.token}`, |
| 6317 | 'X-Fp': getFingerprint(), |
| 6318 | }, |
| 6319 | }); |
| 6320 | } catch { return; } |
| 6321 | if (!res.ok || !iconEl.isConnected) return; |
| 6322 | |
| 6323 | const blob = await res.blob(); |
| 6324 | srcUrl = await buildThumbnailSource(item, blob, kind); |
| 6325 | } |
| 6326 | } |
| 6327 | if (!srcUrl || !iconEl.isConnected) return; |
| 6328 | |
| 6329 | const svg = iconEl.querySelector('svg'); |
| 6330 | if (!svg) |
| 6331 | { |
| 6332 | if (srcUrl.startsWith('blob:')) URL.revokeObjectURL(srcUrl); |
| 6333 | return; |
| 6334 | } |
| 6335 | |
| 6336 | const NS = 'http://www.w3.org/2000/svg'; |
| 6337 | const id = `fcp-${Math.random().toString(36).slice(2, 9)}`; |
| 6338 | |
| 6339 | // clipPath matches the main file body outline exactly (viewBox 0 0 24 24) |
| 6340 | const defs = document.createElementNS(NS, 'defs'); |
| 6341 | const clipPath = document.createElementNS(NS, 'clipPath'); |
| 6342 | clipPath.setAttribute('id', id); |
| 6343 | clipPath.setAttribute('clipPathUnits', 'userSpaceOnUse'); |
| 6344 | const clipShape = document.createElementNS(NS, 'path'); |
| 6345 | clipShape.setAttribute('d', 'M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z'); |
| 6346 | clipPath.appendChild(clipShape); |
| 6347 | defs.appendChild(clipPath); |
| 6348 | |
| 6349 | // Image fills the file bounding box; clip keeps it inside the outline |
| 6350 | const img = document.createElementNS(NS, 'image'); |
| 6351 | img.setAttribute('href', srcUrl); |
| 6352 | img.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', srcUrl); |
| 6353 | img.setAttribute('x', '4'); |
| 6354 | img.setAttribute('y', '2'); |
| 6355 | img.setAttribute('width', '16'); |
| 6356 | img.setAttribute('height', '20'); |
| 6357 | img.setAttribute('clip-path', `url(#${id})`); |
| 6358 | img.setAttribute('preserveAspectRatio', 'xMidYMid slice'); |
| 6359 | |
| 6360 | // Prepend so existing path/polyline elements (the outline) render on top |
| 6361 | svg.prepend(img); |
| 6362 | svg.prepend(defs); |
| 6363 | iconEl.dataset.thumbReady = '1'; |
| 6364 | } |
| 6365 | |
| 6366 | // ─────────────────────────────────────────────────────────────────────────── |
| 6367 | // FOLDER ICON THUMBNAILS |
| 6368 | // ─────────────────────────────────────────────────────────────────────────── |
| 6369 | |
| 6370 | function observeFolderIcon (iconEl) |
| 6371 | { |
| 6372 | if (!iconEl || !iconEl.isConnected) return; |
| 6373 | if (iconEl.dataset.thumbReady === '1') return; |
| 6374 | |
| 6375 | if (!('IntersectionObserver' in window)) |
| 6376 | { |
| 6377 | void loadOneFolderIcon(iconEl); |
| 6378 | return; |
| 6379 | } |
| 6380 | |
| 6381 | if (!STATE.folderIconObserver) |
| 6382 | { |
| 6383 | STATE.folderIconObserver = new IntersectionObserver((entries) => |
| 6384 | { |
| 6385 | for (const entry of entries) |
| 6386 | { |
| 6387 | if (!entry.isIntersecting) continue; |
| 6388 | const icon = entry.target; |
| 6389 | STATE.folderIconObserver.unobserve(icon); |
| 6390 | void loadOneFolderIcon(icon); |
| 6391 | } |
| 6392 | }, { root: null, rootMargin: THUMB_OBSERVER_ROOT_MARGIN, threshold: 0.01 }); |
| 6393 | } |
| 6394 | |
| 6395 | STATE.folderIconObserver.observe(iconEl); |
| 6396 | } |
| 6397 | |
| 6398 | async function loadOneFolderIcon (iconEl) |
| 6399 | { |
| 6400 | if (!iconEl.isConnected || !STATE.token) return; |
| 6401 | if (iconEl.dataset.thumbReady === '1') return; |
| 6402 | |
| 6403 | const folderPath = iconEl.dataset.folderPath; |
| 6404 | if (!folderPath) return; |
| 6405 | |
| 6406 | let res; |
| 6407 | try |
| 6408 | { |
| 6409 | res = await fetch(`/api/files/folder-icon?dir=${encodeURIComponent(folderPath)}`, { |
| 6410 | headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() }, |
| 6411 | }); |
| 6412 | } catch { return; } |
| 6413 | |
| 6414 | if (!res.ok || !iconEl.isConnected) return; |
| 6415 | |
| 6416 | const data = await res.json(); |
| 6417 | if (!data.icon) return; // No icon available — keep plain folder SVG. |
| 6418 | |
| 6419 | // Fetch the thumbnail through the auth-gated endpoint. |
| 6420 | let thumbRes; |
| 6421 | try |
| 6422 | { |
| 6423 | thumbRes = await fetch( |
| 6424 | `/api/files/thumbnail?file=${encodeURIComponent(data.icon.filePath)}`, |
| 6425 | { headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() } }, |
| 6426 | ); |
| 6427 | } catch { return; } |
| 6428 | |
| 6429 | if (!thumbRes.ok || !iconEl.isConnected) return; |
| 6430 | |
| 6431 | const blob = await thumbRes.blob(); |
| 6432 | const srcUrl = URL.createObjectURL(blob); |
| 6433 | STATE.thumbnailUrls.push(srcUrl); |
| 6434 | |
| 6435 | applyFolderThumbnail(iconEl, srcUrl); |
| 6436 | } |
| 6437 | |
| 6438 | /** |
| 6439 | * Overlays a thumbnail image inside the folder SVG outline. |
| 6440 | * The folder viewBox is 0 0 24 24; the folder body covers roughly x=2,y=5 to x=22,y=21. |
| 6441 | */ |
| 6442 | function applyFolderThumbnail (iconEl, srcUrl) |
| 6443 | { |
| 6444 | if (!iconEl.isConnected) return; |
| 6445 | const svg = iconEl.querySelector('svg'); |
| 6446 | if (!svg) |
| 6447 | { |
| 6448 | if (srcUrl.startsWith('blob:')) URL.revokeObjectURL(srcUrl); |
| 6449 | return; |
| 6450 | } |
| 6451 | |
| 6452 | const NS = 'http://www.w3.org/2000/svg'; |
| 6453 | const id = `fcp-${Math.random().toString(36).slice(2, 9)}`; |
| 6454 | |
| 6455 | const defs = document.createElementNS(NS, 'defs'); |
| 6456 | const clipPath = document.createElementNS(NS, 'clipPath'); |
| 6457 | clipPath.setAttribute('id', id); |
| 6458 | clipPath.setAttribute('clipPathUnits', 'userSpaceOnUse'); |
| 6459 | const clipShape = document.createElementNS(NS, 'path'); |
| 6460 | // Folder outline path (same as iconFolder SVG path) |
| 6461 | 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'); |
| 6462 | clipPath.appendChild(clipShape); |
| 6463 | defs.appendChild(clipPath); |
| 6464 | |
| 6465 | // Image covers the folder body area; clip keeps it inside the outline. |
| 6466 | const img = document.createElementNS(NS, 'image'); |
| 6467 | img.setAttribute('href', srcUrl); |
| 6468 | img.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', srcUrl); |
| 6469 | img.setAttribute('x', '2'); |
| 6470 | img.setAttribute('y', '3'); |
| 6471 | img.setAttribute('width', '20'); |
| 6472 | img.setAttribute('height', '18'); |
| 6473 | img.setAttribute('clip-path', `url(#${id})`); |
| 6474 | img.setAttribute('preserveAspectRatio', 'xMidYMid slice'); |
| 6475 | |
| 6476 | // Prepend so the folder outline strokes render on top. |
| 6477 | svg.prepend(img); |
| 6478 | svg.prepend(defs); |
| 6479 | iconEl.dataset.thumbReady = '1'; |
| 6480 | } |
| 6481 | |
| 6482 | function closeTopbarDropdowns () |
| 6483 | { |
| 6484 | // Prevent jump-to-(0,0) glitches by snapping badge back before the menu is hidden. |
| 6485 | syncAdminUpdateBadgeAnchor({ animate: false, forceUserAnchor: true }); |
| 6486 | |
| 6487 | document.querySelectorAll('.topbar-dropdown.open').forEach((dropdown) => |
| 6488 | { |
| 6489 | dropdown.classList.remove('open'); |
| 6490 | const trigger = dropdown.querySelector('button[aria-expanded]'); |
| 6491 | if (trigger) trigger.setAttribute('aria-expanded', 'false'); |
| 6492 | }); |
| 6493 | } |
| 6494 | |
| 6495 | function initTopbarDropdowns () |
| 6496 | { |
| 6497 | document.querySelectorAll('.topbar-dropdown').forEach((dropdown) => |
| 6498 | { |
| 6499 | const trigger = dropdown.querySelector('button[aria-expanded]'); |
| 6500 | if (!trigger) return; |
| 6501 | |
| 6502 | trigger.addEventListener('click', (e) => |
| 6503 | { |
| 6504 | e.stopPropagation(); |
| 6505 | const shouldOpen = !dropdown.classList.contains('open'); |
| 6506 | closeTopbarDropdowns(); |
| 6507 | if (shouldOpen) |
| 6508 | { |
| 6509 | dropdown.classList.add('open'); |
| 6510 | trigger.setAttribute('aria-expanded', 'true'); |
| 6511 | syncAdminUpdateBadgeAnchor(); |
| 6512 | } |
| 6513 | }); |
| 6514 | |
| 6515 | dropdown.querySelectorAll('.topbar-menu-item').forEach((itemBtn) => |
| 6516 | { |
| 6517 | itemBtn.addEventListener('click', () => closeTopbarDropdowns()); |
| 6518 | }); |
| 6519 | }); |
| 6520 | |
| 6521 | document.addEventListener('click', (e) => |
| 6522 | { |
| 6523 | if (e.target && e.target.closest && e.target.closest('.topbar-dropdown')) return; |
| 6524 | closeTopbarDropdowns(); |
| 6525 | }); |
| 6526 | |
| 6527 | document.addEventListener('keydown', (e) => |
| 6528 | { |
| 6529 | if (e.key === 'Escape') closeTopbarDropdowns(); |
| 6530 | }); |
| 6531 | } |
| 6532 | |
| 6533 | function wireEvents () |
| 6534 | { |
| 6535 | initTopbarDropdowns(); |
| 6536 | |
| 6537 | // Auth form |
| 6538 | document.getElementById('auth-form').addEventListener('submit', async (e) => |
| 6539 | { |
| 6540 | e.preventDefault(); |
| 6541 | const username = document.getElementById('auth-username').value.trim(); |
| 6542 | const password = document.getElementById('auth-password').value; |
| 6543 | const isSetup = e.target.dataset.mode === 'setup'; |
| 6544 | const errEl = document.getElementById('auth-erro |
| 6545 | … afgekapt |