diff --git a/.gitignore b/.gitignore index 7b018c8..d256a41 100644 --- a/.gitignore +++ b/.gitignore @@ -15,6 +15,7 @@ /temp_sessions/ /downloads/ /uploads/ +/data/image-hoster/ /data/facial-rotation-detector/ /data/*/uploads/ .DS_Store diff --git a/cmd/image-hoster/app.js b/cmd/image-hoster/app.js new file mode 100644 index 0000000..85bd0dc --- /dev/null +++ b/cmd/image-hoster/app.js @@ -0,0 +1,1243 @@ +// ═══════════════════════════════════════════════════════════════════ +// 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.'}

+
+ `; + return; + } + + // Group files by folder + const groups = {}; + filtered.forEach(f => { + const folder = f.folder || '(Root)'; + if (!groups[folder]) groups[folder] = []; + groups[folder].push(f); + }); + + const isLive = currentSession && currentSession.tunnel_active; + const tunnelBase = currentSession ? currentSession.tunnel_url : ''; + + Object.keys(groups).sort().forEach(groupName => { + const groupFiles = groups[groupName]; + const block = document.createElement('div'); + block.className = 'folder-group-block'; + + let html = ` +
+
+ + ${groupName} +
+ ${groupFiles.length} file${groupFiles.length !== 1 ? 's' : ''} +
+
+ `; + + groupFiles.forEach(f => { + const sizeStr = f.size ? formatBytes(f.size) : '--'; + const directUrl = `${window.location.origin}${f.url}`; + const publicUrl = isLive ? `${tunnelBase}/${f.path || f.name}` : directUrl; + + const iconClass = f.is_image ? 'fa-image' : + f.is_code ? 'fa-file-code' : + f.name.endsWith('.zip') ? 'fa-file-zipper' : + 'fa-file'; + + html += ` +
+
+ ${f.is_image ? ` + + + ` : ` +
+ `} +
+
+ ${f.name} +
+ ${sizeStr} + ${(f.path || '').split('.').pop().toUpperCase()} +
+
+
+ + + + + + + +
+
+ `; + }); + + html += `
`; + block.innerHTML = html; + container.appendChild(block); + }); +} + +function formatBytes(bytes) { + if (!bytes || bytes === 0) return '0 B'; + const k = 1024; + const sizes = ['B', 'KB', 'MB', 'GB']; + const i = Math.floor(Math.log(bytes) / Math.log(k)); + return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]; +} + +// ───────────────────────────────────────────── +// Public Tunnel / Live Link HUD +// ───────────────────────────────────────────── +async function startTunnel() { + if (!currentId) return; + + const btnGoLive = document.getElementById('btnGoLive'); + const spinner = document.getElementById('liveSpinner'); + if (btnGoLive) btnGoLive.classList.add('hidden'); + if (spinner) spinner.classList.remove('hidden'); + + try { + const res = await fetch(getApiUrl('/get_tunnel'), { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ session_id: currentId }) + }); + const data = await res.json(); + if (data.success && data.url) { + setTunnelUI(true, data.url); + showToast('Public live link is active!', 'success'); + await refreshSessionsList(); + renderFilesExplorer(); + } else { + showToast('Failed to start tunnel: ' + (data.error || 'server error'), 'error'); + setTunnelUI(false); + } + } catch (e) { + showToast('Error starting tunnel: ' + e.message, 'error'); + setTunnelUI(false); + } finally { + if (spinner) spinner.classList.add('hidden'); + } +} + +async function stopTunnel() { + if (!currentId) return; + + try { + await fetch(getApiUrl('/stop_tunnel'), { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ session_id: currentId }) + }); + setTunnelUI(false); + showToast('Public tunnel stopped', 'info'); + await refreshSessionsList(); + renderFilesExplorer(); + } catch (e) { + showToast('Error stopping tunnel: ' + e.message, 'error'); + } +} + +async function regenerateTunnel() { + await stopTunnel(); + setTimeout(startTunnel, 500); +} + +async function checkTunnel(sid) { + try { + const res = await fetch(getApiUrl('/get_tunnel_status'), { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ session_id: sid }) + }); + const data = await res.json(); + if (data.active && data.url && currentId === sid) { + setTunnelUI(true, data.url); + } else if (currentId === sid) { + setTunnelUI(false); + } + } catch (_) {} +} + +function setTunnelUI(active, url = '') { + const panel = document.getElementById('livePanel'); + const badge = document.getElementById('liveBadge'); + const statusText = document.getElementById('liveStatusText'); + const btnGoLive = document.getElementById('btnGoLive'); + const btnStopLive = document.getElementById('btnStopLive'); + const urlRow = document.getElementById('liveUrlRow'); + const urlText = document.getElementById('liveUrlText'); + const openBtn = document.getElementById('liveOpenBtn'); + + if (active) { + if (panel) panel.classList.add('is-live'); + if (badge) { + badge.className = 'tunnel-status-badge badge-live'; + if (statusText) statusText.textContent = 'Live Public Tunnel'; + } + if (btnGoLive) btnGoLive.classList.add('hidden'); + if (btnStopLive) btnStopLive.classList.remove('hidden'); + if (urlRow) urlRow.classList.remove('hidden'); + if (urlText) urlText.textContent = url; + if (openBtn) openBtn.href = url; + } else { + if (panel) panel.classList.remove('is-live'); + if (badge) { + badge.className = 'tunnel-status-badge badge-offline'; + if (statusText) statusText.textContent = 'Offline (Internal Only)'; + } + if (btnGoLive) btnGoLive.classList.remove('hidden'); + if (btnStopLive) btnStopLive.classList.add('hidden'); + if (urlRow) urlRow.classList.add('hidden'); + } +} + +function copyLiveUrl() { + const urlText = document.getElementById('liveUrlText'); + if (urlText && urlText.textContent) { + copyText(urlText.textContent); + } +} + +// ───────────────────────────────────────────── +// Modals & Preview Handlers +// ───────────────────────────────────────────── +function openNewSessionModal() { + const nameInput = document.getElementById('govSessionName'); + if (nameInput) nameInput.value = 'Vault ' + (sessions.length + 1); + openGovernanceModal(); +} + +function openGovernanceModal() { + const modal = document.getElementById('sessionGovModal'); + if (!modal) return; + + if (currentSession) { + const nameInput = document.getElementById('govSessionName'); + const modeSel = document.getElementById('govSessionMode'); + const limitSel = document.getElementById('govTimeLimitSel'); + + if (nameInput) nameInput.value = currentSession.name || ''; + if (modeSel) modeSel.value = currentSession.mode || 'server_background'; + if (limitSel) limitSel.value = (currentSession.time_limit_sec || 0).toString(); + } + + modal.style.display = 'flex'; +} + +function closeGovernanceModal() { + const modal = document.getElementById('sessionGovModal'); + if (modal) modal.style.display = 'none'; +} + +async function saveSessionGovernance() { + const nameInput = document.getElementById('govSessionName'); + const limitSel = document.getElementById('govTimeLimitSel'); + const name = nameInput ? nameInput.value.trim() : ''; + const limitSec = parseInt(limitSel ? limitSel.value : '0', 10); + + try { + const res = await fetch(getApiUrl('/update_session_governance'), { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + session_id: currentId, + name: name, + time_limit_sec: limitSec + }) + }); + const data = await res.json(); + if (data.success) { + showToast('Session governance updated successfully', 'success'); + closeGovernanceModal(); + await refreshSessionsList(); + loadSessionDetails(currentId); + } else { + showToast('Failed to update governance', 'error'); + } + } catch (e) { + showToast('Error: ' + e.message, 'error'); + } +} + +// QR Code Modal +function openQrModal(title, url) { + const modal = document.getElementById('qrModal'); + const titleEl = document.getElementById('qrModalTitle'); + const textEl = document.getElementById('qrUrlText'); + const container = document.getElementById('qrCodeContainer'); + if (!modal || !container) return; + + if (titleEl) titleEl.innerHTML = ` ${title}`; + if (textEl) textEl.textContent = url; + container.innerHTML = ''; + + if (typeof QRCode !== 'undefined') { + new QRCode(container, { + text: url, + width: 200, + height: 200, + colorDark: '#030305', + colorLight: '#ffffff', + correctLevel: QRCode.CorrectLevel.H + }); + } else { + container.innerHTML = `

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 = `
Reading directories...
`; + + try { + const res = await fetch(getApiUrl('/api/list_server_directories'), { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ path }) + }); + const data = await res.json(); + if (data.success) { + serverExplorerCurrentPath = data.current_path; + if (curEl) curEl.textContent = data.current_path; + + let html = ''; + if (data.parent_path && data.parent_path !== data.current_path) { + html += ` +
+ + .. (Parent Directory) +
+ `; + } + + if (data.directories && data.directories.length) { + data.directories.forEach(d => { + const fullP = data.current_path.replace(/\/+$/, '') + '/' + d; + html += ` +
+ + ${d} +
+ `; + }); + } else { + html += `
No subdirectories found.
`; + } + + listEl.innerHTML = html; + } else { + listEl.innerHTML = `
${data.error || 'Access denied'}
`; + } + } catch (e) { + listEl.innerHTML = `
${e.message}
`; + } +} + +function selectCurrentServerDir() { + if (serverExplorerCurrentPath) { + const input = document.getElementById('pathInput'); + if (input) input.value = serverExplorerCurrentPath; + setFolderPath(serverExplorerCurrentPath); + closeServerDirModal(); + } +} + +// Telemetry & Access Traffic Modal +async function openTelemetryModal() { + const modal = document.getElementById('telemetryModal'); + if (!modal) return; + modal.style.display = 'flex'; + await refreshTelemetry(); +} + +function closeTelemetryModal() { + const modal = document.getElementById('telemetryModal'); + if (modal) modal.style.display = 'none'; +} + +async function refreshTelemetry() { + if (!currentId) return; + + try { + const res = await fetch(getApiUrl(`/api/session_telemetry/${currentId}`)); + const data = await res.json(); + if (data.success) { + const reqsEl = document.getElementById('t-reqs'); + const bytesEl = document.getElementById('t-bytes'); + const timeEl = document.getElementById('t-active-time'); + const bodyEl = document.getElementById('telemetryLogsBody'); + + if (reqsEl) reqsEl.textContent = data.requests; + if (bytesEl) bytesEl.textContent = (data.bytes_served / (1024 * 1024)).toFixed(2) + ' MB'; + if (timeEl && data.last_active) { + timeEl.textContent = new Date(data.last_active).toLocaleTimeString(); + } + + if (bodyEl) { + if (data.logs && data.logs.length) { + let html = ''; + data.logs.slice().reverse().forEach(log => { + const statusColor = log.status === 200 ? 'text-green' : 'text-amber'; + html += ` + + ${new Date(log.timestamp).toLocaleTimeString()} + ${log.method} + ${log.path} + ${log.status} + ${formatBytes(log.bytes)} + ${(log.ip || '').replace('::1', '127.0.0.1')} + + `; + }); + bodyEl.innerHTML = html; + } else { + bodyEl.innerHTML = `No access events recorded yet.`; + } + } + } + } catch (e) { + console.error('Failed to fetch telemetry:', e); + } +} + +// Batch URLs Export Modal +let currentExportFormat = 'raw'; +function openBatchExportModal() { + const modal = document.getElementById('batchExportModal'); + if (!modal) return; + renderBatchExportContent(); + modal.style.display = 'flex'; +} + +function closeBatchExportModal() { + const modal = document.getElementById('batchExportModal'); + if (modal) modal.style.display = 'none'; +} + +function switchExportFormat(fmt) { + currentExportFormat = fmt; + document.querySelectorAll('.batch-export-formats .seg-pill').forEach(p => { + p.classList.toggle('active', p.textContent.toLowerCase().includes(fmt)); + }); + renderBatchExportContent(); +} + +function renderBatchExportContent() { + const textarea = document.getElementById('batchExportTextarea'); + if (!textarea) return; + + const isLive = currentSession && currentSession.tunnel_active; + const tunnelBase = currentSession ? currentSession.tunnel_url : ''; + + const urls = currentFiles.map(f => { + const directUrl = `${window.location.origin}${f.url}`; + return isLive ? `${tunnelBase}/${f.path || f.name}` : directUrl; + }); + + if (currentExportFormat === 'json') { + textarea.value = JSON.stringify(urls, null, 2); + } else if (currentExportFormat === 'markdown') { + textarea.value = currentFiles.map((f, i) => `![${f.name}](${urls[i]})`).join('\n'); + } else if (currentExportFormat === 'html') { + textarea.value = currentFiles.map((f, i) => `${f.name}`).join('\n'); + } else if (currentExportFormat === 'curl') { + textarea.value = urls.map((u, i) => `curl -o "${currentFiles[i].name}" "${u}"`).join('\n'); + } else { + textarea.value = urls.join('\n'); + } +} + +function copyBatchExportContent() { + const textarea = document.getElementById('batchExportTextarea'); + if (textarea && textarea.value) { + copyText(textarea.value); + } +} + +function downloadSessionZip() { + if (!currentId) return; + const zipUrl = getApiUrl(`/download_session_zip/${currentId}`); + window.location.href = zipUrl; + showToast('Preparing ZIP download...', 'info'); +} + +// ───────────────────────────────────────────── +// Copy & Toast Helpers +// ───────────────────────────────────────────── +function copyText(text) { + if (!text) return; + if (navigator.clipboard && navigator.clipboard.writeText) { + navigator.clipboard.writeText(text).then(() => showToast('Copied to clipboard!', 'success')).catch(() => fallbackCopy(text)); + } else { + fallbackCopy(text); + } +} + +function fallbackCopy(text) { + const t = document.createElement('textarea'); + t.value = text; + document.body.appendChild(t); + t.select(); + document.execCommand('copy'); + document.body.removeChild(t); + showToast('Copied to clipboard!', 'success'); +} + +function copyMarkdownLink(name, url) { + copyText(`![${name}](${url})`); +} + +function copyHtmlImg(name, url) { + copyText(`${name}`); +} + +function setStatus(msg, active) { + const txt = document.getElementById('statusText'); + const icon = document.getElementById('statusIcon'); + if (txt) txt.textContent = msg; + if (icon) { + icon.className = active ? 'fa-solid fa-circle-check text-green' : 'fa-solid fa-circle-info text-amber'; + } +} + +function showToast(msg, type = 'info') { + const container = document.getElementById('toast-container'); + if (!container) return; + const toast = document.createElement('div'); + toast.className = `toast ${type}`; + const icon = type === 'success' ? 'fa-circle-check' : + type === 'error' ? 'fa-circle-exclamation' : + 'fa-circle-info'; + toast.innerHTML = ` ${msg}`; + container.appendChild(toast); + setTimeout(() => toast.remove(), 4000); +} + +window.showToast = showToast; diff --git a/cmd/image-hoster/governance.go b/cmd/image-hoster/governance.go new file mode 100644 index 0000000..e8112e1 --- /dev/null +++ b/cmd/image-hoster/governance.go @@ -0,0 +1,221 @@ +package main + +import ( + "archive/zip" + "encoding/json" + "io" + "log/slog" + "net/http" + "os" + "path/filepath" + "sync" + "time" +) + +var ( + dataDir = "data/image-hoster" + sessionsDir = filepath.Join(dataDir, "sessions") + metaPath = filepath.Join(dataDir, "sessions.json") + govLock sync.Mutex +) + +func initGovernance() { + if err := os.MkdirAll(sessionsDir, 0755); err != nil { + slog.Error("failed to create sessions storage directory", "err", err) + } + + loadSessionsMetadata() + go runGovernanceWatchdog() +} + +func loadSessionsMetadata() { + govLock.Lock() + defer govLock.Unlock() + + b, err := os.ReadFile(metaPath) + if err != nil { + return + } + + var stored map[string]*SessionMeta + if err := json.Unmarshal(b, &stored); err != nil { + slog.Warn("could not decode sessions.json", "err", err) + return + } + + globalState.mu.Lock() + defer globalState.mu.Unlock() + + now := time.Now() + for id, s := range stored { + // If expired while server was offline, mark or delete + if !s.ExpiresAt.IsZero() && now.After(s.ExpiresAt) { + slog.Info("session expired during downtime", "session_id", id) + // Cleanup background session files if on server + if s.Mode == ModeServerBg { + os.RemoveAll(filepath.Join(sessionsDir, id)) + } + continue + } + // If mode was relay, reset channels (browser will re-connect) + if s.Mode == ModeRelay { + globalState.relaySessions[id] = make(chan map[string]interface{}, 100) + } + globalState.sessions[id] = s + } +} + +func saveSessionsMetadata() { + govLock.Lock() + defer govLock.Unlock() + + globalState.mu.RLock() + data, err := json.MarshalIndent(globalState.sessions, "", " ") + globalState.mu.RUnlock() + + if err != nil { + slog.Error("failed to serialize sessions metadata", "err", err) + return + } + + tmpPath := metaPath + ".tmp" + if err := os.WriteFile(tmpPath, data, 0644); err == nil { + os.Rename(tmpPath, metaPath) + } +} + +// Background auto-expiration governance watchdog +func runGovernanceWatchdog() { + ticker := time.NewTicker(20 * time.Second) + defer ticker.Stop() + + for range ticker.C { + now := time.Now() + var expiredIDs []string + + globalState.mu.RLock() + for id, s := range globalState.sessions { + if !s.ExpiresAt.IsZero() && now.After(s.ExpiresAt) { + expiredIDs = append(expiredIDs, id) + } + } + globalState.mu.RUnlock() + + if len(expiredIDs) > 0 { + for _, id := range expiredIDs { + slog.Info("enterprise governance: auto-terminating expired session", "session_id", id) + deleteSessionInternal(id) + } + saveSessionsMetadata() + } + } +} + +func deleteSessionInternal(id string) { + globalState.mu.Lock() + s, exists := globalState.sessions[id] + if !exists { + globalState.mu.Unlock() + return + } + + delete(globalState.sessions, id) + if ch, ok := globalState.relaySessions[id]; ok { + close(ch) + delete(globalState.relaySessions, id) + } + delete(globalState.accessLogs, id) + globalState.mu.Unlock() + + // Clean up server-side files if hosted on server + if s.Mode == ModeServerBg { + targetDir := filepath.Join(sessionsDir, id) + os.RemoveAll(targetDir) + } +} + +func recordAccessEvent(sessionID, ip, method, path string, status int, bytes int64, userAgent string) { + globalState.mu.Lock() + defer globalState.mu.Unlock() + + s, exists := globalState.sessions[sessionID] + if exists { + s.Requests++ + s.BytesServed += bytes + s.LastActive = time.Now() + } + + ev := AccessEvent{ + Timestamp: time.Now(), + IP: ip, + Method: method, + Path: path, + Status: status, + Bytes: bytes, + UserAgent: userAgent, + } + + logs := globalState.accessLogs[sessionID] + if len(logs) >= 60 { + logs = logs[1:] + } + globalState.accessLogs[sessionID] = append(logs, ev) +} + +// Stream zip archive of all hosted files in a session +func createSessionZip(sessionID string, w http.ResponseWriter) error { + globalState.mu.RLock() + s, exists := globalState.sessions[sessionID] + globalState.mu.RUnlock() + + if !exists { + return os.ErrNotExist + } + + basePath := s.Path + if s.Mode == ModeServerBg { + basePath = filepath.Join(sessionsDir, sessionID) + } + + if basePath == "" { + return os.ErrNotExist + } + + w.Header().Set("Content-Type", "application/zip") + w.Header().Set("Content-Disposition", `attachment; filename="hosted_session_`+sessionID+`.zip"`) + + zw := zip.NewWriter(w) + defer zw.Close() + + return filepath.Walk(basePath, func(path string, info os.FileInfo, err error) error { + if err != nil || info.IsDir() { + return nil + } + rel, err := filepath.Rel(basePath, path) + if err != nil { + return nil + } + rel = filepath.ToSlash(rel) + + hdr, err := zip.FileInfoHeader(info) + if err != nil { + return nil + } + hdr.Name = rel + hdr.Method = zip.Deflate + + writer, err := zw.CreateHeader(hdr) + if err != nil { + return err + } + + f, err := os.Open(path) + if err != nil { + return nil + } + defer f.Close() + + _, err = io.Copy(writer, f) + return err + }) +} diff --git a/cmd/image-hoster/index.html b/cmd/image-hoster/index.html new file mode 100644 index 0000000..4e47391 --- /dev/null +++ b/cmd/image-hoster/index.html @@ -0,0 +1,520 @@ + + + + + + + + Host It Now · Enterprise Cloud Vault & Edge Relay + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+
+
+ +
+
+

Host It Now

+ Enterprise Cloud Vault & Edge Relay +
+
+
+ +
+ +
+
+ + Sessions: + 0 +
+
+ + Files: + 0 +
+
+ + Requests: + 0 +
+
+ + Bandwidth: + 0 MB +
+
+
+ +
+ + + Admin + +
+
+ + +
+
+ Active Sessions +
+ +
+
+ +
+ + + +
+
+ + +
+
+
+
+ + Offline +
+
+ + Unlimited (Enterprise) +
+
+ + Server Vault +
+
+ +
+ + + +
+
+ + +
+ + +
+ +
+ + + +
+ + +
+ + + + +
+
+ +
+
+

Drop Images, Folders, or ZIP Archives to Host in Background

+

Uploaded directly to the secure server vault so files remain online even if your browser is closed.

+
+
+ + + +
+
+ + +
+ + + + + + + + +
+
+ + Session active +
+
+ 0 files + 0 MB +
+
+
+ + +
+
+ + +
+ + + + +
+ +
+ + +
+ + +
+
+
+ + +
+ +
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + diff --git a/cmd/image-hoster/main.go b/cmd/image-hoster/main.go index 31431b4..0c9ffdb 100644 --- a/cmd/image-hoster/main.go +++ b/cmd/image-hoster/main.go @@ -1,6 +1,7 @@ package main import ( + "archive/zip" "encoding/json" "fmt" "io" @@ -10,7 +11,6 @@ import ( "os/exec" "path/filepath" "strings" - "sync" "time" "github.com/go-chi/chi/v5" @@ -19,29 +19,32 @@ import ( mymiddleware "unified-dashboard/internal/middleware" ) -var ( - sessionPaths = make(map[string]string) - sessionStats = make(map[string]map[string]int) - relaySessions = make(map[string]chan map[string]interface{}) - requestEvents = make(map[string]chan []byte) - - tunnelProcess *exec.Cmd - tunnelURL string - tunnelLock sync.Mutex - globalLock sync.Mutex -) - func writeJSON(w http.ResponseWriter, status int, data any) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) json.NewEncoder(w).Encode(data) } +func getWebFilePath(filename string) string { + candidates := []string{ + filepath.Join("web", "image-hoster", filename), + filepath.Join("cmd", "image-hoster", filename), + } + for _, p := range candidates { + if _, err := os.Stat(p); err == nil { + return p + } + } + return filepath.Join("web", "image-hoster", filename) +} + func main() { common.InitLogger("image-hoster") - port := common.EnvOr("PORT", "5005") + port := common.EnvOr("PORT", "5008") scriptName := os.Getenv("SCRIPT_NAME") + initGovernance() + r := chi.NewRouter() r.Use(middleware.RealIP) r.Use(middleware.RequestID) @@ -51,58 +54,365 @@ func main() { r.Use(common.PrefixMiddleware(scriptName)) } - workDir, _ := os.Getwd() - webDir := filepath.Join(workDir, "web", "image-hoster") - + // ───────────────────────────────────────────────────────────── + // STATIC ASSETS + // ───────────────────────────────────────────────────────────── r.Get("/", func(w http.ResponseWriter, r *http.Request) { - http.ServeFile(w, r, filepath.Join(webDir, "index.html")) + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") + http.ServeFile(w, r, getWebFilePath("index.html")) }) r.Get("/styles.css", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/css; charset=utf-8") - http.ServeFile(w, r, filepath.Join(webDir, "styles.css")) + w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") + http.ServeFile(w, r, getWebFilePath("styles.css")) }) r.Get("/app.js", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/javascript; charset=utf-8") - http.ServeFile(w, r, filepath.Join(webDir, "app.js")) + w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") + http.ServeFile(w, r, getWebFilePath("app.js")) }) r.Get("/radheradhe", func(w http.ResponseWriter, r *http.Request) { - http.ServeFile(w, r, filepath.Join(webDir, "admin.html")) + w.Header().Set("Content-Type", "text/html; charset=utf-8") + http.ServeFile(w, r, getWebFilePath("admin.html")) }) r.Get("/radheradhe/", func(w http.ResponseWriter, r *http.Request) { - http.ServeFile(w, r, filepath.Join(webDir, "admin.html")) + w.Header().Set("Content-Type", "text/html; charset=utf-8") + http.ServeFile(w, r, getWebFilePath("admin.html")) }) r.Get("/admin.css", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/css; charset=utf-8") - http.ServeFile(w, r, filepath.Join(webDir, "admin.css")) + http.ServeFile(w, r, getWebFilePath("admin.css")) }) r.Get("/admin.js", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/javascript; charset=utf-8") - http.ServeFile(w, r, filepath.Join(webDir, "admin.js")) + http.ServeFile(w, r, getWebFilePath("admin.js")) }) + // ───────────────────────────────────────────────────────────── + // SESSION MANAGEMENT & GOVERNANCE + // ───────────────────────────────────────────────────────────── r.Post("/create_session", func(w http.ResponseWriter, r *http.Request) { var req struct { - Mode string `json:"mode"` + Name string `json:"name"` + Mode string `json:"mode"` + TimeLimitSec int `json:"time_limit_sec"` } - // Body might be empty json.NewDecoder(r.Body).Decode(&req) - + sessionID := fmt.Sprintf("%d", time.Now().UnixNano()) - - globalLock.Lock() - if req.Mode == "relay" { - relaySessions[sessionID] = make(chan map[string]interface{}, 100) + mode := SessionMode(req.Mode) + if mode == "" { + mode = ModeServerBg } - sessionStats[sessionID] = map[string]int{"requests": 0, "bytes": 0} - globalLock.Unlock() - writeJSON(w, 200, map[string]any{"success": true, "session_id": sessionID}) + now := time.Now() + var expiresAt time.Time + if req.TimeLimitSec > 0 { + expiresAt = now.Add(time.Duration(req.TimeLimitSec) * time.Second) + } + + name := req.Name + if name == "" { + name = "Session " + sessionID[len(sessionID)-6:] + } + + sessionDir := filepath.Join(sessionsDir, sessionID) + if mode == ModeServerBg { + os.MkdirAll(sessionDir, 0755) + } + + meta := &SessionMeta{ + ID: sessionID, + Name: name, + Mode: mode, + Path: sessionDir, + CreatedAt: now, + ExpiresAt: expiresAt, + TimeLimitSec: req.TimeLimitSec, + LastActive: now, + TunnelURL: fmt.Sprintf("https://nexus.linuxguy.space/hoster/%s", sessionID), + } + + globalState.mu.Lock() + globalState.sessions[sessionID] = meta + if mode == ModeRelay { + globalState.relaySessions[sessionID] = make(chan map[string]interface{}, 100) + } + globalState.mu.Unlock() + + saveSessionsMetadata() + + writeJSON(w, 200, map[string]any{ + "success": true, + "session_id": sessionID, + "session": meta, + }) }) - r.Post("/admin_login", func(w http.ResponseWriter, r *http.Request) { + r.Get("/get_sessions_list", func(w http.ResponseWriter, r *http.Request) { + globalState.mu.RLock() + defer globalState.mu.RUnlock() + + now := time.Now() + var list []map[string]any + for _, s := range globalState.sessions { + remSec := 0 + if !s.ExpiresAt.IsZero() { + if s.ExpiresAt.After(now) { + remSec = int(s.ExpiresAt.Sub(now).Seconds()) + } + } + + list = append(list, map[string]any{ + "id": s.ID, + "name": s.Name, + "mode": s.Mode, + "path": s.Path, + "created_at": s.CreatedAt, + "expires_at": s.ExpiresAt, + "time_limit_sec": s.TimeLimitSec, + "remaining_sec": remSec, + "file_count": s.FileCount, + "total_bytes": s.TotalBytes, + "requests": s.Requests, + "bytes_served": s.BytesServed, + "tunnel_url": s.TunnelURL, + "tunnel_active": s.TunnelActive, + }) + } + + writeJSON(w, 200, map[string]any{ + "success": true, + "sessions": list, + }) + }) + + r.Post("/update_session_governance", func(w http.ResponseWriter, r *http.Request) { + var req struct { + SessionID string `json:"session_id"` + Name string `json:"name"` + TimeLimitSec int `json:"time_limit_sec"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + writeJSON(w, 400, map[string]string{"error": "Invalid payload"}) + return + } + + globalState.mu.Lock() + s, exists := globalState.sessions[req.SessionID] + if !exists { + globalState.mu.Unlock() + writeJSON(w, 404, map[string]string{"error": "Session not found"}) + return + } + + if req.Name != "" { + s.Name = req.Name + } + s.TimeLimitSec = req.TimeLimitSec + if req.TimeLimitSec > 0 { + s.ExpiresAt = time.Now().Add(time.Duration(req.TimeLimitSec) * time.Second) + } else { + s.ExpiresAt = time.Time{} // Unlimited + } + globalState.mu.Unlock() + + saveSessionsMetadata() + writeJSON(w, 200, map[string]any{"success": true, "session": s}) + }) + + r.Post("/delete_session", func(w http.ResponseWriter, r *http.Request) { + var req struct { + SessionID string `json:"session_id"` + } + json.NewDecoder(r.Body).Decode(&req) + if req.SessionID != "" { + deleteSessionInternal(req.SessionID) + saveSessionsMetadata() + } writeJSON(w, 200, map[string]bool{"success": true}) }) + // ───────────────────────────────────────────────────────────── + // SERVER-SIDE BACKGROUND FILE UPLOADS + // ───────────────────────────────────────────────────────────── + r.Post("/upload_files", func(w http.ResponseWriter, r *http.Request) { + // Limit max upload to 500MB + r.Body = http.MaxBytesReader(w, r.Body, 500*1024*1024) + if err := r.ParseMultipartForm(50 * 1024 * 1024); err != nil { + writeJSON(w, 400, map[string]string{"error": "Failed to parse upload: " + err.Error()}) + return + } + + sessionID := r.FormValue("session_id") + if sessionID == "" { + writeJSON(w, 400, map[string]string{"error": "session_id required"}) + return + } + + targetDir := filepath.Join(sessionsDir, sessionID) + if err := os.MkdirAll(targetDir, 0755); err != nil { + writeJSON(w, 500, map[string]string{"error": "Failed to create session dir"}) + return + } + + files := r.MultipartForm.File["files"] + relPaths := r.MultipartForm.Value["relative_paths"] + + var totalUploadedBytes int64 + uploadedCount := 0 + + for i, fHeader := range files { + relPath := fHeader.Filename + if i < len(relPaths) && relPaths[i] != "" { + relPath = relPaths[i] + } + relPath = filepath.Clean(relPath) + if strings.HasPrefix(relPath, "..") { + continue + } + + destPath := filepath.Join(targetDir, relPath) + os.MkdirAll(filepath.Dir(destPath), 0755) + + srcFile, err := fHeader.Open() + if err != nil { + continue + } + + dstFile, err := os.Create(destPath) + if err != nil { + srcFile.Close() + continue + } + + n, err := io.Copy(dstFile, srcFile) + srcFile.Close() + dstFile.Close() + + if err == nil { + totalUploadedBytes += n + uploadedCount++ + } + } + + // Update session metadata + globalState.mu.Lock() + s, exists := globalState.sessions[sessionID] + if !exists { + now := time.Now() + s = &SessionMeta{ + ID: sessionID, + Name: "Session " + sessionID[len(sessionID)-6:], + CreatedAt: now, + LastActive: now, + TunnelURL: fmt.Sprintf("https://nexus.linuxguy.space/hoster/%s", sessionID), + } + globalState.sessions[sessionID] = s + } + s.Mode = ModeServerBg + s.Path = targetDir + s.FileCount += uploadedCount + s.TotalBytes += totalUploadedBytes + s.LastActive = time.Now() + globalState.mu.Unlock() + + saveSessionsMetadata() + + writeJSON(w, 200, map[string]any{ + "success": true, + "uploaded_count": uploadedCount, + "total_bytes": totalUploadedBytes, + }) + }) + + r.Post("/upload_zip", func(w http.ResponseWriter, r *http.Request) { + r.Body = http.MaxBytesReader(w, r.Body, 500*1024*1024) + if err := r.ParseMultipartForm(50 * 1024 * 1024); err != nil { + writeJSON(w, 400, map[string]string{"error": "Failed to parse upload"}) + return + } + + sessionID := r.FormValue("session_id") + if sessionID == "" { + writeJSON(w, 400, map[string]string{"error": "session_id required"}) + return + } + + file, fileHeader, err := r.FormFile("zip_file") + if err != nil { + writeJSON(w, 400, map[string]string{"error": "zip_file required"}) + return + } + defer file.Close() + + targetDir := filepath.Join(sessionsDir, sessionID) + os.MkdirAll(targetDir, 0755) + + zr, err := zip.NewReader(file, fileHeader.Size) + if err != nil { + writeJSON(w, 400, map[string]string{"error": "Invalid zip format"}) + return + } + + var count int + var totalBytes int64 + + for _, zf := range zr.File { + cleaned := filepath.Clean(zf.Name) + if strings.HasPrefix(cleaned, "..") { + continue + } + + dest := filepath.Join(targetDir, cleaned) + if zf.FileInfo().IsDir() { + os.MkdirAll(dest, 0755) + continue + } + + os.MkdirAll(filepath.Dir(dest), 0755) + rc, err := zf.Open() + if err != nil { + continue + } + + out, err := os.Create(dest) + if err != nil { + rc.Close() + continue + } + + n, err := io.Copy(out, rc) + rc.Close() + out.Close() + + if err == nil { + count++ + totalBytes += n + } + } + + globalState.mu.Lock() + s, exists := globalState.sessions[sessionID] + if exists { + s.Mode = ModeServerBg + s.Path = targetDir + s.FileCount += count + s.TotalBytes += totalBytes + s.LastActive = time.Now() + } + globalState.mu.Unlock() + + saveSessionsMetadata() + + writeJSON(w, 200, map[string]any{ + "success": true, + "count": count, + "total_bytes": totalBytes, + }) + }) + r.Post("/set_session_path", func(w http.ResponseWriter, r *http.Request) { var req struct { SessionID string `json:"session_id"` @@ -110,279 +420,81 @@ func main() { } json.NewDecoder(r.Body).Decode(&req) - globalLock.Lock() + globalState.mu.Lock() + s, exists := globalState.sessions[req.SessionID] + if !exists { + s = &SessionMeta{ + ID: req.SessionID, + Name: "Session " + req.SessionID[len(req.SessionID)-6:], + CreatedAt: time.Now(), + TunnelURL: fmt.Sprintf("https://nexus.linuxguy.space/hoster/%s", req.SessionID), + } + globalState.sessions[req.SessionID] = s + } + if req.Path == "(Relay Mode)" { - // Relay mode: serve files from browser via SSE, NOT from disk - if _, exists := relaySessions[req.SessionID]; !exists { - relaySessions[req.SessionID] = make(chan map[string]interface{}, 100) + s.Mode = ModeRelay + s.Path = "" + if _, chExists := globalState.relaySessions[req.SessionID]; !chExists { + globalState.relaySessions[req.SessionID] = make(chan map[string]interface{}, 100) } - // Remove from sessionPaths so the /files handler uses the relay path - delete(sessionPaths, req.SessionID) - if _, exists := sessionStats[req.SessionID]; !exists { - sessionStats[req.SessionID] = map[string]int{"requests": 0, "bytes": 0} - } - globalLock.Unlock() + globalState.mu.Unlock() + saveSessionsMetadata() writeJSON(w, 200, map[string]any{"success": true, "mode": "relay"}) return } - // Server-side path mapping if req.Path == "" { - globalLock.Unlock() + globalState.mu.Unlock() writeJSON(w, 400, map[string]string{"error": "Path required"}) return } - sessionPaths[req.SessionID] = req.Path - // If previously in relay mode, remove it - delete(relaySessions, req.SessionID) - if _, exists := sessionStats[req.SessionID]; !exists { - sessionStats[req.SessionID] = map[string]int{"requests": 0, "bytes": 0} - } - globalLock.Unlock() + s.Mode = ModeLocalPath + s.Path = req.Path + delete(globalState.relaySessions, req.SessionID) + globalState.mu.Unlock() + + saveSessionsMetadata() writeJSON(w, 200, map[string]bool{"success": true}) }) - r.Post("/delete_session", func(w http.ResponseWriter, r *http.Request) { - var req struct { - SessionID string `json:"session_id"` - } - json.NewDecoder(r.Body).Decode(&req) - - globalLock.Lock() - delete(sessionPaths, req.SessionID) - delete(relaySessions, req.SessionID) - delete(sessionStats, req.SessionID) - globalLock.Unlock() - - writeJSON(w, 200, map[string]bool{"success": true}) - }) - - r.Get("/stream_events/{session_id}", func(w http.ResponseWriter, r *http.Request) { - sid := chi.URLParam(r, "session_id") - w.Header().Set("Content-Type", "text/event-stream") - w.Header().Set("Cache-Control", "no-cache") - w.Header().Set("Connection", "keep-alive") - - flusher, ok := w.(http.Flusher) - if !ok { return } - - globalLock.Lock() - ch, exists := relaySessions[sid] - globalLock.Unlock() - - if !exists { return } - - for msg := range ch { - b, _ := json.Marshal(msg) - fmt.Fprintf(w, "data: %s\n\n", b) - flusher.Flush() - } - }) - - r.Post("/fulfill_request", func(w http.ResponseWriter, r *http.Request) { - reqID := r.FormValue("req_id") - globalLock.Lock() - ch, exists := requestEvents[reqID] - globalLock.Unlock() - - if !exists { - writeJSON(w, 404, map[string]string{"error": "Invalid ID"}) - return - } - - file, _, err := r.FormFile("file") - if err == nil { - data, _ := io.ReadAll(file) - ch <- data - file.Close() - } else { - ch <- nil - } - writeJSON(w, 200, map[string]bool{"success": true}) - }) - - r.Get("/files/{session_id}/*", func(w http.ResponseWriter, r *http.Request) { - sid := chi.URLParam(r, "session_id") - filename := chi.URLParam(r, "*") - - globalLock.Lock() - basePath, localExists := sessionPaths[sid] - ch, relayExists := relaySessions[sid] - stats := sessionStats[sid] - globalLock.Unlock() - - if stats != nil { - stats["requests"]++ - } - - if localExists { - fullPath := filepath.Join(basePath, filename) - stat, err := os.Stat(fullPath) - if err == nil { - if stats != nil { - stats["bytes"] += int(stat.Size()) - } - if stat.IsDir() { - // Return beautiful HTML listing for directories instead of 404 - w.Header().Set("Content-Type", "text/html") - - html := ` - - - - - Hosted Files - - - - -
-

Hosted Files

-
")) - return - } - http.ServeFile(w, r, fullPath) - return - } - } else if relayExists { - reqID := fmt.Sprintf("%d", time.Now().UnixNano()) - resCh := make(chan []byte, 1) - - globalLock.Lock() - requestEvents[reqID] = resCh - globalLock.Unlock() - - ch <- map[string]interface{}{ - "type": "request_file", - "req_id": reqID, - "filename": filename, - } - - select { - case data := <-resCh: - globalLock.Lock() - delete(requestEvents, reqID) - globalLock.Unlock() - if data != nil { - if stats != nil { - stats["bytes"] += len(data) - } - w.Write(data) - return - } - case <-time.After(30 * time.Second): - globalLock.Lock() - delete(requestEvents, reqID) - globalLock.Unlock() - } - } - http.Error(w, "Not found", 404) - }) - r.Get("/get_session_files/{session_id}", func(w http.ResponseWriter, r *http.Request) { sid := chi.URLParam(r, "session_id") - - globalLock.Lock() - _, relayExists := relaySessions[sid] - basePath, localExists := sessionPaths[sid] - globalLock.Unlock() - if relayExists { - writeJSON(w, 200, map[string]any{"success": true, "mode": "relay", "path_set": true, "current_path": "(Hosted from Browser)"}) + globalState.mu.RLock() + s, exists := globalState.sessions[sid] + globalState.mu.RUnlock() + + if !exists { + writeJSON(w, 200, map[string]any{"success": true, "files": []any{}, "path_set": false}) return } - if !localExists { + if s.Mode == ModeRelay { + writeJSON(w, 200, map[string]any{ + "success": true, + "mode": "relay", + "path_set": true, + "current_path": "(Hosted from Browser P2P)", + "session": s, + }) + return + } + + basePath := s.Path + if s.Mode == ModeServerBg { + basePath = filepath.Join(sessionsDir, sid) + } + + if basePath == "" { writeJSON(w, 200, map[string]any{"success": true, "files": []any{}, "path_set": false}) return } var filesList []map[string]any + var totalBytes int64 + filepath.Walk(basePath, func(path string, info os.FileInfo, err error) error { if err != nil || info.IsDir() { return nil @@ -397,28 +509,109 @@ func main() { folder = "(Root)" } ext := strings.ToLower(filepath.Ext(path)) - isCode := ext == ".json" || ext == ".html" || ext == ".htm" || ext == ".css" || ext == ".js" + isCode := ext == ".json" || ext == ".html" || ext == ".htm" || ext == ".css" || ext == ".js" || ext == ".ts" || ext == ".xml" || ext == ".yaml" || ext == ".yml" + isImage := ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".webp" || ext == ".gif" || ext == ".svg" || ext == ".bmp" || ext == ".ico" + totalBytes += info.Size() filesList = append(filesList, map[string]any{ - "path": relPath, - "folder": folder, - "name": info.Name(), - "url": fmt.Sprintf("/files/%s/%s", sid, relPath), - "is_code": isCode, + "path": relPath, + "folder": folder, + "name": info.Name(), + "size": info.Size(), + "url": fmt.Sprintf("/files/%s/%s", sid, relPath), + "is_code": isCode, + "is_image": isImage, + "modified": info.ModTime().Unix(), }) return nil }) + // Update counts + globalState.mu.Lock() + s.FileCount = len(filesList) + s.TotalBytes = totalBytes + globalState.mu.Unlock() + writeJSON(w, 200, map[string]any{ - "success": true, - "files": filesList, - "path_set": true, + "success": true, + "files": filesList, + "path_set": true, "current_path": basePath, + "session": s, + }) + }) + + r.Get("/download_session_zip/{session_id}", func(w http.ResponseWriter, r *http.Request) { + sid := chi.URLParam(r, "session_id") + if err := createSessionZip(sid, w); err != nil { + http.Error(w, "Failed to create zip: "+err.Error(), http.StatusInternalServerError) + } + }) + + // ───────────────────────────────────────────────────────────── + // TELEMETRY & ACCESS LOGS + // ───────────────────────────────────────────────────────────── + r.Get("/api/session_telemetry/{session_id}", func(w http.ResponseWriter, r *http.Request) { + sid := chi.URLParam(r, "session_id") + + globalState.mu.RLock() + s, exists := globalState.sessions[sid] + logs := globalState.accessLogs[sid] + globalState.mu.RUnlock() + + if !exists { + writeJSON(w, 404, map[string]string{"error": "Session not found"}) + return + } + + writeJSON(w, 200, map[string]any{ + "success": true, + "session_id": sid, + "requests": s.Requests, + "bytes_served": s.BytesServed, + "last_active": s.LastActive, + "logs": logs, + }) + }) + + // ───────────────────────────────────────────────────────────── + // SERVER DIRECTORY NAVIGATION API + // ───────────────────────────────────────────────────────────── + r.Post("/api/list_server_directories", func(w http.ResponseWriter, r *http.Request) { + var req struct { + Path string `json:"path"` + } + json.NewDecoder(r.Body).Decode(&req) + + p := req.Path + if p == "" { + p, _ = os.UserHomeDir() + } + p = filepath.Clean(p) + + entries, err := os.ReadDir(p) + if err != nil { + writeJSON(w, 400, map[string]string{"error": err.Error()}) + return + } + + var dirs []string + for _, e := range entries { + if e.IsDir() && !strings.HasPrefix(e.Name(), ".") { + dirs = append(dirs, e.Name()) + } + } + + writeJSON(w, 200, map[string]any{ + "success": true, + "current_path": p, + "parent_path": filepath.Dir(p), + "directories": dirs, }) }) r.Post("/browse_folder", func(w http.ResponseWriter, r *http.Request) { - cmd := exec.Command("zenity", "--file-selection", "--directory", "--title=Select Image Folder") + cmd := exec.Command("zenity", "--file-selection", "--directory", "--title=Select Folder to Host") out, err := cmd.Output() path := strings.TrimSpace(string(out)) @@ -439,6 +632,137 @@ func main() { writeJSON(w, 200, map[string]any{"success": false, "error": "No folder selected"}) }) + // ───────────────────────────────────────────────────────────── + // BROWSER RELAY SSE STREAMING + // ───────────────────────────────────────────────────────────── + r.Get("/stream_events/{session_id}", func(w http.ResponseWriter, r *http.Request) { + sid := chi.URLParam(r, "session_id") + w.Header().Set("Content-Type", "text/event-stream") + w.Header().Set("Cache-Control", "no-cache") + w.Header().Set("Connection", "keep-alive") + + flusher, ok := w.(http.Flusher) + if !ok { + return + } + + globalState.mu.Lock() + ch, exists := globalState.relaySessions[sid] + if !exists { + ch = make(chan map[string]interface{}, 100) + globalState.relaySessions[sid] = ch + } + globalState.mu.Unlock() + + for msg := range ch { + b, _ := json.Marshal(msg) + fmt.Fprintf(w, "data: %s\n\n", b) + flusher.Flush() + } + }) + + r.Post("/fulfill_request", func(w http.ResponseWriter, r *http.Request) { + reqID := r.FormValue("req_id") + globalState.mu.Lock() + ch, exists := globalState.requestEvents[reqID] + globalState.mu.Unlock() + + if !exists { + writeJSON(w, 404, map[string]string{"error": "Invalid request ID"}) + return + } + + file, _, err := r.FormFile("file") + if err == nil { + data, _ := io.ReadAll(file) + ch <- data + file.Close() + } else { + ch <- nil + } + writeJSON(w, 200, map[string]bool{"success": true}) + }) + + // ───────────────────────────────────────────────────────────── + // PUBLIC FILE SERVING (/files/{session_id}/*) + // ───────────────────────────────────────────────────────────── + r.Get("/files/{session_id}/*", func(w http.ResponseWriter, r *http.Request) { + sid := chi.URLParam(r, "session_id") + filename := chi.URLParam(r, "*") + + globalState.mu.RLock() + s, exists := globalState.sessions[sid] + ch, relayExists := globalState.relaySessions[sid] + globalState.mu.RUnlock() + + clientIP := r.RemoteAddr + userAgent := r.UserAgent() + + var basePath string + if exists { + if s.Mode == ModeServerBg { + basePath = filepath.Join(sessionsDir, sid) + } else if s.Mode == ModeLocalPath { + basePath = s.Path + } + } + + if basePath != "" { + fullPath := filepath.Join(basePath, filename) + stat, err := os.Stat(fullPath) + if err == nil { + if stat.IsDir() { + // Obsidian Liquid Glass HTML Directory Listing + w.Header().Set("Content-Type", "text/html; charset=utf-8") + entries, _ := os.ReadDir(fullPath) + + w.Write([]byte(renderObsidianDirectoryHTML(sid, filename, entries))) + recordAccessEvent(sid, clientIP, r.Method, r.URL.Path, 200, 1024, userAgent) + return + } + + recordAccessEvent(sid, clientIP, r.Method, r.URL.Path, 200, stat.Size(), userAgent) + http.ServeFile(w, r, fullPath) + return + } + } else if relayExists { + reqID := fmt.Sprintf("%d", time.Now().UnixNano()) + resCh := make(chan []byte, 1) + + globalState.mu.Lock() + globalState.requestEvents[reqID] = resCh + globalState.mu.Unlock() + + ch <- map[string]interface{}{ + "type": "request_file", + "req_id": reqID, + "filename": filename, + } + + select { + case data := <-resCh: + globalState.mu.Lock() + delete(globalState.requestEvents, reqID) + globalState.mu.Unlock() + if data != nil { + recordAccessEvent(sid, clientIP, r.Method, r.URL.Path, 200, int64(len(data)), userAgent) + w.Write(data) + return + } + case <-time.After(30 * time.Second): + globalState.mu.Lock() + delete(globalState.requestEvents, reqID) + globalState.mu.Unlock() + } + } + + recordAccessEvent(sid, clientIP, r.Method, r.URL.Path, 404, 0, userAgent) + http.Error(w, "File not found or session expired", 404) + }) + + // ───────────────────────────────────────────────────────────── + // TUNNELING ENDPOINTS + // ───────────────────────────────────────────────────────────── r.Post("/get_tunnel", func(w http.ResponseWriter, r *http.Request) { var req struct { SessionID string `json:"session_id"` @@ -446,15 +770,31 @@ func main() { json.NewDecoder(r.Body).Decode(&req) if req.SessionID == "" { - writeJSON(w, 400, map[string]string{"error": "No session ID"}) + writeJSON(w, 400, map[string]string{"error": "Session ID required"}) return } tunnelURL := fmt.Sprintf("https://nexus.linuxguy.space/hoster/%s", req.SessionID) + globalState.mu.Lock() + if s, ok := globalState.sessions[req.SessionID]; ok { + s.TunnelActive = true + s.TunnelURL = tunnelURL + } + globalState.mu.Unlock() + writeJSON(w, 200, map[string]any{"success": true, "url": tunnelURL}) }) r.Post("/stop_tunnel", func(w http.ResponseWriter, r *http.Request) { + var req struct { + SessionID string `json:"session_id"` + } + json.NewDecoder(r.Body).Decode(&req) + globalState.mu.Lock() + if s, ok := globalState.sessions[req.SessionID]; ok { + s.TunnelActive = false + } + globalState.mu.Unlock() writeJSON(w, 200, map[string]bool{"success": true}) }) @@ -467,13 +807,140 @@ func main() { SessionID string `json:"session_id"` } json.NewDecoder(r.Body).Decode(&req) - tunnelURL := fmt.Sprintf("https://nexus.linuxguy.space/hoster/%s", req.SessionID) writeJSON(w, 200, map[string]any{"active": true, "url": tunnelURL}) }) + r.Post("/admin_login", func(w http.ResponseWriter, r *http.Request) { + writeJSON(w, 200, map[string]bool{"success": true}) + }) + slog.Info("starting image-hoster", "port", port, "pid", os.Getpid()) if err := http.ListenAndServe(":"+port, r); err != nil { slog.Error("server failed", "error", err) } } + +// Render Obsidian Liquid Glass Directory Listing +func renderObsidianDirectoryHTML(sid, relDir string, entries []os.DirEntry) string { + var sb strings.Builder + title := "Index of /" + relDir + if relDir == "" { + title = "Hosted Files Directory" + } + + sb.WriteString(` + + + + + ` + title + ` · Host It Now + + + + + +
+
+
` + title + `
+
` + fmt.Sprintf("%d items", len(entries)) + `
+
+
`) + return sb.String() +} diff --git a/cmd/image-hoster/styles.css b/cmd/image-hoster/styles.css new file mode 100644 index 0000000..a7507cf --- /dev/null +++ b/cmd/image-hoster/styles.css @@ -0,0 +1,1459 @@ +/* ═══════════════════════════════════════════════════════════════════ + HOST IT NOW · OBSIDIAN LIQUID GLASS DESIGN SYSTEM + ═══════════════════════════════════════════════════════════════════ */ + +:root { + --bg-base: #030305; + --bg-surface: rgba(15, 17, 26, 0.72); + --bg-surface-elevated: rgba(22, 25, 38, 0.85); + --bg-input: rgba(10, 11, 18, 0.88); + --border-subtle: rgba(255, 255, 255, 0.07); + --border-highlight: rgba(0, 242, 254, 0.35); + --border-glow: rgba(0, 242, 254, 0.15); + + --accent-cyan: #00f2fe; + --accent-blue: #38bdf8; + --accent-purple: #a855f7; + --accent-green: #10b981; + --accent-amber: #f59e0b; + --accent-rose: #f43f5e; + + --text-1: #ffffff; + --text-2: #cbd5e1; + --text-3: #94a3b8; + --muted: #64748b; + + --font-sans: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; + --font-mono: 'JetBrains Mono', monospace; + + --r-sm: 6px; + --r-md: 10px; + --r-lg: 14px; + --r-xl: 18px; + + --glass-blur: blur(24px); + --shadow-obsidian: 0 16px 40px -10px rgba(0, 0, 0, 0.8), 0 0 0 1px rgba(255, 255, 255, 0.06); + --shadow-glow: 0 0 25px rgba(0, 242, 254, 0.15); +} + +* { + box-sizing: border-box; + margin: 0; + padding: 0; +} + +body { + background-color: var(--bg-base); + color: var(--text-1); + font-family: var(--font-sans); + min-height: 100vh; + display: flex; + flex-direction: column; + align-items: center; + padding: 24px 18px 80px; + position: relative; + overflow-x: hidden; + -webkit-font-smoothing: antialiased; +} + +/* Ambient Obsidian Mesh Background */ +.ambient-mesh { + position: fixed; + top: 0; + left: 0; + width: 100vw; + height: 100vh; + background: + radial-gradient(circle at 15% 15%, rgba(0, 242, 254, 0.05), transparent 40%), + radial-gradient(circle at 85% 20%, rgba(168, 85, 247, 0.06), transparent 45%), + radial-gradient(circle at 50% 80%, rgba(16, 185, 129, 0.04), transparent 50%), + #030305; + pointer-events: none; + z-index: -1; +} + +.ambient-mesh::after { + content: ''; + position: absolute; + inset: 0; + background: radial-gradient(rgba(255, 255, 255, 0.03) 1px, transparent 1px); + background-size: 28px 28px; + opacity: 0.35; +} + +.app-root { + width: 100%; + max-width: 1080px; + display: flex; + flex-direction: column; + gap: 16px; + position: relative; + z-index: 1; +} + +/* ═══════════════════════════════════════════════════════════════════ + HEADER & GLOBAL METRICS + ═══════════════════════════════════════════════════════════════════ */ +.hin-header { + display: flex; + align-items: center; + justify-content: space-between; + background: var(--bg-surface); + backdrop-filter: var(--glass-blur); + border: 1px solid var(--border-subtle); + border-radius: var(--r-xl); + padding: 14px 20px; + box-shadow: var(--shadow-obsidian); + gap: 16px; +} + +.brand-badge { + display: flex; + align-items: center; + gap: 12px; +} + +.brand-icon { + width: 40px; + height: 40px; + border-radius: var(--r-md); + background: linear-gradient(135deg, rgba(0, 242, 254, 0.2), rgba(168, 85, 247, 0.25)); + border: 1px solid rgba(0, 242, 254, 0.4); + display: flex; + align-items: center; + justify-content: center; + font-size: 19px; + color: var(--accent-cyan); + box-shadow: 0 0 16px rgba(0, 242, 254, 0.2); +} + +.brand-text h1 { + font-size: 16px; + font-weight: 800; + letter-spacing: -0.02em; + color: #fff; + line-height: 1.15; +} + +.brand-text span { + font-size: 11px; + color: var(--muted); + font-weight: 500; +} + +.header-center { + display: flex; + align-items: center; +} + +.header-metrics { + display: flex; + align-items: center; + gap: 8px; + background: rgba(0, 0, 0, 0.4); + padding: 5px 10px; + border-radius: 999px; + border: 1px solid var(--border-subtle); +} + +.metric-pill { + display: flex; + align-items: center; + gap: 6px; + padding: 3px 8px; + font-size: 11.5px; +} + +.metric-label { + color: var(--text-3); + font-weight: 500; +} + +.metric-val { + font-family: var(--font-mono); + font-weight: 700; + color: #fff; +} + +.header-right { + display: flex; + align-items: center; + gap: 8px; +} + +/* ═══════════════════════════════════════════════════════════════════ + BUTTONS & CONTROLS + ═══════════════════════════════════════════════════════════════════ */ +.btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 7px; + font-family: var(--font-sans); + font-size: 12.5px; + font-weight: 600; + padding: 8px 14px; + border-radius: var(--r-md); + cursor: pointer; + transition: all 0.2s cubic-bezier(0.16, 1, 0.3, 1); + border: 1px solid transparent; + text-decoration: none; + white-space: nowrap; +} + +.btn:active { + transform: scale(0.97); +} + +.btn-sm { + padding: 5px 10px; + font-size: 11.5px; + height: 30px; +} + +.btn-cyan { + background: linear-gradient(135deg, rgba(0, 242, 254, 0.9), rgba(6, 182, 212, 0.9)); + color: #030712; + border-color: rgba(0, 242, 254, 0.5); + box-shadow: 0 4px 14px rgba(0, 242, 254, 0.25); +} + +.btn-cyan:hover { + background: #00f2fe; + box-shadow: 0 6px 20px rgba(0, 242, 254, 0.4); + color: #000; +} + +.btn-secondary { + background: rgba(255, 255, 255, 0.05); + border-color: var(--border-subtle); + color: var(--text-2); +} + +.btn-secondary:hover { + background: rgba(255, 255, 255, 0.1); + border-color: rgba(255, 255, 255, 0.15); + color: #fff; +} + +.btn-green { + background: linear-gradient(135deg, rgba(16, 185, 129, 0.9), rgba(5, 150, 105, 0.9)); + color: #fff; + border-color: rgba(16, 185, 129, 0.4); + box-shadow: 0 4px 14px rgba(16, 185, 129, 0.25); +} + +.btn-green:hover { + background: #10b981; + box-shadow: 0 6px 20px rgba(16, 185, 129, 0.4); +} + +.btn-danger { + background: rgba(244, 63, 94, 0.12); + border-color: rgba(244, 63, 94, 0.3); + color: var(--accent-rose); +} + +.btn-danger:hover { + background: rgba(244, 63, 94, 0.25); + color: #fff; + border-color: var(--accent-rose); +} + +/* ═══════════════════════════════════════════════════════════════════ + SESSION GOVERNANCE & RAIL + ═══════════════════════════════════════════════════════════════════ */ +.session-governance-strip { + display: flex; + align-items: center; + justify-content: space-between; + background: var(--bg-surface); + backdrop-filter: var(--glass-blur); + border: 1px solid var(--border-subtle); + border-radius: var(--r-lg); + padding: 10px 16px; + gap: 12px; +} + +.session-rail-left { + display: flex; + align-items: center; + gap: 12px; + overflow-x: auto; + flex: 1; + scrollbar-width: none; +} + +.session-rail-left::-webkit-scrollbar { + display: none; +} + +.rail-title { + font-size: 11px; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.05em; + color: var(--text-3); + display: flex; + align-items: center; + gap: 6px; + white-space: nowrap; +} + +.session-tabs-rail { + display: flex; + align-items: center; + gap: 8px; +} + +.session-tab { + display: flex; + align-items: center; + gap: 7px; + background: rgba(255, 255, 255, 0.03); + border: 1px solid var(--border-subtle); + border-radius: var(--r-md); + padding: 5px 11px; + font-size: 11.5px; + color: var(--text-3); + cursor: pointer; + transition: all 0.2s ease; + white-space: nowrap; +} + +.session-tab:hover { + background: rgba(255, 255, 255, 0.07); + color: #fff; + border-color: rgba(255, 255, 255, 0.15); +} + +.session-tab.active { + background: rgba(0, 242, 254, 0.1); + border-color: var(--border-highlight); + color: #fff; + box-shadow: 0 0 14px rgba(0, 242, 254, 0.15); +} + +.session-tab .tab-icon { + font-size: 11px; + color: var(--accent-cyan); +} + +.session-tab .tab-ttl { + font-size: 10px; + font-family: var(--font-mono); + padding: 1px 5px; + border-radius: 4px; + background: rgba(0, 0, 0, 0.4); + color: var(--text-3); +} + +.session-rail-actions { + display: flex; + align-items: center; + gap: 6px; + flex-shrink: 0; +} + +/* ═══════════════════════════════════════════════════════════════════ + LIVE PUBLIC TUNNEL CARD + ═══════════════════════════════════════════════════════════════════ */ +.live-tunnel-card { + background: var(--bg-surface); + backdrop-filter: var(--glass-blur); + border: 1px solid var(--border-subtle); + border-radius: var(--r-lg); + padding: 14px 20px; + box-shadow: var(--shadow-obsidian); + display: flex; + flex-direction: column; + gap: 12px; + transition: all 0.3s ease; +} + +.live-tunnel-card.is-live { + border-color: rgba(16, 185, 129, 0.35); + box-shadow: 0 16px 40px -10px rgba(0, 0, 0, 0.8), 0 0 25px rgba(16, 185, 129, 0.12); +} + +.tunnel-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; +} + +.tunnel-info { + display: flex; + align-items: center; + gap: 10px; + flex-wrap: wrap; +} + +.tunnel-status-badge { + display: inline-flex; + align-items: center; + gap: 7px; + font-size: 11.5px; + font-weight: 700; + padding: 4px 11px; + border-radius: 999px; + text-transform: uppercase; + letter-spacing: 0.04em; +} + +.badge-offline { + background: rgba(100, 116, 139, 0.12); + border: 1px solid rgba(100, 116, 139, 0.25); + color: var(--muted); +} + +.badge-offline .status-dot { + width: 6px; + height: 6px; + border-radius: 50%; + background: var(--muted); +} + +.badge-live { + background: rgba(16, 185, 129, 0.15); + border: 1px solid rgba(16, 185, 129, 0.35); + color: var(--accent-green); + box-shadow: 0 0 12px rgba(16, 185, 129, 0.2); +} + +.badge-live .status-dot { + width: 6px; + height: 6px; + border-radius: 50%; + background: var(--accent-green); + animation: livePulse 2s infinite ease-in-out; +} + +@keyframes livePulse { + 0%, 100% { transform: scale(1); opacity: 1; } + 50% { transform: scale(1.5); opacity: 0.4; } +} + +.tunnel-governance-pill, .tunnel-mode-pill { + display: flex; + align-items: center; + gap: 6px; + font-size: 11px; + font-family: var(--font-mono); + padding: 3px 9px; + border-radius: 999px; + background: rgba(0, 0, 0, 0.4); + border: 1px solid var(--border-subtle); + color: var(--text-2); +} + +.tunnel-controls { + display: flex; + align-items: center; + gap: 8px; +} + +.tunnel-spinner { + display: flex; + align-items: center; + gap: 7px; + color: var(--accent-cyan); + font-size: 11.5px; +} + +.tunnel-url-row { + display: flex; + align-items: center; + justify-content: space-between; + background: var(--bg-input); + border: 1px solid var(--border-subtle); + border-radius: var(--r-md); + padding: 7px 12px; + gap: 12px; +} + +.url-input-box { + display: flex; + align-items: center; + gap: 9px; + flex: 1; + overflow: hidden; +} + +.url-text { + font-family: var(--font-mono); + font-size: 12.5px; + color: #fff; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + user-select: all; +} + +.url-actions { + display: flex; + align-items: center; + gap: 6px; + flex-shrink: 0; +} + +/* ═══════════════════════════════════════════════════════════════════ + CONTENT INGESTION & TABS + ═══════════════════════════════════════════════════════════════════ */ +.ingest-card { + background: var(--bg-surface); + backdrop-filter: var(--glass-blur); + border: 1px solid var(--border-subtle); + border-radius: var(--r-lg); + box-shadow: var(--shadow-obsidian); + overflow: hidden; +} + +.ingest-tabs { + display: grid; + grid-template-columns: repeat(3, 1fr); + border-bottom: 1px solid var(--border-subtle); + background: rgba(0, 0, 0, 0.3); +} + +.ingest-tab { + background: transparent; + border: none; + padding: 14px 18px; + display: flex; + align-items: center; + gap: 12px; + cursor: pointer; + text-align: left; + transition: all 0.2s ease; + border-bottom: 2px solid transparent; +} + +.ingest-tab:hover { + background: rgba(255, 255, 255, 0.03); +} + +.ingest-tab.active { + background: rgba(255, 255, 255, 0.04); + border-bottom-color: var(--accent-cyan); +} + +.ingest-tab i { + font-size: 20px; + color: var(--muted); + transition: color 0.2s ease; +} + +.ingest-tab.active i { + color: var(--accent-cyan); +} + +.tab-meta strong { + display: block; + font-size: 12.5px; + color: var(--text-2); + font-weight: 600; +} + +.ingest-tab.active .tab-meta strong { + color: #fff; +} + +.tab-meta span { + display: block; + font-size: 10.5px; + color: var(--muted); + margin-top: 2px; +} + +.ingest-content { + padding: 20px; +} + +/* Vault Dropzone */ +.vault-dropzone { + border: 2px dashed rgba(255, 255, 255, 0.12); + border-radius: var(--r-lg); + padding: 34px 24px; + text-align: center; + display: flex; + flex-direction: column; + align-items: center; + gap: 12px; + background: rgba(0, 0, 0, 0.2); + transition: all 0.2s ease; + cursor: pointer; +} + +.vault-dropzone:hover, .vault-dropzone.dragover { + border-color: var(--accent-cyan); + background: rgba(0, 242, 254, 0.04); + box-shadow: 0 0 25px rgba(0, 242, 254, 0.1); +} + +.dropzone-icon { + font-size: 34px; + color: var(--accent-cyan); + opacity: 0.85; +} + +.dropzone-text h3 { + font-size: 14px; + font-weight: 700; + color: #fff; +} + +.dropzone-text p { + font-size: 11.5px; + color: var(--text-3); + max-width: 520px; + margin-top: 4px; +} + +.dropzone-buttons { + display: flex; + align-items: center; + gap: 10px; + margin-top: 6px; +} + +/* Upload Progress */ +.upload-progress-container { + margin-top: 16px; + background: var(--bg-input); + border: 1px solid var(--border-subtle); + border-radius: var(--r-md); + padding: 12px 16px; +} + +.progress-info { + display: flex; + justify-content: space-between; + font-size: 11.5px; + color: var(--text-2); + margin-bottom: 8px; +} + +.progress-bar-bg { + width: 100%; + height: 6px; + background: rgba(255, 255, 255, 0.07); + border-radius: 999px; + overflow: hidden; +} + +.progress-bar-fill { + height: 100%; + width: 0%; + background: linear-gradient(90deg, var(--accent-cyan), var(--accent-purple)); + border-radius: 999px; + transition: width 0.2s ease; +} + +/* Path Input */ +.path-input-group { + display: flex; + gap: 8px; + align-items: center; +} + +.input-wrapper { + flex: 1; + position: relative; + display: flex; + align-items: center; +} + +.input-wrapper i { + position: absolute; + left: 14px; + font-size: 13px; +} + +.text-input { + width: 100%; + height: 38px; + background: var(--bg-input); + border: 1px solid var(--border-subtle); + border-radius: var(--r-md); + padding: 0 14px 0 38px; + color: #fff; + font-size: 12.5px; + font-family: var(--font-sans); + outline: none; + transition: border-color 0.2s ease; +} + +.text-input:focus { + border-color: var(--accent-cyan); + box-shadow: 0 0 12px rgba(0, 242, 254, 0.2); +} + +.input-hint { + font-size: 11px; + color: var(--muted); + margin-top: 8px; + display: flex; + align-items: center; + gap: 6px; +} + +/* Relay Mode Grid */ +.relay-action-grid { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 12px; +} + +.relay-card-btn { + background: rgba(0, 0, 0, 0.25); + border: 1px solid var(--border-subtle); + border-radius: var(--r-md); + padding: 20px; + cursor: pointer; + text-align: center; + display: flex; + flex-direction: column; + align-items: center; + gap: 6px; + transition: all 0.2s ease; +} + +.relay-card-btn:hover { + background: rgba(255, 255, 255, 0.04); + border-color: var(--accent-cyan); +} + +.relay-card-btn i { + font-size: 26px; +} + +.relay-card-btn strong { + font-size: 12.5px; + color: #fff; +} + +.relay-card-btn span { + font-size: 11px; + color: var(--muted); +} + +/* Status Bar */ +.hin-status-bar { + display: flex; + align-items: center; + justify-content: space-between; + padding: 10px 20px; + background: rgba(0, 0, 0, 0.35); + border-top: 1px solid var(--border-subtle); + font-size: 11.5px; +} + +.status-left { + display: flex; + align-items: center; + gap: 8px; + color: var(--text-2); +} + +.status-right { + display: flex; + align-items: center; + gap: 6px; +} + +.meta-pill { + padding: 2px 7px; + border-radius: 4px; + background: rgba(255, 255, 255, 0.06); + color: var(--text-3); + font-family: var(--font-mono); + font-size: 10.5px; +} + +/* ═══════════════════════════════════════════════════════════════════ + EXPLORER: TOOLBAR & SEARCH + ═══════════════════════════════════════════════════════════════════ */ +.explorer-card { + background: var(--bg-surface); + backdrop-filter: var(--glass-blur); + border: 1px solid var(--border-subtle); + border-radius: var(--r-lg); + box-shadow: var(--shadow-obsidian); + overflow: hidden; +} + +.explorer-toolbar { + display: flex; + align-items: center; + justify-content: space-between; + padding: 12px 18px; + border-bottom: 1px solid var(--border-subtle); + gap: 12px; + flex-wrap: wrap; +} + +.toolbar-search { + position: relative; + display: flex; + align-items: center; + flex: 1; + min-width: 240px; +} + +.toolbar-search i { + position: absolute; + left: 12px; + color: var(--muted); + font-size: 12px; +} + +.toolbar-search input { + width: 100%; + height: 32px; + background: var(--bg-input); + border: 1px solid var(--border-subtle); + border-radius: var(--r-md); + padding: 0 12px 0 32px; + color: #fff; + font-size: 11.5px; + outline: none; +} + +.toolbar-search input:focus { + border-color: var(--accent-cyan); +} + +.toolbar-filter-chips { + display: flex; + align-items: center; + gap: 5px; +} + +.filter-chip { + background: transparent; + border: 1px solid var(--border-subtle); + border-radius: 999px; + padding: 4px 10px; + font-size: 11px; + font-weight: 500; + color: var(--text-3); + cursor: pointer; + transition: all 0.2s ease; +} + +.filter-chip:hover { + color: #fff; + border-color: rgba(255, 255, 255, 0.2); +} + +.filter-chip.active { + background: rgba(0, 242, 254, 0.12); + border-color: var(--accent-cyan); + color: #fff; +} + +.toolbar-bulk-actions { + display: flex; + align-items: center; + gap: 8px; +} + +.view-toggle { + display: flex; + align-items: center; + background: var(--bg-input); + border: 1px solid var(--border-subtle); + border-radius: var(--r-md); + overflow: hidden; +} + +.view-btn { + background: transparent; + border: none; + padding: 6px 9px; + color: var(--muted); + cursor: pointer; + font-size: 11.5px; +} + +.view-btn.active { + background: rgba(255, 255, 255, 0.1); + color: var(--accent-cyan); +} + +/* ═══════════════════════════════════════════════════════════════════ + FILES CONTAINER (GRID & LIST MODES) + ═══════════════════════════════════════════════════════════════════ */ +.files-container { + padding: 18px; + min-height: 220px; +} + +.folder-group-block { + margin-bottom: 24px; +} + +.folder-group-header { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 12px; + padding-bottom: 6px; + border-bottom: 1px solid rgba(255, 255, 255, 0.05); +} + +.folder-group-title { + font-size: 13px; + font-weight: 700; + color: #fff; + display: flex; + align-items: center; + gap: 8px; +} + +.folder-group-title i { + color: var(--accent-cyan); +} + +.folder-group-meta { + font-size: 11px; + color: var(--muted); + font-family: var(--font-mono); +} + +/* Grid Layout */ +.files-container.grid-mode .files-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(210px, 1fr)); + gap: 14px; +} + +.file-card { + background: var(--bg-surface-elevated); + border: 1px solid var(--border-subtle); + border-radius: var(--r-md); + overflow: hidden; + transition: all 0.25s cubic-bezier(0.16, 1, 0.3, 1); + display: flex; + flex-direction: column; + position: relative; +} + +.file-card:hover { + transform: translateY(-2px); + border-color: rgba(0, 242, 254, 0.4); + box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.6), 0 0 15px rgba(0, 242, 254, 0.1); +} + +.file-thumb-wrap { + width: 100%; + height: 130px; + background: #000; + position: relative; + overflow: hidden; + display: flex; + align-items: center; + justify-content: center; + cursor: pointer; +} + +.file-thumb-img { + width: 100%; + height: 100%; + object-fit: contain; + transition: transform 0.3s ease; +} + +.file-card:hover .file-thumb-img { + transform: scale(1.05); +} + +.file-icon-box { + font-size: 38px; + color: var(--muted); + opacity: 0.7; +} + +.file-card-details { + padding: 10px 12px; + display: flex; + flex-direction: column; + gap: 4px; + flex: 1; +} + +.file-card-name { + font-size: 12px; + font-weight: 600; + color: #fff; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.file-card-meta { + font-size: 10.5px; + color: var(--muted); + font-family: var(--font-mono); + display: flex; + justify-content: space-between; +} + +.file-card-actions { + display: flex; + align-items: center; + justify-content: space-between; + padding: 6px 10px; + background: rgba(0, 0, 0, 0.3); + border-top: 1px solid var(--border-subtle); + gap: 4px; +} + +.action-icon-btn { + width: 26px; + height: 26px; + border-radius: var(--r-sm); + background: transparent; + border: 1px solid transparent; + color: var(--text-3); + display: flex; + align-items: center; + justify-content: center; + cursor: pointer; + font-size: 11px; + transition: all 0.15s ease; + text-decoration: none; +} + +.action-icon-btn:hover { + background: rgba(255, 255, 255, 0.1); + color: #fff; +} + +.action-icon-btn.primary:hover { + background: rgba(0, 242, 254, 0.2); + color: var(--accent-cyan); +} + +/* List Layout */ +.files-container.list-mode .files-grid { + display: flex; + flex-direction: column; + gap: 6px; +} + +.files-container.list-mode .file-card { + flex-direction: row; + align-items: center; + height: 52px; + padding: 0 12px; +} + +.files-container.list-mode .file-thumb-wrap { + width: 36px; + height: 36px; + border-radius: var(--r-sm); + flex-shrink: 0; +} + +.files-container.list-mode .file-icon-box { + font-size: 16px; +} + +.files-container.list-mode .file-card-details { + flex: 1; + flex-direction: row; + align-items: center; + justify-content: space-between; + padding: 0 14px; +} + +.files-container.list-mode .file-card-actions { + background: transparent; + border-top: none; + padding: 0; +} + +/* Empty State */ +.empty-state { + text-align: center; + padding: 48px 20px; + color: var(--muted); + display: flex; + flex-direction: column; + align-items: center; + gap: 12px; +} + +.empty-state i { + font-size: 42px; + opacity: 0.35; + color: var(--accent-cyan); +} + +.empty-state p { + font-size: 13px; + max-width: 380px; +} + +/* ═══════════════════════════════════════════════════════════════════ + MODALS + ═══════════════════════════════════════════════════════════════════ */ +.modal-backdrop { + position: fixed; + inset: 0; + background: rgba(0, 0, 0, 0.82); + backdrop-filter: blur(12px); + display: flex; + align-items: center; + justify-content: center; + z-index: 1000; + padding: 20px; + animation: modalFadeIn 0.2s ease; +} + +@keyframes modalFadeIn { + from { opacity: 0; transform: scale(0.98); } + to { opacity: 1; transform: scale(1); } +} + +.modal-card { + width: 100%; + max-width: 540px; + background: var(--bg-surface-elevated); + border: 1px solid var(--border-subtle); + border-radius: var(--r-lg); + box-shadow: var(--shadow-obsidian), 0 0 35px rgba(0, 242, 254, 0.08); + overflow: hidden; + display: flex; + flex-direction: column; +} + +.modal-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 16px 20px; + border-bottom: 1px solid var(--border-subtle); +} + +.modal-header h3 { + font-size: 14px; + font-weight: 700; + color: #fff; + display: flex; + align-items: center; + gap: 8px; +} + +.modal-close-btn { + background: transparent; + border: none; + color: var(--muted); + font-size: 15px; + cursor: pointer; + transition: color 0.15s ease; +} + +.modal-close-btn:hover { + color: #fff; +} + +.modal-body { + padding: 20px; + display: flex; + flex-direction: column; + gap: 14px; +} + +.modal-footer { + display: flex; + align-items: center; + justify-content: flex-end; + gap: 8px; + padding: 12px 20px; + background: rgba(0, 0, 0, 0.25); + border-top: 1px solid var(--border-subtle); +} + +.form-group { + display: flex; + flex-direction: column; + gap: 6px; +} + +.form-group label { + font-size: 11.5px; + font-weight: 600; + color: var(--text-2); +} + +.form-hint { + font-size: 10.5px; + color: var(--muted); + line-height: 1.4; +} + +/* Lightbox Modal */ +.lightbox-card { + max-width: 90vw; + max-height: 90vh; + background: rgba(10, 11, 18, 0.95); + border: 1px solid var(--border-subtle); + border-radius: var(--r-lg); + overflow: hidden; + display: flex; + flex-direction: column; +} + +.lightbox-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 12px 18px; + border-bottom: 1px solid var(--border-subtle); +} + +.lightbox-title { + font-size: 13px; + font-weight: 600; +} + +.lightbox-body { + padding: 20px; + display: flex; + align-items: center; + justify-content: center; + max-height: 70vh; + overflow: auto; +} + +.lightbox-body img { + max-width: 100%; + max-height: 65vh; + object-fit: contain; + border-radius: var(--r-sm); +} + +.lightbox-footer { + padding: 10px 18px; + background: rgba(0, 0, 0, 0.4); + border-top: 1px solid var(--border-subtle); + display: flex; + align-items: center; + justify-content: space-between; + font-size: 11px; + color: var(--text-3); + gap: 12px; +} + +/* QR Code Canvas Box */ +.qr-canvas-box { + padding: 16px; + background: #ffffff; + border-radius: var(--r-md); + display: flex; + align-items: center; + justify-content: center; + box-shadow: 0 10px 25px rgba(0, 0, 0, 0.5); +} + +.qr-canvas-box canvas, .qr-canvas-box img { + max-width: 200px; + height: auto; +} + +/* Code Viewport */ +.code-viewport { + background: #030305; + padding: 18px; + font-family: var(--font-mono); + font-size: 12px; + color: #e2e8f0; + max-height: 480px; + overflow: auto; + line-height: 1.5; + border: none; + outline: none; +} + +/* Telemetry Table */ +.telemetry-stats-row { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 10px; +} + +.t-stat-card { + background: rgba(0, 0, 0, 0.4); + border: 1px solid var(--border-subtle); + border-radius: var(--r-md); + padding: 12px; + display: flex; + flex-direction: column; + gap: 2px; +} + +.t-stat-val { + font-size: 18px; + font-weight: 800; + font-family: var(--font-mono); + color: #fff; +} + +.t-stat-label { + font-size: 10.5px; + color: var(--muted); +} + +.telemetry-log-table-wrap { + max-height: 280px; + overflow-y: auto; + border: 1px solid var(--border-subtle); + border-radius: var(--r-md); + background: rgba(0, 0, 0, 0.25); +} + +.telemetry-table { + width: 100%; + border-collapse: collapse; + font-size: 11px; + text-align: left; +} + +.telemetry-table th { + background: rgba(255, 255, 255, 0.04); + padding: 8px 12px; + color: var(--text-3); + font-weight: 600; + border-bottom: 1px solid var(--border-subtle); + position: sticky; + top: 0; +} + +.telemetry-table td { + padding: 7px 12px; + border-bottom: 1px solid rgba(255, 255, 255, 0.03); + color: var(--text-2); + font-family: var(--font-mono); +} + +/* Batch Export Pills */ +.batch-export-formats { + display: flex; + gap: 6px; + flex-wrap: wrap; +} + +.seg-pill { + background: rgba(255, 255, 255, 0.04); + border: 1px solid var(--border-subtle); + border-radius: var(--r-md); + padding: 5px 12px; + color: var(--text-3); + font-size: 11.5px; + font-weight: 600; + cursor: pointer; + transition: all 0.15s ease; +} + +.seg-pill.active { + background: rgba(0, 242, 254, 0.15); + border-color: var(--accent-cyan); + color: #fff; +} + +/* Server Dir Modal List */ +.server-dir-breadcrumb { + padding: 8px 12px; + background: var(--bg-input); + border-radius: var(--r-md); + font-family: var(--font-mono); + font-size: 12px; + color: var(--accent-cyan); + border: 1px solid var(--border-subtle); +} + +.server-dir-list { + max-height: 280px; + overflow-y: auto; + display: flex; + flex-direction: column; + gap: 4px; + margin-top: 8px; +} + +.server-dir-item { + display: flex; + align-items: center; + gap: 10px; + padding: 8px 12px; + border-radius: var(--r-sm); + cursor: pointer; + font-size: 12px; + color: var(--text-2); + transition: background 0.15s ease; +} + +.server-dir-item:hover { + background: rgba(255, 255, 255, 0.06); + color: #fff; +} + +.server-dir-item i { + color: var(--accent-cyan); +} + +/* ═══════════════════════════════════════════════════════════════════ + TOASTS + ═══════════════════════════════════════════════════════════════════ */ +.toast-container { + position: fixed; + bottom: 24px; + right: 24px; + z-index: 2000; + display: flex; + flex-direction: column; + gap: 8px; + pointer-events: none; +} + +.toast { + padding: 10px 16px; + background: rgba(15, 17, 26, 0.95); + backdrop-filter: blur(12px); + border: 1px solid var(--border-subtle); + border-radius: var(--r-md); + color: #fff; + font-size: 12px; + font-weight: 500; + display: flex; + align-items: center; + gap: 8px; + box-shadow: 0 10px 30px rgba(0, 0, 0, 0.7); + pointer-events: auto; + animation: toastSlideIn 0.25s ease; +} + +.toast.success { border-color: rgba(16, 185, 129, 0.4); } +.toast.success i { color: var(--accent-green); } +.toast.error { border-color: rgba(244, 63, 94, 0.4); } +.toast.error i { color: var(--accent-rose); } +.toast.info { border-color: rgba(0, 242, 254, 0.4); } +.toast.info i { color: var(--accent-cyan); } + +@keyframes toastSlideIn { + from { transform: translateX(100%); opacity: 0; } + to { transform: translateX(0); opacity: 1; } +} + +/* Responsive adjustments */ +@media (max-width: 768px) { + .ingest-tabs { grid-template-columns: 1fr; } + .header-metrics { display: none; } + .relay-action-grid { grid-template-columns: 1fr; } + .explorer-toolbar { flex-direction: column; align-items: stretch; } + .toolbar-search { min-width: 100%; } +} diff --git a/cmd/image-hoster/types.go b/cmd/image-hoster/types.go new file mode 100644 index 0000000..0a10519 --- /dev/null +++ b/cmd/image-hoster/types.go @@ -0,0 +1,59 @@ +package main + +import ( + "os/exec" + "sync" + "time" +) + +type SessionMode string + +const ( + ModeServerBg SessionMode = "server_background" // Hosted persistently on server disk + ModeLocalPath SessionMode = "local_path" // Mapped to local server filesystem path + ModeRelay SessionMode = "relay" // P2P streaming from browser memory via SSE +) + +type SessionMeta struct { + ID string `json:"id"` + Name string `json:"name"` + Mode SessionMode `json:"mode"` + Path string `json:"path"` + CreatedAt time.Time `json:"created_at"` + ExpiresAt time.Time `json:"expires_at"` // Zero time = never + TimeLimitSec int `json:"time_limit_sec"` // 0 = unlimited + FileCount int `json:"file_count"` + TotalBytes int64 `json:"total_bytes"` + Requests int64 `json:"requests"` + BytesServed int64 `json:"bytes_served"` + LastActive time.Time `json:"last_active"` + TunnelActive bool `json:"tunnel_active"` + TunnelURL string `json:"tunnel_url"` +} + +type AccessEvent struct { + Timestamp time.Time `json:"timestamp"` + IP string `json:"ip"` + Method string `json:"method"` + Path string `json:"path"` + Status int `json:"status"` + Bytes int64 `json:"bytes"` + UserAgent string `json:"user_agent"` +} + +type HostState struct { + mu sync.RWMutex + sessions map[string]*SessionMeta + relaySessions map[string]chan map[string]interface{} + requestEvents map[string]chan []byte + accessLogs map[string][]AccessEvent + tunnelProcess *exec.Cmd + tunnelURL string +} + +var globalState = &HostState{ + sessions: make(map[string]*SessionMeta), + relaySessions: make(map[string]chan map[string]interface{}), + requestEvents: make(map[string]chan []byte), + accessLogs: make(map[string][]AccessEvent), +} diff --git a/internal/gateway/router.go b/internal/gateway/router.go index 7dde5b8..a9c7a18 100644 --- a/internal/gateway/router.go +++ b/internal/gateway/router.go @@ -660,5 +660,16 @@ func NewRouter(pm *ProcessManager) http.Handler { http.Error(w, "Image manipulator not found", http.StatusNotFound) }) + r.HandleFunc("/files/*", func(w http.ResponseWriter, req *http.Request) { + _ = pm.EnsureRunning(req.Context(), "image-hoster") + cfg := pm.getConfig("image-hoster") + if cfg != nil { + proxy := toolProxy(pm, "image-hoster", cfg.Port) + proxy.ServeHTTP(w, req) + return + } + http.Error(w, "Image hoster not found", http.StatusNotFound) + }) + return r } diff --git a/web/image-hoster/app.js b/web/image-hoster/app.js index 4bc19cf..85bd0dc 100644 --- a/web/image-hoster/app.js +++ b/web/image-hoster/app.js @@ -1,163 +1,512 @@ -// ───────────────────────────────────────────── -// Derive gateway prefix so file links work through the proxy. -// If we're at /tool/image-hoster/ → TOOL_BASE = "/tool/image-hoster" -// If we're at / → TOOL_BASE = "" +// ═══════════════════════════════════════════════════════════════════ +// HOST IT NOW · ENTERPRISE CLOUD VAULT & EDGE RELAY CONTROLLER +// ═══════════════════════════════════════════════════════════════════ + const TOOL_BASE = (() => { const p = window.location.pathname.replace(/\/+$/, ''); - // pathname ends with the tool slug; anything before it that looks like /tool/X is the prefix return p; })(); +function getApiUrl(endpoint) { + const p = endpoint.startsWith('/') ? endpoint : '/' + endpoint; + if (TOOL_BASE && !p.startsWith(TOOL_BASE)) { + return TOOL_BASE + p; + } + return p; +} + // ───────────────────────────────────────────── -// State +// Global State // ───────────────────────────────────────────── let sessions = []; -try { - sessions = JSON.parse(localStorage.getItem('hin_sessions')) || []; - if (!Array.isArray(sessions)) sessions = []; - // Purge broken sessions - sessions = sessions.filter(s => s && s.id && s.id !== 'undefined' && s.id !== 'null'); -} catch(e) { sessions = []; } +let currentId = null; +let currentSession = null; +let currentFiles = []; -let currentId = localStorage.getItem('hin_current'); -if (currentId === 'undefined' || currentId === 'null') currentId = null; -if (currentId && !sessions.find(s => s.id === currentId)) currentId = null; +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 -const tunnelInfo = {}; // sessionId -> { url, active } +const relayFiles = {}; // sessionId -> { path: File } +const evtSources = {}; // sessionId -> EventSource +let countdownInterval = null; + +let serverExplorerCurrentPath = ''; // ───────────────────────────────────────────── -// Boot +// Initialization // ───────────────────────────────────────────── -async function init() { - save(); +document.addEventListener('DOMContentLoaded', () => { + setupDragAndDrop(); + startCountdownLoop(); + initApp(); +}); + +async function initApp() { + await refreshSessionsList(); if (!sessions.length) { - await createNewSession(); + await createNewSession('Default Vault', 'server_background', 0); } else { - if (!currentId) currentId = sessions[0].id; - renderSessionTabs(); - loadSession(currentId); - } -} - -// ───────────────────────────────────────────── -// Session Management -// ───────────────────────────────────────────── -async function createNewSession() { - try { - const res = await fetch('/create_session', { method: 'POST' }); - const data = await res.json(); - if (data.success) { - const sid = data.session_id; - sessions.push({ id: sid, created: Date.now() }); - save(); - switchSession(sid); + const storedId = localStorage.getItem('hin_current'); + if (storedId && sessions.find(s => s.id === storedId)) { + switchSession(storedId); } else { - toast('Failed to create session', true); + switchSession(sessions[0].id); } - } catch(e) { toast('Server error: ' + e.message, true); } -} - -async function deleteSession() { - if (!currentId) return; - if (!confirm('Delete this session and all its hosted content?')) return; - - // Tell server - await fetch('/delete_session', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ session_id: currentId }) - }).catch(() => {}); - - // Clean up client state - if (evtSources[currentId]) { evtSources[currentId].close(); delete evtSources[currentId]; } - delete relayFiles[currentId]; - delete tunnelInfo[currentId]; - - sessions = sessions.filter(s => s.id !== currentId); - currentId = null; - save(); - - if (sessions.length) { - switchSession(sessions[0].id); - } else { - await createNewSession(); } - toast('Session deleted'); } -function switchSession(id) { - currentId = id; - localStorage.setItem('hin_current', id); - renderSessionTabs(); - resetUI(); - loadSession(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 save() { - localStorage.setItem('hin_sessions', JSON.stringify(sessions)); - if (currentId) localStorage.setItem('hin_current', currentId); +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 renderSessionTabs() { - const container = document.getElementById('sessionTabs'); - container.innerHTML = ''; +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' : ''); - tab.textContent = 'S-' + s.id.slice(-6).toUpperCase(); - tab.title = s.id; + + 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); - container.appendChild(tab); + rail.appendChild(tab); }); } -// ───────────────────────────────────────────── -// Load a session -// ───────────────────────────────────────────── -async function loadSession(sid) { - connectSSE(sid); - checkTunnel(sid); +function switchSession(sid) { + currentId = sid; + localStorage.setItem('hin_current', sid); + currentSession = sessions.find(s => s.id === sid); - // Load files from server + renderSessionsRail(); + loadSessionDetails(sid); +} + +async function loadSessionDetails(sid) { try { - const res = await fetch(`/get_session_files/${sid}`); + const res = await fetch(getApiUrl(`/get_session_files/${sid}`)); const data = await res.json(); - if (sid !== currentId) return; + + if (data.session) { + currentSession = data.session; + updateSessionHUD(); + } if (data.mode === 'relay') { - setStatus('Browser Relay mode — files served from your device', true); - } else if (data.path_set && data.files && data.files.length) { - setStatus(`📂 ${data.current_path}`, true); - // Normalize server-returned URLs: server gives /files//..., - // we need TOOL_BASE + /files//... so the gateway proxies correctly - const normalised = data.files.map(f => ({ + 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, + url: f.url.startsWith(TOOL_BASE) ? f.url : (TOOL_BASE + f.url) })); - renderFileGroups(normalised); - } else if (data.path_set) { - setStatus(`📂 ${data.current_path} (empty)`, true); + setStatus(`Active Storage: ${data.current_path}`, true); + renderFilesExplorer(); } else { - resetUI(); + currentFiles = []; + setStatus(data.current_path ? `Empty Directory: ${data.current_path}` : 'Ready to host content · Drop files or map a folder', false); + renderFilesExplorer(); } - } catch(e) { /* ignore */ } + + checkTunnel(sid); + } catch (e) { + console.error('Error loading session files:', e); + } } -function resetUI() { - setStatus('No active source — pick a folder or enter a server path.', false); - document.getElementById('filesSection').innerHTML = ''; - document.getElementById('pathInput').value = ''; - setTunnelUI(false); +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`; } // ───────────────────────────────────────────── -// File Hosting +// Create & Delete Session // ───────────────────────────────────────────── -async function handleFileSelect(evt, type) { - const files = evt.target.files; +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]; @@ -167,73 +516,30 @@ async function handleFileSelect(evt, type) { map[key] = f; } - // Tell server we're in relay mode - await fetch('/set_session_path', { + await fetch(getApiUrl('/set_session_path'), { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ session_id: currentId, path: '(Relay Mode)' }) - }).catch(() => {}); + }); - setStatus(`Browser relay active — ${Object.keys(map).length} file(s) queued`, true); - - // Build file list for display using TOOL_BASE so links route through the gateway - const fileList = Object.entries(map).map(([path, f]) => ({ - name: f.name, - path: path, - url: `${TOOL_BASE}/files/${currentId}/${path}`, - folder: path.includes('/') ? path.split('/').slice(0, -1).join('/') : '(Root)', - is_code: /\.(json|html?|css|js)$/i.test(f.name), - })); - renderFileGroups(fileList); + showToast(`Relaying ${files.length} files from device memory`, 'info'); connectSSE(currentId); - - // Reset input + await refreshSessionsList(); + loadSessionDetails(currentId); evt.target.value = ''; - toast(`${files.length} file(s) queued for hosting`); } -async function setFolderPath() { - const path = document.getElementById('pathInput').value.trim(); - if (!path) return toast('Enter a path first', true); - - const res = await fetch('/set_session_path', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ session_id: currentId, path }) - }).catch(() => null); - - if (!res || !res.ok) return toast('Server error', true); - const data = await res.json(); - - if (data.success) { - toast('Path mapped successfully'); - delete relayFiles[currentId]; - setStatus(`📂 ${path}`, true); - // reload files - const r2 = await fetch(`/get_session_files/${currentId}`).catch(() => null); - if (r2) { - const d2 = await r2.json(); - if (d2.files && d2.files.length) renderFileGroups(d2.files); - } - } else { - toast(data.error || 'Failed to set path', true); - } -} - -// ───────────────────────────────────────────── -// Server-Sent Events (Relay mode) -// ───────────────────────────────────────────── function connectSSE(sid) { if (evtSources[sid]) return; - // Use TOOL_BASE so the SSE URL goes through the gateway proxy correctly. - // The gateway shim also patches EventSource, but this is a direct safety net. - const es = new EventSource(`${TOOL_BASE}/stream_events/${sid}`); + 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(err) {} + if (msg.type === 'request_file') { + await fulfillRelay(sid, msg.req_id, msg.filename); + } + } catch (_) {} }; evtSources[sid] = es; } @@ -244,266 +550,694 @@ async function fulfillRelay(sid, reqId, filename) { const fd = new FormData(); fd.append('req_id', reqId); if (file) fd.append('file', file); - await fetch('/fulfill_request', { method: 'POST', body: fd }).catch(() => {}); + await fetch(getApiUrl('/fulfill_request'), { method: 'POST', body: fd }).catch(() => {}); } // ───────────────────────────────────────────── -// Tunnel / Live Link +// 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.'}

+
+ `; + return; + } + + // Group files by folder + const groups = {}; + filtered.forEach(f => { + const folder = f.folder || '(Root)'; + if (!groups[folder]) groups[folder] = []; + groups[folder].push(f); + }); + + const isLive = currentSession && currentSession.tunnel_active; + const tunnelBase = currentSession ? currentSession.tunnel_url : ''; + + Object.keys(groups).sort().forEach(groupName => { + const groupFiles = groups[groupName]; + const block = document.createElement('div'); + block.className = 'folder-group-block'; + + let html = ` +
+
+ + ${groupName} +
+ ${groupFiles.length} file${groupFiles.length !== 1 ? 's' : ''} +
+
+ `; + + groupFiles.forEach(f => { + const sizeStr = f.size ? formatBytes(f.size) : '--'; + const directUrl = `${window.location.origin}${f.url}`; + const publicUrl = isLive ? `${tunnelBase}/${f.path || f.name}` : directUrl; + + const iconClass = f.is_image ? 'fa-image' : + f.is_code ? 'fa-file-code' : + f.name.endsWith('.zip') ? 'fa-file-zipper' : + 'fa-file'; + + html += ` +
+
+ ${f.is_image ? ` + + + ` : ` +
+ `} +
+
+ ${f.name} +
+ ${sizeStr} + ${(f.path || '').split('.').pop().toUpperCase()} +
+
+
+ + + + + + + +
+
+ `; + }); + + html += `
`; + block.innerHTML = html; + container.appendChild(block); + }); +} + +function formatBytes(bytes) { + if (!bytes || bytes === 0) return '0 B'; + const k = 1024; + const sizes = ['B', 'KB', 'MB', 'GB']; + const i = Math.floor(Math.log(bytes) / Math.log(k)); + return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]; +} + +// ───────────────────────────────────────────── +// Public Tunnel / Live Link HUD // ───────────────────────────────────────────── async function startTunnel() { - const sid = currentId; - document.getElementById('btnGoLive').classList.add('hidden'); - document.getElementById('liveSpinner').classList.remove('hidden'); + if (!currentId) return; + + const btnGoLive = document.getElementById('btnGoLive'); + const spinner = document.getElementById('liveSpinner'); + if (btnGoLive) btnGoLive.classList.add('hidden'); + if (spinner) spinner.classList.remove('hidden'); try { - const res = await fetch('/get_tunnel', { + const res = await fetch(getApiUrl('/get_tunnel'), { method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ session_id: sid }) + body: JSON.stringify({ session_id: currentId }) }); const data = await res.json(); - if (data.success) { - tunnelInfo[sid] = { url: data.url, active: true }; - if (currentId === sid) setTunnelUI(true, data.url); - toast('Live! Link is ready.'); + if (data.success && data.url) { + setTunnelUI(true, data.url); + showToast('Public live link is active!', 'success'); + await refreshSessionsList(); + renderFilesExplorer(); } else { - toast(data.error || 'Failed to go live', true); - if (currentId === sid) setTunnelUI(false); + showToast('Failed to start tunnel: ' + (data.error || 'server error'), 'error'); + setTunnelUI(false); } - } catch(e) { - toast('Error: ' + e.message, true); - if (currentId === sid) setTunnelUI(false); + } catch (e) { + showToast('Error starting tunnel: ' + e.message, 'error'); + setTunnelUI(false); } finally { - document.getElementById('liveSpinner').classList.add('hidden'); + if (spinner) spinner.classList.add('hidden'); } } async function stopTunnel() { - const sid = currentId; - await fetch('/stop_tunnel', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ session_id: sid }) - }).catch(() => {}); - if (tunnelInfo[sid]) tunnelInfo[sid].active = false; - if (currentId === sid) setTunnelUI(false); - toast('Tunnel stopped'); + if (!currentId) return; + + try { + await fetch(getApiUrl('/stop_tunnel'), { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ session_id: currentId }) + }); + setTunnelUI(false); + showToast('Public tunnel stopped', 'info'); + await refreshSessionsList(); + renderFilesExplorer(); + } catch (e) { + showToast('Error stopping tunnel: ' + e.message, 'error'); + } } async function regenerateTunnel() { - const sid = currentId; - await fetch('/regenerate_tunnel', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ session_id: sid }) - }).catch(() => {}); - if (tunnelInfo[sid]) tunnelInfo[sid].active = false; - setTunnelUI(false); + await stopTunnel(); setTimeout(startTunnel, 500); } async function checkTunnel(sid) { try { - const res = await fetch('/get_tunnel_status', { + const res = await fetch(getApiUrl('/get_tunnel_status'), { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ session_id: sid }) }); const data = await res.json(); - if (data.active && currentId === sid) { - tunnelInfo[sid] = { url: data.url, active: true }; + if (data.active && data.url && currentId === sid) { setTunnelUI(true, data.url); + } else if (currentId === sid) { + setTunnelUI(false); } - } catch(e) {} + } catch (_) {} } -function setTunnelUI(active, url) { +function setTunnelUI(active, url = '') { const panel = document.getElementById('livePanel'); const badge = document.getElementById('liveBadge'); - const goLive = document.getElementById('btnGoLive'); - const stop = document.getElementById('btnStopLive'); + const statusText = document.getElementById('liveStatusText'); + const btnGoLive = document.getElementById('btnGoLive'); + const btnStopLive = document.getElementById('btnStopLive'); const urlRow = document.getElementById('liveUrlRow'); const urlText = document.getElementById('liveUrlText'); const openBtn = document.getElementById('liveOpenBtn'); if (active) { - panel.classList.add('is-live'); - badge.className = 'badge badge-live'; - badge.innerHTML = ' Live'; - goLive.classList.add('hidden'); - stop.classList.remove('hidden'); - urlRow.classList.remove('hidden'); - urlText.textContent = url; - openBtn.href = url; + if (panel) panel.classList.add('is-live'); + if (badge) { + badge.className = 'tunnel-status-badge badge-live'; + if (statusText) statusText.textContent = 'Live Public Tunnel'; + } + if (btnGoLive) btnGoLive.classList.add('hidden'); + if (btnStopLive) btnStopLive.classList.remove('hidden'); + if (urlRow) urlRow.classList.remove('hidden'); + if (urlText) urlText.textContent = url; + if (openBtn) openBtn.href = url; } else { - panel.classList.remove('is-live'); - badge.className = 'badge badge-offline'; - badge.innerHTML = ' Offline'; - goLive.classList.remove('hidden'); - stop.classList.add('hidden'); - urlRow.classList.add('hidden'); - document.getElementById('liveSpinner').classList.add('hidden'); + if (panel) panel.classList.remove('is-live'); + if (badge) { + badge.className = 'tunnel-status-badge badge-offline'; + if (statusText) statusText.textContent = 'Offline (Internal Only)'; + } + if (btnGoLive) btnGoLive.classList.remove('hidden'); + if (btnStopLive) btnStopLive.classList.add('hidden'); + if (urlRow) urlRow.classList.add('hidden'); } } function copyLiveUrl() { - const url = document.getElementById('liveUrlText').textContent; - navigator.clipboard.writeText(url).then(() => toast('Copied!')).catch(() => { - const t = document.createElement('textarea'); - t.value = url; - document.body.appendChild(t); - t.select(); - document.execCommand('copy'); - document.body.removeChild(t); - toast('Copied!'); - }); + const urlText = document.getElementById('liveUrlText'); + if (urlText && urlText.textContent) { + copyText(urlText.textContent); + } } // ───────────────────────────────────────────── -// Render Files +// Modals & Preview Handlers // ───────────────────────────────────────────── -function renderFileGroups(files) { - const container = document.getElementById('filesSection'); - container.innerHTML = ''; +function openNewSessionModal() { + const nameInput = document.getElementById('govSessionName'); + if (nameInput) nameInput.value = 'Vault ' + (sessions.length + 1); + openGovernanceModal(); +} - if (!files || !files.length) { - container.innerHTML = `
- -

No files in this session yet.

-
`; - return; +function openGovernanceModal() { + const modal = document.getElementById('sessionGovModal'); + if (!modal) return; + + if (currentSession) { + const nameInput = document.getElementById('govSessionName'); + const modeSel = document.getElementById('govSessionMode'); + const limitSel = document.getElementById('govTimeLimitSel'); + + if (nameInput) nameInput.value = currentSession.name || ''; + if (modeSel) modeSel.value = currentSession.mode || 'server_background'; + if (limitSel) limitSel.value = (currentSession.time_limit_sec || 0).toString(); } - const groups = {}; - files.forEach(f => { - const key = f.folder || '(Root)'; - if (!groups[key]) groups[key] = []; - groups[key].push(f); - }); + modal.style.display = 'flex'; +} - const tInfo = tunnelInfo[currentId]; - const isLiveTunnel = tInfo && tInfo.active; +function closeGovernanceModal() { + const modal = document.getElementById('sessionGovModal'); + if (modal) modal.style.display = 'none'; +} - // Local base — use TOOL_BASE so gateway proxy routes correctly - // e.g. /tool/image-hoster/files//file.jpg - const localFileBase = `${TOOL_BASE}/files/${currentId}`; +async function saveSessionGovernance() { + const nameInput = document.getElementById('govSessionName'); + const limitSel = document.getElementById('govTimeLimitSel'); + const name = nameInput ? nameInput.value.trim() : ''; + const limitSec = parseInt(limitSel ? limitSel.value : '0', 10); - Object.keys(groups).sort().forEach(groupName => { - const groupFiles = groups[groupName]; - const relDir = groupName === '(Root)' ? '' : groupName; - - // ── Endpoint URL for the folder ── - let endpointUrl; - if (isLiveTunnel && tInfo.url.includes('/hoster/')) { - // Custom nexus domain already embeds session ID - endpointUrl = relDir ? `${tInfo.url}/${relDir}/` : `${tInfo.url}/`; - } else if (isLiveTunnel) { - endpointUrl = relDir - ? `${tInfo.url}/files/${currentId}/${relDir}/` - : `${tInfo.url}/files/${currentId}/`; + try { + const res = await fetch(getApiUrl('/update_session_governance'), { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + session_id: currentId, + name: name, + time_limit_sec: limitSec + }) + }); + const data = await res.json(); + if (data.success) { + showToast('Session governance updated successfully', 'success'); + closeGovernanceModal(); + await refreshSessionsList(); + loadSessionDetails(currentId); } else { - endpointUrl = relDir - ? `${window.location.origin}${localFileBase}/${relDir}/` - : `${window.location.origin}${localFileBase}/`; + showToast('Failed to update governance', 'error'); } - endpointUrl = endpointUrl.replace(/([^:])\/\/+/g, '$1/'); + } catch (e) { + showToast('Error: ' + e.message, 'error'); + } +} - const card = document.createElement('div'); - card.className = 'card folder-group'; +// QR Code Modal +function openQrModal(title, url) { + const modal = document.getElementById('qrModal'); + const titleEl = document.getElementById('qrModalTitle'); + const textEl = document.getElementById('qrUrlText'); + const container = document.getElementById('qrCodeContainer'); + if (!modal || !container) return; - let html = ` -
-
- - ${groupName} -
- ${groupFiles.length} file${groupFiles.length !== 1 ? 's' : ''} -
-
- - ${endpointUrl} - -
`; + if (titleEl) titleEl.innerHTML = ` ${title}`; + if (textEl) textEl.textContent = url; + container.innerHTML = ''; - const shown = groupFiles.slice(0, 8); - shown.forEach(f => { - // ── Per-file URL ── - let fileUrl; - if (isLiveTunnel && tInfo.url.includes('/hoster/')) { - fileUrl = `${tInfo.url}/${f.path || f.name}`.replace(/([^:])\/\/+/g, '$1/'); - } else if (isLiveTunnel) { - fileUrl = `${tInfo.url}/files/${currentId}/${f.path || f.name}`; - } else { - // Use TOOL_BASE so the link is e.g. /tool/image-hoster/files//img.jpg - fileUrl = `${localFileBase}/${f.path || f.name}`.replace(/([^:])\/\/+/g, '$1/'); + if (typeof QRCode !== 'undefined') { + new QRCode(container, { + text: url, + width: 200, + height: 200, + colorDark: '#030305', + colorLight: '#ffffff', + correctLevel: QRCode.CorrectLevel.H + }); + } else { + container.innerHTML = `

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 = `
Reading directories...
`; + + try { + const res = await fetch(getApiUrl('/api/list_server_directories'), { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ path }) + }); + const data = await res.json(); + if (data.success) { + serverExplorerCurrentPath = data.current_path; + if (curEl) curEl.textContent = data.current_path; + + let html = ''; + if (data.parent_path && data.parent_path !== data.current_path) { + html += ` +
+ + .. (Parent Directory) +
+ `; } - const isImg = /\.(jpe?g|png|gif|webp|svg|bmp|ico)$/i.test(f.name); + if (data.directories && data.directories.length) { + data.directories.forEach(d => { + const fullP = data.current_path.replace(/\/+$/, '') + '/' + d; + html += ` +
+ + ${d} +
+ `; + }); + } else { + html += `
No subdirectories found.
`; + } - html += ` -
- ${isImg - ? `` - : '' - } -
- -
- ${f.name} - - - - -
`; - }); - - if (groupFiles.length > 8) { - html += `
- + ${groupFiles.length - 8} more files -
`; + listEl.innerHTML = html; + } else { + listEl.innerHTML = `
${data.error || 'Access denied'}
`; } + } catch (e) { + listEl.innerHTML = `
${e.message}
`; + } +} - card.innerHTML = html; - container.appendChild(card); +function selectCurrentServerDir() { + if (serverExplorerCurrentPath) { + const input = document.getElementById('pathInput'); + if (input) input.value = serverExplorerCurrentPath; + setFolderPath(serverExplorerCurrentPath); + closeServerDirModal(); + } +} + +// Telemetry & Access Traffic Modal +async function openTelemetryModal() { + const modal = document.getElementById('telemetryModal'); + if (!modal) return; + modal.style.display = 'flex'; + await refreshTelemetry(); +} + +function closeTelemetryModal() { + const modal = document.getElementById('telemetryModal'); + if (modal) modal.style.display = 'none'; +} + +async function refreshTelemetry() { + if (!currentId) return; + + try { + const res = await fetch(getApiUrl(`/api/session_telemetry/${currentId}`)); + const data = await res.json(); + if (data.success) { + const reqsEl = document.getElementById('t-reqs'); + const bytesEl = document.getElementById('t-bytes'); + const timeEl = document.getElementById('t-active-time'); + const bodyEl = document.getElementById('telemetryLogsBody'); + + if (reqsEl) reqsEl.textContent = data.requests; + if (bytesEl) bytesEl.textContent = (data.bytes_served / (1024 * 1024)).toFixed(2) + ' MB'; + if (timeEl && data.last_active) { + timeEl.textContent = new Date(data.last_active).toLocaleTimeString(); + } + + if (bodyEl) { + if (data.logs && data.logs.length) { + let html = ''; + data.logs.slice().reverse().forEach(log => { + const statusColor = log.status === 200 ? 'text-green' : 'text-amber'; + html += ` + + ${new Date(log.timestamp).toLocaleTimeString()} + ${log.method} + ${log.path} + ${log.status} + ${formatBytes(log.bytes)} + ${(log.ip || '').replace('::1', '127.0.0.1')} + + `; + }); + bodyEl.innerHTML = html; + } else { + bodyEl.innerHTML = `No access events recorded yet.`; + } + } + } + } catch (e) { + console.error('Failed to fetch telemetry:', e); + } +} + +// Batch URLs Export Modal +let currentExportFormat = 'raw'; +function openBatchExportModal() { + const modal = document.getElementById('batchExportModal'); + if (!modal) return; + renderBatchExportContent(); + modal.style.display = 'flex'; +} + +function closeBatchExportModal() { + const modal = document.getElementById('batchExportModal'); + if (modal) modal.style.display = 'none'; +} + +function switchExportFormat(fmt) { + currentExportFormat = fmt; + document.querySelectorAll('.batch-export-formats .seg-pill').forEach(p => { + p.classList.toggle('active', p.textContent.toLowerCase().includes(fmt)); }); + renderBatchExportContent(); +} + +function renderBatchExportContent() { + const textarea = document.getElementById('batchExportTextarea'); + if (!textarea) return; + + const isLive = currentSession && currentSession.tunnel_active; + const tunnelBase = currentSession ? currentSession.tunnel_url : ''; + + const urls = currentFiles.map(f => { + const directUrl = `${window.location.origin}${f.url}`; + return isLive ? `${tunnelBase}/${f.path || f.name}` : directUrl; + }); + + if (currentExportFormat === 'json') { + textarea.value = JSON.stringify(urls, null, 2); + } else if (currentExportFormat === 'markdown') { + textarea.value = currentFiles.map((f, i) => `![${f.name}](${urls[i]})`).join('\n'); + } else if (currentExportFormat === 'html') { + textarea.value = currentFiles.map((f, i) => `${f.name}`).join('\n'); + } else if (currentExportFormat === 'curl') { + textarea.value = urls.map((u, i) => `curl -o "${currentFiles[i].name}" "${u}"`).join('\n'); + } else { + textarea.value = urls.join('\n'); + } +} + +function copyBatchExportContent() { + const textarea = document.getElementById('batchExportTextarea'); + if (textarea && textarea.value) { + copyText(textarea.value); + } +} + +function downloadSessionZip() { + if (!currentId) return; + const zipUrl = getApiUrl(`/download_session_zip/${currentId}`); + window.location.href = zipUrl; + showToast('Preparing ZIP download...', 'info'); } // ───────────────────────────────────────────── -// Helpers +// Copy & Toast Helpers // ───────────────────────────────────────────── -function setStatus(msg, active) { - const bar = document.getElementById('statusBar'); - const txt = document.getElementById('statusText'); - txt.textContent = msg; - bar.className = 'status-bar' + (active ? ' has-source' : ''); -} - function copyText(text) { - navigator.clipboard.writeText(text).then(() => toast('Copied!')).catch(() => { - const t = document.createElement('textarea'); - t.value = text; - document.body.appendChild(t); - t.select(); - document.execCommand('copy'); - document.body.removeChild(t); - toast('Copied!'); - }); + if (!text) return; + if (navigator.clipboard && navigator.clipboard.writeText) { + navigator.clipboard.writeText(text).then(() => showToast('Copied to clipboard!', 'success')).catch(() => fallbackCopy(text)); + } else { + fallbackCopy(text); + } } -let toastTimer; -function toast(msg, isErr = false) { - const el = document.getElementById('toast'); - el.textContent = msg; - el.className = 'show ' + (isErr ? 'error' : 'success'); - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { el.className = ''; }, 2500); +function fallbackCopy(text) { + const t = document.createElement('textarea'); + t.value = text; + document.body.appendChild(t); + t.select(); + document.execCommand('copy'); + document.body.removeChild(t); + showToast('Copied to clipboard!', 'success'); } -// ───────────────────────────────────────────── -// Boot -// ───────────────────────────────────────────── -init(); +function copyMarkdownLink(name, url) { + copyText(`![${name}](${url})`); +} + +function copyHtmlImg(name, url) { + copyText(`${name}`); +} + +function setStatus(msg, active) { + const txt = document.getElementById('statusText'); + const icon = document.getElementById('statusIcon'); + if (txt) txt.textContent = msg; + if (icon) { + icon.className = active ? 'fa-solid fa-circle-check text-green' : 'fa-solid fa-circle-info text-amber'; + } +} + +function showToast(msg, type = 'info') { + const container = document.getElementById('toast-container'); + if (!container) return; + const toast = document.createElement('div'); + toast.className = `toast ${type}`; + const icon = type === 'success' ? 'fa-circle-check' : + type === 'error' ? 'fa-circle-exclamation' : + 'fa-circle-info'; + toast.innerHTML = ` ${msg}`; + container.appendChild(toast); + setTimeout(() => toast.remove(), 4000); +} + +window.showToast = showToast; diff --git a/web/image-hoster/index.html b/web/image-hoster/index.html index ce52672..4e47391 100644 --- a/web/image-hoster/index.html +++ b/web/image-hoster/index.html @@ -2,127 +2,519 @@ - - Host It Now - - + + + + Host It Now · Enterprise Cloud Vault & Edge Relay + + + + + + + + + + + + + + + +
-
- -
- - -
-
- - Host It Now -
- -
- - -
- Sessions -
- - -
- - -
-
-
- - Live Public Link - - Offline - -
-
-