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 = 3000; // ─── 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); }); }); } async function monitor() { await Promise.all(targets.map(async (t) => { const online = await checkConnectivity(t.url); if (!online && t.isOnline) { t.isOnline = false; t.outageStart = Date.now(); throttledLog(t.id, 'disc', `${t.label} DISCONNECTED`); 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 }); throttledLog(t.id, 'rest', `${t.label} RESTORED (outage: ${formatDuration(duration)})`); t.isOnline = true; t.outageStart = null; saveState(); } })); } 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(` Network Dashboard

Network Dashboard

Loading...
Checking…
Total Uptime
–
Total Downtime
–
Outages
–
Avg Outage
–
Longest Outage
–
Network Info
Port ${PORT}
Adapter …
Network …
Local IP ${localIP}
Public IP ${publicIP}
Targets
LabelURLStatusUptimeOutagesDowntime
Local IP History
IP AddressNetworkAdapterSinceUntilDuration
Gathering data…
Public IP History
IP AddressSinceUntilDuration
Gathering data…
Outage History
#TargetStartEndDuration
No outages recorded yet — connection has been stable.
✓ Settings saved
`); }); // 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}`); });