Files
2026-11-18 01:35:56 +08:00

377 lines
19 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
window.__ModuleLoader__.load({
id: '@local/dsh-server-manager',
factory(require) {
const React = require('react')
const h = React.createElement
const ACCENT = '#5b8cff'
const GOOD = '#38d39f'
const WARN = '#f2b544'
const BAD = '#ff6b81'
const MONO = 'ui-monospace, SFMono-Regular, Menlo, monospace'
const T = {
text: 'var(--dsw-alias-text, #e8eefc)',
sub: 'var(--dsw-alias-text-secondary, rgba(232,238,252,.62))',
line: 'var(--dsw-alias-border-subtle, rgba(255,255,255,.14))',
bg: 'var(--dsw-alias-bg-elevated, #101623)',
soft: 'rgba(255,255,255,.05)'
}
const s = {
trigger: {
display: 'inline-flex', alignItems: 'center', gap: 6, height: 26, padding: '0 11px',
borderRadius: 999, border: '1px solid rgba(91,140,255,.45)', background: 'rgba(91,140,255,.16)',
color: 'inherit', font: 'inherit', fontSize: 12.5, fontWeight: 550, cursor: 'pointer',
whiteSpace: 'nowrap', letterSpacing: '.01em'
},
mask: {
position: 'fixed', inset: 0, zIndex: 9000, display: 'flex', alignItems: 'center', justifyContent: 'center',
background: 'rgba(4,8,16,.55)', backdropFilter: 'blur(3px)', padding: 12
},
panel: {
width: 'min(680px, 100%)', maxHeight: 'min(84vh, 780px)', overflow: 'auto', display: 'flex',
flexDirection: 'column', gap: 14, padding: 18, borderRadius: 18,
border: `1px solid ${T.line}`, background: T.bg, color: T.text,
boxShadow: '0 24px 64px rgba(0,0,0,.5)'
},
header: { display: 'flex', alignItems: 'center', gap: 12 },
bigDot: (on) => ({
width: 12, height: 12, borderRadius: 6, background: on ? GOOD : BAD,
boxShadow: `0 0 0 4px ${on ? 'rgba(56,211,159,.18)' : 'rgba(255,107,129,.16)'}`
}),
title: { fontSize: 16, fontWeight: 650, lineHeight: 1.2 },
small: { fontSize: 12, color: T.sub, lineHeight: 1.5 },
cards: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))', gap: 10 },
card: { border: `1px solid ${T.line}`, borderRadius: 12, padding: '10px 12px', background: T.soft },
cardLabel: { fontSize: 12, color: T.sub, marginBottom: 4 },
cardValue: { fontSize: 18, fontWeight: 600, fontFamily: MONO },
bar: { height: 5, borderRadius: 3, background: 'rgba(255,255,255,.1)', overflow: 'hidden', marginTop: 8 },
fill: (pct, color) => ({ height: '100%', width: `${Math.min(Math.max(pct, 0), 100)}%`, background: color, borderRadius: 3 }),
chips: { display: 'flex', flexWrap: 'wrap', gap: 8 },
chip: (on) => ({
display: 'inline-flex', alignItems: 'center', gap: 6, padding: '5px 10px', borderRadius: 999,
fontSize: 12.5, border: `1px solid ${T.line}`, color: on ? T.text : T.sub, background: T.soft
}),
dot: (on) => ({ width: 7, height: 7, borderRadius: 4, background: on ? 'rgba(255,255,255,.28)' : 'rgba(255,255,255,.28)' }),
svcDot: (on) => ({ width: 7, height: 7, borderRadius: 4, background: on ? GOOD : 'rgba(255,255,255,.28)' }),
actions: { display: 'flex', flexWrap: 'wrap', gap: 8 },
prim: { height: 34, padding: '0 14px', borderRadius: 9, border: 'none', background: ACCENT, color: '#fff', fontSize: 13.5, cursor: 'pointer' },
ghost: { height: 34, padding: '0 12px', borderRadius: 9, border: `1px solid ${T.line}`, background: 'transparent', color: 'inherit', fontSize: 13, cursor: 'pointer' },
pre: {
margin: 0, padding: 10, borderRadius: 10, background: 'rgba(0,0,0,.3)', maxHeight: 200, overflow: 'auto',
fontSize: 12, fontFamily: MONO, whiteSpace: 'pre-wrap', wordBreak: 'break-word', color: T.text
},
err: { fontSize: 13, color: BAD, lineHeight: 1.6 },
ok: { fontSize: 13, color: GOOD, lineHeight: 1.6 },
adv: { borderTop: `1px dashed ${T.line}`, paddingTop: 12, display: 'flex', flexDirection: 'column', gap: 8 },
input: {
flex: 1, height: 34, padding: '0 10px', borderRadius: 9, fontSize: 13, color: 'inherit',
border: `1px solid ${T.line}`, background: 'rgba(255,255,255,.04)', fontFamily: MONO
},
field: { display: 'flex', flexDirection: 'column', gap: 5, flex: '1 1 180px' },
label: { fontSize: 12, color: T.sub },
row: { display: 'flex', gap: 10, flexWrap: 'wrap' }
}
async function call(path, body) {
const init = body
? { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }
: {}
const res = await fetch(path, init)
const text = await res.text()
let data = {}
try { data = text ? JSON.parse(text) : {} } catch { data = { error: text.trim() } }
if (res.status === 401) data = { ok: false, error: '登录状态过期了,刷新一下页面再打开。' }
else if (!res.ok && !data.error) data.error = `HTTP ${res.status}`
return data
}
function Fill({ pct }) {
const color = pct >= 90 ? BAD : pct >= 75 ? WARN : GOOD
return h('div', { style: s.bar }, h('div', { style: s.fill(pct, color) }))
}
function Field({ label, value, onChange, placeholder, type }) {
return h('label', { style: s.field },
h('span', { style: s.label }, label),
h('input', {
style: s.input, value: value, placeholder, spellCheck: false,
inputMode: type === 'number' ? 'numeric' : undefined,
onChange: (e) => onChange(e.target.value)
})
)
}
function Panel({ onClose }) {
const [servers, setServers] = React.useState([])
const [serverId, setServerId] = React.useState('')
const [data, setData] = React.useState(null)
const [loading, setLoading] = React.useState(true)
const [logs, setLogs] = React.useState(null)
const [logBusy, setLogBusy] = React.useState(false)
const [busyAction, setBusyAction] = React.useState('')
const [advanced, setAdvanced] = React.useState(false)
const [cmd, setCmd] = React.useState('')
const [run, setRun] = React.useState(null)
const [addOpen, setAddOpen] = React.useState(false)
const [form, setForm] = React.useState({ label: '', host: '', port: '22', user: 'root', key: '', id: '' })
const [formMsg, setFormMsg] = React.useState(null)
const [testing, setTesting] = React.useState(false)
const [saving, setSaving] = React.useState(false)
const setField = (k) => (v) => setForm((f) => ({ ...f, [k]: v }))
const loadServers = React.useCallback(async (preferId) => {
const res = await call('/server-manager/servers')
const rows = res.servers || []
setServers(rows)
const next = preferId || rows.find((x) => x.default)?.id || rows[0]?.id || ''
setServerId(next)
return next
}, [])
const connect = React.useCallback(async (id) => {
setLoading(true)
const res = await call(`/server-manager/overview${id ? `?server=${encodeURIComponent(id)}` : ''}`).catch((e) => ({ ok: false, error: String(e.message || e) }))
setData(res)
setLogs(null)
setLoading(false)
}, [])
React.useEffect(() => {
loadServers().then((id) => connect(id)).catch((e) => { setData({ ok: false, error: String(e.message || e) }); setLoading(false) })
}, [loadServers, connect])
React.useEffect(() => {
const onKey = (e) => { if (e.key === 'Escape') { if (addOpen) setAddOpen(false); else onClose() } }
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [onClose, addOpen])
const showLogs = async () => {
if (logBusy) return
setLogBusy(true)
const res = await call(`/server-manager/logs?server=${encodeURIComponent(serverId)}&unit=gitea&lines=40`)
setLogs(res)
setLogBusy(false)
}
const act = async (label, command) => {
if (busyAction) return
setBusyAction(label)
const res = await call('/server-manager/exec', { server: serverId, command })
setRun({ ...res, label })
setBusyAction('')
connect(serverId)
}
const restartGitea = () => {
if (!window.confirm('要重启 Gitea 服务吗?大概 3–5 秒,期间网页打不开。')) return
act('重启 Gitea', 'systemctl restart gitea && sleep 1 && systemctl is-active gitea')
}
const openGitea = () => {
const host = data?.target?.split('@')[1]?.split(':')[0]
window.open(`http://${host || 'localhost'}:3000`, '_blank', 'noopener')
}
const testConn = async () => {
if (testing) return
setTesting(true)
setFormMsg(null)
const res = await call('/server-manager/test', form).catch((e) => ({ ok: false, error: String(e.message || e) }))
setFormMsg(res.ok ? { tone: 'ok', text: `连上了:${res.text.replace(/\n/g, ' · ')}(${res.ms} ms)` } : { tone: 'err', text: res.error || '连不上' })
setTesting(false)
}
const saveServer = async () => {
if (saving) return
setSaving(true)
setFormMsg(null)
const res = await call('/server-manager/servers/add', form).catch((e) => ({ ok: false, error: String(e.message || e) }))
if (!res.ok) {
setFormMsg({ tone: 'err', text: res.error || '保存失败' })
setSaving(false)
return
}
const id = res.server?.id
setSaving(false)
setAddOpen(false)
setForm({ label: '', host: '', port: '22', user: 'root', key: '', id: '' })
const next = await loadServers(id)
connect(next || id)
}
const removeServer = async () => {
if (!window.confirm(`从列表里删掉「${serverId}」吗?(只是删配置,不动服务器)`)) return
await call('/server-manager/servers/remove', { id: serverId })
const next = await loadServers('')
connect(next)
}
const online = Boolean(data?.ok)
const view = data || {}
const header = h('div', { style: s.header },
h('div', { style: s.bigDot(online) }),
h('div', { style: { flex: 1, minWidth: 0 } },
h('div', { style: s.title }, addOpen ? '添加服务器' : loading ? '正在连接…' : online ? '已连接' : '连不上'),
h('div', { style: s.small },
addOpen
? '填地址、用户名和私钥路径;先点「测试连接」再保存'
: loading
? (data?.target || '正在握手')
: online
? `${view.host || '服务器'} · ${view.os || ''} · 开机 ${view.uptime || '-'}`
: (data?.target || ''))
),
!addOpen && servers.length > 1 && h('select', {
value: serverId,
onChange: (e) => { setServerId(e.target.value); connect(e.target.value) },
style: { ...s.ghost, height: 32, padding: '0 8px' }
}, servers.map((x) => h('option', { key: x.id, value: x.id }, x.label))),
!addOpen && h('button', { style: s.ghost, onClick: () => { setAddOpen(true); setFormMsg(null) } }, '+ 添加'),
h('button', { style: s.ghost, onClick: onClose }, '关闭')
)
if (addOpen) {
return h('div', { style: s.mask, onMouseDown: (e) => { if (e.target === e.currentTarget) onClose() } },
h('div', { style: s.panel, role: 'dialog', 'aria-label': '添加服务器' },
header,
h('div', { style: s.row },
h(Field, { label: '显示名(随便写)', value: form.label, onChange: setField('label'), placeholder: '测试机' }),
h(Field, { label: '地址(IP 或域名)', value: form.host, onChange: setField('host'), placeholder: '1.2.3.4' })
),
h('div', { style: s.row },
h(Field, { label: '端口', value: form.port, onChange: setField('port'), placeholder: '22', type: 'number' }),
h(Field, { label: '用户名', value: form.user, onChange: setField('user'), placeholder: 'root' })
),
h(Field, { label: '私钥路径(留空走默认密钥)', value: form.key, onChange: setField('key'), placeholder: '~/.ssh/id_ed25519' }),
h(Field, { label: '短名字(留空自动,用于对话里指代)', value: form.id, onChange: setField('id'), placeholder: 'test' }),
formMsg && h('div', { style: formMsg.tone === 'ok' ? s.ok : s.err }, formMsg.text),
h('div', { style: s.actions },
h('button', { style: s.prim, onClick: saveServer, disabled: saving }, saving ? '保存中…' : '保存'),
h('button', { style: s.ghost, onClick: testConn, disabled: testing }, testing ? '测试中…' : '测试连接'),
h('button', { style: s.ghost, onClick: () => { setAddOpen(false); setFormMsg(null) } }, '取消')
),
h('div', { style: s.small }, '前提:这台手机的私钥已经装到目标服务器的 ~/.ssh/authorized_keys(免密能进)。密码登录不支持。')
)
)
}
return h('div', { style: s.mask, onMouseDown: (e) => { if (e.target === e.currentTarget) onClose() } },
h('div', { style: s.panel, role: 'dialog', 'aria-label': '服务器' },
header,
!online && !loading && h('div', { style: s.err },
view.error || '无法连接到服务器',
h('div', { style: { ...s.small, marginTop: 6 } }, '检查一下:服务器是否开机、SSH 端口是否放行、私钥是否配对。'),
h('div', { style: { ...s.actions, marginTop: 10 } },
h('button', { style: s.prim, onClick: () => connect(serverId) }, '重试'),
h('button', { style: s.ghost, onClick: () => { setAddOpen(true); setFormMsg(null) } }, '+ 添加服务器'),
servers.length > 1 && h('button', { style: s.ghost, onClick: removeServer }, '删除这台')
)
),
online && h(React.Fragment, null,
h('div', { style: s.cards },
h('div', { style: s.card },
h('div', { style: s.cardLabel }, '内存'),
h('div', { style: s.cardValue }, view.memText),
h(Fill, { pct: view.mem?.pct || 0 })
),
h('div', { style: s.card },
h('div', { style: s.cardLabel }, '磁盘'),
h('div', { style: s.cardValue }, view.diskText),
h(Fill, { pct: view.disk?.pct || 0 })
),
h('div', { style: s.card },
h('div', { style: s.cardLabel }, '负载'),
h('div', { style: s.cardValue }, (view.load || '-').split(' ')[0]),
h('div', { style: { ...s.small, marginTop: 6 } }, `${view.cores || 1} 核 · ${view.giteaVersion ? `Gitea ${view.giteaVersion}` : ''}`)
)
),
h('div', { style: s.chips }, Object.entries(view.services || {}).map(([name, state]) =>
h('span', { key: name, style: s.chip(state === 'active') },
h('span', { style: s.svcDot(state === 'active') }),
`${name} · ${state === 'active' ? '运行中' : '未运行'}`
)))
),
online && h('div', { style: s.actions },
h('button', { style: s.prim, onClick: () => connect(serverId), disabled: loading }, loading ? '刷新中…' : '刷新状态'),
h('button', { style: s.ghost, onClick: showLogs, disabled: logBusy }, logBusy ? '读取日志…' : '看 Gitea 日志'),
h('button', { style: s.ghost, onClick: restartGitea, disabled: Boolean(busyAction) }, busyAction === '重启 Gitea' ? '重启中…' : '重启 Gitea'),
h('button', { style: s.ghost, onClick: openGitea }, '打开 Gitea 网页')
),
logs && h('div', null,
logs.ok
? h('pre', { style: s.pre }, logs.text || '(没有日志)')
: h('div', { style: s.err }, logs.error || '读不到日志')
),
run && h('div', null,
h('div', { style: { ...s.small, marginBottom: 6 } }, `${run.label}:${run.ok ? '成功' : '失败'}${run.ms ? ` · ${run.ms} ms` : ''}`),
run.stdout && h('pre', { style: s.pre }, run.stdout),
run.stderr && h('pre', { style: { ...s.pre, color: '#ffb4be' } }, run.stderr)
),
h('div', { style: s.adv },
h('button', { style: { ...s.ghost, alignSelf: 'flex-start' }, onClick: () => setAdvanced(!advanced) },
advanced ? '收起高级(自己敲命令)' : '高级:自己敲一条命令'),
advanced && h('div', { style: { display: 'flex', gap: 8 } },
h('input', {
style: s.input, placeholder: '例如 df -h 或 systemctl status gitea', value: cmd, spellCheck: false,
onChange: (e) => setCmd(e.target.value),
onKeyDown: (e) => { if (e.key === 'Enter' && cmd.trim()) act(cmd.trim(), cmd.trim()) }
}),
h('button', { style: s.prim, onClick: () => cmd.trim() && act(cmd.trim(), cmd.trim()), disabled: Boolean(busyAction) }, '执行')
),
online && servers.length > 1 && h('button', { style: { ...s.ghost, alignSelf: 'flex-start' }, onClick: removeServer }, '删除这台服务器'),
h('div', { style: s.small }, '命令以服务器上的登录用户执行。接口只接受本机同源请求。')
)
)
)
}
function Trigger() {
const [open, setOpen] = React.useState(false)
return h(React.Fragment, null,
h('div', {
style: { position: 'fixed', right: 14, bottom: 92, zIndex: 8000, pointerEvents: 'auto' }
},
h('button', {
style: {
display: 'inline-flex', alignItems: 'center', gap: 7, height: 34, padding: '0 14px',
borderRadius: 999, border: '1px solid rgba(91,140,255,.5)',
background: 'linear-gradient(180deg, rgba(91,140,255,.30), rgba(91,140,255,.18))',
color: '#eef3ff', fontSize: 13, fontWeight: 600, cursor: 'pointer',
boxShadow: '0 8px 24px rgba(0,0,0,.35), inset 0 1px 0 rgba(255,255,255,.12)',
backdropFilter: 'blur(8px)'
},
onClick: () => setOpen(true),
title: '连接服务器(也可以直接输入 /server)'
},
h('span', { style: { width: 7, height: 7, borderRadius: 4, background: GOOD, boxShadow: '0 0 0 3px rgba(56,211,159,.20)' } }),
'服务器'
)
),
open && h(Panel, { onClose: () => setOpen(false) })
)
}
return {
inject: ['slots'],
apply(ctx) {
ctx.slots.inject('shell.overlay', () => ctx.slots.register({
name: 'shell.overlay',
id: 'dsh-server-manager-fab',
order: 40
}, Trigger))
}
}
}
})