689 lines
25 KiB
JavaScript
689 lines
25 KiB
JavaScript
const express = require('express');
|
||
const https = require('https');
|
||
const http = require('http');
|
||
const app = express();
|
||
app.use(express.json());
|
||
const PORT = 3000;
|
||
|
||
// ─── IP Helpers ───────────────────────────────────────────────────────────────
|
||
|
||
function getLocalIP() {
|
||
const dgram = require('dgram');
|
||
return new Promise((resolve) => {
|
||
const socket = dgram.createSocket('udp4');
|
||
socket.connect(80, '8.8.8.8', () => {
|
||
const address = socket.address().address;
|
||
socket.close();
|
||
resolve(address);
|
||
});
|
||
socket.on('error', () => resolve('Unavailable'));
|
||
});
|
||
}
|
||
|
||
function getPublicIP() {
|
||
return new Promise((resolve) => {
|
||
https.get('https://api.ipify.org', (res) => {
|
||
let data = '';
|
||
res.on('data', (chunk) => { data += chunk; });
|
||
res.on('end', () => resolve(data.trim()));
|
||
}).on('error', () => resolve('Unavailable'));
|
||
});
|
||
}
|
||
|
||
// ─── Internet Monitor State ───────────────────────────────────────────────────
|
||
|
||
let checkIntervalMs = 5000;
|
||
let checkUrl = 'https://www.google.com';
|
||
let intervalId = null;
|
||
|
||
let isOnline = true;
|
||
let outageStart = null;
|
||
const outages = [];
|
||
let monitorStartTime = Date.now();
|
||
let totalDowntimeMs = 0;
|
||
|
||
function checkConnectivity() {
|
||
return new Promise((resolve) => {
|
||
const mod = checkUrl.startsWith('https://') ? https : http;
|
||
const req = mod.get(checkUrl, { timeout: 4000 }, (res) => {
|
||
res.resume();
|
||
resolve(true);
|
||
});
|
||
req.on('error', () => resolve(false));
|
||
req.on('timeout', () => { req.destroy(); resolve(false); });
|
||
});
|
||
}
|
||
|
||
async function monitor() {
|
||
const online = await checkConnectivity();
|
||
if (!online && isOnline) {
|
||
isOnline = false;
|
||
outageStart = Date.now();
|
||
console.log(`[${new Date(outageStart).toISOString()}] Internet DISCONNECTED`);
|
||
} else if (online && !isOnline) {
|
||
const end = Date.now();
|
||
const duration = end - outageStart;
|
||
totalDowntimeMs += duration;
|
||
outages.push({ start: outageStart, end, duration });
|
||
console.log(`[${new Date(end).toISOString()}] Internet RESTORED (outage lasted ${formatDuration(duration)})`);
|
||
isOnline = true;
|
||
outageStart = null;
|
||
}
|
||
}
|
||
|
||
function formatDuration(ms) {
|
||
const s = Math.floor(ms / 1000);
|
||
const h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60), sec = s % 60;
|
||
if (h > 0) return `${h}h ${m}m ${sec}s`;
|
||
if (m > 0) return `${m}m ${sec}s`;
|
||
return `${sec}s`;
|
||
}
|
||
|
||
function restartMonitor() {
|
||
if (intervalId) clearInterval(intervalId);
|
||
intervalId = setInterval(monitor, checkIntervalMs);
|
||
}
|
||
|
||
restartMonitor();
|
||
monitor();
|
||
|
||
// ─── Routes ───────────────────────────────────────────────────────────────────
|
||
|
||
// Unified Dashboard
|
||
app.get('/', async (req, res) => {
|
||
const [localIP, publicIP] = await Promise.all([getLocalIP(), getPublicIP()]);
|
||
res.send(`<!DOCTYPE html>
|
||
<html lang="en">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||
<title>Network Dashboard</title>
|
||
<style>
|
||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||
body {
|
||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
||
background: #0f172a;
|
||
color: #e2e8f0;
|
||
min-height: 100vh;
|
||
padding: 2rem;
|
||
}
|
||
|
||
/* ── Header ── */
|
||
header {
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: space-between;
|
||
margin-bottom: 2rem;
|
||
flex-wrap: wrap;
|
||
gap: 0.75rem;
|
||
}
|
||
header h1 { font-size: 1.5rem; font-weight: 700; letter-spacing: -0.01em; }
|
||
header .subtitle { color: #64748b; font-size: 0.8rem; margin-top: 0.15rem; }
|
||
#status-badge {
|
||
display: inline-flex;
|
||
align-items: center;
|
||
gap: 0.5rem;
|
||
padding: 0.35rem 1rem;
|
||
border-radius: 999px;
|
||
font-weight: 600;
|
||
font-size: 0.9rem;
|
||
}
|
||
#status-badge.online { background: #14532d; color: #4ade80; }
|
||
#status-badge.offline { background: #450a0a; color: #f87171; }
|
||
.dot { width: 9px; height: 9px; border-radius: 50%; animation: pulse 1.5s infinite; }
|
||
.online .dot { background: #4ade80; }
|
||
.offline .dot { background: #f87171; }
|
||
@keyframes pulse { 0%,100%{opacity:1} 50%{opacity:.35} }
|
||
|
||
/* ── Top row: IP + Uptime % side by side ── */
|
||
.top-row {
|
||
display: grid;
|
||
grid-template-columns: 1fr 1fr;
|
||
gap: 1rem;
|
||
margin-bottom: 1rem;
|
||
}
|
||
@media (max-width: 640px) { .top-row { grid-template-columns: 1fr; } }
|
||
|
||
/* ── Cards ── */
|
||
.panel {
|
||
background: #1e293b;
|
||
border: 1px solid #334155;
|
||
border-radius: 14px;
|
||
padding: 1.25rem 1.5rem;
|
||
}
|
||
.panel-title {
|
||
font-size: 0.7rem;
|
||
font-weight: 600;
|
||
text-transform: uppercase;
|
||
letter-spacing: 0.07em;
|
||
color: #64748b;
|
||
margin-bottom: 1rem;
|
||
}
|
||
|
||
/* IP info */
|
||
.ip-row { display: flex; align-items: center; justify-content: space-between; padding: 0.45rem 0; }
|
||
.ip-row + .ip-row { border-top: 1px solid #334155; }
|
||
.ip-label { font-size: 0.8rem; color: #94a3b8; }
|
||
.ip-val {
|
||
font-family: monospace;
|
||
font-size: 0.9rem;
|
||
background: #0f172a;
|
||
padding: 0.2rem 0.6rem;
|
||
border-radius: 5px;
|
||
color: #e2e8f0;
|
||
}
|
||
|
||
/* Big uptime % */
|
||
.pct-wrap { display: flex; align-items: flex-end; gap: 0.5rem; margin-bottom: 0.75rem; }
|
||
.pct-big { font-size: 3rem; font-weight: 800; line-height: 1; }
|
||
.pct-label { font-size: 0.8rem; color: #64748b; margin-bottom: 0.3rem; }
|
||
.green { color: #4ade80; }
|
||
.yellow { color: #facc15; }
|
||
.red { color: #f87171; }
|
||
|
||
/* Bar */
|
||
.bar-row { display: flex; align-items: center; gap: 0.6rem; margin-bottom: 0.45rem; }
|
||
.bar-lbl { width: 55px; font-size: 0.75rem; color: #94a3b8; }
|
||
.bar-bg { flex: 1; height: 8px; background: #334155; border-radius: 999px; overflow: hidden; }
|
||
.bar-fill { height: 100%; border-radius: 999px; transition: width 0.6s; }
|
||
.bar-pct { width: 48px; font-size: 0.75rem; text-align: right; color: #94a3b8; }
|
||
|
||
/* Stats grid */
|
||
.stats-grid {
|
||
display: grid;
|
||
grid-template-columns: repeat(4, 1fr);
|
||
gap: 1rem;
|
||
margin-bottom: 1rem;
|
||
}
|
||
@media (max-width: 700px) { .stats-grid { grid-template-columns: repeat(2, 1fr); } }
|
||
.stat-card {
|
||
background: #1e293b;
|
||
border: 1px solid #334155;
|
||
border-radius: 12px;
|
||
padding: 1rem 1.2rem;
|
||
}
|
||
.stat-label { font-size: 0.7rem; color: #64748b; text-transform: uppercase; letter-spacing: 0.06em; margin-bottom: 0.35rem; }
|
||
.stat-val { font-size: 1.35rem; font-weight: 700; }
|
||
|
||
/* Outage table */
|
||
.table-wrap {
|
||
background: #1e293b;
|
||
border: 1px solid #334155;
|
||
border-radius: 14px;
|
||
overflow: hidden;
|
||
}
|
||
.table-header {
|
||
padding: 0.85rem 1.25rem;
|
||
border-bottom: 1px solid #334155;
|
||
font-size: 0.7rem;
|
||
font-weight: 600;
|
||
text-transform: uppercase;
|
||
letter-spacing: 0.07em;
|
||
color: #64748b;
|
||
}
|
||
table { width: 100%; border-collapse: collapse; font-size: 0.85rem; }
|
||
th {
|
||
text-align: left; padding: 0.55rem 1.25rem;
|
||
color: #475569; font-size: 0.72rem;
|
||
text-transform: uppercase; letter-spacing: 0.05em;
|
||
background: #162032;
|
||
}
|
||
td { padding: 0.6rem 1.25rem; border-top: 1px solid #1e293b; }
|
||
tr:hover td { background: #243044; }
|
||
.no-outages { text-align: center; padding: 2.5rem; color: #475569; font-size: 0.85rem; }
|
||
|
||
/* Footer */
|
||
#last-updated { margin-top: 1.25rem; font-size: 0.72rem; color: #334155; text-align: right; }
|
||
|
||
/* Export */
|
||
.export-wrap { position: relative; display: inline-block; }
|
||
.export-btn {
|
||
display: inline-flex; align-items: center; gap: 0.45rem;
|
||
background: #1e293b; border: 1px solid #334155; color: #e2e8f0;
|
||
padding: 0.4rem 1rem; border-radius: 8px; font-size: 0.85rem;
|
||
font-weight: 600; cursor: pointer; transition: background 0.15s;
|
||
}
|
||
.export-btn:hover { background: #243044; }
|
||
.export-menu {
|
||
display: none; position: absolute; right: 0; top: calc(100% + 6px);
|
||
background: #1e293b; border: 1px solid #334155; border-radius: 10px;
|
||
min-width: 160px; overflow: hidden; z-index: 99;
|
||
box-shadow: 0 8px 24px rgba(0,0,0,.4);
|
||
}
|
||
.export-menu.open { display: block; }
|
||
.export-menu a {
|
||
display: flex; align-items: center; gap: 0.5rem;
|
||
padding: 0.6rem 1rem; font-size: 0.85rem; color: #e2e8f0;
|
||
text-decoration: none; transition: background 0.12s;
|
||
}
|
||
.export-menu a:hover { background: #243044; }
|
||
.export-menu a + a { border-top: 1px solid #334155; }
|
||
|
||
/* Settings */
|
||
.settings-btn {
|
||
display: inline-flex; align-items: center; gap: 0.45rem;
|
||
background: #1e293b; border: 1px solid #334155; color: #e2e8f0;
|
||
padding: 0.4rem 1rem; border-radius: 8px; font-size: 0.85rem;
|
||
font-weight: 600; cursor: pointer; transition: background 0.15s;
|
||
}
|
||
.settings-btn:hover { background: #243044; }
|
||
.modal-overlay {
|
||
display: none; position: fixed; inset: 0;
|
||
background: rgba(0,0,0,.65); z-index: 200;
|
||
align-items: center; justify-content: center;
|
||
}
|
||
.modal-overlay.open { display: flex; }
|
||
.modal {
|
||
background: #1e293b; border: 1px solid #334155;
|
||
border-radius: 16px; padding: 1.75rem;
|
||
width: 100%; max-width: 420px;
|
||
box-shadow: 0 20px 60px rgba(0,0,0,.5);
|
||
}
|
||
.modal-title { font-size: 1rem; font-weight: 700; margin-bottom: 1.25rem; }
|
||
.form-group { margin-bottom: 1rem; }
|
||
.form-label {
|
||
display: block; font-size: 0.75rem; font-weight: 600; color: #94a3b8;
|
||
text-transform: uppercase; letter-spacing: 0.06em; margin-bottom: 0.4rem;
|
||
}
|
||
.form-input {
|
||
width: 100%; background: #0f172a; border: 1px solid #334155;
|
||
border-radius: 8px; padding: 0.55rem 0.75rem;
|
||
color: #e2e8f0; font-size: 0.9rem; outline: none;
|
||
transition: border-color 0.15s;
|
||
}
|
||
.form-input:focus { border-color: #6366f1; }
|
||
.form-hint { font-size: 0.72rem; color: #64748b; margin-top: 0.3rem; }
|
||
.modal-actions { display: flex; gap: 0.75rem; margin-top: 1.5rem; justify-content: flex-end; }
|
||
.btn-save {
|
||
background: #6366f1; color: white; border: none;
|
||
padding: 0.5rem 1.25rem; border-radius: 8px;
|
||
font-size: 0.85rem; font-weight: 600; cursor: pointer;
|
||
transition: background 0.15s;
|
||
}
|
||
.btn-save:hover { background: #4f46e5; }
|
||
.btn-cancel {
|
||
background: transparent; color: #94a3b8; border: 1px solid #334155;
|
||
padding: 0.5rem 1.25rem; border-radius: 8px;
|
||
font-size: 0.85rem; cursor: pointer; transition: background 0.15s;
|
||
}
|
||
.btn-cancel:hover { background: #243044; color: #e2e8f0; }
|
||
.toast {
|
||
position: fixed; bottom: 1.5rem; right: 1.5rem;
|
||
background: #14532d; color: #4ade80; border: 1px solid #166534;
|
||
padding: 0.65rem 1.25rem; border-radius: 10px; font-size: 0.85rem;
|
||
font-weight: 600; opacity: 0; transition: opacity 0.3s; z-index: 300;
|
||
pointer-events: none;
|
||
}
|
||
.toast.show { opacity: 1; }
|
||
</style>
|
||
</head>
|
||
<body>
|
||
|
||
<header>
|
||
<div>
|
||
<h1>Network Dashboard</h1>
|
||
<div class="subtitle" id="monitor-since">Loading...</div>
|
||
</div>
|
||
<div id="status-badge" class="online"><div class="dot"></div><span id="status-text">Checking…</span></div>
|
||
<button class="settings-btn" onclick="openSettings()">⚙ Settings</button>
|
||
<div class="export-wrap">
|
||
<button class="export-btn" onclick="toggleExportMenu(event)">⬇ Export</button>
|
||
<div class="export-menu" id="export-menu">
|
||
<a href="/export/json" download>📄 Export as JSON</a>
|
||
<a href="/export/csv" download>📊 Export as CSV</a>
|
||
</div>
|
||
</div>
|
||
</header>
|
||
|
||
<!-- Top row: IP info + Uptime % -->
|
||
<div class="top-row">
|
||
<div class="panel">
|
||
<div class="panel-title">Network Info</div>
|
||
<div class="ip-row">
|
||
<span class="ip-label">Port</span>
|
||
<span class="ip-val">${PORT}</span>
|
||
</div>
|
||
<div class="ip-row">
|
||
<span class="ip-label">Local IP</span>
|
||
<span class="ip-val">${localIP}</span>
|
||
</div>
|
||
<div class="ip-row">
|
||
<span class="ip-label">Public IP</span>
|
||
<span class="ip-val" id="public-ip">${publicIP}</span>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="panel">
|
||
<div class="panel-title">Uptime</div>
|
||
<div class="pct-wrap">
|
||
<div class="pct-big green" id="stat-pct">–</div>
|
||
<div class="pct-label">uptime</div>
|
||
</div>
|
||
<div class="bar-row">
|
||
<div class="bar-lbl">Online</div>
|
||
<div class="bar-bg"><div class="bar-fill" id="bar-up" style="background:#4ade80;width:0%"></div></div>
|
||
<div class="bar-pct green" id="bar-up-pct">–</div>
|
||
</div>
|
||
<div class="bar-row">
|
||
<div class="bar-lbl">Offline</div>
|
||
<div class="bar-bg"><div class="bar-fill" id="bar-down" style="background:#f87171;width:0%"></div></div>
|
||
<div class="bar-pct red" id="bar-down-pct">–</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Stats row -->
|
||
<div class="stats-grid">
|
||
<div class="stat-card">
|
||
<div class="stat-label">Total Uptime</div>
|
||
<div class="stat-val green" id="stat-uptime">–</div>
|
||
</div>
|
||
<div class="stat-card">
|
||
<div class="stat-label">Total Downtime</div>
|
||
<div class="stat-val red" id="stat-downtime">–</div>
|
||
</div>
|
||
<div class="stat-card">
|
||
<div class="stat-label">Outages</div>
|
||
<div class="stat-val" id="stat-count">–</div>
|
||
</div>
|
||
<div class="stat-card">
|
||
<div class="stat-label">Avg / Longest Outage</div>
|
||
<div class="stat-val" id="stat-avg-max">–</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Outage history -->
|
||
<div class="table-wrap">
|
||
<div class="table-header">Outage History</div>
|
||
<table>
|
||
<thead>
|
||
<tr><th>#</th><th>Start</th><th>End</th><th>Duration</th></tr>
|
||
</thead>
|
||
<tbody id="outage-table"></tbody>
|
||
</table>
|
||
<div class="no-outages" id="no-outages">No outages recorded yet — connection has been stable.</div>
|
||
</div>
|
||
|
||
<div id="last-updated"></div>
|
||
|
||
<!-- Settings Modal -->
|
||
<div class="modal-overlay" id="settings-overlay" onclick="closeSettingsOnOverlay(event)">
|
||
<div class="modal">
|
||
<div class="modal-title">⚙ Settings</div>
|
||
<div class="form-group">
|
||
<label class="form-label" for="inp-interval">Check Interval (seconds)</label>
|
||
<input class="form-input" type="number" id="inp-interval" min="1" max="3600" step="1">
|
||
<div class="form-hint">How often to check connectivity (1–3600 s)</div>
|
||
</div>
|
||
<div class="form-group">
|
||
<label class="form-label" for="inp-url">Check URL</label>
|
||
<input class="form-input" type="url" id="inp-url" placeholder="https://www.google.com">
|
||
<div class="form-hint">URL used to test internet connectivity</div>
|
||
</div>
|
||
<div class="modal-actions">
|
||
<button class="btn-cancel" onclick="closeSettings()">Cancel</button>
|
||
<button class="btn-save" onclick="saveSettings()">Save</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="toast" id="toast">✓ Settings saved</div>
|
||
|
||
<script>
|
||
let checkIntervalMs = ${checkIntervalMs};
|
||
|
||
function fmtMs(ms) {
|
||
const s = Math.floor(ms / 1000);
|
||
const h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60), sec = s % 60;
|
||
if (h > 0) return h + 'h ' + m + 'm ' + sec + 's';
|
||
if (m > 0) return m + 'm ' + sec + 's';
|
||
return sec + 's';
|
||
}
|
||
function fmtDate(ts) { return new Date(ts).toLocaleString(); }
|
||
|
||
async function refresh() {
|
||
try {
|
||
const d = await fetch('/api/status').then(r => r.json());
|
||
|
||
// Status badge
|
||
const badge = document.getElementById('status-badge');
|
||
badge.className = d.isOnline ? 'online' : 'offline';
|
||
document.getElementById('status-text').textContent = d.isOnline ? 'Online' : 'Offline';
|
||
|
||
document.getElementById('monitor-since').textContent =
|
||
'Monitoring since ' + fmtDate(d.monitorStartTime);
|
||
|
||
// Uptime %
|
||
const pct = d.uptimeMs > 0 ? (d.totalUptimeMs / d.uptimeMs * 100).toFixed(2) : '100.00';
|
||
const downPct = (100 - parseFloat(pct)).toFixed(2);
|
||
const pctEl = document.getElementById('stat-pct');
|
||
pctEl.textContent = pct + '%';
|
||
pctEl.className = 'pct-big ' + (parseFloat(pct) >= 99 ? 'green' : parseFloat(pct) >= 95 ? 'yellow' : 'red');
|
||
|
||
// Bars
|
||
document.getElementById('bar-up').style.width = pct + '%';
|
||
document.getElementById('bar-up-pct').textContent = pct + '%';
|
||
document.getElementById('bar-down').style.width = downPct + '%';
|
||
document.getElementById('bar-down-pct').textContent = downPct + '%';
|
||
|
||
// Stats
|
||
document.getElementById('stat-uptime').textContent = fmtMs(d.totalUptimeMs);
|
||
document.getElementById('stat-downtime').textContent = fmtMs(d.totalDowntimeMs);
|
||
document.getElementById('stat-count').textContent = d.outageCount;
|
||
|
||
const completed = d.outages;
|
||
const avgMs = completed.length > 0 ? completed.reduce((a, b) => a + b.duration, 0) / completed.length : 0;
|
||
const maxMs = completed.length > 0 ? Math.max(...completed.map(o => o.duration)) : 0;
|
||
document.getElementById('stat-avg-max').textContent =
|
||
completed.length ? fmtMs(avgMs) + ' / ' + fmtMs(maxMs) : '–';
|
||
|
||
// Table
|
||
const tbody = document.getElementById('outage-table');
|
||
const allOutages = [...d.outages];
|
||
if (!d.isOnline && d.currentOutageStart) {
|
||
allOutages.unshift({ start: d.currentOutageStart, end: null, duration: Date.now() - d.currentOutageStart });
|
||
}
|
||
|
||
if (allOutages.length === 0) {
|
||
tbody.innerHTML = '';
|
||
document.getElementById('no-outages').style.display = '';
|
||
} else {
|
||
document.getElementById('no-outages').style.display = 'none';
|
||
tbody.innerHTML = allOutages.map((o, i) =>
|
||
'<tr>' +
|
||
'<td style="color:#64748b">#' + (allOutages.length - i) + '</td>' +
|
||
'<td>' + fmtDate(o.start) + '</td>' +
|
||
'<td>' + (o.end ? fmtDate(o.end) : '<span style="color:#f87171;font-weight:600">Ongoing</span>') + '</td>' +
|
||
'<td style="font-family:monospace">' + fmtMs(o.duration) + '</td>' +
|
||
'</tr>'
|
||
).join('');
|
||
}
|
||
|
||
document.getElementById('last-updated').textContent =
|
||
'Last updated ' + new Date().toLocaleTimeString() +
|
||
' · checks every ' + (checkIntervalMs / 1000) + 's';
|
||
|
||
} catch (e) {
|
||
document.getElementById('status-text').textContent = 'Error';
|
||
}
|
||
}
|
||
|
||
refresh();
|
||
setInterval(refresh, 1000);
|
||
|
||
// ── Export menu ───────────────────────────────────────────────────────────
|
||
function toggleExportMenu(e) {
|
||
e.stopPropagation();
|
||
document.getElementById('export-menu').classList.toggle('open');
|
||
}
|
||
document.addEventListener('click', () => {
|
||
document.getElementById('export-menu').classList.remove('open');
|
||
});
|
||
|
||
// ── Settings ─────────────────────────────────────────────────────────────
|
||
function openSettings() {
|
||
fetch('/api/settings').then(r => r.json()).then(s => {
|
||
document.getElementById('inp-interval').value = s.checkIntervalMs / 1000;
|
||
document.getElementById('inp-url').value = s.checkUrl;
|
||
document.getElementById('settings-overlay').classList.add('open');
|
||
});
|
||
}
|
||
function closeSettings() {
|
||
document.getElementById('settings-overlay').classList.remove('open');
|
||
}
|
||
function closeSettingsOnOverlay(e) {
|
||
if (e.target === document.getElementById('settings-overlay')) closeSettings();
|
||
}
|
||
async function saveSettings() {
|
||
const intervalSec = parseFloat(document.getElementById('inp-interval').value);
|
||
const url = document.getElementById('inp-url').value.trim();
|
||
if (!intervalSec || intervalSec < 1) return alert('Interval must be at least 1 second.');
|
||
if (!url) return alert('URL cannot be empty.');
|
||
const res = await fetch('/api/settings', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ checkIntervalMs: Math.round(intervalSec * 1000), checkUrl: url })
|
||
});
|
||
if (res.ok) {
|
||
const s = await res.json();
|
||
checkIntervalMs = s.checkIntervalMs;
|
||
closeSettings();
|
||
const toast = document.getElementById('toast');
|
||
toast.classList.add('show');
|
||
setTimeout(() => toast.classList.remove('show'), 2500);
|
||
} else {
|
||
const err = await res.json().catch(() => ({}));
|
||
alert('Failed to save settings: ' + (err.error || res.status));
|
||
}
|
||
}
|
||
</script>
|
||
</body>
|
||
</html>`);
|
||
});
|
||
|
||
// Monitor API
|
||
app.get('/api/status', (req, res) => {
|
||
const uptimeMs = Date.now() - monitorStartTime;
|
||
const currentDowntime = !isOnline && outageStart ? Date.now() - outageStart : 0;
|
||
const totalDown = totalDowntimeMs + currentDowntime;
|
||
res.json({
|
||
isOnline,
|
||
monitorStartTime,
|
||
uptimeMs,
|
||
totalDowntimeMs: totalDown,
|
||
totalUptimeMs: uptimeMs - totalDown,
|
||
outageCount: outages.length + (!isOnline ? 1 : 0),
|
||
currentOutageStart: outageStart,
|
||
outages: outages.slice().reverse(),
|
||
checkIntervalMs,
|
||
checkUrl
|
||
});
|
||
});
|
||
|
||
// Export as JSON
|
||
app.get('/export/json', (req, res) => {
|
||
const uptimeMs = Date.now() - monitorStartTime;
|
||
const currentDowntime = !isOnline && outageStart ? Date.now() - outageStart : 0;
|
||
const totalDown = totalDowntimeMs + currentDowntime;
|
||
const allOutages = outages.slice().reverse();
|
||
if (!isOnline && outageStart) {
|
||
allOutages.unshift({ start: outageStart, end: null, duration: Date.now() - outageStart, ongoing: true });
|
||
}
|
||
const data = {
|
||
exportedAt: new Date().toISOString(),
|
||
monitorStartTime: new Date(monitorStartTime).toISOString(),
|
||
isOnline,
|
||
uptimePct: uptimeMs > 0 ? ((uptimeMs - totalDown) / uptimeMs * 100).toFixed(4) : '100.0000',
|
||
totalUptimeMs: uptimeMs - totalDown,
|
||
totalDowntimeMs: totalDown,
|
||
outageCount: outages.length + (!isOnline ? 1 : 0),
|
||
outages: allOutages.map(o => ({
|
||
start: new Date(o.start).toISOString(),
|
||
end: o.end ? new Date(o.end).toISOString() : null,
|
||
durationMs: o.duration,
|
||
durationFormatted: formatDuration(o.duration),
|
||
ongoing: !!o.ongoing
|
||
}))
|
||
};
|
||
const filename = `uptime-stats-${new Date().toISOString().replace(/[:.]/g, '-')}.json`;
|
||
res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
|
||
res.setHeader('Content-Type', 'application/json');
|
||
res.send(JSON.stringify(data, null, 2));
|
||
});
|
||
|
||
// Export as CSV
|
||
app.get('/export/csv', (req, res) => {
|
||
const uptimeMs = Date.now() - monitorStartTime;
|
||
const currentDowntime = !isOnline && outageStart ? Date.now() - outageStart : 0;
|
||
const totalDown = totalDowntimeMs + currentDowntime;
|
||
const uptimePct = uptimeMs > 0 ? ((uptimeMs - totalDown) / uptimeMs * 100).toFixed(4) : '100.0000';
|
||
const allOutages = outages.slice().reverse();
|
||
if (!isOnline && outageStart) {
|
||
allOutages.unshift({ start: outageStart, end: null, duration: Date.now() - outageStart, ongoing: true });
|
||
}
|
||
|
||
const lines = [
|
||
'# Uptime Monitor Export',
|
||
`# Exported At,${new Date().toISOString()}`,
|
||
`# Monitor Start,${new Date(monitorStartTime).toISOString()}`,
|
||
`# Current Status,${isOnline ? 'Online' : 'Offline'}`,
|
||
`# Uptime %,${uptimePct}%`,
|
||
`# Total Uptime,${formatDuration(uptimeMs - totalDown)}`,
|
||
`# Total Downtime,${formatDuration(totalDown)}`,
|
||
`# Outage Count,${allOutages.length}`,
|
||
'',
|
||
'#,Start,End,Duration (ms),Duration,Ongoing'
|
||
];
|
||
|
||
allOutages.forEach((o, i) => {
|
||
const cols = [
|
||
i + 1,
|
||
new Date(o.start).toISOString(),
|
||
o.end ? new Date(o.end).toISOString() : '',
|
||
o.duration,
|
||
formatDuration(o.duration),
|
||
o.ongoing ? 'Yes' : 'No'
|
||
];
|
||
lines.push(cols.join(','));
|
||
});
|
||
|
||
if (allOutages.length === 0) lines.push('No outages recorded');
|
||
|
||
const filename = `uptime-stats-${new Date().toISOString().replace(/[:.]/g, '-')}.csv`;
|
||
res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
|
||
res.setHeader('Content-Type', 'text/csv');
|
||
res.send(lines.join('\r\n'));
|
||
});
|
||
|
||
// Settings API
|
||
app.get('/api/settings', (req, res) => {
|
||
res.json({ checkIntervalMs, checkUrl });
|
||
});
|
||
|
||
app.post('/api/settings', (req, res) => {
|
||
const { checkIntervalMs: newInterval, checkUrl: newUrl } = req.body || {};
|
||
if (newInterval !== undefined) {
|
||
const ms = parseInt(newInterval, 10);
|
||
if (isNaN(ms) || ms < 1000) {
|
||
return res.status(400).json({ error: 'checkIntervalMs must be >= 1000' });
|
||
}
|
||
checkIntervalMs = ms;
|
||
restartMonitor();
|
||
}
|
||
if (newUrl !== undefined) {
|
||
try {
|
||
const u = new URL(newUrl);
|
||
if (u.protocol !== 'http:' && u.protocol !== 'https:') throw new Error();
|
||
} catch (e) {
|
||
return res.status(400).json({ error: 'checkUrl must be a valid http/https URL' });
|
||
}
|
||
checkUrl = newUrl;
|
||
}
|
||
res.json({ checkIntervalMs, checkUrl });
|
||
});
|
||
|
||
// ─── Start ────────────────────────────────────────────────────────────────────
|
||
|
||
app.listen(PORT, () => {
|
||
console.log(`Server running at http://localhost:${PORT}`);
|
||
});
|