/* ============================================================ 登录门 + 云端实时同步 这样组织的原因:app.js 启动时从 localStorage 读状态并立刻渲染。 所以先把服务器上的记录写进 localStorage,再动态加载 app.js, 应用本身一行都不用改。 ============================================================ */ (function () { 'use strict'; const SYNC_KEYS = ['ykt.marks', 'ykt.notes', 'ykt.seen', 'ykt.pos', 'ykt.ins', 'ykt.side', 'ykt.theme']; const SID = Math.random().toString(36).slice(2, 10); let me = null; let lastRev = -1; let appLoaded = false; let pushing = false; let pushTimer = 0; let applyingRemote = false; let lastTouch = Date.now(); const $ = s => document.querySelector(s); /* ---------------- 收集本地状态 ---------------- */ function snapshot() { const out = {}; for (const k of SYNC_KEYS) { const v = localStorage.getItem(k); if (v !== null) out[k] = v; } return out; } function applyData(data) { if (!data || typeof data !== 'object') return; applyingRemote = true; try { for (const k of SYNC_KEYS) { if (typeof data[k] === 'string') localStorage.setItem(k, data[k]); } } finally { applyingRemote = false; } } function hasLocal() { for (const k of ['ykt.marks', 'ykt.notes', 'ykt.seen']) { const v = localStorage.getItem(k); if (v && v !== '{}' && v.length > 4) return true; } return false; } /* ---------------- 网络 ---------------- */ async function api(path, opts) { const r = await fetch(path, Object.assign({ credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, }, opts || {})); let j = null; try { j = await r.json(); } catch (e) {} return { status: r.status, ok: r.ok, body: j || {} }; } function setDot(state, title) { const d = $('#syncDot'); if (!d) return; d.className = state; d.title = title || ''; } /* 冲突合并:每页的标记取并集,笔记本地优先(刚写的那页不会被冲掉) */ function mergeLocalWith(remote, local) { const out = {}; const keys = new Set([...Object.keys(local), ...Object.keys(remote)]); for (const k of keys) { if (k === 'ykt.marks') { let a = {}, b = {}; try { a = JSON.parse(remote[k] || '{}') || {}; } catch (e) {} try { b = JSON.parse(local[k] || '{}') || {}; } catch (e) {} const m = {}; for (const p of new Set([...Object.keys(a), ...Object.keys(b)])) { const x = a[p] || {}, y = b[p] || {}; const know = (x.know || y.know) ? 1 : 0; const review = know ? 0 : ((x.review || y.review) ? 1 : 0); const fav = (x.fav || y.fav) ? 1 : 0; if (know || review || fav) m[p] = { know, review, fav }; else m[p] = {}; } out[k] = JSON.stringify(m); } else if (k === 'ykt.notes') { let a = {}, b = {}; try { a = JSON.parse(remote[k] || '{}') || {}; } catch (e) {} try { b = JSON.parse(local[k] || '{}') || {}; } catch (e) {} const m = Object.assign({}, a, b); out[k] = JSON.stringify(m); } else if (k === 'ykt.seen') { let a = {}, b = {}; try { a = JSON.parse(remote[k] || '{}') || {}; } catch (e) {} try { b = JSON.parse(local[k] || '{}') || {}; } catch (e) {} out[k] = JSON.stringify(Object.assign({}, a, b)); } else { out[k] = local[k] !== undefined ? local[k] : remote[k]; } } return out; } async function push(force) { if (!me || applyingRemote) return; clearTimeout(pushTimer); if (pushing && !force) { pushTimer = setTimeout(push, 320); return; } pushing = true; setDot('busy', '正在保存…'); try { for (let attempt = 0; attempt < 3; attempt++) { const body = { data: snapshot(), sid: SID }; if (lastRev >= 0) body.baseRev = lastRev; const r = await api('/api/data', { method: 'PUT', body: JSON.stringify(body) }); if (r.status === 401) { location.reload(); return; } if (r.status === 409 && r.body.data) { // 另一处先写了:按页合并后带上新版本号重推;成功就重新加载页面, // 因为正在运行的 app.js 内存里还是旧状态,光改 localStorage 它看不见。 const merged = mergeLocalWith(r.body.data, snapshot()); applyData(merged); lastRev = r.body.rev; setDot('busy', '正在合并另一处的修改…'); const r2 = await api('/api/data', { method: 'PUT', body: JSON.stringify({ data: merged, sid: SID, baseRev: lastRev }), }); if (r2.ok) { lastRev = r2.body.rev; setDot('live', '已合并另一处的修改'); setTimeout(() => location.reload(), 260); } else { setDot('off', '同步冲突,刷新一下'); } return; } if (r.ok) { lastRev = r.body.rev; setDot('live', '已保存到服务器'); return; } setDot('off', '保存失败'); return; } setDot('off', '同步冲突,刷新一下'); } catch (e) { setDot('off', '连不上服务器'); } finally { pushing = false; } } function schedulePush() { if (applyingRemote || !me) return; setDot('busy', '正在保存…'); clearTimeout(pushTimer); pushTimer = setTimeout(push, 420); } /* 拦截 localStorage 写入:应用每改一次标记录一次 */ const rawSet = Storage.prototype.setItem; Storage.prototype.setItem = function (k, v) { rawSet.call(this, k, v); if (this === localStorage && SYNC_KEYS.indexOf(k) >= 0 && !applyingRemote) { lastTouch = Date.now(); schedulePush(); } }; /* ---------------- 实时推送(SSE)+ 轮询兜底 ---------------- */ // 公网隧道(cloudflared / Cloudflare 免费版等)会把 SSE 的分块体缓冲住不转发, // 所以 SSE 建连后若迟迟收不到首帧,就退化成定时轮询,同步照样生效。 let es = null; let esGotFrame = false; let pollTimer = null; let pulling = false; function startPolling(sec) { if (pollTimer) return; pollTimer = setInterval(() => { if (!me || document.hidden) return; if (Date.now() - lastTouch < 6000) return; // 正在操作就别打扰 pullQuiet(); }, (sec || 15) * 1000); } async function pullQuiet() { if (pulling || !me) return; pulling = true; try { const r = await api('/api/me'); if (r.status === 401) { location.reload(); return; } if (!r.ok) return; if (r.body.rev > lastRev) { applyData(r.body.data); lastRev = r.body.rev; setDot('live', '已同步另一处设备的修改'); location.reload(); } else { setDot('live', '已同步'); } } finally { setTimeout(() => { pulling = false; }, 1500); } } function startStream() { if (es || !me) return; esGotFrame = false; try { es = new EventSource('/api/events'); } catch (e) { startPolling(15); return; } es.onopen = () => setDot('live', '实时同步已连接'); es.onmessage = ev => { esGotFrame = true; let msg; try { msg = JSON.parse(ev.data); } catch (e) { return; } if (msg.type !== 'data' || msg.sid === SID) return; if (msg.rev <= lastRev) return; pullRemote(); }; es.onerror = () => { if (es) { es.close(); es = null; } // 隧道环境里 SSE 半死不活,直接切轮询,不要一直重连 if (!esGotFrame) { setDot('busy', '实时通道受限,已切换定时同步'); startPolling(15); setTimeout(() => { if (!esGotFrame) startStream(); }, 60000); return; } setDot('off', '实时同步断开,正在重连…'); setTimeout(startStream, 4000); }; } async function pullRemote() { if (pulling) return; pulling = true; try { const r = await api('/api/me'); if (r.status === 401) { location.reload(); return; } if (!r.ok) return; const idle = Date.now() - lastTouch > 6000 || document.hidden; applyData(r.body.data); lastRev = r.body.rev; if (idle) { setDot('live', '已同步另一处设备的修改'); location.reload(); } else { setDot('busy', '另一处有更新'); note('另一台设备改了记录,点这里同步', () => location.reload()); } } finally { setTimeout(() => { pulling = false; }, 1200); } } /* ---------------- 小提示 ---------------- */ function note(text, onclick) { const t = $('#toast'); if (!t) return; t.textContent = text; t.classList.add('show'); t.onclick = onclick || null; t.style.cursor = onclick ? 'pointer' : ''; clearTimeout(note._t); note._t = setTimeout(() => { t.classList.remove('show'); t.onclick = null; }, 6000); } /* ---------------- 登录界面 ---------------- */ const gate = document.createElement('div'); gate.id = 'authGate'; gate.innerHTML = `

电工及工业电子学 C2

复习台 · 云端同步

登录后,收藏、待复习、已掌握和笔记会实时保存到服务器,换台电脑接着复习。

还没有账号?
`; document.body.appendChild(gate); let mode = 'login'; function setMode(m) { mode = m; $('#auGo').textContent = m === 'login' ? '登录' : '注册并登录'; $('#auHint').textContent = m === 'login' ? '还没有账号?' : '已经有账号了?'; $('#auToggle').textContent = m === 'login' ? '注册一个' : '去登录'; $('#auPwd').setAttribute('autocomplete', m === 'login' ? 'current-password' : 'new-password'); $('#authSub').textContent = m === 'login' ? '登录后,收藏、待复习、已掌握和笔记会实时保存到服务器,换台电脑接着复习。' : '注册一个账号,复习记录就存在这台电脑的服务器上,不会因为清缓存丢掉。'; $('#auMsg').textContent = ''; $('#auMsg').className = 'auth-msg'; } function msg(text, ok) { const m = $('#auMsg'); m.textContent = text; m.className = 'auth-msg' + (ok ? ' ok' : ''); } async function submit() { const name = $('#auName').value.trim(); const pwd = $('#auPwd').value; if (!name) { msg('请填写用户名'); return; } if (!pwd) { msg('请填写密码'); return; } if (mode === 'register' && pwd.length < 6) { msg('密码至少 6 位'); return; } const btn = $('#auGo'); btn.disabled = true; btn.textContent = mode === 'login' ? '登录中…' : '注册中…'; try { const r = await api(mode === 'login' ? '/api/login' : '/api/register', { method: 'POST', body: JSON.stringify({ username: name, password: pwd }) }); if (!r.ok) { msg(r.body.error || '出错了,再试一次'); return; } await afterAuth(r.body); } catch (e) { msg('连不上服务器,确认 server.py 还开着'); } finally { btn.disabled = false; btn.textContent = mode === 'login' ? '登录' : '注册并登录'; } } async function afterAuth(body) { me = body.user; lastRev = body.rev || 0; const serverEmpty = !body.data || Object.keys(body.data).length === 0; if (serverEmpty && hasLocal()) { // 第一次登录:把本机已有的复习记录带上服务器 msg('正在把本机记录同步上去…', true); await push(true); } else { applyData(body.data); } localStorage.setItem('ykt.user', JSON.stringify({ id: me.id, username: me.username })); openApp(); } function openApp() { gate.hidden = true; document.body.classList.remove('gating'); renderAcct(); setDot('live', '已连接'); startStream(); // SSE 在公网隧道下常被缓冲,先把轮询兜底挂上;SSE 真能收到帧也不影响(rev 没变就不做事) startPolling(20); if (!appLoaded) { appLoaded = true; const s = document.createElement('script'); s.src = 'app.js'; s.onload = dockAcct; s.onerror = () => note('app.js 加载失败'); document.body.appendChild(s); } } /* 把账号条挪进左侧栏页脚,别浮在舞台右下角挡视线 */ function dockAcct() { const foot = document.querySelector('.side-foot'); if (!foot) { setTimeout(dockAcct, 300); return; } foot.appendChild(acct); acct.classList.add('in-foot'); } /* ---------------- 账号区 ---------------- */ const acct = document.createElement('div'); acct.id = 'acctBox'; acct.hidden = true; acct.innerHTML = ` ? `; document.body.appendChild(acct); const acctOv = document.createElement('div'); acctOv.id = 'acctOverlay'; acctOv.hidden = true; acctOv.innerHTML = `

账号与同步

记录保存在本机 server.py 的数据库里,同一账号在任何浏览器登录都能接上。

用户名—
已同步版本—
实时通道—
`; document.body.appendChild(acctOv); function renderAcct() { if (!me) { acct.hidden = true; return; } acct.hidden = false; $('#acctAvatar').textContent = (me.username || '?').slice(0, 1).toUpperCase(); $('#acctName').textContent = me.username; } acct.addEventListener('click', e => { if (e.target.id === 'acctOut') return; openPanel(); }); function openPanel() { $('#acName').textContent = me ? me.username : '—'; $('#acRev').textContent = lastRev >= 0 ? '#' + lastRev : '—'; $('#acStream').textContent = (es && es.readyState === 1 && esGotFrame) ? '实时推送' : (pollTimer ? '定时同步(15s)' : '连接中'); $('#acMsg').textContent = ''; $('#acMsg').className = 'auth-msg'; acctOv.hidden = false; } $('#acClose').onclick = () => (acctOv.hidden = true); acctOv.addEventListener('click', e => { if (e.target === acctOv) acctOv.hidden = true; }); $('#acSync').onclick = async () => { $('#acMsg').textContent = '正在上传…'; $('#acMsg').className = 'auth-msg'; await push(true); $('#acRev').textContent = '#' + lastRev; $('#acMsg').textContent = '已保存到服务器(版本 #' + lastRev + ')'; $('#acMsg').className = 'auth-msg ok'; }; $('#acPwd').onclick = async () => { const old = $('#acOld').value, nw = $('#acNew').value; if (!old || !nw) { $('#acMsg').textContent = '原密码和新密码都要填'; return; } const r = await api('/api/password', { method: 'POST', body: JSON.stringify({ old, new: nw }) }); if (r.ok) { $('#acMsg').textContent = '密码已修改,请重新登录'; $('#acMsg').className = 'auth-msg ok'; setTimeout(() => location.reload(), 1200); } else { $('#acMsg').textContent = r.body.error || '修改失败'; } }; $('#acctOut').onclick = async () => { if (!confirm('退出后,这台电脑上的本地缓存还在,重新登录即可接上。确定退出?')) return; await api('/api/logout', { method: 'POST', body: '{}' }); try { localStorage.removeItem('ykt.user'); } catch (e) {} location.reload(); }; /* ---------------- 启动 ---------------- */ $('#auGo').onclick = submit; $('#auToggle').onclick = () => setMode(mode === 'login' ? 'register' : 'login'); [$('#auName'), $('#auPwd')].forEach(inp => { inp.addEventListener('keydown', e => { if (e.key === 'Enter') submit(); }); }); // 关页面前补一次保存(sendBeacon 是 POST,只能用同步 XHR 发 PUT) window.addEventListener('pagehide', () => { if (!me || applyingRemote) return; try { const x = new XMLHttpRequest(); x.open('PUT', '/api/data', false); x.setRequestHeader('Content-Type', 'application/json'); x.send(JSON.stringify({ data: snapshot(), sid: SID })); } catch (e) {} }); ['pointerdown', 'keydown'].forEach(t => window.addEventListener(t, () => { lastTouch = Date.now(); }, { passive: true })); document.body.classList.add('gating'); setMode('login'); (async function boot() { try { const r = await api('/api/me', { method: 'GET' }); if (r.ok && r.body.user) { me = r.body.user; lastRev = r.body.rev || 0; applyData(r.body.data); openApp(); return; } } catch (e) {} // 没登录:显示登录页,输入框聚焦 $('#auName').focus(); })(); })();