fix: preserve background connection state and durable disconnect logs
This commit is contained in:
+105
-24
@@ -4,20 +4,77 @@ import {el, $, $$, clone, getPath, setPath, pathKey, textValue, number, chinaTim
|
||||
import {PageView, PAGES} from './pages.js';
|
||||
import {notice, dialog, confirm, filePicker, fileBase64} from './ui.js';
|
||||
|
||||
const state = {accounts:new Map(),active:null,schema:null,meta:null,ready:false,polling:false,seq:0,redirecting:false};
|
||||
const state = {accounts:new Map(),active:null,schema:null,meta:null,ready:false,polling:false,seq:0,redirecting:false,webStatusError:null,statusMessage:'连接中'};
|
||||
const current = () => state.accounts.get(state.active);
|
||||
const currentPage = () => { const account=current(); return account?.pages.get(account.page); };
|
||||
const terminal = new Set(['succeeded','failed','cancelled']);
|
||||
const jobLabels = {queued:'排队中',running:'执行中',succeeded:'已完成',failed:'失败',cancelled:'已取消'};
|
||||
const operationLabels = {login:'登录',enter_server:'进入区服',restore_session:'恢复会话',refresh:'刷新 / 预览',start:'开启策略',stop:'停止策略',set_config:'保存配置',import_config:'导入策略',import_yields:'导入收益',claim_daily:'领取每日奖励',quote_expansion:'读取扩建费用',expand:'扩建',sell:'派遣',feed:'喂养',lock:'锁定',unlock:'解锁'};
|
||||
const connectionLabels = {online:'已登录',retrying:'正在重试',expired:'登录已过期',offline:'游戏离线'};
|
||||
const gameRefreshOperations = new Set(['start','refresh','refresh_maps','refresh_tasks']);
|
||||
|
||||
function connectionState(summary) {
|
||||
if(summary?.demo)return 'online';
|
||||
return Object.hasOwn(connectionLabels,summary?.connection_state)?summary.connection_state:summary?.connected?'online':'offline';
|
||||
}
|
||||
|
||||
function gameAvailable(account) { return Boolean(account && !state.webStatusError && !account.transportErrors.has('status') && connectionState(account.summary)==='online'); }
|
||||
|
||||
function connectionReason(summary) {
|
||||
return summary?.connection_message || summary?.error || {retrying:'游戏请求暂时失败,等待重试。',expired:'游戏登录状态已失效,请在登录页重新登录或恢复会话。',offline:'尚未连接游戏,请在登录页登录或恢复已保存会话。'}[connectionState(summary)] || '';
|
||||
}
|
||||
|
||||
function connectionDetails(account) {
|
||||
if(!account)return '';
|
||||
const summary=account.summary,kind=connectionState(summary),parts=[];
|
||||
if(state.webStatusError)parts.push(state.webStatusError);
|
||||
if(kind!=='online')parts.push(connectionReason(summary));
|
||||
if(kind==='retrying'){
|
||||
const value=summary.next_retry_at;
|
||||
const retryAt=typeof value==='number'?(value<1e12?value*1000:value):Date.parse(value);
|
||||
if(value!=null && Number.isFinite(retryAt)){
|
||||
const seconds=Math.max(0,Math.ceil((retryAt-Date.now())/1000));
|
||||
parts.push(seconds?`${seconds} 秒后重试(${chinaTime(value,{date:true})},北京时间)`:'等待重试结果');
|
||||
}else parts.push('等待重试安排');
|
||||
}
|
||||
if(!gameAvailable(account))parts.push(summary.last_game_success_at!=null?`显示缓存数据;最后成功通信:${chinaTime(summary.last_game_success_at,{date:true})}(北京时间)`:'显示已保存数据(缓存);尚无成功通信记录。');
|
||||
return parts.join(';');
|
||||
}
|
||||
|
||||
function transportMessages(account=current()) { return [...(account?.transportErrors.values() || [])]; }
|
||||
|
||||
function renderStatus() {
|
||||
const message=[connectionDetails(current()),...transportMessages()].filter(Boolean).join(';') || state.statusMessage;
|
||||
const node=$('#status-text');if(node.textContent!==message)node.textContent=message;node.title=message;
|
||||
}
|
||||
|
||||
function transportError(account,key,label,failure) {
|
||||
if(failure && failure.status!==401)account.transportErrors.set(key,`${label}读取失败:${failure.message || String(failure)} 正在重试。`);
|
||||
else account.transportErrors.delete(key);
|
||||
renderSummary();
|
||||
}
|
||||
|
||||
function connectionError(account) { return Object.assign(new Error(connectionDetails(account) || '请等待游戏连接恢复后再操作。'),{connection:true}); }
|
||||
|
||||
function renderPageConnection(page) {
|
||||
if(!page.connectionStatus){
|
||||
page.connectionStatus=el('p',{class:'page-summary','data-connection-status':'',hidden:true});
|
||||
page.header.after(page.connectionStatus);
|
||||
}
|
||||
const stale=!gameAvailable(page.account),message=connectionDetails(page.account);
|
||||
page.connectionStatus.hidden=!stale;page.connectionStatus.textContent=message;
|
||||
if(stale){page.loading.dataset.loading='false';page.loading.textContent=page.data?'已载入缓存':'缓存中暂无数据';clearTimeout(page.loadTimer);}
|
||||
else if(page.loading.textContent.includes('缓存')){page.loading.textContent=page.data?'已载入':'正在读取…';page.loading.dataset.loading=String(!page.data);}
|
||||
$$('button[data-operation]',page.actionsHost).filter(button=>gameRefreshOperations.has(button.dataset.operation)).forEach(button=>button.disabled=stale);
|
||||
}
|
||||
|
||||
function makeAccount(summary) {
|
||||
return {id:summary.id,summary,config:null,revision:null,edits:new Map(),pages:new Map(),page:'login',jobs:new Map(),savePromise:null,saveError:null,
|
||||
logs:{entries:[],next:0,debug:false,loading:false},loadingConfig:false};
|
||||
logs:{entries:[],next:0,debug:false,loading:false},loadingConfig:false,transportErrors:new Map()};
|
||||
}
|
||||
|
||||
function setStatus(message) { $('#status-text').textContent=message; $('#status-text').title=message; }
|
||||
function error(error) { if(state.redirecting)return;notice(error.message || String(error),true); setStatus(error.message || String(error)); }
|
||||
function setStatus(message) { state.statusMessage=message;renderStatus(); }
|
||||
function error(error) { if(state.redirecting)return;if(error.connection){renderSummary();return;}notice(error.message || String(error),true);setStatus(error.message || String(error)); }
|
||||
|
||||
function renderAccountTabs() {
|
||||
const root=$('#account-tabs');
|
||||
@@ -28,11 +85,11 @@ function renderAccountTabs() {
|
||||
button=el('button',{type:'button',class:'account-tab',role:'tab','data-account':account.id,onClick:()=>selectAccount(account.id)},el('span',{class:'account-dot'}),el('span',{class:'account-label'}));
|
||||
root.append(button);
|
||||
}
|
||||
const summary=account.summary, selected=state.active===account.id;
|
||||
const summary=account.summary,selected=state.active===account.id,kind=connectionState(summary);
|
||||
$('.account-label',button).textContent=summary.label || summary.player?.name || '账号';
|
||||
$('.account-dot',button).className=`account-dot${summary.error?' error':summary.running?' running':''}`;
|
||||
$('.account-dot',button).className=`account-dot${summary.error || kind!=='online'?' error':summary.running?' running':''}`;
|
||||
button.setAttribute('aria-selected',String(selected));button.tabIndex=selected?0:-1;
|
||||
button.title=`${summary.label || '账号'}${summary.demo?' · 离线演示':''}${summary.running?' · 策略运行中':''}${summary.error?' · '+summary.error:''}`;
|
||||
button.title=[summary.label || '账号',summary.demo?'离线演示':connectionLabels[kind],summary.running?'策略运行中':'',kind==='online'?summary.error:connectionReason(summary)].filter(Boolean).join(' · ');
|
||||
});
|
||||
}
|
||||
|
||||
@@ -45,22 +102,27 @@ function syncSaveStatus(account=current()) {
|
||||
|
||||
function renderSummary() {
|
||||
const account=current(),summary=account?.summary,player=summary?.player || {};
|
||||
const connected=summary?.connected,demo=summary?.demo;
|
||||
$('#connection').textContent=demo?'离线演示':connected?'已登录':'未登录';
|
||||
$('#connection').className=`connection${demo?' demo':connected?' online':''}`;
|
||||
const kind=connectionState(summary),connected=gameAvailable(account),demo=summary?.demo,details=connectionDetails(account);
|
||||
$('#connection').textContent=state.webStatusError || account?.transportErrors.has('status')?'Web 状态重试中':demo?'离线演示':connectionLabels[kind];
|
||||
$('#connection').className=`connection${connected?(demo?' demo':' online'):kind==='retrying'?' demo':''}`;
|
||||
$('#connection').title=details || (demo?'当前为离线演示,不连接游戏服务器。':summary?.connection_message || '游戏连接正常');
|
||||
$('#player-name').textContent=player.name || '—';$('#player-name').title=player.name || '';
|
||||
for (const [id,key] of [['player-level','level'],['player-money','money'],['player-ke','ke'],['player-ti','ti']]) $('#'+id).textContent=number(player[key]);
|
||||
$('#player-exp').textContent=player.exp==null?'—':`${number(player.exp)} / ${number(player.next_exp)}`;
|
||||
$('#experience-progress').max=Math.max(1,Number(player.next_exp)||1);$('#experience-progress').value=Number(player.exp)||0;
|
||||
const run=$('#strategy-toggle');run.textContent=summary?.running?'停止':'开启';run.classList.toggle('running',Boolean(summary?.running));run.disabled=!account || !account.config || !connected && !demo;
|
||||
const run=$('#strategy-toggle');run.textContent=summary?.running?'停止':'开启';run.classList.toggle('running',Boolean(summary?.running));run.disabled=!account || !summary?.running && (!account.config || !connected);
|
||||
run.setAttribute('aria-pressed',String(Boolean(summary?.running)));
|
||||
run.title=summary?.running?'停止自动执行已勾选功能;取消尚未发送的请求':'开启后自动执行各页面已勾选功能';
|
||||
run.title=summary?.running?'停止自动执行已勾选功能;取消尚未发送的请求':!connected?details:'开启后自动执行各页面已勾选功能';
|
||||
$('[data-command="start"]').disabled=!account?.config || !connected;
|
||||
$('[data-command="start-all"]').disabled=![...state.accounts.values()].some(gameAvailable);
|
||||
if (account?.config && document.activeElement!==$('#refresh-interval')) $('#refresh-interval').value=String(account.config.interval);
|
||||
$('#refresh-interval').disabled=!account?.config;
|
||||
$('#refresh').disabled=!account;
|
||||
$('#refresh').disabled=!connected;$('#refresh').title=connected?'读取游戏状态并预览策略':details;
|
||||
const task=account?[...account.jobs.values()].at(-1)?.job:null;
|
||||
$('#job-status').textContent=task?`${operationLabels[task.operation] || task.operation} · ${jobLabels[task.status]}`:summary?.busy?'后台任务执行中':'';
|
||||
$('#data-summary').textContent=summary?.error || (demo?'当前为离线演示,不连接游戏服务器。':connected?'角色状态自动刷新;配置功能后开启策略。':'请在登录页输入账号密码,或恢复已保存会话。');
|
||||
const message=[details || summary?.error || (demo?'当前为离线演示,不连接游戏服务器。':connected?'角色状态自动刷新;配置功能后开启策略。':'请在登录页输入账号密码,或恢复已保存会话。'),...transportMessages(account)].filter(Boolean).join(';');
|
||||
$('#data-summary').textContent=message;$('#data-summary').title=message;
|
||||
account?.pages.forEach(renderPageConnection);renderStatus();
|
||||
syncSaveStatus(account);
|
||||
}
|
||||
|
||||
@@ -164,30 +226,35 @@ async function pollJob(account,record) {
|
||||
if(record.polling)return;record.polling=true;
|
||||
try {
|
||||
const job=await api.job(account.id,record.job.id);record.job=job;
|
||||
account.transportErrors.delete(`job:${job.id}`);
|
||||
if(terminal.has(job.status)){
|
||||
account.jobs.delete(job.id);
|
||||
if(job.status==='succeeded')record.resolve(job.result);
|
||||
else record.reject(new Error(job.error || '任务已取消'));
|
||||
}
|
||||
}catch(failure){if([400,401,403,404].includes(failure.status)){account.jobs.delete(record.job.id);record.reject(failure);}}
|
||||
}catch(failure){if([400,401,403,404].includes(failure.status)){account.transportErrors.delete(`job:${record.job.id}`);account.jobs.delete(record.job.id);record.reject(failure);}else transportError(account,`job:${record.job.id}`,'任务状态',failure);}
|
||||
finally{record.polling=false;renderSummary();}
|
||||
}
|
||||
|
||||
async function perform(account,operation,payload={},options={}) {
|
||||
if(!account)throw new Error('请先新增或选择一个账号。');
|
||||
if(gameRefreshOperations.has(operation) && !gameAvailable(account))throw connectionError(account);
|
||||
if(operation==='start'){
|
||||
const invalid=account.pages.get(account.page)?.root.querySelector(':invalid');
|
||||
if(invalid){invalid.reportValidity();throw new Error('请先完成当前输入,再开启策略。');}
|
||||
}
|
||||
if(operation!=='stop')await flushConfig(account);
|
||||
if(gameRefreshOperations.has(operation) && !gameAvailable(account))throw connectionError(account);
|
||||
const job=await api.action(account.id,operation,payload);
|
||||
setStatus(`${operationLabels[operation] || '操作'}:${jobLabels[job.status] || '已提交'}`);
|
||||
setStatus(`${operationLabels[operation] || '操作'}:${gameRefreshOperations.has(operation)&&job.status==='succeeded'?'等待确认游戏状态':jobLabels[job.status] || '已提交'}`);
|
||||
const result=await trackJob(account,job);
|
||||
if(!state.accounts.has(account.id))return result;
|
||||
if(result?.config){account.config=clone(result.config);account.revision=result.revision;}
|
||||
if(['enter_server','restore_session','logout','forget_login','import_config','import_yields'].includes(operation))await refreshConfig(account);
|
||||
account.summary=await api.status(account.id);
|
||||
try{account.summary=await api.status(account.id);account.transportErrors.delete('status');}
|
||||
catch(failure){transportError(account,'status','Web 账号状态',failure);failure.connection=true;throw failure;}
|
||||
renderAccountTabs();renderSummary();
|
||||
if((gameRefreshOperations.has(operation)||['enter_server','restore_session'].includes(operation)) && !gameAvailable(account)){setStatus('工作台状态已更新');throw connectionError(account);}
|
||||
const page=options.page || account.pages.get(account.page);if(page)await loadPage(page,true);
|
||||
if(operation==='login'&&result)account.pages.get('login')?.login?.update(result);
|
||||
if(operation==='enter_server'||operation==='restore_session')notice('已读取角色。策略保持关闭,请配置功能后开启。');
|
||||
@@ -206,14 +273,16 @@ function getPage(account,key) {
|
||||
}
|
||||
|
||||
async function loadPage(page,force=false) {
|
||||
if(!force && !gameAvailable(page.account) && (page.key!=='login'||state.webStatusError||page.account.transportErrors.has('status'))){clearTimeout(page.loadTimer);renderPageConnection(page);return;}
|
||||
if(page.fetching){if(force)page.reload=true;return;}
|
||||
page.fetching=true;const generation=page.generation || 0;
|
||||
try {
|
||||
const response=await api.view(page.account.id,page.key,page.query);
|
||||
if(generation!==(page.generation||0))return;
|
||||
page.clearError();page.render(response.data,response.loading);page.lastLoad=Date.now();
|
||||
if(response.loading){clearTimeout(page.loadTimer);page.loadTimer=setTimeout(()=>loadPage(page),650);}
|
||||
}catch(failure){page.showError(failure.message);}
|
||||
transportError(page.account,`view:${page.key}`,'页面数据',null);renderPageConnection(page);
|
||||
if(response.loading && gameAvailable(page.account)){clearTimeout(page.loadTimer);page.loadTimer=setTimeout(()=>loadPage(page),650);}
|
||||
}catch(failure){if(generation===(page.generation||0)){page.showError(failure.message);transportError(page.account,`view:${page.key}`,'页面数据',failure);}}
|
||||
finally{page.fetching=false;if(page.reload){page.reload=false;loadPage(page);}}
|
||||
}
|
||||
|
||||
@@ -310,7 +379,13 @@ async function command(name,account=current()) {
|
||||
if(name==='debug'){account.logs.debug=!account.logs.debug;account.logs.entries=[];account.logs.next=0;account.logs.generation=(account.logs.generation || 0)+1;$('#debug-log').checked=account.logs.debug;setLogVisible(true);renderLogs(true);await fetchLogs(account);return;}
|
||||
if(name==='save'){await flushConfig(account);notice('策略已保存。');return;}
|
||||
if(name==='stop'||name==='start')return await perform(account,name);
|
||||
if(name==='start-all'||name==='stop-all'){await Promise.all([...state.accounts.values()].map(item=>perform(item,name==='start-all'?'start':'stop')));return;}
|
||||
if(name==='start-all'||name==='stop-all'){
|
||||
const accounts=[...state.accounts.values()],eligible=name==='start-all'?accounts.filter(gameAvailable):accounts;
|
||||
if(!eligible.length)throw connectionError(account);
|
||||
await Promise.all(eligible.map(item=>perform(item,name==='start-all'?'start':'stop')));
|
||||
if(eligible.length<accounts.length)notice('已跳过未连接游戏的账号,请在登录页登录或恢复会话。',true);
|
||||
return;
|
||||
}
|
||||
if(name==='logout')return await perform(account,'logout');
|
||||
if(name==='forget-login'){
|
||||
if(await confirm('退出并清除登录记录','将退出当前角色,删除当前账号保存的登录会话和账号密码。培养策略和其他账号不受影响。',{confirm:'清除登录记录',danger:true}))await perform(account,'forget_login');return;
|
||||
@@ -435,7 +510,8 @@ async function fetchLogs(account) {
|
||||
account.logs.entries.push(...(response.entries || []).filter(entry=>entry.id==null||!seen.has(entry.id)));account.logs.next=response.next;
|
||||
if(account.id===state.active)renderLogs();
|
||||
if(account.logs.entries.length>1200){account.logs.entries=account.logs.entries.slice(-600);if(account.id===state.active)renderLogs(true);}
|
||||
}catch(failure){if(failure.status!==401)setStatus(failure.message);}finally{account.logs.loading=false;}
|
||||
transportError(account,'logs','日志',null);
|
||||
}catch(failure){if(generation===(account.logs.generation || 0))transportError(account,'logs','日志',failure);}finally{account.logs.loading=false;}
|
||||
}
|
||||
|
||||
async function showDebugEntry(account,entry) {
|
||||
@@ -455,11 +531,14 @@ function showNoAccounts() {
|
||||
}
|
||||
|
||||
async function syncAccounts() {
|
||||
const response=await api.accounts(),summaries=Array.isArray(response)?response:response.accounts || [];
|
||||
let response;
|
||||
try{response=await api.accounts();state.webStatusError=null;}
|
||||
catch(failure){if(failure.status!==401){state.webStatusError=`Web 状态读取失败:${failure.message || String(failure)} 正在重试。`;renderAccountTabs();renderSummary();}throw failure;}
|
||||
const summaries=Array.isArray(response)?response:response.accounts || [];
|
||||
const ids=new Set(summaries.map(summary=>summary.id));
|
||||
for(const [id,account]of state.accounts)if(!ids.has(id)){account.pages.forEach(page=>{clearTimeout(page.loadTimer);page.root.remove();});state.accounts.delete(id);}
|
||||
summaries.forEach(summary=>{
|
||||
const account=state.accounts.get(summary.id);if(account){account.summary=summary;if(account.config&&account.revision!==summary.revision&&!account.edits.size&&!account.savePromise)refreshConfig(account).catch(error);}
|
||||
const account=state.accounts.get(summary.id);if(account){account.summary=summary;account.transportErrors.delete('status');if(account.config&&account.revision!==summary.revision&&!account.edits.size&&!account.savePromise)refreshConfig(account).catch(error);}
|
||||
else state.accounts.set(summary.id,makeAccount(summary));
|
||||
});
|
||||
renderAccountTabs();renderSummary();
|
||||
@@ -467,9 +546,11 @@ async function syncAccounts() {
|
||||
}
|
||||
|
||||
async function tick() {
|
||||
if(state.ready)renderSummary();
|
||||
if(!state.ready||state.polling)return;state.polling=true;
|
||||
try{
|
||||
const account=current();await Promise.allSettled([syncAccounts(),...([...state.accounts.values()].flatMap(item=>[...item.jobs.values()].map(job=>pollJob(item,job))))]);
|
||||
await Promise.allSettled([syncAccounts(),...([...state.accounts.values()].flatMap(item=>[...item.jobs.values()].map(job=>pollJob(item,job))))]);
|
||||
const account=current();
|
||||
if(state.ready&&account&&state.accounts.has(account.id)){fetchLogs(account);const page=account.pages.get(account.page);if(page&&Date.now()-(page.lastLoad||0)>4000)loadPage(page);}
|
||||
}finally{state.polling=false;}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user