Repository navigation
Expand file tree
/
Copy pathsync.js
More file actions
20 lines (20 loc) · 5.09 KB
/
Copy pathsync.js
File metadata and controls
20 lines (20 loc) · 5.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
let syncUser=null,syncTimer,syncBusy=false,syncAgain=false;
function syncLabel(text){const n=document.getElementById('sync-state');if(n)n.textContent=text;}
async function api(path,data){const ctl=new AbortController(),timer=setTimeout(()=>ctl.abort(),12000);try{const r=await fetch('./api/'+path,{signal:ctl.signal,credentials:'same-origin',...(data?{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(data)}:{})});const j=await r.json();if(!r.ok)throw Error(j.error||'同步失败');return j;}finally{clearTimeout(timer);}}
function saveLocal(){try{localStorage.setItem(KEY,JSON.stringify(state));}catch{storageOK=false;}}
function mergeLocal(remote){state.done=[...new Set([...state.done,...(remote.done||[])])].sort((a,b)=>a-b);for(const[k,v]of Object.entries(remote.scores||{}))state.scores[k]=Math.max(v,state.scores[k]||0);saveLocal();}
function scheduleSync(){saveLocal();clearTimeout(syncTimer);if(syncUser){syncLabel('正在保存…');syncTimer=setTimeout(pushProgress,500);}}
async function pushProgress(){if(!syncUser)return;if(syncBusy){syncAgain=true;return;}syncBusy=true;try{const r=await api('progress',state);mergeLocal(r.progress);syncLabel('已同步 · '+syncUser);}catch(e){syncLabel('待同步 · '+e.message);}finally{syncBusy=false;if(syncAgain){syncAgain=false;pushProgress();}}}
function accountPanel(){const box=document.getElementById('account');box.innerHTML=syncUser?`<span id="sync-state">已登录 · ${esc(syncUser)}</span><button id="sync-now">立即同步</button><button id="logout">退出</button>`:`<span id="sync-state">未登录 · 记录暂存本机</span><button id="login-open">登录同步</button>`;
document.getElementById('login-open')?.addEventListener('click',showLogin);
document.getElementById('sync-now')?.addEventListener('click',async()=>{await pushProgress();render();});
document.getElementById('logout')?.addEventListener('click',async()=>{try{await pushProgress();await api('logout',{});syncUser=null;state={done:[],scores:{},last:1};saveLocal();render();}catch(e){syncLabel(e.message);}});}
function showLogin(){let d=document.getElementById('login-dialog');if(!d){d=document.createElement('dialog');d.id='login-dialog';document.body.append(d);}d.innerHTML=`<form id="login-form"><h2>登录,接着上次学</h2><p>同一账号可在多个设备使用。登录后合并本机学习记录。</p><label>账号<input name="username" autocomplete="username" value="lehaifeng" required></label><label>密码<input name="password" type="password" autocomplete="current-password" required></label><p class="muted">当前使用 HTTP 访问,请使用本站专用密码。</p><p id="login-status" role="status"></p><div class="actions"><button class="button" type="submit">登录并同步</button><button type="button" id="cancel-login" class="button secondary">稍后</button></div></form>`;d.showModal();document.getElementById('cancel-login').onclick=()=>d.close();document.getElementById('login-form').onsubmit=async e=>{e.preventDefault();const b=e.target.querySelector('[type=submit]');b.disabled=true;try{const j=await api('login',Object.fromEntries(new FormData(e.target)));syncUser=j.user;const old=await api('progress');mergeLocal(old.progress);await pushProgress();d.close();render();}catch(error){document.getElementById('login-status').textContent=error.message;}finally{b.disabled=false;}};}
async function bootSync(){try{const s=await api('session');syncUser=s.user;if(syncUser){const r=await api('progress');mergeLocal(r.progress);if(!location.hash||location.hash==='#home')state.last=r.progress.last||state.last;await pushProgress();}render();}catch{syncLabel('离线模式 · 记录暂存本机');}}
function passwordPanel(){return `<section class="paper"><h2>修改学习账号密码</h2><form id="password-form"><label>原密码<input name="old" type="password" autocomplete="current-password" required></label><label>新密码(至少12位)<input name="new" type="password" minlength="12" maxlength="200" autocomplete="new-password" required></label><button class="button">更新密码</button><p id="password-status" role="status"></p></form></section>`;}
function bindPassword(){const f=document.getElementById('password-form');if(f)f.onsubmit=async e=>{e.preventDefault();try{await api('password',Object.fromEntries(new FormData(f)));f.reset();document.getElementById('password-status').textContent='密码已更新,其他设备需要重新登录。';}catch(error){document.getElementById('password-status').textContent=error.message;}};}
save=scheduleSync;
const originalShell=shell;shell=function(page){originalShell(page);const account=document.createElement('div');account.id='account';document.querySelector('header').after(account);accountPanel();if(location.hash==='#method'&&syncUser){document.querySelector('footer').insertAdjacentHTML('beforebegin',passwordPanel());bindPassword();}document.querySelectorAll('.side-progress small').forEach(n=>n.textContent=syncUser?'学习记录自动同步到账号':'登录后可跨设备保存');};
window.addEventListener('online',bootSync);
document.addEventListener('visibilitychange',()=>{if(document.visibilityState==='visible')bootSync();});
bootSync();