|
|
const byId = (id) => document.getElementById(id);
|
|
|
const REINSTALL_JOB_STORAGE_PREFIX = "virsh-panel:reinstall-job:";
|
|
|
const UPDATE_REPOSITORY_URL = "https://g.luoli.live/root/virt.git";
|
|
|
const UPDATE_BRANCH = "main";
|
|
|
|
|
|
const state = {
|
|
|
csrfToken: "",
|
|
|
username: "",
|
|
|
vms: [],
|
|
|
resources: null,
|
|
|
templateLoad: null,
|
|
|
templateImportJobId: null,
|
|
|
loadingVMs: false,
|
|
|
pollTimer: null,
|
|
|
activeModal: null,
|
|
|
lastFocus: null,
|
|
|
deleteTarget: null,
|
|
|
confirmTarget: null,
|
|
|
reinstallTarget: null,
|
|
|
reinstallJobId: null,
|
|
|
reinstallInProgress: false,
|
|
|
reinstallExpectGeneratedPassword: false,
|
|
|
reinstallPasswordPendingAck: false,
|
|
|
reinstallPollToken: 0,
|
|
|
rfb: null,
|
|
|
consoleToken: 0,
|
|
|
hostConfig: null,
|
|
|
scannedHost: null,
|
|
|
uploadedPrivateKey: "",
|
|
|
updateSettings: null,
|
|
|
updateCheck: null,
|
|
|
updateJobId: null,
|
|
|
updateLastShownJobId: null,
|
|
|
updatePollToken: 0,
|
|
|
updateReturnView: null,
|
|
|
};
|
|
|
|
|
|
function text(id, value) {
|
|
|
byId(id).textContent = value;
|
|
|
}
|
|
|
|
|
|
function showError(id, message) {
|
|
|
const element = byId(id);
|
|
|
element.textContent = message;
|
|
|
element.hidden = !message;
|
|
|
}
|
|
|
|
|
|
function resourceWarnings(payload) {
|
|
|
if (Array.isArray(payload?.warnings)) return payload.warnings.filter((item) => typeof item === "string" && item.trim());
|
|
|
return typeof payload?.resource_warning === "string" && payload.resource_warning.trim() ? [payload.resource_warning] : [];
|
|
|
}
|
|
|
|
|
|
function showResourceWarning(message) {
|
|
|
const element = byId("resource-warning");
|
|
|
element.textContent = message;
|
|
|
element.hidden = !message;
|
|
|
}
|
|
|
|
|
|
function toast(message, kind = "info") {
|
|
|
const item = document.createElement("div");
|
|
|
item.className = `toast ${kind}`;
|
|
|
item.textContent = message;
|
|
|
byId("toast-region").append(item);
|
|
|
window.setTimeout(() => item.remove(), 5000);
|
|
|
}
|
|
|
|
|
|
function errorMessage(payload, fallback) {
|
|
|
if (typeof payload?.error === "string") return payload.error;
|
|
|
if (typeof payload?.message === "string") return payload.message;
|
|
|
if (typeof payload?.detail === "string") return payload.detail;
|
|
|
return fallback;
|
|
|
}
|
|
|
|
|
|
async function api(path, options = {}) {
|
|
|
const method = options.method || "GET";
|
|
|
const headers = { Accept: "application/json" };
|
|
|
if (options.body !== undefined) headers["Content-Type"] = "application/json";
|
|
|
if (((method !== "GET" && method !== "HEAD" && options.csrf !== false) || options.csrf === true) && state.csrfToken) {
|
|
|
headers["X-CSRF-Token"] = state.csrfToken;
|
|
|
}
|
|
|
|
|
|
let response;
|
|
|
try {
|
|
|
response = await fetch(path, {
|
|
|
method,
|
|
|
headers,
|
|
|
credentials: "same-origin",
|
|
|
cache: "no-store",
|
|
|
body: options.body === undefined ? undefined : JSON.stringify(options.body),
|
|
|
});
|
|
|
} catch {
|
|
|
throw new Error("无法连接面板服务,请检查网络或稍后重试。");
|
|
|
}
|
|
|
|
|
|
let payload = null;
|
|
|
if (response.status !== 204) {
|
|
|
try { payload = await response.json(); } catch { /* A failed HTTP response may not be JSON. */ }
|
|
|
}
|
|
|
if (response.status === 401 && path !== "/api/v1/login" && path !== "/api/v1/session" && !path.startsWith("/api/v1/setup/") && !path.startsWith("/api/v1/database/")) {
|
|
|
showLogin();
|
|
|
throw new Error("登录已过期,请重新登录。");
|
|
|
}
|
|
|
if (response.status === 423 && payload?.error_code === "key_locked" && path !== "/api/v1/host/unlock") {
|
|
|
showUnlockView({ ...state.hostConfig, configured: true, key_locked: true });
|
|
|
throw new Error("宿主机私钥已锁定,请输入私钥口令解锁。");
|
|
|
}
|
|
|
if (!response.ok) {
|
|
|
const error = new Error(errorMessage(payload, `请求失败(HTTP ${response.status})`));
|
|
|
error.status = response.status;
|
|
|
throw error;
|
|
|
}
|
|
|
return payload;
|
|
|
}
|
|
|
|
|
|
function stopPolling() {
|
|
|
if (state.pollTimer) window.clearInterval(state.pollTimer);
|
|
|
state.pollTimer = null;
|
|
|
}
|
|
|
|
|
|
function showLogin() {
|
|
|
stopPolling();
|
|
|
closeModal();
|
|
|
state.updatePollToken += 1;
|
|
|
state.updateJobId = null;
|
|
|
state.updateLastShownJobId = null;
|
|
|
state.updateCheck = null;
|
|
|
state.updateSettings = null;
|
|
|
state.updateReturnView = null;
|
|
|
state.csrfToken = "";
|
|
|
state.vms = [];
|
|
|
clearHostPrivateKey();
|
|
|
byId("unlock-passphrase").value = "";
|
|
|
byId("update-access-token").value = "";
|
|
|
byId("boot-screen").hidden = true;
|
|
|
byId("database-view").hidden = true;
|
|
|
byId("setup-view").hidden = true;
|
|
|
byId("host-view").hidden = true;
|
|
|
byId("unlock-view").hidden = true;
|
|
|
byId("dashboard-view").hidden = true;
|
|
|
byId("login-view").hidden = false;
|
|
|
}
|
|
|
|
|
|
function showDatabaseView() {
|
|
|
stopPolling();
|
|
|
closeModal();
|
|
|
byId("boot-screen").hidden = true;
|
|
|
byId("setup-view").hidden = true;
|
|
|
byId("login-view").hidden = true;
|
|
|
byId("host-view").hidden = true;
|
|
|
byId("unlock-view").hidden = true;
|
|
|
byId("dashboard-view").hidden = true;
|
|
|
byId("database-view").hidden = false;
|
|
|
}
|
|
|
|
|
|
function showSetup() {
|
|
|
stopPolling();
|
|
|
closeModal();
|
|
|
byId("unlock-passphrase").value = "";
|
|
|
byId("boot-screen").hidden = true;
|
|
|
byId("database-view").hidden = true;
|
|
|
byId("login-view").hidden = true;
|
|
|
byId("host-view").hidden = true;
|
|
|
byId("unlock-view").hidden = true;
|
|
|
byId("dashboard-view").hidden = true;
|
|
|
byId("setup-view").hidden = false;
|
|
|
}
|
|
|
|
|
|
function clearHostPrivateKey() {
|
|
|
state.uploadedPrivateKey = "";
|
|
|
byId("host-private-key").value = "";
|
|
|
byId("host-private-key-file").value = "";
|
|
|
byId("host-private-key-passphrase").value = "";
|
|
|
text("host-key-file-label", "未选择文件;已保存的密钥不会在这里显示。");
|
|
|
}
|
|
|
|
|
|
function showUnlockView(hostConfig) {
|
|
|
stopPolling();
|
|
|
closeModal();
|
|
|
state.hostConfig = hostConfig;
|
|
|
clearHostPrivateKey();
|
|
|
byId("unlock-passphrase").value = "";
|
|
|
showError("unlock-error", "");
|
|
|
text("unlock-current-user", state.username || "管理员");
|
|
|
text("unlock-host-label", hostConfig?.host ? `${hostConfig.host}:${hostConfig.port || 22}` : "当前宿主机");
|
|
|
byId("boot-screen").hidden = true;
|
|
|
byId("database-view").hidden = true;
|
|
|
byId("setup-view").hidden = true;
|
|
|
byId("login-view").hidden = true;
|
|
|
byId("host-view").hidden = true;
|
|
|
byId("dashboard-view").hidden = true;
|
|
|
byId("unlock-view").hidden = false;
|
|
|
}
|
|
|
|
|
|
function resetFingerprint() {
|
|
|
state.scannedHost = null;
|
|
|
byId("host-fingerprint-result").hidden = true;
|
|
|
byId("host-confirm-row").hidden = true;
|
|
|
byId("host-fingerprint-confirm").checked = false;
|
|
|
text("host-test-status", "主机地址或端口已变更,请重新扫描并核对指纹。");
|
|
|
byId("host-test-status").classList.remove("success", "warning");
|
|
|
}
|
|
|
|
|
|
function markHostTestStale() {
|
|
|
if (byId("host-test-status").classList.contains("success") || byId("host-test-status").classList.contains("warning")) {
|
|
|
text("host-test-status", "配置已变更;保存时会重新测试连接。");
|
|
|
byId("host-test-status").classList.remove("success", "warning");
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function showHostView(hostConfig = { configured: false }) {
|
|
|
stopPolling();
|
|
|
closeModal();
|
|
|
state.hostConfig = hostConfig;
|
|
|
clearHostPrivateKey();
|
|
|
byId("unlock-passphrase").value = "";
|
|
|
state.scannedHost = null;
|
|
|
byId("host-fingerprint-result").hidden = true;
|
|
|
byId("host-confirm-row").hidden = true;
|
|
|
byId("host-fingerprint-confirm").checked = false;
|
|
|
showError("host-error", "");
|
|
|
text("host-current-user", state.username || "管理员");
|
|
|
const configured = Boolean(hostConfig.configured);
|
|
|
text("host-step-label", configured ? "HOST SETTINGS" : "步骤 03 / 03");
|
|
|
text("host-page-title", configured ? "宿主机设置" : "连接 libvirt 宿主机");
|
|
|
text("host-save-button", configured ? "保存修改" : "保存并进入面板");
|
|
|
byId("host-back-button").hidden = !configured;
|
|
|
byId("host-address").value = configured ? (hostConfig.host || "") : "";
|
|
|
byId("host-port").value = configured ? (hostConfig.port || 22) : 22;
|
|
|
byId("host-storage-pool").value = configured ? (hostConfig.storage_pool || "default") : "default";
|
|
|
byId("host-iso-pool").value = configured ? (hostConfig.iso_pool || "iso") : "iso";
|
|
|
byId("host-network").value = configured ? (hostConfig.default_network || "default") : "default";
|
|
|
text("host-key-required-mark", configured ? "" : "*");
|
|
|
text("host-key-hint", configured
|
|
|
? "留空则继续使用已保存的私钥;填写或选择文件会替换它。已保存私钥不会回显。"
|
|
|
: "仅通过 HTTPS 传输并保存在面板服务器。请确保这把密钥已在宿主机 root 账号上获得授权。");
|
|
|
text("host-test-status", configured
|
|
|
? `当前已保存 ${hostConfig.host}:${hostConfig.port},修改前请重新扫描并核对主机指纹。`
|
|
|
: "尚未测试连接");
|
|
|
byId("host-test-status").classList.remove("success", "warning");
|
|
|
byId("boot-screen").hidden = true;
|
|
|
byId("database-view").hidden = true;
|
|
|
byId("setup-view").hidden = true;
|
|
|
byId("login-view").hidden = true;
|
|
|
byId("unlock-view").hidden = true;
|
|
|
byId("dashboard-view").hidden = true;
|
|
|
byId("host-view").hidden = false;
|
|
|
}
|
|
|
|
|
|
async function showDashboard(session) {
|
|
|
state.updateReturnView = null;
|
|
|
state.csrfToken = session.csrf_token || "";
|
|
|
state.username = session.username || "管理员";
|
|
|
text("current-username", state.username);
|
|
|
byId("login-view").hidden = true;
|
|
|
byId("database-view").hidden = true;
|
|
|
byId("setup-view").hidden = true;
|
|
|
byId("host-view").hidden = true;
|
|
|
byId("unlock-view").hidden = true;
|
|
|
byId("boot-screen").hidden = true;
|
|
|
byId("dashboard-view").hidden = false;
|
|
|
showVmWorkspace();
|
|
|
await Promise.allSettled([loadVMs(), loadResources()]);
|
|
|
if (byId("dashboard-view").hidden) return;
|
|
|
resumeReinstallJob();
|
|
|
stopPolling();
|
|
|
state.pollTimer = window.setInterval(() => {
|
|
|
if (!document.hidden) void loadVMs(true);
|
|
|
}, 15000);
|
|
|
}
|
|
|
|
|
|
async function continueAfterLogin(session) {
|
|
|
state.csrfToken = session.csrf_token || "";
|
|
|
state.username = session.username || "管理员";
|
|
|
const hostConfig = await api("/api/v1/host");
|
|
|
state.hostConfig = hostConfig || { configured: false };
|
|
|
if (hostConfig?.configured && hostConfig?.key_locked) showUnlockView(hostConfig);
|
|
|
else if (hostConfig?.configured) await showDashboard(session);
|
|
|
else showHostView(hostConfig || { configured: false });
|
|
|
}
|
|
|
|
|
|
async function initialize() {
|
|
|
try {
|
|
|
const database = await api("/api/v1/database/status");
|
|
|
if (database?.setup_required) { showDatabaseView(); return; }
|
|
|
const setup = await api("/api/v1/setup/status");
|
|
|
if (setup?.setup_required) { showSetup(); return; }
|
|
|
const session = await api("/api/v1/session");
|
|
|
if (session?.authenticated) await continueAfterLogin(session);
|
|
|
else showLogin();
|
|
|
} catch (error) {
|
|
|
showLogin();
|
|
|
showError("login-error", error.message);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function showVmWorkspace() {
|
|
|
byId("vm-workspace").hidden = false;
|
|
|
byId("update-workspace").hidden = true;
|
|
|
byId("vm-navigation-button").classList.add("active");
|
|
|
byId("vm-navigation-button").setAttribute("aria-current", "page");
|
|
|
byId("update-settings-button").classList.remove("active");
|
|
|
byId("update-settings-button").removeAttribute("aria-current");
|
|
|
text("breadcrumb-current", "虚拟机");
|
|
|
}
|
|
|
|
|
|
function openUpdateFromGate(returnView) {
|
|
|
if (returnView === "host") {
|
|
|
const hasKeyInput = Boolean(byId("host-private-key").value || state.uploadedPrivateKey || byId("host-private-key-passphrase").value);
|
|
|
if (hasKeyInput && !window.confirm("切换到网站更新会清空尚未保存的 SSH 私钥与口令输入。确定继续吗?")) return;
|
|
|
clearHostPrivateKey();
|
|
|
} else if (returnView === "unlock") {
|
|
|
byId("unlock-passphrase").value = "";
|
|
|
}
|
|
|
state.updateReturnView = returnView;
|
|
|
text("current-username", state.username || "管理员");
|
|
|
byId("host-view").hidden = true;
|
|
|
byId("unlock-view").hidden = true;
|
|
|
byId("dashboard-view").hidden = false;
|
|
|
void showUpdateWorkspace();
|
|
|
}
|
|
|
|
|
|
function leaveUpdateWorkspace() {
|
|
|
byId("update-access-token").value = "";
|
|
|
const returnView = state.updateReturnView;
|
|
|
if (returnView === "host" || returnView === "unlock") {
|
|
|
state.updateReturnView = null;
|
|
|
byId("dashboard-view").hidden = true;
|
|
|
byId("host-view").hidden = returnView !== "host";
|
|
|
byId("unlock-view").hidden = returnView !== "unlock";
|
|
|
return;
|
|
|
}
|
|
|
showVmWorkspace();
|
|
|
}
|
|
|
|
|
|
async function showUpdateWorkspace() {
|
|
|
byId("vm-workspace").hidden = true;
|
|
|
byId("update-workspace").hidden = false;
|
|
|
byId("vm-navigation-button").classList.remove("active");
|
|
|
byId("vm-navigation-button").removeAttribute("aria-current");
|
|
|
byId("update-settings-button").classList.add("active");
|
|
|
byId("update-settings-button").setAttribute("aria-current", "page");
|
|
|
text("breadcrumb-current", "网站更新");
|
|
|
showError("update-settings-error", "");
|
|
|
if (!state.updateLastShownJobId && !state.updateJobId) showError("update-action-error", "");
|
|
|
try {
|
|
|
await loadUpdateSettings();
|
|
|
} catch (error) {
|
|
|
showError("update-settings-error", `无法读取更新设置:${error.message}`);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async function loadUpdateSettings() {
|
|
|
const settings = await api("/api/v1/update/settings");
|
|
|
state.updateCheck = null;
|
|
|
state.updateSettings = { configured: Boolean(settings?.configured), token_configured: Boolean(settings?.token_configured) };
|
|
|
byId("update-repository-url").value = UPDATE_REPOSITORY_URL;
|
|
|
byId("update-branch").value = UPDATE_BRANCH;
|
|
|
byId("update-access-token").value = "";
|
|
|
text("update-token-hint", settings?.token_configured
|
|
|
? "访问令牌已保存;留空则继续使用现有令牌。令牌不会在页面回显。"
|
|
|
: "填写具有仓库读取权限的令牌。保存后不会回显,也不会写入浏览器存储。");
|
|
|
if (settings?.current_version) text("update-current-version", settings.current_version);
|
|
|
byId("update-check-button").disabled = !settings?.configured || Boolean(settings?.active_job_id);
|
|
|
byId("update-apply-button").disabled = true;
|
|
|
if (settings?.checkout_error) text("update-status", settings.checkout_error);
|
|
|
else if (!settings?.token_configured) text("update-status", "请先保存私有仓库访问令牌,再检查更新。");
|
|
|
const activeJobId = settings?.active_job_id;
|
|
|
if (activeJobId && activeJobId !== state.updateJobId) {
|
|
|
state.updateJobId = activeJobId;
|
|
|
void pollUpdateJob(activeJobId, ++state.updatePollToken);
|
|
|
return;
|
|
|
}
|
|
|
if (activeJobId) return;
|
|
|
const lastJobId = settings?.last_job_id;
|
|
|
if (lastJobId && lastJobId !== state.updateLastShownJobId) {
|
|
|
try {
|
|
|
const job = await api(`/api/v1/update/jobs/${encodeURIComponent(lastJobId)}`);
|
|
|
const status = String(job?.status || "");
|
|
|
if (status === "succeeded" || status === "completed") {
|
|
|
state.updateLastShownJobId = lastJobId;
|
|
|
state.updateJobId = null;
|
|
|
state.updatePollToken += 1;
|
|
|
if (job?.new_commit) text("update-current-version", job.new_commit);
|
|
|
showError("update-action-error", "");
|
|
|
text("update-status", "上次面板更新已完成。请确认虚拟机与宿主机连接正常。");
|
|
|
} else if (status === "failed") {
|
|
|
state.updateLastShownJobId = lastJobId;
|
|
|
state.updateJobId = null;
|
|
|
state.updatePollToken += 1;
|
|
|
text("update-status", "上次面板更新未完成。");
|
|
|
showError("update-action-error", String(job?.error || job?.message || "请检查独立更新服务日志。"));
|
|
|
} else if (status === "queued" || status === "running") {
|
|
|
state.updateJobId = lastJobId;
|
|
|
void pollUpdateJob(lastJobId, ++state.updatePollToken);
|
|
|
}
|
|
|
} catch (error) {
|
|
|
showError("update-action-error", `无法读取上次更新结果:${error.message}`);
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async function pollUpdateJob(jobId, token) {
|
|
|
let errors = 0;
|
|
|
for (let attempt = 0; attempt < 420; attempt += 1) {
|
|
|
if (token !== state.updatePollToken) return;
|
|
|
try {
|
|
|
const job = await api(`/api/v1/update/jobs/${encodeURIComponent(jobId)}`);
|
|
|
if (token !== state.updatePollToken) return;
|
|
|
errors = 0;
|
|
|
const status = String(job?.status || "running");
|
|
|
const phase = String(job?.phase || job?.message || "正在更新面板文件…");
|
|
|
text("update-status", `更新任务:${phase}`);
|
|
|
if (status === "succeeded" || status === "completed") {
|
|
|
text("update-status", "面板更新已完成。请刷新页面,并确认虚拟机与宿主机连接正常。");
|
|
|
state.updateJobId = null;
|
|
|
state.updateLastShownJobId = jobId;
|
|
|
byId("update-check-button").disabled = false;
|
|
|
toast("面板更新已完成。", "success");
|
|
|
return;
|
|
|
}
|
|
|
if (status === "failed") {
|
|
|
const message = String(job?.error || job?.message || "更新失败,请检查面板日志。");
|
|
|
text("update-status", "更新未完成。");
|
|
|
showError("update-action-error", message);
|
|
|
state.updateJobId = null;
|
|
|
state.updateLastShownJobId = jobId;
|
|
|
byId("update-check-button").disabled = false;
|
|
|
return;
|
|
|
}
|
|
|
} catch (error) {
|
|
|
if (token !== state.updatePollToken) return;
|
|
|
errors += 1;
|
|
|
text("update-status", `面板暂时无法响应(第 ${errors} 次),可能正在重启;将继续查询同一更新任务。`);
|
|
|
}
|
|
|
await new Promise((resolve) => window.setTimeout(resolve, 5000));
|
|
|
}
|
|
|
if (token === state.updatePollToken) {
|
|
|
text("update-status", "暂时无法确认更新结果。请检查服务状态和日志,不要重复点击更新。");
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function setButtonBusy(button, busy, busyLabel = "处理中…") {
|
|
|
if (busy) {
|
|
|
button.dataset.originalLabel = button.textContent;
|
|
|
button.textContent = busyLabel;
|
|
|
button.disabled = true;
|
|
|
} else {
|
|
|
button.textContent = button.dataset.originalLabel || button.textContent;
|
|
|
button.disabled = false;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function saveReinstallJob(jobId) {
|
|
|
try {
|
|
|
sessionStorage.setItem(`${REINSTALL_JOB_STORAGE_PREFIX}${state.username}`, JSON.stringify({
|
|
|
job_id: jobId,
|
|
|
username: state.username,
|
|
|
expect_generated_password: state.reinstallExpectGeneratedPassword,
|
|
|
}));
|
|
|
} catch { /* Private browsing may disable session storage; the open page still tracks this job. */ }
|
|
|
}
|
|
|
|
|
|
function clearSavedReinstallJob() {
|
|
|
try { sessionStorage.removeItem(`${REINSTALL_JOB_STORAGE_PREFIX}${state.username}`); } catch { /* Storage is optional. */ }
|
|
|
}
|
|
|
|
|
|
function readSavedReinstallJob() {
|
|
|
try {
|
|
|
const record = JSON.parse(sessionStorage.getItem(`${REINSTALL_JOB_STORAGE_PREFIX}${state.username}`) || "null");
|
|
|
if (!record || record.username !== state.username || !/^[0-9a-f-]{36}$/.test(record.job_id)) return null;
|
|
|
return record;
|
|
|
} catch { return null; }
|
|
|
}
|
|
|
|
|
|
function setConnection(connected) {
|
|
|
text("host-connection-label", connected ? "连接正常" : "连接失败");
|
|
|
byId("host-connection-dot").classList.toggle("offline", !connected);
|
|
|
}
|
|
|
|
|
|
function hostCoordinates() {
|
|
|
return {
|
|
|
host: byId("host-address").value.trim(),
|
|
|
port: Number(byId("host-port").value),
|
|
|
};
|
|
|
}
|
|
|
|
|
|
function requireSecureCredentialTransport() {
|
|
|
if (location.protocol === "https:") return;
|
|
|
throw new Error("不能通过明文 HTTP 提交密码或 root 私钥。请通过你配置的 HTTPS 反向代理访问面板。");
|
|
|
}
|
|
|
|
|
|
function hostPayload() {
|
|
|
if (!byId("host-form").reportValidity()) return null;
|
|
|
const { host, port } = hostCoordinates();
|
|
|
const scan = state.scannedHost;
|
|
|
if (!scan || scan.host !== host || Number(scan.port) !== port || !byId("host-fingerprint-confirm").checked) {
|
|
|
throw new Error("请先扫描主机指纹,并在宿主机控制台独立核对后勾选确认。");
|
|
|
}
|
|
|
const privateKey = byId("host-private-key").value.trim() || state.uploadedPrivateKey.trim();
|
|
|
if (!privateKey && !state.hostConfig?.private_key_configured) {
|
|
|
throw new Error("首次连接需要提供宿主机 root 账号已有的 SSH 私钥。");
|
|
|
}
|
|
|
return {
|
|
|
host,
|
|
|
port,
|
|
|
private_key: privateKey,
|
|
|
private_key_passphrase: byId("host-private-key-passphrase").value,
|
|
|
host_key: scan.known_hosts_line,
|
|
|
confirmed_fingerprint: scan.fingerprint,
|
|
|
storage_pool: byId("host-storage-pool").value.trim(),
|
|
|
iso_pool: byId("host-iso-pool").value.trim(),
|
|
|
default_network: byId("host-network").value.trim(),
|
|
|
};
|
|
|
}
|
|
|
|
|
|
async function scanHost() {
|
|
|
showError("host-error", "");
|
|
|
const { host, port } = hostCoordinates();
|
|
|
if (!host || !Number.isInteger(port) || port < 1 || port > 65535) {
|
|
|
showError("host-error", "请先填写有效的宿主机地址和 SSH 端口。");
|
|
|
return;
|
|
|
}
|
|
|
resetFingerprint();
|
|
|
const button = byId("host-scan-button");
|
|
|
setButtonBusy(button, true, "扫描中…");
|
|
|
try {
|
|
|
const result = await api("/api/v1/host/scan", { method: "POST", body: { host, port } });
|
|
|
const current = hostCoordinates();
|
|
|
if (current.host !== host || current.port !== port) return;
|
|
|
if (!result?.fingerprint || !result?.known_hosts_line) throw new Error("扫描结果缺少主机公钥,请重试。");
|
|
|
state.scannedHost = { ...result, host, port };
|
|
|
text("host-key-type", result.key_type || "未知类型");
|
|
|
text("host-fingerprint", result.fingerprint);
|
|
|
byId("host-fingerprint-result").hidden = false;
|
|
|
byId("host-confirm-row").hidden = false;
|
|
|
text("host-test-status", "扫描完成。请在宿主机控制台独立核对指纹,再勾选确认。");
|
|
|
} catch (error) {
|
|
|
showError("host-error", `扫描失败:${error.message}`);
|
|
|
} finally {
|
|
|
setButtonBusy(button, false);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async function submitHost(save) {
|
|
|
showError("host-error", "");
|
|
|
const button = byId(save ? "host-save-button" : "host-test-button");
|
|
|
try {
|
|
|
requireSecureCredentialTransport();
|
|
|
const body = hostPayload();
|
|
|
if (!body) return;
|
|
|
setButtonBusy(button, true, save ? "保存并连接中…" : "测试连接中…");
|
|
|
const result = await api(save ? "/api/v1/host" : "/api/v1/host/test", {
|
|
|
method: save ? "PUT" : "POST", body,
|
|
|
});
|
|
|
const warnings = resourceWarnings(result);
|
|
|
if (save) {
|
|
|
if (!result?.configured) throw new Error("宿主机配置未确认保存,请检查后重试。");
|
|
|
state.hostConfig = result;
|
|
|
clearHostPrivateKey();
|
|
|
await showDashboard({ username: state.username, csrf_token: state.csrfToken });
|
|
|
if (warnings.length) {
|
|
|
const message = `宿主机已连接,但资源尚未就绪:${warnings.join(";")}`;
|
|
|
showResourceWarning(message);
|
|
|
toast(message);
|
|
|
} else {
|
|
|
toast("宿主机已连接,设置已保存。", "success");
|
|
|
}
|
|
|
} else {
|
|
|
if (warnings.length) {
|
|
|
text("host-test-status", `root SSH 和 libvirt 连接成功,但资源尚未就绪:${warnings.join(";")}。仍可保存宿主机配置。`);
|
|
|
byId("host-test-status").classList.add("warning");
|
|
|
byId("host-test-status").classList.remove("success");
|
|
|
} else {
|
|
|
text("host-test-status", body.default_network.startsWith("bridge:")
|
|
|
? "连接成功:root SSH、libvirt 和存储池可访问。现有网桥将在创建虚拟机时由宿主机验证;现在可以保存设置。"
|
|
|
: "连接成功:root SSH、libvirt、存储池和虚拟网络均可访问。现在可以保存设置。");
|
|
|
byId("host-test-status").classList.add("success");
|
|
|
byId("host-test-status").classList.remove("warning");
|
|
|
}
|
|
|
}
|
|
|
} catch (error) {
|
|
|
byId("host-private-key-passphrase").value = "";
|
|
|
text("host-test-status", "连接未完成,请检查错误信息。");
|
|
|
byId("host-test-status").classList.remove("success", "warning");
|
|
|
showError("host-error", error.message);
|
|
|
} finally {
|
|
|
setButtonBusy(button, false);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async function submitUnlock() {
|
|
|
showError("unlock-error", "");
|
|
|
const button = byId("unlock-submit");
|
|
|
try {
|
|
|
requireSecureCredentialTransport();
|
|
|
const passphrase = byId("unlock-passphrase").value;
|
|
|
if (!passphrase) throw new Error("请输入 SSH 私钥口令。");
|
|
|
setButtonBusy(button, true, "解锁中…");
|
|
|
const result = await api("/api/v1/host/unlock", {
|
|
|
method: "POST", body: { passphrase },
|
|
|
});
|
|
|
if (!result?.configured || result?.key_locked) throw new Error("私钥未解锁,请确认口令后重试。");
|
|
|
const hostConfig = await api("/api/v1/host");
|
|
|
if (!hostConfig?.configured || hostConfig?.key_locked) throw new Error("无法确认私钥已解锁,请重试。");
|
|
|
state.hostConfig = hostConfig;
|
|
|
await showDashboard({ username: state.username, csrf_token: state.csrfToken });
|
|
|
toast("宿主机私钥已解锁。", "success");
|
|
|
} catch (error) {
|
|
|
showError("unlock-error", error.message);
|
|
|
} finally {
|
|
|
byId("unlock-passphrase").value = "";
|
|
|
setButtonBusy(button, false);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async function loadVMs(silent = false) {
|
|
|
if (state.loadingVMs || byId("dashboard-view").hidden) return;
|
|
|
state.loadingVMs = true;
|
|
|
const refreshButton = byId("refresh-button");
|
|
|
refreshButton.disabled = true;
|
|
|
try {
|
|
|
const result = await api("/api/v1/vms");
|
|
|
state.vms = Array.isArray(result?.items) ? result.items : [];
|
|
|
setConnection(true);
|
|
|
renderVMs();
|
|
|
} catch (error) {
|
|
|
setConnection(false);
|
|
|
if (!silent && !byId("dashboard-view").hidden) toast(error.message, "error");
|
|
|
if (!state.vms.length) renderVMs(true);
|
|
|
} finally {
|
|
|
refreshButton.disabled = false;
|
|
|
state.loadingVMs = false;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function stateCategory(value) {
|
|
|
const normalized = String(value || "unknown").toLowerCase().replace(/[_\s-]+/g, "");
|
|
|
if (normalized === "running" || normalized === "blocked") return "running";
|
|
|
if (["shutoff", "stopped", "crashed"].includes(normalized)) return "stopped";
|
|
|
return "other";
|
|
|
}
|
|
|
|
|
|
function stateLabel(value) {
|
|
|
const normalized = String(value || "unknown").toLowerCase().replace(/[_\s-]+/g, "");
|
|
|
const labels = {
|
|
|
running: "运行中", blocked: "运行中", shutoff: "已关机", stopped: "已关机",
|
|
|
shutdown: "关机中", crashed: "已崩溃", paused: "已暂停", pmsuspended: "已挂起",
|
|
|
nostate: "未知", unknown: "未知",
|
|
|
};
|
|
|
return labels[normalized] || String(value || "未知");
|
|
|
}
|
|
|
|
|
|
function diskLabel(vm) {
|
|
|
if (Array.isArray(vm.disks)) {
|
|
|
if (!vm.disks.length) return "—";
|
|
|
const size = vm.disks.reduce((sum, disk) => sum + Number(disk.capacity_gib || disk.size_gib || 0), 0);
|
|
|
return size > 0 ? `${vm.disks.length} 块 · ${size} GiB` : `${vm.disks.length} 块磁盘`;
|
|
|
}
|
|
|
if (Number.isFinite(Number(vm.disk_gib)) && Number(vm.disk_gib) > 0) return `${vm.disk_gib} GiB`;
|
|
|
return "—";
|
|
|
}
|
|
|
|
|
|
function makeCell(row, className = "") {
|
|
|
const cell = document.createElement("td");
|
|
|
if (className) cell.className = className;
|
|
|
row.append(cell);
|
|
|
return cell;
|
|
|
}
|
|
|
|
|
|
function makeElement(tag, className, content) {
|
|
|
const element = document.createElement(tag);
|
|
|
if (className) element.className = className;
|
|
|
if (content !== undefined) element.textContent = String(content);
|
|
|
return element;
|
|
|
}
|
|
|
|
|
|
function actionButton(label, handler, options = {}) {
|
|
|
const button = makeElement("button", `row-button ${options.variant || ""}`, label);
|
|
|
button.type = "button";
|
|
|
button.disabled = Boolean(options.disabled);
|
|
|
if (options.title) button.title = options.title;
|
|
|
button.addEventListener("click", handler);
|
|
|
return button;
|
|
|
}
|
|
|
|
|
|
function renderVMs(connectionError = false) {
|
|
|
const all = state.vms;
|
|
|
const runningCount = all.filter((vm) => stateCategory(vm.state) === "running").length;
|
|
|
const stoppedCount = all.filter((vm) => stateCategory(vm.state) === "stopped").length;
|
|
|
text("stat-total", String(all.length));
|
|
|
text("stat-running", String(runningCount));
|
|
|
text("stat-stopped", String(stoppedCount));
|
|
|
|
|
|
const query = byId("search-input").value.trim().toLocaleLowerCase();
|
|
|
const filter = byId("state-filter").value;
|
|
|
const filtered = all.filter((vm) => {
|
|
|
const matchesText = !query || String(vm.name || "").toLocaleLowerCase().includes(query) || String(vm.uuid || "").toLocaleLowerCase().includes(query) || String(vm.public_ip_cidr || "").toLocaleLowerCase().includes(query);
|
|
|
return matchesText && (filter === "all" || stateCategory(vm.state) === filter);
|
|
|
});
|
|
|
text("inventory-count", `${filtered.length} 台虚拟机${filtered.length !== all.length ? ` · 共 ${all.length} 台` : ""}`);
|
|
|
const tbody = byId("vm-table-body");
|
|
|
tbody.replaceChildren();
|
|
|
const empty = byId("empty-state");
|
|
|
empty.hidden = filtered.length !== 0;
|
|
|
if (!filtered.length) {
|
|
|
if (connectionError) {
|
|
|
text("empty-title", "无法加载虚拟机");
|
|
|
text("empty-description", "请检查面板与宿主机的连接,然后点击刷新。");
|
|
|
} else if (all.length) {
|
|
|
text("empty-title", "没有匹配的虚拟机");
|
|
|
text("empty-description", "尝试更换搜索词或状态筛选。");
|
|
|
} else {
|
|
|
text("empty-title", "还没有虚拟机");
|
|
|
text("empty-description", "点击右上角“创建虚拟机”开始。");
|
|
|
}
|
|
|
return;
|
|
|
}
|
|
|
|
|
|
for (const vm of filtered) {
|
|
|
const uuid = String(vm.uuid || "");
|
|
|
const category = stateCategory(vm.state);
|
|
|
const running = category === "running";
|
|
|
const stopped = category === "stopped";
|
|
|
const row = document.createElement("tr");
|
|
|
const identity = makeElement("div", "vm-identity");
|
|
|
identity.append(makeElement("div", "vm-icon", "▣"));
|
|
|
const identityText = makeElement("div");
|
|
|
identityText.append(makeElement("span", "vm-name", vm.name || "未命名虚拟机"));
|
|
|
identityText.append(makeElement("span", "vm-id", uuid || "UUID 未知"));
|
|
|
if (vm.public_ip_cidr) identityText.append(makeElement("span", "vm-public-ip", `公网 ${vm.public_ip_cidr}`));
|
|
|
identity.append(identityText);
|
|
|
makeCell(row).append(identity);
|
|
|
|
|
|
makeCell(row).append(makeElement("span", `state-pill ${category}`, stateLabel(vm.state)));
|
|
|
const spec = makeElement("div", "vm-spec");
|
|
|
spec.append(makeElement("strong", "", `${vm.vcpu ?? "—"} vCPU · ${vm.memory_mib ?? "—"} MiB`));
|
|
|
spec.append(makeElement("small", "", "计算资源"));
|
|
|
makeCell(row).append(spec);
|
|
|
makeCell(row).append(makeElement("span", "vm-spec", diskLabel(vm)));
|
|
|
|
|
|
const actions = makeElement("div", "row-actions");
|
|
|
const hasConsole = Number(vm.console_port) > 0;
|
|
|
actions.append(actionButton("控制台", () => void openConsole(vm), {
|
|
|
disabled: !running || !uuid || !hasConsole,
|
|
|
variant: "primary",
|
|
|
title: !running ? "虚拟机运行时可用" : hasConsole ? "打开 VNC 控制台" : "该虚拟机未配置 VNC 控制台",
|
|
|
}));
|
|
|
if (running) {
|
|
|
actions.append(actionButton("关机", (event) => void runAction(vm, "shutdown", event.currentTarget)));
|
|
|
actions.append(actionButton("重启", (event) => void runAction(vm, "reboot", event.currentTarget)));
|
|
|
actions.append(actionButton("强制断电", () => openConfirm(vm, "poweroff"), { variant: "danger" }));
|
|
|
actions.append(actionButton("强制重置", () => openConfirm(vm, "reset"), { variant: "danger" }));
|
|
|
} else {
|
|
|
actions.append(actionButton("开机", (event) => void runAction(vm, "start", event.currentTarget), { disabled: !stopped || !uuid }));
|
|
|
}
|
|
|
if (vm.managed && vm.public_ip_cidr) {
|
|
|
actions.append(actionButton("重装", () => openReinstall(vm), {
|
|
|
disabled: !uuid,
|
|
|
variant: "danger",
|
|
|
title: "从云镜像模板重装,成功后自动删除旧系统盘",
|
|
|
}));
|
|
|
}
|
|
|
actions.append(actionButton("删除", () => openDelete(vm), { disabled: !stopped || !uuid, variant: "danger", title: stopped ? "删除虚拟机" : "请先关机再删除" }));
|
|
|
makeCell(row).append(actions);
|
|
|
tbody.append(row);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function resourceValue(item, kind) {
|
|
|
if (typeof item === "string") return item;
|
|
|
if (item && typeof item === "object") return String(kind === "iso" ? (item.path || item.name || "") : (item.name || item.id || ""));
|
|
|
return "";
|
|
|
}
|
|
|
|
|
|
function resourceLabel(item, kind) {
|
|
|
if (typeof item === "string") return kind === "iso" ? item.split("/").pop() : item;
|
|
|
if (item && typeof item === "object") return String(item.label || item.name || item.path || item.id || "");
|
|
|
return "";
|
|
|
}
|
|
|
|
|
|
function fillSelect(id, items, kind) {
|
|
|
const select = byId(id);
|
|
|
const previous = select.value;
|
|
|
select.replaceChildren();
|
|
|
const placeholder = document.createElement("option");
|
|
|
placeholder.value = "";
|
|
|
placeholder.textContent = items.length ? (kind === "iso" ? "选择安装镜像" : "选择虚拟网络或网桥") : (kind === "iso" ? "没有可用 ISO 镜像" : "没有可用虚拟网络或网桥");
|
|
|
select.append(placeholder);
|
|
|
for (const item of items) {
|
|
|
const value = resourceValue(item, kind);
|
|
|
if (!value) continue;
|
|
|
const option = document.createElement("option");
|
|
|
option.value = value;
|
|
|
option.textContent = resourceLabel(item, kind);
|
|
|
select.append(option);
|
|
|
}
|
|
|
if (previous && Array.from(select.options).some((option) => option.value === previous)) select.value = previous;
|
|
|
select.disabled = select.options.length <= 1;
|
|
|
}
|
|
|
|
|
|
async function loadResources() {
|
|
|
try {
|
|
|
const result = await api("/api/v1/resources");
|
|
|
state.resources = result || {};
|
|
|
fillSelect("vm-network", Array.isArray(result?.networks) ? result.networks : [], "network");
|
|
|
fillSelect("vm-iso", Array.isArray(result?.isos) ? result.isos : [], "iso");
|
|
|
updateCreateSource();
|
|
|
showResourceWarning("");
|
|
|
} catch (error) {
|
|
|
state.resources = null;
|
|
|
fillSelect("vm-network", [], "network");
|
|
|
fillSelect("vm-iso", [], "iso");
|
|
|
updateCreateSource();
|
|
|
showResourceWarning(`宿主机资源尚未就绪:${error.message}。请检查存储池和网络或网桥设置。`);
|
|
|
throw error;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function fillTemplateSelect(items, preferredId = "") {
|
|
|
const select = byId("vm-template");
|
|
|
const previous = preferredId || select.value;
|
|
|
select.replaceChildren();
|
|
|
const placeholder = document.createElement("option");
|
|
|
placeholder.value = "";
|
|
|
placeholder.textContent = items.length ? "选择云镜像模板" : "暂无模板,请先导入";
|
|
|
select.append(placeholder);
|
|
|
for (const item of items) {
|
|
|
const id = String(item?.id || "");
|
|
|
if (!id) continue;
|
|
|
const option = document.createElement("option");
|
|
|
option.value = id;
|
|
|
option.textContent = String(item.name || id);
|
|
|
select.append(option);
|
|
|
}
|
|
|
if (previous && Array.from(select.options).some((option) => option.value === previous)) select.value = previous;
|
|
|
select.disabled = selectedCreateSource() !== "cloud" || select.options.length <= 1;
|
|
|
if (!items.length) byId("template-import").open = true;
|
|
|
|
|
|
const reinstallSelect = byId("reinstall-template");
|
|
|
const reinstallPrevious = reinstallSelect.value;
|
|
|
reinstallSelect.replaceChildren();
|
|
|
const reinstallPlaceholder = document.createElement("option");
|
|
|
reinstallPlaceholder.value = "";
|
|
|
reinstallPlaceholder.textContent = items.length ? "选择重装模板" : "暂无模板,请先在创建虚拟机窗口导入";
|
|
|
reinstallSelect.append(reinstallPlaceholder);
|
|
|
for (const item of items) {
|
|
|
const id = String(item?.id || "");
|
|
|
if (!id) continue;
|
|
|
const option = document.createElement("option");
|
|
|
option.value = id;
|
|
|
option.textContent = String(item.name || id);
|
|
|
reinstallSelect.append(option);
|
|
|
}
|
|
|
if (reinstallPrevious && Array.from(reinstallSelect.options).some((option) => option.value === reinstallPrevious)) {
|
|
|
reinstallSelect.value = reinstallPrevious;
|
|
|
}
|
|
|
reinstallSelect.disabled = reinstallSelect.options.length <= 1;
|
|
|
}
|
|
|
|
|
|
async function loadTemplates(preferredId = "") {
|
|
|
if (state.templateLoad) await state.templateLoad;
|
|
|
const request = api("/api/v1/vm-templates");
|
|
|
state.templateLoad = request;
|
|
|
try {
|
|
|
const result = await request;
|
|
|
fillTemplateSelect(Array.isArray(result?.templates) ? result.templates : [], preferredId);
|
|
|
} finally {
|
|
|
if (state.templateLoad === request) state.templateLoad = null;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function showTemplateImportStatus(message) {
|
|
|
const element = byId("template-import-status");
|
|
|
element.textContent = message;
|
|
|
element.hidden = !message;
|
|
|
}
|
|
|
|
|
|
async function waitForTemplateImport(jobId) {
|
|
|
for (let attempt = 0; attempt < 360; attempt += 1) {
|
|
|
await new Promise((resolve) => window.setTimeout(resolve, 5000));
|
|
|
const job = await api(`/api/v1/vm-templates/import-jobs/${encodeURIComponent(jobId)}`);
|
|
|
if (job?.status === "completed") return job;
|
|
|
if (job?.status === "failed") {
|
|
|
state.templateImportJobId = null;
|
|
|
throw new Error(job.error || "模板导入失败,请核对下载地址和 SHA-256 校验值。");
|
|
|
}
|
|
|
if (job?.status !== "running") throw new Error("模板导入状态未知,请稍后重新查看。");
|
|
|
if (attempt % 6 === 5) {
|
|
|
const seconds = (attempt + 1) * 5;
|
|
|
showTemplateImportStatus(`宿主机正在后台导入镜像,已等待约 ${seconds < 60 ? `${seconds} 秒` : `${Math.floor(seconds / 60)} 分钟`}。关闭弹窗不会取消任务。`);
|
|
|
}
|
|
|
}
|
|
|
throw new Error("模板仍在后台导入。稍后重新打开创建窗口并查看导入状态。");
|
|
|
}
|
|
|
|
|
|
function selectedCreateSource() {
|
|
|
return document.querySelector('input[name="source"]:checked')?.value || "iso";
|
|
|
}
|
|
|
|
|
|
function updateCreateAuthMode() {
|
|
|
const cloud = selectedCreateSource() === "cloud";
|
|
|
const publicKey = byId("vm-guest-ssh-public-key");
|
|
|
const password = byId("vm-root-password");
|
|
|
const passwordMode = cloud && !publicKey.value.trim();
|
|
|
byId("vm-root-password-field").hidden = !passwordMode;
|
|
|
password.required = passwordMode;
|
|
|
password.disabled = !passwordMode;
|
|
|
if (!passwordMode) password.value = "";
|
|
|
}
|
|
|
|
|
|
function updateCreateSource() {
|
|
|
const cloud = selectedCreateSource() === "cloud";
|
|
|
byId("vm-iso-field").hidden = cloud;
|
|
|
byId("vm-template-field").hidden = !cloud;
|
|
|
byId("vm-cloud-fields").hidden = !cloud;
|
|
|
byId("create-iso-tip").hidden = cloud;
|
|
|
byId("create-cloud-tip").hidden = !cloud;
|
|
|
|
|
|
const iso = byId("vm-iso");
|
|
|
iso.required = !cloud;
|
|
|
iso.disabled = cloud || iso.options.length <= 1;
|
|
|
const template = byId("vm-template");
|
|
|
template.required = cloud;
|
|
|
template.disabled = !cloud || template.options.length <= 1;
|
|
|
["vm-public-ip-cidr", "vm-gateway", "vm-dns"].forEach((id) => {
|
|
|
const input = byId(id);
|
|
|
input.required = cloud;
|
|
|
input.disabled = !cloud;
|
|
|
});
|
|
|
const publicKey = byId("vm-guest-ssh-public-key");
|
|
|
publicKey.required = false;
|
|
|
publicKey.disabled = !cloud;
|
|
|
updateCreateAuthMode();
|
|
|
|
|
|
const network = byId("vm-network");
|
|
|
for (const option of network.options) {
|
|
|
option.disabled = cloud && !!option.value && !option.value.startsWith("bridge:");
|
|
|
}
|
|
|
if (cloud && network.value && !network.value.startsWith("bridge:")) network.value = "";
|
|
|
if (cloud && !network.value) {
|
|
|
const bridge = Array.from(network.options).find((option) => option.value.startsWith("bridge:"));
|
|
|
if (bridge) network.value = bridge.value;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function openModal(id) {
|
|
|
if (state.activeModal) closeModal();
|
|
|
state.lastFocus = document.activeElement;
|
|
|
state.activeModal = byId(id);
|
|
|
state.activeModal.hidden = false;
|
|
|
document.body.style.overflow = "hidden";
|
|
|
const focusTarget = state.activeModal.querySelector("input:not(:disabled),button:not(:disabled)");
|
|
|
window.requestAnimationFrame(() => focusTarget?.focus());
|
|
|
}
|
|
|
|
|
|
function closeModal() {
|
|
|
if (!state.activeModal) return;
|
|
|
if (state.activeModal.id === "console-modal") disconnectConsole();
|
|
|
if (state.activeModal.id === "create-modal") {
|
|
|
byId("vm-guest-ssh-public-key").value = "";
|
|
|
byId("vm-root-password").value = "";
|
|
|
}
|
|
|
if (state.activeModal.id === "reinstall-modal") {
|
|
|
state.reinstallPollToken += 1;
|
|
|
state.reinstallTarget = null;
|
|
|
state.reinstallJobId = null;
|
|
|
state.reinstallInProgress = false;
|
|
|
state.reinstallExpectGeneratedPassword = false;
|
|
|
state.reinstallPasswordPendingAck = false;
|
|
|
byId("reinstall-ssh-public-key").value = "";
|
|
|
byId("reinstall-root-password").value = "";
|
|
|
byId("reinstall-generated-password").textContent = "";
|
|
|
}
|
|
|
state.activeModal.hidden = true;
|
|
|
state.activeModal = null;
|
|
|
state.deleteTarget = null;
|
|
|
state.confirmTarget = null;
|
|
|
document.body.style.overflow = "";
|
|
|
state.lastFocus?.focus?.();
|
|
|
}
|
|
|
|
|
|
function openCreate() {
|
|
|
byId("create-form").reset();
|
|
|
byId("vm-root-password").value = "";
|
|
|
byId("template-import").open = !!state.templateImportJobId;
|
|
|
showTemplateImportStatus(state.templateImportJobId ? "宿主机仍在后台导入模板。查询会自动更新;若中断,可点击“导入模板”继续查看。" : "");
|
|
|
showError("template-import-error", "");
|
|
|
showError("create-error", "");
|
|
|
updateCreateSource();
|
|
|
openModal("create-modal");
|
|
|
if (!state.resources) {
|
|
|
void loadResources().catch((error) => showError("create-error", `无法加载宿主机资源:${error.message}`));
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function openDelete(vm) {
|
|
|
state.deleteTarget = vm;
|
|
|
text("delete-vm-name", vm.name || vm.uuid || "此虚拟机");
|
|
|
byId("delete-disks").checked = false;
|
|
|
showError("delete-error", "");
|
|
|
openModal("delete-modal");
|
|
|
state.deleteTarget = vm;
|
|
|
}
|
|
|
|
|
|
function openReinstall(vm) {
|
|
|
if (readSavedReinstallJob()) {
|
|
|
resumeReinstallJob();
|
|
|
toast("此标签页已有重装任务,已恢复任务状态;请不要重复提交。", "info");
|
|
|
return;
|
|
|
}
|
|
|
byId("reinstall-form").reset();
|
|
|
byId("reinstall-fields").hidden = false;
|
|
|
byId("reinstall-progress").hidden = true;
|
|
|
byId("reinstall-result").hidden = true;
|
|
|
byId("reinstall-password-box").hidden = true;
|
|
|
byId("reinstall-generated-password").textContent = "";
|
|
|
byId("reinstall-result-warning").hidden = true;
|
|
|
byId("reinstall-cancel").hidden = false;
|
|
|
byId("reinstall-submit").hidden = false;
|
|
|
byId("reinstall-forget").hidden = true;
|
|
|
byId("reinstall-retry").hidden = true;
|
|
|
byId("reinstall-done").hidden = true;
|
|
|
text("reinstall-done", "完成");
|
|
|
byId("reinstall-close-top").disabled = false;
|
|
|
showError("reinstall-error", "");
|
|
|
text("reinstall-subtitle", `${vm.name || vm.uuid} · 保留公网网络参数,重新创建系统盘。`);
|
|
|
text("reinstall-public-ip", String(vm.public_ip_cidr || "未知"));
|
|
|
text("reinstall-confirm-hint", `请准确输入“${vm.name || ""}”;这也是防止选错虚拟机的最后一道确认。`);
|
|
|
byId("reinstall-confirm-name").placeholder = vm.name || "请输入完整的虚拟机名称";
|
|
|
openModal("reinstall-modal");
|
|
|
state.reinstallTarget = vm;
|
|
|
void loadTemplates().catch((error) => showError("reinstall-error", `无法加载重装模板:${error.message}`));
|
|
|
}
|
|
|
|
|
|
function resumeReinstallJob() {
|
|
|
const saved = readSavedReinstallJob();
|
|
|
if (!saved || state.activeModal) return;
|
|
|
byId("reinstall-form").reset();
|
|
|
byId("reinstall-fields").hidden = true;
|
|
|
byId("reinstall-result").hidden = true;
|
|
|
byId("reinstall-progress").hidden = false;
|
|
|
byId("reinstall-cancel").hidden = true;
|
|
|
byId("reinstall-submit").hidden = true;
|
|
|
byId("reinstall-forget").hidden = true;
|
|
|
byId("reinstall-retry").hidden = true;
|
|
|
byId("reinstall-done").hidden = true;
|
|
|
byId("reinstall-generated-password").textContent = "";
|
|
|
byId("reinstall-password-box").hidden = true;
|
|
|
showError("reinstall-error", "");
|
|
|
text("reinstall-subtitle", "正在恢复此标签页中尚未确认的重装任务。");
|
|
|
text("reinstall-phase", "正在查询已有重装任务…");
|
|
|
openModal("reinstall-modal");
|
|
|
state.reinstallTarget = null;
|
|
|
state.reinstallJobId = saved.job_id;
|
|
|
state.reinstallExpectGeneratedPassword = Boolean(saved.expect_generated_password);
|
|
|
state.reinstallPasswordPendingAck = false;
|
|
|
state.reinstallInProgress = true;
|
|
|
byId("reinstall-close-top").disabled = true;
|
|
|
const token = ++state.reinstallPollToken;
|
|
|
void pollReinstallJob(saved.job_id, token);
|
|
|
}
|
|
|
|
|
|
function reinstallPhaseLabel(phase) {
|
|
|
const labels = {
|
|
|
queued: "等待执行…",
|
|
|
validating: "检查虚拟机、模板和原系统盘…",
|
|
|
shutting_down: "正在请求虚拟机正常关机…",
|
|
|
waiting_for_shutdown: "等待虚拟机完成正常关机…",
|
|
|
preparing: "正在准备新的系统盘和 cloud-init 配置…",
|
|
|
cloning: "正在复制云镜像模板到新系统盘…",
|
|
|
defining: "正在切换虚拟机系统盘…",
|
|
|
starting: "正在启动新系统…",
|
|
|
cleaning_up: "libvirt/QEMU 已报告启动,正在删除旧系统盘…",
|
|
|
};
|
|
|
return labels[phase] || (typeof phase === "string" && phase.trim() ? phase : "正在执行重装任务…");
|
|
|
}
|
|
|
|
|
|
function showReinstallResult(success, message, job = {}, terminal = true) {
|
|
|
state.reinstallInProgress = false;
|
|
|
const password = success && typeof job.generated_password === "string" ? job.generated_password : "";
|
|
|
state.reinstallPasswordPendingAck = Boolean(password);
|
|
|
if (terminal && !state.reinstallPasswordPendingAck) {
|
|
|
state.reinstallJobId = null;
|
|
|
clearSavedReinstallJob();
|
|
|
}
|
|
|
byId("reinstall-fields").hidden = true;
|
|
|
byId("reinstall-progress").hidden = true;
|
|
|
byId("reinstall-result").hidden = false;
|
|
|
byId("reinstall-cancel").hidden = true;
|
|
|
byId("reinstall-submit").hidden = true;
|
|
|
byId("reinstall-forget").hidden = true;
|
|
|
byId("reinstall-retry").hidden = terminal;
|
|
|
byId("reinstall-done").hidden = false;
|
|
|
text("reinstall-done", state.reinstallPasswordPendingAck ? "已保存密码,完成" : "完成");
|
|
|
byId("reinstall-close-top").disabled = state.reinstallPasswordPendingAck;
|
|
|
text("reinstall-result-title", success ? "重装任务已完成" : "重装任务未完成");
|
|
|
text("reinstall-result-message", message);
|
|
|
byId("reinstall-result").classList.toggle("failed", !success);
|
|
|
byId("reinstall-result").classList.remove("unknown");
|
|
|
byId("reinstall-generated-password").textContent = password;
|
|
|
byId("reinstall-password-box").hidden = !password;
|
|
|
const warnings = [];
|
|
|
if (typeof job.warning === "string" && job.warning) warnings.push(job.warning);
|
|
|
if (success && state.reinstallExpectGeneratedPassword && !password) {
|
|
|
warnings.push("未收到自动生成的 root 密码,请通过虚拟机控制台恢复 root 登录,并检查面板日志。");
|
|
|
}
|
|
|
const warning = warnings.join(" ");
|
|
|
text("reinstall-result-warning", warning);
|
|
|
byId("reinstall-result-warning").hidden = !warning;
|
|
|
showError("reinstall-error", "");
|
|
|
}
|
|
|
|
|
|
function showReinstallUnknown(message) {
|
|
|
showReinstallResult(false, message, {}, false);
|
|
|
text("reinstall-result-title", "重装任务状态未明");
|
|
|
byId("reinstall-result").classList.remove("failed");
|
|
|
byId("reinstall-result").classList.add("unknown");
|
|
|
byId("reinstall-done").hidden = true;
|
|
|
byId("reinstall-forget").hidden = false;
|
|
|
}
|
|
|
|
|
|
async function pollReinstallJob(jobId, token) {
|
|
|
let consecutiveErrors = 0;
|
|
|
for (let attempt = 0; attempt < 600; attempt += 1) {
|
|
|
if (state.reinstallPollToken !== token) return;
|
|
|
let job;
|
|
|
try {
|
|
|
job = await api(`/api/v1/reinstall-jobs/${encodeURIComponent(jobId)}`, { csrf: true });
|
|
|
consecutiveErrors = 0;
|
|
|
} catch (error) {
|
|
|
if (state.reinstallPollToken !== token) return;
|
|
|
if (error.status === 404) {
|
|
|
showReinstallUnknown("面板找不到此重装任务。面板进程可能已重启,内存中的任务和未确认密码可能已丢失。请检查虚拟机、旧盘和新盘状态,切勿直接再次重装;如有必要可在控制台恢复 root 登录。");
|
|
|
return;
|
|
|
}
|
|
|
consecutiveErrors += 1;
|
|
|
text("reinstall-phase", `暂时无法读取任务进度(第 ${consecutiveErrors} 次):${error.message}。面板仍会继续查询。`);
|
|
|
}
|
|
|
if (state.reinstallPollToken !== token) return;
|
|
|
if (job) {
|
|
|
if (job.status === "succeeded" || job.status === "completed") {
|
|
|
showReinstallResult(true, "libvirt/QEMU 已报告虚拟机从新系统盘启动,但尚不能证明客户机系统、网络或 SSH 正常。请通过控制台及 SSH 验证。公网网络参数沿用原配置。", job);
|
|
|
void loadVMs(true);
|
|
|
return;
|
|
|
}
|
|
|
if (job.status === "failed") {
|
|
|
showReinstallResult(false, String(job.error || "重装失败,请检查宿主机状态后再决定是否重试。"), job);
|
|
|
void loadVMs(true);
|
|
|
return;
|
|
|
}
|
|
|
text("reinstall-phase", reinstallPhaseLabel(job.phase || job.status));
|
|
|
}
|
|
|
await new Promise((resolve) => window.setTimeout(resolve, 3000));
|
|
|
}
|
|
|
if (state.reinstallPollToken === token) {
|
|
|
showReinstallUnknown("连续查询约 30 分钟仍未取得最终状态。任务可能仍在面板进程中运行;请点击“重新查询任务”,不要重新提交重装。若面板进程已重启,请先检查虚拟机、旧盘和新盘状态。");
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function openConfirm(vm, action) {
|
|
|
const label = action === "poweroff" ? "强制断电" : "强制重置";
|
|
|
text("confirm-title", label);
|
|
|
text("confirm-message", `确定对 ${vm.name || vm.uuid} 执行“${label}”吗?这可能导致虚拟机内未保存的数据丢失。`);
|
|
|
text("confirm-submit", label);
|
|
|
showError("confirm-error", "");
|
|
|
openModal("confirm-modal");
|
|
|
state.confirmTarget = { vm, action };
|
|
|
}
|
|
|
|
|
|
async function runAction(vm, action, button) {
|
|
|
const label = { start: "开机", shutdown: "关机", reboot: "重启", poweroff: "强制断电", reset: "强制重置" }[action] || action;
|
|
|
if (button) setButtonBusy(button, true);
|
|
|
try {
|
|
|
await api(`/api/v1/vms/${encodeURIComponent(vm.uuid)}/actions`, { method: "POST", body: { action } });
|
|
|
toast(`已向 ${vm.name || vm.uuid} 发送${label}指令。`, "success");
|
|
|
await loadVMs(true);
|
|
|
window.setTimeout(() => void loadVMs(true), 1200);
|
|
|
return true;
|
|
|
} catch (error) {
|
|
|
toast(`${label}失败:${error.message}`, "error");
|
|
|
return false;
|
|
|
} finally {
|
|
|
if (button?.isConnected) setButtonBusy(button, false);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function disconnectConsole() {
|
|
|
state.consoleToken += 1;
|
|
|
const rfb = state.rfb;
|
|
|
state.rfb = null;
|
|
|
if (rfb) {
|
|
|
try { rfb.disconnect(); } catch { /* Already disconnected. */ }
|
|
|
}
|
|
|
const stage = byId("console-stage");
|
|
|
const placeholder = byId("console-placeholder");
|
|
|
stage.replaceChildren(placeholder);
|
|
|
placeholder.hidden = false;
|
|
|
byId("console-password-form").hidden = true;
|
|
|
byId("console-cad").disabled = true;
|
|
|
}
|
|
|
|
|
|
async function openConsole(vm) {
|
|
|
openModal("console-modal");
|
|
|
text("console-title", `${vm.name || vm.uuid} · 控制台`);
|
|
|
text("console-status", "正在连接…");
|
|
|
const stage = byId("console-stage");
|
|
|
const placeholder = byId("console-placeholder");
|
|
|
placeholder.hidden = false;
|
|
|
const token = ++state.consoleToken;
|
|
|
try {
|
|
|
const { default: RFB } = await import("/vendor/novnc/core/rfb.js");
|
|
|
if (token !== state.consoleToken) return;
|
|
|
const url = new URL(`/api/v1/vms/${encodeURIComponent(vm.uuid)}/console`, location.href);
|
|
|
url.protocol = location.protocol === "https:" ? "wss:" : "ws:";
|
|
|
const rfb = new RFB(stage, url.toString(), { shared: true });
|
|
|
state.rfb = rfb;
|
|
|
placeholder.hidden = true;
|
|
|
rfb.scaleViewport = true;
|
|
|
rfb.resizeSession = false;
|
|
|
rfb.addEventListener("connect", () => {
|
|
|
if (state.rfb !== rfb) return;
|
|
|
text("console-status", "已连接");
|
|
|
byId("console-cad").disabled = false;
|
|
|
});
|
|
|
rfb.addEventListener("disconnect", (event) => {
|
|
|
if (state.rfb !== rfb) return;
|
|
|
text("console-status", event.detail?.clean ? "连接已关闭" : "连接已中断,请关闭后重试");
|
|
|
byId("console-cad").disabled = true;
|
|
|
});
|
|
|
rfb.addEventListener("credentialsrequired", () => {
|
|
|
if (state.rfb !== rfb) return;
|
|
|
byId("console-password-form").hidden = false;
|
|
|
byId("console-password").focus();
|
|
|
text("console-status", "请输入 VNC 密码");
|
|
|
});
|
|
|
} catch (error) {
|
|
|
if (token !== state.consoleToken) return;
|
|
|
text("console-status", `连接失败:${error.message}`);
|
|
|
placeholder.hidden = false;
|
|
|
placeholder.lastElementChild.textContent = "控制台连接失败,请关闭后重试。";
|
|
|
}
|
|
|
}
|
|
|
|
|
|
byId("database-form").addEventListener("submit", async (event) => {
|
|
|
event.preventDefault();
|
|
|
showError("database-error", "");
|
|
|
const button = byId("database-submit");
|
|
|
const token = byId("database-token").value.trim();
|
|
|
const body = {
|
|
|
host: byId("database-host").value.trim(),
|
|
|
port: Number(byId("database-port").value),
|
|
|
database: byId("database-name").value.trim(),
|
|
|
username: byId("database-username").value.trim(),
|
|
|
password: byId("database-password").value,
|
|
|
setup_token: token,
|
|
|
};
|
|
|
setButtonBusy(button, true, "正在连接…");
|
|
|
try {
|
|
|
requireSecureCredentialTransport();
|
|
|
const result = await api("/api/v1/database/setup", { method: "POST", csrf: false, body });
|
|
|
if (result?.configured !== true) throw new Error("无法确认数据库配置已保存,请刷新页面后检查状态。");
|
|
|
byId("setup-token").value = token;
|
|
|
byId("database-password").value = "";
|
|
|
byId("database-token").value = "";
|
|
|
showSetup();
|
|
|
} catch (error) {
|
|
|
showError("database-error", error.message);
|
|
|
} finally {
|
|
|
delete body.password;
|
|
|
delete body.setup_token;
|
|
|
byId("database-password").value = "";
|
|
|
byId("database-token").value = "";
|
|
|
setButtonBusy(button, false);
|
|
|
}
|
|
|
});
|
|
|
|
|
|
byId("setup-form").addEventListener("submit", async (event) => {
|
|
|
event.preventDefault();
|
|
|
showError("setup-error", "");
|
|
|
const password = byId("setup-password").value;
|
|
|
if (password !== byId("setup-password-confirm").value) {
|
|
|
showError("setup-error", "两次输入的管理员密码不一致。");
|
|
|
return;
|
|
|
}
|
|
|
const button = byId("setup-submit");
|
|
|
setButtonBusy(button, true, "正在创建…");
|
|
|
try {
|
|
|
requireSecureCredentialTransport();
|
|
|
const session = await api("/api/v1/setup/admin", {
|
|
|
method: "POST", csrf: false,
|
|
|
body: {
|
|
|
token: byId("setup-token").value.trim(),
|
|
|
username: byId("setup-username").value.trim(),
|
|
|
password,
|
|
|
},
|
|
|
});
|
|
|
if (!session?.authenticated || !session?.csrf_token) throw new Error("管理员已创建,但未能登录。请刷新页面后登录。");
|
|
|
byId("setup-token").value = "";
|
|
|
byId("setup-password").value = "";
|
|
|
byId("setup-password-confirm").value = "";
|
|
|
await continueAfterLogin(session);
|
|
|
} catch (error) {
|
|
|
showError("setup-error", error.message);
|
|
|
} finally {
|
|
|
setButtonBusy(button, false);
|
|
|
}
|
|
|
});
|
|
|
|
|
|
byId("login-form").addEventListener("submit", async (event) => {
|
|
|
event.preventDefault();
|
|
|
showError("login-error", "");
|
|
|
const button = byId("login-submit");
|
|
|
setButtonBusy(button, true, "正在登录…");
|
|
|
try {
|
|
|
requireSecureCredentialTransport();
|
|
|
const session = await api("/api/v1/login", {
|
|
|
method: "POST", csrf: false,
|
|
|
body: { username: byId("login-username").value.trim(), password: byId("login-password").value },
|
|
|
});
|
|
|
if (!session?.authenticated) throw new Error("登录失败,请检查用户名和密码。");
|
|
|
byId("login-password").value = "";
|
|
|
await continueAfterLogin(session);
|
|
|
} catch (error) {
|
|
|
showError("login-error", error.message);
|
|
|
} finally {
|
|
|
setButtonBusy(button, false);
|
|
|
}
|
|
|
});
|
|
|
|
|
|
async function logout(button) {
|
|
|
setButtonBusy(button, true, "退出中…");
|
|
|
try {
|
|
|
await api("/api/v1/logout", { method: "POST" });
|
|
|
showLogin();
|
|
|
} catch (error) {
|
|
|
toast(`退出失败:${error.message}`, "error");
|
|
|
} finally {
|
|
|
setButtonBusy(button, false);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
byId("logout-button").addEventListener("click", () => void logout(byId("logout-button")));
|
|
|
byId("host-logout-button").addEventListener("click", () => void logout(byId("host-logout-button")));
|
|
|
byId("unlock-logout-button").addEventListener("click", () => void logout(byId("unlock-logout-button")));
|
|
|
byId("host-settings-button").addEventListener("click", () => showHostView(state.hostConfig || { configured: true }));
|
|
|
byId("host-settings-mobile-button").addEventListener("click", () => showHostView(state.hostConfig || { configured: true }));
|
|
|
byId("host-update-button").addEventListener("click", () => openUpdateFromGate("host"));
|
|
|
byId("unlock-update-button").addEventListener("click", () => openUpdateFromGate("unlock"));
|
|
|
byId("vm-navigation-button").addEventListener("click", leaveUpdateWorkspace);
|
|
|
byId("update-settings-button").addEventListener("click", () => void showUpdateWorkspace());
|
|
|
byId("update-settings-mobile-button").addEventListener("click", () => void showUpdateWorkspace());
|
|
|
byId("update-back-button").addEventListener("click", leaveUpdateWorkspace);
|
|
|
byId("unlock-settings-button").addEventListener("click", () => showHostView(state.hostConfig || { configured: true }));
|
|
|
byId("host-back-button").addEventListener("click", () => {
|
|
|
clearHostPrivateKey();
|
|
|
if (state.hostConfig?.key_locked) showUnlockView(state.hostConfig);
|
|
|
else void showDashboard({ username: state.username, csrf_token: state.csrfToken });
|
|
|
});
|
|
|
byId("host-address").addEventListener("input", resetFingerprint);
|
|
|
byId("host-port").addEventListener("input", resetFingerprint);
|
|
|
for (const id of ["host-storage-pool", "host-iso-pool", "host-network"]) {
|
|
|
byId(id).addEventListener("input", markHostTestStale);
|
|
|
}
|
|
|
byId("host-private-key").addEventListener("input", () => {
|
|
|
if (state.uploadedPrivateKey) {
|
|
|
state.uploadedPrivateKey = "";
|
|
|
byId("host-private-key-file").value = "";
|
|
|
text("host-key-file-label", "未选择文件;已保存的密钥不会在这里显示。");
|
|
|
}
|
|
|
markHostTestStale();
|
|
|
});
|
|
|
byId("host-private-key-passphrase").addEventListener("input", markHostTestStale);
|
|
|
byId("host-scan-button").addEventListener("click", () => void scanHost());
|
|
|
byId("host-test-button").addEventListener("click", () => void submitHost(false));
|
|
|
byId("host-form").addEventListener("submit", (event) => {
|
|
|
event.preventDefault();
|
|
|
void submitHost(true);
|
|
|
});
|
|
|
byId("unlock-form").addEventListener("submit", (event) => {
|
|
|
event.preventDefault();
|
|
|
void submitUnlock();
|
|
|
});
|
|
|
byId("host-private-key-file").addEventListener("change", async (event) => {
|
|
|
state.uploadedPrivateKey = "";
|
|
|
const input = event.currentTarget;
|
|
|
const file = input.files?.[0];
|
|
|
if (!file) {
|
|
|
text("host-key-file-label", "未选择文件;已保存的密钥不会在这里显示。");
|
|
|
return;
|
|
|
}
|
|
|
if (file.size > 64 * 1024) {
|
|
|
input.value = "";
|
|
|
showError("host-error", "私钥文件超过 64 KiB,请检查是否选错文件。");
|
|
|
return;
|
|
|
}
|
|
|
try {
|
|
|
const content = await file.text();
|
|
|
if (input.files?.[0] !== file) return;
|
|
|
state.uploadedPrivateKey = content;
|
|
|
byId("host-private-key").value = "";
|
|
|
text("host-key-file-label", `已选择 ${file.name};文件内容不会在页面回显。`);
|
|
|
showError("host-error", "");
|
|
|
markHostTestStale();
|
|
|
} catch {
|
|
|
input.value = "";
|
|
|
showError("host-error", "无法读取所选私钥文件,请重试或粘贴私钥内容。");
|
|
|
}
|
|
|
});
|
|
|
|
|
|
byId("update-settings-form").addEventListener("submit", async (event) => {
|
|
|
event.preventDefault();
|
|
|
showError("update-settings-error", "");
|
|
|
const body = { repository_url: UPDATE_REPOSITORY_URL, branch: UPDATE_BRANCH };
|
|
|
const accessToken = byId("update-access-token").value;
|
|
|
if (accessToken) body.access_token = accessToken;
|
|
|
if (!accessToken && !state.updateSettings?.token_configured) {
|
|
|
showError("update-settings-error", "请填写具有仓库读取权限的 Gitea 访问令牌。");
|
|
|
return;
|
|
|
}
|
|
|
const button = byId("update-settings-submit");
|
|
|
setButtonBusy(button, true, "正在保存…");
|
|
|
try {
|
|
|
requireSecureCredentialTransport();
|
|
|
const settings = await api("/api/v1/update/settings", { method: "PUT", body });
|
|
|
state.updateSettings = { configured: Boolean(settings?.configured), token_configured: Boolean(settings?.token_configured) };
|
|
|
state.updateCheck = null;
|
|
|
byId("update-check-button").disabled = !settings?.configured;
|
|
|
byId("update-apply-button").disabled = true;
|
|
|
byId("update-access-token").value = "";
|
|
|
text("update-token-hint", "访问令牌已保存;留空则继续使用现有令牌。令牌不会在页面回显。");
|
|
|
text("update-latest-version", "—");
|
|
|
text("update-status", settings?.checkout_error || "访问令牌已保存。请点击“检查更新”。");
|
|
|
toast("更新来源已保存。", "success");
|
|
|
} catch (error) {
|
|
|
showError("update-settings-error", error.message);
|
|
|
} finally {
|
|
|
delete body.access_token;
|
|
|
byId("update-access-token").value = "";
|
|
|
setButtonBusy(button, false);
|
|
|
}
|
|
|
});
|
|
|
|
|
|
byId("update-check-button").addEventListener("click", async () => {
|
|
|
showError("update-action-error", "");
|
|
|
const button = byId("update-check-button");
|
|
|
setButtonBusy(button, true, "正在检查…");
|
|
|
byId("update-apply-button").disabled = true;
|
|
|
try {
|
|
|
const result = await api("/api/v1/update/check", { method: "POST" });
|
|
|
state.updateCheck = result;
|
|
|
text("update-current-version", result?.current_version || "—");
|
|
|
text("update-latest-version", result?.latest_version || "—");
|
|
|
const available = result?.update_available === true;
|
|
|
byId("update-apply-button").disabled = !available || Boolean(state.updateJobId);
|
|
|
text("update-status", available ? "发现新版本。请先备份数据库和面板数据,再点击“一键更新”。" : "当前已是最新版本。");
|
|
|
} catch (error) {
|
|
|
state.updateCheck = null;
|
|
|
showError("update-action-error", `检查更新失败:${error.message}`);
|
|
|
text("update-status", "未能确认仓库版本,请检查更新来源与令牌。");
|
|
|
} finally {
|
|
|
setButtonBusy(button, false);
|
|
|
}
|
|
|
});
|
|
|
|
|
|
byId("update-apply-button").addEventListener("click", async () => {
|
|
|
if (!state.updateCheck?.update_available || state.updateJobId) return;
|
|
|
const expectedCurrent = String(state.updateCheck.current_version || "");
|
|
|
const expectedRemote = String(state.updateCheck.latest_version || "");
|
|
|
if (!expectedCurrent || !expectedRemote) {
|
|
|
showError("update-action-error", "缺少已检查的提交编号,请重新检查更新。");
|
|
|
return;
|
|
|
}
|
|
|
if (!window.confirm(`即将把面板更新到已检查的提交 ${expectedRemote.slice(0, 12)}。如果仓库版本已变化,更新会停止并要求重新检查。过程可能重启服务。确认已备份数据库和面板数据,并且可以使用服务器控制台恢复后,再继续。确定执行吗?`)) return;
|
|
|
showError("update-action-error", "");
|
|
|
const button = byId("update-apply-button");
|
|
|
setButtonBusy(button, true, "正在提交…");
|
|
|
byId("update-check-button").disabled = true;
|
|
|
try {
|
|
|
const started = await api("/api/v1/update/apply", { method: "POST", body: {
|
|
|
expected_current_commit: expectedCurrent,
|
|
|
expected_remote_commit: expectedRemote,
|
|
|
} });
|
|
|
const jobId = String(started?.job_id || "");
|
|
|
if (!jobId) throw new Error("未收到更新任务编号;请检查服务端状态,勿重复提交。");
|
|
|
state.updateJobId = jobId;
|
|
|
text("update-status", "更新任务已提交,正在查询进度。服务可能短暂断开。");
|
|
|
void pollUpdateJob(jobId, ++state.updatePollToken);
|
|
|
} catch (error) {
|
|
|
showError("update-action-error", `提交更新失败:${error.message}`);
|
|
|
byId("update-check-button").disabled = false;
|
|
|
} finally {
|
|
|
setButtonBusy(button, false);
|
|
|
byId("update-apply-button").disabled = true;
|
|
|
}
|
|
|
});
|
|
|
|
|
|
byId("refresh-button").addEventListener("click", () => void loadVMs());
|
|
|
byId("search-input").addEventListener("input", () => renderVMs());
|
|
|
byId("state-filter").addEventListener("change", () => renderVMs());
|
|
|
byId("create-button").addEventListener("click", openCreate);
|
|
|
byId("vm-guest-ssh-public-key").addEventListener("input", updateCreateAuthMode);
|
|
|
document.querySelectorAll('input[name="source"]').forEach((radio) => radio.addEventListener("change", () => {
|
|
|
showError("create-error", "");
|
|
|
updateCreateSource();
|
|
|
if (selectedCreateSource() === "cloud") {
|
|
|
void loadTemplates().catch((error) => showError("create-error", `无法加载云镜像模板:${error.message}`));
|
|
|
}
|
|
|
}));
|
|
|
|
|
|
byId("template-import-button").addEventListener("click", async () => {
|
|
|
showError("template-import-error", "");
|
|
|
const existingJobId = state.templateImportJobId;
|
|
|
const name = byId("template-name").value.trim();
|
|
|
const rawUrl = byId("template-url").value.trim();
|
|
|
const sha256 = byId("template-sha256").value.trim().toLowerCase();
|
|
|
let url;
|
|
|
try { url = new URL(rawUrl); } catch { /* Validate below without displaying the supplied URL. */ }
|
|
|
if (!existingJobId && (!name || name.length > 64)) {
|
|
|
showError("template-import-error", "请填写不超过 64 个字符的模板名称。");
|
|
|
return;
|
|
|
}
|
|
|
if (!existingJobId && (!url || url.origin !== "https://repo.almalinux.org" || url.username || url.password || url.search || url.hash || !url.pathname.toLowerCase().endsWith(".qcow2"))) {
|
|
|
showError("template-import-error", "目前仅支持 repo.almalinux.org 上的 AlmaLinux 10 x86_64 GenericCloud qcow2 HTTPS 地址。");
|
|
|
return;
|
|
|
}
|
|
|
if (!existingJobId && !/^[a-f0-9]{64}$/.test(sha256)) {
|
|
|
showError("template-import-error", "请填写镜像发布方提供的 64 位 SHA-256 校验值。");
|
|
|
return;
|
|
|
}
|
|
|
const button = byId("template-import-button");
|
|
|
setButtonBusy(button, true, "正在检查后台导入…");
|
|
|
try {
|
|
|
let jobId = existingJobId;
|
|
|
if (!jobId) {
|
|
|
const started = await api("/api/v1/vm-templates/import", { method: "POST", body: { name, url: url.href, sha256 } });
|
|
|
jobId = String(started?.job_id || "");
|
|
|
if (!jobId) throw new Error("面板未返回模板导入任务编号,请刷新模板列表确认结果。");
|
|
|
state.templateImportJobId = jobId;
|
|
|
}
|
|
|
showTemplateImportStatus("宿主机正在后台下载并校验云镜像。关闭弹窗不会取消任务,请稍候。");
|
|
|
const completed = await waitForTemplateImport(jobId);
|
|
|
state.templateImportJobId = null;
|
|
|
showTemplateImportStatus("");
|
|
|
await loadTemplates(String(completed?.template?.id || ""));
|
|
|
byId("template-import").open = false;
|
|
|
byId("template-name").value = "";
|
|
|
byId("template-url").value = "";
|
|
|
byId("template-sha256").value = "";
|
|
|
toast("云镜像模板已导入,请在系统模板中确认选择。", "success");
|
|
|
} catch (error) {
|
|
|
showTemplateImportStatus(state.templateImportJobId ? "暂时无法确认导入进度,任务可能仍在后台运行;稍后点击按钮继续查看。" : "");
|
|
|
showError("template-import-error", error.message);
|
|
|
} finally {
|
|
|
setButtonBusy(button, false);
|
|
|
}
|
|
|
});
|
|
|
|
|
|
function ipv4Parts(value) {
|
|
|
if (!/^\d{1,3}(?:\.\d{1,3}){3}$/.test(value)) return null;
|
|
|
const segments = value.split(".");
|
|
|
const parts = segments.map(Number);
|
|
|
return parts.every((part, index) => part >= 0 && part <= 255 && String(part) === segments[index]) ? parts : null;
|
|
|
}
|
|
|
|
|
|
function ipv4Number(parts) {
|
|
|
return parts.reduce((accumulator, part) => ((accumulator << 8) | part) >>> 0, 0);
|
|
|
}
|
|
|
|
|
|
function validPublicIpCidr(value) {
|
|
|
const match = /^([^/]+)\/(\d{1,2})$/.exec(value);
|
|
|
if (!match) return false;
|
|
|
const parts = ipv4Parts(match[1]);
|
|
|
const prefix = Number(match[2]);
|
|
|
if (!parts || prefix < 1 || prefix > 30) return false;
|
|
|
const [first, second] = parts;
|
|
|
if (first === 0 || first === 10 || first === 127 || first >= 224 ||
|
|
|
(first === 100 && second >= 64 && second <= 127) ||
|
|
|
(first === 169 && second === 254) ||
|
|
|
(first === 172 && second >= 16 && second <= 31) ||
|
|
|
(first === 192 && second === 168)) return false;
|
|
|
if (prefix <= 30) {
|
|
|
const address = ipv4Number(parts);
|
|
|
const hostMask = 2 ** (32 - prefix) - 1;
|
|
|
const host = address & hostMask;
|
|
|
if (host === 0 || host === hostMask) return false;
|
|
|
}
|
|
|
return true;
|
|
|
}
|
|
|
|
|
|
function validGatewayForCidr(gateway, publicIpCidr) {
|
|
|
const gatewayParts = ipv4Parts(gateway);
|
|
|
const [ip, prefixText] = publicIpCidr.split("/");
|
|
|
const ipParts = ipv4Parts(ip);
|
|
|
const prefix = Number(prefixText);
|
|
|
if (!gatewayParts || !ipParts || !Number.isInteger(prefix) || prefix < 1 || prefix > 30 || gateway === ip) return false;
|
|
|
const mask = (0xffffffff << (32 - prefix)) >>> 0;
|
|
|
const gatewayNumber = ipv4Number(gatewayParts);
|
|
|
if ((gatewayNumber & mask) !== (ipv4Number(ipParts) & mask)) return false;
|
|
|
if (prefix <= 30) {
|
|
|
const hostMask = (~mask) >>> 0;
|
|
|
const host = gatewayNumber & hostMask;
|
|
|
if (host === 0 || host === hostMask) return false;
|
|
|
}
|
|
|
return true;
|
|
|
}
|
|
|
|
|
|
function validSshPublicKey(value) {
|
|
|
return !/[\r\n]/.test(value) && /^(?:ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(?:256|384|521)) [A-Za-z0-9+/]{32,}={0,2}(?: [^\r\n]*)?$/.test(value);
|
|
|
}
|
|
|
|
|
|
byId("create-form").addEventListener("submit", async (event) => {
|
|
|
event.preventDefault();
|
|
|
showError("create-error", "");
|
|
|
const button = byId("create-submit");
|
|
|
const data = new FormData(event.currentTarget);
|
|
|
const source = selectedCreateSource();
|
|
|
const body = {
|
|
|
name: String(data.get("name") || "").trim(),
|
|
|
vcpu: Number(data.get("vcpu")),
|
|
|
memory_mib: Number(data.get("memory_mib")),
|
|
|
disk_gib: Number(data.get("disk_gib")),
|
|
|
network: String(data.get("network") || ""),
|
|
|
};
|
|
|
if (source === "cloud") {
|
|
|
body.source = "cloud";
|
|
|
body.template_id = String(data.get("template_id") || "");
|
|
|
body.public_ip_cidr = String(data.get("public_ip_cidr") || "").trim();
|
|
|
body.gateway = String(data.get("gateway") || "").trim();
|
|
|
body.dns_servers = String(data.get("dns_servers") || "").split(/[\s,;]+/).filter(Boolean);
|
|
|
body.guest_ssh_public_key = String(data.get("guest_ssh_public_key") || "").trim();
|
|
|
if (!body.network.startsWith("bridge:")) {
|
|
|
showError("create-error", "公网云镜像需要 Linux 网桥。请先在宿主机设置中配置 bridge:br0 等网桥。");
|
|
|
return;
|
|
|
}
|
|
|
if (!body.template_id) {
|
|
|
showError("create-error", "请先选择或导入云镜像模板。");
|
|
|
return;
|
|
|
}
|
|
|
if (!validPublicIpCidr(body.public_ip_cidr)) {
|
|
|
showError("create-error", "请填写有效的公网 IPv4/CIDR,例如已分配给你的地址和 /24 或 /28 前缀;不能填写网段或广播地址。");
|
|
|
return;
|
|
|
}
|
|
|
if (!validGatewayForCidr(body.gateway, body.public_ip_cidr)) {
|
|
|
showError("create-error", "请填写与虚拟机 IP 同网段的有效网关 IPv4,且不能与虚拟机 IP 相同。非同网段网关暂不支持。");
|
|
|
return;
|
|
|
}
|
|
|
if (!body.dns_servers.length || body.dns_servers.length > 4 || !body.dns_servers.every((address) => ipv4Parts(address))) {
|
|
|
showError("create-error", "请填写 1 至 4 个有效的 DNS IPv4 地址,用逗号或空格分隔。");
|
|
|
return;
|
|
|
}
|
|
|
if (body.guest_ssh_public_key) {
|
|
|
if (!validSshPublicKey(body.guest_ssh_public_key)) {
|
|
|
showError("create-error", "请粘贴单行 OpenSSH 公钥;不要粘贴私钥。");
|
|
|
return;
|
|
|
}
|
|
|
} else {
|
|
|
body.root_password = String(data.get("root_password") || "");
|
|
|
if (body.root_password.length < 12 || body.root_password.length > 128) {
|
|
|
showError("create-error", "未填写 SSH 公钥时,请设置 12 至 128 个字符的初始 root 密码。");
|
|
|
return;
|
|
|
}
|
|
|
}
|
|
|
} else {
|
|
|
body.iso = String(data.get("iso") || "");
|
|
|
if (!body.network || !body.iso) {
|
|
|
showError("create-error", "请先选择可用的虚拟网络或网桥,以及 ISO 镜像。");
|
|
|
return;
|
|
|
}
|
|
|
}
|
|
|
data.delete("root_password");
|
|
|
byId("vm-root-password").value = "";
|
|
|
setButtonBusy(button, true, "正在创建…");
|
|
|
try {
|
|
|
await api("/api/v1/vms", { method: "POST", body });
|
|
|
closeModal();
|
|
|
toast(`虚拟机 ${body.name} 创建成功。`, "success");
|
|
|
await loadVMs(true);
|
|
|
window.setTimeout(() => void loadVMs(true), 1200);
|
|
|
} catch (error) {
|
|
|
showError("create-error", error.message);
|
|
|
} finally {
|
|
|
delete body.root_password;
|
|
|
byId("vm-root-password").value = "";
|
|
|
setButtonBusy(button, false);
|
|
|
}
|
|
|
});
|
|
|
|
|
|
byId("reinstall-form").addEventListener("submit", async (event) => {
|
|
|
event.preventDefault();
|
|
|
const vm = state.reinstallTarget;
|
|
|
if (!vm || state.reinstallInProgress) return;
|
|
|
showError("reinstall-error", "");
|
|
|
const templateId = byId("reinstall-template").value;
|
|
|
const publicKey = byId("reinstall-ssh-public-key").value.trim();
|
|
|
const rootPassword = byId("reinstall-root-password").value;
|
|
|
const confirmationName = byId("reinstall-confirm-name").value;
|
|
|
if (!templateId) {
|
|
|
showError("reinstall-error", "请先选择已导入的云镜像模板。若列表为空,请在“创建虚拟机”窗口先导入模板。");
|
|
|
return;
|
|
|
}
|
|
|
if (publicKey && !validSshPublicKey(publicKey)) {
|
|
|
showError("reinstall-error", "请粘贴单行 OpenSSH 公钥,不要粘贴私钥。");
|
|
|
return;
|
|
|
}
|
|
|
if (publicKey && rootPassword) {
|
|
|
showError("reinstall-error", "SSH 公钥和初始密码只能选择一种;两项都留空会自动生成密码。");
|
|
|
return;
|
|
|
}
|
|
|
if (rootPassword && (rootPassword.length < 12 || rootPassword.length > 128)) {
|
|
|
showError("reinstall-error", "初始 root 密码需要 12 至 128 个字符。");
|
|
|
return;
|
|
|
}
|
|
|
if (confirmationName !== vm.name) {
|
|
|
showError("reinstall-error", "确认名称与虚拟机名称不一致,未执行重装。");
|
|
|
return;
|
|
|
}
|
|
|
const button = byId("reinstall-submit");
|
|
|
const body = {
|
|
|
template_id: templateId,
|
|
|
ssh_public_key: publicKey,
|
|
|
root_password: rootPassword,
|
|
|
confirmation_name: confirmationName,
|
|
|
};
|
|
|
state.reinstallInProgress = true;
|
|
|
state.reinstallExpectGeneratedPassword = !publicKey && !rootPassword;
|
|
|
byId("reinstall-close-top").disabled = true;
|
|
|
byId("reinstall-cancel").disabled = true;
|
|
|
setButtonBusy(button, true, "正在提交…");
|
|
|
try {
|
|
|
const started = await api(`/api/v1/vms/${encodeURIComponent(vm.uuid)}/reinstall`, { method: "POST", body });
|
|
|
const jobId = String(started?.job_id || "");
|
|
|
if (!jobId) throw new Error("面板未返回重装任务编号,请先检查虚拟机状态,勿重复提交。");
|
|
|
state.reinstallJobId = jobId;
|
|
|
saveReinstallJob(jobId);
|
|
|
byId("reinstall-fields").hidden = true;
|
|
|
byId("reinstall-progress").hidden = false;
|
|
|
byId("reinstall-cancel").hidden = true;
|
|
|
byId("reinstall-submit").hidden = true;
|
|
|
text("reinstall-phase", "重装任务已提交,正在检查宿主机状态…");
|
|
|
const token = ++state.reinstallPollToken;
|
|
|
void pollReinstallJob(jobId, token);
|
|
|
} catch (error) {
|
|
|
state.reinstallInProgress = false;
|
|
|
byId("reinstall-close-top").disabled = false;
|
|
|
byId("reinstall-cancel").disabled = false;
|
|
|
showError("reinstall-error", error.message);
|
|
|
} finally {
|
|
|
delete body.root_password;
|
|
|
byId("reinstall-root-password").value = "";
|
|
|
byId("reinstall-ssh-public-key").value = "";
|
|
|
setButtonBusy(button, false);
|
|
|
}
|
|
|
});
|
|
|
|
|
|
byId("reinstall-copy-password").addEventListener("click", async () => {
|
|
|
const password = byId("reinstall-generated-password").textContent;
|
|
|
if (!password) return;
|
|
|
try {
|
|
|
await navigator.clipboard.writeText(password);
|
|
|
toast("root 密码已复制,请安全保存。", "success");
|
|
|
} catch {
|
|
|
toast("浏览器无法复制,请手动选中并保存密码。", "error");
|
|
|
}
|
|
|
});
|
|
|
byId("reinstall-done").addEventListener("click", async () => {
|
|
|
if (!state.reinstallPasswordPendingAck) {
|
|
|
closeModal();
|
|
|
return;
|
|
|
}
|
|
|
const jobId = state.reinstallJobId;
|
|
|
if (!jobId) {
|
|
|
showError("reinstall-error", "无法确认此密码已保存,请立即手动复制,并检查面板任务状态。");
|
|
|
return;
|
|
|
}
|
|
|
const button = byId("reinstall-done");
|
|
|
setButtonBusy(button, true, "正在确认…");
|
|
|
try {
|
|
|
const result = await api(`/api/v1/reinstall-jobs/${encodeURIComponent(jobId)}/ack-password`, { method: "POST" });
|
|
|
if (result?.acknowledged !== true) throw new Error("面板未确认密码已经清除,请稍后重试。");
|
|
|
state.reinstallPasswordPendingAck = false;
|
|
|
clearSavedReinstallJob();
|
|
|
closeModal();
|
|
|
} catch (error) {
|
|
|
showError("reinstall-error", `确认密码失败:${error.message}。密码仍在此窗口中,请先安全保存后重试。`);
|
|
|
} finally {
|
|
|
setButtonBusy(button, false);
|
|
|
}
|
|
|
});
|
|
|
byId("reinstall-retry").addEventListener("click", () => {
|
|
|
const jobId = state.reinstallJobId;
|
|
|
if (!jobId) return;
|
|
|
state.reinstallInProgress = true;
|
|
|
byId("reinstall-close-top").disabled = true;
|
|
|
byId("reinstall-result").hidden = true;
|
|
|
byId("reinstall-progress").hidden = false;
|
|
|
byId("reinstall-retry").hidden = true;
|
|
|
byId("reinstall-done").hidden = true;
|
|
|
text("reinstall-phase", "正在重新查询已有重装任务…");
|
|
|
const token = ++state.reinstallPollToken;
|
|
|
void pollReinstallJob(jobId, token);
|
|
|
});
|
|
|
byId("reinstall-forget").addEventListener("click", () => {
|
|
|
if (!window.confirm("请先在宿主机核对虚拟机、新旧系统盘和登录方式。放弃恢复后,本标签页将不再查询此任务,尚未领取的自动 root 密码也可能无法找回。确定放弃吗?")) return;
|
|
|
clearSavedReinstallJob();
|
|
|
closeModal();
|
|
|
});
|
|
|
|
|
|
byId("delete-form").addEventListener("submit", async (event) => {
|
|
|
event.preventDefault();
|
|
|
const vm = state.deleteTarget;
|
|
|
if (!vm) return;
|
|
|
showError("delete-error", "");
|
|
|
const button = byId("delete-submit");
|
|
|
setButtonBusy(button, true, "正在删除…");
|
|
|
const deleteDisks = byId("delete-disks").checked;
|
|
|
try {
|
|
|
await api(`/api/v1/vms/${encodeURIComponent(vm.uuid)}?delete_disks=${deleteDisks}`, { method: "DELETE" });
|
|
|
closeModal();
|
|
|
toast(`${vm.name || vm.uuid} 已删除${deleteDisks ? ",磁盘已一并删除" : ""}。`, "success");
|
|
|
await loadVMs(true);
|
|
|
} catch (error) {
|
|
|
showError("delete-error", error.message);
|
|
|
} finally {
|
|
|
setButtonBusy(button, false);
|
|
|
}
|
|
|
});
|
|
|
|
|
|
byId("confirm-submit").addEventListener("click", async () => {
|
|
|
const target = state.confirmTarget;
|
|
|
if (!target) return;
|
|
|
const button = byId("confirm-submit");
|
|
|
setButtonBusy(button, true);
|
|
|
try {
|
|
|
const succeeded = await runAction(target.vm, target.action);
|
|
|
if (succeeded) closeModal();
|
|
|
else showError("confirm-error", "操作未完成,请检查宿主机状态后重试。");
|
|
|
} finally {
|
|
|
setButtonBusy(button, false);
|
|
|
}
|
|
|
});
|
|
|
|
|
|
byId("console-cad").addEventListener("click", () => state.rfb?.sendCtrlAltDel());
|
|
|
byId("console-fullscreen").addEventListener("click", async () => {
|
|
|
const stage = byId("console-stage");
|
|
|
try {
|
|
|
if (document.fullscreenElement) await document.exitFullscreen();
|
|
|
else await stage.requestFullscreen();
|
|
|
} catch (error) { toast(`无法进入全屏:${error.message}`, "error"); }
|
|
|
});
|
|
|
byId("console-password-form").addEventListener("submit", (event) => {
|
|
|
event.preventDefault();
|
|
|
if (!state.rfb) return;
|
|
|
state.rfb.sendCredentials({ password: byId("console-password").value });
|
|
|
byId("console-password").value = "";
|
|
|
byId("console-password-form").hidden = true;
|
|
|
text("console-status", "正在验证 VNC 密码…");
|
|
|
});
|
|
|
|
|
|
function requestCloseModal() {
|
|
|
if (state.activeModal?.id === "reinstall-modal" && state.reinstallPasswordPendingAck) {
|
|
|
toast("请先保存 root 密码,再点击“已保存密码,完成”确认清除。", "error");
|
|
|
return;
|
|
|
}
|
|
|
if (state.activeModal?.id === "reinstall-modal" && state.reinstallInProgress) {
|
|
|
toast("重装正在进行,请保持此窗口打开,以免错过一次性显示的 root 密码。", "error");
|
|
|
return;
|
|
|
}
|
|
|
closeModal();
|
|
|
}
|
|
|
|
|
|
document.querySelectorAll("[data-close-modal]").forEach((button) => button.addEventListener("click", requestCloseModal));
|
|
|
document.querySelectorAll(".modal-backdrop").forEach((backdrop) => backdrop.addEventListener("click", (event) => {
|
|
|
if (event.target === backdrop) requestCloseModal();
|
|
|
}));
|
|
|
document.addEventListener("keydown", (event) => {
|
|
|
if (!state.activeModal) return;
|
|
|
if (event.key === "Escape") { requestCloseModal(); return; }
|
|
|
if (event.key !== "Tab") return;
|
|
|
const focusables = Array.from(state.activeModal.querySelectorAll("button:not(:disabled):not([hidden]),input:not(:disabled):not([hidden]),select:not(:disabled):not([hidden])"))
|
|
|
.filter((element) => element.getClientRects().length);
|
|
|
if (!focusables.length) return;
|
|
|
const first = focusables[0];
|
|
|
const last = focusables[focusables.length - 1];
|
|
|
if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }
|
|
|
else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }
|
|
|
});
|
|
|
|
|
|
void initialize();
|