Files
UptimeMonitor/index.js
T

1504 lines
61 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
const express = require('express');
const https = require('https');
const http = require('http');
const fs = require('fs');
const path = require('path');
const app = express();
app.use(express.json());
const PORT = 3010;
// ─── Persistence ──────────────────────────────────────────────────────────────
const DATA_FILE = path.join(__dirname, 'data.json');
function loadState() {
try {
if (fs.existsSync(DATA_FILE)) {
const raw = fs.readFileSync(DATA_FILE, 'utf8');
return JSON.parse(raw);
}
} catch (e) {
console.warn('Could not load persisted state:', e.message);
}
return null;
}
function saveState() {
const state = {
checkIntervalMs,
dateFormat,
timeFormat,
localIpHistory,
publicIpHistory,
targets: targets.map(t => ({
id: t.id, url: t.url, label: t.label,
isOnline: t.isOnline, outageStart: t.outageStart,
outages: t.outages, totalDowntimeMs: t.totalDowntimeMs,
monitorStartTime: t.monitorStartTime
}))
};
fs.writeFile(DATA_FILE, JSON.stringify(state, null, 2), (err) => {
if (err) console.warn('Could not save state:', err.message);
});
}
const os = require('os');
const { execFile } = require('child_process');
// ─── IP / Network 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'));
});
}
function getAdapterForIP(ip) {
const ifaces = os.networkInterfaces();
for (const [name, addrs] of Object.entries(ifaces)) {
if (addrs && addrs.some(a => a.address === ip)) return name;
}
return 'Unknown';
}
function getWifiSSID() {
return new Promise((resolve) => {
if (process.platform !== 'win32') return resolve(null);
execFile('netsh', ['wlan', 'show', 'interfaces'], { timeout: 3000 }, (err, stdout) => {
if (err) return resolve(null);
const m = stdout.match(/^\s+SSID\s+:\s+(.+)$/m);
resolve(m ? m[1].trim() : null);
});
});
}
async function getNetworkInfo(localIp) {
const adapter = getAdapterForIP(localIp);
const lc = adapter.toLowerCase();
const isWifi = lc.includes('wi-fi') || lc.includes('wifi') ||
lc.includes('wlan') || lc.includes('wireless');
let network;
if (isWifi) {
const ssid = await getWifiSSID();
network = ssid || adapter;
} else {
network = adapter;
}
return { adapter, network };
}
// ─── Internet Monitor State ───────────────────────────────────────────────────
// Per-target log throttle to suppress flapping spam.
// Stores { lastType: 'disc'|'rest', lastAt: ms, suppressed: n } keyed by target id.
const logThrottle = {};
const LOG_COOLDOWN_MS = 30_000; // max one log of the same event type per target per 30 s
function throttledLog(targetId, type, msg) {
const now = Date.now();
const s = logThrottle[targetId] || (logThrottle[targetId] = { lastType: null, lastAt: 0, suppressed: 0 });
const ts = `[${new Date(now).toISOString()}]`;
if (s.lastType === type && (now - s.lastAt) < LOG_COOLDOWN_MS) {
s.suppressed++;
return;
}
// If switching event type and we suppressed some, report the count first
if (s.suppressed > 0) {
console.log(`${ts} ... (${s.suppressed} duplicate event${s.suppressed !== 1 ? 's' : ''} suppressed)`);
}
console.log(`${ts} ${msg}`);
s.lastType = type;
s.lastAt = now;
s.suppressed = 0;
}
let checkIntervalMs = 5000;
let dateFormat = 'locale';
let timeFormat = '24h';
let targets = [];
let intervalId = null;
let monitoringPaused = false;
// ─── IP History ───────────────────────────────────────────────────────────────
// Each entry: { ip, since, until } (until=null means currently active)
let localIpHistory = [];
let publicIpHistory = [];
let ipPollId = null;
function recordIp(history, newIp, extra) {
const now = Date.now();
const last = history.length > 0 ? history[history.length - 1] : null;
if (last && last.ip === newIp &&
last.adapter === (extra && extra.adapter) &&
last.network === (extra && extra.network)) return false;
if (last && last.until === null) last.until = now;
history.push(Object.assign({ ip: newIp, since: now, until: null }, extra || {}));
return true;
}
async function pollIPs() {
const [local, pub] = await Promise.all([getLocalIP(), getPublicIP()]);
const netInfo = await getNetworkInfo(local);
const localChanged = recordIp(localIpHistory, local, netInfo);
const pubChanged = recordIp(publicIpHistory, pub);
if (localChanged || pubChanged) saveState();
}
function makeTarget(url, label) {
return {
id: Date.now().toString(36) + Math.random().toString(36).slice(2, 6),
url,
label: label || url,
isOnline: true,
outageStart: null,
outages: [],
totalDowntimeMs: 0,
monitorStartTime: Date.now()
};
}
// Restore persisted state
{
const saved = loadState();
if (saved) {
if (typeof saved.checkIntervalMs === 'number' && saved.checkIntervalMs >= 1000) checkIntervalMs = saved.checkIntervalMs;
if (typeof saved.dateFormat === 'string') dateFormat = saved.dateFormat;
else if (typeof saved.dateTimeFormat === 'string') dateFormat = saved.dateTimeFormat; // migrate old setting
if (typeof saved.timeFormat === 'string') timeFormat = saved.timeFormat;
if (Array.isArray(saved.localIpHistory)) localIpHistory = saved.localIpHistory;
if (Array.isArray(saved.publicIpHistory)) publicIpHistory = saved.publicIpHistory;
if (Array.isArray(saved.targets) && saved.targets.length > 0) {
targets = saved.targets.map(t => ({
id: t.id || Date.now().toString(36) + Math.random().toString(36).slice(2, 6),
url: t.url,
label: t.label || t.url,
isOnline: typeof t.isOnline === 'boolean' ? t.isOnline : true,
outageStart: t.outageStart || null,
outages: Array.isArray(t.outages) ? t.outages : [],
totalDowntimeMs: typeof t.totalDowntimeMs === 'number' ? t.totalDowntimeMs : 0,
monitorStartTime: typeof t.monitorStartTime === 'number' ? t.monitorStartTime : Date.now()
}));
} else if (typeof saved.checkUrl === 'string' && saved.checkUrl) {
// Migrate from old single-URL format
const t = makeTarget(saved.checkUrl);
if (typeof saved.monitorStartTime === 'number') t.monitorStartTime = saved.monitorStartTime;
if (typeof saved.totalDowntimeMs === 'number') t.totalDowntimeMs = saved.totalDowntimeMs;
if (Array.isArray(saved.outages)) t.outages = saved.outages;
targets = [t];
}
console.log(`Loaded ${targets.length} target(s)`);
}
if (targets.length === 0) targets = [makeTarget('https://www.google.com')];
}
function checkConnectivity(url) {
return new Promise((resolve) => {
const mod = url.startsWith('https://') ? https : http;
const req = mod.get(url, { timeout: 4000 }, (res) => {
res.resume();
resolve(true);
});
req.on('error', () => resolve(false));
req.on('timeout', () => { req.destroy(); resolve(false); });
});
}
let internetDown = false;
async function monitor() {
const changed = [];
await Promise.all(targets.map(async (t) => {
const online = await checkConnectivity(t.url);
if (!online && t.isOnline) {
t.isOnline = false;
t.outageStart = Date.now();
changed.push({ t, event: 'disc' });
saveState();
} else if (online && !t.isOnline) {
const end = Date.now();
const duration = end - t.outageStart;
t.totalDowntimeMs += duration;
t.outages.push({ start: t.outageStart, end, duration });
t.isOnline = true;
t.outageStart = null;
changed.push({ t, event: 'rest', duration });
saveState();
}
}));
if (changed.length === 0) return;
const allDown = targets.length > 0 && targets.every(t => !t.isOnline);
const allUp = targets.length > 0 && targets.every(t => t.isOnline);
if (allDown && !internetDown) {
internetDown = true;
console.log(`[${new Date().toISOString()}] INTERNET DOWN`);
} else if (allUp && internetDown) {
internetDown = false;
console.log(`[${new Date().toISOString()}] INTERNET RESTORED`);
} else {
// Partial change — log per target, but skip targets that are part of an ongoing internet outage
for (const { t, event, duration } of changed) {
if (event === 'disc' && !internetDown) {
throttledLog(t.id, 'disc', `${t.label} DISCONNECTED`);
} else if (event === 'rest' && !internetDown) {
throttledLog(t.id, 'rest', `${t.label} RESTORED (outage: ${formatDuration(duration)})`);
}
}
}
}
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);
if (!monitoringPaused) intervalId = setInterval(monitor, checkIntervalMs);
}
restartMonitor();
monitor();
// Start IP polling (every 30 seconds)
pollIPs();
ipPollId = setInterval(pollIPs, 30000);
// ─── 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; }
html { background: #0f172a; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
background: #0f172a;
color: #e2e8f0;
min-height: 100vh;
padding: 2rem;
max-width: 1440px;
margin: 0 auto;
}
/* ── 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 + Targets side by side ── */
.top-row {
display: grid;
grid-template-columns: minmax(220px, 1fr) 2fr;
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: 1fr 1fr 0.667fr 0.667fr 0.667fr;
gap: 1rem;
margin-bottom: 1.25rem;
}
@media (max-width: 900px) { .stats-grid { grid-template-columns: repeat(2, 1fr); } }
@media (max-width: 480px) { .stats-grid { grid-template-columns: 1fr; } }
.stat-card {
background: #1e293b;
border: 1px solid #334155;
border-radius: 14px;
padding: 1.25rem 1.5rem;
}
.stat-card--up { background: #0d2818; border-color: #166534; }
.stat-card--down { background: #1c0808; border-color: #7f1d1d; }
.stat-label { font-size: 0.7rem; color: #64748b; text-transform: uppercase; letter-spacing: 0.06em; margin-bottom: 0.5rem; }
.stat-val { font-size: 1.75rem; font-weight: 700; }
.stat-sub-pct { font-size: 0.82rem; font-weight: 600; margin-top: 0.3rem; margin-bottom: 0.5rem; }
.stat-bar-bg { height: 6px; background: #334155; border-radius: 999px; overflow: hidden; margin-top: 0.5rem; }
.stat-bar-fill { height: 100%; border-radius: 999px; transition: width 0.6s; }
.stat-bar-fill--up { background: #4ade80; }
.stat-bar-fill--down { background: #f87171; }
/* 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; }
.pagination {
display: flex; align-items: center; justify-content: space-between;
padding: 0.55rem 1.25rem; border-top: 1px solid #334155;
font-size: 0.78rem; color: #64748b;
}
.pagination-btns { display: flex; gap: 0.35rem; }
.pg-btn {
background: #1e293b; border: 1px solid #334155; color: #94a3b8;
border-radius: 6px; padding: 0.25rem 0.6rem; cursor: pointer; font-size: 0.78rem;
}
.pg-btn:hover:not(:disabled) { background: #243044; color: #e2e8f0; }
.pg-btn:disabled { opacity: 0.35; cursor: default; }
.pg-btn.active { background: #0f172a; border-color: #3b82f6; color: #3b82f6; }
/* IP History */
.ip-history-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1rem;
margin-bottom: 1rem;
}
@media (max-width: 640px) { .ip-history-grid { grid-template-columns: 1fr; } }
.ip-history-current {
font-family: monospace;
font-size: 0.92rem;
background: #0f172a;
padding: 0.2rem 0.6rem;
border-radius: 5px;
color: #e2e8f0;
}
/* Footer */
#last-updated { font-size: 0.72rem; color: #475569; margin-bottom: 0.6rem; }
/* 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; }
.pause-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, border-color 0.15s;
}
.pause-btn:hover { background: #243044; }
.pause-btn.paused { border-color: #f59e0b; color: #fbbf24; }
.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; }
/* Target cards */
.targets-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
gap: 1rem;
margin-bottom: 1rem;
}
.target-badge {
display: inline-flex; align-items: center; gap: 0.3rem;
padding: 0.2rem 0.55rem; border-radius: 999px;
font-size: 0.72rem; font-weight: 600;
}
.target-badge.online { background: #14532d; color: #4ade80; }
.target-badge.offline { background: #450a0a; color: #f87171; }
#targets-table td { padding: 0.55rem 1.25rem; }
#targets-table tbody tr:hover td { background: #243044; }
.tgt-label { font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 120px; }
.tgt-url { font-size: 0.72rem; color: #64748b; font-family: monospace; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 200px; }
.tgt-pct { font-weight: 700; }
/* URL list in settings modal */
.url-list { display: flex; flex-direction: column; gap: 0.5rem; margin-bottom: 0.5rem; }
.url-row { display: flex; gap: 0.4rem; align-items: center; }
.url-label-input { width: 110px !important; flex: none !important; }
.btn-remove {
background: transparent; border: 1px solid #334155; color: #f87171;
border-radius: 6px; padding: 0.45rem 0.55rem; cursor: pointer;
font-size: 0.85rem; transition: background 0.12s; flex-shrink: 0;
}
.btn-remove:hover { background: #450a0a; }
.btn-move {
background: transparent; border: 1px solid #334155; color: #64748b;
border-radius: 6px; padding: 0.35rem 0.45rem; cursor: pointer;
font-size: 0.7rem; line-height: 1; transition: background 0.12s; flex-shrink: 0;
}
.btn-move:hover:not(:disabled) { background: #1e3a5f; color: #93c5fd; }
.btn-move:disabled { opacity: 0.2; cursor: default; }
.url-order-btns { display: flex; flex-direction: column; gap: 2px; }
.btn-add-url {
background: transparent; border: 1px dashed #334155; color: #64748b;
border-radius: 8px; padding: 0.45rem 1rem; cursor: pointer;
font-size: 0.8rem; width: 100%; transition: all 0.12s;
}
.btn-add-url:hover { border-color: #6366f1; color: #a5b4fc; }
.modal { max-width: 540px !important; max-height: 90vh; overflow-y: auto; }
/* ── Last-Hour History Bar ── */
.history-bar-wrap {
background: #1e293b;
border: 1px solid #334155;
border-radius: 14px;
padding: 1rem 1.5rem;
margin-bottom: 1rem;
}
.history-bar-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 0.5rem;
}
.history-bar-title {
font-size: 0.7rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.07em;
color: #64748b;
}
.history-bar-legend {
display: flex;
gap: 0.85rem;
align-items: center;
font-size: 0.7rem;
color: #64748b;
}
.history-bar-legend span { display: flex; align-items: center; gap: 0.3rem; }
.legend-dot { width: 8px; height: 8px; border-radius: 2px; display: inline-block; }
.history-bar {
width: 100%;
height: 28px;
border-radius: 6px;
overflow: hidden;
display: flex;
background: #334155;
}
.history-bar-seg--up { background: #4ade80; height: 100%; }
.history-bar-seg--down { background: #f87171; height: 100%; }
.history-bar-seg--unknown { background: #334155; height: 100%; }
.history-bar-timestamps {
display: flex;
justify-content: space-between;
margin-top: 0.35rem;
font-size: 0.68rem;
color: #475569;
}
.history-range-btns { display: flex; gap: 0.25rem; }
.history-range-btn {
background: #0f172a;
border: 1px solid #334155;
color: #64748b;
border-radius: 6px;
padding: 0.2rem 0.55rem;
font-size: 0.72rem;
font-weight: 600;
cursor: pointer;
transition: background 0.12s, color 0.12s, border-color 0.12s;
}
.history-range-btn:hover { background: #1e3a5f; color: #93c5fd; }
.history-range-btn.active { background: #1e3a5f; border-color: #3b82f6; color: #3b82f6; }
</style>
</head>
<body>
<header>
<div style="flex:1">
<h1>Network Dashboard</h1>
<div class="subtitle" id="monitor-since">Loading...</div>
</div>
<div style="display:flex;align-items:center;gap:0.75rem;margin-left:auto">
<div id="status-badge" class="online"><div class="dot"></div><span id="status-text">Checking…</span></div>
<button class="pause-btn" id="pause-btn" onclick="toggleMonitor()">&#9646;&#9646; Pause</button>
<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>
</div>
</header>
<!-- Connectivity History Bar -->
<div class="history-bar-wrap">
<div class="history-bar-header">
<span class="history-bar-title">Connectivity History</span>
<div class="history-range-btns">
<button class="history-range-btn active" data-range="3600000" onclick="setHistoryRange(3600000)">1H</button>
<button class="history-range-btn" data-range="86400000" onclick="setHistoryRange(86400000)">24H</button>
<button class="history-range-btn" data-range="2592000000" onclick="setHistoryRange(2592000000)">30D</button>
<button class="history-range-btn" data-range="null" onclick="setHistoryRange(null)">All</button>
</div>
<div class="history-bar-legend">
<span><span class="legend-dot" style="background:#4ade80"></span>Online</span>
<span><span class="legend-dot" style="background:#f87171"></span>Offline</span>
<span><span class="legend-dot" style="background:#334155"></span>No data</span>
</div>
</div>
<div class="history-bar" id="history-bar"></div>
<div class="history-bar-timestamps">
<span id="history-bar-start"></span>
<span id="history-bar-end"></span>
</div>
</div>
<!-- Stats row -->
<div class="stats-grid">
<div class="stat-card stat-card--up">
<div class="stat-label">Total Uptime</div>
<div class="stat-val green" id="stat-uptime-pct"></div>
<div class="stat-sub-pct green" id="stat-uptime">–</div>
<div class="stat-bar-bg"><div class="stat-bar-fill stat-bar-fill--up" id="stat-uptime-bar" style="width:0%"></div></div>
</div>
<div class="stat-card stat-card--down">
<div class="stat-label">Total Downtime</div>
<div class="stat-val red" id="stat-downtime-pct"></div>
<div class="stat-sub-pct red" id="stat-downtime">–</div>
<div class="stat-bar-bg"><div class="stat-bar-fill stat-bar-fill--down" id="stat-downtime-bar" style="width:0%"></div></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 Outage</div>
<div class="stat-val" id="stat-avg">–</div>
</div>
<div class="stat-card">
<div class="stat-label">Longest Outage</div>
<div class="stat-val" id="stat-max">–</div>
</div>
</div>
<!-- Network Info + Targets summary -->
<div class="top-row">
<div class="panel">
<div class="panel-title">Network Info</div>
<div id="last-updated"></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">Adapter</span>
<span class="ip-val" id="net-adapter">…</span>
</div>
<div class="ip-row">
<span class="ip-label">Network</span>
<span class="ip-val" id="net-name">…</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="table-wrap">
<div class="table-header">Targets</div>
<table id="targets-table">
<thead><tr><th>Label</th><th>URL</th><th>Status</th><th>Uptime</th><th>Outages</th><th>Downtime</th></tr></thead>
<tbody id="targets-summary"></tbody>
</table>
<div class="no-outages" id="no-targets" style="display:none">No targets configured.</div>
<div class="pagination" id="pg-targets" style="display:none">
<span id="pg-targets-info"></span>
<div class="pagination-btns" id="pg-targets-btns"></div>
</div>
</div>
</div>
<!-- Outage history -->
<div class="ip-history-grid">
<div class="table-wrap">
<div class="table-header">Local IP History</div>
<table>
<thead><tr><th>IP Address</th><th>Network</th><th>Adapter</th><th>Since</th><th>Until</th><th>Duration</th></tr></thead>
<tbody id="local-ip-table"></tbody>
</table>
<div class="no-outages" id="no-local-ip">Gathering data…</div>
<div class="pagination" id="pg-local-ip" style="display:none">
<span id="pg-local-ip-info"></span>
<div class="pagination-btns" id="pg-local-ip-btns"></div>
</div>
</div>
<div class="table-wrap">
<div class="table-header">Public IP History</div>
<table>
<thead><tr><th>IP Address</th><th>Since</th><th>Until</th><th>Duration</th></tr></thead>
<tbody id="public-ip-table"></tbody>
</table>
<div class="no-outages" id="no-public-ip">Gathering data…</div>
<div class="pagination" id="pg-public-ip" style="display:none">
<span id="pg-public-ip-info"></span>
<div class="pagination-btns" id="pg-public-ip-btns"></div>
</div>
</div>
</div>
<div class="table-wrap">
<div class="table-header">Outage History</div>
<table>
<thead>
<tr><th>#</th><th>Target</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 class="pagination" id="pg-outage" style="display:none">
<span id="pg-outage-info"></span>
<div class="pagination-btns" id="pg-outage-btns"></div>
</div>
</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-dtf">Date Format</label>
<select class="form-input" id="inp-dtf">
<option value="locale">Browser default (locale)</option>
<option value="iso">ISO 8601 &mdash; YYYY-MM-DD</option>
<option value="us">US &mdash; MM/DD/YYYY</option>
<option value="eu">European &mdash; DD/MM/YYYY</option>
<option value="dot">DD.MM.YYYY</option>
<option value="ymd">YYYY/MM/DD</option>
</select>
</div>
<div class="form-group">
<label class="form-label" for="inp-timef">Time Format</label>
<select class="form-input" id="inp-timef">
<option value="24h">24-hour &mdash; HH:mm:ss</option>
<option value="12h">12-hour &mdash; hh:mm:ss AM/PM</option>
</select>
</div>
<div class="form-group">
<label class="form-label">Targets <span style="color:#475569;font-weight:400;text-transform:none;letter-spacing:0">(label, url)</span></label>
<div class="url-list" id="target-list"></div>
<button class="btn-add-url" onclick="addTarget()">+ Add URL</button>
</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};
let dateFormat = '${dateFormat}';
let timeFormat = '${timeFormat}';
const PAGE_SIZE = 10;
const pgState = { outage: 1, 'local-ip': 1, 'public-ip': 1, targets: 1 };
let lastOutageRows = [];
let lastLocalIp = [];
let lastPublicIp = [];
let lastTargets = [];
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) {
const d = new Date(ts);
const p = v => String(v).padStart(2, '0');
let datePart;
switch (dateFormat) {
case 'iso': datePart = d.getFullYear() + '-' + p(d.getMonth()+1) + '-' + p(d.getDate()); break;
case 'us': datePart = p(d.getMonth()+1) + '/' + p(d.getDate()) + '/' + d.getFullYear(); break;
case 'eu': datePart = p(d.getDate()) + '/' + p(d.getMonth()+1) + '/' + d.getFullYear(); break;
case 'dot': datePart = p(d.getDate()) + '.' + p(d.getMonth()+1) + '.' + d.getFullYear(); break;
case 'ymd': datePart = d.getFullYear() + '/' + p(d.getMonth()+1) + '/' + p(d.getDate()); break;
default: return timeFormat === '12h'
? d.toLocaleString([], { hour12: true })
: d.toLocaleString([], { hour12: false });
}
let timePart;
if (timeFormat === '12h') {
let h = d.getHours();
const ampm = h >= 12 ? 'PM' : 'AM';
h = h % 12 || 12;
timePart = p(h) + ':' + p(d.getMinutes()) + ':' + p(d.getSeconds()) + ' ' + ampm;
} else {
timePart = p(d.getHours()) + ':' + p(d.getMinutes()) + ':' + p(d.getSeconds());
}
return datePart + ' ' + timePart;
}
function pctColor(p) { return p >= 99 ? 'green' : p >= 95 ? 'yellow' : 'red'; }
async function refresh() {
try {
const d = await fetch('/api/status').then(r => r.json());
checkIntervalMs = d.checkIntervalMs;
// Pause button state
const pauseBtn = document.getElementById('pause-btn');
if (d.monitoringPaused) {
pauseBtn.classList.add('paused');
pauseBtn.innerHTML = '&#9654; Resume';
} else {
pauseBtn.classList.remove('paused');
pauseBtn.innerHTML = '&#9646;&#9646; Pause';
}
// Overall status badge: online only if all targets online
const allOnline = d.targets.every(t => t.isOnline);
const offlineCount = d.targets.filter(t => !t.isOnline).length;
const badge = document.getElementById('status-badge');
badge.className = allOnline ? 'online' : 'offline';
document.getElementById('status-text').textContent =
allOnline ? 'Online' : offlineCount + '/' + d.targets.length + ' Offline';
const earliest = Math.min(...d.targets.map(t => t.monitorStartTime));
document.getElementById('monitor-since').textContent =
'Monitoring since ' + fmtDate(earliest);
// Targets panel
lastTargets = d.targets;
renderTargetPage();
// Aggregate stats
const totalOutages = d.targets.reduce((s, t) => s + t.outageCount, 0);
const allOutagesList = d.targets.flatMap(t => t.outages);
const avgMs = allOutagesList.length > 0 ? allOutagesList.reduce((s, o) => s + o.duration, 0) / allOutagesList.length : 0;
const maxMs = allOutagesList.length > 0 ? Math.max(...allOutagesList.map(o => o.duration)) : 0;
const n = d.targets.length || 1;
const totalUptimeMs = d.targets.reduce((s, t) => s + t.totalUptimeMs, 0) / n;
const totalDowntimeMs = d.targets.reduce((s, t) => s + t.totalDowntimeMs, 0) / n;
const totalMonitorMs = d.targets.reduce((s, t) => s + t.uptimeMs, 0) / n;
const uptimePct = totalMonitorMs > 0 ? totalUptimeMs / totalMonitorMs * 100 : 100;
const downtimePct = totalMonitorMs > 0 ? totalDowntimeMs / totalMonitorMs * 100 : 0;
document.getElementById('stat-uptime').textContent = fmtMs(totalUptimeMs);
document.getElementById('stat-downtime').textContent = fmtMs(totalDowntimeMs);
document.getElementById('stat-uptime-pct').textContent = uptimePct.toFixed(2) + '%';
document.getElementById('stat-downtime-pct').textContent = downtimePct.toFixed(2) + '%';
document.getElementById('stat-uptime-bar').style.width = Math.min(uptimePct, 100).toFixed(2) + '%';
document.getElementById('stat-downtime-bar').style.width = Math.min(downtimePct, 100).toFixed(2) + '%';
document.getElementById('stat-count').textContent = totalOutages;
document.getElementById('stat-avg').textContent = allOutagesList.length ? fmtMs(avgMs) : '\u2013';
document.getElementById('stat-max').textContent = allOutagesList.length ? fmtMs(maxMs) : '\u2013';
// Outage table (all targets combined, newest first)
const tbody = document.getElementById('outage-table');
const rows = [];
d.targets.forEach(t => {
const list = t.outages.slice();
if (!t.isOnline && t.currentOutageStart) {
list.unshift({ start: t.currentOutageStart, end: null, duration: Date.now() - t.currentOutageStart });
}
list.forEach(o => rows.push(Object.assign({}, o, { targetLabel: t.label })));
});
rows.sort((a, b) => b.start - a.start);
if (rows.length === 0) {
document.getElementById('outage-table').innerHTML = '';
document.getElementById('no-outages').style.display = '';
document.getElementById('pg-outage').style.display = 'none';
} else {
document.getElementById('no-outages').style.display = 'none';
lastOutageRows = rows;
renderOutagePage();
}
document.getElementById('last-updated').textContent =
'Last updated ' + new Date().toLocaleTimeString() +
' \xb7 checks every ' + (checkIntervalMs / 1000) + 's';
// Last-hour history bar
renderHistoryBar(d.targets);
// IP History tables
// Update current adapter/network in Network Info panel
if (d.localIpHistory && d.localIpHistory.length > 0) {
const cur = d.localIpHistory[d.localIpHistory.length - 1];
document.getElementById('net-adapter').textContent = cur.adapter || '–';
document.getElementById('net-name').textContent = cur.network || '–';
}
renderIpTable('local-ip-table', 'no-local-ip', 'local-ip', d.localIpHistory, true);
renderIpTable('public-ip-table', 'no-public-ip', 'public-ip', d.publicIpHistory, false);
} catch (e) {
console.error('refresh() error:', e);
document.getElementById('status-text').textContent = 'Error';
}
}
let historyBarRange = 3600000; // ms; null = all time
function setHistoryRange(ms) {
historyBarRange = ms;
renderHistoryBar(lastTargets);
document.querySelectorAll('.history-range-btn').forEach(btn => {
const val = btn.dataset.range === 'null' ? null : Number(btn.dataset.range);
btn.classList.toggle('active', val === ms);
});
}
function renderHistoryBar(targets) {
const now = Date.now();
// Determine earliest monitor start (data before this is "unknown")
const dataStart = targets.length > 0
? Math.min(...targets.map(t => t.monitorStartTime))
: now;
// rangeStart: beginning of the window to display
const rangeStart = historyBarRange === null ? dataStart : now - historyBarRange;
// Collect down intervals overlapping the selected range from all targets
const downIntervals = [];
targets.forEach(t => {
t.outages.forEach(o => {
const s = Math.max(o.start, rangeStart);
const e = Math.min(o.end || now, now);
if (e > s) downIntervals.push({ start: s, end: e });
});
if (!t.isOnline && t.currentOutageStart) {
const s = Math.max(t.currentOutageStart, rangeStart);
if (now > s) downIntervals.push({ start: s, end: now });
}
});
// Sort and merge overlapping down intervals
downIntervals.sort((a, b) => a.start - b.start);
const merged = [];
for (const iv of downIntervals) {
if (!merged.length || iv.start > merged[merged.length - 1].end) {
merged.push({ start: iv.start, end: iv.end });
} else {
merged[merged.length - 1].end = Math.max(merged[merged.length - 1].end, iv.end);
}
}
// Build segments: unknown -> up/down alternation
const segments = [];
const knownStart = Math.max(rangeStart, dataStart);
// Gray "no data" segment before monitoring began
if (dataStart > rangeStart) {
segments.push({ type: 'unknown', start: rangeStart, end: knownStart });
}
let cursor = knownStart;
for (const iv of merged) {
if (iv.start > cursor) segments.push({ type: 'up', start: cursor, end: iv.start });
segments.push({ type: 'down', start: iv.start, end: iv.end });
cursor = iv.end;
}
if (cursor < now) segments.push({ type: 'up', start: cursor, end: now });
const totalMs = now - rangeStart;
const bar = document.getElementById('history-bar');
bar.innerHTML = segments.map(s => {
const pct = (s.end - s.start) / totalMs * 100;
return '<div class="history-bar-seg--' + s.type + '" style="width:' + pct.toFixed(3) + '%" title="' +
fmtDate(s.start) + ' – ' + fmtDate(s.end) + ' (' + s.type + ')"></div>';
}).join('');
document.getElementById('history-bar-start').textContent = fmtDate(rangeStart);
document.getElementById('history-bar-end').textContent = fmtDate(now);
}
refresh();
setInterval(refresh, 1000);
function renderPagination(key, total, renderFn) {
const pages = Math.max(1, Math.ceil(total / PAGE_SIZE));
if (pgState[key] > pages) pgState[key] = pages;
const cur = pgState[key];
const pgBar = document.getElementById('pg-' + key);
pgBar.style.display = total > PAGE_SIZE ? '' : 'none';
if (total <= PAGE_SIZE) { renderFn(1); return; }
document.getElementById('pg-' + key + '-info').textContent =
'Page ' + cur + ' of ' + pages + ' \xb7 ' + total + ' entries';
const btns = document.getElementById('pg-' + key + '-btns');
let html = '<button class="pg-btn" ' + (cur === 1 ? 'disabled' : '') +
' onclick="setPage(\\'' + key + '\\',1)">\xab</button>' +
'<button class="pg-btn" ' + (cur === 1 ? 'disabled' : '') +
' onclick="setPage(\\'' + key + '\\',' + (cur - 1) + ')">&lsaquo;</button>';
const range = 2;
for (let p = Math.max(1, cur - range); p <= Math.min(pages, cur + range); p++) {
html += '<button class="pg-btn' + (p === cur ? ' active' : '') + '" onclick="setPage(\\'' + key + '\\',' + p + ')">' + p + '</button>';
}
html += '<button class="pg-btn" ' + (cur === pages ? 'disabled' : '') +
' onclick="setPage(\\'' + key + '\\',' + (cur + 1) + ')">&rsaquo;</button>' +
'<button class="pg-btn" ' + (cur === pages ? 'disabled' : '') +
' onclick="setPage(\\'' + key + '\\',' + pages + ')">\xbb</button>';
btns.innerHTML = html;
renderFn(cur);
}
function setPage(key, page) {
pgState[key] = page;
if (key === 'outage') renderOutagePage();
else if (key === 'targets') renderTargetPage();
else if (key === 'local-ip') renderIpPage('local-ip-table', 'local-ip', lastLocalIp, true);
else if (key === 'public-ip') renderIpPage('public-ip-table', 'public-ip', lastPublicIp, false);
}
function renderTargetPage() {
const targets = lastTargets;
const tbody = document.getElementById('targets-summary');
const noEl = document.getElementById('no-targets');
noEl.style.display = targets.length === 0 ? '' : 'none';
document.getElementById('targets-table').style.display = targets.length === 0 ? 'none' : '';
renderPagination('targets', targets.length, (cur) => {
const start = (cur - 1) * PAGE_SIZE;
const pageTargets = targets.slice(start, start + PAGE_SIZE);
tbody.innerHTML = pageTargets.map(t => {
const pct = t.uptimeMs > 0 ? (t.totalUptimeMs / t.uptimeMs * 100).toFixed(2) : '100.00';
const cls = t.isOnline ? 'online' : 'offline';
const color = pctColor(parseFloat(pct));
const curDown = !t.isOnline && t.currentOutageStart ? Date.now() - t.currentOutageStart : 0;
return '<tr>' +
'<td><span class="tgt-label" title="' + t.label + '">' + t.label + '</span></td>' +
'<td><span class="tgt-url" title="' + t.url + '">' + t.url + '</span></td>' +
'<td><span class="target-badge ' + cls + '"><span class="dot"></span>' + (t.isOnline ? 'Online' : 'Offline') + '</span></td>' +
'<td><span class="tgt-pct ' + color + '">' + pct + '%</span></td>' +
'<td>' + t.outageCount + '</td>' +
'<td style="font-family:monospace">' + fmtMs(t.totalDowntimeMs + curDown) + (curDown ? ' <span style="color:#f87171;font-size:0.7rem">(ongoing)</span>' : '') + '</td>' +
'</tr>';
}).join('');
});
}
function renderOutagePage() {
const rows = lastOutageRows;
renderPagination('outage', rows.length, (cur) => {
const start = (cur - 1) * PAGE_SIZE;
const pageRows = rows.slice(start, start + PAGE_SIZE);
document.getElementById('outage-table').innerHTML = pageRows.map((o, i) =>
'<tr>' +
'<td style="color:#64748b">#' + (rows.length - start - i) + '</td>' +
'<td style="color:#94a3b8;font-size:0.78rem">' + o.targetLabel + '</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('');
});
}
function renderIpPage(tbodyId, key, rows, showNetwork) {
const now = Date.now();
renderPagination(key, rows.length, (cur) => {
const start = (cur - 1) * PAGE_SIZE;
const pageRows = rows.slice(start, start + PAGE_SIZE);
document.getElementById(tbodyId).innerHTML = pageRows.map((entry) => {
const duration = (entry.until || now) - entry.since;
const isCurrent = entry.until === null;
const currentBadge = isCurrent
? ' <span style="background:#14532d;color:#4ade80;font-size:0.7rem;padding:0.1rem 0.4rem;border-radius:999px;font-family:sans-serif">current</span>'
: '';
let row = '<tr><td style="font-family:monospace">' + entry.ip + currentBadge + '</td>';
if (showNetwork) {
row += '<td style="color:#e2e8f0">' + (entry.network || '\u2013') + '</td>' +
'<td style="color:#94a3b8;font-size:0.8rem">' + (entry.adapter || '\u2013') + '</td>';
}
row += '<td>' + fmtDate(entry.since) + '</td>' +
'<td>' + (entry.until ? fmtDate(entry.until) : '<span style="color:#4ade80">Now</span>') + '</td>' +
'<td style="font-family:monospace">' + fmtMs(duration) + '</td>' +
'</tr>';
return row;
}).join('');
});
}
function renderIpTable(tbodyId, emptyId, key, history, showNetwork) {
const empty = document.getElementById(emptyId);
if (!history || history.length === 0) {
document.getElementById(tbodyId).innerHTML = '';
empty.style.display = '';
document.getElementById('pg-' + key).style.display = 'none';
return;
}
empty.style.display = 'none';
const rows = history.slice().reverse();
if (key === 'local-ip') lastLocalIp = rows;
else lastPublicIp = rows;
renderIpPage(tbodyId, key, rows, showNetwork);
}
// ── Export menu ───────────────────────────────────────────────────────────
function toggleExportMenu(e) {
e.stopPropagation();
document.getElementById('export-menu').classList.toggle('open');
}
document.addEventListener('click', () => {
document.getElementById('export-menu').classList.remove('open');
});
// ── Pause / Resume ───────────────────────────────────────────────────────
async function toggleMonitor() {
const btn = document.getElementById('pause-btn');
const paused = btn.classList.contains('paused');
await fetch(paused ? '/api/monitor/resume' : '/api/monitor/pause', { method: 'POST' });
await refresh();
}
// ── Settings ─────────────────────────────────────────────────────────────
let settingsTargets = [];
function openSettings() {
fetch('/api/settings').then(r => r.json()).then(s => {
document.getElementById('inp-interval').value = s.checkIntervalMs / 1000;
document.getElementById('inp-dtf').value = s.dateFormat || 'locale';
document.getElementById('inp-timef').value = s.timeFormat || '24h';
settingsTargets = s.targets.map(t => Object.assign({}, t));
renderTargetList();
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();
}
function renderTargetList() {
const n = settingsTargets.length;
document.getElementById('target-list').innerHTML = settingsTargets.map((t, i) =>
'<div class="url-row">' +
'<div class="url-order-btns">' +
'<button class="btn-move" ' + (i === 0 ? 'disabled' : '') + ' onclick="moveTarget(' + i + ',-1)" title="Move up">\u25b4</button>' +
'<button class="btn-move" ' + (i === n - 1 ? 'disabled' : '') + ' onclick="moveTarget(' + i + ',1)" title="Move down">\u25be</button>' +
'</div>' +
'<input class="form-input url-label-input" placeholder="Label" value="' + (t.label !== t.url ? t.label : '') + '" oninput="settingsTargets[' + i + '].label=this.value">' +
'<input class="form-input url-inp" type="url" placeholder="https://..." value="' + t.url + '" oninput="settingsTargets[' + i + '].url=this.value;if(!settingsTargets[' + i + '].label)settingsTargets[' + i + '].label=this.value">' +
'<button class="btn-remove" onclick="removeTarget(' + i + ')">\u00d7</button>' +
'</div>'
).join('');
}
function moveTarget(i, dir) {
const j = i + dir;
if (j < 0 || j >= settingsTargets.length) return;
document.querySelectorAll('#target-list .url-row').forEach((row, idx) => {
settingsTargets[idx].url = row.querySelector('.url-inp').value.trim();
settingsTargets[idx].label = row.querySelector('.url-label-input').value.trim() || settingsTargets[idx].url;
});
const tmp = settingsTargets[i];
settingsTargets[i] = settingsTargets[j];
settingsTargets[j] = tmp;
renderTargetList();
}
function removeTarget(i) {
if (settingsTargets.length <= 1) return alert('At least one target is required.');
settingsTargets.splice(i, 1);
renderTargetList();
}
function addTarget() {
settingsTargets.push({ id: null, url: '', label: '' });
renderTargetList();
const inputs = document.querySelectorAll('#target-list .url-inp');
inputs[inputs.length - 1].focus();
}
async function saveSettings() {
const intervalSec = parseFloat(document.getElementById('inp-interval').value);
if (!intervalSec || intervalSec < 1) return alert('Interval must be at least 1 second.');
document.querySelectorAll('#target-list .url-row').forEach((row, i) => {
settingsTargets[i].url = row.querySelector('.url-inp').value.trim();
settingsTargets[i].label = row.querySelector('.url-label-input').value.trim() || settingsTargets[i].url;
});
for (const t of settingsTargets) {
if (!t.url) return alert('URL cannot be empty.');
try { new URL(t.url); } catch (e) { return alert('Invalid URL: ' + t.url); }
}
const res = await fetch('/api/settings', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
checkIntervalMs: Math.round(intervalSec * 1000),
dateFormat: document.getElementById('inp-dtf').value,
timeFormat: document.getElementById('inp-timef').value,
targets: settingsTargets
})
});
if (res.ok) {
const s = await res.json();
checkIntervalMs = s.checkIntervalMs;
dateFormat = s.dateFormat;
timeFormat = s.timeFormat;
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 now = Date.now();
res.json({
checkIntervalMs,
monitoringPaused,
localIpHistory,
publicIpHistory,
targets: targets.map(t => {
const uptimeMs = now - t.monitorStartTime;
const currentDowntime = !t.isOnline && t.outageStart ? now - t.outageStart : 0;
const totalDown = t.totalDowntimeMs + currentDowntime;
return {
id: t.id,
url: t.url,
label: t.label,
isOnline: t.isOnline,
monitorStartTime: t.monitorStartTime,
uptimeMs,
totalDowntimeMs: totalDown,
totalUptimeMs: uptimeMs - totalDown,
outageCount: t.outages.length + (!t.isOnline ? 1 : 0),
currentOutageStart: t.outageStart,
outages: t.outages.slice().reverse()
};
})
});
});
// Export as JSON
app.get('/export/json', (req, res) => {
const now = Date.now();
const data = {
exportedAt: new Date().toISOString(),
checkIntervalMs,
targets: targets.map(t => {
const uptimeMs = now - t.monitorStartTime;
const currentDowntime = !t.isOnline && t.outageStart ? now - t.outageStart : 0;
const totalDown = t.totalDowntimeMs + currentDowntime;
const allOutages = t.outages.slice().reverse();
if (!t.isOnline && t.outageStart) {
allOutages.unshift({ start: t.outageStart, end: null, duration: now - t.outageStart, ongoing: true });
}
return {
id: t.id, url: t.url, label: t.label,
monitorStartTime: new Date(t.monitorStartTime).toISOString(),
isOnline: t.isOnline,
uptimePct: uptimeMs > 0 ? ((uptimeMs - totalDown) / uptimeMs * 100).toFixed(4) : '100.0000',
totalUptimeMs: uptimeMs - totalDown,
totalDowntimeMs: totalDown,
outageCount: allOutages.length,
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 now = Date.now();
const lines = [
'# Uptime Monitor Export',
`# Exported At,${new Date().toISOString()}`,
`# Targets,${targets.length}`,
'',
'Target,URL,Uptime %,Start,End,Duration (ms),Duration,Ongoing'
];
targets.forEach(t => {
const uptimeMs = now - t.monitorStartTime;
const currentDowntime = !t.isOnline && t.outageStart ? now - t.outageStart : 0;
const totalDown = t.totalDowntimeMs + currentDowntime;
const uptimePct = uptimeMs > 0 ? ((uptimeMs - totalDown) / uptimeMs * 100).toFixed(4) : '100.0000';
const allOutages = t.outages.slice().reverse();
if (!t.isOnline && t.outageStart) {
allOutages.unshift({ start: t.outageStart, end: null, duration: now - t.outageStart, ongoing: true });
}
if (allOutages.length === 0) {
lines.push(['"' + t.label + '"', '"' + t.url + '"', uptimePct + '%', '', '', '', '', ''].join(','));
} else {
allOutages.forEach((o, i) => {
lines.push([
i === 0 ? '"' + t.label + '"' : '',
i === 0 ? '"' + t.url + '"' : '',
i === 0 ? uptimePct + '%' : '',
new Date(o.start).toISOString(),
o.end ? new Date(o.end).toISOString() : '',
o.duration,
formatDuration(o.duration),
o.ongoing ? 'Yes' : 'No'
].join(','));
});
}
});
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, dateFormat, timeFormat, targets: targets.map(t => ({ id: t.id, url: t.url, label: t.label })) });
});
app.post('/api/monitor/pause', (req, res) => {
if (!monitoringPaused) {
monitoringPaused = true;
if (intervalId) { clearInterval(intervalId); intervalId = null; }
console.log(`[${new Date().toISOString()}] Monitoring PAUSED`);
}
res.json({ monitoringPaused });
});
app.post('/api/monitor/resume', (req, res) => {
if (monitoringPaused) {
monitoringPaused = false;
restartMonitor();
monitor();
console.log(`[${new Date().toISOString()}] Monitoring RESUMED`);
}
res.json({ monitoringPaused });
});
app.post('/api/settings', (req, res) => {
const { checkIntervalMs: newInterval, dateFormat: newDateFormat, timeFormat: newTimeFormat, targets: newTargets } = req.body || {};
const VALID_DATE_FORMATS = ['locale', 'iso', 'us', 'eu', 'dot', 'ymd'];
const VALID_TIME_FORMATS = ['24h', '12h'];
if (newDateFormat !== undefined) {
if (!VALID_DATE_FORMATS.includes(newDateFormat)) return res.status(400).json({ error: 'Invalid dateFormat' });
dateFormat = newDateFormat;
}
if (newTimeFormat !== undefined) {
if (!VALID_TIME_FORMATS.includes(newTimeFormat)) return res.status(400).json({ error: 'Invalid timeFormat' });
timeFormat = newTimeFormat;
}
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 (Array.isArray(newTargets)) {
if (newTargets.length === 0) return res.status(400).json({ error: 'At least one target required' });
for (const nt of newTargets) {
try {
const u = new URL(nt.url);
if (u.protocol !== 'http:' && u.protocol !== 'https:') throw new Error();
} catch (e) {
return res.status(400).json({ error: 'Invalid URL: ' + nt.url });
}
}
targets = newTargets.map(nt => {
const existing = targets.find(t => t.id === nt.id);
if (existing) { existing.url = nt.url; existing.label = nt.label || nt.url; return existing; }
return makeTarget(nt.url, nt.label || nt.url);
});
}
saveState();
res.json({ checkIntervalMs, dateFormat, timeFormat, targets: targets.map(t => ({ id: t.id, url: t.url, label: t.label })) });
});
// ─── Start ────────────────────────────────────────────────────────────────────
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});