feat: add Synology NAS, Home Assistant monitoring, multi-channel notifications

New tabs:
- Synology NAS: CPU, RAM, temp, volumes, VMs, Docker containers
- Home Assistant: sensors, automations, persons, climate, battery, doors

New features:
- Personalized PC agent download with custom name
- Notification settings: per-category Telegram/Email/WhatsApp toggles
- Email via SMTP, WhatsApp via CallMeBot API
- Test notification buttons for each channel
- Unified notifier replaces direct Telegram calls in alerter

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Андрей Бобырев
2026-05-20 13:59:57 +03:00
parent bab8fc33cc
commit cc01667879
12 changed files with 1910 additions and 82 deletions

115
server/api/ha.py Normal file
View File

@@ -0,0 +1,115 @@
"""Home Assistant monitoring API endpoints."""
import json
from datetime import datetime
from typing import Dict
from fastapi import APIRouter, Request, Depends
from server.auth import require_auth
from server.config import DATA_DIR
router = APIRouter(prefix="/api/ha", tags=["homeassistant"])
# In-memory cache
ha_metrics: Dict[str, dict] = {}
HA_FILE = DATA_DIR / "homeassistant.json"
def _load_ha():
if HA_FILE.exists():
with open(HA_FILE) as f:
return json.load(f)
return []
def _save_ha(data):
with open(HA_FILE, "w") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
@router.get("/list")
async def ha_list(request: Request, user: str = Depends(require_auth)):
"""List all Home Assistant instances with metrics."""
instances = _load_ha()
for inst in instances:
name = inst["name"]
if name in ha_metrics:
inst["metrics"] = ha_metrics[name]
return instances
@router.post("/add")
async def ha_add(request: Request, user: str = Depends(require_auth)):
"""Add a Home Assistant instance."""
body = await request.json()
name = body.get("name", "").strip()
url = body.get("url", "").strip()
token = body.get("token", "").strip()
if not name or not url or not token:
return {"status": "error", "detail": "name, url, and token required"}
instances = _load_ha()
instance = {
"name": name,
"url": url,
"token": token,
"added": datetime.now().isoformat(),
}
instances.append(instance)
_save_ha(instances)
return {"status": "ok"}
@router.delete("/{name}")
async def ha_delete(name: str, request: Request, user: str = Depends(require_auth)):
"""Remove a Home Assistant instance."""
instances = _load_ha()
instances = [i for i in instances if i["name"] != name]
_save_ha(instances)
ha_metrics.pop(name, None)
return {"status": "ok"}
@router.post("/refresh/{name}")
async def ha_refresh(name: str, request: Request, user: str = Depends(require_auth)):
"""Force refresh metrics for a Home Assistant instance."""
from server.services.ha_client import HomeAssistantClient
instances = _load_ha()
inst = next((i for i in instances if i["name"] == name), None)
if not inst:
return {"status": "error", "detail": "instance not found"}
client = HomeAssistantClient(url=inst["url"], token=inst["token"])
try:
metrics = await client.collect_all_metrics()
metrics["last_updated"] = datetime.now().isoformat()
ha_metrics[name] = metrics
return {"status": "ok", "metrics": metrics}
except Exception as e:
return {"status": "error", "detail": str(e)}
@router.post("/refresh-all")
async def ha_refresh_all(request: Request, user: str = Depends(require_auth)):
"""Refresh metrics for all Home Assistant instances."""
from server.services.ha_client import HomeAssistantClient
instances = _load_ha()
results = []
for inst in instances:
client = HomeAssistantClient(url=inst["url"], token=inst["token"])
try:
metrics = await client.collect_all_metrics()
metrics["last_updated"] = datetime.now().isoformat()
ha_metrics[inst["name"]] = metrics
results.append({"name": inst["name"], "online": metrics["online"]})
except Exception as e:
results.append({"name": inst["name"], "online": False, "error": str(e)})
return {"status": "ok", "results": results}

111
server/api/notifications.py Normal file
View File

@@ -0,0 +1,111 @@
"""Notification settings and test endpoints."""
from fastapi import APIRouter, Request, Depends
from server.auth import require_auth
from server.config import load_settings, save_settings
router = APIRouter(prefix="/api/notifications", tags=["notifications"])
@router.get("/settings")
async def get_notification_settings(request: Request, user: str = Depends(require_auth)):
"""Get notification preferences per category."""
settings = load_settings()
return {
"notifications": settings.get("notifications", {
"servers": {"telegram": True, "email": False, "whatsapp": False},
"pc": {"telegram": True, "email": False, "whatsapp": False},
"synology": {"telegram": True, "email": False, "whatsapp": False},
"ha": {"telegram": True, "email": False, "whatsapp": False},
}),
"email": {
"smtp_host": settings.get("smtp_host", ""),
"smtp_port": settings.get("smtp_port", 587),
"smtp_user": settings.get("smtp_user", ""),
"email_to": settings.get("email_to", ""),
"configured": bool(settings.get("smtp_host") and settings.get("smtp_user")),
},
"whatsapp": {
"phone": settings.get("whatsapp_phone", ""),
"configured": bool(settings.get("whatsapp_phone") and settings.get("whatsapp_apikey")),
},
"telegram": {
"configured": bool(settings.get("telegram_bot_token") and settings.get("telegram_chat_id")),
},
}
@router.put("/settings")
async def save_notification_settings(request: Request, user: str = Depends(require_auth)):
"""Save notification preferences."""
body = await request.json()
settings = load_settings()
# Notification toggles per category
if "notifications" in body:
settings["notifications"] = body["notifications"]
# Email settings
if "smtp_host" in body:
settings["smtp_host"] = body["smtp_host"]
if "smtp_port" in body:
settings["smtp_port"] = int(body["smtp_port"])
if "smtp_user" in body:
settings["smtp_user"] = body["smtp_user"]
if "smtp_password" in body:
settings["smtp_password"] = body["smtp_password"]
if "email_to" in body:
settings["email_to"] = body["email_to"]
# WhatsApp settings
if "whatsapp_phone" in body:
settings["whatsapp_phone"] = body["whatsapp_phone"]
if "whatsapp_apikey" in body:
settings["whatsapp_apikey"] = body["whatsapp_apikey"]
save_settings(settings)
return {"status": "ok"}
@router.post("/test/{channel}")
async def test_notification(channel: str, request: Request, user: str = Depends(require_auth)):
"""Send test notification via specified channel."""
from server.services.notifier import send_telegram, send_email, send_whatsapp
message = "🧪 Тест уведомления VPS Monitoring"
ok = False
if channel == "telegram":
ok = await send_telegram(message)
elif channel == "email":
ok = await send_email("Тест", message)
elif channel == "whatsapp":
ok = await send_whatsapp(message)
else:
return {"status": "error", "detail": f"unknown channel: {channel}"}
return {"status": "ok" if ok else "error", "channel": channel}
@router.post("/generate-pc-agent")
async def generate_pc_agent(request: Request, user: str = Depends(require_auth)):
"""Generate personalized PC agent install command."""
body = await request.json()
agent_name = body.get("agent_name", "MyPC").strip()
server_url = body.get("server_url", "").strip()
if not server_url:
# Auto-detect
host = request.headers.get("host", "localhost:7272")
proto = "http"
server_url = f"{proto}://{host}"
cmd = (
f'powershell -ExecutionPolicy Bypass -Command '
f'"Invoke-WebRequest -Uri \'{server_url}/static/downloads/install_agent.ps1\' '
f'-OutFile install_agent.ps1; .\\install_agent.ps1 '
f'-ServerUrl \'{server_url}\' -AgentName \'{agent_name}\'"'
)
return {"status": "ok", "command": cmd, "agent_name": agent_name}

132
server/api/synology.py Normal file
View File

@@ -0,0 +1,132 @@
"""Synology NAS monitoring API endpoints."""
import json
from datetime import datetime
from typing import Dict, List
from fastapi import APIRouter, Request, Depends
from server.auth import require_auth
from server.config import DATA_DIR
router = APIRouter(prefix="/api/synology", tags=["synology"])
# In-memory cache
synology_metrics: Dict[str, dict] = {}
SYNOLOGY_FILE = DATA_DIR / "synology.json"
def _load_synology():
if SYNOLOGY_FILE.exists():
with open(SYNOLOGY_FILE) as f:
return json.load(f)
return []
def _save_synology(data):
with open(SYNOLOGY_FILE, "w") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
@router.get("/list")
async def synology_list(request: Request, user: str = Depends(require_auth)):
"""List all Synology NAS devices with metrics."""
devices = _load_synology()
# Merge with in-memory cache
for dev in devices:
name = dev["name"]
if name in synology_metrics:
dev["metrics"] = synology_metrics[name]
return devices
@router.post("/add")
async def synology_add(request: Request, user: str = Depends(require_auth)):
"""Add a Synology NAS device."""
body = await request.json()
name = body.get("name", "").strip()
host = body.get("host", "").strip()
if not name or not host:
return {"status": "error", "detail": "name and host required"}
devices = _load_synology()
device = {
"name": name,
"host": host,
"port": int(body.get("port", 5000)),
"https": body.get("https", False),
"username": body.get("username", ""),
"password": body.get("password", ""),
"added": datetime.now().isoformat(),
}
devices.append(device)
_save_synology(devices)
return {"status": "ok"}
@router.delete("/{name}")
async def synology_delete(name: str, request: Request, user: str = Depends(require_auth)):
"""Remove a Synology NAS device."""
devices = _load_synology()
devices = [d for d in devices if d["name"] != name]
_save_synology(devices)
synology_metrics.pop(name, None)
return {"status": "ok"}
@router.post("/refresh/{name}")
async def synology_refresh(name: str, request: Request, user: str = Depends(require_auth)):
"""Force refresh metrics for a Synology device."""
from server.services.synology_client import SynologyClient
devices = _load_synology()
dev = next((d for d in devices if d["name"] == name), None)
if not dev:
return {"status": "error", "detail": "device not found"}
client = SynologyClient(
host=dev["host"],
port=dev.get("port", 5000),
https=dev.get("https", False),
username=dev.get("username", ""),
password=dev.get("password", ""),
)
try:
metrics = await client.collect_all_metrics()
metrics["last_updated"] = datetime.now().isoformat()
synology_metrics[name] = metrics
await client.logout()
return {"status": "ok", "metrics": metrics}
except Exception as e:
return {"status": "error", "detail": str(e)}
@router.post("/refresh-all")
async def synology_refresh_all(request: Request, user: str = Depends(require_auth)):
"""Refresh metrics for all Synology devices."""
from server.services.synology_client import SynologyClient
devices = _load_synology()
results = []
for dev in devices:
client = SynologyClient(
host=dev["host"],
port=dev.get("port", 5000),
https=dev.get("https", False),
username=dev.get("username", ""),
password=dev.get("password", ""),
)
try:
metrics = await client.collect_all_metrics()
metrics["last_updated"] = datetime.now().isoformat()
synology_metrics[dev["name"]] = metrics
await client.logout()
results.append({"name": dev["name"], "online": metrics["online"]})
except Exception as e:
results.append({"name": dev["name"], "online": False, "error": str(e)})
return {"status": "ok", "results": results}