serverdeck 1.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,819 @@
1
+ (function () {
2
+ 'use strict';
3
+
4
+ var REFRESH_MS = __REFRESH_MS__;
5
+
6
+ // ---------- DOM 辅助 ----------
7
+ function h(tag, attrs) {
8
+ var node = document.createElement(tag);
9
+ if (attrs) {
10
+ Object.keys(attrs).forEach(function (key) {
11
+ var val = attrs[key];
12
+ if (val === null || val === undefined || val === false) return;
13
+ if (key === 'class') node.className = val;
14
+ else if (key === 'text') node.textContent = val;
15
+ else if (key === 'style') node.setAttribute('style', val);
16
+ else if (key.indexOf('on') === 0 && typeof val === 'function') {
17
+ node.addEventListener(key.slice(2).toLowerCase(), val);
18
+ } else {
19
+ node.setAttribute(key, val);
20
+ }
21
+ });
22
+ }
23
+ for (var i = 2; i < arguments.length; i++) append(node, arguments[i]);
24
+ return node;
25
+ }
26
+ function append(node, child) {
27
+ if (child === null || child === undefined || child === false) return;
28
+ if (Array.isArray(child)) { child.forEach(function (c) { append(node, c); }); return; }
29
+ node.append(child instanceof Node ? child : document.createTextNode(String(child)));
30
+ }
31
+ function setText(id, text) {
32
+ var node = document.getElementById(id);
33
+ if (node) node.textContent = text;
34
+ }
35
+ function svgEl(tag, attrs) {
36
+ var node = document.createElementNS('http://www.w3.org/2000/svg', tag);
37
+ Object.keys(attrs || {}).forEach(function (k) { node.setAttribute(k, attrs[k]); });
38
+ return node;
39
+ }
40
+
41
+ // ---------- 格式化 ----------
42
+ function pad(n) { return String(n).padStart(2, '0'); }
43
+ function fmtTime(epoch) {
44
+ if (!epoch) return '—';
45
+ var d = new Date(epoch * 1000);
46
+ return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()) +
47
+ ' ' + pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds());
48
+ }
49
+ function duration(sec) {
50
+ sec = Math.floor(Math.abs(sec));
51
+ if (sec < 60) return sec + ' 秒';
52
+ var m = Math.floor(sec / 60);
53
+ if (m < 60) return m + ' 分钟';
54
+ var hr = Math.floor(m / 60);
55
+ if (hr < 48) return hr + ' 小时';
56
+ return Math.floor(hr / 24) + ' 天';
57
+ }
58
+ function relTime(epoch) {
59
+ if (!epoch) return '—';
60
+ var diff = epoch - Date.now() / 1000;
61
+ return diff >= 0 ? duration(diff) + '后' : duration(-diff) + '前';
62
+ }
63
+ function fmtUptime(sec) {
64
+ if (sec === null || sec === undefined) return '—';
65
+ var d = Math.floor(sec / 86400);
66
+ var hr = Math.floor((sec % 86400) / 3600);
67
+ var m = Math.floor((sec % 3600) / 60);
68
+ var out = [];
69
+ if (d) out.push(d + ' 天');
70
+ if (hr || d) out.push(hr + ' 小时');
71
+ out.push(m + ' 分');
72
+ return out.join(' ');
73
+ }
74
+ function bytes(n) {
75
+ if (n === null || n === undefined || isNaN(n)) return '—';
76
+ n = Number(n);
77
+ var units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'];
78
+ var i = 0;
79
+ while (n >= 1024 && i < units.length - 1) { n /= 1024; i++; }
80
+ var digits = i === 0 ? 0 : (n >= 100 ? 0 : (n >= 10 ? 1 : 2));
81
+ return n.toFixed(digits) + ' ' + units[i];
82
+ }
83
+ function num(v, digits) {
84
+ if (v === null || v === undefined || isNaN(v)) return '—';
85
+ return Number(v).toFixed(digits === undefined ? 1 : digits);
86
+ }
87
+ function pctColor(p, warn, bad) {
88
+ if (p === null || p === undefined) return 'var(--faint)';
89
+ if (p >= (bad === undefined ? 90 : bad)) return 'var(--bad)';
90
+ if (p >= (warn === undefined ? 75 : warn)) return 'var(--warn)';
91
+ return 'var(--accent)';
92
+ }
93
+ function noteFor(ts) {
94
+ if (!ts) return '';
95
+ return relTime(ts) + '更新';
96
+ }
97
+
98
+ // ---------- 历史与 sparkline ----------
99
+ var history = { cpu: [], mem: [] };
100
+ function pushHistory(key, value, cap) {
101
+ if (typeof value !== 'number' || !isFinite(value)) return;
102
+ var arr = history[key];
103
+ arr.push(Math.max(0, Math.min(100, value)));
104
+ while (arr.length > (cap || 60)) arr.shift();
105
+ }
106
+ function sparkline(values, color, max) {
107
+ var w = 260, hh = 46, pad = 3;
108
+ var svg = svgEl('svg', { viewBox: '0 0 ' + w + ' ' + hh, preserveAspectRatio: 'none', class: 'spark-svg' });
109
+ if (!values.length) return svg;
110
+ var top = max || Math.min(100, Math.max(10, Math.max.apply(null, values) * 1.25));
111
+ var points = values.map(function (v, i) {
112
+ var x = values.length === 1 ? w / 2 : pad + (i / (values.length - 1)) * (w - pad * 2);
113
+ var y = hh - pad - (Math.min(v, top) / top) * (hh - pad * 2);
114
+ return [x, y];
115
+ });
116
+ var line = points.map(function (p) { return p[0].toFixed(1) + ',' + p[1].toFixed(1); }).join(' ');
117
+ var area = svgEl('polygon', {
118
+ points: points[0][0].toFixed(1) + ',' + (hh - pad) + ' ' + line + ' ' +
119
+ points[points.length - 1][0].toFixed(1) + ',' + (hh - pad),
120
+ fill: color, opacity: '0.12'
121
+ });
122
+ var poly = svgEl('polyline', {
123
+ points: line, fill: 'none', stroke: color, 'stroke-width': '1.5',
124
+ 'vector-effect': 'non-scaling-stroke', 'stroke-linejoin': 'round'
125
+ });
126
+ svg.append(area, poly);
127
+ return svg;
128
+ }
129
+
130
+ // ---------- 渲染:系统 / CPU / 内存 ----------
131
+ function kvRow(key, value, title) {
132
+ return h('div', { class: 'kv-row' },
133
+ h('span', { class: 'kv-key', text: key }),
134
+ h('span', { class: 'kv-val', title: title || String(value), text: value === null || value === undefined || value === '' ? '—' : value })
135
+ );
136
+ }
137
+
138
+ function renderSystem(data) {
139
+ var s = data.system || {};
140
+ setText('sys-note', noteFor(s.updated_at));
141
+ var host = document.getElementById('hostname');
142
+ if (host && s.hostname) host.textContent = s.hostname + (s.os ? ' · ' + s.os : '');
143
+ document.title = (s.hostname ? s.hostname + ' · ' : '') + '服务器状态';
144
+
145
+ var body = document.getElementById('sys-body');
146
+ var load = (s.load || []).map(function (v) { return v.toFixed(2); }).join(' ');
147
+ var procs = s.processes ? s.processes.running + ' 运行 / ' + s.processes.total + ' 总计' : '—';
148
+ body.replaceChildren(
149
+ kvRow('主机名', s.hostname || '—'),
150
+ kvRow('系统', s.os || '—'),
151
+ kvRow('内核', (s.kernel || '—') + (s.arch ? ' · ' + s.arch : '')),
152
+ kvRow('运行时间', fmtUptime(s.uptime_seconds)),
153
+ kvRow('负载 (1/5/15)', load || '—'),
154
+ kvRow('进程', procs),
155
+ kvRow('处理器', (s.cpu_model || '—') + (s.cpu_cores ? ' · ' + s.cpu_cores + ' 核' : ''),
156
+ s.cpu_model || '')
157
+ );
158
+ }
159
+
160
+ function renderCpu(data) {
161
+ var c = data.cpu || {};
162
+ var usage = typeof c.usage === 'number' ? c.usage : null;
163
+ pushHistory('cpu', usage === null ? NaN : usage);
164
+ setText('cpu-note', noteFor(c.updated_at));
165
+ setText('cpu-pct', usage === null ? '—' : num(usage, 1));
166
+ var color = pctColor(usage, 80, 92);
167
+ var bar = document.getElementById('cpu-bar');
168
+ bar.style.width = (usage || 0) + '%';
169
+ bar.style.background = color;
170
+
171
+ var spark = document.getElementById('cpu-spark');
172
+ spark.replaceChildren(sparkline(history.cpu, 'var(--accent)'));
173
+
174
+ var cores = document.getElementById('cpu-cores');
175
+ var values = (c.per_core || []).slice(0, 32);
176
+ cores.replaceChildren.apply(cores, values.map(function (v, idx) {
177
+ return h('div', { class: 'core', title: 'cpu' + idx + ' ' + num(v, 0) + '%' },
178
+ h('i', { style: 'height:' + Math.max(2, Math.min(100, v)) + '%;background:' + pctColor(v, 80, 92) + ';' })
179
+ );
180
+ }));
181
+
182
+ var meta = document.getElementById('cpu-meta');
183
+ meta.replaceChildren(
184
+ kvRow('核心数', (c.cores || (c.per_core || []).length || '—').toString()),
185
+ kvRow('平均频率', c.mhz ? Math.round(c.mhz) + ' MHz' : '—')
186
+ );
187
+ }
188
+
189
+ function renderMemory(data) {
190
+ var m = data.memory || {};
191
+ var p = typeof m.percent === 'number' ? m.percent : null;
192
+ pushHistory('mem', p === null ? NaN : p);
193
+ setText('mem-note', noteFor(m.updated_at));
194
+ setText('mem-pct', p === null ? '—' : num(p, 1));
195
+ var color = pctColor(p, 80, 92);
196
+ var bar = document.getElementById('mem-bar');
197
+ bar.style.width = (p || 0) + '%';
198
+ bar.style.background = color;
199
+
200
+ var spark = document.getElementById('mem-spark');
201
+ spark.replaceChildren(sparkline(history.mem, 'var(--info)'));
202
+
203
+ var swap = m.swap_total ? bytes(m.swap_used) + ' / ' + bytes(m.swap_total) : '未启用';
204
+ document.getElementById('mem-body').replaceChildren(
205
+ kvRow('已用', bytes(m.used) + ' / ' + bytes(m.total)),
206
+ kvRow('可用', bytes(m.available)),
207
+ kvRow('缓存', bytes(m.cached)),
208
+ kvRow('交换', swap)
209
+ );
210
+ }
211
+
212
+ // ---------- 渲染:磁盘 ----------
213
+ function renderDisks(data) {
214
+ var d = data.disks || {};
215
+ setText('disk-note', noteFor(d.updated_at));
216
+ var body = document.getElementById('disk-body');
217
+ var items = d.items || [];
218
+ if (!items.length) {
219
+ body.replaceChildren(
220
+ d.error ? h('div', { class: 'error-text', text: d.error }) : h('div', { class: 'empty', text: '没有可显示的文件系统' })
221
+ );
222
+ return;
223
+ }
224
+ body.replaceChildren.apply(body, items.map(function (item) {
225
+ var color = pctColor(item.percent, 75, 90);
226
+ return h('div', { class: 'disk-row' },
227
+ h('div', { class: 'row-top' },
228
+ h('span', { class: 'mono trunc', title: item.mount, text: item.mount }),
229
+ h('span', { class: 'muted tiny grow trunc', title: item.filesystem, text: item.type + ' · ' + bytes(item.used) + ' / ' + bytes(item.size) + ' · 可用 ' + bytes(item.available) }),
230
+ h('span', { class: 'pct', style: 'color:' + color, text: num(item.percent, 0) + '%' })
231
+ ),
232
+ h('div', { class: 'meter thin' }, h('div', { class: 'meter-fill', style: 'width:' + Math.min(100, item.percent) + '%;background:' + color }))
233
+ );
234
+ }));
235
+ if (d.error) {
236
+ body.append(h('div', { class: 'error-text', text: d.error }));
237
+ }
238
+ }
239
+
240
+ // ---------- 渲染:网络 ----------
241
+ function renderNetwork(data) {
242
+ var net = data.network || {};
243
+ setText('net-iface-note', noteFor(net.updated_at));
244
+ setText('net-note', net.updated_at_slow ? '监听 ' + noteFor(net.updated_at_slow) : '');
245
+ var ifaceBox = document.getElementById('net-ifaces');
246
+ var ifaces = (net.interfaces || []).slice().sort(function (a, b) {
247
+ if ((a.name === 'lo') !== (b.name === 'lo')) return a.name === 'lo' ? 1 : -1;
248
+ return (b.rx_rate + b.tx_rate) - (a.rx_rate + a.tx_rate);
249
+ });
250
+ if (!ifaces.length) {
251
+ ifaceBox.replaceChildren(h('div', { class: 'empty', text: '暂无接口数据' }));
252
+ } else {
253
+ ifaceBox.replaceChildren.apply(ifaceBox, ifaces.map(function (i) {
254
+ return h('div', { class: 'iface' },
255
+ h('div', { class: 'iface-head' },
256
+ h('span', { class: 'mono', text: i.name }),
257
+ h('span', { class: 'muted tiny trunc', title: (i.addresses || []).join(', '), text: (i.addresses || []).join(', ') || '无地址' })
258
+ ),
259
+ h('div', { class: 'iface-rates' },
260
+ h('span', {}, '↓ ', h('span', { class: 'mono', text: bytes(i.rx_rate) + '/s' })),
261
+ h('span', {}, '↑ ', h('span', { class: 'mono', text: bytes(i.tx_rate) + '/s' })),
262
+ h('span', { class: 'tiny', text: '累计 ↓ ' + bytes(i.rx_bytes) + ' ↑ ' + bytes(i.tx_bytes) })
263
+ )
264
+ );
265
+ }));
266
+ }
267
+
268
+ var states = Object.keys(net.tcp_states || {}).map(function (k) {
269
+ return [k, net.tcp_states[k]];
270
+ }).sort(function (a, b) { return b[1] - a[1]; });
271
+ var chips = states.map(function (pair) {
272
+ return h('span', { class: 'chip' }, h('span', { text: pair[0] }), h('b', { text: String(pair[1]) }));
273
+ });
274
+ chips.push(h('span', { class: 'chip' }, h('span', { text: 'TCP 总计' }), h('b', { text: String(net.tcp_total || 0) })));
275
+ document.getElementById('net-states').replaceChildren.apply(document.getElementById('net-states'), chips);
276
+
277
+ var listeners = net.listeners || [];
278
+ var filter = document.getElementById('listener-filter').value;
279
+ var rows = listeners.map(function (l) {
280
+ var process = l.process ? l.process + (l.pid ? ' (' + l.pid + ')' : '') : '—';
281
+ var addr = (l.addresses || []).join(', ');
282
+ var tr = h('tr', {
283
+ 'data-search': (l.proto + ' ' + l.port + ' ' + addr + ' ' + process).toLowerCase()
284
+ },
285
+ h('td', {}, h('span', { class: 'badge ' + (l.proto === 'tcp' ? 'info' : 'off'), text: l.proto })),
286
+ h('td', { class: 'mono', text: String(l.port) }),
287
+ h('td', { class: 'mono muted trunc', title: addr, text: addr || '—' }),
288
+ h('td', { class: 'trunc', title: process, text: process })
289
+ );
290
+ if (filter && tr.dataset.search.indexOf(filter.trim().toLowerCase()) === -1) tr.hidden = true;
291
+ return tr;
292
+ });
293
+ if (!rows.length) {
294
+ rows.push(h('tr', {}, h('td', { colspan: '4' }, h('div', { class: 'empty', text: net.error || '没有监听端口' }))));
295
+ } else if (net.error) {
296
+ rows.push(h('tr', {}, h('td', { colspan: '4' }, h('div', { class: 'error-text', text: net.error }))));
297
+ }
298
+ document.getElementById('listener-body').replaceChildren.apply(document.getElementById('listener-body'), rows);
299
+ }
300
+
301
+ function applyListenerFilter() {
302
+ var q = (document.getElementById('listener-filter').value || '').trim().toLowerCase();
303
+ document.querySelectorAll('#listener-body tr').forEach(function (tr) {
304
+ if (tr.dataset.search === undefined) return;
305
+ tr.hidden = !!q && tr.dataset.search.indexOf(q) === -1;
306
+ });
307
+ }
308
+
309
+ // ---------- 渲染:容器 ----------
310
+ function renderContainers(data) {
311
+ var c = data.containers || {};
312
+ var counts = c.counts || {};
313
+ var body = document.getElementById('container-body');
314
+ if (!c.runtime) {
315
+ body.replaceChildren();
316
+ setText('container-note', '');
317
+ return;
318
+ }
319
+ setText('container-note', c.runtime + ' · 运行 ' + counts.running + ' / 共 ' + counts.total);
320
+ var items = c.items || [];
321
+ if (!items.length) {
322
+ body.replaceChildren(h('tr', {}, h('td', { colspan: '5' }, h('div', { class: 'empty', text: c.error || '没有容器' }))));
323
+ return;
324
+ }
325
+ var rows = items.map(function (item) {
326
+ var statusBadge = h('span', { class: 'badge ' + (item.running ? 'ok' : 'off') },
327
+ h('span', { class: 'dot ' + (item.running ? 'ok' : 'off') }),
328
+ item.running ? '运行中' : '已停止'
329
+ );
330
+ return h('tr', {},
331
+ h('td', {}, statusBadge),
332
+ h('td', {}, h('div', { class: 'mono', text: item.name }), h('div', { class: 'cell-sub mono', text: item.id || '' })),
333
+ h('td', {},
334
+ h('div', { class: 'trunc small', title: item.image, text: item.image || '—' }),
335
+ h('div', { class: 'cell-sub trunc', title: item.ports, text: item.ports || item.status || '' })
336
+ ),
337
+ h('td', { class: 'num mono', text: item.cpu || '—' }),
338
+ h('td', { class: 'num mono', title: item.mem_usage || '', text: item.mem_percent || '—' })
339
+ );
340
+ });
341
+ if (c.error) {
342
+ rows.push(h('tr', {}, h('td', { colspan: '5' }, h('div', { class: 'error-text', text: c.error }))));
343
+ }
344
+ if (c.stats_error) {
345
+ rows.push(h('tr', {}, h('td', { colspan: '5' }, h('div', { class: 'error-text', text: '统计不可用: ' + c.stats_error }))));
346
+ }
347
+ body.replaceChildren.apply(body, rows);
348
+ }
349
+
350
+ // ---------- 渲染:定时任务 ----------
351
+ function timerBadge(item) {
352
+ var result = (item.service_result || '').toLowerCase();
353
+ if (result && result !== 'success' && result !== 'done') {
354
+ return h('span', { class: 'badge bad', title: 'service: ' + result + (item.service_exit ? ' (exit ' + item.service_exit + ')' : ''), text: result === 'failed' ? '上次失败' : result });
355
+ }
356
+ if ((item.timer_state || '').toLowerCase() === 'active') {
357
+ return h('span', { class: 'badge ok', text: '已启用' });
358
+ }
359
+ if ((item.timer_state || '').toLowerCase() === 'inactive') {
360
+ return h('span', { class: 'badge off', text: '未激活' });
361
+ }
362
+ return h('span', { class: 'badge', text: item.timer_state || '—' });
363
+ }
364
+ function renderTimers(data) {
365
+ var t = data.timers || {};
366
+ setText('timer-note', (t.items ? t.items.length + ' 个 · ' : '') + noteFor(t.updated_at));
367
+ var body = document.getElementById('timer-body');
368
+ var items = t.items || [];
369
+ if (!items.length) {
370
+ body.replaceChildren(h('tr', {}, h('td', { colspan: '4' }, h('div', { class: 'empty', text: t.error || '没有定时任务' }))));
371
+ return;
372
+ }
373
+ var rows = items.map(function (item) {
374
+ return h('tr', {},
375
+ h('td', {},
376
+ h('div', { class: 'mono', text: item.unit }),
377
+ h('div', { class: 'cell-sub mono', text: item.activates || '' })
378
+ ),
379
+ h('td', {}, timerBadge(item), item.service_exit && item.service_exit !== '0'
380
+ ? h('span', { class: 'tiny muted', text: ' exit ' + item.service_exit }) : null),
381
+ h('td', { class: 'nowrap' },
382
+ h('div', { class: 'mono small', text: fmtTime(item.next) }),
383
+ h('div', { class: 'cell-sub', text: item.next ? relTime(item.next) : '无计划' })
384
+ ),
385
+ h('td', { class: 'nowrap' },
386
+ h('div', { class: 'mono small', text: fmtTime(item.last) }),
387
+ h('div', { class: 'cell-sub', text: item.last ? relTime(item.last) : '从未运行' })
388
+ )
389
+ );
390
+ });
391
+ if (t.error) {
392
+ rows.push(h('tr', {}, h('td', { colspan: '4' }, h('div', { class: 'error-text', text: t.error }))));
393
+ }
394
+ body.replaceChildren.apply(body, rows);
395
+ }
396
+
397
+ // ---------- 渲染:restic ----------
398
+ function resticBadge(repo) {
399
+ if (!repo.ok) return h('span', { class: 'badge bad', text: '错误' });
400
+ if (!repo.latest_time) return h('span', { class: 'badge warn', text: '无快照' });
401
+ var age = repo.latest_age || 0;
402
+ if (age > 7 * 86400) return h('span', { class: 'badge bad', text: '超过 7 天' });
403
+ if (age > 2 * 86400) return h('span', { class: 'badge warn', text: '超过 2 天' });
404
+ return h('span', { class: 'badge ok', text: '正常' });
405
+ }
406
+ function snapshotTable(repo) {
407
+ if (!repo.snapshots || !repo.snapshots.length) {
408
+ return h('div', { class: 'empty', text: '没有快照' });
409
+ }
410
+ var rows = repo.snapshots.map(function (s) {
411
+ var paths = (s.paths || []).join(', ');
412
+ return h('tr', {},
413
+ h('td', { class: 'mono small nowrap', text: fmtTime(s.time) }),
414
+ h('td', { class: 'mono small', text: s.hostname || '—' }),
415
+ h('td', { class: 'small trunc', title: paths, text: paths || '—' }),
416
+ h('td', { class: 'tiny muted', text: (s.tags || []).join(', ') || '' })
417
+ );
418
+ });
419
+ return h('div', { class: 'table-wrap' },
420
+ h('table', { class: 'data' },
421
+ h('thead', {}, h('tr', {},
422
+ h('th', { text: '时间' }), h('th', { text: '主机' }), h('th', { text: '路径' }), h('th', { text: '标签' })
423
+ )),
424
+ h('tbody', {}, rows)
425
+ )
426
+ );
427
+ }
428
+ function renderRestic(data) {
429
+ var r = data.restic || {};
430
+ setText('restic-note', r.updated_at ? noteFor(r.updated_at) : '采集间隔较长');
431
+ var body = document.getElementById('restic-body');
432
+
433
+ if (r.enabled === false) {
434
+ body.replaceChildren(h('div', { class: 'empty', text: 'restic 采集已在配置中禁用。' }));
435
+ return;
436
+ }
437
+ if (r.error) {
438
+ body.replaceChildren(h('div', { class: 'error-text', text: r.error }));
439
+ return;
440
+ }
441
+ var repos = r.repos || [];
442
+ if (!repos.length) {
443
+ body.replaceChildren(h('div', { class: 'hint' },
444
+ h('div', { text: '没有发现 restic 仓库。可以用命令行参数或配置文件指定:' }),
445
+ h('div', { style: 'margin-top:8px' }, h('code', { text: 'serverdeck --restic-repo /mnt/backup/restic --restic-password-file /etc/restic/pass' })),
446
+ h('div', { style: 'margin-top:6px', text: '也会自动扫描 systemd 单元和 cron 中出现的 restic 命令。' })
447
+ ));
448
+ return;
449
+ }
450
+ body.replaceChildren.apply(body, repos.map(function (repo) {
451
+ var header = h('div', { class: 'repo-head' },
452
+ h('div', { class: 'repo-title' },
453
+ h('strong', { text: repo.name || '仓库' }),
454
+ h('span', { class: 'mono', text: repo.repository || '' }),
455
+ repo.source ? h('span', { class: 'tiny muted', text: '来源: ' + repo.source }) : null
456
+ ),
457
+ resticBadge(repo)
458
+ );
459
+ var meta = h('div', { class: 'repo-meta' },
460
+ h('span', {}, '快照 ', h('b', { text: String(repo.snapshot_count || 0) })),
461
+ h('span', {}, '最新 ', h('b', { text: repo.latest_time ? fmtTime(repo.latest_time) : '—' })),
462
+ h('span', {}, '距今 ', h('b', { text: repo.latest_age !== null && repo.latest_age !== undefined ? duration(repo.latest_age) : '—' }))
463
+ );
464
+ var children = [header, meta];
465
+ if (repo.error) {
466
+ children.push(h('div', { class: 'error-text', text: repo.error }));
467
+ } else {
468
+ children.push(h('div', { class: 'repo-body' }, snapshotTable(repo)));
469
+ }
470
+ return h('div', { class: 'repo' }, children);
471
+ }));
472
+ }
473
+
474
+ // ---------- 页面分组 ----------
475
+ var TAB_ORDER = ['system', 'network', 'timers', 'containers', 'restic'];
476
+ var tabsNav = document.getElementById('tabs');
477
+ var currentTab = 'system';
478
+
479
+ function tabButton(name) {
480
+ return tabsNav ? tabsNav.querySelector('[data-tab="' + name + '"]') : null;
481
+ }
482
+ function tabPanel(name) {
483
+ return document.getElementById('panel-' + name);
484
+ }
485
+ function activateTab(name, options) {
486
+ if (TAB_ORDER.indexOf(name) === -1) name = 'system';
487
+ var button = tabButton(name);
488
+ if (!button || button.hidden) name = 'system';
489
+ currentTab = name;
490
+ TAB_ORDER.forEach(function (key) {
491
+ var btn = tabButton(key);
492
+ var panel = tabPanel(key);
493
+ var active = key === name;
494
+ if (btn) {
495
+ btn.classList.toggle('active', active);
496
+ btn.setAttribute('aria-selected', active ? 'true' : 'false');
497
+ btn.tabIndex = active ? 0 : -1;
498
+ }
499
+ if (panel) panel.classList.toggle('active', active);
500
+ });
501
+ if (!options || !options.silent) {
502
+ try { history.replaceState(null, '', '#' + name); }
503
+ catch (e) { location.hash = name; }
504
+ window.scrollTo(0, 0);
505
+ }
506
+ }
507
+ function initTabs() {
508
+ if (!tabsNav) return;
509
+ tabsNav.addEventListener('click', function (event) {
510
+ var button = event.target.closest('[data-tab]');
511
+ if (button && !button.hidden) activateTab(button.getAttribute('data-tab'));
512
+ });
513
+ tabsNav.addEventListener('keydown', function (event) {
514
+ if (event.key !== 'ArrowRight' && event.key !== 'ArrowLeft') return;
515
+ var buttons = Array.prototype.slice.call(tabsNav.querySelectorAll('[data-tab]'))
516
+ .filter(function (item) { return !item.hidden; });
517
+ var index = buttons.indexOf(document.activeElement);
518
+ if (index === -1) return;
519
+ event.preventDefault();
520
+ var direction = event.key === 'ArrowRight' ? 1 : -1;
521
+ var next = buttons[(index + direction + buttons.length) % buttons.length];
522
+ next.focus();
523
+ activateTab(next.getAttribute('data-tab'));
524
+ });
525
+ window.addEventListener('hashchange', function () {
526
+ activateTab((location.hash || '#system').slice(1), { silent: true });
527
+ });
528
+ activateTab((location.hash || '#system').slice(1));
529
+ }
530
+
531
+ function updateContainerTab(data) {
532
+ var button = tabButton('containers');
533
+ if (!button) return;
534
+ var runtime = data.containers && data.containers.runtime;
535
+ button.hidden = !runtime;
536
+ if (!runtime && currentTab === 'containers') activateTab('system');
537
+ }
538
+
539
+ function setTabCount(name, value) {
540
+ var node = document.getElementById('tab-count-' + name);
541
+ if (!node) return;
542
+ if (value === null || value === undefined || value === 0) {
543
+ node.hidden = true;
544
+ node.textContent = '';
545
+ } else {
546
+ node.hidden = false;
547
+ node.textContent = String(value);
548
+ }
549
+ }
550
+ function updateTabCounts(data) {
551
+ setTabCount('timers', ((data.timers || {}).items || []).length);
552
+ var containerData = data.containers || {};
553
+ setTabCount('containers', containerData.runtime ? ((containerData.counts || {}).running || 0) : null);
554
+ setTabCount('restic', ((data.restic || {}).repos || []).length);
555
+ }
556
+
557
+ function summaryRow(label, value, extra, target, tone) {
558
+ return h('button', { class: 'summary-row', type: 'button', 'data-goto': target },
559
+ h('span', { class: 'summary-label', text: label }),
560
+ h('span', { class: 'summary-value' + (tone ? ' tone-' + tone : ''), text: value }),
561
+ h('span', { class: 'summary-extra', text: extra || '' }),
562
+ h('span', { class: 'summary-chevron', text: '›' })
563
+ );
564
+ }
565
+ function renderSummary(data) {
566
+ var body = document.getElementById('summary-body');
567
+ if (!body) return;
568
+ var rows = [];
569
+ var systemData = data.system || {};
570
+ setText('summary-note', noteFor(systemData.updated_at));
571
+
572
+ var cpu = data.cpu || {};
573
+ if (typeof cpu.usage === 'number') {
574
+ rows.push(summaryRow('CPU', num(cpu.usage, 1) + '%', (cpu.cores || 0) + ' 核', 'card-cpu',
575
+ cpu.usage >= 90 ? 'bad' : (cpu.usage >= 80 ? 'warn' : 'ok')));
576
+ }
577
+
578
+ var memory = data.memory || {};
579
+ if (typeof memory.percent === 'number') {
580
+ rows.push(summaryRow('内存', num(memory.percent, 1) + '%',
581
+ bytes(memory.used) + ' / ' + bytes(memory.total), 'card-memory',
582
+ memory.percent >= 90 ? 'bad' : (memory.percent >= 80 ? 'warn' : 'ok')));
583
+ }
584
+
585
+ var disks = (data.disks || {}).items || [];
586
+ if (disks.length) {
587
+ var topDisk = disks[0];
588
+ disks.forEach(function (item) {
589
+ if (item.percent > topDisk.percent) topDisk = item;
590
+ });
591
+ rows.push(summaryRow('磁盘', num(topDisk.percent, 0) + '%', topDisk.mount, 'card-disk',
592
+ topDisk.percent >= 90 ? 'bad' : (topDisk.percent >= 75 ? 'warn' : 'ok')));
593
+ }
594
+
595
+ var networkData = data.network || {};
596
+ var listeners = networkData.listeners || [];
597
+ if (networkData.tcp_total !== undefined) {
598
+ rows.push(summaryRow('网络', String(networkData.tcp_total || 0) + ' 连接',
599
+ ((networkData.tcp_states || {}).ESTAB || 0) + ' 已建立 · ' + listeners.length + ' 监听', 'network'));
600
+ }
601
+
602
+ var timersData = data.timers || {};
603
+ var timerItems = timersData.items || [];
604
+ var failedTimers = timerItems.filter(function (item) {
605
+ var result = (item.service_result || '').toLowerCase();
606
+ return result && result !== 'success' && result !== 'done';
607
+ }).length;
608
+ rows.push(summaryRow('定时任务', String(timerItems.length) + ' 个',
609
+ failedTimers ? failedTimers + ' 个异常' : (timersData.error ? '采集异常' : '全部正常'),
610
+ 'timers', failedTimers || timersData.error ? 'bad' : 'ok'));
611
+
612
+ var containerData = data.containers || {};
613
+ if (containerData.runtime) {
614
+ var counts = containerData.counts || {};
615
+ rows.push(summaryRow('容器', String(counts.running || 0) + ' / ' + String(counts.total || 0),
616
+ containerData.runtime, 'containers', containerData.error ? 'bad' : 'ok'));
617
+ }
618
+
619
+ var resticData = data.restic || {};
620
+ if (resticData.enabled === false) {
621
+ rows.push(summaryRow('Restic 备份', '已禁用', '配置中关闭了采集', 'restic', 'warn'));
622
+ } else if (resticData.available === false) {
623
+ rows.push(summaryRow('Restic 备份', '未安装', '未找到 restic 命令', 'restic', 'warn'));
624
+ } else {
625
+ var repos = resticData.repos || [];
626
+ var badRepos = repos.filter(function (repo) { return !repo.ok; }).length;
627
+ var latestAge = 0;
628
+ repos.forEach(function (repo) {
629
+ if (repo.latest_age && repo.latest_age > latestAge) latestAge = repo.latest_age;
630
+ });
631
+ var resticValue = '未配置';
632
+ var resticTone = 'warn';
633
+ var resticExtra = '';
634
+ if (resticData.error) {
635
+ resticValue = '错误';
636
+ resticTone = 'bad';
637
+ resticExtra = resticData.error;
638
+ } else if (repos.length) {
639
+ resticValue = badRepos ? badRepos + ' 个异常' : '正常';
640
+ resticTone = badRepos ? 'bad' : (latestAge > 7 * 86400 ? 'bad' : (latestAge > 2 * 86400 ? 'warn' : 'ok'));
641
+ resticExtra = repos.length + ' 个仓库';
642
+ }
643
+ rows.push(summaryRow('Restic 备份', resticValue, resticExtra, 'restic', resticTone));
644
+ }
645
+
646
+ if (!rows.length) {
647
+ body.replaceChildren(h('div', { class: 'empty', text: '采集尚未完成' }));
648
+ } else {
649
+ body.replaceChildren.apply(body, rows);
650
+ }
651
+ }
652
+
653
+ function initSummary() {
654
+ var body = document.getElementById('summary-body');
655
+ if (!body) return;
656
+ body.addEventListener('click', function (event) {
657
+ var row = event.target.closest('[data-goto]');
658
+ if (!row) return;
659
+ var target = row.getAttribute('data-goto');
660
+ if (target === 'card-cpu' || target === 'card-memory' || target === 'card-disk') {
661
+ var card = document.getElementById(target);
662
+ if (card) card.scrollIntoView({ behavior: 'smooth', block: 'start' });
663
+ return;
664
+ }
665
+ activateTab(target);
666
+ });
667
+ }
668
+
669
+ // ---------- 状态与错误 ----------
670
+ var lastLoadedAt = 0;
671
+ var healthIssues = [];
672
+
673
+ function setHealth(level, title) {
674
+ var dot = document.getElementById('health-dot');
675
+ dot.className = 'dot' + (level === 'ok' ? '' : ' ' + level);
676
+ dot.title = title || '';
677
+ }
678
+ function showBanner(message) {
679
+ var banner = document.getElementById('banner');
680
+ banner.hidden = false;
681
+ banner.replaceChildren(h('span', { text: message }));
682
+ }
683
+ function clearBanner() {
684
+ document.getElementById('banner').hidden = true;
685
+ }
686
+ function collectIssues(data) {
687
+ var issues = [];
688
+ ['disks', 'timers', 'network', 'restic'].forEach(function (key) {
689
+ var part = data[key];
690
+ if (part && part.error) issues.push(key + ': ' + part.error);
691
+ });
692
+ if (data.containers && data.containers.runtime) {
693
+ if (data.containers.error) issues.push('containers: ' + data.containers.error);
694
+ if (data.containers.stats_error) issues.push('容器统计: ' + data.containers.stats_error);
695
+ }
696
+ ((data.restic && data.restic.repos) || []).forEach(function (repo) {
697
+ if (!repo.ok) issues.push(repo.name + ': ' + (repo.error || '错误'));
698
+ });
699
+ return issues;
700
+ }
701
+
702
+ // ---------- 数据加载 ----------
703
+ var token = '';
704
+ try { token = localStorage.getItem('serverdeck-token') || ''; } catch (e) { token = ''; }
705
+ var loading = false;
706
+ var autoRefresh = true;
707
+ var refreshTimer = null;
708
+ function authHeaders() {
709
+ return token ? { 'Authorization': 'Bearer ' + token } : {};
710
+ }
711
+
712
+ function showTokenForm(invalid) {
713
+ var banner = document.getElementById('banner');
714
+ banner.hidden = false;
715
+ var existingHint = document.getElementById('token-hint');
716
+ if (existingHint) {
717
+ existingHint.textContent = invalid ? '令牌无效,请重新输入。' : '此面板需要访问令牌。';
718
+ return;
719
+ }
720
+ var input = h('input', {
721
+ id: 'token-input', class: 'filter', type: 'password',
722
+ placeholder: '访问令牌', autocomplete: 'off', value: token || ''
723
+ });
724
+ var hint = h('span', {
725
+ id: 'token-hint',
726
+ text: invalid ? '令牌无效,请重新输入。' : '此面板需要访问令牌。'
727
+ });
728
+ var save = h('button', { class: 'btn', type: 'button', text: '保存令牌' });
729
+ function submit() {
730
+ token = input.value.trim();
731
+ try { localStorage.setItem('serverdeck-token', token); } catch (e) { /* ignore */ }
732
+ banner.hidden = true;
733
+ load();
734
+ }
735
+ save.addEventListener('click', submit);
736
+ input.addEventListener('keydown', function (e) { if (e.key === 'Enter') submit(); });
737
+ banner.replaceChildren(hint, input, save);
738
+ input.focus();
739
+ }
740
+
741
+ async function load() {
742
+ if (loading) return;
743
+ loading = true;
744
+ try {
745
+ var res = await fetch('/api/status', { headers: authHeaders(), cache: 'no-store' });
746
+ if (res.status === 401) { showTokenForm(!!token); setHealth('bad', '需要访问令牌'); return; }
747
+ if (!res.ok) throw new Error('HTTP ' + res.status);
748
+ var data = await res.json();
749
+ clearBanner();
750
+ lastLoadedAt = Date.now();
751
+ document.getElementById('updated').textContent = '数据 ' + duration((Date.now() - lastLoadedAt) / 1000) + '前';
752
+ renderSystem(data);
753
+ renderCpu(data);
754
+ renderMemory(data);
755
+ renderDisks(data);
756
+ renderNetwork(data);
757
+ renderContainers(data);
758
+ renderTimers(data);
759
+ renderRestic(data);
760
+ renderSummary(data);
761
+ updateContainerTab(data);
762
+ updateTabCounts(data);
763
+ healthIssues = collectIssues(data);
764
+ if (healthIssues.length) setHealth('warn', healthIssues.join('\n'));
765
+ else setHealth('ok', '所有采集正常');
766
+ var dot = document.getElementById('health-dot');
767
+ if (dot) dot.title = healthIssues.length ? healthIssues.join('\n') : '所有采集正常';
768
+ } catch (err) {
769
+ setHealth('bad', String(err));
770
+ showBanner('无法获取状态数据:' + err.message + '(' + Math.round(REFRESH_MS / 1000) + ' 秒后重试)');
771
+ } finally {
772
+ loading = false;
773
+ }
774
+ }
775
+
776
+ function schedule() {
777
+ if (refreshTimer) { clearInterval(refreshTimer); refreshTimer = null; }
778
+ if (!autoRefresh) return;
779
+ refreshTimer = setInterval(function () {
780
+ if (!document.hidden) load();
781
+ }, REFRESH_MS);
782
+ }
783
+
784
+ document.getElementById('refresh').addEventListener('click', async function () {
785
+ var btn = this;
786
+ btn.disabled = true;
787
+ try {
788
+ await fetch('/api/refresh', { method: 'POST', headers: authHeaders() });
789
+ await load();
790
+ } catch (err) {
791
+ showBanner('刷新失败:' + err.message);
792
+ } finally {
793
+ setTimeout(function () { btn.disabled = false; }, 600);
794
+ }
795
+ });
796
+
797
+ document.getElementById('auto').addEventListener('change', function () {
798
+ autoRefresh = this.checked;
799
+ schedule();
800
+ if (autoRefresh) load();
801
+ });
802
+
803
+ document.getElementById('listener-filter').addEventListener('input', applyListenerFilter);
804
+
805
+ setInterval(function () {
806
+ if (lastLoadedAt) {
807
+ setText('updated', '数据 ' + duration((Date.now() - lastLoadedAt) / 1000) + '前');
808
+ }
809
+ }, 1000);
810
+
811
+ document.addEventListener('visibilitychange', function () {
812
+ if (!document.hidden) load();
813
+ });
814
+
815
+ initTabs();
816
+ initSummary();
817
+ load();
818
+ schedule();
819
+ })();