const columns = ['实例', '用户', '位置与网络', '配置', '状态', '流量与期限', '操作']; const filterNames = ['q', 'user_id', 'host_id', 'service_status', 'expiry', 'attention', 'sort', 'per_page']; function el(tag, className = '', text) { const node = document.createElement(tag); node.className = className; if (text !== undefined) node.textContent = String(text); return node; } function text(...values) { return values.find(value => value !== null && value !== undefined && String(value).trim() !== '') ?? '—'; } function stack(primary, secondary) { const node = el('span', 'admin-checkout-user'); node.append(primary instanceof Node ? primary : el('strong', '', text(primary))); if (secondary) node.append(el('span', '', secondary)); return node; } function safeLink(value, label) { try { const url = new URL(value, location.origin); if (url.origin !== location.origin || !/^https?:$/.test(url.protocol)) throw new Error('Unsafe URL'); const link = el('a', '', label); link.href = url.pathname + url.search + url.hash; return link; } catch { return el('span', '', label); } } function date(value, short = false) { if (!value) return '未记录'; const numeric = Number(value); const timestamp = Number.isFinite(numeric) ? numeric * (numeric < 1e12 ? 1000 : 1) : Date.parse(value); const parsed = new Date(timestamp); if (!Number.isFinite(parsed.getTime())) return '未记录'; return short ? parsed.toLocaleDateString('zh-CN') : parsed.toLocaleString('zh-CN', { hour12: false }); } function copyButton(value, label = '复制') { const button = el('button', 'btn btn-light btn-sm'); button.type = 'button'; button.dataset.copy = String(value); button.setAttribute('aria-label', `${label} ${value}`); const icon = el('i', 'mdi mdi-content-copy'); icon.setAttribute('aria-hidden', 'true'); button.append(icon); return button; } function powerInfo(value, sync = '') { const normalizedSync = String(sync || '').toLowerCase(); if (['unavailable', 'offline', 'host_offline', 'host_unreachable'].includes(normalizedSync)) { return ['暂时无法同步', 'secondary']; } if (['pending', 'never'].includes(normalizedSync)) return ['等待宿主机同步', 'secondary']; const normalized = String(value || '').toLowerCase().replace(/[_\s-]+/g, ''); return ({ running: ['运行中', 'success'], blocked: ['运行中', 'success'], shutoff: ['已关机', 'secondary'], stopped: ['已关机', 'secondary'], shutdown: ['关机中', 'warning'], paused: ['已暂停', 'warning'], pmsuspended: ['已挂起', 'warning'], crashed: ['已崩溃', 'danger'], })[normalized] || ['等待宿主机同步', 'secondary']; } function paintPower(node, vm) { const sync = String(vm?.state_sync_status || '').toLowerCase(); const [label, tone] = powerInfo(vm?.state, sync); const stale = !['', 'fresh'].includes(sync) && !['pending', 'never', 'unavailable', 'offline', 'host_offline', 'host_unreachable'].includes(sync); node.textContent = `电源:${label}${stale ? ' · 状态同步中' : ''}`; node.className = `badge bg-${tone}-subtle text-${tone}-emphasis`; node.title = sync === 'offline' || sync === 'unavailable' ? '宿主机暂时无法同步;保留最近一次状态,不表示已关机。' : vm.live_state_available === true || sync === 'fresh' ? '来自运行状态缓存的最近成功同步结果' : '尚未获取成功状态,或状态已超过有效期。'; } function jobStatus(task) { if (task?.completed === false && task.status === 'active') return '执行中'; if (task?.completed === true) { if (task.recovery?.pending === true) { const code = String(task.recovery?.code || task.finalization_error_code || ''); if (code === 'recovery_dispatch_ledger_conflict' || task.dispatch_state === 'invalid') { return '派发账本异常 · 待修复'; } if (task.dispatch_state === 'not_dispatched') return 'PHP 本地账本收尾中'; return task.status === 'failed' ? '已失败 · 持续恢复中' : '安全恢复中'; } return ({ succeeded: '已成功', failed: '已失败' })[task.status] || '任务状态协议无效'; } return '任务状态协议无效'; } export function createAdminInstanceDirectory({ root, byId, read, onOpenDetail, onOpenBackupLibrary, onCopy, } = {}) { if (!root || typeof byId !== 'function' || typeof read !== 'function') { throw new TypeError('Instance directory dependencies are incomplete'); } const state = { items: [], pagination: { page: 1, per_page: 20, total: 0, total_pages: 1 }, request: null, serial: 0, loading: false, hasData: false, active: true, timer: null, statusRequest: null, statusFailures: 0, started: false, }; function notice(message, error = false) { const node = byId('instances-notice'); node.textContent = message; node.className = `admin-config-status ${error ? 'is-error' : 'is-success'}`; node.setAttribute('role', error ? 'alert' : 'status'); } function row(vm) { const tr = el('tr'); tr.dataset.instanceId = String(vm.id); const addresses = el('span', 'admin-instance-addresses'); for (const [family, value] of [[4, vm.public_ipv4], [6, vm.public_ipv6]]) { const ip = el('span', 'admin-instance-ip'); ip.dataset.addressFamily = String(family); ip.append(el('small', 'text-muted', `IPv${family}`), el('span', 'admin-mono', text(value, '未记录'))); if (value) ip.append(copyButton(value, `复制公网 IPv${family}`)); addresses.append(ip); } const statuses = el('div', 'admin-instance-status'); const power = el('span'); power.dataset.powerStatus = ''; paintPower(power, vm); statuses.append(power, el('span', 'fs-12', `服务:${text(vm.display?.service)}`), el('span', 'fs-12', `网络:${text(vm.display?.network)}`)); if (vm.active_job) { const locked = vm.active_job.blocks_mutation === true; statuses.append(el('span', 'text-warning fs-12', `任务 #${vm.active_job.id} · ${jobStatus(vm.active_job)}${locked ? ' · 资源安全锁定' : ''}`)); } const detail = el('button', 'btn btn-primary btn-sm', '查看详情'); detail.type = 'button'; detail.dataset.instanceDetail = String(vm.id); detail.setAttribute('aria-label', `查看 ${text(vm.name)} 的详情`); const usage = stack(vm.display?.traffic, vm.display?.expiry); if (vm.service_expires_at && vm.service_status !== 'exempt') { usage.append(el('span', '', `到期 ${date(vm.service_expires_at, true)}`)); } const location = stack( text(vm.host_name, `宿主机 #${vm.host_id}`), text(vm.region, '地区未记录'), ); location.append(addresses); const cells = [ stack(text(vm.name), `#${vm.id} · ${text(vm.os_name, '系统未记录')}`), stack(vm.user_url ? safeLink(vm.user_url, text(vm.user_name, `用户 #${vm.user_id}`)) : text(vm.user_name), `ID ${vm.user_id}`), location, stack(vm.display?.configuration, text(vm.plan_name, '无关联套餐')), statuses, usage, detail, ]; cells.forEach((content, index) => { const td = el('td'); td.dataset.label = columns[index]; td.append(content); tr.append(td); }); return tr; } function renderRows() { const body = byId('instances-body'); body.replaceChildren(); state.items.forEach(vm => body.append(row(vm))); if (!state.items.length) { const tr = el('tr'); const td = el('td', 'text-center text-muted py-4', '没有符合条件的实例。'); td.colSpan = columns.length; tr.append(td); body.append(tr); } } function renderPagination() { const page = state.pagination; byId('instances-count').textContent = state.hasData ? `共 ${page.total} 台` : '数据未获取'; byId('instances-page-label').textContent = state.hasData ? `第 ${page.page} / ${page.total_pages} 页 · 共 ${page.total} 台` : '实例数据暂不可用'; byId('instances-previous').disabled = !state.hasData || state.loading || page.page <= 1; byId('instances-next').disabled = !state.hasData || state.loading || page.page >= page.total_pages; byId('instances-refresh').disabled = state.loading; byId('instances-body').setAttribute('aria-busy', String(state.loading)); } function syncForm(payload) { const form = byId('instances-filter'); const hosts = form.elements.namedItem('host_id'); hosts.replaceChildren(new Option('全部宿主机', '')); for (const host of payload.hosts || []) { hosts.add(new Option(`${host.name}${host.region ? ` · ${host.region}` : ''}`, host.id)); } for (const name of filterNames) { const control = form.elements.namedItem(name); const value = String(name === 'per_page' ? payload.pagination.per_page : (payload.filters?.[name] ?? '')); if (control instanceof HTMLSelectElement && value && !Array.from(control.options).some(option => option.value === value)) { control.add(new Option(value, value)); } control.value = value || ({ expiry: 'all', attention: 'all', sort: 'newest' })[name] || ''; } const advancedActive = String(form.elements.namedItem('user_id').value || '') !== '' || form.elements.namedItem('expiry').value !== 'all' || form.elements.namedItem('attention').value !== 'all' || form.elements.namedItem('sort').value !== 'newest' || String(form.elements.namedItem('per_page').value) !== '20'; const advanced = byId('instances-advanced'); if (advanced) advanced.open = advancedActive; const activeQuick = form.elements.namedItem('attention').value === 'network' ? 'network' : (form.elements.namedItem('attention').value === 'jobs' ? 'jobs' : (form.elements.namedItem('expiry').value === 'soon' ? 'expiry' : '')); for (const card of root.querySelectorAll('[data-instance-quick-filter]')) { card.setAttribute('aria-pressed', String(card.dataset.instanceQuickFilter === activeQuick)); } } function applyPayload(payload, replaceRows = true) { if (!Array.isArray(payload?.items) || !payload?.pagination) { throw new Error('实例数据格式无效,请重试。'); } state.items = payload.items; state.pagination = payload.pagination; state.hasData = true; for (const key of ['total', 'expiring', 'network_restricted', 'attention']) { byId(`instances-${key.replaceAll('_', '-')}`).textContent = Number(payload.summary?.[key] ?? 0).toLocaleString('zh-CN'); } syncForm(payload); if (replaceRows) renderRows(); renderPagination(); } function formUrl(page = 1) { const url = new URL(location.pathname, location.origin); const form = byId('instances-filter'); for (const key of filterNames) { const value = form.elements.namedItem(key).value.trim(); if (value && value !== 'all' && !(key === 'sort' && value === 'newest')) { url.searchParams.set(key, value); } } if (page > 1) url.searchParams.set('page', String(page)); return url; } function stopStatuses() { clearTimeout(state.timer); state.timer = null; state.statusRequest?.abort(); state.statusRequest = null; } function scheduleStatuses() { clearTimeout(state.timer); if (!state.active || document.hidden || !state.items.length || state.loading) return; state.timer = setTimeout(refreshStatuses, Math.min(120000, 30000 * 2 ** state.statusFailures)); } async function refreshStatuses() { if (!state.active || document.hidden || state.loading || state.statusRequest || !state.items.length) return; const controller = new AbortController(); state.statusRequest = controller; const serial = state.serial; byId('instances-live-status').textContent = '正在更新当前页电源状态…'; try { const ids = state.items.map(vm => vm.id).join(','); const payload = await read(`/api/v1/vms/statuses?ids=${encodeURIComponent(ids)}`, controller); if (controller.signal.aborted || serial !== state.serial) return; const updates = Array.isArray(payload?.vms) ? payload.vms : []; let syncing = 0; for (const vm of state.items) { const update = updates.find(item => String(item.api_id ?? item.id) === String(vm.id) && item.uuid === vm.uuid); const candidate = String(update?.state || update?.status || '').trim(); const normalized = candidate.toLowerCase().replace(/[_\s-]+/g, ''); if (candidate !== '' && !['unknown', 'nostate'].includes(normalized)) vm.state = candidate; vm.live_state_available = update?.live_state_available === true; vm.state_fresh = update?.state_fresh === true || update?.fresh === true || update?.fresh === 1 || update?.fresh === '1' || vm.live_state_available; vm.state_sync_status = String(update?.state_sync_status ?? update?.sync_status ?? (vm.live_state_available ? 'fresh' : vm.state_sync_status || 'pending')).toLowerCase(); if (!['', 'fresh'].includes(vm.state_sync_status)) syncing += 1; const rowNode = Array.from(byId('instances-body').rows) .find(node => node.dataset.instanceId === String(vm.id)); const badge = rowNode?.querySelector('[data-power-status]'); if (badge) paintPower(badge, vm); } state.statusFailures = 0; byId('instances-live-status').textContent = `电源状态更新于 ${new Date().toLocaleTimeString('zh-CN')}${syncing ? ` · ${syncing} 台状态同步中` : ''}`; } catch (error) { if (controller.signal.aborted && controller.signal.reason !== 'timeout') return; if (serial !== state.serial) return; state.statusFailures = Math.min(2, state.statusFailures + 1); for (const vm of state.items) { vm.live_state_available = false; vm.state_sync_status = 'offline'; const rowNode = Array.from(byId('instances-body').rows) .find(node => node.dataset.instanceId === String(vm.id)); const badge = rowNode?.querySelector('[data-power-status]'); if (badge) paintPower(badge, vm); } byId('instances-live-status').textContent = `${error.message} 列表已保留,电源状态暂时无法同步。`; } finally { if (state.statusRequest === controller) { state.statusRequest = null; scheduleStatuses(); } } } async function reload(url, historyMode = 'push') { state.request?.abort(); stopStatuses(); const controller = new AbortController(); state.request = controller; const serial = ++state.serial; state.loading = true; renderPagination(); notice('正在读取实例数据…'); try { const payload = await read(`/api/v1/admin/instances${url.search}`, controller); if (controller.signal.aborted || serial !== state.serial) return; applyPayload(payload); const canonical = formUrl(payload.pagination.page); if (historyMode === 'push' && canonical.href !== location.href) history.pushState(null, '', canonical); notice(`已读取 ${payload.pagination.total} 台实例 · ${new Date().toLocaleTimeString('zh-CN')}`); } catch (error) { if (controller.signal.aborted && controller.signal.reason !== 'timeout') return; if (serial === state.serial) notice(`${error.message} 已保留原列表。`, true); } finally { if (serial === state.serial) { state.loading = false; state.request = null; renderPagination(); void refreshStatuses(); } } } function updatePublicNetwork(id, publicNetwork = {}) { const ipv4 = String(publicNetwork.public_ipv4 || ''); const ipv4Cidr = String(publicNetwork.public_ipv4_cidr || ''); const ipv6 = String(publicNetwork.public_ipv6 || ''); const ipv6Cidr = String(publicNetwork.public_ipv6_cidr || ''); const item = state.items.find(entry => String(entry.id) === String(id)); if (item) { item.public_ip = ipv4; item.public_ip_cidr = ipv4Cidr; item.public_ipv4 = ipv4; item.public_ipv4_cidr = ipv4Cidr; item.public_ipv6 = ipv6; item.public_ipv6_cidr = ipv6Cidr; } const rowNode = Array.from(byId('instances-body').rows) .find(node => node.dataset.instanceId === String(id)); for (const [family, value] of [[4, ipv4], [6, ipv6]]) { const ipNode = rowNode?.querySelector(`[data-address-family="${family}"]`); if (!ipNode) continue; ipNode.replaceChildren(el('small', 'text-muted', `IPv${family}`), el('span', 'admin-mono', text(value, '未记录'))); if (value) ipNode.append(copyButton(value, `复制公网 IPv${family}`)); } } const handlers = { submit: event => { event.preventDefault(); void reload(formUrl()); }, reset: event => { if (event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return; event.preventDefault(); void reload(new URL(location.pathname, location.origin)); }, refresh: () => { void reload(new URL(location.href), 'none'); }, library: event => onOpenBackupLibrary?.(event.currentTarget), previous: () => { void reload(formUrl(state.pagination.page - 1)); }, next: () => { void reload(formUrl(state.pagination.page + 1)); }, click: event => { const quick = event.target.closest('[data-instance-quick-filter]'); if (quick) { const value = quick.dataset.instanceQuickFilter; if (value === 'all') { void reload(new URL(location.pathname, location.origin)); return; } const form = byId('instances-filter'); form.elements.namedItem('expiry').value = value === 'expiry' ? 'soon' : 'all'; form.elements.namedItem('attention').value = ['network', 'jobs'].includes(value) ? value : 'all'; const advanced = byId('instances-advanced'); if (advanced) advanced.open = true; void reload(formUrl()); return; } const detail = event.target.closest('[data-instance-detail]'); if (detail) onOpenDetail?.(detail.dataset.instanceDetail, detail); const button = event.target.closest('[data-copy]'); if (button) onCopy?.(button.dataset.copy); }, popstate: () => { void reload(new URL(location.href), 'none'); }, visibility: () => { if (document.hidden) stopStatuses(); else void refreshStatuses(); }, pagehide: () => { state.active = false; stopStatuses(); state.request?.abort(); }, pageshow: event => { state.active = true; if (event.persisted) void reload(new URL(location.href), 'none'); }, }; function start(payload) { if (state.started) return; state.started = true; byId('instances-filter').addEventListener('submit', handlers.submit); byId('instances-reset').addEventListener('click', handlers.reset); byId('instances-refresh').addEventListener('click', handlers.refresh); byId('instances-backup-library').addEventListener('click', handlers.library); byId('instances-previous').addEventListener('click', handlers.previous); byId('instances-next').addEventListener('click', handlers.next); root.addEventListener('click', handlers.click); window.addEventListener('popstate', handlers.popstate); document.addEventListener('visibilitychange', handlers.visibility); window.addEventListener('pagehide', handlers.pagehide); window.addEventListener('pageshow', handlers.pageshow); if (payload) { try { applyPayload(payload, false); void refreshStatuses(); return; } catch { notice('初始数据读取失败,正在重试…', true); } } else notice('初始数据读取失败,正在重试…', true); void reload(new URL(location.href), 'none'); } function dispose() { if (!state.started) return; state.started = false; state.active = false; stopStatuses(); state.request?.abort(); byId('instances-filter').removeEventListener('submit', handlers.submit); byId('instances-reset').removeEventListener('click', handlers.reset); byId('instances-refresh').removeEventListener('click', handlers.refresh); byId('instances-backup-library').removeEventListener('click', handlers.library); byId('instances-previous').removeEventListener('click', handlers.previous); byId('instances-next').removeEventListener('click', handlers.next); root.removeEventListener('click', handlers.click); window.removeEventListener('popstate', handlers.popstate); document.removeEventListener('visibilitychange', handlers.visibility); window.removeEventListener('pagehide', handlers.pagehide); window.removeEventListener('pageshow', handlers.pageshow); } return Object.freeze({ start, reload, updatePublicNetwork, dispose }); }