/* ========================================================= 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, // Background refresh state autoRefreshTimer: null, uploadInProgress: false, // Blob URLs for thumbnail previews — revoked on each grid rebuild thumbnailUrls: [], // Preview overlay state previewObjectUrl: null, previewSourceEl: null, // SVG element that triggered the preview previewClosing: false, // guard to prevent double-close during animation }; 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'; // ─────────────────────────────────────────────────────────────────────────── // 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 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 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 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 */ } } // ─────────────────────────────────────────────────────────────────────────── // 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; headers['X-Fp'] = getFingerprint(); } 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) { return new Promise((resolve) => { const overlay = document.getElementById('confirm-modal'); document.getElementById('confirm-modal-title').textContent = title; document.getElementById('confirm-modal-message').textContent = message; overlay.classList.remove('hidden'); const ok = document.getElementById('confirm-modal-ok'); const cancel = document.getElementById('confirm-modal-cancel'); function finish (result) { overlay.classList.add('hidden'); 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(); }); } /** * 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(); }); } // ─────────────────────────────────────────────────────────────────────────── // AUTH FLOW // ─────────────────────────────────────────────────────────────────────────── function showAuthOverlay (setupMode = false) { document.getElementById('app').classList.add('hidden'); const overlay = document.getElementById('auth-overlay'); 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'); document.getElementById('auth-username').value = ''; document.getElementById('auth-password').value = ''; document.getElementById('auth-username').focus(); document.getElementById('auth-form').dataset.mode = setupMode ? 'setup' : 'login'; } function showApp () { document.getElementById('auth-overlay').classList.add('hidden'); document.getElementById('app').classList.remove('hidden'); document.getElementById('app').classList.add('sidebar-open'); document.getElementById('sidebar').classList.remove('hidden'); document.getElementById('btn-admin').classList.toggle('hidden', !STATE.isAdmin); startAutoRefresh(); } async function initAuth () { // Always generate a fresh key pair so each page-load session is independent await 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(); } 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; clearSessionState(); closePreview(); 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 || null; const preferredRootPath = opts.preferredRootPath || null; if (preferredDir && preferredRootPath) { const preferredRoot = STATE.roots.find(r => samePath(r.path, preferredRootPath)); if (preferredRoot && pathInside(preferredDir, preferredRoot.path)) { try { await navigateTo(preferredDir, preferredRoot, { keepSidebar: true }); 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]); } else { renderRootsView(); } } function renderRootsView () { STATE.currentDir = null; STATE.currentRoot = 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); } } async function navigateTo (absPath, root, opts = {}) { 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(); } function renderBreadcrumb () { const nav = document.getElementById('breadcrumb'); 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.currentDir || !STATE.currentRoot) return; // Build path segments relative to the root const rootPath = STATE.currentRoot.path; const relative = STATE.currentDir === rootPath ? '' : STATE.currentDir.replace(rootPath, '').replace(/^[\\/]/, ''); const parts = [STATE.currentRoot.label, ...relative.split(/[\\/]/).filter(Boolean)]; let accumulated = rootPath; 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]; // Capture the path for this crumb const capturedPath = i === 0 ? rootPath : accumulated; if (i < parts.length - 1) { crumb.addEventListener('click', () => navigateTo(capturedPath, STATE.currentRoot)); } nav.appendChild(crumb); // Advance accumulated path (skip for root label) if (i > 0) accumulated = accumulated + '/' + parts[i]; else if (i === 0 && parts.length > 1) { // After root label, next crumb should append the next segment accumulated = rootPath; } } } async function refreshFolderStats () { const el = document.getElementById('folder-stats'); if (!STATE.currentDir) { 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); 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.size, it.isDir]) .sort((a, b) => String(a[0]).localeCompare(String(b[0]))), ); } async function incrementalRefreshCurrentDir () { if (!STATE.currentDir || STATE.uploadInProgress) return; closeSidebar(); 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(); } } } 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 renderFileGrid () { revokeThumbnails(); const grid = document.getElementById('file-grid'); grid.innerHTML = ''; const empty = document.getElementById('empty-notice'); const sorted = [...STATE.items].sort((a, b) => { if (a.isDir !== b.isDir) return a.isDir ? -1 : 1; return a.name.localeCompare(b.name); }); empty.classList.toggle('hidden', sorted.length > 0); for (const item of sorted) { grid.appendChild(makeFileItem(item)); } loadThumbnails(); } function makeFileItem (item) { const el = document.createElement('div'); el.className = 'file-item'; el.dataset.path = item.path; const icon = document.createElement('div'); icon.className = 'icon'; icon.innerHTML = item.isDir ? iconFolder() : iconFile(item.name); if (!item.isDir) { icon.dataset.previewPath = item.path; } el.appendChild(icon); const name = document.createElement('div'); name.className = 'name'; name.textContent = item.name; el.appendChild(name); // Single-click: open sidebar el.addEventListener('click', (e) => { e.stopPropagation(); if (item._root) { // Clicking a root tile goes straight in navigateTo(item.path, item._root); return; } selectItem(el, item); }); // Double-click: enter folder or view/download file el.addEventListener('dblclick', (e) => { e.stopPropagation(); if (item.isDir) { navigateTo(item.path, STATE.currentRoot); } else { downloadOrView(item, icon.querySelector('svg')); } }); return el; } function selectItem (el, item) { document.querySelectorAll('.file-item.selected').forEach(e => e.classList.remove('selected')); el.classList.add('selected'); STATE.selectedItem = item; openSidebar(item); } // ─────────────────────────────────────────────────────────────────────────── // SIDEBAR // ─────────────────────────────────────────────────────────────────────────── async function openSidebar (item) { 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); 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 = ''; if (!item.isDir) { const meta = await api('GET', `/files/meta?file=${encodeURIComponent(item.path)}`); if (meta) { dl.innerHTML = `
Size
${formatBytes(meta.size)}
Modified
${new Date(meta.mtime).toLocaleString()}
Uploaded by
${meta.uploader || '—'}
Downloaded by
${meta.downloaders.join(', ') || '—'}
`; } // View / download button 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); } else { dl.innerHTML = `
Type
Folder
`; const btnOpen = document.createElement('button'); btnOpen.textContent = 'Open folder'; btnOpen.addEventListener('click', () => navigateTo(item.path, STATE.currentRoot)); actions.appendChild(btnOpen); } // Rename button (write access required) if (canWrite()) { const btnRen = document.createElement('button'); btnRen.textContent = 'Rename'; btnRen.addEventListener('click', () => openRenameModal(item)); actions.appendChild(btnRen); const btnDel = document.createElement('button'); btnDel.textContent = 'Delete'; btnDel.className = 'danger'; btnDel.addEventListener('click', () => deleteItem(item)); actions.appendChild(btnDel); } } function openFolderSidebar () { 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 = ''; 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; dl.innerHTML = `
Path
${STATE.currentDir}
Folders
${dirs}
Files
${files}
`; } function closeSidebar () { document.querySelectorAll('.file-item.selected').forEach(e => e.classList.remove('selected')); STATE.selectedItem = null; openFolderSidebar(); } // ─────────────────────────────────────────────────────────────────────────── // 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 (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 () { if (!STATE.previewObjectUrl) return; URL.revokeObjectURL(STATE.previewObjectUrl); STATE.previewObjectUrl = null; } 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 (DOC_EXTS.has(ext)) return '#f97316'; if (CODE_EXTS.has(ext)) return '#38bdf8'; if (ARCHIVE_EXTS.has(ext)) return '#facc15'; return '#7880a0'; } function animatePreviewOpen (sourceSvgEl, sheetEl) { if (!sourceSvgEl || !sheetEl || !sourceSvgEl.isConnected) return Promise.resolve({ startScale: 0.12 }); const start = sourceSvgEl.getBoundingClientRect(); const end = sheetEl.getBoundingClientRect(); if (!start.width || !start.height || !end.width || !end.height) return Promise.resolve({ startScale: 0.12 }); // Hide source icon for the duration of the preview sourceSvgEl.style.visibility = 'hidden'; const ghost = document.createElement('div'); ghost.className = 'preview-ghost'; ghost.style.left = `${start.left}px`; ghost.style.top = `${start.top}px`; ghost.style.width = `${start.width}px`; ghost.style.height = `${start.height}px`; const clone = sourceSvgEl.cloneNode(true); clone.style.width = '100%'; clone.style.height = '100%'; clone.style.display = 'block'; ghost.appendChild(clone); document.body.appendChild(ghost); // Bézier path: random control points in viewport space const vw = window.innerWidth; const vh = window.innerHeight; const startCx = start.left + start.width / 2; const startCy = start.top + start.height / 2; const endCx = end.left + end.width / 2; const endCy = end.top + end.height / 2; const cp1x = startCx + (Math.random() - 0.5) * vw * 0.8; const cp1y = startCy + (Math.random() - 0.5) * vh * 0.8; const cp2x = endCx + (Math.random() - 0.5) * vw * 0.6; const cp2y = endCy + (Math.random() - 0.5) * vh * 0.6; // Random full rotations: -3 to +3 const totalDeg = (Math.random() * 6 - 3) * 360; const duration = 640; const startTime = performance.now(); const startScale = start.width / end.width; function easeInOut (t) { return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2; } function bezier1D (p0, p1, p2, p3, t) { const u = 1 - t; return u * u * u * p0 + 3 * u * u * t * p1 + 3 * u * t * t * p2 + t * t * t * p3; } return new Promise((resolve) => { function frame (now) { const raw = Math.min((now - startTime) / duration, 1); const t = easeInOut(raw); const cx = bezier1D(startCx, cp1x, cp2x, endCx, t); const cy = bezier1D(startCy, cp1y, cp2y, endCy, t); const w = start.width + (end.width - start.width) * t; const h = start.height + (end.height - start.height) * t; const angle = t * totalDeg; const opacity = raw > 0.82 ? 1 - (raw - 0.82) / 0.18 : 1; ghost.style.left = `${cx - w / 2}px`; ghost.style.top = `${cy - h / 2}px`; ghost.style.width = `${w}px`; ghost.style.height = `${h}px`; ghost.style.transform = `rotate(${angle}deg)`; ghost.style.opacity = opacity; if (raw < 1) { requestAnimationFrame(frame); } else { ghost.remove(); resolve({ startScale }); } } requestAnimationFrame(frame); }); } } function animatePreviewClose (sourceSvgEl, sheetEl) { if (!sourceSvgEl || !sheetEl || !sourceSvgEl.isConnected) return Promise.resolve(); const sheetRect = sheetEl.getBoundingClientRect(); const iconRect = sourceSvgEl.getBoundingClientRect(); if (!sheetRect.width || !iconRect.width) return Promise.resolve(); // Ghost starts at sheet center, icon-sized, then flies back to icon const ghost = document.createElement('div'); ghost.className = 'preview-ghost'; const clone = sourceSvgEl.cloneNode(true); clone.style.width = '100%'; clone.style.height = '100%'; clone.style.display = 'block'; ghost.appendChild(clone); document.body.appendChild(ghost); const vw = window.innerWidth; const vh = window.innerHeight; const startCx = sheetRect.left + sheetRect.width / 2; const startCy = sheetRect.top + sheetRect.height / 2; const endCx = iconRect.left + iconRect.width / 2; const endCy = iconRect.top + iconRect.height / 2; const cp1x = startCx + (Math.random() - 0.5) * vw * 0.6; const cp1y = startCy + (Math.random() - 0.5) * vh * 0.6; const cp2x = endCx + (Math.random() - 0.5) * vw * 0.5; const cp2y = endCy + (Math.random() - 0.5) * vh * 0.5; const totalDeg = (Math.random() * 6 - 3) * 360; const duration = 580; const startTime = performance.now(); function easeInOut (t) { return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2; } function bezier1D (p0, p1, p2, p3, t) { const u = 1 - t; return u * u * u * p0 + 3 * u * u * t * p1 + 3 * u * t * t * p2 + t * t * t * p3; } return new Promise((resolve) => { function frame (now) { const raw = Math.min((now - startTime) / duration, 1); const t = easeInOut(raw); const cx = bezier1D(startCx, cp1x, cp2x, endCx, t); const cy = bezier1D(startCy, cp1y, cp2y, endCy, t); const angle = t * totalDeg; const opacity = raw < 0.85 ? 1 : 1 - (raw - 0.85) / 0.15; ghost.style.left = `${cx - iconRect.width / 2}px`; ghost.style.top = `${cy - iconRect.height / 2}px`; ghost.style.width = `${iconRect.width}px`; ghost.style.height = `${iconRect.height}px`; ghost.style.transform = `rotate(${angle}deg)`; ghost.style.opacity = opacity; if (raw < 1) { requestAnimationFrame(frame); } else { ghost.remove(); sourceSvgEl.style.visibility = ''; resolve(); } } requestAnimationFrame(frame); }); } async function closePreview () { const overlay = document.getElementById('preview-overlay'); const body = document.getElementById('preview-body'); if (!overlay || !body) return; if (overlay.classList.contains('hidden')) return; if (STATE.previewClosing) return; STATE.previewClosing = true; const sourceSvgEl = STATE.previewSourceEl; if (sourceSvgEl && sourceSvgEl.isConnected) { const sheet = document.getElementById('preview-sheet'); // Shrink the sheet first, then fly ghost back await new Promise((res) => { const a = sheet.animate( [{ transform: 'scale(1)', opacity: 1 }, { transform: 'scale(0.06)', opacity: 0 }], { duration: 180, easing: 'cubic-bezier(0.4, 0, 1, 1)', fill: 'forwards' } ); a.onfinish = res; a.oncancel = res; }); overlay.classList.add('preview-prep'); sheet.style.transform = ''; sheet.style.opacity = ''; await animatePreviewClose(sourceSvgEl, sheet); } else if (sourceSvgEl) { sourceSvgEl.style.visibility = ''; } overlay.classList.add('hidden'); overlay.classList.remove('preview-prep'); body.innerHTML = ''; clearPreviewObjectUrl(); STATE.previewSourceEl = null; 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.click(); } async function renderPreviewBody (item, blob, objectUrl) { const body = 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 (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) { const blob = await fetchFileBlob(item); if (!blob) { toast('Download failed.', 'err'); return; } clearPreviewObjectUrl(); const objectUrl = URL.createObjectURL(blob); STATE.previewObjectUrl = objectUrl; const overlay = document.getElementById('preview-overlay'); const sheet = document.getElementById('preview-sheet'); const title = document.getElementById('preview-title'); const dlBtn = document.getElementById('preview-download'); sheet.style.setProperty('--preview-accent', fileAccentColor(item.name)); title.textContent = item.name; dlBtn.onclick = () => triggerDownload(item.name, objectUrl); await renderPreviewBody(item, blob, objectUrl); STATE.previewSourceEl = sourceSvgEl || null; overlay.classList.add('preview-prep'); overlay.classList.remove('hidden'); const { startScale } = await animatePreviewOpen(sourceSvgEl, sheet); overlay.classList.remove('preview-prep'); // Scale sheet up from the icon's apparent size, driven by JS so the start // scale matches the actual icon-to-sheet ratio for this specific invocation const s = (startScale > 0 && startScale < 1) ? startScale : 0.12; const scaleAnim = sheet.animate( [{ transform: `scale(${s})`, opacity: 0 }, { transform: 'scale(1)', opacity: 1 }], { duration: 220, easing: 'cubic-bezier(0.2, 0.9, 0.2, 1.05)', fill: 'forwards' } ); scaleAnim.onfinish = () => { sheet.style.transform = ''; sheet.style.opacity = ''; }; } // ─────────────────────────────────────────────────────────────────────────── // UPLOAD // ─────────────────────────────────────────────────────────────────────────── function canWrite () { if (STATE.isAdmin) return true; if (!STATE.currentRoot) return false; const p = STATE.permissions[STATE.currentRoot.label]; 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; } const totalSize = Array.from(fileList).reduce((sum, f) => sum + (f.size || 0), 0); const formData = new FormData(); for (const f of fileList) formData.append('files', f); // Show upload bar const wrap = document.createElement('div'); wrap.className = 'upload-bar-wrap'; wrap.innerHTML = `Uploading ${fileList.length} file(s)…
`; document.body.appendChild(wrap); STATE.uploadInProgress = true; try { const xhr = new XMLHttpRequest(); xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(STATE.currentDir)}`); xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token); xhr.setRequestHeader('X-Fp', getFingerprint()); xhr.setRequestHeader('X-Upload-Size', String(totalSize)); xhr.upload.addEventListener('progress', e => { if (e.lengthComputable) { wrap.querySelector('.upload-bar-fill').style.width = (e.loaded / e.total * 100) + '%'; } }); await new Promise((resolve, reject) => { xhr.onload = () => { if (xhr.status === 200) resolve(); else reject(new Error(JSON.parse(xhr.responseText).error || 'Upload failed')); }; xhr.onerror = () => reject(new Error('Network error')); xhr.send(formData); }); toast(`Uploaded ${fileList.length} file(s).`, 'ok'); await navigateTo(STATE.currentDir, STATE.currentRoot); } catch (err) { toast(err.message, 'err'); } finally { STATE.uploadInProgress = false; wrap.remove(); } } async function uploadSingleFile (file, targetDir) { const formData = new FormData(); formData.append('files', file); await new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); 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)); xhr.onload = () => xhr.status === 200 ? resolve() : reject(new Error((JSON.parse(xhr.responseText) || {}).error || 'Upload failed')); xhr.onerror = () => reject(new Error('Network error')); xhr.send(formData); }); } 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 (!fileList || !fileList.length) return; const files = Array.from(fileList); const total = files.length; let done = 0; const wrap = document.createElement('div'); wrap.className = 'upload-bar-wrap'; wrap.innerHTML = `Preparing folder upload…
`; document.body.appendChild(wrap); STATE.uploadInProgress = true; try { const dirCache = new Map(); dirCache.set('', STATE.currentDir); for (const file of files) { 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); done++; wrap.querySelector('span').textContent = `Uploading ${done} / ${total} file(s)…`; wrap.querySelector('.upload-bar-fill').style.width = (done / total * 100) + '%'; } toast(`Uploaded ${total} file(s).`, 'ok'); await navigateTo(STATE.currentDir, STATE.currentRoot); } catch (err) { 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; } const wrap = document.createElement('div'); wrap.className = 'upload-bar-wrap'; wrap.innerHTML = `Scanning…
`; document.body.appendChild(wrap); STATE.uploadInProgress = true; try { const toUpload = []; for (const entry of entries) { await collectEntries(entry, STATE.currentDir, toUpload); } if (!toUpload.length) { toast('No files found.', 'err'); return; } let done = 0; const total = toUpload.length; const updateBar = () => { wrap.querySelector('span').textContent = `Uploading ${done} / ${total} file(s)…`; wrap.querySelector('.upload-bar-fill').style.width = (done / total * 100) + '%'; }; updateBar(); for (const { file, targetDir } of toUpload) { await uploadSingleFile(file, targetDir); done++; updateBar(); } toast(`Uploaded ${total} file(s).`, 'ok'); await navigateTo(STATE.currentDir, STATE.currentRoot); } catch (err) { 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 { await api('POST', '/files/rename', { from: item.path, to: newName }); modal.classList.add('hidden'); toast('Renamed.', 'ok'); 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 // ─────────────────────────────────────────────────────────────────────────── async function openAdminModal () { document.getElementById('admin-modal').classList.remove('hidden'); await refreshAdminConfig(); await refreshAdminUsers(); } async function refreshAdminConfig () { const data = await api('GET', '/admin/config'); if (!data) return; const container = document.getElementById('admin-paths'); container.innerHTML = ''; for (const p of data.paths) { const row = document.createElement('div'); row.className = 'path-row'; row.innerHTML = `${p}`; row.querySelector('button').addEventListener('click', () => { row.remove(); }); container.appendChild(row); } } async function refreshAdminUsers () { const data = await api('GET', '/admin/users'); if (!data) return; const container = document.getElementById('admin-users-list'); container.innerHTML = ''; // Need paths for permission rows const cfg = await api('GET', '/admin/config'); const paths = cfg ? (cfg.effectivePaths || []) : []; for (const u of data.users) { const row = document.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); } } 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 = ''; document.getElementById('user-is-admin').checked = user ? user.isAdmin : false; // 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 adminChk = document.getElementById('user-is-admin'); 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)); 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'; permDiv.appendChild(row); } } 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']); const VIDEO_EXTS = new Set(['mp4', 'webm', 'ogv', 'mov', 'avi', 'mkv']); const AUDIO_EXTS = new Set(['mp3', 'ogg', 'wav', 'flac', 'aac', 'm4a']); 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']); function iconFolder (size = 52) { return ` `; } function iconFile (name, size = 52) { const color = fileAccentColor(name); let symbol = ''; return ` `; } // ─────────────────────────────────────────────────────────────────────────── // EVENT WIRING // ─────────────────────────────────────────────────────────────────────────── // ─────────────────────────────────────────────────────────────────────────── // THUMBNAIL PREVIEWS // ─────────────────────────────────────────────────────────────────────────── function revokeThumbnails () { STATE.thumbnailUrls.forEach(u => URL.revokeObjectURL(u)); STATE.thumbnailUrls = []; } function getThumbnailKind (name) { const ext = extOf(name || ''); if (IMAGE_EXTS.has(ext)) return 'image'; if (VIDEO_EXTS.has(ext)) return 'video'; if (CODE_EXTS.has(ext)) return 'text'; if (AUDIO_EXTS.has(ext)) return 'audio'; if (ext === 'pdf') return 'pdf'; return 'badge'; } function maxThumbBytesForKind (kind) { if (kind === 'image') return 15 * 1024 * 1024; if (kind === 'video') return 25 * 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 = kind === 'audio' ? '#c084fc' : kind === 'pdf' ? '#f97316' : '#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 videoThumbnailDataUrl (blob) { const src = URL.createObjectURL(blob); try { const video = document.createElement('video'); video.src = src; video.muted = true; video.preload = 'metadata'; await new Promise((resolve, reject) => { const fail = () => reject(new Error('video load failed')); video.addEventListener('error', fail, { once: true }); video.addEventListener('loadeddata', resolve, { once: true }); }); const targetTime = Number.isFinite(video.duration) && video.duration > 1 ? 1 : 0; await new Promise((resolve) => { video.currentTime = targetTime; video.addEventListener('seeked', resolve, { once: true }); }); 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); const rw = video.videoWidth || 1; const rh = video.videoHeight || 1; const scale = Math.max(canvas.width / rw, canvas.height / rh); const dw = rw * scale; const dh = rh * scale; ctx.drawImage(video, (canvas.width - dw) / 2, (canvas.height - dh) / 2, dw, dh); // subtle play badge ctx.fillStyle = 'rgba(0,0,0,0.45)'; ctx.beginPath(); ctx.arc(80, 100, 18, 0, Math.PI * 2); ctx.fill(); ctx.fillStyle = '#ffffff'; ctx.beginPath(); ctx.moveTo(75, 90); ctx.lineTo(75, 110); ctx.lineTo(90, 100); ctx.closePath(); ctx.fill(); return canvas.toDataURL('image/png'); } catch { return null; } finally { URL.revokeObjectURL(src); } } async function buildThumbnailSource (item, blob, kind) { if (kind === 'image') return URL.createObjectURL(blob); if (kind === 'video') return await videoThumbnailDataUrl(blob); if (kind === 'text') return textThumbnailDataUrl(await blob.text()); return badgeThumbnailDataUrl(item.name, kind); } async function loadThumbnails () { const icons = Array.from(document.querySelectorAll('.icon[data-preview-path]')); if (!icons.length) return; const queue = [...icons]; async function worker () { while (queue.length) { await loadOneThumbnail(queue.shift()); } } // Four concurrent fetches — keeps the Pi's network from flooding await Promise.all(Array.from({ length: Math.min(4, icons.length) }, worker)); } 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' || kind === 'audio' || kind === 'pdf') { srcUrl = badgeThumbnailDataUrl(item.name, kind); } else { 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 (kind === 'image' && srcUrl) STATE.thumbnailUrls.push(srcUrl); } } 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'; } function wireEvents () { // 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(); }); // 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 () => { 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'); } }); // Sidebar is persistent; close button is intentionally disabled. // Click outside grid clears selection and returns to folder sidebar info. document.getElementById('main-content').addEventListener('click', (e) => { if (!e.target.closest('.file-item')) closeSidebar(); }); // Admin panel document.getElementById('btn-admin').addEventListener('click', openAdminModal); document.getElementById('admin-modal-close').addEventListener('click', () => document.getElementById('admin-modal').classList.add('hidden')); // 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'); } }); // Shutdown server document.getElementById('admin-shutdown-btn').addEventListener('click', async () => { if (!await showConfirm('Shut down server', 'Shut down the server? You will lose access until it is restarted manually.')) return; try { await api('POST', '/admin/shutdown'); toast('Server is shutting down…', 'ok'); document.getElementById('admin-modal').classList.add('hidden'); } catch { // Fetch may throw because the connection closes before a response arrives. toast('Server is shutting down…', 'ok'); document.getElementById('admin-modal').classList.add('hidden'); } }); // 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')); // Preview close document.getElementById('preview-close').addEventListener('click', closePreview); document.getElementById('preview-overlay').addEventListener('click', (e) => { if (e.target.id === 'preview-overlay') closePreview(); }); document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && !document.getElementById('preview-overlay').classList.contains('hidden')) { closePreview(); } }); // 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); await initAuth(); })();