diff --git a/tests/weread/core/note_mutate_spec.lua b/tests/weread/core/note_mutate_spec.lua new file mode 100644 index 0000000..27ec357 --- /dev/null +++ b/tests/weread/core/note_mutate_spec.lua @@ -0,0 +1,236 @@ +--[[-- +book.note:条目键、改备注、删除时走源侧墓碑,以及打开中的章节会被同步改写。 + +@module tests.book.note_mutate_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, redundant-parameter, missing-parameter, inject-field, assign-type-mismatch, param-type-mismatch, cast-type-mismatch, return-type-mismatch, cast-local-type + +local Assert = require("support.assert") +local Config = require("support.config") + +local JSON = require("support.json_stub") +package.loaded["json"] = JSON +package.preload["json"] = function() return JSON end + +local sqlite_ok = pcall(require, "lua-ljsqlite3/init") +if not sqlite_ok then + Assert.skip("当前离线环境没有 ljsqlite3 Lua 模块") +end + +local db_path = Config.dir() .. "/note_mutate_spec.sqlite3" +for _idx, suffix in ipairs({ "", "-wal", "-shm" }) do os.remove(db_path .. suffix) end + +package.loaded["utils.paths"] = nil +package.preload["utils.paths"] = function() + return { + dbPath = function() return db_path end, + ensureSettings = function() end, + } +end +package.loaded["ui/network/manager"] = { isConnected = function() return false end } + +local live = { + annotations = { + { + datetime = "2026-11-01 10:00:00", drawer = "lighten", color = "yellow", + text = "打开中的句子", note = "旧备注", + page = "/body/p[1]/text()[1].0", pos0 = "/body/p[1]/text()[1].0", + pos1 = "/body/p[1]/text()[1].6", + }, + }, +} +live.annotation = live +function live.updateAnnotations() live.updated = true end +live.doc_settings = { + saveSetting = function(_, key, value) live.saved = { key, value } end, + flush = function() live.flushed = true end, +} +package.loaded["apps/reader/readerui"] = { instance = live } +package.loaded["reader.session"] = { + _snapshot = { identity = { source_id = "local", stable_id = "open-book", chapter_idx = 2 } }, +} + +local wechat_notes = require("moonsource_weread.notes") +local function kavitaPrepare(_, previous, current, deleted) + -- 与 source.kavita.prepareLocalAnnotations 的删除墓碑契约一致(见 init.lua)。 + if type(deleted) == "table" and deleted.pos0 then + for _idx, old in ipairs(previous or {}) do + if old.pos0 == deleted.pos0 and old.kavita_id then + current[#current + 1] = { + datetime = old.datetime, chapter_idx = old.chapter_idx, + kavita_id = old.kavita_id, kavita_note = old.kavita_note, kavita_deleted = true, + } + end + end + end + return current +end + +package.loaded["source.registry"] = { + resolve = function(id) + if id == "ext.weread" then + return { + id = "ext.weread", + cleanAnnotations = wechat_notes.cleanAnnotations, + prepareLocalAnnotations = function(_, prev, cur) + return wechat_notes.prepareLocalAnnotations(prev, cur) + end, + } + end + if id == "kavita" then + return { + id = "kavita", + cleanAnnotations = function(_, items, total) + return require("book.note.normalize").clean(items, total) + end, + prepareLocalAnnotations = kavitaPrepare, + } + end + return { id = id } + end, +} + +for _idx, name in ipairs({ "utils.db", "book.books_db", "book.note_db", "book.note" }) do + package.loaded[name] = nil +end + +local Base = require("utils.db") +local NoteDB = require("book.note_db") +local Note = require("book.note") +local Normalize = require("book.note.normalize") +Assert.not_nil(Base.open()) + +local function item(extra) + local it = { + datetime = "2026-11-01 10:00:00", + drawer = "lighten", + color = "yellow", + text = "一段原文", + page = "/body/p[1]/text()[1].0", + pos0 = "/body/p[1]/text()[1].0", + pos1 = "/body/p[1]/text()[1].6", + chapter = "第一章", + chapter_idx = 1, + } + for k, v in pairs(extra or {}) do it[k] = v end + return it +end + +local function save(source_id, stable_id, chapter_idx, items, synced) + Assert.is_true(NoteDB.upsert(source_id, stable_id, chapter_idx, JSON.encode(items), 100, synced)) +end + +-- 键可往返,分页 pos 表不会因地址误撞。 +local a = item({ pos0 = { page = 3, x = 1, y = 2 }, pos1 = { page = 3, x = 9, y = 2 }, page = 3 }) +local key = Note.itemKey("moon", "book", 0, a) +local parsed = Note.parseItemKey(key) +Assert.not_nil(parsed) +Assert.eq(parsed.source_id, "moon") +Assert.eq(parsed.stable_id, "book") +Assert.eq(parsed.chapter_idx, 0) +Assert.eq(Note.itemKey("moon", "book", 0, a), key) +Assert.is_nil(Note.parseItemKey("")) +Assert.is_nil(Note.parseItemKey("%%%")) + +-- 改备注:只动 note,不动 text / 位置。 +save("local", "book-a", 1, { item({ note = "旧" }) }) +local edit_key = Note.itemKey("local", "book-a", 1, item({ note = "旧" })) +Assert.is_true(Note.mutate({ key = edit_key, note = " 新备注 " })) +local row = NoteDB.get("local", "book-a", 1) +local got = Normalize.decode(row.payload) +Assert.eq(got[1].note, "新备注") +Assert.eq(got[1].text, "一段原文") +Assert.eq(got[1].pos0, "/body/p[1]/text()[1].0") +Assert.eq(row.sync_status, 0) + +-- 清空备注。 +Assert.is_true(Note.mutate({ key = edit_key, note = " " })) +got = Normalize.decode(NoteDB.get("local", "book-a", 1).payload) +Assert.is_nil(got[1].note) + +-- 微信:删除带 bookmark id 的划线必须留下 wr_deleted 墓碑,不能只从快照抹掉。 +local wr = item({ wr_bookmark_id = "bm-1", wr_range = "10-20", text = "微信句子" }) +save("ext.weread", "wr-book", 3, { wr }) +local wr_key = Note.itemKey("ext.weread", "wr-book", 3, wr) +Assert.is_true(Note.mutate({ key = wr_key, remove = true })) +local wr_items = Normalize.decode(NoteDB.get("ext.weread", "wr-book", 3).payload) +local tombs, visible = 0, 0 +for _idx, it in ipairs(wr_items) do + if it.wr_deleted then + tombs = tombs + 1 + Assert.eq(it.wr_bookmark_id, "bm-1") + else + visible = visible + 1 + end +end +Assert.eq(tombs, 1) +Assert.eq(visible, 0) + +-- Kavita:删除必须把 deleted 交给 prepareLocalAnnotations,写出 kavita_deleted 墓碑。 +local kv = item({ kavita_id = 42, kavita_note = "k", text = "Kavita 句子", pos0 = "/body/p[2]/text()[1].0" }) +save("kavita", "kv-book", 0, { kv }, true) +local kv_key = Note.itemKey("kavita", "kv-book", 0, kv) +Assert.is_true(Note.mutate({ key = kv_key, remove = true })) +local kv_items = Normalize.decode(NoteDB.get("kavita", "kv-book", 0).payload) +local kv_tomb = 0 +for _idx, it in ipairs(kv_items) do + if it.kavita_deleted then + kv_tomb = kv_tomb + 1 + Assert.eq(it.kavita_id, 42) + end +end +Assert.eq(kv_tomb, 1) + +-- 属主源已不可用:不允许通用清洗抹掉源字段、删除墓碑和原有同步状态。 +do + local Registry = require("source.registry") + local resolve = Registry.resolve + local pending = { datetime = wr.datetime, wr_bookmark_id = "pending", wr_deleted = true } + save("ext.weread", "unavailable", 0, { wr, pending }, true) + local before = NoteDB.get("ext.weread", "unavailable", 0) + Registry.resolve = function() return nil, "source unavailable" end + local unavailable_key = Note.itemKey("ext.weread", "unavailable", 0, wr) + for _idx, opts in ipairs({ + { key = unavailable_key, note = "不能保存" }, + { key = unavailable_key, remove = true }, + }) do + local changed, change_err = Note.mutate(opts) + Assert.is_false(changed) + Assert.eq(change_err, "source unavailable") + local after = NoteDB.get("ext.weread", "unavailable", 0) + Assert.eq(after.payload, before.payload) + Assert.eq(after.updated_at, before.updated_at) + Assert.eq(after.sync_status, before.sync_status) + end + Registry.resolve = resolve +end + +-- 当前正打开的章节:改备注会写进阅读器内存和 sidecar,避免下次保存盖掉。 +local open_item = item({ + text = "打开中的句子", note = "旧备注", + page = "/body/p[1]/text()[1].0", + pos0 = "/body/p[1]/text()[1].0", + pos1 = "/body/p[1]/text()[1].6", +}) +save("local", "open-book", 2, { open_item }) +local open_key = Note.itemKey("local", "open-book", 2, open_item) +Assert.is_true(Note.mutate({ key = open_key, note = " 远程改的 " })) +Assert.eq(live.annotations[1].note, "远程改的") +Assert.eq(Normalize.decode(NoteDB.get("local", "open-book", 2).payload)[1].note, live.annotations[1].note) +Assert.is_true(live.updated) +Assert.is_true(live.flushed) +Assert.eq(live.saved[1], "annotations") + +Assert.is_true(Note.mutate({ key = open_key, remove = true })) +Assert.eq(#live.annotations, 0) + +-- 找不到的键:格式错误,或书不存在。 +local ok, err = Note.mutate({ key = "%%%", note = "x" }) +Assert.is_false(ok) +Assert.eq(err, "invalid key") +ok, err = Note.mutate({ key = Note.itemKey("local", "missing", 0, item()), remove = true }) +Assert.is_false(ok) +Assert.eq(err, "not found") + +Base.close() +for _idx, suffix in ipairs({ "", "-wal", "-shm" }) do os.remove(db_path .. suffix) end diff --git a/tests/weread/core/note_sync_spec.lua b/tests/weread/core/note_sync_spec.lua new file mode 100644 index 0000000..596bcf6 --- /dev/null +++ b/tests/weread/core/note_sync_spec.lua @@ -0,0 +1,897 @@ +---@diagnostic disable: undefined-field, missing-fields, redundant-parameter, missing-parameter, inject-field, assign-type-mismatch, param-type-mismatch, cast-type-mismatch, return-type-mismatch, cast-local-type + +--[[-- book.note 从本地未同步快照上传,并在打开时拉取远端快照。 --]] + +local Assert = require("support.assert") +local Stubs = require("support.stubs") + +local previous_settings = _G.G_reader_settings +local source +_G.G_reader_settings = { + readSetting = function() + return "device-1" + end, + saveSetting = function() end, +} + +local rows = {} +package.preload["book.note_db"] = function() + return { + upsert = function(source_id, stable_id, chapter_idx, payload, updated_at, synced) + rows[source_id .. ":" .. stable_id .. ":" .. (chapter_idx or 0)] = { + source_id = source_id, + stable_id = stable_id, + chapter_idx = chapter_idx or 0, + payload = payload, + updated_at = updated_at, + sync_status = synced and 1 or 0, + } + return true + end, + -- 返回副本:真身每次都从 sqlite 新建表。共享引用会让调用方手里的 row + -- 跟着库里的行一起变,把「期间被改过」的判定悄悄变成永远相等。 + get = function(source_id, stable_id, chapter_idx) + local row = rows[source_id .. ":" .. stable_id .. ":" .. (chapter_idx or 0)] + if not row then return nil end + local copy = {} + for k, v in pairs(row) do copy[k] = v end + return copy + end, + upsertRemote = function(source_id, stable_id, chapter_idx, payload, updated_at) + local key = source_id .. ":" .. stable_id .. ":" .. (chapter_idx or 0) + local old = rows[key] + if not old or old.sync_status == 1 then + rows[key] = { source_id = source_id, stable_id = stable_id, + chapter_idx = chapter_idx or 0, payload = payload, + updated_at = updated_at, sync_status = 1 } + end + return true + end, + unsynced = function() + local out = {} + for _, row in pairs(rows) do + if row.sync_status == 0 then out[#out + 1] = row end + end + return out + end, + all = function(source_id) + local out = {} + for _, row in pairs(rows) do + if not source_id or row.source_id == source_id then out[#out + 1] = row end + end + return out + end, + -- 与真身同语义:payload 与 sync_status 同一条语句写入,受 updated_at 乐观锁保护 + markSynced = function(source_id, stable_id, chapter_idx, updated_at, payload) + local row = rows[source_id .. ":" .. stable_id .. ":" .. chapter_idx] + if row and row.updated_at == updated_at then + row.sync_status = 1 + if payload ~= nil then row.payload = payload end + end + return true + end, + -- 与真身同语义:只写 payload,sync_status / updated_at 不动 + updatePayload = function(source_id, stable_id, chapter_idx, payload) + local row = rows[source_id .. ":" .. stable_id .. ":" .. (chapter_idx or 0)] + if row then row.payload = payload end + return true + end, + } +end +package.preload["source.registry"] = function() + return { resolve = function() return source end } +end +package.preload["json"] = function() + local payloads = {} + local revision = 0 + return { + encode = function(value) + revision = revision + 1 + local payload = "[snapshot-" .. revision .. "]" + payloads[payload] = value + return payload + end, + decode = function(payload) return payloads[payload] end, + } +end +package.loaded["book.note_db"] = nil +package.loaded["json"] = nil +package.loaded["source.registry"] = nil +package.loaded["book.note"] = nil +package.loaded["reader.session.note"] = nil +local open_files = { + ["/a.epub"] = { source_id = "moon", stable_id = "小说.epub" }, + ["/b2.epub"] = { source_id = "unlocated", stable_id = "book2.epub" }, + ["/b3.epub"] = { source_id = "authoritative", stable_id = "book.epub", chapter_idx = 2 }, + ["/b4.epub"] = { source_id = "dropped", stable_id = "book8.epub" }, + ["/b6.epub"] = { source_id = "dedupe", stable_id = "book9.epub" }, +} +package.preload["book.store"] = function() + return { identityFor = function(file) return open_files[file] end } +end +package.loaded["book.store"] = nil + +local sent = {} +local pull_count = 0 +source = { + id = "moon", + pushNotesAsync = function(_, pushed_identity, pushed_annotations, cb) + sent[#sent + 1] = { identity = pushed_identity, annotations = pushed_annotations } + cb({ code = 200 }) + end, + pullNotesAsync = function(_, _identity, cb) + pull_count = pull_count + 1 + cb({ { datetime = "2026-08-20", page = "/remote" } }) + end, +} +local annotations = { + { + datetime = "2026-08-15 21:11:53", + datetime_updated = "2026-08-15 21:35:51", + drawer = "lighten", + color = "cyan", + text = "高亮文字", + note = "笔记", + chapter = "第一章", + pageno = 12, + page = "/body/p[1].0", + pos0 = "/body/p[1].0", + pos1 = "/body/p[1].4", + ignored = "不能上报", + }, +} +local ui = { + document = { + file = "/a.epub", + getPageCount = function() + return 100 + end, + }, + doc_settings = { + flush = function() end, + readSetting = function(_, key) + if key == "annotations" then + return annotations + end + end, + saveSetting = function(_, key, value) + if key == "annotations" then annotations = value end + end, + }, +} +local identity = { + source_id = "moon", + stable_id = "小说.epub", + source = source, +} +local Note = require("book.note") +local SessionNote = require("reader.session.note") +source.syncNotesAsync = function(self, opts, cb) + return Note.syncAsync(self, opts, cb) +end + +SessionNote.save(ui, identity, nil, function(ok) + if ok then Note.syncAsync(source, { identity = identity }, function() end) end +end) +Stubs.flush() +Assert.eq(#sent, 1) +Assert.eq(sent[1].identity.source_id, "moon") +Assert.eq(sent[1].identity.stable_id, "小说.epub") +Assert.is_nil(sent[1].identity.chapter_idx) +Assert.eq(sent[1].annotations[1].total_pages, 100) +Assert.eq(sent[1].annotations[1].text, "高亮文字") +Assert.eq(sent[1].annotations[1].ignored, nil) + +annotations = {} +SessionNote.save(ui, identity, nil, function(ok) + if ok then Note.syncAsync(source, { identity = identity }, function() end) end +end) +Stubs.flush() +Assert.eq(#sent, 2) +Assert.eq(#sent[2].annotations, 0, "空快照必须上报以传播删除") + +-- 网络恢复只重试本地脏快照,不顺手拉远端。 +annotations = { { datetime = "2026-08-21", page = "/local-new" } } +SessionNote.save(ui, identity, nil, function(ok) + if ok then Note.syncAsync(source, { identity = identity, dirty_only = true }, function() end) end +end) +Stubs.flush() +Assert.eq(#sent, 3) +Assert.eq(pull_count, 2) + +SessionNote.pull(ui, identity) +Stubs.flush() +Assert.eq(annotations[1].page, "/remote", "pull 必须在保存当前快照后应用远端快照") +Assert.eq(rows["moon:小说.epub:0"].sync_status, 1, "拉取结果必须先作为已同步快照写入 SQLite") + +-- 只读源:本地脏快照不能上传,但仍应拉取远端。 +pull_count = 0 +local readonly = { + id = "readonly", + pullNotesAsync = function(_, _identity, cb) + pull_count = pull_count + 1 + cb({ { datetime = "2026-08-22", page = "/remote-readonly", drawer = "lighten", text = "远端" } }) + end, +} +readonly.syncNotesAsync = function(self, opts, cb) + return Note.syncAsync(self, opts, cb) +end +rows["readonly:book.epub:0"] = { + source_id = "readonly", + stable_id = "book.epub", + chapter_idx = 0, + payload = "[snapshot-dirty]", + updated_at = 99, + sync_status = 0, +} +local sync_err +Note.syncAsync(readonly, { identity = { + source_id = "readonly", stable_id = "book.epub", source = readonly, +} }, function(result, err) + sync_err = err + Assert.eq(result.conflicts, 1) + Assert.eq(result.pulled, 1) +end) +Stubs.flush() +Assert.is_nil(sync_err, "只读源拉取不应因无法上传而失败") +Assert.eq(pull_count, 1) + +-- 重复开书拉到同一份远端快照:payload 与库里那行逐字节相同就不写, +-- 修订号(updated_at)不抖 —— 否则每次开书都像「有新内容」。 +-- 本 spec 的 JSON 桩每次 encode 都返回新的 `[snapshot-N]`,payload 永远不相等, +-- 这条断言无从谈起;这一段临时换成「按内容稳定编码」的 JSON(decode 同步换),结束后恢复。 +-- 另外用独立的小书(pageCount=0)验:pageCount 非 0 时保存侧会给快照补 total_pages, +-- 与 pull 落的桶本就不等,那是保存侧的差异,不该混进来干扰本条断言。 +do + local JSON = require("json") + local real_encode, real_decode = JSON.encode, JSON.decode + local encoded = {} + local function stable(value) + if type(value) ~= "table" then return tostring(value) end + local keys = {} + for key in pairs(value) do keys[#keys + 1] = key end + table.sort(keys, function(a, b) return tostring(a) < tostring(b) end) + local parts = {} + for _idx, key in ipairs(keys) do + parts[#parts + 1] = tostring(key) .. "=" .. stable(value[key]) + end + return "{" .. table.concat(parts, ",") .. "}" + end + JSON.encode = function(value) + local payload = stable(value) + encoded[payload] = value + return payload + end + JSON.decode = function(payload) return encoded[payload] end + + -- 让 applyLocal 认得这本书,否则远端快照落不进 doc_settings,下一轮保存又把它当成本地改动。 + open_files["/idem.epub"] = { source_id = "idem", stable_id = "idem.epub" } + local idem_annotations = {} + local idem_ui = { + document = { file = "/idem.epub", getPageCount = function() return 0 end }, + doc_settings = { + flush = function() end, + readSetting = function(_, key) + if key == "annotations" then return idem_annotations end + end, + saveSetting = function(_, key, value) + if key == "annotations" then idem_annotations = value end + end, + }, + } + local idem_source = { + id = "idem", + pushNotesAsync = function(_, _, _, cb) cb({ code = 200 }) end, + pullNotesAsync = function(_, _, cb) cb({ { datetime = "2026-09-01", page = "/idem" } }) end, + } + idem_source.syncNotesAsync = function(self, opts, cb) return Note.syncAsync(self, opts, cb) end + local idem_identity = { source_id = "idem", stable_id = "idem.epub", source = idem_source } + + SessionNote.pull(idem_ui, idem_identity) + Stubs.flush() + local key = "idem:idem.epub:0" + Assert.not_nil(rows[key], "首次拉取要落库") + local revision = rows[key].updated_at + SessionNote.pull(idem_ui, idem_identity) + Stubs.flush() + Assert.eq(rows[key].updated_at, revision, "同一份快照重复拉取不刷新修订号") + SessionNote.pull(idem_ui, idem_identity) + Stubs.flush() + Assert.eq(rows[key].updated_at, revision, "再开一次也不抖") + JSON.encode, JSON.decode = real_encode, real_decode +end + +-- 未定位的远端划线不能进 doc_settings: +-- ReaderAnnotation:onReadSettings 按首条 page 的类型判定整份注解的格式,数字 page 会把 +-- 本地划线一起搬去 annotations_paging 并加载空表;缺 pos0 则让 drawSavedHighlight 抛错。 +do + local unlocated = { + id = "unlocated", + pullNotesAsync = function(_, _identity, cb) + cb({ + -- 定位失败:只有 wr_range,没有 page/pos0 + { datetime = "2026-08-23", drawer = "lighten", text = "远端未定位", wr_range = "0-5" }, + -- 已定位:page 是 xpointer + { + datetime = "2026-08-23", drawer = "lighten", text = "远端已定位", + page = "/html/body/p[1]/text().0", + pos0 = "/html/body/p[1]/text().0", + pos1 = "/html/body/p[1]/text().5", + wr_range = "10-15", wr_bookmark_id = "bm-1", + }, + }) + end, + } + unlocated.syncNotesAsync = function(self, opts, cb) + return Note.syncAsync(self, opts, cb) + end + annotations = {} + local ui2 = { + document = { file = "/b2.epub", getPageCount = function() return 10 end }, + doc_settings = { + flush = function() end, + readSetting = function(_, key) + if key == "annotations" then return annotations end + end, + saveSetting = function(_, key, value) + if key == "annotations" then annotations = value end + end, + }, + } + SessionNote.pull(ui2, { + source_id = "unlocated", stable_id = "book2.epub", source = unlocated, + }) + Stubs.flush() + Assert.eq(#annotations, 1, "只有定位成功的远端划线可进 doc_settings") + Assert.eq(annotations[1].text, "远端已定位") + Assert.eq(type(annotations[1].page), "string", "page 必须是 xpointer 字符串") +end + +-- 远端一条注解都没报回来时,不能把已同步的本地快照覆盖成空: +-- 协议字段缺失与「云端确实为空」在 wire 上无法区分,宁可漏掉云端删除也不能清空划线。 +do + local empty = { + id = "empty", + pullNotesAsync = function(_, _identity, cb) cb({}) end, + } + rows["empty:book3.epub:0"] = { + source_id = "empty", + stable_id = "book3.epub", + chapter_idx = 0, + payload = "[snapshot-kept]", + updated_at = 7, + sync_status = 1, + } + local result_err + Note.syncAsync(empty, { identity = { + source_id = "empty", stable_id = "book3.epub", source = empty, + } }, function(_, err) result_err = err end) + Stubs.flush() + Assert.is_nil(result_err) + Assert.eq(rows["empty:book3.epub:0"].payload, "[snapshot-kept]", + "远端空回包不能覆盖已同步的本地划线") +end + +-- 完整远端快照为空时必须覆盖旧分片,并携带 authoritative 标记供 applyLocal 删除旧项。 +do + local merge_authoritative + local authoritative = { + id = "authoritative", + pullNotesAsync = function(_, _identity, cb) + cb({}, nil, { authoritative = true }) + end, + mergeAnnotations = function(_, remote, _current, _paging, is_authoritative) + merge_authoritative = is_authoritative + return remote + end, + } + local JSON = require("json") + rows["authoritative:book.epub:2"] = { + source_id = "authoritative", + stable_id = "book.epub", + chapter_idx = 2, + payload = JSON.encode({ + { + datetime = "old", page = "/body/a", pos0 = "/body/a", pos1 = "/body/b", + drawer = "lighten", wr_bookmark_id = "bm-old", + }, + }), + updated_at = 7, + sync_status = 1, + } + Note.syncAsync(authoritative, { identity = { + source_id = "authoritative", stable_id = "book.epub", chapter_idx = 2, + source = authoritative, + } }, function() end) + Stubs.flush() + local snapshot = JSON.decode(rows["authoritative:book.epub:2"].payload) + Assert.is_true(snapshot.authoritative) + Assert.eq(#snapshot.items, 0) + + annotations = { + { + datetime = "old", page = "/body/a", pos0 = "/body/a", pos1 = "/body/b", + drawer = "lighten", wr_bookmark_id = "bm-old", + }, + } + local ui3 = { + document = { file = "/b3.epub" }, + doc_settings = { + readSetting = function(_, key) + if key == "annotations" then return annotations end + end, + saveSetting = function(_, key, value) + if key == "annotations" then annotations = value end + end, + flush = function() end, + }, + } + SessionNote.applyLocal(ui3, { + source_id = "authoritative", stable_id = "book.epub", chapter_idx = 2, + source = authoritative, + }) + Assert.eq(#annotations, 0, "权威远端删除不能被本地防丢保护挡住") + Assert.is_true(merge_authoritative) + + -- 回调回来时阅读器已换了章:不得把别章快照写进当前文档 + Assert.eq(SessionNote.applyLocal(ui3, { + source_id = "authoritative", stable_id = "book.epub", chapter_idx = 3, + source = authoritative, + }), 0) + Assert.eq(SessionNote.applyLocal({ doc_settings = ui3.doc_settings }, { + source_id = "authoritative", stable_id = "book.epub", chapter_idx = 2, + source = authoritative, + }), 0, "没有打开文档时不应用") +end + +-- 上传窗口内用户又划了线:不能用上传时那份快照 + 旧修订号覆盖回去。 +-- 曾经的写法是「先 upsert 旧 payload + 旧 updated_at,再 markSynced」, +-- 第一步把新划的线抹掉,第二步的乐观锁于是恰好匹配、脏标记也被清掉。 +do + local racing = { id = "racing" } + -- payload 必须经 json stub 的 encode 生成,decode 才认得(否则 sync 在解码处就退出) + local JSON = require("json") + local uploaded_payload = JSON.encode({ + { datetime = "2026-08-24", page = "/body/p[1].0" }, + }) + local newer_payload = JSON.encode({ + { datetime = "2026-08-24", page = "/body/p[1].0" }, + { datetime = "2026-08-24", page = "/body/p[2].0" }, + }) + rows["racing:book4.epub:0"] = { + source_id = "racing", + stable_id = "book4.epub", + chapter_idx = 0, + payload = uploaded_payload, + updated_at = 100, + sync_status = 0, + } + racing.pushNotesAsync = function(_, _identity, _annotations, cb) + -- 模拟上传耗时期间用户新划一条线:payload 与修订号都变了 + rows["racing:book4.epub:0"].payload = newer_payload + rows["racing:book4.epub:0"].updated_at = 101 + rows["racing:book4.epub:0"].sync_status = 0 + cb({ code = 200 }) + end + racing.pullNotesAsync = function(_, _identity, cb) cb({}) end + + local pushed_result + Note.syncAsync(racing, { identity = { + source_id = "racing", stable_id = "book4.epub", source = racing, + }, dirty_only = true }, function(result) pushed_result = result end) + Stubs.flush() + + local row = rows["racing:book4.epub:0"] + Assert.eq(row.payload, newer_payload, "上传期间新划的线不能被旧快照覆盖") + Assert.eq(row.updated_at, 101, "修订号不能被回退") + Assert.eq(row.sync_status, 0, "本地仍有未上传内容,脏标记必须保留") + Assert.eq(pushed_result.pushed, 1, "这次上传本身是成功的") +end + +-- 同一源并发触发两次同步时必须串行;第二次应看到第一轮已确认的干净快照。 +do + local JSON = require("json") + local callbacks = {} + local serial = { + id = "serial", + pushNotesAsync = function(_, _identity, _annotations, cb) + callbacks[#callbacks + 1] = cb + return { cancel = function() end } + end, + } + rows["serial:book.epub:0"] = { + source_id = "serial", stable_id = "book.epub", chapter_idx = 0, + payload = JSON.encode({ { datetime = "2026-09-04", page = "/local" } }), + updated_at = 200, sync_status = 0, + } + local completed = 0 + local opts = { + identity = { source_id = "serial", stable_id = "book.epub", source = serial }, + dirty_only = true, + } + Note.syncAsync(serial, opts, function() completed = completed + 1 end) + Note.syncAsync(serial, opts, function() completed = completed + 1 end) + Stubs.flush() + Assert.eq(#callbacks, 1, "第二轮不能与第一轮并发上传") + callbacks[1]({ code = 200 }) + Stubs.flush() + Assert.eq(#callbacks, 1, "第一轮确认后第二轮不应重复上传干净快照") + Assert.eq(completed, 2) + + -- 已结束任务的句柄迟到 cancel,不能放行同源的下一轮并发。 + rows["serial:book.epub:0"].sync_status = 0 + rows["serial:book.epub:0"].updated_at = 300 + local done_handle = Note.syncAsync(serial, opts, function() end) + Stubs.flush() + callbacks[2]({ code = 200 }) + Stubs.flush() + rows["serial:book.epub:0"].sync_status = 0 + rows["serial:book.epub:0"].updated_at = 400 + Note.syncAsync(serial, opts, function() end) + Stubs.flush() + Assert.eq(#callbacks, 3) + done_handle.cancel() + rows["serial:other.epub:0"] = { + source_id = "serial", stable_id = "other.epub", chapter_idx = 0, + payload = JSON.encode({ { datetime = "2026-09-05", page = "/x" } }), + updated_at = 500, sync_status = 0, + } + Note.syncAsync(serial, { + identity = { source_id = "serial", stable_id = "other.epub", source = serial }, + dirty_only = true, + }, function() end) + Stubs.flush() + Assert.eq(#callbacks, 3, "第三轮仍在飞,第四轮必须排队") +end + +-- 上传期间又改了笔记(stale):回填的 kavita_id 并进 live 快照,脏标记与修订号都不动。 +-- 之前整份丢弃,下一轮推送只好重新按键认领(甚至重复建)。 +do + local JSON = require("json") + local racing_backfill = { id = "backfill" } + local uploaded = JSON.encode({ + { + datetime = "2026-10-01", page = "/body/p[1].0", pos0 = "/body/p[1].0", pos1 = "/body/p[1].5", + text = "高亮", kavita_id = nil, + }, + }) + local newer = JSON.encode({ + { + datetime = "2026-10-01", page = "/body/p[1].0", pos0 = "/body/p[1].0", pos1 = "/body/p[1].5", + text = "高亮", + }, + { datetime = "2026-10-01", page = "/body/p[2].0", pos0 = "/body/p[2].0", pos1 = "/body/p[2].4", text = "新划的" }, + }) + local key = "backfill:book5.epub:0" + rows[key] = { + source_id = "backfill", stable_id = "book5.epub", chapter_idx = 0, + payload = uploaded, updated_at = 10, sync_status = 0, + } + -- 真实源会把 kavita_* 透传进快照;这里明确这条路(核心不自己补字段)。 + racing_backfill.cleanAnnotations = function(_, items) return items end + racing_backfill.pushNotesAsync = function(_, _identity, annotations, cb) + annotations[1].kavita_id = 77 + annotations[1].kavita_note = "高亮" + -- 回包还没到,用户又划了一条:payload 与修订号都变了 + rows[key].payload = newer + rows[key].updated_at = 11 + cb(true, nil, { pushed = 1 }) + end + racing_backfill.pullNotesAsync = function(_, _identity, cb) cb({}) end + + local result + Note.syncAsync(racing_backfill, { identity = { + source_id = "backfill", stable_id = "book5.epub", source = racing_backfill, + }, dirty_only = true }, function(value) result = value end) + Stubs.flush() + + local snapshot = JSON.decode(rows[key].payload) + Assert.eq(#snapshot, 2, "上传期间新划的线不能被覆盖") + Assert.eq(snapshot[1].kavita_id, 77, "回填的 id 并进 live 快照") + Assert.eq(snapshot[1].kavita_note, "高亮") + Assert.is_nil(snapshot[2].kavita_id, "没推的那条不编 id") + Assert.eq(rows[key].updated_at, 11, "修订号不能被回退") + Assert.eq(rows[key].sync_status, 0, "仍是脏行,下轮再推") + Assert.eq(result.pushed, 1) +end + +-- pushed 如实计数:源说「这轮没什么可推」时核心不能 +1,否则首页会白刷一次。 +do + local JSON = require("json") + local quiet = { id = "quiet" } + local key = "quiet:book6.epub:0" + rows[key] = { + source_id = "quiet", stable_id = "book6.epub", chapter_idx = 0, + payload = JSON.encode({ { datetime = "2026-10-02", page = "/body/p[1].0" } }), + updated_at = 500, sync_status = 0, + } + quiet.pushNotesAsync = function(_, _identity, _annotations, cb) cb(true, nil, { pushed = 0 }) end + quiet.pullNotesAsync = function(_, _identity, cb) cb({}) end + local result + Note.syncAsync(quiet, { identity = { + source_id = "quiet", stable_id = "book6.epub", source = quiet, + }, dirty_only = true }, function(value) result = value end) + Stubs.flush() + Assert.eq(result.pushed, 0, "源如实回 0 就按 0 记") + Assert.eq(rows[key].sync_status, 1, "对账完的快照仍要清脏,否则每轮重推") +end + +-- 远端删除穿过条数保护:源返回 dropped = 主动判定为「远端已删」的条数, +-- 守卫要把它们算进来;老源没有第二返回值时行为不变(仍然不覆盖本地划线)。 +do + local JSON = require("json") + local kept = { + { datetime = "2026-10-04", page = "/body/a", pos0 = "/body/a", pos1 = "/body/b", + drawer = "lighten", text = "远端删了" }, + } + rows["dropped:book8.epub:0"] = { + source_id = "dropped", stable_id = "book8.epub", chapter_idx = 0, + payload = JSON.encode(kept), updated_at = 9, sync_status = 1, + } + local current_annotations = kept + local ui8 = { + document = { file = "/b4.epub", getPageCount = function() return 10 end }, + doc_settings = { + flush = function() end, + readSetting = function(_, name) + if name == "annotations" then return current_annotations end + end, + saveSetting = function(_, name, value) + if name == "annotations" then current_annotations = value end + end, + }, + } + local dropping = { + id = "dropped", + mergeAnnotations = function(_, _remote, _current, _paging, _authoritative) + return {}, 1 + end, + } + Assert.eq(SessionNote.applyLocal(ui8, { + source_id = "dropped", stable_id = "book8.epub", source = dropping, + }), 0) + Assert.eq(#current_annotations, 0, "dropped 计入守卫,合法删除不被条数保护拦住") + + current_annotations = { kept[1] } + local legacy = { + id = "dropped", + mergeAnnotations = function() return {} end, + } + Assert.eq(SessionNote.applyLocal(ui8, { + source_id = "dropped", stable_id = "book8.epub", source = legacy, + }), 0) + Assert.eq(#current_annotations, 1, "没有 dropped 第二返回值时仍按条数保护跳过") +end + +-- 远端同键去重穿过条数保护:第一次修正时 doc_settings 里旧有 5 条(37 / 43 都在), +-- 合并后只剩 4 条 + 1 条被抑制(deduped)。守卫必须把 deduped 算回来,否则重复条目永远修不掉; +-- 没有 dropped / deduped 解释的「少一条」仍按误删拦住。 +do + local JSON = require("json") + local function ann(page) + return { datetime = "2026-10-05", page = page, pos0 = page, pos1 = page .. ".5", + drawer = "lighten", text = "线" } + end + local five = { ann("/body/p[1]"), ann("/body/p[2]"), ann("/body/p[3]"), ann("/body/p[4]"), ann("/body/p[5]") } + rows["dedupe:book9.epub:0"] = { + source_id = "dedupe", stable_id = "book9.epub", chapter_idx = 0, + payload = JSON.encode(five), updated_at = 9, sync_status = 1, + } + local current_annotations = five + local ui9 = { + document = { file = "/b6.epub", getPageCount = function() return 10 end }, + doc_settings = { + flush = function() end, + readSetting = function(_, name) + if name == "annotations" then return current_annotations end + end, + saveSetting = function(_, name, value) + if name == "annotations" then current_annotations = value end + end, + }, + } + local deduping = { + id = "dedupe", + mergeAnnotations = function(_, _remote, _current, _paging, _authoritative) + return { five[1], five[2], five[3], five[4] }, 0, 1 + end, + } + Assert.eq(SessionNote.applyLocal(ui9, { + source_id = "dedupe", stable_id = "book9.epub", source = deduping, + }), 4, "deduped 计入守卫:4 merged + 1 deduped vs 5 current → 放行") + Assert.eq(#current_annotations, 4) + + current_annotations = five + local losing = { + id = "dedupe", + mergeAnnotations = function(_, _remote, _current, _paging, _authoritative) + return { five[1], five[2], five[3], five[4] } + end, + } + Assert.eq(SessionNote.applyLocal(ui9, { + source_id = "dedupe", stable_id = "book9.epub", source = losing, + }), 0, "没解释的丢条仍被拦住") + Assert.eq(#current_annotations, 5, "旧快照原样保留") +end + +-- 删除事件判据(spec §9.1):index_modified < 0 取 changed[1] 作被删条目传给源; +-- 划线转笔记 / 只删备注时 nb_highlights_added 也是负的,但 index_modified 非负 → 不是删除。 +do + local JSON = require("json") + local seen = {} + local deleting = { + id = "deleting", + cleanAnnotations = function(_, items) return items end, + prepareLocalAnnotations = function(_, previous, current, deleted) + seen[#seen + 1] = { previous = previous, current = current, deleted = deleted } + return current + end, + } + local key = "deleting:book7.epub:0" + local item = { datetime = "2026-10-03", page = "/body/p[1].0", pos0 = "/body/p[1].0", + pos1 = "/body/p[1].5", drawer = "lighten", text = "划的线", note = "备注" } + local current_annotations = {} + local ui7 = { + document = { file = "/b5.epub", getPageCount = function() return 10 end }, + doc_settings = { + flush = function() end, + readSetting = function(_, name) + if name == "annotations" then return current_annotations end + end, + saveSetting = function(_, name, value) + if name == "annotations" then current_annotations = value end + end, + }, + } + local identity7 = { source_id = "deleting", stable_id = "book7.epub", source = deleting } + local function seed() + rows[key] = { source_id = "deleting", stable_id = "book7.epub", chapter_idx = 0, + payload = JSON.encode({ item }), updated_at = 1, sync_status = 1 } + end + + -- 删除:阅读器数组里已经没有它了(annotation.annotations 是删除后的状态)。 + seed() + current_annotations = {} + SessionNote.save(ui7, identity7, { item, nb_highlights_added = -1, index_modified = -7 }) + Assert.eq(seen[#seen].deleted, item, "被删条目就是 changed[1]") + + -- 划线转笔记 / 只删备注:条目还在,index_modified 非负 → 不传 deleted。 + seed() + current_annotations = { item } + SessionNote.save(ui7, identity7, { item, nb_highlights_added = -1, index_modified = 0 }) + Assert.is_nil(seen[#seen].deleted) + Assert.eq(#seen, 2) + + -- 老调用方不传 changed:它是可选参数,不产生删除。 + seed() + current_annotations = { item } + SessionNote.save(ui7, identity7, nil) + Assert.is_nil(seen[#seen].deleted) + Assert.eq(#seen, 3) +end + + +-- 已膨胀的章节快照:applyLocal 去重后只留下有效条目;再 apply / pull 无新笔记时不再全量重写。 +do + local JSON = require("json") + local marker = { + datetime = "2026-11-03 14:54:54", + page = "/html/body/div[2]/p[431]/text()[1].37", + pageno = 45, + total_pages = 448, + } + local highlight = { + datetime = "2026-11-04 10:00:00", + page = "/html/body/div[2]/p[2]/text()[1].0", + pos0 = "/html/body/div[2]/p[2]/text()[1].0", + pos1 = "/html/body/div[2]/p[2]/text()[1].6", + drawer = "lighten", + text = "合法高亮", + } + local bloated = {} + for _i = 1, 4096 do bloated[#bloated + 1] = marker end + bloated[#bloated + 1] = highlight + + open_files["/b10.epub"] = { source_id = "bloat", stable_id = "book10.epub" } + rows["bloat:book10.epub:0"] = { + source_id = "bloat", stable_id = "book10.epub", chapter_idx = 0, + payload = JSON.encode(bloated), updated_at = 11, sync_status = 1, + } + + local current_annotations = bloated + local updates, writes = 0, 0 + local ui10 = { + document = { file = "/b10.epub", getPageCount = function() return 448 end }, + annotation = { + annotations = current_annotations, + updateAnnotations = function(self) + updates = updates + 1 + current_annotations = self.annotations + end, + }, + doc_settings = { + flush = function() end, + readSetting = function(_, name) + if name == "annotations" then return current_annotations end + end, + saveSetting = function(_, name, value) + if name == "annotations" then + writes = writes + 1 + current_annotations = value + end + end, + }, + } + local identity10 = { source_id = "bloat", stable_id = "book10.epub" } + Assert.eq(SessionNote.applyLocal(ui10, identity10), 2, + "apply 后应只剩 1 条位置记录 + 1 条高亮") + Assert.eq(#current_annotations, 2) + Assert.eq(current_annotations[2].text, "合法高亮", "合法高亮必须保留") + Assert.eq(writes, 1) + Assert.eq(updates, 1, "清理脏数据时需要写回并刷新绘制") + + Assert.eq(SessionNote.applyLocal(ui10, identity10), 2) + Assert.eq(writes, 1, "内容没变就不要再写 sidecar") + Assert.eq(updates, 1, "无新笔记时不要再全量 updateAnnotations") + + local pull_applies = 0 + identity10.source = { + id = "bloat", + syncNotesAsync = function(_, _opts, cb) + cb({ pulled = 1, pushed = 0 }) + end, + } + local real_apply = SessionNote.applyLocal + SessionNote.applyLocal = function(...) + pull_applies = pull_applies + 1 + return real_apply(...) + end + SessionNote.pull(ui10, identity10) + Stubs.flush() + SessionNote.applyLocal = real_apply + Assert.eq(pull_applies, 0, "pull 后快照修订号没变就不要再 apply") + Assert.eq(updates, 1) + Assert.eq(#current_annotations, 2) +end + + +do -- 微信同文异位的离线笔记不能在开书时丢失,也不能落库成少一条的快照。 + local JSON = require("json") + local Notes = require("moonsource_weread.notes") + local current = { + { datetime = "2026-11-12 10:00:00", page = "/p[1]", pos0 = "/p[1].0", pos1 = "/p[1].4", + drawer = "lighten", text = "重复原文", note = "想法一" }, + { datetime = "2026-11-12 10:01:00", page = "/p[8]", pos0 = "/p[8].0", pos1 = "/p[8].4", + drawer = "lighten", text = "重复原文", note = "想法二" }, + } + local wechat = { + id = "ext.weread", + cleanAnnotations = function(_self, items, total) return Notes.cleanAnnotations(items, total) end, + mergeAnnotations = function(_self, remote, live, paging, authoritative) + return Notes.mergeAnnotations(remote, live, paging, authoritative) + end, + } + local ref = { source_id = "ext.weread", stable_id = "offline-notes", source = wechat } + open_files["/offline-notes.epub"] = ref + rows["ext.weread:offline-notes:0"] = { payload = JSON.encode({}), updated_at = 1, sync_status = 0 } + local flushed = 0 + local reader = { + document = { file = "/offline-notes.epub", getPageCount = function() return 10 end }, + doc_settings = { + readSetting = function(_self, key) if key == "annotations" then return current end end, + saveSetting = function(_self, key, value) if key == "annotations" then current = value end end, + flush = function() flushed = flushed + 1 end, + }, + } + Assert.eq(SessionNote.applyLocal(reader, ref), 2) + Assert.len(current, 2) + Assert.eq(current[2].note, "想法二") + Assert.eq(flushed, 0, "不能把误判为重复的丢线结果刷新到 sidecar") + SessionNote.save(reader, ref) + local stored = JSON.decode(rows["ext.weread:offline-notes:0"].payload) + Assert.len(stored, 2) + Assert.eq(stored[1].note, "想法一") + Assert.eq(stored[2].note, "想法二") +end + +_G.G_reader_settings = previous_settings diff --git a/tests/weread/core/stats_db_book_total_spec.lua b/tests/weread/core/stats_db_book_total_spec.lua new file mode 100644 index 0000000..a88a0a7 --- /dev/null +++ b/tests/weread/core/stats_db_book_total_spec.lua @@ -0,0 +1,158 @@ +--[[-- +book.stats_db:云端单书累计 / 单书按日 / 账户日桶与本地逐页记录的合并口径,真实 sqlite 执行。 + +规则:有云端值 = 云端 + 本地(未上传 或 拉取之后才读);否则只有本地。 + +@module tests.book.stats_db_book_total_spec +--]] + +local Assert = require("support.assert") +local Config = require("support.config") + +local sqlite_ok = pcall(require, "lua-ljsqlite3/init") +if not sqlite_ok then + Assert.skip("当前离线环境没有 ljsqlite3 Lua 模块") +end + +local db_path = Config.dir() .. "/stats_book_total_spec.sqlite3" +for _, suffix in ipairs({ "", "-wal", "-shm" }) do os.remove(db_path .. suffix) end +package.loaded["utils.paths"] = nil +package.preload["utils.paths"] = function() + return { + dbPath = function() return db_path end, + ensureSettings = function() end, + sanitizeSourceId = function(id) return id end, + } +end +package.loaded["utils.settings"] = nil +package.preload["utils.settings"] = function() + return { getSource = function() return {} end } +end +for _, name in ipairs({ "utils.db", "book.stats_db" }) do package.loaded[name] = nil end + +local Base = require("utils.db") +local StatsDB = require("book.stats_db") +local WStats = require("moonsource_weread.stats") +Assert.not_nil(Base.open()) + +local D0 = os.time({ year = 2026, month = 9, day = 26, hour = 0 }) +local D1 = D0 + 86400 +local T1 = D1 + 12 * 3600 +local YMD0, YMD1 = os.date("%Y-%m-%d", D0), os.date("%Y-%m-%d", D1) + +local function page(source_id, stable_id, start_time, duration, synced) + Assert.is_true(StatsDB.add({ + source_id = source_id, stable_id = stable_id, record_type = "page", + page = 7, start_time = start_time, duration = duration, total_pages = 100, + }, synced and StatsDB.SYNCED or StatsDB.PENDING)) +end + +--- 走真实入库路径:mapper → replaceSynced。 +local function pull(annual_days, books, fetched_at) + local result = WStats.fromWires("ext.weread", {}, + annual_days and { { baseTime = D0, dailyReadTimes = annual_days } } or {}, + nil, books, fetched_at) + Assert.not_nil(StatsDB.replaceSynced("ext.weread", result.replace, result.rows)) +end + +local function byYmd(rows) + local out = {} + for _, row in ipairs(rows) do out[row.ymd] = row.seconds end + return out +end + +-- 本地:D0 已上传 100(快照前)、D1 未上传 50、D1 快照后已上传 30 +page("ext.weread", "42", D0 + 3600, 100, true) +page("ext.weread", "42", D1 + 3600, 50, false) +page("ext.weread", "42", T1 + 3600, 30, true) + +-- 无云端:全本地 +Assert.eq(StatsDB.summaryByBook("ext.weread", "42").total_seconds, 180) +Assert.eq(byYmd(StatsDB.dailyByBook("ext.weread", "42", 30))[YMD0], 100) + +pull({ [tostring(D1)] = 195 }, { + { id = "42", reading_time = 2578, wire = { readDetail = { data = { + { readDate = D0, readTime = 440 }, { readDate = D1, readTime = 134 }, + } } } }, + { id = "phone_only", reading_time = 300, wire = { readDetail = { data = { + { readDate = D0, readTime = 300 }, + } } } }, +}, T1) + +-- 单书累计:快照 + 未上传 50 + 快照后 30;快照前已上传的 100 已含在快照里 +Assert.eq(StatsDB.summaryByBook("ext.weread", "42").total_seconds, 2578 + 50 + 30) +Assert.eq(StatsDB.summaryByBook("ext.weread", "42").pages, 3, "页数只数本地逐页记录") +Assert.eq(StatsDB.summaryByBook("ext.weread", "phone_only").total_seconds, 300) + +-- 单书按日:D0 以云端 440 为准(本地 100 已含),D1 = 134 + 50 + 30 +local daily = StatsDB.dailyByBook("ext.weread", "42", 30) +Assert.len(daily, 2) +Assert.eq(daily[1].ymd, YMD1, "最近在前") +Assert.eq(daily[1].seconds, 214) +Assert.eq(daily[2].seconds, 440) +Assert.len(StatsDB.dailyByBook("ext.weread", "42", 1), 1) +Assert.eq(byYmd(StatsDB.dailyByBook("ext.weread", "phone_only", 30))[YMD0], 300, + "只在其他设备读过的书也有按日时长") + +-- 洞察当日书单:只有云端的书页坐标为 0 +local found +for _, row in ipairs(StatsDB.dailyBooksBySource("ext.weread")) do + if row.stable_id == "phone_only" then found = row end +end +Assert.eq(found.ymd, YMD0) +Assert.eq(found.seconds, 300) +Assert.eq(found.max_total_pages, 0) + +-- 账单:书单与书数含其他设备读过的书 +local books = StatsDB.periodBooks("ext.weread", D0, D1 + 86400, 5) +Assert.len(books, 2) +Assert.eq(books[1].stable_id, "42") +Assert.eq(books[1].seconds, 440 + 214) +Assert.eq(books[2].stable_id, "phone_only") +local period = StatsDB.periodSummary("ext.weread", D0, D1 + 86400) +Assert.eq(period.book_count, 2) +Assert.eq(period.pages, 3) + +-- 账户日历:D1 云端 195 + 拉取后本地新读 80;D0 无云端日桶 → 本地 100 +local account = byYmd(StatsDB.dailyBySource("ext.weread")) +Assert.eq(account[YMD1], 195 + 50 + 30) +Assert.eq(account[YMD0], 100) +Assert.eq(period.total_seconds, 100 + 275) + +-- 再拉一次:整本替换不累加;快照时间后移,T1 后已上传的 30 已含在新快照里 +local T2 = D1 + 14 * 3600 +pull(nil, { { id = "42", reading_time = 2700, wire = { readDetail = { data = { + { readDate = D1, readTime = 500 }, +} } } } }, T2) +Assert.eq(StatsDB.summaryByBook("ext.weread", "42").total_seconds, 2700 + 50) +local again = byYmd(StatsDB.dailyByBook("ext.weread", "42", 30)) +Assert.eq(again[YMD1], 500 + 50) +Assert.eq(again[YMD0], 100, "旧云端日明细被整本替换掉,回落本地") +Assert.eq(StatsDB.summaryByBook("ext.weread", "phone_only").total_seconds, 300, "其他书不受影响") + +-- 按书精确替换:书 id 互为前缀也不误删 +pull(nil, { { id = "4", reading_time = 60, wire = {} } }, T2) +Assert.eq(StatsDB.summaryByBook("ext.weread", "42").total_seconds, 2750) +Assert.eq(StatsDB.summaryByBook("ext.weread", "4").total_seconds, 60) + +-- 云端累计清零:旧快照与明细一并清掉,回落本地 +pull(nil, { { id = "phone_only", reading_time = 0, wire = {} } }, T2) +Assert.eq(StatsDB.summaryByBook("ext.weread", "phone_only").total_seconds, 0) +Assert.len(StatsDB.dailyByBook("ext.weread", "phone_only", 30), 0) + +-- 旧版拉取的日桶没有 last_time:只补未上传的,已上传的不再加(宁可少算不双计) +Assert.is_true(StatsDB.add({ + source_id = "legacy", stable_id = "__wr:day:" .. D1, record_type = "day", + page = 0, start_time = D1, duration = 600, total_pages = 0, +}, StatsDB.SYNCED)) +page("legacy", "b", D1 + 3600, 40, true) +page("legacy", "b", D1 + 7200, 20, false) +Assert.eq(byYmd(StatsDB.dailyBySource("legacy"))[YMD1], 620) + +-- 账户级统计拉取的区间清理(只删 day/book/total)不碰单书明细 +pull({ [tostring(D1)] = 195 }, nil, T2) +Assert.eq(StatsDB.summaryByBook("ext.weread", "42").total_seconds, 2750) +Assert.eq(byYmd(StatsDB.dailyByBook("ext.weread", "42", 30))[YMD1], 550) + +Base.close() +for _, suffix in ipairs({ "", "-wal", "-shm" }) do os.remove(db_path .. suffix) end diff --git a/tests/weread/core/stats_db_merge_spec.lua b/tests/weread/core/stats_db_merge_spec.lua new file mode 100644 index 0000000..97c7283 --- /dev/null +++ b/tests/weread/core/stats_db_merge_spec.lua @@ -0,0 +1,104 @@ +--[[-- +book.stats_db:merge_local_stats 打开时按天(与按时段)取云端与本地较大值,补上离线阅读;关闭时云端优先。真实 sqlite 执行。 + +@module tests.book.stats_db_merge_spec +--]] + +local Assert = require("support.assert") +local Config = require("support.config") + +local sqlite_ok = pcall(require, "lua-ljsqlite3/init") +if not sqlite_ok then + Assert.skip("当前离线环境没有 ljsqlite3 Lua 模块") +end + +local db_path = Config.dir() .. "/stats_merge_spec.sqlite3" +for _idx, suffix in ipairs({ "", "-wal", "-shm" }) do os.remove(db_path .. suffix) end +package.loaded["utils.paths"] = nil +package.preload["utils.paths"] = function() + return { + dbPath = function() return db_path end, + ensureSettings = function() end, + sanitizeSourceId = function(id) return id end, + } +end +local cfg = {} +package.loaded["utils.settings"] = nil +package.preload["utils.settings"] = function() + return { getSource = function() return cfg end } +end +for _idx, name in ipairs({ "utils.db", "book.stats_db", "moonsource_weread.stats" }) do package.loaded[name] = nil end + +local Base = require("utils.db") +local StatsDB = require("book.stats_db") +local WStats = require("moonsource_weread.stats") +Assert.not_nil(Base.open()) + +local DAY = os.time({ year = 2026, month = 10, day = 10, hour = 0 }) +local PREV = DAY - 86400 +local FETCHED = DAY + 22 * 3600 + +local function page(start_time, duration) + Assert.is_true(StatsDB.add({ source_id = "ext.weread", stable_id = "b1", record_type = "page", + page = 1, start_time = start_time, duration = duration, total_pages = 9, chapter_idx = 1 }, StatsDB.SYNCED)) +end + +-- 上午在线读 1:35 已被心跳报上;下午离线读 2 小时云端没有;前一天离线读 10 分钟;拉取后又读 100 秒。 +page(DAY + 9 * 3600, 5700) +page(DAY + 14 * 3600, 7200) +page(PREV + 10 * 3600, 600) +local result = WStats.fromWires("ext.weread", { totalReadTime = 5700 }, {}, + { { readTimes = { [tostring(DAY)] = 5700 } } }, {}, FETCHED) +Assert.not_nil(StatsDB.replaceSynced("ext.weread", result.replace, result.rows)) +page(FETCHED + 3600, 100) + +local function day(ymd) + for _idx, row in ipairs(StatsDB.dailyBySource("ext.weread")) do + if row.ymd == ymd then return row.seconds end + end +end + +-- 云端优先(默认):有日桶的日期 = 云端 + 拉取后新读;总时长 = 云端 total + 拉取后新读。 +Assert.eq(StatsDB.summaryBySource("ext.weread").total_seconds, 5700 + 100) +Assert.eq(day("2026-10-10"), 5700 + 100) +Assert.eq(day("2026-10-09"), 600, "没有云端日桶的日期本来就用本地") + +-- 合并:当天取较大值,离线的 2 小时和前一天的 10 分钟都补进总时长,在线那段不双计。 +cfg.merge_local_stats = true +Assert.eq(day("2026-10-10"), 5700 + 7200 + 100) +Assert.eq(day("2026-10-09"), 600) +Assert.eq(StatsDB.summaryBySource("ext.weread").total_seconds, 5700 + 7200 + 600 + 100) + +-- 云端比本地多(挂机不翻页心跳照报)时仍用云端,不往下压。 +cfg.merge_local_stats = true +Assert.is_true(Base.exec("UPDATE reading_stats SET duration=20000 WHERE record_type='day';") ~= nil) +Assert.eq(day("2026-10-10"), 20000 + 100) + +-- ── 时段(hour):与按天同一套合并口径 ────────────────────────────────────── +-- 云端 10-10 的 05 点 600s、22 点 400s;本机 05 点已上报 900s(不叠加)、07 点离线 300s +-- (云端没有这一格)、22 点拉取后新读 300s(补在云端格上)。 +local H = os.time({ year = 2026, month = 10, day = 10, hour = 0 }) +local function cloudHour(hour, duration) + Assert.is_true(StatsDB.add({ source_id = "ext.weread", stable_id = "__wx:hour:" .. (H + hour * 3600), + record_type = "hour", page = 0, start_time = H + hour * 3600, duration = duration, + total_pages = 0, last_time = FETCHED }, StatsDB.SYNCED)) +end +cloudHour(5, 600) +cloudHour(22, 400) +page(H + 5 * 3600 + 1800, 900) -- 快照里已含(已上报):不叠加 +page(H + 7 * 3600 + 1800, 300) -- 云端没有这一格(离线读) +page(FETCHED + 300, 300) -- 拉取之后才读的 22:05 + +cfg.merge_local_stats = false +local by_hour = StatsDB.hourlyBySource("ext.weread")["2026-10-10"] +Assert.eq(by_hour[6], 600, "05 点:云端 600,本机已上报的 900 不叠加") +Assert.eq(by_hour[8], 300, "07 点:没有云端格,用本机离线 300") +Assert.eq(by_hour[23], 700, "22 点:云端 400 + 拉取后新读 300") +cfg.merge_local_stats = true +by_hour = StatsDB.hourlyBySource("ext.weread")["2026-10-10"] +Assert.eq(by_hour[6], 900, "合并打开:05 点取本机 900") +Assert.eq(by_hour[8], 300, "合并打开:07 点仍是本机 300") +Assert.eq(by_hour[23], 700, "合并打开:22 点云端 + 增量比本机大,不往下压") + +Base.close() +for _idx, suffix in ipairs({ "", "-wal", "-shm" }) do os.remove(db_path .. suffix) end diff --git a/tests/weread/core/stats_db_total_spec.lua b/tests/weread/core/stats_db_total_spec.lua new file mode 100644 index 0000000..d4a5c1b --- /dev/null +++ b/tests/weread/core/stats_db_total_spec.lua @@ -0,0 +1,79 @@ +--[[-- +book.stats_db:微信权威累计 total 与拉取后本地新读时长合并,真实 sqlite 执行。 + +@module tests.book.stats_db_total_spec +--]] + +local Assert = require("support.assert") +local Config = require("support.config") + +local sqlite_ok = pcall(require, "lua-ljsqlite3/init") +if not sqlite_ok then + Assert.skip("当前离线环境没有 ljsqlite3 Lua 模块") +end + +local db_path = Config.dir() .. "/stats_total_spec.sqlite3" +for _, suffix in ipairs({ "", "-wal", "-shm" }) do os.remove(db_path .. suffix) end +package.loaded["utils.paths"] = nil +package.preload["utils.paths"] = function() + return { + dbPath = function() return db_path end, + ensureSettings = function() end, + sanitizeSourceId = function(id) return id end, + } +end +package.loaded["utils.settings"] = nil +package.preload["utils.settings"] = function() + return { getSource = function() return {} end } +end +for _, name in ipairs({ "utils.db", "book.stats_db", "moonsource_weread.stats" }) do package.loaded[name] = nil end + +local Base = require("utils.db") +local StatsDB = require("book.stats_db") +local WStats = require("moonsource_weread.stats") +Assert.not_nil(Base.open()) + +local FETCHED = os.time() - 3600 +local ID = "book-1" + +local function pull(total, fetched_at) + local result = WStats.fromWires("ext.weread", { totalReadTime = total }, {}, {}, {}, fetched_at) + Assert.not_nil(StatsDB.replaceSynced("ext.weread", result.replace, result.rows)) +end + +local function page(start_time, duration, synced) + Assert.is_true(StatsDB.add({ source_id = "ext.weread", stable_id = ID, record_type = "page", + page = 1, start_time = start_time, duration = duration, total_pages = 9, chapter_idx = 1 }, synced and StatsDB.SYNCED or StatsDB.PENDING)) +end + +-- 拉取前已上传的已含在快照里;拉取后读的(已上传或未上传)都要补上。 +page(FETCHED - 600, 50, true) +pull(7200, FETCHED) +Assert.eq(StatsDB.summaryBySource("ext.weread").total_seconds, 7200) +page(FETCHED + 60, 30, false) +page(FETCHED + 120, 40, true) +Assert.eq(StatsDB.summaryBySource("ext.weread").total_seconds, 7200 + 30 + 40, "总时长随本地新读增长") + +-- 先推后拉:新快照已含之前读的,替换旧 total、不累加。 +Assert.is_true(Base.exec("UPDATE reading_stats SET sync_status=1 WHERE record_type='page';") ~= nil) +pull(7300, FETCHED + 600) +Assert.eq(StatsDB.summaryBySource("ext.weread").total_seconds, 7300) + +-- 旧版拉取没记拉取时间:只补未上传的,宁可少算也不双计。 +Assert.is_true(Base.exec("UPDATE reading_stats SET last_time=0 WHERE record_type='total';") ~= nil) +page(FETCHED + 900, 20, false) +Assert.eq(StatsDB.summaryBySource("ext.weread").total_seconds, 7300 + 20) + +-- 清除列表:源含合成桶;书只留真实 stable_id,已删/未上架没有标题。 +local sources = StatsDB.distinctSources() +Assert.eq(sources[1], "ext.weread") +local recorded, seen = StatsDB.distinctBooks(), {} +for _idx, book in ipairs(recorded) do + Assert.is_true(book.stable_id:sub(1, 2) ~= "__", book.stable_id) + seen[book.stable_id] = book +end +Assert.eq(seen[ID].source_id, "ext.weread") +Assert.is_nil(seen[ID].title) + +Base.close() +for _, suffix in ipairs({ "", "-wal", "-shm" }) do os.remove(db_path .. suffix) end