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(` Network Dashboard

Network Dashboard

Loading...
Checking…
Network Info
Port ${PORT}
Local IP ${localIP}
Public IP ${publicIP}
Uptime
–
uptime
Online
–
Offline
–
Total Uptime
–
Total Downtime
–
Outages
–
Avg / Longest Outage
–
Outage History
#StartEndDuration
No outages recorded yet — connection has been stable.
`); }); // 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}`); });