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