805 lines
27 KiB
HTML
805 lines
27 KiB
HTML
<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
|
|
<title>KLUBHAUS ALERT</title>
|
|
<style>
|
|
* {
|
|
margin: 0;
|
|
padding: 0;
|
|
box-sizing: border-box;
|
|
-webkit-tap-highlight-color: transparent;
|
|
}
|
|
|
|
body {
|
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
|
background: #0a0a0a;
|
|
color: #fff8fa;
|
|
min-height: 100vh;
|
|
display: flex;
|
|
flex-direction: column;
|
|
padding: 20px;
|
|
}
|
|
|
|
h1 {
|
|
font-size: 14px;
|
|
font-weight: 300;
|
|
letter-spacing: 4px;
|
|
text-transform: uppercase;
|
|
color: #0bd3d3;
|
|
margin-bottom: 10px;
|
|
text-align: center;
|
|
}
|
|
|
|
#connection {
|
|
text-align: center;
|
|
font-size: 9px;
|
|
margin-bottom: 5px;
|
|
letter-spacing: 1px;
|
|
font-family: monospace;
|
|
}
|
|
|
|
#connection.connected { color: #64e8ba; }
|
|
#connection.connecting { color: #f890e7; }
|
|
#connection.error { color: #f890e7; }
|
|
#connection.backoff { color: #888; }
|
|
|
|
#status {
|
|
text-align: center;
|
|
padding: 15px;
|
|
margin-bottom: 15px;
|
|
border-radius: 8px;
|
|
font-size: 12px;
|
|
letter-spacing: 2px;
|
|
text-transform: uppercase;
|
|
transition: all 0.3s ease;
|
|
min-height: 50px;
|
|
display: flex;
|
|
flex-direction: column;
|
|
justify-content: center;
|
|
align-items: center;
|
|
}
|
|
|
|
#status.silent {
|
|
background: #1a1a1a;
|
|
color: #888;
|
|
border: 1px solid #333;
|
|
}
|
|
|
|
#status.alerting {
|
|
background: linear-gradient(90deg, #0bd3d3 0%, #f890e7 100%);
|
|
color: #000;
|
|
font-weight: 600;
|
|
animation: pulse 1s ease-in-out infinite;
|
|
}
|
|
|
|
#status.sending {
|
|
background: #f890e7;
|
|
color: #000;
|
|
font-weight: 600;
|
|
}
|
|
|
|
#status.confirming {
|
|
background: #0bd3d3;
|
|
color: #000;
|
|
font-weight: 600;
|
|
}
|
|
|
|
#status.offline {
|
|
background: #1a1a1a;
|
|
color: #f890e7;
|
|
border: 1px solid #f890e7;
|
|
}
|
|
|
|
@keyframes pulse {
|
|
0%, 100% { opacity: 1; }
|
|
50% { opacity: 0.7; }
|
|
}
|
|
|
|
.status-detail {
|
|
font-size: 10px;
|
|
font-weight: 400;
|
|
opacity: 0.8;
|
|
margin-top: 4px;
|
|
letter-spacing: 1px;
|
|
}
|
|
|
|
#metrics {
|
|
font-size: 9px;
|
|
color: #444;
|
|
text-align: center;
|
|
margin-bottom: 15px;
|
|
letter-spacing: 1px;
|
|
font-family: monospace;
|
|
}
|
|
|
|
#backoffInfo {
|
|
font-size: 9px;
|
|
color: #555;
|
|
text-align: center;
|
|
margin-bottom: 10px;
|
|
letter-spacing: 1px;
|
|
font-family: monospace;
|
|
}
|
|
|
|
.buttons {
|
|
display: grid;
|
|
gap: 15px;
|
|
flex: 1;
|
|
}
|
|
|
|
button {
|
|
border: none;
|
|
border-radius: 12px;
|
|
padding: 30px 20px;
|
|
font-size: 18px;
|
|
font-weight: 500;
|
|
letter-spacing: 2px;
|
|
text-transform: uppercase;
|
|
cursor: pointer;
|
|
transition: transform 0.1s ease, opacity 0.2s ease;
|
|
color: #fff8fa;
|
|
}
|
|
|
|
button:disabled {
|
|
opacity: 0.5;
|
|
cursor: not-allowed;
|
|
}
|
|
|
|
button:not(:disabled):active {
|
|
transform: scale(0.96);
|
|
opacity: 0.8;
|
|
}
|
|
|
|
#frontDoor {
|
|
background: linear-gradient(135deg, #0bd3d3 0%, #08a8a8 100%);
|
|
box-shadow: 0 10px 40px rgba(11, 211, 211, 0.3);
|
|
}
|
|
|
|
#loadingDock {
|
|
background: linear-gradient(135deg, #f890e7 0%, #d660c4 100%);
|
|
box-shadow: 0 10px 40px rgba(248, 144, 231, 0.3);
|
|
}
|
|
|
|
#custom {
|
|
background: #1a1a1a;
|
|
border: 2px solid #fff8fa;
|
|
padding: 20px;
|
|
}
|
|
|
|
#customInput {
|
|
width: 100%;
|
|
background: transparent;
|
|
border: none;
|
|
border-bottom: 1px solid #fff8fa;
|
|
color: #fff8fa;
|
|
font-size: 16px;
|
|
padding: 10px 0;
|
|
margin-bottom: 15px;
|
|
outline: none;
|
|
text-transform: uppercase;
|
|
letter-spacing: 1px;
|
|
}
|
|
|
|
#customInput::placeholder {
|
|
color: #666;
|
|
text-transform: uppercase;
|
|
font-size: 12px;
|
|
}
|
|
|
|
#sendCustom {
|
|
width: 100%;
|
|
background: #fff8fa;
|
|
color: #000;
|
|
border: none;
|
|
border-radius: 8px;
|
|
padding: 15px;
|
|
font-size: 14px;
|
|
font-weight: 600;
|
|
letter-spacing: 2px;
|
|
text-transform: uppercase;
|
|
cursor: pointer;
|
|
}
|
|
|
|
#sendCustom:not(:disabled):active {
|
|
background: #0bd3d3;
|
|
}
|
|
|
|
#silence {
|
|
background: #1a1a1a;
|
|
border: 2px solid #64e8ba;
|
|
color: #64e8ba;
|
|
margin-top: 10px;
|
|
}
|
|
|
|
#silence:not(:disabled):active {
|
|
background: #64e8ba;
|
|
color: #000;
|
|
}
|
|
|
|
#toast {
|
|
position: fixed;
|
|
bottom: 30px;
|
|
left: 50%;
|
|
transform: translateX(-50%) translateY(100px);
|
|
background: #64e8ba;
|
|
color: #000;
|
|
padding: 15px 30px;
|
|
border-radius: 8px;
|
|
font-size: 12px;
|
|
font-weight: 600;
|
|
letter-spacing: 2px;
|
|
text-transform: uppercase;
|
|
opacity: 0;
|
|
transition: all 0.3s ease;
|
|
pointer-events: none;
|
|
}
|
|
|
|
#toast.show {
|
|
transform: translateX(-50%) translateY(0);
|
|
opacity: 1;
|
|
}
|
|
|
|
#toast.error {
|
|
background: #f890e7;
|
|
}
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<h1>KLUBHAUS ALERT</h1>
|
|
<div id="connection" class="connecting">WebSocket: connecting...</div>
|
|
<div id="backoffInfo">—</div>
|
|
|
|
<div id="status" class="offline">
|
|
<span>Initializing...</span>
|
|
</div>
|
|
<div id="metrics">—</div>
|
|
|
|
<div class="buttons">
|
|
<button id="frontDoor" onclick="sendAlert('FRONT DOOR')">Front Door</button>
|
|
<button id="loadingDock" onclick="sendAlert('LOADING DOCK')">Loading Dock</button>
|
|
|
|
<div id="custom">
|
|
<input type="text" id="customInput" maxlength="60" placeholder="Custom message (60 chars)">
|
|
<button id="sendCustom" onclick="sendCustom()">Send Custom</button>
|
|
</div>
|
|
|
|
<button id="silence" onclick="sendSilence()">Silence</button>
|
|
</div>
|
|
|
|
<div id="toast">Sent</div>
|
|
|
|
<script>
|
|
// ============== TOPIC URLS ==============
|
|
const COMMAND_POST_URL = 'https://ntfy.sh/ALERT_klubhaus_topic';
|
|
const SILENCE_POST_URL = 'https://ntfy.sh/SILENCE_klubhaus_topic';
|
|
const METRICS_POST_URL = 'https://ntfy.sh/METRICS_klubhaus_topic';
|
|
const STATUS_WS_URL = 'wss://ntfy.sh/STATUS_klubhaus_topic/ws';
|
|
|
|
// ============== BACKOFF CONFIGURATION ==============
|
|
const ACTIVE_DURATION = 180000;
|
|
const BASE_INTERVAL = 5000;
|
|
const BACKOFF_INTERVALS = [
|
|
10000,
|
|
30000,
|
|
60000,
|
|
120000,
|
|
300000
|
|
];
|
|
|
|
// ============== CLIENT ID (persistent, anonymous) ==============
|
|
function getOrCreateClientId() {
|
|
let id = localStorage.getItem('klubhaus_client_id');
|
|
if (!id) {
|
|
const seed = [
|
|
navigator.userAgent.split('/')[0],
|
|
screen.width,
|
|
screen.height,
|
|
navigator.hardwareConcurrency || 'unknown',
|
|
new Date().getTimezoneOffset(),
|
|
Math.random().toString(36).substring(2, 8)
|
|
].join('|');
|
|
|
|
id = 'web-' + hashString(seed).substring(0, 12);
|
|
localStorage.setItem('klubhaus_client_id', id);
|
|
}
|
|
return id;
|
|
}
|
|
|
|
function hashString(str) {
|
|
let hash = 0;
|
|
for (let i = 0; i < str.length; i++) {
|
|
hash = ((hash << 5) - hash) + str.charCodeAt(i);
|
|
hash = hash & hash;
|
|
}
|
|
return Math.abs(hash).toString(16).padStart(16, '0');
|
|
}
|
|
|
|
const CLIENT_ID = getOrCreateClientId();
|
|
|
|
// ============== METRICS (with localStorage persistence) ==============
|
|
function loadMetrics() {
|
|
const saved = localStorage.getItem('klubhaus_metrics');
|
|
if (saved) {
|
|
try {
|
|
const parsed = JSON.parse(saved);
|
|
return {
|
|
totalPosted: parsed.totalPosted || 0,
|
|
totalConfirmed: parsed.totalConfirmed || 0,
|
|
totalReceived: parsed.totalReceived || 0,
|
|
totalErrors: parsed.totalErrors || 0,
|
|
roundTripMs: parsed.roundTripMs || [],
|
|
sessionStart: parsed.sessionStart || Date.now()
|
|
};
|
|
} catch (e) {
|
|
console.error('Failed to load metrics:', e);
|
|
}
|
|
}
|
|
return {
|
|
totalPosted: 0,
|
|
totalConfirmed: 0,
|
|
totalReceived: 0,
|
|
totalErrors: 0,
|
|
roundTripMs: [],
|
|
sessionStart: Date.now()
|
|
};
|
|
}
|
|
|
|
function saveMetrics() {
|
|
localStorage.setItem('klubhaus_metrics', JSON.stringify(metrics));
|
|
}
|
|
|
|
const metrics = loadMetrics();
|
|
|
|
// ============== BACKOFF STATE ==============
|
|
let lastInteraction = Date.now();
|
|
let currentInterval = BASE_INTERVAL;
|
|
let ws = null;
|
|
let isProcessing = false;
|
|
let lastConfirmedMessage = '';
|
|
let metricsIntervalId = null;
|
|
|
|
function recordInteraction() {
|
|
lastInteraction = Date.now();
|
|
currentInterval = BASE_INTERVAL;
|
|
updateBackoffDisplay();
|
|
console.log('Interaction recorded, speed: 100%');
|
|
}
|
|
|
|
function getCurrentInterval() {
|
|
const idleTime = Date.now() - lastInteraction;
|
|
|
|
if (idleTime < ACTIVE_DURATION) {
|
|
return BASE_INTERVAL;
|
|
}
|
|
|
|
const idleMinutes = (idleTime - ACTIVE_DURATION) / 60000;
|
|
|
|
if (idleMinutes < 5) return BACKOFF_INTERVALS[0];
|
|
if (idleMinutes < 10) return BACKOFF_INTERVALS[1];
|
|
if (idleMinutes < 20) return BACKOFF_INTERVALS[2];
|
|
if (idleMinutes < 40) return BACKOFF_INTERVALS[3];
|
|
return BACKOFF_INTERVALS[4];
|
|
}
|
|
|
|
function updateBackoffDisplay() {
|
|
const el = document.getElementById('backoffInfo');
|
|
const idleTime = Date.now() - lastInteraction;
|
|
const interval = getCurrentInterval();
|
|
|
|
if (idleTime < ACTIVE_DURATION) {
|
|
const remaining = Math.ceil((ACTIVE_DURATION - idleTime) / 1000);
|
|
el.textContent = `Active mode: ${remaining}s remaining`;
|
|
el.style.color = '#64e8ba';
|
|
} else {
|
|
const minutes = Math.floor((idleTime - ACTIVE_DURATION) / 60000);
|
|
el.textContent = `Idle ${minutes}min | Poll: ${interval/1000}s`;
|
|
el.style.color = '#555';
|
|
}
|
|
}
|
|
|
|
setInterval(updateBackoffDisplay, 10000);
|
|
|
|
// ============== WEBSOCKET WITH ADAPTIVE RECONNECT ==============
|
|
function connectWebSocket() {
|
|
const connEl = document.getElementById('connection');
|
|
const interval = getCurrentInterval();
|
|
|
|
connEl.className = 'connecting';
|
|
connEl.textContent = `WebSocket: connecting (poll: ${interval/1000}s)...`;
|
|
|
|
ws = new WebSocket(STATUS_WS_URL);
|
|
|
|
ws.onopen = () => {
|
|
connEl.className = 'connected';
|
|
connEl.textContent = 'WebSocket: connected';
|
|
console.log('WebSocket connected');
|
|
};
|
|
|
|
ws.onmessage = (event) => {
|
|
try {
|
|
const data = JSON.parse(event.data);
|
|
handleStatusMessage(data);
|
|
} catch (e) {
|
|
console.error('Invalid JSON:', event.data);
|
|
}
|
|
};
|
|
|
|
ws.onerror = (err) => {
|
|
connEl.className = 'error';
|
|
connEl.textContent = 'WebSocket: error';
|
|
console.error('WebSocket error:', err);
|
|
};
|
|
|
|
ws.onclose = () => {
|
|
connEl.className = 'backoff';
|
|
const nextInterval = getCurrentInterval();
|
|
connEl.textContent = `WebSocket: reconnect in ${nextInterval/1000}s...`;
|
|
console.log(`WebSocket closed, reconnecting in ${nextInterval}ms...`);
|
|
setTimeout(connectWebSocket, nextInterval);
|
|
};
|
|
}
|
|
|
|
function handleStatusMessage(data) {
|
|
if (data.event === 'open') {
|
|
console.log('Subscription confirmed');
|
|
return;
|
|
}
|
|
|
|
if (data.event !== 'message' || !data.message) return;
|
|
|
|
let payload;
|
|
try {
|
|
payload = JSON.parse(data.message);
|
|
} catch (e) {
|
|
console.error('Failed to parse payload:', data.message);
|
|
return;
|
|
}
|
|
|
|
metrics.totalReceived++;
|
|
saveMetrics();
|
|
|
|
updateStatusDisplay(payload);
|
|
updateMetricsDisplay();
|
|
|
|
if (isProcessing && payload.state === 'ALERTING' && payload.message === lastConfirmedMessage) {
|
|
finishConfirmation(true, payload.message);
|
|
}
|
|
}
|
|
|
|
function updateStatusDisplay(data) {
|
|
const statusEl = document.getElementById('status');
|
|
const state = data.state || 'UNKNOWN';
|
|
const message = data.message || '';
|
|
|
|
if (isProcessing && state === 'ALERTING') return;
|
|
|
|
if (state === 'ALERTING') {
|
|
statusEl.className = 'alerting';
|
|
statusEl.innerHTML = `<span>ALERTING</span><span class="status-detail">${escapeHtml(message)}</span>`;
|
|
} else if (state === 'SILENT') {
|
|
statusEl.className = 'silent';
|
|
statusEl.innerHTML = `<span>SILENT</span><span class="status-detail">System Ready</span>`;
|
|
} else {
|
|
statusEl.className = 'offline';
|
|
statusEl.innerHTML = `<span>UNKNOWN</span>`;
|
|
}
|
|
}
|
|
|
|
function escapeHtml(text) {
|
|
const div = document.createElement('div');
|
|
div.textContent = text;
|
|
return div.innerHTML;
|
|
}
|
|
|
|
// ============== ALERT SENDING ==============
|
|
async function sendAlert(message) {
|
|
recordInteraction();
|
|
|
|
if (isProcessing) return;
|
|
isProcessing = true;
|
|
lastConfirmedMessage = message;
|
|
|
|
const statusEl = document.getElementById('status');
|
|
const startTime = performance.now();
|
|
|
|
statusEl.className = 'sending';
|
|
statusEl.innerHTML = `<span>SENDING</span><span class="status-detail">Posting...</span>`;
|
|
setButtonsDisabled(true);
|
|
|
|
try {
|
|
const response = await fetch(COMMAND_POST_URL, {
|
|
method: 'POST',
|
|
body: message,
|
|
headers: { 'Title': 'KLUBHAUS ALERT' }
|
|
});
|
|
|
|
metrics.totalPosted++;
|
|
saveMetrics();
|
|
|
|
if (!response.ok) throw new Error('HTTP ' + response.status);
|
|
|
|
statusEl.className = 'confirming';
|
|
statusEl.innerHTML = `<span>CONFIRMING</span><span class="status-detail">Waiting for device...</span>`;
|
|
|
|
const confirmed = await waitForWebSocketConfirmation(message, 8000);
|
|
const roundTripMs = Math.round(performance.now() - startTime);
|
|
|
|
if (confirmed) {
|
|
finishConfirmation(true, message, roundTripMs);
|
|
} else {
|
|
statusEl.innerHTML = `<span>CHECKING</span><span class="status-detail">Fallback...</span>`;
|
|
const fallback = await fallbackPollForConfirmation(message, 3000);
|
|
finishConfirmation(fallback, message, roundTripMs);
|
|
}
|
|
|
|
} catch (e) {
|
|
metrics.totalErrors++;
|
|
saveMetrics();
|
|
statusEl.className = 'offline';
|
|
statusEl.innerHTML = `<span>FAILED</span><span class="status-detail">${escapeHtml(e.message)}</span>`;
|
|
showToast('NETWORK ERROR', true);
|
|
isProcessing = false;
|
|
setButtonsDisabled(false);
|
|
updateMetricsDisplay();
|
|
}
|
|
}
|
|
|
|
function waitForWebSocketConfirmation(expectedMessage, timeoutMs) {
|
|
return new Promise(resolve => {
|
|
const deadline = Date.now() + timeoutMs;
|
|
const check = setInterval(() => {
|
|
if (!isProcessing || Date.now() > deadline) {
|
|
clearInterval(check);
|
|
resolve(!isProcessing);
|
|
}
|
|
}, 100);
|
|
});
|
|
}
|
|
|
|
async function fallbackPollForConfirmation(expectedMessage, timeoutMs) {
|
|
const deadline = Date.now() + timeoutMs;
|
|
|
|
while (Date.now() < deadline) {
|
|
try {
|
|
const response = await fetch('https://ntfy.sh/STATUS_klubhaus_topic/json', {
|
|
signal: AbortSignal.timeout(3000)
|
|
});
|
|
if (!response.ok) continue;
|
|
|
|
const text = await response.text();
|
|
const lines = text.split('\n').filter(l => l.trim());
|
|
if (lines.length === 0) continue;
|
|
|
|
const data = JSON.parse(lines[0]);
|
|
if (data.state === 'ALERTING' && data.message === expectedMessage) {
|
|
return true;
|
|
}
|
|
} catch (e) {}
|
|
|
|
await sleep(500);
|
|
}
|
|
return false;
|
|
}
|
|
|
|
function sleep(ms) {
|
|
return new Promise(resolve => setTimeout(resolve, ms));
|
|
}
|
|
|
|
function finishConfirmation(success, message, roundTripMs = 0) {
|
|
isProcessing = false;
|
|
setButtonsDisabled(false);
|
|
|
|
if (success) {
|
|
metrics.totalConfirmed++;
|
|
if (roundTripMs > 0) {
|
|
metrics.roundTripMs.push(roundTripMs);
|
|
if (metrics.roundTripMs.length > 10) metrics.roundTripMs.shift();
|
|
}
|
|
saveMetrics();
|
|
showToast(`ALERT: ${message}${roundTripMs > 0 ? ' (' + roundTripMs + 'ms)' : ''}`);
|
|
publishSuccessMetric(message, roundTripMs, true);
|
|
} else {
|
|
showToast('POSTED — UNCONFIRMED', true);
|
|
publishSuccessMetric(message, roundTripMs, false);
|
|
}
|
|
|
|
updateMetricsDisplay();
|
|
}
|
|
|
|
async function publishSuccessMetric(message, roundTripMs, confirmed) {
|
|
const payload = {
|
|
client: CLIENT_ID,
|
|
timestamp: Date.now(),
|
|
event: 'publish_success',
|
|
message: message.substring(0, 20),
|
|
roundTripMs: roundTripMs,
|
|
confirmed: confirmed
|
|
};
|
|
|
|
try {
|
|
await fetch(METRICS_POST_URL, {
|
|
method: 'POST',
|
|
body: JSON.stringify(payload),
|
|
headers: { 'Content-Type': 'application/json' }
|
|
});
|
|
} catch (e) {}
|
|
}
|
|
|
|
// ============== CUSTOM & SILENCE ==============
|
|
function sendCustom() {
|
|
const input = document.getElementById('customInput');
|
|
const message = input.value.trim().toUpperCase();
|
|
|
|
if (message.length === 0) {
|
|
showToast('ENTER MESSAGE', true);
|
|
return;
|
|
}
|
|
if (message.length > 60) {
|
|
showToast('TOO LONG — MAX 60', true);
|
|
return;
|
|
}
|
|
|
|
sendAlert(message);
|
|
input.value = '';
|
|
}
|
|
|
|
async function sendSilence() {
|
|
recordInteraction();
|
|
|
|
if (isProcessing) return;
|
|
isProcessing = true;
|
|
|
|
const statusEl = document.getElementById('status');
|
|
statusEl.className = 'sending';
|
|
statusEl.innerHTML = `<span>SENDING SILENCE</span><span class="status-detail">To all topics...</span>`;
|
|
setButtonsDisabled(true);
|
|
|
|
try {
|
|
await Promise.all([
|
|
fetch(SILENCE_POST_URL, {
|
|
method: 'POST',
|
|
body: 'SILENCE',
|
|
headers: { 'Title': 'KLUBHAUS SILENCE' }
|
|
}),
|
|
fetch(COMMAND_POST_URL, {
|
|
method: 'POST',
|
|
body: 'SILENCE',
|
|
headers: { 'Title': 'KLUBHAUS SILENCE' }
|
|
})
|
|
]);
|
|
|
|
metrics.totalPosted += 2;
|
|
saveMetrics();
|
|
showToast('SILENCE SENT');
|
|
|
|
} catch (e) {
|
|
metrics.totalErrors++;
|
|
saveMetrics();
|
|
showToast('SILENCE FAILED', true);
|
|
} finally {
|
|
isProcessing = false;
|
|
setButtonsDisabled(false);
|
|
updateMetricsDisplay();
|
|
}
|
|
}
|
|
|
|
// ============== UI HELPERS ==============
|
|
function setButtonsDisabled(disabled) {
|
|
document.getElementById('frontDoor').disabled = disabled;
|
|
document.getElementById('loadingDock').disabled = disabled;
|
|
document.getElementById('sendCustom').disabled = disabled;
|
|
document.getElementById('silence').disabled = disabled;
|
|
}
|
|
|
|
function showToast(text, isError = false) {
|
|
const toast = document.getElementById('toast');
|
|
toast.textContent = text;
|
|
toast.className = isError ? 'show error' : 'show';
|
|
setTimeout(() => toast.className = '', 2500);
|
|
}
|
|
|
|
function updateMetricsDisplay() {
|
|
const el = document.getElementById('metrics');
|
|
const avgRtt = metrics.roundTripMs.length > 0
|
|
? Math.round(metrics.roundTripMs.reduce((a,b) => a+b, 0) / metrics.roundTripMs.length)
|
|
: 0;
|
|
const sessionHours = ((Date.now() - metrics.sessionStart) / 3600000).toFixed(1);
|
|
el.textContent = `${CLIENT_ID} | posted:${metrics.totalPosted} confirmed:${metrics.totalConfirmed} errors:${metrics.totalErrors} avg:${avgRtt}ms | session:${sessionHours}h`;
|
|
}
|
|
|
|
// ============== AGGREGATE METRICS (deduplicated) ==============
|
|
|
|
let lastMetricsHash = null;
|
|
let lastMetricsTimestamp = 0;
|
|
|
|
function hashMetricsPayload(payload) {
|
|
const canonical = JSON.stringify({
|
|
client: payload.client,
|
|
totalPosted: payload.metrics.totalPosted,
|
|
totalConfirmed: payload.metrics.totalConfirmed,
|
|
totalReceived: payload.metrics.totalReceived,
|
|
totalErrors: payload.metrics.totalErrors,
|
|
avgRoundTripMs: payload.metrics.avgRoundTripMs
|
|
});
|
|
|
|
let hash = 0x811c9dc5;
|
|
for (let i = 0; i < canonical.length; i++) {
|
|
hash ^= canonical.charCodeAt(i);
|
|
hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24);
|
|
}
|
|
return (hash >>> 0).toString(16);
|
|
}
|
|
|
|
function scheduleMetricsPublish() {
|
|
if (metricsIntervalId) clearInterval(metricsIntervalId);
|
|
|
|
const interval = getCurrentInterval();
|
|
console.log(`Scheduling metrics publish: ${interval}ms`);
|
|
|
|
metricsIntervalId = setInterval(async () => {
|
|
const payload = {
|
|
client: CLIENT_ID,
|
|
timestamp: Date.now(),
|
|
metrics: {
|
|
totalPosted: metrics.totalPosted,
|
|
totalConfirmed: metrics.totalConfirmed,
|
|
totalReceived: metrics.totalReceived,
|
|
totalErrors: metrics.totalErrors,
|
|
avgRoundTripMs: metrics.roundTripMs.length > 0
|
|
? Math.round(metrics.roundTripMs.reduce((a,b) => a+b, 0) / metrics.roundTripMs.length)
|
|
: 0,
|
|
currentPollInterval: getCurrentInterval()
|
|
}
|
|
};
|
|
|
|
const currentHash = hashMetricsPayload(payload);
|
|
const now = Date.now();
|
|
|
|
if (currentHash === lastMetricsHash && (now - lastMetricsTimestamp) < 300000) {
|
|
console.log('Metrics unchanged, skipping emission');
|
|
} else {
|
|
try {
|
|
await fetch(METRICS_POST_URL, {
|
|
method: 'POST',
|
|
body: JSON.stringify(payload),
|
|
headers: { 'Content-Type': 'application/json' }
|
|
});
|
|
console.log('Aggregate metrics published');
|
|
|
|
lastMetricsHash = currentHash;
|
|
lastMetricsTimestamp = now;
|
|
|
|
} catch (e) {
|
|
console.error('Metrics publish failed:', e.message);
|
|
}
|
|
}
|
|
|
|
scheduleMetricsPublish();
|
|
|
|
}, interval);
|
|
}
|
|
|
|
// ============== INIT ==============
|
|
document.getElementById('customInput').addEventListener('keypress', (e) => {
|
|
if (e.key === 'Enter') sendCustom();
|
|
});
|
|
|
|
document.addEventListener('click', recordInteraction);
|
|
document.addEventListener('touchstart', recordInteraction);
|
|
document.addEventListener('keydown', recordInteraction);
|
|
|
|
connectWebSocket();
|
|
scheduleMetricsPublish();
|
|
updateMetricsDisplay();
|
|
updateBackoffDisplay();
|
|
|
|
console.log('KLUBHAUS ALERT v4.2 initialized');
|
|
console.log('Client ID:', CLIENT_ID);
|
|
console.log('Loaded metrics:', metrics);
|
|
</script>
|
|
</body>
|
|
</html>
|
|
|