LAN-Orangutan is a self-hosted network discovery tool. Find every device on your LAN, label and group them, snapshot your network and compare it later, and get flagged when something unexpected shows up. Single binary, no setup, Tailscale built in. Built by 291 Group.
Go clidevice-discoverygolanghomelabinternet-of-thingslannetwork-discoverynetwork-monitoringnetwork-monitoring-toolnetwork-scannernetworkingnmapsecurityself-hostedselfhostedtailscaletailscale-networkweb-dashboard
<!DOCTYPE html>
<html lang="en" data-theme="{{.Theme}}">
<head>
<script>(function(){try{var t=localStorage.getItem("theme");if(t)document.documentElement.setAttribute("data-theme",t);var a=localStorage.getItem("accent")||"blue";if(a!=="orange")document.documentElement.setAttribute("data-accent",a);}catch(e){}})();</script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Settings - LAN Orangutan</title>
<link rel="stylesheet" href="/static/style.css">
<link rel="icon" type="image/svg+xml" href="/static/orangutan.svg">
</head>
<body>
<noscript>
<div class="noscript-screen">
<div class="noscript-card">
<div class="noscript-head">
<img src="/static/orangutan.svg" alt="LAN Orangutan" class="noscript-logo" width="60" height="60">
<div>
<h1>JavaScript is switched off</h1>
<p class="noscript-sub">The web dashboard needs JavaScript to run. Here's what it offers, and how to use LAN Orangutan without it. Pick whichever you prefer.</p>
</div>
</div>
<div class="noscript-cols">
<section class="noscript-panel">
<h2>The web dashboard</h2>
<p>A live, visual view of your network. It uses JavaScript for:</p>
<ul>
<li>Live device updates as the server scans</li>
<li>Running scans, and sorting, filtering, searching</li>
<li>Editing labels and groups, and copying addresses</li>
</ul>
<p class="noscript-action">Allow JavaScript for this site (in your browser or script blocker), then reload.</p>
</section>
<section class="noscript-panel">
<h2>Or the command line</h2>
<p>Same discovery, no browser or JavaScript needed, straight from your terminal:</p>
<pre class="noscript-cli"><code>orangutan scan all # scan your networks
orangutan list # list found devices
orangutan status # service & network status
orangutan export out.csv</code></pre>
<p class="noscript-action-muted">Run <code>orangutan --help</code> to see everything.</p>
</section>
</div>
<p class="noscript-safety"><strong>Is the dashboard safe?</strong> Yes. LAN Orangutan is self-hosted: its JavaScript runs entirely in your own browser against your own server, and makes no third-party or external calls. It is served from this machine at <code>/static/app.js</code>.</p>
<footer class="noscript-footer">
<img src="/static/orangutan.svg" alt="" class="noscript-footer-logo" width="22" height="22">
<span class="noscript-footer-name">LAN Orangutan by 291 Group</span>
<span class="noscript-footer-sep">•</span>
<a href="https://github.com/291-Group/LAN-Orangutan" target="_blank" rel="noopener">github.com/291-Group/LAN-Orangutan</a>
</footer>
</div>
</div>
</noscript>
<header class="header">
<a href="/" class="header-brand">
<img src="/static/orangutan.svg" alt="" class="logo" width="32" height="32">
<h1>LAN Orangutan</h1>
</a>
<nav class="header-nav">
<a href="/" class="nav-link">Dashboard</a>
<a href="/settings" class="nav-link active">Settings</a>
{{if .AuthEnabled}}<a href="/logout" class="nav-link">Sign out</a>{{end}}
<button class="theme-toggle" onclick="toggleTheme()" title="Toggle theme">◐</button>
</nav>
</header>
<main class="main">
{{if .Error}}
<div class="alert alert-error">{{.Error}}</div>
{{end}}
<section class="section">
<h2 class="section-title">System Information</h2>
<div class="card">
<div class="status-row">
<span class="status-label">Version:</span>
<span class="status-value">{{if .Version}}{{.Version}}{{else}}dev{{end}}</span>
</div>
<div class="status-row">
<span class="status-label">Total Devices:</span>
<span class="status-value">{{.Stats.Total}}</span>
</div>
<div class="status-row">
<span class="status-label">Online:</span>
<span class="status-value online">{{.Stats.Online}}</span>
</div>
<div class="status-row">
<span class="status-label">Offline:</span>
<span class="status-value">{{.Stats.Offline}}</span>
</div>
</div>
</section>
<section class="section">
<h2 class="section-title">Tailscale</h2>
<div class="card">
<div class="status-row">
<span class="status-label">Status:</span>
{{if .Tailscale.Connected}}
<span class="status-value online">✓ {{.Tailscale.StatusLabel}}</span>
{{else if .Tailscale.Installed}}
<span class="status-value offline">✗ {{.Tailscale.StatusLabel}}</span>
{{else}}
<span class="status-value warning">Not Installed</span>
{{end}}
</div>
{{/* These details are cached from the last session and go stale
once Tailscale stops, so only show them while connected. */}}
{{if .Tailscale.Connected}}
{{if .Tailscale.SelfIP}}
<div class="status-row">
<span class="status-label">IP:</span>
<span class="status-value">{{.Tailscale.SelfIP}}</span>
</div>
{{end}}
{{if .Tailscale.SelfHostname}}
<div class="status-row">
<span class="status-label">Hostname:</span>
<span class="status-value">{{.Tailscale.SelfHostname}}</span>
</div>
{{end}}
<div class="status-row">
<span class="status-label">Peers:</span>
<span class="status-value">{{.Tailscale.PeerCount}}</span>
</div>
{{end}}
{{if .Tailscale.Installed}}
<div class="form-group" style="margin-top: 1rem;">
{{if .Tailscale.Connected}}
<button class="btn btn-primary" onclick="disconnectTailscale()">Disconnect</button>
<p class="form-help">Disconnects this machine from your tailnet.</p>
{{else}}
<button class="btn btn-primary" onclick="connectTailscale()">Connect</button>
<p class="form-help">Connects this machine to your tailnet.</p>
{{end}}
<div id="tailscale-message" class="tailscale-message"></div>
</div>
{{end}}
</div>
</section>
<section class="section">
<h2 class="section-title">Appearance</h2>
<div class="card">
<div class="form-group">
<label>Theme</label>
<div class="radio-group">
<label class="radio-label">
<input type="radio" name="theme" value="light" {{if eq .Theme "light"}}checked{{end}} onchange="setTheme('light')"> Light
</label>
<label class="radio-label">
<input type="radio" name="theme" value="dark" {{if eq .Theme "dark"}}checked{{end}} onchange="setTheme('dark')"> Dark
</label>
<label class="radio-label">
<input type="radio" name="theme" value="auto" {{if eq .Theme "auto"}}checked{{end}} onchange="setTheme('auto')"> Auto
</label>
</div>
</div>
<div class="form-group" style="margin-top: 1rem;">
<label>Accent color</label>
<div class="accent-swatches">
<button type="button" class="accent-swatch" data-accent="orange" style="background:#e0842c" onclick="setAccent('orange')" title="Orange" aria-label="Orange accent"></button>
<button type="button" class="accent-swatch" data-accent="gold" style="background:#d9a227" onclick="setAccent('gold')" title="Gold" aria-label="Gold accent"></button>
<button type="button" class="accent-swatch" data-accent="blue" style="background:#2f7fd4" onclick="setAccent('blue')" title="Blue" aria-label="Blue accent"></button>
<button type="button" class="accent-swatch" data-accent="green" style="background:#2c9e6b" onclick="setAccent('green')" title="Green" aria-label="Green accent"></button>
<button type="button" class="accent-swatch" data-accent="purple" style="background:#8b6fc4" onclick="setAccent('purple')" title="Purple" aria-label="Purple accent"></button>
</div>
<p class="form-help">Applies across the app, in both light and dark.</p>
</div>
</div>
</section>
<section class="section">
<h2 class="section-title">Scanning</h2>
<div class="card">
<div class="form-group" style="display: flex; align-items: flex-start; justify-content: space-between; gap: 1.5rem;">
<div>
<label style="margin-bottom: 0.35rem;">Service detection</label>
<p class="form-help" style="margin: 0;">Also check each device on a short list of well-known ports (web, printer, NAS, and so on) to identify it more precisely and flag a web interface. Sends a little more traffic and takes a little longer, so it is off by default. Applies on the next scan.</p>
</div>
<div class="toggle-switch" id="service-detection-toggle" role="switch" aria-checked="false" tabindex="0" onclick="toggleServiceDetection()" data-tip="Deeper device identification via a light port probe"></div>
</div>
<div class="form-group" style="margin-bottom: 0;">
<label for="set-scan-interval">Automatic scan interval (seconds)</label>
<div style="display: flex; align-items: center; gap: 0.6rem;">
<input type="number" id="set-scan-interval" class="input" min="10" max="86400" style="width: 160px;">
<button class="btn btn-primary" onclick="saveScanInterval()">Save</button>
<span id="scan-interval-status" class="form-help" style="margin: 0;"></span>
</div>
<p class="form-help">How often the background scanner re-scans while continuous scan is on. Takes effect on the next cycle. Default: <span id="def-scan-interval">300</span> seconds.</p>
</div>
</div>
</section>
<section class="section">
<h2 class="section-title">Networks</h2>
<div class="card">
<div class="form-group" style="display: flex; align-items: flex-start; justify-content: space-between; gap: 1.5rem;">
<div>
<label style="margin-bottom: 0.35rem;">Scan only the networks I list</label>
<p class="form-help" style="margin: 0;">Ignore the auto-detected interfaces and scan only the "Networks to scan" list below. Useful on a host with many Docker bridges, VLANs, or routed interfaces.</p>
</div>
<div class="toggle-switch" id="only-configured-toggle" role="switch" aria-checked="false" tabindex="0" onclick="toggleOnlyConfigured()" data-tip="Scan only the networks you list, not the detected ones"></div>
</div>
<div class="form-group">
<label>Networks to scan</label>
<div id="include-list" class="cidr-list"></div>
<div style="display: flex; gap: 0.5rem; margin-top: 0.5rem;">
<input type="text" id="include-input" class="input" placeholder="e.g. 192.168.10.0/24" style="width: 220px;" onkeydown="if(event.key==='Enter'){event.preventDefault();addCidr('include');}">
<button class="btn" onclick="addCidr('include')">Add</button>
</div>
<p class="form-help" id="detected-suggestions" style="margin-top: 0.5rem;"></p>
</div>
<div class="form-group">
<label>Networks to hide</label>
<div id="exclude-list" class="cidr-list"></div>
<div style="display: flex; gap: 0.5rem; margin-top: 0.5rem;">
<input type="text" id="exclude-input" class="input" placeholder="e.g. 10.99.0.0/16" style="width: 220px;" onkeydown="if(event.key==='Enter'){event.preventDefault();addCidr('exclude');}">
<button class="btn" onclick="addCidr('exclude')">Add</button>
</div>
</div>
<div class="form-group" style="display: flex; align-items: center; gap: 0.6rem; margin-bottom: 0;">
<button class="btn btn-primary" onclick="saveNetworks()">Save</button>
<button class="btn" onclick="resetNetworks()">Reset to defaults</button>
<span id="networks-status" class="form-help" style="margin: 0;"></span>
</div>
<p class="form-help">A routed network (reached through a router, not on a local interface) is scanned but has no MAC addresses. Applies on the next scan. Saved to this instance, not your config file.</p>
</div>
</section>
<section class="section">
<h2 class="section-title">Device Groups</h2>
<div class="card">
<div class="form-group">
<label>Your groups</label>
<p class="form-help" style="margin-top: 0;">Rename a group to fit your own kit, or add ones that suit it better. Renaming updates every device already in that group. Deleting a group leaves its devices ungrouped, it never deletes a device.</p>
<div id="group-list" class="group-list"></div>
<div style="display: flex; gap: 0.5rem; margin-top: 0.75rem;">
<input type="text" id="group-input" class="input" placeholder="e.g. Wearables" maxlength="32" style="width: 220px;" onkeydown="if(event.key==='Enter'){event.preventDefault();addGroup();}">
<button class="btn" onclick="addGroup()">Add group</button>
</div>
</div>
<div class="form-group" style="display: flex; align-items: center; gap: 0.6rem; margin-bottom: 0;">
<button class="btn" onclick="resetGroups()">Reset to defaults</button>
<span id="groups-status" class="form-help" style="margin: 0;"></span>
</div>
<p class="form-help">Changes apply immediately. Saved to this instance, not your config file.</p>
</div>
</section>
<section class="section">
<h2 class="section-title">Storage</h2>
<div class="card">
<div class="form-group">
<label for="set-retention">Days to keep offline devices</label>
<input type="number" id="set-retention" class="input" min="0" max="36500" style="width: 160px;">
<p class="form-help">A device not seen for this many days is removed. Devices you have labelled, grouped, or added notes to, and devices currently online, are always kept. 0 keeps them forever. Default: <span id="def-retention">90</span>.</p>
</div>
<div class="form-group">
<label for="set-maxdevices">Maximum devices to track</label>
<input type="number" id="set-maxdevices" class="input" min="0" max="1000000" style="width: 160px;">
<p class="form-help">When the list grows past this, the devices seen longest ago are dropped first (labelled, grouped, noted, and online devices are kept). 0 means no cap. Default: <span id="def-maxdevices">1000</span>.</p>
</div>
<div class="form-group" style="display: flex; align-items: center; gap: 0.6rem; margin-bottom: 0;">
<button class="btn btn-primary" onclick="saveStorageSettings()">Save</button>
<button class="btn" onclick="resetStorageSettings()">Reset to defaults</button>
<span id="storage-status" class="form-help" style="margin: 0;"></span>
</div>
<p class="form-help">Changes apply immediately: lowering these can remove stale devices right away. Saved to this instance, not your config file.</p>
</div>
</section>
{{if .AuthEnabled}}
<section class="section">
<h2 class="section-title">Security</h2>
<div class="card">
<div class="status-row">
<span class="status-label">Password:</span>
<span class="status-value online">✓ Enabled</span>
</div>
<div class="form-group" style="margin-top: 1rem;">
<a href="/logout" class="btn btn-primary">Sign out</a>
<p class="form-help">Ends this session on this browser.</p>
</div>
</div>
</section>
{{end}}
<section class="section">
<h2 class="section-title">Data Management</h2>
<div class="card">
<div class="form-group">
<button class="btn btn-primary" onclick="exportDevices()">Export Devices (CSV)</button>
<a class="btn" href="/api/report">Download report (HTML)</a>
<p class="form-help">A CSV of the device list, or a shareable, self-contained HTML report of the whole network.</p>
</div>
<div class="form-group" style="margin-bottom: 0;">
<label>Backup</label>
<div style="display: flex; gap: 0.5rem; align-items: center; flex-wrap: wrap;">
<a class="btn btn-primary" href="/api/backup">Back up everything</a>
<input type="file" id="restore-file" accept="application/json,.json" style="display:none" onchange="onRestoreFile()">
<button class="btn" onclick="document.getElementById('restore-file').click()">Restore from backup…</button>
<span id="restore-status" class="form-help" style="margin: 0;"></span>
</div>
<div id="restore-confirm" style="display: none; margin-top: 0.6rem;">
<p class="form-help" style="margin: 0 0 0.4rem;">Restore <strong id="restore-filename"></strong>? This <strong>replaces</strong> the current devices, settings, and snapshots on this instance.</p>
<button class="btn btn-primary" onclick="doRestore()">Confirm restore</button>
<button class="btn" onclick="cancelRestore()">Cancel</button>
</div>
<p class="form-help">Download a copy of your devices, settings, and snapshots (not your password) as a single file, or restore from one.</p>
</div>
</div>
</section>
<section class="section">
<h2 class="section-title">About</h2>
<div class="card">
<p>LAN Orangutan is a network discovery and monitoring tool that helps you keep track of devices on your local network.</p>
<p style="margin-top: 1rem;">
<a href="https://github.com/291-Group/LAN-Orangutan" target="_blank">GitHub</a> ·
<a href="https://291group.com" target="_blank">291 Group</a>
</p>
</div>
</section>
</main>
{{/* A scan runs on the server, not in the page, so it can still be going
while the user is on this page. Without somewhere to show it, the scan
would carry on invisibly and this page would never notice it finish. */}}
<div id="scan-progress" class="scan-progress" style="display:none">
<div class="scan-progress-head">
<span id="scan-title">Scanning network...</span>
<button type="button" class="btn btn-sm scan-cancel" id="scan-cancel" onclick="cancelScan()">Cancel</button>
</div>
<div class="scan-bar" id="scan-bar">
<div class="scan-bar-fill" id="scan-bar-fill"></div>
</div>
<div class="scan-progress-meta">
<span id="scan-detail"></span>
<span id="scan-eta"></span>
</div>
<div class="scan-progress-count" id="scan-count"></div>
<div class="scan-progress-hint" id="scan-hint"></div>
</div>
<div id="toast" class="toast"></div>
<footer class="footer">
<p>LAN Orangutan by <a href="https://291group.com" target="_blank">291 Group</a></p>
</footer>
<script src="/static/app.js"></script>
<script>
function setTheme(theme) {
// Shared with the header toggle so the radios also switch without the
// staggered transition. applyTheme is defined in app.js.
applyTheme(theme);
}
function exportDevices() {
window.location.href = '/api/devices?format=csv';
}
// Storage settings (retention window + device cap). These are stored as
// overrides on this instance, not written to config.ini, and applied
// immediately by the server.
async function loadStorageSettings() {
try {
const res = await fetch('/api/settings').then(r => r.json());
if (!res.success) return;
const d = res.data;
document.getElementById('set-retention').value = d.retention_days.value;
document.getElementById('set-maxdevices').value = d.max_devices.value;
document.getElementById('def-retention').textContent = d.retention_days.default;
document.getElementById('def-maxdevices').textContent = d.max_devices.default;
} catch (e) { /* leave the fields blank if the API is unreachable */ }
}
function saveStorageSettings() {
// A blank field clears that override (falls back to the default).
const r = document.getElementById('set-retention').value.trim();
const m = document.getElementById('set-maxdevices').value.trim();
postStorageSettings({
retention_days: r === '' ? null : parseInt(r, 10),
max_devices: m === '' ? null : parseInt(m, 10)
});
}
function resetStorageSettings() {
postStorageSettings({ retention_days: null, max_devices: null });
}
async function postStorageSettings(body) {
const status = document.getElementById('storage-status');
try {
const res = await fetch('/api/settings', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
}).then(r => r.json());
if (res.success) {
// Reflect what the server actually applied (it clamps out-of-range
// values), so the fields never disagree with the stored setting.
document.getElementById('set-retention').value = res.data.retention_days.value;
document.getElementById('set-maxdevices').value = res.data.max_devices.value;
status.textContent = 'Saved';
status.style.color = 'var(--success)';
} else {
status.textContent = res.error || 'Could not save';
status.style.color = 'var(--danger)';
}
} catch (e) {
status.textContent = 'Could not save';
status.style.color = 'var(--danger)';
}
setTimeout(() => { status.textContent = ''; }, 2500);
}
loadStorageSettings();
// Scanning: service-detection toggle. Its own endpoint (like continuous
// scan), saved as an override on this instance and applied on the next
// scan.
function setServiceDetectionToggle(on) {
const t = document.getElementById('service-detection-toggle');
t.classList.toggle('active', on);
t.setAttribute('aria-checked', on ? 'true' : 'false');
}
async function loadScanningSettings() {
try {
const res = await fetch('/api/scan/service-detection').then(r => r.json());
if (res.success) setServiceDetectionToggle(res.data.enabled);
} catch (e) { /* leave it off if unreachable */ }
}
async function toggleServiceDetection() {
const t = document.getElementById('service-detection-toggle');
const next = t.getAttribute('aria-checked') !== 'true';
setServiceDetectionToggle(next); // optimistic
try {
const res = await fetch('/api/scan/service-detection', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ enabled: next })
}).then(r => r.json());
setServiceDetectionToggle(res.success ? res.data.enabled : !next);
} catch (e) {
setServiceDetectionToggle(!next); // revert on failure
}
}
loadScanningSettings();
// Scanning: automatic scan interval (seconds). Its own endpoint; the
// background scanner re-reads it before each cycle.
async function loadScanInterval() {
try {
const res = await fetch('/api/scan/interval').then(r => r.json());
if (!res.success) return;
document.getElementById('set-scan-interval').value = res.data.seconds;
document.getElementById('def-scan-interval').textContent = res.data.default;
} catch (e) { /* leave blank if unreachable */ }
}
async function saveScanInterval() {
const status = document.getElementById('scan-interval-status');
const secs = parseInt(document.getElementById('set-scan-interval').value, 10);
if (isNaN(secs)) {
status.textContent = 'Enter a number';
status.style.color = 'var(--danger)';
setTimeout(() => { status.textContent = ''; }, 2500);
return;
}
try {
const res = await fetch('/api/scan/interval', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ seconds: secs })
}).then(r => r.json());
if (res.success) {
// Reflect the clamped value the server actually applied.
document.getElementById('set-scan-interval').value = res.data.seconds;
status.textContent = 'Saved';
status.style.color = 'var(--success)';
} else {
status.textContent = res.error || 'Could not save';
status.style.color = 'var(--danger)';
}
} catch (e) {
status.textContent = 'Could not save';
status.style.color = 'var(--danger)';
}
setTimeout(() => { status.textContent = ''; }, 2500);
}
loadScanInterval();
// Networks: include/exclude CIDR lists + only-configured toggle. Backed by
// /api/scan/networks; the server validates every CIDR and the change
// applies on the next scan. Chips are built with the DOM (textContent) so
// a value can never inject markup.
let includeList = [];
let excludeList = [];
function setOnlyConfiguredToggle(on) {
const t = document.getElementById('only-configured-toggle');
t.classList.toggle('active', on);
t.setAttribute('aria-checked', on ? 'true' : 'false');
}
function toggleOnlyConfigured() {
const t = document.getElementById('only-configured-toggle');
setOnlyConfiguredToggle(t.getAttribute('aria-checked') !== 'true');
}
function renderCidrList(kind) {
const arr = kind === 'include' ? includeList : excludeList;
const el = document.getElementById(kind + '-list');
el.textContent = '';
if (arr.length === 0) {
const none = document.createElement('span');
none.className = 'form-help';
none.style.margin = '0';
none.textContent = 'None yet.';
el.appendChild(none);
return;
}
arr.forEach((c, i) => {
const chip = document.createElement('span');
chip.className = 'cidr-chip';
chip.textContent = c;
const btn = document.createElement('button');
btn.type = 'button';
btn.setAttribute('aria-label', 'Remove ' + c);
btn.innerHTML = '×';
btn.onclick = () => removeCidr(kind, i);
chip.appendChild(btn);
el.appendChild(chip);
});
}
function addCidr(kind) {
const input = document.getElementById(kind + '-input');
const v = input.value.trim();
if (!v) return;
const arr = kind === 'include' ? includeList : excludeList;
if (!arr.includes(v)) arr.push(v);
input.value = '';
renderCidrList(kind);
}
function removeCidr(kind, i) {
const arr = kind === 'include' ? includeList : excludeList;
arr.splice(i, 1);
renderCidrList(kind);
}
function quickAddDetected(cidr) {
if (!includeList.includes(cidr)) {
includeList.push(cidr);
renderCidrList('include');
applyDetectedSuggestions(lastDetected);
}
}
let lastDetected = [];
function applyDetectedSuggestions(detected) {
lastDetected = detected || [];
const sug = document.getElementById('detected-suggestions');
sug.textContent = '';
const det = lastDetected.filter(c => !includeList.includes(c) && !excludeList.includes(c));
if (det.length === 0) return;
sug.appendChild(document.createTextNode('Detected: '));
det.forEach((c, idx) => {
if (idx) sug.appendChild(document.createTextNode(' · '));
const a = document.createElement('a');
a.href = '#';
a.textContent = c;
a.onclick = (e) => { e.preventDefault(); quickAddDetected(c); };
sug.appendChild(a);
});
}
function applyNetworksData(d) {
includeList = (d.networks || []).slice();
excludeList = (d.exclude_networks || []).slice();
setOnlyConfiguredToggle(!!d.only_configured);
renderCidrList('include');
renderCidrList('exclude');
applyDetectedSuggestions(d.detected);
}
async function loadNetworks() {
try {
const res = await fetch('/api/scan/networks').then(r => r.json());
if (res.success) applyNetworksData(res.data);
} catch (e) { /* leave empty if unreachable */ }
}
async function saveNetworks(reset) {
const status = document.getElementById('networks-status');
const only = document.getElementById('only-configured-toggle').getAttribute('aria-checked') === 'true';
const body = reset ? { reset: true } :
{ networks: includeList, exclude_networks: excludeList, only_configured: only };
try {
const res = await fetch('/api/scan/networks', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
}).then(r => r.json());
if (res.success) {
applyNetworksData(res.data);
status.textContent = 'Saved';
status.style.color = 'var(--success)';
} else {
status.textContent = res.error || 'Could not save';
status.style.color = 'var(--danger)';
}
} catch (e) {
status.textContent = 'Could not save';
status.style.color = 'var(--danger)';
}
setTimeout(() => { status.textContent = ''; }, 3500);
}
function resetNetworks() { saveNetworks(true); }
loadNetworks();
// Device groups. The list is built with the DOM (textContent), never by
// string-concatenating markup, so a group name can never inject anything.
// Rename edits in place; delete asks first when devices would be affected.
let groupCounts = {};
function renderGroups(data) {
groupCounts = data.counts || {};
const el = document.getElementById('group-list');
el.textContent = '';
const groups = data.groups || [];
if (groups.length === 0) {
const none = document.createElement('span');
none.className = 'form-help';
none.style.margin = '0';
none.textContent = 'No groups. Add one below, or reset to the defaults.';
el.appendChild(none);
return;
}
groups.forEach(name => el.appendChild(groupRow(name)));
}
function groupRow(name) {
const row = document.createElement('div');
row.className = 'group-row';
const label = document.createElement('span');
label.className = 'group-name';
label.textContent = name;
row.appendChild(label);
const count = groupCounts[name] || 0;
const meta = document.createElement('span');
meta.className = 'group-count';
meta.textContent = count === 1 ? '1 device' : count + ' devices';
row.appendChild(meta);
const actions = document.createElement('span');
actions.className = 'group-actions';
const rename = document.createElement('button');
rename.type = 'button';
rename.className = 'btn btn-sm';
rename.textContent = 'Rename';
rename.onclick = () => startRename(row, name);
actions.appendChild(rename);
const del = document.createElement('button');
del.type = 'button';
del.className = 'btn btn-sm danger';
del.textContent = 'Delete';
del.onclick = () => confirmDeleteGroup(row, name, count);
actions.appendChild(del);
row.appendChild(actions);
return row;
}
// Rename in place: swap the row for an input seeded with the current
// name, so the user edits the name rather than retyping it.
function startRename(row, name) {
row.textContent = '';
const input = document.createElement('input');
input.type = 'text';
input.className = 'input';
input.value = name;
input.maxLength = 32;
input.style.width = '220px';
input.onkeydown = (e) => {
if (e.key === 'Enter') { e.preventDefault(); commit(); }
if (e.key === 'Escape') { e.preventDefault(); loadGroups(); }
};
row.appendChild(input);
const save = document.createElement('button');
save.type = 'button';
save.className = 'btn btn-sm btn-primary';
save.textContent = 'Save';
save.onclick = commit;
row.appendChild(save);
const cancel = document.createElement('button');
cancel.type = 'button';
cancel.className = 'btn btn-sm';
cancel.textContent = 'Cancel';
cancel.onclick = () => loadGroups();
row.appendChild(cancel);
input.focus();
input.select();
function commit() {
const next = input.value.trim();
if (!next || next === name) { loadGroups(); return; }
groupAction({ action: 'rename', name: name, new_name: next });
}
}
// Deleting a group that devices are using is worth a confirm, since it
// clears the group from all of them. An empty group just goes.
function confirmDeleteGroup(row, name, count) {
if (count === 0) {
groupAction({ action: 'delete', name: name });
return;
}
row.textContent = '';
const msg = document.createElement('span');
msg.className = 'group-name';
msg.textContent = 'Remove "' + name + '" from ' + (count === 1 ? '1 device' : count + ' devices') + '?';
row.appendChild(msg);
const yes = document.createElement('button');
yes.type = 'button';
yes.className = 'btn btn-sm danger';
yes.textContent = 'Delete group';
yes.onclick = () => groupAction({ action: 'delete', name: name });
row.appendChild(yes);
const no = document.createElement('button');
no.type = 'button';
no.className = 'btn btn-sm';
no.textContent = 'Cancel';
no.onclick = () => loadGroups();
row.appendChild(no);
}
function addGroup() {
const input = document.getElementById('group-input');
const v = input.value.trim();
if (!v) return;
groupAction({ action: 'add', name: v }, () => { input.value = ''; });
}
function resetGroups() {
groupAction({ action: 'reset' });
}
async function loadGroups() {
try {
const res = await fetch('/api/groups').then(r => r.json());
if (res.success) renderGroups(res.data);
} catch (e) { /* leave empty if unreachable */ }
}
async function groupAction(body, onOk) {
const status = document.getElementById('groups-status');
try {
const res = await fetch('/api/groups', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
}).then(r => r.json());
if (res.success) {
renderGroups(res.data);
if (onOk) onOk();
status.textContent = 'Saved';
status.style.color = 'var(--success)';
} else {
// The server rejected it (duplicate, empty, too long). Show
// its message and put the list back the way it was.
status.textContent = res.error || 'Could not save';
status.style.color = 'var(--danger)';
loadGroups();
}
} catch (e) {
status.textContent = 'Could not save';
status.style.color = 'var(--danger)';
loadGroups();
}
setTimeout(() => { status.textContent = ''; }, 3500);
}
loadGroups();
// Backup / restore. Backup is a plain download link. Restore reads the
// chosen file, shows an inline confirm (destructive), then POSTs it.
let restoreData = null;
function onRestoreFile() {
const input = document.getElementById('restore-file');
const status = document.getElementById('restore-status');
const file = input.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = () => {
try {
restoreData = JSON.parse(reader.result);
} catch (e) {
status.textContent = 'That file is not valid JSON.';
status.style.color = 'var(--danger)';
input.value = '';
return;
}
status.textContent = '';
document.getElementById('restore-filename').textContent = file.name;
document.getElementById('restore-confirm').style.display = 'block';
};
reader.readAsText(file);
}
function cancelRestore() {
restoreData = null;
document.getElementById('restore-confirm').style.display = 'none';
document.getElementById('restore-file').value = '';
}
async function doRestore() {
if (!restoreData) return;
const status = document.getElementById('restore-status');
try {
const res = await fetch('/api/backup/restore', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(restoreData)
}).then(r => r.json());
if (res.success) {
status.textContent = 'Restored. Reloading…';
status.style.color = 'var(--success)';
setTimeout(() => location.reload(), 900);
} else {
status.textContent = res.error || 'Restore failed';
status.style.color = 'var(--danger)';
}
} catch (e) {
status.textContent = 'Restore failed';
status.style.color = 'var(--danger)';
}
document.getElementById('restore-confirm').style.display = 'none';
}
</script>
</body>
</html>