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.
307 lines
11 KiB
JavaScript
307 lines
11 KiB
JavaScript
const runtimeUrl = new URL('/cloud/runtime.js', location.origin);
|
|
const assetVersion = new URL(import.meta.url).searchParams.get('v');
|
|
if (assetVersion) runtimeUrl.searchParams.set('v', assetVersion);
|
|
const {
|
|
api, bindPageCleanup, byId, initializeSession, showError, state, toast,
|
|
} = await import(runtimeUrl.href);
|
|
|
|
const pageState = {
|
|
isos: [], canImport: true, busy: false, stopped: false,
|
|
loadEpoch: 0, loadController: null,
|
|
activeStatusUrl: '', polling: false, pollEpoch: 0, pollController: null,
|
|
pollTimer: 0, pollResolve: null,
|
|
};
|
|
|
|
function element(tag, className = '', content = '') {
|
|
const node = document.createElement(tag);
|
|
if (className) node.className = className;
|
|
if (content !== '') node.textContent = String(content);
|
|
return node;
|
|
}
|
|
|
|
function formatBytes(value) {
|
|
let amount = Number(value);
|
|
if (!Number.isFinite(amount) || amount < 0) return '大小未知';
|
|
const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB'];
|
|
let index = 0;
|
|
while (amount >= 1024 && index < units.length - 1) { amount /= 1024; index += 1; }
|
|
return `${amount.toFixed(index === 0 ? 0 : amount < 10 ? 2 : 1)} ${units[index]}`;
|
|
}
|
|
|
|
function activeJobStorageKey() {
|
|
const userId = String(state.userId || '');
|
|
return /^\d+$/.test(userId) ? `virt-cloud:user-iso-job:${userId}` : '';
|
|
}
|
|
|
|
function storedActiveJob() {
|
|
const key = activeJobStorageKey();
|
|
if (!key) return '';
|
|
try {
|
|
const jobId = String(sessionStorage.getItem(key) || '');
|
|
return /^[A-Za-z0-9_-]{8,80}$/.test(jobId) ? jobId : '';
|
|
} catch { return ''; }
|
|
}
|
|
|
|
function rememberActiveJob(jobId) {
|
|
const key = activeJobStorageKey();
|
|
if (!key || !/^[A-Za-z0-9_-]{8,80}$/.test(String(jobId))) return;
|
|
try { sessionStorage.setItem(key, String(jobId)); } catch {}
|
|
}
|
|
|
|
function forgetActiveJob() {
|
|
const key = activeJobStorageKey();
|
|
if (!key) return;
|
|
try { sessionStorage.removeItem(key); } catch {}
|
|
}
|
|
|
|
function setImportStatus(message, failed = false) {
|
|
const node = byId('user-iso-import-status');
|
|
node.textContent = message;
|
|
node.classList.toggle('warning', failed);
|
|
node.hidden = !message;
|
|
}
|
|
|
|
function updateImportAvailability() {
|
|
const running = Boolean(pageState.activeStatusUrl);
|
|
const availability = byId('user-iso-availability');
|
|
const message = running ? '已有 ISO 下载任务正在执行,完成前不能再次导入。'
|
|
: !pageState.canImport ? '账户的套餐购买及 ISO 上传服务已被管理员停用。' : '';
|
|
availability.textContent = message;
|
|
availability.hidden = !message;
|
|
byId('user-iso-submit').disabled = pageState.busy || running || !pageState.canImport;
|
|
}
|
|
|
|
function renderIsos() {
|
|
const container = byId('user-iso-list');
|
|
if (!pageState.isos.length) {
|
|
container.replaceChildren(element('p', 'muted', '还没有个人 ISO 镜像。'));
|
|
return;
|
|
}
|
|
const rows = pageState.isos.map(record => {
|
|
const row = element('article', 'user-iso-row');
|
|
const details = element('div', 'user-iso-details');
|
|
const fingerprint = String(record.sha256 || '');
|
|
details.append(element('strong', '', record.name || '未命名 ISO'),
|
|
element('small', '', `${formatBytes(record.size_bytes)}${fingerprint ? ` · SHA-256 ${fingerprint.slice(0, 12)}…` : ''}`));
|
|
const remove = element('button', 'row-button user-iso-delete', '删除');
|
|
remove.type = 'button';
|
|
remove.addEventListener('click', async () => {
|
|
if (!confirm(`删除 ISO“${record.name || record.id}”?未完成账单或仍在安装的实例会阻止删除。`)) return;
|
|
remove.disabled = true;
|
|
try {
|
|
await api(`/api/v1/user-isos/${encodeURIComponent(record.id)}`, { method: 'DELETE' });
|
|
toast('ISO 已从全局个人库删除。', 'success');
|
|
await loadIsos();
|
|
} catch (error) {
|
|
showError('user-iso-list-error', error.message);
|
|
remove.disabled = false;
|
|
}
|
|
});
|
|
row.append(details, remove);
|
|
return row;
|
|
});
|
|
container.replaceChildren(...rows);
|
|
}
|
|
|
|
async function loadIsos() {
|
|
showError('user-iso-list-error', '');
|
|
const epoch = ++pageState.loadEpoch;
|
|
pageState.loadController?.abort();
|
|
pageState.loadController = new AbortController();
|
|
try {
|
|
const result = await api('/api/v1/user-isos', {
|
|
signal: pageState.loadController.signal,
|
|
});
|
|
if (epoch !== pageState.loadEpoch || pageState.stopped) return;
|
|
pageState.isos = Array.isArray(result?.isos) ? result.isos : [];
|
|
pageState.canImport = result?.can_import !== false;
|
|
renderIsos();
|
|
const job = result?.active_import_job;
|
|
const activeJobId = String(job?.job_id || '');
|
|
const status = String(job?.status || '').toLowerCase();
|
|
const jobId = /^[A-Za-z0-9_-]{8,80}$/.test(activeJobId)
|
|
&& ['queued', 'running'].includes(status) ? activeJobId : storedActiveJob();
|
|
if (jobId) {
|
|
rememberActiveJob(jobId);
|
|
pageState.activeStatusUrl = `/api/v1/user-isos/import-jobs/${encodeURIComponent(jobId)}`;
|
|
setImportStatus(job?.phase || '正在远程下载并校验 ISO…');
|
|
updateImportAvailability();
|
|
const statusUrl = pageState.activeStatusUrl;
|
|
window.setTimeout(() => void resumeImport(statusUrl), 0);
|
|
} else if (!pageState.polling) {
|
|
pageState.activeStatusUrl = '';
|
|
setImportStatus('');
|
|
updateImportAvailability();
|
|
}
|
|
} catch (error) {
|
|
if (epoch === pageState.loadEpoch && error.name !== 'AbortError') {
|
|
showError('user-iso-list-error', error.message);
|
|
}
|
|
}
|
|
}
|
|
|
|
function abortError() {
|
|
const error = new Error('ISO 下载任务继续在后台执行。');
|
|
error.name = 'AbortError';
|
|
return error;
|
|
}
|
|
|
|
function cancelPoll() {
|
|
pageState.pollEpoch += 1;
|
|
pageState.pollController?.abort();
|
|
pageState.pollController = null;
|
|
clearTimeout(pageState.pollTimer);
|
|
pageState.pollTimer = 0;
|
|
pageState.pollResolve?.();
|
|
pageState.pollResolve = null;
|
|
pageState.polling = false;
|
|
pageState.busy = false;
|
|
}
|
|
|
|
function startPoll() {
|
|
cancelPoll();
|
|
pageState.pollController = new AbortController();
|
|
pageState.polling = true;
|
|
pageState.busy = true;
|
|
updateImportAvailability();
|
|
return { epoch: pageState.pollEpoch, signal: pageState.pollController.signal };
|
|
}
|
|
|
|
function pollIsCurrent(epoch) {
|
|
return !pageState.stopped && epoch === pageState.pollEpoch;
|
|
}
|
|
|
|
function finishPoll(epoch) {
|
|
if (epoch !== pageState.pollEpoch) return;
|
|
pageState.pollController = null;
|
|
pageState.polling = false;
|
|
pageState.busy = false;
|
|
updateImportAvailability();
|
|
}
|
|
|
|
async function waitForImport(statusUrl, epoch, signal) {
|
|
const started = Date.now();
|
|
try {
|
|
while (Date.now() - started < 65 * 60 * 1000) {
|
|
if (!pollIsCurrent(epoch)) throw abortError();
|
|
const result = await api(statusUrl, { signal });
|
|
if (!pollIsCurrent(epoch)) throw abortError();
|
|
const status = String(result?.status || '').toLowerCase();
|
|
if (status === 'completed' || status === 'succeeded') {
|
|
pageState.activeStatusUrl = '';
|
|
forgetActiveJob();
|
|
setImportStatus('ISO 已导入全局个人库。');
|
|
await loadIsos();
|
|
return;
|
|
}
|
|
if (status === 'failed') {
|
|
pageState.activeStatusUrl = '';
|
|
forgetActiveJob();
|
|
throw new Error(result?.error || 'ISO 下载失败,请检查地址后重试。');
|
|
}
|
|
setImportStatus(result?.phase || '正在远程下载并校验 ISO…');
|
|
await new Promise(resolve => {
|
|
pageState.pollResolve = () => { pageState.pollResolve = null; resolve(); };
|
|
pageState.pollTimer = window.setTimeout(pageState.pollResolve, 2000);
|
|
});
|
|
}
|
|
if (!pollIsCurrent(epoch)) throw abortError();
|
|
throw new Error('任务仍在后台执行,请稍后刷新页面查看。');
|
|
} finally {
|
|
if (epoch === pageState.pollEpoch) {
|
|
clearTimeout(pageState.pollTimer);
|
|
pageState.pollTimer = 0;
|
|
pageState.pollResolve = null;
|
|
}
|
|
}
|
|
}
|
|
|
|
async function resumeImport(statusUrl = pageState.activeStatusUrl) {
|
|
if (!statusUrl || pageState.polling || pageState.stopped
|
|
|| statusUrl !== pageState.activeStatusUrl) return;
|
|
const poll = startPoll();
|
|
try {
|
|
await waitForImport(statusUrl, poll.epoch, poll.signal);
|
|
if (pollIsCurrent(poll.epoch)) toast('ISO 已保存,可用于所有地区。', 'success');
|
|
} catch (error) {
|
|
if (error.name !== 'AbortError' && pollIsCurrent(poll.epoch)) {
|
|
if (error.status === 404) {
|
|
pageState.activeStatusUrl = '';
|
|
forgetActiveJob();
|
|
}
|
|
setImportStatus(error.message, true);
|
|
showError('user-iso-form-error', error.message);
|
|
}
|
|
} finally {
|
|
finishPoll(poll.epoch);
|
|
}
|
|
}
|
|
|
|
async function importIso(event) {
|
|
event.preventDefault();
|
|
if (pageState.busy || pageState.activeStatusUrl || !pageState.canImport) return;
|
|
const name = byId('user-iso-name').value.trim();
|
|
const url = byId('user-iso-url').value.trim();
|
|
let parsed;
|
|
try { parsed = new URL(url); } catch { return showError('user-iso-form-error', '请输入有效的 HTTPS ISO 直链。'); }
|
|
if (parsed.protocol !== 'https:' || !parsed.hostname || parsed.username || parsed.password
|
|
|| (parsed.port && parsed.port !== '443') || parsed.hash) {
|
|
return showError('user-iso-form-error', '仅支持无需账号、使用 443 端口且不含片段的 HTTPS ISO 直链。');
|
|
}
|
|
if (!parsed.pathname.toLowerCase().endsWith('.iso')) {
|
|
return showError('user-iso-form-error', '下载地址的文件名必须以 .iso 结尾。');
|
|
}
|
|
pageState.busy = true;
|
|
let poll = null;
|
|
updateImportAvailability();
|
|
showError('user-iso-form-error', '');
|
|
setImportStatus('正在建立远程下载任务…');
|
|
try {
|
|
const result = await api('/api/v1/user-isos', { method: 'POST', body: { name, url } });
|
|
const jobId = String(result?.job_id || '');
|
|
if (!/^[A-Za-z0-9_-]{8,80}$/.test(jobId)) throw new Error('引擎没有返回有效的下载任务编号。');
|
|
const statusUrl = `/api/v1/user-isos/import-jobs/${encodeURIComponent(jobId)}`;
|
|
pageState.activeStatusUrl = statusUrl;
|
|
rememberActiveJob(jobId);
|
|
byId('user-iso-url').value = '';
|
|
poll = startPoll();
|
|
await waitForImport(statusUrl, poll.epoch, poll.signal);
|
|
if (pollIsCurrent(poll.epoch)) toast('ISO 已保存,可用于所有地区。', 'success');
|
|
} catch (error) {
|
|
const current = poll ? pollIsCurrent(poll.epoch) : !pageState.stopped;
|
|
if (error.name !== 'AbortError' && current) {
|
|
if (error.status === 404) {
|
|
pageState.activeStatusUrl = '';
|
|
forgetActiveJob();
|
|
}
|
|
setImportStatus(error.message, true);
|
|
showError('user-iso-form-error', error.message);
|
|
}
|
|
} finally {
|
|
if (poll) finishPoll(poll.epoch);
|
|
else {
|
|
pageState.busy = false;
|
|
updateImportAvailability();
|
|
}
|
|
}
|
|
}
|
|
|
|
export async function initialize() {
|
|
try {
|
|
if (!await initializeSession('isos')) return;
|
|
bindPageCleanup();
|
|
window.addEventListener('pagehide', () => {
|
|
pageState.stopped = true;
|
|
pageState.loadController?.abort();
|
|
cancelPoll();
|
|
});
|
|
window.addEventListener('pageshow', event => {
|
|
if (!event.persisted) return;
|
|
pageState.stopped = false;
|
|
void loadIsos();
|
|
});
|
|
byId('user-iso-form')?.addEventListener('submit', importIso);
|
|
await loadIsos();
|
|
} catch (error) { showError('cloud-page-error', error.message); }
|
|
}
|