Files

1128 lines
38 KiB
HTML
Raw Permalink Normal View History

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Host It Now</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<style>
:root {
--bg: #0b0b10;
--surface: #13131a;
--surface2: #1c1c28;
--border: rgba(255,255,255,0.07);
--primary: #7c3aed;
--primary-dim: rgba(124,58,237,0.15);
--cyan: #22d3ee;
--cyan-dim: rgba(34,211,238,0.12);
--green: #10b981;
--green-dim: rgba(16,185,129,0.15);
--pink: #f43f5e;
--pink-dim: rgba(244,63,94,0.15);
--text: #f1f5f9;
--muted: #64748b;
--radius: 12px;
--transition: 0.2s ease;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
background: var(--bg);
color: var(--text);
font-family: 'Segoe UI', system-ui, sans-serif;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
padding: 24px 16px 60px;
}
.app {
width: 100%;
max-width: 860px;
display: flex;
flex-direction: column;
gap: 16px;
}
/* ─── Topbar ─── */
.topbar {
display: flex;
align-items: center;
justify-content: space-between;
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 14px 20px;
}
.topbar-brand {
display: flex;
align-items: center;
gap: 10px;
font-size: 1.25rem;
font-weight: 700;
color: var(--cyan);
}
.topbar-brand i { font-size: 1.1rem; }
.topbar-right {
display: flex;
align-items: center;
gap: 8px;
}
/* ─── Buttons ─── */
.btn {
display: inline-flex;
align-items: center;
gap: 7px;
padding: 9px 16px;
border-radius: 8px;
border: 1px solid var(--border);
background: var(--surface2);
color: var(--text);
font-size: 0.875rem;
font-weight: 600;
cursor: pointer;
transition: var(--transition);
text-decoration: none;
white-space: nowrap;
}
.btn:hover { background: rgba(255,255,255,0.08); border-color: rgba(255,255,255,0.15); }
.btn:active { transform: scale(0.97); }
.btn-primary {
background: var(--primary);
border-color: transparent;
box-shadow: 0 0 16px rgba(124,58,237,0.4);
}
.btn-primary:hover { background: #6d28d9; box-shadow: 0 0 22px rgba(124,58,237,0.55); }
.btn-cyan {
background: var(--cyan-dim);
border-color: rgba(34,211,238,0.25);
color: var(--cyan);
}
.btn-cyan:hover { background: rgba(34,211,238,0.2); }
.btn-green {
background: var(--green-dim);
border-color: rgba(16,185,129,0.3);
color: var(--green);
}
.btn-green:hover { background: rgba(16,185,129,0.25); }
.btn-danger {
background: var(--pink-dim);
border-color: rgba(244,63,94,0.3);
color: var(--pink);
}
.btn-danger:hover { background: rgba(244,63,94,0.25); }
.btn-icon { padding: 9px 11px; }
.btn-sm { padding: 6px 12px; font-size: 0.8rem; }
/* ─── Session Bar ─── */
.session-bar {
display: flex;
align-items: center;
gap: 8px;
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 12px 16px;
}
.session-label {
font-size: 0.75rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--muted);
flex-shrink: 0;
}
.session-tabs {
display: flex;
gap: 6px;
flex-wrap: wrap;
flex: 1;
}
.session-tab {
padding: 5px 12px;
border-radius: 20px;
border: 1px solid var(--border);
background: var(--surface2);
color: var(--muted);
font-size: 0.8rem;
font-weight: 600;
cursor: pointer;
transition: var(--transition);
}
.session-tab:hover { border-color: rgba(255,255,255,0.2); color: var(--text); }
.session-tab.active {
background: var(--primary-dim);
border-color: rgba(124,58,237,0.5);
color: #c4b5fd;
}
/* ─── Card ─── */
.card {
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
overflow: hidden;
}
.card-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 16px 20px;
border-bottom: 1px solid var(--border);
}
.card-title {
display: flex;
align-items: center;
gap: 10px;
font-size: 0.95rem;
font-weight: 700;
}
.card-body { padding: 20px; }
/* ─── Live Link Panel ─── */
.live-panel {
border-color: var(--border);
}
.live-panel.is-live {
border-color: rgba(16,185,129,0.4);
background: linear-gradient(135deg, var(--surface), rgba(16,185,129,0.04));
}
.badge {
display: inline-flex;
align-items: center;
gap: 5px;
padding: 3px 10px;
border-radius: 20px;
font-size: 0.7rem;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.badge-offline {
background: rgba(255,255,255,0.06);
color: var(--muted);
}
.badge-live {
background: var(--green-dim);
color: var(--green);
border: 1px solid rgba(16,185,129,0.3);
animation: pulse-badge 2s infinite;
}
@keyframes pulse-badge {
0%, 100% { box-shadow: 0 0 0 0 rgba(16,185,129,0.4); }
50% { box-shadow: 0 0 0 5px rgba(16,185,129,0); }
}
.live-url-box {
display: flex;
align-items: center;
gap: 8px;
padding: 10px 14px;
background: var(--surface2);
border: 1px solid rgba(34,211,238,0.2);
border-radius: 8px;
flex: 1;
}
.live-url-text {
font-family: 'Consolas', 'Fira Code', monospace;
font-size: 0.9rem;
color: var(--cyan);
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.live-actions {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
/* ─── Host Panel ─── */
.host-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
}
.host-btn {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 10px;
padding: 24px;
border-radius: 10px;
border: 2px dashed rgba(255,255,255,0.1);
background: transparent;
color: var(--muted);
cursor: pointer;
transition: var(--transition);
font-size: 0.9rem;
font-weight: 600;
}
.host-btn i { font-size: 1.8rem; }
.host-btn:hover { border-color: var(--cyan); color: var(--cyan); background: var(--cyan-dim); }
.host-btn.pink:hover { border-color: var(--pink); color: var(--pink); background: var(--pink-dim); }
/* ─── Path Input ─── */
.path-row {
display: flex;
gap: 8px;
margin-top: 12px;
}
.input-field {
flex: 1;
background: var(--surface2);
border: 1px solid var(--border);
color: var(--text);
padding: 10px 14px;
border-radius: 8px;
font-size: 0.9rem;
transition: var(--transition);
}
.input-field:focus {
outline: none;
border-color: rgba(34,211,238,0.4);
box-shadow: 0 0 0 3px rgba(34,211,238,0.08);
}
.input-field::placeholder { color: var(--muted); }
/* ─── Status Bar ─── */
.status-bar {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 14px;
border-radius: 8px;
background: var(--surface2);
font-size: 0.875rem;
color: var(--muted);
margin-top: 12px;
min-height: 42px;
}
.status-bar.has-source { color: var(--cyan); background: var(--cyan-dim); border: 1px solid rgba(34,211,238,0.2); }
/* ─── Files Section ─── */
.files-section { margin-top: 4px; }
.folder-group {
border: 1px solid var(--border);
border-radius: var(--radius);
overflow: hidden;
margin-bottom: 12px;
}
.folder-group-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 16px;
background: var(--surface2);
border-bottom: 1px solid var(--border);
}
.folder-name {
display: flex;
align-items: center;
gap: 8px;
font-weight: 700;
font-size: 0.9rem;
}
.count-badge {
padding: 2px 8px;
border-radius: 12px;
background: rgba(255,255,255,0.06);
color: var(--muted);
font-size: 0.75rem;
font-weight: 700;
}
.endpoint-strip {
display: flex;
align-items: center;
gap: 8px;
padding: 10px 16px;
background: rgba(0,0,0,0.25);
border-bottom: 1px solid var(--border);
}
.endpoint-url {
font-family: monospace;
font-size: 0.82rem;
color: var(--cyan);
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.file-row {
display: flex;
align-items: center;
gap: 12px;
padding: 10px 16px;
border-bottom: 1px solid var(--border);
transition: background var(--transition);
}
.file-row:last-child { border-bottom: none; }
.file-row:hover { background: rgba(255,255,255,0.03); }
.file-thumb {
width: 36px;
height: 36px;
border-radius: 6px;
object-fit: cover;
flex-shrink: 0;
background: var(--surface2);
}
.file-icon-placeholder {
width: 36px;
height: 36px;
border-radius: 6px;
background: var(--primary-dim);
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.file-icon-placeholder i { color: #c4b5fd; font-size: 0.9rem; }
.file-name {
flex: 1;
font-size: 0.875rem;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.empty-state {
padding: 50px 20px;
text-align: center;
color: var(--muted);
}
.empty-state i { font-size: 2.5rem; margin-bottom: 12px; opacity: 0.4; display: block; }
.empty-state p { font-size: 0.9rem; }
/* ─── Spinner ─── */
.spinner {
display: inline-block;
width: 16px;
height: 16px;
border: 2px solid rgba(255,255,255,0.2);
border-top-color: var(--cyan);
border-radius: 50%;
animation: spin 0.7s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
/* ─── Toast ─── */
#toast {
position: fixed;
bottom: 28px;
left: 50%;
transform: translateX(-50%) translateY(10px);
padding: 10px 24px;
border-radius: 30px;
font-size: 0.875rem;
font-weight: 600;
pointer-events: none;
opacity: 0;
transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
z-index: 9999;
white-space: nowrap;
}
#toast.show {
opacity: 1;
transform: translateX(-50%) translateY(0);
}
#toast.success { background: var(--green); color: #fff; }
#toast.error { background: var(--pink); color: #fff; }
/* ─── Divider ─── */
.divider {
width: 1px;
height: 20px;
background: var(--border);
flex-shrink: 0;
}
/* hidden util */
.hidden { display: none !important; }
@media (max-width: 580px) {
.host-grid { grid-template-columns: 1fr; }
.live-actions { flex-direction: column; align-items: stretch; }
.topbar { flex-direction: column; gap: 12px; align-items: flex-start; }
}
</style>
</head>
<body>
<div id="toast"></div>
<div class="app">
<!-- Topbar -->
<div class="topbar">
<div class="topbar-brand">
<i class="fas fa-broadcast-tower"></i>
Host It Now
</div>
<div class="topbar-right">
<a href="/radheradhe/" target="_blank" class="btn btn-sm">
<i class="fas fa-user-shield"></i> Admin
</a>
</div>
</div>
<!-- Session Bar -->
<div class="session-bar">
<span class="session-label"><i class="fas fa-layer-group"></i> Sessions</span>
<div class="session-tabs" id="sessionTabs"></div>
<button class="btn btn-sm btn-cyan" onclick="createNewSession()" title="New Session">
<i class="fas fa-plus"></i> New
</button>
<button class="btn btn-sm btn-danger" onclick="deleteSession()" title="Delete Session">
<i class="fas fa-trash-alt"></i>
</button>
</div>
<!-- Live Link Panel -->
<div class="card live-panel" id="livePanel">
<div class="card-header">
<div class="card-title">
<i class="fas fa-globe" style="color: var(--green)"></i>
Live Public Link
<span id="liveBadge" class="badge badge-offline">
<i class="fas fa-circle" style="font-size:0.5rem"></i> Offline
</span>
</div>
<div style="display:flex; gap:8px; align-items:center;">
<div id="liveSpinner" class="hidden" style="display:flex; align-items:center; gap:8px; color:var(--muted); font-size:0.85rem;">
<div class="spinner"></div> Starting…
</div>
<button id="btnGoLive" class="btn btn-green" onclick="startTunnel()">
<i class="fas fa-satellite-dish"></i> Go Live
</button>
<button id="btnStopLive" class="btn btn-danger hidden" onclick="stopTunnel()">
<i class="fas fa-power-off"></i> Stop
</button>
</div>
</div>
<div id="liveUrlRow" class="card-body hidden" style="padding:16px 20px;">
<div class="live-actions">
<div class="live-url-box">
<i class="fas fa-link" style="color:var(--cyan); flex-shrink:0;"></i>
<span class="live-url-text" id="liveUrlText"></span>
</div>
<button class="btn btn-cyan btn-sm" onclick="copyLiveUrl()">
<i class="fas fa-copy"></i> Copy
</button>
<a id="liveOpenBtn" href="#" target="_blank" class="btn btn-sm">
<i class="fas fa-external-link-alt"></i> Open
</a>
<button class="btn btn-sm" onclick="regenerateTunnel()" title="Regenerate">
<i class="fas fa-sync-alt"></i>
</button>
</div>
</div>
</div>
<!-- Host Content Card -->
<div class="card">
<div class="card-header">
<div class="card-title">
<i class="fas fa-folder-open" style="color:var(--cyan)"></i>
Host Your Content
</div>
</div>
<div class="card-body">
<input type="file" id="folderInput" webkitdirectory directory multiple style="display:none" onchange="handleFileSelect(event,'folder')">
<input type="file" id="fileInput" multiple style="display:none" onchange="handleFileSelect(event,'file')">
<div class="host-grid">
<button class="host-btn" onclick="document.getElementById('folderInput').click()">
<i class="fas fa-folder-plus"></i>
Host a Folder
</button>
<button class="host-btn pink" onclick="document.getElementById('fileInput').click()">
<i class="fas fa-file-upload"></i>
Host Files
</button>
</div>
<div class="path-row">
<input type="text" class="input-field" id="pathInput" placeholder="Or enter absolute server path — e.g. /home/user/images">
<button class="btn" onclick="setFolderPath()">
<i class="fas fa-map-pin"></i> Map
</button>
</div>
<div class="status-bar" id="statusBar">
<i class="fas fa-info-circle"></i>
<span id="statusText">No active source — pick a folder or enter a server path.</span>
</div>
</div>
</div>
<!-- Files List -->
<div id="filesSection" class="files-section"></div>
</div>
<script>
// ─────────────────────────────────────────────
// 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 = ""
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;
})();
// ─────────────────────────────────────────────
// 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 = localStorage.getItem('hin_current');
if (currentId === 'undefined' || currentId === 'null') currentId = null;
if (currentId && !sessions.find(s => s.id === currentId)) currentId = null;
const relayFiles = {}; // sessionId -> { path: File }
const evtSources = {}; // sessionId -> EventSource
const tunnelInfo = {}; // sessionId -> { url, active }
// ─────────────────────────────────────────────
// Boot
// ─────────────────────────────────────────────
async function init() {
save();
if (!sessions.length) {
await createNewSession();
} 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);
} else {
toast('Failed to create session', true);
}
} 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);
}
function save() {
localStorage.setItem('hin_sessions', JSON.stringify(sessions));
if (currentId) localStorage.setItem('hin_current', currentId);
}
function renderSessionTabs() {
const container = document.getElementById('sessionTabs');
container.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;
tab.onclick = () => switchSession(s.id);
container.appendChild(tab);
});
}
// ─────────────────────────────────────────────
// Load a session
// ─────────────────────────────────────────────
async function loadSession(sid) {
connectSSE(sid);
checkTunnel(sid);
// Load files from server
try {
const res = await fetch(`/get_session_files/${sid}`);
const data = await res.json();
if (sid !== currentId) return;
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/<id>/...,
// we need TOOL_BASE + /files/<id>/... so the gateway proxies correctly
const normalised = data.files.map(f => ({
...f,
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);
} else {
resetUI();
}
} catch(e) { /* ignore */ }
}
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);
}
// ─────────────────────────────────────────────
// File Hosting
// ─────────────────────────────────────────────
async function handleFileSelect(evt, type) {
const files = evt.target.files;
if (!files.length) 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;
}
// Tell server we're in relay mode
await fetch('/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);
connectSSE(currentId);
// Reset input
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}`);
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) {}
};
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('/fulfill_request', { method: 'POST', body: fd }).catch(() => {});
}
// ─────────────────────────────────────────────
// Tunnel / Live Link
// ─────────────────────────────────────────────
async function startTunnel() {
const sid = currentId;
document.getElementById('btnGoLive').classList.add('hidden');
document.getElementById('liveSpinner').classList.remove('hidden');
try {
const res = await fetch('/get_tunnel', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ session_id: sid })
});
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.');
} else {
toast(data.error || 'Failed to go live', true);
if (currentId === sid) setTunnelUI(false);
}
} catch(e) {
toast('Error: ' + e.message, true);
if (currentId === sid) setTunnelUI(false);
} finally {
document.getElementById('liveSpinner').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');
}
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);
setTimeout(startTunnel, 500);
}
async function checkTunnel(sid) {
try {
const res = await fetch('/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 };
setTunnelUI(true, data.url);
}
} catch(e) {}
}
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 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 = '<i class="fas fa-circle" style="font-size:0.5rem"></i> Live';
goLive.classList.add('hidden');
stop.classList.remove('hidden');
urlRow.classList.remove('hidden');
urlText.textContent = url;
openBtn.href = url;
} else {
panel.classList.remove('is-live');
badge.className = 'badge badge-offline';
badge.innerHTML = '<i class="fas fa-circle" style="font-size:0.5rem"></i> Offline';
goLive.classList.remove('hidden');
stop.classList.add('hidden');
urlRow.classList.add('hidden');
document.getElementById('liveSpinner').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!');
});
}
// ─────────────────────────────────────────────
// Render Files
// ─────────────────────────────────────────────
function renderFileGroups(files) {
const container = document.getElementById('filesSection');
container.innerHTML = '';
if (!files || !files.length) {
container.innerHTML = `<div class="card"><div class="empty-state">
<i class="fas fa-folder-open"></i>
<p>No files in this session yet.</p>
</div></div>`;
return;
}
const groups = {};
files.forEach(f => {
const key = f.folder || '(Root)';
if (!groups[key]) groups[key] = [];
groups[key].push(f);
});
const tInfo = tunnelInfo[currentId];
const isLiveTunnel = tInfo && tInfo.active;
// Local base — use TOOL_BASE so gateway proxy routes correctly
// e.g. /tool/image-hoster/files/<id>/file.jpg
const localFileBase = `${TOOL_BASE}/files/${currentId}`;
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}/`;
} else {
endpointUrl = relDir
? `${window.location.origin}${localFileBase}/${relDir}/`
: `${window.location.origin}${localFileBase}/`;
}
endpointUrl = endpointUrl.replace(/([^:])\/\/+/g, '$1/');
const card = document.createElement('div');
card.className = 'card folder-group';
let html = `
<div class="folder-group-header">
<div class="folder-name">
<i class="fas ${groupName === '(Root)' ? 'fa-home' : 'fa-folder'}" style="color:var(--cyan)"></i>
${groupName}
</div>
<span class="count-badge">${groupFiles.length} file${groupFiles.length !== 1 ? 's' : ''}</span>
</div>
<div class="endpoint-strip">
<i class="fas fa-link" style="color:var(--muted); font-size:0.8rem; flex-shrink:0;"></i>
<span class="endpoint-url" title="${endpointUrl}">${endpointUrl}</span>
<button class="btn btn-sm btn-cyan" onclick="copyText('${endpointUrl}')">
<i class="fas fa-copy"></i>
</button>
</div>`;
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/<id>/img.jpg
fileUrl = `${localFileBase}/${f.path || f.name}`.replace(/([^:])\/\/+/g, '$1/');
}
const isImg = /\.(jpe?g|png|gif|webp|svg|bmp|ico)$/i.test(f.name);
html += `
<div class="file-row">
${isImg
? `<img src="${fileUrl}" class="file-thumb" onerror="this.style.display='none';this.nextElementSibling.style.display='flex'">`
: ''
}
<div class="file-icon-placeholder" style="${isImg ? 'display:none' : ''}">
<i class="fas ${f.is_code ? 'fa-file-code' : 'fa-file'}"></i>
</div>
<span class="file-name" title="${f.name}">${f.name}</span>
<a href="${fileUrl}" target="_blank" class="btn btn-icon btn-sm" title="Open">
<i class="fas fa-external-link-alt"></i>
</a>
<button class="btn btn-icon btn-sm" onclick="copyText('${fileUrl}')" title="Copy URL">
<i class="fas fa-copy"></i>
</button>
</div>`;
});
if (groupFiles.length > 8) {
html += `<div style="padding:10px 16px; color:var(--muted); font-size:0.82rem; text-align:center;">
+ ${groupFiles.length - 8} more files
</div>`;
}
card.innerHTML = html;
container.appendChild(card);
});
}
// ─────────────────────────────────────────────
// 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!');
});
}
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);
}
// ─────────────────────────────────────────────
// Boot
// ─────────────────────────────────────────────
init();
</script>
</body>
</html>