You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/public/cloud/admin-object-storage.js

322 lines
12 KiB
JavaScript

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

(function () {
'use strict';
function request(url, payload) {
return fetch(url, {
method: 'POST',
credentials: 'same-origin',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
},
body: JSON.stringify(payload),
}).then(function (response) {
return response.text().then(function (body) {
var result;
try {
result = JSON.parse(body);
} catch (error) {
throw new Error('服务器未返回有效结果(HTTP ' + response.status + ')');
}
if (!response.ok || Number(result.ret) !== 1) {
throw new Error(result.msg || '请求失败');
}
return result;
});
});
}
function showNotice(node, message, ok) {
if (!node) return;
node.textContent = message;
node.className = 'os-notice is-show ' + (ok ? 'is-ok' : 'is-error');
}
function initializeConfirmation() {
var layer = document.getElementById('osConfirmDialog');
if (!layer) return null;
var dialog = layer.querySelector('[role="alertdialog"]');
var title = document.getElementById('osConfirmTitle');
var message = document.getElementById('osConfirmMessage');
var submit = document.getElementById('osConfirmSubmit');
var cancelButtons = layer.querySelectorAll('[data-os-confirm-cancel]');
var pending = null;
var previousFocus = null;
function close(result) {
if (!pending) return;
var resolve = pending;
pending = null;
layer.hidden = true;
document.body.classList.remove('os-dialog-open');
if (previousFocus && typeof previousFocus.focus === 'function') {
previousFocus.focus({ preventScroll: true });
}
previousFocus = null;
resolve(result);
}
cancelButtons.forEach(function (button) {
button.addEventListener('click', function () { close(false); });
});
submit.addEventListener('click', function () { close(true); });
document.addEventListener('keydown', function (event) {
if (event.key === 'Escape' && !layer.hidden) close(false);
});
return function confirmAction(options) {
if (pending) return Promise.resolve(false);
title.textContent = options.title;
message.textContent = options.message;
submit.textContent = options.confirmLabel;
submit.className = options.tone === 'primary' ? 'btn btn-primary' : 'btn btn-danger';
dialog.classList.toggle('is-primary', options.tone === 'primary');
previousFocus = document.activeElement;
layer.hidden = false;
document.body.classList.add('os-dialog-open');
submit.focus({ preventScroll: true });
return new Promise(function (resolve) { pending = resolve; });
};
}
function initializeConfiguration(confirmAction) {
var form = document.getElementById('objectStorageForm');
if (!form) return;
var notice = document.getElementById('osNotice');
var saveButton = document.getElementById('osSave');
var testButton = document.getElementById('osTest');
var disableButton = document.getElementById('osDisable');
var canManage = form.dataset.canManage === '1';
var dirty = false;
function revision() {
return Number(form.elements.expected_revision.value || 0);
}
function setBusy(busy) {
saveButton.disabled = busy || !canManage;
testButton.disabled = busy || !canManage || revision() < 1 || dirty;
disableButton.disabled = busy || !canManage || disableButton.dataset.disabled === '1';
}
disableButton.dataset.disabled = disableButton.disabled ? '1' : '0';
form.addEventListener('input', function () {
if (!canManage || dirty) return;
dirty = true;
setBusy(false);
showNotice(notice, '配置已修改,请先保存,再验证当前版本。', true);
});
form.addEventListener('submit', function (event) {
event.preventDefault();
if (!canManage || saveButton.disabled) return;
var payload = {
expected_revision: String(form.elements.expected_revision.value || ''),
name: String(form.elements.name.value || ''),
endpoint: String(form.elements.endpoint.value || ''),
region: String(form.elements.region.value || ''),
bucket: String(form.elements.bucket.value || ''),
prefix: String(form.elements.prefix.value || ''),
path_style: String(form.elements.path_style.value || ''),
access_key_id: String(form.elements.access_key_id.value || ''),
secret_access_key: String(form.elements.secret_access_key.value || ''),
};
setBusy(true);
showNotice(notice, '正在加密并保存配置...', true);
request('/admin/object-storage/config', payload).then(function (result) {
form.elements.access_key_id.value = '';
form.elements.secret_access_key.value = '';
showNotice(notice, result.msg, true);
window.setTimeout(function () { window.location.reload(); }, 650);
}).catch(function (error) {
showNotice(notice, error.message, false);
setBusy(false);
});
});
testButton.addEventListener('click', function () {
if (!canManage || testButton.disabled) return;
setBusy(true);
showNotice(notice, '正在执行签名的 Bucket 连接验证...', true);
request('/admin/object-storage/test', { expected_revision: revision() }).then(function (result) {
showNotice(notice, result.msg, true);
window.setTimeout(function () { window.location.reload(); }, 650);
}).catch(function (error) {
showNotice(notice, error.message, false);
window.setTimeout(function () { window.location.reload(); }, 1200);
});
});
disableButton.addEventListener('click', function () {
if (!canManage || disableButton.disabled || !confirmAction) return;
confirmAction({
title: '停用对象存储',
message: '停用后云备份不会再使用当前连接;已加密保存的访问凭据不会被删除。',
confirmLabel: '确认停用',
tone: 'danger',
}).then(function (confirmed) {
if (!confirmed) return;
setBusy(true);
showNotice(notice, '正在停用对象存储...', true);
request('/admin/object-storage/disable', { expected_revision: revision() }).then(function (result) {
showNotice(notice, result.msg, true);
window.setTimeout(function () { window.location.reload(); }, 650);
}).catch(function (error) {
showNotice(notice, error.message, false);
setBusy(false);
});
});
});
}
function initializeConfigurationDrawer() {
var drawer = document.getElementById('osConfigDrawer');
var openButton = document.getElementById('osEditConfig');
var form = document.getElementById('objectStorageForm');
if (!drawer || !openButton || !form) return;
var dialog = drawer.querySelector('[role="dialog"]');
var closeButtons = drawer.querySelectorAll('[data-os-drawer-close]');
var replaceCredentials = document.getElementById('osReplaceCredentials');
var credentialFields = document.getElementById('osCredentialFields');
var accessKey = form.elements.access_key_id;
var secretKey = form.elements.secret_access_key;
var previousFocus = null;
function setCredentialFields(visible) {
if (!credentialFields) return;
credentialFields.hidden = !visible;
if (accessKey) accessKey.required = visible;
if (secretKey) secretKey.required = visible;
if (!visible) {
if (accessKey) accessKey.value = '';
if (secretKey) secretKey.value = '';
}
}
function openDrawer() {
if (openButton.disabled) return;
previousFocus = document.activeElement;
drawer.hidden = false;
document.body.classList.add('os-drawer-open');
if (dialog) dialog.focus({ preventScroll: true });
}
function closeDrawer() {
if (drawer.hidden) return;
drawer.hidden = true;
document.body.classList.remove('os-drawer-open');
if (previousFocus && typeof previousFocus.focus === 'function') {
previousFocus.focus({ preventScroll: true });
}
previousFocus = null;
}
openButton.addEventListener('click', openDrawer);
closeButtons.forEach(function (button) {
button.addEventListener('click', closeDrawer);
});
document.addEventListener('keydown', function (event) {
if (event.key === 'Escape' && !drawer.hidden) closeDrawer();
});
if (replaceCredentials) {
replaceCredentials.addEventListener('change', function () {
setCredentialFields(replaceCredentials.checked);
if (replaceCredentials.checked && accessKey) accessKey.focus();
});
setCredentialFields(replaceCredentials.checked);
} else {
setCredentialFields(true);
}
}
function formatBytes(value) {
var bytes = Math.max(0, Number(value) || 0);
var units = ['B', 'KiB', 'MiB', 'GiB', 'TiB'];
var index = 0;
while (bytes >= 1024 && index < units.length - 1) {
bytes /= 1024;
index += 1;
}
return (index === 0 ? String(Math.round(bytes)) : bytes.toFixed(bytes >= 10 ? 1 : 2))
+ ' ' + units[index];
}
function initializeCleanupDebt(confirmAction) {
document.querySelectorAll('.os-byte-value').forEach(function (node) {
node.textContent = formatBytes(node.getAttribute('data-bytes'));
});
var refresh = document.getElementById('osDebtRefresh');
if (refresh) {
refresh.addEventListener('click', function () { window.location.reload(); });
}
var notice = document.getElementById('osDebtNotice');
document.querySelectorAll('.os-cleanup-retry').forEach(function (button) {
button.addEventListener('click', function () {
var backupId = String(button.getAttribute('data-backup-id') || '');
if (!/^\d+$/.test(backupId) || button.disabled || !confirmAction) return;
confirmAction({
title: '重新开启清理核对',
message: '系统会先检查准确对象身份并等待第二次稳定证据;此操作不会直接重放原删除请求。',
confirmLabel: '开始核对',
tone: 'primary',
}).then(function (confirmed) {
if (!confirmed) return;
button.disabled = true;
showNotice(notice, '正在核对准确对象版本...', true);
request('/admin/object-storage/cleanup-debts/' + encodeURIComponent(backupId) + '/retry', {})
.then(function (result) {
showNotice(notice, result.msg, true);
window.setTimeout(function () { window.location.reload(); }, 700);
}).catch(function (error) {
showNotice(notice, error.message || '请求失败', false);
button.disabled = false;
});
});
});
});
}
function initializeTabs() {
var tabs = Array.prototype.slice.call(document.querySelectorAll('[data-os-tab]'));
var panels = Array.prototype.slice.call(document.querySelectorAll('[data-os-panel]'));
if (tabs.length === 0 || panels.length === 0) return;
function activate(name, updateLocation) {
var selected = name === 'cleanup' ? 'cleanup' : 'overview';
tabs.forEach(function (tab) {
var active = tab.getAttribute('data-os-tab') === selected;
tab.classList.toggle('is-active', active);
tab.setAttribute('aria-selected', active ? 'true' : 'false');
tab.tabIndex = active ? 0 : -1;
});
panels.forEach(function (panel) {
var active = panel.getAttribute('data-os-panel') === selected;
panel.classList.toggle('is-active', active);
panel.hidden = !active;
});
if (updateLocation && window.history && window.history.replaceState) {
var hash = selected === 'cleanup' ? '#cleanup' : '#overview';
window.history.replaceState(window.history.state, '', window.location.pathname
+ window.location.search + hash);
}
}
tabs.forEach(function (tab) {
tab.addEventListener('click', function () {
activate(tab.getAttribute('data-os-tab'), true);
});
});
activate(window.location.hash === '#cleanup' ? 'cleanup' : 'overview', false);
}
function initialize() {
var confirmAction = initializeConfirmation();
initializeTabs();
initializeConfigurationDrawer();
initializeConfiguration(confirmAction);
initializeCleanupDebt(confirmAction);
}
initialize();
})();