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