From 5f4c10df490fe314c78712fccb6534ed10d33bd0 Mon Sep 17 00:00:00 2001 From: Alex Date: Mon, 16 Nov 2026 03:56:05 +0000 Subject: [PATCH] Template: languages (en/da/de), admin UI, discovery, no site data --- README.md | 123 +++++++++++++++--- prisma/schema.prisma | 20 +++ src/app.js | 15 ++- src/routes/admin.js | 92 ++++++++++---- src/routes/site.js | 110 +++++++++++++++- src/services/analyticsService.js | 59 +++++++++ src/site/admin-nav.js | 20 +++ src/site/admin.css | 40 ++++++ src/site/index.html | 18 +-- src/site/lang/da.json | 125 ++++++++++++++++++ src/site/lang/de.json | 28 +++++ src/site/lang/en.json | 123 ++++++++++++++++++ src/site/site.css | 57 +++++++++ src/site/site.js | 209 ++++++++++++++++++++++++------- src/views/admin/analytics.html | 26 ++++ src/views/admin/app.html | 128 +++++++++++++++++++ src/views/admin/index.ejs | 1 + src/views/admin/login.ejs | 155 ++--------------------- src/views/admin/site.html | 16 +-- src/views/setup/wizard.ejs | 197 ++--------------------------- 20 files changed, 1124 insertions(+), 438 deletions(-) create mode 100644 src/services/analyticsService.js create mode 100644 src/site/admin-nav.js create mode 100644 src/site/admin.css create mode 100644 src/site/lang/da.json create mode 100644 src/site/lang/de.json create mode 100644 src/site/lang/en.json create mode 100644 src/views/admin/analytics.html create mode 100644 src/views/admin/app.html diff --git a/README.md b/README.md index 9d5055e..aac0528 100644 --- a/README.md +++ b/README.md @@ -1,23 +1,116 @@ # LocalPing -Self-hosted uptime monitor for homelabs: ICMP/TCP/UDP/HTTP(S) checks, incident log, news posts, admin panel, and a fast static public status site. +LocalPing Logo + +A simple, self-hosted uptime monitoring system for your homelab. Monitor TrueNAS, Jellyfin, qBittorrent, web services, and anything else with real-time dashboards and historical tracking. + +## Quick Install + +One-liner deployment (Ubuntu 22.04+): -## Install ```bash -git clone https://github.com/YOUR-ORG/localping.git && cd localping -sudo ./install.sh # Ubuntu 22.04+: Node, Postgres, systemd service +sudo apt update && sudo apt install -y curl && curl -fsSL https://raw.githubusercontent.com/YOUR-ORG/localping/main/install.sh | bash ``` -Then open `http://:8000/setup` to create the admin account. -## Public site -The public frontend is plain HTML/CSS/JS in `src/site` (no build step, ~10 KB). It reads a slim JSON API (`/api/site/summary`, `/api/site/news`) and supports: -- service **tiers** (featured / normal / background), per-service **explainers** (ⓘ) and a **public link** switch, edited in *Admin → Site* -- custom **name, accent colour and app icon** (also used for the PWA manifest), in *Admin → Site* -- `SITE_DIR=/path/to/theme` to serve your own theme; `SITE_HOSTS=status.example.com` to limit it to certain hostnames -- `SITE_NAME`, `SITE_URL` env vars for RSS +This automatically: +- Installs Node.js, dependencies, and systemd service +- Configures secure environment variables +- Sets up ICMP capabilities for ping +- Enables auto-start on boot -Edit the About page and footer in `src/site`. +## First-Time Setup -## Dev -`npm install && npx prisma db push && npm run dev`. Tests: `npm test`. -License: MIT. +1. Visit `http://:8000/setup` +2. Create admin username and password +3. Configure gateway IP (auto-detected) +4. Complete setup and login at `http://:8000/admin/login` + +## Features + +- **Multi-Protocol**: ICMP, TCP, UDP, HTTP/HTTPS monitoring +- **Real-Time Dashboards**: Admin panel + public status page +- **Historical Data**: 90+ days stored locally in SQLite +- **Desktop Notifications**: Browser notifications for status changes +- **Service Groups**: Organize monitors by category +- **Quick Commands**: `/jellyfin` style shortcuts on public UI + +## Access Points + +- **Public Dashboard**: `http://localhost:8000` +- **Admin Panel**: `http://localhost:8000/admin` +- **API**: `http://localhost:8000/api` + +## Service Management + +```bash +# Check status +systemctl status localping + +# View logs +journalctl -u localping -f + +# Restart +sudo systemctl restart localping + +# Stop/Start +sudo systemctl stop localping +sudo systemctl start localping +``` + +## Configuration + +All settings are in `/opt/localping/.env`: + +```env +API_PORT=8000 +PING_INTERVAL=60 +ALERT_COOLDOWN=300 +``` + +Admin credentials are set during the setup wizard. The database is stored at `data/localping.db` (SQLite - no external database needed). + +## Development + +```bash +# Clone and install +git clone https://github.com/YOUR-ORG/localping.git +cd localping +npm install + +# Set ICMP capabilities +sudo setcap cap_net_raw=ep $(which node) + +# Run in dev mode +npm run dev +``` + +## Testing + +Unit tests are available to ensure export/import functionality and core services work correctly: + +```bash +# Run all tests +npm test + +# Run tests in watch mode +npm run test:watch + +# Run tests with coverage +npm run test:coverage + +# Run backup service tests only +npm run test:backup + +# Or use the test script +./scripts/run-tests.sh +``` + +Test files are located in `__tests__/` directory: +- `__tests__/services/backupService.test.js` - Tests for export/import functionality +- `__tests__/services/pingService.test.js` - Tests for ping service + +**Important**: Always run tests after making changes to ensure everything still works correctly. + +## License + +MIT diff --git a/prisma/schema.prisma b/prisma/schema.prisma index a32a529..945d745 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -40,6 +40,8 @@ model Target { group String? quickCommands Json? description String? + descriptionDa String? + descriptions Json? tier String @default("normal") // featured | normal | background linkPublic Boolean @default(true) createdAt DateTime @default(now()) @@ -225,3 +227,21 @@ model Post { @@index([createdAt]) @@map("posts") } + +model Visit { + id String @id @default(uuid()) @map("_id") + ts DateTime @default(now()) + path String + country String? + region String? + city String? + referrer String? + device String? + browser String? + vid String + bot Boolean @default(false) + + @@index([ts]) + @@index([bot, ts]) + @@map("visits") +} diff --git a/src/app.js b/src/app.js index c13eae7..c7206be 100644 --- a/src/app.js +++ b/src/app.js @@ -168,10 +168,19 @@ const startServer = async () => { if (require('fs').existsSync(path.join(siteDir, 'index.html'))) { const hosts = (process.env.SITE_HOSTS || '').split(',').map((h) => h.trim().toLowerCase()).filter(Boolean); const onlyHosts = (mw) => (req, res, next) => (!hosts.length || hosts.includes(req.hostname.toLowerCase())) ? mw(req, res, next) : next(); - const spa = (req, res) => res.sendFile(path.join(siteDir, 'index.html'), { headers: { 'Cache-Control': 'no-cache' } }); + // Assets revalidate (ETag) so deploys show up at once, even behind a CDN; the HTML + // references them with a content-version query string. + const fsx = require('fs'); + const assetOpts = { maxAge: 0, setHeaders: (res) => res.set('Cache-Control', 'no-cache') }; + const version = () => ['site.js', 'site.css'].map((f) => { try { return fsx.statSync(path.join(siteDir, f)).mtimeMs.toString(36); } catch (e) { return '0'; } }).join(''); + const spa = (req, res) => { + require('./routes/site').recordPreview(req).catch(() => {}); + const html = fsx.readFileSync(path.join(siteDir, 'index.html'), 'utf8').replace(/(\/s\/site\.(?:js|css))(?:\?v=\w+)?/g, `$1?v=${version()}`); + res.set('Cache-Control', 'no-cache').type('html').send(html); + }; app.use('/', onlyHosts(require('./routes/site'))); - app.use('/s', onlyHosts(express.static(siteDir, { maxAge: '1h' }))); - app.use(onlyHosts(express.static(siteDir, { maxAge: '1h', index: false }))); + app.use('/s', onlyHosts(express.static(siteDir, assetOpts))); + app.use(onlyHosts(express.static(siteDir, { ...assetOpts, index: false }))); ['/', '/status', '/news', '/tools', '/about'].forEach((r) => app.get(r, onlyHosts(spa))); console.log(chalk.cyan('✓ Static site loaded from ' + siteDir + (hosts.length ? ' for ' + hosts.join(',') : ''))); } diff --git a/src/routes/admin.js b/src/routes/admin.js index 3d462af..6ebd89e 100644 --- a/src/routes/admin.js +++ b/src/routes/admin.js @@ -67,39 +67,28 @@ router.get('/logout', (req, res) => { }); // Admin dashboard - Monitors tab (default) -router.get('/', adminPageAuth, (req, res) => { - res.render('admin/index', { currentTab: 'monitors' }); -}); +router.get('/', adminPageAuth, (req, res) => res.sendFile(require('path').join(__dirname, '..', 'views', 'admin', 'app.html'))); +// Legacy UI stays reachable at /admin/legacy +router.get('/discover', adminPageAuth, (req, res) => res.sendFile(require('path').join(__dirname, '..', 'views', 'admin', 'app.html'))); +router.get('/legacy', adminPageAuth, (req, res) => res.render('admin/index', { currentTab: 'monitors' })); // Admin Incidents tab -router.get('/incidents', adminPageAuth, (req, res) => { - res.render('admin/index', { currentTab: 'incidents' }); -}); +router.get('/incidents', adminPageAuth, (req, res) => res.sendFile(require('path').join(__dirname, '..', 'views', 'admin', 'app.html'))); // Admin Event Detection Rules tab -router.get('/events', adminPageAuth, (req, res) => { - res.render('admin/index', { currentTab: 'event-rules' }); -}); +router.get('/events', adminPageAuth, (req, res) => res.sendFile(require('path').join(__dirname, '..', 'views', 'admin', 'app.html'))); // Admin Blog Posts tab -router.get('/blogs', adminPageAuth, (req, res) => { - res.render('admin/index', { currentTab: 'posts' }); -}); +router.get('/blogs', adminPageAuth, (req, res) => res.sendFile(require('path').join(__dirname, '..', 'views', 'admin', 'app.html'))); // Admin Public Visibility tab -router.get('/visibility', adminPageAuth, (req, res) => { - res.render('admin/index', { currentTab: 'visibility' }); -}); +router.get('/visibility', adminPageAuth, (req, res) => res.sendFile(require('path').join(__dirname, '..', 'views', 'admin', 'app.html'))); // Admin Settings tab -router.get('/settings', adminPageAuth, (req, res) => { - res.render('admin/index', { currentTab: 'settings' }); -}); +router.get('/settings', adminPageAuth, (req, res) => res.sendFile(require('path').join(__dirname, '..', 'views', 'admin', 'app.html'))); // Admin Backup & Restore tab -router.get('/backup', adminPageAuth, (req, res) => { - res.render('admin/index', { currentTab: 'backup' }); -}); +router.get('/backup', adminPageAuth, (req, res) => res.sendFile(require('path').join(__dirname, '..', 'views', 'admin', 'app.html'))); // Proxy endpoint for icons router.get('/api/proxy-icon', async (req, res) => { @@ -144,19 +133,70 @@ router.use('/api', (req, res, next) => { adminPageAuth(req, res, next); }); +router.get('/analytics', adminPageAuth, (req, res) => res.sendFile(require('path').join(__dirname, '..', 'views', 'admin', 'analytics.html'))); +router.get('/api/analytics', async (req, res) => { + try { res.json(await require('../services/analyticsService').stats(req.query.range)); } catch (e) { res.status(500).json({ error: e.message }); } +}); + +// ---- Discovery from an external inventory (any JSON inventory with this shape) ---- +// Env: DISCOVER_URL (full URL returning {hosts:[{ip,name,items:[{name,public,target,protected,kind}]}]}), +// DISCOVER_KEY (sent in header DISCOVER_KEY_HEADER, default X-API-Key), DISCOVER_DOMAINS (comma list, default: none = all). +async function discoverCandidates() { + const url = process.env.DISCOVER_URL; + if (!url) return { configured: false, candidates: [] }; + const r = await axios.get(url, { headers: { [process.env.DISCOVER_KEY_HEADER || 'X-API-Key']: process.env.DISCOVER_KEY || '' }, timeout: 15000, httpsAgent: new (require('https').Agent)({ rejectUnauthorized: false }) }); + const domains = (process.env.DISCOVER_DOMAINS || '').split(',').map((d) => d.trim().toLowerCase()).filter(Boolean); + const targets = await getPrisma().target.findMany({ select: { host: true, appUrl: true, name: true } }); + const known = new Set(); + targets.forEach((t) => { known.add(String(t.host).toLowerCase()); try { known.add(new URL(t.appUrl).hostname.toLowerCase()); } catch (e) {} }); + const out = [], seen = new Set(); + for (const h of r.data.hosts || []) for (const it of h.items || []) { + const name = String(it.name || '').toLowerCase(); + if (!name || name.startsWith('*') || seen.has(name) || !/^https?:/i.test(String(it.target || ''))) continue; + if (domains.length && !domains.some((d) => name === d || name.endsWith('.' + d))) continue; + seen.add(name); + if (known.has(name)) continue; + out.push({ hostname: name, ip: h.ip, device: h.name, target: it.target, kind: it.kind, protected: !!it.protected, access: it.access || null }); + } + return { configured: true, candidates: out.sort((a, b) => a.hostname.localeCompare(b.hostname)) }; +} +router.get('/api/discover', async (req, res) => { + try { res.json({ success: true, ...(await discoverCandidates()) }); } catch (e) { res.status(502).json({ success: false, error: 'Inventory unreachable: ' + e.message }); } +}); +router.post('/api/discover/add', async (req, res) => { + try { + const wanted = Array.isArray(req.body.hostnames) ? req.body.hostnames.map(String) : []; + const { candidates } = await discoverCandidates(); + const prisma = getPrisma(); let added = 0; + for (const c of candidates.filter((x) => wanted.includes(x.hostname))) { + const label = c.hostname.split('.')[0].replace(/(^|-)(\w)/g, (m, a, b) => (a ? ' ' : '') + b.toUpperCase()); + let name = label, n = 2; while (await prisma.target.findUnique({ where: { name } })) name = label + ' ' + n++; + await prisma.target.create({ data: { name, host: c.hostname, protocol: 'HTTPS', port: 443, interval: 60, retries: 1, statusCodes: '200-499', ignoreSsl: true, publicVisible: false, publicShowAppLink: false, linkPublic: false, tier: 'background', appUrl: 'https://' + c.hostname, enabled: true } }); + added++; + } + require('../services/cacheService').clear(); + res.json({ success: true, added, note: 'Added as hidden monitors. Enable them on the public site in Admin → Site when ready.' }); + } catch (e) { res.status(500).json({ success: false, error: e.message }); } +}); + // Site (public frontend) management: per-service explainers/tiers + branding router.get('/site', adminPageAuth, (req, res) => res.sendFile(require('path').join(__dirname, '..', 'views', 'admin', 'site.html'))); router.get('/api/site/meta', async (req, res) => { const prisma = getPrisma(); - const targets = await prisma.target.findMany({ select: { id: true, name: true, description: true, tier: true, linkPublic: true, publicVisible: true, appUrl: true, position: true }, orderBy: { position: 'asc' } }); + const targets = await prisma.target.findMany({ select: { id: true, name: true, description: true, descriptions: true, descriptionDa: true, tier: true, linkPublic: true, publicVisible: true, appUrl: true, position: true }, orderBy: { position: 'asc' } }); const b = await prisma.siteBrand.findUnique({ where: { id: 'brand' } }); - res.json({ targets, brand: { name: b?.name || '', accent: b?.accent || '', tagline: b?.tagline || '', hasIcon: !!b?.iconData } }); + res.json({ langs: require('./site').languages(), targets: targets.map((t) => ({ ...t, descriptions: { ...(t.descriptionDa ? { da: t.descriptionDa } : {}), ...(t.descriptions || {}) } })), brand: { name: b?.name || '', accent: b?.accent || '', tagline: b?.tagline || '', hasIcon: !!b?.iconData } }); }); router.put('/api/site/meta/:id', async (req, res) => { - const { description, tier, linkPublic } = req.body; + const { description, descriptions, tier, linkPublic } = req.body; const data = {}; if (description !== undefined) data.description = String(description).slice(0, 400) || null; - if (['featured', 'normal', 'background'].includes(tier)) data.tier = tier; + if (descriptions && typeof descriptions === 'object') { + const clean = {}; + for (const [k, v] of Object.entries(descriptions)) if (/^[a-z]{2,3}(-[A-Za-z]{2,4})?$/.test(k) && String(v).trim()) clean[k] = String(v).slice(0, 400); + data.descriptions = clean; data.descriptionDa = null; + } + if (['quick', 'featured', 'normal', 'background'].includes(tier)) data.tier = tier; if (linkPublic !== undefined) data.linkPublic = !!linkPublic; await getPrisma().target.update({ where: { id: req.params.id }, data }); require('./site').invalidate && require('./site').invalidate(); @@ -609,7 +649,7 @@ router.put('/api/targets/:id', async (req, res) => { 'publicShowDetails', 'publicShowStatus', 'publicShowAppLink', 'appUrl', 'appIcon', 'retries', 'retryInterval', 'timeout', 'httpMethod', 'statusCodes', 'maxRedirects', 'ignoreSsl', 'upsideDown', 'important', - 'auth', 'position', 'group', 'quickCommands', 'description', 'tier', 'linkPublic', + 'auth', 'position', 'group', 'quickCommands', 'description', 'descriptionDa', 'tier', 'linkPublic', ]; Object.keys(updateData).forEach((key) => { if (!allowedFields.includes(key)) delete updateData[key]; diff --git a/src/routes/site.js b/src/routes/site.js index 998ff6a..7d12bbe 100644 --- a/src/routes/site.js +++ b/src/routes/site.js @@ -3,15 +3,61 @@ const express = require('express'); const { getPrisma } = require('../config/prisma'); const monitorService = require('../services/monitorService'); const router = express.Router(); +const fs = require('fs'), path = require('path'), https = require('https'), crypto = require('crypto'); +const axios = require('axios'), sharp = require('sharp'); +const analytics = require('../services/analyticsService'); const TTL = 30 * 1000; let cache = { at: 0, data: null, inflight: null }; +// ---- Local icon cache: fetched once, resized to 96px PNG, served with long cache headers ---- +const ICON_DIR = path.join(__dirname, '..', '..', 'data', 'icons'); +fs.mkdirSync(ICON_DIR, { recursive: true }); +const iconHash = (u) => crypto.createHash('sha1').update(u).digest('hex').slice(0, 8); +const iconFail = new Map(), iconBusy = new Map(); +async function ensureIcon(id) { + const t = await getPrisma().target.findFirst({ where: { id, enabled: true, publicVisible: true }, select: { appIcon: true } }); + if (!t || !t.appIcon) return null; + const f = path.join(ICON_DIR, `${id}-${iconHash(t.appIcon)}.png`); + if (fs.existsSync(f) && Date.now() - fs.statSync(f).mtimeMs < 14 * 864e5) return f; + if ((iconFail.get(f) || 0) > Date.now() - 36e5) return fs.existsSync(f) ? f : null; + if (!iconBusy.has(f)) { + iconBusy.set(f, (async () => { + try { + const r = await axios.get(t.appIcon, { responseType: 'arraybuffer', timeout: 10000, maxContentLength: 5e6, headers: { 'User-Agent': 'Mozilla/5.0' }, httpsAgent: new https.Agent({ rejectUnauthorized: false }) }); + const png = await sharp(Buffer.from(r.data), { density: 300 }).resize(96, 96, { fit: 'contain', background: { r: 0, g: 0, b: 0, alpha: 0 } }).png({ compressionLevel: 9 }).toBuffer(); + fs.writeFileSync(f, png); + fs.readdirSync(ICON_DIR).filter((n) => n.startsWith(id + '-') && n !== path.basename(f)).forEach((n) => fs.unlinkSync(path.join(ICON_DIR, n))); + return f; + } catch (e) { iconFail.set(f, Date.now()); return fs.existsSync(f) ? f : null; } + finally { iconBusy.delete(f); } + })()); + } + return iconBusy.get(f); +} +router.get('/icons/:id', async (req, res) => { + if (!/^[0-9a-f-]{36}$/.test(req.params.id)) return res.status(404).end(); + try { + const f = await ensureIcon(req.params.id); + if (!f) return res.status(404).end(); + res.set('Cache-Control', 'public, max-age=604800, immutable').type('png').sendFile(f); + } catch (e) { res.status(404).end(); } +}); +async function prewarmIcons() { + try { const ts = await getPrisma().target.findMany({ where: { enabled: true, publicVisible: true, appIcon: { not: null } }, select: { id: true } }); for (const t of ts) await ensureIcon(t.id); } catch (e) {} +} +setTimeout(prewarmIcons, 5000); +analytics.startRetention(); + +// ---- Visit beacon (outside /api so the API rate limiter doesn't apply) ---- +router.post('/t', (req, res) => { analytics.recordHit(req, req.body && req.body.p, req.body && req.body.r).catch(() => {}); res.status(204).end(); }); +router.recordPreview = analytics.recordPreview; + async function build() { const prisma = getPrisma(); const targets = await prisma.target.findMany({ where: { enabled: true, publicVisible: true }, - select: { id: true, name: true, appUrl: true, appIcon: true, position: true, group: true, publicShowStatus: true, publicShowAppLink: true, description: true, tier: true, linkPublic: true }, + select: { id: true, name: true, appUrl: true, appIcon: true, position: true, group: true, publicShowStatus: true, publicShowAppLink: true, description: true, descriptions: true, descriptionDa: true, tier: true, linkPublic: true }, orderBy: { position: 'asc' }, }); const ids = targets.map((t) => t.id); @@ -44,16 +90,16 @@ async function build() { let rtSum = 0, rtN = 0; for (let i = 0; i < 24; i++) { const r = h.get(start + i * 3600); - if (!r || !r.t) { bars.push(0); continue; } + if (!r || !r.t) { bars.push([0, null, null]); continue; } const f = r.s / r.t; - bars.push(f >= 0.98 ? 1 : f >= 0.5 ? 2 : 3); + bars.push([f >= 0.98 ? 1 : f >= 0.5 ? 2 : 3, Math.round(f * 1000) / 10, r.rt || null]); if (r.rt) { rtSum += r.rt; rtN++; } } return { id: t.id, name: t.name, status, url: t.publicShowAppLink !== false && t.linkPublic !== false ? t.appUrl || null : null, - description: t.description || null, tier: t.tier || 'normal', - icon: t.appIcon || null, group: t.group || null, + description: t.description || null, i18n: { ...(t.descriptionDa ? { da: t.descriptionDa } : {}), ...(t.descriptions || {}) }, tier: t.tier || 'normal', + icon: t.appIcon ? `/icons/${t.id}?v=${iconHash(t.appIcon)}` : null, group: t.group || null, up24: pct(m24.get(t.id)), up30: pct(m30.get(t.id)), rt: rtN ? Math.round(rtSum / rtN) : null, bars, }; @@ -90,6 +136,27 @@ router.get('/api/site/summary', async (req, res) => { } catch (e) { res.status(500).json({ error: 'unavailable' }); } }); +const RANGES = { '24h': [24 * 3600, 300], '7d': [7 * 86400, 1800], '30d': [30 * 86400, 7200] }; +router.get('/api/site/service/:id', async (req, res) => { + try { + if (!/^[0-9a-f-]{36}$/.test(req.params.id)) return res.status(404).end(); + const prisma = getPrisma(); + const t = await prisma.target.findFirst({ where: { id: req.params.id, enabled: true, publicVisible: true }, select: { id: true, name: true } }); + if (!t) return res.status(404).json({ error: 'not found' }); + const [span, step] = RANGES[req.query.range] || RANGES['24h']; + const since = Math.floor(Date.now() / 1000) - span; + const rows = await prisma.$queryRaw` + SELECT floor(extract(epoch from timestamp)/${step})::bigint*${step} AS b, count(*)::int t, + sum(CASE WHEN success THEN 1 ELSE 0 END)::int s, + COALESCE(avg("responseTime") FILTER (WHERE success), 0)::int rt + FROM "pingResults" WHERE "targetId" = ${t.id} AND timestamp >= to_timestamp(${since}::bigint) + GROUP BY 1 ORDER BY 1`; + const points = rows.map((r) => [Number(r.b) * 1000, r.t, r.s, r.rt]); + res.set('Cache-Control', 'public, max-age=20'); + res.json({ id: t.id, name: t.name, step: step * 1000, since: since * 1000, points }); + } catch (e) { res.status(500).json({ error: 'unavailable' }); } +}); + router.get('/api/site/news', async (req, res) => { try { const posts = await getPrisma().post.findMany({ where: { published: true }, orderBy: { createdAt: 'desc' }, take: 50 }); @@ -107,6 +174,37 @@ router.get('/api/site/news.rss', async (req, res) => { } catch (e) { res.status(500).end(); } }); +// ---- Languages: every src/site/lang/.json is a language; SITE_LANGS (comma list) limits which are enabled ---- +const LANG_DIR = path.join(process.env.SITE_DIR || path.join(__dirname, '..', 'site'), 'lang'); +let langCache = { at: 0, v: [] }; +function languages() { + if (Date.now() - langCache.at < 30000) return langCache.v; + const allow = (process.env.SITE_LANGS || '').split(',').map((x) => x.trim().toLowerCase()).filter(Boolean); + const out = []; + try { + for (const f of fs.readdirSync(LANG_DIR)) { + const m = /^([a-z]{2,3}(?:-[A-Za-z]{2,4})?)\.json$/.exec(f); if (!m) continue; + if (allow.length && !allow.includes(m[1])) continue; + try { const j = JSON.parse(fs.readFileSync(path.join(LANG_DIR, f), 'utf8')); out.push({ code: m[1], name: j.meta?.name || m[1], flag: j.meta?.flag || '', switchTo: j.meta?.switchTo || j.meta?.name || m[1], countries: j.meta?.countries || [] }); } catch (e) {} + } + } catch (e) {} + const def = process.env.SITE_DEFAULT_LANG || 'en'; + out.sort((a, b) => (a.code === def ? -1 : b.code === def ? 1 : a.code.localeCompare(b.code))); + langCache = { at: Date.now(), v: out }; + return out; +} +router.get('/api/site/langs', (req, res) => { + const langs = languages(), def = process.env.SITE_DEFAULT_LANG || 'en'; + const c = String(req.headers['cf-ipcountry'] || '').toUpperCase(); + const hit = langs.find((l) => l.countries.includes(c)); + res.set('Cache-Control', 'no-store'); + res.json({ langs, default: langs.some((l) => l.code === def) ? def : (langs[0] && langs[0].code) || 'en', detected: hit ? hit.code : (langs.some((l) => l.code === def) ? def : (langs[0] && langs[0].code) || 'en'), country: c || null, vars: { site: process.env.SITE_NAME || 'Status', owner: process.env.SITE_OWNER || '' } }); +}); +router.get('/api/site/lang', (req, res) => { // legacy + const c = String(req.headers['cf-ipcountry'] || '').toUpperCase(); + res.set('Cache-Control', 'no-store').json({ lang: c === 'DK' && languages().some((l) => l.code === 'da') ? 'da' : 'en', country: c || null }); +}); + router.get('/api/site/tools/ip', (req, res) => { const ip = req.headers['cf-connecting-ip'] || req.ip; res.set('Cache-Control', 'no-store'); @@ -114,7 +212,6 @@ router.get('/api/site/tools/ip', (req, res) => { }); // ---- Branding / PWA ---- -const fs = require('fs'), path = require('path'); const BR = path.join(__dirname, '..', 'site', 'brand'); let brandCache = null; async function brand() { @@ -141,6 +238,7 @@ router.get('/manifest.webmanifest', async (req, res) => { icons: [192, 512].map((n) => ({ src: `/brand/icon-${n}.png?v=${b.v}`, sizes: `${n}x${n}`, type: 'image/png', purpose: 'any maskable' })), }); }); +router.languages = languages; router.invalidateBrand = () => { brandCache = null; }; router.invalidate = () => { cache = { at: 0, data: null, inflight: null }; }; diff --git a/src/services/analyticsService.js b/src/services/analyticsService.js new file mode 100644 index 0000000..61aef20 --- /dev/null +++ b/src/services/analyticsService.js @@ -0,0 +1,59 @@ +const crypto = require('crypto'); +const { Prisma } = require('@prisma/client'); +const { getPrisma } = require('../config/prisma'); + +const PREVIEW = /(Discordbot|Twitterbot|facebookexternalhit|Slackbot|TelegramBot|WhatsApp|LinkedInBot|Mastodon|Signal|iMessage|Applebot|Bluesky|Pinterest)/i; +const ANYBOT = /bot|crawl|spider|slurp|preview|curl|wget|python|httpclient|headless|monitor|uptime|lighthouse/i; +const dec = (v) => { try { return v ? decodeURIComponent(String(v)).slice(0, 80) : null; } catch { return null; } }; + +function vidFor(req) { + const day = new Date().toISOString().slice(0, 10); + const salt = (process.env.SESSION_SECRET || 'localping') + day; + return crypto.createHash('sha256').update(salt + (req.ip || '') + (req.headers['user-agent'] || '')).digest('hex').slice(0, 16); +} +function uaInfo(ua = '') { + const device = /iPad|Tablet/i.test(ua) ? 'tablet' : /Mobi|Android|iPhone/i.test(ua) ? 'mobile' : 'desktop'; + const browser = /Edg\//.test(ua) ? 'Edge' : /OPR\/|Opera/.test(ua) ? 'Opera' : /Firefox\//.test(ua) ? 'Firefox' : /Chrome\//.test(ua) ? 'Chrome' : /Safari\//.test(ua) ? 'Safari' : 'Other'; + return { device, browser }; +} +function base(req) { + const h = req.headers; + return { country: (h['cf-ipcountry'] || '').toString().toUpperCase().slice(0, 2) || null, region: dec(h['cf-region']), city: dec(h['cf-ipcity']), vid: vidFor(req) }; +} +async function recordHit(req, pathStr, ref) { + const ua = req.headers['user-agent'] || ''; + if (ANYBOT.test(ua) || !ua) return; + let referrer = null; + try { const u = new URL(ref); if (u.hostname !== req.hostname) referrer = u.hostname.replace(/^www\./, ''); } catch {} + const { device, browser } = uaInfo(ua); + await getPrisma().visit.create({ data: { path: String(pathStr || '/').slice(0, 120), referrer, device, browser, bot: false, ...base(req) } }); +} +async function recordPreview(req) { + const m = PREVIEW.exec(req.headers['user-agent'] || ''); + if (!m) return; + await getPrisma().visit.create({ data: { path: req.path, browser: m[1], device: 'preview', bot: true, ...base(req) } }); +} + +async function stats(range) { + const prisma = getPrisma(); + const hours = { '24h': 24, '7d': 168, '30d': 720 }[range] || 24; + const unit = hours <= 24 ? 'hour' : 'day'; + const since = new Date(Date.now() - hours * 3600e3); + const five = new Date(Date.now() - 5 * 60e3); + const U = Prisma.raw(`'${unit}'`); + const top = (col) => prisma.$queryRaw`SELECT ${Prisma.raw('"' + col + '"')} AS k, count(*)::int AS views, count(DISTINCT vid)::int AS visitors FROM visits WHERE bot = false AND ts >= ${since} AND ${Prisma.raw('"' + col + '"')} IS NOT NULL GROUP BY 1 ORDER BY 2 DESC LIMIT 12`; + const [online, totals, series, countries, pages, referrers, devices, browsers, cities, previews, recent] = await Promise.all([ + prisma.$queryRaw`SELECT count(DISTINCT vid)::int AS n FROM visits WHERE bot = false AND ts >= ${five}`, + prisma.$queryRaw`SELECT count(*)::int AS views, count(DISTINCT vid)::int AS visitors FROM visits WHERE bot = false AND ts >= ${since}`, + prisma.$queryRaw`SELECT date_trunc(${U}, ts) AS t, count(*)::int AS views, count(DISTINCT vid)::int AS visitors FROM visits WHERE bot = false AND ts >= ${since} GROUP BY 1 ORDER BY 1`, + top('country'), top('path'), top('referrer'), top('device'), top('browser'), top('city'), + prisma.$queryRaw`SELECT browser AS k, count(*)::int AS views FROM visits WHERE bot = true AND ts >= ${since} GROUP BY 1 ORDER BY 2 DESC`, + prisma.$queryRaw`SELECT ts, path, country, city, referrer, device, browser, bot FROM visits WHERE ts >= ${since} ORDER BY ts DESC LIMIT 30`, + ]); + return { range, unit, online: online[0].n, ...totals[0], series, countries, pages, referrers, devices, browsers, cities, previews, recent, now: new Date().toISOString() }; +} +function startRetention() { + const run = () => getPrisma().visit.deleteMany({ where: { ts: { lt: new Date(Date.now() - 90 * 864e5) } } }).catch(() => {}); + setTimeout(run, 60e3); setInterval(run, 24 * 3600e3); +} +module.exports = { recordHit, recordPreview, stats, startRetention }; diff --git a/src/site/admin-nav.js b/src/site/admin-nav.js new file mode 100644 index 0000000..bf16f5f --- /dev/null +++ b/src/site/admin-nav.js @@ -0,0 +1,20 @@ +// Shared admin header/nav, injected into every new-style admin page. +(() => { + const I = { + mon: '', + inc: '', + post: '', + tr: '', + site: '', + more: '', + }; + const items = [['/admin', 'Monitors', 'mon'], ['/admin/incidents', 'Incidents', 'inc'], ['/admin/blogs', 'Posts', 'post'], ['/admin/analytics', 'Traffic', 'tr'], ['/admin/site', 'Site', 'site'], ['/admin/settings', 'More', 'more']]; + const here = location.pathname.replace(/\/$/, '') || '/admin'; + const on = (h) => h === here || (h === '/admin/settings' && ['/admin/discover', '/admin/events', '/admin/visibility', '/admin/backup', '/admin/settings'].includes(here)); + const hdr = document.createElement('header'); + hdr.className = 'top'; + hdr.innerHTML = `Admin · LocalPing + + View siteSign out`; + document.body.prepend(hdr); +})(); diff --git a/src/site/admin.css b/src/site/admin.css new file mode 100644 index 0000000..517b6dc --- /dev/null +++ b/src/site/admin.css @@ -0,0 +1,40 @@ +.adm-nav{display:flex;gap:2px;overflow-x:auto;scrollbar-width:none}.adm-nav::-webkit-scrollbar{display:none} +.adm-nav a{display:inline-flex;align-items:center;gap:7px;color:var(--muted);padding:7px 12px;border-radius:9px;font-weight:500;white-space:nowrap} +.adm-nav a:hover{color:var(--text);background:var(--panel);text-decoration:none}.adm-nav a.on{color:var(--text);background:var(--panel2)} +.adm-nav svg{width:16px;height:16px} +.toolbar{display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin:0 0 14px}.toolbar input[type=search]{flex:1;min-width:160px} +.toolbar .sp{flex:1} +.ar{display:grid;grid-template-columns:minmax(0,1.4fr) auto auto auto;gap:12px;align-items:center;padding:11px 14px;border-top:1px solid var(--line)} +.ar:first-child{border-top:0}.ar .nm{min-width:0}.ar .nm b{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.ar .nm small{color:var(--muted);display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.ar .acts{display:flex;gap:6px} +button.sm{padding:5px 10px;font-size:13px}button.danger{background:#3a161b;color:#ff8c97;border:1px solid #5c1f27} +.dim{opacity:.5} +.fm{display:grid;grid-template-columns:1fr 1fr;gap:10px 12px}.fm label{display:flex;flex-direction:column;gap:4px;font-size:13px;color:var(--muted)}.fm .full{grid-column:1/-1} +.fm label.chk{flex-direction:row;align-items:center;gap:8px;color:var(--text)}.fm label.chk input{width:auto} +select{width:100%} +.mo{position:fixed;inset:0;z-index:30;background:rgba(5,7,10,.7);display:flex;align-items:center;justify-content:center;padding:14px} +.mc{background:var(--panel);border:1px solid var(--line);border-radius:var(--r);padding:18px;width:min(640px,100%);max-height:92vh;overflow:auto} +.mc h3{margin:0 0 12px}.mc .btns{justify-content:flex-end;margin-top:14px} +.toast{position:fixed;left:50%;bottom:24px;transform:translateX(-50%);background:var(--panel2);border:1px solid var(--line);padding:10px 16px;border-radius:10px;z-index:40} +.toast.err{border-color:#5c1f27;color:var(--bad)} +.upd{border-left:2px solid var(--line);padding:2px 0 2px 10px;margin:6px 0;font-size:13px;color:var(--muted)} +@media(max-width:680px){ + .top{flex-wrap:nowrap} + .adm-nav{position:fixed;left:0;right:0;bottom:0;z-index:8;justify-content:space-around;gap:0;padding:6px 4px calc(6px + env(safe-area-inset-bottom));background:rgba(18,21,28,.97);border-top:1px solid var(--line);overflow:visible} + .adm-nav a{flex:1;flex-direction:column;gap:3px;padding:8px 2px;font-size:11.5px;text-align:center;justify-content:center}.adm-nav svg{width:20px;height:20px} + body{padding-bottom:calc(64px + env(safe-area-inset-bottom))} + .ar{grid-template-columns:1fr auto;row-gap:8px}.ar .acts{grid-column:1/-1} + .fm{grid-template-columns:1fr} + .mo{align-items:flex-end;padding:0}.mc{border-radius:18px 18px 0 0;width:100%} +} +@media(max-width:680px){ + .top .btns{flex-wrap:nowrap;flex:none;gap:2px}.top .btns a{white-space:nowrap;font-size:13px;padding:5px 8px!important} + .top .brand .muted{display:none} + .ar>.muted{display:none} + .ar .acts button{flex:1} +} +@media(max-width:680px){ + #list table th,#list table td{padding-left:6px!important;padding-right:6px!important;font-size:13px} + #list table td:first-child,#list table th:first-child{padding-left:12px!important;max-width:120px;word-break:break-word} + #list table th{font-size:12px} +} diff --git a/src/site/index.html b/src/site/index.html index 5c3ad06..260eca1 100644 --- a/src/site/index.html +++ b/src/site/index.html @@ -4,8 +4,8 @@ Status - - + + @@ -16,18 +16,20 @@
Status + +
diff --git a/src/site/lang/da.json b/src/site/lang/da.json new file mode 100644 index 0000000..62ca3d8 --- /dev/null +++ b/src/site/lang/da.json @@ -0,0 +1,125 @@ +{ + "operational": "Alle systemer kører", + "degraded": "Nogle tjenester er nede", + "down": "Større nedbrud", + "unknown": "Status ukendt", + "justNow": "lige nu", + "minAgo": "{n} min. siden", + "hAgo": "{n} t. siden", + "stale": "Live-data er ikke tilgængelige lige nu. Viser seneste kendte status.", + "up": "Kører", + "dn": "Nede", + "unk": "Ukendt", + "bars": "Seneste 24 timer, pr. time", + "about": "Om", + "featured": "Populære tjenester", + "normal": "Andre tjenester", + "background": "Infrastruktur og baggrundstjenester", + "servicesUp": "{u} af {t} tjenester kører", + "updated": "opdateret", + "homeH1": "Status for {site}", + "homeLead": "Live status, hændelser og nyheder for de selvhostede tjenester på {site}.", + "active": "Aktuelle og kommende", + "barsNote": "Søjlerne viser de seneste 24 timer. Procenten er oppetid de seneste 30 dage.", + "fullStatus": "Fuld status og historik →", + "latestNews": "Seneste nyt", + "allNews": "Alle nyheder →", + "statusH1": "Status", + "statusLead": "Tjekkes hvert minut fra en overvågning på en separat server.", + "sUp": "tjenester kører", + "sAvg": "gns. oppetid (30 dage)", + "sRt": "gns. svartid (24 t.)", + "history": "Hændelseshistorik", + "noInc": "Ingen hændelser registreret.", + "resolved": "løst", + "scheduled": "planlagt", + "newsH1": "Nyheder", + "newsLead": "Meddelelser, ændringer og vedligeholdelse.", + "rss": "RSS-feed", + "nothing": "Intet endnu.", + "toolsH1": "Værktøjer", + "toolsLead": "Små værktøjer. Alt undtagen IP-tjekket kører i din browser.", + "aboutH1": "Om", + "aboutLead": "{site} er et privat homelab drevet af {owner}. Tjenesterne er selvhostede og delt med venner og familie.", + "contact": "Kontakt", + "contactP": "Spørgsmål, adgangsanmodninger eller problemer:", + "projects": "Projekter", + "projectsP": "Kildekode og andre projekter findes på {link}.", + "how": "Sådan fungerer det", + "howP": "Status måles af {a}, en open source-oppetidsmonitor, der kører uden for hovedserveren, så nedbrud stadig bliver registreret. Siden er bygget sammen med {b}.", + "ping": "Svartid", + "uptimeL": "Oppetid", + "avgPing": "gns.", + "slow": "Langsommere end normalt", + "outage": "Nedbrud", + "noData": "Ingen data", + "r24": "24 timer", + "r7": "7 dage", + "r30": "30 dage", + "close": "Luk", + "checks": "tjek", + "clickHint": "Klik på en tjeneste for at se grafen.", + "quick": "Hurtig adgang", + "nav": [ + "Overblik", + "Status", + "Nyheder", + "Værktøjer", + "Om" + ], + "builtWith": "Bygget med", + "input": "Input", + "failed": "Fejlede", + "invalid": "Ugyldigt input", + "none": "Ingen records", + "tIp": [ + "Min IP-adresse", + "Den adresse, internettet ser dig med." + ], + "tDns": [ + "DNS-opslag", + "Slå et domænenavn op via Cloudflare DNS-over-HTTPS." + ], + "tB64": [ + "Base64", + "Kod eller afkod tekst.", + "Kod", + "Afkod" + ], + "tHash": [ + "SHA-256", + "Hash tekst i din browser.", + "Hash" + ], + "tPw": [ + "Adgangskodegenerator", + "Tilfældig adgangskode på 20 tegn.", + "Generér" + ], + "tTime": [ + "Unix-tid", + "Konvertér mellem tidsstempler og datoer.", + "Konvertér" + ], + "sev": { + "minor": "mindre", + "major": "større", + "critical": "kritisk" + }, + "st": { + "investigating": "undersøger", + "identified": "fundet", + "monitoring": "overvåger", + "resolved": "løst", + "scheduled": "planlagt" + }, + "meta": { + "name": "Dansk", + "flag": "🇩🇰", + "switchTo": "🇩🇰 Skift til Dansk", + "locale": "da-DK", + "countries": [ + "DK" + ] + } +} diff --git a/src/site/lang/de.json b/src/site/lang/de.json new file mode 100644 index 0000000..c3a84bb --- /dev/null +++ b/src/site/lang/de.json @@ -0,0 +1,28 @@ +{ + "justNow": "gerade eben", "minAgo": "vor {n} Min.", "hAgo": "vor {n} Std.", + "stale": "Live-Daten sind derzeit nicht verfügbar. Zeige den zuletzt bekannten Stand.", + "up": "Läuft", "dn": "Ausgefallen", "unk": "Unbekannt", "bars": "Letzte 24 Stunden, stündlich", "about": "Info", + "featured": "Beliebte Dienste", "normal": "Weitere Dienste", "background": "Infrastruktur & Hintergrunddienste", + "operational": "Alle Systeme laufen", "degraded": "Einige Dienste sind ausgefallen", "down": "Größere Störung", "unknown": "Status unbekannt", + "servicesUp": "{u} von {t} Diensten laufen", "updated": "aktualisiert", + "homeH1": "Status von {site}", "homeLead": "Live-Status, Vorfälle und Neuigkeiten.", + "active": "Aktuell und geplant", "barsNote": "Die Balken zeigen die letzten 24 Stunden. Der Prozentwert ist die Verfügbarkeit der letzten 30 Tage.", "fullStatus": "Vollständiger Status und Verlauf →", + "latestNews": "Neueste Meldungen", "allNews": "Alle Meldungen →", + "statusH1": "Status", "statusLead": "Jede Minute von einem separaten Host geprüft.", + "sUp": "Dienste laufen", "sAvg": "Ø Verfügbarkeit (30 Tage)", "sRt": "Ø Antwortzeit (24 Std.)", "history": "Vorfallshistorie", "noInc": "Keine Vorfälle erfasst.", + "resolved": "behoben", "scheduled": "geplant", + "newsH1": "Neuigkeiten", "newsLead": "Ankündigungen, Änderungen und Wartungshinweise.", "rss": "RSS-Feed", "nothing": "Noch nichts.", + "toolsH1": "Werkzeuge", "toolsLead": "Kleine Hilfsprogramme. Alles außer der IP-Abfrage läuft in Ihrem Browser.", + "aboutH1": "Info", "aboutLead": "{site} wird von {owner} betrieben.", + "contact": "Kontakt", "contactP": "Fragen oder Probleme:", "projects": "Projekte", "projectsP": "Quellcode und weitere Projekte: {link}.", "how": "So funktioniert es", + "howP": "Der Status wird von {a} gemessen, einem Open-Source-Uptime-Monitor. Diese Seite wurde mit {b} gebaut.", + "nav": ["Übersicht", "Status", "Neuigkeiten", "Werkzeuge", "Info"], "builtWith": "Gebaut mit", "input": "Eingabe", "failed": "Fehlgeschlagen", "invalid": "Ungültige Eingabe", "none": "Keine Einträge", + "ping": "Antwortzeit", "uptimeL": "Verfügbarkeit", "avgPing": "Ø", "slow": "Langsamer als üblich", "outage": "Ausfall", "noData": "Keine Daten", "r24": "24 Stunden", "r7": "7 Tage", "r30": "30 Tage", "close": "Schließen", "checks": "Prüfungen", "clickHint": "Klicken Sie auf einen Dienst für den Graphen.", + "quick": "Schnellzugriff", + "tIp": ["Meine IP-Adresse", "Die Adresse, mit der das Internet Sie sieht."], "tDns": ["DNS-Abfrage", "Hostnamen über Cloudflare DNS-over-HTTPS auflösen."], + "tB64": ["Base64", "Text kodieren oder dekodieren.", "Kodieren", "Dekodieren"], "tHash": ["SHA-256", "Text im Browser hashen.", "Hashen"], + "tPw": ["Passwortgenerator", "Zufälliges Passwort mit 20 Zeichen.", "Erzeugen"], "tTime": ["Unix-Zeit", "Zwischen Zeitstempeln und Datum umrechnen.", "Umrechnen"], + "sev": {"minor": "gering", "major": "erheblich", "critical": "kritisch"}, + "st": {"investigating": "wird untersucht", "identified": "Ursache gefunden", "monitoring": "wird beobachtet", "resolved": "behoben", "scheduled": "geplant"}, + "meta": {"name": "Deutsch", "flag": "🇩🇪", "switchTo": "🇩🇪 Auf Deutsch wechseln", "locale": "de-DE", "countries": ["DE", "AT", "CH", "LI"]} +} diff --git a/src/site/lang/en.json b/src/site/lang/en.json new file mode 100644 index 0000000..84ea384 --- /dev/null +++ b/src/site/lang/en.json @@ -0,0 +1,123 @@ +{ + "operational": "All systems operational", + "degraded": "Some services are down", + "down": "Major outage", + "unknown": "Status unknown", + "justNow": "just now", + "minAgo": "{n} min ago", + "hAgo": "{n} h ago", + "stale": "Live data is unavailable right now. Showing the last known state.", + "up": "Operational", + "dn": "Down", + "unk": "Unknown", + "bars": "Last 24 hours, hourly", + "about": "About", + "featured": "Popular services", + "normal": "Other services", + "background": "Infrastructure & background services", + "servicesUp": "{u} of {t} services up", + "updated": "updated", + "homeH1": "Status of {site}", + "homeLead": "Live health, incidents and news for the self-hosted services running on {site}.", + "active": "Active & upcoming", + "barsNote": "Bars show the last 24 hours. Percentage is 30-day uptime.", + "fullStatus": "Full status & history →", + "latestNews": "Latest news", + "allNews": "All news →", + "statusH1": "Status", + "statusLead": "Checked every minute from a monitor on a separate host.", + "sUp": "services up", + "sAvg": "avg 30-day uptime", + "sRt": "avg response (24h)", + "history": "Incident history", + "noInc": "No incidents recorded.", + "resolved": "resolved", + "scheduled": "scheduled", + "newsH1": "News", + "newsLead": "Announcements, changes and maintenance notes.", + "rss": "RSS feed", + "nothing": "Nothing yet.", + "toolsH1": "Tools", + "toolsLead": "Small utilities. Everything except the IP check runs in your browser.", + "aboutH1": "About", + "aboutLead": "{site} is a personal homelab run by {owner}. Services here are self-hosted and shared with friends and family.", + "contact": "Contact", + "contactP": "Questions, access requests or problems:", + "projects": "Projects", + "projectsP": "Source code and other projects live on {link}.", + "how": "How this works", + "howP": "Status is measured by {a}, an open-source uptime monitor, running outside the main server so outages are still reported. This site was built together with {b}.", + "ping": "Response time", + "uptimeL": "Uptime", + "avgPing": "avg", + "slow": "Slower than usual", + "outage": "Outage", + "noData": "No data", + "r24": "24 hours", + "r7": "7 days", + "r30": "30 days", + "close": "Close", + "checks": "checks", + "clickHint": "Click a service for its graph.", + "quick": "Quick access", + "nav": [ + "Overview", + "Status", + "News", + "Tools", + "About" + ], + "builtWith": "Built with", + "input": "Input", + "failed": "Failed", + "invalid": "Invalid input", + "none": "No records", + "tIp": [ + "My IP address", + "The address the internet sees for you." + ], + "tDns": [ + "DNS lookup", + "Resolve a hostname via Cloudflare DNS-over-HTTPS." + ], + "tB64": [ + "Base64", + "Encode or decode text.", + "Encode", + "Decode" + ], + "tHash": [ + "SHA-256", + "Hash text in your browser.", + "Hash" + ], + "tPw": [ + "Password generator", + "Random 20-character password.", + "Generate" + ], + "tTime": [ + "Unix time", + "Convert between timestamps and dates.", + "Convert" + ], + "sev": { + "minor": "minor", + "major": "major", + "critical": "critical" + }, + "st": { + "investigating": "investigating", + "identified": "identified", + "monitoring": "monitoring", + "resolved": "resolved", + "scheduled": "scheduled" + }, + "meta": { + "name": "English", + "flag": "🇺🇸", + "switchTo": "🇺🇸 Switch to English", + "locale": "en-GB", + "countries": [] + } +} diff --git a/src/site/site.css b/src/site/site.css index b92eb03..cb942dc 100644 --- a/src/site/site.css +++ b/src/site/site.css @@ -62,3 +62,60 @@ input{width:100%}button{cursor:pointer;background:var(--acc);color:#07101f;borde .svc{position:relative}.info{flex:none;width:18px;height:18px;padding:0;border-radius:50%;background:var(--panel2);color:var(--muted);border:1px solid var(--line);font:italic 700 11px/1 Georgia,serif;display:inline-grid;place-items:center} .info:hover,.info[aria-expanded=true]{color:var(--acc);border-color:var(--acc)} .tip{position:absolute;left:0;top:100%;margin-top:6px;z-index:6;width:min(320px,80vw);background:#1b2030;border:1px solid var(--line);border-radius:10px;padding:10px 12px;font-size:13px;line-height:1.45;box-shadow:0 8px 30px rgba(0,0,0,.5)} +.lang{padding:5px 11px;font-size:13px;flex:none} + +.quick{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:12px} +.qc{display:flex;flex-direction:column;gap:6px;padding:16px;background:var(--panel);border:1px solid var(--line);border-radius:var(--r);color:var(--text);transition:transform .12s,border-color .12s} +.qc:hover{text-decoration:none;border-color:var(--acc);transform:translateY(-2px)} +.qc b{font-size:16px}.qc>span{color:var(--muted);font-size:13px;line-height:1.4} +.qi{position:relative;width:48px;height:48px;margin-bottom:4px}.qi img,.qi .ph{width:48px;height:48px;border-radius:12px} +.qi .dot{position:absolute;right:-3px;bottom:-3px;width:12px;height:12px;border:2px solid var(--panel)} +.lang{white-space:nowrap} + +.adm{opacity:.7;font-size:12px} +@media(max-width:680px){ + .top{flex-wrap:nowrap;padding:10px 14px;backdrop-filter:none;-webkit-backdrop-filter:none;background:rgba(11,13,18,.96)} + .lang{padding:5px 10px;font-size:12px} + nav{position:fixed;left:0;right:0;bottom:0;z-index:8;justify-content:space-around;gap:0;padding:6px 6px calc(6px + env(safe-area-inset-bottom));background:rgba(18,21,28,.96);backdrop-filter:blur(12px);border-top:1px solid var(--line);overflow:visible} + nav a{flex:1;text-align:center;padding:10px 2px;font-size:12.5px;border-radius:10px} + body{padding-bottom:calc(64px + env(safe-area-inset-bottom))} + main{padding-top:18px} + h1{font-size:26px} + .quick{grid-template-columns:1fr 1fr;gap:10px} + .qc{padding:13px;gap:4px}.qc>span{font-size:12px}.qc b{font-size:15px} + .qi,.qi img,.qi .ph{width:40px;height:40px} + .banner{padding:14px}.banner .big{font-size:17px} + .foot .wrap{flex-direction:column;gap:6px} +} + +.stats{grid-template-columns:repeat(3,minmax(0,1fr))!important} +.ni{width:16px;height:16px;flex:none} +nav a{display:inline-flex;align-items:center;gap:7px} +.row[data-sid]{cursor:pointer}.row[data-sid]:hover{background:var(--panel2)} +.bars i{cursor:pointer}.bars i:hover{filter:brightness(1.3)} +.tip.bt{position:absolute;margin:0;pointer-events:none} +.gm{position:fixed;inset:0;z-index:20;background:rgba(5,7,10,.7);display:flex;align-items:center;justify-content:center;padding:14px} +.gc{background:var(--panel);border:1px solid var(--line);border-radius:var(--r);padding:18px;width:min(820px,100%);max-height:92vh;overflow:auto} +.gh{display:flex;justify-content:space-between;align-items:center;gap:10px;margin-bottom:10px}.gh .svc{flex:1} +.gsvg{width:100%;height:auto;touch-action:pan-y}.gt{min-height:20px;color:var(--muted);font-size:13px;margin-top:4px} +.lg{display:inline-block;width:10px;height:10px;border-radius:3px;margin:0 4px 0 8px;vertical-align:-1px} +.g3{margin-top:0} +@media(max-width:680px){ + nav a{flex-direction:column;gap:3px}.ni{width:20px;height:20px} + .stat{padding:10px}.stat b{font-size:17px}.stat span{font-size:11px}.stats{gap:8px!important} + .gc{padding:14px} +} + +@media(max-width:680px){ + .foot{text-align:center;padding:22px 0 26px} + .foot .wrap{align-items:center;gap:10px} + .foot .wrap>span{display:block} + .adm{opacity:1;font-size:13px;display:inline-block;padding:2px 8px;border:1px solid var(--line);border-radius:8px;margin-left:4px} + .gm{align-items:flex-end;padding:0} + .gc{border-radius:18px 18px 0 0;width:100%;max-height:88vh;padding:14px 14px calc(18px + env(safe-area-inset-bottom))} + .gh .svc b{font-size:15px}.gh .pill{display:none} + .gc .btns{margin:4px 0 10px}.gc .btns button{flex:1;padding:8px 4px;font-size:13px} + .gc .stats .stat{padding:9px 8px}.gc .stats b{font-size:16px} + .gc .meta{line-height:2} + .gt{min-height:36px} +} diff --git a/src/site/site.js b/src/site/site.js index 02462c4..36a8432 100644 --- a/src/site/site.js +++ b/src/site/site.js @@ -1,9 +1,48 @@ const $ = (s, r = document) => r.querySelector(s); const main = $('#main'); const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); -const LABEL = { operational: 'All systems operational', degraded: 'Some services are down', down: 'Major outage', unknown: 'Status unknown' }; -const ago = (d) => { const s = (Date.now() - new Date(d)) / 1e3; return s < 90 ? 'just now' : s < 5400 ? Math.round(s / 60) + ' min ago' : s < 129600 ? Math.round(s / 3600) + ' h ago' : new Date(d).toLocaleDateString(); }; -const fmt = (d) => new Date(d).toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' }); +const ago = (d) => { const s = (Date.now() - new Date(d)) / 1e3; return s < 90 ? T().justNow : s < 5400 ? T().minAgo(Math.round(s / 60)) : s < 129600 ? T().hAgo(Math.round(s / 3600)) : new Date(d).toLocaleDateString(T().locale); }; +const fmt = (d) => new Date(d).toLocaleString(T().locale, { dateStyle: 'medium', timeStyle: 'short' }); + + +// ---- i18n: strings live in /s/lang/.json. The server decides which languages are enabled +// (SITE_LANGS) and which one a visitor's country maps to (meta.countries in each file). +let LANG = 'en', LANGS = [], DICT = {}, BASE = null, VARS = { site: 'Status', owner: '' }; +const fill = (str, v) => String(str).replace(/\{(\w+)\}/g, (m, k) => (k in v ? v[k] : m)); +const T = () => { + const d = DICT, S = (k, v) => fill(d[k] ?? '', { ...VARS, ...v }); + return new Proxy(d, { get: (o, k) => ({ + minAgo: (n) => S('minAgo', { n }), hAgo: (n) => S('hAgo', { n }), servicesUp: (u, t) => S('servicesUp', { u, t }), + projectsP: (link) => S('projectsP', { link }), howP: (a, b) => S('howP', { a, b }), + homeH1: S('homeH1'), homeLead: S('homeLead'), aboutLead: S('aboutLead'), locale: d.meta?.locale || 'en-GB', switchTo: d.meta?.switchTo, + })[k] ?? o[k] }); +}; +async function loadLang(code) { + const r = await fetch(`/s/lang/${code}.json`); if (!r.ok) throw 0; + const d = await r.json(); + if (code !== 'en' && !BASE) { try { BASE = await (await fetch('/s/lang/en.json')).json(); } catch { BASE = {}; } } + DICT = code === 'en' ? d : { ...BASE, ...d }; if (code === 'en') BASE = d; LANG = code; +} +async function initLang() { + let cfg = { langs: [], default: 'en', detected: 'en', vars: VARS }; + try { cfg = await (await fetch('/api/site/langs')).json(); } catch {} + LANGS = cfg.langs; VARS = { ...VARS, ...cfg.vars }; + const saved = localStorage.getItem('lang'); + const code = LANGS.some((l) => l.code === saved) ? saved : cfg.detected; + try { await loadLang(code); } catch { try { await loadLang(cfg.default); } catch {} } + applyShell(); +} +function applyShell() { + document.documentElement.lang = LANG; + document.querySelectorAll('#nav a').forEach((a, i) => { a.querySelector('span').textContent = T().nav[i]; }); + const bw = document.getElementById('built-with'); if (bw) bw.textContent = T().builtWith; + const lb = document.getElementById('lang-btn'), ls = document.getElementById('lang-sel'); + if (LANGS.length < 2) { lb && (lb.hidden = true); ls && (ls.hidden = true); return; } + if (LANGS.length === 2) { ls && (ls.hidden = true); const o = LANGS.find((l) => l.code !== LANG); if (lb && o) { lb.hidden = false; lb.textContent = o.switchTo; lb.dataset.to = o.code; } } + else { lb && (lb.hidden = true); if (ls) { ls.hidden = false; ls.innerHTML = LANGS.map((l) => ``).join(''); } } +} +async function switchLang(code) { localStorage.setItem('lang', code); await loadLang(code); applyShell(); render(location.pathname); } +const descOf = (s) => (s.i18n && s.i18n[LANG]) || s.description || ''; let summary = null, lastOk = 0; async function load() { @@ -16,90 +55,96 @@ async function load() { $('#brand-dot').className = 'dot ' + (summary?.overall || ''); return summary; } -const stale = () => (!lastOk || Date.now() - lastOk > 120e3) ? '
Live data is unavailable right now. Showing the last known state.
' : ''; +const stale = () => (!lastOk || Date.now() - lastOk > 120e3) ? `
${T().stale}
` : ''; -const icon = (s) => s.icon ? `` : '
'; -const row = (s) => `
-
${icon(s)}${s.url ? `${esc(s.name)}` : esc(s.name)}${s.description ? `` : ''}
- ${s.status === 'up' ? 'Operational' : s.status === 'down' ? 'Down' : 'Unknown'} -
${s.bars.map((b) => ``).join('')}
+const icon = (s) => s.icon ? `` : '
'; +const row = (s) => `
+
${icon(s)}${s.url ? `${esc(s.name)}` : esc(s.name)}${descOf(s) ? `` : ''}
+ ${s.status === 'up' ? T().up : s.status === 'down' ? T().dn : T().unk} +
${s.bars.map((b, i) => ``).join('')}
${s.up30 == null ? '–' : s.up30.toFixed(1) + '%'}
`; -const TIERS = [['featured', 'Popular services'], ['normal', 'Other services'], ['background', 'Infrastructure & background services']]; -const groups = (list) => TIERS.map(([t, h]) => { const l = list.filter((s) => (s.tier || 'normal') === t); return l.length ? `

${h}

${l.map(row).join('')}
` : ''; }).join(''); +const qdesc = descOf; +const quick = (list) => { const q = list.filter((s) => s.tier === 'quick'); return q.length ? `

${T().quick}

${q.map((s) => `
${icon(s)}
${esc(s.name)}${esc(qdesc(s))}
`).join('')}
` : ''; }; +const TIERS = ['featured', 'normal', 'background']; +const groups = (list) => TIERS.map((t) => { const l = list.filter((s) => (s.tier === 'quick' ? 'featured' : (s.tier || 'normal')) === t); return l.length ? `

${T()[t]}

${l.map(row).join('')}
` : ''; }).join(''); function banner(d) { - return ``; + return ``; } -const incCard = (i) => `

${i.scheduled ? 'scheduled' : esc(i.severity)}${esc(i.status)}${esc(i.title)}

-
${fmt(i.scheduled && i.start ? i.start : i.createdAt)}${i.resolvedAt ? ' · resolved ' + fmt(i.resolvedAt) : ''}
${i.description ? `

${esc(i.description)}

` : ''}
`; +const incCard = (i) => `

${i.scheduled ? T().scheduled : esc(T().sev[i.severity] || i.severity)}${esc(T().st[i.status] || i.status)}${esc(i.title)}

+
${fmt(i.scheduled && i.start ? i.start : i.createdAt)}${i.resolvedAt ? ' · ' + T().resolved + ' ' + fmt(i.resolvedAt) : ''}
${i.description ? `

${esc(i.description)}

` : ''}
`; const views = { async '/'() { const d = await load(); const news = await (await fetch('/api/site/news').catch(() => null))?.json?.().catch(() => null); const active = d?.incidents.filter((i) => i.status !== 'resolved' && (!i.scheduled || new Date(i.start) <= Date.now() + 864e5)) || []; - return `
${stale()}

Service status

Live health, incidents and news.

+ return `
${stale()}

${T().homeH1}

${T().homeLead}

${d ? banner(d) : ''} - ${active.length ? `

Active & upcoming

${active.map(incCard).join('')}` : ''} + ${quick(d?.services || [])} + ${active.length ? `

${T().active}

${active.map(incCard).join('')}` : ''} ${groups(d?.services || [])} -

Bars show the last 24 hours. Percentage is 30-day uptime. Full status & history →

- ${news?.posts?.length ? `

Latest news

${news.posts.slice(0, 2).map(post).join('')}All news →` : ''}
`; +

${T().barsNote} ${T().clickHint} ${T().fullStatus}

+ ${news?.posts?.length ? `

${T().latestNews}

${news.posts.slice(0, 2).map(post).join('')}${T().allNews}` : ''}
`; }, async '/status'() { const d = await load(); if (!d) return `
${stale()}

Status

`; const avg = d.services.filter((s) => s.up30 != null); const u = avg.length ? (avg.reduce((a, s) => a + s.up30, 0) / avg.length).toFixed(2) : '–'; const rts = d.services.filter((s) => s.rt); const rt = rts.length ? Math.round(rts.reduce((a, s) => a + s.rt, 0) / rts.length) : '–'; - return `
${stale()}

Status

Checked every minute from a monitor on a separate host.

${banner(d)} -
${d.up}/${d.total}services up
${u}%avg 30-day uptime
${rt}${rt === '–' ? '' : ' ms'}avg response (24h)
+ return `
${stale()}

${T().statusH1}

${T().statusLead}

${banner(d)} +
${d.up}/${d.total}${T().sUp}
${u}%${T().sAvg}
${rt}${rt === '–' ? '' : ' ms'}${T().sRt}
${groups(d.services)} -

Incident history

${d.incidents.length ? d.incidents.map(incCard).join('') : '

No incidents recorded.

'}
`; +

${T().history}

${d.incidents.length ? d.incidents.map(incCard).join('') : `

${T().noInc}

`}
`; }, async '/news'() { const r = await fetch('/api/site/news').then((x) => x.json()).catch(() => null); - return `

News

Announcements, changes and maintenance notes. RSS feed

${r?.posts?.length ? r.posts.map(post).join('') : '

Nothing yet.

'}
`; + return `

${T().newsH1}

${T().newsLead} ${T().rss}

${r?.posts?.length ? r.posts.map(post).join('') : `

${T().nothing}

`}
`; }, async '/tools'() { return toolsView(); }, async '/about'() { - return `

About

Edit this page in src/site/site.js (or point SITE_DIR at your own theme).

-
`; + return `

${T().aboutH1}

${T().aboutLead}

+

${T().contact}

you@example.com

`; }, }; const post = (p) => `

${esc(p.title)}

${esc(p.content)}

`; // ---- Tools: small, client-side only ---- -const tools = [ - { id: 'ip', name: 'My IP address', desc: 'The address the internet sees for you.', run: async (o) => { const r = await fetch('/api/site/tools/ip').then((x) => x.json()); o.textContent = r.ip; } }, - { id: 'dns', name: 'DNS lookup', desc: 'Resolve a hostname via Cloudflare DNS-over-HTTPS.', input: 'Status', - run: async (o, v) => { const r = await fetch(`https://cloudflare-dns.com/dns-query?name=${encodeURIComponent(v)}&type=A`, { headers: { accept: 'application/dns-json' } }).then((x) => x.json()); o.textContent = (r.Answer || []).map((a) => a.data).join('\n') || 'No records'; } }, - { id: 'b64', name: 'Base64', desc: 'Encode or decode text.', area: true, - run: (o, v, m) => { try { o.textContent = m === 'dec' ? new TextDecoder().decode(Uint8Array.from(atob(v), (c) => c.charCodeAt(0))) : btoa(String.fromCharCode(...new TextEncoder().encode(v))); } catch { o.textContent = 'Invalid input'; } }, modes: [['enc', 'Encode'], ['dec', 'Decode']] }, - { id: 'hash', name: 'SHA-256', desc: 'Hash text in your browser.', area: true, modes: [['go', 'Hash']], +const tools = () => { const t = T(); return [ + { id: 'ip', name: t.tIp[0], desc: t.tIp[1], run: async (o) => { const r = await fetch('/api/site/tools/ip').then((x) => x.json()); o.textContent = r.ip; } }, + { id: 'dns', name: t.tDns[0], desc: t.tDns[1], input: 'example.com', + run: async (o, v) => { const r = await fetch(`https://cloudflare-dns.com/dns-query?name=${encodeURIComponent(v)}&type=A`, { headers: { accept: 'application/dns-json' } }).then((x) => x.json()); o.textContent = (r.Answer || []).map((a) => a.data).join('\n') || t.none; } }, + { id: 'b64', name: t.tB64[0], desc: t.tB64[1], area: true, + run: (o, v, m) => { try { o.textContent = m === 'dec' ? new TextDecoder().decode(Uint8Array.from(atob(v), (c) => c.charCodeAt(0))) : btoa(String.fromCharCode(...new TextEncoder().encode(v))); } catch { o.textContent = t.invalid; } }, modes: [['enc', t.tB64[2]], ['dec', t.tB64[3]]] }, + { id: 'hash', name: t.tHash[0], desc: t.tHash[1], area: true, modes: [['go', t.tHash[2]]], run: async (o, v) => { const h = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(v)); o.textContent = [...new Uint8Array(h)].map((b) => b.toString(16).padStart(2, '0')).join(''); } }, - { id: 'pw', name: 'Password generator', desc: 'Random 20-character password.', modes: [['go', 'Generate']], + { id: 'pw', name: t.tPw[0], desc: t.tPw[1], modes: [['go', t.tPw[2]]], run: (o) => { const c = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789!@#$%^&*-_'; const a = crypto.getRandomValues(new Uint32Array(20)); o.textContent = [...a].map((n) => c[n % c.length]).join(''); } }, - { id: 'time', name: 'Unix time', desc: 'Convert between timestamps and dates.', input: String(Math.floor(Date.now() / 1e3)), modes: [['go', 'Convert']], + { id: 'time', name: t.tTime[0], desc: t.tTime[1], input: String(Math.floor(Date.now() / 1e3)), modes: [['go', t.tTime[2]]], run: (o, v) => { const n = Number(v); o.textContent = isNaN(n) ? new Date(v).getTime() / 1e3 + ' (unix)' : new Date(n * (n < 1e12 ? 1e3 : 1)).toISOString(); } }, -]; +]; }; function toolsView() { - setTimeout(() => tools.forEach((t) => { + const tl = tools(); + setTimeout(() => tl.forEach((t) => { const el = $('#t-' + t.id); if (!el) return; const out = $('.out', el), inp = $('input,textarea', el); - const go = async (m) => { out.textContent = '…'; try { await t.run(out, inp?.value ?? '', m); } catch { out.textContent = 'Failed'; } }; + const go = async (m) => { out.textContent = '…'; try { await t.run(out, inp?.value ?? '', m); } catch { out.textContent = T().failed; } }; el.querySelectorAll('button[data-m]').forEach((b) => b.addEventListener('click', () => go(b.dataset.m))); if (!t.modes) go(); })); - return `

Tools

Small utilities. Everything except the IP check runs in your browser.

${tools.map((t) => `

${t.name}

${t.desc}
- ${t.area ? '' : t.input ? `` : ''} + return `

${T().toolsH1}

${T().toolsLead}

${tl.map((t) => `

${t.name}

${t.desc}
+ ${t.area ? '' : t.input ? `` : ''} ${t.modes ? `
${t.modes.map(([m, l]) => ``).join('')}
` : ''}
`).join('')}
`; } // ---- router ---- -async function render(path, push) { +let firstView = true; +async function render(path, push, quiet) { const p = views[path] ? path : '/'; if (push) history.pushState({}, '', path); document.querySelectorAll('#nav a').forEach((a) => a.classList.toggle('on', a.getAttribute('href') === p)); - const titles = { '/': 'Overview', '/status': 'Status', '/news': 'News', '/tools': 'Tools', '/about': 'About' }; - document.title = (p === '/' ? '' : titles[p] + ' · ') + 'Status'; + const titles = Object.fromEntries(['/', '/status', '/news', '/tools', '/about'].map((k, i) => [k, T().nav[i]])); + document.title = (p === '/' ? '' : titles[p] + ' · ') + (VARS.site || 'Status'); main.innerHTML = await views[p](); + if (!quiet) try { navigator.sendBeacon('/t', new Blob([JSON.stringify({ p, r: firstView ? document.referrer : '' })], { type: 'application/json' })); firstView = false; } catch {} if (push) window.scrollTo(0, 0); } document.addEventListener('click', (e) => { @@ -117,9 +162,87 @@ document.addEventListener('click', (e) => { }); document.addEventListener('keydown', (e) => { if (e.key === 'Escape') document.querySelectorAll('.tip').forEach((t) => t.remove()); }); $('#yr').textContent = new Date().getFullYear(); -render(location.pathname.replace(/\/$/, '') || '/'); -setInterval(() => { if (!document.hidden && ['/', '/status'].includes(location.pathname)) render(location.pathname); }, 60e3); +document.getElementById('lang-btn')?.addEventListener('click', (e) => switchLang(e.currentTarget.dataset.to)); +document.getElementById('lang-sel')?.addEventListener('change', (e) => switchLang(e.target.value)); +initLang().then(() => render(location.pathname.replace(/\/$/, '') || '/')); +setInterval(() => { if (!document.hidden && ['/', '/status'].includes(location.pathname)) render(location.pathname, false, true); }, 60e3); // Broken icon -> neutral placeholder document.addEventListener('error', (e) => { const i = e.target; if (i.tagName === 'IMG' && i.closest('.svc')) { const d = document.createElement('div'); d.className = 'ph'; i.replaceWith(d); } }, true); + +// ---- bar details + per-service graph ---- +const svcById = (id) => (summary?.services || []).find((x) => x.id === id); +function closeTips() { document.querySelectorAll('.tip.bt').forEach((t) => t.remove()); } +document.addEventListener('click', (e) => { + const bar = e.target.closest('.bars i'); + if (bar) { + e.stopPropagation(); closeTips(); + const row = bar.closest('.row'), s = svcById(row.dataset.sid), i = +bar.dataset.i; if (!s) return; + const end = Math.floor(new Date(summary.generatedAt) / 3600e3) * 3600e3, start = end - (23 - i) * 3600e3, b = s.bars[i]; + const tm = (t) => new Date(t).toLocaleTimeString(T().locale, { hour: '2-digit', minute: '2-digit' }); + const t = document.createElement('div'); t.className = 'tip bt'; + t.innerHTML = `${new Date(start).toLocaleDateString(T().locale, { weekday: 'short', day: 'numeric', month: 'short' })} ${tm(start)}–${tm(start + 3600e3)}
` + (b[1] == null ? T().noData : `${T().uptimeL}: ${b[1]}%
${T().ping}: ${b[2] != null ? b[2] + ' ms' : '–'}`); + const sv = row.querySelector('.bars'); sv.style.position = 'relative'; sv.appendChild(t); + const bx = bar.getBoundingClientRect(), sx = sv.getBoundingClientRect(); t.style.left = Math.max(0, Math.min(bx.left - sx.left - 80, sx.width - 200)) + 'px'; t.style.top = '28px'; t.style.width = '200px'; + return; + } + closeTips(); + const row = e.target.closest('.row[data-sid]'); + if (row && !e.target.closest('a,.info,.tip')) openGraph(row.dataset.sid); +}); +document.addEventListener('keydown', (e) => { if (e.key === 'Enter' && e.target.matches?.('.row[data-sid]')) openGraph(e.target.dataset.sid); if (e.key === 'Escape') document.getElementById('gm')?.remove(); }); + +async function openGraph(id, range = '24h') { + const s = svcById(id); if (!s) return; + document.getElementById('gm')?.remove(); + const m = document.createElement('div'); m.id = 'gm'; m.className = 'gm'; + m.innerHTML = ``; + document.body.appendChild(m); + m.addEventListener('click', (e) => { if (e.target === m || e.target.id === 'gx') m.remove(); const r = e.target.dataset?.r; if (r) openGraph(id, r); }); + let d; try { d = await (await fetch(`/api/site/service/${id}?range=${range}`)).json(); } catch {} + if (!document.getElementById('gm')) return; + $('#gb').innerHTML = d?.points ? drawGraph(d, range) : `

${T().noData}

`; + const g = $('#gb svg'); if (g) wireGraph(g, d); +} +function drawGraph(d, range) { + const NARROW = innerWidth < 600, W = NARROW ? 360 : 760, H = NARROW ? 300 : 260, L = NARROW ? 36 : 44, R = 8, Tp = 10, B = 26, pw = W - L - R, ph = H - Tp - B; + const t1 = Date.now(), t0 = d.since, X = (t) => L + (t - t0) / (t1 - t0) * pw; + const pts = d.points.map(([t, n, ok, rt]) => ({ t: t + d.step / 2, n, ok, rt, down: ok / n < 0.5, part: ok / n < 0.98 && ok / n >= 0.5 })); + const rts = pts.filter((p) => !p.down && p.rt).map((p) => p.rt).sort((a, b) => a - b); + const med = rts.length ? rts[Math.floor(rts.length / 2)] : 0, thr = Math.max(med * 2.5, med + 150); + const top = Math.max(thr * 1.3, ...(rts.length ? [rts[Math.min(rts.length - 1, Math.floor(rts.length * .98))] * 1.1] : [100]), 50); + const Y = (v) => Tp + ph - Math.min(v, top) / top * ph; + const col = (p) => p.down ? '#ff5d6c' : (p.part || p.rt > thr) ? '#f5b942' : '#3ddc97'; + let seg = '', area = ''; + for (let i = 0; i < pts.length; i++) { + const p = pts[i], q = pts[i - 1], x = X(p.t), y = p.down ? Y(0) : Y(p.rt); + if (q && p.t - q.t < d.step * 2.5) { const qx = X(q.t), qy = q.down ? Y(0) : Y(q.rt); seg += ``; } + else seg += ``; + if (p.down) area += ``; + } + const grid = [0, .5, 1].map((f) => { const v = Math.round(top * f / 10) * 10, y = Y(v); return `${v}`; }).join(''); + const ticks = (NARROW ? [0, .5, 1] : [0, .25, .5, .75, 1]).map((f) => { const t = t0 + (t1 - t0) * f; return `${new Date(t).toLocaleString(T().locale, range === '24h' ? { hour: '2-digit', minute: '2-digit' } : { day: 'numeric', month: 'short' })}`; }).join(''); + const thrY = Y(thr); + const tot = pts.reduce((a, p) => a + p.n, 0), ok = pts.reduce((a, p) => a + p.ok, 0), avg = rts.length ? Math.round(rts.reduce((a, b) => a + b, 0) / rts.length) : null; + d._geo = { X, Y, L, pw, pts, t0, t1, thr, W }; + return `
${tot ? (ok / tot * 100).toFixed(2) + '%' : '–'}${T().uptimeL}
${avg ?? '–'}${avg != null ? ' ms' : ''}${T().ping} (${T().avgPing})
${tot}${T().checks}
+ ${grid}${area}${seg}${ticks}
+

${T().ping} · ${T().slow} · ${T().outage}

`; +} +function wireGraph(svg, d) { + const g = d._geo, gt = $('#gt'), gl = $('#gl', svg), gd = $('#gd', svg); + const mv = (ev) => { + const r = svg.getBoundingClientRect(), cx = (ev.touches ? ev.touches[0].clientX : ev.clientX), x = (cx - r.left) / r.width * g.W; + const tt = g.t0 + (x - g.L) / g.pw * (g.t1 - g.t0); let best = null; + for (const p of g.pts) if (!best || Math.abs(p.t - tt) < Math.abs(best.t - tt)) best = p; + if (!best) return; const px = g.X(best.t), py = best.down ? g.Y(0) : g.Y(best.rt); + gl.setAttribute('x1', px); gl.setAttribute('x2', px); gl.setAttribute('opacity', .5); gd.setAttribute('cx', px); gd.setAttribute('cy', py); gd.setAttribute('opacity', 1); + gd.setAttribute('fill', best.down ? '#ff5d6c' : best.part || best.rt > g.thr ? '#f5b942' : '#3ddc97'); + gt.textContent = `${new Date(best.t).toLocaleString(T().locale, { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' })} · ${best.down ? T().outage : best.rt + ' ms'} · ${(best.ok / best.n * 100).toFixed(0)}% (${best.n} ${T().checks})`; + }; + svg.addEventListener('mousemove', mv); svg.addEventListener('touchmove', mv, { passive: true }); svg.addEventListener('touchstart', mv, { passive: true }); +} + // Branding from Admin → Site fetch('/api/site/brand').then((r) => r.json()).then((b) => { const n = document.getElementById('brand-name'); if (n && b.name) n.textContent = b.name; if (b.accent) document.documentElement.style.setProperty('--acc', b.accent); }).catch(() => {}); diff --git a/src/views/admin/analytics.html b/src/views/admin/analytics.html new file mode 100644 index 0000000..76758e6 --- /dev/null +++ b/src/views/admin/analytics.html @@ -0,0 +1,26 @@ +Traffic · LocalPing + + +

Traffic

Cookie-free, privacy-friendly: visitors are counted with a daily-rotating hash, no IPs are stored, bots are excluded. Data is kept for 90 days.

+
+
–online now (5 min)
–unique visitors
–page views
–views / visitor
+

Visits over time

+

Countries

Cities

+

Pages

Referrers

+

Devices

Browsers

+

Link previews (Discord, X, …)

Times the link was unfurled by a platform.

+

Latest visits

+ diff --git a/src/views/admin/app.html b/src/views/admin/app.html new file mode 100644 index 0000000..9ffcaa4 --- /dev/null +++ b/src/views/admin/app.html @@ -0,0 +1,128 @@ +Admin · LocalPing + +
+ + diff --git a/src/views/admin/index.ejs b/src/views/admin/index.ejs index 17fa676..9574a75 100644 --- a/src/views/admin/index.ejs +++ b/src/views/admin/index.ejs @@ -1061,6 +1061,7 @@ Settings + Traffic Site Backup diff --git a/src/views/admin/login.ejs b/src/views/admin/login.ejs index 04102a0..f609788 100644 --- a/src/views/admin/login.ejs +++ b/src/views/admin/login.ejs @@ -1,144 +1,11 @@ - - - - - - Admin Login - LocalPing - - - - - - - - - +Admin login · LocalPing + +
+

Admin

Sign in to manage the site

+
+

+

← Back to site

+ diff --git a/src/views/admin/site.html b/src/views/admin/site.html index 31f17a6..d623168 100644 --- a/src/views/admin/site.html +++ b/src/views/admin/site.html @@ -1,19 +1,19 @@ Site settings · LocalPing - -
← Admin
-

Public site

+ + +

Public site

Branding & app icon

Used for the header, favicon and when installed as an app (PWA). PNG/WebP/JPEG/SVG, max 2 MB, square works best.

-

Services: explainers, tiers & links

Tier decides placement (featured = shown first). Untick “Link” for private services so no link to them is shown publicly.

-
ServiceTierLinkExplainer (shown in ⓘ)
+

Services: explainers, tiers & links

Tier decides placement (quick = big cards on the home page, featured = top of the list). Untick “Link” for private services so no link to them is shown publicly.

+
ServiceTierLinkExplainers (ⓘ)
- - - -
-
- -
-

LocalPing

-

Initial Setup Wizard

-
- - -
- <% if (error) { %> -
-

Error: <%= error %>

-
- <% } %> - -
- -
-

Admin Credentials

- -
- - -

Used to log in to the admin panel

-
- -
- - -
- -
- - -
-
- - -
-

Network Configuration

- -
- - -

- <% if (detectedGateway) { %> - ✓ Auto-detected: <%= detectedGateway %> (you can change this) - <% } else { %> - Enter your network gateway IP address - <% } %> -

-
-
- - -
-

- Default monitors will be created for: -

-
    -
  • ✓ Gateway monitoring (ICMP ping)
  • -
  • ✓ Cloudflare DNS at 1.1.1.1 (ICMP ping)
  • -
-
- - -
- -
- -

- By completing setup, you agree that LocalPing will monitor your network -

-
-
- - -

- LocalPing • Homelab Dashboard & System Monitor -

-
-
- - - - +Setup · LocalPing + +
+

Welcome to LocalPing

Create your admin account to get started

+<% if (error) { %>
<%= error %>
<% } %> +
+ + + + +

<% if (detectedGateway) { %>Auto-detected: <%= detectedGateway %> (you can change this)<% } else { %>Could not auto-detect the gateway. Enter your router IP.<% } %>

+