@ -1,9 +1,9 @@
// PHP owns authentication, authorisation, ownership and purchasing. No engine
// address, token, host credential or unrestricted create API exists in this UI.
const byId = ( id ) => document . getElementById ( id ) ;
const state = { csrfToken : '' , userId : '' , username : '' , admin : false , vms : [ ] , plans : [ ] , sshKeys : [ ] , templates : [ ] , resources : null , view : 'list' , selectedVmId : null , metricsRange : '24h' , metricsPayload : null , metricsRequest : null , metricsPollTimer : null , metricsResizeTimer : null , credentialPassword : '' , credentialVisible : false , credentialTimer : null , rfb : null , consoleToken : 0 , loadingVMs : false , selectedKeys : { create : '' , reinstall : '' } , formEpoch : 0 , resourceController : null , orderPoll : null , mutationBusy : false , orderIdempotency : '' , orderFingerprint : '' , renewalIdempotency : { } , rescueActive : false , rescueStaged : false } ;
const RENEWAL _STORAGE _PREFIX = 'virt-cloud:pending-renewal:' ;
const state = { csrfToken : '' , userId : '' , username : '' , admin : false , vms : [ ] , plans : [ ] , sshKeys : [ ] , templates : [ ] , resources : null , invoices : [ ] , invoicePaymentMethods : [ ] , invoicePollTimers : new Map ( ) , view : 'list' , selectedVmId : null , detailTab : 'operations' , metricsRange : '24h' , metricsPayload : null , metricsRequest : null , metricsPollTimer : null , metricsResizeTimer : null , trafficDailyPayload : null , trafficDailyVmId : '' , trafficDailyRequest : null , trafficDailyResizeTimer : null , trafficDailyLoadedAt : 0 , credentialPassword : '' , credentialVisible : false , credentialTimer : null , rfb : null , consoleToken : 0 , loadingVMs : false , selectedKeys : { create : '' , reinstall : '' } , formEpoch : 0 , resourceController : null , orderPoll : null , mutationBusy : false , orderIdempotency : '' , orderFingerprint : '' , rescueActive : false , rescueStaged : false } ;
const ORDER _STORAGE _PREFIX = 'virt-cloud:pending-order:' ;
const INVOICE _PAYMENT _STORAGE _PREFIX = 'virt-cloud:invoice-payment:' ;
const text = ( id , value ) => { byId ( id ) . textContent = value ? ? '—' ; } ;
const items = ( payload ) => Array . isArray ( payload ) ? payload : Array . isArray ( payload ? . items ) ? payload . items : Array . isArray ( payload ? . plans ) ? payload . plans : Array . isArray ( payload ? . orders ) ? payload . orders : Array . isArray ( payload ? . templates ) ? payload . templates : Array . isArray ( payload ? . keys ) ? payload . keys : Array . isArray ( payload ? . vms ) ? payload . vms : [ ] ;
function showError ( id , message ) { text ( id , message ) ; byId ( id ) . hidden = ! message ; }
@ -38,14 +38,6 @@ function firstNumber(...values) {
}
return null ;
}
function firstBoolean ( ... values ) {
for ( const value of values ) {
if ( value === true || value === false ) return value ;
if ( value === 1 || value === '1' || value === 'true' ) return true ;
if ( value === 0 || value === '0' || value === 'false' ) return false ;
}
return null ;
}
function firstText ( ... values ) {
for ( const value of values ) {
if ( value !== null && value !== undefined && String ( value ) . trim ( ) !== '' ) return String ( value ) . trim ( ) ;
@ -69,19 +61,10 @@ function vmServiceData(vm) {
rx !== null && tx !== null ? rx + tx : null ) ;
const remaining = firstNumber ( vm ? . traffic _remaining _bytes , service . traffic _remaining _bytes , period . traffic _remaining _bytes , traffic . remaining _bytes ,
quota !== null && used !== null ? Math . max ( 0 , quota - used ) : null ) ;
const validityDays = firstNumber ( vm ? . renewal _days , vm ? . validity _days , service . renewal _days , service . validity _days , period . renewal _days , period . validity _days , billing . renewal _days , billing . validity _days ) ;
const renewalPrice = firstNumber ( vm ? . renewal _price , service . renewal _price , period . renewal _price , billing . renewal _price ) ;
const renewalQuota = firstNumber ( vm ? . renewal _traffic _bytes , service . renewal _traffic _bytes , period . renewal _traffic _bytes , billing . renewal _traffic _bytes , quota ) ;
const periodStartsAt = vm ? . current _period _starts _at ? ? vm ? . current _period _started _at ? ? vm ? . current _period _start ? ? service . current _period _starts _at ? ? service . current _period _started _at ? ? service . current _period _start ? ? period . started _at ? ? period . starts _at ? ? period . start _at ? ? null ;
const periodEndsAt = vm ? . current _period _ends _at ? ? vm ? . current _period _end ? ? service . current _period _ends _at ? ? service . current _period _end ? ? period . ends _at ? ? period . end _at ? ? null ;
const expiresAt = vm ? . service _expires _at ? ? vm ? . final _expires _at ? ? vm ? . expires _at ? ? vm ? . valid _until ? ? service . service _expires _at ? ? service . final _expires _at ? ? service . expires _at ? ? service . valid _until ? ? period . final _expires _at ? ? period . expires _at ? ? billing . expires _at ? ? null ;
const prepaidPeriods = firstNumber ( vm ? . prepaid _future _periods , vm ? . prepaid _periods , vm ? . future _period _count , vm ? . scheduled _period _count ,
service . prepaid _future _periods , service . prepaid _periods , service . future _period _count , period . prepaid _future _periods , period . prepaid _periods , billing . prepaid _periods ) ;
const status = firstText ( vm ? . service _status , service . status , period . status , billing . status , vm ? . subscription _status ) ;
const networkStatus = firstText ( vm ? . network _status , service . network _status , period . network _status , traffic . network _status ) ;
const renewable = firstBoolean ( vm ? . can _renew , vm ? . renewable , service . can _renew , service . renewable , period . can _renew , period . renewable , billing . can _renew , billing . renewable ) ;
return { quota , rx , tx , used , remaining , validityDays , renewalPrice , renewalQuota , periodStartsAt , periodEndsAt , expiresAt , prepaidPeriods , status , networkStatus , renewable ,
available : Boolean ( status || networkStatus || expiresAt !== null || periodStartsAt !== null || periodEndsAt !== null || [ quota , rx , tx , used , remaining , validityDays , renewalPrice , renewalQuota , prepaidPeriods ] . some ( value => value !== null ) || renewable !== null ) } ;
return { quota , rx , tx , used , remaining , periodEndsAt , status , networkStatus } ;
}
function formatBytes ( value ) {
if ( value === null || ! Number . isFinite ( value ) || value < 0 ) return '暂未提供' ;
@ -108,7 +91,7 @@ function formatServiceDate(value) {
}
function serviceStatusInfo ( data ) {
let status = data . status . toLowerCase ( ) . replace ( /[\s-]+/g , '_' ) ;
if ( ! status && serviceTimestamp ( data . expire sAt) !== null ) status = serviceTimestamp ( data . expire sAt) <= Date . now ( ) ? 'expired' : 'active' ;
if ( ! status && serviceTimestamp ( data . periodEnd sAt) !== null ) status = serviceTimestamp ( data . periodEnd sAt) <= Date . now ( ) ? 'expired' : 'active' ;
const labels = {
active : [ '服务有效' , 'active' ] , pending : [ '待生效' , 'warning' ] , renewing : [ '续费处理中' , 'warning' ] , grace : [ '宽限期' , 'warning' ] ,
resume _pending : [ '等待恢复服务' , 'warning' ] , resuming : [ '正在恢复服务' , 'warning' ] , resume _failed : [ '服务恢复失败,请联系管理员' , 'stopped' ] , suspending : [ '正在暂停' , 'warning' ] ,
@ -132,10 +115,31 @@ function networkStatusInfo(value) {
function selectedVm ( ) { return state . vms . find ( vm => vm . uuid === state . selectedVmId ) ; }
function vmPath ( vm = selectedVm ( ) ) { if ( ! vm ) throw new Error ( '请先选择虚拟机。' ) ; return ` /api/v1/vms/ ${ encodeURIComponent ( vm . api _id ) } ` ; }
function clearCredential ( ) { clearTimeout ( state . credentialTimer ) ; state . credentialPassword = '' ; state . credentialVisible = false ; text ( 'vm-detail-root-password' , '********' ) ; byId ( 'vm-detail-password-reveal' ) . setAttribute ( 'aria-pressed' , 'false' ) ; }
const VM _DETAIL _TABS = [ 'operations' , 'performance' , 'traffic' ] ;
function setVmDetailTab ( tab , focus = false ) {
const next = VM _DETAIL _TABS . includes ( tab ) ? tab : 'operations' ;
state . detailTab = next ;
for ( const name of VM _DETAIL _TABS ) {
const button = byId ( ` vm-detail-tab- ${ name } ` ) ;
const active = name === next ;
button . classList . toggle ( 'active' , active ) ;
button . setAttribute ( 'aria-selected' , String ( active ) ) ;
button . tabIndex = active ? 0 : - 1 ;
byId ( ` vm-detail- ${ name } -panel ` ) . hidden = ! active ;
}
stopVmMetrics ( ) ;
stopVmTrafficDaily ( ) ;
if ( state . view === 'detail' ) {
if ( next === 'performance' ) startVmMetrics ( ) ;
if ( next === 'traffic' ) startVmTrafficDaily ( ) ;
}
if ( focus ) byId ( ` vm-detail-tab- ${ next } ` ) . focus ( ) ;
}
function showView ( view ) {
clearCredential ( ) ; stopVmMetrics ( ) ; state . view = view ;
byId ( 'vm-workspace' ) . hidden = [ 'keys' , 'orders' ] . includes ( view ) ;
byId ( 'ssh-keys-workspace' ) . hidden = view !== 'keys' ; byId ( 'orders-workspace' ) . hidden = view !== 'orders' ;
clearCredential ( ) ; stopVmMetrics ( ) ; stopVmTrafficDaily ( ) ; state . view = view ;
if ( view !== 'invoices' && state . invoicePollTimers . size ) stopInvoicePoll ( ) ;
byId ( 'vm-workspace' ) . hidden = [ 'keys' , 'orders' , 'invoices' ] . includes ( view ) ;
byId ( 'ssh-keys-workspace' ) . hidden = view !== 'keys' ; byId ( 'orders-workspace' ) . hidden = view !== 'orders' ; byId ( 'invoices-workspace' ) . hidden = view !== 'invoices' ;
const sections = { list : 'vm-list-view' , detail : 'vm-detail-view' , create : 'create-view' , reinstall : 'reinstall-view' , rescue : 'rescue-view' } ;
for ( const [ name , id ] of Object . entries ( sections ) ) byId ( id ) . hidden = view !== name ;
const navigationView = [ 'detail' , 'reinstall' , 'rescue' ] . includes ( view ) ? 'list' : view ;
@ -145,13 +149,13 @@ function showView(view) {
if ( active ) button . setAttribute ( 'aria-current' , 'page' ) ;
else button . removeAttribute ( 'aria-current' ) ;
} ) ;
text ( 'breadcrumb-current' , ( { list : '实例管理' , detail : '虚拟机详情' , create : '部署实例' , reinstall : '重装系统' , rescue : '紧急救援' , keys : 'SSH 公钥' , orders : '开通订单' } ) [ view ] ) ;
const hash = ( { list : '' , create : 'plans' , keys : 'keys' , orders : 'orders' } ) [ view ] ? ? ( selectedVm ( ) ? ` vm= ${ encodeURIComponent ( selectedVm ( ) . api _id ) } ` : '' ) ;
text ( 'breadcrumb-current' , ( { list : '实例管理' , detail : '虚拟机详情' , create : '部署实例' , reinstall : '重装系统' , rescue : '紧急救援' , keys : 'SSH 公钥' , orders : '开通订单' , invoices : '续费账单' } ) [ view ] ) ;
const hash = ( { list : '' , create : 'plans' , keys : 'keys' , orders : 'orders' , invoices : 'invoices' } ) [ view ] ? ? ( selectedVm ( ) ? ` vm= ${ encodeURIComponent ( selectedVm ( ) . api _id ) } ` : '' ) ;
history . replaceState ( null , '' , ` ${ location . pathname } ${ location . search } ${ hash ? '#' + hash : '' } ` ) ;
window . scrollTo ( { top : 0 , behavior : 'auto' } ) ;
if ( view === 'detail' ) s tartVmMetrics( ) ;
if ( view === 'detail' ) s etVmDetailTab( state . detailTab ) ;
}
async function routeHash ( hash = location . hash ) { const target = hash . replace ( /^#/ , '' ) ; try { if ( target === 'plans' ) await openCreate ( ) ; else if ( target === 'keys' ) { showView ( 'keys' ) ; await loadKeys ( ) ; } else if ( target === 'orders' ) { showView ( 'orders' ) ; await loadOrders ( ) ; } else if ( target . startsWith ( 'vm=' ) ) { const id = decodeURIComponent ( target . slice ( 3 ) ) ; const vm = state . vms . find ( item => item . api _id === id ) ; if ( vm ) openVmDetail ( vm . uuid ) ; else showView ( 'list' ) ; } else showView ( 'list' ) ; } catch ( error ) { showError ( 'cloud-page-error' , error . message ) ; } }
async function routeHash ( hash = location . hash ) { const target = hash . replace ( /^#/ , '' ) ; try { if ( target === 'plans' ) await openCreate ( ) ; else if ( target === 'keys' ) { showView ( 'keys' ) ; await loadKeys ( ) ; } else if ( target === 'orders' ) { showView ( 'orders' ) ; await loadOrders ( ) ; } else if ( target === 'invoices' ) { showView ( 'invoices' ) ; await loadInvoices ( ) ; } else if ( target . startsWith ( 'vm=' ) ) { const id = decodeURIComponent ( target . slice ( 3 ) ) ; const vm = state . vms . find ( item => item . api _id === id ) ; if ( vm ) openVmDetail ( vm . uuid ) ; else showView ( 'list' ) ; } else showView ( 'list' ) ; } catch ( error ) { showError ( 'cloud-page-error' , error . message ) ; } }
async function loadVms ( ) {
if ( state . loadingVMs ) return ;
state . loadingVMs = true ;
@ -159,7 +163,7 @@ async function loadVms() {
catch ( error ) { showError ( 'cloud-page-error' , error . message ) ; if ( ! state . vms . length ) renderVMs ( true ) ; }
finally { state . loadingVMs = false ; }
}
function openVmDetail ( uuid ) { const vm = state . vms . find ( item => item . uuid === String ( uuid ) ) ; if ( ! vm ) return toast ( '虚拟机不存在,请刷新。' , 'error' ) ; state . selectedVmId = vm . uuid ; renderVmDetail( vm ) ; showView ( 'detail' ) ; clearVmMetrics ( '正在加载监控数据… ') ; }
function openVmDetail ( uuid ) { const vm = state . vms . find ( item => item . uuid === String ( uuid ) ) ; if ( ! vm ) return toast ( '虚拟机不存在,请刷新。' , 'error' ) ; state . selectedVmId = vm . uuid ; state. detailTab = 'operations' ; clearVmMetrics ( '打开“性能监控”页签后加载监控数据。' ) ; clearVmTrafficDaily ( '打开“流量信息”页签后加载最近 30 天数据。' ) ; renderVmDetail ( vm ) ; showView ( 'detail ') ; }
function renderVmDetail ( vm ) {
text ( 'vm-detail-name' , vm . name ) ; text ( 'vm-detail-state' , stateLabel ( vm . state ) ) ; byId ( 'vm-detail-state' ) . className = ` state-pill ${ stateCategory ( vm . state ) } ` ;
for ( const id of [ 'vm-detail-region' , 'vm-detail-header-region' ] ) text ( id , vmRegion ( vm ) ) ;
@ -179,7 +183,7 @@ function renderVmDetail(vm) {
} else {
primary . append ( makeElement ( 'p' , 'muted' , '这是其他用户的实例;当前管理员账户只有查看权限。' ) ) ;
}
if ( state . mutationBusy ) document . querySelectorAll ( '#vm-detail-primary-actions button,#vm-detail-danger-actions button ,#vm-detail-renew-button ') . forEach ( button => { button . disabled = true ; } ) ;
if ( state . mutationBusy ) document . querySelectorAll ( '#vm-detail-primary-actions button,#vm-detail-danger-actions button ') . forEach ( button => { button . disabled = true ; } ) ;
}
function renderVmService ( vm ) {
const data = vmServiceData ( vm ) ;
@ -191,15 +195,11 @@ function renderVmService(vm) {
const networkStatusElement = byId ( 'vm-detail-network-status' ) ;
networkStatusElement . textContent = networkStatus . label ;
networkStatusElement . className = ` service-pill ${ networkStatus . className } ` ;
text ( 'vm-detail-period-start' , formatServiceDate ( data . periodStartsAt ) ) ;
text ( 'vm-detail-period-end' , formatServiceDate ( data . periodEndsAt ) ) ;
text ( 'vm-detail-expires-at' , formatServiceDate ( data . expiresAt ) ) ;
text ( 'vm-detail-prepaid-periods' , data . prepaidPeriods === null ? '暂未提供' : ` ${ Math . floor ( data . prepaidPeriods ) } 个 ` ) ;
text ( 'vm-detail-traffic-rx' , formatBytes ( data . rx ) ) ;
text ( 'vm-detail-traffic-tx' , formatBytes ( data . tx ) ) ;
text ( 'vm-detail-traffic-used' , formatBytes ( data . used ) ) ;
text ( 'vm-detail-traffic-quota' , formatTrafficQuota ( data . quota ) ) ;
text ( 'vm-detail-traffic-remaining' , data . quota === 0 ? '不限流量' : formatBytes ( data . remaining ) ) ;
text ( 'vm-detail-traffic-total-remaining' , ` ${ formatTrafficQuota ( data . quota ) } / ${ data . quota === 0 ? '不限流量' : formatBytes ( data . remaining ) } ` ) ;
const progress = byId ( 'vm-detail-traffic-progress' ) ;
const ratio = data . quota !== null && data . quota > 0 && data . used !== null ? Math . max ( 0 , Math . min ( 100 , data . used / data . quota * 100 ) ) : null ;
progress . hidden = ratio === null ;
@ -212,64 +212,10 @@ function renderVmService(vm) {
byId ( 'vm-detail-traffic-progress-bar' ) . style . width = '0' ;
progress . classList . remove ( 'is-exhausted' ) ;
}
const renewButton = byId ( 'vm-detail-renew-button' ) ;
const hasRenewalMetadata = data . renewable !== null || data . validityDays !== null || data . renewalPrice !== null ;
renewButton . hidden = vm . is _owner === false || ! data . available || ! hasRenewalMetadata ;
renewButton . disabled = state . mutationBusy || data . renewable === false ;
renewButton . textContent = data . renewalPrice !== null && data . validityDays !== null
? ` 续费 ${ Math . floor ( data . validityDays ) } 天 · ¥ ${ data . renewalPrice . toFixed ( 2 ) } ` : '立即续费' ;
renewButton . title = data . renewable === false ? '当前实例暂不能续费' : '购买下一个服务周期' ;
let note = '接口暂未提供服务周期与流量信息。' ;
if ( data . available ) {
note = '流量按当前账期单独计算;用尽时仅暂停网络,下一账期开始流量归零并自动恢复网络。' ;
if ( data . prepaidPeriods !== null && data . prepaidPeriods > 0 ) note += ` 已预付 ${ Math . floor ( data . prepaidPeriods ) } 个未来账期。 ` ;
if ( data . renewable !== false ) note += ' 续费购买的下一账期会从当前已购期限末尾开始。' ;
}
text ( 'vm-detail-service-note' , note ) ;
}
async function powerAction ( action , dangerous = false ) { const vm = selectedVm ( ) ; if ( ! vm ? . can _mutate ) return toast ( '当前账户只有查看权限。' , 'error' ) ; if ( state . mutationBusy ) return ; if ( dangerous && ! confirm ( '此操作会强制断电,可能丢失未保存的数据。确认继续?' ) ) return ; state . mutationBusy = true ; setDetailBusy ( true ) ; try { const result = await api ( ` ${ vmPath ( ) } /actions ` , { method : 'POST' , body : { action } } ) ; toast ( '电源任务已提交,正在执行…' ) ; if ( result . job _id ) await pollJob ( 'power' , result . job _id ) ; toast ( '电源操作已完成。' , 'success' ) ; await loadVms ( ) ; } catch ( error ) { toast ( error . message , 'error' ) ; } finally { state . mutationBusy = false ; setDetailBusy ( false ) ; } }
async function deleteVm ( ) { const vm = selectedVm ( ) ; if ( ! vm ? . can _mutate ) return toast ( '当前账户只有查看权限。' , 'error' ) ; if ( state . mutationBusy ) return ; const confirmation = prompt ( ` 永久删除“ ${ vm . name } ”及面板管理的虚拟磁盘,此操作不可恢复。请输入完整虚拟机名称确认: ` ) ; if ( confirmation === null ) return ; if ( confirmation !== vm . name ) return toast ( '虚拟机名称不匹配,未执行删除。' , 'error' ) ; state . mutationBusy = true ; setDetailBusy ( true ) ; try { const result = await api ( vmPath ( vm ) , { method : 'DELETE' , body : { confirmation _name : vm . name , delete _disks : true } } ) ; toast ( '删除任务已提交,正在执行…' ) ; if ( result . job _id ) await pollJob ( 'delete' , result . job _id ) ; toast ( '虚拟机删除已完成。' , 'success' ) ; state . selectedVmId = null ; showView ( 'list' ) ; await loadVms ( ) ; } catch ( error ) { toast ( error . message , 'error' ) ; } finally { state . mutationBusy = false ; setDetailBusy ( false ) ; } }
function setDetailBusy ( busy ) { if ( ! busy && selectedVm ( ) ) renderVmDetail ( selectedVm ( ) ) ; else if ( busy ) document . querySelectorAll ( '#vm-detail-primary-actions button,#vm-detail-danger-actions button,#vm-detail-renew-button' ) . forEach ( button => { button . disabled = true ; } ) ; }
function renewalStorageKey ( vmId ) { return ` ${ RENEWAL _STORAGE _PREFIX } ${ vmId } ` ; }
function pendingRenewalKey ( vmId ) {
if ( state . renewalIdempotency [ vmId ] ) return state . renewalIdempotency [ vmId ] ;
let key = '' ;
try { key = sessionStorage . getItem ( renewalStorageKey ( vmId ) ) || '' ; } catch { }
if ( ! /^[A-Za-z0-9_.-]{16,128}$/ . test ( key ) ) key = crypto . randomUUID ( ) ;
state . renewalIdempotency [ vmId ] = key ;
try { sessionStorage . setItem ( renewalStorageKey ( vmId ) , key ) ; } catch { }
return key ;
}
function clearPendingRenewalKey ( vmId ) {
delete state . renewalIdempotency [ vmId ] ;
try { sessionStorage . removeItem ( renewalStorageKey ( vmId ) ) ; } catch { }
}
async function renewVm ( ) {
const vm = selectedVm ( ) ;
if ( ! vm || state . mutationBusy ) return ;
const service = vmServiceData ( vm ) ;
if ( service . renewable === false ) return toast ( '当前实例暂不能续费。' , 'error' ) ;
const details = [ ] ;
if ( service . renewalPrice !== null ) details . push ( ` 从账户余额支付 ¥ ${ service . renewalPrice . toFixed ( 2 ) } ` ) ;
if ( service . validityDays !== null ) details . push ( ` 购买下一个 ${ Math . floor ( service . validityDays ) } 天账期 ` ) ;
if ( service . renewalQuota !== null ) details . push ( ` 下一账期流量额度 ${ formatTrafficQuota ( service . renewalQuota ) } ` ) ;
const prompt = ` ${ details . length ? details . join ( ', ' ) : '确认购买下一个服务账期' } 。下一账期将从当前已购买期限末尾生效,确认续费? ` ;
if ( ! confirm ( prompt ) ) return ;
state . mutationBusy = true ;
setDetailBusy ( true ) ;
const key = pendingRenewalKey ( vm . api _id ) ;
try {
await api ( ` ${ vmPath ( vm ) } /renewals ` , { method : 'POST' , body : { idempotency _key : key } } ) ;
clearPendingRenewalKey ( vm . api _id ) ;
await loadVms ( ) ;
toast ( '续费成功,下一账期将在当前已购期限末尾生效。已关机的虚拟机仍保持关机,需要时请手动开机。' , 'success' ) ;
} catch ( error ) {
toast ( ` ${ error . message } 可再次点击续费安全核对同一请求。 ` , 'error' ) ;
} finally {
state . mutationBusy = false ;
setDetailBusy ( false ) ;
}
}
function setDetailBusy ( busy ) { if ( ! busy && selectedVm ( ) ) renderVmDetail ( selectedVm ( ) ) ; else if ( busy ) document . querySelectorAll ( '#vm-detail-primary-actions button,#vm-detail-danger-actions button' ) . forEach ( button => { button . disabled = true ; } ) ; }
async function credential ( copy = false ) {
const vm = selectedVm ( ) ; if ( ! vm ? . can _view _credential || ! vm . password _available ) return ;
if ( ! copy && state . credentialVisible ) return clearCredential ( ) ;
@ -337,6 +283,31 @@ function clearPendingOrderKey() {
state . orderFingerprint = '' ;
try { sessionStorage . removeItem ( orderStorageKey ( ) ) ; } catch { }
}
function invoicePaymentStorageKey ( invoiceId , methodId ) {
return ` ${ INVOICE _PAYMENT _STORAGE _PREFIX } ${ state . userId || 'unknown' } : ${ invoiceId } : ${ methodId } ` ;
}
function pendingInvoicePaymentKey ( invoiceId , methodId ) {
const storageKey = invoicePaymentStorageKey ( invoiceId , methodId ) ;
let key = '' ;
try { key = String ( sessionStorage . getItem ( storageKey ) || '' ) ; } catch { }
if ( ! /^[A-Za-z0-9_.-]{16,128}$/ . test ( key ) ) key = crypto . randomUUID ( ) ;
try { sessionStorage . setItem ( storageKey , key ) ; } catch { }
return key ;
}
function clearInvoicePaymentKey ( invoiceId , methodId ) {
try { sessionStorage . removeItem ( invoicePaymentStorageKey ( invoiceId , methodId ) ) ; } catch { }
}
function clearInvoicePaymentKeys ( invoiceId ) {
const prefix = ` ${ INVOICE _PAYMENT _STORAGE _PREFIX } ${ state . userId || 'unknown' } : ${ invoiceId } : ` ;
try {
const keys = [ ] ;
for ( let index = 0 ; index < sessionStorage . length ; index += 1 ) {
const key = sessionStorage . key ( index ) ;
if ( key ? . startsWith ( prefix ) ) keys . push ( key ) ;
}
keys . forEach ( key => sessionStorage . removeItem ( key ) ) ;
} catch { }
}
async function existingPendingOrder ( key ) {
try { return await api ( ` /api/v1/orders/by-request/ ${ encodeURIComponent ( key ) } ` ) ; }
catch ( error ) { if ( error . status === 404 ) return null ; throw error ; }
@ -349,7 +320,7 @@ async function buy(event) {
if ( ! byId ( 'vm-plan' ) . value || ! state . resources ) return showError ( 'create-error' , '请先选择可用套餐。' ) ;
const selectedPlan = state . plans . find ( plan => String ( plan . id ) === byId ( 'vm-plan' ) . value ) ;
const purchaseSummary = selectedPlan ? ` 每期 ¥ ${ selectedPlan . price } , ${ planBillingLabel ( selectedPlan ) } ` : '所选套餐' ;
if ( ! confirm ( ` 确认从账户余额支付并开通虚拟机? ${ purchaseSummary } 。到期前 可手动续费 。` ) ) return ;
if ( ! confirm ( ` 确认从账户余额支付并开通虚拟机? ${ purchaseSummary } 。到期前 7 天会自动生成续费账单 。` ) ) return ;
state . mutationBusy = true ; byId ( 'create-submit' ) . disabled = true ; showError ( 'create-error' , '' ) ;
const body = { plan _id : Number ( byId ( 'vm-plan' ) . value ) , name : byId ( 'vm-name' ) . value . trim ( ) , source : sourceMode ( ) } ;
if ( cloud ) { body . template _id = byId ( 'vm-template' ) . value ; if ( state . selectedKeys . create ) body . guest _ssh _key _id = state . selectedKeys . create ; if ( password ) body . root _password = password ; } else body . iso _path = byId ( 'vm-iso' ) . value ;
@ -412,6 +383,175 @@ async function loadOrders() {
}
} catch ( error ) { showError ( 'cloud-page-error' , error . message ) ; }
}
function invoiceStatusInfo ( status ) {
const values = {
open : [ '待支付' , 'warning' ] , overdue : [ '已逾期' , 'failed' ] ,
paid : [ '已支付' , 'running' ] , void : [ '已失效' , 'other' ] ,
} ;
return values [ String ( status || '' ) . toLowerCase ( ) ] || [ String ( status || '未知' ) , 'other' ] ;
}
function validPaymentUrl ( value ) {
try {
const url = new URL ( String ( value || '' ) ) ;
return [ 'https:' , 'weixin:' , 'alipays:' , 'alipayqr:' ] . includes ( url . protocol ) ? url . href : '' ;
}
catch { return '' ; }
}
function appendPaymentQr ( container , value ) {
if ( ! value || typeof window . QRCode !== 'function' ) return false ;
const qr = makeElement ( 'div' , 'cloud-payment-qr' ) ;
try {
const levels = window . QRCode . CorrectLevel || { L : 1 , M : 0 } ;
new window . QRCode ( qr , {
text : String ( value ) , width : 196 , height : 196 ,
correctLevel : String ( value ) . length > 1200 ? levels . L : levels . M ,
} ) ;
if ( ! qr . children . length ) return false ;
container . append ( qr ) ;
return true ;
} catch { return false ; }
}
function stopInvoicePoll ( invoiceId = null ) {
if ( invoiceId !== null ) {
const key = String ( invoiceId ) ;
const timer = state . invoicePollTimers . get ( key ) ;
if ( timer !== undefined ) clearTimeout ( timer ) ;
state . invoicePollTimers . delete ( key ) ;
return ;
}
for ( const timer of state . invoicePollTimers . values ( ) ) clearTimeout ( timer ) ;
state . invoicePollTimers . clear ( ) ;
}
function scheduleInvoicePoll ( invoiceId ) {
const key = String ( invoiceId ) ;
stopInvoicePoll ( key ) ;
const started = Date . now ( ) ;
const poll = async ( ) => {
if ( state . view !== 'invoices' ) return stopInvoicePoll ( key ) ;
try {
const result = await api ( ` /api/v1/invoices/ ${ encodeURIComponent ( key ) } ` ) ;
if ( result . invoice ? . status === 'paid' ) {
stopInvoicePoll ( key ) ; toast ( '账单支付成功,服务期限已延长。' , 'success' ) ; await loadInvoices ( ) ; await loadVms ( ) ; return ;
}
if ( [ 'void' ] . includes ( result . invoice ? . status ) ) {
stopInvoicePoll ( key ) ; toast ( '账单已失效,到账金额会保留在账户余额中。' , 'error' ) ; await loadInvoices ( ) ; return ;
}
} catch { }
if ( Date . now ( ) - started < 10 * 60 * 1000 ) {
state . invoicePollTimers . set ( key , setTimeout ( poll , 3000 ) ) ;
} else {
stopInvoicePoll ( key ) ;
await loadInvoices ( ) ;
}
} ;
state . invoicePollTimers . set ( key , setTimeout ( poll , 3000 ) ) ;
}
function renderOnlinePayment ( container , payment ) {
let box = container . querySelector ( '.cloud-payment-instructions' ) ;
if ( ! box ) { box = makeElement ( 'div' , 'cloud-payment-instructions' ) ; container . append ( box ) ; }
box . replaceChildren ( ) ;
if ( payment . payment _kind === 'usdt' ) {
box . append ( makeElement ( 'strong' , '' , ` 请支付 ${ payment . actual _amount } USDT( TRC20) ` ) ,
makeElement ( 'code' , '' , payment . receive _address || '收款地址不可用' ) ,
makeElement ( 'small' , '' , ` 支付订单有效至 ${ formatOrderDate ( payment . expires _at ) } ;链上确认后自动结清账单。 ` ) ) ;
appendPaymentQr ( box , payment . receive _address || '' ) ;
const copy = actionButton ( '复制收款地址' , async ( ) => {
try { await copyText ( payment . receive _address || '' ) ; toast ( 'USDT 收款地址已复制。' , 'success' ) ; }
catch ( error ) { toast ( error . message , 'error' ) ; }
} ) ;
box . append ( copy ) ;
} else {
const url = validPaymentUrl ( payment . payment _value ) ;
box . append ( makeElement ( 'strong' , '' , ` ${ payment . label || '在线支付' } 订单已生成 ` ) ) ;
appendPaymentQr ( box , payment . payment _value || '' ) ;
if ( url ) {
const link = makeElement ( 'a' , 'button button-primary small' , '前往支付' ) ;
link . href = url ; link . target = '_blank' ; link . rel = 'noopener noreferrer' ; box . append ( link ) ;
} else {
box . append ( makeElement ( 'code' , '' , payment . payment _value || '支付信息暂不可用' ) ) ;
const copy = actionButton ( '复制支付信息' , async ( ) => {
try { await copyText ( payment . payment _value || '' ) ; toast ( '支付信息已复制。' , 'success' ) ; }
catch ( error ) { toast ( error . message , 'error' ) ; }
} ) ;
box . append ( copy ) ;
}
box . append ( makeElement ( 'small' , '' , '完成付款后本页会自动核对账单状态。请勿同时使用多个渠道重复付款。' ) ) ;
}
scheduleInvoicePoll ( payment . invoice _id ) ;
}
async function payInvoiceBalance ( invoice , row ) {
if ( state . mutationBusy || ! confirm ( ` 确认使用账户余额支付账单 ${ invoice . invoice _no } ,金额 ¥ ${ invoice . amount } ? ` ) ) return ;
state . mutationBusy = true ;
row . querySelectorAll ( 'button' ) . forEach ( button => { button . disabled = true ; } ) ;
try {
await api ( ` /api/v1/invoices/ ${ encodeURIComponent ( invoice . id ) } /pay-balance ` , {
method : 'POST' , body : { idempotency _key : crypto . randomUUID ( ) } ,
} ) ;
toast ( '账单已支付,服务期限已延长。' , 'success' ) ; await loadInvoices ( ) ; await loadVms ( ) ;
} catch ( error ) { toast ( error . message , 'error' ) ; }
finally {
state . mutationBusy = false ;
row . querySelectorAll ( 'button' ) . forEach ( button => { button . disabled = false ; } ) ;
}
}
async function createInvoicePayment ( invoice , method , row ) {
if ( state . mutationBusy || ! confirm ( ` 确认通过“ ${ method . name } ”生成 ¥ ${ invoice . amount } 的支付订单? ` ) ) return ;
state . mutationBusy = true ;
row . querySelectorAll ( 'button' ) . forEach ( button => { button . disabled = true ; } ) ;
const idempotencyKey = pendingInvoicePaymentKey ( invoice . id , method . id ) ;
try {
const result = await api ( ` /api/v1/invoices/ ${ encodeURIComponent ( invoice . id ) } /payments ` , {
method : 'POST' , body : { method : method . id , idempotency _key : idempotencyKey } ,
} ) ;
renderOnlinePayment ( row , result . payment || { } ) ;
} catch ( error ) {
// A transport failure may hide a successfully created provider order, so
// retain the key and recover it on the next click. Only a definite 4xx
// rejection proves no ambiguous 5xx/network outcome needs reconciling.
const status = Number ( error . status || 0 ) ;
const ambiguousHttpFailure = [ 408 , 425 , 429 ] . includes ( status ) ;
if ( status >= 400 && status < 500 && ! ambiguousHttpFailure
&& ! String ( error . message ) . includes ( '正在创建' ) ) {
clearInvoicePaymentKey ( invoice . id , method . id ) ;
}
toast ( error . message , 'error' ) ;
}
finally { state . mutationBusy = false ; row . querySelectorAll ( 'button' ) . forEach ( button => { button . disabled = false ; } ) ; }
}
function renderInvoices ( ) {
const container = byId ( 'invoices-list' ) ; container . replaceChildren ( ) ;
if ( ! state . invoices . length ) return container . append ( makeElement ( 'p' , 'muted' , '暂无续费账单。账单会在实例到期前 7 天自动生成。' ) ) ;
for ( const invoice of state . invoices ) {
const row = makeElement ( 'article' , 'cloud-order cloud-invoice' ) ;
const detail = makeElement ( 'div' , 'cloud-order-detail' ) ;
detail . append ( makeElement ( 'strong' , '' , ` ${ invoice . instance _name || '实例' } · ¥ ${ invoice . amount } ` ) ,
makeElement ( 'p' , 'muted' , ` 账单 ${ invoice . invoice _no } · 到期时间 ${ formatOrderDate ( invoice . due _at ) } ` ) ,
makeElement ( 'p' , 'cloud-order-message' , ` 支付后增加 ${ invoice . validity _days } 天服务期 · 新账期流量 ${ formatTrafficQuota ( Number ( invoice . traffic _quota _bytes || 0 ) ) } ` ) ) ;
const actions = makeElement ( 'div' , 'cloud-order-actions' ) ;
const [ label , className ] = invoiceStatusInfo ( invoice . status ) ;
actions . append ( makeElement ( 'span' , ` state-pill ${ className } ` , label ) ) ;
if ( [ 'open' , 'overdue' ] . includes ( invoice . status ) ) {
actions . append ( actionButton ( '余额支付' , ( ) => payInvoiceBalance ( invoice , row ) ) ) ;
for ( const method of state . invoicePaymentMethods ) actions . append ( actionButton ( method . name , ( ) => createInvoicePayment ( invoice , method , row ) ) ) ;
} else if ( invoice . status === 'paid' ) {
stopInvoicePoll ( invoice . id ) ;
clearInvoicePaymentKeys ( invoice . id ) ;
actions . append ( makeElement ( 'span' , 'muted' , invoice . paid _at ? ` 支付于 ${ formatOrderDate ( invoice . paid _at ) } ` : '已结清' ) ) ;
} else if ( invoice . status === 'void' ) {
stopInvoicePoll ( invoice . id ) ;
clearInvoicePaymentKeys ( invoice . id ) ;
}
row . append ( detail , actions ) ; container . append ( row ) ;
}
}
async function loadInvoices ( ) {
try {
const payload = await api ( '/api/v1/invoices' ) ;
state . invoices = Array . isArray ( payload . invoices ) ? payload . invoices : [ ] ;
state . invoicePaymentMethods = Array . isArray ( payload . payment _methods ) ? payload . payment _methods : [ ] ;
text ( 'invoices-balance' , ` ¥ ${ payload . balance ? ? '—' } ` ) ; renderInvoices ( ) ; showError ( 'cloud-page-error' , '' ) ;
} catch ( error ) { showError ( 'cloud-page-error' , error . message ) ; }
}
async function openReinstall ( vm ) {
if ( ! vm ? . can _mutate ) return toast ( '当前账户只有查看权限。' , 'error' ) ;
showView ( 'reinstall' ) ; text ( 'reinstall-subtitle' , ` ${ vm . name } · 保留原有公网网络参数,重新创建系统盘。 ` ) ; text ( 'reinstall-public-ip' , vmIp ( vm ) ) ; byId ( 'reinstall-confirm-name' ) . value = '' ; byId ( 'reinstall-root-password' ) . value = '' ; byId ( 'reinstall-template' ) . value = '' ; showError ( 'reinstall-error' , '' ) ; byId ( 'reinstall-progress' ) . hidden = true ; byId ( 'reinstall-result' ) . hidden = true ; byId ( 'reinstall-fields' ) . hidden = false ;
@ -675,7 +815,7 @@ const VM_METRIC_CHARTS = [
] ;
function metricViewVisible ( ) {
return Boolean ( state . selectedVmId ) && ! document . hidden && ! byId ( "dashboard-view" ) . hidden
return state . view === "detail" && state . detailTab === "performance" && Boolean ( state . selectedVmId ) && ! document . hidden && ! byId ( "dashboard-view" ) . hidden
&& ! byId ( "vm-workspace" ) . hidden && ! byId ( "vm-detail-view" ) . hidden ;
}
@ -898,6 +1038,180 @@ function renderVmMetrics(payload) {
setVmMetricsStatus ( ` ${ visiblePoints . length } 个采样点 · ${ stale ? "最近历史记录" : "最近采样" } ${ formatMetricTime ( latest ) } · 每分钟自动刷新 ${ stale ? "(当前无新数据)" : "" } ` , stale ) ;
}
function trafficDailyViewVisible ( ) {
return state . view === "detail" && state . detailTab === "traffic" && Boolean ( state . selectedVmId ) && ! document . hidden
&& ! byId ( "dashboard-view" ) . hidden && ! byId ( "vm-workspace" ) . hidden && ! byId ( "vm-detail-view" ) . hidden ;
}
function stopVmTrafficDaily ( ) {
state . trafficDailyRequest ? . controller . abort ( ) ;
state . trafficDailyRequest = null ;
if ( state . trafficDailyResizeTimer ) window . clearTimeout ( state . trafficDailyResizeTimer ) ;
state . trafficDailyResizeTimer = null ;
}
function setVmTrafficDailyStatus ( message , warning = false ) {
const status = byId ( "vm-traffic-daily-status" ) ;
status . textContent = message ;
status . classList . toggle ( "warning" , warning ) ;
}
function clearVmTrafficDaily ( message ) {
stopVmTrafficDaily ( ) ;
state . trafficDailyPayload = null ;
state . trafficDailyVmId = "" ;
state . trafficDailyLoadedAt = 0 ;
setVmTrafficDailyStatus ( message ) ;
byId ( "vm-traffic-daily-plot" ) . replaceChildren ( makeElement ( "p" , "vm-metric-empty" , message ) ) ;
}
function trafficDailyItems ( payload ) {
if ( Array . isArray ( payload ) ) return payload ;
for ( const value of [ payload ? . points , payload ? . days , payload ? . items , payload ? . daily , payload ? . data ? . points , payload ? . data ? . days , payload ? . data ] ) {
if ( Array . isArray ( value ) ) return value ;
}
return null ;
}
function trafficDailyDate ( point ) {
const value = point ? . date ? ? point ? . day ? ? point ? . bucket _date ? ? point ? . observed _date ? ? point ? . day _start ? ? point ? . timestamp ? ? point ? . time ;
const dateText = typeof value === "string" ? value . trim ( ) : "" ;
if ( /^\d{4}-\d{2}-\d{2}$/ . test ( dateText ) ) {
return { timestamp : Date . parse ( ` ${ dateText } T00:00:00Z ` ) , label : dateText } ;
}
const timestamp = serviceTimestamp ( value ) ;
if ( timestamp === null ) return null ;
const date = new Date ( timestamp ) ;
return { timestamp , label : ` ${ date . getUTCFullYear ( ) } - ${ String ( date . getUTCMonth ( ) + 1 ) . padStart ( 2 , "0" ) } - ${ String ( date . getUTCDate ( ) ) . padStart ( 2 , "0" ) } ` } ;
}
function normalizeTrafficDailyPoints ( payload ) {
const values = trafficDailyItems ( payload ) ;
if ( values === null ) throw new Error ( "每日流量数据格式无效" ) ;
const points = [ ] ;
for ( const point of values ) {
const date = trafficDailyDate ( point ) ;
if ( ! date ) continue ;
const download = firstNumber ( point ? . download _bytes , point ? . rx _bytes , point ? . traffic _download _bytes , point ? . download , point ? . rx ) ;
const upload = firstNumber ( point ? . upload _bytes , point ? . tx _bytes , point ? . traffic _upload _bytes , point ? . upload , point ? . tx ) ;
points . push ( { ... date , download , upload } ) ;
}
return points . sort ( ( a , b ) => a . timestamp - b . timestamp ) . slice ( - 30 ) ;
}
function trafficDailyShortDate ( point ) {
return point . label . slice ( 5 ) . replace ( "-" , "/" ) ;
}
function drawVmTrafficDaily ( payload ) {
const plot = byId ( "vm-traffic-daily-plot" ) ;
const points = normalizeTrafficDailyPoints ( payload ) ;
if ( ! points . length ) {
plot . replaceChildren ( makeElement ( "p" , "vm-metric-empty" , "最近 30 天暂无每日流量记录。" ) ) ;
setVmTrafficDailyStatus ( "最近 30 天暂无每日流量记录。" , true ) ;
return ;
}
const values = points . flatMap ( point => [ point . download , point . upload ] ) . filter ( value => value !== null ) ;
if ( ! values . length ) {
plot . replaceChildren ( makeElement ( "p" , "vm-metric-empty" , "最近 30 天暂无每日流量采样。" ) ) ;
setVmTrafficDailyStatus ( "最近 30 天暂无每日流量采样。" , true ) ;
return ;
}
const maximum = metricNiceMax ( Math . max ( ... values ) ) ;
const width = Math . max ( 300 , Math . floor ( plot . clientWidth || 800 ) ) ;
const height = Math . max ( 220 , Math . floor ( plot . clientHeight || 290 ) ) ;
const left = 68 ;
const right = 18 ;
const top = 18 ;
const bottom = 38 ;
const plotWidth = width - left - right ;
const plotHeight = height - top - bottom ;
const groupWidth = plotWidth / points . length ;
const barWidth = Math . max ( 2 , Math . min ( 12 , groupWidth * . 32 ) ) ;
const y = ( value ) => top + ( 1 - Math . min ( value , maximum ) / maximum ) * plotHeight ;
const totalDownload = points . reduce ( ( sum , point ) => sum + ( point . download ? ? 0 ) , 0 ) ;
const totalUpload = points . reduce ( ( sum , point ) => sum + ( point . upload ? ? 0 ) , 0 ) ;
const sampledDays = points . filter ( point => point . download !== null || point . upload !== null ) . length ;
const svg = metricSvgElement ( "svg" , {
viewBox : ` 0 0 ${ width } ${ height } ` ,
role : "img" ,
"aria-label" : ` 最近 ${ points . length } 天每日流量;下载 ${ formatBytes ( totalDownload ) } ,上传 ${ formatBytes ( totalUpload ) } ` ,
} ) ;
for ( const fraction of [ 1 , . 5 , 0 ] ) {
const lineY = top + ( 1 - fraction ) * plotHeight ;
svg . append ( metricSvgElement ( "line" , { x1 : left , x2 : width - right , y1 : lineY , y2 : lineY , class : "vm-metric-gridline" } ) ) ;
const label = metricSvgElement ( "text" , { x : left - 8 , y : lineY + 4 , "text-anchor" : "end" , class : "vm-metric-axis-label" } ) ;
label . textContent = formatBytes ( fraction * maximum ) ;
svg . append ( label ) ;
}
points . forEach ( ( point , index ) => {
const center = left + ( index + . 5 ) * groupWidth ;
for ( const [ value , className , offset ] of [ [ point . download , "download" , - barWidth ] , [ point . upload , "upload" , 0 ] ] ) {
if ( value === null ) continue ;
const topY = y ( value ) ;
const bar = metricSvgElement ( "rect" , {
x : center + offset ,
y : topY ,
width : barWidth ,
height : Math . max ( 1 , top + plotHeight - topY ) ,
rx : Math . min ( 2 , barWidth / 3 ) ,
class : ` vm-traffic-daily-bar ${ className } ` ,
} ) ;
const title = metricSvgElement ( "title" ) ;
title . textContent = ` ${ point . label } ${ className === "download" ? "下载" : "上传" } ${ formatBytes ( value ) } ` ;
bar . append ( title ) ;
svg . append ( bar ) ;
}
} ) ;
const labelIndexes = [ ... new Set ( [ 0 , Math . floor ( ( points . length - 1 ) / 2 ) , points . length - 1 ] ) ] ;
for ( const index of labelIndexes ) {
const anchor = index === 0 ? "start" : index === points . length - 1 ? "end" : "middle" ;
const label = metricSvgElement ( "text" , { x : left + ( index + . 5 ) * groupWidth , y : height - 8 , "text-anchor" : anchor , class : "vm-metric-axis-label" } ) ;
label . textContent = trafficDailyShortDate ( points [ index ] ) ;
svg . append ( label ) ;
}
plot . replaceChildren ( svg ) ;
setVmTrafficDailyStatus ( ` 最近 ${ points . length } 天 · ${ sampledDays } 天有采样 · 下载 ${ formatBytes ( totalDownload ) } · 上传 ${ formatBytes ( totalUpload ) } ` ) ;
}
async function loadVmTrafficDaily ( force = false ) {
if ( ! trafficDailyViewVisible ( ) ) return ;
const vmId = state . selectedVmId ;
if ( ! force && state . trafficDailyPayload && state . trafficDailyVmId === vmId
&& Date . now ( ) - state . trafficDailyLoadedAt < 60000 ) return ;
if ( state . trafficDailyRequest ? . vmId === vmId ) return ;
state . trafficDailyRequest ? . controller . abort ( ) ;
const request = { vmId , controller : new AbortController ( ) } ;
state . trafficDailyRequest = request ;
setVmTrafficDailyStatus ( "正在加载最近 30 天每日流量…" ) ;
try {
const payload = await api ( ` ${ vmPath ( ) } /traffic/daily?days=30 ` , { signal : request . controller . signal } ) ;
if ( request !== state . trafficDailyRequest || ! trafficDailyViewVisible ( ) ) return ;
state . trafficDailyPayload = payload ;
state . trafficDailyVmId = vmId ;
state . trafficDailyLoadedAt = Date . now ( ) ;
drawVmTrafficDaily ( payload ) ;
} catch ( error ) {
if ( request !== state . trafficDailyRequest || request . controller . signal . aborted || ! trafficDailyViewVisible ( ) ) return ;
setVmTrafficDailyStatus ( ` 每日流量暂时无法加载: ${ error . message } 。 ` , true ) ;
if ( ! state . trafficDailyPayload || state . trafficDailyVmId !== vmId ) {
byId ( "vm-traffic-daily-plot" ) . replaceChildren ( makeElement ( "p" , "vm-metric-empty" , "每日流量暂时无法加载。" ) ) ;
}
} finally {
if ( request === state . trafficDailyRequest ) state . trafficDailyRequest = null ;
}
}
function startVmTrafficDaily ( ) {
if ( ! trafficDailyViewVisible ( ) ) return ;
if ( state . trafficDailyPayload && state . trafficDailyVmId === state . selectedVmId ) drawVmTrafficDaily ( state . trafficDailyPayload ) ;
void loadVmTrafficDaily ( ) ;
}
const TEMPLATE _FAMILY _NAMES = {
almalinux : "AlmaLinux" ,
debian : "Debian" ,
@ -997,20 +1311,42 @@ function renderTemplateCatalog(inputId) {
}
container . replaceChildren ( ... cards ) ;
}
document . querySelectorAll ( '[data-view]' ) . forEach ( button => button . addEventListener ( 'click' , async event => { event . preventDefault ( ) ; const view = button . dataset . view ; button . closest ( 'details' ) ? . removeAttribute ( 'open' ) ; try { if ( view === 'create' ) await openCreate ( ) ; else { showView ( view ) ; if ( view === 'keys' ) await loadKeys ( ) ; if ( view === 'orders' ) await loadOrders ( ) ; } } catch ( error ) { showError ( 'cloud-page-error' , error . message ) ; } } ) ) ;
for ( const id of [ 'refresh-button' , 'vm-detail-refresh-button' ] ) byId ( id ) . addEventListener ( 'click' , loadVms ) ;
document . querySelectorAll ( '[data-view]' ) . forEach ( button => button . addEventListener ( 'click' , async event => { event . preventDefault ( ) ; const view = button . dataset . view ; button . closest ( 'details' ) ? . removeAttribute ( 'open' ) ; try { if ( view === 'create' ) await openCreate ( ) ; else { showView ( view ) ; if ( view === 'keys' ) await loadKeys ( ) ; if ( view === 'orders' ) await loadOrders ( ) ; if ( view === 'invoices' ) await loadInvoices ( ) ; } } catch ( error ) { showError ( 'cloud-page-error' , error . message ) ; } } ) ) ;
byId ( 'refresh-button' ) . addEventListener ( 'click' , loadVms ) ;
byId ( 'vm-detail-refresh-button' ) . addEventListener ( 'click' , async ( ) => {
await loadVms ( ) ;
if ( trafficDailyViewVisible ( ) ) await loadVmTrafficDaily ( true ) ;
} ) ;
byId ( 'create-button' ) . addEventListener ( 'click' , openCreate ) ; byId ( 'create-back' ) . addEventListener ( 'click' , ( ) => showView ( 'list' ) ) ; byId ( 'vm-detail-back-button' ) . addEventListener ( 'click' , ( ) => { state . selectedVmId = null ; showView ( 'list' ) ; } ) ; byId ( 'ssh-keys-back-button' ) . addEventListener ( 'click' , ( ) => showView ( 'list' ) ) ;
for ( const id of [ 'reinstall-back' , 'reinstall-cancel' , 'rescue-back' ] ) byId ( id ) . addEventListener ( 'click' , ( ) => { if ( ! state . mutationBusy ) { const vm = selectedVm ( ) ; if ( vm ) openVmDetail ( vm . uuid ) ; else showView ( 'list' ) ; } } ) ;
byId ( 'search-input' ) . addEventListener ( 'input' , ( ) => renderVMs ( ) ) ; byId ( 'state-filter' ) . addEventListener ( 'change' , ( ) => renderVMs ( ) ) ; byId ( 'vm-plan' ) . addEventListener ( 'change' , ( ) => { void loadPlanResources ( ) ; } ) ; byId ( 'create-form' ) . querySelectorAll ( '[name="source"]' ) . forEach ( radio => radio . addEventListener ( 'change' , updateSource ) ) ;
byId ( 'create-form' ) . addEventListener ( 'submit' , buy ) ; byId ( 'reinstall-form' ) . addEventListener ( 'submit' , reinstall ) ; byId ( 'rescue-form' ) . addEventListener ( 'submit' , event => { event . preventDefault ( ) ; void rescueAction ( 'load' ) ; } ) ; byId ( 'rescue-force-start' ) . addEventListener ( 'click' , ( ) => rescueAction ( 'force-start' ) ) ; byId ( 'rescue-exit' ) . addEventListener ( 'click' , ( ) => rescueAction ( 'exit' ) ) ; byId ( 'orders-refresh' ) . addEventListener ( 'click' , loadOrders ) ;
byId ( 'create-form' ) . addEventListener ( 'submit' , buy ) ; byId ( 'reinstall-form' ) . addEventListener ( 'submit' , reinstall ) ; byId ( 'rescue-form' ) . addEventListener ( 'submit' , event => { event . preventDefault ( ) ; void rescueAction ( 'load' ) ; } ) ; byId ( 'rescue-force-start' ) . addEventListener ( 'click' , ( ) => rescueAction ( 'force-start' ) ) ; byId ( 'rescue-exit' ) . addEventListener ( 'click' , ( ) => rescueAction ( 'exit' ) ) ; byId ( 'orders-refresh' ) . addEventListener ( 'click' , loadOrders ) ; byId ( 'invoices-refresh' ) . addEventListener ( 'click' , loadInvoices ) ;
for ( const id of [ 'vm-open-ssh-keys' , 'reinstall-open-ssh-keys' ] ) byId ( id ) . addEventListener ( 'click' , async ( ) => { showView ( 'keys' ) ; try { await loadKeys ( ) ; } catch ( error ) { toast ( error . message , 'error' ) ; } } ) ;
byId ( 'ssh-key-form' ) . addEventListener ( 'submit' , async event => { event . preventDefault ( ) ; const button = byId ( 'ssh-key-save-button' ) ; button . disabled = true ; showError ( 'ssh-key-form-error' , '' ) ; try { await api ( '/api/v1/ssh-keys' , { method : 'POST' , body : { name : byId ( 'ssh-key-name' ) . value . trim ( ) , public _key : byId ( 'ssh-key-public-key' ) . value . trim ( ) } } ) ; byId ( 'ssh-key-form' ) . reset ( ) ; await loadKeys ( ) ; toast ( '公钥已保存。' , 'success' ) ; } catch ( error ) { showError ( 'ssh-key-form-error' , error . message ) ; } finally { button . disabled = false ; } } ) ;
byId ( 'ssh-key-file' ) . addEventListener ( 'change' , async event => { const file = event . target . files ? . [ 0 ] ; if ( ! file ) return ; if ( file . size > 16384 ) return showError ( 'ssh-key-form-error' , '公钥文件超过 16 KiB 限制。' ) ; const content = await file . text ( ) ; if ( /PRIVATE KEY/ . test ( content ) ) return showError ( 'ssh-key-form-error' , '不能导入私钥,只能导入 .pub 公钥。' ) ; byId ( 'ssh-key-public-key' ) . value = content . trim ( ) ; } ) ;
byId ( 'vm-detail-ip-copy' ) . addEventListener ( 'click' , async ( ) => { try { await copyText ( vmIp ( selectedVm ( ) ) ) ; toast ( '公网 IP 已复制。' ) ; } catch ( error ) { toast ( error . message , 'error' ) ; } } ) ; byId ( 'vm-detail-password-reveal' ) . addEventListener ( 'click' , ( ) => credential ( ) ) ; byId ( 'vm-detail-password-copy' ) . addEventListener ( 'click' , ( ) => credential ( true ) ) ;
byId ( 'vm-detail-renew-button' ) . addEventListener ( 'click' , renewVm ) ;
byId ( 'vm-metrics-range' ) . addEventListener ( 'change' , ( ) => { state . metricsRange = byId ( 'vm-metrics-range' ) . value ; state . metricsRequest ? . controller . abort ( ) ; state . metricsRequest = null ; void loadVmMetrics ( ) ; } ) ; window . addEventListener ( 'resize' , ( ) => { clearTimeout ( state . metricsResizeTimer ) ; state . metricsResizeTimer = setTimeout ( ( ) => { if ( state . metricsPayload && state . view === 'detail' ) renderVmMetrics ( state . metricsPayload ) ; } , 150 ) ; } ) ;
document . querySelectorAll ( '[data-detail-tab]' ) . forEach ( button => {
button . addEventListener ( 'click' , ( ) => setVmDetailTab ( button . dataset . detailTab ) ) ;
button . addEventListener ( 'keydown' , event => {
const current = VM _DETAIL _TABS . indexOf ( button . dataset . detailTab ) ;
let next = current ;
if ( event . key === 'ArrowRight' ) next = ( current + 1 ) % VM _DETAIL _TABS . length ;
else if ( event . key === 'ArrowLeft' ) next = ( current - 1 + VM _DETAIL _TABS . length ) % VM _DETAIL _TABS . length ;
else if ( event . key === 'Home' ) next = 0 ;
else if ( event . key === 'End' ) next = VM _DETAIL _TABS . length - 1 ;
else return ;
event . preventDefault ( ) ;
setVmDetailTab ( VM _DETAIL _TABS [ next ] , true ) ;
} ) ;
} ) ;
byId ( 'vm-metrics-range' ) . addEventListener ( 'change' , ( ) => { state . metricsRange = byId ( 'vm-metrics-range' ) . value ; state . metricsRequest ? . controller . abort ( ) ; state . metricsRequest = null ; void loadVmMetrics ( ) ; } ) ; window . addEventListener ( 'resize' , ( ) => {
clearTimeout ( state . metricsResizeTimer ) ;
clearTimeout ( state . trafficDailyResizeTimer ) ;
state . metricsResizeTimer = setTimeout ( ( ) => { if ( state . metricsPayload && metricViewVisible ( ) ) renderVmMetrics ( state . metricsPayload ) ; } , 150 ) ;
state . trafficDailyResizeTimer = setTimeout ( ( ) => { if ( state . trafficDailyPayload && state . trafficDailyVmId === state . selectedVmId && trafficDailyViewVisible ( ) ) drawVmTrafficDaily ( state . trafficDailyPayload ) ; } , 150 ) ;
} ) ;
byId ( 'console-modal' ) . querySelector ( '[data-close-modal]' ) . addEventListener ( 'click' , closeConsole ) ; byId ( 'console-cad' ) . addEventListener ( 'click' , ( ) => state . rfb ? . sendCtrlAltDel ( ) ) ; byId ( 'console-fullscreen' ) . addEventListener ( 'click' , ( ) => { byId ( 'console-stage' ) . requestFullscreen ? . ( ) . catch ( error => toast ( error . message , 'error' ) ) ; } ) ; byId ( 'console-password-form' ) . addEventListener ( 'submit' , event => { event . preventDefault ( ) ; state . rfb ? . sendCredentials ( { password : byId ( 'console-password' ) . value } ) ; byId ( 'console-password' ) . value = '' ; byId ( 'console-password-form' ) . hidden = true ; } ) ; window . addEventListener ( 'keydown' , event => { if ( event . key === 'Escape' ) closeConsole ( ) ; } ) ;
document . addEventListener ( 'visibilitychange' , ( ) => { if ( document . hidden ) clearCredential ( ) ; else { void loadVms ( ) ; if ( state . view === 'detail' ) startVmMetrics ( ) ; } } ) ; window . addEventListener ( 'pagehide' , ( ) => { clearCredential ( ) ; closeConsole ( ) ; state . resourceController ? . abort ( ) ; } ) ; byId ( 'logout-button' ) . addEventListener ( 'click' , ( ) => { clearCredential ( ) ; closeConsole ( ) ; location . assign ( '/user/logout' ) ; } ) ;
async function initialize ( ) { const initialHash = location . hash ; try { const session = await api ( '/api/v1/session' ) ; if ( session . authenticated === false ) { location . assign ( '/auth/login' ) ; return ; } state . csrfToken = session . csrf _token || '' ; if ( ! state . csrfToken ) throw new Error ( '会话 CSRF 令牌缺失,请重新登录。' ) ; state . userId = String ( session . user _id || '' ) ; if ( ! /^\d+$/ . test ( state . userId ) ) throw new Error ( '会话用户标识缺失,请重新登录。' ) ; state . username = session . username || session . user _name || session . email || session . user ? . email || '用户' ; state . admin = session . admin === true || session . is _admin === true || Number ( session . is _admin ) === 1 ; text ( 'current-username' , state . username ) ; for ( const id of [ 'cloud-admin-link' , 'cloud-admin-menu-link' ] ) { const link = byId ( id ) ; if ( link ) link . hidden = ! state . admin ; } showView ( 'list' ) ; updateSource ( ) ; await loadVms ( ) ; await routeHash ( initialHash ) ; setInterval ( ( ) => { if ( ! document . hidden ) { void loadVms ( ) ; if ( state . view === 'orders' ) void loadOrders ( ) ; } } , 15000 ) ; } catch ( error ) { showError ( 'cloud-page-error' , error . message ) ; } }
document . addEventListener ( 'visibilitychange' , ( ) => { if ( document . hidden ) { clearCredential ( ) ; stopVmMetrics ( ) ; stopVmTrafficDaily ( ) ; stopInvoicePoll ( ) ; } else { void loadVms ( ) ; if ( state . view === 'detail' ) s etVmDetailTab( state . detailTab ) ; if ( state . view === 'invoices' ) void loadInvoice s( ) ; } } ) ; window . addEventListener ( 'pagehide' , ( ) => { clearCredentia l( ) ; stopVmMetrics ( ) ; stopVmTrafficDaily ( ) ; stopInvoicePol l( ) ; closeConsole ( ) ; state . resourceController ? . abort ( ) ; } ) ; byId ( 'logout-button' ) . addEventListener ( 'click' , ( ) => { clearCredential ( ) ; closeConsole ( ) ; location . assign ( '/user/logout' ) ; } ) ;
async function initialize ( ) { const initialHash = location . hash ; try { const session = await api ( '/api/v1/session' ) ; if ( session . authenticated === false ) { location . assign ( '/auth/login' ) ; return ; } state . csrfToken = session . csrf _token || '' ; if ( ! state . csrfToken ) throw new Error ( '会话 CSRF 令牌缺失,请重新登录。' ) ; state . userId = String ( session . user _id || '' ) ; if ( ! /^\d+$/ . test ( state . userId ) ) throw new Error ( '会话用户标识缺失,请重新登录。' ) ; state . username = session . username || session . user _name || session . email || session . user ? . email || '用户' ; state . admin = session . admin === true || session . is _admin === true || Number ( session . is _admin ) === 1 ; text ( 'current-username' , state . username ) ; for ( const id of [ 'cloud-admin-link' , 'cloud-admin-menu-link' ] ) { const link = byId ( id ) ; if ( link ) link . hidden = ! state . admin ; } showView ( 'list' ) ; updateSource ( ) ; await loadVms ( ) ; await routeHash ( initialHash ) ; setInterval ( ( ) => { if ( ! document . hidden ) { void loadVms ( ) ; if ( trafficDailyViewVisible( ) ) void loadVmTrafficDaily ( ) ; if ( state. view === 'orders' ) void loadOrder s( ) ; if ( state . view === 'invoices' && state . invoicePollTimers . size === 0 ) void loadInvoice s( ) ; } } , 15000 ) ; } catch ( error ) { showError ( 'cloud-page-error' , error . message ) ; } }
window . addEventListener ( 'hashchange' , ( ) => { if ( state . csrfToken ) void routeHash ( ) ; } ) ;
void initialize ( ) ;