Files
homelab-config/status-monitor/app.py
T

731 lines
33 KiB
Python
Executable File

#!/usr/bin/env python3
"""Homelab Status Monitor v1.3.0"""
import socket
import ssl
import urllib.request
import json
import threading
from datetime import datetime
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
VERSION = "1.3.0"
# Service configuration: name, type (ssh/http/https), host, port, url (for http/https), insecure (for https)
# public_url: external HTTPS URL shown as clickable link (optional)
# label: extra tag shown as badge on card, e.g. "reverse proxy" (optional)
SERVICES = {
# Containers LXC
"ct101-mqtt": {"name": "MQTT", "type": "ssh", "host": "192.168.0.5", "port": 22},
"ct101-mqtt-http": {"name": "MQTT HTTP", "type": "http", "host": "192.168.0.5", "port": 1883, "url": "/"},
"ct102-frigate": {"name": "Frigate", "type": "ssh", "host": "192.168.0.91", "port": 22},
"ct102-frigate-http": {"name": "Frigate Web", "type": "http", "host": "192.168.0.91", "port": 5000, "url": "/"},
"ct103-adguard": {"name": "AdGuard", "type": "ssh", "host": "192.168.0.92", "port": 22},
"ct103-adguard-http": {"name": "AdGuard Web", "type": "http", "host": "192.168.0.92", "port": 80, "url": "/"},
"ct103-adguard-https": {"name": "AdGuard HTTPS", "type": "https", "host": "192.168.0.92", "port": 443, "url": "/", "insecure": True},
"ct105-alpine": {"name": "Alpine-Docker", "type": "ssh", "host": "192.168.0.155", "port": 22},
"ct105-alpine-docker": {"name": "Alpine Docker API", "type": "http", "host": "192.168.0.155", "port": 2375, "url": "/"},
"ct106-zigbee": {"name": "Zigbee2MQTT", "type": "ssh", "host": "192.168.0.177", "port": 22},
"ct106-zigbee-http": {"name": "Zigbee2MQTT Web", "type": "http", "host": "192.168.0.177", "port": 8081, "url": "/"},
# Traefik (CT200/CT100) - reverse proxy, no other service mixed here
"ct200-traefik": {"name": "Traefik Proxy", "type": "ssh", "host": "192.168.0.100", "port": 22},
"ct200-traefik-http": {"name": "Traefik HTTP", "type": "http", "host": "192.168.0.100", "port": 80, "url": "/"},
"ct200-traefik-https": {"name": "Traefik Dashboard", "type": "https", "host": "192.168.0.100", "port": 443, "url": "/", "public_url": "https://traefik.peis.fr/dashboard/", "insecure": True},
# Status Monitor (CT201)
"ct201-status": {"name": "Status Monitor", "type": "ssh", "host": "192.168.0.201", "port": 22},
"ct201-status-http": {"name": "Status Monitor Web", "type": "http", "host": "192.168.0.201", "port": 80, "url": "/"},
"ct201-status-https": {"name": "status.peis.fr", "type": "https", "host": "status.peis.fr", "port": 443, "url": "/", "public_url": "https://status.peis.fr/", "label": "reverse proxy", "insecure": True},
# Gitea (CT202) - own dedicated service, not mixed with Traefik
"ct202-gitea": {"name": "Gitea", "type": "ssh", "host": "192.168.0.202", "port": 22},
"ct202-gitea-http": {"name": "Gitea Web", "type": "http", "host": "192.168.0.202", "port": 3000, "url": "/", "public_url": "https://git.peis.fr/"},
"ct202-gitea-https": {"name": "git.peis.fr", "type": "https", "host": "git.peis.fr", "port": 443, "url": "/", "public_url": "https://git.peis.fr/", "label": "reverse proxy", "insecure": True},
# VM
"vm100-ha": {"name": "Home Assistant", "type": "ssh", "host": "192.168.0.43", "port": 22},
"vm100-ha-http": {"name": "Home Assistant Web", "type": "http", "host": "192.168.0.43", "port": 8123, "url": "/", "public_url": "https://ha.peis.fr/"},
# Proxmox hosts
"prox": {"name": "Proxmox (prox)", "type": "ssh", "host": "192.168.0.94", "port": 22},
"prox2": {"name": "Proxmox (prox2)", "type": "ssh", "host": "192.168.0.95", "port": 22},
# Raspberry Pi
"pi3": {"name": "Raspberry Pi 3", "type": "ssh", "host": "192.168.0.156", "port": 22},
# External HTTPS endpoints (Traefik reverse proxy)
"ha-peis-fr": {"name": "ha.peis.fr", "type": "https", "host": "ha.peis.fr", "port": 443, "url": "/", "public_url": "https://ha.peis.fr/", "label": "reverse proxy", "insecure": True},
"traefik-dash": {"name": "traefik.peis.fr", "type": "https", "host": "traefik.peis.fr", "port": 443, "url": "/dashboard/", "public_url": "https://traefik.peis.fr/dashboard/", "label": "reverse proxy", "insecure": True},
"test-peis-fr": {"name": "test.peis.fr", "type": "https", "host": "test.peis.fr", "port": 443, "url": "/", "public_url": "https://test.peis.fr/", "label": "reverse proxy", "insecure": True},
}
status_history = {}
status_cache = {}
lock = threading.Lock()
def check_ssh(host, port, timeout=3):
"""Check if SSH port is open."""
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
result = sock.connect_ex((host, port))
sock.close()
if result == 0:
return {"status": "online", "error": None}
else:
return {"status": "offline", "error": f"Connection refused (code: {result})"}
except socket.timeout:
return {"status": "timeout", "error": "Connection timed out"}
except Exception as e:
return {"status": "offline", "error": str(e)[:100]}
def check_http(host, port, url="/", timeout=5):
"""Check HTTP endpoint."""
try:
full_url = f"http://{host}:{port}{url}"
req = urllib.request.Request(full_url, headers={"User-Agent": "StatusMon"})
with urllib.request.urlopen(req, timeout=timeout) as r:
return {"status": "online", "status_code": r.status, "error": None}
except urllib.error.HTTPError as e:
return {"status": "online", "status_code": e.code, "error": None} # HTTP error still means service is up
except Exception as e:
return {"status": "offline", "error": str(e)[:100]}
def check_https(host, port, url="/", timeout=5, insecure=False):
"""Check HTTPS endpoint."""
try:
full_url = f"https://{host}:{port}{url}"
req = urllib.request.Request(full_url, headers={"User-Agent": "StatusMon"})
if insecure:
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
else:
ctx = ssl.create_default_context()
with urllib.request.urlopen(req, context=ctx, timeout=timeout) as r:
return {"status": "online", "status_code": r.status, "error": None}
except ssl.SSLError as e:
return {"status": "ssl_error", "error": f"SSL: {str(e)[:80]}"}
except urllib.error.HTTPError as e:
return {"status": "online", "status_code": e.code, "error": None}
except Exception as e:
return {"status": "offline", "error": str(e)[:100]}
def check_service(service_id, config):
"""Check a single service based on its type."""
st = config["type"]
if st == "ssh":
return check_ssh(config["host"], config["port"])
elif st == "http":
return check_http(config["host"], config["port"], config.get("url", "/"))
elif st == "https":
return check_https(config["host"], config["port"], config.get("url", "/"), config.get("insecure", False))
return {"status": "error", "error": f"Unknown type: {st}"}
def update_history(sid, old, new):
"""Update status change history."""
global status_history
if old != new:
status_history[sid] = {
"old_status": old,
"new_status": new,
"changed_at": datetime.now().isoformat()
}
def check_single(sid):
"""Check a single service and return its status."""
if sid not in SERVICES:
return None
result = check_service(sid, SERVICES[sid])
return {"config": SERVICES[sid], "result": result, "time": datetime.now().isoformat()}
def check_all():
"""Check all services and update cache."""
global status_cache, status_history
new_cache = {}
for sid, cfg in SERVICES.items():
result = check_service(sid, cfg)
old = status_cache.get(sid, {}).get("result", {}).get("status", "unknown")
new = result["status"]
if old != new:
update_history(sid, old, new)
new_cache[sid] = {"config": cfg, "result": result, "time": datetime.now().isoformat()}
with lock:
status_cache = new_cache
return new_cache
# HTML Templates
def generate_html():
"""Generate the main dashboard HTML page."""
services_json = json.dumps(SERVICES)
return '''<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Homelab Status Monitor v''' + VERSION + '''</title>
<style>
:root {
--bg: #0b0f19;
--surface: rgba(30, 41, 59, 0.65);
--surface-solid: #151d2a;
--text: #e2e8f0;
--muted: #94a3b8;
--accent: #60a5fa;
--accent-2: #818cf8;
--online: #22c55e;
--offline: #ef4444;
--warning: #f59e0b;
--waiting: #64748b;
}
* { box-sizing: border-box; }
body {
font-family: "Segoe UI", system-ui, -apple-system, sans-serif;
background: radial-gradient(circle at top left, #172033 0%, var(--bg) 40%), var(--bg);
color: var(--text);
margin: 0;
padding: 24px;
min-height: 100vh;
}
.container { max-width: 1400px; margin: 0 auto; }
header { text-align: center; margin-bottom: 24px; position: relative; }
h1 {
font-size: 2.4em;
font-weight: 800;
margin: 0;
background: linear-gradient(90deg, var(--accent), var(--accent-2));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
letter-spacing: -0.02em;
}
.version { color: var(--muted); font-size: 0.9em; margin-top: 6px; }
.topbar {
display: flex;
justify-content: center;
align-items: center;
gap: 12px;
flex-wrap: wrap;
margin: 20px 0;
}
.topbar a, .topbar button {
padding: 10px 18px;
border-radius: 999px;
border: 1px solid rgba(148, 163, 184, 0.25);
background: var(--surface);
color: var(--text);
font-size: 0.9em;
cursor: pointer;
text-decoration: none;
backdrop-filter: blur(12px);
transition: transform 0.15s, background 0.2s, box-shadow 0.2s;
}
.topbar a:hover, .topbar button:hover:not(:disabled) {
background: rgba(96, 165, 250, 0.18);
transform: translateY(-1px);
box-shadow: 0 4px 20px rgba(96, 165, 250, 0.12);
}
.topbar button:disabled { opacity: 0.6; cursor: not-allowed; }
.filters { text-align: center; margin: 18px 0; }
.filter-btn {
background: transparent;
border: 1px solid rgba(148, 163, 184, 0.25);
color: var(--muted);
margin: 0 5px 8px 0;
border-radius: 999px;
padding: 8px 18px;
backdrop-filter: blur(10px);
}
.filter-btn.active { background: linear-gradient(90deg, var(--accent), var(--accent-2)); color: #fff; border-color: transparent; font-weight: 600; }
.summary { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 16px; margin: 22px 0; }
.card-sum {
background: var(--surface);
border: 1px solid rgba(148, 163, 184, 0.15);
border-radius: 16px;
padding: 18px;
text-align: center;
backdrop-filter: blur(14px);
box-shadow: 0 8px 32px rgba(0,0,0,0.18);
}
.card-sum .count { font-size: 2.2em; font-weight: 800; color: var(--accent); }
.card-sum .label { color: var(--muted); font-size: 0.9em; margin-top: 4px; }
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 18px; margin-top: 24px; }
.card {
background: var(--surface);
border: 1px solid rgba(148, 163, 184, 0.12);
border-radius: 18px;
padding: 18px;
position: relative;
backdrop-filter: blur(16px);
box-shadow: 0 10px 40px rgba(0,0,0,0.2);
transition: transform 0.2s, box-shadow 0.2s;
overflow: hidden;
}
.card::before {
content: "";
position: absolute;
top: 0; left: 0; right: 0; height: 4px;
background: var(--waiting);
}
.card.online::before { background: var(--online); box-shadow: 0 0 14px var(--online); }
.card.offline::before { background: var(--offline); box-shadow: 0 0 14px var(--offline); }
.card.timeout::before, .card.ssl_error::before { background: var(--warning); box-shadow: 0 0 14px var(--warning); }
.card.error::before { background: var(--offline); box-shadow: 0 0 14px var(--offline); }
.card.waiting::before { background: var(--waiting); }
.card:hover { transform: translateY(-3px); box-shadow: 0 16px 48px rgba(0,0,0,0.28); }
.card-header { display: flex; justify-content: space-between; align-items: center; gap: 10px; margin-bottom: 12px; }
.name { font-weight: 700; font-size: 1.15em; flex: 1; }
.badges-row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
.tag {
font-size: 0.72em;
padding: 4px 10px;
border-radius: 999px;
text-transform: uppercase;
letter-spacing: 0.03em;
font-weight: 700;
}
.tag.type { background: rgba(148, 163, 184, 0.18); color: var(--muted); }
.tag.label { background: linear-gradient(90deg, rgba(96,165,250,0.2), rgba(129,140,248,0.2)); color: var(--accent); border: 1px solid rgba(96,165,250,0.25); }
.badge {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 14px;
border-radius: 999px;
font-size: 0.85em;
font-weight: 700;
margin-top: 6px;
}
.badge::before { content: ""; width: 8px; height: 8px; border-radius: 50%; background: currentColor; }
.badge.online { background: rgba(34, 197, 94, 0.12); color: var(--online); }
.badge.offline { background: rgba(239, 68, 68, 0.12); color: var(--offline); }
.badge.timeout, .badge.ssl_error { background: rgba(245, 158, 11, 0.12); color: var(--warning); }
.badge.error { background: rgba(239, 68, 68, 0.12); color: var(--offline); }
.badge.waiting { background: rgba(100, 116, 139, 0.12); color: var(--waiting); }
.details { margin-top: 14px; font-size: 0.88em; color: var(--muted); }
.details a { color: var(--accent); text-decoration: none; }
.details a:hover { text-decoration: underline; }
.error { color: #fca5a5; margin-top: 8px; font-size: 0.85em; word-break: break-word; }
.history-note { font-size: 0.78em; color: var(--muted); margin-top: 10px; }
.refresh-btn {
width: 32px; height: 32px;
border-radius: 50%;
border: 1px solid rgba(148, 163, 184, 0.25);
background: var(--surface-solid);
color: var(--text);
display: inline-flex;
align-items: center;
justify-content: center;
cursor: pointer;
font-size: 0.95em;
transition: background 0.2s, transform 0.15s;
padding: 0;
flex-shrink: 0;
}
.refresh-btn:hover:not(:disabled) { background: rgba(96, 165, 250, 0.22); transform: rotate(90deg); }
.refresh-btn:disabled { opacity: 0.5; cursor: not-allowed; }
@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
.loading-spinner { display: inline-block; width: 16px; height: 16px; border: 2px solid rgba(148,163,184,0.25); border-top-color: var(--accent); border-radius: 50%; animation: spin 0.8s linear infinite; }
.loading { width: 16px; height: 16px; border-radius: 50%; border: 2px solid rgba(148,163,184,0.25); border-top-color: var(--accent); animation: spin 0.9s linear infinite; }
#ts { color: var(--muted); font-size: 0.85em; margin-left: 10px; }
#global-loading { margin-left: 8px; vertical-align: middle; }
</style>
</head>
<body>
<div class="container">
<header>
<h1>Homelab Status Monitor</h1>
<div class="version">v''' + VERSION + '''</div>
</header>
<div class="topbar">
<button class="refresh-all" onclick="refreshAll()">Refresh All</button>
<button onclick="location.reload()">Reload Page</button>
<a href="/apps">Applications List</a>
<span id="ts"></span>
<span id="global-loading"></span>
</div>
<div class="filters" id="filters">
<button class="filter-btn active" data-filter="all" onclick="setFilter('all')">All</button>
<button class="filter-btn" data-filter="ssh" onclick="setFilter('ssh')">SSH</button>
<button class="filter-btn" data-filter="http" onclick="setFilter('http')">HTTP</button>
<button class="filter-btn" data-filter="https" onclick="setFilter('https')">HTTPS</button>
<button class="filter-btn" data-filter="reverse" onclick="setFilter('reverse')">Reverse Proxy</button>
<button class="filter-btn" data-filter="others" onclick="setFilter('others')">Others</button>
</div>
<div class="summary">
<div class="card-sum"><div class="count" id="total">0</div><div class="label">Total</div></div>
<div class="card-sum"><div class="count" id="ok">0</div><div class="label">Online</div></div>
<div class="card-sum"><div class="count" id="ko">0</div><div class="label">Offline</div></div>
<div class="card-sum"><div class="count" id="err">0</div><div class="label">Errors</div></div>
</div>
<div class="grid" id="grid"></div>
</div>
<script>
const SERVICE_DEFS = ''' + services_json + ''';
let data = {};
let history = {};
let refreshInProgress = false;
let activeFilter = 'all';
function initWaiting() {
const now = new Date().toISOString();
for (const [id, cfg] of Object.entries(SERVICE_DEFS)) {
data[id] = {config: cfg, result: {status: "waiting"}, time: now};
}
render();
}
function getClass(s) {
return {"online": "online", "offline": "offline", "timeout": "timeout", "error": "error", "ssl_error": "ssl_error", "waiting": "waiting"}[s] || "offline";
}
function fmtHist(sid) {
if (history[sid]) {
const h = history[sid];
return "Changed: " + h.old_status + " -> " + h.new_status + " at " + new Date(h.changed_at).toLocaleTimeString();
}
return "";
}
function setGlobalLoad(b) {
refreshInProgress = b;
document.getElementById("global-loading").innerHTML = b ? '<span class="loading-spinner"></span>' : '';
}
function setFilter(type) {
activeFilter = type;
document.querySelectorAll('.filter-btn').forEach(btn => btn.classList.toggle('active', btn.dataset.filter === type));
render();
}
function buildLink(c) {
if (c.public_url) return "<a href='" + c.public_url + "' target='_blank' rel='noopener noreferrer'>" + c.public_url + "</a>";
if (c.type === 'http') return "<a href='http://" + c.host + ":" + c.port + c.url + "' target='_blank' rel='noopener noreferrer'>" + c.host + ":" + c.port + c.url + "</a>";
if (c.type === 'https') return "<a href='https://" + c.host + ":" + c.port + c.url + "' target='_blank' rel='noopener noreferrer'>" + c.host + ":" + c.port + c.url + "</a>";
return c.host + ":" + c.port;
}
function matchesFilter(c) {
if (activeFilter === 'all') return true;
if (activeFilter === 'others') return c.type !== 'ssh' && c.type !== 'http' && c.type !== 'https';
if (activeFilter === 'reverse') return c.label === 'reverse proxy';
return c.type === activeFilter;
}
function render() {
let h = "";
let t = 0, ok = 0, ko = 0, err = 0;
for (const [id, v] of Object.entries(data)) {
const c = v.config, r = v.result, s = r.status;
if (!matchesFilter(c)) continue;
t++;
if (s === "online") ok++;
else if (s === "offline" || s === "error" || s === "timeout" || s === "ssl_error") ko++;
else if (s !== "waiting") err++;
const bc = getClass(s);
const label = c.label ? "<span class='tag label'>" + c.label + "</span>" : "";
const link = s === 'waiting' ? "<span class='loading'></span> Checking..." : buildLink(c);
h += "<div class='card " + bc + "'>";
h += "<div class='card-header'>";
h += "<div class='name'>" + c.name + "</div>";
h += "<div class='badges-row'>" + label + "<span class='tag type'>" + c.type + "</span><button class='refresh-btn' onclick='refreshService(&quot;" + id + "&quot;)' title='Refresh'>&#x21bb;</button></div>";
h += "</div>";
h += "<span class='badge " + bc + "'>" + s.replace(/_/g, " ") + "</span>";
h += "<div class='details'>" + link + "</div>";
if (r.error && s !== 'waiting') h += "<div class='error'>" + r.error + "</div>";
if (r.status_code) h += "<div class='details'>Status: " + r.status_code + "</div>";
if (s !== 'waiting') h += "<div class='details'>Checked: " + new Date(v.time).toLocaleTimeString() + "</div>";
const hist = fmtHist(id);
if (hist) h += "<div class='history-note'>" + hist + "</div>";
h += "</div>";
}
document.getElementById("grid").innerHTML = h || "<p style='color:#64748b;text-align:center;'>No services to display for this filter</p>";
document.getElementById("total").textContent = t;
document.getElementById("ok").textContent = ok;
document.getElementById("ko").textContent = ko;
document.getElementById("err").textContent = err;
document.getElementById("ts").textContent = "Updated: " + new Date().toLocaleTimeString();
}
function refreshService(sid) {
const btn = event.currentTarget;
const original = btn.innerHTML;
btn.disabled = true;
btn.innerHTML = '<span class="loading-spinner"></span>';
fetch("/api/check/" + encodeURIComponent(sid))
.then(r => r.json())
.then(d => { data[sid] = d; if (d.history) history[sid] = d.history; render(); })
.catch(err => console.error("Error:", err))
.finally(() => { btn.disabled = false; btn.innerHTML = original; });
}
function refreshAll() {
const btn = document.querySelector(".refresh-all");
setGlobalLoad(true);
btn.disabled = true;
btn.innerHTML = '<span class="loading-spinner"></span> Refreshing...';
fetch("/api/refresh")
.then(r => r.json())
.then(d => { data = d.data; history = d.history || {}; render(); })
.catch(err => console.error("Error:", err))
.finally(() => { setGlobalLoad(false); btn.disabled = false; btn.innerHTML = "Refresh All"; });
}
function fetchStatus() {
setGlobalLoad(true);
fetch("/api/status")
.then(r => r.json())
.then(d => { data = d.data; history = d.history || {}; render(); })
.catch(err => console.error("Error:", err))
.finally(() => setGlobalLoad(false));
}
initWaiting();
fetchStatus();
setInterval(fetchStatus, 30000);
</script>
</body>
</html>'''
def generate_apps_html():
"""Generate the applications list page with sortable and persistent order."""
apps = []
for sid, cfg in SERVICES.items():
url = None
if cfg.get("public_url"):
url = cfg["public_url"]
elif cfg.get("type") in ("http", "https"):
proto = cfg["type"]
url = f"{proto}://{cfg['host']}:{cfg['port']}{cfg.get('url', '/')}"
if url:
apps.append({"id": sid, "name": cfg["name"], "url": url})
apps_json = json.dumps(apps)
return '''<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Applications - Homelab Status Monitor v''' + VERSION + '''</title>
<style>
:root {
--bg: #0b0f19;
--surface: rgba(30, 41, 59, 0.65);
--text: #e2e8f0;
--muted: #94a3b8;
--accent: #60a5fa;
--accent-2: #818cf8;
}
* { box-sizing: border-box; }
body {
font-family: "Segoe UI", system-ui, -apple-system, sans-serif;
background: radial-gradient(circle at top left, #172033 0%, var(--bg) 40%), var(--bg);
color: var(--text);
margin: 0; padding: 24px; min-height: 100vh;
}
.container { max-width: 900px; margin: 0 auto; }
header { text-align: center; margin-bottom: 24px; }
h1 {
font-size: 2.2em; font-weight: 800; margin: 0;
background: linear-gradient(90deg, var(--accent), var(--accent-2));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.back { display: inline-block; margin-bottom: 20px; color: var(--accent); text-decoration: none; }
.back:hover { text-decoration: underline; }
.hint { color: var(--muted); font-size: 0.9em; margin-bottom: 18px; text-align: center; }
.app-list { list-style: none; padding: 0; margin: 0; }
.app-item {
background: var(--surface);
border: 1px solid rgba(148, 163, 184, 0.15);
border-radius: 16px;
padding: 16px 18px;
margin-bottom: 12px;
display: flex;
align-items: center;
gap: 14px;
cursor: grab;
backdrop-filter: blur(14px);
box-shadow: 0 8px 32px rgba(0,0,0,0.18);
transition: transform 0.15s, box-shadow 0.2s, background 0.2s;
}
.app-item:active { cursor: grabbing; }
.app-item.dragging { opacity: 0.5; transform: scale(0.98); }
.app-item:hover { box-shadow: 0 12px 40px rgba(0,0,0,0.25); transform: translateY(-2px); }
.drag-handle {
width: 24px; height: 24px;
display: flex; flex-direction: column; justify-content: center; gap: 4px;
color: var(--muted);
}
.drag-handle span { display: block; height: 2px; background: currentColor; border-radius: 2px; }
.app-name { font-weight: 700; font-size: 1.05em; flex: 1; }
.app-url { color: var(--accent); text-decoration: none; word-break: break-all; }
.app-url:hover { text-decoration: underline; }
</style>
</head>
<body>
<div class="container">
<header>
<a href="/" class="back">&larr; Back to dashboard</a>
<h1>Applications</h1>
</header>
<div class="hint">Drag items to reorder. The order is saved in your browser.</div>
<ul class="app-list" id="app-list"></ul>
</div>
<script>
const APPS = ''' + apps_json + ''';
const STORAGE_KEY = "statusmonitor_apps_order";
function getOrderedApps() {
const saved = localStorage.getItem(STORAGE_KEY);
if (!saved) return APPS.slice();
let order;
try { order = JSON.parse(saved); } catch (e) { return APPS.slice(); }
const map = new Map(APPS.map(a => [a.id, a]));
const ordered = order.map(id => map.get(id)).filter(a => a);
const remaining = APPS.filter(a => !order.includes(a.id));
return ordered.concat(remaining);
}
function saveOrder(order) {
localStorage.setItem(STORAGE_KEY, JSON.stringify(order));
}
function renderList() {
const list = document.getElementById("app-list");
const apps = getOrderedApps();
list.innerHTML = apps.map(a =>
"<li class='app-item' draggable='true' data-id='" + a.id + "'>" +
"<div class='drag-handle'><span></span><span></span><span></span></div>" +
"<div class='app-name'>" + a.name + "</div>" +
"<a class='app-url' href='" + a.url + "' target='_blank' rel='noopener noreferrer'>" + a.url + "</a>" +
"</li>"
).join("");
initDrag();
}
function initDrag() {
const list = document.getElementById("app-list");
let dragged = null;
list.querySelectorAll(".app-item").forEach(item => {
item.addEventListener("dragstart", function(e) {
dragged = item;
item.classList.add("dragging");
e.dataTransfer.effectAllowed = "move";
});
item.addEventListener("dragend", function() {
item.classList.remove("dragging");
dragged = null;
const order = Array.from(list.children).map(li => li.dataset.id);
saveOrder(order);
});
item.addEventListener("dragover", function(e) {
e.preventDefault();
if (!dragged || dragged === item) return;
const rect = item.getBoundingClientRect();
const offset = e.clientY - rect.top - rect.height / 2;
if (offset < 0) list.insertBefore(dragged, item);
else list.insertBefore(dragged, item.nextSibling);
});
});
}
renderList();
</script>
</body>
</html>'''
class Handler(BaseHTTPRequestHandler):
"""HTTP request handler."""
def log_message(self, *args):
"""Suppress default logging."""
pass
def do_GET(self):
"""Handle GET requests."""
try:
if self.path in ['/', '/index.html']:
self.send_response(200)
self.send_header('Content-type', 'text/html; charset=utf-8')
self.end_headers()
self.wfile.write(generate_html().encode('utf-8'))
elif self.path in ['/apps', '/apps.html']:
self.send_response(200)
self.send_header('Content-type', 'text/html; charset=utf-8')
self.end_headers()
self.wfile.write(generate_apps_html().encode('utf-8'))
elif self.path == '/api/status':
check_all() # Always refresh cache
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.send_header('Cache-Control', 'no-cache')
self.end_headers()
self.wfile.write(json.dumps({"data": status_cache, "history": status_history}, default=str).encode('utf-8'))
elif self.path == '/api/refresh':
result = check_all()
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({"data": result, "history": status_history}, default=str).encode('utf-8'))
elif self.path.startswith('/api/check/'):
sid = self.path.split('/')[-1]
if sid in SERVICES:
old = status_cache.get(sid, {}).get("result", {}).get("status", "unknown")
rd = check_single(sid)
new_st = rd["result"]["status"]
if old != new_st:
update_history(sid, old, new_st)
with lock:
status_cache[sid] = rd
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({**rd, "history": status_history.get(sid)}, default=str).encode('utf-8'))
else:
self.send_response(404)
self.end_headers()
else:
self.send_response(404)
self.end_headers()
except Exception as e:
self.send_response(500)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({"error": str(e)}).encode('utf-8'))
def main():
"""Main entry point."""
print(f"Starting Status Monitor v{VERSION}")
check_all()
server = ThreadingHTTPServer(('', 80), Handler)
print(f'Status Monitor v{VERSION} running on port 80')
server.serve_forever()
if __name__ == '__main__':
main()