${esc(p.title)}
${esc(p.content)}
.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'}
-
+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.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)}
- ${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)}
+ ${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 || [])}
-
- ${news?.posts?.length ? `Latest news
${news.posts.slice(0, 2).map(post).join('')}All news →` : ''}`;
+
+ ${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).
- Contact
`;
+ return ``;
},
};
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.area ? '' : t.input ? `` : ''}
+ return `${T().toolsH1}
${T().toolsLead}
${tl.map((t) => `${t.name}
+ ${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 = `${icon(s)}${esc(s.name)}${s.status === 'up' ? T().up : s.status === 'down' ? T().dn : T().unk}
+ ${[['24h', T().r24], ['7d', T().r7], ['30d', T().r30]].map(([r, l]) => ``).join('')}
+ `;
+ 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}
+
+ `;
+}
+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, …)
+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
-
-
-
-
-
-
-
-
- LocalPing
- Admin Panel
-
-
-
-
- Admin Login
-
-
-
-
-
-
-
- Forgot your password? Reset setup
-
-
-
-
-
-
- LocalPing • Homelab Dashboard & System Monitor
-
-
-
-
-
-
-
+Admin login · LocalPing
+
+
+
Admin
Sign in to manage the 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
-Services: explainers, tiers & links
-Service Tier Link Explainer (shown in ⓘ)
+Services: explainers, tiers & links
+Service Tier Link Explainers (ⓘ)
-
-
-
-
-
-
-
- LocalPing
- Initial Setup Wizard
-
-
-
-
- <% if (error) { %>
-
- Error: <%= error %>
-
- <% } %>
-
-
-
-
-
-
- LocalPing • Homelab Dashboard & System Monitor
-
-
-
-
-
-
-
+Setup · LocalPing
+
+
+
Welcome to LocalPing
Create your admin account to get started
+<% if (error) { %><%= error %><% } %>
+