'use strict'; jQuery(function ($) { const $updates = $('[data-about-updates]'); const $check = $updates.find('[data-update-check]'); const $updateStatus = $updates.find('[data-update-status]'); $check.prop('hidden', false).on('click', function () { $check.prop('disabled', true); $updateStatus.text('正在查询上游仓库…'); $.ajax({url: '/admin/about/update', dataType: 'json', timeout: 7500}) .done(({current, latest, comparison}) => { if (latest === null) { $updateStatus.text('上游仓库暂无已发布版本。'); } else if (comparison > 0) { $updateStatus.text('发现已发布的新版本 ' + latest + ',当前版本为 ' + current + '。'); } else if (comparison < 0) { $updateStatus.text('当前版本 ' + current + ' 高于上游最新已发布版本 ' + latest + '。'); } else { $updateStatus.text('当前版本 ' + current + ' 已是上游最新发布版本。'); } }) .fail(({status, responseJSON}) => { $updateStatus.text(status === 401 ? '登录已过期,请重新登录。' : (responseJSON?.message ?? '检查更新失败,请重试。')); }) .always(() => $check.prop('disabled', false)); }); const $metrics = $('[data-about-metrics]'); if (!$metrics.length) return; const $cpu = $metrics.find('[data-about-cpu]'); const $memory = $metrics.find('[data-about-memory]'); const percent = new Intl.NumberFormat('zh-CN', {style: 'percent', maximumFractionDigits: 1}); let previous = null; let timer = null; let pending = null; let sessionExpired = false; function active() { return $metrics[0].open && !document.hidden && !sessionExpired; } function poll() { timer = null; if (!active()) return; let delay = 5000; pending = $.ajax({url: '/admin/about/metrics', dataType: 'json', timeout: 4000}); pending .done(({cpu, memory}) => { if (!cpu || !previous || cpu.total <= previous.total) { $cpu.text(cpu ? '采样中…' : '暂不可用'); if (cpu) delay = 1000; } else { const total = cpu.total - previous.total; const idle = cpu.idle - previous.idle; $cpu.text(percent.format(Math.max(0, Math.min(1, 1 - idle / total)))); } previous = cpu; $memory.text(memory ?? '暂不可用'); }) .fail(({status}, reason) => { if (reason === 'abort') return; previous = null; sessionExpired = status === 401; const message = sessionExpired ? '登录已过期' : '暂不可用'; $cpu.text(message); $memory.text(message); }) .always(() => { pending = null; if (active()) timer = window.setTimeout(poll, delay); }); } function sync() { if (active()) { if (timer === null && pending === null) { $cpu.text('采样中…'); poll(); } return; } window.clearTimeout(timer); timer = null; previous = null; pending?.abort(); } $metrics.on('toggle', sync); $(document).on('visibilitychange', sync); sync(); });