Files
Unified_Dashboard_Suite_Go/cmd/image-hoster/app.js
T

1244 lines
46 KiB
JavaScript
Raw Normal View History

// ═══════════════════════════════════════════════════════════════════
// 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 = `
<i class="fa-solid ${modeIcon} tab-icon"></i>
<span style="font-weight:600;">${name}</span>
<span class="tab-ttl" id="ttl-pill-${s.id}">${remStr}</span>
`;
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 = `
<div class="empty-state">
<i class="fa-solid fa-folder-open"></i>
<p>${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.'}</p>
</div>
`;
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 = `
<div class="folder-group-header">
<div class="folder-group-title">
<i class="fa-solid ${groupName === '(Root)' ? 'fa-house' : 'fa-folder'}"></i>
<span>${groupName}</span>
</div>
<span class="folder-group-meta">${groupFiles.length} file${groupFiles.length !== 1 ? 's' : ''}</span>
</div>
<div class="files-grid">
`;
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 += `
<div class="file-card">
<div class="file-thumb-wrap" onclick="previewFile('${encodeURIComponent(JSON.stringify(f))}')">
${f.is_image ? `
<img src="${f.url}" class="file-thumb-img" loading="lazy" onerror="this.style.display='none';this.nextElementSibling.style.display='flex'">
<div class="file-icon-box" style="display:none;"><i class="fa-solid ${iconClass}"></i></div>
` : `
<div class="file-icon-box"><i class="fa-solid ${iconClass}"></i></div>
`}
</div>
<div class="file-card-details">
<span class="file-card-name" title="${f.name}">${f.name}</span>
<div class="file-card-meta">
<span>${sizeStr}</span>
<span>${(f.path || '').split('.').pop().toUpperCase()}</span>
</div>
</div>
<div class="file-card-actions">
<button class="action-icon-btn primary" onclick="copyText('${publicUrl}')" title="Copy raw URL">
<i class="fa-solid fa-copy"></i>
</button>
<button class="action-icon-btn" onclick="copyMarkdownLink('${f.name}', '${publicUrl}')" title="Copy Markdown ![img](url)">
<i class="fa-brands fa-markdown"></i>
</button>
<button class="action-icon-btn" onclick="copyHtmlImg('${f.name}', '${publicUrl}')" title="Copy HTML &lt;img&gt;">
<i class="fa-solid fa-code"></i>
</button>
<button class="action-icon-btn" onclick="openQrModal('${f.name}', '${publicUrl}')" title="Generate QR Code">
<i class="fa-solid fa-qrcode"></i>
</button>
<a href="${f.url}" target="_blank" class="action-icon-btn" title="Open in new tab">
<i class="fa-solid fa-arrow-up-right-from-square"></i>
</a>
</div>
</div>
`;
});
html += `</div>`;
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 = `<i class="fa-solid fa-qrcode text-cyan"></i> ${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 = `<p style="color:#000;font-size:12px;">QR Code library loading...</p>`;
}
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 = `<i class="fa-solid fa-code text-cyan"></i> ${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 = `<div style="text-align:center;padding:20px;color:var(--muted);"><i class="fa-solid fa-circle-notch fa-spin"></i> Reading directories...</div>`;
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 += `
<div class="server-dir-item" onclick="navigateServerDir('${encodeURIComponent(data.parent_path)}')">
<i class="fa-solid fa-arrow-turn-up"></i>
<span>.. (Parent Directory)</span>
</div>
`;
}
if (data.directories && data.directories.length) {
data.directories.forEach(d => {
const fullP = data.current_path.replace(/\/+$/, '') + '/' + d;
html += `
<div class="server-dir-item" onclick="navigateServerDir('${encodeURIComponent(fullP)}')">
<i class="fa-solid fa-folder"></i>
<span>${d}</span>
</div>
`;
});
} else {
html += `<div style="padding:14px;color:var(--muted);font-size:12px;">No subdirectories found.</div>`;
}
listEl.innerHTML = html;
} else {
listEl.innerHTML = `<div style="padding:14px;color:var(--accent-rose);">${data.error || 'Access denied'}</div>`;
}
} catch (e) {
listEl.innerHTML = `<div style="padding:14px;color:var(--accent-rose);">${e.message}</div>`;
}
}
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 += `
<tr>
<td>${new Date(log.timestamp).toLocaleTimeString()}</td>
<td><span style="font-weight:700;color:var(--accent-cyan);">${log.method}</span></td>
<td style="max-width:240px;overflow:hidden;text-overflow:ellipsis;" title="${log.path}">${log.path}</td>
<td><span class="${statusColor}">${log.status}</span></td>
<td>${formatBytes(log.bytes)}</td>
<td style="color:var(--muted);">${(log.ip || '').replace('::1', '127.0.0.1')}</td>
</tr>
`;
});
bodyEl.innerHTML = html;
} else {
bodyEl.innerHTML = `<tr><td colspan="6" style="text-align:center; color: var(--muted); padding: 18px;">No access events recorded yet.</td></tr>`;
}
}
}
} 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) => `<img src="${urls[i]}" alt="${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(`<img src="${url}" alt="${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 = `<i class="fa-solid ${icon}"></i> <span>${msg}</span>`;
container.appendChild(toast);
setTimeout(() => toast.remove(), 4000);
}
window.showToast = showToast;