// This is temporary to prepare the new script
const formatBytes = (bytes, decimals = 2) => {
if (bytes === 0) return '0 B';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
};
const formatRate = (bytesPerSec) => {
return formatBytes(bytesPerSec) + '/s';
};
const createInterfaceCard = (interfaceData, index) => {
const interfaceId = interfaceData.id.replace(/[^a-z0-9]/gi, '-');
const isMultiple = networkData.interfaces.length > 1;
return `
No network data available
`;
return;
}
const gridClass = networkData.interfaces.length > 1 ? 'grid grid-cols-1 md:grid-cols-2 gap-6' : 'grid grid-cols-1 gap-6';
container.className = gridClass;
container.innerHTML = networkData.interfaces
.map((iface, index) => createInterfaceCard(iface, index))
.join('');
// Set up chart toggles
document.querySelectorAll('.chart-toggle').forEach(button => {
button.addEventListener('click', (e) => {
const interfaceId = e.currentTarget.dataset.interface;
const container = document.querySelector(`[data-chart-container="${interfaceId}"]`);
if (container) {
container.classList.toggle('open');
// Create chart on first open
if (container.classList.contains('open') && !charts[interfaceId]) {
const interfaceData = networkData.interfaces.find(i =>
i.id.replace(/[^a-z0-9]/gi, '-') === interfaceId
);
if (interfaceData) {
setTimeout(() => createChart(interfaceId, interfaceData), 100);
}
}
}
});
});
};
const poll = async () => {
if (pollInFlight || !pollingEndpoint) return;
pollInFlight = true;
try {
const csrfElement = document.querySelector('meta[name="csrf-token"]');
const csrfToken = csrfElement ? csrfElement.content : '';
const response = await fetch(pollingEndpoint, {
method: 'GET',
headers: {
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-TOKEN': csrfToken,
},
credentials: 'same-origin',
});
if (response.ok) {
const data = await response.json();
const wasEmpty = !networkData || networkData.interfaces.length === 0;
networkData = data;
// Render interfaces if first load or structure changed
if (wasEmpty || data.interfaces.length !== (document.querySelectorAll('.chart-toggle').length || 0)) {
renderInterfaces();
}
// Update data for all interfaces
data.interfaces.forEach(updateInterfaceData);
}
} catch (error) {
console.error('Failed to fetch live traffic data', error);
} finally {
pollInFlight = false;
}
};
const bootstrap = () => {
const container = document.getElementById('network-traffic-container');
pollingEndpoint = container?.dataset?.liveTrafficEndpoint || null;
if (pollingEndpoint) {
poll();
setInterval(poll, 5000); // Poll every 5 seconds
}
};
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', bootstrap);
} else {
bootstrap();
}