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(`
Network Dashboard
Network Dashboard
Loading...
Network Info
Port
${PORT}
Local IP
${localIP}
Public IP
${publicIP}
No outages recorded yet — connection has been stable.
✓ Settings saved
`);
});
// 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}`);
});