Use Home Assistant notifications

This commit is contained in:
seo
2026-06-21 07:30:39 +09:00
parent 81a24530d6
commit 49394a8ee5
15 changed files with 234 additions and 2371 deletions
-202
View File
@@ -34,9 +34,6 @@
statusBatteryRemaining: $('#statusBatteryRemaining'),
spikeLogList: $('#spikeLogList'),
noticeBaseline: $('#noticeBaseline'),
pushStatus: $('#pushStatus'),
pushDeviceList: $('#pushDeviceList'),
pushHealthcheckBtn: $('#pushHealthcheckBtn'),
rebootBtn: $('#rebootBtn'),
translateBtn: $('#translateBtn'),
themeBtn: $('#themeBtn'),
@@ -70,7 +67,6 @@
wsFallbackTimer: null,
wsReconnectTimer: null,
wsReconnectDelay: 1000,
pushDevicesLastRefresh: 0,
rebootRequesting: false,
lang: 'en',
theme: 'dark',
@@ -141,10 +137,6 @@
systemNotice: 'System Notice',
noticeHistory: 'Notice History',
noNoticeHistory: 'No system notice history.',
pushDevices: 'Push Devices',
healthCheck: 'Health Check',
pushStatusChecking: 'Push status checking...',
noPushDevices: 'No push devices.',
show: 'Show',
hide: 'Hide',
translateButton: 'Translate',
@@ -179,34 +171,8 @@
avg: 'AVG',
min: 'MIN',
minuteAgo: ({ minutes }) => `${minutes}m ago`,
health_healthy: 'Healthy',
health_watch: 'Watch',
health_stale: 'Stale',
health_failed: 'Failed',
health_pending: 'Pending',
pushSummary: ({ total, healthy, watch, stale, failed, pending }) => `Push devices: ${total} total / ${healthy} healthy / ${watch} watch / ${stale} stale / ${failed} failed / ${pending} pending`,
statusUnsupported: 'Push status: browser unsupported',
statusDenied: 'Push status: permission denied',
statusUngrant: 'Push status: permission not granted',
statusManualOff: 'Push status: manually disabled',
browserHas: 'browser registered',
browserMissing: 'browser missing',
serverHas: 'server registered',
serverMissing: 'server missing',
serverPending: 'server not checked',
pushStatus: 'Push status',
registeredRefresh: 'Registered refresh',
lastSendSuccess: 'Last send success',
lastReceived: 'Last received',
lastShown: 'Last shown',
lastClick: 'Last click',
failures: 'Failures',
unknownDevice: 'unknown device',
unnamed: 'Unnamed',
pendingReceive: 'Pending receive',
ago: 'ago',
healthSent: ({ sent, failed }) => `Health check sent ${sent} / failed ${failed}`,
healthFailed: 'Health check failed',
refreshFailed: 'refresh failed',
applyingFan: 'Applying fan policy...',
fanUpdated: 'Fan updated',
@@ -225,16 +191,7 @@
rebootStarted: 'Reboot Started',
rebootStartedBody: 'Reboot command sent. The connection may drop shortly.',
rebootFailed: 'Reboot Failed',
pushDeviceNamePrompt: 'Enter a device name. Korean names require at least 2 Hangul characters.',
pushRegisterTitle: 'Push Register',
register: 'Register',
phone: 'Phone',
pushDeviceNameInvalid: 'Device name must contain at least 2 Hangul characters.',
autoRepair: 'Auto Repair',
pushDeletePrompt: 'Delete this browser Push subscription?',
pushDeleteTitle: 'Delete Push',
delete: 'Delete',
pushErrorTitle: 'Push Error',
wakeLockTitle: 'Prevent screen sleep',
wakeLockUnsupported: 'WakeLock is not supported by this browser.',
wakeLockErrorTitle: 'WakeLock Error',
@@ -298,10 +255,6 @@
systemNotice: '시스템 알림',
noticeHistory: '알림 이력',
noNoticeHistory: '시스템 알림 이력이 없습니다.',
pushDevices: 'Push 기기',
healthCheck: '상태 점검',
pushStatusChecking: 'Push 상태 확인 중...',
noPushDevices: 'Push 기기가 없습니다.',
show: '보기',
hide: '숨기기',
translateButton: '번역',
@@ -336,34 +289,8 @@
avg: '평균',
min: '최소',
minuteAgo: ({ minutes }) => `${minutes}분 전`,
health_healthy: '정상',
health_watch: '주의',
health_stale: '장기 미수신',
health_failed: '실패',
health_pending: '수신 대기',
pushSummary: ({ total, healthy, watch, stale, failed, pending }) => `Push 기기: 총 ${total} / 정상 ${healthy} / 주의 ${watch} / 장기 미수신 ${stale} / 실패 ${failed} / 대기 ${pending}`,
statusUnsupported: 'Push 상태: 브라우저 미지원',
statusDenied: 'Push 상태: 권한 꺼짐',
statusUngrant: 'Push 상태: 권한 미허용',
statusManualOff: 'Push 상태: 사용자가 직접 해제함',
browserHas: '브라우저에는 있음',
browserMissing: '브라우저에는 없음',
serverHas: '서버에는 있음',
serverMissing: '서버에는 없음',
serverPending: '서버 확인 전',
pushStatus: 'Push 상태',
registeredRefresh: '등록 갱신',
lastSendSuccess: '마지막 발송 성공',
lastReceived: '마지막 수신',
lastShown: '마지막 표시',
lastClick: '마지막 클릭',
failures: '실패',
unknownDevice: '알 수 없는 기기',
unnamed: '이름 없음',
pendingReceive: '수신 대기',
ago: '전',
healthSent: ({ sent, failed }) => `상태 점검 발송 ${sent} / 실패 ${failed}`,
healthFailed: '상태 점검 실패',
refreshFailed: '갱신 실패',
applyingFan: '팬 정책 적용 중...',
fanUpdated: '팬 갱신 완료',
@@ -382,16 +309,7 @@
rebootStarted: '재부팅 시작',
rebootStartedBody: '재부팅 명령을 전송했습니다. 잠시 후 연결이 끊어질 수 있습니다.',
rebootFailed: '재부팅 실패',
pushDeviceNamePrompt: '등록할 기기 이름을 입력하세요. 한글 2글자 이상이어야 합니다.',
pushRegisterTitle: 'Push 등록',
register: '등록',
phone: '휴대폰',
pushDeviceNameInvalid: '기기 이름은 한글 2글자 이상이어야 합니다.',
autoRepair: '자동복구',
pushDeletePrompt: '현재 브라우저의 Push 구독을 삭제할까요?',
pushDeleteTitle: 'Push 삭제',
delete: '삭제',
pushErrorTitle: 'Push 오류',
wakeLockTitle: '화면 꺼짐 방지',
wakeLockUnsupported: '현재 브라우저에서 WakeLock을 지원하지 않습니다.',
wakeLockErrorTitle: 'WakeLock 오류',
@@ -408,11 +326,6 @@
}
window.controlT = t;
function pushHealthText(status, fallback = '') {
const key = `health_${status || 'pending'}`;
return messages[state.lang]?.[key] ?? messages.en[key] ?? fallback ?? t('pendingReceive');
}
function applyTheme(theme) {
state.theme = theme === 'light' ? 'light' : 'dark';
localStorage.setItem(storageKeys.theme, state.theme);
@@ -1084,119 +997,6 @@
: `<div class="spike-log-empty">${escapeHtml(t('noNoticeHistory'))}</div>`;
}
function renderPushDevices(devices = [], summary = null) {
if (!els.pushDeviceList) return;
if (summary && els.pushStatus) {
const total = Number(summary.total || 0);
const healthy = Number(summary.healthy || 0);
const watch = Number(summary.watch || 0);
const stale = Number(summary.stale || 0);
const failed = Number(summary.failed || 0);
const pending = Number(summary.pending || 0);
els.pushStatus.textContent = t('pushSummary', { total, healthy, watch, stale, failed, pending });
}
els.pushDeviceList.innerHTML = devices.length
? devices.map(device => {
const healthStatus = device.health_status || 'pending';
const healthText = pushHealthText(healthStatus, device.health_text);
return `
<div class="push-device-row ${escapeHtml(healthStatus)}">
<div class="push-device-main">
<strong>${escapeHtml(device.device_name || t('unnamed'))}</strong>
<span class="push-device-badge ${escapeHtml(healthStatus)}">${escapeHtml(healthText)}</span>
<span>${escapeHtml(t('hostLabel'))}: ${escapeHtml(device.host || 'unknown')}</span>
<span>${escapeHtml(t('ipLabel'))}: ${escapeHtml(device.actor_ip || '-')}</span>
<span>${escapeHtml(t('created'))}: ${escapeHtml(device.created_at || '-')}</span>
<span>${escapeHtml(t('registeredRefresh'))}: ${escapeHtml(device.last_seen_at || '-')} (${escapeHtml(timeAgo(device.last_seen_seconds))})</span>
<span>${escapeHtml(t('lastSendSuccess'))}: ${escapeHtml(device.last_send_success_at || '-')} (${escapeHtml(timeAgo(device.last_send_success_seconds))})</span>
<span>${escapeHtml(t('lastReceived'))}: ${escapeHtml(device.last_received_at || '-')} (${escapeHtml(timeAgo(device.last_received_seconds))})</span>
<span>${escapeHtml(t('lastShown'))}: ${escapeHtml(device.last_notification_at || '-')} (${escapeHtml(timeAgo(device.last_notification_seconds))})</span>
<span>${escapeHtml(t('lastClick'))}: ${escapeHtml(device.last_click_at || '-')}</span>
<span>${escapeHtml(t('failures'))}: ${Number(device.failure_count || 0).toLocaleString()}${device.last_failure_reason ? ` / ${escapeHtml(device.last_failure_reason)}` : ''}</span>
<span>${escapeHtml(t('encoding'))}: ${escapeHtml(device.content_encoding || '-')}</span>
<span>${escapeHtml(t('hash'))}: ${escapeHtml(device.hash || '-')}</span>
<span>${escapeHtml(t('endpoint'))}: ${escapeHtml(device.endpoint || '-')}</span>
<span>${escapeHtml(t('userAgent'))}: ${escapeHtml(device.user_agent || t('unknownDevice'))}</span>
</div>
</div>
`;
}).join('')
: `<div class="spike-log-empty">${escapeHtml(t('noPushDevices'))}</div>`;
}
function renderPushStatus(detail = {}) {
if (!els.pushStatus) return;
const supported = detail.supported === true;
const permission = detail.permission || 'unknown';
const hasBrowserSubscription = detail.browser_subscription === true;
const hasServerSubscription = detail.server_subscription === true;
const manualDisabled = detail.manual_disabled === true;
const serverChecked = detail.server_checked === true;
let text = '';
if (!supported) {
text = t('statusUnsupported');
} else if (permission === 'denied') {
text = t('statusDenied');
} else if (permission !== 'granted') {
text = t('statusUngrant');
} else if (manualDisabled) {
text = t('statusManualOff');
} else {
const browserText = hasBrowserSubscription ? t('browserHas') : t('browserMissing');
const serverText = serverChecked
? (hasServerSubscription ? t('serverHas') : t('serverMissing'))
: t('serverPending');
text = `${t('pushStatus')}: ${browserText} / ${serverText}`;
}
els.pushStatus.textContent = text;
}
async function refreshPushDevices(force = false) {
if (!force && Date.now() - state.pushDevicesLastRefresh < 30000) {
return;
}
state.pushDevicesLastRefresh = Date.now();
try {
const data = await api('push_devices');
renderPushDevices(data.devices || [], data.summary || null);
} catch (e) {
console.error(e);
}
}
async function sendPushHealthcheck() {
if (!els.pushHealthcheckBtn) return;
els.pushHealthcheckBtn.disabled = true;
try {
const data = await api('send_push_healthcheck', {});
renderPushDevices(data.devices || [], data.summary || null);
const result = data.result || {};
notice(t('healthSent', { sent: Number(result.sent || 0), failed: Number(result.failed || 0) }), result.failed ? 'error' : 'success');
} catch (e) {
notice(e.message || t('healthFailed'), 'error');
} finally {
els.pushHealthcheckBtn.disabled = false;
}
}
window.addEventListener('pushdevices:refresh', () => {
refreshPushDevices(true);
});
window.addEventListener('pushstatus:update', event => {
renderPushStatus(event.detail || {});
});
els.pushHealthcheckBtn?.addEventListener('click', sendPushHealthcheck);
function renderFanCause(data) {
const processes = data.processes || {};
const baseline = data.fan_spike || {};
@@ -1211,7 +1011,6 @@
renderProcessRows(els.processCpuTable, processes.cpu || [], 'cpu');
renderProcessRows(els.processMemoryTable, processes.memory || [], 'memory');
refreshPushDevices();
}
function rollingStats(values, windowSize = 30) {
@@ -1736,7 +1535,6 @@
});
els.translateBtn?.addEventListener('click', () => {
applyLang(state.lang === 'ko' ? 'en' : 'ko');
refreshPushDevices(true);
refreshStatus();
});
els.themeBtn?.addEventListener('click', () => {