let servers = [];
let currentTerminal = null;
let currentWs = null;
// i18n render
function renderPage() {
document.querySelectorAll('[data-i18n]').forEach(el => {
const key = el.getAttribute('data-i18n');
el.textContent = t(key);
});
document.getElementById('langBtn').textContent = currentLang.toUpperCase();
document.getElementById('addServerBtn').textContent = t('addServer');
renderServers();
}
// Load servers
async function loadServers() {
try {
const resp = await fetch('/api/servers', {credentials: 'include'});
if (resp.status === 401) {
window.location.href = '/login';
return;
}
servers = await resp.json();
renderServers();
} catch (e) {
console.error('Load error:', e);
}
}
function renderServers() {
const grid = document.getElementById('servers-grid');
const online = servers.filter(s => s.metrics?.online).length;
const offline = servers.length - online;
document.getElementById('total-count').textContent = servers.length;
document.getElementById('online-count').textContent = online;
document.getElementById('offline-count').textContent = offline;
if (!servers.length) {
grid.innerHTML = `
${m.online ? `
` : ''}
${srv.description ? `
` : ''}
`;
modal.style.display = 'flex';
}
// Instructions
function showInstructions() {
const content = document.getElementById('instructions-content');
content.innerHTML = `
📥 ${t('instr_install')}
${t('instr_add_server_text').includes('Click') ? 'One command to install on any Ubuntu/Debian server:' : 'Одна команда для установки на Ubuntu/Debian:'}
${t('instr_install_text')}
➕ ${t('instr_add_server')}
${t('instr_add_server_text')}
💻 ${t('instr_ssh')}
${t('instr_ssh_text')}
🤖 ${t('instr_telegram')}
${t('instr_telegram_text')}
🔄 ${t('instr_reboot')}
${t('instr_reboot_text')}
⚠️ ${t('instr_thresholds')}
${t('instr_thresholds_text')}
🔧 ${t('instr_commands')}
📊 ${t('instr_cmd_status')}
🔄 ${t('instr_cmd_restart')}
📋 ${t('instr_cmd_logs')}
⬆️ ${t('instr_cmd_update')}
🔌 ${t('instr_api')}
GET /api/servers — list all
POST /api/servers — add server
DELETE /api/servers/{id} — remove
POST /api/servers/{id}/reboot — reboot
GET /api/synology/list — Synology NAS
GET /api/ha/list — Home Assistant
GET /api/pc/list — PC agents
GET /api/notifications/settings
WS /ws/ssh/{id} — SSH terminal
`;
document.getElementById('instructionsModal').style.display = 'flex';
}
// SSH Terminal
function openSSH(id, name) {
const modal = document.getElementById('sshModal');
document.getElementById('ssh-title').textContent = `${t('sshTerminal')} — ${name}`;
modal.style.display = 'flex';
const container = document.getElementById('terminal-container');
container.innerHTML = '';
if (typeof Terminal === 'undefined') {
container.innerHTML = 'Нет подключённых ПК. Нажмите "📥 Скачать агент".
';
return;
}
grid.innerHTML = pcAgents.map(pc => {
const m = pc.metrics || {};
const isOnline = pc.online;
const cpu = m.cpu_percent || 0;
const ram = m.ram_percent || 0;
const disk = m.disk_percent || 0;
const cpuClass = cpu > 90 ? 'crit' : cpu > 70 ? 'warn' : '';
const ramClass = ram > 90 ? 'crit' : ram > 70 ? 'warn' : '';
const diskClass = disk > 90 ? 'crit' : disk > 70 ? 'warn' : '';
const disksHtml = (m.disks || []).map(d =>
`Нет Synology NAS. Нажмите "+ Добавить NAS".
';
return;
}
grid.innerHTML = synologyDevices.map(dev => {
const m = dev.metrics || {};
const isOnline = m.online;
const cpu = m.cpu_percent || 0;
const ram = m.ram_percent || 0;
const temp = m.temperature || 0;
const cpuClass = cpu > 90 ? 'crit' : cpu > 70 ? 'warn' : '';
const ramClass = ram > 90 ? 'crit' : ram > 70 ? 'warn' : '';
const tempClass = temp > 60 ? 'crit' : temp > 50 ? 'warn' : '';
const vmsCount = (m.vms || []).length;
const dockerCount = (m.docker || []).length;
const volsHtml = (m.volumes || []).map(v => {
const vc = v.percent > 90 ? 'crit' : v.percent > 70 ? 'warn' : '';
return `
${isOnline ? `
${m.dsm_version ? `
${m.dsm_version} • ${m.uptime || ''}
` : ''}
${vmsCount ? `
🖥 ${vmsCount} VM
` : ''}
${dockerCount ? `
🐳 ${dockerCount} контейнеров
` : ''}
${volsHtml}
` : '
Нет данных — нажмите 🔄
'}
🔄 Обновить
🗑
`;
}).join('');
}
function showSynologyDetail(name) {
const dev = synologyDevices.find(d => d.name === name);
if (!dev || !dev.metrics) return;
const m = dev.metrics;
const modal = document.getElementById('synDetailModal');
document.getElementById('syn-detail-title').textContent = `📦 ${name}`;
let html = ``;
// System
html += `
💻 Система
Модель: ${m.model || 'N/A'} ${m.dsm_version || ''} Uptime: ${m.uptime || 'N/A'}
Температура: ${m.temperature || 0}°C CPU: ${m.cpu_percent || 0}% | RAM: ${m.ram_percent || 0}% (${m.ram_used_mb || 0}/${m.ram_total_mb || 0} MB)
`;
// Volumes
if (m.volumes?.length) {
html += `
💾 Тома `;
m.volumes.forEach(v => {
const vc = v.percent > 90 ? 'crit' : v.percent > 70 ? 'warn' : 'ok';
html += `
${v.name} — ${v.used_gb}/${v.total_gb} GB (${v.percent}%) ${v.status ? '• ' + v.status : ''}
`;
});
html += `
`;
}
// Disks
if (m.disks?.length) {
html += `
🔩 Диски `;
m.disks.forEach(d => {
html += `
${d.name} — ${d.model || ''} (${d.size_gb} GB) 🌡${d.temp}°C ${d.smart_status ? '• SMART: ' + d.smart_status : ''} ${d.status || ''}
`;
});
html += `
`;
}
// VMs
if (m.vms?.length) {
html += `
🖥 Виртуальные машины `;
m.vms.forEach(vm => {
const st = vm.status === 'running' ? '🟢' : '🔴';
html += `
${st} ${vm.name} — ${vm.vcpu} vCPU, ${vm.ram_mb} MB RAM ${vm.autorun ? '• AutoStart' : ''}
`;
});
html += `
`;
}
// Docker
if (m.docker?.length) {
html += `
🐳 Docker контейнеры `;
m.docker.forEach(c => {
const st = c.state === 'running' ? '🟢' : '🔴';
html += `
${st} ${c.name} — ${c.image || ''}
`;
});
html += `
`;
}
html += `
`;
document.getElementById('syn-detail-content').innerHTML = html;
modal.style.display = 'flex';
}
function showAddSynology() {
document.getElementById('addSynologyModal').style.display = 'flex';
}
document.getElementById('addSynologyForm')?.addEventListener('submit', async (e) => {
e.preventDefault();
const form = e.target;
const data = {
name: form.name.value,
host: form.host.value,
port: parseInt(form.port.value) || 5000,
https: form.querySelector('[name=https]').checked,
username: form.username.value,
password: form.password.value,
};
try {
const resp = await fetch('/api/synology/add', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
credentials: 'include',
body: JSON.stringify(data),
});
if (resp.ok) {
closeModal('addSynologyModal');
form.reset();
loadSynology();
}
} catch (e) { alert('Error: ' + e.message); }
});
async function refreshSynology(name) {
try {
await fetch(`/api/synology/refresh/${encodeURIComponent(name)}`, {method: 'POST', credentials: 'include'});
loadSynology();
} catch (e) { alert('Error: ' + e.message); }
}
async function refreshAllSynology() {
try {
await fetch('/api/synology/refresh-all', {method: 'POST', credentials: 'include'});
loadSynology();
} catch (e) { alert('Error: ' + e.message); }
}
async function deleteSynology(name) {
if (!confirm(`Удалить Synology "${name}"?`)) return;
await fetch(`/api/synology/${encodeURIComponent(name)}`, {method: 'DELETE', credentials: 'include'});
loadSynology();
}
// ===================== HOME ASSISTANT =====================
let haInstances = [];
async function loadHA() {
try {
const resp = await fetch('/api/ha/list', {credentials: 'include'});
if (resp.status === 401) return;
haInstances = await resp.json();
renderHA();
} catch (e) { console.error('HA load error:', e); }
}
function renderHA() {
const grid = document.getElementById('ha-grid');
if (!haInstances.length) {
grid.innerHTML = 'Нет Home Assistant. Нажмите "+ Добавить HA".
';
return;
}
grid.innerHTML = haInstances.map(inst => {
const m = inst.metrics || {};
const isOnline = m.online;
const temps = (m.sensors?.temperature || []).filter(s => s.value !== null).slice(0, 4);
const humidity = (m.sensors?.humidity || []).filter(s => s.value !== null).slice(0, 4);
const doors = m.sensors?.door || [];
const motion = m.sensors?.motion || [];
const battery = (m.sensors?.battery || []).filter(s => s.value !== null && s.value < 20);
const problems = (m.problem_entities || []).length;
const updates = (m.updates_available || []).length;
const persons = m.persons || [];
return `
${isOnline ? `
📡 ${m.entities_count || 0} сущностей
${persons.length ? `
👤 ${persons.map(p => `${p.name}: ${p.state === 'home' ? '🏠' : '🚗'}`).join(', ')}
` : ''}
${temps.length ? `
🌡 ${temps.map(s => s.name.substring(0, 15) + ': ' + s.value + s.unit).join(' | ')}
` : ''}
${humidity.length ? `
💧 ${humidity.map(s => s.name.substring(0, 15) + ': ' + s.value + '%').join(' | ')}
` : ''}
${doors.length ? `
🚪 ${doors.filter(d => d.state === 'on').length ? '' + doors.filter(d => d.state === 'on').length + ' открыто ' : 'все закрыты ✅'}
` : ''}
${motion.length ? `
🏃 ${motion.filter(m => m.state === 'on').length ? 'движение! ' : 'нет движения'}
` : ''}
${battery.length ? `
🔋 ${battery.length} устройств с низким зарядом
` : ''}
${problems ? `
⚠️ ${problems} проблемных сущностей
` : ''}
${updates ? `
📦 ${updates} обновлений
` : ''}
` : '
Нет данных — нажмите 🔄
'}
🔄 Обновить
🗑
`;
}).join('');
}
function showHADetail(name) {
const inst = haInstances.find(i => i.name === name);
if (!inst || !inst.metrics) return;
const m = inst.metrics;
const modal = document.getElementById('haDetailModal');
document.getElementById('ha-detail-title').textContent = `🏠 ${name}`;
let html = ``;
// System
html += `
🔧 Система
Версия: ${m.version || 'N/A'} Локация: ${m.location_name || 'N/A'}
Компоненты: ${m.components_count || 0} Сущности: ${m.entities_count || 0}
`;
// Temperatures
const temps = m.sensors?.temperature || [];
if (temps.length) {
html += `
🌡️ Температура `;
temps.forEach(s => {
if (s.value === null) return;
const cls = s.value > 30 ? 'style="color:var(--danger)"' : s.value < 10 ? 'style="color:var(--accent)"' : '';
html += `
${s.name}: ${s.value}${s.unit}
`;
});
html += `
`;
}
// Humidity
const humid = m.sensors?.humidity || [];
if (humid.length) {
html += `
💧 Влажность `;
humid.forEach(s => { if (s.value !== null) html += `
${s.name}: ${s.value}%
`; });
html += `
`;
}
// Doors/Windows
const doors = m.sensors?.door || [];
if (doors.length) {
html += `
🚪 Двери / Окна `;
doors.forEach(d => {
const icon = d.state === 'on' ? '🔓 Открыто' : '🔒 Закрыто';
const cls = d.state === 'on' ? 'style="color:var(--warning)"' : '';
html += `
${d.name}: ${icon}
`;
});
html += `
`;
}
// Motion
const motion = m.sensors?.motion || [];
if (motion.length) {
html += `
🏃 Движение `;
motion.forEach(s => {
const cls = s.state === 'on' ? 'style="color:var(--warning)"' : '';
html += `
${s.name}: ${s.state === 'on' ? '⚡ Обнаружено' : '—'}
`;
});
html += `
`;
}
// Battery
const battery = m.sensors?.battery || [];
if (battery.length) {
html += `
🔋 Батареи `;
battery.forEach(b => {
if (b.value === null) return;
const cls = b.value < 20 ? 'crit' : b.value < 50 ? 'warn' : '';
html += `
${b.value}% ${b.name}
`;
});
html += `
`;
}
// Climate
if (m.climate?.length) {
html += `
🌡 Климат `;
m.climate.forEach(c => {
html += `
${c.name}: ${c.state} (${c.current_temp || '?'}° → ${c.target_temp || '?'}°) ${c.hvac_action}
`;
});
html += `
`;
}
// Persons
if (m.persons?.length) {
html += `
👤 Люди `;
m.persons.forEach(p => {
const icon = p.state === 'home' ? '🏠 Дома' : '🚗 Не дома';
html += `
${p.name}: ${icon}
`;
});
html += `
`;
}
// Automations
if (m.automations?.length) {
html += `
⚙️ Автоматизации (${m.automations.length}) `;
m.automations.slice(0, 20).forEach(a => {
const st = a.state === 'on' ? '🟢' : '🔴';
html += `
${st} ${a.name}
`;
});
html += `
`;
}
// Updates
if (m.updates_available?.length) {
html += `
📦 Доступные обновления `;
m.updates_available.forEach(u => {
html += `
${u.name}: ${u.installed} → ${u.latest}
`;
});
html += `
`;
}
// Problems
if (m.problem_entities?.length) {
html += `
⚠️ Проблемные сущности `;
m.problem_entities.slice(0, 20).forEach(p => {
html += `
${p.entity_id}: ${p.state}
`;
});
html += `
`;
}
html += `
`;
document.getElementById('ha-detail-content').innerHTML = html;
modal.style.display = 'flex';
}
function showAddHA() {
document.getElementById('addHAModal').style.display = 'flex';
}
document.getElementById('addHAForm')?.addEventListener('submit', async (e) => {
e.preventDefault();
const form = e.target;
const data = {
name: form.name.value,
url: form.url.value,
token: form.token.value,
};
try {
const resp = await fetch('/api/ha/add', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
credentials: 'include',
body: JSON.stringify(data),
});
if (resp.ok) {
closeModal('addHAModal');
form.reset();
loadHA();
}
} catch (e) { alert('Error: ' + e.message); }
});
async function refreshHA(name) {
try {
await fetch(`/api/ha/refresh/${encodeURIComponent(name)}`, {method: 'POST', credentials: 'include'});
loadHA();
} catch (e) { alert('Error: ' + e.message); }
}
async function refreshAllHA() {
try {
await fetch('/api/ha/refresh-all', {method: 'POST', credentials: 'include'});
loadHA();
} catch (e) { alert('Error: ' + e.message); }
}
async function deleteHA(name) {
if (!confirm(`Удалить Home Assistant "${name}"?`)) return;
await fetch(`/api/ha/${encodeURIComponent(name)}`, {method: 'DELETE', credentials: 'include'});
loadHA();
}
// ===================== NOTIFICATIONS =====================
async function showNotificationSettings() {
try {
const resp = await fetch('/api/notifications/settings', {credentials: 'include'});
const data = await resp.json();
const n = data.notifications || {};
// Set checkboxes
['servers', 'pc', 'synology', 'ha'].forEach(cat => {
const prefs = n[cat] || {};
const tgEl = document.getElementById(`n-${cat}-tg`);
const emEl = document.getElementById(`n-${cat}-email`);
const waEl = document.getElementById(`n-${cat}-wa`);
if (tgEl) tgEl.checked = prefs.telegram !== false;
if (emEl) emEl.checked = !!prefs.email;
if (waEl) waEl.checked = !!prefs.whatsapp;
});
// Email fields
document.getElementById('n-smtp-host').value = data.email?.smtp_host || '';
document.getElementById('n-smtp-port').value = data.email?.smtp_port || 587;
document.getElementById('n-smtp-user').value = data.email?.smtp_user || '';
document.getElementById('n-email-to').value = data.email?.email_to || '';
// WhatsApp
document.getElementById('n-wa-phone').value = data.whatsapp?.phone || '';
// Status indicators
document.getElementById('tg-status').innerHTML = data.telegram?.configured
? '