Files
UptimeMonitor/index.js
T

525 lines
19 KiB
JavaScript
Raw Normal View History

const express = require('express');
const https = require('https');
const app = express();
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 ───────────────────────────────────────────────────
const CHECK_INTERVAL_MS = 5000;
const CHECK_URL = 'https://www.google.com';
let isOnline = true;
let outageStart = null;
const outages = [];
let monitorStartTime = Date.now();
let totalDowntimeMs = 0;
function checkConnectivity() {
return new Promise((resolve) => {
const req = https.get(CHECK_URL, { 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`;
}
setInterval(monitor, CHECK_INTERVAL_MS);
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; }
</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>
<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>
<script>
const CHECK_INTERVAL_MS = ${CHECK_INTERVAL_MS};
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 ' + (CHECK_INTERVAL_MS / 1000) + 's';
} catch (e) {
document.getElementById('status-text').textContent = 'Error';
}
}
refresh();
setInterval(refresh, 1000);
</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: CHECK_INTERVAL_MS
});
});
// 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'));
});
// ─── Start ────────────────────────────────────────────────────────────────────
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});