Template: languages (en/da/de), admin UI, discovery, no site data
This commit is contained in:
1 parent
cb61a7d457
commit
5f4c10df49
20 files changed
+1124
-438
No files matched your search
@@ -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.
|
||||
<img src="src/public/ms-icon-310x310.png" alt="LocalPing Logo" width="200" style="border-radius: 20px;">
|
||||
|
||||
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://<host>: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://<your-ip>:8000/setup`
|
||||
2. Create admin username and password
|
||||
3. Configure gateway IP (auto-detected)
|
||||
4. Complete setup and login at `http://<your-ip>: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
|
||||
@@ -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")
|
||||
}
|
||||
+12
-3
@@ -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(',') : '')));
|
||||
}
|
||||
|
||||
+66
-26
@@ -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];
|
||||
|
||||
+104
-6
@@ -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/<code>.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 }; };
|
||||
|
||||
|
||||
@@ -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 };
|
||||
@@ -0,0 +1,20 @@
|
||||
// Shared admin header/nav, injected into every new-style admin page.
|
||||
(() => {
|
||||
const I = {
|
||||
mon: '<path d="M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"/>',
|
||||
inc: '<path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"/><path d="M12 9v4"/><path d="M12 17h.01"/>',
|
||||
post: '<path d="M15 18h-5"/><path d="M18 14h-8"/><path d="M4 22h16a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v16a2 2 0 0 1-4 0v-9a2 2 0 0 1 2-2h2"/><rect width="8" height="4" x="10" y="6" rx="1"/>',
|
||||
tr: '<path d="M3 3v16a2 2 0 0 0 2 2h16"/><path d="M18 17V9"/><path d="M13 17V5"/><path d="M8 17v-3"/>',
|
||||
site: '<circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/>',
|
||||
more: '<circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/><circle cx="5" cy="12" r="1"/>',
|
||||
};
|
||||
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 = `<a class="brand" href="/admin"><span class="dot operational"></span><span>Admin<span class="muted"> · LocalPing</span></span></a>
|
||||
<nav class="adm-nav" aria-label="Admin">${items.map(([h, l, i]) => `<a href="${h}" class="${on(h) ? 'on' : ''}"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${I[i]}</svg><span>${l}</span></a>`).join('')}</nav>
|
||||
<span class="btns" style="margin:0"><a href="/" class="ghost" style="padding:5px 10px;border:1px solid var(--line);border-radius:10px;color:var(--text)">View site</a><a href="/admin/logout" style="padding:5px 8px;color:var(--muted)">Sign out</a></span>`;
|
||||
document.body.prepend(hdr);
|
||||
})();
|
||||
@@ -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}
|
||||
}
|
||||
+10
-8
@@ -4,8 +4,8 @@
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<title>Status</title>
|
||||
<meta name="description" content="Live status, incident history, news and small tools for the services on example.com.">
|
||||
<meta name="theme-color" content="#0b0d12">
|
||||
<meta name="description" content="Live status, incident history, news and small tools for the services.">
|
||||
<meta name="theme-color" content="#6ea8ff">
|
||||
<link rel="icon" href="/brand/icon-32.png"><link rel="apple-touch-icon" href="/brand/icon-180.png"><link rel="manifest" href="/manifest.webmanifest">
|
||||
<link rel="alternate" type="application/rss+xml" title="News" href="/api/site/news.rss">
|
||||
<link rel="stylesheet" href="/s/site.css">
|
||||
@@ -16,18 +16,20 @@
|
||||
<header class="top">
|
||||
<a class="brand" href="/" data-link><span class="dot" id="brand-dot"></span><span id="brand-name">Status</span></a>
|
||||
<nav id="nav" aria-label="Main">
|
||||
<a href="/" data-link>Overview</a>
|
||||
<a href="/status" data-link>Status</a>
|
||||
<a href="/news" data-link>News</a>
|
||||
<a href="/tools" data-link>Tools</a>
|
||||
<a href="/about" data-link>About</a>
|
||||
<a href="/" data-link><svg class="ni" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8"/><path d="M3 10a2 2 0 0 1 .709-1.528l7-5.999a2 2 0 0 1 2.582 0l7 5.999A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg><span>Overview</span></a>
|
||||
<a href="/status" data-link><svg class="ni" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"/></svg><span>Status</span></a>
|
||||
<a href="/news" data-link><svg class="ni" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15 18h-5"/><path d="M18 14h-8"/><path d="M4 22h16a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v16a2 2 0 0 1-4 0v-9a2 2 0 0 1 2-2h2"/><rect width="8" height="4" x="10" y="6" rx="1"/></svg><span>News</span></a>
|
||||
<a href="/tools" data-link><svg class="ni" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94z"/></svg><span>Tools</span></a>
|
||||
<a href="/about" data-link><svg class="ni" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg><span>About</span></a>
|
||||
</nav>
|
||||
<button id="lang-btn" class="ghost lang" type="button" aria-label="Language" hidden></button>
|
||||
<select id="lang-sel" class="ghost lang" aria-label="Language" hidden></select>
|
||||
</header>
|
||||
<main id="main" tabindex="-1"><div class="wrap"><div class="skeleton"></div></div></main>
|
||||
<footer class="foot">
|
||||
<div class="wrap">
|
||||
<span>© <span id="yr"></span> <span class="site-owner">Your Name</span></span>
|
||||
<span><a href="mailto:[email protected]">[email protected]</a> · <a href="/api/site/news.rss">RSS</a></span>
|
||||
<span class="fl"><a href="mailto:[email protected]">[email protected]</a> · <a href="/api/site/news.rss">RSS</a> · <a href="/admin/login" class="adm" rel="nofollow">Admin</a></span>
|
||||
<span>Powered by <a href="https://github.com/YOUR-ORG/localping">LocalPing</a></span>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
@@ -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"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -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"]}
|
||||
}
|
||||
@@ -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": []
|
||||
}
|
||||
}
|
||||
@@ -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}
|
||||
}
|
||||
+166
-43
@@ -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/<code>.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) => `<option value="${l.code}" ${l.code === LANG ? 'selected' : ''}>${l.flag} ${l.name}</option>`).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) ? '<div class="stale">Live data is unavailable right now. Showing the last known state.</div>' : '';
|
||||
const stale = () => (!lastOk || Date.now() - lastOk > 120e3) ? `<div class="stale">${T().stale}</div>` : '';
|
||||
|
||||
const icon = (s) => s.icon ? `<img loading="lazy" decoding="async" width="24" height="24" alt="" src="/api/proxy-icon?url=${encodeURIComponent(s.icon)}">` : '<div class="ph"></div>';
|
||||
const row = (s) => `<div class="row">
|
||||
<div class="svc">${icon(s)}<span>${s.url ? `<a href="${esc(s.url)}" rel="noopener">${esc(s.name)}</a>` : esc(s.name)}</span>${s.description ? `<button class="info" type="button" aria-label="About ${esc(s.name)}" aria-expanded="false" data-info="${esc(s.description)}">i</button>` : ''}</div>
|
||||
<span class="pill ${esc(s.status)}">${s.status === 'up' ? 'Operational' : s.status === 'down' ? 'Down' : 'Unknown'}</span>
|
||||
<div class="bars" title="Last 24 hours, hourly">${s.bars.map((b) => `<i class="b${b}"></i>`).join('')}</div>
|
||||
const icon = (s) => s.icon ? `<img loading="lazy" decoding="async" width="24" height="24" alt="" src="${esc(s.icon)}">` : '<div class="ph"></div>';
|
||||
const row = (s) => `<div class="row" data-sid="${esc(s.id)}" tabindex="0">
|
||||
<div class="svc">${icon(s)}<span>${s.url ? `<a href="${esc(s.url)}" rel="noopener">${esc(s.name)}</a>` : esc(s.name)}</span>${descOf(s) ? `<button class="info" type="button" aria-label="${T().about} ${esc(s.name)}" aria-expanded="false" data-info="${esc(descOf(s))}">i</button>` : ''}</div>
|
||||
<span class="pill ${esc(s.status)}">${s.status === 'up' ? T().up : s.status === 'down' ? T().dn : T().unk}</span>
|
||||
<div class="bars" title="${T().bars}">${s.bars.map((b, i) => `<i class="b${b[0]}" data-i="${i}"></i>`).join('')}</div>
|
||||
<div class="pc">${s.up30 == null ? '–' : s.up30.toFixed(1) + '%'}</div></div>`;
|
||||
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 ? `<h2>${h}</h2><div class="list">${l.map(row).join('')}</div>` : ''; }).join('');
|
||||
const qdesc = descOf;
|
||||
const quick = (list) => { const q = list.filter((s) => s.tier === 'quick'); return q.length ? `<h2>${T().quick}</h2><div class="quick">${q.map((s) => `<a class="qc" href="${esc(s.url || '#')}" rel="noopener"><div class="qi">${icon(s)}<span class="dot ${s.status === 'up' ? 'operational' : s.status === 'down' ? 'down' : ''}" title="${s.status === 'up' ? T().up : T().dn}"></span></div><b>${esc(s.name)}</b><span>${esc(qdesc(s))}</span></a>`).join('')}</div>` : ''; };
|
||||
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 ? `<h2>${T()[t]}</h2><div class="list">${l.map(row).join('')}</div>` : ''; }).join('');
|
||||
|
||||
function banner(d) {
|
||||
return `<div class="banner ${d.overall}"><span class="dot ${d.overall}"></span><div><div class="big">${LABEL[d.overall]}</div><small>${d.up} of ${d.total} services up · updated ${ago(d.generatedAt)}</small></div></div>`;
|
||||
return `<div class="banner ${d.overall}"><span class="dot ${d.overall}"></span><div><div class="big">${T()[d.overall]}</div><small>${T().servicesUp(d.up, d.total)} · ${T().updated} ${ago(d.generatedAt)}</small></div></div>`;
|
||||
}
|
||||
const incCard = (i) => `<div class="card"><h3><span class="tag ${i.scheduled ? 'scheduled' : esc(i.severity)}">${i.scheduled ? 'scheduled' : esc(i.severity)}</span><span class="tag ${esc(i.status)}">${esc(i.status)}</span>${esc(i.title)}</h3>
|
||||
<div class="meta">${fmt(i.scheduled && i.start ? i.start : i.createdAt)}${i.resolvedAt ? ' · resolved ' + fmt(i.resolvedAt) : ''}</div>${i.description ? `<p>${esc(i.description)}</p>` : ''}</div>`;
|
||||
const incCard = (i) => `<div class="card"><h3><span class="tag ${i.scheduled ? 'scheduled' : esc(i.severity)}">${i.scheduled ? T().scheduled : esc(T().sev[i.severity] || i.severity)}</span><span class="tag ${esc(i.status)}">${esc(T().st[i.status] || i.status)}</span>${esc(i.title)}</h3>
|
||||
<div class="meta">${fmt(i.scheduled && i.start ? i.start : i.createdAt)}${i.resolvedAt ? ' · ' + T().resolved + ' ' + fmt(i.resolvedAt) : ''}</div>${i.description ? `<p>${esc(i.description)}</p>` : ''}</div>`;
|
||||
|
||||
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 `<div class="wrap">${stale()}<h1>Service status</h1><p class="lead">Live health, incidents and news.</p>
|
||||
return `<div class="wrap">${stale()}<h1>${T().homeH1}</h1><p class="lead">${T().homeLead}</p>
|
||||
${d ? banner(d) : ''}
|
||||
${active.length ? `<h2>Active & upcoming</h2>${active.map(incCard).join('')}` : ''}
|
||||
${quick(d?.services || [])}
|
||||
${active.length ? `<h2>${T().active}</h2>${active.map(incCard).join('')}` : ''}
|
||||
${groups(d?.services || [])}
|
||||
<p class="meta">Bars show the last 24 hours. Percentage is 30-day uptime. <a href="/status" data-link>Full status & history →</a></p>
|
||||
${news?.posts?.length ? `<h2>Latest news</h2>${news.posts.slice(0, 2).map(post).join('')}<a href="/news" data-link>All news →</a>` : ''}</div>`;
|
||||
<p class="meta">${T().barsNote} ${T().clickHint} <a href="/status" data-link>${T().fullStatus}</a></p>
|
||||
${news?.posts?.length ? `<h2>${T().latestNews}</h2>${news.posts.slice(0, 2).map(post).join('')}<a href="/news" data-link>${T().allNews}</a>` : ''}</div>`;
|
||||
},
|
||||
async '/status'() {
|
||||
const d = await load(); if (!d) return `<div class="wrap">${stale()}<h1>Status</h1></div>`;
|
||||
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 `<div class="wrap">${stale()}<h1>Status</h1><p class="lead">Checked every minute from a monitor on a separate host.</p>${banner(d)}
|
||||
<div class="stats"><div class="stat"><b>${d.up}/${d.total}</b><span>services up</span></div><div class="stat"><b>${u}%</b><span>avg 30-day uptime</span></div><div class="stat"><b>${rt}${rt === '–' ? '' : ' ms'}</b><span>avg response (24h)</span></div></div>
|
||||
return `<div class="wrap">${stale()}<h1>${T().statusH1}</h1><p class="lead">${T().statusLead}</p>${banner(d)}
|
||||
<div class="stats"><div class="stat"><b>${d.up}/${d.total}</b><span>${T().sUp}</span></div><div class="stat"><b>${u}%</b><span>${T().sAvg}</span></div><div class="stat"><b>${rt}${rt === '–' ? '' : ' ms'}</b><span>${T().sRt}</span></div></div>
|
||||
${groups(d.services)}
|
||||
<h2>Incident history</h2>${d.incidents.length ? d.incidents.map(incCard).join('') : '<p class="muted">No incidents recorded.</p>'}</div>`;
|
||||
<h2>${T().history}</h2>${d.incidents.length ? d.incidents.map(incCard).join('') : `<p class="muted">${T().noInc}</p>`}</div>`;
|
||||
},
|
||||
async '/news'() {
|
||||
const r = await fetch('/api/site/news').then((x) => x.json()).catch(() => null);
|
||||
return `<div class="wrap"><h1>News</h1><p class="lead">Announcements, changes and maintenance notes. <a href="/api/site/news.rss">RSS feed</a></p>${r?.posts?.length ? r.posts.map(post).join('') : '<p class="muted">Nothing yet.</p>'}</div>`;
|
||||
return `<div class="wrap"><h1>${T().newsH1}</h1><p class="lead">${T().newsLead} <a href="/api/site/news.rss">${T().rss}</a></p>${r?.posts?.length ? r.posts.map(post).join('') : `<p class="muted">${T().nothing}</p>`}</div>`;
|
||||
},
|
||||
async '/tools'() { return toolsView(); },
|
||||
async '/about'() {
|
||||
return `<div class="wrap"><h1>About</h1><p class="lead">Edit this page in src/site/site.js (or point SITE_DIR at your own theme).</p>
|
||||
<div class="card"><h3>Contact</h3><p><a href="mailto:[email protected]">[email protected]</a></p></div></div>`;
|
||||
return `<div class="wrap"><h1>${T().aboutH1}</h1><p class="lead">${T().aboutLead}</p>
|
||||
<div class="card"><h3>${T().contact}</h3><p><a href="mailto:[email protected]">[email protected]</a></p></div></div>`;
|
||||
},
|
||||
};
|
||||
const post = (p) => `<article class="card" id="${esc(p.id)}"><h3>${esc(p.title)}</h3><time>${fmt(p.createdAt)}</time><p>${esc(p.content)}</p></article>`;
|
||||
|
||||
// ---- 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 `<div class="wrap"><h1>Tools</h1><p class="lead">Small utilities. Everything except the IP check runs in your browser.</p><div class="grid">${tools.map((t) => `<div class="card" id="t-${t.id}"><h3>${t.name}</h3><div class="meta">${t.desc}</div>
|
||||
${t.area ? '<textarea placeholder="Input"></textarea>' : t.input ? `<input value="${esc(t.input)}" placeholder="${esc(t.input)}">` : ''}
|
||||
return `<div class="wrap"><h1>${T().toolsH1}</h1><p class="lead">${T().toolsLead}</p><div class="grid">${tl.map((t) => `<div class="card" id="t-${t.id}"><h3>${t.name}</h3><div class="meta">${t.desc}</div>
|
||||
${t.area ? '<textarea placeholder="${T().input}"></textarea>' : t.input ? `<input value="${esc(t.input)}" placeholder="${esc(t.input)}">` : ''}
|
||||
${t.modes ? `<div class="btns">${t.modes.map(([m, l]) => `<button data-m="${m}">${l}</button>`).join('')}</div>` : ''}<div class="out"></div></div>`).join('')}</div></div>`;
|
||||
}
|
||||
|
||||
// ---- 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 = `<b>${new Date(start).toLocaleDateString(T().locale, { weekday: 'short', day: 'numeric', month: 'short' })} ${tm(start)}–${tm(start + 3600e3)}</b><br>` + (b[1] == null ? T().noData : `${T().uptimeL}: ${b[1]}%<br>${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 = `<div class="gc" role="dialog" aria-modal="true"><div class="gh"><div class="svc">${icon(s)}<b>${esc(s.name)}</b><span class="pill ${esc(s.status)}">${s.status === 'up' ? T().up : s.status === 'down' ? T().dn : T().unk}</span></div><button class="ghost" id="gx" aria-label="${T().close}">✕</button></div>
|
||||
<div class="btns" id="gr">${[['24h', T().r24], ['7d', T().r7], ['30d', T().r30]].map(([r, l]) => `<button data-r="${r}" class="${r === range ? '' : 'ghost'}">${l}</button>`).join('')}</div>
|
||||
<div id="gb"><div class="skeleton" style="height:240px"></div></div></div>`;
|
||||
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) : `<p class="muted">${T().noData}</p>`;
|
||||
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 += `<line x1="${qx.toFixed(1)}" y1="${qy.toFixed(1)}" x2="${x.toFixed(1)}" y2="${y.toFixed(1)}" stroke="${col(p)}" stroke-width="2.2" stroke-linecap="round"/>`; }
|
||||
else seg += `<circle cx="${x.toFixed(1)}" cy="${y.toFixed(1)}" r="1.8" fill="${col(p)}"/>`;
|
||||
if (p.down) area += `<rect x="${(X(p.t - d.step / 2)).toFixed(1)}" y="${Tp}" width="${Math.max(2, pw * d.step / (t1 - t0)).toFixed(1)}" height="${ph}" fill="#ff5d6c" opacity=".12"/>`;
|
||||
}
|
||||
const grid = [0, .5, 1].map((f) => { const v = Math.round(top * f / 10) * 10, y = Y(v); return `<line x1="${L}" x2="${W - R}" y1="${y}" y2="${y}" stroke="#232836"/><text x="${L - 6}" y="${y + 4}" text-anchor="end" fill="#8a93a6" font-size="${NARROW ? 13 : 11}">${v}</text>`; }).join('');
|
||||
const ticks = (NARROW ? [0, .5, 1] : [0, .25, .5, .75, 1]).map((f) => { const t = t0 + (t1 - t0) * f; return `<text x="${L + pw * f}" y="${H - 6}" text-anchor="${f === 0 ? 'start' : f === 1 ? 'end' : 'middle'}" fill="#8a93a6" font-size="${NARROW ? 13 : 11}">${new Date(t).toLocaleString(T().locale, range === '24h' ? { hour: '2-digit', minute: '2-digit' } : { day: 'numeric', month: 'short' })}</text>`; }).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 `<div class="stats g3"><div class="stat"><b>${tot ? (ok / tot * 100).toFixed(2) + '%' : '–'}</b><span>${T().uptimeL}</span></div><div class="stat"><b>${avg ?? '–'}${avg != null ? ' ms' : ''}</b><span>${T().ping} (${T().avgPing})</span></div><div class="stat"><b>${tot}</b><span>${T().checks}</span></div></div>
|
||||
<svg viewBox="0 0 ${W} ${H}" class="gsvg" role="img" aria-label="${T().ping}">${grid}${area}<line x1="${L}" x2="${W - R}" y1="${thrY}" y2="${thrY}" stroke="#f5b942" stroke-dasharray="4 4" opacity=".35"/>${seg}${ticks}<line id="gl" y1="${Tp}" y2="${Tp + ph}" stroke="#8a93a6" opacity="0" /><circle id="gd" r="4" opacity="0"/></svg><div id="gt" class="gt"></div>
|
||||
<p class="meta"><span class="lg" style="background:#3ddc97"></span>${T().ping} · <span class="lg" style="background:#f5b942"></span>${T().slow} · <span class="lg" style="background:#ff5d6c"></span>${T().outage}</p>`;
|
||||
}
|
||||
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(() => {});
|
||||
@@ -0,0 +1,26 @@
|
||||
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Traffic · LocalPing</title>
|
||||
<link rel="stylesheet" href="/s/site.css"><link rel="stylesheet" href="/s/admin.css"><style>.chart{display:flex;align-items:flex-end;gap:2px;height:120px;margin:10px 0}.chart i{flex:1;background:var(--acc);border-radius:2px 2px 0 0;min-height:2px;opacity:.85}.two{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:12px}.kv{display:flex;justify-content:space-between;gap:10px;padding:5px 0;border-top:1px solid var(--line);font-size:14px}.kv:first-of-type{border:0}.kv span:first-child{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.live{display:inline-block;width:9px;height:9px;border-radius:50%;background:var(--ok);box-shadow:0 0 8px var(--ok);margin-right:6px}.btns button.on{background:var(--acc);color:#07101f}</style></head>
|
||||
<body>
|
||||
<script src="/s/admin-nav.js"></script><main><div class="wrap"><h1>Traffic</h1><p class="lead">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.</p>
|
||||
<div class="btns" id="rng"><button data-r="24h" class="on">24 hours</button><button data-r="7d" class="ghost">7 days</button><button data-r="30d" class="ghost">30 days</button></div>
|
||||
<div class="stats"><div class="stat"><b><span class="live"></span><span id="online">–</span></b><span>online now (5 min)</span></div><div class="stat"><b id="visitors">–</b><span>unique visitors</span></div><div class="stat"><b id="views">–</b><span>page views</span></div><div class="stat"><b id="pv">–</b><span>views / visitor</span></div></div>
|
||||
<div class="card"><h3>Visits over time</h3><div class="chart" id="chart"></div><div class="meta" id="axis"></div></div>
|
||||
<div class="two"><div class="card"><h3>Countries</h3><div id="countries"></div></div><div class="card"><h3>Cities</h3><div id="cities"></div></div>
|
||||
<div class="card"><h3>Pages</h3><div id="pages"></div></div><div class="card"><h3>Referrers</h3><div id="referrers"></div></div>
|
||||
<div class="card"><h3>Devices</h3><div id="devices"></div></div><div class="card"><h3>Browsers</h3><div id="browsers"></div></div>
|
||||
<div class="card"><h3>Link previews (Discord, X, …)</h3><p class="meta">Times the link was unfurled by a platform.</p><div id="previews"></div></div></div>
|
||||
<div class="card"><h3>Latest visits</h3><div id="recent"></div></div></div></main>
|
||||
<script>
|
||||
const $=s=>document.querySelector(s);let R='24h';
|
||||
const flag=c=>c&&c.length===2?String.fromCodePoint(...[...c.toUpperCase()].map(x=>127397+x.charCodeAt())):'';
|
||||
const esc=s=>String(s??'').replace(/[&<>"]/g,c=>({'&':'&','<':'<','>':'>','"':'"'}[c]));
|
||||
const kv=(el,rows,f=x=>x)=>{$(el).innerHTML=rows.length?rows.map(r=>`<div class="kv"><span>${esc(f(r.k))}</span><span>${r.views}${r.visitors!=null?' · '+r.visitors+' <span class="muted">uniq</span>':''}</span></div>`).join(''):'<span class="muted">No data yet</span>'};
|
||||
async function load(){const d=await fetch('/admin/api/analytics?range='+R).then(r=>r.json());if(d.error)return;
|
||||
$('#online').textContent=d.online;$('#visitors').textContent=d.visitors;$('#views').textContent=d.views;$('#pv').textContent=d.visitors?(d.views/d.visitors).toFixed(1):'–';
|
||||
const mx=Math.max(1,...d.series.map(x=>x.views));$('#chart').innerHTML=d.series.map(x=>`<i style="height:${x.views/mx*100}%" title="${new Date(x.t).toLocaleString()}: ${x.views} views, ${x.visitors} visitors"></i>`).join('')||'<span class="muted">No data yet</span>';
|
||||
$('#axis').textContent=d.series.length?new Date(d.series[0].t).toLocaleString()+' → now':'';
|
||||
kv('#countries',d.countries,k=>flag(k)+' '+(new Intl.DisplayNames(['en'],{type:'region'}).of(k)||k));kv('#cities',d.cities);kv('#pages',d.pages);kv('#referrers',d.referrers);kv('#devices',d.devices);kv('#browsers',d.browsers);kv('#previews',d.previews);
|
||||
$('#recent').innerHTML=d.recent.map(v=>`<div class="kv"><span>${v.bot?'🔗 preview ('+esc(v.browser)+')':esc(v.path)} · ${flag(v.country)} ${esc(v.city||v.country||'?')} ${v.bot?'':'· '+esc(v.device)+' '+esc(v.browser)}${v.referrer?' · from '+esc(v.referrer):''}</span><span class="muted">${new Date(v.ts).toLocaleTimeString()}</span></div>`).join('')||'<span class="muted">No visits yet</span>'}
|
||||
$('#rng').onclick=e=>{const r=e.target.dataset.r;if(!r)return;R=r;document.querySelectorAll('#rng button').forEach(b=>b.className=b.dataset.r===r?'on':'ghost');load()};
|
||||
load();setInterval(load,15000);
|
||||
</script></body></html>
|
||||
@@ -0,0 +1,128 @@
|
||||
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex"><title>Admin · LocalPing</title>
|
||||
<link rel="icon" href="/brand/icon-32.png"><link rel="stylesheet" href="/s/site.css"><link rel="stylesheet" href="/s/admin.css"></head>
|
||||
<body><main><div class="wrap" id="app"></div></main>
|
||||
<script src="/s/admin-nav.js"></script>
|
||||
<script>
|
||||
const $=(s,r=document)=>r.querySelector(s),esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||
const app=$('#app'),page=location.pathname.replace(/\/$/,'');
|
||||
async function api(u,m='GET',b){const r=await fetch('/admin/api'+u,{method:m,headers:{'content-type':'application/json',accept:'application/json'},body:b?JSON.stringify(b):undefined});if(r.status===401){location='/admin/login';throw 0}const d=await r.json().catch(()=>({}));if(!r.ok||d.success===false)throw new Error(d.error||'Request failed');return d}
|
||||
function toast(t,err){const e=document.createElement('div');e.className='toast'+(err?' err':'');e.textContent=t;document.body.appendChild(e);setTimeout(()=>e.remove(),2600)}
|
||||
function modal(title,body,onSave,extra=''){const m=document.createElement('div');m.className='mo';m.innerHTML=`<div class="mc"><h3>${esc(title)}</h3><form>${body}<div class="btns"><button type="button" class="ghost" data-x>Cancel</button>${extra}<button type="submit">Save</button></div></form></div>`;document.body.appendChild(m);
|
||||
m.addEventListener('click',e=>{if(e.target===m||e.target.dataset.x!==undefined)m.remove()});
|
||||
$('form',m).addEventListener('submit',async e=>{e.preventDefault();const f=new FormData(e.target),o={};for(const el of e.target.elements){if(!el.name)continue;o[el.name]=el.type==='checkbox'?el.checked:el.value}
|
||||
try{await onSave(o);m.remove()}catch(x){if(x)toast(x.message,1)}});return m}
|
||||
const f=(n,l,v='',t='text',x='')=>`<label>${l}<input name="${n}" type="${t}" value="${esc(v)}" ${x}></label>`;
|
||||
const ck=(n,l,v)=>`<label class="chk"><input type="checkbox" name="${n}" ${v?'checked':''}>${l}</label>`;
|
||||
const sel=(n,l,opts,v)=>`<label>${l}<select name="${n}">${opts.map(o=>`<option ${o===v?'selected':''}>${o}</option>`).join('')}</select></label>`;
|
||||
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()};
|
||||
|
||||
// ---------- Monitors ----------
|
||||
async function monitors(){
|
||||
let list=[],q='';
|
||||
const draw=()=>{const l=list.filter(t=>!q||(t.name+t.host).toLowerCase().includes(q)).sort((a,b)=>(a.position-b.position)||a.name.localeCompare(b.name));
|
||||
$('#list').innerHTML=l.map(t=>`<div class="ar ${t.enabled?'':'dim'}" data-id="${t.id}"><div class="nm"><b>${esc(t.name)}</b><small>${esc(t.protocol)} · ${esc(t.host)}${t.port?':'+t.port:''} · every ${t.interval}s</small></div>
|
||||
<span class="pill ${!t.enabled?'unknown':t.currentStatus==='up'?'up':t.currentStatus==='down'?'down':'unknown'}">${!t.enabled?'Paused':t.currentStatus==='up'?'Up':t.currentStatus==='down'?'Down':'…'}</span>
|
||||
<span class="muted" style="font-size:12px">${t.publicVisible?'public':'hidden'}</span><div class="acts"><button class="sm ghost" data-a="test">Test</button><button class="sm ghost" data-a="edit">Edit</button><button class="sm ghost" data-a="tog">${t.enabled?'Pause':'Resume'}</button></div></div>`).join('')||'<div class="ar">No monitors</div>';
|
||||
const up=list.filter(t=>t.enabled&&t.currentStatus==='up').length,dn=list.filter(t=>t.enabled&&t.currentStatus==='down').length;$('#sum').textContent=`${list.length} monitors · ${up} up · ${dn} down · ${list.filter(t=>!t.enabled).length} paused`};
|
||||
const load=async()=>{list=(await api('/targets')).targets;draw()};
|
||||
app.innerHTML=`<h1>Monitors</h1><p class="lead" id="sum">Loading…</p><div class="toolbar"><input type="search" id="q" placeholder="Search…"><button id="add">+ Add monitor</button></div><div class="list" id="list"></div>`;
|
||||
$('#q').oninput=e=>{q=e.target.value.toLowerCase();draw()};
|
||||
const form=t=>f('name','Name',t.name,'text','required')+sel('protocol','Protocol',['HTTPS','HTTP','TCP','UDP','ICMP'],t.protocol||'HTTPS')+f('host','Host / IP',t.host,'text','required')+f('port','Port',t.port??'','number')+f('path','Path',t.path||'')+f('interval','Interval (s)',t.interval||60,'number','min=10')+f('retries','Retries',t.retries??1,'number','min=0')+f('timeout','Timeout (s)',t.timeout||30,'number','min=1')+f('statusCodes','OK status codes',t.statusCodes||'200-299')+sel('httpMethod','HTTP method',['GET','HEAD','POST'],t.httpMethod||'GET')+f('appUrl','App URL',t.appUrl||'','text','class="full"')+f('appIcon','Icon URL',t.appIcon||'')+`<div class="full">${ck('publicVisible','Show on public site',t.publicVisible!==false)}${ck('ignoreSsl','Ignore TLS errors',t.ignoreSsl)}${ck('upsideDown','Upside-down (down = OK)',t.upsideDown)}${ck('enabled','Enabled',t.enabled!==false)}</div>`;
|
||||
const clean=o=>{['port','interval','retries','timeout'].forEach(k=>{o[k]=o[k]===''?null:Number(o[k])});if(o.port===null)delete o.port;return o};
|
||||
$('#add').onclick=()=>modal('Add monitor',`<div class="fm">${form({})}</div>`,async o=>{await api('/targets','POST',clean(o));toast('Added');load()});
|
||||
$('#list').onclick=async e=>{const b=e.target.closest('button');if(!b)return;const t=list.find(x=>x.id===b.closest('.ar').dataset.id);
|
||||
if(b.dataset.a==='tog'){await api('/targets/'+t.id,'PUT',{enabled:!t.enabled});load()}
|
||||
if(b.dataset.a==='test'){b.textContent='…';try{const r=await api('/targets/'+t.id+'/test','POST');toast(r.success?`OK${r.result?.responseTime!=null?' · '+r.result.responseTime+' ms':''}`:'Check failed: '+(r.result?.error||''),!r.success)}catch(x){toast(x.message,1)}b.textContent='Test';load()}
|
||||
if(b.dataset.a==='edit')modal('Edit '+t.name,`<div class="fm">${form(t)}</div>`,async o=>{await api('/targets/'+t.id,'PUT',clean(o));toast('Saved');load()},`<button type="button" class="danger" data-del>Delete</button>`).addEventListener('click',async ev=>{if(ev.target.dataset.del!==undefined&&confirm('Delete '+t.name+' and ALL its history?')){await api('/targets/'+t.id,'DELETE');ev.currentTarget.remove();toast('Deleted');load()}})};
|
||||
load();setInterval(()=>{if(!document.querySelector('.mo')&&!document.hidden)load()},30000);
|
||||
}
|
||||
|
||||
// ---------- Incidents ----------
|
||||
async function incidents(){
|
||||
let list=[],names=[];
|
||||
const draw=()=>{$('#list').innerHTML=list.map(i=>`<div class="card" data-id="${i.id}"><h3><span class="tag ${i.isScheduled?'scheduled':esc(i.severity)}">${i.isScheduled?'scheduled':esc(i.severity)}</span><span class="tag ${esc(i.status)}">${esc(i.status)}</span>${esc(i.title)}</h3><div class="meta">${new Date(i.createdAt).toLocaleString()}${i.resolvedAt?' · resolved '+new Date(i.resolvedAt).toLocaleString():''}</div><p>${esc(i.description||'')}</p>${(i.updates||[]).slice(1).map(u=>`<div class="upd"><b>${esc(u.status)}</b> · ${ago(u.timestamp)}<br>${esc(u.message)}</div>`).join('')}<div class="btns"><button class="sm" data-a="upd">Post update</button><button class="sm ghost" data-a="edit">Edit</button><button class="sm danger" data-a="del">Delete</button></div></div>`).join('')||'<p class="muted">No incidents.</p>'};
|
||||
const load=async()=>{list=(await api('/incidents')).incidents;list.sort((a,b)=>new Date(b.createdAt)-new Date(a.createdAt));draw()};
|
||||
names=(await api('/targets')).targets.map(t=>t.name).sort();
|
||||
app.innerHTML=`<h1>Incidents</h1><p class="lead">Outages and planned maintenance shown on the public site.</p><div class="toolbar"><button id="add">+ New incident</button></div><div id="list"></div>`;
|
||||
const form=i=>f('title','Title',i.title||'','text','required class="full"')+sel('severity','Severity',['minor','major','critical'],i.severity||'minor')+sel('status','Status',['investigating','identified','monitoring','resolved','scheduled'],i.status||'investigating')+`<label class="full">Description<textarea name="description" required>${esc(i.description||'')}</textarea></label>`+f('scheduledStart','Maintenance start',i.scheduledStart?i.scheduledStart.slice(0,16):'','datetime-local')+f('scheduledEnd','Maintenance end',i.scheduledEnd?i.scheduledEnd.slice(0,16):'','datetime-local')+`<div class="full">${ck('isScheduled','Planned maintenance',i.isScheduled)}</div><label class="full">Affected services<select name="affectedServices" multiple size="5">${names.map(n=>`<option ${(i.affectedServices||[]).includes(n)?'selected':''}>${esc(n)}</option>`).join('')}</select></label>`;
|
||||
const grab=(o,m)=>{const s=[...m.querySelector('[name=affectedServices]').selectedOptions].map(x=>x.value);o.affectedServices=s;if(!o.scheduledStart)delete o.scheduledStart;if(!o.scheduledEnd)delete o.scheduledEnd;return o};
|
||||
$('#add').onclick=()=>{const m=modal('New incident',`<div class="fm">${form({})}</div>`,async o=>{await api('/incidents','POST',grab(o,m));toast('Created');load()})};
|
||||
$('#list').onclick=async e=>{const b=e.target.closest('button');if(!b)return;const i=list.find(x=>x.id===b.closest('.card').dataset.id);
|
||||
if(b.dataset.a==='del'&&confirm('Delete this incident?')){await api('/incidents/'+i.id,'DELETE');load()}
|
||||
if(b.dataset.a==='edit'){const m=modal('Edit incident',`<div class="fm">${form(i)}</div>`,async o=>{await api('/incidents/'+i.id,'PUT',grab(o,m));toast('Saved');load()})}
|
||||
if(b.dataset.a==='upd'){modal('Post update',`<div class="fm">${sel('status','New status',['investigating','identified','monitoring','resolved'],i.status==='scheduled'?'investigating':i.status)}<label class="full">Message<textarea name="updateMessage" required></textarea></label></div>`,async o=>{await api('/incidents/'+i.id,'PUT',{status:o.status,updateMessage:o.updateMessage,isScheduled:i.isScheduled});toast('Update posted');load()})}};
|
||||
load();
|
||||
}
|
||||
|
||||
// ---------- Posts ----------
|
||||
async function posts(){
|
||||
let list=[];
|
||||
const draw=()=>{$('#list').innerHTML=list.map(p=>`<div class="card" data-id="${p.id}"><h3>${p.published?'':'<span class="tag">draft</span>'}${esc(p.title)}</h3><div class="meta">${new Date(p.createdAt).toLocaleString()}</div><p>${esc(p.content.slice(0,300))}${p.content.length>300?'…':''}</p><div class="btns"><button class="sm ghost" data-a="edit">Edit</button><button class="sm danger" data-a="del">Delete</button></div></div>`).join('')||'<p class="muted">No posts.</p>'};
|
||||
const load=async()=>{list=(await api('/posts')).posts;draw()};
|
||||
app.innerHTML=`<h1>Posts</h1><p class="lead">News shown on the public site and in the RSS feed.</p><div class="toolbar"><button id="add">+ New post</button></div><div id="list"></div>`;
|
||||
const form=p=>f('title','Title',p.title||'','text','required class="full"')+`<label class="full">Content<textarea name="content" required style="min-height:200px">${esc(p.content||'')}</textarea></label><div class="full">${ck('published','Published',p.published!==false)}</div>`;
|
||||
$('#add').onclick=()=>modal('New post',`<div class="fm">${form({})}</div>`,async o=>{await api('/posts','POST',o);toast('Published');load()});
|
||||
$('#list').onclick=async e=>{const b=e.target.closest('button');if(!b)return;const p=list.find(x=>x.id===b.closest('.card').dataset.id);
|
||||
if(b.dataset.a==='del'&&confirm('Delete this post?')){await api('/posts/'+p.id,'DELETE');load()}
|
||||
if(b.dataset.a==='edit')modal('Edit post',`<div class="fm">${form(p)}</div>`,async o=>{await api('/posts/'+p.id,'PUT',o);toast('Saved');load()})};
|
||||
load();
|
||||
}
|
||||
|
||||
// ---------- More: sub-nav ----------
|
||||
const SUB=[['/admin/settings','Settings'],['/admin/discover','Discover'],['/admin/events','Event rules'],['/admin/visibility','Visibility'],['/admin/backup','Backup']];
|
||||
const subnav=()=>`<div class="btns" style="margin:0 0 16px">${SUB.map(([h,l])=>`<a href="${h}" style="padding:7px 14px;border-radius:10px;border:1px solid var(--line);${h===page?'background:var(--acc);color:#07101f;font-weight:650':'color:var(--text)'}">${l}</a>`).join('')}</div>`;
|
||||
const fmtB=n=>n>1e9?(n/1e9).toFixed(2)+' GB':n>1e6?(n/1e6).toFixed(1)+' MB':(n/1e3).toFixed(0)+' KB';
|
||||
|
||||
async function settings(){
|
||||
const [a,n]=await Promise.all([api('/admin-settings'),api('/notification-settings')]);const A=a.settings,N=n.settings,D=N.discord||{},E=N.events||{};
|
||||
app.innerHTML=`<h1>Settings</h1>${subnav()}
|
||||
<div class="card"><h3>General</h3><p class="meta">Database size: ${fmtB(a.dbSize)}</p><form id="fa" class="fm">${f('sessionDurationDays','Admin session length (days)',A.sessionDurationDays,'number','min=1 max=365')}${f('dataRetentionDays','Keep ping data (days)',A.dataRetentionDays,'number','min=1 max=3650')}<div class="full">${ck('debugLogging','Debug logging',A.debugLogging)}</div><div class="full"><button>Save</button></div></form></div>
|
||||
<div class="card"><h3>Notifications (Discord)</h3><p class="meta">Alerts when monitors go down or come back, and when incidents are posted.</p><form id="fn" class="fm"><div class="full">${ck('enabled','Enable notifications',N.enabled)}${ck('dEnabled','Discord enabled',D.enabled)}</div>${f('webhookUrl','Webhook URL',D.webhookUrl||'','url','class="full" placeholder="https://discord.com/api/webhooks/…"')}${f('username','Bot name',D.username||'LocalPing')}${f('monitorDownDelayMinutes','Alert after down for (min)',N.monitorDownDelayMinutes,'number','min=1 max=1440')}<div class="full">${ck('monitorDown','Monitor down',E.monitorDown!==false)}${ck('monitorUp','Monitor back up',E.monitorUp!==false)}${ck('incidentCreated','Incident created',E.incidentCreated!==false)}${ck('incidentUpdated','Incident updated',E.incidentUpdated!==false)}</div><div class="full btns" style="justify-content:flex-start"><button>Save</button><button type="button" class="ghost" id="tn">Send test</button></div></form></div>
|
||||
<div class="card"><h3>Maintenance</h3><div class="btns" style="justify-content:flex-start"><button class="ghost" id="cc">Clear cache</button><button class="danger" id="cp">Delete ALL ping history…</button></div></div>`;
|
||||
$('#fa').onsubmit=async e=>{e.preventDefault();const o=Object.fromEntries([...new FormData(e.target)]);try{await api('/admin-settings','PUT',{sessionDurationDays:o.sessionDurationDays,dataRetentionDays:o.dataRetentionDays,debugLogging:e.target.debugLogging.checked});toast('Saved')}catch(x){toast(x.message,1)}};
|
||||
$('#fn').onsubmit=async e=>{e.preventDefault();const t=e.target;try{await api('/notification-settings','PUT',{enabled:t.enabled.checked,monitorDownDelayMinutes:t.monitorDownDelayMinutes.value,discord:{enabled:t.dEnabled.checked,webhookUrl:t.webhookUrl.value||null,username:t.username.value||'LocalPing',avatarUrl:D.avatarUrl||null},events:{monitorDown:t.monitorDown.checked,monitorUp:t.monitorUp.checked,incidentCreated:t.incidentCreated.checked,incidentUpdated:t.incidentUpdated.checked}});toast('Saved')}catch(x){toast(x.message,1)}};
|
||||
$('#tn').onclick=async()=>{try{await api('/notification-settings/test','POST',{provider:'discord'});toast('Test sent')}catch(x){toast(x.message,1)}};
|
||||
$('#cc').onclick=async()=>{await api('/cache/clear','POST');toast('Cache cleared')};
|
||||
$('#cp').onclick=async()=>{if(prompt('This deletes every ping and statistic. Type DELETE to confirm')==='DELETE'){await api('/clear-ping-data','POST');toast('Ping data cleared')}};
|
||||
}
|
||||
|
||||
async function events(){
|
||||
let list=[];const T=['monitor_down','monitor_up','multiple_monitors_down','monitor_response_time','uptime_threshold','custom_condition'];
|
||||
const names=(await api('/targets')).targets;
|
||||
const draw=()=>{$('#list').innerHTML=list.map(r=>`<div class="card ${r.enabled?'':'dim'}" data-id="${r.id}"><h3><span class="tag">${esc(r.eventType)}</span>${esc(r.name)}</h3><p class="meta">Creates incident “${esc(r.incidentTitle)}” (${esc(r.incidentSeverity)}) · cooldown ${r.cooldownMinutes} min${r.autoResolve?' · auto-resolves':''}</p><div class="btns"><button class="sm ghost" data-a="tog">${r.enabled?'Disable':'Enable'}</button><button class="sm ghost" data-a="edit">Edit</button><button class="sm danger" data-a="del">Delete</button></div></div>`).join('')||'<p class="muted">No event rules yet. Rules automatically create incidents when conditions are met.</p>'};
|
||||
const load=async()=>{list=(await api('/event-rules')).rules||[];draw()};
|
||||
const form=r=>f('name','Name',r.name||'','text','required class="full"')+sel('eventType','Event',T,r.eventType||'monitor_down')+sel('incidentSeverity','Severity',['minor','major','critical'],r.incidentSeverity||'major')+f('incidentTitle','Incident title',r.incidentTitle||'','text','required class="full"')+`<label class="full">Incident description<textarea name="incidentDescription" required>${esc(r.incidentDescription||'')}</textarea></label>`+sel('incidentStatus','Initial status',['investigating','identified','monitoring'],r.incidentStatus||'investigating')+f('cooldownMinutes','Cooldown (min)',r.cooldownMinutes||0,'number','min=0')+`<label class="full">Conditions (JSON)<textarea name="conditions" style="min-height:90px">${esc(JSON.stringify(r.conditions||{},null,1))}</textarea></label><div class="full">${ck('autoResolve','Auto-resolve when OK again',r.autoResolve)}${ck('enabled','Enabled',r.enabled!==false)}</div><label class="full">Auto-resolve message<input name="autoResolveMessage" value="${esc(r.autoResolveMessage||'')}"></label><p class="meta full">Monitor IDs: ${names.slice(0,40).map(t=>esc(t.name)+' = '+t.id.slice(0,8)).join(', ')}…</p>`;
|
||||
const clean=o=>{try{o.conditions=JSON.parse(o.conditions||'{}')}catch{throw new Error('Conditions must be valid JSON')}o.cooldownMinutes=Number(o.cooldownMinutes)||0;return o};
|
||||
app.innerHTML=`<h1>Event rules</h1>${subnav()}<div class="toolbar"><button id="add">+ New rule</button></div><div id="list"></div>`;
|
||||
$('#add').onclick=()=>modal('New event rule',`<div class="fm">${form({})}</div>`,async o=>{await api('/event-rules','POST',clean(o));toast('Created');load()});
|
||||
$('#list').onclick=async e=>{const b=e.target.closest('button');if(!b)return;const r=list.find(x=>x.id===b.closest('.card').dataset.id);
|
||||
if(b.dataset.a==='del'&&confirm('Delete rule?')){await api('/event-rules/'+r.id,'DELETE');load()}
|
||||
if(b.dataset.a==='tog'){await api('/event-rules/'+r.id,'PUT',{enabled:!r.enabled});load()}
|
||||
if(b.dataset.a==='edit')modal('Edit rule',`<div class="fm">${form(r)}</div>`,async o=>{await api('/event-rules/'+r.id,'PUT',clean(o));toast('Saved');load()})};
|
||||
load();
|
||||
}
|
||||
|
||||
async function visibility(){
|
||||
let list=(await api('/targets')).targets.sort((a,b)=>a.position-b.position||a.name.localeCompare(b.name));
|
||||
const cols=[['publicVisible','Listed'],['publicShowStatus','Status'],['publicShowAppLink','Link'],['publicShowDetails','Host']];
|
||||
app.innerHTML=`<h1>Visibility</h1>${subnav()}<p class="lead">What each monitor reveals on the public site. Tier, explainers and per-language text are in <a href="/admin/site">Site</a>.</p><div class="list" id="list" style="overflow-x:auto"><table style="width:100%;border-collapse:collapse"><thead><tr><th style="text-align:left;padding:10px 14px">Monitor</th>${cols.map(c=>`<th style="padding:10px">${c[1]}</th>`).join('')}</tr></thead><tbody>${list.map(t=>`<tr data-id="${t.id}" style="border-top:1px solid var(--line)"><td style="padding:9px 14px">${esc(t.name)}</td>${cols.map(([k])=>`<td style="text-align:center"><input type="checkbox" data-k="${k}" ${t[k]!==false&&t[k]?'checked':''} style="width:auto"></td>`).join('')}</tr>`).join('')}</tbody></table></div>`;
|
||||
$('#list').onchange=async e=>{const k=e.target.dataset.k;if(!k)return;try{await api('/targets/'+e.target.closest('tr').dataset.id,'PUT',{[k]:e.target.checked});toast('Saved')}catch(x){toast(x.message,1);e.target.checked=!e.target.checked}};
|
||||
}
|
||||
|
||||
async function backup(){
|
||||
app.innerHTML=`<h1>Backup</h1>${subnav()}<div class="card"><h3>Export</h3><p class="meta">Download your configuration (and optionally history) as JSON.</p><form id="fe" class="fm"><div class="full">${ck('monitors','Monitors',1)}${ck('incidents','Incidents',1)}${ck('posts','Posts',1)}${ck('settings','Settings',1)}${ck('actions','Actions',0)}${ck('dataPoints','Ping history (large)',0)}</div><div class="full"><button>Download backup</button></div></form></div>
|
||||
<div class="card"><h3>Import</h3><p class="meta">Restore from a backup file.</p><form id="fi" class="fm"><label class="full">Backup file<input type="file" name="file" accept=".json,application/json" required></label><div class="full">${ck('overwrite','Overwrite existing items',0)}</div><div class="full"><button>Import</button></div></form></div>`;
|
||||
$('#fe').onsubmit=async e=>{e.preventDefault();const o={};[...e.target.elements].forEach(x=>{if(x.name)o[x.name]=x.checked});try{const d=await api('/backup/export','POST',o);const a=document.createElement('a');a.href=URL.createObjectURL(new Blob([JSON.stringify(d.data,null,1)],{type:'application/json'}));a.download='localping-backup-'+new Date().toISOString().slice(0,10)+'.json';a.click();toast('Exported')}catch(x){toast(x.message,1)}};
|
||||
$('#fi').onsubmit=async e=>{e.preventDefault();const t=e.target;try{const j=JSON.parse(await t.file.files[0].text());if(!confirm('Import this backup'+(t.overwrite.checked?' and OVERWRITE existing items':'')+'?'))return;await api('/backup/import','POST',{importData:j.data?j:{data:j},overwrite:t.overwrite.checked});toast('Imported')}catch(x){toast(x.message||'Invalid file',1)}};
|
||||
}
|
||||
async function discover(){
|
||||
app.innerHTML=`<h1>Discover</h1>${subnav()}<p class="lead">Services found by your network inventory that aren't monitored yet. Added monitors start hidden from the public site.</p><div id="out"><div class="skeleton"></div></div>`;
|
||||
let d;try{d=await api('/discover')}catch(x){$('#out').innerHTML=`<div class="stale">${esc(x.message)}</div>`;return}
|
||||
if(!d.configured){$('#out').innerHTML='<div class="card"><h3>Not configured</h3><p class="meta">Set <code>DISCOVER_URL</code> (and optionally <code>DISCOVER_KEY</code>, <code>DISCOVER_KEY_HEADER</code>, <code>DISCOVER_DOMAINS</code>) in the server .env.</p></div>';return}
|
||||
if(!d.candidates.length){$('#out').innerHTML='<p class="muted">Everything the inventory knows about is already monitored.</p>';return}
|
||||
$('#out').innerHTML=`<div class="toolbar"><button id="all" class="ghost">Select all</button><span class="sp"></span><button id="add">Add selected</button></div><div class="list">${d.candidates.map(c=>`<label class="ar" style="grid-template-columns:auto minmax(0,1fr) auto;cursor:pointer"><input type="checkbox" value="${esc(c.hostname)}" style="width:auto"><div class="nm"><b>${esc(c.hostname)}</b><small>${esc(c.device)} · ${esc(c.target)}</small></div><span class="pill ${c.protected?'up':'unknown'}">${c.protected?'Access-protected':'Open'}</span></label>`).join('')}</div>`;
|
||||
$('#all').onclick=()=>document.querySelectorAll('#out input').forEach(i=>i.checked=true);
|
||||
$('#add').onclick=async()=>{const h=[...document.querySelectorAll('#out input:checked')].map(i=>i.value);if(!h.length)return;try{const r=await api('/discover/add','POST',{hostnames:h});toast('Added '+r.added);discover()}catch(x){toast(x.message,1)}};
|
||||
}
|
||||
({'/admin':monitors,'/admin/discover':discover,'/admin/incidents':incidents,'/admin/blogs':posts,'/admin/settings':settings,'/admin/events':events,'/admin/visibility':visibility,'/admin/backup':backup}[page]||monitors)();
|
||||
</script></body></html>
|
||||
@@ -1061,6 +1061,7 @@
|
||||
<a href="/admin/settings" title="Settings" aria-label="Settings" class="tab-button text-sm sm:text-base <%= typeof currentTab !== 'undefined' && currentTab === 'settings' ? 'active' : '' %>" onclick="handleTabClick(event, 'settings')">
|
||||
<i class="fas fa-cog mr-1 sm:mr-2" aria-hidden="true"></i><span class="admin-tab-label">Settings</span>
|
||||
</a>
|
||||
<a href="/admin/analytics" title="Analytics" aria-label="Analytics" class="tab-button text-sm sm:text-base">Traffic</a>
|
||||
<a href="/admin/site" title="Public site" aria-label="Public site" class="tab-button text-sm sm:text-base">Site</a>
|
||||
<a href="/admin/backup" title="Backup" aria-label="Backup" class="tab-button text-sm sm:text-base <%= typeof currentTab !== 'undefined' && currentTab === 'backup' ? 'active' : '' %>" onclick="handleTabClick(event, 'backup')">
|
||||
<i class="fas fa-download mr-1 sm:mr-2" aria-hidden="true"></i><span class="admin-tab-label">Backup</span>
|
||||
|
||||
+11
-144
@@ -1,144 +1,11 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Admin Login - LocalPing</title>
|
||||
<script src="/vendor/tailwindcss.js"></script>
|
||||
<style>
|
||||
body {
|
||||
background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
|
||||
min-height: 100vh;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
|
||||
}
|
||||
.form-input {
|
||||
background-color: #0f1419;
|
||||
border-color: #2a2a4e;
|
||||
}
|
||||
.form-input:focus {
|
||||
border-color: #4f46e5;
|
||||
box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
|
||||
}
|
||||
.btn-primary {
|
||||
background: linear-gradient(135deg, #4f46e5 0%, #6366f1 100%);
|
||||
}
|
||||
.btn-primary:hover {
|
||||
opacity: 0.9;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="min-h-screen flex items-center justify-center p-4">
|
||||
<div class="w-full max-w-md">
|
||||
<!-- Header -->
|
||||
<div class="text-center mb-8">
|
||||
<h1 class="text-4xl font-bold text-white mb-2">LocalPing</h1>
|
||||
<p class="text-gray-400">Admin Panel</p>
|
||||
</div>
|
||||
|
||||
<!-- Login Card -->
|
||||
<div class="bg-[#0f1419] border border-[#2a2a4e] rounded-lg p-8">
|
||||
<h2 class="text-2xl font-bold text-white mb-6">Admin Login</h2>
|
||||
|
||||
<div id="error-message" class="mb-6 p-4 bg-red-500/10 border border-red-500/20 rounded-lg hidden">
|
||||
<p class="text-red-400 text-sm" id="error-text"></p>
|
||||
</div>
|
||||
|
||||
<form id="loginForm" class="space-y-6">
|
||||
<div>
|
||||
<label for="username" class="block text-sm font-medium text-gray-300 mb-2">
|
||||
Username
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
id="username"
|
||||
name="username"
|
||||
class="form-input w-full px-4 py-2 border rounded-lg text-white placeholder-gray-500"
|
||||
placeholder="Enter admin username"
|
||||
required
|
||||
autofocus
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label for="password" class="block text-sm font-medium text-gray-300 mb-2">
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
id="password"
|
||||
name="password"
|
||||
class="form-input w-full px-4 py-2 border rounded-lg text-white placeholder-gray-500"
|
||||
placeholder="Enter admin password"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
class="btn-primary w-full py-3 rounded-lg font-semibold text-white transition"
|
||||
id="submitBtn"
|
||||
>
|
||||
Login
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div class="mt-6 pt-6 border-t border-[#2a2a4e]">
|
||||
<p class="text-gray-400 text-sm text-center">
|
||||
Forgot your password? <a href="/setup" class="text-indigo-400 hover:text-indigo-300">Reset setup</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Footer -->
|
||||
<p class="text-center text-gray-500 text-xs mt-8">
|
||||
LocalPing • Homelab Dashboard & System Monitor
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.getElementById('loginForm').addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
|
||||
const username = document.getElementById('username').value;
|
||||
const password = document.getElementById('password').value;
|
||||
const errorDiv = document.getElementById('error-message');
|
||||
const errorText = document.getElementById('error-text');
|
||||
const submitBtn = document.getElementById('submitBtn');
|
||||
|
||||
try {
|
||||
submitBtn.disabled = true;
|
||||
submitBtn.textContent = 'Logging in...';
|
||||
|
||||
const response = await fetch('/admin/login', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ username, password }),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (response.ok && data.success) {
|
||||
// Redirect to admin panel
|
||||
window.location.href = '/admin';
|
||||
} else {
|
||||
// Show error
|
||||
errorText.textContent = data.error || 'Invalid username or password';
|
||||
errorDiv.classList.remove('hidden');
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.textContent = 'Login';
|
||||
document.getElementById('username').focus();
|
||||
}
|
||||
} catch (err) {
|
||||
errorText.textContent = 'An error occurred. Please try again.';
|
||||
errorDiv.classList.remove('hidden');
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.textContent = 'Login';
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex"><title>Admin login · LocalPing</title>
|
||||
<link rel="icon" href="/brand/icon-32.png"><link rel="stylesheet" href="/s/site.css"><link rel="stylesheet" href="/s/admin.css"></head>
|
||||
<body><main style="display:grid;place-items:center;padding:24px 0"><div class="wrap" style="max-width:400px;width:100%">
|
||||
<div style="text-align:center;margin-bottom:22px"><img src="/brand/icon-192.png" width="64" height="64" alt="" style="border-radius:16px"><h1 style="margin:12px 0 4px">Admin</h1><p class="muted" style="margin:0">Sign in to manage the site</p></div>
|
||||
<form id="f" class="card"><div class="fm" style="grid-template-columns:1fr"><label>Username<input id="u" name="username" autocomplete="username" required autofocus></label><label>Password<input id="p" name="password" type="password" autocomplete="current-password" required></label></div>
|
||||
<p id="e" class="meta" style="color:var(--bad);min-height:20px;margin:10px 0 0"></p><button style="width:100%;margin-top:6px" id="b">Sign in</button></form>
|
||||
<p style="text-align:center"><a href="/" class="muted">← Back to site</a></p></div></main>
|
||||
<script>
|
||||
document.getElementById('f').addEventListener('submit',async e=>{e.preventDefault();const b=document.getElementById('b'),er=document.getElementById('e');b.disabled=true;b.textContent='Signing in…';er.textContent='';
|
||||
try{const r=await fetch('/admin/login',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({username:u.value,password:p.value})});const d=await r.json();if(r.ok&&d.success)location.href='/admin';else{er.textContent=d.error||'Login failed';b.disabled=false;b.textContent='Sign in'}}catch{er.textContent='Network error';b.disabled=false;b.textContent='Sign in'}});
|
||||
</script></body></html>
|
||||
@@ -1,19 +1,19 @@
|
||||
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Site settings · LocalPing</title>
|
||||
<link rel="stylesheet" href="/s/site.css"><style>td,th{padding:8px;text-align:left;border-top:1px solid var(--line);vertical-align:top}table{width:100%;border-collapse:collapse}select{width:auto}input[type=text],input[type=color]{width:100%}.sv{font-size:12px;color:var(--ok)}</style></head>
|
||||
<body><header class="top"><a class="brand" href="/admin"><span>← Admin</span></a><nav><a class="on" href="/admin/site">Public site</a></nav></header>
|
||||
<main><div class="wrap"><h1>Public site</h1>
|
||||
<link rel="stylesheet" href="/s/site.css"><link rel="stylesheet" href="/s/admin.css"><style>td,th{padding:8px;text-align:left;border-top:1px solid var(--line);vertical-align:top}table{width:100%;border-collapse:collapse}select{width:auto}input[type=text],input[type=color]{width:100%}.sv{font-size:12px;color:var(--ok)}</style></head>
|
||||
<body>
|
||||
<script src="/s/admin-nav.js"></script><main><div class="wrap"><h1>Public site</h1>
|
||||
<div class="card"><h3>Branding & app icon</h3><p class="meta">Used for the header, favicon and when installed as an app (PWA). PNG/WebP/JPEG/SVG, max 2 MB, square works best.</p>
|
||||
<div class="grid"><div><label>Name</label><input type="text" id="b-name"></div><div><label>Tagline</label><input type="text" id="b-tag"></div><div><label>Accent colour</label><input type="color" id="b-acc" value="#6ea8ff"></div><div><label>Icon</label><input type="file" id="b-file" accept="image/png,image/jpeg,image/webp,image/svg+xml"></div></div>
|
||||
<div class="btns"><button id="b-save">Save branding</button><button class="ghost" id="b-reset">Reset icon to default</button><img id="b-prev" src="/brand/icon-192.png" width="48" height="48" alt="" style="border-radius:10px"><span class="sv" id="b-msg"></span></div></div>
|
||||
<div class="card"><h3>Services: explainers, tiers & links</h3><p class="meta">Tier decides placement (featured = shown first). Untick “Link” for private services so no link to them is shown publicly.</p>
|
||||
<div style="overflow-x:auto"><table><thead><tr><th>Service</th><th>Tier</th><th>Link</th><th>Explainer (shown in ⓘ)</th><th></th></tr></thead><tbody id="rows"></tbody></table></div></div></div></main>
|
||||
<div class="card"><h3>Services: explainers, tiers & links</h3><p class="meta">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.</p>
|
||||
<div style="overflow-x:auto"><table><thead><tr><th>Service</th><th>Tier</th><th>Link</th><th>Explainers (ⓘ)</th><th></th></tr></thead><tbody id="rows"></tbody></table></div></div></div></main>
|
||||
<script>
|
||||
const $=s=>document.querySelector(s),j=(u,o)=>fetch(u,o).then(r=>r.json());
|
||||
const H={'content-type':'application/json'};
|
||||
async function load(){const d=await j('/admin/api/site/meta');$('#b-name').value=d.brand.name;$('#b-tag').value=d.brand.tagline;if(d.brand.accent)$('#b-acc').value=d.brand.accent;
|
||||
$('#rows').innerHTML=d.targets.map(t=>`<tr data-id="${t.id}"><td><b></b></td><td><select data-k="tier">${['featured','normal','background'].map(x=>`<option ${x===t.tier?'selected':''}>${x}</option>`).join('')}</select></td><td><input type="checkbox" data-k="linkPublic" ${t.linkPublic?'checked':''}></td><td><input type="text" data-k="description" maxlength="400"></td><td class="sv"></td></tr>`).join('');
|
||||
[...$('#rows').children].forEach((tr,i)=>{const t=d.targets[i];tr.querySelector('b').textContent=t.name+(t.publicVisible?'':' (hidden)');tr.querySelector('[data-k=description]').value=t.description||'';
|
||||
tr.addEventListener('change',async()=>{const b={tier:tr.querySelector('[data-k=tier]').value,linkPublic:tr.querySelector('[data-k=linkPublic]').checked,description:tr.querySelector('[data-k=description]').value};
|
||||
$('#rows').innerHTML=d.targets.map(t=>`<tr data-id="${t.id}"><td><b></b></td><td><select data-k="tier">${['quick','featured','normal','background'].map(x=>`<option ${x===t.tier?'selected':''}>${x}</option>`).join('')}</select></td><td><input type="checkbox" data-k="linkPublic" ${t.linkPublic?'checked':''}></td><td class="dl"></td><td class="sv"></td></tr>`).join('');
|
||||
[...$('#rows').children].forEach((tr,i)=>{const t=d.targets[i];tr.querySelector('b').textContent=t.name+(t.publicVisible?'':' (hidden)');const dl=tr.querySelector('.dl');dl.innerHTML=d.langs.map(l=>`<label style="display:flex;gap:6px;align-items:center;margin-bottom:4px"><span style="width:28px">${l.flag}</span><input type="text" data-l="${l.code}" maxlength="400" placeholder="${l.name}"></label>`).join('');dl.querySelectorAll('input').forEach(x=>{x.value=x.dataset.l==='en'?(t.description||''):(t.descriptions||{})[x.dataset.l]||''});
|
||||
tr.addEventListener('change',async()=>{const b={tier:tr.querySelector('[data-k=tier]').value,linkPublic:tr.querySelector('[data-k=linkPublic]').checked,description:(tr.querySelector('[data-l=en]')||{}).value,descriptions:Object.fromEntries([...tr.querySelectorAll('[data-l]')].filter(x=>x.dataset.l!=='en').map(x=>[x.dataset.l,x.value]))};
|
||||
const r=await j('/admin/api/site/meta/'+t.id,{method:'PUT',headers:H,body:JSON.stringify(b)});tr.querySelector('.sv').textContent=r.success?'saved':'error';});});}
|
||||
const file=()=>new Promise(r=>{const f=$('#b-file').files[0];if(!f)return r(null);const fr=new FileReader();fr.onload=()=>r(fr.result);fr.readAsDataURL(f)});
|
||||
async function save(reset){const r=await j('/admin/api/site/brand',{method:'PUT',headers:H,body:JSON.stringify({name:$('#b-name').value,tagline:$('#b-tag').value,accent:$('#b-acc').value,iconBase64:reset?null:await file(),resetIcon:!!reset})});$('#b-msg').textContent=r.success?'saved':r.error;$('#b-prev').src='/brand/icon-192.png?'+Date.now();}
|
||||
|
||||
+12
-185
@@ -1,185 +1,12 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>LocalPing Setup</title>
|
||||
<script src="/vendor/tailwindcss.js"></script>
|
||||
<style>
|
||||
body {
|
||||
background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
|
||||
min-height: 100vh;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
|
||||
}
|
||||
.form-input {
|
||||
background-color: #0f1419;
|
||||
border-color: #2a2a4e;
|
||||
}
|
||||
.form-input:focus {
|
||||
border-color: #4f46e5;
|
||||
box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
|
||||
}
|
||||
.btn-primary {
|
||||
background: linear-gradient(135deg, #4f46e5 0%, #6366f1 100%);
|
||||
}
|
||||
.btn-primary:hover {
|
||||
opacity: 0.9;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="min-h-screen flex items-center justify-center p-4">
|
||||
<div class="w-full max-w-md">
|
||||
<!-- Header -->
|
||||
<div class="text-center mb-8">
|
||||
<h1 class="text-4xl font-bold text-white mb-2">LocalPing</h1>
|
||||
<p class="text-gray-400">Initial Setup Wizard</p>
|
||||
</div>
|
||||
|
||||
<!-- Setup Card -->
|
||||
<div class="bg-[#0f1419] border border-[#2a2a4e] rounded-lg p-8">
|
||||
<% if (error) { %>
|
||||
<div class="mb-6 p-4 bg-red-500/10 border border-red-500/20 rounded-lg">
|
||||
<p class="text-red-400 text-sm"><strong>Error:</strong> <%= error %></p>
|
||||
</div>
|
||||
<% } %>
|
||||
|
||||
<form method="POST" class="space-y-6">
|
||||
<!-- Step 1: Admin Credentials -->
|
||||
<div>
|
||||
<h2 class="text-lg font-semibold text-white mb-4">Admin Credentials</h2>
|
||||
|
||||
<div class="mb-4">
|
||||
<label for="adminUsername" class="block text-sm font-medium text-gray-300 mb-2">
|
||||
Admin Username
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
id="adminUsername"
|
||||
name="adminUsername"
|
||||
value="admin"
|
||||
class="form-input w-full px-4 py-2 border rounded-lg text-white placeholder-gray-500"
|
||||
required
|
||||
/>
|
||||
<p class="text-gray-400 text-xs mt-1">Used to log in to the admin panel</p>
|
||||
</div>
|
||||
|
||||
<div class="mb-4">
|
||||
<label for="adminPassword" class="block text-sm font-medium text-gray-300 mb-2">
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
id="adminPassword"
|
||||
name="adminPassword"
|
||||
class="form-input w-full px-4 py-2 border rounded-lg text-white placeholder-gray-500"
|
||||
placeholder="At least 6 characters"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="mb-4">
|
||||
<label for="passwordConfirm" class="block text-sm font-medium text-gray-300 mb-2">
|
||||
Confirm Password
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
id="passwordConfirm"
|
||||
name="passwordConfirm"
|
||||
class="form-input w-full px-4 py-2 border rounded-lg text-white placeholder-gray-500"
|
||||
placeholder="Re-enter your password"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Step 2: Network Configuration -->
|
||||
<div class="pt-4 border-t border-[#2a2a4e]">
|
||||
<h2 class="text-lg font-semibold text-white mb-4">Network Configuration</h2>
|
||||
|
||||
<div>
|
||||
<label for="gatewayIp" class="block text-sm font-medium text-gray-300 mb-2">
|
||||
Gateway IP Address
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
id="gatewayIp"
|
||||
name="gatewayIp"
|
||||
value="<%= detectedGateway %>"
|
||||
class="form-input w-full px-4 py-2 border rounded-lg text-white placeholder-gray-500"
|
||||
placeholder="e.g., 192.168.1.1"
|
||||
required
|
||||
/>
|
||||
<p class="text-gray-400 text-xs mt-1">
|
||||
<% if (detectedGateway) { %>
|
||||
✓ Auto-detected: <%= detectedGateway %> (you can change this)
|
||||
<% } else { %>
|
||||
Enter your network gateway IP address
|
||||
<% } %>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Info -->
|
||||
<div class="pt-4 border-t border-[#2a2a4e]">
|
||||
<p class="text-gray-400 text-sm mb-2">
|
||||
<strong>Default monitors will be created for:</strong>
|
||||
</p>
|
||||
<ul class="text-gray-400 text-sm space-y-1 ml-4">
|
||||
<li>✓ Gateway monitoring (ICMP ping)</li>
|
||||
<li>✓ Cloudflare DNS at 1.1.1.1 (ICMP ping)</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<!-- Submit -->
|
||||
<div class="pt-4">
|
||||
<button
|
||||
type="submit"
|
||||
class="btn-primary w-full py-3 rounded-lg font-semibold text-white transition"
|
||||
>
|
||||
Complete Setup
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p class="text-center text-gray-400 text-xs mt-4">
|
||||
By completing setup, you agree that LocalPing will monitor your network
|
||||
</p>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<!-- Footer -->
|
||||
<p class="text-center text-gray-500 text-xs mt-8">
|
||||
LocalPing • Homelab Dashboard & System Monitor
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Form validation on client side
|
||||
document.querySelector('form').addEventListener('submit', function(e) {
|
||||
const password = document.getElementById('adminPassword').value;
|
||||
const passwordConfirm = document.getElementById('passwordConfirm').value;
|
||||
const gateway = document.getElementById('gatewayIp').value;
|
||||
|
||||
if (password.length < 6) {
|
||||
e.preventDefault();
|
||||
alert('Password must be at least 6 characters');
|
||||
return;
|
||||
}
|
||||
|
||||
if (password !== passwordConfirm) {
|
||||
e.preventDefault();
|
||||
alert('Passwords do not match');
|
||||
return;
|
||||
}
|
||||
|
||||
const ipRegex = /^(\d{1,3}\.){3}\d{1,3}$/;
|
||||
if (!ipRegex.test(gateway)) {
|
||||
e.preventDefault();
|
||||
alert('Invalid IP address format');
|
||||
return;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex"><title>Setup · LocalPing</title>
|
||||
<link rel="icon" href="/brand/icon-32.png"><link rel="stylesheet" href="/s/site.css"><link rel="stylesheet" href="/s/admin.css"></head>
|
||||
<body><main style="display:grid;place-items:center;padding:24px 0"><div class="wrap" style="max-width:460px;width:100%">
|
||||
<div style="text-align:center;margin-bottom:22px"><img src="/brand/icon-192.png" width="64" height="64" alt="" style="border-radius:16px"><h1 style="margin:12px 0 4px">Welcome to LocalPing</h1><p class="muted" style="margin:0">Create your admin account to get started</p></div>
|
||||
<% if (error) { %><div class="stale" style="color:var(--bad);border-color:#5c1f27;background:#2a1216"><%= error %></div><% } %>
|
||||
<form method="POST" class="card"><div class="fm" style="grid-template-columns:1fr">
|
||||
<label>Admin username<input name="adminUsername" required minlength="3" autocomplete="username" value="<%= (typeof formData !== 'undefined' && formData && formData.adminUsername) || '' %>"></label>
|
||||
<label>Password (min 6 characters)<input name="adminPassword" type="password" required minlength="6" autocomplete="new-password"></label>
|
||||
<label>Confirm password<input name="passwordConfirm" type="password" required minlength="6" autocomplete="new-password"></label>
|
||||
<label>Gateway IP<input name="gatewayIp" required value="<%= detectedGateway %>" placeholder="192.168.1.1"></label>
|
||||
<p class="meta" style="margin:0"><% if (detectedGateway) { %>Auto-detected: <%= detectedGateway %> (you can change this)<% } else { %>Could not auto-detect the gateway. Enter your router IP.<% } %></p></div>
|
||||
<button style="width:100%;margin-top:14px">Complete setup</button></form></div></main></body></html>
|
||||
Reference in new issue
Block a user