/* ========================================================= FILE MANAGER — CLIENT SPA ========================================================= Architecture: - RSA-OAEP + AES-256-GCM hybrid encryption via Web Crypto API - Token is stored in localStorage to survive full page refresh - Token is sent as Bearer header on every API call - Fingerprint (derived from navigator info) locks the token to this browser ========================================================= */ 'use strict'; // ─────────────────────────────────────────────────────────────────────────── // STATE // ─────────────────────────────────────────────────────────────────────────── const STATE = { token: null, // decrypted JWT string username: null, isAdmin: false, permissions: {}, roots: [], // [{ label, path }] currentDir: null, // absolute path currently shown (null = roots view) currentRoot: null, // { label, path } of the active root items: [], // current directory listing selectedItem: null, // item object selected in sidebar // Ephemeral key pair per session (client-side) clientPrivateKey: null, clientPublicKeyJwk: null, // Server public key for encrypting login serverPublicKeyJwk: null, // Stable per-browser binding id used in fingerprint derivation clientBindingId: null, // Persisted view state restoreDir: null, restoreRootPath: null, lastOperationAt: null, // In-app navigation history mirrored to browser history state. navigationHistory: [], navigationIndex: -1, // Background refresh state autoRefreshTimer: null, uploadInProgress: false, // Blob URLs for thumbnail previews — revoked on each grid rebuild thumbnailUrls: [], thumbnailObserver: null, folderIconObserver: null, // Preview overlay state previewObjectUrl: null, previewCleanup: null, previewVideoStreamSessionId: null, previewStreamInitToken: 0, previewSourceEl: null, // SVG element that triggered the preview previewClosing: false, // guard to prevent double-close during animation previewExpandState: null, // in-place expanded tile preview state movePicker: null, // Sidebar async loading guard to prevent stale updates on rapid selection changes. sidebarLoadId: 0, sidebarAbortController: null, // Watched overlays are resolved asynchronously from /files/meta responses. watchedStatusByPath: {}, watchedLoadId: 0, // Cross-root file search mode (null = regular folder browsing). searchQuery: null, // Bust cache when favicon changes. faviconVersion: Date.now(), }; const SESSION_KEY = 'filemanager.session.v1'; const SESSION_IDLE_TIMEOUT_MS = 60 * 60 * 1000; // 1 hour const CLIENT_BINDING_KEY = 'filemanager.client-binding-id.v1'; const MOBILE_BREAKPOINT_QUERY = '(max-width: 600px)'; const MOBILE_LONG_PRESS_MS = 420; const MOBILE_LONG_PRESS_MOVE_THRESHOLD = 10; const THUMB_OBSERVER_ROOT_MARGIN = '120px'; const VIDEO_PREFS_KEY_PREFIX = 'filemanager.video-prefs.v1.'; const FOLDER_VIEW_PREFS_KEY_PREFIX = 'filemanager.folder-view-prefs.v1.'; const VIDEO_TEXT_TRACK_SETTINGS_KEY = 'vjs-text-track-settings'; const VIDEO_TEXT_TRACK_OVERRIDE_SETTINGS_RAW = JSON.stringify({ backgroundOpacity: '0', edgeStyle: 'uniform', }); const DEFAULT_FOLDER_VIEW_PREFS = { sortBy: 'alphabetical', groupBy: 'none', foldersFirst: true, ascending: true, }; const FOLDER_SORT_OPTIONS = [ { value: 'alphabetical', label: 'Alphabetically' }, { value: 'fileType', label: 'File type' }, { value: 'lastChanged', label: 'Last changed' }, { value: 'timeUploaded', label: 'Time uploaded' }, { value: 'size', label: 'Size' }, ]; const FOLDER_GROUP_OPTIONS = [ { value: 'none', label: 'None' }, { value: 'alphabetical', label: 'Alphabetically' }, { value: 'fileType', label: 'File type' }, { value: 'lastChangedDate', label: 'Last changed date' }, { value: 'timeUploadedDate', label: 'Upload date' }, { value: 'size', label: 'Size' }, ]; const VIDEO_FORWARD_BUFFER_SECONDS = 60 * 60; const VIDEO_FORWARD_BUFFER_OVERRIDE_ENABLED = false; const VIDEO_PREVIEW_LOAD_TIMEOUT_MS = 120 * 1000; const IMAGE_SUBTITLE_LOOKAHEAD_SECONDS = 15; const IMAGE_SUBTITLE_INITIAL_PREFETCH_SECONDS = 60; const IMAGE_SUBTITLE_PREFETCH_REQUEST_INTERVAL_MS = 40; const IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS_NEAR = 3; const IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS_FAR = 10; let videoJsLoaderPromise = null; let threePreviewModulesPromise = null; // ─────────────────────────────────────────────────────────────────────────── // CRYPTO HELPERS (Web Crypto API) // ─────────────────────────────────────────────────────────────────────────── async function generateClientKeyPair () { if (!hasWebCrypto()) return; const kp = await crypto.subtle.generateKey( { name: 'RSA-OAEP', modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256' }, true, ['encrypt', 'decrypt'], ); STATE.clientPrivateKey = kp.privateKey; STATE.clientPublicKeyJwk = await crypto.subtle.exportKey('jwk', kp.publicKey); } /** * Hybrid-encrypt a JS object using the server's RSA public key. * Returns { encryptedKey, iv, ciphertext, tag } all as base64 strings. */ async function hybridEncryptForServer (obj) { if (!hasWebCrypto() || !STATE.serverPublicKeyJwk) { return { plaintext: obj }; } const serverPub = await crypto.subtle.importKey( 'jwk', STATE.serverPublicKeyJwk, { name: 'RSA-OAEP', hash: 'SHA-256' }, false, ['encrypt'], ); const plaintext = new TextEncoder().encode(JSON.stringify(obj)); const aesKey = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt']); const iv = crypto.getRandomValues(new Uint8Array(12)); const gcmResult = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, aesKey, plaintext); // gcmResult = ciphertext || tag (last 16 bytes are auth tag) const gcmBytes = new Uint8Array(gcmResult); const ciphertext = gcmBytes.slice(0, gcmBytes.length - 16); const tag = gcmBytes.slice(gcmBytes.length - 16); const rawAes = await crypto.subtle.exportKey('raw', aesKey); const encryptedKey = await crypto.subtle.encrypt({ name: 'RSA-OAEP' }, serverPub, rawAes); return { encryptedKey: b64(encryptedKey), iv: b64(iv), ciphertext: b64(ciphertext), tag: b64(tag), }; } /** * Hybrid-decrypt a payload encrypted by the server for us (using our public key). */ async function hybridDecryptFromServer (payload) { if (!payload) return null; if (payload.token) return payload.token; if (!hasWebCrypto()) return null; const encryptedKey = unb64(payload.encryptedKey); const iv = unb64(payload.iv); const ciphertext = unb64(payload.ciphertext); const tag = unb64(payload.tag); const rawAes = await crypto.subtle.decrypt( { name: 'RSA-OAEP' }, STATE.clientPrivateKey, encryptedKey, ); const aesKey = await crypto.subtle.importKey('raw', rawAes, { name: 'AES-GCM' }, false, ['decrypt']); // Recombine ciphertext + tag for AES-GCM const combined = new Uint8Array(ciphertext.byteLength + tag.byteLength); combined.set(new Uint8Array(ciphertext)); combined.set(new Uint8Array(tag), ciphertext.byteLength); const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, aesKey, combined); return new TextDecoder().decode(plain); } // ─────────────────────────────────────────────────────────────────────────── // UTIL // ─────────────────────────────────────────────────────────────────────────── function b64 (buf) { return btoa(String.fromCharCode(...new Uint8Array(buf instanceof ArrayBuffer ? buf : buf.buffer))); } function hasWebCrypto () { return !!(window.crypto && window.crypto.subtle); } function unb64 (str) { const binary = atob(str); const buf = new Uint8Array(binary.length); for (let i = 0; i < binary.length; i++) buf[i] = binary.charCodeAt(i); return buf.buffer; } /** Stable browser fingerprint (not stored, derived fresh each load) */ function getFingerprint () { const binding = getOrCreateClientBindingId(); const nav = navigator; // Keep this stable: avoid viewport/screen metrics that can change when // devtools opens, orientation changes, or window state changes. return [ binding, nav.userAgent || '', nav.language, nav.platform || nav.userAgentData?.platform || '', Intl.DateTimeFormat().resolvedOptions().timeZone, ].join('|'); } function randomIdHex (bytes = 16) { const arr = new Uint8Array(bytes); if (window.crypto && typeof window.crypto.getRandomValues === 'function') { window.crypto.getRandomValues(arr); } else { for (let i = 0; i < arr.length; i++) arr[i] = Math.floor(Math.random() * 256); } return Array.from(arr).map(n => n.toString(16).padStart(2, '0')).join(''); } function userVideoPrefsKey () { const name = String(STATE.username || 'anonymous').trim().toLowerCase() || 'anonymous'; return VIDEO_PREFS_KEY_PREFIX + name; } function loadUserVideoPrefs () { try { const raw = localStorage.getItem(userVideoPrefsKey()); const parsed = raw ? JSON.parse(raw) : {}; if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {}; return parsed; } catch { return {}; } } function saveUserVideoPrefs (patch) { try { const current = loadUserVideoPrefs(); localStorage.setItem(userVideoPrefsKey(), JSON.stringify({ ...current, ...(patch || {}) })); } catch { // Ignore localStorage failures. } } function userFolderViewPrefsKey () { const name = String(STATE.username || 'anonymous').trim().toLowerCase() || 'anonymous'; return FOLDER_VIEW_PREFS_KEY_PREFIX + name; } function normaliseFolderViewPrefs (value) { const input = value && typeof value === 'object' ? value : {}; const sortBy = ['alphabetical', 'fileType', 'lastChanged', 'timeUploaded', 'size'].includes(input.sortBy) ? input.sortBy : DEFAULT_FOLDER_VIEW_PREFS.sortBy; const groupBy = ['none', 'alphabetical', 'fileType', 'lastChangedDate', 'timeUploadedDate', 'size'].includes(input.groupBy) ? input.groupBy : DEFAULT_FOLDER_VIEW_PREFS.groupBy; return { sortBy, groupBy, foldersFirst: input.foldersFirst !== undefined ? !!input.foldersFirst : DEFAULT_FOLDER_VIEW_PREFS.foldersFirst, ascending: input.ascending !== undefined ? !!input.ascending : DEFAULT_FOLDER_VIEW_PREFS.ascending, }; } function loadFolderViewPrefsMap () { try { const raw = localStorage.getItem(userFolderViewPrefsKey()); const parsed = raw ? JSON.parse(raw) : {}; if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {}; const out = {}; for (const [dirPath, prefs] of Object.entries(parsed)) { out[String(dirPath)] = normaliseFolderViewPrefs(prefs); } return out; } catch { return {}; } } function saveFolderViewPrefsMap (prefsByPath) { try { localStorage.setItem(userFolderViewPrefsKey(), JSON.stringify(prefsByPath || {})); } catch { // Ignore localStorage failures. } } function folderViewPrefsForDir (dirPath) { if (!dirPath) return { ...DEFAULT_FOLDER_VIEW_PREFS }; const prefsByPath = loadFolderViewPrefsMap(); return normaliseFolderViewPrefs(prefsByPath[String(dirPath)] || DEFAULT_FOLDER_VIEW_PREFS); } function saveFolderViewPrefsForDir (dirPath, patch) { if (!dirPath) return; const key = String(dirPath); const prefsByPath = loadFolderViewPrefsMap(); const current = normaliseFolderViewPrefs(prefsByPath[key] || DEFAULT_FOLDER_VIEW_PREFS); prefsByPath[key] = normaliseFolderViewPrefs({ ...current, ...(patch || {}) }); saveFolderViewPrefsMap(prefsByPath); } function buildAuthHeaders () { const headers = {}; if (STATE.token) { headers.Authorization = 'Bearer ' + STATE.token; try { const fp = getFingerprint(); if (fp) headers['X-Fp'] = fp; } catch { // Continue without a fingerprint header in constrained test/runtime contexts. } } return headers; } function applyUserVideoTextTrackPrefs () { const shared = sharedVideoPlayer(); if (!shared || typeof shared.applyDefaultTextTrackPrefs !== 'function') return; shared.applyDefaultTextTrackPrefs(); } function sharedVideoPlayer () { return window.FilemanagerSharedVideoPlayer || null; } function bindUserVideoTrackPrefs (player, prefs) { const shared = sharedVideoPlayer(); if (!shared || typeof shared.bindTrackPrefs !== 'function') { return { applySavedTracks: () => { }, captureSelectedTracks: () => { }, detach: () => { }, }; } return shared.bindTrackPrefs(player, prefs, saveUserVideoPrefs); } function bindImageSubtitleOverlay (player, videojs, prefs, session, item) { const shared = sharedVideoPlayer(); if (!shared || typeof shared.bindImageSubtitleOverlay !== 'function') return null; const sendSubtitleLogBatch = (entries) => { if (!Array.isArray(entries) || !entries.length) return Promise.resolve(); const headers = { ...buildAuthHeaders(), 'Content-Type': 'application/json', }; return fetch('/api/files/video-stream-subtitle-log', { method: 'POST', headers, credentials: 'same-origin', keepalive: true, body: JSON.stringify({ filePath: item.path, sessionId: session.sessionId || null, entries, }), }).catch(() => null); }; return shared.bindImageSubtitleOverlay(player, videojs, prefs, session, { savePrefs: saveUserVideoPrefs, currentFetchEnabled: false, lookaheadSeconds: IMAGE_SUBTITLE_LOOKAHEAD_SECONDS, initialPrefetchSeconds: IMAGE_SUBTITLE_INITIAL_PREFETCH_SECONDS, prefetchRequestIntervalMs: IMAGE_SUBTITLE_PREFETCH_REQUEST_INTERVAL_MS, prefetchAdaptiveStepEnabled: true, prefetchAdaptivePacingEnabled: true, prefetchStepSecondsMin: IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS_NEAR, prefetchStepSecondsMax: IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS_FAR, sendSubtitleLogBatch, buildPrefetchRequest: ({ currentTime, endTime, streamIndex, session: activeSession }) => ({ url: `/api/files/video-stream-subtitle-range?filePath=${encodeURIComponent(item.path)}&streamIndex=${streamIndex}&startTimeSeconds=${encodeURIComponent(String(currentTime))}&endTimeSeconds=${encodeURIComponent(String(endTime))}&videoWidth=${encodeURIComponent(String(activeSession.videoWidth || ''))}&videoHeight=${encodeURIComponent(String(activeSession.videoHeight || ''))}`, headers: buildAuthHeaders(), credentials: 'same-origin', }), buildFrameRequest: ({ currentTime, streamIndex, session: activeSession }) => ({ 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 || ''))}`, headers: buildAuthHeaders(), credentials: 'same-origin', }), onError: () => toast('Image subtitles could not be rendered for this file.', 'err'), }); } function normaliseVideoDuration (player, durationSeconds) { const shared = sharedVideoPlayer(); if (!shared || typeof shared.normaliseVideoDuration !== 'function') return; shared.normaliseVideoDuration(player, durationSeconds); } function ensureVideoPlaybackUi (player, durationSeconds) { const shared = sharedVideoPlayer(); if (!shared || typeof shared.ensureVideoPlaybackUi !== 'function') return; shared.ensureVideoPlaybackUi(player, durationSeconds); } function enableVideoStreamClientCache () { const shared = sharedVideoPlayer(); if (!shared || typeof shared.enableVideoStreamClientCache !== 'function') return Promise.resolve(false); return shared.enableVideoStreamClientCache(); } function clearVideoStreamClientCache (playlistUrl) { const shared = sharedVideoPlayer(); if (!shared || typeof shared.clearVideoStreamClientCache !== 'function') return Promise.resolve(); return shared.clearVideoStreamClientCache(playlistUrl); } function bindStreamAheadPrefetch (playlistUrl) { const shared = sharedVideoPlayer(); if (!shared || typeof shared.bindStreamAheadPrefetch !== 'function') return null; return shared.bindStreamAheadPrefetch({ playlistUrl, headers: buildAuthHeaders(), credentials: 'same-origin', }); } function bindStreamAheadSeekMarker (player, streamAheadPrefetch) { const shared = sharedVideoPlayer(); if (!shared || typeof shared.bindStreamAheadSeekMarker !== 'function') return null; return shared.bindStreamAheadSeekMarker(player, streamAheadPrefetch); } async function reportWatchProgress (filePath, progress) { if (!filePath || !Number.isFinite(progress)) return; await api('POST', '/files/watch-progress', { filePath, progress, }).catch(() => null); const nextStatus = progress >= 0.7 ? 'fully' : progress >= 0.1 ? 'partway' : null; if (!nextStatus) return; const prev = STATE.watchedStatusByPath[filePath]; if (prev === 'fully') return; STATE.watchedStatusByPath[filePath] = nextStatus; const iconEl = findTileIconByPath(filePath); renderWatchedOverlayOnIcon(iconEl, nextStatus); } function getOrCreateClientBindingId () { if (STATE.clientBindingId) return STATE.clientBindingId; try { const existing = localStorage.getItem(CLIENT_BINDING_KEY); if (existing && typeof existing === 'string') { STATE.clientBindingId = existing; return existing; } } catch { // Ignore storage read errors. } const created = randomIdHex(16); STATE.clientBindingId = created; try { localStorage.setItem(CLIENT_BINDING_KEY, created); } catch { // Ignore storage write errors; in-memory fallback still keeps this stable // for the current page session. } return created; } function formatBytes (bytes) { if (bytes == null) return '—'; if (bytes < 1024) return bytes + ' B'; if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB'; if (bytes < 1073741824) return (bytes / 1048576).toFixed(1) + ' MB'; return (bytes / 1073741824).toFixed(2) + ' GB'; } function parseHumanSize (input) { const raw = String(input || '').trim(); if (!raw) return null; const m = raw.match(/^(\d+(?:\.\d+)?)\s*([kmgt]?)(?:i?b)?$/i); if (!m) return null; const value = Number(m[1]); if (!Number.isFinite(value) || value <= 0) return null; const unit = String(m[2] || '').toLowerCase(); const multipliers = { '': 1, k: 1024, m: 1024 * 1024, g: 1024 * 1024 * 1024, t: 1024 * 1024 * 1024 * 1024, }; return Math.floor(value * (multipliers[unit] || 1)); } function updateAdminSizeFeedback (rawValue) { const feedback = document.getElementById('admin-user-size-feedback'); if (!feedback) return { bytes: null, valid: true }; const trimmed = String(rawValue || '').trim(); if (!trimmed) { feedback.textContent = ''; feedback.classList.add('hidden'); feedback.classList.remove('ok', 'err'); return { bytes: null, valid: true }; } const bytes = parseHumanSize(trimmed); feedback.classList.remove('hidden', 'ok', 'err'); if (bytes == null) { feedback.textContent = 'Invalid size. Use formats like 25 MB, 1 GB, or 500 KB.'; feedback.classList.add('err'); return { bytes: null, valid: false }; } feedback.textContent = `Valid size: ${formatBytes(bytes)}`; feedback.classList.add('ok'); return { bytes, valid: true }; } function extOf (name) { const i = name.lastIndexOf('.'); return i >= 0 ? name.slice(i + 1).toLowerCase() : ''; } function getPathSep (basePath) { return basePath && basePath.includes('\\') ? '\\' : '/'; } function joinServerPath (basePath, segment) { const sep = getPathSep(basePath); const base = String(basePath || '').replace(/[\\/]+$/, ''); return base + sep + segment; } function samePath (a, b) { if (!a || !b) return false; return String(a).toLowerCase() === String(b).toLowerCase(); } function pathInside (child, root) { if (!child || !root) return false; if (samePath(child, root)) return true; const sep = getPathSep(root); return String(child).toLowerCase().startsWith((String(root) + sep).toLowerCase()); } function relativePathFromRoot (targetPath, rootPath) { if (!targetPath || !rootPath) return String(targetPath || ''); if (samePath(targetPath, rootPath)) return '.'; const prefix = String(rootPath).replace(/[\\/]+$/, ''); const rel = String(targetPath).slice(prefix.length).replace(/^[\\/]+/, ''); if (!rel) return '.'; return rel; } function displayPathWithRootLabel (targetPath, rootPath, rootLabel) { const rel = relativePathFromRoot(targetPath, rootPath); const safeRoot = String(rootLabel || '').replace(/^\/+|\/+$/g, ''); if (!safeRoot) return '/'; if (rel === '.') return `/${safeRoot}`; return `/${safeRoot}/${String(rel).replace(/\\/g, '/')}`; } function splitNameExt (name) { const dot = String(name || '').lastIndexOf('.'); if (dot <= 0) return { stem: String(name || ''), ext: '' }; return { stem: String(name).slice(0, dot), ext: String(name).slice(dot), }; } function nextAvailableName (requestedName, existingNames) { const set = existingNames instanceof Set ? existingNames : new Set(existingNames || []); if (!set.has(requestedName)) return requestedName; const { stem, ext } = splitNameExt(requestedName); let n = 1; while (n <= 10000) { const candidate = `${stem || 'file'} (${n})${ext}`; if (!set.has(candidate)) return candidate; n++; } return requestedName; } async function listDirNameSet (dir) { const data = await api('GET', `/files/list?dir=${encodeURIComponent(dir)}`); const names = new Set(); for (const it of ((data && data.items) || [])) names.add(it.name); return names; } function cloneFileWithName (file, newName) { return new File([file], newName, { type: file.type, lastModified: file.lastModified, }); } function saveSessionState () { if (!STATE.token) return; const now = Date.now(); STATE.lastOperationAt = now; const payload = { token: STATE.token, dir: STATE.currentDir || null, rootPath: STATE.currentRoot ? STATE.currentRoot.path : null, lastOperationAt: STATE.lastOperationAt, }; try { localStorage.setItem(SESSION_KEY, JSON.stringify(payload)); } catch { // Ignore storage errors (private mode/full quota). } } function loadSessionState () { try { const raw = localStorage.getItem(SESSION_KEY); if (!raw) return null; const parsed = JSON.parse(raw); if (!parsed || typeof parsed.token !== 'string') return null; if (!Number.isFinite(parsed.lastOperationAt)) return null; if (Date.now() - parsed.lastOperationAt > SESSION_IDLE_TIMEOUT_MS) { clearSessionState(); return null; } return parsed; } catch { return null; } } function clearSessionState () { try { localStorage.removeItem(SESSION_KEY); } catch { /* ignore */ } } function makeNavEntryForRoots () { return { kind: 'roots' }; } function makeNavEntryForDir (dirPath, rootPath) { return { kind: 'dir', dir: String(dirPath || ''), rootPath: String(rootPath || ''), }; } function sameNavEntry (a, b) { if (!a || !b) return false; if (a.kind !== b.kind) return false; if (a.kind === 'roots') return true; return samePath(a.dir, b.dir) && samePath(a.rootPath, b.rootPath); } function trimNavState (state) { if (!state || typeof state !== 'object') return null; const kind = String(state.kind || '').trim().toLowerCase(); if (kind === 'roots') return makeNavEntryForRoots(); if (kind !== 'dir') return null; const dir = String(state.dir || '').trim(); const rootPath = String(state.rootPath || '').trim(); if (!dir || !rootPath) return null; return makeNavEntryForDir(dir, rootPath); } function navStatePayload (entry, index) { return { filemanagerNav: entry, filemanagerNavIndex: Number(index), }; } function canUseBrowserHistory () { return !!( typeof window !== 'undefined' && window.history && typeof window.history.pushState === 'function' && typeof window.history.replaceState === 'function' ); } function writeBrowserNavState (entry, index, mode = 'push') { if (!canUseBrowserHistory()) return; const payload = navStatePayload(entry, index); if (mode === 'replace') { window.history.replaceState(payload, '', window.location.href); } else { window.history.pushState(payload, '', window.location.href); } } function recordNavigationEntry (entry, mode = 'push') { if (!entry) return; if (!STATE.navigationHistory.length) { STATE.navigationHistory = [entry]; STATE.navigationIndex = 0; writeBrowserNavState(entry, 0, 'replace'); return; } const current = STATE.navigationHistory[STATE.navigationIndex] || null; if (sameNavEntry(current, entry)) { writeBrowserNavState(entry, STATE.navigationIndex, 'replace'); return; } if (mode === 'replace') { STATE.navigationHistory[STATE.navigationIndex] = entry; writeBrowserNavState(entry, STATE.navigationIndex, 'replace'); return; } STATE.navigationHistory = STATE.navigationHistory.slice(0, STATE.navigationIndex + 1); STATE.navigationHistory.push(entry); STATE.navigationIndex = STATE.navigationHistory.length - 1; writeBrowserNavState(entry, STATE.navigationIndex, 'push'); } async function applyPopNavigationState (navEntry) { if (!navEntry) return; if (navEntry.kind === 'roots') { renderRootsView({ historyMode: 'skip' }); return; } if (navEntry.kind !== 'dir') return; const currentRoot = STATE.roots.find(r => samePath(r.path, navEntry.rootPath)); if (currentRoot) { await navigateTo(navEntry.dir, currentRoot, { historyMode: 'skip', keepSidebar: true }); return; } await loadRoots({ preferredDir: navEntry.dir, preferredRootPath: navEntry.rootPath, historyMode: 'skip', }); } async function onBrowserPopState (event) { if (!canUseBrowserHistory()) return; if (!STATE.token) return; const state = event && event.state && typeof event.state === 'object' ? event.state : null; const navEntry = trimNavState(state && state.filemanagerNav); if (!navEntry) return; const rawIndex = Number(state.filemanagerNavIndex); const hasIndex = Number.isInteger(rawIndex); const maxIndex = Math.max(STATE.navigationHistory.length - 1, 0); const targetIndex = hasIndex ? Math.max(0, Math.min(rawIndex, maxIndex)) : 0; STATE.navigationIndex = targetIndex; try { await applyPopNavigationState(navEntry); } catch { await loadRoots({ historyMode: 'replace' }); return; } if (targetIndex === 0 && STATE.navigationHistory.length > 1) { const leave = await showConfirm( 'Leave application', 'Do you want to close the application and return to the previous webpage?', { okLabel: 'Yes' } ); if (leave) { window.history.back(); } } } // ─────────────────────────────────────────────────────────────────────────── // API // ─────────────────────────────────────────────────────────────────────────── async function api (method, path, body, opts = {}) { const headers = { 'Content-Type': 'application/json' }; const noAutoLogout = !!opts.noAutoLogout; if (STATE.token) { headers['Authorization'] = 'Bearer ' + STATE.token; try { const fp = getFingerprint(); if (fp) headers['X-Fp'] = fp; } catch { // Continue without a fingerprint header in constrained test/runtime contexts. } } const fetchOpts = { ...opts }; delete fetchOpts.noAutoLogout; const res = await fetch('/api' + path, { method, headers, body: body != null ? JSON.stringify(body) : undefined, ...fetchOpts, }); if (!res.ok) { const j = await res.json().catch(() => ({})); // Session-expired → force re-login if (res.status === 401) { if (!noAutoLogout) logout(); return null; } throw new Error(j.error || res.statusText); } if (STATE.token && !path.startsWith('/auth/server-key') && !path.startsWith('/auth/setup-needed')) { saveSessionState(); } return res.json(); } // ─────────────────────────────────────────────────────────────────────────── // TOAST // ─────────────────────────────────────────────────────────────────────────── function toast (msg, type = '') { const el = document.createElement('div'); el.className = 'toast-msg' + (type ? ' ' + type : ''); el.textContent = msg; document.getElementById('toast').appendChild(el); setTimeout(() => el.remove(), 3500); } // ─────────────────────────────────────────────────────────────────────────── // DIALOG MODALS — centralised replacements for alert / confirm / prompt // ─────────────────────────────────────────────────────────────────────────── /** * Show a confirmation dialog. * @param {string} title * @param {string} message * @returns {Promise} true = OK, false = Cancel */ function showConfirm (title, message, { html = false, okLabel = null, modalClass = '' } = {}) { return new Promise((resolve) => { const overlay = document.getElementById('confirm-modal'); const dialogEl = overlay ? overlay.querySelector('.modal') : null; const className = typeof modalClass === 'string' ? modalClass.trim() : ''; document.getElementById('confirm-modal-title').textContent = title; const msgEl = document.getElementById('confirm-modal-message'); if (html) msgEl.innerHTML = message; else msgEl.textContent = message; if (dialogEl && className) dialogEl.classList.add(className); overlay.classList.remove('hidden'); const ok = document.getElementById('confirm-modal-ok'); const prevOkLabel = ok.textContent; if (okLabel != null) ok.textContent = okLabel; const cancel = document.getElementById('confirm-modal-cancel'); function finish (result) { overlay.classList.add('hidden'); if (dialogEl && className) dialogEl.classList.remove(className); ok.textContent = prevOkLabel; ok.removeEventListener('click', onOk); cancel.removeEventListener('click', onCancel); resolve(result); } function onOk () { finish(true); } function onCancel () { finish(false); } ok.addEventListener('click', onOk); cancel.addEventListener('click', onCancel); ok.focus(); }); } function escHtml (s) { return String(s || '') .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"'); } function normaliseUpdateCommits (commitsAhead) { if (!Array.isArray(commitsAhead)) return []; const out = []; for (const raw of commitsAhead) { if (typeof raw === 'string') { const line = raw.trim(); if (!line) continue; const match = line.match(/^([0-9a-f]{7,40})\s+(.+)$/i); out.push({ hash: match ? match[1] : '', subject: match ? match[2].trim() : line, body: '', }); continue; } if (!raw || typeof raw !== 'object') continue; const subject = String(raw.subject || '').trim(); if (!subject) continue; out.push({ hash: String(raw.hash || '').trim(), subject, body: String(raw.body || '').trim(), }); } return out; } function renderUpdateCommitListHtml (commitsAhead) { const commits = normaliseUpdateCommits(commitsAhead); if (!commits.length) return ''; const commitItems = commits.map((commit) => { const hashLabel = commit.hash ? `${escHtml(commit.hash.slice(0, 7))}` : ''; const subjectLabel = `${escHtml(commit.subject)}`; const bodyHtml = commit.body ? `

${escHtml(commit.body).replace(/\n/g, '
')}

` : ''; return `

${hashLabel}${hashLabel ? ' ' : ''}${subjectLabel}

${bodyHtml}
`; }).join(''); return `
${commitItems}
`; } /** * Show a text-input dialog. * @param {string} title * @param {string} [message] — optional helper text shown above the input * @param {string} [defaultValue] — pre-filled value * @returns {Promise} string = submitted value, null = cancelled */ function showPrompt (title, message = '', defaultValue = '') { return new Promise((resolve) => { const overlay = document.getElementById('prompt-modal'); const msgEl = document.getElementById('prompt-modal-message'); const input = document.getElementById('prompt-modal-input'); const errorEl = document.getElementById('prompt-modal-error'); const form = document.getElementById('prompt-modal-form'); const cancel = document.getElementById('prompt-modal-cancel'); document.getElementById('prompt-modal-title').textContent = title; msgEl.textContent = message; msgEl.classList.toggle('hidden', !message); input.value = defaultValue; errorEl.classList.add('hidden'); overlay.classList.remove('hidden'); input.focus(); input.select(); function finish (result) { overlay.classList.add('hidden'); form.removeEventListener('submit', onSubmit); cancel.removeEventListener('click', onCancel); resolve(result); } function onSubmit (e) { e.preventDefault(); finish(input.value); } function onCancel () { finish(null); } form.addEventListener('submit', onSubmit); cancel.addEventListener('click', onCancel); }); } /** * Show an overwrite-decision dialog for a single file conflict. * @param {string} filename * @returns {Promise<'yes'|'no'|'all'|'none'>} */ function showOverwrite (filename) { return new Promise((resolve) => { const overlay = document.getElementById('overwrite-modal'); document.getElementById('overwrite-modal-filename').textContent = filename; overlay.classList.remove('hidden'); const btnYes = document.getElementById('overwrite-modal-yes'); const btnNo = document.getElementById('overwrite-modal-no'); const btnAll = document.getElementById('overwrite-modal-all'); const btnSkipAll = document.getElementById('overwrite-modal-skip-all'); function finish (result) { overlay.classList.add('hidden'); btnYes.removeEventListener('click', onYes); btnNo.removeEventListener('click', onNo); btnAll.removeEventListener('click', onAll); btnSkipAll.removeEventListener('click', onSkipAll); resolve(result); } function onYes () { finish('yes'); } function onNo () { finish('no'); } function onAll () { finish('all'); } function onSkipAll () { finish('none'); } btnYes.addEventListener('click', onYes); btnNo.addEventListener('click', onNo); btnAll.addEventListener('click', onAll); btnSkipAll.addEventListener('click', onSkipAll); btnNo.focus(); }); } /** * Show single-file conflict options. * @param {string} filename * @param {string} renameTo * @param {string} mode - upload|move * @returns {Promise<'overwrite'|'rename'|'cancel'>} */ function showFileConflictChoice (filename, renameTo, mode = 'upload') { return new Promise((resolve) => { const overlay = document.getElementById('file-conflict-modal'); const title = document.getElementById('file-conflict-title'); const fileEl = document.getElementById('file-conflict-filename'); const renameEl = document.getElementById('file-conflict-rename'); const btnOverwrite = document.getElementById('file-conflict-overwrite'); const btnRename = document.getElementById('file-conflict-rename-btn'); const btnCancel = document.getElementById('file-conflict-cancel'); title.textContent = mode === 'move' ? 'Move file' : 'Upload file'; fileEl.textContent = filename; renameEl.textContent = renameTo; btnRename.textContent = `Rename (${renameTo})`; overlay.classList.remove('hidden'); function finish (result) { overlay.classList.add('hidden'); btnOverwrite.removeEventListener('click', onOverwrite); btnRename.removeEventListener('click', onRename); btnCancel.removeEventListener('click', onCancel); resolve(result); } function onOverwrite () { finish('overwrite'); } function onRename () { finish('rename'); } function onCancel () { finish('cancel'); } btnOverwrite.addEventListener('click', onOverwrite); btnRename.addEventListener('click', onRename); btnCancel.addEventListener('click', onCancel); btnCancel.focus(); }); } // ─────────────────────────────────────────────────────────────────────────── // SHARE MODAL // ─────────────────────────────────────────────────────────────────────────── async function openShareModal (item) { const overlay = document.getElementById('share-modal'); const urlInput = document.getElementById('share-url-input'); const copyBtn = document.getElementById('share-copy-btn'); const okBtn = document.getElementById('share-modal-ok'); const closeBtn = document.getElementById('share-modal-close'); const msgEl = document.getElementById('share-modal-msg'); urlInput.value = 'Creating link...'; copyBtn.disabled = true; msgEl.textContent = 'This link is valid for 24 hours.'; overlay.classList.remove('hidden'); let data; try { data = await api('POST', '/share/create', { filePath: item.path }); } catch (err) { msgEl.textContent = 'Error: ' + (err.message || 'Could not create link.'); urlInput.value = ''; return; } if (!data || !data.token) { msgEl.textContent = 'Unknown error while creating link.'; urlInput.value = ''; return; } const shareUrl = `${location.origin}/share/${data.token}`; urlInput.value = shareUrl; copyBtn.disabled = false; function close () { overlay.classList.add('hidden'); okBtn.removeEventListener('click', close); closeBtn.removeEventListener('click', close); copyBtn.removeEventListener('click', onCopy); } function onCopy () { navigator.clipboard.writeText(shareUrl).then(() => { const orig = copyBtn.textContent; copyBtn.textContent = 'Copied!'; setTimeout(() => { copyBtn.textContent = orig; }, 1500); }).catch(() => { // Fallback: select the text urlInput.select(); }); } okBtn.addEventListener('click', close); closeBtn.addEventListener('click', close); copyBtn.addEventListener('click', onCopy); okBtn.focus(); } // ─────────────────────────────────────────────────────────────────────────── // AUTH FLOW // ─────────────────────────────────────────────────────────────────────────── function showAuthOverlay (setupMode = false) { if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return; closeDebugModal(); document.getElementById('app').classList.add('hidden'); const overlay = document.getElementById('auth-overlay'); const usernameInput = document.getElementById('auth-username'); const passwordInput = document.getElementById('auth-password'); overlay.classList.remove('hidden'); document.getElementById('auth-title').textContent = setupMode ? 'Create Admin Account' : 'Sign In'; document.getElementById('auth-subtitle').classList.toggle('hidden', !setupMode); const submitBtn = document.getElementById('auth-submit'); submitBtn.disabled = false; submitBtn.textContent = setupMode ? 'Create Account' : 'Sign In'; document.getElementById('auth-error').classList.add('hidden'); usernameInput.value = ''; passwordInput.value = ''; usernameInput.autocomplete = 'username'; passwordInput.autocomplete = setupMode ? 'new-password' : 'current-password'; usernameInput.focus(); document.getElementById('auth-form').dataset.mode = setupMode ? 'setup' : 'login'; } function showApp () { if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return; document.getElementById('auth-overlay').classList.add('hidden'); document.getElementById('app').classList.remove('hidden'); if (isMobileViewport()) { hideSidebarPanel(); } else { openFolderSidebar(); } document.getElementById('btn-admin').classList.toggle('hidden', !STATE.isAdmin); document.getElementById('btn-debug').classList.toggle('hidden', !STATE.isAdmin); const userLabel = document.getElementById('user-menu-label'); if (userLabel) userLabel.textContent = STATE.username || 'User'; void refreshGlobalFavicon(); if (STATE.isAdmin) { void refreshAdminUpdateStatus(); } else { setAdminUpdateBadge(0); } startAutoRefresh(); } async function initAuth () { // Generate a fresh key pair in the background; login falls back gracefully // while this is still in progress. generateClientKeyPair().catch(() => { toast('Secure crypto unavailable in this browser context; using compatibility login mode.', 'err'); }); // Fetch server public key const { publicKey } = await api('GET', '/auth/server-key').catch(() => ({ publicKey: null })); if (publicKey) STATE.serverPublicKeyJwk = publicKey; if (!publicKey && hasWebCrypto()) { toast('Could not reach server.', 'err'); return; } STATE.serverPublicKeyJwk = publicKey; // Check whether first-run setup is needed const { needed } = await api('GET', '/auth/setup-needed').catch(() => ({ needed: false })); if (!needed) { const saved = loadSessionState(); if (saved && saved.token) { STATE.token = saved.token; STATE.restoreDir = saved.dir || null; STATE.restoreRootPath = saved.rootPath || null; STATE.lastOperationAt = saved.lastOperationAt; const me = await api('GET', '/auth/me', null, { noAutoLogout: true }).catch(() => null); if (me) { STATE.username = me.username; STATE.isAdmin = me.isAdmin; STATE.permissions = me.permissions; showApp(); await loadRoots({ preferredDir: STATE.restoreDir, preferredRootPath: STATE.restoreRootPath, }); return; } STATE.token = null; clearSessionState(); } } showAuthOverlay(needed); } async function doLogin (username, password, isSetup) { const encrypted = await hybridEncryptForServer({ username, password }); const endpoint = isSetup ? '/auth/setup' : '/auth/login'; let data; try { data = await api('POST', endpoint, { encrypted, clientPublicKey: STATE.clientPublicKeyJwk, fingerprint: getFingerprint(), }); } catch (err) { return err.message; } if (!data) return 'Login failed.'; // Decrypt the token sent back by the server const token = await hybridDecryptFromServer(data.encrypted || data); if (!token) return 'Login failed.'; STATE.token = token; // Load user info const me = await api('GET', '/auth/me'); if (!me) return 'Session error.'; STATE.username = me.username; STATE.isAdmin = me.isAdmin; STATE.permissions = me.permissions; saveSessionState(); showApp(); await loadRoots(); return null; // no error } function logout () { void performLogout(); } function openChangePasswordModal () { const modal = document.getElementById('change-password-modal'); const form = document.getElementById('change-password-form'); const currentInput = document.getElementById('change-password-current'); const nextInput = document.getElementById('change-password-next'); const confirmInput = document.getElementById('change-password-confirm'); const errorEl = document.getElementById('change-password-error'); function hide () { modal.classList.add('hidden'); form.onsubmit = null; } currentInput.value = ''; nextInput.value = ''; confirmInput.value = ''; errorEl.textContent = ''; errorEl.classList.add('hidden'); modal.classList.remove('hidden'); currentInput.focus(); form.onsubmit = async (e) => { e.preventDefault(); const currentPassword = currentInput.value; const newPassword = nextInput.value; const confirmPassword = confirmInput.value; if (newPassword !== confirmPassword) { errorEl.textContent = 'New passwords do not match.'; errorEl.classList.remove('hidden'); return; } if (newPassword.length < 8) { errorEl.textContent = 'New password must be at least 8 characters.'; errorEl.classList.remove('hidden'); return; } try { await api('POST', '/auth/change-password', { currentPassword, newPassword, }); hide(); toast('Password changed.', 'ok'); } catch (err) { errorEl.textContent = err.message || 'Failed to change password.'; errorEl.classList.remove('hidden'); } }; } async function performLogout () { const tokenAtStart = STATE.token; stopAutoRefresh(); if (tokenAtStart) { try { await api('POST', '/auth/logout', {}, { noAutoLogout: true }); } catch { // Ignore network errors while logging out locally. } } STATE.token = null; STATE.username = null; STATE.isAdmin = false; STATE.permissions = {}; STATE.currentDir = null; STATE.currentRoot = null; STATE.items = []; STATE.restoreDir = null; STATE.restoreRootPath = null; STATE.lastOperationAt = null; STATE.navigationHistory = []; STATE.navigationIndex = -1; _adminUpdateStatus = null; setAdminUpdateBadge(0); clearSessionState(); closePreview({ force: true }); closeSidebar(); await initAuth(); } // ─────────────────────────────────────────────────────────────────────────── // NAVIGATION // ─────────────────────────────────────────────────────────────────────────── async function loadRoots (opts = {}) { const data = await api('GET', '/files/roots'); if (!data) return; STATE.roots = data.roots; const preferredDir = opts.preferredDir || data.lastDir || null; const preferredRootPath = opts.preferredRootPath || null; const historyMode = opts.historyMode || 'replace'; if (preferredDir) { const preferredRoot = preferredRootPath ? STATE.roots.find(r => samePath(r.path, preferredRootPath)) : STATE.roots.find(r => pathInside(preferredDir, r.path)); if (preferredRoot && pathInside(preferredDir, preferredRoot.path)) { try { await navigateTo(preferredDir, preferredRoot, { keepSidebar: true, historyMode }); return; } catch { // Fall back to default root behavior. } } } if (STATE.roots.length === 1) { // Single root → open it directly await navigateTo(STATE.roots[0].path, STATE.roots[0], { historyMode }); } else { renderRootsView({ historyMode }); } } function renderRootsView (opts = {}) { if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return; disconnectThumbnailObserver(); disconnectFolderIconObserver(); revokeThumbnails(); STATE.currentDir = null; STATE.currentRoot = null; STATE.searchQuery = null; saveSessionState(); renderBreadcrumb(); const grid = document.getElementById('file-grid'); grid.innerHTML = ''; document.getElementById('empty-notice').classList.add('hidden'); document.getElementById('folder-stats').classList.add('hidden'); closeSidebar(); for (const root of STATE.roots) { const el = makeFileItem({ name: root.label, isDir: true, path: root.path, _root: root }); grid.appendChild(el); } if (opts.historyMode !== 'skip') { recordNavigationEntry(makeNavEntryForRoots(), opts.historyMode || 'push'); } loadThumbnails(); } async function navigateTo (absPath, root, opts = {}) { STATE.searchQuery = null; if (root) STATE.currentRoot = root; STATE.currentDir = absPath; const data = await api('GET', `/files/list?dir=${encodeURIComponent(absPath)}`); if (!data) return; STATE.items = data.items; saveSessionState(); renderBreadcrumb(); renderFileGrid(); await refreshFolderStats(); closeSidebar(); if (opts.historyMode !== 'skip') { recordNavigationEntry(makeNavEntryForDir(absPath, STATE.currentRoot && STATE.currentRoot.path), opts.historyMode || 'push'); } } async function runGlobalFileSearch () { const input = document.getElementById('top-search-input'); if (!input) return; const query = String(input.value || '').trim(); if (!query) { toast('Enter a search term first.', 'err'); return; } let data; try { data = await api('GET', `/files/search?query=${encodeURIComponent(query)}&limit=250`); } catch (err) { toast('Search failed: ' + err.message, 'err'); return; } STATE.searchQuery = query; STATE.currentDir = null; STATE.currentRoot = null; STATE.items = Array.isArray(data && data.results) ? data.results.map((it) => ({ name: it.name, path: it.path, dir: it.dir, isDir: false, size: it.size, mtime: it.mtime, })) : []; renderBreadcrumb(); renderFileGrid(); closeSidebar(); const stats = document.getElementById('folder-stats'); if (stats) { const n = STATE.items.length; stats.textContent = n === 1 ? `1 file found for "${query}".` : `${n} files found for "${query}".`; stats.classList.remove('hidden'); } } function renderBreadcrumb () { if (typeof document === 'undefined') return; const nav = document.getElementById('breadcrumb'); if (!nav) return; nav.innerHTML = ''; // "Home" crumb const home = document.createElement('span'); home.className = 'crumb' + (STATE.currentDir == null ? ' active' : ''); home.textContent = 'Home'; home.addEventListener('click', () => { if (STATE.roots.length === 1) { navigateTo(STATE.roots[0].path, STATE.roots[0]); } else { renderRootsView(); } }); nav.appendChild(home); if (STATE.searchQuery) { const sep = document.createElement('span'); sep.className = 'sep'; sep.textContent = ' / '; nav.appendChild(sep); const searchCrumb = document.createElement('span'); searchCrumb.className = 'crumb active'; searchCrumb.textContent = `Search: ${STATE.searchQuery}`; nav.appendChild(searchCrumb); return; } if (!STATE.currentDir || !STATE.currentRoot) return; // Build path segments relative to the root. const rootPath = STATE.currentRoot.path; const relative = relativePathFromRoot(STATE.currentDir, rootPath); const segments = relative === '.' ? [] : relative.split(/[\\/]/).filter(Boolean); const parts = [STATE.currentRoot.label, ...segments]; for (let i = 0; i < parts.length; i++) { const sep = document.createElement('span'); sep.className = 'sep'; sep.textContent = ' / '; nav.appendChild(sep); const crumb = document.createElement('span'); crumb.className = 'crumb' + (i === parts.length - 1 ? ' active' : ''); crumb.textContent = parts[i]; // Root crumb points to rootPath; segment crumbs point to their folder. const capturedPath = i === 0 ? rootPath : joinServerPath(rootPath, segments.slice(0, i).join('/')); crumb.classList.add('crumb-drop-target'); crumb.dataset.path = capturedPath; if (i < parts.length - 1) { crumb.addEventListener('click', () => navigateTo(capturedPath, STATE.currentRoot)); } nav.appendChild(crumb); } } async function refreshFolderStats () { if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return; const el = document.getElementById('folder-stats'); if (!STATE.currentDir || STATE.searchQuery) { el.classList.add('hidden'); return; } const data = await api('GET', `/files/space?dir=${encodeURIComponent(STATE.currentDir)}`).catch(() => null); if (!data) { el.classList.add('hidden'); return; } const used = formatBytes(data.usedBytes); if (data.userFreeBytes != null) { el.textContent = `Folder usage: ${used} | Free space remaining: ${formatBytes(data.userFreeBytes)}`; } else { const free = data.freeBytes == null ? 'unknown' : formatBytes(data.freeBytes); el.textContent = `Folder usage: ${used} | Free on disk: ${free}`; } el.classList.remove('hidden'); } function itemsSignature (items) { return JSON.stringify( (items || []).map(it => [it.path, it.mtime, it.uploadedAt, it.size, it.isDir]) .sort((a, b) => String(a[0]).localeCompare(String(b[0]))), ); } async function incrementalRefreshCurrentDir () { if (STATE.previewExpandState) return; if (STATE.searchQuery) return; if (!STATE.currentDir || STATE.uploadInProgress) return; const data = await api('GET', `/files/list?dir=${encodeURIComponent(STATE.currentDir)}`).catch(() => null); if (!data) return; const oldSig = itemsSignature(STATE.items); const newSig = itemsSignature(data.items); if (oldSig !== newSig) { const selectedPath = STATE.selectedItem ? STATE.selectedItem.path : null; STATE.items = data.items; renderFileGrid(); if (selectedPath) { const match = STATE.items.find(i => i.path === selectedPath); if (match) { const selectedEl = Array.from(document.querySelectorAll('.file-item')) .find(el => el.dataset.path === selectedPath); if (selectedEl) selectItem(selectedEl, match); } else { closeSidebar(); } } } else { loadThumbnails(); void loadWatchedStatusesForCurrentDir(); } await refreshFolderStats(); } function startAutoRefresh () { stopAutoRefresh(); STATE.autoRefreshTimer = setInterval(() => { if (document.hidden) return; incrementalRefreshCurrentDir(); }, 5000); } function stopAutoRefresh () { if (STATE.autoRefreshTimer) { clearInterval(STATE.autoRefreshTimer); STATE.autoRefreshTimer = null; } } // ─────────────────────────────────────────────────────────────────────────── // FILE GRID RENDERING // ─────────────────────────────────────────────────────────────────────────── function parseItemTimestampMs (value) { if (value == null || value === '') return null; const asNumber = Number(value); if (Number.isFinite(asNumber) && asNumber > 0) return asNumber; const asDate = Date.parse(String(value)); return Number.isFinite(asDate) ? asDate : null; } function dayStartMsFromTimestamp (value) { const ts = parseItemTimestampMs(value); if (!Number.isFinite(ts)) return null; const d = new Date(ts); return new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime(); } function dayCountWord (count) { const words = { 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', }; return words[count] || String(count); } function groupDateLabel (dayStartMs) { if (!Number.isFinite(dayStartMs)) return 'Unknown date'; const now = new Date(); const todayStartMs = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime(); const diffDays = Math.floor((todayStartMs - dayStartMs) / (24 * 60 * 60 * 1000)); if (diffDays === 0) return 'today'; if (diffDays === 1) return 'yesterday'; if (diffDays >= 2 && diffDays <= 6) return `${dayCountWord(diffDays)} days ago`; if (diffDays === 7) return 'one week ago'; return new Date(dayStartMs).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric', }); } function itemFileTypeLabel (item) { if (item.isDir) return 'Folder'; const ext = extOf(item.name); return ext ? `.${ext}` : 'No extension'; } function itemAlphabeticalGroupLabel (item) { const first = String(item.name || '').trim().charAt(0).toUpperCase(); if (!first) return '#'; return /[A-Z0-9]/.test(first) ? first : '#'; } function itemSizeGroupInfo (item) { if (item.isDir) return { id: 'folder', label: 'Folder', rank: -1 }; const size = Number(item.size); if (!Number.isFinite(size) || size < 0) return { id: 'unknown', label: 'Unknown size', rank: 999 }; if (size === 0) return { id: 'empty', label: 'Empty', rank: 0 }; if (size < (1024 * 1024)) return { id: 'small', label: 'Smaller than 1 MB', rank: 1 }; if (size < (100 * 1024 * 1024)) return { id: 'medium', label: '1 MB to 100 MB', rank: 2 }; if (size < (1024 * 1024 * 1024)) return { id: 'large', label: '100 MB to 1 GB', rank: 3 }; return { id: 'huge', label: 'Larger than 1 GB', rank: 4 }; } function itemGroupInfo (item, groupBy) { if (groupBy === 'alphabetical') { const label = itemAlphabeticalGroupLabel(item); return { id: `alpha:${label}`, label, rank: label.charCodeAt(0) || 999 }; } if (groupBy === 'fileType') { const label = itemFileTypeLabel(item); return { id: `type:${label.toLowerCase()}`, label, rank: 0 }; } if (groupBy === 'lastChangedDate') { const dayStart = dayStartMsFromTimestamp(item.mtime); return { id: `mtime:${dayStart == null ? 'unknown' : dayStart}`, label: groupDateLabel(dayStart), rank: dayStart == null ? Number.NEGATIVE_INFINITY : dayStart, }; } if (groupBy === 'timeUploadedDate') { const dayStart = dayStartMsFromTimestamp(item.uploadedAt != null ? item.uploadedAt : item.mtime); return { id: `uploaded:${dayStart == null ? 'unknown' : dayStart}`, label: groupDateLabel(dayStart), rank: dayStart == null ? Number.NEGATIVE_INFINITY : dayStart, }; } if (groupBy === 'size') { const sizeGroup = itemSizeGroupInfo(item); return { id: `size:${sizeGroup.id}`, label: sizeGroup.label, rank: sizeGroup.rank, }; } return { id: 'none', label: '', rank: 0 }; } function compareText (a, b) { return String(a || '').localeCompare(String(b || ''), undefined, { numeric: true, sensitivity: 'base' }); } function compareNullableNumber (a, b, ascending) { const hasA = Number.isFinite(a); const hasB = Number.isFinite(b); if (!hasA && !hasB) return 0; if (!hasA) return 1; if (!hasB) return -1; const diff = a - b; return ascending ? diff : -diff; } function compareBySortMode (a, b, sortBy, ascending) { if (sortBy === 'fileType') { const extA = itemFileTypeLabel(a.item).toLowerCase(); const extB = itemFileTypeLabel(b.item).toLowerCase(); const byType = compareText(extA, extB); if (byType !== 0) return ascending ? byType : -byType; const byName = compareText(a.item.name, b.item.name); return ascending ? byName : -byName; } if (sortBy === 'lastChanged') { return compareNullableNumber(parseItemTimestampMs(a.item.mtime), parseItemTimestampMs(b.item.mtime), ascending); } if (sortBy === 'timeUploaded') { const uploadedA = parseItemTimestampMs(a.item.uploadedAt != null ? a.item.uploadedAt : a.item.mtime); const uploadedB = parseItemTimestampMs(b.item.uploadedAt != null ? b.item.uploadedAt : b.item.mtime); return compareNullableNumber(uploadedA, uploadedB, ascending); } if (sortBy === 'size') { const sizeA = Number.isFinite(Number(a.item.size)) ? Number(a.item.size) : null; const sizeB = Number.isFinite(Number(b.item.size)) ? Number(b.item.size) : null; return compareNullableNumber(sizeA, sizeB, ascending); } const byName = compareText(a.item.name, b.item.name); return ascending ? byName : -byName; } function buildFileGridRows (items, prefs) { const list = Array.isArray(items) ? items : []; const groupBy = prefs.groupBy || 'none'; const sortBy = prefs.sortBy || 'alphabetical'; const descriptors = list.map((item) => ({ item, group: itemGroupInfo(item, groupBy), })); descriptors.sort((a, b) => { if (groupBy !== 'none') { const dateGrouping = groupBy === 'lastChangedDate' || groupBy === 'timeUploadedDate'; if (a.group.rank !== b.group.rank) { const byRank = dateGrouping ? (b.group.rank - a.group.rank) : (a.group.rank - b.group.rank); if (byRank !== 0) return byRank; } const byGroupLabel = compareText(a.group.label, b.group.label); if (byGroupLabel !== 0) return dateGrouping ? byGroupLabel : (prefs.ascending ? byGroupLabel : -byGroupLabel); } if (prefs.foldersFirst && a.item.isDir !== b.item.isDir) { return a.item.isDir ? -1 : 1; } const bySort = compareBySortMode(a, b, sortBy, !!prefs.ascending); if (bySort !== 0) return bySort; return compareText(a.item.name, b.item.name); }); const rows = []; let previousGroupId = null; for (const descriptor of descriptors) { if (groupBy !== 'none' && descriptor.group.id !== previousGroupId) { rows.push({ type: 'group', label: descriptor.group.label }); previousGroupId = descriptor.group.id; } rows.push({ type: 'item', item: descriptor.item }); } return rows; } function makeGroupSeparator (label) { const el = document.createElement('div'); el.className = 'file-group-separator'; const text = document.createElement('span'); text.textContent = String(label || 'Other'); el.appendChild(text); return el; } function renderFileItemName (targetEl, fileName) { if (!targetEl) return; const rawName = String(fileName || ''); targetEl.textContent = ''; if (!rawName) return; const segments = rawName.split(/([\-.,])/); for (const segment of segments) { if (!segment) continue; targetEl.appendChild(document.createTextNode(segment)); if (segment === '-' || segment === ',' || segment === '.') { targetEl.appendChild(document.createElement('wbr')); } } } function renderFileGrid () { if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return; disconnectThumbnailObserver(); disconnectFolderIconObserver(); revokeThumbnails(); const grid = document.getElementById('file-grid'); grid.innerHTML = ''; const empty = document.getElementById('empty-notice'); const prefs = (!STATE.searchQuery && STATE.currentDir) ? folderViewPrefsForDir(STATE.currentDir) : { ...DEFAULT_FOLDER_VIEW_PREFS }; const rows = buildFileGridRows(STATE.items, prefs); empty.classList.toggle('hidden', STATE.items.length > 0); for (const row of rows) { if (row.type === 'group') { grid.appendChild(makeGroupSeparator(row.label)); continue; } grid.appendChild(makeFileItem(row.item)); } loadThumbnails(); void loadWatchedStatusesForCurrentDir(); } function makeFileItem (item) { const el = document.createElement('div'); el.className = 'file-item'; el.dataset.path = item.path; if (item.isDir) el.dataset.isdir = '1'; const icon = document.createElement('div'); icon.className = 'icon'; icon.innerHTML = item.isDir ? iconFolder() : iconFile(item.name); if (!item.isDir) { icon.dataset.previewPath = item.path; renderWatchedOverlayOnIcon(icon, watchStatusForTile(item)); } else { icon.dataset.folderPath = item.path; } el.appendChild(icon); const name = document.createElement('div'); name.className = 'name'; renderFileItemName(name, item.name); el.appendChild(name); if (!item._root) makeDraggable(el, item); attachMobileLongPress(el, item); el.addEventListener('contextmenu', (e) => { e.preventDefault(); e.stopPropagation(); if (isMobileViewport()) return; if (el.classList.contains('file-item--preview')) return; document.querySelectorAll('.file-item.selected').forEach(node => node.classList.remove('selected')); el.classList.add('selected'); STATE.selectedItem = item; openItemContextMenu(item, e.clientX, e.clientY); }); // Single-click: open sidebar el.addEventListener('click', (e) => { e.stopPropagation(); closeCustomContextMenu(); if (el.classList.contains('file-item--preview')) return; if (isMobileViewport()) { if (el.dataset.longPressTriggered === '1') { el.dataset.longPressTriggered = '0'; return; } if (item.isDir) { navigateTo(item.path, item._root || STATE.currentRoot); } else { downloadOrView(item, icon.querySelector('svg')); } return; } selectItem(el, item); }); // Double-click: enter folder or view/download file el.addEventListener('dblclick', (e) => { e.stopPropagation(); if (el.classList.contains('file-item--preview')) return; if (item.isDir) { navigateTo(item.path, item._root || STATE.currentRoot); } else { downloadOrView(item, icon.querySelector('svg')); } }); return el; } function attachMobileLongPress (el, item) { if (item._root) return; let pressTimer = null; let startX = 0; let startY = 0; function clearPress () { if (!pressTimer) return; clearTimeout(pressTimer); pressTimer = null; } function cancelPress () { clearPress(); } el.addEventListener('pointerdown', (e) => { if (!isMobileViewport()) return; if (e.button !== undefined && e.button !== 0) return; if (e.pointerType && e.pointerType === 'mouse') return; startX = e.clientX; startY = e.clientY; clearPress(); pressTimer = setTimeout(() => { pressTimer = null; el.dataset.longPressTriggered = '1'; selectItem(el, item); }, MOBILE_LONG_PRESS_MS); }); el.addEventListener('pointermove', (e) => { if (!pressTimer) return; if (Math.hypot(e.clientX - startX, e.clientY - startY) > MOBILE_LONG_PRESS_MOVE_THRESHOLD) { clearPress(); } }); el.addEventListener('pointerup', cancelPress); el.addEventListener('pointercancel', cancelPress); el.addEventListener('pointerleave', cancelPress); } function selectItem (el, item) { document.querySelectorAll('.file-item.selected').forEach(e => e.classList.remove('selected')); el.classList.add('selected'); STATE.selectedItem = item; openSidebar(item); } function isAbortError (err) { if (!err) return false; return err.name === 'AbortError' || /abort/i.test(String(err.message || '')); } function beginSidebarLoad () { if (STATE.sidebarAbortController && typeof STATE.sidebarAbortController.abort === 'function') { try { STATE.sidebarAbortController.abort(); } catch { /* ignore */ } } STATE.sidebarLoadId += 1; STATE.sidebarAbortController = null; return { id: STATE.sidebarLoadId, }; } function isSidebarLoadStale (item, sidebarLoadId) { if (sidebarLoadId !== STATE.sidebarLoadId) return true; if (!STATE.selectedItem) return true; return STATE.selectedItem !== item && STATE.selectedItem.path !== item.path; } // ─────────────────────────────────────────────────────────────────────────── // SIDEBAR // ─────────────────────────────────────────────────────────────────────────── /** * Renders (or clears) the duplicates panel at the bottom of the sidebar. * @param {object|null} item — the item whose duplicates are shown; null = clear * @param {Array|null} duplicates — array of {path, name, dir, relativePath}; null = loading state */ function renderSidebarDuplicates (item, duplicates) { if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return; const panel = document.getElementById('sidebar-duplicates'); if (!panel) return; // Clear / hide when no item or no duplicates. if (!item || (Array.isArray(duplicates) && duplicates.length === 0)) { panel.classList.add('hidden'); panel.innerHTML = ''; return; } // Loading state. if (duplicates === null) { panel.classList.add('hidden'); panel.innerHTML = ''; return; } panel.innerHTML = ''; const heading = document.createElement('p'); heading.className = 'sidebar-duplicates-heading'; heading.textContent = `Duplicates (${duplicates.length})`; panel.appendChild(heading); const list = document.createElement('ul'); list.className = 'sidebar-duplicates-list'; for (const dup of duplicates) { const li = document.createElement('li'); const btn = document.createElement('button'); btn.className = 'sidebar-duplicate-entry'; btn.title = dup.path; // Show path relative to its root; keep absolute path in the tooltip. btn.textContent = dup.relativePath || dup.path; btn.addEventListener('click', () => navigateToDuplicate(dup)); li.appendChild(btn); list.appendChild(li); } panel.appendChild(list); panel.classList.remove('hidden'); } /** * Navigates to the folder containing a duplicate file and then auto-opens it. * @param {{ path: string, name: string, dir: string }} dup */ async function navigateToDuplicate (dup) { // If the duplicate lives in the folder already shown, just select it. if (STATE.currentDir && samePath(dup.dir, STATE.currentDir)) { const tile = Array.from(document.querySelectorAll('.file-item')) .find((el) => el.dataset.path === dup.path); const dupItem = STATE.items.find((i) => i.path === dup.path); if (tile && dupItem) { selectItem(tile, dupItem); } return; } // Find the root that contains the duplicate. const root = STATE.roots.find( (r) => dup.dir === r.path || dup.dir.startsWith(r.path + '/') || dup.dir.startsWith(r.path + '\\'), ); if (!root) { toast('Cannot navigate to duplicate: root not accessible.', 'err'); return; } await navigateTo(dup.dir, root); // After navigation, find and select the file tile to open it. const tile = Array.from(document.querySelectorAll('.file-item')) .find((el) => el.dataset.path === dup.path); const dupItem = STATE.items.find((i) => i.path === dup.path); if (tile && dupItem) { selectItem(tile, dupItem); } } function renderItemActionButtons (actions, item) { if (!actions || !item) return; actions.innerHTML = ''; if (!item.isDir) { const btnDl = document.createElement('button'); btnDl.textContent = 'View / Download'; btnDl.addEventListener('click', () => { const tile = Array.from(document.querySelectorAll('.file-item')).find(node => node.dataset.path === item.path); const source = (tile ? tile.querySelector('.icon svg') : null) || document.querySelector('#sidebar-icon svg'); downloadOrView(item, source); }); actions.appendChild(btnDl); const btnShareFile = document.createElement('button'); btnShareFile.textContent = 'Share'; btnShareFile.addEventListener('click', () => openShareModal(item)); actions.appendChild(btnShareFile); } else { const btnOpen = document.createElement('button'); btnOpen.textContent = 'Open folder'; btnOpen.addEventListener('click', () => navigateTo(item.path, item._root || STATE.currentRoot)); actions.appendChild(btnOpen); const btnZip = document.createElement('button'); btnZip.textContent = 'Download as zip'; btnZip.addEventListener('click', () => { btnZip.disabled = true; btnZip.textContent = 'Working...'; const url = `/api/files/download-zip?dir=${encodeURIComponent(item.path)}`; const headers = { Authorization: 'Bearer ' + STATE.token, 'X-Fp': getFingerprint(), }; fetch(url, { headers }) .then(res => { if (!res.ok) throw new Error('Download mislukt'); return res.blob(); }) .then(blob => { const blobUrl = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = blobUrl; a.download = item.name + '.zip'; a.click(); setTimeout(() => URL.revokeObjectURL(blobUrl), 10000); }) .catch((err) => toast(err.message || 'Download mislukt', 'err')) .finally(() => { btnZip.disabled = false; btnZip.textContent = 'Download as zip'; }); }); actions.appendChild(btnZip); const btnShareFolder = document.createElement('button'); btnShareFolder.textContent = 'Share'; btnShareFolder.addEventListener('click', () => openShareModal(item)); actions.appendChild(btnShareFolder); } if (!canWrite(item)) return; if (item.isDir) { const btnSetIcon = document.createElement('button'); btnSetIcon.textContent = 'Set icon'; btnSetIcon.addEventListener('click', () => openFolderIconPicker(item)); actions.appendChild(btnSetIcon); } if (!item._root) { const btnMove = document.createElement('button'); btnMove.textContent = 'Move to'; btnMove.addEventListener('click', () => openMovePicker(item)); actions.appendChild(btnMove); if (!item.isDir) { const btnCopy = document.createElement('button'); btnCopy.textContent = 'Copy to'; btnCopy.addEventListener('click', () => openCopyPicker(item)); actions.appendChild(btnCopy); } } const btnRen = document.createElement('button'); btnRen.textContent = 'Rename'; btnRen.addEventListener('click', () => openRenameModal(item)); actions.appendChild(btnRen); if (!item._root) { const btnDel = document.createElement('button'); btnDel.textContent = 'Delete'; btnDel.className = 'danger'; btnDel.addEventListener('click', () => deleteItem(item)); actions.appendChild(btnDel); } } function closeCustomContextMenu () { const menu = document.getElementById('custom-context-menu'); if (!menu) return; menu.classList.add('hidden'); menu.innerHTML = ''; } function ensureCustomContextMenu () { let menu = document.getElementById('custom-context-menu'); if (menu) return menu; menu = document.createElement('div'); menu.id = 'custom-context-menu'; menu.className = 'custom-context-menu hidden'; menu.setAttribute('role', 'menu'); menu.setAttribute('aria-label', 'Context menu'); menu.addEventListener('click', (e) => e.stopPropagation()); document.body.appendChild(menu); return menu; } function openCustomContextMenuAt (x, y, build) { const menu = ensureCustomContextMenu(); menu.innerHTML = ''; build(menu); if (!menu.childElementCount) { closeCustomContextMenu(); return; } menu.classList.remove('hidden'); menu.style.left = '0px'; menu.style.top = '0px'; const maxLeft = Math.max(6, window.innerWidth - menu.offsetWidth - 6); const maxTop = Math.max(6, window.innerHeight - menu.offsetHeight - 6); menu.style.left = `${Math.min(Math.max(6, x), maxLeft)}px`; menu.style.top = `${Math.min(Math.max(6, y), maxTop)}px`; } function addContextMenuButton (menu, label, onClick, { danger = false, checked = null, hasSubmenu = false } = {}) { const btn = document.createElement('button'); btn.type = 'button'; btn.className = 'custom-context-menu-item'; if (danger) btn.classList.add('danger'); if (checked !== null) btn.classList.add('custom-context-menu-item--check'); if (hasSubmenu) btn.classList.add('custom-context-menu-item--submenu'); const labelEl = document.createElement('span'); if (checked === true) labelEl.textContent = '✓ ' + label; else if (checked === false) labelEl.textContent = '□ ' + label; else labelEl.textContent = label; btn.appendChild(labelEl); if (hasSubmenu) { const arrow = document.createElement('span'); arrow.textContent = '›'; btn.appendChild(arrow); } btn.addEventListener('click', async (e) => { e.stopPropagation(); await onClick(); closeCustomContextMenu(); }); menu.appendChild(btn); return btn; } function addContextMenuSeparator (menu) { const sep = document.createElement('div'); sep.className = 'custom-context-menu-separator'; menu.appendChild(sep); } function addContextMenuSubmenu (menu, label, options) { const row = document.createElement('div'); row.className = 'custom-context-menu-row'; const trigger = addContextMenuButton(row, label, () => { }, { hasSubmenu: true }); trigger.addEventListener('click', (e) => e.preventDefault()); const panel = document.createElement('div'); panel.className = 'custom-context-submenu'; for (const option of options) { addContextMenuButton(panel, option.label, option.onClick, { checked: option.checked, }); } row.appendChild(panel); menu.appendChild(row); } function openItemContextMenu (item, x, y) { openCustomContextMenuAt(x, y, (menu) => { renderItemActionButtons(menu, item); menu.querySelectorAll('button').forEach((btn) => { if (btn.classList.contains('danger')) btn.classList.add('danger'); btn.addEventListener('click', () => closeCustomContextMenu(), { once: true }); }); }); } function openFolderContextMenu (x, y) { if (!STATE.currentDir) { closeCustomContextMenu(); return; } const prefs = folderViewPrefsForDir(STATE.currentDir); const makeOptionHandler = (patch) => async () => { saveFolderViewPrefsForDir(STATE.currentDir, patch); renderFileGrid(); }; openCustomContextMenuAt(x, y, (menu) => { if (canWrite()) { addContextMenuButton(menu, 'Create Folder', createFolderInCurrentDir); addContextMenuSeparator(menu); } addContextMenuSubmenu(menu, 'Sort by', FOLDER_SORT_OPTIONS.map((option) => ({ label: option.label, checked: prefs.sortBy === option.value, onClick: makeOptionHandler({ sortBy: option.value }), }))); addContextMenuSubmenu(menu, 'Group by', FOLDER_GROUP_OPTIONS.map((option) => ({ label: option.label, checked: prefs.groupBy === option.value, onClick: makeOptionHandler({ groupBy: option.value }), }))); addContextMenuSeparator(menu); addContextMenuButton(menu, 'Always keep folders at the top', makeOptionHandler({ foldersFirst: !prefs.foldersFirst }), { checked: !!prefs.foldersFirst, }); addContextMenuButton(menu, prefs.ascending ? 'Ascending' : 'Descending', makeOptionHandler({ ascending: !prefs.ascending }), { checked: !!prefs.ascending, }); }); } // ─────────────────────────────────────────────────────────────────────────── async function openSidebar (item) { const sidebarLoad = beginSidebarLoad(); const sidebar = document.getElementById('sidebar'); sidebar.classList.remove('hidden'); document.getElementById('app').classList.add('sidebar-open'); document.getElementById('sidebar-icon').innerHTML = item.isDir ? iconFolder(64) : iconFile(item.name, 64); if (item.isDir) { document.getElementById('sidebar-icon').dataset.folderPath = item.path; } else { delete document.getElementById('sidebar-icon').dataset.folderPath; } document.getElementById('sidebar-name').textContent = item.name; // Load metadata const dl = document.getElementById('sidebar-meta'); dl.innerHTML = '
Loading…
'; const actions = document.getElementById('sidebar-actions'); actions.innerHTML = ''; // Reset duplicates panel whenever a new item is opened. renderSidebarDuplicates(null, null); if (!item.isDir) { const meta = await api('GET', `/files/meta?file=${encodeURIComponent(item.path)}`).catch((err) => { if (isAbortError(err)) return null; throw err; }); if (isSidebarLoadStale(item, sidebarLoad.id)) return; if (meta) { const watchedBy = VIDEO_EXTS.has(extOf(item.name)) ? Object.entries(meta.watchedBy || {}) .map(([user, status]) => `${String(user)}: ${String(status)}`) .sort((a, b) => a.localeCompare(b)) : []; dl.innerHTML = `
Size
${formatBytes(meta.size)}
Modified
${new Date(meta.mtime).toLocaleString()}
Uploaded by
${meta.uploader || '—'}
Downloaded by
${meta.downloaders.join(', ') || '—'}
${VIDEO_EXTS.has(extOf(item.name)) ? `
Watched by
${watchedBy.join(', ') || '—'}
` : ''} `; } // Fetch and render duplicate files. renderSidebarDuplicates(item, null); // show loading state const selectedPathAtRequest = item.path; api('GET', `/files/duplicates?file=${encodeURIComponent(item.path)}`) .then((data) => { if (isSidebarLoadStale(item, sidebarLoad.id)) return; if (!STATE.selectedItem || STATE.selectedItem.path !== selectedPathAtRequest) return; renderSidebarDuplicates(item, data ? data.duplicates : []); }) .catch((err) => { if (isAbortError(err)) return; if (isSidebarLoadStale(item, sidebarLoad.id)) return; if (!STATE.selectedItem || STATE.selectedItem.path !== selectedPathAtRequest) return; renderSidebarDuplicates(item, []); }); } else { dl.innerHTML = `
Type
${item._root ? 'Root folder' : 'Folder'}
`; if (item._root) { dl.innerHTML += `
Alias
${item.name}
Original name
${item._root.originalName || basenameOfPath(item.path)}
`; const space = await api('GET', `/files/space?dir=${encodeURIComponent(item.path)}`).catch((err) => { if (isAbortError(err)) return null; return null; }); if (isSidebarLoadStale(item, sidebarLoad.id)) return; if (space) { const used = formatBytes(space.usedBytes); const free = space.userFreeBytes != null ? formatBytes(space.userFreeBytes) : (space.freeBytes == null ? 'unknown' : formatBytes(space.freeBytes)); const freeLabel = space.userFreeBytes != null ? 'Free space remaining' : 'Remaining'; dl.innerHTML += `
Used
${used}
${freeLabel}
${free}
`; } if (item._root.isUserFolder) { dl.innerHTML += `
Access
Private (your folder)
`; } else { const accessUsers = await fetchRootAccessList(item.path); if (isSidebarLoadStale(item, sidebarLoad.id)) return; if (accessUsers) { dl.innerHTML += `
Access
${formatRootAccessList(accessUsers)}
`; } } } } renderItemActionButtons(actions, item); if (item.isDir) { // Load folder icon thumbnail into the sidebar icon element. void loadOneFolderIcon(document.getElementById('sidebar-icon')); } } function openFolderSidebar () { beginSidebarLoad(); const sidebar = document.getElementById('sidebar'); sidebar.classList.remove('hidden'); document.getElementById('app').classList.add('sidebar-open'); document.getElementById('sidebar-icon').innerHTML = iconFolder(64); const nameEl = document.getElementById('sidebar-name'); const dl = document.getElementById('sidebar-meta'); const actions = document.getElementById('sidebar-actions'); actions.innerHTML = ''; renderSidebarDuplicates(null, null); if (!STATE.currentDir || !STATE.currentRoot) { nameEl.textContent = 'Storage Roots'; dl.innerHTML = `
Type
Root overview
Roots
${STATE.roots.length}
`; return; } const parts = String(STATE.currentDir).split(/[\\/]/).filter(Boolean); const fallback = STATE.currentRoot.label || 'Folder'; nameEl.textContent = parts.length ? parts[parts.length - 1] : fallback; const dirs = STATE.items.filter(i => i.isDir).length; const files = STATE.items.length - dirs; const displayPath = displayPathWithRootLabel(STATE.currentDir, STATE.currentRoot.path, STATE.currentRoot.label); const baseDetails = `
Path
${displayPath}
Folders
${dirs}
Files
${files}
`; dl.innerHTML = baseDetails; renderFolderViewControls(actions, STATE.currentDir); if (samePath(STATE.currentDir, STATE.currentRoot.path)) { if (STATE.currentRoot.isUserFolder) { dl.innerHTML += '
Access
Private (your folder)
'; return; } dl.innerHTML += '
Access
Loading…
'; const currentDirAtStart = STATE.currentDir; const currentRootPathAtStart = STATE.currentRoot.path; void fetchRootAccessList(currentRootPathAtStart).then((accessUsers) => { if (!accessUsers) return; if (!STATE.currentRoot) return; if (!samePath(STATE.currentDir, currentDirAtStart)) return; if (!samePath(STATE.currentRoot.path, currentRootPathAtStart)) return; dl.innerHTML = `${baseDetails}
Access
${formatRootAccessList(accessUsers)}
`; }); } } function renderFolderViewControls (actions, dirPath) { if (!actions || !dirPath) return; const prefs = folderViewPrefsForDir(dirPath); const section = document.createElement('section'); section.className = 'sidebar-view-options'; const heading = document.createElement('h3'); heading.textContent = 'View options'; section.appendChild(heading); const sortLabel = document.createElement('label'); sortLabel.className = 'sidebar-view-option-label'; sortLabel.textContent = 'Sort by'; const sortSelect = document.createElement('select'); sortSelect.className = 'sidebar-view-option-control'; sortSelect.dataset.viewOption = 'sort'; for (const option of FOLDER_SORT_OPTIONS) { const optEl = document.createElement('option'); optEl.value = option.value; optEl.textContent = option.label; sortSelect.appendChild(optEl); } sortSelect.value = prefs.sortBy; sortSelect.addEventListener('change', () => { saveFolderViewPrefsForDir(dirPath, { sortBy: sortSelect.value }); renderFileGrid(); }); sortLabel.appendChild(sortSelect); section.appendChild(sortLabel); const groupLabel = document.createElement('label'); groupLabel.className = 'sidebar-view-option-label'; groupLabel.textContent = 'Group by'; const groupSelect = document.createElement('select'); groupSelect.className = 'sidebar-view-option-control'; groupSelect.dataset.viewOption = 'group'; for (const option of FOLDER_GROUP_OPTIONS) { const optEl = document.createElement('option'); optEl.value = option.value; optEl.textContent = option.label; groupSelect.appendChild(optEl); } groupSelect.value = prefs.groupBy; groupSelect.addEventListener('change', () => { saveFolderViewPrefsForDir(dirPath, { groupBy: groupSelect.value }); renderFileGrid(); }); groupLabel.appendChild(groupSelect); section.appendChild(groupLabel); const foldersTopLabel = document.createElement('label'); foldersTopLabel.className = 'sidebar-view-toggle'; const foldersTopInput = document.createElement('input'); foldersTopInput.type = 'checkbox'; foldersTopInput.dataset.viewOption = 'folders-first'; foldersTopInput.checked = !!prefs.foldersFirst; foldersTopInput.addEventListener('change', () => { saveFolderViewPrefsForDir(dirPath, { foldersFirst: foldersTopInput.checked }); renderFileGrid(); }); const foldersTopText = document.createElement('span'); foldersTopText.textContent = 'Always keep folders at the top'; foldersTopLabel.appendChild(foldersTopInput); foldersTopLabel.appendChild(foldersTopText); section.appendChild(foldersTopLabel); const ascLabel = document.createElement('label'); ascLabel.className = 'sidebar-view-toggle'; const ascInput = document.createElement('input'); ascInput.type = 'checkbox'; ascInput.dataset.viewOption = 'ascending'; ascInput.checked = !!prefs.ascending; ascInput.addEventListener('change', () => { saveFolderViewPrefsForDir(dirPath, { ascending: ascInput.checked }); renderFileGrid(); }); const ascText = document.createElement('span'); ascText.textContent = ascInput.checked ? 'Ascending' : 'Descending'; ascInput.addEventListener('change', () => { ascText.textContent = ascInput.checked ? 'Ascending' : 'Descending'; }); ascLabel.appendChild(ascInput); ascLabel.appendChild(ascText); section.appendChild(ascLabel); actions.appendChild(section); } function closeSidebar () { if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') return; beginSidebarLoad(); document.querySelectorAll('.file-item.selected').forEach(e => e.classList.remove('selected')); STATE.selectedItem = null; if (isMobileViewport()) { hideSidebarPanel(); return; } openFolderSidebar(); } function isMobileViewport () { return window.matchMedia(MOBILE_BREAKPOINT_QUERY).matches; } function hideSidebarPanel () { const sidebar = document.getElementById('sidebar'); const app = document.getElementById('app'); sidebar.classList.add('hidden'); app.classList.remove('sidebar-open'); } function basenameOfPath (p) { const parts = String(p || '').split(/[\\/]/).filter(Boolean); return parts.length ? parts[parts.length - 1] : String(p || ''); } async function fetchRootAccessList (rootPath) { if (!rootPath) return null; const data = await api('GET', `/files/root-access?rootPath=${encodeURIComponent(rootPath)}`).catch((err) => { if (isAbortError(err)) return null; return null; }); if (!data || !Array.isArray(data.users)) return null; return data.users; } function formatRootAccessList (users) { if (!Array.isArray(users) || users.length === 0) return 'No users'; const sorted = [...users].sort((a, b) => { const modeRank = (mode) => mode === 'R+W' ? 0 : 1; const byMode = modeRank(a.mode) - modeRank(b.mode); if (byMode !== 0) return byMode; return String(a.username).localeCompare(String(b.username)); }); const items = sorted .map((u) => `
  • ${escapeHtml(String(u.username || ''))} ${escapeHtml(String(u.mode || 'R'))}
  • `) .join(''); return ``; } function rootPermissionLabel (root) { if (root && root.isUserFolder) return 'My Folder'; return (root && (root.originalName || root.label)) || ''; } function resolveRootForPath (targetPath) { if (!targetPath) return null; return STATE.roots.find((r) => samePath(targetPath, r.path) || pathInside(targetPath, r.path)) || null; } function writableRoots () { if (STATE.isAdmin) return STATE.roots.slice(); return STATE.roots.filter((r) => { if (r.isUserFolder) return true; const perm = STATE.permissions[rootPermissionLabel(r)]; return !!(perm && perm.write); }); } async function moveWithConflictResolution (item, targetDir) { try { return await api('POST', '/files/move', { from: item.path, toDir: targetDir }); } catch (err) { if (!/already exists/i.test(err.message || '')) throw err; const existingNames = await listDirNameSet(targetDir); const desiredName = item.name || basenameOfPath(item.path) || 'file'; const suggestedName = nextAvailableName(desiredName, existingNames); const decision = await showFileConflictChoice(desiredName, suggestedName, 'move'); if (decision === 'cancel') return null; if (decision === 'overwrite') { return api('POST', '/files/move', { from: item.path, toDir: targetDir, conflict: 'overwrite', }); } return api('POST', '/files/move', { from: item.path, toDir: targetDir, conflict: 'rename', targetName: suggestedName, }); } } async function copyWithConflictResolution (item, targetDir) { try { return await api('POST', '/files/copy', { from: item.path, toDir: targetDir }); } catch (err) { if (!/already exists/i.test(err.message || '')) throw err; const existingNames = await listDirNameSet(targetDir); const desiredName = item.name || basenameOfPath(item.path) || 'file'; const suggestedName = nextAvailableName(desiredName, existingNames); const decision = await showFileConflictChoice(desiredName, suggestedName, 'copy'); if (decision === 'cancel') return null; if (decision === 'overwrite') { return api('POST', '/files/copy', { from: item.path, toDir: targetDir, conflict: 'overwrite', }); } return api('POST', '/files/copy', { from: item.path, toDir: targetDir, conflict: 'rename', targetName: suggestedName, }); } } function ensureMoveModal () { let overlay = document.getElementById('move-modal'); if (overlay) return overlay; overlay = document.createElement('div'); overlay.id = 'move-modal'; overlay.className = 'modal-overlay hidden'; overlay.innerHTML = ` `; document.body.appendChild(overlay); const closeBtn = overlay.querySelector('#move-modal-close'); const cancelBtn = overlay.querySelector('#move-modal-cancel'); const confirmBtn = overlay.querySelector('#move-modal-confirm'); function hide () { overlay.classList.add('hidden'); STATE.movePicker = null; } closeBtn.addEventListener('click', hide); cancelBtn.addEventListener('click', hide); overlay.addEventListener('click', (e) => { if (e.target === overlay) hide(); }); confirmBtn.addEventListener('click', async () => { const st = STATE.movePicker; if (!st || !st.item || !st.selectedPath) { toast('Select a destination folder first.', 'err'); return; } try { if (st.mode === 'copy') { const copied = await copyWithConflictResolution(st.item, st.selectedPath); if (!copied) return; } else { const moved = await moveWithConflictResolution(st.item, st.selectedPath); if (!moved) return; } } catch (err) { const action = st.mode === 'copy' ? 'Copy' : 'Move'; toast(`${action} failed: ${err.message}`, 'err'); return; } hide(); if (st.mode !== 'copy' && STATE.selectedItem && STATE.selectedItem.path === st.item.path) closeSidebar(); navigateTo(STATE.currentDir, STATE.currentRoot); }); return overlay; } function setMoveSelection (path, buttonEl) { if (!STATE.movePicker) return; STATE.movePicker.selectedPath = path; document.querySelectorAll('.move-node-label.selected').forEach((el) => el.classList.remove('selected')); if (buttonEl) buttonEl.classList.add('selected'); const selectedEl = document.getElementById('move-selected'); selectedEl.textContent = path ? `Destination: ${path}` : 'Destination: none'; } async function loadMoveChildren (containerEl, dirPath) { if (containerEl.dataset.loaded === '1') return; containerEl.dataset.loaded = '1'; const data = await api('GET', `/files/list?dir=${encodeURIComponent(dirPath)}`).catch(() => null); const folders = data ? data.items.filter((it) => it.isDir).sort((a, b) => a.name.localeCompare(b.name)) : []; if (!folders.length) { const empty = document.createElement('div'); empty.className = 'move-empty'; empty.textContent = 'No subfolders'; containerEl.appendChild(empty); return; } for (const child of folders) { containerEl.appendChild(createMoveNode(child.path, child.name)); } } function createMoveNode (folderPath, label) { const node = document.createElement('div'); node.className = 'move-node'; const row = document.createElement('div'); row.className = 'move-node-row'; const toggle = document.createElement('button'); toggle.type = 'button'; toggle.className = 'move-toggle'; toggle.textContent = '▸'; const selectBtn = document.createElement('button'); selectBtn.type = 'button'; selectBtn.className = 'move-node-label'; selectBtn.textContent = label; selectBtn.addEventListener('click', () => setMoveSelection(folderPath, selectBtn)); const children = document.createElement('div'); children.className = 'move-children hidden'; toggle.addEventListener('click', async () => { if (children.classList.contains('hidden')) { await loadMoveChildren(children, folderPath); children.classList.remove('hidden'); toggle.textContent = '▾'; } else { children.classList.add('hidden'); toggle.textContent = '▸'; } }); row.appendChild(toggle); row.appendChild(selectBtn); node.appendChild(row); node.appendChild(children); return node; } function openDestinationPicker (item, mode) { if (!canWrite()) { toast('No write access.', 'err'); return; } const roots = writableRoots(); if (!roots.length) { toast('No writable destination roots available.', 'err'); return; } const overlay = ensureMoveModal(); const tree = overlay.querySelector('#move-tree'); const caption = overlay.querySelector('#move-modal-caption'); const titleEl = overlay.querySelector('h2'); const confirmBtn = overlay.querySelector('#move-modal-confirm'); const op = mode === 'copy' ? 'copy' : 'move'; STATE.movePicker = { item, selectedPath: null, mode: op }; titleEl.textContent = op === 'copy' ? 'Copy To' : 'Move To'; confirmBtn.textContent = op === 'copy' ? 'Copy' : 'Move'; caption.textContent = `Select destination folder for: ${item.name}`; tree.innerHTML = ''; for (const root of roots) { tree.appendChild(createMoveNode(root.path, root.label)); } setMoveSelection(null, null); overlay.classList.remove('hidden'); } function openMovePicker (item) { openDestinationPicker(item, 'move'); } function openCopyPicker (item) { openDestinationPicker(item, 'copy'); } // ─────────────────────────────────────────────────────────────────────────── // FOLDER ICON PICKER // ─────────────────────────────────────────────────────────────────────────── function globalFaviconFallbackMarkup () { return iconFile('favicon.png', 18); } function applyGlobalFaviconPreview (hasFavicon) { if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return; const preview = document.getElementById('global-favicon-preview'); if (!preview) return; if (!hasFavicon) { preview.innerHTML = globalFaviconFallbackMarkup(); return; } const img = document.createElement('img'); img.alt = 'Current favicon'; img.src = `/api/files/global-favicon-image?v=${STATE.faviconVersion}`; img.addEventListener('error', () => { preview.innerHTML = globalFaviconFallbackMarkup(); }, { once: true }); preview.innerHTML = ''; preview.appendChild(img); } function applyGlobalFaviconLink (hasFavicon) { if (typeof document === 'undefined' || typeof document.getElementById !== 'function' || !document.head) return; let link = document.getElementById('global-favicon-link'); if (!link) { link = document.createElement('link'); link.id = 'global-favicon-link'; link.rel = 'icon'; document.head.appendChild(link); } if (!hasFavicon) { link.removeAttribute('href'); return; } link.href = `/api/files/global-favicon-image?v=${STATE.faviconVersion}`; } async function refreshGlobalFavicon () { const data = await api('GET', '/files/global-favicon').catch(() => null); const hasFavicon = !!(data && data.favicon && data.favicon.filePath); applyGlobalFaviconPreview(hasFavicon); applyGlobalFaviconLink(hasFavicon); } async function openIconPickerModal ({ dirPath, titleText, subtitleText, emptyText, confirmLabel, clearLabel, onSelect, onClear, }) { if (!dirPath) { toast('Open a folder first.', 'err'); return; } const data = await api('GET', `/files/folder-images?dir=${encodeURIComponent(dirPath)}`).catch(() => null); const images = data ? data.images : []; const existingIconOverlay = document.getElementById('folder-icon-picker'); if (existingIconOverlay) existingIconOverlay.remove(); const overlay = document.createElement('div'); overlay.id = 'folder-icon-picker'; overlay.className = 'modal-overlay'; const modal = document.createElement('div'); modal.className = 'modal folder-icon-modal'; const closeBtn = document.createElement('button'); closeBtn.className = 'modal-close'; closeBtn.setAttribute('aria-label', 'Close'); closeBtn.textContent = '✕'; const title = document.createElement('h2'); title.textContent = titleText; const filterInput = document.createElement('input'); filterInput.type = 'text'; filterInput.className = 'folder-icon-filter'; filterInput.placeholder = 'Search icons'; filterInput.setAttribute('aria-label', 'Search icons'); const subtitle = document.createElement('p'); subtitle.className = 'muted'; subtitle.textContent = images.length ? subtitleText : emptyText; const grid = document.createElement('div'); grid.className = 'folder-icon-grid'; for (const { filePath } of images) { const name = filePath.split('/').pop(); const cell = document.createElement('div'); cell.className = 'folder-icon-cell'; cell.dataset.path = filePath; cell.dataset.name = String(name || '').toLowerCase(); const imgEl = document.createElement('img'); imgEl.alt = name; imgEl.className = 'folder-icon-thumb'; imgEl.dataset.src = filePath; const label = document.createElement('div'); label.className = 'folder-icon-label'; label.textContent = name; cell.appendChild(imgEl); cell.appendChild(label); cell.addEventListener('click', () => { grid.querySelectorAll('.folder-icon-cell.selected').forEach(el => el.classList.remove('selected')); cell.classList.add('selected'); confirmBtn.disabled = false; }); grid.appendChild(cell); } function applyFilter () { const needle = String(filterInput.value || '').trim().toLowerCase(); let visible = 0; for (const cell of grid.querySelectorAll('.folder-icon-cell')) { const name = cell.dataset.name || ''; const show = !needle || name.includes(needle); cell.classList.toggle('hidden', !show); if (show) visible += 1; } subtitle.textContent = visible ? subtitleText : 'No matching thumbnails were found.'; } filterInput.addEventListener('input', applyFilter); const dialogActions = document.createElement('div'); dialogActions.className = 'dialog-actions'; const clearBtn = document.createElement('button'); clearBtn.textContent = clearLabel; clearBtn.addEventListener('click', async () => { try { await onClear(); } catch (err) { toast('Failed to clear icon: ' + err.message, 'err'); return; } hide(); }); const cancelBtn = document.createElement('button'); cancelBtn.textContent = 'Cancel'; cancelBtn.addEventListener('click', () => hide()); const confirmBtn = document.createElement('button'); confirmBtn.className = 'primary'; confirmBtn.textContent = confirmLabel; confirmBtn.disabled = true; confirmBtn.addEventListener('click', async () => { const selected = grid.querySelector('.folder-icon-cell.selected'); if (!selected) return; try { await onSelect(selected.dataset.path); } catch (err) { toast('Failed to set icon: ' + err.message, 'err'); return; } hide(); }); dialogActions.appendChild(clearBtn); dialogActions.appendChild(cancelBtn); dialogActions.appendChild(confirmBtn); modal.appendChild(closeBtn); modal.appendChild(title); modal.appendChild(filterInput); modal.appendChild(subtitle); modal.appendChild(grid); modal.appendChild(dialogActions); overlay.appendChild(modal); document.body.appendChild(overlay); function hide () { overlay.remove(); grid.querySelectorAll('.folder-icon-thumb[src^="blob:"]').forEach((img) => { URL.revokeObjectURL(img.src); }); } closeBtn.addEventListener('click', hide); overlay.addEventListener('click', (e) => { if (e.target === overlay) hide(); }); for (const cell of grid.querySelectorAll('.folder-icon-cell')) { const imgEl = cell.querySelector('.folder-icon-thumb'); const filePath = imgEl.dataset.src; void fetch(`/api/files/thumbnail?file=${encodeURIComponent(filePath)}`, { headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() }, }).then(async (r) => { if (!r.ok || !overlay.isConnected) return; const blob = await r.blob(); const url = URL.createObjectURL(blob); imgEl.src = url; }).catch(() => { }); } filterInput.focus(); } async function openFolderIconPicker (item) { if (!canWrite(item)) { toast('No write access.', 'err'); return; } await openIconPickerModal({ dirPath: item.path, titleText: 'Set folder icon', subtitleText: 'Select a file thumbnail to use as the folder icon.', emptyText: 'No files with cached thumbnails were found inside this folder.', confirmLabel: 'Set icon', clearLabel: 'Clear icon', onSelect: async (imagePath) => { await api('POST', '/files/folder-icon', { folderPath: item.path, imagePath }); refreshAfterIconChange(item); }, onClear: async () => { await api('POST', '/files/folder-icon', { folderPath: item.path, imagePath: null }); refreshAfterIconChange(item); }, }); } async function openGlobalFaviconPicker () { if (!STATE.isAdmin) { toast('Admin access required.', 'err'); return; } const existingIconOverlay = document.getElementById('folder-icon-picker'); if (existingIconOverlay) existingIconOverlay.remove(); const overlay = document.createElement('div'); overlay.id = 'folder-icon-picker'; overlay.className = 'modal-overlay'; const modal = document.createElement('div'); modal.className = 'modal folder-icon-modal'; const closeBtn = document.createElement('button'); closeBtn.className = 'modal-close'; closeBtn.setAttribute('aria-label', 'Close'); closeBtn.textContent = '✕'; const title = document.createElement('h2'); title.textContent = 'Set global favicon'; const filterInput = document.createElement('input'); filterInput.type = 'text'; filterInput.className = 'folder-icon-filter'; filterInput.placeholder = 'Search images across all folders'; filterInput.setAttribute('aria-label', 'Search images'); const subtitle = document.createElement('p'); subtitle.className = 'muted'; subtitle.textContent = 'Type at least 2 characters to search accessible images.'; const grid = document.createElement('div'); grid.className = 'folder-icon-grid'; const dialogActions = document.createElement('div'); dialogActions.className = 'dialog-actions'; const clearBtn = document.createElement('button'); clearBtn.textContent = 'Clear favicon'; clearBtn.addEventListener('click', async () => { try { await api('POST', '/files/global-favicon', { imagePath: null }); STATE.faviconVersion = Date.now(); await refreshGlobalFavicon(); } catch (err) { toast('Failed to clear icon: ' + err.message, 'err'); return; } hide(); }); const cancelBtn = document.createElement('button'); cancelBtn.textContent = 'Cancel'; cancelBtn.addEventListener('click', () => hide()); const confirmBtn = document.createElement('button'); confirmBtn.className = 'primary'; confirmBtn.textContent = 'Set favicon'; confirmBtn.disabled = true; let selectedPath = null; let searchToken = 0; let searchTimer = null; confirmBtn.addEventListener('click', async () => { if (!selectedPath) return; try { await api('POST', '/files/global-favicon', { imagePath: selectedPath }); STATE.faviconVersion = Date.now(); await refreshGlobalFavicon(); } catch (err) { toast('Failed to set icon: ' + err.message, 'err'); return; } hide(); }); function revokeCellThumbs () { grid.querySelectorAll('.folder-icon-thumb[src^="blob:"]').forEach((img) => { URL.revokeObjectURL(img.src); }); } function renderResults (items) { selectedPath = null; confirmBtn.disabled = true; revokeCellThumbs(); grid.innerHTML = ''; for (const { path: filePath, name } of (items || [])) { const cell = document.createElement('div'); cell.className = 'folder-icon-cell'; cell.dataset.path = filePath; const imgEl = document.createElement('img'); imgEl.alt = name; imgEl.className = 'folder-icon-thumb'; const label = document.createElement('div'); label.className = 'folder-icon-label'; label.textContent = name; cell.appendChild(imgEl); cell.appendChild(label); cell.addEventListener('click', () => { grid.querySelectorAll('.folder-icon-cell.selected').forEach(el => el.classList.remove('selected')); cell.classList.add('selected'); selectedPath = filePath; confirmBtn.disabled = false; }); grid.appendChild(cell); void fetch(`/api/files/thumbnail?file=${encodeURIComponent(filePath)}`, { headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() }, }).then(async (r) => { if (!r.ok || !overlay.isConnected) return; const blob = await r.blob(); const url = URL.createObjectURL(blob); imgEl.src = url; }).catch(() => { }); } } async function runSearchNow () { const query = String(filterInput.value || '').trim(); searchToken += 1; const token = searchToken; if (query.length < 2) { subtitle.textContent = 'Type at least 2 characters to search accessible images.'; renderResults([]); return; } subtitle.textContent = 'Searching…'; const data = await api('GET', `/files/search-images?query=${encodeURIComponent(query)}&limit=80`).catch(() => null); if (!overlay.isConnected || token !== searchToken) return; const results = Array.isArray(data && data.results) ? data.results : []; renderResults(results); if (!results.length) { subtitle.textContent = 'No matching thumbnails were found.'; return; } const suffix = data && data.truncated ? ` Scanned first ${Number(data.scannedFiles) || 0} files; refine your search for more.` : ''; subtitle.textContent = `${results.length} matching image${results.length === 1 ? '' : 's'} found.${suffix}`; } filterInput.addEventListener('input', () => { if (searchTimer) clearTimeout(searchTimer); searchTimer = setTimeout(() => { void runSearchNow(); }, 240); }); dialogActions.appendChild(clearBtn); dialogActions.appendChild(cancelBtn); dialogActions.appendChild(confirmBtn); modal.appendChild(closeBtn); modal.appendChild(title); modal.appendChild(filterInput); modal.appendChild(subtitle); modal.appendChild(grid); modal.appendChild(dialogActions); overlay.appendChild(modal); document.body.appendChild(overlay); function hide () { if (searchTimer) clearTimeout(searchTimer); overlay.remove(); revokeCellThumbs(); } closeBtn.addEventListener('click', hide); overlay.addEventListener('click', (e) => { if (e.target === overlay) hide(); }); filterInput.focus(); } function refreshAfterIconChange (item) { // Reset and reload icon in grid tiles. const gridTile = Array.from(document.querySelectorAll('.icon[data-folder-path]')) .find(el => el.dataset.folderPath === item.path); if (gridTile) { const svg = gridTile.querySelector('svg'); if (svg) { // Rebuild to plain folder SVG, then reload. gridTile.innerHTML = iconFolder(); delete gridTile.dataset.thumbReady; gridTile.dataset.folderPath = item.path; void loadOneFolderIcon(gridTile); } } // Also reset the sidebar icon if it's showing the same folder. const sidebarIcon = document.getElementById('sidebar-icon'); if (sidebarIcon && sidebarIcon.dataset.folderPath === item.path) { sidebarIcon.innerHTML = iconFolder(64); delete sidebarIcon.dataset.thumbReady; void loadOneFolderIcon(sidebarIcon); } } // ─────────────────────────────────────────────────────────────────────────── // DOWNLOAD / VIEW // ─────────────────────────────────────────────────────────────────────────── function isInlinePreviewableBlob (blob, name) { const mime = String(blob.type || '').toLowerCase(); if (/^(image|video|audio)\//.test(mime)) return true; if (/^text\//.test(mime)) return true; if (mime === 'application/pdf') return true; if (mime === 'application/json') return true; if (mime === 'application/xml') return true; if (mime === 'application/javascript') return true; // Fallback by extension when MIME is missing or generic. const ext = extOf(name || ''); if (IMAGE_EXTS.has(ext) || VIDEO_EXTS.has(ext) || AUDIO_EXTS.has(ext)) return true; if (MODEL_EXTS.has(ext)) return true; if (MODEL_EXTS.has(ext)) return true; if (CODE_EXTS.has(ext)) return true; return false; } function isTextLikeBlob (blob, name) { const mime = String(blob.type || '').toLowerCase(); if (/^text\//.test(mime)) return true; if (mime === 'application/json' || mime === 'application/xml' || mime === 'application/javascript') return true; const ext = extOf(name || ''); return CODE_EXTS.has(ext); } function detectCodeLanguage (name, mime) { const ext = extOf(name || ''); const m = String(mime || '').toLowerCase(); if (m.includes('json') || ext === 'json') return 'json'; if (m.includes('xml') || ext === 'xml') return 'xml'; if (m.includes('html') || ext === 'html' || ext === 'htm') return 'html'; if (m.includes('css') || ext === 'css') return 'css'; if (m.includes('javascript') || ['js', 'jsx', 'mjs', 'cjs'].includes(ext)) return 'js'; if (m.includes('typescript') || ['ts', 'tsx'].includes(ext)) return 'ts'; if (['sh', 'bash', 'zsh'].includes(ext)) return 'sh'; if (['md', 'txt', 'log', 'ini', 'toml', 'yaml', 'yml'].includes(ext)) return 'plain'; return CODE_EXTS.has(ext) ? 'js' : 'plain'; } function prettyPrintMarkup (raw) { const src = String(raw || '') .replace(/>\s+<') .replace(/\r\n/g, '\n'); const lines = src.replace(/>\n<').split('\n'); let indent = 0; const out = []; for (const ln of lines) { const line = ln.trim(); if (!line) continue; const isClose = /^<\//.test(line); const isSelf = /\/>$/.test(line) || /^<[^!?][^>]*>[^<]*<\/[^>]+>$/.test(line); const isOpen = /^<[^!?/][^>]*>$/.test(line); if (isClose) indent = Math.max(0, indent - 1); out.push(' '.repeat(indent) + line); if (isOpen && !isSelf) indent += 1; } return out.join('\n'); } function prettyPrintBraces (raw) { const lines = String(raw || '') .replace(/\r\n/g, '\n') .split('\n'); let indent = 0; const out = []; for (const ln of lines) { const line = ln.trim(); if (!line) { out.push(''); continue; } if (/^[}\])]/.test(line)) indent = Math.max(0, indent - 1); out.push(' '.repeat(indent) + line); if (/[{[(]$/.test(line) || /[{[(]\s*(\/\/.*)?$/.test(line)) indent += 1; } return out.join('\n'); } function prettyPrintCode (raw, lang) { const text = String(raw || '').replace(/\r\n/g, '\n'); if (lang === 'json') { try { return JSON.stringify(JSON.parse(text), null, 2); } catch { return text; } } if (lang === 'xml' || lang === 'html') return prettyPrintMarkup(text); if (lang === 'js' || lang === 'ts' || lang === 'css') return prettyPrintBraces(text); return text; } function escapeHtml (s) { return String(s) .replace(/&/g, '&') .replace(//g, '>'); } function highlightCode (raw, lang) { if (lang === 'plain') return escapeHtml(raw); let html = escapeHtml(raw); const stash = []; const keep = (regex, cls) => { html = html.replace(regex, (m) => { const idx = stash.push(`${m}`) - 1; return `@@TOK${idx}@@`; }); }; if (lang === 'json') { html = html .replace(/("(?:\\.|[^"\\])*")\s*:/g, '$1:') .replace(/: ("(?:\\.|[^"\\])*")/g, ': $1') .replace(/\b(true|false|null)\b/g, '$1') .replace(/\b(-?\d+(?:\.\d+)?(?:e[+\-]?\d+)?)\b/gi, '$1'); return html; } if (lang === 'xml' || lang === 'html') { html = html .replace(/(<\/?)([a-zA-Z0-9:_-]+)/g, '$1$2') .replace(/([a-zA-Z0-9:_-]+)=("[^&]*"|"[^"]*")/g, '$1=$2'); return html; } if (lang === 'sh') keep(/(^|\s)#.*$/gm, 'comment'); else keep(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, 'comment'); keep(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`/g, 'string'); html = html .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, '$1') .replace(/\b(-?\d+(?:\.\d+)?(?:e[+\-]?\d+)?)\b/gi, '$1'); html = html.replace(/@@TOK(\d+)@@/g, (_, idx) => stash[Number(idx)] || ''); return html; } function clearPreviewObjectUrl () { STATE.previewStreamInitToken += 1; if (typeof STATE.previewCleanup === 'function') { try { STATE.previewCleanup(); } catch { /* ignore */ } } STATE.previewCleanup = null; if (!STATE.previewObjectUrl) return; if (String(STATE.previewObjectUrl).startsWith('blob:')) { URL.revokeObjectURL(STATE.previewObjectUrl); } STATE.previewObjectUrl = null; } function ensureStylesheet (id, href) { let link = document.getElementById(id); if (link) return Promise.resolve(link); link = document.createElement('link'); link.id = id; link.rel = 'stylesheet'; link.href = href; return new Promise((resolve, reject) => { link.addEventListener('load', () => resolve(link), { once: true }); link.addEventListener('error', () => reject(new Error('Failed to load video player styles.')), { once: true }); document.head.appendChild(link); }); } function ensureScript (id, src) { let script = document.getElementById(id); if (script && window.videojs) return Promise.resolve(window.videojs); if (!script) { script = document.createElement('script'); script.id = id; script.src = src; } return new Promise((resolve, reject) => { script.addEventListener('load', () => resolve(window.videojs), { once: true }); script.addEventListener('error', () => reject(new Error('Failed to load video player script.')), { once: true }); if (!script.isConnected) document.head.appendChild(script); }); } async function ensureVideoJsLoaded () { if (window.videojs) { configureVideoJsBuffering(window.videojs); return window.videojs; } if (!videoJsLoaderPromise) { videoJsLoaderPromise = Promise.all([ ensureStylesheet('videojs-styles', '/vendor/video.js/video-js.css'), ensureScript('videojs-script', '/vendor/video.js/video.min.js'), ]).then(() => { configureVideoJsBuffering(window.videojs); return window.videojs; }); } return videoJsLoaderPromise; } function configureVideoJsBuffering (videojs) { const shared = sharedVideoPlayer(); if (!shared || typeof shared.configureVideoJsBuffering !== 'function') return; shared.configureVideoJsBuffering(videojs, { enabled: VIDEO_FORWARD_BUFFER_OVERRIDE_ENABLED, seconds: VIDEO_FORWARD_BUFFER_SECONDS, }); } async function createVideoStreamSessionForItem (item) { return api('POST', '/files/video-stream', { filePath: item.path }); } async function releaseVideoStreamSession (sessionId, opts = {}) { const id = String(sessionId || '').trim(); if (!id) return; await api('DELETE', `/files/video-stream/${encodeURIComponent(id)}`, null, { keepalive: !!opts.keepalive, noAutoLogout: true, }).catch(() => null); } function releaseActivePreviewVideoStreamSession (opts = {}) { const sessionId = String(STATE.previewVideoStreamSessionId || '').trim(); if (!sessionId) return; STATE.previewVideoStreamSessionId = null; void releaseVideoStreamSession(sessionId, opts); } const SERVER_PREVIEW_IMAGE_EXTS = new Set(['heif', 'heic']); function needsServerPreviewImage (name) { return SERVER_PREVIEW_IMAGE_EXTS.has(extOf(name || '')); } function previewObjectUrlIsDownloadableOriginal (item) { if (!STATE.previewObjectUrl || !item) return false; return !needsServerPreviewImage(item.name); } async function fetchPreviewImageBlob (item) { const url = `/api/files/preview-image?file=${encodeURIComponent(item.path)}`; try { const res = await fetch(url, { headers: { Authorization: 'Bearer ' + STATE.token, 'X-Fp': getFingerprint(), }, }); if (!res.ok) throw new Error('Preview failed.'); return await res.blob(); } catch { return null; } } function attachPreviewLoadingOverlay (targetEl, opts = {}) { const showPercent = opts.showPercent !== false; const overlay = document.createElement('div'); overlay.className = 'preview-loading-overlay'; overlay.setAttribute('aria-busy', 'true'); overlay.setAttribute('aria-live', 'polite'); const indicator = document.createElement('div'); indicator.className = 'preview-loading-indicator'; const spinner = document.createElement('div'); spinner.className = 'preview-loading-spinner'; spinner.setAttribute('aria-hidden', 'true'); indicator.appendChild(spinner); const percentEl = document.createElement('span'); percentEl.className = 'preview-loading-percent'; percentEl.hidden = true; indicator.appendChild(percentEl); overlay.appendChild(indicator); targetEl.appendChild(overlay); return { setPercent (value) { if (!showPercent) return; const n = Number(value); if (!Number.isFinite(n)) { percentEl.hidden = true; percentEl.textContent = ''; return; } const clamped = Math.max(0, Math.min(100, Math.round(n))); percentEl.hidden = false; percentEl.textContent = `${clamped}%`; }, remove () { if (overlay.isConnected) overlay.remove(); }, }; } function getVideoPlayerBufferedPercent (player) { if (!player) return 0; try { if (typeof player.bufferedPercent === 'function') { const ratio = Number(player.bufferedPercent()); if (Number.isFinite(ratio) && ratio >= 0) return Math.min(1, ratio); } } catch { /* ignore */ } try { const tech = typeof player.tech === 'function' ? player.tech(true) : null; const el = tech && typeof tech.el === 'function' ? tech.el() : null; if (!el || !el.buffered || !Number.isFinite(el.duration) || el.duration <= 0) return 0; let end = 0; for (let i = 0; i < el.buffered.length; i += 1) { end = Math.max(end, el.buffered.end(i)); } return Math.max(0, Math.min(1, end / el.duration)); } catch { return 0; } } function computeVideoPreviewLoadPercent (setupPercent, streamAheadPrefetch, player) { let prefetchPercent = 0; if (streamAheadPrefetch && typeof streamAheadPrefetch.getStatus === 'function') { const status = streamAheadPrefetch.getStatus(); const ratio = Number(status && status.cachedThroughRatio); if (Number.isFinite(ratio) && ratio >= 0) { prefetchPercent = Math.min(100, ratio * 100); } } const bufferPercent = getVideoPlayerBufferedPercent(player) * 100; const combined = Math.max(Number(setupPercent) || 0, prefetchPercent, bufferPercent); return Math.max(0, Math.min(99, Math.round(combined))); } function getVideoJsPlayerErrorMessage (player) { if (!player || typeof player.error !== 'function') return ''; try { const err = player.error(); if (!err) return ''; const code = err.code != null ? String(err.code) : ''; const message = String(err.message || '').trim(); if (message && code) return `${message} (${code})`; return message || code; } catch { return ''; } } function showVideoPreviewLoadFailure (targetEl, message, resources = {}) { const { loading, player, streamAheadPrefetch, sessionPlaylistUrl, imageSubtitleController, streamAheadSeekMarker, trackPrefs, } = resources; if (loading) { try { loading.remove(); } catch { /* ignore */ } } if (targetEl && targetEl.isConnected) { targetEl.querySelectorAll('.preview-loading-overlay').forEach((el) => el.remove()); } if (imageSubtitleController) { try { imageSubtitleController.detach(); } catch { /* ignore */ } } try { streamAheadSeekMarker && streamAheadSeekMarker.detach(); } catch { /* ignore */ } try { trackPrefs && trackPrefs.detach(); } catch { /* ignore */ } try { streamAheadPrefetch && streamAheadPrefetch.stop(); } catch { /* ignore */ } if (player) { try { player.dispose(); } catch { /* ignore */ } } if (targetEl && targetEl.isConnected) { targetEl.classList.remove('preview-expand-content--video'); targetEl.querySelectorAll('.preview-video-js, video, .preview-media').forEach((el) => el.remove()); if (!targetEl.querySelector('.preview-unsupported')) { const msg = document.createElement('p'); msg.className = 'preview-unsupported'; msg.textContent = message; targetEl.appendChild(msg); } } void clearVideoStreamClientCache(sessionPlaylistUrl); releaseActivePreviewVideoStreamSession(); STATE.previewCleanup = () => { void clearVideoStreamClientCache(sessionPlaylistUrl); releaseActivePreviewVideoStreamSession(); }; } function blobForAttachmentDownload (filename, blob) { if (!blob) return blob; const ext = extOf(filename || ''); if (!VIDEO_EXTS.has(ext) && !AUDIO_EXTS.has(ext)) return blob; if (String(blob.type || '').toLowerCase() === 'application/octet-stream') return blob; return new Blob([blob], { type: 'application/octet-stream' }); } async function downloadFileItem (item) { const blob = await fetchFileBlob(item); if (!blob) { toast('Download failed.', 'err'); return; } const downloadBlob = blobForAttachmentDownload(item.name, blob); const objectUrl = URL.createObjectURL(downloadBlob); triggerDownload(item.name, objectUrl); setTimeout(() => URL.revokeObjectURL(objectUrl), 60 * 1000); } async function renderStreamedVideoPreview (item, targetEl) { const streamInitToken = ++STATE.previewStreamInitToken; const isStaleInit = () => streamInitToken !== STATE.previewStreamInitToken || !targetEl || !targetEl.isConnected; targetEl.querySelectorAll('.preview-loading-overlay').forEach((el) => el.remove()); const loading = attachPreviewLoadingOverlay(targetEl, { showPercent: true }); let setupPercent = 2; loading.setPercent(setupPercent); const resources = { loading, player: null, streamAheadPrefetch: null, sessionPlaylistUrl: null, imageSubtitleController: null, streamAheadSeekMarker: null, trackPrefs: null, }; let previewFailed = false; let loadTimeoutId = null; const clearLoadTimeout = () => { if (loadTimeoutId != null) { window.clearTimeout(loadTimeoutId); loadTimeoutId = null; } }; const abortLoading = () => { clearLoadTimeout(); try { loading.remove(); } catch { /* ignore */ } }; const failPreview = (message) => { if (previewFailed || isStaleInit()) return; previewFailed = true; clearLoadTimeout(); showVideoPreviewLoadFailure(targetEl, message, resources); }; const releaseSessionIfNeeded = (session) => { void releaseVideoStreamSession(session && session.sessionId, { keepalive: true }); }; let session; let videojs; try { videojs = await ensureVideoJsLoaded(); if (isStaleInit()) { abortLoading(); return; } setupPercent = 12; loading.setPercent(setupPercent); await enableVideoStreamClientCache(); if (isStaleInit()) { abortLoading(); return; } setupPercent = 22; loading.setPercent(setupPercent); session = await createVideoStreamSessionForItem(item); if (!session || !String(session.playlistUrl || '').trim()) { throw new Error('Video stream could not be started.'); } if (isStaleInit()) { abortLoading(); releaseSessionIfNeeded(session); return; } setupPercent = 32; loading.setPercent(setupPercent); resources.sessionPlaylistUrl = String(session.playlistUrl || '').trim() || null; resources.streamAheadPrefetch = bindStreamAheadPrefetch(resources.sessionPlaylistUrl); if (isStaleInit()) { abortLoading(); try { resources.streamAheadPrefetch && resources.streamAheadPrefetch.stop(); } catch { /* ignore */ } void clearVideoStreamClientCache(resources.sessionPlaylistUrl); releaseSessionIfNeeded(session); return; } STATE.previewVideoStreamSessionId = String(session.sessionId || '').trim() || null; const prefs = loadUserVideoPrefs(); applyUserVideoTextTrackPrefs(); if ((session.subtitleSummary && session.subtitleSummary.skipped > 0)) { toast('Some subtitle tracks could not be converted for web playback.', 'err'); } setupPercent = 40; loading.setPercent(setupPercent); const video = document.createElement('video'); video.className = 'video-js vjs-big-play-centered preview-media preview-video-js'; video.controls = true; video.preload = 'auto'; video.playsInline = true; targetEl.classList.add('preview-expand-content--video'); targetEl.appendChild(video); const player = videojs(video, { controls: true, fluid: false, fill: true, responsive: false, preload: 'auto', controlBar: { currentTimeDisplay: true, timeDivider: true, durationDisplay: true, remainingTimeDisplay: false, }, sources: [{ src: session.playlistUrl, type: 'application/x-mpegURL' }], tracks: (session.subtitleTracks || []).map((track) => ({ kind: 'subtitles', src: track.src, srclang: track.language || 'und', label: track.label, default: !!track.default, })), }); resources.player = player; resources.trackPrefs = bindUserVideoTrackPrefs(player, prefs); resources.streamAheadSeekMarker = bindStreamAheadSeekMarker(player, resources.streamAheadPrefetch); ensureVideoPlaybackUi(player, session.durationSeconds); resources.imageSubtitleController = bindImageSubtitleOverlay(player, videojs, prefs, session, item); setupPercent = 48; let detachPrefetchProgress = null; let loadingHidden = false; const refreshLoadingPercent = () => { if (loadingHidden || previewFailed) return; loading.setPercent(computeVideoPreviewLoadPercent(setupPercent, resources.streamAheadPrefetch, player)); }; const hidePreviewLoading = () => { if (loadingHidden || previewFailed) return; loadingHidden = true; clearLoadTimeout(); if (detachPrefetchProgress) { try { detachPrefetchProgress(); } catch { /* ignore */ } detachPrefetchProgress = null; } loading.setPercent(100); abortLoading(); }; if (resources.streamAheadPrefetch && typeof resources.streamAheadPrefetch.subscribe === 'function') { detachPrefetchProgress = resources.streamAheadPrefetch.subscribe(() => refreshLoadingPercent()); } refreshLoadingPercent(); player.on('progress', refreshLoadingPercent); player.one('canplay', hidePreviewLoading); player.one('loadeddata', () => { refreshLoadingPercent(); window.setTimeout(hidePreviewLoading, 350); }); player.one('error', () => { const detail = getVideoJsPlayerErrorMessage(player); failPreview( detail ? `Video playback failed: ${detail}. You can try again or download the file.` : 'Video playback failed. You can try again or download the file.', ); }); loadTimeoutId = window.setTimeout(() => { failPreview('Video preview timed out. You can try again or download the file.'); }, VIDEO_PREVIEW_LOAD_TIMEOUT_MS); // ------------------------------------------------------------------------- let sentPartway = false; let sentFully = false; const markWatch = async () => { let ratio = 0; try { const duration = Number(player.duration()); const current = Number(player.currentTime()); if (Number.isFinite(duration) && duration > 0 && Number.isFinite(current)) { ratio = current / duration; } } catch { return; } if (ratio >= 0.7) { if (sentFully) return; sentPartway = true; sentFully = true; void reportWatchProgress(item.path, ratio); return; } if (ratio >= 0.05) { if (sentPartway) return; sentPartway = true; void reportWatchProgress(item.path, ratio); } }; player.ready(() => { const volume = Number(prefs.volume); if (Number.isFinite(volume)) { player.volume(Math.max(0, Math.min(1, volume))); } const settings = player && player.textTrackSettings; if (settings && typeof settings.setValues === 'function' && typeof settings.updateDisplay === 'function') { settings.setValues({ backgroundColor: '#000', backgroundOpacity: '0', edgeStyle: 'uniform', }); settings.updateDisplay(); } resources.trackPrefs.applySavedTracks(); }); player.on('loadedmetadata', resources.trackPrefs.applySavedTracks); player.on('loadedplaylist', resources.trackPrefs.applySavedTracks); player.on('timeupdate', markWatch); player.on('ended', () => { sentPartway = true; sentFully = true; void reportWatchProgress(item.path, 1); }); player.on('volumechange', () => { const v = Number(player.volume()); if (Number.isFinite(v)) saveUserVideoPrefs({ volume: v }); }); const cleanupPreviewPlayer = () => { if (!previewFailed) hidePreviewLoading(); if (resources.imageSubtitleController) { try { resources.imageSubtitleController.captureSelectedTracks(); } catch { /* ignore */ } try { resources.imageSubtitleController.detach(); } catch { /* ignore */ } } try { resources.streamAheadSeekMarker && resources.streamAheadSeekMarker.detach(); } catch { /* ignore */ } try { resources.streamAheadPrefetch && resources.streamAheadPrefetch.stop(); } catch { /* ignore */ } void clearVideoStreamClientCache(resources.sessionPlaylistUrl); releaseActivePreviewVideoStreamSession(); try { markWatch(); } catch { /* ignore */ } try { resources.trackPrefs.captureSelectedTracks(); } catch { /* ignore */ } try { resources.trackPrefs.detach(); } catch { /* ignore */ } try { player.dispose(); } catch { /* ignore */ } }; if (isStaleInit()) { cleanupPreviewPlayer(); return; } if (!previewFailed) { STATE.previewCleanup = cleanupPreviewPlayer; } } catch (err) { if (isStaleInit()) { abortLoading(); releaseSessionIfNeeded(session); return; } const fallback = 'Video preview failed to load. You can try again or download the file.'; failPreview(err && err.message ? String(err.message) : fallback); } } function fileAccentColor (name) { const ext = extOf(name || ''); if (IMAGE_EXTS.has(ext)) return '#3fcf8e'; if (VIDEO_EXTS.has(ext)) return '#e05c6e'; if (AUDIO_EXTS.has(ext)) return '#c084fc'; if (MODEL_EXTS.has(ext)) return '#2f6dff'; if (DOC_EXTS.has(ext)) return '#f97316'; if (CODE_EXTS.has(ext)) return '#38bdf8'; if (ARCHIVE_EXTS.has(ext)) return '#facc15'; return '#7880a0'; } function animateRect (el, fromRect, toRect, opts = {}) { const duration = opts.duration == null ? 260 : opts.duration; const easeOut = (t) => 1 - Math.pow(1 - t, 3); el.style.left = `${fromRect.left}px`; el.style.top = `${fromRect.top}px`; el.style.width = `${fromRect.width}px`; el.style.height = `${fromRect.height}px`; return new Promise((resolve) => { const t0 = performance.now(); function frame (now) { const raw = Math.min((now - t0) / duration, 1); const t = easeOut(raw); const left = fromRect.left + (toRect.left - fromRect.left) * t; const top = fromRect.top + (toRect.top - fromRect.top) * t; const width = fromRect.width + (toRect.width - fromRect.width) * t; const height = fromRect.height + (toRect.height - fromRect.height) * t; el.style.left = `${left}px`; el.style.top = `${top}px`; el.style.width = `${width}px`; el.style.height = `${height}px`; if (raw < 1) { requestAnimationFrame(frame); } else { resolve(); } } requestAnimationFrame(frame); }); } async function openExpandedTilePreview (item, tileEl, sourceSvgEl, loadPreviewContent) { if (!tileEl || !sourceSvgEl) return false; if (STATE.previewExpandState) { await closeExpandedTilePreview(); } const iconEl = tileEl.querySelector('.icon'); const nameEl = tileEl.querySelector('.name'); if (!iconEl) return false; const startRect = tileEl.getBoundingClientRect(); const targetW = Math.min(window.innerWidth * 0.94, 1100); const targetH = Math.min(window.innerHeight * 0.9, 860); const targetRect = { left: (window.innerWidth - targetW) / 2, top: (window.innerHeight - targetH) / 2, width: targetW, height: targetH, }; const backdrop = document.createElement('div'); backdrop.className = 'preview-backdrop'; document.body.appendChild(backdrop); const parent = tileEl.parentNode; const nextSibling = tileEl.nextSibling; const iconHtml = iconEl.innerHTML; const originalIconSvg = iconEl.querySelector('svg'); const placeholder = document.createElement('div'); placeholder.className = 'file-item file-item--preview-placeholder'; placeholder.style.width = `${startRect.width}px`; placeholder.style.height = `${startRect.height}px`; if (parent) { parent.insertBefore(placeholder, tileEl); } tileEl.remove(); document.body.appendChild(tileEl); tileEl.classList.add('file-item--preview'); tileEl.style.setProperty('--preview-accent', fileAccentColor(item.name)); tileEl.style.position = 'fixed'; tileEl.style.left = `${startRect.left}px`; tileEl.style.top = `${startRect.top}px`; tileEl.style.width = `${startRect.width}px`; tileEl.style.height = `${startRect.height}px`; tileEl.style.margin = '0'; tileEl.style.zIndex = '10000'; if (nameEl) nameEl.style.display = 'none'; const titleEl = document.createElement('div'); titleEl.className = 'preview-expand-title'; titleEl.textContent = item.name; const closeBtn = document.createElement('button'); closeBtn.className = 'preview-expand-close'; closeBtn.type = 'button'; closeBtn.textContent = '×'; closeBtn.setAttribute('aria-label', 'Close preview'); const dlBtn = document.createElement('button'); dlBtn.className = 'preview-expand-download'; dlBtn.type = 'button'; dlBtn.textContent = 'Download'; dlBtn.addEventListener('click', (e) => { e.stopPropagation(); const previewItem = STATE.previewExpandState && STATE.previewExpandState.item; if (!previewItem) { toast('Preview unavailable.', 'err'); return; } if (previewObjectUrlIsDownloadableOriginal(previewItem)) { triggerDownload(previewItem.name, STATE.previewObjectUrl); return; } if (VIDEO_EXTS.has(extOf(previewItem.name)) || AUDIO_EXTS.has(extOf(previewItem.name))) { void downloadFileItem(previewItem); return; } toast('Preview still loading.', 'err'); }); const shareBtn = document.createElement('button'); shareBtn.className = 'preview-expand-share'; shareBtn.type = 'button'; shareBtn.textContent = 'Share'; shareBtn.addEventListener('click', (e) => { e.stopPropagation(); openShareModal(item); }); const actionsEl = document.createElement('div'); actionsEl.className = 'preview-expand-actions'; actionsEl.appendChild(shareBtn); actionsEl.appendChild(dlBtn); iconEl.innerHTML = ''; if (originalIconSvg) { const outline = originalIconSvg.cloneNode(true); outline.classList.add('preview-expand-outline'); iconEl.appendChild(outline); } const previewMount = document.createElement('div'); previewMount.className = 'preview-expand-content'; iconEl.appendChild(previewMount); // Spinner during expansion; video preview keeps an overlay until the player is ready. attachPreviewLoadingOverlay(previewMount, { showPercent: VIDEO_EXTS.has(extOf(item.name)) }); tileEl.insertBefore(titleEl, tileEl.firstChild); tileEl.appendChild(closeBtn); tileEl.appendChild(actionsEl); STATE.previewExpandState = { item, requireExplicitClose: VIDEO_EXTS.has(extOf(item.name)), tileEl, sourceSvgEl, parent, nextSibling, iconEl, iconHtml, nameEl, backdrop, placeholder, closeBtn, dlBtn, shareBtn, actionsEl, titleEl, previewMount, startRect, }; const onBackdrop = (e) => { if (e.target === backdrop) closePreview(); }; const onClose = () => closePreview({ force: true }); backdrop.addEventListener('click', onBackdrop); closeBtn.addEventListener('click', onClose); STATE.previewExpandState.onBackdrop = onBackdrop; STATE.previewExpandState.onClose = onClose; requestAnimationFrame(() => backdrop.classList.add('visible')); await animateRect(tileEl, startRect, targetRect); tileEl.style.left = `${targetRect.left}px`; tileEl.style.top = `${targetRect.top}px`; tileEl.style.width = `${targetRect.width}px`; tileEl.style.height = `${targetRect.height}px`; try { await loadPreviewContent(previewMount); } catch { if (previewMount.isConnected) { previewMount.innerHTML = ''; const msg = document.createElement('p'); msg.className = 'preview-unsupported'; msg.textContent = 'Preview failed to load. You can try again.'; previewMount.appendChild(msg); } } return true; } async function closeExpandedTilePreview () { const st = STATE.previewExpandState; if (!st) return; st.backdrop.classList.remove('visible'); if (st.backdrop && st.onBackdrop) st.backdrop.removeEventListener('click', st.onBackdrop); if (st.closeBtn && st.onClose) st.closeBtn.removeEventListener('click', st.onClose); const fromRect = st.tileEl.getBoundingClientRect(); await animateRect(st.tileEl, fromRect, st.startRect, { duration: 220 }); st.tileEl.classList.remove('file-item--preview'); st.tileEl.style.position = ''; st.tileEl.style.left = ''; st.tileEl.style.top = ''; st.tileEl.style.width = ''; st.tileEl.style.height = ''; st.tileEl.style.margin = ''; st.tileEl.style.zIndex = ''; if (st.titleEl) st.titleEl.remove(); if (st.closeBtn) st.closeBtn.remove(); if (st.actionsEl) st.actionsEl.remove(); if (st.iconEl) st.iconEl.innerHTML = st.iconHtml; if (st.nameEl) st.nameEl.style.display = ''; if (st.placeholder && st.placeholder.parentNode) { st.placeholder.parentNode.insertBefore(st.tileEl, st.placeholder); st.placeholder.remove(); } else if (st.parent) { if (st.nextSibling && st.nextSibling.parentNode === st.parent) { st.parent.insertBefore(st.tileEl, st.nextSibling); } else { st.parent.appendChild(st.tileEl); } } if (st.backdrop) st.backdrop.remove(); STATE.previewExpandState = null; } async function closePreview (opts = {}) { if (STATE.previewClosing) return; if (STATE.previewExpandState) { if (STATE.previewExpandState.requireExplicitClose && !opts.force) { return; } STATE.previewClosing = true; clearPreviewObjectUrl(); try { await closeExpandedTilePreview(); STATE.previewSourceEl = null; } finally { STATE.previewClosing = false; } } } async function fetchFileBlob (item) { const url = `/api/files/download?file=${encodeURIComponent(item.path)}`; try { const res = await fetch(url, { headers: { Authorization: 'Bearer ' + STATE.token, 'X-Fp': getFingerprint(), }, }); if (!res.ok) throw new Error('Download failed.'); return await res.blob(); } catch { return null; } } function triggerDownload (filename, objectUrl) { const a = document.createElement('a'); a.href = objectUrl; a.download = filename; a.style.display = 'none'; document.body.appendChild(a); a.click(); document.body.removeChild(a); } function modelPreviewType (name) { const ext = extOf(name || ''); if (MODEL_EXTS.has(ext)) return ext; return null; } async function loadThreePreviewModules () { if (!threePreviewModulesPromise) { threePreviewModulesPromise = Promise.all([ import('/vendor/three/three.module.js'), import('/vendor/three/addons/controls/OrbitControls.js'), import('/vendor/three/addons/loaders/STLLoader.js'), import('/vendor/three/addons/loaders/OBJLoader.js'), ]).then(([THREE, controlsMod, stlMod, objMod]) => { return { THREE, OrbitControls: controlsMod.OrbitControls, STLLoader: stlMod.STLLoader, OBJLoader: objMod.OBJLoader, }; }); } return threePreviewModulesPromise; } function disposeObject3D (root) { if (!root || typeof root.traverse !== 'function') return; root.traverse((node) => { if (node.geometry && typeof node.geometry.dispose === 'function') { node.geometry.dispose(); } if (!node.material) return; if (Array.isArray(node.material)) { node.material.forEach((material) => { if (material && typeof material.dispose === 'function') material.dispose(); }); return; } if (typeof node.material.dispose === 'function') node.material.dispose(); }); } async function buildModelObjectFromBlob (blob, type, modules) { const { THREE, STLLoader, OBJLoader } = modules; const sharedMaterial = new THREE.MeshStandardMaterial({ color: 0x2f6dff, metalness: 0.08, roughness: 0.72, }); if (type === 'stl') { const arr = await blob.arrayBuffer(); const geometry = new STLLoader().parse(arr); geometry.computeVertexNormals(); return new THREE.Mesh(geometry, sharedMaterial); } if (type === 'obj') { const text = await blob.text(); const obj = new OBJLoader().parse(text); obj.traverse((node) => { if (!node || !node.isMesh) return; node.material = sharedMaterial.clone(); }); sharedMaterial.dispose(); return obj; } throw new Error('Unsupported 3D model format.'); } function setModelPreviewMessage (wrap, text) { wrap.innerHTML = ''; const msg = document.createElement('p'); msg.className = 'preview-unsupported'; msg.textContent = text; wrap.appendChild(msg); } async function renderModelPreview (item, blob, targetEl) { const type = modelPreviewType(item && item.name); if (!type) { const msg = document.createElement('p'); msg.className = 'preview-unsupported'; msg.textContent = 'This 3D file type is not supported yet.'; targetEl.appendChild(msg); return; } const wrap = document.createElement('div'); wrap.className = 'preview-model-wrap'; targetEl.appendChild(wrap); const canvas = document.createElement('canvas'); canvas.className = 'preview-model-canvas'; canvas.style.touchAction = 'none'; wrap.appendChild(canvas); const hint = document.createElement('p'); hint.className = 'preview-model-hint'; hint.textContent = 'Drag to rotate. Use the scroll wheel to zoom.'; wrap.appendChild(hint); const gl = canvas.getContext('webgl2', { antialias: true, alpha: true }) || canvas.getContext('webgl', { antialias: true, alpha: true }); if (!gl) { setModelPreviewMessage(wrap, '3D preview is not available in this browser. You can still download this file.'); return; } let modules; try { modules = await loadThreePreviewModules(); } catch { setModelPreviewMessage(wrap, '3D preview dependencies failed to load. You can still download this file.'); return; } if (!wrap.isConnected) return; const { THREE, OrbitControls } = modules; const scene = new THREE.Scene(); scene.background = new THREE.Color(0x0d111a); const camera = new THREE.PerspectiveCamera(50, 1, 0.01, 5000); const renderer = new THREE.WebGLRenderer({ canvas, context: gl, antialias: true, alpha: true }); renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2)); const ambient = new THREE.AmbientLight(0xffffff, 0.9); const key = new THREE.DirectionalLight(0xffffff, 0.95); key.position.set(1.2, 1.6, 1.1); scene.add(ambient); scene.add(key); let modelRoot; try { modelRoot = await buildModelObjectFromBlob(blob, type, modules); } catch { renderer.dispose(); setModelPreviewMessage(wrap, 'This 3D file could not be parsed. You can still download it.'); return; } if (!wrap.isConnected) { disposeObject3D(modelRoot); renderer.dispose(); return; } scene.add(modelRoot); const box = new THREE.Box3().setFromObject(modelRoot); if (box.isEmpty()) { disposeObject3D(modelRoot); renderer.dispose(); setModelPreviewMessage(wrap, 'This 3D file has no visible geometry to preview.'); return; } const size = new THREE.Vector3(); const center = new THREE.Vector3(); box.getSize(size); box.getCenter(center); modelRoot.position.sub(center); const maxDim = Math.max(size.x, size.y, size.z) || 1; const camDistance = maxDim * 1.8; camera.position.set(camDistance, camDistance * 0.75, camDistance); camera.near = Math.max(0.001, maxDim / 2000); camera.far = Math.max(1000, maxDim * 2000); camera.updateProjectionMatrix(); const controls = new OrbitControls(camera, renderer.domElement); controls.enableDamping = true; controls.dampingFactor = 0.08; controls.target.set(0, 0, 0); controls.minDistance = maxDim * 0.2; controls.maxDistance = maxDim * 25; controls.update(); const resize = () => { const w = Math.max(160, Math.floor(wrap.clientWidth || 0)); const h = Math.max(160, Math.floor((wrap.clientHeight || 0) - (hint.offsetHeight || 0) - 6)); renderer.setSize(w, h, false); camera.aspect = w / h; camera.updateProjectionMatrix(); }; resize(); let stop = false; let rafId = 0; const frame = () => { if (stop) return; controls.update(); renderer.render(scene, camera); rafId = requestAnimationFrame(frame); }; frame(); const resizeObserver = typeof ResizeObserver === 'function' ? new ResizeObserver(() => resize()) : null; if (resizeObserver) resizeObserver.observe(wrap); STATE.previewCleanup = () => { stop = true; if (rafId) cancelAnimationFrame(rafId); if (resizeObserver) resizeObserver.disconnect(); try { controls.dispose(); } catch { /* ignore */ } try { disposeObject3D(modelRoot); } catch { /* ignore */ } try { renderer.dispose(); } catch { /* ignore */ } }; } async function renderPreviewBody (item, blob, objectUrl, targetEl = null) { const body = targetEl || document.getElementById('preview-body'); body.innerHTML = ''; const mime = String(blob.type || '').toLowerCase(); const previewable = isInlinePreviewableBlob(blob, item.name); if (!previewable) { const msg = document.createElement('p'); msg.className = 'preview-unsupported'; msg.textContent = 'This file cannot be previewed, but you can download it with the button below.'; body.appendChild(msg); return; } if (/^image\//.test(mime) || IMAGE_EXTS.has(extOf(item.name))) { const img = document.createElement('img'); img.className = 'preview-media'; img.src = objectUrl; img.alt = item.name; body.appendChild(img); return; } if (/^video\//.test(mime) || VIDEO_EXTS.has(extOf(item.name))) { const video = document.createElement('video'); video.className = 'preview-media'; video.src = objectUrl; video.controls = true; video.preload = 'metadata'; body.appendChild(video); return; } if (/^audio\//.test(mime) || AUDIO_EXTS.has(extOf(item.name))) { const audio = document.createElement('audio'); audio.className = 'preview-audio'; audio.src = objectUrl; audio.controls = true; body.appendChild(audio); return; } if (modelPreviewType(item.name)) { await renderModelPreview(item, blob, body); return; } if (mime === 'application/pdf') { const frame = document.createElement('iframe'); frame.className = 'preview-frame'; frame.src = objectUrl; frame.title = item.name; body.appendChild(frame); return; } if (isTextLikeBlob(blob, item.name)) { const text = await blob.text(); const lang = detectCodeLanguage(item.name, mime); const formatted = prettyPrintCode(text, lang); const pre = document.createElement('pre'); pre.className = 'preview-text preview-code'; pre.innerHTML = highlightCode(formatted, lang); body.appendChild(pre); return; } const msg = document.createElement('p'); msg.className = 'preview-unsupported'; msg.textContent = 'This file cannot be previewed, but you can download it with the button below.'; body.appendChild(msg); } async function downloadOrView (item, sourceSvgEl = null) { if (STATE.previewExpandState) { await closePreview({ force: true }); } const sourceTileEl = sourceSvgEl ? sourceSvgEl.closest('.file-item') : null; if (sourceTileEl) { STATE.previewSourceEl = sourceSvgEl; const expanded = await openExpandedTilePreview(item, sourceTileEl, sourceSvgEl, async (previewMount) => { if (VIDEO_EXTS.has(extOf(item.name))) { clearPreviewObjectUrl(); previewMount.querySelectorAll('.preview-video-js, video, .preview-media').forEach((el) => el.remove()); await renderStreamedVideoPreview(item, previewMount); return; } const blob = needsServerPreviewImage(item.name) ? await fetchPreviewImageBlob(item) : await fetchFileBlob(item); if (!blob) throw new Error('Download failed'); clearPreviewObjectUrl(); const objectUrl = URL.createObjectURL(blob); STATE.previewObjectUrl = objectUrl; if (!previewMount.isConnected) return; previewMount.innerHTML = ''; await renderPreviewBody(item, blob, objectUrl, previewMount); }); if (expanded) return; } toast('Preview unavailable — no source tile found.', 'err'); } // ─────────────────────────────────────────────────────────────────────────── // UPLOAD // ─────────────────────────────────────────────────────────────────────────── async function createFolderInCurrentDir () { if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; } if (!canWrite()) { toast('No write access.', 'err'); return; } const name = await showPrompt('New Folder', 'Enter a name for the new folder:'); if (name == null) return; const folderName = name.trim(); if (!folderName) { toast('Folder name is required.', 'err'); return; } try { await api('POST', '/files/mkdir', { dir: STATE.currentDir, name: folderName }); toast('Folder created.', 'ok'); await navigateTo(STATE.currentDir, STATE.currentRoot); } catch (err) { toast(err.message, 'err'); } } function canWrite (item = null) { if (STATE.isAdmin) return true; const root = item && item._root ? item._root : (STATE.currentRoot || (item ? resolveRootForPath(item.path) : null)); if (!root) return false; if (root.isUserFolder) return true; const p = STATE.permissions[rootPermissionLabel(root)]; return p && p.write; } async function uploadFiles (fileList) { if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; } if (!canWrite()) { toast('No write access.', 'err'); return; } if (!canStartUpload()) return; const files = Array.from(fileList || []); if (!files.length) return; const uploadUi = createUploadProgressBar('Preparing upload...'); const { wrap, abortSignal } = uploadUi; STATE.uploadInProgress = true; try { const existingNames = await listDirNameSet(STATE.currentDir); let done = 0; let uploaded = 0; let uploadedBytes = 0; const totalBytes = getTotalUploadBytes(files); updateUploadProgressBar(wrap, { done, total: files.length, uploadedBytes, totalBytes }); for (const original of files) { throwIfUploadAborted(abortSignal); let fileToUpload = original; if (existingNames.has(original.name)) { const suggested = nextAvailableName(original.name, existingNames); const decision = await showFileConflictChoice(original.name, suggested, 'upload'); throwIfUploadAborted(abortSignal); if (decision === 'cancel') { done++; uploadedBytes += getUploadFileSize(original); updateUploadProgressBar(wrap, { done, total: files.length, uploadedBytes, totalBytes }); continue; } if (decision === 'rename') { fileToUpload = cloneFileWithName(original, suggested); } } await uploadSingleFile(fileToUpload, STATE.currentDir, (fileBytes) => { updateUploadProgressBar(wrap, { done, total: files.length, uploadedBytes: uploadedBytes + fileBytes, totalBytes, }); }, abortSignal); existingNames.add(fileToUpload.name); done++; uploaded++; uploadedBytes += getUploadFileSize(fileToUpload); updateUploadProgressBar(wrap, { done, total: files.length, uploadedBytes, totalBytes }); } toast(`Uploaded ${uploaded} file(s).`, 'ok'); await navigateTo(STATE.currentDir, STATE.currentRoot); } catch (err) { if (isUploadAbortError(err)) { toast('Upload cancelled.', 'ok'); await navigateTo(STATE.currentDir, STATE.currentRoot); return; } toast(err.message, 'err'); } finally { STATE.uploadInProgress = false; wrap.remove(); } } function canStartUpload () { if (!STATE.uploadInProgress) return true; toast('An upload is already in progress.', 'err'); return false; } function createUploadProgressBar (text) { const abortSignal = createUploadAbortSignal(); const wrap = document.createElement('div'); wrap.className = 'upload-bar-wrap'; wrap.innerHTML = `
    ${escapeHtml(text)}
    `; wrap.querySelector('.upload-abort-btn').addEventListener('click', () => { abortSignal.abort(); wrap.querySelector('.upload-abort-btn').disabled = true; wrap.querySelector('span').textContent = 'Cancelling upload...'; }); document.body.appendChild(wrap); return { wrap, abortSignal }; } function createUploadAbortSignal () { return { aborted: false, activeXhr: null, abort () { if (this.aborted) return; this.aborted = true; if (this.activeXhr) this.activeXhr.abort(); }, }; } function createUploadAbortError () { const err = new Error('Upload cancelled.'); err.name = 'AbortError'; return err; } function isUploadAbortError (err) { return err && (err.name === 'AbortError' || /upload cancelled|abort/i.test(String(err.message || ''))); } function throwIfUploadAborted (abortSignal) { if (abortSignal && abortSignal.aborted) throw createUploadAbortError(); } function getUploadFileSize (file) { const size = Number(file && file.size); return Number.isFinite(size) && size > 0 ? size : 0; } function getTotalUploadBytes (files) { return (files || []).reduce((sum, file) => sum + getUploadFileSize(file), 0); } function uploadProgressPercent (done, total, uploadedBytes, totalBytes) { if (totalBytes > 0) return Math.max(0, Math.min(100, (uploadedBytes / totalBytes) * 100)); if (total > 0) return Math.max(0, Math.min(100, (done / total) * 100)); return 0; } function updateUploadProgressBar (wrap, { done, total, uploadedBytes, totalBytes }) { const percent = uploadProgressPercent(done, total, uploadedBytes, totalBytes); const active = Math.min(total, done < total ? done + 1 : done); wrap.querySelector('span').textContent = `Uploading ${active} / ${total} file(s)... ${Math.round(percent)}%`; wrap.querySelector('.upload-bar-fill').style.width = `${percent}%`; } async function uploadSingleFile (file, targetDir, onProgress, abortSignal) { const formData = new FormData(); formData.append('files', file); await new Promise((resolve, reject) => { if (abortSignal && abortSignal.aborted) { reject(createUploadAbortError()); return; } const xhr = new XMLHttpRequest(); const fileSize = getUploadFileSize(file); let settled = false; const cleanup = () => { if (abortSignal && abortSignal.activeXhr === xhr) abortSignal.activeXhr = null; }; const finishResolve = () => { if (settled) return; settled = true; cleanup(); resolve(); }; const finishReject = (err) => { if (settled) return; settled = true; cleanup(); reject(err); }; xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(targetDir)}`); xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token); xhr.setRequestHeader('X-Fp', getFingerprint()); xhr.setRequestHeader('X-Upload-Size', String(file.size || 0)); if (abortSignal) abortSignal.activeXhr = xhr; if (xhr.upload) { xhr.upload.onprogress = (event) => { if (typeof onProgress !== 'function') return; if (event.lengthComputable && event.total > 0 && fileSize > 0) { onProgress(Math.min(fileSize, fileSize * (event.loaded / event.total))); } }; } xhr.onload = () => { if (xhr.status === 200) { if (typeof onProgress === 'function') onProgress(fileSize); finishResolve(); return; } finishReject(new Error(parseUploadError(xhr.responseText))); }; xhr.onerror = () => finishReject(new Error('Network error')); xhr.onabort = () => finishReject(createUploadAbortError()); xhr.send(formData); }); } function parseUploadError (responseText) { try { return (JSON.parse(responseText) || {}).error || 'Upload failed'; } catch { return 'Upload failed'; } } async function ensureServerDir (baseDir, relativeDir) { const parts = String(relativeDir || '').split(/[\\/]/).filter(Boolean); let current = baseDir; for (const part of parts) { try { const resp = await api('POST', '/files/mkdir', { dir: current, name: part }); current = resp && resp.path ? resp.path : joinServerPath(current, part); } catch (err) { if (!/exist|EEXIST/i.test(err.message || '')) throw err; current = joinServerPath(current, part); } } return current; } async function uploadFolderInputFiles (fileList) { if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; } if (!canWrite()) { toast('No write access.', 'err'); return; } if (!canStartUpload()) return; if (!fileList || !fileList.length) return; const files = Array.from(fileList); const total = files.length; let done = 0; let uploadedBytes = 0; const totalBytes = getTotalUploadBytes(files); const uploadUi = createUploadProgressBar('Preparing folder upload...'); const { wrap, abortSignal } = uploadUi; STATE.uploadInProgress = true; try { const dirCache = new Map(); dirCache.set('', STATE.currentDir); updateUploadProgressBar(wrap, { done, total, uploadedBytes, totalBytes }); for (const file of files) { throwIfUploadAborted(abortSignal); const rel = file.webkitRelativePath || file.name; const relParts = rel.split(/[\\/]/).filter(Boolean); const relDir = relParts.slice(0, -1).join('/'); if (!dirCache.has(relDir)) { const parentRel = relParts.slice(0, -2).join('/'); const parentAbs = dirCache.get(parentRel) || await ensureServerDir(STATE.currentDir, parentRel); const thisName = relParts[relParts.length - 2]; try { const created = await api('POST', '/files/mkdir', { dir: parentAbs, name: thisName }); dirCache.set(relDir, created.path || joinServerPath(parentAbs, thisName)); } catch (err) { if (!/exist|EEXIST/i.test(err.message || '')) throw err; dirCache.set(relDir, joinServerPath(parentAbs, thisName)); } } const targetDir = dirCache.get(relDir) || STATE.currentDir; await uploadSingleFile(file, targetDir, (fileBytes) => { updateUploadProgressBar(wrap, { done, total, uploadedBytes: uploadedBytes + fileBytes, totalBytes, }); }, abortSignal); done++; uploadedBytes += getUploadFileSize(file); updateUploadProgressBar(wrap, { done, total, uploadedBytes, totalBytes }); } toast(`Uploaded ${total} file(s).`, 'ok'); await navigateTo(STATE.currentDir, STATE.currentRoot); } catch (err) { if (isUploadAbortError(err)) { toast('Upload cancelled.', 'ok'); await navigateTo(STATE.currentDir, STATE.currentRoot); return; } toast(err.message, 'err'); } finally { STATE.uploadInProgress = false; wrap.remove(); } } // ─────────────────────────────────────────────────────────────────────────── // FOLDER DRAG-AND-DROP (recursive) // ─────────────────────────────────────────────────────────────────────────── /** * Reads all readEntries batches from a DirectoryReader (browsers may return * results in chunks; we must keep calling until we get an empty array). */ function readAllEntries (reader) { return new Promise((resolve, reject) => { const all = []; function next () { reader.readEntries(batch => { if (!batch.length) { resolve(all); return; } all.push(...batch); next(); }, reject); } next(); }); } /** * Recursively walk a FileSystemEntry tree, creating server-side directories * on the fly and collecting { file, targetDir } pairs for upload. */ async function collectEntries (entry, serverDir, toUpload) { if (entry.isFile) { const file = await new Promise((res, rej) => entry.file(res, rej)); toUpload.push({ file, targetDir: serverDir }); } else if (entry.isDirectory) { // Ask the server to create the directory; it returns the canonical path. let newServerDir; try { const resp = await api('POST', '/files/mkdir', { dir: serverDir, name: entry.name }); newServerDir = resp.path; } catch { // Directory may already exist — reconstruct path from what we know. // The server always returns JSON with {error} on failure, so we can // still continue by falling back to a best-effort path join. // We rely on the fact that the server separator is consistent within // a session (the list/browse API already returned paths in that format). const sep = serverDir.includes('\\') ? '\\' : '/'; newServerDir = serverDir + sep + entry.name; } const reader = entry.createReader(); const subEntries = await readAllEntries(reader); for (const sub of subEntries) { await collectEntries(sub, newServerDir, toUpload); } } } async function uploadEntries (entries) { if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; } if (!canWrite()) { toast('No write access.', 'err'); return; } if (!canStartUpload()) return; const uploadUi = createUploadProgressBar('Scanning...'); const { wrap, abortSignal } = uploadUi; STATE.uploadInProgress = true; try { const toUpload = []; for (const entry of entries) { throwIfUploadAborted(abortSignal); await collectEntries(entry, STATE.currentDir, toUpload); } if (!toUpload.length) { toast('No files found.', 'err'); return; } let done = 0; const total = toUpload.length; let uploadedBytes = 0; const totalBytes = getTotalUploadBytes(toUpload.map(({ file }) => file)); const updateBar = () => { updateUploadProgressBar(wrap, { done, total, uploadedBytes, totalBytes }); }; updateBar(); for (const { file, targetDir } of toUpload) { throwIfUploadAborted(abortSignal); await uploadSingleFile(file, targetDir, (fileBytes) => { updateUploadProgressBar(wrap, { done, total, uploadedBytes: uploadedBytes + fileBytes, totalBytes, }); }, abortSignal); done++; uploadedBytes += getUploadFileSize(file); updateBar(); } toast(`Uploaded ${total} file(s).`, 'ok'); await navigateTo(STATE.currentDir, STATE.currentRoot); } catch (err) { if (isUploadAbortError(err)) { toast('Upload cancelled.', 'ok'); await navigateTo(STATE.currentDir, STATE.currentRoot); return; } toast(err.message, 'err'); } finally { STATE.uploadInProgress = false; wrap.remove(); } } // DRAG-AND-DROP // ─────────────────────────────────────────────────────────────────────────── function initDragDrop () { const main = document.getElementById('main-content'); const dropOvl = document.getElementById('drop-overlay'); let dragDepth = 0; main.addEventListener('dragenter', e => { e.preventDefault(); dragDepth++; dropOvl.classList.remove('hidden'); }); main.addEventListener('dragleave', () => { dragDepth--; if (dragDepth <= 0) { dragDepth = 0; dropOvl.classList.add('hidden'); } }); main.addEventListener('dragover', e => e.preventDefault()); main.addEventListener('drop', async e => { e.preventDefault(); dragDepth = 0; dropOvl.classList.add('hidden'); if (!canWrite()) { toast('No write access.', 'err'); return; } const items = Array.from(e.dataTransfer.items || []); // Use the FileSystem Entry API when available so we can handle folders. if (items.length && typeof items[0].webkitGetAsEntry === 'function') { const entries = items.map(i => i.webkitGetAsEntry()).filter(Boolean); if (entries.some(en => en.isDirectory)) { await uploadEntries(entries); return; } } // Plain files only — use the fast batch path. const files = e.dataTransfer.files; if (files.length) await uploadFiles(files); }); } // ─────────────────────────────────────────────────────────────────────────── // RENAME // ─────────────────────────────────────────────────────────────────────────── function openRenameModal (item) { const modal = document.getElementById('rename-modal'); modal.classList.remove('hidden'); const input = document.getElementById('rename-input'); input.value = item.name; input.focus(); input.select(); document.getElementById('rename-error').classList.add('hidden'); document.getElementById('rename-form').onsubmit = async (e) => { e.preventDefault(); const newName = input.value.trim(); if (!newName) return; try { if (item._root) { await api('POST', '/files/root-alias', { rootPath: item.path, alias: newName }); } else { await api('POST', '/files/rename', { from: item.path, to: newName }); } modal.classList.add('hidden'); toast(item._root ? 'Alias updated.' : 'Renamed.', 'ok'); if (item._root) { await loadRoots({ preferredDir: STATE.currentDir, preferredRootPath: (STATE.currentRoot && STATE.currentRoot.path) || item.path, }); } else { await navigateTo(STATE.currentDir, STATE.currentRoot); } } catch (err) { document.getElementById('rename-error').textContent = err.message; document.getElementById('rename-error').classList.remove('hidden'); } }; } // ─────────────────────────────────────────────────────────────────────────── // DELETE // ─────────────────────────────────────────────────────────────────────────── async function deleteItem (item) { if (!await showConfirm('Delete item', `Delete "${item.name}"? This cannot be undone.`)) return; try { await api('POST', '/files/delete', { path: item.path }); toast('Deleted.', 'ok'); closeSidebar(); await navigateTo(STATE.currentDir, STATE.currentRoot); } catch (err) { toast(err.message, 'err'); } } // ─────────────────────────────────────────────────────────────────────────── // ADMIN PANEL // ─────────────────────────────────────────────────────────────────────────── let _adminUpdateStatus = null; let _debugRefreshTimer = null; let _debugUptimeTimer = null; let _debugLatestData = null; let _adminConfigCache = null; function scheduledRestartCadenceLabel (value) { const key = String(value || '').trim(); if (key === 'daily') return 'Daily'; if (key === 'every3days') return 'Every 3 days'; if (key === 'weekly') return 'Weekly'; if (key === 'biweekly') return 'Bi-weekly'; if (key === 'monthly') return 'Monthly'; return 'Unknown'; } function syncScheduledRestartControls (underSystemd) { const container = document.getElementById('admin-scheduled-restart'); const enabled = document.getElementById('admin-scheduled-restart-enabled'); const cadence = document.getElementById('admin-scheduled-restart-cadence'); const time = document.getElementById('admin-scheduled-restart-time'); const save = document.getElementById('admin-save-scheduled-restart'); const help = document.getElementById('admin-scheduled-restart-help'); if (!container || !enabled || !cadence || !time || !save || !help) return; const disabled = !underSystemd; container.classList.toggle('admin-scheduled-restart--disabled', disabled); enabled.disabled = disabled; cadence.disabled = disabled || !enabled.checked; time.disabled = disabled || !enabled.checked; save.disabled = disabled; if (disabled) { help.textContent = 'Scheduled restart is available only when the server is started via the systemd service.'; return; } help.textContent = 'When the scheduled time is reached, restart waits until there have been no logged-in clients for at least one hour.'; } function formatTimestamp (ms) { const value = Number(ms || 0); if (!Number.isFinite(value) || value <= 0) return '—'; try { return new Date(value).toLocaleString(); } catch { return '—'; } } function formatElapsedDuration (ms) { const totalMs = Number(ms || 0); if (!Number.isFinite(totalMs) || totalMs < 0) return '—'; const totalSeconds = Math.floor(totalMs / 1000); const days = Math.floor(totalSeconds / 86400); const hours = Math.floor((totalSeconds % 86400) / 3600); const minutes = Math.floor((totalSeconds % 3600) / 60); const seconds = totalSeconds % 60; const hms = `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`; if (days <= 0) return hms; return `${days}d ${hms}`; } function getDebugUptimeMsNow () { const data = _debugLatestData || {}; const maintenance = data.maintenance || {}; const baseUptimeMs = Number(maintenance.uptimeMs || 0); if (!Number.isFinite(baseUptimeMs) || baseUptimeMs < 0) return null; const generatedAt = Number(data.generatedAt || 0); const elapsedSinceSnapshotMs = Number.isFinite(generatedAt) && generatedAt > 0 ? Math.max(0, Date.now() - generatedAt) : 0; return baseUptimeMs + elapsedSinceSnapshotMs; } function renderDebugUptimeTimer () { const valueEl = document.getElementById('debug-maintenance-uptime-value'); if (!valueEl) return; const uptimeMs = getDebugUptimeMsNow(); valueEl.textContent = uptimeMs === null ? '—' : formatElapsedDuration(uptimeMs); } function renderDebugTable (containerId, columns, rows) { const container = document.getElementById(containerId); if (!container) return; if (!Array.isArray(rows) || rows.length === 0) { container.innerHTML = '
    No data.
    '; return; } const headHtml = columns.map((col) => `${escapeHtml(col.label)}`).join(''); const bodyHtml = rows.map((row) => `${columns.map((col) => `${col.render(row)}`).join('')}`).join(''); container.innerHTML = `${headHtml}${bodyHtml}
    `; } function renderDebugDashboardData (data) { _debugLatestData = data; const generatedAt = document.getElementById('debug-generated-at'); if (generatedAt) generatedAt.textContent = `Last update: ${formatTimestamp(data.generatedAt)}`; const usersEl = document.getElementById('debug-users'); if (usersEl) { const users = Array.isArray(data.loggedInUsers) ? data.loggedInUsers : []; usersEl.innerHTML = users.length ? users.map((user) => `${escapeHtml(user.username || 'Unknown')} · ${escapeHtml(formatTimestamp(user.lastSeenAt))}`).join('') : 'No active sessions.'; } const summary = document.getElementById('debug-storage-summary'); if (summary) { const storage = data.storage || {}; const memory = data.memory || {}; const roots = Array.isArray(storage.roots) ? storage.roots.length : 0; const activeStreams = Number(data.videoStream && data.videoStream.activeSessionCount) || 0; const activeLeases = Number(data.videoStream && data.videoStream.activeLeaseCount) || 0; const segmentRetention = Number(data.videoStream && data.videoStream.streamSegmentRetentionCount) || 0; summary.innerHTML = [ ['Configured roots', String(roots)], ['Total used', formatBytes(storage.totalBytes || 0)], ['Total files', String(storage.totalFiles || 0)], ['RAM used', `${formatBytes(memory.usedBytes || 0)} / ${formatBytes(memory.totalBytes || 0)} (${Number(memory.usedPercent || 0).toFixed(1)}%)`], ['Process RSS', formatBytes(memory.processRssBytes || 0)], ['Active streams', String(activeStreams)], ['Active viewers', String(activeLeases)], ['Segment retention', String(segmentRetention)], ].map(([k, v]) => `
    ${escapeHtml(k)}${escapeHtml(v)}
    `).join(''); } const maintenanceSummary = document.getElementById('debug-maintenance-summary'); if (maintenanceSummary) { const maintenance = data.maintenance || {}; const rows = maintenance.rows || {}; const authCleanup = maintenance.authCleanup || {}; const shareMaintenance = maintenance.shareMaintenance || {}; const scheduledRestart = maintenance.scheduledRestart || {}; const scheduledLine = !scheduledRestart.underSystemd ? 'Unavailable (not systemd)' : !scheduledRestart.config || !scheduledRestart.config.enabled ? 'Disabled' : `${scheduledRestartCadenceLabel(scheduledRestart.config.cadence)} at ${scheduledRestart.config.time || '—'}`; maintenanceSummary.innerHTML = [ ['Auth sessions (total)', String(rows.authSessionsTotal || 0)], ['Auth sessions (active)', String(rows.authSessionsActive || 0)], ['Auth sessions (revoked)', String(rows.authSessionsRevoked || 0)], ['Share tokens (total)', String(rows.shareTokensTotal || 0)], ['Share tokens (expired)', String(rows.shareTokensExpired || 0)], ['Auth cleanup last run', formatTimestamp(authCleanup.lastRunAt)], ['Share cleanup last run', formatTimestamp(shareMaintenance.lastRunAt)], ['Server uptime', `${escapeHtml(formatElapsedDuration(getDebugUptimeMsNow()))}`], ['Scheduled restart', scheduledLine], ['Next scheduled restart', formatTimestamp(scheduledRestart.nextDueAt)], ['Pending since', formatTimestamp(scheduledRestart.pendingSinceAt)], ].map(([k, v]) => `
    ${escapeHtml(k)}${k === 'Server uptime' ? v : escapeHtml(v)}
    `).join(''); renderDebugUptimeTimer(); } renderDebugTable( 'debug-roots', [ { label: 'Root', render: (row) => `${escapeHtml(row.path || '')}` }, { label: 'Exists', render: (row) => row.exists ? 'Yes' : 'No' }, { label: 'Used', render: (row) => escapeHtml(formatBytes(row.bytes || 0)) }, { label: 'Files', render: (row) => escapeHtml(String(row.files || 0)) }, { label: 'Folders', render: (row) => escapeHtml(String(row.directories || 0)) }, ], Array.isArray(data.storage && data.storage.roots) ? data.storage.roots : [], ); renderDebugTable( 'debug-video-files', [ { label: 'Video file', render: (row) => `${escapeHtml(row.filePath || '')}` }, { label: 'Viewers', render: (row) => escapeHtml(String(row.viewers || 0)) }, { label: 'Segments', render: (row) => escapeHtml(String(row.stream && row.stream.output ? row.stream.output.segmentFiles : 0)) }, { label: 'Segment bytes', render: (row) => escapeHtml(formatBytes(row.stream && row.stream.output ? row.stream.output.segmentBytes : 0)) }, { label: 'Event cache', render: (row) => escapeHtml(String(row.subtitleCache ? row.subtitleCache.eventEntries : 0)) }, { label: 'Event bytes', render: (row) => escapeHtml(formatBytes(row.subtitleCache ? row.subtitleCache.eventBytes : 0)) }, { label: 'Event PNG bytes', render: (row) => escapeHtml(formatBytes(row.subtitleCache ? row.subtitleCache.eventImageBytes : 0)) }, { label: 'Frame cache', render: (row) => escapeHtml(String(row.subtitleCache ? row.subtitleCache.frameEntries : 0)) }, { label: 'Frame bytes', render: (row) => escapeHtml(formatBytes(row.subtitleCache ? row.subtitleCache.frameBytes : 0)) }, { label: 'Retention', render: (row) => escapeHtml(String(row.stream ? row.stream.segmentRetentionCount : 0)) }, { label: 'Slowest seg', render: (row) => { const v = row.stream ? row.stream.slowestViewerSegmentIndex : -1; return escapeHtml(v === -1 ? '\u2014' : String(v)); } }, { label: 'Pruned until', render: (row) => escapeHtml(String(row.stream ? row.stream.segmentPrunedUntil : 0)) }, { label: 'Session ID', render: (row) => escapeHtml((row.activeSessionIds || []).join(', ') || '—') }, ], Array.isArray(data.videoFiles) ? data.videoFiles : [], ); renderDebugTable( 'debug-orphaned-streams', [ { label: 'Output directory', render: (row) => `${escapeHtml(row.outputDir || '')}` }, { label: 'Files', render: (row) => escapeHtml(String(row.output && row.output.totalFiles || 0)) }, { label: 'Bytes', render: (row) => escapeHtml(formatBytes(row.output && row.output.totalBytes || 0)) }, { label: 'Segments', render: (row) => escapeHtml(String(row.output && row.output.segmentFiles || 0)) }, ], Array.isArray(data.videoStream && data.videoStream.orphanedOutputDirs) ? data.videoStream.orphanedOutputDirs : [], ); const subtitleSection = document.getElementById('debug-subtitle-log-section'); const subtitlePath = document.getElementById('debug-subtitle-log-path'); const subtitleMeta = document.getElementById('debug-subtitle-log-meta'); const subtitleOpen = document.getElementById('debug-open-subtitle-log-folder'); const subtitleLog = data.subtitleDebugLog || {}; if (subtitleSection && subtitlePath && subtitleMeta && subtitleOpen) { if (!subtitleLog.exists) { subtitleSection.classList.add('hidden'); } else { subtitleSection.classList.remove('hidden'); subtitlePath.textContent = subtitleLog.path || 'Unknown path'; const fileCount = Number(subtitleLog.files || 0); subtitleMeta.textContent = `${fileCount} log file${fileCount === 1 ? '' : 's'} · ${formatBytes(subtitleLog.bytes || 0)}`; subtitleOpen.dataset.subtitleLogPath = subtitleLog.path || ''; subtitleOpen.disabled = !subtitleLog.path; } } } function csvEscape (value) { const raw = String(value == null ? '' : value); if (/[,"\n\r]/.test(raw)) return `"${raw.replace(/"/g, '""')}"`; return raw; } function toCsv (rows, columns) { const header = columns.join(','); const body = rows.map((row) => columns.map((col) => csvEscape(row[col])).join(',')).join('\n'); return `${header}\n${body}`; } async function copyDebugText (text, successMessage) { const payload = String(text || ''); if (!payload.trim()) { toast('No debug data to copy yet.', 'err'); return; } try { await navigator.clipboard.writeText(payload); toast(successMessage, 'ok'); } catch { toast('Could not copy to clipboard.', 'err'); } } function copyDebugUsersJson () { const users = Array.isArray(_debugLatestData && _debugLatestData.loggedInUsers) ? _debugLatestData.loggedInUsers : []; void copyDebugText(JSON.stringify(users, null, 2), 'Copied users JSON.'); } function copyDebugStorageJson () { const payload = { generatedAt: _debugLatestData && _debugLatestData.generatedAt, storage: _debugLatestData && _debugLatestData.storage, memory: _debugLatestData && _debugLatestData.memory, }; void copyDebugText(JSON.stringify(payload, null, 2), 'Copied storage JSON.'); } function copyDebugMaintenanceJson () { const payload = { generatedAt: _debugLatestData && _debugLatestData.generatedAt, maintenance: _debugLatestData && _debugLatestData.maintenance, }; void copyDebugText(JSON.stringify(payload, null, 2), 'Copied maintenance JSON.'); } function copyDebugVideoFilesCsv () { const files = Array.isArray(_debugLatestData && _debugLatestData.videoFiles) ? _debugLatestData.videoFiles : []; const rows = files.map((row) => ({ filePath: row.filePath || '', viewers: Number(row.viewers || 0), segmentFiles: Number(row.stream && row.stream.output ? row.stream.output.segmentFiles : 0), segmentBytes: Number(row.stream && row.stream.output ? row.stream.output.segmentBytes : 0), eventEntries: Number(row.subtitleCache ? row.subtitleCache.eventEntries : 0), eventBytes: Number(row.subtitleCache ? row.subtitleCache.eventBytes : 0), eventPngBytes: Number(row.subtitleCache ? row.subtitleCache.eventImageBytes : 0), frameEntries: Number(row.subtitleCache ? row.subtitleCache.frameEntries : 0), frameBytes: Number(row.subtitleCache ? row.subtitleCache.frameBytes : 0), segmentRetentionCount: Number(row.stream ? row.stream.segmentRetentionCount : 0), slowestViewerSegmentIndex: row.stream ? row.stream.slowestViewerSegmentIndex : -1, segmentPrunedUntil: Number(row.stream ? row.stream.segmentPrunedUntil : 0), sessionIds: Array.isArray(row.activeSessionIds) ? row.activeSessionIds.join(';') : '', })); const csv = toCsv(rows, [ 'filePath', 'viewers', 'segmentFiles', 'segmentBytes', 'eventEntries', 'eventBytes', 'eventPngBytes', 'frameEntries', 'frameBytes', 'segmentRetentionCount', 'slowestViewerSegmentIndex', 'segmentPrunedUntil', 'sessionIds', ]); void copyDebugText(csv, 'Copied video/cache CSV.'); } function copyDebugOrphanedCsv () { const rowsRaw = Array.isArray(_debugLatestData && _debugLatestData.videoStream && _debugLatestData.videoStream.orphanedOutputDirs) ? _debugLatestData.videoStream.orphanedOutputDirs : []; const rows = rowsRaw.map((row) => ({ outputDir: row.outputDir || '', totalFiles: Number(row.output && row.output.totalFiles || 0), totalBytes: Number(row.output && row.output.totalBytes || 0), segmentFiles: Number(row.output && row.output.segmentFiles || 0), segmentBytes: Number(row.output && row.output.segmentBytes || 0), })); const csv = toCsv(rows, ['outputDir', 'totalFiles', 'totalBytes', 'segmentFiles', 'segmentBytes']); void copyDebugText(csv, 'Copied orphaned output CSV.'); } async function openSubtitleDebugLogFolder () { const button = document.getElementById('debug-open-subtitle-log-folder'); const targetPath = String(button && button.dataset && button.dataset.subtitleLogPath || '').trim(); if (!targetPath) return; try { await navigateTo(targetPath, { label: 'Subtitle Logs', originalName: 'Subtitle Logs', alias: null, path: targetPath, isUserFolder: false, isDebugLogFolder: true, }); closeDebugModal(); } catch (err) { toast(err.message || 'Failed to open subtitle log folder.', 'err'); } } async function refreshDebugDashboard () { const data = await api('GET', '/admin/debug/stream-stats'); if (!data) return; renderDebugDashboardData(data); } async function openDebugModal () { const modal = document.getElementById('debug-modal'); if (!modal) return; modal.classList.remove('hidden'); await refreshDebugDashboard(); if (_debugRefreshTimer) clearInterval(_debugRefreshTimer); _debugRefreshTimer = setInterval(() => { void refreshDebugDashboard(); }, 5000); if (_debugUptimeTimer) clearInterval(_debugUptimeTimer); _debugUptimeTimer = setInterval(() => { renderDebugUptimeTimer(); }, 1000); } function closeDebugModal () { const modal = document.getElementById('debug-modal'); if (modal) modal.classList.add('hidden'); if (_debugRefreshTimer) { clearInterval(_debugRefreshTimer); _debugRefreshTimer = null; } if (_debugUptimeTimer) { clearInterval(_debugUptimeTimer); _debugUptimeTimer = null; } } function animateBadgeToTarget (targetEl) { const badge = document.getElementById('admin-update-badge'); if (!badge || !targetEl) return; if (badge.parentElement === targetEl) return; const from = badge.getBoundingClientRect(); targetEl.appendChild(badge); const to = badge.getBoundingClientRect(); const dx = from.left - to.left; const dy = from.top - to.top; badge.style.transition = 'none'; badge.style.transform = `translate(${dx}px, ${dy}px)`; badge.style.willChange = 'transform'; requestAnimationFrame(() => { badge.style.transition = 'transform 240ms cubic-bezier(0.22, 1, 0.36, 1)'; badge.style.transform = 'translate(0, 0)'; }); const cleanup = () => { badge.style.transition = ''; badge.style.transform = ''; badge.style.willChange = ''; badge.removeEventListener('transitionend', cleanup); }; badge.addEventListener('transitionend', cleanup); } function moveBadgeToTarget (targetEl) { const badge = document.getElementById('admin-update-badge'); if (!badge || !targetEl) return; if (badge.parentElement === targetEl) return; badge.style.transition = ''; badge.style.transform = ''; badge.style.willChange = ''; targetEl.appendChild(badge); } function syncAdminUpdateBadgeAnchor ({ animate = true, forceUserAnchor = false } = {}) { const badge = document.getElementById('admin-update-badge'); const userMenuBtn = document.getElementById('btn-user-menu'); const adminBtn = document.getElementById('btn-admin'); if (!badge || !userMenuBtn || !adminBtn) return; const userDropdown = userMenuBtn.closest('.topbar-dropdown'); const userMenuOpen = !!(userDropdown && userDropdown.classList.contains('open')); const target = forceUserAnchor ? userMenuBtn : (userMenuOpen ? adminBtn : userMenuBtn); if (badge.classList.contains('hidden')) { moveBadgeToTarget(userMenuBtn); return; } if (animate) animateBadgeToTarget(target); else moveBadgeToTarget(target); } function setAdminUpdateBadge (count) { const badge = document.getElementById('admin-update-badge'); const userMenuBtn = document.getElementById('btn-user-menu'); if (!badge || !userMenuBtn) return; if (!STATE.isAdmin || !Number.isFinite(count) || count <= 0) { badge.classList.add('hidden'); badge.textContent = ''; if (badge.parentElement !== userMenuBtn) userMenuBtn.appendChild(badge); userMenuBtn.removeAttribute('data-update-count'); return; } const whole = Math.floor(count); const capped = Math.min(whole, 99); badge.textContent = capped >= 99 ? '99+' : String(capped); badge.classList.remove('hidden'); userMenuBtn.dataset.updateCount = String(whole); syncAdminUpdateBadgeAnchor(); } function pulseAdminUpdateButton () { const btn = document.getElementById('admin-shutdown-btn'); if (!btn) return; if (typeof btn.scrollIntoView === 'function') { btn.scrollIntoView({ behavior: 'smooth', block: 'center' }); } btn.classList.remove('admin-update-highlight'); // Force reflow so repeated openings can replay the pulse animation. void btn.offsetWidth; btn.classList.add('admin-update-highlight'); setTimeout(() => { btn.classList.remove('admin-update-highlight'); }, 1800); } async function openAdminModal () { if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return; const adminModal = document.getElementById('admin-modal'); if (!adminModal) return; adminModal.classList.remove('hidden'); await refreshGlobalFavicon(); await refreshAdminConfig(); await refreshAdminUsers(); await refreshAdminUpdateStatus({ pulseIfUpdateAvailable: true }); syncScheduledRestartControls(!!(_adminUpdateStatus && _adminUpdateStatus.underSystemd)); } async function refreshAdminConfig () { if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return; const doc = document; const data = await api('GET', '/admin/config'); if (!data) return; _adminConfigCache = data; if (!doc.defaultView || doc.defaultView.closed) return; const userPathInput = doc.getElementById('admin-user-path'); const sizeInput = doc.getElementById('admin-user-size-limit'); if (userPathInput) userPathInput.value = data.userPath || ''; if (sizeInput) { sizeInput.value = data.userFolderSizeLimit ? formatBytes(data.userFolderSizeLimit) : ''; updateAdminSizeFeedback(sizeInput.value); } const srEnabled = doc.getElementById('admin-scheduled-restart-enabled'); const srCadence = doc.getElementById('admin-scheduled-restart-cadence'); const srTime = doc.getElementById('admin-scheduled-restart-time'); const sr = data.scheduledRestart || {}; if (srEnabled) srEnabled.checked = !!sr.enabled; if (srCadence) srCadence.value = sr.cadence || 'daily'; if (srTime) srTime.value = sr.time || '04:00'; const underSystemd = !!(_adminUpdateStatus && _adminUpdateStatus.underSystemd); syncScheduledRestartControls(underSystemd); const container = doc.getElementById('admin-paths'); if (!container) return; container.innerHTML = ''; for (const p of data.paths) { const row = doc.createElement('div'); row.className = 'path-row'; row.innerHTML = `${p}`; row.querySelector('button').addEventListener('click', () => { row.remove(); }); container.appendChild(row); } } async function refreshAdminUsers () { if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return; const doc = document; const data = await api('GET', '/admin/users'); if (!data) return; if (!doc.defaultView || doc.defaultView.closed) return; const container = doc.getElementById('admin-users-list'); if (!container) return; container.innerHTML = ''; // Need paths for permission rows const cfg = await api('GET', '/admin/config'); if (!doc.defaultView || doc.defaultView.closed) return; const paths = cfg ? (cfg.effectivePaths || []) : []; for (const u of data.users) { const row = doc.createElement('div'); row.className = 'user-row'; row.innerHTML = ` ${u.username} ${u.isAdmin ? 'Admin' : ''} ${u.username === STATE.username ? '' : ``} `; row.querySelector('[data-action="edit"]').addEventListener('click', () => openUserModal(u, paths)); const deleteBtn = row.querySelector('[data-action="delete"]'); if (deleteBtn) deleteBtn.addEventListener('click', async () => { if (!await showConfirm('Delete user', `Delete user "${u.username}"? This cannot be undone.`)) return; try { await api('DELETE', `/admin/users/${u.id}`); toast('User deleted.', 'ok'); await refreshAdminUsers(); } catch (err) { toast(err.message, 'err'); } }); container.appendChild(row); } await refreshAdminOrphanUserFolders(); } async function refreshAdminOrphanUserFolders () { if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return; const doc = document; const section = doc.getElementById('admin-orphan-userfolders-section'); const list = doc.getElementById('admin-orphan-userfolders-list'); if (!section || !list) return; let data = null; try { data = await api('GET', '/admin/orphan-userfolders'); } catch { section.classList.add('hidden'); list.innerHTML = ''; return; } if (!doc.defaultView || doc.defaultView.closed) return; const folders = Array.isArray(data && data.folders) ? data.folders : []; if (!folders.length) { section.classList.add('hidden'); list.innerHTML = ''; return; } section.classList.remove('hidden'); list.innerHTML = ''; for (const folder of folders) { const row = doc.createElement('div'); row.className = 'user-row orphan-folder-row'; const name = doc.createElement('span'); name.className = 'user-name'; name.textContent = folder.folderName || 'Unknown folder'; const info = doc.createElement('span'); info.className = 'orphan-folder-meta'; const itemCount = Number(folder.itemCount) || 0; info.textContent = `${itemCount} item${itemCount === 1 ? '' : 's'}`; const openBtn = doc.createElement('button'); openBtn.dataset.action = 'open-orphan-folder'; openBtn.textContent = 'Open folder'; openBtn.addEventListener('click', async () => { const targetPath = String(folder.path || '').trim(); if (!targetPath) return; try { const syntheticRoot = { label: name.textContent, originalName: name.textContent, alias: null, path: targetPath, isUserFolder: true, isOrphanUserFolder: true, }; await navigateTo(targetPath, syntheticRoot); const adminModal = doc.getElementById('admin-modal'); if (adminModal) adminModal.classList.add('hidden'); } catch (err) { toast(err.message || 'Failed to open folder.', 'err'); } }); row.appendChild(name); row.appendChild(info); row.appendChild(openBtn); list.appendChild(row); } } async function refreshAdminUpdateStatus (opts = {}) { const pulseIfUpdateAvailable = !!opts.pulseIfUpdateAvailable; const btn = document.getElementById('admin-shutdown-btn'); _adminUpdateStatus = null; btn.textContent = 'Shut down server'; setAdminUpdateBadge(0); syncScheduledRestartControls(false); try { const data = await api('GET', '/admin/update-status'); if (!data) return; _adminUpdateStatus = data; const updateCount = (data.underSystemd && Array.isArray(data.commitsAhead)) ? data.commitsAhead.length : 0; setAdminUpdateBadge(updateCount); if (!data.underSystemd) { btn.textContent = 'Shut down server'; syncScheduledRestartControls(false); } else if (data.commitsAhead.length === 0) { btn.textContent = 'Restart Server'; syncScheduledRestartControls(true); } else { btn.textContent = 'Restart & Update'; syncScheduledRestartControls(true); if (pulseIfUpdateAvailable) pulseAdminUpdateButton(); } } catch { // Not critical; button stays as "Shut down server". syncScheduledRestartControls(false); } } function openUserModal (user, paths) { const modal = document.getElementById('user-modal'); modal.classList.remove('hidden'); document.getElementById('user-modal-title').textContent = user ? `Edit: ${user.username}` : 'New User'; document.getElementById('user-error').classList.add('hidden'); const usernameInput = document.getElementById('user-username'); usernameInput.value = user ? user.username : ''; usernameInput.readOnly = !!user; document.getElementById('user-password').value = ''; const adminChk = document.getElementById('user-is-admin'); const editingOwnAccount = !!(user && String(user.username || '').toLowerCase() === String(STATE.username || '').toLowerCase()); adminChk.checked = user ? user.isAdmin : false; adminChk.disabled = editingOwnAccount; adminChk.title = editingOwnAccount ? 'You cannot remove admin privileges from your own account.' : ''; // Password placeholder document.getElementById('user-password').placeholder = user ? 'Leave blank to keep current' : 'Min 8 characters'; // Build permissions grid const permDiv = document.getElementById('user-permissions'); permDiv.innerHTML = ''; if (paths.length) { const heading = document.createElement('h4'); heading.textContent = 'Path Permissions'; permDiv.appendChild(heading); const isAdminUser = !!(user && user.isAdmin); // Mirror the is-admin checkbox so toggling it live-updates the perm rows. const rebuildPermRows = (admin) => { permDiv.querySelectorAll('.perm-row').forEach(r => { r.querySelectorAll('input[type=checkbox]').forEach(cb => { cb.disabled = admin; if (admin) cb.checked = true; }); r.title = admin ? 'Admins always have full access' : ''; }); }; adminChk.addEventListener('change', () => rebuildPermRows(adminChk.checked)); const syncReadWriteConstraints = (row, admin = false) => { const readCb = row.querySelector('input[data-type="read"]'); const writeCb = row.querySelector('input[data-type="write"]'); if (!readCb || !writeCb) return; if (admin) { readCb.checked = true; writeCb.checked = true; readCb.disabled = true; writeCb.disabled = true; return; } readCb.disabled = false; if (!readCb.checked) { writeCb.checked = false; writeCb.disabled = true; } else { writeCb.disabled = false; } }; const syncAllReadWriteConstraints = () => { const admin = adminChk.checked; permDiv.querySelectorAll('.perm-row').forEach((row) => { syncReadWriteConstraints(row, admin); }); }; for (const p of paths) { const label = p.split(/[\\/]/).pop(); const perms = user && user.permissions ? (user.permissions[label] || {}) : {}; const row = document.createElement('div'); row.className = 'perm-row'; const readChecked = isAdminUser || perms.read; const writeChecked = isAdminUser || perms.write; row.innerHTML = ` ${label} `; if (isAdminUser) row.title = 'Admins always have full access'; const readCb = row.querySelector('input[data-type="read"]'); if (readCb) { readCb.addEventListener('change', () => { syncReadWriteConstraints(row, adminChk.checked); }); } permDiv.appendChild(row); } syncAllReadWriteConstraints(); adminChk.addEventListener('change', syncAllReadWriteConstraints); } document.getElementById('user-form').onsubmit = async (e) => { e.preventDefault(); const password = document.getElementById('user-password').value; const isAdmin = document.getElementById('user-is-admin').checked; const permissions = {}; permDiv.querySelectorAll('input[data-label]').forEach(cb => { const lbl = cb.dataset.label; if (!permissions[lbl]) permissions[lbl] = {}; permissions[lbl][cb.dataset.type] = cb.checked; }); try { if (user) { const body = { isAdmin, permissions }; if (password) body.password = password; await api('PATCH', `/admin/users/${user.id}`, body); } else { const uname = document.getElementById('user-username').value.trim(); await api('POST', '/admin/users', { username: uname, password, isAdmin, permissions }); } modal.classList.add('hidden'); toast('User saved.', 'ok'); await refreshAdminUsers(); } catch (err) { document.getElementById('user-error').textContent = err.message; document.getElementById('user-error').classList.remove('hidden'); } }; } // ─────────────────────────────────────────────────────────────────────────── // SVG ICONS // ─────────────────────────────────────────────────────────────────────────── const IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'ico', 'avif', 'heif', 'heic']); const VIDEO_EXTS = new Set(['mp4', 'webm', 'ogv', 'mov', 'avi', 'mkv']); const AUDIO_EXTS = new Set(['mp3', 'ogg', 'wav', 'flac', 'aac', 'm4a']); const MODEL_EXTS = new Set(['stl', 'obj']); const DOC_EXTS = new Set(['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'ods', 'odp']); 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']); const ARCHIVE_EXTS = new Set(['zip', 'tar', 'gz', 'bz2', 'xz', 'rar', '7z']); const MAX_DIRECT_SVG_THUMB_BYTES = 1024 * 1024; function iconFolder (size = 52) { return ` `; } function iconFile (name, size = 52) { const color = fileAccentColor(name); let symbol = ''; return ` `; } function watchStatusForTile (item) { if (!item || item.isDir) return null; if (!VIDEO_EXTS.has(extOf(item.name || ''))) return null; const cached = STATE.watchedStatusByPath[item.path]; if (cached === 'fully' || cached === 'partway') return cached; const currentUser = String(STATE.username || '').trim(); if (!currentUser) return null; const watchedBy = item.watchedBy && typeof item.watchedBy === 'object' ? item.watchedBy : {}; const statusRaw = watchedBy[currentUser]; const status = String(statusRaw || '').toLowerCase(); if (status === 'fully' || status === 'partway') return status; return null; } function renderWatchedOverlayOnIcon (iconEl, watchStatus) { if (!iconEl) return; const existing = iconEl.querySelector('.watched-overlay'); if (existing) existing.remove(); if (watchStatus !== 'fully' && watchStatus !== 'partway') return; const overlay = document.createElement('div'); overlay.className = `watched-overlay watched-overlay--${watchStatus}`; overlay.innerHTML = watchedEyeFilledSvg(); iconEl.appendChild(overlay); } function findTileIconByPath (filePath) { if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') return null; const tile = Array.from(document.querySelectorAll('.file-item')).find((el) => el.dataset.path === filePath); if (!tile) return null; return tile.querySelector('.icon'); } function watchStatusFromWatchedBy (watchedBy) { const currentUser = String(STATE.username || '').trim(); if (!currentUser) return null; const map = watchedBy && typeof watchedBy === 'object' ? watchedBy : {}; const statusRaw = map[currentUser]; const status = String(statusRaw || '').toLowerCase(); if (status === 'fully' || status === 'partway') return status; return null; } async function loadWatchedStatusesForCurrentDir () { const dirAtStart = STATE.currentDir; if (!dirAtStart) return; const videoItems = (STATE.items || []).filter((item) => item && !item.isDir && VIDEO_EXTS.has(extOf(item.name || '')) ); if (!videoItems.length) return; const loadId = ++STATE.watchedLoadId; let statusMap = null; const filePaths = videoItems.map((item) => item.path); const bulk = await api('POST', '/files/watched-statuses', { filePaths }).catch(() => null); if (bulk && bulk.statuses && typeof bulk.statuses === 'object') { statusMap = {}; for (const item of videoItems) { const status = String(bulk.statuses[item.path] || '').toLowerCase(); statusMap[item.path] = status === 'fully' || status === 'partway' ? status : null; } } // Compatibility fallback for older servers that do not expose bulk statuses yet. if (!statusMap) { statusMap = {}; const statuses = await Promise.all(videoItems.map(async (item) => { const meta = await api('GET', `/files/meta?file=${encodeURIComponent(item.path)}`).catch(() => null); return { path: item.path, status: watchStatusFromWatchedBy(meta && meta.watchedBy), }; })); for (const entry of statuses) { statusMap[entry.path] = entry.status; } } if (loadId !== STATE.watchedLoadId) return; if (!samePath(STATE.currentDir, dirAtStart)) return; if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') return; for (const item of videoItems) { const status = statusMap[item.path] || null; if (status) STATE.watchedStatusByPath[item.path] = status; else delete STATE.watchedStatusByPath[item.path]; const iconEl = findTileIconByPath(item.path); renderWatchedOverlayOnIcon(iconEl, status); } } function watchedEyeFilledSvg () { return ``; } // ─────────────────────────────────────────────────────────────────────────── // EVENT WIRING // ─────────────────────────────────────────────────────────────────────────── // ─────────────────────────────────────────────────────────────────────────── // THUMBNAIL PREVIEWS // ─────────────────────────────────────────────────────────────────────────── function revokeThumbnails () { STATE.thumbnailUrls.forEach(u => URL.revokeObjectURL(u)); STATE.thumbnailUrls = []; } function disconnectThumbnailObserver () { if (!STATE.thumbnailObserver) return; STATE.thumbnailObserver.disconnect(); STATE.thumbnailObserver = null; } function disconnectFolderIconObserver () { if (!STATE.folderIconObserver) return; STATE.folderIconObserver.disconnect(); STATE.folderIconObserver = null; } function setThumbnailPending (iconEl, pending) { if (!iconEl) return; if (pending) { iconEl.classList.add('thumb-pending'); iconEl.dataset.thumbPending = '1'; return; } iconEl.classList.remove('thumb-pending'); delete iconEl.dataset.thumbPending; } function getThumbnailKind (name) { const ext = extOf(name || ''); if (IMAGE_EXTS.has(ext) || VIDEO_EXTS.has(ext) || MODEL_EXTS.has(ext)) return 'image'; if (CODE_EXTS.has(ext)) return 'text'; return 'badge'; } function maxThumbBytesForKind (kind) { if (kind === 'image') return 15 * 1024 * 1024; if (kind === 'text') return 1024 * 1024; return 0; } function drawTokenizedLine (ctx, line, x, y) { 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; let last = 0; let cursor = x; for (const m of line.matchAll(tokenRe)) { const i = m.index == null ? 0 : m.index; if (i > last) { const plain = line.slice(last, i); ctx.fillStyle = '#dce4ff'; ctx.fillText(plain, cursor, y); cursor += ctx.measureText(plain).width; } const tok = m[0]; if (/^\/\//.test(tok) || /^\/\*/.test(tok)) ctx.fillStyle = '#6f7f9a'; else if (/^['"`]/.test(tok)) ctx.fillStyle = '#9ee37d'; else if (/^\d/.test(tok)) ctx.fillStyle = '#f8c46a'; else ctx.fillStyle = '#8bb4ff'; ctx.fillText(tok, cursor, y); cursor += ctx.measureText(tok).width; last = i + tok.length; } if (last < line.length) { const tail = line.slice(last); ctx.fillStyle = '#dce4ff'; ctx.fillText(tail, cursor, y); } } function textThumbnailDataUrl (text) { const canvas = document.createElement('canvas'); canvas.width = 160; canvas.height = 200; const ctx = canvas.getContext('2d'); if (!ctx) return null; ctx.fillStyle = '#0d111a'; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.font = '8px ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace'; ctx.textBaseline = 'top'; const lines = String(text || '') .replace(/\r\n/g, '\n') .split('\n') .slice(0, 17); let y = 8; for (const line of lines) { drawTokenizedLine(ctx, line.slice(0, 42), 6, y); y += 11; if (y > 190) break; } return canvas.toDataURL('image/png'); } function badgeThumbnailDataUrl (name, kind) { const canvas = document.createElement('canvas'); canvas.width = 160; canvas.height = 200; const ctx = canvas.getContext('2d'); if (!ctx) return null; const ext = (extOf(name || '') || 'file').toUpperCase().slice(0, 5); const color = '#5b7fff'; ctx.fillStyle = '#111826'; ctx.fillRect(0, 0, 160, 200); ctx.fillStyle = color; ctx.fillRect(0, 0, 160, 28); ctx.fillStyle = '#ffffff'; ctx.font = 'bold 12px sans-serif'; ctx.textAlign = 'center'; ctx.fillText(ext, 80, 8); ctx.textAlign = 'left'; ctx.fillStyle = '#9fb1d8'; ctx.font = '10px sans-serif'; ctx.fillText('Preview', 8, 48); ctx.fillStyle = '#dce4ff'; ctx.font = 'bold 11px sans-serif'; ctx.fillText(ext, 8, 66); return canvas.toDataURL('image/png'); } async function buildThumbnailSource (item, blob, kind) { if (kind === 'text') return textThumbnailDataUrl(await blob.text()); return badgeThumbnailDataUrl(item.name, kind); } function observeThumbnailIcon (iconEl) { if (!iconEl || !iconEl.isConnected) return; if (iconEl.dataset.thumbReady === '1') return; if (!('IntersectionObserver' in window)) { void loadOneThumbnail(iconEl); return; } if (!STATE.thumbnailObserver) { STATE.thumbnailObserver = new IntersectionObserver((entries) => { for (const entry of entries) { if (!entry.isIntersecting) continue; const icon = entry.target; STATE.thumbnailObserver.unobserve(icon); void loadOneThumbnail(icon); } }, { root: null, rootMargin: THUMB_OBSERVER_ROOT_MARGIN, threshold: 0.01 }); } STATE.thumbnailObserver.observe(iconEl); } async function loadThumbnails () { const icons = Array.from(document.querySelectorAll('.icon[data-preview-path]')); for (const icon of icons) { observeThumbnailIcon(icon); } const folderIcons = Array.from(document.querySelectorAll('.icon[data-folder-path]')); for (const icon of folderIcons) { observeFolderIcon(icon); } } async function loadOneThumbnail (iconEl) { if (!iconEl.isConnected || !STATE.token) return; if (iconEl.dataset.thumbReady === '1') return; const filePath = iconEl.dataset.previewPath; const item = STATE.items.find(i => i.path === filePath); if (!item) return; const kind = getThumbnailKind(item.name); let srcUrl = null; if (kind === 'badge') { setThumbnailPending(iconEl, false); srcUrl = badgeThumbnailDataUrl(item.name, kind); } else if (kind === 'image') { const ext = extOf(item.name || ''); const useDirectSource = ext === 'ico' || ( ext === 'svg' && typeof item.size === 'number' && item.size > 0 && item.size <= MAX_DIRECT_SVG_THUMB_BYTES ); const url = useDirectSource ? `/api/files/download?file=${encodeURIComponent(filePath)}` : `/api/files/thumbnail?file=${encodeURIComponent(filePath)}`; let res; try { res = await fetch(url, { headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint(), }, }); } catch { return; } if (!useDirectSource && res.status === 404) { setThumbnailPending(iconEl, true); return; } if (!res.ok || !iconEl.isConnected) return; setThumbnailPending(iconEl, false); const blob = await res.blob(); srcUrl = URL.createObjectURL(blob); STATE.thumbnailUrls.push(srcUrl); } else { setThumbnailPending(iconEl, false); const maxBytes = maxThumbBytesForKind(kind); if (maxBytes > 0 && typeof item.size === 'number' && item.size > maxBytes) { srcUrl = badgeThumbnailDataUrl(item.name, kind); } else { const url = `/api/files/download?file=${encodeURIComponent(filePath)}`; let res; try { res = await fetch(url, { headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint(), }, }); } catch { return; } if (!res.ok || !iconEl.isConnected) return; const blob = await res.blob(); srcUrl = await buildThumbnailSource(item, blob, kind); } } if (!srcUrl || !iconEl.isConnected) return; const svg = iconEl.querySelector('svg'); if (!svg) { if (srcUrl.startsWith('blob:')) URL.revokeObjectURL(srcUrl); return; } const NS = 'http://www.w3.org/2000/svg'; const id = `fcp-${Math.random().toString(36).slice(2, 9)}`; // clipPath matches the main file body outline exactly (viewBox 0 0 24 24) const defs = document.createElementNS(NS, 'defs'); const clipPath = document.createElementNS(NS, 'clipPath'); clipPath.setAttribute('id', id); clipPath.setAttribute('clipPathUnits', 'userSpaceOnUse'); const clipShape = document.createElementNS(NS, 'path'); clipShape.setAttribute('d', 'M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z'); clipPath.appendChild(clipShape); defs.appendChild(clipPath); // Image fills the file bounding box; clip keeps it inside the outline const img = document.createElementNS(NS, 'image'); img.setAttribute('href', srcUrl); img.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', srcUrl); img.setAttribute('x', '4'); img.setAttribute('y', '2'); img.setAttribute('width', '16'); img.setAttribute('height', '20'); img.setAttribute('clip-path', `url(#${id})`); img.setAttribute('preserveAspectRatio', 'xMidYMid slice'); // Prepend so existing path/polyline elements (the outline) render on top svg.prepend(img); svg.prepend(defs); iconEl.dataset.thumbReady = '1'; } // ─────────────────────────────────────────────────────────────────────────── // FOLDER ICON THUMBNAILS // ─────────────────────────────────────────────────────────────────────────── function observeFolderIcon (iconEl) { if (!iconEl || !iconEl.isConnected) return; if (iconEl.dataset.thumbReady === '1') return; if (!('IntersectionObserver' in window)) { void loadOneFolderIcon(iconEl); return; } if (!STATE.folderIconObserver) { STATE.folderIconObserver = new IntersectionObserver((entries) => { for (const entry of entries) { if (!entry.isIntersecting) continue; const icon = entry.target; STATE.folderIconObserver.unobserve(icon); void loadOneFolderIcon(icon); } }, { root: null, rootMargin: THUMB_OBSERVER_ROOT_MARGIN, threshold: 0.01 }); } STATE.folderIconObserver.observe(iconEl); } async function loadOneFolderIcon (iconEl) { if (!iconEl.isConnected || !STATE.token) return; if (iconEl.dataset.thumbReady === '1') return; const folderPath = iconEl.dataset.folderPath; if (!folderPath) return; let res; try { res = await fetch(`/api/files/folder-icon?dir=${encodeURIComponent(folderPath)}`, { headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() }, }); } catch { return; } if (!res.ok || !iconEl.isConnected) return; const data = await res.json(); if (!data.icon) return; // No icon available — keep plain folder SVG. // Fetch the thumbnail through the auth-gated endpoint. let thumbRes; try { thumbRes = await fetch( `/api/files/thumbnail?file=${encodeURIComponent(data.icon.filePath)}`, { headers: { Authorization: `Bearer ${STATE.token}`, 'X-Fp': getFingerprint() } }, ); } catch { return; } if (!thumbRes.ok || !iconEl.isConnected) return; const blob = await thumbRes.blob(); const srcUrl = URL.createObjectURL(blob); STATE.thumbnailUrls.push(srcUrl); applyFolderThumbnail(iconEl, srcUrl); } /** * Overlays a thumbnail image inside the folder SVG outline. * The folder viewBox is 0 0 24 24; the folder body covers roughly x=2,y=5 to x=22,y=21. */ function applyFolderThumbnail (iconEl, srcUrl) { if (!iconEl.isConnected) return; const svg = iconEl.querySelector('svg'); if (!svg) { if (srcUrl.startsWith('blob:')) URL.revokeObjectURL(srcUrl); return; } const NS = 'http://www.w3.org/2000/svg'; const id = `fcp-${Math.random().toString(36).slice(2, 9)}`; const defs = document.createElementNS(NS, 'defs'); const clipPath = document.createElementNS(NS, 'clipPath'); clipPath.setAttribute('id', id); clipPath.setAttribute('clipPathUnits', 'userSpaceOnUse'); const clipShape = document.createElementNS(NS, 'path'); // Folder outline path (same as iconFolder SVG path) clipShape.setAttribute('d', 'M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z'); clipPath.appendChild(clipShape); defs.appendChild(clipPath); // Image covers the folder body area; clip keeps it inside the outline. const img = document.createElementNS(NS, 'image'); img.setAttribute('href', srcUrl); img.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', srcUrl); img.setAttribute('x', '2'); img.setAttribute('y', '3'); img.setAttribute('width', '20'); img.setAttribute('height', '18'); img.setAttribute('clip-path', `url(#${id})`); img.setAttribute('preserveAspectRatio', 'xMidYMid slice'); // Prepend so the folder outline strokes render on top. svg.prepend(img); svg.prepend(defs); iconEl.dataset.thumbReady = '1'; } function closeTopbarDropdowns () { // Prevent jump-to-(0,0) glitches by snapping badge back before the menu is hidden. syncAdminUpdateBadgeAnchor({ animate: false, forceUserAnchor: true }); document.querySelectorAll('.topbar-dropdown.open').forEach((dropdown) => { dropdown.classList.remove('open'); const trigger = dropdown.querySelector('button[aria-expanded]'); if (trigger) trigger.setAttribute('aria-expanded', 'false'); }); } function initTopbarDropdowns () { document.querySelectorAll('.topbar-dropdown').forEach((dropdown) => { const trigger = dropdown.querySelector('button[aria-expanded]'); if (!trigger) return; trigger.addEventListener('click', (e) => { e.stopPropagation(); const shouldOpen = !dropdown.classList.contains('open'); closeTopbarDropdowns(); if (shouldOpen) { dropdown.classList.add('open'); trigger.setAttribute('aria-expanded', 'true'); syncAdminUpdateBadgeAnchor(); } }); dropdown.querySelectorAll('.topbar-menu-item').forEach((itemBtn) => { itemBtn.addEventListener('click', () => closeTopbarDropdowns()); }); }); document.addEventListener('click', (e) => { if (e.target && e.target.closest && e.target.closest('.topbar-dropdown')) return; closeTopbarDropdowns(); }); document.addEventListener('keydown', (e) => { if (e.key === 'Escape') closeTopbarDropdowns(); }); } function wireEvents () { initTopbarDropdowns(); // Auth form document.getElementById('auth-form').addEventListener('submit', async (e) => { e.preventDefault(); const username = document.getElementById('auth-username').value.trim(); const password = document.getElementById('auth-password').value; const isSetup = e.target.dataset.mode === 'setup'; const errEl = document.getElementById('auth-error'); const btn = document.getElementById('auth-submit'); btn.disabled = true; btn.textContent = 'Please wait…'; const err = await doLogin(username, password, isSetup); if (err) { errEl.textContent = err; errEl.classList.remove('hidden'); btn.disabled = false; btn.textContent = isSetup ? 'Create Account' : 'Sign In'; } }); // Logout document.getElementById('btn-logout').addEventListener('click', logout); // Hard refresh while keeping auth/session state. document.getElementById('btn-refresh').addEventListener('click', () => { saveSessionState(); location.reload(); }); const topSearchInput = document.getElementById('top-search-input'); const topSearchBtn = document.getElementById('btn-search'); if (topSearchInput && topSearchBtn) { topSearchInput.addEventListener('keydown', (e) => { if (e.key !== 'Enter') return; e.preventDefault(); void runGlobalFileSearch(); }); topSearchBtn.addEventListener('click', () => { void runGlobalFileSearch(); }); } // Upload button document.getElementById('btn-upload').addEventListener('click', () => { if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; } if (!canWrite()) { toast('No write access.', 'err'); return; } document.getElementById('file-input').click(); }); document.getElementById('file-input').addEventListener('change', async (e) => { if (e.target.files.length) await uploadFiles(e.target.files); e.target.value = ''; }); document.getElementById('btn-upload-folder').addEventListener('click', () => { if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; } if (!canWrite()) { toast('No write access.', 'err'); return; } document.getElementById('folder-input').click(); }); document.getElementById('folder-input').addEventListener('change', async (e) => { if (e.target.files.length) await uploadFolderInputFiles(e.target.files); e.target.value = ''; }); document.getElementById('btn-new-folder').addEventListener('click', async () => { await createFolderInCurrentDir(); }); document.getElementById('btn-change-password').addEventListener('click', openChangePasswordModal); document.getElementById('change-password-modal-close').addEventListener('click', () => { document.getElementById('change-password-modal').classList.add('hidden'); }); document.getElementById('sidebar-close').addEventListener('click', (e) => { e.stopPropagation(); hideSidebarPanel(); }); const mobileQuery = window.matchMedia(MOBILE_BREAKPOINT_QUERY); const syncSidebarForViewport = () => { if (isMobileViewport()) { hideSidebarPanel(); return; } if (!STATE.selectedItem) openFolderSidebar(); }; if (typeof mobileQuery.addEventListener === 'function') { mobileQuery.addEventListener('change', syncSidebarForViewport); } else if (typeof mobileQuery.addListener === 'function') { mobileQuery.addListener(syncSidebarForViewport); } // Click outside grid clears selection and returns to folder sidebar info. document.getElementById('main-content').addEventListener('click', (e) => { closeCustomContextMenu(); if (!e.target.closest('.file-item')) closeSidebar(); }); document.getElementById('main-content').addEventListener('contextmenu', (e) => { if (isMobileViewport()) return; if (e.target && e.target.closest && e.target.closest('.file-item')) return; e.preventDefault(); closeSidebar(); openFolderContextMenu(e.clientX, e.clientY); }); window.addEventListener('resize', closeCustomContextMenu); window.addEventListener('scroll', closeCustomContextMenu, true); window.addEventListener('popstate', (event) => { void onBrowserPopState(event); }); document.addEventListener('click', closeCustomContextMenu); document.addEventListener('keydown', (e) => { if (e.key === 'Escape') closeCustomContextMenu(); if (e.key === 'Escape') closeDebugModal(); }); // Admin panel document.getElementById('btn-admin').addEventListener('click', openAdminModal); document.getElementById('btn-debug').addEventListener('click', () => { void openDebugModal(); }); document.getElementById('btn-admin-favicon').addEventListener('click', () => { void openGlobalFaviconPicker(); }); document.getElementById('admin-modal-close').addEventListener('click', () => document.getElementById('admin-modal').classList.add('hidden')); const debugModalClose = document.getElementById('debug-modal-close'); if (debugModalClose) debugModalClose.addEventListener('click', closeDebugModal); const debugRefresh = document.getElementById('debug-refresh'); if (debugRefresh) debugRefresh.addEventListener('click', () => { void refreshDebugDashboard(); }); const debugCopyUsers = document.getElementById('debug-copy-users'); if (debugCopyUsers) debugCopyUsers.addEventListener('click', copyDebugUsersJson); const debugCopyStorage = document.getElementById('debug-copy-storage'); if (debugCopyStorage) debugCopyStorage.addEventListener('click', copyDebugStorageJson); const debugCopyMaintenance = document.getElementById('debug-copy-maintenance'); if (debugCopyMaintenance) debugCopyMaintenance.addEventListener('click', copyDebugMaintenanceJson); const debugCopyVideoFiles = document.getElementById('debug-copy-video-files'); if (debugCopyVideoFiles) debugCopyVideoFiles.addEventListener('click', copyDebugVideoFilesCsv); const debugCopyOrphaned = document.getElementById('debug-copy-orphaned'); if (debugCopyOrphaned) debugCopyOrphaned.addEventListener('click', copyDebugOrphanedCsv); const debugOpenSubtitleLog = document.getElementById('debug-open-subtitle-log-folder'); if (debugOpenSubtitleLog) debugOpenSubtitleLog.addEventListener('click', () => { void openSubtitleDebugLogFolder(); }); const debugModal = document.getElementById('debug-modal'); if (debugModal) debugModal.addEventListener('click', (e) => { if (e.target && e.target.id === 'debug-modal') closeDebugModal(); }); // Add path document.getElementById('admin-add-path').addEventListener('click', () => { const val = document.getElementById('admin-new-path').value.trim(); if (!val) return; const row = document.createElement('div'); row.className = 'path-row'; row.innerHTML = `${val}`; row.querySelector('button').addEventListener('click', () => row.remove()); document.getElementById('admin-paths').appendChild(row); document.getElementById('admin-new-path').value = ''; }); // Save paths document.getElementById('admin-save-paths').addEventListener('click', async () => { const rows = document.querySelectorAll('#admin-paths .path-row span'); const paths = [...rows].map(s => s.textContent.trim()).filter(Boolean); try { await api('PUT', '/admin/config', { paths }); toast('Paths saved.', 'ok'); await loadRoots(); } catch (err) { toast(err.message, 'err'); } }); const sizeInput = document.getElementById('admin-user-size-limit'); if (sizeInput) { sizeInput.addEventListener('input', () => { updateAdminSizeFeedback(sizeInput.value); }); } const scheduledEnabledInput = document.getElementById('admin-scheduled-restart-enabled'); if (scheduledEnabledInput) { scheduledEnabledInput.addEventListener('change', () => { syncScheduledRestartControls(!!(_adminUpdateStatus && _adminUpdateStatus.underSystemd)); }); } document.getElementById('admin-save-scheduled-restart').addEventListener('click', async () => { if (!(_adminUpdateStatus && _adminUpdateStatus.underSystemd)) { toast('Scheduled restart is available only under systemd.', 'err'); return; } const rows = document.querySelectorAll('#admin-paths .path-row span'); const paths = [...rows].map(s => s.textContent.trim()).filter(Boolean); const enabled = !!document.getElementById('admin-scheduled-restart-enabled').checked; const cadence = String(document.getElementById('admin-scheduled-restart-cadence').value || '').trim(); const time = String(document.getElementById('admin-scheduled-restart-time').value || '').trim(); if (!time) { toast('Please choose a restart time.', 'err'); return; } const existing = _adminConfigCache || {}; try { await api('PUT', '/admin/config', { paths, userPath: existing.userPath || null, userFolderSizeLimit: existing.userFolderSizeLimit || null, scheduledRestart: { enabled, cadence, time, }, }); toast('Scheduled restart saved.', 'ok'); await refreshAdminConfig(); await refreshAdminUpdateStatus(); } catch (err) { toast(err.message || 'Failed to save scheduled restart settings.', 'err'); } }); document.getElementById('admin-save-userpath').addEventListener('click', async () => { const rows = document.querySelectorAll('#admin-paths .path-row span'); const paths = [...rows].map(s => s.textContent.trim()).filter(Boolean); const userPath = document.getElementById('admin-user-path').value.trim(); const rawLimit = document.getElementById('admin-user-size-limit').value.trim(); const parsed = updateAdminSizeFeedback(rawLimit); if (!parsed.valid) { toast('Please enter a valid user size limit.', 'err'); return; } try { await api('PUT', '/admin/config', { paths, userPath: userPath || null, userFolderSizeLimit: rawLimit ? parsed.bytes : null, }); toast('User folder settings saved.', 'ok'); await loadRoots(); await refreshAdminConfig(); } catch (err) { toast(err.message, 'err'); } }); // Shutdown / restart server document.getElementById('admin-shutdown-btn').addEventListener('click', async () => { const status = _adminUpdateStatus; if (!status || !status.underSystemd) { // Not running under systemd — plain shutdown (manual restart required). if (!await showConfirm('Shut down server', 'Shut down the server? You will lose access until it is restarted manually.')) return; } else if (status.commitsAhead.length === 0) { // Under systemd, no updates — restart only. if (!await showConfirm('Restart server', 'No update available. Would you like to restart?', { okLabel: 'Restart' })) return; } else { // Under systemd, updates available. const commitList = renderUpdateCommitListHtml(status.commitsAhead); const msg = `Updates available:

    ${commitList}

    Update now?`; if (!await showConfirm('Restart & Update', msg, { html: true, okLabel: 'Update now', modalClass: 'confirm-modal-wide' })) return; } try { await api('POST', '/admin/shutdown'); const toastMsg = (!status || !status.underSystemd) ? 'Server is shutting down\u2026' : status.commitsAhead.length > 0 ? 'Server is updating and restarting\u2026' : 'Server is restarting\u2026'; toast(toastMsg, 'ok'); document.getElementById('admin-modal').classList.add('hidden'); } catch { // Fetch may throw because the connection closes before a response arrives. const toastMsg = (!status || !status.underSystemd) ? 'Server is shutting down\u2026' : status.commitsAhead.length > 0 ? 'Server is updating and restarting\u2026' : 'Server is restarting\u2026'; toast(toastMsg, 'ok'); document.getElementById('admin-modal').classList.add('hidden'); } setTimeout(() => location.reload(), 3000); }); // New user document.getElementById('admin-new-user-btn').addEventListener('click', async () => { const cfg = await api('GET', '/admin/config'); const paths = cfg ? (cfg.effectivePaths || []) : []; openUserModal(null, paths); }); // User modal close document.getElementById('user-modal-close').addEventListener('click', () => document.getElementById('user-modal').classList.add('hidden')); // Rename modal close document.getElementById('rename-modal-close').addEventListener('click', () => document.getElementById('rename-modal').classList.add('hidden')); // Close modals on backdrop click document.querySelectorAll('.modal-overlay').forEach(overlay => { overlay.addEventListener('click', e => { if (e.target === overlay) overlay.classList.add('hidden'); }); }); } // ─────────────────────────────────────────────────────────────────────────── // BOOT // ─────────────────────────────────────────────────────────────────────────── (async function boot () { wireEvents(); initDragDrop(); window.addEventListener('beforeunload', () => { saveSessionState(); releaseActivePreviewVideoStreamSession({ keepalive: true }); }); window.addEventListener('pagehide', () => { releaseActivePreviewVideoStreamSession({ keepalive: true }); }); await initAuth(); })();