// ═══════════════════════════════════════════════════════════════════ // HOST IT NOW · ENTERPRISE CLOUD VAULT & EDGE RELAY CONTROLLER // ═══════════════════════════════════════════════════════════════════ const TOOL_BASE = (() => { const p = window.location.pathname.replace(/\/+$/, ''); return p; })(); function getApiUrl(endpoint) { const p = endpoint.startsWith('/') ? endpoint : '/' + endpoint; if (TOOL_BASE && !p.startsWith(TOOL_BASE)) { return TOOL_BASE + p; } return p; } // ───────────────────────────────────────────── // Global State // ───────────────────────────────────────────── let sessions = []; let currentId = null; let currentSession = null; let currentFiles = []; let activeIngestTab = 'vault'; // 'vault', 'path', 'relay' let currentViewMode = 'grid'; // 'grid', 'list' let activeCategoryFilter = 'all'; let searchQuery = ''; const relayFiles = {}; // sessionId -> { path: File } const evtSources = {}; // sessionId -> EventSource let countdownInterval = null; let serverExplorerCurrentPath = ''; // ───────────────────────────────────────────── // Initialization // ───────────────────────────────────────────── document.addEventListener('DOMContentLoaded', () => { setupDragAndDrop(); startCountdownLoop(); initApp(); }); async function initApp() { await refreshSessionsList(); if (!sessions.length) { await createNewSession('Default Vault', 'server_background', 0); } else { const storedId = localStorage.getItem('hin_current'); if (storedId && sessions.find(s => s.id === storedId)) { switchSession(storedId); } else { switchSession(sessions[0].id); } } } // ───────────────────────────────────────────── // Session Management & Governance // ───────────────────────────────────────────── async function refreshSessionsList() { try { const res = await fetch(getApiUrl('/get_sessions_list')); if (!res.ok) return; const data = await res.json(); if (data.success && data.sessions) { sessions = data.sessions; renderSessionsRail(); updateGlobalMetrics(); } } catch (e) { console.error('Failed to fetch sessions list:', e); } } function updateGlobalMetrics() { const totalFiles = sessions.reduce((acc, s) => acc + (s.file_count || 0), 0); const totalReqs = sessions.reduce((acc, s) => acc + (s.requests || 0), 0); const totalBytes = sessions.reduce((acc, s) => acc + (s.bytes_served || 0), 0); const mSessions = document.getElementById('metric-total-sessions'); const mFiles = document.getElementById('metric-total-files'); const mReqs = document.getElementById('metric-total-reqs'); const mBytes = document.getElementById('metric-total-bytes'); if (mSessions) mSessions.textContent = sessions.length; if (mFiles) mFiles.textContent = totalFiles; if (mReqs) mReqs.textContent = totalReqs; if (mBytes) mBytes.textContent = (totalBytes / (1024 * 1024)).toFixed(1) + ' MB'; } function renderSessionsRail() { const rail = document.getElementById('sessionTabsRail'); if (!rail) return; rail.innerHTML = ''; sessions.forEach(s => { const tab = document.createElement('div'); tab.className = 'session-tab' + (s.id === currentId ? ' active' : ''); const modeIcon = s.mode === 'relay' ? 'fa-tower-broadcast' : s.mode === 'local_path' ? 'fa-hard-drive' : 'fa-cloud'; const name = s.name || ('Session ' + s.id.slice(-6)); const remStr = formatRemainingTime(s.remaining_sec, s.time_limit_sec); tab.innerHTML = ` ${name} ${remStr} `; tab.onclick = () => switchSession(s.id); rail.appendChild(tab); }); } function switchSession(sid) { currentId = sid; localStorage.setItem('hin_current', sid); currentSession = sessions.find(s => s.id === sid); renderSessionsRail(); loadSessionDetails(sid); } async function loadSessionDetails(sid) { try { const res = await fetch(getApiUrl(`/get_session_files/${sid}`)); const data = await res.json(); if (data.session) { currentSession = data.session; updateSessionHUD(); } if (data.mode === 'relay') { setStatus('Browser Relay Mode · Files served directly from device memory', true); if (relayFiles[sid]) { const map = relayFiles[sid]; const fileList = Object.entries(map).map(([path, f]) => ({ name: f.name, path: path, size: f.size, url: `${TOOL_BASE}/files/${currentId}/${path}`, folder: path.includes('/') ? path.split('/').slice(0, -1).join('/') : '(Root)', is_code: /\.(json|html?|css|js|ts|ya?ml)$/i.test(f.name), is_image: /\.(jpe?g|png|gif|webp|svg|bmp|ico)$/i.test(f.name) })); currentFiles = fileList; renderFilesExplorer(); } else { currentFiles = []; renderFilesExplorer(); } connectSSE(sid); } else if (data.files && data.files.length) { currentFiles = data.files.map(f => ({ ...f, url: f.url.startsWith(TOOL_BASE) ? f.url : (TOOL_BASE + f.url) })); setStatus(`Active Storage: ${data.current_path}`, true); renderFilesExplorer(); } else { currentFiles = []; setStatus(data.current_path ? `Empty Directory: ${data.current_path}` : 'Ready to host content · Drop files or map a folder', false); renderFilesExplorer(); } checkTunnel(sid); } catch (e) { console.error('Error loading session files:', e); } } function updateSessionHUD() { if (!currentSession) return; // Mode Pill const modePill = document.getElementById('sessionModePill'); const modeText = document.getElementById('sessionModeText'); if (modeText) { if (currentSession.mode === 'relay') modeText.textContent = 'Browser Relay'; else if (currentSession.mode === 'local_path') modeText.textContent = 'Server Path'; else modeText.textContent = 'Server Vault'; } // TTL Pill const ttlText = document.getElementById('sessionTtlText'); if (ttlText) { ttlText.textContent = formatRemainingTime(currentSession.remaining_sec, currentSession.time_limit_sec); } // Status details const countPill = document.getElementById('statusFileCountPill'); const sizePill = document.getElementById('statusSizePill'); if (countPill) countPill.textContent = `${currentSession.file_count || currentFiles.length} files`; if (sizePill) sizePill.textContent = `${((currentSession.total_bytes || 0) / (1024 * 1024)).toFixed(2)} MB`; } function startCountdownLoop() { if (countdownInterval) clearInterval(countdownInterval); countdownInterval = setInterval(() => { let needsRefresh = false; sessions.forEach(s => { if (s.time_limit_sec > 0 && s.remaining_sec !== undefined) { s.remaining_sec = Math.max(0, s.remaining_sec - 1); const pill = document.getElementById(`ttl-pill-${s.id}`); if (pill) pill.textContent = formatRemainingTime(s.remaining_sec, s.time_limit_sec); if (s.remaining_sec === 0) needsRefresh = true; } }); if (currentSession && currentSession.time_limit_sec > 0) { const ttlText = document.getElementById('sessionTtlText'); if (ttlText) ttlText.textContent = formatRemainingTime(currentSession.remaining_sec, currentSession.time_limit_sec); } if (needsRefresh) { refreshSessionsList(); } }, 1000); } function formatRemainingTime(remSec, limitSec) { if (!limitSec || limitSec <= 0) return 'Unlimited'; if (remSec === undefined || remSec === null) return 'Active'; if (remSec <= 0) return 'Expired'; const h = Math.floor(remSec / 3600); const m = Math.floor((remSec % 3600) / 60); const s = remSec % 60; if (h > 0) return `${h}h ${m}m left`; if (m > 0) return `${m}m ${s}s left`; return `${s}s left`; } // ───────────────────────────────────────────── // Create & Delete Session // ───────────────────────────────────────────── async function createNewSession(name, mode, timeLimitSec) { try { const res = await fetch(getApiUrl('/create_session'), { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: name || '', mode: mode || 'server_background', time_limit_sec: parseInt(timeLimitSec || '0', 10) }) }); const data = await res.json(); if (data.success) { showToast(`Session "${data.session?.name || data.session_id}" created`, 'success'); await refreshSessionsList(); switchSession(data.session_id); return data.session_id; } else { showToast('Failed to create session: ' + (data.error || 'unknown error'), 'error'); } } catch (e) { showToast('Error: ' + e.message, 'error'); } } async function deleteCurrentSession() { if (!currentId) return; if (!confirm('Are you sure you want to delete this session and all its hosted contents?')) return; try { await fetch(getApiUrl('/delete_session'), { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ session_id: currentId }) }); if (evtSources[currentId]) { evtSources[currentId].close(); delete evtSources[currentId]; } delete relayFiles[currentId]; showToast('Session deleted', 'info'); await refreshSessionsList(); if (sessions.length) { switchSession(sessions[0].id); } else { await createNewSession('Cloud Vault', 'server_background', 0); } } catch (e) { showToast('Failed to delete session: ' + e.message, 'error'); } } // ───────────────────────────────────────────── // Ingesting Modes & Uploads // ───────────────────────────────────────────── function switchIngestMode(mode) { activeIngestTab = mode; document.querySelectorAll('.ingest-tab').forEach(t => { t.classList.toggle('active', t.getAttribute('data-tab') === mode); }); const vBox = document.getElementById('mode-content-vault'); const pBox = document.getElementById('mode-content-path'); const rBox = document.getElementById('mode-content-relay'); if (vBox) vBox.classList.toggle('hidden', mode !== 'vault'); if (pBox) pBox.classList.toggle('hidden', mode !== 'path'); if (rBox) rBox.classList.toggle('hidden', mode !== 'relay'); } function setupDragAndDrop() { const dropzone = document.getElementById('vaultDropzone'); if (!dropzone) return; ['dragenter', 'dragover'].forEach(name => { dropzone.addEventListener(name, (e) => { e.preventDefault(); e.stopPropagation(); dropzone.classList.add('dragover'); }); }); ['dragleave', 'drop'].forEach(name => { dropzone.addEventListener(name, (e) => { e.preventDefault(); e.stopPropagation(); dropzone.classList.remove('dragover'); }); }); dropzone.addEventListener('drop', async (e) => { const files = e.dataTransfer.files; if (!files || !files.length) return; // Check if first file is a zip if (files.length === 1 && files[0].name.toLowerCase().endsWith('.zip')) { await uploadZipFile(files[0]); } else { await uploadFilesToServerVault(Array.from(files)); } }); } async function handleVaultUpload(evt, type) { const files = Array.from(evt.target.files || []); if (!files.length) return; await uploadFilesToServerVault(files, type); evt.target.value = ''; } async function handleZipUpload(evt) { const file = evt.target.files?.[0]; if (!file) return; await uploadZipFile(file); evt.target.value = ''; } async function uploadFilesToServerVault(files, type = 'file') { if (!currentId) return; const progressBox = document.getElementById('uploadProgressBox'); const progressBar = document.getElementById('uploadProgressBar'); const statusText = document.getElementById('uploadStatusText'); const percentText = document.getElementById('uploadPercentText'); if (progressBox) progressBox.classList.remove('hidden'); if (statusText) statusText.textContent = `Uploading ${files.length} file(s) to server vault...`; const formData = new FormData(); formData.append('session_id', currentId); files.forEach(f => { const relPath = type === 'folder' ? (f.webkitRelativePath || f.name) : f.name; formData.append('files', f); formData.append('relative_paths', relPath); }); try { const xhr = new XMLHttpRequest(); xhr.open('POST', getApiUrl('/upload_files')); xhr.upload.onprogress = (e) => { if (e.lengthComputable) { const pct = Math.round((e.loaded / e.total) * 100); if (progressBar) progressBar.style.width = pct + '%'; if (percentText) percentText.textContent = pct + '%'; } }; xhr.onload = async () => { if (xhr.status >= 200 && xhr.status < 300) { showToast(`Successfully hosted ${files.length} file(s) in background!`, 'success'); if (progressBar) progressBar.style.width = '100%'; if (percentText) percentText.textContent = '100%'; setTimeout(() => { if (progressBox) progressBox.classList.add('hidden'); }, 1200); await refreshSessionsList(); loadSessionDetails(currentId); } else { showToast('Upload failed: ' + xhr.responseText, 'error'); if (progressBox) progressBox.classList.add('hidden'); } }; xhr.onerror = () => { showToast('Network error during upload', 'error'); if (progressBox) progressBox.classList.add('hidden'); }; xhr.send(formData); } catch (e) { showToast('Error uploading: ' + e.message, 'error'); if (progressBox) progressBox.classList.add('hidden'); } } async function uploadZipFile(file) { if (!currentId) return; const progressBox = document.getElementById('uploadProgressBox'); const progressBar = document.getElementById('uploadProgressBar'); const statusText = document.getElementById('uploadStatusText'); const percentText = document.getElementById('uploadPercentText'); if (progressBox) progressBox.classList.remove('hidden'); if (statusText) statusText.textContent = `Unpacking archive "${file.name}" on server...`; const formData = new FormData(); formData.append('session_id', currentId); formData.append('zip_file', file); try { const xhr = new XMLHttpRequest(); xhr.open('POST', getApiUrl('/upload_zip')); xhr.upload.onprogress = (e) => { if (e.lengthComputable) { const pct = Math.round((e.loaded / e.total) * 100); if (progressBar) progressBar.style.width = pct + '%'; if (percentText) percentText.textContent = pct + '%'; } }; xhr.onload = async () => { if (xhr.status >= 200 && xhr.status < 300) { const data = JSON.parse(xhr.responseText); showToast(`Extracted and hosted ${data.count} file(s) from ZIP!`, 'success'); setTimeout(() => { if (progressBox) progressBox.classList.add('hidden'); }, 1200); await refreshSessionsList(); loadSessionDetails(currentId); } else { showToast('Failed to unpack ZIP', 'error'); if (progressBox) progressBox.classList.add('hidden'); } }; xhr.onerror = () => { showToast('Network error uploading ZIP', 'error'); if (progressBox) progressBox.classList.add('hidden'); }; xhr.send(formData); } catch (e) { showToast('Error uploading ZIP: ' + e.message, 'error'); if (progressBox) progressBox.classList.add('hidden'); } } async function setFolderPath(explicitPath) { const input = document.getElementById('pathInput'); const path = explicitPath || (input ? input.value.trim() : ''); if (!path) { showToast('Please enter an absolute server path', 'error'); return; } try { const res = await fetch(getApiUrl('/set_session_path'), { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ session_id: currentId, path }) }); const data = await res.json(); if (data.success) { showToast(`Mapped directory: ${path}`, 'success'); await refreshSessionsList(); loadSessionDetails(currentId); } else { showToast(data.error || 'Failed to map directory', 'error'); } } catch (e) { showToast('Error setting path: ' + e.message, 'error'); } } // ───────────────────────────────────────────── // Browser Relay (SSE) Implementation // ───────────────────────────────────────────── async function handleRelaySelect(evt, type) { const files = evt.target.files; if (!files || !files.length || !currentId) return; if (!relayFiles[currentId]) relayFiles[currentId] = {}; const map = relayFiles[currentId]; for (const f of files) { const key = type === 'folder' ? (f.webkitRelativePath || f.name) : f.name; map[key] = f; } await fetch(getApiUrl('/set_session_path'), { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ session_id: currentId, path: '(Relay Mode)' }) }); showToast(`Relaying ${files.length} files from device memory`, 'info'); connectSSE(currentId); await refreshSessionsList(); loadSessionDetails(currentId); evt.target.value = ''; } function connectSSE(sid) { if (evtSources[sid]) return; const es = new EventSource(getApiUrl(`/stream_events/${sid}`)); es.onmessage = async (e) => { if (!e.data) return; try { const msg = JSON.parse(e.data); if (msg.type === 'request_file') { await fulfillRelay(sid, msg.req_id, msg.filename); } } catch (_) {} }; evtSources[sid] = es; } async function fulfillRelay(sid, reqId, filename) { const map = relayFiles[sid] || {}; const file = map[filename]; const fd = new FormData(); fd.append('req_id', reqId); if (file) fd.append('file', file); await fetch(getApiUrl('/fulfill_request'), { method: 'POST', body: fd }).catch(() => {}); } // ───────────────────────────────────────────── // Explorer & File Grid Rendering // ───────────────────────────────────────────── function setViewMode(mode) { currentViewMode = mode; const container = document.getElementById('filesContainer'); const btnGrid = document.getElementById('btnViewGrid'); const btnList = document.getElementById('btnViewList'); if (container) { container.classList.toggle('grid-mode', mode === 'grid'); container.classList.toggle('list-mode', mode === 'list'); } if (btnGrid) btnGrid.classList.toggle('active', mode === 'grid'); if (btnList) btnList.classList.toggle('active', mode === 'list'); } function setCategoryFilter(category) { activeCategoryFilter = category; document.querySelectorAll('.filter-chip').forEach(c => { c.classList.toggle('active', c.getAttribute('data-filter') === category); }); renderFilesExplorer(); } function handleSearchFilter(query) { searchQuery = (query || '').toLowerCase().trim(); renderFilesExplorer(); } function renderFilesExplorer() { const container = document.getElementById('filesContainer'); if (!container) return; container.innerHTML = ''; // Filter files let filtered = currentFiles; if (activeCategoryFilter === 'images') { filtered = filtered.filter(f => f.is_image); } else if (activeCategoryFilter === 'code') { filtered = filtered.filter(f => f.is_code); } else if (activeCategoryFilter === 'docs') { filtered = filtered.filter(f => !f.is_image && !f.is_code); } if (searchQuery) { filtered = filtered.filter(f => f.name.toLowerCase().includes(searchQuery) || (f.folder && f.folder.toLowerCase().includes(searchQuery)) || (f.path && f.path.toLowerCase().includes(searchQuery)) ); } if (!filtered.length) { container.innerHTML = `
${currentFiles.length === 0 ? 'No files hosted in this session yet. Upload files, a folder, or map a server path above.' : 'No files match your search query or filter.'}
QR Code library loading...
`; } modal.style.display = 'flex'; } function closeQrModal() { const modal = document.getElementById('qrModal'); if (modal) modal.style.display = 'none'; } // Media Lightbox function previewFile(jsonStr) { try { const f = JSON.parse(decodeURIComponent(jsonStr)); if (f.is_image) { openLightbox(f); } else if (f.is_code) { openCodeModal(f); } else { window.open(f.url, '_blank'); } } catch (e) { console.error('Cannot preview file:', e); } } function openLightbox(f) { const modal = document.getElementById('lightboxModal'); const title = document.getElementById('lightboxTitle'); const img = document.getElementById('lightboxImg'); const dims = document.getElementById('lightboxDims'); const size = document.getElementById('lightboxSize'); const urlEl = document.getElementById('lightboxUrl'); const dlBtn = document.getElementById('lightboxDlBtn'); if (!modal || !img) return; if (title) title.textContent = f.name; img.src = f.url; if (size) size.textContent = `Size: ${f.size ? formatBytes(f.size) : '--'}`; if (urlEl) urlEl.textContent = f.url; if (dlBtn) dlBtn.href = f.url; img.onload = () => { if (dims) dims.textContent = `${img.naturalWidth} × ${img.naturalHeight} px`; }; modal.style.display = 'flex'; } function closeLightbox() { const modal = document.getElementById('lightboxModal'); if (modal) modal.style.display = 'none'; } // Code & JSON Viewer Modal async function openCodeModal(f) { const modal = document.getElementById('codeModal'); const title = document.getElementById('codeModalTitle'); const content = document.getElementById('codeModalContent'); if (!modal || !content) return; if (title) title.innerHTML = ` ${f.name}`; content.textContent = 'Loading document content...'; modal.style.display = 'flex'; try { const res = await fetch(f.url); const text = await res.text(); // If JSON, format nicely if (f.name.toLowerCase().endsWith('.json')) { try { const parsed = JSON.parse(text); content.textContent = JSON.stringify(parsed, null, 2); return; } catch (_) {} } content.textContent = text; } catch (e) { content.textContent = 'Failed to load file: ' + e.message; } } function closeCodeModal() { const modal = document.getElementById('codeModal'); if (modal) modal.style.display = 'none'; } function copyCodeContent() { const content = document.getElementById('codeModalContent'); if (content) copyText(content.textContent); } // Server Directory Explorer Modal async function openServerDirModal() { const modal = document.getElementById('serverDirModal'); if (!modal) return; modal.style.display = 'flex'; await navigateServerDir(''); } function closeServerDirModal() { const modal = document.getElementById('serverDirModal'); if (modal) modal.style.display = 'none'; } async function navigateServerDir(path) { const curEl = document.getElementById('serverDirCurrent'); const listEl = document.getElementById('serverDirList'); if (!listEl) return; listEl.innerHTML = `