/* ============================================================ 登录门 + 云端实时同步 这样组织的原因: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 = `
复习台 · 云端同步
登录后,收藏、待复习、已掌握和笔记会实时保存到服务器,换台电脑接着复习。
记录保存在本机 server.py 的数据库里,同一账号在任何浏览器登录都能接上。