auto indent lines

This commit is contained in:
Eduardo Silva 2025-02-25 14:50:22 -03:00
parent f7917c478a
commit d2aa1ef044

View File

@ -1,10 +1,10 @@
{% extends "base.html" %}
{% block page_custom_head %}
<style>
.peer-extra-info {
display: none;
}
</style>
<style>
.peer-extra-info {
display: none;
}
</style>
{% endblock %}
@ -244,208 +244,208 @@
</script>
<script>
var previousMeasurements = {};
var toastShownThisCycle = false;
var previousMeasurements = {};
var toastShownThisCycle = false;
const updateThroughput = (peerId, peerInfo) => {
const throughputElement = document.getElementById(`peer-throughput-${peerId}`);
const currentTime = Date.now() / 1000; // current timestamp in seconds
let formattedThroughput = '';
const updateThroughput = (peerId, peerInfo) => {
const throughputElement = document.getElementById(`peer-throughput-${peerId}`);
const currentTime = Date.now() / 1000; // current timestamp in seconds
let formattedThroughput = '';
if (previousMeasurements[peerId]) {
const prev = previousMeasurements[peerId];
const timeDiff = currentTime - prev.timestamp; // time difference in seconds
if (previousMeasurements[peerId]) {
const prev = previousMeasurements[peerId];
const timeDiff = currentTime - prev.timestamp; // time difference in seconds
// For peer perspective: download corresponds to tx and upload to rx
let downloadDiff = peerInfo.transfer.tx - prev.transfer.tx;
let uploadDiff = peerInfo.transfer.rx - prev.transfer.rx;
// For peer perspective: download corresponds to tx and upload to rx
let downloadDiff = peerInfo.transfer.tx - prev.transfer.tx;
let uploadDiff = peerInfo.transfer.rx - prev.transfer.rx;
// If counters have been reset (current < previous), show toast (only once per cycle)
if (downloadDiff < 0 || uploadDiff < 0) {
if (!toastShownThisCycle) {
$(document).Toasts('create', {
class: 'bg-info',
title: 'info',
body: 'Throughput discarded due to counter reset',
delay: 10000,
autohide: true
});
toastShownThisCycle = true;
// If counters have been reset (current < previous), show toast (only once per cycle)
if (downloadDiff < 0 || uploadDiff < 0) {
if (!toastShownThisCycle) {
$(document).Toasts('create', {
class: 'bg-info',
title: 'info',
body: 'Throughput discarded due to counter reset',
delay: 10000,
autohide: true
});
toastShownThisCycle = true;
}
downloadDiff = 0;
uploadDiff = 0;
}
downloadDiff = 0;
uploadDiff = 0;
// Calculate throughput in bytes per second
const downloadThroughput = downloadDiff / timeDiff;
const uploadThroughput = uploadDiff / timeDiff;
// Format throughput values (using convertBytes function)
let downloadDisplay = convertBytes(downloadThroughput) + '/s';
let uploadDisplay = convertBytes(uploadThroughput) + '/s';
// Threshold: 1mb (1 megabit/s = 125000 bytes per second)
const threshold = 125000;
if (downloadThroughput > threshold) {
downloadDisplay = `<strong>${downloadDisplay}</strong>`;
}
if (uploadThroughput > threshold) {
uploadDisplay = `<strong>${uploadDisplay}</strong>`;
}
formattedThroughput = `<i class="fas fa-arrow-down"></i> ${downloadDisplay}, <i class="fas fa-arrow-up"></i> ${uploadDisplay}`;
throughputElement.innerHTML = formattedThroughput;
} else {
// First cycle: no previous measurement available.
formattedThroughput = `<i class="fas fa-arrow-down"></i> -.- B/s, <i class="fas fa-arrow-up"></i> -.- B/s`;
throughputElement.innerHTML = formattedThroughput;
}
// Calculate throughput in bytes per second
const downloadThroughput = downloadDiff / timeDiff;
const uploadThroughput = uploadDiff / timeDiff;
previousMeasurements[peerId] = {
timestamp: currentTime,
transfer: {
tx: peerInfo.transfer.tx,
rx: peerInfo.transfer.rx
}
};
// Format throughput values (using convertBytes function)
let downloadDisplay = convertBytes(downloadThroughput) + '/s';
let uploadDisplay = convertBytes(uploadThroughput) + '/s';
// Threshold: 1mb (1 megabit/s = 125000 bytes per second)
const threshold = 125000;
if (downloadThroughput > threshold) {
downloadDisplay = `<strong>${downloadDisplay}</strong>`;
}
if (uploadThroughput > threshold) {
uploadDisplay = `<strong>${uploadDisplay}</strong>`;
}
formattedThroughput = `<i class="fas fa-arrow-down"></i> ${downloadDisplay}, <i class="fas fa-arrow-up"></i> ${uploadDisplay}`;
throughputElement.innerHTML = formattedThroughput;
} else {
// First cycle: no previous measurement available.
formattedThroughput = `<i class="fas fa-arrow-down"></i> -.- B/s, <i class="fas fa-arrow-up"></i> -.- B/s`;
throughputElement.innerHTML = formattedThroughput;
}
previousMeasurements[peerId] = {
timestamp: currentTime,
transfer: {
tx: peerInfo.transfer.tx,
rx: peerInfo.transfer.rx
}
return formattedThroughput;
};
return formattedThroughput;
};
// Convert bytes to human-readable format with abbreviated units
const convertBytes = (bytes) => {
if (bytes === 0) return '0 B';
const k = 1024;
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(2)) + ' ' + sizes[i];
};
// Convert bytes to human-readable format with abbreviated units
const convertBytes = (bytes) => {
if (bytes === 0) return '0 B';
const k = 1024;
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(2)) + ' ' + sizes[i];
};
// Fetch Wireguard status and update UI
document.addEventListener('DOMContentLoaded', function() {
const fetchWireguardStatus = async () => {
try {
const response = await fetch('/api/wireguard_status/');
let data = await response.json();
// Fetch Wireguard status and update UI
document.addEventListener('DOMContentLoaded', function() {
const fetchWireguardStatus = async () => {
try {
const response = await fetch('/api/wireguard_status/');
let data = await response.json();
// If latest-handshakes is 0, use the stored value
for (const [interfaceName, peers] of Object.entries(data)) {
for (const [peerId, peerInfo] of Object.entries(peers)) {
const peerElementId = `peer-stored-latest-handshake-${peerId}`;
const storedHandshakeElement = document.getElementById(peerElementId);
if (peerInfo['latest-handshakes'] === '0' && storedHandshakeElement) {
peerInfo['latest-handshakes'] = storedHandshakeElement.textContent;
}
}
}
// If latest-handshakes is 0, use the stored value
for (const [interfaceName, peers] of Object.entries(data)) {
for (const [peerId, peerInfo] of Object.entries(peers)) {
const peerElementId = `peer-stored-latest-handshake-${peerId}`;
const storedHandshakeElement = document.getElementById(peerElementId);
if (peerInfo['latest-handshakes'] === '0' && storedHandshakeElement) {
peerInfo['latest-handshakes'] = storedHandshakeElement.textContent;
updateUI(data);
} catch (error) {
console.error('Error fetching Wireguard status:', error);
}
};
fetchWireguardStatus();
setInterval(fetchWireguardStatus, {{ current_instance.peer_list_refresh_interval }} * 1000);
});
const updateUI = (data) => {
// Reset the toast flag for this update cycle
toastShownThisCycle = false;
for (const [interfaceName, peers] of Object.entries(data)) {
for (const [peerId, peerInfo] of Object.entries(peers)) {
const peerDiv = document.getElementById(`peer-${peerId}`);
if (peerDiv) {
updatePeerInfo(peerDiv, peerId, peerInfo);
updateCalloutClass(peerDiv, peerInfo['latest-handshakes']);
// Calculate throughput and update the card
const throughputHTML = updateThroughput(peerId, peerInfo);
// If the modal is active for this peer, update its fields as well
const peerUuid = peerDiv.getAttribute("data-uuid");
if ($('#peerPreviewModal').is(':visible') && $('#peerPreviewModal').data('peer-uuid') === peerUuid) {
$('#peerThroughput').html(throughputHTML);
$('#peerTransfer').text(`${convertBytes(peerInfo.transfer.tx)} TX, ${convertBytes(peerInfo.transfer.rx)} RX`);
$('#peerHandshake').text(
peerInfo['latest-handshakes'] !== '0'
? new Date(parseInt(peerInfo['latest-handshakes']) * 1000).toLocaleString()
: '0'
);
$('#peerEndpoints').text(peerInfo.endpoints);
const allowedIpsModalElement = document.getElementById('peerAllowedIPs');
checkAllowedIps(allowedIpsModalElement, peerInfo['allowed-ips']);
}
}
}
updateUI(data);
} catch (error) {
console.error('Error fetching Wireguard status:', error);
}
};
fetchWireguardStatus();
setInterval(fetchWireguardStatus, {{ current_instance.peer_list_refresh_interval }} * 1000);
});
const updatePeerInfo = (peerDiv, peerId, peerInfo) => {
const escapedPeerId = peerId.replace(/([!"#$%&'()*+,.\/:;<=>?@[\]^`{|}~])/g, '\\$1');
const transfer = peerDiv.querySelector(`#peer-transfer-${escapedPeerId}`);
const latestHandshake = peerDiv.querySelector(`#peer-latest-handshake-${escapedPeerId}`);
const endpoints = peerDiv.querySelector(`#peer-endpoints-${escapedPeerId}`);
const allowedIps = peerDiv.querySelector(`#peer-allowed-ips-${escapedPeerId}`);
const updateUI = (data) => {
// Reset the toast flag for this update cycle
toastShownThisCycle = false;
transfer.textContent = `${convertBytes(peerInfo.transfer.tx)} TX, ${convertBytes(peerInfo.transfer.rx)} RX`;
latestHandshake.textContent = `${peerInfo['latest-handshakes'] !== '0' ? new Date(parseInt(peerInfo['latest-handshakes']) * 1000).toLocaleString() : '0'}`;
endpoints.textContent = `${peerInfo.endpoints}`;
checkAllowedIps(allowedIps, peerInfo['allowed-ips']);
};
for (const [interfaceName, peers] of Object.entries(data)) {
for (const [peerId, peerInfo] of Object.entries(peers)) {
const peerDiv = document.getElementById(`peer-${peerId}`);
if (peerDiv) {
updatePeerInfo(peerDiv, peerId, peerInfo);
updateCalloutClass(peerDiv, peerInfo['latest-handshakes']);
// Calculate throughput and update the card
const throughputHTML = updateThroughput(peerId, peerInfo);
const checkAllowedIps = (allowedIpsElement, allowedIpsApiResponse) => {
const apiIps = allowedIpsApiResponse[0].split(' ');
const htmlIpsText = allowedIpsElement.textContent.trim();
const htmlIpsArray = htmlIpsText.match(/\b(?:\d{1,3}\.){3}\d{1,3}\/\d{1,2}\b/g) || [];
// If the modal is active for this peer, update its fields as well
const peerUuid = peerDiv.getAttribute("data-uuid");
if ($('#peerPreviewModal').is(':visible') && $('#peerPreviewModal').data('peer-uuid') === peerUuid) {
$('#peerThroughput').html(throughputHTML);
$('#peerTransfer').text(`${convertBytes(peerInfo.transfer.tx)} TX, ${convertBytes(peerInfo.transfer.rx)} RX`);
$('#peerHandshake').text(
peerInfo['latest-handshakes'] !== '0'
? new Date(parseInt(peerInfo['latest-handshakes']) * 1000).toLocaleString()
: '0'
);
$('#peerEndpoints').text(peerInfo.endpoints);
const allowedIpsModalElement = document.getElementById('peerAllowedIPs');
checkAllowedIps(allowedIpsModalElement, peerInfo['allowed-ips']);
}
allowedIpsElement.innerHTML = '';
let showExtraInfo = false;
htmlIpsArray.forEach((ip, index, array) => {
const ipSpan = document.createElement('span');
ipSpan.textContent = ip;
allowedIpsElement.appendChild(ipSpan);
if (!apiIps.includes(ip)) {
ipSpan.style.color = 'red';
ipSpan.style.textDecoration = 'underline';
ipSpan.title = 'This address does not appear in the wg show command output, likely indicating that another peer has an IP overlapping this network or that the configuration file is outdated.';
showExtraInfo = true;
}
if (index < array.length - 1) {
allowedIpsElement.appendChild(document.createTextNode(', '));
}
});
if (showExtraInfo) {
const extraInfoContainerId = allowedIpsElement.id.replace('peer-allowed-ips-', 'peer-extra-info-allowed-ips-');
const extraInfoContainer = document.getElementById(extraInfoContainerId);
if (extraInfoContainer) {
extraInfoContainer.style.display = 'block';
}
}
}
};
const updatePeerInfo = (peerDiv, peerId, peerInfo) => {
const escapedPeerId = peerId.replace(/([!"#$%&'()*+,.\/:;<=>?@[\]^`{|}~])/g, '\\$1');
const transfer = peerDiv.querySelector(`#peer-transfer-${escapedPeerId}`);
const latestHandshake = peerDiv.querySelector(`#peer-latest-handshake-${escapedPeerId}`);
const endpoints = peerDiv.querySelector(`#peer-endpoints-${escapedPeerId}`);
const allowedIps = peerDiv.querySelector(`#peer-allowed-ips-${escapedPeerId}`);
transfer.textContent = `${convertBytes(peerInfo.transfer.tx)} TX, ${convertBytes(peerInfo.transfer.rx)} RX`;
latestHandshake.textContent = `${peerInfo['latest-handshakes'] !== '0' ? new Date(parseInt(peerInfo['latest-handshakes']) * 1000).toLocaleString() : '0'}`;
endpoints.textContent = `${peerInfo.endpoints}`;
checkAllowedIps(allowedIps, peerInfo['allowed-ips']);
};
const checkAllowedIps = (allowedIpsElement, allowedIpsApiResponse) => {
const apiIps = allowedIpsApiResponse[0].split(' ');
const htmlIpsText = allowedIpsElement.textContent.trim();
const htmlIpsArray = htmlIpsText.match(/\b(?:\d{1,3}\.){3}\d{1,3}\/\d{1,2}\b/g) || [];
allowedIpsElement.innerHTML = '';
let showExtraInfo = false;
htmlIpsArray.forEach((ip, index, array) => {
const ipSpan = document.createElement('span');
ipSpan.textContent = ip;
allowedIpsElement.appendChild(ipSpan);
if (!apiIps.includes(ip)) {
ipSpan.style.color = 'red';
ipSpan.style.textDecoration = 'underline';
ipSpan.title = 'This address does not appear in the wg show command output, likely indicating that another peer has an IP overlapping this network or that the configuration file is outdated.';
showExtraInfo = true;
}
if (index < array.length - 1) {
allowedIpsElement.appendChild(document.createTextNode(', '));
}
});
if (showExtraInfo) {
const extraInfoContainerId = allowedIpsElement.id.replace('peer-allowed-ips-', 'peer-extra-info-allowed-ips-');
const extraInfoContainer = document.getElementById(extraInfoContainerId);
if (extraInfoContainer) {
extraInfoContainer.style.display = 'block';
}
}
};
};
const updateCalloutClass = (peerDiv, latestHandshake) => {
const calloutDiv = peerDiv.querySelector('.callout');
calloutDiv.classList.remove('callout-success', 'callout-info', 'callout-warning', 'callout-danger');
const handshakeAge = Date.now() / 1000 - parseInt(latestHandshake);
const updateCalloutClass = (peerDiv, latestHandshake) => {
const calloutDiv = peerDiv.querySelector('.callout');
calloutDiv.classList.remove('callout-success', 'callout-info', 'callout-warning', 'callout-danger');
const handshakeAge = Date.now() / 1000 - parseInt(latestHandshake);
if (latestHandshake === '0') {
calloutDiv.classList.add('callout-danger');
} else if (handshakeAge < 600) {
calloutDiv.classList.add('callout-success');
} else if (handshakeAge < 1800) {
calloutDiv.classList.add('callout-info');
} else if (handshakeAge < 21600) {
calloutDiv.classList.add('callout-warning');
}
calloutDiv.style.transition = 'all 5s';
};
</script>
if (latestHandshake === '0') {
calloutDiv.classList.add('callout-danger');
} else if (handshakeAge < 600) {
calloutDiv.classList.add('callout-success');
} else if (handshakeAge < 1800) {
calloutDiv.classList.add('callout-info');
} else if (handshakeAge < 21600) {
calloutDiv.classList.add('callout-warning');
}
calloutDiv.style.transition = 'all 5s';
};
</script>
<script>
$(document).ready(function(){