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

510 lines
20 KiB
JavaScript
Raw Normal View History

// ─────────────────────────────────────────────
// 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();