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