diff --git a/.gitignore b/.gitignore index 9095c52..8f54a3a 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ yarn-error.log* .env .env.* *.log +data.json diff --git a/index.js b/index.js index 97fb78c..fe515ca 100644 --- a/index.js +++ b/index.js @@ -1,11 +1,51 @@ 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; -// ─── IP Helpers ─────────────────────────────────────────────────────────────── +// ─── 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'); @@ -30,22 +70,148 @@ function getPublicIP() { }); } +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 checkUrl = 'https://www.google.com'; +let dateFormat = 'locale'; +let timeFormat = '24h'; +let targets = []; let intervalId = null; +let monitoringPaused = false; -let isOnline = true; -let outageStart = null; -const outages = []; -let monitorStartTime = Date.now(); -let totalDowntimeMs = 0; +// ─── IP History ─────────────────────────────────────────────────────────────── +// Each entry: { ip, since, until } (until=null means currently active) +let localIpHistory = []; +let publicIpHistory = []; +let ipPollId = null; -function checkConnectivity() { +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 = checkUrl.startsWith('https://') ? https : http; - const req = mod.get(checkUrl, { timeout: 4000 }, (res) => { + const mod = url.startsWith('https://') ? https : http; + const req = mod.get(url, { timeout: 4000 }, (res) => { res.resume(); resolve(true); }); @@ -55,20 +221,24 @@ function checkConnectivity() { } 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; - } + 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) { @@ -81,12 +251,16 @@ function formatDuration(ms) { function restartMonitor() { if (intervalId) clearInterval(intervalId); - intervalId = setInterval(monitor, checkIntervalMs); + if (!monitoringPaused) intervalId = setInterval(monitor, checkIntervalMs); } restartMonitor(); monitor(); +// Start IP polling (every 30 seconds) +pollIPs(); +ipPollId = setInterval(pollIPs, 30000); + // ─── Routes ─────────────────────────────────────────────────────────────────── // Unified Dashboard @@ -100,12 +274,15 @@ app.get('/', async (req, res) => {