commit 994167fbe55f10c5314a1afec13d02ba483460dd
Author: Garfield
]*>%s*
%s*
" .. Text.xmlEscape(line) .. "
") + end + return { + comment = JSON.encode({ ops = { { insert = text .. "\n" } } }), + commentHtml = table.concat(lines), + } +end + +--- 幂等键(spec §8.2):`html
", "plain"), "html") +Assert.eq(Annotation.noteText('{"ops":[{"insert":"delta\\n"}]}', "", "plain"), "plain") +Assert.eq(Annotation.noteText('{"ops":[{"insert":"delta\\n"}]}', " ", " "), "delta") + +-- commentHtml:块级边界转换行(后端 StripHtml 不插分隔,块之间会粘)。 +Assert.eq(Annotation.noteText(nil, "第一段
第二段
", ""), "第一段\n第二段") +Assert.eq(Annotation.noteText(nil, "a
b
a
b
", ""), "a\n\nb", "Quill 空行") +Assert.eq(Annotation.noteText(nil, "a & b <c> "d"
", ""), 'a & b。 +local one = Annotation.toRemote("第一行\n第二行") +local ops = JsonStub.decode(one.comment).ops +Assert.eq(#ops, 1, "只有一个 insert op") +Assert.eq(ops[1].insert, "第一行\n第二行\n") +Assert.eq(one.commentHtml, "
第一行
第二行
", "空行写a
b
") + +-- 写入:转义 & < > ";先转 & 再转别的,避免二次转义。 +Assert.eq( + Annotation.toRemote('a & b < c > d "e"').commentHtml, + "a & b < c > d "e"
" +) + +-- 写入:CRLF 归一、尾部换行去掉(否则每轮读回都多一行 → 判改过)。 +local crlf = Annotation.toRemote("a\r\nb\n\n") +Assert.eq(JsonStub.decode(crlf.comment).ops[1].insert, "a\nb\n") +Assert.eq(crlf.commentHtml, "a
b
") + +-- 往返:自己写的备注读回后与归一后的 note 一致(push / pull 同一口径 → 零 update)。 +for _idx, note in ipairs({ + "一句话", + "第一行\n第二行", + "a\n\nb", + '引号 " 与反斜杠 \\ 都原样', + "小于 < 大于 > 和 & 号", + "好书📚 与 emoji 👍🏽", + " 行首缩进保留", +}) do + local remote = Annotation.toRemote(note) + Assert.eq(Annotation.noteText(remote.comment), note, "Delta 读回:" .. note) + Assert.eq( + Annotation.noteText(remote.comment, remote.commentHtml, ""), + note, + "完整 DTO 读回(commentHtml 优先):" .. note + ) +end + +-- 比较归一:trim + 内部连续空白压一个 + 零宽剔除;两边都空判等。 +Assert.is_true(Annotation.sameNote(nil, "")) +Assert.is_true(Annotation.sameNote("", " ")) +Assert.is_true(Annotation.sameNote("a b", " a b ")) +Assert.is_true(Annotation.sameNote("a\nb", "a b"), "换行也是空白") +Assert.is_true(Annotation.sameNote("a\226\128\139b", "ab"), "零宽空格剔除") +Assert.is_true(Annotation.sameNote("a\239\187\191b", "ab"), "BOM 剔除") +Assert.is_false(Annotation.sameNote("a", "b")) +Assert.is_false(Annotation.sameNote("", "a")) + +-- 幂等键:comment 不参与、selectedText 空白归一、xPath 精确。 +local base = { chapterId = 7, xPath = "//body/p[1]", endingXPath = "//body/p[2]", selectedText = "选中 文本" } +local function keyOf(over) + local ann = {} + for k, v in pairs(base) do ann[k] = v end + for k, v in pairs(over or {}) do ann[k] = v end + return Annotation.key(ann) +end +Assert.eq(keyOf({ comment = "甲" }), keyOf({ comment = "乙" }), "改备注不是新建") +Assert.eq(keyOf({ selectedText = " 选中\n文本 " }), keyOf({}), "选中文本的空白差异命中") +Assert.is_true(keyOf({ xPath = "//body/p[9]" }) ~= keyOf({})) +Assert.is_true(keyOf({ endingXPath = "//body/p[9]" }) ~= keyOf({})) +Assert.is_true(keyOf({ chapterId = 8 }) ~= keyOf({})) +Assert.eq(keyOf({}), "7" .. string.char(31) .. "//body/p[1]" .. string.char(31) .. "//body/p[2]" .. string.char(31) .. "选中 文本") +-- 分隔符对外导出:源侧拼「同坐标」判定键用的是同一个字符,不各写一份字面量。 +Assert.eq(Annotation.KEY_SEP, string.char(31)) +-- pull 落库后的本地条目把选中文本叫 text。 +Assert.eq( + Annotation.key({ chapterId = 7, xPath = "//body/p[1]", endingXPath = "//body/p[2]", text = "选中 文本" }), + keyOf({}) +) +-- payload 形状(pull 落库后 / 阅读器快照里的条目)没有 DTO 字段名:xPath / endingXPath / selectedText +-- 的回退是 kavita_xpath / kavita_ending_xpath / text。源侧「远端同键去重」直接拿它当键。 +Assert.eq( + Annotation.key({ chapterId = 7, kavita_xpath = "//body/p[1]", kavita_ending_xpath = "//body/p[2]", + text = "选中 文本" }), + keyOf({}), + "payload 字段与 DTO 字段算出同一个键" +) +Assert.eq( + Annotation.key({ kavita_xpath = "//body/p[1]", kavita_ending_xpath = "//body/p[2]", text = "选中 文本" }), + Annotation.key({ xPath = "//body/p[1]", endingXPath = "//body/p[2]", selectedText = "选中 文本" }) +) +Assert.eq( + Annotation.key({ chapterId = 7, xPath = "//body/p[1]", kavita_xpath = "//body/p[9]", endingXPath = "//body/p[2]", + text = "选中 文本" }), + keyOf({}), + "DTO 字段优先,回退只在缺失时生效" +) + +-- 对账命中:同键多条取 id 最小;无命中 nil。 +local remote = { + { id = 9, chapterId = 7, xPath = "//body/p[1]", endingXPath = "//body/p[2]", selectedText = "选中 文本", comment = "{}" }, + { id = 3, chapterId = 7, xPath = "//body/p[1]", endingXPath = "//body/p[2]", selectedText = " 选中\n文本 ", comment = "{ops}" }, + { id = 1, chapterId = 7, xPath = "//body/p[5]", endingXPath = "//body/p[6]", selectedText = "别的划线" }, +} +Assert.eq(Annotation.match(remote, base).id, 3, "同键两条取 id 最小") +Assert.eq(Annotation.match({ { id = "12", chapterId = 7, xPath = "//body/p[1]", endingXPath = "//body/p[2]", selectedText = "选中 文本" } }, base).id, "12", "字符串 id 也能比") +Assert.is_nil(Annotation.match(remote, { chapterId = 7, xPath = "//body/p[7]", endingXPath = "//body/p[8]", selectedText = "x" })) +Assert.is_nil(Annotation.match(nil, base)) + +-- 列表:`GET /api/Annotation/all?chapterId=`,无分页;owner_id 非空才按 ownerUserId 过滤 +-- (owner_id 为空是 `/api/Users/me` 不可用时的降级:不过滤,宁可多看到自己的)。 +local chapter = { + { id = 1, ownerUserId = 5, comment = "{}" }, + { id = 2, ownerUserId = 9, comment = "别人的纯文本备注" }, + { id = 3, ownerUserId = 5, comment = "" }, +} +local calls = {} +local function clientReturning(data, err) + return { + json = function(_self, method, path, query, body, cb) + calls[#calls + 1] = { method = method, path = path, query = query, body = body } + cb(data, err) + return { cancel = function() end } + end, + } +end + +local got, got_err +Annotation.listByChapter(clientReturning(chapter), 12763, nil, function(list, err) got, got_err = list, err end) +Assert.eq(calls[1].method, "GET") +Assert.eq(calls[1].path, "/api/Annotation/all") +Assert.eq(calls[1].query.chapterId, 12763) +Assert.is_nil(calls[1].query.pageNumber, "该接口没有分页") +Assert.is_nil(calls[1].body) +Assert.eq(#got, 3, "owner_id 为空时不过滤") +Assert.is_nil(got_err) + +calls = {} +Annotation.listByChapter(clientReturning(chapter), 12763, 5, function(list) got = list end) +Assert.eq(#got, 2, "只留自己的注解") +Assert.eq(got[1].id, 1) +Assert.eq(got[2].id, 3) + +calls = {} +Annotation.listByChapter(clientReturning(chapter), 12763, "5", function(list) got = list end) +Assert.eq(#got, 2, "字符串 owner_id 也能对上数字 ownerUserId") + +Annotation.listByChapter(clientReturning(nil, "请求失败 (HTTP 400)"), 12763, 5, function(list, err) + got, got_err = list, err +end) +Assert.is_nil(got, "失败回 nil") +Assert.eq(got_err, "请求失败 (HTTP 400)") + +Annotation.listByChapter(clientReturning({}), 12763, 5, function(list) got = list end) +Assert.eq(#got, 0, "该章没有注解 = 空列表,不是 nil") diff --git a/tests/kavita/cache_spec.lua b/tests/kavita/cache_spec.lua new file mode 100644 index 0000000..4c35427 --- /dev/null +++ b/tests/kavita/cache_spec.lua @@ -0,0 +1,859 @@ +--[[-- +book.koplugin/source/kavita/cache.lua:kamare 缓存适配层。 + +kamare 的 `kamarecache` 是唯一的缓存执行者。这里只做探测、能力门面、配置镜像、 +错误文案、书架投影与删除保护,所有 kamare 模块都在函数内 pcall require、不持有 table。 + +@module tests.moonsource_kavita.cache_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, inject-field + +local Assert = require("support.assert") +local Config = require("support.config") + +local PLUGIN = (debug.getinfo(1, "S").source:match("^@(.-)/tests/") .. "/moonsource-kavita.koplugin/moonsource_kavita") + +-- 源配置:每个用例自己改;cache 只读 base_url / api_key。 +local cfg = {} +package.preload["utils.settings"] = function() + return { + getSource = function() return cfg end, + saveSource = function() end, + } +end + +-- 日志:记录每一行,供「一次性 / 不刷屏」断言。 +local logs = {} +package.preload["utils.log"] = function() + local function push(level, ...) + local parts = {} + for index = 1, select("#", ...) do + parts[#parts + 1] = tostring(select(index, ...)) + end + logs[#logs + 1] = { level = level, text = table.concat(parts, " ") } + end + return { + dbg = function(...) push("dbg", ...) end, + info = function(...) push("info", ...) end, + warn = function(...) push("warn", ...) end, + error = function(...) push("error", ...) end, + } +end + +package.preload["moonsource_kavita.cache"] = function() + return dofile(PLUGIN .. "/cache.lua") +end +local Cache = require("moonsource_kavita.cache") + +--- 清空 kamare 模块,模拟未安装。 +local function uninstall() + package.loaded["kamarecache"] = nil + package.preload["kamarecache"] = nil + package.loaded["kamareimageviewer"] = nil + package.preload["kamareimageviewer"] = nil + package.loaded["kamareversion"] = nil + package.preload["kamareversion"] = nil +end + +--- 装一个 kamarecache 桩;status 用 loadstring 造出可预测的模块路径。 +---@param spec table { api_version, capabilities, version, path, viewer } +---@return table +local function installCache(spec) + package.loaded["kamareimageviewer"] = spec.viewer + local mod = { + api_version = spec.api_version, + capabilities = spec.capabilities or {}, + } + if spec.path then + mod.status = assert(loadstring("return function() end", "@" .. spec.path))() + end + package.loaded["kamarecache"] = mod + if spec.version then + package.loaded["kamareversion"] = spec.version + end + Cache.reset() + return mod +end + +local function resetLogs() + logs = {} +end + +local function logText() + local parts = {} + for _idx, line in ipairs(logs) do parts[#parts + 1] = line.text end + return table.concat(parts, "\n") +end + +--- 含某段文字的行数(一次性 / 不刷屏断言用)。 +---@param fragment string +---@return integer +local function countLines(fragment) + local count = 0 + for _idx, line in ipairs(logs) do + if line.text:find(fragment, 1, true) then count = count + 1 end + end + return count +end + +---------------------------------------------------------------------- +-- 探测:四安装态、版本、加载路径;成功记忆、失败不记忆。 +---------------------------------------------------------------------- +uninstall() +Cache.reset() +local probe = Cache.probe() +Assert.is_false(probe.ok, "没有 kamarecache 不可用") +Assert.eq(probe.state, "missing", "未安装 / 已安装但被禁用") +Assert.eq(probe.reason, "missing") +Assert.eq(Cache.available("open"), false, "未安装时没有任何缓存能力") + +uninstall() +package.loaded["kamareimageviewer"] = { new = function() end } +Cache.reset() +probe = Cache.probe() +Assert.is_false(probe.ok, "官方版没有缓存接口") +Assert.eq(probe.state, "official", "有查看器但无 kamarecache") + +installCache({ api_version = 2, capabilities = { status = true, open = true } }) +probe = Cache.probe() +Assert.is_false(probe.ok, "主版本不符整体禁用") +Assert.eq(probe.state, "incompatible") +Assert.eq(probe.api_version, 2) +Assert.eq(probe.reason, "major_mismatch") +Assert.eq(Cache.available("status"), false, "主版本不符整体禁用缓存") +Assert.eq(Cache.available("open"), false, "没有查看器可退回时 open 也不可用") + +local fake_path = "/fake/plugins/kamare.koplugin/src/kamarecache.lua" +installCache({ + api_version = 1, + capabilities = { status = true, open = true }, + version = "0.10.0-dev", + path = fake_path, +}) +probe = Cache.probe() +Assert.is_true(probe.ok) +Assert.eq(probe.state, "enhanced") +Assert.eq(probe.api_version, 1) +Assert.eq(probe.version, "0.10.0-dev", "kamareversion 返回字符串") +Assert.eq(probe.path, fake_path, "加载路径取自 debug.getinfo(module.status)") + +-- data 目录里的插件路径是 `plugins//x.koplugin`(KOReader 的 extra_plugin_paths 带尾斜杠): +-- 展示前归一,否则用户会以为路径坏了。 +installCache({ + api_version = 1, + capabilities = { status = true, open = true }, + version = "0.10.0-dev", + path = "/fake/plugins//kamare.koplugin/kamarecache.lua", +}) +Assert.eq(Cache.probe().path, "/fake/plugins/kamare.koplugin/kamarecache.lua", "重复斜杠归一") +Assert.eq(probe.capabilities.status, true) +Assert.eq(Cache.available("status"), true) +Assert.eq(Cache.available("index"), false, "能力逐项判断") + +-- 成功结果进程内记忆:模块从 package 里消失后仍按上次结果 +package.loaded["kamarecache"] = nil +Assert.eq(Cache.probe().state, "enhanced", "成功结果记住,不重复 require") +Assert.eq(Cache.reprobe().state, "missing", "「重新检测」清掉成功记忆") +Cache.reset() +Assert.eq(Cache.probe().state, "missing", "reset 后重新探测") + +-- 失败不记忆:装上模块后立刻能看到增强版 +Assert.eq(Cache.probe().state, "missing") +installCache({ api_version = 1, capabilities = {} }) +Assert.eq(Cache.probe().state, "enhanced", "失败结果不缓存") + +-- kamareversion 用表形状也认(老写法) +package.loaded["kamareversion"] = { version = "0.9.9" } +Cache.reset() +Assert.eq(Cache.probe().version, "0.9.9") + +---------------------------------------------------------------------- +-- 功能清单:kamarefeatures.lua 原样展示;缺文件 / 版本不符 / 结构不合法都不显示。 +---------------------------------------------------------------------- +local function withManifest(value) + package.loaded["kamarefeatures"] = value + Cache.reset() + return Cache.featureText() +end + +uninstall() +installCache({ api_version = 1, capabilities = { open = true }, path = fake_path }) +Assert.eq(withManifest({ api_version = 1, features = { "缓存", "双页", "裁切" } }), + "缓存 · 双页 · 裁切", "按清单顺序拼接") +Assert.eq(withManifest({ api_version = 1, features = { "缓存", "缓存", "", 42, "裁切" } }), + "缓存 · 裁切", "去重并忽略空串 / 非字符串") +Assert.is_nil(withManifest({ api_version = 2, features = { "缓存" } }), "api_version 不符") +Assert.is_nil(withManifest({ api_version = 1, features = {} }), "空清单") +Assert.is_nil(withManifest({ api_version = 1, features = "缓存" }), "不是数组") +Assert.is_nil(withManifest({ api_version = 1 }), "没有 features") +Assert.is_nil(withManifest("not a table"), "不是表") +package.loaded["kamarefeatures"] = nil +Cache.reset() +Assert.is_nil(Cache.featureText(), "没有清单不显示") + +-- 最多 8 项 +local many = {} +for i = 1, 10 do many[i] = "功能" .. i end +local text = withManifest({ api_version = 1, features = many }) +Assert.not_nil(text:find("功能8", 1, true), "保留前 8 项") +Assert.is_nil(text:find("功能9", 1, true), "超出 8 项截断") + +-- 未安装 kamare 时,即使有清单也不显示。 +package.loaded["kamarefeatures"] = { api_version = 1, features = { "缓存" } } +uninstall() +Cache.reset() +Assert.is_nil(Cache.featureText(), "非增强版不显示") + +---------------------------------------------------------------------- +-- 门面:每个能力一个显式包装,参数只从配置补 base_url;缺能力则 unsupported。 +---------------------------------------------------------------------- +cfg = { base_url = "http://kav/", api_key = " k " } + +local calls = {} +local function record(name, impl) + return function(...) + calls[#calls + 1] = { name = name, args = { ... } } + if impl then return impl(...) end + return true + end +end + +local function lastCall(name) + for index = #calls, 1, -1 do + if calls[index].name == name then return calls[index] end + end +end + +local index_result = { used = 1, available = 2, series = { ["60"] = { seriesId = 60 } } } +local mod = installCache({ + api_version = 1, + capabilities = { + status = true, summary = true, resume = true, queue = true, + index = true, enqueue = true, delete = true, estimate = true, + queue_control = true, + }, +}) +mod.index = record("index", function() return index_result end) +mod.status = record("status", function() return { state = "complete" } end) +mod.resume_page = record("resume_page", function() return { page = 7 } end) +mod.summary = record("summary", function() return { used = 10, available = 20, chapters = 3 } end) +mod.queue_state = record("queue_state", function() return { state = "idle" } end) +mod.enqueue = record("enqueue", function() return true, nil, { chapters = 1 } end) +mod.delete = record("delete", function() return true, nil, 1 end) +mod.estimate = record("estimate", function() return { ok = true, chapters = 1, bytes = 1, available = 2 } end) + +Assert.eq(Cache.index(), index_result) +Assert.eq(lastCall("index").args[1], "http://kav", "base_url 去尾斜杠;不传 api_key") + +Assert.eq(Cache.status(6001).state, "complete") +Assert.eq(lastCall("status").args[1], "http://kav") +Assert.eq(lastCall("status").args[2], 6001) + +Assert.eq(Cache.resumePage(6001, 60).page, 7) +Assert.eq(lastCall("resume_page").args[1], "http://kav") +Assert.eq(lastCall("resume_page").args[2], 6001) +Assert.eq(lastCall("resume_page").args[3], 60) + +Assert.eq(Cache.summary().chapters, 3) +Assert.eq(lastCall("summary").args[1], "http://kav") + +Assert.eq(Cache.queueState().state, "idle") +Assert.eq(lastCall("queue_state").args[1], "http://kav") + +local ok, code, info = Cache.enqueue({ { chapterId = 6001 } }) +Assert.is_true(ok) +Assert.is_nil(code) +Assert.eq(info.chapters, 1, "成功时第三个返回值原样透出") +Assert.eq(lastCall("enqueue").args[1], "http://kav") +Assert.eq(lastCall("enqueue").args[2][1].chapterId, 6001) + +local deleted_ok, deleted_code, deleted = Cache.delete({ 6001 }) +Assert.is_true(deleted_ok) +Assert.is_nil(deleted_code) +Assert.eq(deleted, 1) +Assert.eq(lastCall("delete").args[1], "http://kav") +Assert.eq(lastCall("delete").args[2][1], 6001) + +Assert.is_true(Cache.estimate({ { chapterId = 6001 } }).ok) +Assert.eq(lastCall("estimate").args[1], "http://kav") +Assert.eq(lastCall("estimate").args[2][1].chapterId, 6001) + +-- 队列控制:三个显式包装,全部作用在全局队列上。 +mod.queue_pause = record("queue_pause") +mod.queue_resume = record("queue_resume") +mod.queue_retry = record("queue_retry") +Assert.is_true(Cache.queuePause()) +Assert.is_true(Cache.queueResume()) +Assert.is_true(Cache.queueRetry({ 6001, 6002 })) +Assert.eq(lastCall("queue_pause").args[1], "http://kav") +Assert.eq(lastCall("queue_resume").args[1], "http://kav") +Assert.eq(lastCall("queue_retry").args[1], "http://kav") +Assert.eq(lastCall("queue_retry").args[2][2], 6002) + +-- 缺能力:对应功能单独降级,kamare 的函数不会被调用。 +calls = {} +installCache({ api_version = 1, capabilities = { status = true } }) +local value, code = Cache.status(1) +Assert.eq(code, "unsupported", "能力声明了但没有函数也按缺失处理") +value, code = Cache.index() +Assert.is_nil(value, "缺 index 返回 nil") +Assert.eq(code, "unsupported") +value, code = Cache.summary() +Assert.is_nil(value) +Assert.eq(code, "unsupported") +Assert.eq(select(2, Cache.queueState()), "unsupported") +Assert.eq(select(2, Cache.queueState()), "unsupported") +Assert.eq(select(2, Cache.queuePause()), "unsupported") +Assert.eq(select(2, Cache.enqueue({ { chapterId = 1 } })), "unsupported") +Assert.eq(select(2, Cache.delete({ 1 })), "unsupported") +Assert.eq(select(2, Cache.estimate({ { chapterId = 1 } })), "unsupported") + +-- 未配置服务器:静默 unknown_server,不碰 kamare。 +cfg = { base_url = "", api_key = "" } +calls = {} +Assert.eq(select(2, Cache.index()), "unknown_server") +Assert.eq(select(2, Cache.enqueue({ { chapterId = 1 } })), "unknown_server") +Assert.len(calls, 0, "未配置时不发任何调用") + +-- kamare 的错误码原样透出,文案交给 message 表。 +cfg = { base_url = "http://kav/", api_key = "k" } +installCache({ + api_version = 1, + capabilities = { index = true, enqueue = true }, +}) +mod = package.loaded["kamarecache"] +mod.index = function() return nil, "unknown_server" end +mod.enqueue = function() return nil, "not_enough_space", "空间不足", { needed = 3, available = 1 } end +local read, read_code = Cache.index() +Assert.is_nil(read) +Assert.eq(read_code, "unknown_server") +local written, write_code, write_message, write_detail = Cache.enqueue({ { chapterId = 1 } }) +Assert.is_nil(written) +Assert.eq(write_code, "not_enough_space") +Assert.eq(write_message, "空间不足") +Assert.eq(write_detail.available, 1) + +---------------------------------------------------------------------- +-- 配置镜像:首次缓存操作前 + 每次写操作前;只传 base_url + api_key,不传 name。 +---------------------------------------------------------------------- +cfg = { base_url = "http://kav/", api_key = " k " } +calls = {} +resetLogs() +local mirror_mod = installCache({ + api_version = 1, + capabilities = { server = true, index = true, status = true, enqueue = true, + delete = true, queue_control = true, estimate = true }, +}) +mirror_mod.register_server = record("register_server", function() return "srv-1" end) +mirror_mod.index = record("index", function() return { series = {} } end) +mirror_mod.status = record("status") +mirror_mod.enqueue = record("enqueue", function() return true end) +mirror_mod.delete = record("delete", function() return true, nil, 1 end) +mirror_mod.queue_pause = record("queue_pause") +mirror_mod.queue_resume = record("queue_resume") +mirror_mod.queue_retry = record("queue_retry") +mirror_mod.estimate = record("estimate", function() return { ok = true } end) + +local function callCount(name) + local n = 0 + for _idx, call in ipairs(calls) do + if call.name == name then n = n + 1 end + end + return n +end + +--- 某次调用在 calls 里的位置(从 1 起;没有为 0) +local function callIndex(name) + for index, call in ipairs(calls) do + if call.name == name then return index end + end + return 0 +end + +Cache.index() +Assert.eq(callCount("register_server"), 1, "首次缓存操作前镜像一次") +local registered = lastCall("register_server").args[1] +Assert.eq(registered.base_url, "http://kav", "URL 规范化:去尾斜杠") +Assert.eq(registered.api_key, "k", "API Key 去空白") +Assert.is_nil(registered.name, "不传固定显示名(否则两台服务器会共用一个缓存目录)") + +Cache.status(1) +Assert.eq(callCount("register_server"), 1, "读操作不重复镜像") + +Cache.enqueue({ { chapterId = 1 } }) +Assert.eq(callCount("register_server"), 2, "每次写操作前幂等兜底") +Assert.is_true(callIndex("register_server") < callIndex("enqueue"), "镜像先于写入") + +Cache.delete({ 1 }) +Cache.queuePause() +Cache.queueResume() +Cache.queueRetry({ 1 }) +Cache.estimate({ { chapterId = 1 } }) +Assert.eq(callCount("register_server"), 6, "delete / queue_* / 估计写盘前路径都镜像") + +-- 显式调用:设置页保存后走这一个入口。 +local server_key, mirror_code = Cache.registerServer("http://kav/", " k ") +Assert.eq(server_key, "srv-1") +Assert.is_nil(mirror_code) +Assert.eq(callCount("register_server"), 7) + +-- 失败:后台只记一次日志,功能照常交给 kamare(按 unknown_server 静默降级)。 +mirror_mod.register_server = record("register_server", function() return nil, "settings_write_failed" end) +local before = callCount("register_server") +Cache.enqueue({ { chapterId = 2 } }) +Assert.eq(callCount("register_server"), before + 1) +Assert.eq(callCount("enqueue"), 2, "镜像失败不阻断写操作,最终以 kamare 为准") +Assert.is_true(Cache.mirrorFailed(), "本次会话镜像失败") +Assert.matches(logText(), "settings_write_failed", "失败记一行") +local mirror_lines = 0 +for _idx, line in ipairs(logs) do + if line.text:find("mirror", 1, true) then mirror_lines = mirror_lines + 1 end +end +Assert.eq(mirror_lines, 1, "同一原因只记一次") +Cache.enqueue({ { chapterId = 3 } }) +mirror_lines = 0 +for _idx, line in ipairs(logs) do + if line.text:find("mirror", 1, true) then mirror_lines = mirror_lines + 1 end +end +Assert.eq(mirror_lines, 1, "重复失败不刷屏") + +mirror_mod.register_server = record("register_server", function() return "srv-1" end) +Cache.enqueue({ { chapterId = 4 } }) +Assert.is_false(Cache.mirrorFailed(), "成功后清除失败态") + +-- 未配置 / 未安装时不假装镜像。 +cfg = { base_url = "", api_key = "" } +calls = {} +Cache.index() +Assert.len(calls, 0, "未配置不发镜像") + +cfg = { base_url = "http://kav/", api_key = "k" } +uninstall() +Cache.reset() +calls = {} +Cache.available("index") +Assert.len(calls, 0, "未安装不发镜像") + +---------------------------------------------------------------------- +-- 文案:02 A9 的 code 表 + 07 A7 的 lastError 特征。 +---------------------------------------------------------------------- +local CODE_CASES = { + { "offline_not_cached", "这一卷还没缓存,联网后可下载" }, + { "viewer_running", "漫画阅读器已在运行" }, + { "no_pages", "这一卷没有可显示的页面" }, + { "settings_write_failed", "无法写入 kamare 配置" }, + { "retry_no_entry", "没有可重试的任务" }, + { "chapter_open", "正在阅读这一卷,关闭后可以删除" }, +} +for _idx, case in ipairs(CODE_CASES) do + Assert.eq(Cache.message(case[1]), case[2], "code → 文案: " .. case[1]) +end +-- 静默:已是目标状态 / 未知服务器都当无缓存,不打扰用户。 +Assert.is_nil(Cache.message("unknown_server"), "unknown_server 静默") +Assert.is_nil(Cache.message("already_cached"), "已缓存静默") +Assert.is_nil(Cache.message("already_queued"), "已排队静默") +Assert.is_nil(Cache.message(nil), "没有 code 没有说话") +-- 未知 code:kamare 的 message 优先,再退通用文案。 +Assert.eq(Cache.message("weird_code", "kamare 的原话"), "kamare 的原话") +Assert.eq(Cache.message("weird_code"), "缓存操作失败") + +local MB = 1024 * 1024 +Assert.eq(Cache.sizeText(3 * MB), "3.0 MB") +Assert.eq(Cache.message("not_enough_space", nil, { needed = 3 * MB, available = MB }), + "空间不足:需要 3.0 MB,可用 1.0 MB") +Assert.eq(Cache.message("cache_limit_reached", nil, { needed = 2 * MB, limit = 9 * MB }), + "缓存空间已满:需要 2.0 MB,上限 9.0 MB") +Assert.eq(Cache.message("low_space", nil, { available = MB, low_water = 500 * MB }), + "可用空间低于 500.0 MB,清理后再下载") + +-- estimate 的三种裁决:确认框就地换文案,不复制 kamare 的 2.05 / 500MB 常量。 +Assert.eq(Cache.estimateMessage({ reason = "nothing_to_do" }), "全部已缓存或正在下载") +Assert.eq(Cache.estimateMessage({ reason = "space", bytes = 3 * MB, available = MB }), + "空间不足:需要 3.0 MB,可用 1.0 MB") +Assert.eq(Cache.estimateMessage({ reason = "low_water", available = MB }), + "可用空间不足(剩余 1.0 MB),清理后再下载") +Assert.is_nil(Cache.estimateMessage({ ok = true, reason = nil }), "可下载时没有额外文案") +Assert.is_nil(Cache.estimateMessage(nil)) + +-- 失败原因(07 A7):按 kamare 的 lastError 特征归并成可读文案。 +local FAILED = { + { "http 403 while fetching page 3", "服务器拒绝下载(403),检查 API Key / 权限" }, + { "not an archive: text/html", "下载内容不完整或不是有效压缩包" }, + { "size 120/900", "下载内容不完整或不是有效压缩包" }, + { "extracted 3 of 5 pages", "下载内容不完整或不是有效压缩包" }, + { "sink write failed: no space left on device", "存储空间不足或写入失败" }, + { "socket closed", "网络中断或服务器不可达" }, + { "connect timeout", "网络中断或服务器不可达" }, + { "connection truncated", "网络中断或服务器不可达" }, +} +for _idx, case in ipairs(FAILED) do + Assert.eq(Cache.failureText(case[1]), case[2], "lastError → 文案: " .. case[1]) +end +Assert.eq(Cache.failureText("weird failure"), "缓存失败:weird failure", "未知错误前缀保留原话") +Assert.is_nil(Cache.failureText(nil)) + +---------------------------------------------------------------------- +-- 打开:enhanced 有 open 走 kamare;官方 / 缺 open 退回 legacy;记录当前打开的章。 +---------------------------------------------------------------------- +cfg = { base_url = "http://kav/", api_key = "k" } +calls = {} +local opened = installCache({ + api_version = 1, + capabilities = { open = true, delete = true, server = true }, +}) +opened.register_server = record("register_server", function() return "srv-1" end) +local closed = {} +local nexts = {} +local fake_viewer = { kind = "viewer" } +opened.open = record("open", function() return fake_viewer end) +Assert.is_true(Cache.enhancedOpen(), "增强版有 open:由 kamare 决定起始页 / 离线") +local open_result, open_code = Cache.open({ + base_url = "http://kav/", api_key = "k", + entry = { chapterId = 6001, pages = 20 }, title = "漫画", + on_close = function(page, total) closed[#closed + 1] = { page, total } end, + on_next = function(id) nexts[#nexts + 1] = id end, +}) +Assert.eq(open_result, fake_viewer) +Assert.is_nil(open_code) +local open_opts = lastCall("open").args[1] +Assert.eq(open_opts.entry.chapterId, 6001, "目录条目原样交给 kamare") +Assert.eq(open_opts.title, "漫画") +Assert.not_nil(open_opts.on_next) +Assert.is_true(Cache.isChapterOpen(6001), "打开成功记下当前章") +Assert.is_false(Cache.isChapterOpen(6002)) + +open_opts.on_close(7, 20) +Assert.eq(closed[1][1], 7, "关闭回调原样透出") +Assert.eq(closed[1][2], 20) +Assert.is_false(Cache.isChapterOpen(6001), "关闭后清除当前章") + +-- 打开失败不留 active。 +opened.open = function() return nil, "viewer_running", "漫画阅读器已在运行" end +local failed, failed_code, failed_message = Cache.open({ + base_url = "http://kav/", api_key = "k", entry = { chapterId = 6003, pages = 4 }, +}) +Assert.is_nil(failed) +Assert.eq(failed_code, "viewer_running") +Assert.eq(failed_message, "漫画阅读器已在运行") +Assert.is_false(Cache.isChapterOpen(6003)) + +-- 删除保护:本地先拦,kamare 的 delete 根本不会被调用。 +calls = {} +local deleted_viewer = installCache({ + api_version = 1, + capabilities = { open = true, delete = true }, +}) +deleted_viewer.open = record("open", function() return { kind = "viewer" } end) +deleted_viewer.delete = record("delete", function() return true, nil, 1 end) +Cache.open({ base_url = "http://kav/", api_key = "k", entry = { chapterId = 6001, pages = 20 } }) +local del_ok, del_code = Cache.delete({ 6001 }) +Assert.is_nil(del_ok) +Assert.eq(del_code, "chapter_open", "正在读的章拒绝删除") +Assert.eq(Cache.message(del_code), "正在阅读这一卷,关闭后可以删除") +Assert.eq(callCount("delete"), 0, "kamare 的 delete 不被调用") + +Assert.is_true(Cache.delete({ 6002 }), "别的章照删") +Assert.eq(lastCall("delete").args[2][1], 6002) + +-- 关掉查看器后可以删。 +lastCall("open").args[1].on_close(1, 20) +Assert.is_true(Cache.delete({ 6001 })) + +-- 官方版 / enhanced 缺 open:退回 legacy 通道(今天的在线看图能力不能丢)。 +uninstall() +package.loaded["kamareimageviewer"] = { new = function(_self, spec) return spec end } +local streamed = {} +package.loaded["kavitaclient"] = { + streamChapter = function(_self, id) streamed[#streamed + 1] = id; return { { pageNumber = 1 } } end, +} +local shown = {} +package.loaded["ui/uimanager"] = { show = function(_, widget) shown[#shown + 1] = widget end } +Cache.reset() +Assert.is_true(Cache.available("open"), "官方版仍能在线看图") +Assert.is_false(Cache.enhancedOpen(), "官方版不接管 open:起始页由 moon 补") +local legacy_viewer, legacy_code = Cache.open({ + base_url = "http://kav/", api_key = "k", entry = { chapterId = 6001, pages = 20 }, title = "漫画", + start_page = 3, on_close = function() end, on_next = function() end, +}) +Assert.is_nil(legacy_code) +Assert.eq(legacy_viewer.metadata.chapterId, 6001) +Assert.eq(legacy_viewer.metadata.startPage, 3) +Assert.eq(legacy_viewer.images_list_nb, 20) +Assert.eq(legacy_viewer.title, "漫画") +Assert.eq(require("kavitaclient").api_key, "k") +Assert.eq(require("kavitaclient").device_id, "moon-kavita") +Assert.eq(streamed[1], 6001) +Assert.eq(shown[1], legacy_viewer, "交给 UIManager 显示") +Assert.is_true(Cache.isChapterOpen(6001), "legacy 也记当前章") + +-- enhanced 但缺 open 能力:同样退回 legacy。 +installCache({ api_version = 1, capabilities = { status = true } }) +Assert.is_false(Cache.enhancedOpen(), "增强版缺 open:退回 legacy,由 moon 给起始页") +package.loaded["kamareimageviewer"] = { new = function(_self, spec) return spec end } +package.loaded["kavitaclient"] = { streamChapter = function() return { { pageNumber = 1 } } end } +Cache.reset() +local fallback = Cache.open({ + base_url = "http://kav/", api_key = "k", entry = { chapterId = 6004, pages = 4 }, +}) +Assert.not_nil(fallback, "增强版缺 open 时退回查看器") +Assert.eq(fallback.metadata.chapterId, 6004) + +-- legacy 没有页面 / 查看器已被占用 / 串流失败:稳定 code。 +Cache.reset() +local no_pages, no_pages_code = Cache.open({ + base_url = "http://kav/", api_key = "k", entry = { chapterId = 6005, pages = 0 }, +}) +Assert.is_nil(no_pages) +Assert.eq(no_pages_code, "no_pages") + +package.loaded["kamareimageviewer"] = { new = function(_self, spec) spec._aborted = true; return spec end } +local running, running_code = Cache.open({ + base_url = "http://kav/", api_key = "k", entry = { chapterId = 6006, pages = 3 }, +}) +Assert.is_nil(running) +Assert.eq(running_code, "viewer_running") + +package.loaded["kamareimageviewer"] = { new = function(_self, spec) return spec end } +package.loaded["kavitaclient"] = { streamChapter = function() return nil end } +local broken, broken_code, broken_message = Cache.open({ + base_url = "http://kav/", api_key = "k", entry = { chapterId = 6007, pages = 3 }, +}) +Assert.is_nil(broken) +Assert.eq(broken_code, "open_failed") +Assert.eq(broken_message, "打开漫画阅读器失败") + +-- 完全没有 kamare:不能假装能打开。 +uninstall() +Cache.reset() +Assert.is_false(Cache.available("open")) +local none, none_code = Cache.open({ base_url = "http://kav/", api_key = "k", entry = { chapterId = 1, pages = 1 } }) +Assert.is_nil(none) +Assert.eq(none_code, "unsupported") + +---------------------------------------------------------------------- +-- 书架投影:complete / stale 才算已缓存;三张表按服务器记忆,无 TTL。 +---------------------------------------------------------------------- +cfg = { base_url = "http://kav/", api_key = "k" } +local work = Config.dir() .. "/cache_spec" +os.execute("mkdir -p '" .. work .. "'") +local cover = work .. "/cover-60.jpg" +local cover_file = assert(io.open(cover, "wb")) +cover_file:write("jpeg") +cover_file:close() + +calls = {} +local shelf_mod = installCache({ + api_version = 1, + capabilities = { index = true, server = true, enqueue = true, delete = true, queue_control = true }, +}) +shelf_mod.register_server = record("register_server", function() return "srv" end) +local shelf_index = { + series = { + ["60"] = { seriesId = 60, chapters = 2, complete = true, coverPath = cover }, + ["61"] = { seriesId = 61, chapters = 0, complete = true, coverPath = work .. "/missing.jpg" }, + ["62"] = { seriesId = 62, chapters = 1, stale = true }, + ["63"] = { seriesId = 63, chapters = 1 }, + ["64"] = { seriesId = 64, chapters = 3, stale = true, complete = false }, + }, +} +shelf_mod.index = record("index", function() return shelf_index end) +shelf_mod.enqueue = record("enqueue", function() return true end) +shelf_mod.delete = record("delete", function() return true, nil, 1 end) +shelf_mod.queue_pause = record("queue_pause", function() return true end) + +local shelf = Cache.shelf() +Assert.is_true(shelf.series_ids["60"], "complete 算已缓存") +Assert.is_true(shelf.mark["60"]) +Assert.is_true(shelf.series_ids["62"], "stale 与 complete 等价") +Assert.is_true(shelf.series_ids["64"]) +Assert.is_nil(shelf.series_ids["61"], "没有章不算(chapters = 0)") +Assert.is_nil(shelf.series_ids["63"], "queued / downloading 不算") +Assert.eq(shelf.cover["60"], cover, "封面路径存在才给") +Assert.is_nil(shelf.cover["61"], "文件不存在不给") +Assert.eq(callCount("index"), 1) + +Cache.shelf() +Assert.eq(callCount("index"), 1, "进程内记忆,无 TTL、翻页不重拉") + +-- 三类失效:写操作成功、手动刷新、Registry.reload(源实例重建时调 resetShelf)。 +Cache.enqueue({ { chapterId = 6001 } }) +Cache.shelf() +Assert.eq(callCount("index"), 2, "enqueue 成功后失效") +Cache.delete({ 6001 }) +Cache.shelf() +Assert.eq(callCount("index"), 3, "delete 成功后失效") +Cache.queuePause() +Cache.shelf() +Assert.eq(callCount("index"), 4, "queue_* 成功后失效") +Cache.resetShelf() +Cache.shelf() +Assert.eq(callCount("index"), 5, "手动刷新 / Registry.reload") + +-- 写失败不能误伤投影(失败时缓存没变)。 +shelf_mod.enqueue = record("enqueue", function() return nil, "not_enough_space" end) +Cache.enqueue({ { chapterId = 6002 } }) +Cache.shelf() +Assert.eq(callCount("index"), 5, "失败的写操作不失效") + +-- 按服务器分开记忆:切回旧服务器不重拉。 +cfg.base_url = "http://other/" +Cache.shelf() +Assert.eq(callCount("index"), 6) +Assert.eq(lastCall("index").args[1], "http://other") +cfg.base_url = "http://kav/" +Cache.shelf() +Assert.eq(callCount("index"), 6, "旧服务器的投影还在") + +-- unknown_server 不记忆:下次进书架再试(可能刚镜像完)。 +shelf_mod.index = record("index", function() return nil, "unknown_server" end) +cfg.base_url = "http://third/" +Assert.is_nil(Cache.shelf()) +Assert.is_nil(Cache.shelf()) +Assert.eq(callCount("index"), 8, "无缓存不写空投影") + +-- 缺 index 能力:整块降级为无标记。 +installCache({ api_version = 1, capabilities = { status = true } }) +Assert.is_nil(Cache.shelf(), "缺 index 无书架标记") + +-- 「已缓存」口径只在一处:章状态与 index 摘要两种形状都认(03 A3)。 +Assert.is_true(Cache.isCached({ state = "complete" })) +Assert.is_true(Cache.isCached({ state = "stale" })) +Assert.is_false(Cache.isCached({ state = "partial" })) +Assert.is_false(Cache.isCached(nil)) +Assert.is_true(Cache.isCached({ chapters = 1, complete = true })) +Assert.is_false(Cache.isCached({ chapters = 1 })) + +-- 能力名单排序与拼接:设置页与日志共用同一份(08)。 +Assert.eq(Cache.capabilityNames({ open = true, index = true }), "index,open") +Assert.eq(Cache.capabilityNames({ open = true, index = true }, "、"), "index、open") +Assert.eq(Cache.capabilityNames(nil), "none") + +---------------------------------------------------------------------- +-- 日志:探测每进程一次、写操作一行、open 失败去重、暂停原因只在变化时记。 +---------------------------------------------------------------------- +cfg = { base_url = "http://kav/", api_key = "secret-key" } +uninstall() +resetLogs() +Cache.reset() +Cache.probe() +Cache.probe() +Assert.eq(countLines("kamare probe"), 1, "探测结果每进程只记一次") +Assert.matches(logText(), "kamare probe ok=false state=missing") +Assert.is_nil(logText():find("secret-key", 1, true), "日志里绝不出现 API Key") + +installCache({ + api_version = 1, + capabilities = { status = true, index = true, enqueue = true, delete = true, + queue = true, queue_control = true, open = true }, + version = "0.10.0", + path = "/fake/plugins/kamare.koplugin/kamarecache.lua", +}) +resetLogs() +Cache.probe() +Cache.probe() +Assert.eq(countLines("kamare probe ok=true"), 1) +Assert.matches(logText(), "state=enhanced") +Assert.matches(logText(), "version=0.10.0") +Assert.matches(logText(), "caps=.*index") +Assert.is_nil(logText():find("secret-key", 1, true)) + +local log_mod = package.loaded["kamarecache"] +log_mod.status = function() return { state = "complete" } end +log_mod.index = function() return { series = {} } end +log_mod.enqueue = function() return nil, "not_enough_space", "空间不足", { needed = 9, available = 1 } end +resetLogs() +Cache.enqueue({ { chapterId = 6001 }, { chapterId = 6002 } }) +Cache.enqueue({ { chapterId = 6003 } }) +Assert.eq(countLines("cache enqueue cid=6001,6002 code=not_enough_space"), 1, "每次写操作一行,带 code 与章 id") +Assert.eq(countLines("cache enqueue cid=6003 code=not_enough_space"), 1, "另一次失败另记一行") + +log_mod.delete = function() return true, nil, 1 end +resetLogs() +Cache.delete({ 6004 }) +Assert.eq(countLines("cache delete cid=6004 code=ok"), 1) + +log_mod.queue_pause = function() return true end +resetLogs() +Cache.queuePause() +Assert.eq(countLines("cache queue_pause cid=- code=ok"), 1, "队列动作没有章 id,记 -") + +-- 轮询路径不刷日志,只在暂停原因变化时记一行。 +log_mod.queue_state = function() return { state = "paused", pause_reason = "offline" } end +resetLogs() +Cache.queueState() +Cache.queueState() +Assert.eq(countLines("queue paused reason=offline"), 1, "1 秒轮询不重复记") +log_mod.queue_state = function() return { state = "idle" } end +Cache.queueState() +log_mod.queue_state = function() return { state = "paused", pause_reason = "offline" } end +Cache.queueState() +Assert.eq(countLines("queue paused reason=offline"), 2, "恢复后再次暂停要再记") +log_mod.queue_state = function() return { state = "paused", pause_reason = "network" } end +Cache.queueState() +Assert.eq(countLines("queue paused reason=network"), 1) + +-- 读操作不写日志。 +resetLogs() +Cache.status(6001) +Cache.index() +Assert.len(logs, 0, "读路径零日志") + +-- open 失败同一原因只记一次。 +log_mod.open = function() return nil, "viewer_running" end +resetLogs() +Cache.open({ base_url = "http://kav/", api_key = "k", entry = { chapterId = 6001, pages = 4 } }) +Cache.open({ base_url = "http://kav/", api_key = "k", entry = { chapterId = 6001, pages = 4 } }) +Assert.eq(countLines("cache open cid=6001 code=viewer_running"), 1, "open 失败去重") + +-- chapters / delete_all / plan / summaryAll:清理门面 +cfg.base_url, cfg.api_key = "http://kav", "k" +local cleanup_calls = {} +local cleanup_mod = installCache({ + api_version = 1, + capabilities = { status = true, summary = true, chapters = true, delete = true, + delete_all = true, server = true }, + version = "0.10.0", +}) +function cleanup_mod.chapters(base_url, series_id) + cleanup_calls.chapters = { base_url, series_id } + return { { chapterId = 1, pages = 10, bytes = 100, read = true } } +end +function cleanup_mod.delete_all() + cleanup_calls.delete_all = (cleanup_calls.delete_all or 0) + 1 + return true, nil, { chapters = 3, bytes = 300 } +end +function cleanup_mod.summary(base_url) + cleanup_calls.summary = (cleanup_calls.summary or 0) + 1 + cleanup_calls.summary_base = base_url + return { used = 300, available = 1000, chapters = 3 } +end +function cleanup_mod.register_server() return "srv" end +Cache.reset() + +local plan_rows = Cache.chapters(42) +Assert.eq(cleanup_calls.chapters[1], "http://kav", "chapters 用当前服务器") +Assert.eq(cleanup_calls.chapters[2], 42, "chapters 透传 series_id") +Assert.len(plan_rows, 1, "chapters 返回数组") + +local ok, _code, _message, detail = Cache.deleteAll() +Assert.is_true(ok, "deleteAll 成功") +Assert.eq(detail and detail.chapters, 3, "deleteAll 透传估算") +Assert.eq(cleanup_calls.delete_all, 1, "deleteAll 调 kamare 一次") + +Assert.eq(Cache.summaryAll().chapters, 3, "summaryAll 返回合计") +Assert.eq(cleanup_calls.summary_base, nil, "summaryAll 不传 base_url") + +local plan = Cache.plan(plan_rows, "read", nil) +Assert.eq(plan.chapters, 1, "read 过滤保留已读") +Assert.eq(plan.bytes, 100, "字节合计") +Assert.eq(plan.ids[1], 1, "ids 供批量删除") +local not_read = Cache.plan({ { chapterId = 2, pages = 10, bytes = 50, read = false } }, "read", nil) +Assert.eq(not_read.chapters, 0, "未读不入选") +local via_toc = Cache.plan({ { chapterId = 3, pages = 10, bytes = 50, read = false } }, "read", + { ["3"] = 10 }) +Assert.eq(via_toc.chapters, 1, "toc 的 pagesRead 补第三源") +local queued = Cache.plan({ { chapterId = 4, pages = 10, bytes = 1, read = true, queued = true } }, "all", nil) +Assert.eq(queued.queued, 1, "排队数进计划") + + +return true diff --git a/tests/kavita/cache_task_spec.lua b/tests/kavita/cache_task_spec.lua new file mode 100644 index 0000000..27da0a5 --- /dev/null +++ b/tests/kavita/cache_task_spec.lua @@ -0,0 +1,256 @@ +--[[-- +漫画缓存的后台任务:登记 passive 任务、按本批卷轮询、暂停时放行自动休眠、收尾只提示一次。 + +kamare 仍是执行者,这里只观察 queue_state / status;队列全局共享,所以进度只数本批的卷。 + +@module tests.moonsource_kavita.cache_task_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, inject-field, redundant-parameter + +local Assert = require("support.assert") +local Config = require("support.config") +local Kit = require("support.widget_stubs") +Kit.install("paper") + +local Themed = require("support.theme_stubs") +Themed.install() + +package.preload["ui/network/manager"] = function() + return { isConnected = function() return true end } +end +package.preload["ui.guard"] = function() + return { + call = function(_label, fn, ...) return fn(...) end, + wrap = function(_label, fn) return fn end, + } +end +package.preload["utils.log"] = function() + return { info = function() end, warn = function() end, err = function() end, dbg = function() end } +end + +local PLUGIN = (debug.getinfo(1, "S").source:match("^@(.-)/tests/") .. "/moonsource-kavita.koplugin/moonsource_kavita") + +-- 缓存适配层:只提供 cache_task 用到的读接口;写操作不经过这里。 +local st = { queue = { state = "idle", entries = {} }, statuses = {}, queue_ok = true } +package.preload["moonsource_kavita.cache"] = function() + return { + available = function(cap) return st.queue_ok and cap == "queue" end, + queueState = function() return st.queue end, + status = function(id) return st.statuses[tostring(id)] end, + isCached = function(status) + return type(status) == "table" and (status.state == "complete" or status.state == "stale") + end, + } +end + +local Tasks = require("workers.tasks") +local CacheTask = dofile(PLUGIN .. "/cache_task.lua") + +local series = { stable_id = "900", title = "测试系列" } +local entries = { + { chapterId = 1, title = "第 1 卷" }, + { chapterId = 2, title = "第 2 卷" }, + { chapterId = 3, title = "第 3 卷" }, +} + +--- 跑一条指定延迟的定时器:<1 是队列的变更拍,>=1 且 <60 是轮询拍(60 秒是防休眠的 InputEvent 补拍)。 +---@param match fun(delay: number): boolean +---@return boolean +local function runTimer(match) + for index, item in ipairs(Kit.scheduled) do + if match(item.delay) then + table.remove(Kit.scheduled, index) + item.fn() + return true + end + end + return false +end + +--- 结清队列的变更拍(pause_auto_suspend 之类)。 +local function changes() + while runTimer(function(delay) return delay < 1 end) do end +end + +--- 跑一拍轮询。 +local function tick() + Assert.is_true(runTimer(function(delay) return delay >= 1 and delay < 60 end), "排了下一拍轮询") +end + +local function reset() + for _idx, item in ipairs(Tasks.tasks()) do + local live = Tasks.get(item.key) + if live then live.cancel() end + end + changes() + st.queue = { state = "idle", entries = {} } + st.statuses = {} + st.queue_ok = true + Themed.made = {} + Kit.scheduled, Kit.unscheduled = {}, {} +end + +-- 缺 queue 能力:没有可轮询的队列,不登记(免得后台任务永远挂着)。 +do + reset() + st.queue_ok = false + Assert.is_nil(CacheTask.track{ series = series, entries = entries }) + Assert.len(Tasks.tasks(), 0) + st.queue_ok = true +end + +-- 登记:一条 passive 的 cache 任务,顶栏读到「执行中 1/1」;缓存期间不自动休眠。 +do + reset() + local handle = CacheTask.track{ series = series, entries = entries } + Assert.not_nil(handle) + local list = Tasks.tasks() + Assert.len(list, 1, "只登记一条") + Assert.eq(list[1].kind, "cache") + Assert.eq(list[1].title, "测试系列") + Assert.eq(list[1].state, "running", "passive 任务立刻启动,不排队") + changes() + Assert.is_true(require("pluginshare").pause_auto_suspend, "缓存期间压住自动休眠") +end + +-- 进度:只数本批的卷,当前卷名来自 queue.current_chapter_id。 +do + reset() + CacheTask.track{ series = series, entries = entries } + st.statuses["1"] = { state = "complete" } + st.queue = { state = "downloading", entries = { [2] = { state = "downloading" } }, + current_chapter_id = 2 } + tick() + local task = Tasks.tasks()[1] + Assert.eq(task.count, 1, "已落地 1 卷") + Assert.eq(task.total, 3, "总数是本批卷数") + Assert.eq(task.text, "第 2 卷", "说明行写当前卷") + + -- 不在本批的卷(别的系列)不计数。 + st.queue.entries[99] = { state = "downloading" } + tick() + Assert.eq(Tasks.tasks()[1].count, 1, "别的系列不算进度") +end + +-- 全部落地:任务结束、toast 一次、不再排下一拍。 +do + reset() + CacheTask.track{ series = series, entries = entries } + for index = 1, 3 do st.statuses[tostring(index)] = { state = "complete" } end + st.queue = { state = "idle", entries = {} } + local toasts = #Themed.all("toast") + tick() + Assert.len(Tasks.tasks(), 0, "结束后离开未结束列表") + local finished = Tasks.finished()[1] + Assert.is_true(finished.ok, "全成算成功") + Assert.eq(finished.total, 3) + Assert.eq(finished.count, 3, "收尾补报最终计数(不是上一拍的 2/3)") + Assert.is_nil(finished.text, "收尾后不再挂着上一卷的名字") + Assert.eq(#Themed.all("toast"), toasts + 1, "只 toast 一次") + Assert.eq(Themed.last("toast").text, "已缓存 3 卷") + Assert.is_false(runTimer(function(delay) return delay >= 1 end), "收尾后不再轮询") + changes() + Assert.is_false(require("pluginshare").pause_auto_suspend, "结束放行自动休眠") +end + +-- 部分失败:失败项是终态(kamare 留在队列里等重试),收尾报成功 / 失败数。 +do + reset() + CacheTask.track{ series = series, entries = entries } + st.statuses["1"] = { state = "complete" } + st.statuses["2"] = { state = "complete" } + st.queue = { state = "idle", entries = { [3] = { state = "failed", last_error = "http 403" } } } + tick() + local finished = Tasks.finished()[1] + Assert.is_false(finished.ok) + Assert.eq(finished.total, 3) + Assert.eq(finished.count, 2, "失败的那卷不算成功") + Assert.eq(Themed.last("toast").text, "2 卷成功,1 卷失败") +end + +-- 静音:页面自己的进度框负责提示时不出 toast。 +do + reset() + local handle = CacheTask.track{ series = series, entries = entries } + handle.mute(true) + for index = 1, 3 do st.statuses[tostring(index)] = { state = "complete" } end + st.queue = { state = "idle", entries = {} } + local toasts = #Themed.all("toast") + tick() + Assert.eq(#Themed.all("toast"), toasts, "静音时不提示") + Assert.is_true(Tasks.finished()[1].ok, "任务照常收尾") +end + +-- 暂停:说明行给暂停原因,放行自动休眠,轮询放慢到 5 秒;恢复后继续。 +do + reset() + CacheTask.track{ series = series, entries = entries } + st.statuses["1"] = { state = "complete" } + st.queue = { state = "paused", pause_reason = "low_space", + entries = { [2] = { state = "queued" } } } + changes() + tick() + local task = Tasks.tasks()[1] + Assert.eq(task.state, "running", "暂停只是报状态,不结束任务") + Assert.eq(task.text, "空间不足,已暂停") + changes() + Assert.is_false(require("pluginshare").pause_auto_suspend, "暂停时不再撑着不睡") + Assert.is_true(runTimer(function(delay) return delay == 5 end), "暂停时 5 秒一拍") + + -- 恢复:下一拍回到下载说明行,重新压住休眠。 + st.queue = { state = "downloading", entries = { [2] = { state = "downloading" } }, + current_chapter_id = 2 } + tick() + Assert.eq(Tasks.tasks()[1].text, "第 2 卷") + changes() + Assert.is_true(require("pluginshare").pause_auto_suspend, "恢复后继续撑住") +end + +-- 队列丢了(kamare 重启 / 队列被清):连续几拍看不到本批的项就按中断收尾。 +do + reset() + CacheTask.track{ series = series, entries = entries } + local toasts = #Themed.all("toast") + for _idx = 1, 4 do + tick() + Assert.len(Tasks.tasks(), 1, "还没到上限,继续等") + end + tick() + Assert.len(Tasks.tasks(), 0, "超时后收尾") + local finished = Tasks.finished()[1] + Assert.is_false(finished.ok) + Assert.eq(#Themed.all("toast"), toasts + 1) + Assert.eq(Themed.last("toast").text, "缓存已中断") +end + +-- 同一部再有卷入队 / 重试:并进同一条任务,失败项清掉终态重新观察。 +do + reset() + local first = CacheTask.track{ series = series, entries = { entries[1] } } + Assert.eq(Tasks.tasks()[1].total, 1) + st.queue = { state = "downloading", entries = { [1] = { state = "downloading" } } } + tick() + Assert.eq(Tasks.tasks()[1].total, 1) + + local merged = CacheTask.track{ series = series, entries = { entries[2], entries[3] } } + Assert.eq(merged, first, "同一部书复用同一条任务") + Assert.len(Tasks.tasks(), 1, "不新增任务") + Assert.eq(Tasks.tasks()[1].total, 3, "总数并进去") + + -- 失败项重试:终态清掉,重新计入进度。 + st.statuses["1"] = { state = "complete" } + st.queue = { state = "downloading", entries = { [2] = { state = "downloading" }, + [3] = { state = "failed" } } } + tick() + Assert.eq(Tasks.tasks()[1].count, 1, "失败项不算成功") + merged.add({ entries[3] }) + st.queue = { state = "downloading", entries = { [2] = { state = "downloading" }, + [3] = { state = "downloading" } } } + tick() + Assert.eq(Tasks.tasks()[1].count, 1, "重试的卷回到未完成") + st.statuses["2"] = { state = "complete" } + st.statuses["3"] = { state = "complete" } + st.queue = { state = "idle", entries = {} } + tick() + Assert.is_true(Tasks.finished()[1].ok, "重试成功后收尾") +end diff --git a/tests/kavita/client_spec.lua b/tests/kavita/client_spec.lua new file mode 100644 index 0000000..6f0083a --- /dev/null +++ b/tests/kavita/client_spec.lua @@ -0,0 +1,69 @@ +--[[-- +book.koplugin/source/kavita/client.lua:请求超时可配置, +统计分页的 URL 形态与 `Pagination` 头解析。 + +慢设备 / 慢服务器上全量书架(all-v2)一次要几十秒,固定的 30s 上限会让整轮同步中断、 +书架永远加载不出来;这里锁住「默认足够宽 + 可在设置里调大 + 透传到 HTTP 层」。 + +@module tests.moonsource_kavita.client_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, inject-field + +local Assert = require("support.assert") +local Config = require("support.config") +local JsonStub = require("support.json_stub") + +package.loaded["json"] = { encode = JsonStub.encode, decode = JsonStub.decode } + +local captured +package.loaded["http.request"] = { + ok = function(code) return tonumber(code) == 200 end, + request = function(opts, cb) + captured = opts + cb({ code = 200, body = "{}" }) + return { cancel = function() end } + end, +} +local PLUGIN = (debug.getinfo(1, "S").source:match("^@(.-)/tests/") .. "/moonsource-kavita.koplugin/moonsource_kavita") +package.preload["moonsource_kavita.client"] = function() + return dofile(PLUGIN .. "/client.lua") +end +local Client = require("moonsource_kavita.client") + +local function make(timeout) + return Client.new({ base_url = "http://kav/", api_key = "k", timeout = timeout }) +end + +Assert.eq(Client.DEFAULT_TIMEOUT, 60, "默认不再是 30s") +Assert.eq(Client.new({ base_url = "http://kav/", api_key = "k" }).timeout, 60, "未配置用默认超时") +Assert.eq(make("120").timeout, 120, "设置里的字符串数值也认") +Assert.eq(make(1).timeout, 5, "过小收敛到下限") +Assert.eq(make(0).timeout, 5, "0 收敛到下限") +Assert.eq(make(100000).timeout, 600, "过大收敛到上限") + +local client = make(180) +Assert.eq(client:configured(), true) +client:request("GET", "/api/Series/all-v2", { pageNumber = 1 }, nil, function() end) +Assert.eq(captured.timeout, 180, "超时透传到 HTTP 请求,长拉书架不再被 30s 掐断") +Assert.matches(captured.url, "^http://kav/api/Series/all%-v2%?") +Assert.eq(captured.headers["x-api-key"], "k") + +-- 统计拉取:`Libraries` 是重复键(逗号串会被服务端当成一个库,恒返回 0 条), +-- 其余参数按名排序,PageSize 用服务端接受的上限 200。 +Assert.eq( + client:url("/api/Stats/reading-history", { + TimeZoneId = "Asia/Shanghai", Libraries = { 2, 1 }, PageNumber = 1, PageSize = 200, + }), + "http://kav/api/Stats/reading-history?Libraries=2&Libraries=1&PageNumber=1&PageSize=200&TimeZoneId=Asia%2FShanghai" +) +Assert.eq(client:url("/api/Image/series-cover", { seriesId = "10" }), + "http://kav/api/Image/series-cover?seriesId=10", "单值参数与 formEncode 同形") + +-- 分页头(挂在响应上,不在 body 里):只认 totalPages。 +Assert.eq(Client.totalPages('{"currentPage":1,"itemsPerPage":200,"totalItems":316,"totalPages":2}'), 2) +Assert.eq(Client.totalPages('{"totalPages":0}'), 0, "0 页 = 没有数据,读成 nil 会让调用方按「本页拉满」再拉一页") +Assert.is_nil(Client.totalPages('{"currentPage":1}'), "没有 totalPages 就当不可信,调用方走兜底") +Assert.is_nil(Client.totalPages('{"totalPages":-1}'), "负数不可信") +Assert.is_nil(Client.totalPages(nil)) +Assert.is_nil(Client.totalPages("")) +Assert.is_nil(Client.totalPages("oops"), "反代错误页不能当分页头") diff --git a/tests/kavita/continue_point_spec.lua b/tests/kavita/continue_point_spec.lua new file mode 100644 index 0000000..83ee8f3 --- /dev/null +++ b/tests/kavita/continue_point_spec.lua @@ -0,0 +1,133 @@ +--[[-- +卷列表 / 系列页共用的续读目标:主线 = 最远有进度的卷,回顾旧卷只标「上次翻阅」。 + +@module tests.moonsource_kavita.continue_point_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, inject-field + +local Assert = require("support.assert") +local Config = require("support.config") + +local CP = dofile((debug.getinfo(1, "S").source:match("^@(.-)/tests/") .. "/moonsource-kavita.koplugin/moonsource_kavita") .. "/continue_point.lua") + +local function vol(chapter_id, title, pages, pages_read) + return { + idx = chapter_id, chapterId = chapter_id, title = title, + pages = pages, pagesRead = pages_read or 0, + } +end + +local toc = { + vol(101, "第 1 卷", 100, 100), + vol(102, "第 2 卷", 100, 40), + vol(103, "第 3 卷", 100, 0), + vol(104, "第 4 卷", 100, 0), +} + +-- 未开始 +local fresh = CP.pick({ + vol(101, "第 1 卷", 100, 0), + vol(102, "第 2 卷", 100, 0), +}, {}) +Assert.eq(fresh.kind, "fresh") +Assert.eq(fresh.entry.chapterId, 101) +Assert.eq(fresh.page, 0) +local fresh_text, fresh_caption = CP.describe(fresh, "系列") +Assert.eq(fresh_text, "开始阅读 · 第 1 卷") +Assert.eq(fresh_caption, "共 100 页") + +-- 读到第 2 卷一半:主线是第 2 卷 +local mid = CP.pick(toc, {}) +Assert.eq(mid.kind, "continue") +Assert.eq(mid.entry.chapterId, 102) +Assert.eq(mid.fraction, 0.4) +Assert.eq(mid.page, 40) +Assert.eq(mid.total_pages, 100) +local mid_text, mid_caption = CP.describe(mid, "系列") +Assert.eq(mid_text, "继续阅读 · 第 2 卷") +Assert.eq(mid_caption, "第 40/100 页 · 40%") +Assert.is_nil(mid.browsed) + +-- 第 2 卷读完:顺延第 3 卷 +local rolled = CP.pick({ + vol(101, "第 1 卷", 100, 100), + vol(102, "第 2 卷", 100, 100), + vol(103, "第 3 卷", 100, 0), +}, {}) +Assert.eq(rolled.entry.chapterId, 103) +Assert.eq(rolled.kind, "continue") +Assert.eq(rolled.page, 0) + +-- 全部读完:回到第 1 卷,kind = done +local done = CP.pick({ + vol(101, "第 1 卷", 100, 100), + vol(102, "第 2 卷", 100, 100), +}, {}) +Assert.eq(done.kind, "done") +Assert.eq(done.entry.chapterId, 101) + +-- 读到第 4 卷、回头翻第 1 卷:主线不动,第 1 卷只作「上次翻阅」 +local updated = { [101] = 300, [104] = 200 } +local review = CP.pick({ + vol(101, "第 1 卷", 100, 100), + vol(102, "第 2 卷", 100, 100), + vol(103, "第 3 卷", 100, 100), + vol(104, "第 4 卷", 100, 50), +}, { + updated_at = function(e) return updated[e.chapterId] end, +}) +Assert.eq(review.entry.chapterId, 104, "主线仍是最远的第 4 卷") +Assert.eq(review.browsed.chapterId, 101, "上次翻阅单独返回") + +-- 上次翻阅 == 主线:不返回标记 +local same = CP.pick(toc, { updated_at = function(e) return e.chapterId == 102 and 500 or 0 end }) +Assert.is_nil(same.browsed) + +-- 注入 fraction / page(本地 ProgressDB 比 toc 快照新) +local local_better = CP.pick(toc, { + fraction = function(e) return e.chapterId == 102 and 0.9 or nil end, + page = function(e) + if e.chapterId == 102 then return { page = 90, total = 100 } end + end, +}) +Assert.eq(local_better.fraction, 0.9) +Assert.eq(local_better.page, 90) + +-- pages == 0 的卷不参与 +local zero = CP.pick({ + vol(101, "第 1 卷", 0, 0), + vol(102, "第 2 卷", 100, 10), +}, {}) +Assert.eq(zero.entry.chapterId, 102) + +-- 空目录 +Assert.is_nil(CP.pick({}, {})) +Assert.is_nil(CP.pick(nil, nil)) + +-- 服务端已读完、本机重新打开留下 1%:仍按已读完处理,主线顺延下一卷。 +local reread = CP.pick({ + vol(101, "第 1 卷", 100, 100), + vol(102, "第 2 卷", 100, 100), + vol(103, "第 3 卷", 100, 0), +}, { fraction = function(e) return e.chapterId == 102 and 0.01 or nil end }) +Assert.eq(reread.entry.chapterId, 103, "已读完的卷不会被本机低进度拖回主线") +Assert.eq(reread.kind, "continue") + + +-- 调用方说已读完(kamare 三源)时同样按 fraction 1,不再被本机低进度拖回。 +local by_caller = CP.pick({ + vol(101, "第 1 卷", 100, 0), + vol(102, "第 2 卷", 100, 0), +}, { + fraction = function(e) return e.chapterId == 101 and 0.01 or nil end, + complete = function(e) return e.chapterId == 101 end, +}) +Assert.eq(by_caller.entry.chapterId, 102, "调用方标记已读完的卷不会成为主线") + + +-- 卷名:优先标题;空 / 退化成系列名时兜底第 N 卷 +Assert.eq(CP.label({ idx = 3, title = "ONE PIECE (3)" }, "航海王"), "ONE PIECE (3)") +Assert.eq(CP.label({ idx = 3, title = "" }, "航海王"), "第 3 卷") +Assert.eq(CP.label({ idx = 3, title = "航海王" }, "航海王"), "第 3 卷") +Assert.eq(CP.label({ idx = 3 }, "航海王"), "第 3 卷") +Assert.eq(CP.label(nil, "航海王"), "?") diff --git a/tests/kavita/fixtures/history_7453.lua b/tests/kavita/fixtures/history_7453.lua new file mode 100644 index 0000000..9949e8f --- /dev/null +++ b/tests/kavita/fixtures/history_7453.lua @@ -0,0 +1,140 @@ +--[[-- +样本 fixture:`GET /api/Stats/reading-history/series/7453` 实测响应(2026-10-16,Kavita 0.9.1.4) +的精简版,只留聚合用到的字段(seriesId / localDate / startTimeUtc / chapters[])。 + +对账基线(research-kavita-stats-pull.md §3):64 条会话 / 14,237s;逐日见 stats_spec 用例。 +来源完整响应:/tmp/opencode/kavita/live/history-7453-all.json(提交时精简,数值逐条未改)。 + +@module tests.extensions.kavita.fixtures.history_7453 +--]] +return { + { seriesId = 7453, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T13:49:02.6722926", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-15T13:49:02.6722926", durationSeconds = 845, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T11:51:10.7006183", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-15T11:51:10.7006183", durationSeconds = 638, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T11:14:33.5066159", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-15T11:14:33.5066159", durationSeconds = 436, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T08:01:09.6078347", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-15T08:01:09.6078347", durationSeconds = 33, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T07:20:02.0863122", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-15T07:20:02.0863122", durationSeconds = 156, pagesRead = 15 } } }, + { seriesId = 7453, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T04:38:27.7268649", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-15T04:38:27.7268649", durationSeconds = 462, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T03:25:22.1307379", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-15T03:25:22.1307379", durationSeconds = 266, pagesRead = 1 } } }, + { seriesId = 7453, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T02:59:07.9600274", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-15T02:59:07.9600274", durationSeconds = 126, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T14:50:29.2326588", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T14:50:29.2326588", durationSeconds = 329, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T13:55:48.5704762", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T13:55:48.5704762", durationSeconds = 716, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T12:59:54.4012612", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T12:59:54.4012612", durationSeconds = 210, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T12:32:09.2873459", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T12:32:09.2873459", durationSeconds = 354, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T10:50:12.8325335", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T10:50:12.8325335", durationSeconds = 427, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T09:55:45.2531997", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T09:55:45.2531997", durationSeconds = 229, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T08:18:25.5482677", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T08:18:25.5482677", durationSeconds = 631, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T06:35:44.8950968", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T06:56:37.9521487", durationSeconds = 597, pagesRead = 5 }, + { chapterId = 11273, startTimeUtc = "2026-10-14T06:35:44.8950968", durationSeconds = 529, pagesRead = -6 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T06:12:27.3026502", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T06:12:27.3026502", durationSeconds = 686, pagesRead = 1 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T05:35:38.8926445", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T05:35:38.8926445", durationSeconds = 674, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T03:36:59.7411875", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T03:36:59.7411875", durationSeconds = 1352, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T01:39:31.4453653", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T01:39:31.4453653", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T14:56:50.7578846", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-13T14:56:50.7578846", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T12:50:13.6195947", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-13T12:50:13.6195947", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T10:49:24.2700176", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-13T10:49:24.2700176", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T09:19:44.4142404", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-13T09:19:44.4142404", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T07:17:51.0855549", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-13T07:17:51.0855549", durationSeconds = 31, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T06:23:56.2429684", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-13T06:23:56.2429684", durationSeconds = 948, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T04:44:11.1456271", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-13T04:44:11.1456271", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T04:04:52.1419963", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-13T04:04:52.1419963", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-12T00:00:00", startTimeUtc = "2026-10-12T03:52:47.3926019", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-12T03:52:47.3926019", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-11T00:00:00", startTimeUtc = "2026-10-11T15:16:45.9848037", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-11T15:16:45.9848037", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-11T00:00:00", startTimeUtc = "2026-10-11T14:54:13.613368", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-11T14:54:13.613368", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-11T00:00:00", startTimeUtc = "2026-10-11T14:35:43.0809755", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-11T14:35:43.0809755", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-11T00:00:00", startTimeUtc = "2026-10-11T12:58:29.291105", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-11T12:58:29.291105", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-11T00:00:00", startTimeUtc = "2026-10-11T11:00:42.6215043", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-11T11:00:42.6215043", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-11T00:00:00", startTimeUtc = "2026-10-11T04:17:28.3592015", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-11T04:17:28.3592015", durationSeconds = 512, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-10T00:00:00", startTimeUtc = "2026-10-10T04:44:42.7023417", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-10T04:44:42.7023417", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-10T00:00:00", startTimeUtc = "2026-10-10T03:55:35.74839", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-10T03:55:35.74839", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-10T00:00:00", startTimeUtc = "2026-10-10T03:39:55.2030981", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-10T03:39:55.2030981", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T14:45:39.0731175", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-09T14:45:39.0731175", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T07:44:06.636679", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-09T07:44:06.636679", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T07:13:20.7857153", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-09T07:13:20.7857153", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T04:40:28.7189645", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-09T04:40:28.7189645", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T04:05:17.6951039", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-09T04:05:17.6951039", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T14:34:05.7981443", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T14:34:05.7981443", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T13:12:53.6969824", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T13:12:53.6969824", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T11:48:06.6315963", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T11:48:06.6315963", durationSeconds = 544, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T11:02:33.6484158", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T11:02:33.6484158", durationSeconds = 611, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T10:31:08.475182", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T10:31:08.475182", durationSeconds = 3, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T09:03:45.5309711", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T09:03:45.5309711", durationSeconds = 86, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T07:59:09.2881628", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T07:59:09.2881628", durationSeconds = 263, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T07:20:18.0105615", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T07:20:18.0105615", durationSeconds = 233, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T06:48:51.312417", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T06:48:51.312417", durationSeconds = 296, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T04:05:45.0300961", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T04:05:45.0300961", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-07T00:00:00", startTimeUtc = "2026-10-07T13:44:15.125016", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-07T13:44:15.125016", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-07T00:00:00", startTimeUtc = "2026-10-07T09:45:01.0814021", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-07T09:45:01.0814021", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-07T00:00:00", startTimeUtc = "2026-10-07T05:19:38.9892914", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-07T05:19:38.9892914", durationSeconds = 503, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-06T00:00:00", startTimeUtc = "2026-10-06T12:01:31.4949015", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-06T12:01:31.4949015", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-06T00:00:00", startTimeUtc = "2026-10-06T11:37:48.0185472", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-06T11:37:48.0185472", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-06T00:00:00", startTimeUtc = "2026-10-06T03:21:10.9150125", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-06T03:21:10.9150125", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-06T00:00:00", startTimeUtc = "2026-10-06T02:50:29.5547188", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-06T02:50:29.5547188", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-05T00:00:00", startTimeUtc = "2026-10-05T14:10:59.8916334", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-05T14:10:59.8916334", durationSeconds = 195, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-05T00:00:00", startTimeUtc = "2026-10-05T12:18:33.1689018", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-05T12:18:33.1689018", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T10:25:25.4088288", chapters = { + { chapterId = 11271, startTimeUtc = "2026-09-29T10:25:25.4088288", durationSeconds = 86, pagesRead = 2 } } }, + { seriesId = 7453, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T10:01:44.7835505", chapters = { + { chapterId = 11271, startTimeUtc = "2026-09-29T10:01:44.7835505", durationSeconds = 230, pagesRead = 0 } } }, +} diff --git a/tests/kavita/fixtures/history_all.lua b/tests/kavita/fixtures/history_all.lua new file mode 100644 index 0000000..dbfd97b --- /dev/null +++ b/tests/kavita/fixtures/history_all.lua @@ -0,0 +1,657 @@ +--[[-- +样本 fixture:`GET /api/Stats/reading-history` 全量实测响应(2026-10-16,Kavita 0.9.1.4)的 +精简版,只留聚合用到的字段(seriesId / localDate / startTimeUtc / chapters[]),共 316 条会话 / +60 个系列 / 2 页。 + +数值逐条未改;对账基线 = research-kavita-stats-pull.md §2(逐日时长 / 页数)与 §4(Σ=60,238s / +1,406 页 / 起点 2026-09-18)。来源完整响应:/tmp/opencode/kavita/live/history-all-sep-oct.json。 + +@module tests.extensions.kavita.fixtures.history_all +--]] +return { + { seriesId = 7606, localDate = "2026-10-16T00:00:00", startTimeUtc = "2026-10-15T23:51:47.4527045", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-15T23:51:47.4527045", durationSeconds = 220, pagesRead = 6 } } }, + { seriesId = 7453, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T13:49:02.6722926", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-15T13:49:02.6722926", durationSeconds = 845, pagesRead = 0 } } }, + { seriesId = 7606, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T13:41:03.9585123", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-15T13:41:03.9585123", durationSeconds = 469, pagesRead = 6 } } }, + { seriesId = 7606, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T12:18:53.1535569", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-15T12:18:53.1535569", durationSeconds = 163, pagesRead = 7 } } }, + { seriesId = 7453, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T11:51:10.7006183", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-15T11:51:10.7006183", durationSeconds = 638, pagesRead = 0 } } }, + { seriesId = 9249, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T11:40:49.4449693", chapters = { + { chapterId = 13493, startTimeUtc = "2026-10-15T11:40:49.4449693", durationSeconds = 335, pagesRead = 1 } } }, + { seriesId = 10634, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T11:35:04.1639136", chapters = { + { chapterId = 17863, startTimeUtc = "2026-10-15T11:38:58.0370869", durationSeconds = 81, pagesRead = 15 }, + { chapterId = 17868, startTimeUtc = "2026-10-15T11:35:04.1639136", durationSeconds = 210, pagesRead = 29 } } }, + { seriesId = 7453, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T11:14:33.5066159", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-15T11:14:33.5066159", durationSeconds = 436, pagesRead = 0 } } }, + { seriesId = 10634, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T11:04:40.7474367", chapters = { + { chapterId = 17868, startTimeUtc = "2026-10-15T11:04:40.7474367", durationSeconds = 321, pagesRead = 44 } } }, + { seriesId = 7453, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T08:01:09.6078347", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-15T08:01:09.6078347", durationSeconds = 33, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T07:20:02.0863122", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-15T07:20:02.0863122", durationSeconds = 156, pagesRead = 15 } } }, + { seriesId = 7453, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T04:38:27.7268649", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-15T04:38:27.7268649", durationSeconds = 462, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T03:25:22.1307379", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-15T03:25:22.1307379", durationSeconds = 266, pagesRead = 1 } } }, + { seriesId = 7453, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T02:59:07.9600274", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-15T02:59:07.9600274", durationSeconds = 126, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T14:50:29.2326588", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T14:50:29.2326588", durationSeconds = 329, pagesRead = 0 } } }, + { seriesId = 10634, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T14:38:39.3797696", chapters = { + { chapterId = 17868, startTimeUtc = "2026-10-14T14:38:39.3797696", durationSeconds = 481, pagesRead = 32 } } }, + { seriesId = 10634, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T14:08:54.1661113", chapters = { + { chapterId = 17868, startTimeUtc = "2026-10-14T14:08:54.1661113", durationSeconds = 309, pagesRead = 27 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T13:55:48.5704762", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T13:55:48.5704762", durationSeconds = 716, pagesRead = 0 } } }, + { seriesId = 9249, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T13:49:23.172248", chapters = { + { chapterId = 13493, startTimeUtc = "2026-10-14T13:49:23.172248", durationSeconds = 305, pagesRead = 6 } } }, + { seriesId = 10634, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T13:03:43.5815681", chapters = { + { chapterId = 17868, startTimeUtc = "2026-10-14T13:03:43.5815681", durationSeconds = 22, pagesRead = 3 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T12:59:54.4012612", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T12:59:54.4012612", durationSeconds = 210, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T12:32:09.2873459", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T12:32:09.2873459", durationSeconds = 354, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T10:50:12.8325335", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T10:50:12.8325335", durationSeconds = 427, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T09:55:45.2531997", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T09:55:45.2531997", durationSeconds = 229, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T09:17:05.53145", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-14T09:17:05.53145", durationSeconds = 433, pagesRead = 0 } } }, + { seriesId = 7606, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T09:13:54.1770611", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-14T09:13:54.1770611", durationSeconds = 141, pagesRead = 3 } } }, + { seriesId = 7606, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T08:31:01.497007", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-14T08:31:01.497007", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T08:18:25.5482677", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T08:18:25.5482677", durationSeconds = 631, pagesRead = 0 } } }, + { seriesId = 7540, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T07:55:05.3240629", chapters = { + { chapterId = 13394, startTimeUtc = "2026-10-14T07:55:05.3240629", durationSeconds = 82, pagesRead = 0 } } }, + { seriesId = 10705, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T07:38:45.2095335", chapters = { + { chapterId = 18930, startTimeUtc = "2026-10-14T07:38:45.2095335", durationSeconds = 206, pagesRead = 3 } } }, + { seriesId = 7540, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T07:34:26.9247375", chapters = { + { chapterId = 13394, startTimeUtc = "2026-10-14T07:34:26.9247375", durationSeconds = 83, pagesRead = 5 } } }, + { seriesId = 10720, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T07:16:16.0691328", chapters = { + { chapterId = 18951, startTimeUtc = "2026-10-14T07:16:16.0691328", durationSeconds = 72, pagesRead = 10 } } }, + { seriesId = 8661, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T07:14:59.4980606", chapters = { + { chapterId = 12763, startTimeUtc = "2026-10-14T07:14:59.4980606", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7805, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T07:14:45.0436933", chapters = { + { chapterId = 11791, startTimeUtc = "2026-10-14T07:14:45.0436933", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7540, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T07:14:08.0963104", chapters = { + { chapterId = 13394, startTimeUtc = "2026-10-14T07:14:08.0963104", durationSeconds = 71, pagesRead = 2 } } }, + { seriesId = 7606, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T06:46:46.3439122", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-14T07:07:38.102712", durationSeconds = 0, pagesRead = 0 }, + { chapterId = 11501, startTimeUtc = "2026-10-14T06:46:46.3439122", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T06:54:53.1919748", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-14T07:06:44.0374852", durationSeconds = 21, pagesRead = 24 }, + { chapterId = 11285, startTimeUtc = "2026-10-14T06:54:53.1919748", durationSeconds = 48, pagesRead = 1 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T06:35:44.8950968", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T06:56:37.9521487", durationSeconds = 597, pagesRead = 5 }, + { chapterId = 11273, startTimeUtc = "2026-10-14T06:35:44.8950968", durationSeconds = 529, pagesRead = -6 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T06:12:27.3026502", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T06:12:27.3026502", durationSeconds = 686, pagesRead = 1 } } }, + { seriesId = 7460, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T06:02:06.7713486", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-14T06:02:06.7713486", durationSeconds = 647, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T05:48:30.213286", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-14T05:48:30.213286", durationSeconds = 113, pagesRead = 1 } } }, + { seriesId = 7606, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T05:47:30.9663527", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-14T05:47:30.9663527", durationSeconds = 40, pagesRead = 3 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T05:35:38.8926445", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T05:35:38.8926445", durationSeconds = 674, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T03:36:59.7411875", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T03:36:59.7411875", durationSeconds = 1352, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T03:28:46.1491425", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-14T03:28:46.1491425", durationSeconds = 794, pagesRead = -1 } } }, + { seriesId = 7606, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T03:16:21.8058422", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-14T03:16:21.8058422", durationSeconds = 1063, pagesRead = 1 } } }, + { seriesId = 7606, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T01:55:37.5163534", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-14T01:55:37.5163534", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 10004, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T01:49:18.2803981", chapters = { + { chapterId = 14594, startTimeUtc = "2026-10-14T01:49:18.2803981", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T01:39:31.4453653", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T01:39:31.4453653", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 10634, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T14:57:39.6850524", chapters = { + { chapterId = 17868, startTimeUtc = "2026-10-13T14:57:39.6850524", durationSeconds = 296, pagesRead = 43 } } }, + { seriesId = 7453, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T14:56:50.7578846", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-13T14:56:50.7578846", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 10634, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T14:36:12.2101045", chapters = { + { chapterId = 17868, startTimeUtc = "2026-10-13T14:42:41.461277", durationSeconds = 73, pagesRead = 17 }, + { chapterId = 17861, startTimeUtc = "2026-10-13T14:36:12.2101045", durationSeconds = 382, pagesRead = 50 } } }, + { seriesId = 10634, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T13:30:56.9584871", chapters = { + { chapterId = 17861, startTimeUtc = "2026-10-13T13:30:56.9584871", durationSeconds = 965, pagesRead = 35 } } }, + { seriesId = 7453, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T12:50:13.6195947", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-13T12:50:13.6195947", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 10634, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T11:07:48.1054905", chapters = { + { chapterId = 17861, startTimeUtc = "2026-10-13T11:07:48.1054905", durationSeconds = 1557, pagesRead = 87 } } }, + { seriesId = 7453, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T10:49:24.2700176", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-13T10:49:24.2700176", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 10634, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T10:33:26.9620773", chapters = { + { chapterId = 17861, startTimeUtc = "2026-10-13T10:33:26.9620773", durationSeconds = 85, pagesRead = 9 } } }, + { seriesId = 7453, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T09:19:44.4142404", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-13T09:19:44.4142404", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7606, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T08:41:22.7503239", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-13T08:41:22.7503239", durationSeconds = 177, pagesRead = 3 } } }, + { seriesId = 7453, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T07:17:51.0855549", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-13T07:17:51.0855549", durationSeconds = 31, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T06:23:56.2429684", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-13T06:23:56.2429684", durationSeconds = 948, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T04:44:11.1456271", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-13T04:44:11.1456271", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T04:04:52.1419963", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-13T04:04:52.1419963", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 10634, localDate = "2026-10-12T00:00:00", startTimeUtc = "2026-10-12T13:41:25.4902953", chapters = { + { chapterId = 17861, startTimeUtc = "2026-10-12T13:41:25.4902953", durationSeconds = 77, pagesRead = 5 } } }, + { seriesId = 10634, localDate = "2026-10-12T00:00:00", startTimeUtc = "2026-10-12T04:30:51.522376", chapters = { + { chapterId = 17861, startTimeUtc = "2026-10-12T04:30:51.522376", durationSeconds = 26, pagesRead = 4 } } }, + { seriesId = 7453, localDate = "2026-10-12T00:00:00", startTimeUtc = "2026-10-12T03:52:47.3926019", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-12T03:52:47.3926019", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 10634, localDate = "2026-10-12T00:00:00", startTimeUtc = "2026-10-12T02:50:17.2681685", chapters = { + { chapterId = 17861, startTimeUtc = "2026-10-12T02:59:07.2940778", durationSeconds = 505, pagesRead = 5 }, + { chapterId = 17855, startTimeUtc = "2026-10-12T02:50:17.2681685", durationSeconds = 518, pagesRead = 12 } } }, + { seriesId = 10634, localDate = "2026-10-12T00:00:00", startTimeUtc = "2026-10-12T02:26:17.4191481", chapters = { + { chapterId = 17855, startTimeUtc = "2026-10-12T02:26:17.4191481", durationSeconds = 332, pagesRead = 27 } } }, + { seriesId = 10600, localDate = "2026-10-12T00:00:00", startTimeUtc = "2026-10-11T16:06:22.9336343", chapters = { + { chapterId = 17139, startTimeUtc = "2026-10-11T16:06:22.9336343", durationSeconds = 34, pagesRead = 11 } } }, + { seriesId = 10634, localDate = "2026-10-12T00:00:00", startTimeUtc = "2026-10-11T16:00:00.7226412", chapters = { + { chapterId = 17855, startTimeUtc = "2026-10-11T16:00:00.7226412", durationSeconds = 311, pagesRead = 39 } } }, + { seriesId = 10634, localDate = "2026-10-11T00:00:00", startTimeUtc = "2026-10-11T15:54:42.9913657", chapters = { + { chapterId = 17855, startTimeUtc = "2026-10-11T15:54:42.9913657", durationSeconds = 137, pagesRead = 26 } } }, + { seriesId = 7453, localDate = "2026-10-11T00:00:00", startTimeUtc = "2026-10-11T15:16:45.9848037", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-11T15:16:45.9848037", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-11T00:00:00", startTimeUtc = "2026-10-11T14:54:13.613368", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-11T14:54:13.613368", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-11T00:00:00", startTimeUtc = "2026-10-11T14:35:43.0809755", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-11T14:35:43.0809755", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-11T00:00:00", startTimeUtc = "2026-10-11T12:58:29.291105", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-11T12:58:29.291105", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-11T00:00:00", startTimeUtc = "2026-10-11T11:00:42.6215043", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-11T11:00:42.6215043", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-11T00:00:00", startTimeUtc = "2026-10-11T04:17:28.3592015", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-11T04:17:28.3592015", durationSeconds = 512, pagesRead = 0 } } }, + { seriesId = 7606, localDate = "2026-10-11T00:00:00", startTimeUtc = "2026-10-11T02:53:45.4676925", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-11T02:53:45.4676925", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 9249, localDate = "2026-10-10T00:00:00", startTimeUtc = "2026-10-10T15:00:59.375396", chapters = { + { chapterId = 13493, startTimeUtc = "2026-10-10T15:00:59.375396", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 9249, localDate = "2026-10-10T00:00:00", startTimeUtc = "2026-10-10T09:37:25.4148239", chapters = { + { chapterId = 13493, startTimeUtc = "2026-10-10T09:37:25.4148239", durationSeconds = 2, pagesRead = 0 } } }, + { seriesId = 9249, localDate = "2026-10-10T00:00:00", startTimeUtc = "2026-10-10T08:58:13.142957", chapters = { + { chapterId = 13493, startTimeUtc = "2026-10-10T08:58:13.142957", durationSeconds = 9, pagesRead = 0 } } }, + { seriesId = 9249, localDate = "2026-10-10T00:00:00", startTimeUtc = "2026-10-10T08:15:36.7468877", chapters = { + { chapterId = 13493, startTimeUtc = "2026-10-10T08:15:36.7468877", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 9249, localDate = "2026-10-10T00:00:00", startTimeUtc = "2026-10-10T07:52:18.8289612", chapters = { + { chapterId = 13493, startTimeUtc = "2026-10-10T07:52:18.8289612", durationSeconds = 164, pagesRead = 0 } } }, + { seriesId = 9249, localDate = "2026-10-10T00:00:00", startTimeUtc = "2026-10-10T07:10:45.3655221", chapters = { + { chapterId = 13493, startTimeUtc = "2026-10-10T07:10:45.3655221", durationSeconds = 33, pagesRead = 1 } } }, + { seriesId = 7453, localDate = "2026-10-10T00:00:00", startTimeUtc = "2026-10-10T04:44:42.7023417", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-10T04:44:42.7023417", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-10T00:00:00", startTimeUtc = "2026-10-10T03:55:35.74839", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-10T03:55:35.74839", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7606, localDate = "2026-10-10T00:00:00", startTimeUtc = "2026-10-10T03:41:12.3904529", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-10T03:41:12.3904529", durationSeconds = 12, pagesRead = 2 } } }, + { seriesId = 7453, localDate = "2026-10-10T00:00:00", startTimeUtc = "2026-10-10T03:39:55.2030981", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-10T03:39:55.2030981", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7606, localDate = "2026-10-10T00:00:00", startTimeUtc = "2026-10-10T02:29:21.0392738", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-10T02:29:21.0392738", durationSeconds = 40, pagesRead = 2 } } }, + { seriesId = 7606, localDate = "2026-10-10T00:00:00", startTimeUtc = "2026-10-10T02:12:18.2048535", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-10T02:12:18.2048535", durationSeconds = 53, pagesRead = 3 } } }, + { seriesId = 7606, localDate = "2026-10-10T00:00:00", startTimeUtc = "2026-10-10T01:55:30.4051153", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-10T01:55:30.4051153", durationSeconds = 50, pagesRead = 2 } } }, + { seriesId = 7453, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T14:45:39.0731175", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-09T14:45:39.0731175", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7606, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T13:43:07.3149178", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-09T13:43:07.3149178", durationSeconds = 5, pagesRead = 0 } } }, + { seriesId = 10735, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T13:32:16.6705302", chapters = { + { chapterId = 18969, startTimeUtc = "2026-10-09T13:32:16.6705302", durationSeconds = 163, pagesRead = 5 } } }, + { seriesId = 10698, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T13:30:11.0145349", chapters = { + { chapterId = 18923, startTimeUtc = "2026-10-09T13:30:11.0145349", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7606, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T13:17:56.7622935", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-09T13:17:56.7622935", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7606, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T11:51:14.1858092", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-09T11:51:14.1858092", durationSeconds = 7, pagesRead = 0 } } }, + { seriesId = 10732, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T11:20:33.6944863", chapters = { + { chapterId = 18966, startTimeUtc = "2026-10-09T11:20:33.6944863", durationSeconds = 29, pagesRead = 21 } } }, + { seriesId = 10735, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T11:15:31.2028337", chapters = { + { chapterId = 18969, startTimeUtc = "2026-10-09T11:15:31.2028337", durationSeconds = 80, pagesRead = 33 } } }, + { seriesId = 10724, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T11:12:30.4622536", chapters = { + { chapterId = 18957, startTimeUtc = "2026-10-09T11:12:30.4622536", durationSeconds = 4, pagesRead = 0 } } }, + { seriesId = 7606, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T11:04:22.6125371", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-09T11:04:22.6125371", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 10724, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T10:29:16.8959018", chapters = { + { chapterId = 18957, startTimeUtc = "2026-10-09T10:29:16.8959018", durationSeconds = 7, pagesRead = 16 } } }, + { seriesId = 7606, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T09:51:43.6940126", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-09T09:51:43.6940126", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 9249, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T09:34:29.5406473", chapters = { + { chapterId = 13493, startTimeUtc = "2026-10-09T09:34:29.5406473", durationSeconds = 3, pagesRead = 0 } } }, + { seriesId = 7606, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T09:34:17.5161863", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-09T09:34:17.5161863", durationSeconds = 5, pagesRead = 1 } } }, + { seriesId = 7606, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T09:10:02.1865718", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-09T09:10:02.1865718", durationSeconds = 759, pagesRead = 11 } } }, + { seriesId = 10708, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T08:18:07.1620583", chapters = { + { chapterId = 18933, startTimeUtc = "2026-10-09T08:18:07.1620583", durationSeconds = 15, pagesRead = 2 } } }, + { seriesId = 10707, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T07:55:45.2365064", chapters = { + { chapterId = 18932, startTimeUtc = "2026-10-09T07:55:45.2365064", durationSeconds = 7, pagesRead = 4 } } }, + { seriesId = 7453, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T07:44:06.636679", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-09T07:44:06.636679", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T07:13:20.7857153", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-09T07:13:20.7857153", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T04:40:28.7189645", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-09T04:40:28.7189645", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T04:05:17.6951039", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-09T04:05:17.6951039", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 9249, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T03:03:56.2211648", chapters = { + { chapterId = 13493, startTimeUtc = "2026-10-09T03:03:56.2211648", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 9292, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T01:10:42.7539032", chapters = { + { chapterId = 13569, startTimeUtc = "2026-10-09T01:10:42.7539032", durationSeconds = 8, pagesRead = 0 } } }, + { seriesId = 9292, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T15:26:10.3634693", chapters = { + { chapterId = 13569, startTimeUtc = "2026-10-08T15:26:10.3634693", durationSeconds = 15, pagesRead = 10 } } }, + { seriesId = 9249, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T15:12:20.8270779", chapters = { + { chapterId = 13493, startTimeUtc = "2026-10-08T15:12:20.8270779", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T14:34:05.7981443", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T14:34:05.7981443", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T13:12:53.6969824", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T13:12:53.6969824", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 9249, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T11:49:28.3986198", chapters = { + { chapterId = 13493, startTimeUtc = "2026-10-08T11:49:28.3986198", durationSeconds = 95, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T11:48:06.6315963", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T11:48:06.6315963", durationSeconds = 544, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T10:57:20.8373954", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-08T11:15:47.102", durationSeconds = 1111, pagesRead = 0 }, + { chapterId = 11285, startTimeUtc = "2026-10-08T10:57:20.8373954", durationSeconds = 406, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T11:02:33.6484158", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T11:02:33.6484158", durationSeconds = 611, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T10:31:08.475182", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T10:31:08.475182", durationSeconds = 3, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T09:03:45.5309711", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T09:03:45.5309711", durationSeconds = 86, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T07:59:09.2881628", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T07:59:09.2881628", durationSeconds = 263, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T07:20:18.0105615", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T07:20:18.0105615", durationSeconds = 233, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T06:48:51.312417", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T06:48:51.312417", durationSeconds = 296, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T04:42:54.7579483", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-08T04:42:54.7579483", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T04:05:45.0300961", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T04:05:45.0300961", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7540, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T02:52:33.5236184", chapters = { + { chapterId = 13394, startTimeUtc = "2026-10-08T02:52:33.5236184", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T02:20:36.4169563", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-08T02:20:36.4169563", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-07T00:00:00", startTimeUtc = "2026-10-07T13:44:15.125016", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-07T13:44:15.125016", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-07T00:00:00", startTimeUtc = "2026-10-07T09:45:01.0814021", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-07T09:45:01.0814021", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-07T00:00:00", startTimeUtc = "2026-10-07T05:19:38.9892914", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-07T05:19:38.9892914", durationSeconds = 503, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-06T00:00:00", startTimeUtc = "2026-10-06T13:00:26.371751", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-06T13:00:26.371751", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-06T00:00:00", startTimeUtc = "2026-10-06T12:21:25.7149691", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-06T12:21:25.7149691", durationSeconds = 489, pagesRead = 0 } } }, + { seriesId = 9249, localDate = "2026-10-06T00:00:00", startTimeUtc = "2026-10-06T12:07:54.0702478", chapters = { + { chapterId = 13493, startTimeUtc = "2026-10-06T12:07:54.0702478", durationSeconds = 320, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-06T00:00:00", startTimeUtc = "2026-10-06T12:01:31.4949015", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-06T12:01:31.4949015", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-06T00:00:00", startTimeUtc = "2026-10-06T11:37:48.0185472", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-06T11:37:48.0185472", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-06T00:00:00", startTimeUtc = "2026-10-06T03:21:10.9150125", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-06T03:21:10.9150125", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-06T00:00:00", startTimeUtc = "2026-10-06T02:50:29.5547188", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-06T02:50:29.5547188", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-05T00:00:00", startTimeUtc = "2026-10-05T14:10:59.8916334", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-05T14:10:59.8916334", durationSeconds = 195, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-05T00:00:00", startTimeUtc = "2026-10-05T12:18:33.1689018", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-05T12:18:33.1689018", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-05T00:00:00", startTimeUtc = "2026-10-05T11:54:12.1093305", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-05T11:54:12.1093305", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-05T00:00:00", startTimeUtc = "2026-10-05T11:34:55.3786363", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-05T11:34:55.3786363", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-05T00:00:00", startTimeUtc = "2026-10-05T09:15:25.8448735", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-05T09:15:25.8448735", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-04T00:00:00", startTimeUtc = "2026-10-04T09:36:48.7199331", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-04T09:36:48.7199331", durationSeconds = 226, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-04T00:00:00", startTimeUtc = "2026-10-04T06:13:00.6097898", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-04T06:13:00.6097898", durationSeconds = 412, pagesRead = 1 } } }, + { seriesId = 9249, localDate = "2026-10-03T00:00:00", startTimeUtc = "2026-10-03T14:24:26.495891", chapters = { + { chapterId = 13493, startTimeUtc = "2026-10-03T14:24:26.495891", durationSeconds = 337, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-03T00:00:00", startTimeUtc = "2026-10-03T13:00:16.6885142", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-03T13:00:16.6885142", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 10588, localDate = "2026-10-03T00:00:00", startTimeUtc = "2026-10-03T12:25:37.0931958", chapters = { + { chapterId = 16914, startTimeUtc = "2026-10-03T12:25:37.0931958", durationSeconds = 358, pagesRead = 24 } } }, + { seriesId = 7460, localDate = "2026-10-03T00:00:00", startTimeUtc = "2026-10-03T12:09:12.6479717", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-03T12:09:12.6479717", durationSeconds = 409, pagesRead = 1 } } }, + { seriesId = 7540, localDate = "2026-10-03T00:00:00", startTimeUtc = "2026-10-03T02:10:46.4251132", chapters = { + { chapterId = 13394, startTimeUtc = "2026-10-03T02:10:46.4251132", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7540, localDate = "2026-10-02T00:00:00", startTimeUtc = "2026-10-02T04:04:43.6820861", chapters = { + { chapterId = 13394, startTimeUtc = "2026-10-02T04:04:43.6820861", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-02T00:00:00", startTimeUtc = "2026-10-02T01:31:26.0795951", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-02T01:31:26.0795951", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-02T00:00:00", startTimeUtc = "2026-10-02T01:19:47.6481957", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-02T01:19:47.6481957", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-01T00:00:00", startTimeUtc = "2026-10-01T14:01:45.997983", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-01T14:01:45.997983", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 10585, localDate = "2026-10-01T00:00:00", startTimeUtc = "2026-10-01T13:36:40.8506172", chapters = { + { chapterId = 16862, startTimeUtc = "2026-10-01T13:36:40.8506172", durationSeconds = 113, pagesRead = 8 } } }, + { seriesId = 7460, localDate = "2026-10-01T00:00:00", startTimeUtc = "2026-10-01T13:35:51.0806955", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-01T13:35:51.0806955", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-01T00:00:00", startTimeUtc = "2026-10-01T11:55:01.4289659", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-01T11:55:01.4289659", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-01T00:00:00", startTimeUtc = "2026-10-01T11:41:02.5910426", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-01T11:41:02.5910426", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-01T00:00:00", startTimeUtc = "2026-10-01T11:28:36.4902671", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-01T11:28:36.4902671", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-01T00:00:00", startTimeUtc = "2026-10-01T11:10:02.1536935", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-01T11:10:02.1536935", durationSeconds = 289, pagesRead = 0 } } }, + { seriesId = 10585, localDate = "2026-10-01T00:00:00", startTimeUtc = "2026-10-01T11:04:28.7600787", chapters = { + { chapterId = 16862, startTimeUtc = "2026-10-01T11:04:28.7600787", durationSeconds = 241, pagesRead = 15 } } }, + { seriesId = 7540, localDate = "2026-10-01T00:00:00", startTimeUtc = "2026-10-01T10:32:28.7130273", chapters = { + { chapterId = 13394, startTimeUtc = "2026-10-01T10:32:28.7130273", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 8661, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T13:03:27.0677663", chapters = { + { chapterId = 12763, startTimeUtc = "2026-09-30T13:03:27.0677663", durationSeconds = 1530, pagesRead = -3 } } }, + { seriesId = 7540, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T13:02:32.9357375", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-30T13:02:32.9357375", durationSeconds = 22, pagesRead = 0 } } }, + { seriesId = 7540, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T12:28:33.282795", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-30T12:28:33.282795", durationSeconds = 189, pagesRead = 0 } } }, + { seriesId = 8661, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T11:37:13.1197026", chapters = { + { chapterId = 12763, startTimeUtc = "2026-09-30T11:37:13.1197026", durationSeconds = 25, pagesRead = 0 } } }, + { seriesId = 7540, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T11:33:44.6966312", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-30T11:33:44.6966312", durationSeconds = 130, pagesRead = 0 } } }, + { seriesId = 7540, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T09:14:25.3316858", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-30T09:14:25.3316858", durationSeconds = 37, pagesRead = -4 } } }, + { seriesId = 7540, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T08:52:37.2436808", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-30T08:52:37.2436808", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7540, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T07:54:07.7610298", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-30T07:54:07.7610298", durationSeconds = 5, pagesRead = 0 } } }, + { seriesId = 7805, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T03:56:53.2380567", chapters = { + { chapterId = 11791, startTimeUtc = "2026-09-30T03:56:53.2380567", durationSeconds = 6, pagesRead = 0 } } }, + { seriesId = 7540, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T03:42:57.6124947", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-30T03:42:57.6124947", durationSeconds = 1749, pagesRead = 4 } } }, + { seriesId = 7540, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T03:23:47.6591832", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-30T03:23:47.6591832", durationSeconds = 548, pagesRead = 0 } } }, + { seriesId = 10684, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T03:12:37.6514083", chapters = { + { chapterId = 18895, startTimeUtc = "2026-09-30T03:12:37.6514083", durationSeconds = 68, pagesRead = 15 } } }, + { seriesId = 10556, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T01:58:37.2644751", chapters = { + { chapterId = 16398, startTimeUtc = "2026-09-30T01:58:37.2644751", durationSeconds = 5, pagesRead = 6 } } }, + { seriesId = 7805, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T00:43:20.1361231", chapters = { + { chapterId = 11791, startTimeUtc = "2026-09-30T01:16:48.8842393", durationSeconds = 387, pagesRead = 0 }, + { chapterId = 11791, startTimeUtc = "2026-09-30T00:43:20.1361231", durationSeconds = 204, pagesRead = 1 } } }, + { seriesId = 8661, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T00:46:55.2653707", chapters = { + { chapterId = 12763, startTimeUtc = "2026-09-30T00:46:55.2653707", durationSeconds = 1330, pagesRead = 3 } } }, + { seriesId = 7460, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T00:25:09.4803818", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-30T00:37:14.7633119", durationSeconds = 43, pagesRead = 0 }, + { chapterId = 11285, startTimeUtc = "2026-09-30T00:25:09.4803818", durationSeconds = 32, pagesRead = 0 } } }, + { seriesId = 7540, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T00:30:04.5325361", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-30T00:30:04.5325361", durationSeconds = 222, pagesRead = -1 } } }, + { seriesId = 9249, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T00:27:17.7123717", chapters = { + { chapterId = 13493, startTimeUtc = "2026-09-30T00:27:17.7123717", durationSeconds = 108, pagesRead = 1 } } }, + { seriesId = 10584, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T15:27:07.2391439", chapters = { + { chapterId = 16853, startTimeUtc = "2026-09-29T15:27:07.2391439", durationSeconds = 6, pagesRead = 6 } } }, + { seriesId = 7460, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T15:23:24.6913136", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-29T15:23:24.6913136", durationSeconds = 51, pagesRead = 1 } } }, + { seriesId = 10584, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T15:11:40.8997791", chapters = { + { chapterId = 16853, startTimeUtc = "2026-09-29T15:11:40.8997791", durationSeconds = 24, pagesRead = 14 } } }, + { seriesId = 8661, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T15:10:15.9077958", chapters = { + { chapterId = 12763, startTimeUtc = "2026-09-29T15:10:15.9077958", durationSeconds = 23, pagesRead = 6 } } }, + { seriesId = 7540, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T15:02:32.6735695", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-29T15:02:32.6735695", durationSeconds = 452, pagesRead = 7 } } }, + { seriesId = 7460, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T14:58:04.6106466", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-29T14:58:04.6106466", durationSeconds = 82, pagesRead = 0 } } }, + { seriesId = 9249, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T14:38:04.1555096", chapters = { + { chapterId = 13493, startTimeUtc = "2026-09-29T14:38:04.1555096", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 9249, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T14:12:48.9320003", chapters = { + { chapterId = 13493, startTimeUtc = "2026-09-29T14:12:48.9320003", durationSeconds = 86, pagesRead = 3 } } }, + { seriesId = 7460, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T14:07:43.3739949", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-29T14:07:43.3739949", durationSeconds = 439, pagesRead = 20 } } }, + { seriesId = 10560, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T13:55:37.9561391", chapters = { + { chapterId = 16493, startTimeUtc = "2026-09-29T13:55:37.9561391", durationSeconds = 0, pagesRead = 1 } } }, + { seriesId = 9249, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T12:39:52.7733874", chapters = { + { chapterId = 13493, startTimeUtc = "2026-09-29T12:39:52.7733874", durationSeconds = 31, pagesRead = 3 } } }, + { seriesId = 10559, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T12:33:10.2857117", chapters = { + { chapterId = 16479, startTimeUtc = "2026-09-29T12:33:10.2857117", durationSeconds = 7, pagesRead = 15 } } }, + { seriesId = 10560, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T11:51:35.4694759", chapters = { + { chapterId = 16493, startTimeUtc = "2026-09-29T12:22:43.7993875", durationSeconds = 936, pagesRead = 2 }, + { chapterId = 16493, startTimeUtc = "2026-09-29T11:51:35.4694759", durationSeconds = 1223, pagesRead = 12 } } }, + { seriesId = 7460, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T11:58:50.1222492", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-29T12:21:19.3748615", durationSeconds = 909, pagesRead = -2 }, + { chapterId = 11285, startTimeUtc = "2026-09-29T11:58:50.1222492", durationSeconds = 20, pagesRead = 0 } } }, + { seriesId = 10563, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T12:17:34.2571271", chapters = { + { chapterId = 16505, startTimeUtc = "2026-09-29T12:17:34.2571271", durationSeconds = 36, pagesRead = 17 } } }, + { seriesId = 10562, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T12:07:43.0627869", chapters = { + { chapterId = 16502, startTimeUtc = "2026-09-29T12:07:43.0627869", durationSeconds = 70, pagesRead = 17 } } }, + { seriesId = 7910, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T11:50:25.270629", chapters = { + { chapterId = 11904, startTimeUtc = "2026-09-29T11:50:25.270629", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7910, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T11:25:02.6769601", chapters = { + { chapterId = 11896, startTimeUtc = "2026-09-29T11:25:16.5490822", durationSeconds = 442, pagesRead = 6 }, + { chapterId = 11898, startTimeUtc = "2026-09-29T11:25:02.6769601", durationSeconds = 328, pagesRead = 1 } } }, + { seriesId = 7460, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T11:24:52.8021347", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-29T11:24:52.8021347", durationSeconds = 525, pagesRead = 15 } } }, + { seriesId = 10639, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T11:08:39.2618986", chapters = { + { chapterId = 18031, startTimeUtc = "2026-09-29T11:08:39.2618986", durationSeconds = 0, pagesRead = 1 } } }, + { seriesId = 10556, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T10:56:40.6001656", chapters = { + { chapterId = 16398, startTimeUtc = "2026-09-29T10:56:40.6001656", durationSeconds = 11, pagesRead = 9 } } }, + { seriesId = 7460, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T10:45:47.6455857", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-29T10:45:47.6455857", durationSeconds = 4, pagesRead = 4 } } }, + { seriesId = 7462, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T10:45:05.5896105", chapters = { + { chapterId = 11290, startTimeUtc = "2026-09-29T10:45:05.5896105", durationSeconds = 3, pagesRead = 1 } } }, + { seriesId = 7540, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T10:35:52.0518521", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-29T10:35:52.0518521", durationSeconds = 39, pagesRead = 6 } } }, + { seriesId = 7805, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T10:34:39.8658599", chapters = { + { chapterId = 11791, startTimeUtc = "2026-09-29T10:34:39.8658599", durationSeconds = 12, pagesRead = 3 } } }, + { seriesId = 7453, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T10:25:25.4088288", chapters = { + { chapterId = 11271, startTimeUtc = "2026-09-29T10:25:25.4088288", durationSeconds = 86, pagesRead = 2 } } }, + { seriesId = 10004, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T10:22:33.7903381", chapters = { + { chapterId = 14594, startTimeUtc = "2026-09-29T10:22:33.7903381", durationSeconds = 167, pagesRead = 4 } } }, + { seriesId = 7453, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T10:01:44.7835505", chapters = { + { chapterId = 11271, startTimeUtc = "2026-09-29T10:01:44.7835505", durationSeconds = 230, pagesRead = 0 } } }, + { seriesId = 10001, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T09:57:30.1875022", chapters = { + { chapterId = 14591, startTimeUtc = "2026-09-29T09:57:30.1875022", durationSeconds = 14, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T09:39:33.8232177", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-29T09:39:33.8232177", durationSeconds = 332, pagesRead = 19 } } }, + { seriesId = 7476, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T09:30:15.0902649", chapters = { + { chapterId = 11317, startTimeUtc = "2026-09-29T09:30:15.0902649", durationSeconds = 27, pagesRead = 0 } } }, + { seriesId = 7476, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T09:02:28.8339509", chapters = { + { chapterId = 11317, startTimeUtc = "2026-09-29T09:02:28.8339509", durationSeconds = 267, pagesRead = 0 } } }, + { seriesId = 10004, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T08:51:39.2655404", chapters = { + { chapterId = 14594, startTimeUtc = "2026-09-29T08:51:39.2655404", durationSeconds = 39, pagesRead = 0 } } }, + { seriesId = 10004, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T08:33:15.8755207", chapters = { + { chapterId = 14594, startTimeUtc = "2026-09-29T08:33:15.8755207", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 10004, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T08:14:10.4993494", chapters = { + { chapterId = 14594, startTimeUtc = "2026-09-29T08:14:10.4993494", durationSeconds = 106, pagesRead = 0 } } }, + { seriesId = 7476, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T07:47:38.8544242", chapters = { + { chapterId = 11317, startTimeUtc = "2026-09-29T08:02:48.272453", durationSeconds = 461, pagesRead = -1 }, + { chapterId = 11317, startTimeUtc = "2026-09-29T07:47:38.8544242", durationSeconds = 39, pagesRead = 7 } } }, + { seriesId = 7452, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T07:51:52.786463", chapters = { + { chapterId = 11269, startTimeUtc = "2026-09-29T07:51:52.786463", durationSeconds = 365, pagesRead = 115 } } }, + { seriesId = 10042, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T07:39:42.880422", chapters = { + { chapterId = 14638, startTimeUtc = "2026-09-29T07:39:42.880422", durationSeconds = 50, pagesRead = 0 } } }, + { seriesId = 7540, localDate = "2026-09-28T00:00:00", startTimeUtc = "2026-09-28T09:16:47.6382365", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-28T09:16:47.6382365", durationSeconds = 59, pagesRead = 0 } } }, + { seriesId = 9158, localDate = "2026-09-28T00:00:00", startTimeUtc = "2026-09-27T17:16:38.7193514", chapters = { + { chapterId = 13395, startTimeUtc = "2026-09-27T17:16:38.7193514", durationSeconds = 29, pagesRead = 1 } } }, + { seriesId = 10683, localDate = "2026-09-28T00:00:00", startTimeUtc = "2026-09-27T17:13:53.8061535", chapters = { + { chapterId = 18893, startTimeUtc = "2026-09-27T17:13:53.8061535", durationSeconds = 16, pagesRead = -1 } } }, + { seriesId = 7540, localDate = "2026-09-27T00:00:00", startTimeUtc = "2026-09-27T15:13:47.085122", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-27T15:13:47.085122", durationSeconds = 746, pagesRead = 0 } } }, + { seriesId = 7540, localDate = "2026-09-27T00:00:00", startTimeUtc = "2026-09-27T13:34:49.3907937", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-27T13:34:49.3907937", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7540, localDate = "2026-09-27T00:00:00", startTimeUtc = "2026-09-27T13:03:53.8173515", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-27T13:03:53.8173515", durationSeconds = 9, pagesRead = 0 } } }, + { seriesId = 7540, localDate = "2026-09-27T00:00:00", startTimeUtc = "2026-09-27T09:21:25.6490847", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-27T09:21:25.6490847", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7540, localDate = "2026-09-27T00:00:00", startTimeUtc = "2026-09-27T09:03:41.6524393", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-27T09:03:41.6524393", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7540, localDate = "2026-09-27T00:00:00", startTimeUtc = "2026-09-27T01:38:10.6211012", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-27T01:38:10.6211012", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7540, localDate = "2026-09-26T00:00:00", startTimeUtc = "2026-09-26T15:13:21.9970834", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-26T15:13:21.9970834", durationSeconds = 14, pagesRead = 4 } } }, + { seriesId = 8110, localDate = "2026-09-26T00:00:00", startTimeUtc = "2026-09-26T14:58:04.4305334", chapters = { + { chapterId = 12126, startTimeUtc = "2026-09-26T14:58:04.4305334", durationSeconds = 181, pagesRead = 1 } } }, + { seriesId = 8110, localDate = "2026-09-26T00:00:00", startTimeUtc = "2026-09-26T14:37:55.4114027", chapters = { + { chapterId = 12126, startTimeUtc = "2026-09-26T14:37:55.4114027", durationSeconds = 55, pagesRead = 1 } } }, + { seriesId = 7460, localDate = "2026-09-26T00:00:00", startTimeUtc = "2026-09-26T14:33:39.6298963", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-26T14:33:39.6298963", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-09-26T00:00:00", startTimeUtc = "2026-09-26T14:19:48.5269015", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-26T14:19:48.5269015", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 10676, localDate = "2026-09-26T00:00:00", startTimeUtc = "2026-09-26T13:34:15.9269344", chapters = { + { chapterId = 18818, startTimeUtc = "2026-09-26T13:34:15.9269344", durationSeconds = 1021, pagesRead = 54 } } }, + { seriesId = 10676, localDate = "2026-09-26T00:00:00", startTimeUtc = "2026-09-26T12:08:23.540117", chapters = { + { chapterId = 18818, startTimeUtc = "2026-09-26T12:08:23.540117", durationSeconds = 107, pagesRead = 11 } } }, + { seriesId = 7460, localDate = "2026-09-26T00:00:00", startTimeUtc = "2026-09-26T12:07:39.7719041", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-26T12:07:39.7719041", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-09-26T00:00:00", startTimeUtc = "2026-09-26T01:55:50.078051", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-26T01:55:50.078051", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-09-26T00:00:00", startTimeUtc = "2026-09-26T01:32:58.4149147", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-26T01:32:58.4149147", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-09-26T00:00:00", startTimeUtc = "2026-09-26T01:13:02.4223873", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-26T01:13:02.4223873", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 9110, localDate = "2026-09-25T00:00:00", startTimeUtc = "2026-09-25T14:23:56.0117314", chapters = { + { chapterId = 13318, startTimeUtc = "2026-09-25T14:23:56.0117314", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 9110, localDate = "2026-09-25T00:00:00", startTimeUtc = "2026-09-25T13:59:56.4928672", chapters = { + { chapterId = 13318, startTimeUtc = "2026-09-25T13:59:56.4928672", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 9110, localDate = "2026-09-25T00:00:00", startTimeUtc = "2026-09-25T07:58:26.2227579", chapters = { + { chapterId = 13318, startTimeUtc = "2026-09-25T07:58:26.2227579", durationSeconds = 3, pagesRead = 0 } } }, + { seriesId = 8110, localDate = "2026-09-25T00:00:00", startTimeUtc = "2026-09-25T07:08:30.8014023", chapters = { + { chapterId = 12126, startTimeUtc = "2026-09-25T07:08:30.8014023", durationSeconds = 7, pagesRead = 3 } } }, + { seriesId = 7460, localDate = "2026-09-25T00:00:00", startTimeUtc = "2026-09-25T01:28:12.7465578", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-25T01:28:12.7465578", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 10663, localDate = "2026-09-24T00:00:00", startTimeUtc = "2026-09-24T14:34:51.9798262", chapters = { + { chapterId = 18514, startTimeUtc = "2026-09-24T14:34:51.9798262", durationSeconds = 59, pagesRead = 10 } } }, + { seriesId = 10682, localDate = "2026-09-24T00:00:00", startTimeUtc = "2026-09-24T14:00:55.5695168", chapters = { + { chapterId = 18889, startTimeUtc = "2026-09-24T14:00:55.5695168", durationSeconds = 65, pagesRead = 8 } } }, + { seriesId = 10634, localDate = "2026-09-24T00:00:00", startTimeUtc = "2026-09-24T13:41:48.3170857", chapters = { + { chapterId = 17855, startTimeUtc = "2026-09-24T13:41:48.3170857", durationSeconds = 328, pagesRead = 65 } } }, + { seriesId = 10663, localDate = "2026-09-24T00:00:00", startTimeUtc = "2026-09-24T12:55:37.0956115", chapters = { + { chapterId = 18514, startTimeUtc = "2026-09-24T12:55:37.0956115", durationSeconds = 44, pagesRead = 8 } } }, + { seriesId = 10634, localDate = "2026-09-24T00:00:00", startTimeUtc = "2026-09-24T12:54:21.9067307", chapters = { + { chapterId = 17855, startTimeUtc = "2026-09-24T12:54:21.9067307", durationSeconds = 8, pagesRead = 4 } } }, + { seriesId = 10634, localDate = "2026-09-24T00:00:00", startTimeUtc = "2026-09-24T11:36:17.6978208", chapters = { + { chapterId = 17855, startTimeUtc = "2026-09-24T11:36:17.6978208", durationSeconds = 56, pagesRead = 14 } } }, + { seriesId = 10682, localDate = "2026-09-24T00:00:00", startTimeUtc = "2026-09-24T09:54:25.899822", chapters = { + { chapterId = 18889, startTimeUtc = "2026-09-24T09:54:25.899822", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 10674, localDate = "2026-09-24T00:00:00", startTimeUtc = "2026-09-24T09:27:10.4132213", chapters = { + { chapterId = 18789, startTimeUtc = "2026-09-24T09:27:10.4132213", durationSeconds = 8, pagesRead = 3 } } }, + { seriesId = 9249, localDate = "2026-09-24T00:00:00", startTimeUtc = "2026-09-24T07:47:32.97548", chapters = { + { chapterId = 13493, startTimeUtc = "2026-09-24T07:47:32.97548", durationSeconds = 461, pagesRead = 0 } } }, + { seriesId = 9249, localDate = "2026-09-24T00:00:00", startTimeUtc = "2026-09-24T07:26:01.1542479", chapters = { + { chapterId = 13493, startTimeUtc = "2026-09-24T07:26:01.1542479", durationSeconds = 146, pagesRead = 0 } } }, + { seriesId = 9095, localDate = "2026-09-24T00:00:00", startTimeUtc = "2026-09-24T06:46:54.4314754", chapters = { + { chapterId = 13282, startTimeUtc = "2026-09-24T06:46:54.4314754", durationSeconds = 0, pagesRead = 1 } } }, + { seriesId = 9649, localDate = "2026-09-24T00:00:00", startTimeUtc = "2026-09-23T16:09:03.1098014", chapters = { + { chapterId = 14126, startTimeUtc = "2026-09-23T16:09:03.1098014", durationSeconds = 4, pagesRead = 2 } } }, + { seriesId = 7461, localDate = "2026-09-24T00:00:00", startTimeUtc = "2026-09-23T16:05:48.0362145", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-23T16:05:48.0362145", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-09-23T00:00:00", startTimeUtc = "2026-09-23T13:47:22.8458997", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-23T13:47:22.8458997", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 8137, localDate = "2026-09-23T00:00:00", startTimeUtc = "2026-09-23T05:52:39.9019755", chapters = { + { chapterId = 12159, startTimeUtc = "2026-09-23T05:52:39.9019755", durationSeconds = 79, pagesRead = 18 } } }, + { seriesId = 9249, localDate = "2026-09-23T00:00:00", startTimeUtc = "2026-09-23T03:51:46.3681335", chapters = { + { chapterId = 13493, startTimeUtc = "2026-09-23T03:51:46.3681335", durationSeconds = 327, pagesRead = 0 } } }, + { seriesId = 9262, localDate = "2026-09-22T00:00:00", startTimeUtc = "2026-09-22T13:38:38.3358566", chapters = { + { chapterId = 13508, startTimeUtc = "2026-09-22T13:38:38.3358566", durationSeconds = 52, pagesRead = 4 } } }, + { seriesId = 9249, localDate = "2026-09-22T00:00:00", startTimeUtc = "2026-09-22T13:22:52.4340931", chapters = { + { chapterId = 13493, startTimeUtc = "2026-09-22T13:22:52.4340931", durationSeconds = 5, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-09-22T00:00:00", startTimeUtc = "2026-09-22T10:28:46.3070635", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-22T10:28:46.3070635", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-09-22T00:00:00", startTimeUtc = "2026-09-22T09:53:02.9688203", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-22T09:53:02.9688203", durationSeconds = 515, pagesRead = 1 } } }, + { seriesId = 9257, localDate = "2026-09-22T00:00:00", startTimeUtc = "2026-09-22T09:45:09.829169", chapters = { + { chapterId = 13503, startTimeUtc = "2026-09-22T09:45:09.829169", durationSeconds = 5, pagesRead = 11 } } }, + { seriesId = 9249, localDate = "2026-09-22T00:00:00", startTimeUtc = "2026-09-22T08:59:44.2021935", chapters = { + { chapterId = 13493, startTimeUtc = "2026-09-22T08:59:44.2021935", durationSeconds = 85, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-09-22T00:00:00", startTimeUtc = "2026-09-22T08:57:31.3039746", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-22T08:57:31.3039746", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-09-22T00:00:00", startTimeUtc = "2026-09-22T08:34:21.7362395", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-22T08:34:21.7362395", durationSeconds = 697, pagesRead = 0 } } }, + { seriesId = 9249, localDate = "2026-09-22T00:00:00", startTimeUtc = "2026-09-22T08:00:48.3941463", chapters = { + { chapterId = 13493, startTimeUtc = "2026-09-22T08:00:48.3941463", durationSeconds = 149, pagesRead = 2 } } }, + { seriesId = 9180, localDate = "2026-09-22T00:00:00", startTimeUtc = "2026-09-22T03:13:37.560087", chapters = { + { chapterId = 13420, startTimeUtc = "2026-09-22T03:13:37.560087", durationSeconds = 11, pagesRead = 7 } } }, + { seriesId = 7460, localDate = "2026-09-22T00:00:00", startTimeUtc = "2026-09-22T02:24:02.4880326", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-22T02:24:02.4880326", durationSeconds = 163, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-09-21T00:00:00", startTimeUtc = "2026-09-21T13:24:04.9528675", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-21T13:24:04.9528675", durationSeconds = 307, pagesRead = 1 } } }, + { seriesId = 7805, localDate = "2026-09-21T00:00:00", startTimeUtc = "2026-09-21T13:07:31.7048466", chapters = { + { chapterId = 11791, startTimeUtc = "2026-09-21T13:07:31.7048466", durationSeconds = 8, pagesRead = 0 } } }, + { seriesId = 8661, localDate = "2026-09-21T00:00:00", startTimeUtc = "2026-09-21T13:04:31.936106", chapters = { + { chapterId = 12763, startTimeUtc = "2026-09-21T13:04:31.936106", durationSeconds = 84, pagesRead = 0 } } }, + { seriesId = 8661, localDate = "2026-09-21T00:00:00", startTimeUtc = "2026-09-21T10:07:50.9423535", chapters = { + { chapterId = 12763, startTimeUtc = "2026-09-21T10:07:50.9423535", durationSeconds = 563, pagesRead = 5 } } }, + { seriesId = 7805, localDate = "2026-09-21T00:00:00", startTimeUtc = "2026-09-21T09:56:54.7828239", chapters = { + { chapterId = 11791, startTimeUtc = "2026-09-21T09:56:54.7828239", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 9110, localDate = "2026-09-21T00:00:00", startTimeUtc = "2026-09-21T04:49:43.5918775", chapters = { + { chapterId = 13318, startTimeUtc = "2026-09-21T04:49:43.5918775", durationSeconds = 207, pagesRead = 4 } } }, + { seriesId = 7603, localDate = "2026-09-21T00:00:00", startTimeUtc = "2026-09-21T04:49:04.8491169", chapters = { + { chapterId = 11484, startTimeUtc = "2026-09-21T04:49:04.8491169", durationSeconds = 6, pagesRead = 4 } } }, + { seriesId = 7603, localDate = "2026-09-21T00:00:00", startTimeUtc = "2026-09-21T03:38:08.3558687", chapters = { + { chapterId = 11484, startTimeUtc = "2026-09-21T03:38:08.3558687", durationSeconds = 8, pagesRead = 4 } } }, + { seriesId = 8247, localDate = "2026-09-20T00:00:00", startTimeUtc = "2026-09-20T14:14:20.693305", chapters = { + { chapterId = 12300, startTimeUtc = "2026-09-20T14:14:20.693305", durationSeconds = 86, pagesRead = 6 } } }, + { seriesId = 8281, localDate = "2026-09-20T00:00:00", startTimeUtc = "2026-09-20T14:11:24.8897015", chapters = { + { chapterId = 12334, startTimeUtc = "2026-09-20T14:11:24.8897015", durationSeconds = 25, pagesRead = 1 } } }, + { seriesId = 7476, localDate = "2026-09-20T00:00:00", startTimeUtc = "2026-09-20T13:17:19.1246015", chapters = { + { chapterId = 11317, startTimeUtc = "2026-09-20T13:17:19.1246015", durationSeconds = 34, pagesRead = 7 } } }, + { seriesId = 7805, localDate = "2026-09-20T00:00:00", startTimeUtc = "2026-09-20T13:07:24.1160188", chapters = { + { chapterId = 11791, startTimeUtc = "2026-09-20T13:07:24.1160188", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 8310, localDate = "2026-09-20T00:00:00", startTimeUtc = "2026-09-20T09:52:07.5117003", chapters = { + { chapterId = 12363, startTimeUtc = "2026-09-20T09:52:07.5117003", durationSeconds = 671, pagesRead = 3 } } }, + { seriesId = 8310, localDate = "2026-09-20T00:00:00", startTimeUtc = "2026-09-20T09:32:51.5623005", chapters = { + { chapterId = 12363, startTimeUtc = "2026-09-20T09:32:51.5623005", durationSeconds = 364, pagesRead = 1 } } }, + { seriesId = 8106, localDate = "2026-09-20T00:00:00", startTimeUtc = "2026-09-20T08:11:17.3798059", chapters = { + { chapterId = 12122, startTimeUtc = "2026-09-20T08:11:17.3798059", durationSeconds = 35, pagesRead = 5 } } }, + { seriesId = 7510, localDate = "2026-09-20T00:00:00", startTimeUtc = "2026-09-20T07:50:30.9737641", chapters = { + { chapterId = 11360, startTimeUtc = "2026-09-20T07:50:30.9737641", durationSeconds = 19, pagesRead = 0 } } }, + { seriesId = 7805, localDate = "2026-09-20T00:00:00", startTimeUtc = "2026-09-20T07:47:25.7922257", chapters = { + { chapterId = 11791, startTimeUtc = "2026-09-20T07:47:25.7922257", durationSeconds = 3, pagesRead = 0 } } }, + { seriesId = 7461, localDate = "2026-09-20T00:00:00", startTimeUtc = "2026-09-20T07:25:56.7820012", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-20T07:25:56.7820012", durationSeconds = 427, pagesRead = 2 } } }, + { seriesId = 7461, localDate = "2026-09-20T00:00:00", startTimeUtc = "2026-09-20T07:01:03.0337544", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-20T07:01:03.0337544", durationSeconds = 311, pagesRead = 0 } } }, + { seriesId = 7461, localDate = "2026-09-20T00:00:00", startTimeUtc = "2026-09-20T04:37:11.2011378", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-20T04:37:11.2011378", durationSeconds = 407, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-09-20T00:00:00", startTimeUtc = "2026-09-20T04:29:53.9882097", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-20T04:29:53.9882097", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7461, localDate = "2026-09-20T00:00:00", startTimeUtc = "2026-09-20T03:23:39.822214", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-20T03:23:39.822214", durationSeconds = 431, pagesRead = 0 } } }, + { seriesId = 7461, localDate = "2026-09-19T00:00:00", startTimeUtc = "2026-09-19T14:37:14.3112506", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-19T14:37:14.3112506", durationSeconds = 460, pagesRead = 0 } } }, + { seriesId = 7461, localDate = "2026-09-19T00:00:00", startTimeUtc = "2026-09-19T14:16:12.9574126", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-19T14:16:12.9574126", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7461, localDate = "2026-09-19T00:00:00", startTimeUtc = "2026-09-19T13:33:23.8175739", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-19T13:33:23.8175739", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7461, localDate = "2026-09-19T00:00:00", startTimeUtc = "2026-09-19T13:01:57.6991072", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-19T13:01:57.6991072", durationSeconds = 102, pagesRead = 0 } } }, + { seriesId = 7461, localDate = "2026-09-19T00:00:00", startTimeUtc = "2026-09-19T10:51:52.8573558", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-19T10:51:52.8573558", durationSeconds = 445, pagesRead = 0 } } }, + { seriesId = 7461, localDate = "2026-09-19T00:00:00", startTimeUtc = "2026-09-19T09:58:37.3332857", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-19T09:58:37.3332857", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7461, localDate = "2026-09-19T00:00:00", startTimeUtc = "2026-09-19T06:19:27.9750172", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-19T06:19:27.9750172", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7461, localDate = "2026-09-19T00:00:00", startTimeUtc = "2026-09-19T05:44:36.041471", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-19T05:44:36.041471", durationSeconds = 500, pagesRead = 0 } } }, + { seriesId = 7461, localDate = "2026-09-19T00:00:00", startTimeUtc = "2026-09-19T05:08:30.2036102", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-19T05:08:30.2036102", durationSeconds = 263, pagesRead = 4 } } }, + { seriesId = 7560, localDate = "2026-09-19T00:00:00", startTimeUtc = "2026-09-19T04:47:13.2207635", chapters = { + { chapterId = 11430, startTimeUtc = "2026-09-19T04:47:13.2207635", durationSeconds = 1, pagesRead = 1 } } }, + { seriesId = 7556, localDate = "2026-09-19T00:00:00", startTimeUtc = "2026-09-19T04:07:25.0646351", chapters = { + { chapterId = 11426, startTimeUtc = "2026-09-19T04:07:25.0646351", durationSeconds = 0, pagesRead = 1 } } }, + { seriesId = 7561, localDate = "2026-09-19T00:00:00", startTimeUtc = "2026-09-19T03:29:58.6171005", chapters = { + { chapterId = 11438, startTimeUtc = "2026-09-19T03:29:58.6171005", durationSeconds = 5, pagesRead = 4 } } }, + { seriesId = 7461, localDate = "2026-09-19T00:00:00", startTimeUtc = "2026-09-19T02:37:58.1533148", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-19T02:37:58.1533148", durationSeconds = 524, pagesRead = 0 } } }, + { seriesId = 7461, localDate = "2026-09-19T00:00:00", startTimeUtc = "2026-09-19T02:00:00.8956888", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-19T02:00:00.8956888", durationSeconds = 524, pagesRead = 1 } } }, + { seriesId = 7461, localDate = "2026-09-18T00:00:00", startTimeUtc = "2026-09-18T13:54:08.9566107", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-18T13:54:08.9566107", durationSeconds = 174, pagesRead = 0 } } }, + { seriesId = 7461, localDate = "2026-09-18T00:00:00", startTimeUtc = "2026-09-18T12:53:09.8665339", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-18T12:53:09.8665339", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7461, localDate = "2026-09-18T00:00:00", startTimeUtc = "2026-09-18T09:50:06.0469366", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-18T09:50:06.0469366", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7461, localDate = "2026-09-18T00:00:00", startTimeUtc = "2026-09-18T09:25:33.4181389", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-18T09:25:33.4181389", durationSeconds = 738, pagesRead = 1 } } }, + { seriesId = 7490, localDate = "2026-09-18T00:00:00", startTimeUtc = "2026-09-18T07:52:05.2045118", chapters = { + { chapterId = 11335, startTimeUtc = "2026-09-18T07:52:05.2045118", durationSeconds = 6, pagesRead = 2 } } }, + { seriesId = 7476, localDate = "2026-09-18T00:00:00", startTimeUtc = "2026-09-18T06:59:54.0156885", chapters = { + { chapterId = 11317, startTimeUtc = "2026-09-18T06:59:54.0156885", durationSeconds = 2, pagesRead = 2 } } }, + { seriesId = 7461, localDate = "2026-09-18T00:00:00", startTimeUtc = "2026-09-18T06:47:37.6019707", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-18T06:47:37.6019707", durationSeconds = 0, pagesRead = 0 } } }, +} diff --git a/tests/kavita/kamare_update_spec.lua b/tests/kavita/kamare_update_spec.lua new file mode 100644 index 0000000..8ca2c28 --- /dev/null +++ b/tests/kavita/kamare_update_spec.lua @@ -0,0 +1,202 @@ +--[[-- +moonsource_kavita.kamare_update:kamare 目标描述(只问 api.github.com、探测已装版本、装到 kamare 目录)。流程本身由 features.update 的 spec 覆盖。 + +@module tests.moonsource_kavita.kamare_update_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, inject-field + +local Assert = require("support.assert") + +local shown, closed, ticks = {}, {}, {} +local restarted = 0 +package.preload["ui/uimanager"] = function() + return { + nextTick = function(_, fn) ticks[#ticks + 1] = fn end, + } +end +local function flush() + while #ticks > 0 do table.remove(ticks, 1)() end +end +local connected = true +package.preload["ui/network/manager"] = function() + return { isConnected = function() return connected end } +end +package.preload["json"] = function() + return { decode = function(value) return value end } +end +package.preload["utils.log"] = function() + return { warn = function() end, dbg = function() end, info = function() end } +end +package.preload["utils.paths"] = function() + return { + ensureDir = function() return true end, + root = function() return "/tmp" end, + } +end + +-- 探测结果与安装根目录由用例控制。 +local probe_result = { ok = false, state = "missing" } +local plugins_dir = "/fake/plugins" +package.preload["moonsource_kavita.cache"] = function() + return { + probe = function() return probe_result end, + pluginsDir = function() return plugins_dir end, + } +end + +local function dialogModule() + return { + new = function(_, opts) + function opts:show() shown[#shown + 1] = self end + function opts:close() closed[#closed + 1] = self end + return opts + end, + } +end +package.preload["ui.themes.widgets.text_viewer"] = dialogModule +package.preload["ui.themes.widgets.toast"] = dialogModule +package.preload["ui.themes.widgets.progress_dialog"] = function() + return { + new = function(_, opts) + function opts:show() shown[#shown + 1] = self end + function opts:close() closed[#closed + 1] = self end + function opts:bytes(done, total) + self.progress, self.progress_max = done, total + end + function opts:set(text, percent) + self.status, self.percent = text, percent + end + return opts + end, + } +end + +local check_cbs, gets = {}, 0 +local download_cb, download_opts +package.preload["http.request"] = function() + return { + get = function(url, _, cb) + gets = gets + 1 + check_cbs[#check_cbs + 1] = { url = url, cb = cb } + return { cancel = function() end } + end, + download = function(opts, _, cb) + download_opts, download_cb = opts, cb + return { cancel = function() end } + end, + } +end +local pick_calls = 0 +package.preload["http.github"] = function() + return { + pickRelease = function(release, cb) + pick_calls = pick_calls + 1 + cb(release.url) + return { cancel = function() end } + end, + } +end + +local job_opts, job_worker +package.preload["workers.job"] = function() + return { + run = function(worker, opts) + job_worker, job_opts = worker, opts + return { cancel = function() end } + end, + } +end +local install_args +package.preload["utils.plugin_install"] = function() + return { + run = function(archive, parent, sha, opts) + install_args = { archive = archive, parent = parent, sha = sha, opts = opts } + return true, "kamare.koplugin" + end, + } +end +package.preload["utils.restart"] = function() + return { now = function() restarted = restarted + 1 end } +end + +local Kamare = require("moonsource_kavita.kamare_update") + +local hash = string.rep("a", 64) +local direct = "https://github.com/backtracker/kamare.koplugin/releases/download/v0.10.4/kamare.koplugin.zip" +local function release(tag, digest) + local asset = { + name = "kamare.koplugin.zip", + browser_download_url = "https://github.com/backtracker/kamare.koplugin/releases/download/" + .. tag .. "/kamare.koplugin.zip", + size = 2048, + } + if digest ~= false then asset.digest = "sha256:" .. hash end + return { tag_name = tag, body = "## 新增\n\n- **蓝牙翻页器**\n", assets = { asset } } +end + +---@return table|nil, any +local function check(response) + local got, got_err + check_cbs = {} + Kamare:check(function(r, e) got, got_err = r, e end) + for _idx, entry in ipairs(check_cbs) do entry.cb(response) end + flush() + return got, got_err +end + +-- 版本和 digest 先问 api.ankio.net 的转发。 +check_cbs = {} +Kamare:check(function() end) +Assert.eq(#check_cbs, 1) +Assert.eq(check_cbs[1].url, "https://api.ankio.net/gh/repos/backtracker/kamare.koplugin/releases/latest") +check_cbs[1].cb(release("v0.10.4")) +flush() + +-- 已装版本来自探测;没装 / 官方版同版本也要提示安装。 +probe_result = { ok = true, state = "enhanced", version = "0.10.4-dev" } +local parsed = check(release("v0.10.4")) +Assert.eq(parsed.installed, "0.10.4-dev") +Assert.eq(parsed.sha256, hash) +Assert.is_true(parsed.available, "开发版低于同号正式版") +probe_result = { ok = true, state = "enhanced", version = "0.10.4" } +Assert.is_false(check(release("v0.10.4")).available) +probe_result = { ok = false, state = "official", version = "0.10.4" } +Assert.is_true(check(release("v0.10.4")).available) +Assert.is_nil(check(release("v0.10.4", false)).sha256, "kamare 的 digest 可选") + +-- 已是最新:toast 带 kamare 前缀;没装:安装提示。 +local function startCheck(response) + shown, closed = {}, {} + check_cbs = {} + Kamare:manualCheck(nil) + for _idx, entry in ipairs(check_cbs) do entry.cb(response) end + flush() +end +probe_result = { ok = true, state = "enhanced", version = "0.10.4" } +startCheck(release("v0.10.4")) +Assert.matches(shown[#shown].text, "已是最新版本(kamare 0%.10%.4)") +probe_result = { ok = false, state = "missing" } +startCheck(release("v0.10.4")) +local prompt = shown[#shown] +Assert.eq(prompt.title, "更新 kamare") +Assert.matches(prompt.text, "当前未安装可用的 kamare 增强版") + +-- 装到 kamare 当前所在目录,带目录名;没有 digest 只直连。 +plugins_dir = "/mnt/us/koreader/plugins" +prompt.buttons[2].callback() +Assert.eq(download_opts.url, direct) +download_cb(true) +job_worker() +Assert.eq(install_args.sha, hash) +Assert.eq(install_args.opts.name, "kamare.koplugin") +Assert.eq(install_args.parent, plugins_dir) +job_opts.on_done() +flush() +Assert.eq(restarted, 1) + +local nosha = check(release("v0.10.4", false)) +pick_calls = 0 +Kamare:install(nosha, nil, function() end) +Assert.eq(pick_calls, 0, "没有 digest 不走镜像") + +return true diff --git a/tests/kavita/migration_spec.lua b/tests/kavita/migration_spec.lua new file mode 100644 index 0000000..ce787d9 --- /dev/null +++ b/tests/kavita/migration_spec.lua @@ -0,0 +1,108 @@ +--[[-- +Kavita 一次性迁移:卷行继承容器元数据并退出书架。 + +@module tests.moonsource_kavita.migration_spec +--]] + +local Assert = require("support.assert") +local Config = require("support.config") + +local db_path = Config.dir() .. "/kavita_migration_spec.sqlite3" +local state_path = Config.dir() .. "/settings/moonsource_kavita_meta.lua" +for _idx, suffix in ipairs({ "", "-wal", "-shm" }) do os.remove(db_path .. suffix) end +for _idx, suffix in ipairs({ "", ".old" }) do os.remove(state_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 DB = require("utils.db") +require("book.books_db") +Assert.not_nil(DB.open()) + +local function insert(source_id, stable_id, authors, intro, deleted, sync_status, path) + Assert.is_true(DB.exec([[ + INSERT INTO books (source_id, stable_id, title, authors, intro, deleted, sync_status, path) + VALUES (?, ?, ?, ?, ?, ?, ?, ?); + ]], source_id, stable_id, "书 " .. stable_id, authors, intro, deleted, sync_status, path)) +end + +insert("kavita", "10", "容器作者", "容器简介", 0, 1, nil) +insert("kavita", "10:100", nil, "", 0, 0, "/books/volume.epub") +insert("kavita", "10:101", "卷作者", "卷简介", 0, 0, nil) +insert("kavita", "10:102", nil, nil, 1, 0, nil) +insert("other", "10:100", nil, "", 0, 0, nil) + +local cfg = { base_url = "http://kavita/", api_key = "key" } +package.loaded["utils.settings"] = { + getSource = function() return cfg end, + saveSource = function() end, +} +package.loaded["source.base"] = { + loadMeta = function(id) return { id = id, name = "Kavita", type = "book" } end, + capabilities = function() return {} end, + defer = function(_self, cb, ...) + local args = { ... } + cb(unpack(args)) + return { cancel = function() end } + end, +} +package.loaded["moonsource_kavita.client"] = { new = function(options) return options end } +package.loaded["moonsource_kavita.annotation"] = {} +package.loaded["moonsource_kavita.position"] = {} +package.loaded["moonsource_kavita.stats"] = {} +package.loaded["moonsource_kavita.cache"] = { resetShelf = function() end } +package.loaded["moonsource_kavita.volume_list"] = {} +package.loaded["book.note.normalize"] = {} + +local Source = dofile((debug.getinfo(1, "S").source:match("^@(.-)/tests/") .. "/moonsource-kavita.koplugin/moonsource_kavita") .. "/source.lua") +Source.new() + +local function row(source_id, stable_id) + local authors, intro, deleted, sync_status, path = DB.rowexec([[ + SELECT authors, intro, deleted, sync_status, path FROM books + WHERE source_id=? AND stable_id=?; + ]], source_id, stable_id) + return authors, intro, tonumber(deleted), tonumber(sync_status), path +end + +local authors, intro, deleted, sync_status, path = row("kavita", "10:100") +Assert.eq(authors, "容器作者") +Assert.eq(intro, "容器简介") +Assert.eq(deleted, 1, "卷行从书架隐藏") +Assert.eq(sync_status, 1, "迁移后的远端卷行标为已同步") +Assert.eq(path, "/books/volume.epub", "保留已下载文件路径") + +authors, intro, deleted, sync_status = row("kavita", "10:101") +Assert.eq(authors, "卷作者", "保留已有作者") +Assert.eq(intro, "卷简介", "保留已有简介") +Assert.eq(deleted, 1, "所有旧卷行都从书架隐藏") +Assert.eq(sync_status, 1) + +authors, intro, deleted, sync_status = row("kavita", "10:102") +Assert.eq(authors, "容器作者", "已隐藏卷行也补齐元数据") +Assert.eq(intro, "容器简介") +Assert.eq(deleted, 1) +Assert.eq(sync_status, 0, "不改原本已隐藏行的脏状态") + +authors, intro, deleted = row("other", "10:100") +Assert.is_nil(authors, "迁移只影响 Kavita") +Assert.eq(intro, "") +Assert.eq(deleted, 0) + +local state = require("luasettings"):open( + require("datastorage"):getSettingsDir() .. "/moonsource_kavita_meta.lua") +Assert.eq(tonumber(state:readSetting("schema_version")), 1) + +insert("kavita", "10:103", nil, nil, 0, 0, nil) +Source.new() +local _, _, still_visible = row("kavita", "10:103") +Assert.eq(still_visible, 0, "schema_version 阻止重复迁移") + +DB.close() +for _idx, suffix in ipairs({ "", "-wal", "-shm" }) do os.remove(db_path .. suffix) end +for _idx, suffix in ipairs({ "", ".old" }) do os.remove(state_path .. suffix) end + +return true diff --git a/tests/kavita/on_deck_spec.lua b/tests/kavita/on_deck_spec.lua new file mode 100644 index 0000000..626f7ac --- /dev/null +++ b/tests/kavita/on_deck_spec.lua @@ -0,0 +1,171 @@ +--[[-- +extensions/moonsource-kavita.koplugin 首页组件 On Deck:在线且已配置才拉,5 分钟内复用; +两行 × 5 列封面网格(网格尺寸走 CoverCell.denseCoverMetrics / Book.widget,同首页最近阅读), +点开走月读开书;失败 / 空列表 / 离线给提示。 + +@module tests.moonsource_kavita.on_deck_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, inject-field + +local Assert = require("support.assert") +local Config = require("support.config") +local Kit = require("support.widget_stubs") +Kit.install("paper") +local Themed = require("support.theme_stubs") +Themed.install() +local Widget = require("ui/widget/widget") + +local TITLE_EXTRA = 26 +local covers = {} +package.preload["ui.widgets.book"] = function() + return { + captionExtra = function(show_title) return show_title ~= false and TITLE_EXTRA or 0 end, + widget = function(_plugin, _source, book, cw, ch, opts) + local slot_w = (opts and opts.slot_w) or cw + covers[#covers + 1] = { book = book, w = cw, h = ch, slot_w = slot_w, home = opts and opts.home } + return Widget:new{ dimen = { w = slot_w, h = ch + TITLE_EXTRA } } + end, + } +end +package.preload["ui.widgets.cover"] = function() + return { + gridCoverMaxH = function() return 320 end, + denseCoverMetrics = function(w, _budget, opts) + local cols = opts.min_cols or 5 + local gap, row_gap = 8, 10 + local slot_w = math.max(1, math.floor((w - gap * (cols - 1)) / cols)) + local cw = slot_w + local ch = math.min(math.floor(cw * 3 / 2), opts.max_h or 320) + return slot_w, cw, ch, cols, gap, row_gap, ch + opts.title_extra + end, + } +end +local opened = {} +package.preload["desktop.open"] = function() + return { book = function(_plugin, book) opened[#opened + 1] = book end } +end + +local online, configured = true, true +package.loaded["ui/network/manager"] = { isConnected = function() return online end } +local calls, reply = {}, nil +local source = { + configured = function() return configured end, + client = { + json = function(_self, method, path, query, body, cb) + calls[#calls + 1] = { method = method, path = path, query = query, body = body } + reply = cb + return { cancel = function() reply = nil end } + end, + }, +} +package.loaded["source.registry"] = { resolve = function(id) return id == "kavita" and source or nil end } + +local Deck = dofile((debug.getinfo(1, "S").source:match("^@(.-)/tests/") .. "/moonsource-kavita.koplugin/moonsource_kavita") .. "/on_deck.lua") +Assert.eq(Deck.id, "kavita.on_deck") + +local desktop = { plugin = {} } +local deck = Deck:new{} +deck:build({ desktop = desktop, plugin = desktop.plugin }, + { width = 300, height = deck:heightRange(nil, { width = 300 }).height }) +Assert.contains(Kit.texts(deck.slot), "联网后显示 Kavita 上在读的书") + +-- 激活拉一次:POST on-deck,进度按 pagesRead / pages。 +deck:activate() +Assert.len(calls, 1) +Assert.eq(calls[1].method, "POST") +Assert.eq(calls[1].path, "/api/Series/on-deck") +Assert.eq(calls[1].query.pageSize, 10) +local list = {} +for i = 1, 12 do list[i] = { id = i, name = "S" .. i, pages = 10, pagesRead = i } end +reply(list) +Assert.eq(deck.data[3].stable_id, "3") +Assert.eq(deck.data[3].source_id, "kavita") +Assert.eq(deck.data[3].percent, 30) +-- 一页 4 本(跟首页最近阅读一样),12 本分 3 页。 +Assert.eq(#covers, 4, "一页 4 本") +Assert.is_true(covers[1].home, "On Deck 走首页封面策略") +Assert.eq(covers[1].book.title, "S1") +Assert.contains(Kit.texts(deck.slot), "1 / 3") + +-- 一页 4 本、多的分页:翻到后面不该重画前面的书。 +covers = {} +deck.page = 2 +deck:refresh() +Assert.eq(#covers, 4) +Assert.eq(covers[1].book.title, "S5", "第二页从第 5 本开始") +Assert.contains(Kit.texts(deck.slot), "2 / 3") +deck.page = 3 +covers = {} +deck:refresh() +Assert.eq(#covers, 4, "最后一页 4 本") +Assert.eq(covers[1].book.title, "S9") +deck.page = 1 +covers = {} +deck:refresh() + +-- 5 分钟内重新激活不再请求;过期再拉。 +deck:deactivate() +deck:activate() +Assert.len(calls, 1) +deck.loaded_at = os.time() - 301 +deck:deactivate() +deck:activate() +Assert.len(calls, 2) + +-- 离开首页取消在飞请求;失败显示原因;空列表给提示。 +deck:deactivate() +Assert.is_nil(reply) +deck.loaded_at = nil +deck:activate() +reply(nil, "API Key 无效") +Assert.eq(covers[1].book.title, "S1", "失败保留上次的列表") +deck.data, deck.loaded_at = nil, nil +deck:deactivate() +deck:activate() +reply(nil, "API Key 无效") +Assert.contains(Kit.texts(deck.slot), "API Key 无效") +deck.loaded_at = nil +deck:deactivate() +deck:activate() +reply({}) +Assert.contains(Kit.texts(deck.slot), "Kavita 上没有在读的书") + +-- 离线 / 未配置不请求。 +local before = #calls +deck.loaded_at = nil +deck:deactivate() +online = false +deck:activate() +deck:deactivate() +online, configured = true, false +deck:activate() +Assert.len(calls, before) + +-- 点封面走月读开书。 +deck.data = { { source_id = "kavita", stable_id = "9", title = "九" } } +deck:refresh() +local taps = Kit.taps(deck.slot) +Assert.len(taps, 1) +taps[1]:onTapThemeArea() +Assert.eq(opened[1].stable_id, "9") + +-- 一页 4 本,封面按宽度分满,槽宽/封面宽一致,10 本分 3 页。 +covers = {} +online, configured = true, true +local wide = Deck:new{} +local nat = wide:heightRange(nil, { width = 568 }).height +wide:build({ desktop = desktop, plugin = desktop.plugin }, { width = 568, height = nat }) +wide:activate() +local ten = {} +for i = 1, 10 do ten[i] = { id = i, name = "S" .. i, pages = 10, pagesRead = i } end +reply(ten) +Assert.len(wide.data, 10) +Assert.eq(#covers, 4, "每页 4 本") +Assert.contains(Kit.texts(wide.slot), "1 / 3") +-- 内容高不能超过 heightRange(超了 widget 会掉出槽位)。 +Assert.is_true(wide.slot[1]:getSize().h <= nat, "内容高不超过 heightRange") +-- 每格用同一个槽宽(Book.widget 把封面居中到 slot_w),不会有一本看着变小 / 错位。 +for _i, c in ipairs(covers) do + Assert.eq(c.slot_w, covers[1].slot_w, "每格槽宽一致") + Assert.eq(c.w, covers[1].w, "每格封面宽一致") +end diff --git a/tests/kavita/position_spec.lua b/tests/kavita/position_spec.lua new file mode 100644 index 0000000..6e781c2 --- /dev/null +++ b/tests/kavita/position_spec.lua @@ -0,0 +1,90 @@ +--[[-- +extensions/moonsource-kavita.koplugin:xpointer ↔ Kavita pageNum / bookScrollId 换算。 + +@module tests.moonsource_kavita.position_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, inject-field + +local Assert = require("support.assert") +local Config = require("support.config") + +local Position = dofile((debug.getinfo(1, "S").source:match("^@(.-)/tests/") .. "/moonsource-kavita.koplugin/moonsource_kavita") .. "/position.lua") + +-- spine:DocFragment[D] = spine D-1;单 spine 书没有下标。 +Assert.eq(Position.spine("/body/DocFragment[8]/body/p[2]/text().0"), 7) +Assert.eq(Position.spine("/body[1]/DocFragment[1]/body[1]/p"), 0) +Assert.eq(Position.spine("/body/DocFragment/body/p"), 0) +Assert.is_nil(Position.spine(nil)) +Assert.is_nil(Position.spine("#_doc_fragment_3")) + +-- 上报:补全 [1]、丢文本偏移;两种 crengine 写法都认。 +Assert.eq(Position.toScrollId("/body/DocFragment[8]/body/section/p[3]/text().0"), "//body/section[1]/p[3]") +Assert.eq(Position.toScrollId("/body[1]/DocFragment[8]/body[1]/div[2]/p/text()[1].5"), "//body/div[2]/p[1]") +Assert.eq(Position.toScrollId("/body/DocFragment/body/p[4]"), "//body/p[4]") +Assert.is_nil(Position.toScrollId("/body/DocFragment[2]/body"), "body 本身没有章内位置") +Assert.is_nil(Position.toScrollId(nil)) + +-- 下行:[1] 省略;读完(pageNum == pages)落回最后一个 spine;单 spine 书不带下标。 +Assert.eq(Position.toXPointer(7, "//body/section[1]/p[3]", 10), "/body/DocFragment[8]/body/section/p[3]") +Assert.eq(Position.toXPointer(10, nil, 10), "/body/DocFragment[10]/body") +Assert.eq(Position.toXPointer(0, "//body/p[2]", 1), "/body/DocFragment/body/p[2]") +Assert.eq(Position.toXPointer(3, "id(\"x\")", 10), "/body/DocFragment[4]/body", "未解析的锚点只按 spine 定位") + +-- 往返:上报出去的锚点拉回来落在同一段。 +local here = "/body/DocFragment[5]/body/div[2]/p[7]/text().12" +Assert.eq(Position.toXPointer(Position.spine(here), Position.toScrollId(here), 9), "/body/DocFragment[5]/body/div[2]/p[7]") + +-- 网页端的 id("X"):读本地 epub 第 spine 个文档找元素路径。 +local files = { + ["META-INF/container.xml"] = [[a
b
c
前言
+甲乙丙&丁 戊己¹[3]庚辛壬癸
子丑寅卯辰巳
b", "
挪到第二章") +anchor = Position.anchor("挪到第二章", "/body/DocFragment[1]/body/p[2]", "/book.epub") +Assert.eq(anchor.pageNumber, 1, "pos0 所在 spine 没有就去邻近 spine 找") +Assert.eq(anchor.xPath, "//body/section[1]/p[2]") +Assert.is_nil(Position.anchor("不存在的文字", "/body/DocFragment[1]/body/p", "/book.epub")) +Assert.is_nil(Position.anchor("甲乙丙", "/body/DocFragment[1]/body/p", nil), "没下载过") + +files["META-INF/container.xml"] = nil +Assert.is_nil(Position.resolveScrollId("/book.epub", 1, 'id("target")'), "坏 epub 降级成只按 spine") diff --git a/tests/kavita/reconcile_spec.lua b/tests/kavita/reconcile_spec.lua new file mode 100644 index 0000000..14d38ca --- /dev/null +++ b/tests/kavita/reconcile_spec.lua @@ -0,0 +1,385 @@ +--[[-- +Kavita 统计对账:真实响应 fixture 走「拉取钩子 → replaceSynced 入库 → 展示查询」全链, +逐项对 spec 的验收基线。HTTP 与目录缓存打桩,其余全真:源(分页 / 身份判定 / 物化)、 +统计纯核心、真实 sqlite 的 reading_stats 与 books 库。 + +对账基线(research-kavita-stats-pull.md): + §2 全量逐日(29 天 / Σ=60,238s)、§3 样本 7453 逐日(13,921 + 316)、§4 系列累计。 +数字都来自实测响应(fixture 数值逐条未改),不是照实现倒推的。 + +@module tests.moonsource_kavita.reconcile_spec +--]] + +local Assert = require("support.assert") +local Config = require("support.config") +local Json = require("support.json_stub") +local Stubs = require("support.stubs") + +-- 日 / 时归属按进程时区(POSIX TZ)计算:钉死 CST-8,与 fixture 拉取时用的 Asia/Shanghai 对齐, +-- 断言就不会随宿主机时区漂移。 +local ffi = require("ffi") +ffi.cdef[[ int setenv(const char*, const char*, int); void tzset(void); ]] +ffi.C.setenv("TZ", "CST-8", 1) +ffi.C.tzset() + +local sqlite_ok = pcall(require, "lua-ljsqlite3/init") +if not sqlite_ok then + Assert.skip("当前离线环境没有 ljsqlite3 Lua 模块") +end + +-- 沙箱库:books 与 reading_stats 同库,物化行和统计行一起对账。 +local db_path = Config.dir() .. "/kavita_reconcile_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 + +-- 响应体 / 分页头走真实编解码(source_spec 的往返桩同形);books 的 meta 列也用它。 +package.loaded["json"] = nil +package.preload["json"] = function() + return { encode = Json.encode, decode = Json.decode } +end + +-- 设备时钟(POSIX → IANA 映射)与扩展配置;stats_db 也会问 merge_local_stats(本用例默认关)。 +local clock = { timezone = "CST-8" } +local cfg = { base_url = "http://kav/", api_key = " k ", libraries = { ["8"] = true, ["10"] = true } } +package.loaded["utils.settings"] = nil +package.preload["utils.settings"] = function() + local common = { active_source = "local" } + return { + get = function(key) return key == "features.clock" and clock or common end, + getSource = function() return cfg end, + } +end + +-- 插件模块走 preload:不把插件根塞进 package.path(main.lua 会顶掉月读的 main)。 +local PLUGIN = (debug.getinfo(1, "S").source:match("^@(.-)/tests/") .. "/moonsource-kavita.koplugin/moonsource_kavita") +for _idx, name in ipairs({ "client", "position", "annotation", "cache", "volume_list", "source", "stats" }) do + package.preload["moonsource_kavita" .. (name == "source" and ".source" or "." .. name)] = function() + return dofile(PLUGIN .. "/" .. (name == "source" and "source" or name) .. ".lua") + end +end + +-- HTTP:只服务阅读历史;目录全部命中缓存,物化与身份判定不发请求。 +-- 分页头与 body 同一套编解码(同真服务端:PageSize=200、总页数在响应头里)。 +local pagination_calls = {} +local sample = dofile((debug.getinfo(1, "S").source:match("^@(.*)/")) .. "/fixtures/history_all.lua") +local history = sample +local function history_pages() + local pages = { {}, {} } + for _idx, entry in ipairs(history) do + local page = #pages[1] < 200 and 1 or 2 + pages[page][#pages[page] + 1] = entry + end + return pages +end +local function query(opts, key) return opts.url:match("[?&]" .. key .. "=([^&]*)") end +package.loaded["http.request"] = { + ok = function(code) + code = tonumber(code) + return code ~= nil and code >= 200 and code < 300 + end, + header = function(res, name) + for key, value in pairs(res and res.headers or {}) do + if type(key) == "string" and key:lower() == name:lower() then return value end + end + end, + request = function(opts, cb) + local page = tonumber(query(opts, "PageNumber")) or 1 + pagination_calls[#pagination_calls + 1] = opts.url + -- 只认阅读历史:目录 / 其它接口意外被请求时返回 404(身份判定该走目录缓存, + -- 真机也是:判定结果记在状态文件里,不该为身份反复请求目录)。 + local history_call = opts.url:find("/api/Stats/reading%-history", 1) ~= nil + require("ui/uimanager"):nextTick(function() + if not history_call then + cb({ code = 404, body = "" }) + return + end + cb({ + code = 200, + body = Json.encode(history_pages()[page]), + headers = { Pagination = Json.encode({ + currentPage = page, + itemsPerPage = 200, + totalItems = #history, + totalPages = math.max(1, math.ceil(#history / 200)), + }) }, + }) + end) + return { cancel = function() end } + end, +} + +-- 目录缓存(source.toc)替身:身份判定只关心「1 章还是多章」,物化只用条目 title。 +-- 7453 用实测目录(4 卷含卷名,research §5 / series-detail);已知实测章数的系列对齐 §5; +-- 其余按云端读到的章构造 —— 判定结果只影响单书身份粒度,不影响账户日桶。 +local CLOUD_TITLES = { + ["7453"] = { + { chapterId = 11271, title = "2001:太空漫游" }, + { chapterId = 11273, title = "2010:太空漫游" }, + { chapterId = 11270, title = "2061:太空漫游" }, + { chapterId = 11272, title = "3001:太空漫游" }, + }, +} +local TOC_COUNTS = { ["7453"] = 4, ["10634"] = 27, ["7460"] = 2, ["10720"] = 5, ["8661"] = 1, ["7606"] = 1 } +local tocs = {} +for _idx, entry in ipairs(sample) do + local series_id = tostring(entry.seriesId) + local toc = tocs[series_id] + if not toc then toc = {}; tocs[series_id] = toc end + -- 全量取并:同一系列各条会话可能各读不同章,真目录里这些章都在。 + for _i, chapter in ipairs(entry.chapters) do + if chapter.chapterId then + local known = false + for _k, item in ipairs(toc) do + if item.chapterId == chapter.chapterId then known = true end + end + if not known then toc[#toc + 1] = { chapterId = chapter.chapterId } end + end + end +end +for series_id, entries in pairs(CLOUD_TITLES) do tocs[series_id] = entries end +for series_id, count in pairs(TOC_COUNTS) do + -- 补齐到实测章数:补齐条目不带 chapterId,只有 #toc 参与单卷 / 多卷判定。 + while #tocs[series_id] < count do tocs[series_id][#tocs[series_id] + 1] = {} end +end +package.loaded["source.toc"] = { + read = function(_sid, series_id) return tocs[tostring(series_id)] end, + put = function(_sid, series_id, list) tocs[tostring(series_id)] = list; return true end, +} + +-- 统计状态文件(上次身份 + 章数判定)是上一轮的残留:连 .old 备份一起清, +-- 清了才是「首次拉取」(LuaSettings 读不到主文件会回落 .old)。 +local STATS_STATE = require("datastorage"):getSettingsDir() .. "/moonsource_kavita_stats.lua" +local function clearStatsState() + for _idx, suffix in ipairs({ "", ".old" }) do os.remove(STATS_STATE .. suffix) end +end +clearStatsState() + +local Base = require("utils.db") +local StatsDB = require("book.stats_db") +local BookDB = require("book.books_db") +local ProgressDB = require("book.progress_db") +local Kavita = require("moonsource_kavita.source") +Assert.not_nil(Base.open()) + +-- 书架容器行(书架同步的产物):统计侧只当物化标题 / 元数据来源。作者只给断言用到的那本。 +local function container(id, title, authors) + Assert.is_true(BookDB.upsertRemote({ source_id = "kavita", stable_id = id, title = title, + authors = authors, deleted = 0 }, false, true)) +end +container("7453", "太空漫游", "阿瑟·克拉克") +container("8661", "人类简史") +container("7460", "三国演义") +container("10634", "大剑") + +-- 本机逐页记录:10-14 已上报(云端会话已含,不能再算一遍);10-17 拉取后才读(未上报)。 +local L1_T = os.time({ year = 2026, month = 10, day = 14, hour = 21 }) +Assert.is_true(StatsDB.add({ + source_id = "kavita", stable_id = "7453:11273", record_type = "page", + page = 30, start_time = L1_T, duration = 900, total_pages = 150, +}, StatsDB.SYNCED)) + +-- 固定拉取时刻(2026-10-16 20:00 本地,晚于全量最后一天):只看 nil 参数的 os.time。 +local FETCHED = 1792152000 +local real_time = os.time +os.time = function(t) + if t == nil then return FETCHED end + return real_time(t) +end +local source = Kavita.new() + +--- 一次完整的统计同步:拉取 → 入库 → commit(状态文件只在入库成功后前进)。 +---@return BookStatsPullResult +local function pull() + local result, err + source:pullStatsAsync(function(res, pull_err) result, err = res, pull_err end) + Stubs.flush() + Assert.not_nil(result, err) + Assert.not_nil(StatsDB.replaceSynced("kavita", result.replace, result.rows), "入库必须成功") + result.commit() + return result +end + +local pulled = pull() + +--- 逐日聚合(dailyBySource):ymd → { seconds, pages }。 +local function calendar() + local rows = {} + for _idx, row in ipairs(StatsDB.dailyBySource("kavita")) do rows[row.ymd] = row end + return rows +end + +-- ① 单书累计:与云端 Σ 一致(§3 的 7453 两卷 / §4 的系列累计)。 +-- 10-14 的本地 900s 已含在云端快照里(sync_status=1 且早于拉取时刻):不加第二遍。 +Assert.eq(StatsDB.summaryByBook("kavita", "7453:11273").total_seconds, 13921, "样本卷累计 = 云端 Σ") +Assert.eq(StatsDB.summaryByBook("kavita", "7453:11271").total_seconds, 316, "同系列另一卷(只在其它设备读过)") +Assert.eq(StatsDB.summaryByBook("kavita", "7453").total_seconds, 0, "多卷系列不读在容器行上") +Assert.eq(StatsDB.summaryByBook("kavita", "8661").total_seconds, 3555, "单卷系列读在 series 行(§4)") +Assert.eq(StatsDB.summaryByBook("kavita", "7460:11285").total_seconds, 9517, "多章目录 → 逐卷身份(§4)") +-- 页数:云端会话的 pagesRead + 未被会话覆盖的本地页(18 号票)。10-14 的本地 1 页已上报、 +-- 当天有会话覆盖,不再加;22 是该卷各云端会话 pagesRead 之和。 +Assert.eq(StatsDB.summaryByBook("kavita", "7453:11273").pages, 22, "单书页数 = 云端会话 pagesRead 之和") + +-- ② 日历逐日与 §2 一致;合计 = __kv:total。 +-- 页数口径与 §2 的 hist_p 在 9-19 / 9-24 / 9-29 差 1 / 1 / 2 页:那 4 页来自零时长条目, +-- 设计上整条丢弃(§4 已记「零时长条目 100 条,其中带页数 4 条合计 4 页」)。 +local CLOUD_DAYS = { + { "2026-09-18", 920, 5 }, { "2026-09-19", 2824, 10 }, { "2026-09-20", 2813, 25 }, + { "2026-09-21", 1183, 18 }, { "2026-09-22", 1682, 25 }, { "2026-09-23", 406, 18 }, + { "2026-09-24", 1179, 114 }, { "2026-09-25", 10, 3 }, { "2026-09-26", 1378, 71 }, + { "2026-09-27", 755, 0 }, { "2026-09-28", 104, 0 }, { "2026-09-29", 7942, 312 }, + { "2026-09-30", 6640, 22 }, { "2026-10-01", 643, 23 }, { "2026-10-03", 1104, 25 }, + { "2026-10-04", 638, 1 }, { "2026-10-05", 195, 0 }, { "2026-10-06", 809, 0 }, + { "2026-10-07", 503, 0 }, { "2026-10-08", 3663, 10 }, { "2026-10-09", 1092, 93 }, + { "2026-10-10", 363, 10 }, { "2026-10-11", 649, 26 }, { "2026-10-12", 1803, 103 }, + { "2026-10-13", 4514, 244 }, { "2026-10-14", 11665, 120 }, { "2026-10-15", 4541, 118 }, + { "2026-10-16", 220, 6 }, +} +local days = calendar() +local day_count = 0 +for _ymd in pairs(days) do day_count = day_count + 1 end +Assert.eq(day_count, #CLOUD_DAYS, "只有有有效时长的日子落桶(10-02 三条会话全零时长)") +Assert.is_nil(days["2026-10-02"], "零时长日不留桶") +-- 本地逐页记录按条累加;云端日桶显式 0 页不能被补成 1 页。 +local ZERO_PAGE_DAYS = 0 +for _idx, expected in ipairs(CLOUD_DAYS) do + local row = days[expected[1]] + Assert.not_nil(row, "缺日桶 " .. expected[1]) + Assert.eq(row.seconds, expected[2], "日时长 " .. expected[1]) + local stored_pages = expected[3] + (expected[1] == "2026-10-14" and 1 or 0) + if expected[3] == 0 then ZERO_PAGE_DAYS = ZERO_PAGE_DAYS + 1 end + Assert.eq(row.pages, stored_pages, "日页数增量 " .. expected[1]) +end +Assert.eq(ZERO_PAGE_DAYS, 5, "云端 0 页日就 5 天(09-27 / 09-28 / 10-05~10-07)") +local calendar_sum, calendar_pages = 0, 0 +for _ymd, row in pairs(days) do + calendar_sum = calendar_sum + row.seconds + calendar_pages = calendar_pages + row.pages +end +Assert.eq(StatsDB.summaryBySource("kavita").total_pages, calendar_pages, "总页数 = 日历逐日之和") +Assert.eq(calendar_sum, 60238, "各日之和 = 云端全量 Σ(§2)") +local total_row +for _idx, row in ipairs(pulled.rows) do + if row.record_type == "total" then total_row = row end +end +Assert.eq(total_row.duration, calendar_sum, "总时长 = __kv:total") +Assert.eq(StatsDB.summaryBySource("kavita").total_seconds, calendar_sum, "总览合计 = 日历合计") + +-- 分页:分页头说 2 页就拉 2 页,参数形态同真服务端。 +Assert.len(pagination_calls, 2) +Assert.matches(pagination_calls[1], "Libraries=8") +Assert.matches(pagination_calls[1], "Libraries=10") +Assert.matches(pagination_calls[1], "PageNumber=1&PageSize=200") +Assert.matches(pagination_calls[1], "TimeZoneId=Asia%%2FShanghai") +Assert.matches(pagination_calls[2], "PageNumber=2&") + +-- ③ 当日书单:云端读过、本机从没打开过的书也在;单书逐日与云端一致。 +local by_day_book = {} +for _idx, row in ipairs(StatsDB.dailyBooksBySource("kavita")) do + by_day_book[row.ymd] = by_day_book[row.ymd] or {} + by_day_book[row.ymd][row.stable_id] = row +end +Assert.eq(by_day_book["2026-09-29"]["7453:11271"].seconds, 316, "只在其它设备读过的卷进当日书单") +Assert.eq(by_day_book["2026-09-29"]["7453:11271"].max_total_pages, 0, "只有云端时长的那天没有页坐标") +Assert.eq(by_day_book["2026-09-30"]["8661"].seconds, 2885, "单卷系列按 series 身份进当日书单") +Assert.eq(by_day_book["2026-10-15"]["10634:17868"].seconds, 531, "多卷按章拆到各卷(210 + 321)") + +-- 12 号票物化的隐藏身份行:书单里的云端书能显示书名(不是裸 ID),且不上架 / 不标脏 / 不写进度。 +local cloud_only = BookDB.get("kavita", "7453:11271") +Assert.eq(cloud_only.title, "太空漫游 · 2001:太空漫游", "标题 = 系列 · 卷名") +Assert.eq(cloud_only.authors, "阿瑟·克拉克", "作者继承容器行") +Assert.eq(cloud_only.deleted, 1, "隐藏身份行:不进书架") +Assert.eq(cloud_only.sync_status, 1, "隐藏身份行:不标脏、不推云端") +Assert.is_nil(ProgressDB.get("kavita", "7453:11271"), "统计拉取不写进度:不会因此冒进「最近阅读」") +local shelf_ids = BookDB.libraryStableIdsBySource("kavita") +local materialized_on_shelf = false +for _idx, id in ipairs(shelf_ids) do + if id == "7453:11271" or id == "7453:11273" then materialized_on_shelf = true end +end +Assert.is_false(materialized_on_shelf, "物化行不是书架成员") +-- 容器行缺失的系列:物化跳过(12 号票语义),统计行照写。 +Assert.is_nil(BookDB.get("kavita", "7910:11896"), "没有容器行就不物化") +Assert.eq(by_day_book["2026-09-29"]["7910:11896"] ~= nil, true, "不物化不影响统计行") + +-- 单书逐日(详情页「最近几天」)与云端 §3 一致;10-14 = 云端 6734(本地 900 已含,不再加)。 +local function book_days(stable_id) + local rows, count = {}, 0 + for _idx, row in ipairs(StatsDB.dailyByBook("kavita", stable_id, 40)) do + rows[row.ymd] = row.seconds + count = count + 1 + end + return rows, count +end +local sample_days = { + ["2026-10-05"] = 195, ["2026-10-07"] = 503, ["2026-10-08"] = 2036, ["2026-10-11"] = 512, + ["2026-10-13"] = 979, ["2026-10-14"] = 6734, ["2026-10-15"] = 2962, +} +local sample_rows, sample_day_count = book_days("7453:11273") +Assert.eq(sample_rows["2026-10-14"], 6734, "云+本地同一天不双计") +Assert.eq(sample_day_count, 7, "只列有数据的日子(零时长日不出现)") +for ymd, seconds in pairs(sample_days) do Assert.eq(sample_rows[ymd], seconds, "单书逐日 " .. ymd) end +Assert.eq(book_days("7453:11271")["2026-09-29"], 316) + +-- ④ 时段:云端时段桶 + 本机逐页记录,合并口径与按天一致。 +local hourly = StatsDB.hourlyBySource("kavita") +local hourly_days = 0 +for _ymd in pairs(hourly) do hourly_days = hourly_days + 1 end +Assert.eq(hourly["2026-10-14"][22], 1043, "10-14 21 点:云端该格 1043s(本机同格已上报,不叠加)") +Assert.eq(hourly_days, 28, "有云端时长的每天都有时段分布") +Assert.eq(hourly["2026-09-18"][18], 738, "纯云端的日子也有时段(21 点 174 + 17 点 738 …)") +-- 日页面「标题时长 = 时段图逐格之和」:逐日必须对得上 +for _idx, row in ipairs(StatsDB.dailyBySource("kavita")) do + local sum = 0 + for h = 1, 24 do sum = sum + (hourly[row.ymd] and hourly[row.ymd][h] or 0) end + Assert.eq(sum, row.seconds, "时段逐日之和 = 日历 " .. row.ymd) +end + +-- ⑤ 拉取后本地新读:云端快照 + 增量,两边都不双计。 +local L2_T = FETCHED + 5 * 3600 +Assert.is_true(StatsDB.add({ + source_id = "kavita", stable_id = "7453:11273", record_type = "page", + page = 31, start_time = L2_T, duration = 90, total_pages = 150, +}, StatsDB.PENDING)) +Assert.eq(StatsDB.summaryByBook("kavita", "7453:11273").total_seconds, 13921 + 90, "快照 + 拉取后新读") +Assert.eq(book_days("7453:11273")["2026-10-17"], 90, "增量单落到它自己的日子") +Assert.eq(calendar()["2026-10-17"].seconds, 90, "日历同样叠加增量") +Assert.eq(StatsDB.summaryBySource("kavita").total_seconds, 60238 + 90, "总览 = __kv:total + 拉取后新读") +Assert.eq(StatsDB.hourlyBySource("kavita")["2026-10-17"][2], 90, "增量进时段(1 点 = 第 2 格)") + +-- 再拉一次(本次只回样本 7453):整本替换不累加,云端消失的日桶清掉,本地逐页记录不动。 +history = dofile((debug.getinfo(1, "S").source:match("^@(.*)/")) .. "/fixtures/history_7453.lua") +pulled = pull() +Assert.not_nil(pulled.rows[1]) +Assert.eq(StatsDB.summaryByBook("kavita", "7453:11273").total_seconds, 13921 + 90, "重拉不累加,增量仍在") +Assert.eq(StatsDB.summaryByBook("kavita", "8661").total_seconds, 0, "云端消失的书回落本地(没有本地记录 = 0)") +local again = calendar() +Assert.is_nil(again["2026-09-18"], "上一轮的云端日桶被全量重拉清掉") +Assert.eq(again["2026-10-14"].seconds, 6734, "样本日重写为本次回包值") +Assert.eq(again["2026-10-17"].seconds, 90, "本地逐页记录不受替换影响") +Assert.eq(StatsDB.hourlyBySource("kavita")["2026-10-14"][22], 716, "时段格重写为本次回包值(本机同格已上报,不叠加)") +Assert.is_nil(StatsDB.hourlyBySource("kavita")["2026-09-18"], "回包里消失的时段格清掉") + +-- 12 号票物化标题的第二轮回归:二次拉取时章数已判定(不再读目录),卷名必须取自状态文件里的 +-- 持久化卷名 —— 不能退容器名,更不能把上一轮物化出的好标题改写成「太空漫游 · 太空漫游」。 +Assert.eq(BookDB.get("kavita", "7453:11271").title, "太空漫游 · 2001:太空漫游", "二次拉取后标题不回退") +Assert.eq(BookDB.get("kavita", "7453:11273").title, "太空漫游 · 2010:太空漫游") + +-- 升级路径:老状态文件只有章数、没有卷名(本机第一轮物化时还没有持久化)。此时兜底标题 +-- 只能用于新行,不得覆盖既有行的真实标题。 +local stats_state = require("luasettings"):open(STATS_STATE) +stats_state:saveSetting("titles", {}) +stats_state:flush() +pulled = pull() +Assert.eq(BookDB.get("kavita", "7453:11271").title, "太空漫游 · 2001:太空漫游", + "没有持久化卷名时,兜底标题不覆盖既有标题") + +os.time = real_time +Base.close() +for _idx, suffix in ipairs({ "", "-wal", "-shm" }) do os.remove(db_path .. suffix) end +clearStatsState() diff --git a/tests/kavita/reviews_spec.lua b/tests/kavita/reviews_spec.lua new file mode 100644 index 0000000..b98d117 --- /dev/null +++ b/tests/kavita/reviews_spec.lua @@ -0,0 +1,59 @@ +--[[-- Kavita 系列书评:章节过滤、归属校验与卷共用缓存。 @module tests.moonsource_kavita.reviews_spec --]] +local Assert = require("support.assert") +local Stubs = require("support.stubs") +package.loaded.json = require("support.json_stub") +local Mapper = require("moonsource_kavita.mapper") +local wire = { reviews = { + { body = "
Book review
", tagline = "Title", chapterId = 0, seriesId = 5, + username = "Reader", rating = 4, totalVotes = 3, isExternal = false }, + { body = "Chapter review", chapterId = 8, seriesId = 5, username = "Reader" }, + { body = "External book review", chapterId = 0, seriesId = 0, + username = "External", isExternal = true }, +} } +local page, err = Mapper.bookReviewPage(wire, "5") +Assert.is_nil(err) +Assert.len(page.items, 2) +Assert.eq(page.items[1].text, "Title\nBook review") +Assert.eq(page.items[1].grade, 4) +Assert.eq(page.items[1].likes, 3) +Assert.eq(page.items[1].time, "", "协议无日期,不编造日期") +Assert.eq(page.items[2].text, "External book review") +Assert.len(Mapper.bookReviewPage({ reviews = {} }, "5").items, 0) +for _idx, bad in ipairs({ + {}, { reviews = { { body = "Bad", username = "Reader", chapterId = 0, seriesId = 99 } } }, + { reviews = { { body = false } } }, +}) do + local value, reason = Mapper.bookReviewPage(bad, "5") + Assert.is_nil(value) + Assert.eq(reason, "响应无效") +end +local source = require("moonsource_kavita.source").new() +local connected, requests, failed = true, 0, false +package.loaded["ui/network/manager"] = { isConnected = function() return connected end } +source.client.json = function(_self, method, path, query, _body, cb) + requests = requests + 1 + Assert.eq(method, "GET") + Assert.eq(path, "/api/Metadata/series-detail-plus") + Assert.eq(query.seriesId, 5) + if failed then cb(nil, "server failed") else cb(wire) end + return { cancel = function() end } +end +source:bookReviewsAsync({ source_id = "kavita", stable_id = "5:8" }, function(value, reason) + page, err = value, reason +end) +Assert.is_nil(err) +Assert.len(page.items, 2) +connected = false +source:bookReviewsAsync({ source_id = "kavita", stable_id = "5:9" }, function(value, reason) + page, err = value, reason +end) +Stubs.flush() +Assert.is_nil(err) +Assert.len(page.items, 2) +Assert.eq(requests, 1, "两个卷使用所属系列的整书缓存") +connected, failed = true, true +source:bookReviewsAsync({ source_id = "kavita", stable_id = "5" }, function(value, reason) + page, err = value, reason +end) +Assert.is_nil(page) +Assert.eq(err, "server failed") diff --git a/tests/kavita/setting_spec.lua b/tests/kavita/setting_spec.lua new file mode 100644 index 0000000..70d2f87 --- /dev/null +++ b/tests/kavita/setting_spec.lua @@ -0,0 +1,644 @@ +--[[-- +Kavita 设置页:服务器 / API Key / 书库 / 漫画缓存 / 进度心跳 / 请求超时 / 连接测试。 + +@module tests.moonsource_kavita.setting_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, inject-field + +local Assert = require("support.assert") + +local cfg = {} +local saved = 0 +local invalidated = 0 +local events = {} +package.preload["utils.settings"] = function() + return { + getSource = function() return cfg end, + saveSource = function(_, value) + cfg = value + saved = saved + 1 + events[#events + 1] = "save" + end, + } +end +package.preload["source.registry"] = function() + return { invalidate = function() invalidated = invalidated + 1 end } +end +-- 源模块只在设置行里读两个默认值;真常量由 client_spec / source_spec 钉住。 +-- 「测试连接」还要走 client:request,返回内容由 request_reply 控制。 +local request_reply = { version = "0.9.0" } +package.preload["moonsource_kavita.client"] = function() + return { + DEFAULT_TIMEOUT = 60, + new = function() + return { + api_key = "k", + configured = function() return true end, + request = function(_, _method, _path, _query, _body, callback) + callback(request_reply.version, request_reply.err) + end, + } + end, + } +end +package.preload["ui/network/manager"] = function() + return { isConnected = function() return true end } +end +-- 同步删除的忙碌窗会先强制重绘再动手;占用统计在下一拍算(03 E),测试里手动 flush。 +local repaints = 0 +local pending_ticks = {} +local function flush() + while #pending_ticks > 0 do + local tick = table.remove(pending_ticks, 1) + tick() + end +end +package.preload["ui/uimanager"] = function() + return { + forceRePaint = function() repaints = repaints + 1 end, + nextTick = function(_, fn) pending_ticks[#pending_ticks + 1] = fn end, + } +end +package.preload["moonsource_kavita.source"] = function() + return { DEFAULT_HEARTBEAT_INTERVAL = 30 } +end +package.preload["ui.themes.widgets.row"] = function() + return { widget = function(opts) return opts end, note = function(_width, text) return { text = text } end } +end +package.loaded["ui.themes"] = nil +package.preload["ui.themes"] = function() + return { + current = function() + return { space = { md = 8 }, color = { muted = 1, page = 2 } } + end, + px = function(n) return n end, + } +end +package.loaded["ui/geometry"] = nil +package.preload["ui/geometry"] = function() + return { new = function(_, opts) return opts end } +end +package.loaded["ui/widget/container/centercontainer"] = nil +package.preload["ui/widget/container/centercontainer"] = function() + return { new = function(_, opts) return opts end } +end +package.loaded["ui.themes.widgets.text"] = nil +package.preload["ui.themes.widgets.text"] = function() + return { + box = function(_, text, _width, _opts) + return { text = text, getSize = function() return { h = 10 } end } + end, + } +end + +-- 缓存适配层:探测 / 详情 / 保存后镜像;真实现由 cache_spec 钉住。 +local probe_result = { ok = false, state = "missing" } +local feature_text = "缓存(离线阅读与清理) · 双页拆分 · 裁切边框" +local mirror_failed = false +local register_calls, register_ok = {}, true +local available = {} +local summary_result +local summary_all_result +local chapters_result = {} +local delete_calls, delete_all_calls = {}, 0 +local delete_ok, delete_code = true, nil +local delete_all_ok, delete_all_code, delete_all_detail = true, nil, nil +-- 占用 / 计划只在详情页各取一次(06 B 的「占用只算一次」)。 +local summary_calls, summary_all_calls, chapters_calls = 0, 0, 0 +package.preload["moonsource_kavita.cache"] = function() + return { + probe = function() return probe_result end, + featureText = function() return feature_text end, + pluginsDir = function() return "/fake/plugins" end, + reprobe = function() return probe_result end, + mirrorFailed = function() return mirror_failed end, + registerServer = function(base_url, api_key) + register_calls[#register_calls + 1] = { base_url = base_url, api_key = api_key } + events[#events + 1] = "register" + if register_ok then return "srv-1" end + return nil, "settings_write_failed" + end, + available = function(cap) return available[cap] == true end, + summary = function() + summary_calls = summary_calls + 1 + return summary_result + end, + summaryAll = function() + summary_all_calls = summary_all_calls + 1 + return summary_all_result + end, + chapters = function() + chapters_calls = chapters_calls + 1 + return chapters_result + end, + plan = function(entries, filter, toc_read) + local out = { chapters = 0, bytes = 0, ids = {}, queued = 0, open = false } + for __, entry in ipairs(entries or {}) do + local pages = tonumber(entry.pages) or 0 + local server = toc_read and (tonumber(toc_read[tostring(entry.chapterId)]) or 0) or 0 + local read = entry.read == true or (pages > 0 and server >= pages) + if filter ~= "read" or read then + out.chapters = out.chapters + 1 + out.bytes = out.bytes + (tonumber(entry.bytes) or 0) + out.ids[#out.ids + 1] = entry.chapterId + if entry.queued then out.queued = out.queued + 1 end + if entry.open then out.open = true end + end + end + return out + end, + delete = function(ids) + delete_calls[#delete_calls + 1] = ids + if not delete_ok then return nil, delete_code, "nope" end + local wanted = {} + for __, id in ipairs(ids or {}) do wanted[tostring(id)] = true end + local kept = {} + for __, entry in ipairs(chapters_result) do + if not wanted[tostring(entry.chapterId)] then kept[#kept + 1] = entry end + end + chapters_result = kept + return true + end, + deleteAll = function() + delete_all_calls = delete_all_calls + 1 + if delete_all_ok then return true, nil, nil, delete_all_detail end + return nil, delete_all_code, "nope" + end, + resetShelf = function() end, + capabilityNames = function(caps, separator) + local names = {} + for name, on in pairs(caps or {}) do + if on == true then names[#names + 1] = tostring(name) end + end + table.sort(names) + return #names > 0 and table.concat(names, separator or ",") or "none" + end, + sizeText = function(bytes) + local value = tonumber(bytes) + if not value then return "未知" end + return string.format("%.1f MB", value / (1024 * 1024)) + end, + } +end +local Themed = require("support.theme_stubs") +Themed.install() + +-- kamare 在线更新:设置页只负责把行接上,网络 / 安装流程由 kamare_update_spec 钉住。 +local kamare_started = 0 +package.preload["moonsource_kavita.kamare_update"] = function() + return { + manualCheck = function() kamare_started = kamare_started + 1 end, + } +end + +local Config = require("support.config") +local PLUGIN = (debug.getinfo(1, "S").source:match("^@(.-)/tests/") .. "/moonsource-kavita.koplugin/moonsource_kavita") +package.preload["moonsource_kavita.setting"] = function() + return dofile(PLUGIN .. "/setting.lua") +end +package.preload["moonsource_kavita.busy"] = function() + return dofile(PLUGIN .. "/busy.lua") +end + +local overlays, shelf_events, overlay_updates = {}, {}, 0 +local fake_desktop = { + settings_overlay = nil, + onEvent = function(_, event) shelf_events[#shelf_events + 1] = event end, +} +package.preload["desktop.pages.setting.overlay"] = function() + return { + push = function(desktop, spec) + overlays[#overlays + 1] = spec + desktop.settings_overlay = { + updateView = function() overlay_updates = overlay_updates + 1 end, + } + end, + } +end + +local Setting = require("moonsource_kavita.setting") + +local rows = Setting.rows({ path = PLUGIN, desktop = fake_desktop }) +-- 顺序用文案钉住(索引不再稳定),「漫画缓存」插在「书库」之后。 +local titles = {} +for _idx, make in ipairs(rows) do titles[#titles + 1] = make(600).title end +Assert.eq(#rows, 7, "服务器 / API Key / 书库 / 漫画缓存 / 进度心跳 / 请求超时 / 连接测试") +Assert.eq(table.concat(titles, "|"), + "服务器地址|API Key|书库|漫画缓存|进度心跳间隔|请求超时|测试连接", + "「漫画缓存」紧跟「书库」") + +-- 03 原型的三块分组:连接 / 缓存与同步 / 诊断。 +local sections = Setting.sections({ path = PLUGIN, desktop = fake_desktop }) +Assert.eq(#sections, 3, "设置页分三块") +local grouped = {} +for _idx, section in ipairs(sections) do + local names = {} + for _row_idx, make in ipairs(section.rows) do names[#names + 1] = make(600).title end + grouped[#grouped + 1] = section.title .. ":" .. table.concat(names, ",") +end +Assert.eq(table.concat(grouped, "|"), + "连接:服务器地址,API Key,书库|缓存与同步:漫画缓存,进度心跳间隔,请求超时|诊断:测试连接", + "分组与原型一致,扁平的 rows 顺序不变") + +--- 按标题找行(索引会随增删漂移)。 +---@param title string +---@return table +local function rowAt(title) + for _idx, make in ipairs(rows) do + local row = make(600) + if row.title == title then return row end + end + error("没有这一行: " .. title) +end + +Assert.eq(Setting.remote[1].key, "base_url") +Assert.eq(Setting.remote[2].key, "api_key") +Assert.is_true(Setting.remote[2].secret) +-- 远程管理网页表单只含连接配置;开关要在设备上调。 +Assert.len(Setting.remote, 2, "远程管理表单只有服务器地址与 API Key") + +-- 进度心跳:默认 30 秒,可调;0 = 关闭阅读期心跳。 +local hb = rowAt("进度心跳间隔") +Assert.eq(hb.kind, "nav") +Assert.eq(hb.status, "30 秒") +Assert.is_true(hb.status_on) +-- 副标题单行截断(行里有状态 + 箭头,文字位很窄),必须短到放得下;「为什么」在输入框提示里。 +Assert.eq(hb.subtitle, "阅读时补推进度,0 关闭") +hb.callback() +local spin = Themed.last("spin") +Assert.eq(spin.fields[1].value, 30) +Assert.eq(spin.fields[1].step, 10, "10 秒一档") +Assert.eq(spin.fields[1].min, 0) +Assert.eq(spin.fields[1].max, 600) +Assert.eq(spin.fields[1].label, "秒") +spin.callback(120) +Assert.eq(cfg.heartbeat_interval, 120) +Assert.eq(rowAt("进度心跳间隔").status, "120 秒") +Assert.eq(spin.shown and saved, 1, "保存一次") + +spin.callback(0) +Assert.eq(cfg.heartbeat_interval, 0, "0 落盘成关闭") +local off = rowAt("进度心跳间隔") +Assert.eq(off.status, "已关闭") +Assert.is_false(off.status_on) + +spin.callback(30) +Assert.is_nil(cfg.heartbeat_interval, "回到默认值不落盘") + +-- 请求超时:默认 60 秒,10 秒一档。 +local to = rowAt("请求超时") +Assert.eq(to.status, "60 秒") +Assert.is_false(to.status_on, "默认值不高亮") +to.callback() +spin = Themed.last("spin") +Assert.eq(spin.fields[1].value, 60) +Assert.eq(spin.fields[1].step, 10, "10 秒一档") +Assert.eq(spin.fields[1].min, 10) +spin.callback(180) +Assert.eq(cfg.timeout, 180) +Assert.eq(rowAt("请求超时").status, "180 秒") +Assert.is_true(rowAt("请求超时").status_on) +spin.callback(60) +Assert.is_nil(cfg.timeout, "回到默认值不落盘") + +Assert.eq(saved, 5) +Assert.eq(invalidated, 5, "每次保存都作废源实例,新配置立即生效,但不广播 SourceChanged") + +---------------------------------------------------------------------- +-- 漫画缓存:七态(含旧接口/镜像失败)+ 只读详情 + 09 手动安装说明。 +---------------------------------------------------------------------- +local function checkStatus(probe, expected, on, mirror) + probe_result = probe + mirror_failed = mirror == true + local row = rowAt("漫画缓存") + Assert.eq(row.kind, "nav") + Assert.eq(row.status, expected) + Assert.eq(row.status_on, on, expected) +end + +checkStatus({ ok = false, state = "missing" }, "未安装 / 未启用", false) +checkStatus({ ok = false, state = "official" }, "官方版(无缓存接口)", false) +checkStatus({ ok = false, state = "incompatible", api_version = 2 }, "版本不兼容", false) +checkStatus({ ok = true, state = "enhanced", api_version = 1, version = "0.10.0-dev", + capabilities = { chapters = true, delete = true, delete_all = true } }, + "增强版 v0.10.0-dev", true) +-- 旧接口:有 kamarecache 但没有 chapters / delete,清理不可用,不高亮。 +checkStatus({ ok = true, state = "enhanced", api_version = 1, version = "0.9.22", + capabilities = { status = true, summary = true } }, + "增强版 v0.9.22(旧接口)", false) +checkStatus({ ok = true, state = "enhanced", api_version = 1 }, "增强版(旧接口)", false) +checkStatus({ ok = true, state = "enhanced", api_version = 1, version = "0.10.0-dev" }, + "配置同步失败", false, true) + +-- 详情页:状态 → 清理;增强态不显示安装说明。 +local MB = 1024 * 1024 +cfg.base_url, cfg.api_key = "http://kav", "k" +local cache_path = "/fake/plugins/kamare.koplugin/src/kamarecache.lua" +probe_result = { + ok = true, state = "enhanced", api_version = 1, version = "0.10.0-dev", + capabilities = { open = true, index = true, status = true, summary = true, + chapters = true, delete = true, delete_all = true }, + path = cache_path, +} +mirror_failed = false +available = { summary = true } +summary_result = { used = 3 * MB, available = 9 * MB, chapters = 12 } +summary_all_result = { used = 4 * MB, available = 9 * MB, chapters = 15 } +chapters_result = { + { chapterId = 1, pages = 10, bytes = 1 * MB, read = false, queued = false, open = false }, + { chapterId = 2, pages = 10, bytes = 2 * MB, read = true, queued = false, open = false }, +} + +local function findSection(sections, title) + for __, section in ipairs(sections or {}) do + if section.title == title then return section end + end +end + +local function sectionRows(sections, title) + local section = findSection(sections, title) + local out = {} + for i, make in ipairs(section and section.rows or {}) do out[i] = make(600) end + return out +end + +local function statusOf(rows_list, title) + for __, row in ipairs(rows_list) do + if row.title == title then return row end + end +end + +--- 最近一次详情页的最终 sections:先取一拍(触发占用统计),flush 后再取一次。 +---@return BookThemeSection[] +local function currentSections() + overlays[#overlays].sections() + flush() + return overlays[#overlays].sections() +end + +rowAt("漫画缓存").callback() +local page = overlays[#overlays] +Assert.not_nil(page, "详情走叠层,不再用 ConfirmBox") +Assert.eq(page.title, "漫画缓存") +summary_calls, summary_all_calls, chapters_calls = 0, 0, 0 +overlay_updates = 0 +local pending_sections = page.sections() +Assert.eq(summary_calls + summary_all_calls, 0, "先画「正在统计…」,不在这一拍走盘") +Assert.eq(statusOf(sectionRows(pending_sections, "状态"), "缓存占用").subtitle, "正在统计…") +Assert.eq(chapters_calls, 1, "清理计划一次 chapters() 取全") +flush() +Assert.eq(summary_calls, 1, "下一拍算本服务器占用") +Assert.eq(summary_all_calls, 1, "「清理全部」的合计也算出来") +Assert.eq(overlay_updates, 1, "算完刷新叠层") +local sections = page.sections() +Assert.eq(chapters_calls, 2, "重画不重算占用,只重取计划") +local status_rows = sectionRows(sections, "状态") +local version_row = statusOf(status_rows, "kamare 增强版") +Assert.eq(version_row.status, "0.10.0-dev") +Assert.is_true(version_row.chevron, "版本行可点") +Assert.eq(version_row.subtitle, "点按检查 kamare 增强版更新") +version_row.callback() +Assert.eq(kamare_started, 1, "版本行交给 kamare 在线更新模块") +Assert.eq(statusOf(status_rows, "增强版功能").subtitle, feature_text, "功能清单原样显示") + +-- 清单缺失 / 不合法:不显示整行,版本行不受影响。 +feature_text = nil +local without_features = sectionRows(page.sections(), "状态") +Assert.is_nil(statusOf(without_features, "增强版功能"), "没有清单隐藏功能行") +Assert.not_nil(statusOf(without_features, "kamare 增强版"), "版本行仍在") +Assert.eq(statusOf(status_rows, "加载路径").subtitle, cache_path) +Assert.eq(statusOf(status_rows, "缓存占用").status, "12 章") +Assert.matches(statusOf(status_rows, "缓存占用").subtitle, "已用 3.0 MB,可用 9.0 MB") + +local cleanup_rows = sectionRows(sections, "清理") +Assert.eq(cleanup_rows[1].title, "清理已读") +Assert.matches(cleanup_rows[1].subtitle, "1 章") +Assert.eq(cleanup_rows[2].title, "清理本服务器") +Assert.matches(cleanup_rows[2].subtitle, "2 章") +Assert.eq(cleanup_rows[3].title, "清理全部") +Assert.matches(cleanup_rows[3].subtitle, "含未关联服务器 · 15 章", "全部清理用合计,不用本服务器") +Assert.is_nil(findSection(sections, "获取增强版"), "增强态不显示安装说明") + +-- 维护组已移除:更新入口只在诊断页。 +Assert.is_nil(findSection(sections, "维护")) + +-- 清理已读:确认 → 忙碌窗 → 删除 → 复查 → 刷新。 +delete_calls = {} +cleanup_rows[1].callback() +local read_confirm = Themed.last("confirm") +Assert.not_nil(read_confirm) +Assert.matches(read_confirm.text, "将删除 1 章") +local repaints_before = repaints +read_confirm.ok_callback() +local busy = Themed.last("progress_dialog") +Assert.not_nil(busy, "同步删除先弹忙碌窗") +Assert.eq(busy.title, "清理已读") +Assert.eq(busy.text, "正在清理…") +Assert.is_true(busy.dismissable == false, "忙碌窗不可关") +Assert.is_true(busy.shown, "先显示再删除") +Assert.is_true(busy.closed, "删完关闭") +Assert.eq(repaints, repaints_before + 1, "删除前强制重绘一次") +Assert.eq(#delete_calls, 1, "清理已读调用一次批量删除") +Assert.eq(#delete_calls[1], 1, "只删已读完的那一章") +Assert.matches(Themed.last("toast").text, "已清理 1 章") +Assert.eq(shelf_events[#shelf_events], "shelf_changed", "删除后刷新书架") + +-- 删除后占用必须重算(03 E):只 updateView 会留下删前的数字。 +summary_result = { used = 2 * MB, available = 9 * MB, chapters = 11 } +summary_all_result = { used = 3 * MB, available = 9 * MB, chapters = 14 } +local usage_calls_before = summary_calls + summary_all_calls +local after_cleanup = page.sections() +Assert.eq(statusOf(sectionRows(after_cleanup, "状态"), "缓存占用").subtitle, + "正在统计…", "删除后先画「正在统计…」") +flush() +Assert.eq(summary_calls + summary_all_calls, usage_calls_before + 2, "删除后重算本服务器与合计") +Assert.eq(statusOf(sectionRows(page.sections(), "状态"), "缓存占用").status, + "11 章", "占用数字跟着删除刷新") +Assert.matches(sectionRows(page.sections(), "清理")[3].subtitle, + "含未关联服务器 · 14 章", "清理全部的数字也刷新") + +-- 空缓存:三项都置灰(03 待确认 3),清理全部不再可点。 +cfg.base_url, cfg.api_key = "http://kav", "k" +probe_result = { + ok = true, state = "enhanced", api_version = 1, version = "0.10.0-dev", + capabilities = { summary = true, chapters = true, delete = true, delete_all = true }, + path = cache_path, +} +available = { summary = true } +local saved_chapters = chapters_result +chapters_result = {} +summary_result = { used = 0, available = 9 * MB, chapters = 0 } +summary_all_result = { used = 0, available = 9 * MB, chapters = 0 } +rowAt("漫画缓存").callback() +local empty_rows = sectionRows(currentSections(), "清理") +for idx = 1, 3 do + Assert.is_false(empty_rows[idx].enabled, "空缓存置灰:" .. empty_rows[idx].title) + Assert.is_false(empty_rows[idx].chevron, "空缓存不显示箭头:" .. empty_rows[idx].title) + Assert.eq(empty_rows[idx].subtitle, "没有可清理的缓存", "空缓存文案:" .. empty_rows[idx].title) +end +chapters_result = saved_chapters +summary_result = { used = 3 * MB, available = 9 * MB, chapters = 12 } +summary_all_result = { used = 4 * MB, available = 9 * MB, chapters = 15 } + +-- 旧接口:不出清理项,只写升级说明;设置行也不承诺清理。 +probe_result = { + ok = true, state = "enhanced", api_version = 1, version = "0.9.22", + capabilities = { status = true, summary = true }, path = cache_path, +} +Assert.eq(rowAt("漫画缓存").subtitle, "状态与获取增强版", "旧接口不承诺清理") +Assert.eq(rowAt("漫画缓存").status, "增强版 v0.9.22(旧接口)") +rowAt("漫画缓存").callback() +local old_rows = sectionRows(currentSections(), "清理") +Assert.eq(#old_rows, 1, "旧接口只有一段说明") +Assert.eq(old_rows[1].title, "当前 kamare 没有清理接口") +Assert.matches(old_rows[1].subtitle, "chapters / delete_all", "说明要升级到什么") +probe_result = { + ok = true, state = "enhanced", api_version = 1, version = "0.10.0-dev", + capabilities = { open = true, index = true, status = true, summary = true, + chapters = true, delete = true, delete_all = true }, + path = cache_path, +} + +-- 清理全部:没有服务器也能用,确认文案含未关联。 +cfg.base_url, cfg.api_key = "", "" +probe_result = { + ok = true, state = "enhanced", api_version = 1, version = "0.10.0-dev", + capabilities = { summary = true, chapters = true, delete = true, delete_all = true }, + path = cache_path, +} +available = { summary = true } +rowAt("漫画缓存").callback() +summary_all_calls, summary_calls = 0, 0 +local unconfigured = currentSections() +Assert.eq(sectionRows(unconfigured, "清理")[1].title, "未配置服务器") +Assert.eq(summary_all_calls, 1, "没有服务器时占用取合计") +Assert.eq(summary_calls, 0, "没有服务器时不查单服务器") +Assert.matches(statusOf(sectionRows(unconfigured, "状态"), "缓存占用").subtitle, "含未关联服务器") +sectionRows(unconfigured, "清理")[2].callback() +local all_confirm = Themed.last("confirm") +Assert.matches(all_confirm.text, "含未关联服务器") +Assert.matches(all_confirm.text, "共 15 章", "确认框用所有服务器的合计,不用本服务器") +all_confirm.ok_callback() +Assert.eq(Themed.last("progress_dialog").title, "清理全部缓存", "全部清理同样有忙碌窗") +Assert.eq(delete_all_calls, 1, "清理全部走 deleteAll") + +-- 未安装:安装说明;路径归一;不显示占用。 +probe_result = { ok = false, state = "missing" } +available = {} +cfg.base_url = "" +rowAt("漫画缓存").callback() +local missing = currentSections() +local missing_version = statusOf(sectionRows(missing, "状态"), "kamare 增强版") +Assert.eq(missing_version.status, "未安装") +Assert.eq(missing_version.subtitle, "点按检查并安装 kamare 增强版", "没有 kamare 时引导点版本行") +local install = findSection(missing, "获取增强版") +Assert.not_nil(install, "非增强态显示安装说明") +local install_text = install.rows[1](600).text or "" +Assert.matches(install_text, "releases/latest") +Assert.matches(install_text, "kamarecache.lua") +Assert.matches(install_text, "增强版功能随版本不同") +Assert.matches(install_text, "上方「kamare 增强版」") +Assert.matches(install_text, "koreader/plugins", "手动安装路径带 koreader/ 前缀") +Assert.is_nil(findSection(missing, "清理"), "未安装不显示清理") + +-- 版本不兼容:安装说明前先讲清 API 不兼容(03 原型)。 +probe_result = { ok = false, state = "incompatible", api_version = 2 } +rowAt("漫画缓存").callback() +local incompatible = sectionRows(currentSections(), "版本与获取") +Assert.eq(incompatible[1].title, "版本不兼容") +Assert.matches(incompatible[1].subtitle, "API v2") +Assert.not_nil(incompatible[2].text, "后面仍是安装说明") + +-- 镜像失败:状态区给出警告 + 重试同步。 +probe_result = { + ok = true, state = "enhanced", api_version = 1, version = "0.10.0-dev", + capabilities = { summary = true, chapters = true, delete = true, delete_all = true }, + path = "/fake/plugins//kamare.koplugin/kamarecache.lua", +} +mirror_failed = true +available = { summary = true } +rowAt("漫画缓存").callback() +local mirrored = currentSections() +local mirror_row = statusOf(sectionRows(mirrored, "状态"), "配置同步失败") +Assert.not_nil(mirror_row, "镜像失败在状态区") +Assert.eq(mirror_row.status, "重试同步") +Assert.is_nil(statusOf(sectionRows(mirrored, "状态"), "加载路径").subtitle:find("//", 1, true), + "加载路径归一成单斜杠") +mirror_failed = false + +-- 保存后镜像:先落 moon 自己的配置,再 register_server;失败 toast 但不阻断。 +cfg.base_url, cfg.api_key = "http://kav", "k" +probe_result = { ok = true, state = "enhanced", api_version = 1, version = "0.10.0" } +register_calls, register_ok, events = {}, true, {} +local before = saved +rowAt("进度心跳间隔").callback() +Themed.last("spin").callback(70) +Assert.eq(saved, before + 1) +Assert.eq(register_calls[1].base_url, "http://kav") +Assert.eq(register_calls[1].api_key, "k") +Assert.eq(events[#events - 1], "save", "先存 moon 自己的配置") +Assert.eq(events[#events], "register", "镜像失败也不影响 moon 保存") + +register_ok = false +before = saved +rowAt("进度心跳间隔").callback() +Themed.last("spin").callback(60) +Assert.eq(Themed.last("toast").text, "无法同步配置到 kamare", "用户主动保存失败要提示") +Assert.eq(saved, before + 1, "toast 不阻断 moon 自己的保存") + +-- 未安装:不假装能镜像。 +probe_result = { ok = false, state = "missing" } +register_calls = {} +rowAt("进度心跳间隔").callback() +Themed.last("spin").callback(30) +Assert.len(register_calls, 0, "没有缓存接口时跳过镜像") + +---------------------------------------------------------------------- +-- 测试连接:只测 Kavita,不碰 kamare。 +---------------------------------------------------------------------- +Assert.eq(rowAt("测试连接").kind, "action") +Assert.eq(rowAt("测试连接").subtitle, "检查 Kavita 服务器连接与版本") + +---@param probe table +---@param mirror boolean|nil +---@param version string|nil +---@param err string|nil +---@return string +local function connectToast(probe, mirror, version, err) + probe_result = probe + mirror_failed = mirror == true + request_reply = { version = version, err = err } + rowAt("测试连接").callback() + return Themed.last("toast").text +end + +local enhanced = { ok = true, state = "enhanced", api_version = 1, version = "0.10.0-dev", + capabilities = { chapters = true, delete = true, delete_all = true } } +Assert.eq(connectToast(enhanced, false, "0.9.0"), "连接正常\nKavita 0.9.0") +Assert.eq(connectToast(enhanced, true, "0.9.0"), "连接正常\nKavita 0.9.0", + "kamare 镜像失败不影响 Kavita 连接结果") +Assert.eq(connectToast({ ok = false, state = "missing" }, false, "0.9.0"), + "连接正常\nKavita 0.9.0", "测试连接不碰 kamare") +Assert.eq(connectToast({ ok = false, state = "incompatible", api_version = 2 }, false, "0.9.0"), + "连接正常\nKavita 0.9.0") +-- 版本过旧 / 请求失败仍报真正原因,不能让缓存状态盖过去。 +Assert.eq(connectToast(enhanced, false, "0.8.9"), + "连接正常\nKavita 0.8.9 过旧,需要 0.9 及以上") +Assert.eq(connectToast(enhanced, false, nil, "HTTP 401"), "连接失败\nHTTP 401") +Assert.eq(connectToast(enhanced, false, nil, nil), "连接正常\n无法识别 Kavita 版本") + +-- 换服务器清理失败:共享配置、磁盘、kamare 镜像都必须保持旧值。 +do + cfg.base_url, cfg.api_key = "http://old", "old-key" + local saved_before, mirrored_before = saved, #register_calls + package.loaded["source.logout"] = { + replaceLibrary = function() return false end, + } + rowAt("服务器地址").callback() + Themed.last("input").callback("http://new") + Assert.eq(cfg.base_url, "http://old") + Assert.eq(cfg.api_key, "old-key") + Assert.eq(saved, saved_before) + Assert.eq(#register_calls, mirrored_before) + Assert.eq(Themed.last("toast").text, "准备本地同步失败") +end diff --git a/tests/kavita/shelf_cache_spec.lua b/tests/kavita/shelf_cache_spec.lua new file mode 100644 index 0000000..7a08a62 --- /dev/null +++ b/tests/kavita/shelf_cache_spec.lua @@ -0,0 +1,237 @@ +--[[-- +Kavita 源的书架缓存钩子:shelf_cache 能力、shelfCache 同步返回投影、 +syncBooksAsync 同步后预热(05 A1)、coverRequest 优先本地封面(05 A8)。 + +不复用 source_spec 的整套书架夹具:这里只碰钩子本身,HTTP / 书库 / 目录都最小打桩。 + +@module tests.moonsource_kavita.shelf_cache_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, inject-field + +local Assert = require("support.assert") +local Config = require("support.config") +local Stubs = require("support.stubs") +Stubs.install() + +-- 日志:pcall 的失败必须被检查并记录,不能静默吞掉(项目审计口径)。 +local warns = {} +package.loaded["utils.log"] = { + dbg = function() end, + info = function() end, + error = function() end, + warn = function(...) + local parts = {} + for index = 1, select("#", ...) do + parts[#parts + 1] = tostring(select(index, ...)) + end + warns[#warns + 1] = table.concat(parts, " ") + end, +} + +local PLUGIN = (debug.getinfo(1, "S").source:match("^@(.-)/tests/") .. "/moonsource-kavita.koplugin/moonsource_kavita") +-- 走 preload 不改 package.path:插件根上的 main.lua 会顶掉月读的 main。 +for _idx, name in ipairs({ "client", "position", "annotation", "source", "cache", "volume_list", "stats" }) do + package.preload["moonsource_kavita" .. (name == "source" and ".source" or "." .. name)] = function() + return dofile(PLUGIN .. "/" .. (name == "source" and "source" or name) .. ".lua") + end +end + +-- 往返桩:encode 登记表并发令牌,decode 凭令牌取回(不是令牌就报错,同真解析器)。 +local encoded = {} +package.preload["json"] = function() + return { + encode = function(value) + encoded[#encoded + 1] = value + return "\0json" .. #encoded + end, + decode = function(text) + return encoded[tonumber(text:match("^%z?json(%d+)$"))] or error("not json: " .. text) + end, + } +end + +local cfg = { base_url = "http://kav/", api_key = "k", libraries = { ["1"] = true } } +package.preload["utils.settings"] = function() + return { + get = function() return { active_source = "local" } end, + save = function() end, + getSource = function() return cfg end, + saveSource = function() end, + } +end + +-- HTTP:只有书架快照这一个路由。 +local routes, requested = {}, {} +package.preload["http.request"] = function() + return { + ok = function(code) + code = tonumber(code) + return code ~= nil and code >= 200 and code < 300 + end, + header = function() end, + request = function(opts, cb) + requested[#requested + 1] = opts + local route = routes[opts.method .. " " .. opts.url:match("^http://kav(/[^?]*)")] + require("ui/uimanager"):nextTick(function() + cb(route and route(opts) or { code = 404, body = "" }) + end) + return { cancel = function() end } + end, + } +end + +-- 本地库:钩子只需要「取一本书」与「已同步身份」。 +local books = {} +package.loaded["book.books_db"] = { + get = function(_source_id, stable_id) return books[stable_id] end, + libraryStableIdsBySource = function() return {} end, +} +package.loaded["book.progress_db"] = { + get = function() return nil end, +} +package.loaded["book.store"] = { rememberMany = function() end } + +local sequence = {} +package.loaded["source.shelf"] = { + reconcile = function(_source_id, list) + sequence[#sequence + 1] = "reconcile" + return { pulled = #list, pushed = 0, hidden = 0, conflicts = 0, skipped = false } + end, +} + +-- 封面路径只关心「本地缓存 / 在线地址」的分支:目录查不到卷时退回系列封面(卷封面见 source_spec)。 +package.loaded["source.toc"] = { read = function() return nil end } +local SourceMod = require("moonsource_kavita.source") +local Cache = require("moonsource_kavita.cache") +local source = SourceMod.new() + +-- 能力:声明 shelf_cache,UI 据此决定断网时是否收窄书架(05 A2)。 +local caps = source:capabilities() +Assert.is_true(caps.shelf_cache, "Kavita 声明书架缓存能力") +Assert.is_true(caps.stats_pull, "原有能力不受影响") + +-- shelfCache:同步返回适配层记忆的投影;未配置不触盘。 +local projection = { series_ids = { ["700"] = true }, mark = { ["700"] = true }, cover = {} } +local shelf_calls = 0 +local real_shelf = Cache.shelf +Cache.shelf = function() + shelf_calls = shelf_calls + 1 + return projection +end +Assert.eq(source:shelfCache(), projection, "shelfCache 原样交回适配层投影") +Assert.eq(shelf_calls, 1) +cfg.base_url = "" +Assert.is_nil(SourceMod.new():shelfCache(), "未配置返回 nil") +Assert.eq(shelf_calls, 1, "未配置不读投影") +cfg.base_url = "http://kav/" + +-- coverRequest:投影里有本地封面且文件存在 → 本地路径,不再走鉴权 URL(05 A8)。 +local cover_path = Config.dir() .. "/shelf_cover_700.jpg" +local file = assert(io.open(cover_path, "wb")) +file:write("jpg") +file:close() +Cache.shelf = function() return { series_ids = {}, mark = {}, cover = { ["700"] = cover_path } } end +local req = select(1, source:coverRequest({ source_id = "kavita", stable_id = "700" })) +Assert.eq(req.url, cover_path, "已缓存系列用本地封面") +Assert.is_nil(req.headers, "本地文件不需要鉴权头") +Assert.eq(req.authoritative, true, "源封面压过本地抽页缓存") +-- 卷身份同样借系列封面(chapter-cover 是扫描页,不能当封面)。 +req = select(1, source:coverRequest({ source_id = "kavita", stable_id = "700:7001" })) +Assert.eq(req.url, cover_path, "卷身份也用已缓存系列封面") +-- 投影给了路径但文件没了 → 维持在线系列封面。 +Cache.shelf = function() return { series_ids = {}, mark = {}, cover = { ["700"] = cover_path .. ".gone" } } end +req = select(1, source:coverRequest({ source_id = "kavita", stable_id = "700" })) +Assert.is_true(req.url:find("series-cover", 1, true) ~= nil, "文件不存在退回在线封面") +Assert.not_nil(req.headers) +req = select(1, source:coverRequest({ source_id = "kavita", stable_id = "700:7001" })) +Assert.is_true(req.url:find("series-cover", 1, true) ~= nil, "卷身份也走系列封面") +-- 适配层没给投影(无 index):照旧在线封面。 +Cache.shelf = function() return nil end +req = select(1, source:coverRequest({ source_id = "kavita", stable_id = "700" })) +Assert.is_true(req.url:find("series-cover", 1, true) ~= nil) +Cache.shelf = real_shelf + +-- syncBooksAsync 预热:对账后、回调前把投影建好,进书架时 O(1)(05 A1)。 +sequence, requested = {}, {} +Cache.shelf = function() + sequence[#sequence + 1] = "shelf" + return projection +end +routes["POST /api/Series/all-v2"] = function() + return { code = 200, body = require("json").encode({ + { id = 700, name = "漫画一", libraryName = "漫画", wordCount = 10 }, + }) } +end +source.backfillMeta = function() end +local synced +source:syncBooksAsync(nil, function(result, err) + sequence[#sequence + 1] = "cb" + synced = { result = result, err = err } +end) +Stubs.flush() +Assert.not_nil(synced) +Assert.is_nil(synced.err) +Assert.eq(synced.result.pulled, 1, "对账结果照旧回调") +Assert.eq(table.concat(sequence, ","), "reconcile,shelf,cb", "预热排在回调之前") + +-- 手动刷新 / 书库重扫(force)必须让投影失效并重建;后台同步沿用记忆(05 A1)。 +-- 拉回的新缓存状态看不见 = 用户点了刷新但书架标记不更新。 +sequence, requested = {}, {} +local resets = 0 +local real_reset = Cache.resetShelf +Cache.resetShelf = function() + resets = resets + 1 + sequence[#sequence + 1] = "reset" +end +Cache.shelf = function() + sequence[#sequence + 1] = "shelf" + return projection +end +local background +source:syncBooksAsync(nil, function(result, err) background = { result = result, err = err } end) +Stubs.flush() +Assert.not_nil(background and background.result) +Assert.eq(resets, 0, "后台同步不丢投影") +Assert.eq(table.concat(sequence, ","), "reconcile,shelf", "后台同步只预热现有记忆") +sequence = {} +local forced +source:syncBooksAsync({ force = true }, function(result, err) forced = { result = result, err = err } end) +Stubs.flush() +Assert.not_nil(forced and forced.result) +Assert.eq(resets, 1, "手动刷新让投影失效") +Assert.eq(table.concat(sequence, ","), "reset,reconcile,shelf", "重扫先失效再重建,回调前投影已就绪") +sequence = {} +Cache.resetShelf = real_reset + +-- 预热失败不拖垮同步:投影只是书架标记,缓存模块异常照样要回调对账结果。 +sequence, requested = {}, {} +warns = {} +local broken_sequence = sequence +Cache.shelf = function() + broken_sequence[#broken_sequence + 1] = "shelf" + error("kamare index broken") +end +local second +source:syncBooksAsync(nil, function(result, err) second = { result = result, err = err } end) +Stubs.flush() +Assert.not_nil(second and second.result, "预热异常不影响同步结果") +Assert.eq(table.concat(sequence, ","), "reconcile,shelf") +-- 第二次仍失败:不能每次同步都刷一行日志(一次性),但也不能静默。 +source:syncBooksAsync(nil, function(result, err) second = { result = result, err = err } end) +Stubs.flush() +Assert.eq(#warns, 1, "投影预热失败检查并只记一次") +Assert.matches(warns[1] or "", "shelf") +Cache.shelf = real_shelf + +-- Registry.reload() 会重建源实例:新实例顺手丢掉旧服务器的投影(05 A1 的第三类失效点)。 +local resets = 0 +local real_reset = Cache.resetShelf +Cache.resetShelf = function() + resets = resets + 1 + return real_reset() +end +SourceMod.new() +Assert.eq(resets, 1, "重建源实例即失效书架投影") +Cache.resetShelf = real_reset + +return true diff --git a/tests/kavita/source_spec.lua b/tests/kavita/source_spec.lua new file mode 100644 index 0000000..e3eeac4 --- /dev/null +++ b/tests/kavita/source_spec.lua @@ -0,0 +1,2980 @@ +--[[-- +extensions/moonsource-kavita.koplugin:经源注册表发现;书架、开书(单卷 / 选卷 / 失败)、 +封面、进度双向换算。HTTP 与书库全部打桩。 + +@module tests.moonsource_kavita.source_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, inject-field + +local Assert = require("support.assert") +local Config = require("support.config") +local Stubs = require("support.stubs") +local Themed = require("support.theme_stubs") + +-- 往返桩:encode 登记表并发一个令牌串,decode 凭令牌取回(不是令牌就报错,同真解析器)。 +local encoded = {} +local JSON = { + encode = function(value) + encoded[#encoded + 1] = value + return "\0json" .. #encoded + end, + decode = function(text) + return encoded[tonumber(text:match("^%z?json(%d+)$"))] or error("not json: " .. text) + end, +} +package.loaded["json"] = JSON +Themed.install() +local PLUGIN = (debug.getinfo(1, "S").source:match("^@(.-)/tests/") .. "/moonsource-kavita.koplugin/moonsource_kavita") +-- 走 preload 不改 package.path:runner 只还原 preload/loaded,插件根上的 main.lua 会顶掉月读的 main。 +for _idx, name in ipairs({ "client", "position", "annotation", "source", "setting", "cache", "volume_list", "stats" }) do + package.preload["moonsource_kavita" .. (name == "source" and ".source" or "." .. name)] = function() + return dofile(PLUGIN .. "/" .. (name == "source" and "source" or name) .. ".lua") + end +end +-- 首页组件另有 on_deck_spec;这里只验证描述表把它交出去。 +local on_deck = { id = "kavita.on_deck" } +package.preload["moonsource_kavita.on_deck"] = function() return on_deck end + +local cfg = { base_url = "http://kav/", api_key = " k ", libraries = { ["2"] = true, ["1"] = true } } +local ffi = require("ffi") +ffi.cdef("int setenv(const char *name, const char *value, int overwrite);") +local function setTZ(tz) ffi.C.setenv("TZ", tz, 1) end +setTZ("CST-8") +package.preload["utils.settings"] = function() + local common = { active_source = "local" } + return { + get = function() return common end, + save = function() end, + getSource = function() return cfg end, + saveSource = function() end, + } +end +for _idx, id in ipairs({ "local", "moon", "wechat", "jdread", "copymanga", "fanqie" }) do + package.loaded["source." .. id] = { + meta = function() return { id = id, name = id, type = "book" } end, + new = function() return { id = id } end, + } +end + +local online = true +package.loaded["ui/network/manager"] = { isConnected = function() return online end } + +-- HTTP:按 "METHOD /path" 路由;值为响应表或 fun(opts) → 响应表。 +local routes, calls, held = {}, {}, {} +local download = { code = 200, body = "PK\3\4epub" } +package.loaded["http.request"] = { + ok = function(code) + code = tonumber(code) + return code ~= nil and code >= 200 and code < 300 + end, + -- 与真 Request.header 同语义(大小写不敏感;测试里响应头是普通表)。 + header = function(res, name) + for key, value in pairs(res and res.headers or {}) do + if type(key) == "string" and key:lower() == name:lower() then return value end + end + end, + request = function(opts, cb) + calls[#calls + 1] = opts + local route = routes[opts.method .. " " .. opts.url:match("^http://kav(/[^?]*)")] + require("ui/uimanager"):nextTick(function() + local response = type(route) == "function" and route(opts) or route or { code = 404, body = "" } + -- { hold = true, reply = … }:把回包压住,测试用 held 自行放出(验证取消 / 在途中止)。 + if type(response) == "table" and response.hold then + held[#held + 1] = function() cb(response.reply) end + return + end + cb(response) + end) + return { cancel = function() end } + end, + download = function(opts, dest, cb) + calls[#calls + 1] = opts + local file = assert(io.open(dest, "wb")) + file:write(download.body) + file:close() + require("ui/uimanager"):nextTick(function() cb(true, nil, { code = download.code }) end) + return { cancel = function() end } + end, +} +local function json(data, headers) return { code = 200, body = JSON.encode(data), headers = headers } end +local function query(opts, key) return opts.url:match("[?&]" .. key .. "=([^&]*)") end + +-- 书库:books 行(path)、目录缓存、本地进度。 +local books, tocs, stale, progress, remembered, touched, reconciled = {}, {}, {}, {}, {}, {}, nil +local fixed = {} +-- 脏行(sync_status=0):漫画走 kamare 时只写 upsertRemote,任何 upsert 都是回归。 +local dirty = {} +local toc_fresh = true +local shelf_ids, written, written_opts = {}, {}, {} +package.loaded["book.books_db"] = { + get = function(_sid, id) return books[id] end, + getToc = function(_sid, id) return stale[id] end, + libraryStableIdsBySource = function() return shelf_ids end, + -- 补空字段:脏行也允许补,但不覆盖非空值(与真实现同步)。 + fillEmptyMeta = function(_sid, id, authors, intro) + local row = books[id] + if not row then return false end + local changed = false + if authors and authors ~= "" and (row.authors == nil or row.authors == "") then + row.authors, changed = authors, true + end + if intro and intro ~= "" and (row.intro == nil or row.intro == "") then + row.intro, changed = intro, true + end + return changed + end, +} +package.loaded["book.progress_db"] = { + get = function(_sid, id) return progress[id] end, + list = function(_sid, series_id) + local rows = {} + local prefix = series_id .. ":" + for id, row in pairs(progress) do + if id:sub(1, #prefix) == prefix then rows[id] = row end + end + return rows + end, + upsertRemote = function(_sid, id, pos, opts) + written[id] = pos + written_opts[id] = opts + return true + end, + upsert = function(_sid, id, pos) + dirty[id] = true + written[id] = pos + return true + end, + unsynced = function() + local ids = {} + for id in pairs(dirty) do ids[#ids + 1] = id end + table.sort(ids) + return ids + end, + fixRemoteTime = function(_sid, id, at) + fixed[id] = at + return true + end, +} +package.loaded["book.store"] = { + touch = function(path, ref) + touched[#touched + 1] = { path = path, stable_id = ref.stable_id } + books[ref.stable_id] = { path = path } + return true + end, + rememberMany = function(list) + for _idx, book in ipairs(list) do remembered[book.stable_id] = book end + end, +} +package.loaded["source.toc"] = { + -- allow_stale:过期目录也认(身份判定用;卷数 / 卷身份不随时间变)。 + read = function(_sid, id, allow_stale) + return (allow_stale or toc_fresh) and tocs[id] or (stale[id] and JSON.decode(stale[id])) + end, + put = function(_sid, id, list) + tocs[id] = list + return true + end, +} +package.loaded["source.shelf"] = { + reconcile = function(source_id, list, force) + reconciled = { source_id = source_id, books = list, force = force } + return { pulled = #list, pushed = 0, hidden = 0, conflicts = 0, skipped = false } + end, +} +local WORK = Config.dir() .. "/kavita_spec" +-- 后台补简介的 done 状态落在沙箱 settings 里:上一轮跑挂留下的状态会让本轮跳过补全。 +os.remove(require("datastorage"):getSettingsDir() .. "/moonsource_kavita_meta.lua") +-- 统计状态(上次身份 + 系列章数)同理:留着会让本轮读不到「首次拉取」的行为。 +-- .old 备份一起去掉:主文件被删时 LuaSettings 会回落它(别的 spec 中断留下的档就活过来了)。 +local STATS_STATE = require("datastorage"):getSettingsDir() .. "/moonsource_kavita_stats.lua" +for _idx, suffix in ipairs({ "", ".old" }) do os.remove(STATS_STATE .. suffix) end +os.execute("rm -rf '" .. WORK .. "'") +package.loaded["utils.db"] = { transaction = function(fn) return fn() end } +package.loaded["utils.paths"] = { + ensureBookWork = function(id) os.execute("mkdir -p '" .. WORK .. "/" .. id .. "'") end, + bookWorkDir = function(id) return WORK .. "/" .. id end, +} + +package.loaded["pluginloader"] = { enabled_plugins = { Config.selfPlugin() } } +package.loaded["source.registry"] = nil +package.preload["source.kavita"] = function() return require("moonsource_kavita.source") end +local Registry = require("source.registry") + +Assert.eq(Registry.meta("kavita").type, "book") +local source = Registry.resolve("kavita") +Assert.is_true(source:configured()) +Assert.is_false(source:capabilities().shelf_push, "Kavita 书架只拉不推") +Assert.eq(require("moonsource_kavita.source").DEFAULT_HEARTBEAT_INTERVAL, 30, "设置页读的默认心跳间隔") + +---@return any, any, any +local function run(method, ...) + local a, b, c + local n = select("#", ...) + local args = { ... } + args[n + 1] = function(x, y, z) a, b, c = x, y, z end + source[method](source, unpack(args, 1, n + 1)) + Stubs.flush() + return a, b, c +end + +-- 书架:按库分页拉 series,库名即分类;Key 去空白、地址去尾斜杠。 +local series_page = {} +for i = 1, 500 do series_page[i] = { id = i, name = "S" .. i, libraryName = "小说", wordCount = i == 1 and 120000 or 0, + lastChapterAddedUtc = i == 1 and "2026-01-02T03:04:05.123" or nil } end +routes["POST /api/Series/all-v2"] = function(opts) + local body = JSON.decode(opts.body) + local lib, page = body.Statements[1].Value, query(opts, "pageNumber") + if lib == "1" and page == "1" then return json(series_page) end + if lib == "1" then return json({ { id = 501, name = "S501", libraryName = "小说" } }) end + return json({ { id = 900, name = "漫画一", libraryName = "漫画", format = 1, pages = 20, pagesRead = 5, + latestReadDate = "2026-01-02T03:04:05.123" } }) +end +local result = run("syncBooksAsync", nil) +Assert.eq(#reconciled.books, 502) +Assert.eq(result.pulled, 503, "对账 502 本 + 1 本漫画进度") +Assert.eq(reconciled.source_id, "kavita") +Assert.eq(reconciled.books[502].category, "漫画") +Assert.eq(reconciled.books[1].stable_id, "1") +Assert.eq(reconciled.books[1].meta.words, 120000, "书架带字数(0 = 未知,入库时丢掉)") +Assert.eq(reconciled.books[1].series, "S1", "系列列填 Kavita series 名,否则图书馆系列页签全是「无系列」") +Assert.eq(reconciled.books[1].inserted_at, 1767323045, "加入时间用 lastChapterAddedUtc,图书馆「最近添加」才跟 Kavita 一致") +Assert.eq(calls[1].headers["x-api-key"], "k") +Assert.matches(calls[1].url, "^http://kav/api/Series/all%-v2%?") +Assert.eq(calls[1].timeout, 60, "拉书架带足够长的超时,慢设备不会一拉就 30s 超时") +Assert.is_true(run("syncBooksAsync", { dirty_only = true }).skipped, "没有删书接口,只推脏行时跳过") +cfg.libraries = {} +local none, err = run("syncBooksAsync", nil) +Assert.is_nil(none) +Assert.matches(err, "选择书库") +cfg.libraries = { ["1"] = true } + +-- 单卷 series:拉目录(标题退到文件名)、写作者简介、下载到 series 行。 +routes["GET /api/Series/10"] = json({ id = 10, name = "长夜", libraryId = 1, format = 3 }) +routes["GET /api/Series/volumes"] = function(opts) + local sid = query(opts, "seriesId") + if sid == "10" then + return json({ { id = 100, name = "1", chapters = { { + id = 1000, title = "-100000", titleName = "", format = 3, pages = 12, pagesRead = 0, + files = { { filePath = "/books/长夜/Long Night.epub" } }, + } } } }) + end + if sid == "20" then + return json({ + { id = 200, name = "1", chapters = { { id = 2001, titleName = "第一卷", format = 3, pages = 8, pagesRead = 8 } } }, + { id = 201, name = "2", chapters = { { id = 2002, titleName = "第二卷", format = 3, pages = 10, pagesRead = 0, + summary = "第二卷简介" } } }, + }) + end + if sid == "30" then + return json({ { id = 300, chapters = { { id = 3000, titleName = "图册", format = 4, pages = 50 } } } }) + end + return json({ { id = 400, chapters = { { id = 4000, titleName = "散图", format = 0, pages = 3 } } } }) +end +routes["GET /api/Series/metadata"] = json({ summary = "简介", writers = { { name = "甲" }, { name = "乙" } }, + publishers = { { name = "某出版社" } }, releaseYear = 2019, language = "zh" }) +for _idx, sid in ipairs({ 20, 30, 40, 50 }) do + routes["GET /api/Series/" .. sid] = json({ id = sid, name = "合集" .. sid, libraryId = 2 }) +end + +-- 增量书架:快照指纹没变、本地书架非空就跳过对账;漫画按已读页回填远端进度(本地同页不重写)。 +cfg.libraries = { ["2"] = true, ["1"] = true } +Assert.eq(written["900"].page, 6, "首轮同步就回填漫画进度(pageNum 5 → 本地第 6 页)") +Assert.eq(written["900"].fraction, 0.3, "fraction 与 page 同口径") +Assert.eq(written["900"].total_pages, 20) +Assert.eq(written["900"].updated_at, 1767323045, "Kavita 时间按 UTC 解析") +reconciled, shelf_ids = nil, { "1" } +progress["900"] = { page = 6 } +result = run("syncBooksAsync", nil) +Assert.is_nil(reconciled, "快照没变不对账") +Assert.eq(result.pulled, 0) +progress["900"] = nil +Assert.eq(run("syncBooksAsync", nil).pulled, 1, "只有漫画进度变了也让书架重绘") +shelf_ids = {} +run("syncBooksAsync", nil) +Assert.is_true(reconciled ~= nil, "本地书架空了(书库被清)照常对账") + +-- 对账后后台补简介 / 作者:缺任意一项就补,一本一请求,失败就跳过。 +reconciled = nil +books["1"], books["2"], books["3"] = { intro = "已有", authors = "甲" }, {}, {} +local meta_calls = {} +local metadata_route = routes["GET /api/Series/metadata"] +routes["GET /api/Series/metadata"] = function(opts) + meta_calls[#meta_calls + 1] = query(opts, "seriesId") + return metadata_route +end +run("syncBooksAsync", { force = true }) +Assert.is_true(reconciled ~= nil, "force 不看指纹") +Assert.is_true(reconciled.force, "force 传给对账,书架 meta 覆盖本地") +Assert.eq(table.concat(meta_calls, ","), "2,3") +Assert.eq(remembered["2"].intro, "简介") +Assert.eq(remembered["2"].authors, "甲 / 乙") +Assert.eq(remembered["2"].meta.publisher, "某出版社") +Assert.eq(remembered["2"].meta.published, 2019) +Assert.eq(remembered["2"].meta.language, "zh") +Assert.is_nil(remembered["2"].title, "不碰标题") +-- 书库把空简介存成 NULL:补过的记在单独文件里,TTL 内不再重拉。 +meta_calls, books["2"], books["3"] = {}, {}, {} +source:backfillMeta({ "2", "3" }) +Stubs.flush() +Assert.len(meta_calls, 0, "补过的不再补") +local done_file = require("datastorage"):getSettingsDir() .. "/moonsource_kavita_meta.lua" +Assert.eq(type(require("luasettings"):open(done_file):readSetting("done")["2"]), "number", + "状态记的是检查时间戳,不是终身布尔") +-- 指纹没变(不对账)也要接着补:换源 / 断网中断过的书不能永远停在未知作者。 +meta_calls, remembered["3"] = {}, nil +books["2"], books["3"] = { intro = "已有", authors = "甲" }, {} +os.remove(done_file) +Assert.is_true(run("syncBooksAsync", nil).skipped == false, "快照没变也跑完整同步(补简介)") +Assert.eq(table.concat(meta_calls, ","), "3", "没补过的接着补") +Assert.eq(remembered["3"].authors, "甲 / 乙") +os.remove(done_file) +routes["GET /api/Series/metadata"] = function(opts) + local sid = query(opts, "seriesId") + meta_calls[#meta_calls + 1] = sid + -- 只有 2 号失败:后面的 3 号不能被一个坏请求拖住。 + if sid == "2" then return { code = 500, body = "" } end + return metadata_route +end +meta_calls, remembered["3"], books["2"] = {}, nil, {} +run("syncBooksAsync", { force = true }) +Assert.eq(table.concat(meta_calls, ","), "2,3", "单本失败跳过,后面继续补") +Assert.eq(remembered["3"].authors, "甲 / 乙") +online = false +meta_calls = {} +source:backfillMeta({ "2" }) +Stubs.flush() +Assert.len(meta_calls, 0, "离线不补") +online = true +routes["GET /api/Series/metadata"] = metadata_route + +-- 补全门禁:空串算缺数据、旧布尔当过期、TTL / force / server 分区 / 裁剪 / 失败与空响应。 +local State = function() return require("luasettings"):open(done_file) end +local function reset_state(done, server) + local st = State() + st:saveSetting("server", server or "http://kav") + st:saveSetting("done", done or {}) + st:flush() +end +local function state_done() return State():readSetting("done") or {} end +local function flush_backfill(...) + source:backfillMeta(...) + Stubs.flush() +end + +local record_route = function(opts) + meta_calls[#meta_calls + 1] = query(opts, "seriesId") + return metadata_route +end +routes["GET /api/Series/metadata"] = record_route + +os.remove(done_file) +reset_state({ ["2"] = true }) +books["2"] = { intro = "", authors = "" } +meta_calls = {} +flush_backfill({ "2" }) +Assert.eq(table.concat(meta_calls, ","), "2", "intro='' + 旧布尔 true 也要补(空串不是已补全)") +Assert.eq(type(state_done()["2"]), "number", "补完写检查时间戳") + +reset_state({ ["2"] = os.time() }) +books["2"] = {} +meta_calls = {} +flush_backfill({ "2" }) +Assert.len(meta_calls, 0, "TTL 内不重拉") + +reset_state({ ["2"] = os.time() - 8 * 86400 }) +meta_calls = {} +flush_backfill({ "2" }) +Assert.eq(table.concat(meta_calls, ","), "2", "TTL 过期重试") + +reset_state({ ["2"] = os.time() }) +meta_calls = {} +flush_backfill({ "2" }, { force = true }) +Assert.eq(table.concat(meta_calls, ","), "2", "手动刷新忽略 TTL") + +reset_state({ ["2"] = true }) +books["2"] = { intro = "有", authors = "甲" } +meta_calls = {} +flush_backfill({ "2" }) +Assert.len(meta_calls, 0, "完整行永久跳过,旧布尔也一样") + +reset_state({ ["2"] = os.time() }, "http://old") +books["2"] = {} +meta_calls = {} +flush_backfill({ "2" }) +Assert.eq(table.concat(meta_calls, ","), "2", "换服务器后旧标记作废") +Assert.eq(State():readSetting("server"), "http://kav", "记录当前服务器") + +reset_state({}) +books["2"] = {} +meta_calls = {} +local good_route = record_route +routes["GET /api/Series/metadata"] = { code = 500, body = "" } +flush_backfill({ "2" }) +Assert.is_nil(state_done()["2"], "请求失败不推进 checked_at") +routes["GET /api/Series/metadata"] = json({}) +flush_backfill({ "2" }) +Assert.eq(type(state_done()["2"]), "number", "空 DTO 也算检查过(TTL 后再看)") +routes["GET /api/Series/metadata"] = good_route + +reset_state({ ["2"] = os.time(), ["999"] = os.time() }) +meta_calls = {} +flush_backfill({ "2" }) +Assert.is_nil(state_done()["999"], "不在本轮书架的 series 从状态里裁掉") + +-- 快照没变时书架 id 里混着卷行(seriesId:chapterId):不能拿它请求 series metadata(Kavita 判 400)。 +reset_state({}) +books["2"], books["2:2001"] = {}, { title = "第二卷" } +meta_calls = {} +flush_backfill({ "2", "2:2001" }) +Assert.eq(table.concat(meta_calls, ","), "2", "卷行 id 不补 series 元数据") +books["2:2001"] = nil + +reset_state({}) +books["2"] = {} +routes["GET /api/Series/metadata"] = json({ summary = " ", writers = {} }) +flush_backfill({ "2" }) +Assert.is_nil(remembered["2"].intro, "空白 summary 归一成 nil,不写空串") +Assert.is_nil(remembered["2"].authors, "空 writers 归一成 nil") +routes["GET /api/Series/metadata"] = good_route + +-- 60 秒预算:到点停止,已处理的记 checked_at,下一轮接着补。 +reset_state({}) +books["31"], books["32"], books["33"] = {}, {}, {} +meta_calls = {} +local real_time, fake_now = os.time, os.time() +os.time = function() return fake_now end +routes["GET /api/Series/metadata"] = function(opts) + meta_calls[#meta_calls + 1] = query(opts, "seriesId") + fake_now = fake_now + 61 + return metadata_route +end +flush_backfill({ "31", "32", "33" }, { force = true }) +os.time = real_time +routes["GET /api/Series/metadata"] = good_route +Assert.eq(table.concat(meta_calls, ","), "31", "预算到点停止") +Assert.eq(type(state_done()["31"]), "number", "已处理的记时间戳") +Assert.is_nil(state_done()["32"], "没处理的不记,下一轮续跑") +books["31"], books["32"], books["33"] = nil, nil, nil + +-- 容器补全后,读过的卷行在同步里自动继承作者 / 简介(不用展示层兜底)。 +local saved_all = routes["POST /api/Series/all-v2"] +routes["POST /api/Series/all-v2"] = function(opts) + local body = JSON.decode(opts.body) + if body.Statements[1].Value == "2" then + return json({ { id = 71, name = "漫画七", libraryName = "漫画", format = 1, pages = 10, pagesRead = 5, + latestReadDate = "2026-01-02T03:04:05.123" } }) + end + return json({}) +end +tocs["71"] = { { chapterId = 7101, title = "第1话", pages = 10 } } +progress["71:7101"] = { page = 5, fraction = 0.5 } +books["71"] = { title = "漫画七", authors = "作者甲", intro = "整部简介" } +books["71:7101"] = { title = "漫画七 · 第1话" } +shelf_ids = {} +run("syncBooksAsync", { force = true }) +Assert.eq(remembered["71:7101"].authors, "作者甲", "卷行继承容器作者") +Assert.eq(remembered["71:7101"].intro, "整部简介", "卷行继承容器简介") + +-- 脏卷行:本地改过的标题保留,空的作者 / 简介从容器补上(不走 upsertRemote 覆盖)。 +books["71:7101"] = { title = "本地改名", sync_status = 0 } +remembered["71:7101"] = nil +run("syncBooksAsync", { force = true }) +Assert.eq(books["71:7101"].authors, "作者甲", "脏卷行只补空作者") +Assert.eq(books["71:7101"].title, "本地改名", "本地标题保留") +Assert.is_nil(remembered["71:7101"], "脏行不走远端整行覆盖") + +routes["POST /api/Series/all-v2"] = saved_all +books["71"], books["71:7101"] = nil, nil +tocs["71"], progress["71:7101"] = nil, nil + +books["1"], books["2"], books["3"] = nil, nil, nil +cfg.libraries = { ["1"] = true } + +local path = run("openBookAsync", { source_id = "kavita", stable_id = "10", book = { title = "长夜" } }, nil) +Assert.eq(path, WORK .. "/10/1000.epub") +Assert.eq(touched[1].stable_id, "10") +Assert.eq(tocs["10"][1].title, "Long Night", "卷名是纯数字、标题是哨兵时退到文件名") +Assert.eq(tocs["10"][1].libraryId, 1) +Assert.eq(remembered["10"].authors, "甲 / 乙") +Assert.eq(remembered["10"].intro, "简介") +Assert.eq(calls[#calls].headers["x-api-key"], "k", "下载带鉴权头") + +-- 已下载:直接开,不联网也不重新登记。 +online = false +local before = #calls +Assert.eq(run("openBookAsync", { source_id = "kavita", stable_id = "10" }, nil), path) +Assert.eq(#calls, before) +online = true + +-- 下载失败:非 2xx 删文件报状态码;2xx 但文件头不对(反代错误页)删文件报校验失败。 +download.code, download.body = 500, "oops" +routes["GET /api/Series/11"] = json({ id = 11, name = "坏书", libraryId = 1 }) +local saved = routes["GET /api/Series/volumes"] +routes["GET /api/Series/volumes"] = json({ { id = 110, chapters = { { id = 1100, titleName = "坏", format = 3, pages = 1 } } } }) +local failed, ferr = run("openBookAsync", { source_id = "kavita", stable_id = "11" }, nil) +Assert.is_nil(failed) +Assert.matches(ferr, "500") +Assert.is_nil(io.open(WORK .. "/11/1100.epub")) +download.code = 200 +tocs["11"] = nil +failed, ferr = run("openBookAsync", { source_id = "kavita", stable_id = "11" }, nil) +Assert.is_nil(failed) +Assert.matches(ferr, "校验失败") +Assert.is_nil(io.open(WORK .. "/11/1100.epub")) +routes["GET /api/Series/volumes"] = saved +download.body = "PK\3\4epub" + +-- 图片目录格式没有可下载的单文件。 +failed, ferr = run("openBookAsync", { source_id = "kavita", stable_id = "40" }, nil) +Assert.is_nil(failed) +Assert.matches(ferr, "图片目录") + +-- 离线:没缓存目录就当场失败;有过期目录照用(这里卷已下载,直接开)。 +online = false +failed, ferr = run("openBookAsync", { source_id = "kavita", stable_id = "50" }, nil) +Assert.is_nil(failed) +Assert.matches(ferr, "网络不可用") +online = true + +-- 多卷:选卷列表标已读,选中后下到隐藏卷行。 +local multi = { source_id = "kavita", stable_id = "20", book = { stable_id = "20", title = "合集", authors = "丙" } } +local opened, oerr +source:openBookAsync(multi, nil, function(p, e) opened, oerr = p, e end) +Stubs.flush() +local list = Themed.last("list") +Assert.len(list.items, 2) +Assert.eq(list.items[1].mandatory, "已读") +Assert.is_nil(list.items[2].mandatory) +Themed.choose(list, 2) +Stubs.flush() +Assert.eq(opened, WORK .. "/20:2002/2002.epub") +Assert.eq(remembered["20:2002"].title, "合集 · 第二卷") +Assert.eq(remembered["20:2002"].series, "合集") +Assert.eq(remembered["20:2002"].authors, "丙", "卷行继承容器作者,最近阅读里不再是未知作者") +Assert.is_nil(remembered["20:2002"].deleted, "卷行不上书架") + +-- 多卷 series 的阅读统计都记在卷行上:容器详情用 statsIdentities 把各卷并进来。 +local ids = source:statsIdentities({ source_id = "kavita", stable_id = "20" }) +Assert.eq(table.concat(ids or {}, ","), "20:2001,20:2002") +Assert.is_nil(source:statsIdentities({ source_id = "kavita", stable_id = "20:2002" }), + "卷行只看自己") +Assert.is_nil(source:statsIdentities({ source_id = "kavita", stable_id = "10" }), + "单卷 series 直接记在 series 行") + +-- 容器行的作者是 fetchToc 在这次开书里才写回的,identity.book 是开书那一刻的旧快照: +-- 选卷要用重读后的容器行,否则新 series 第一次打开写下的卷行又是「未知作者」。 +books["21"] = { stable_id = "21", title = "合集21", authors = "丁" } +routes["GET /api/Series/21"] = json({ id = 21, name = "合集21", libraryId = 2 }) +local volumes_route = routes["GET /api/Series/volumes"] +routes["GET /api/Series/volumes"] = function(opts) + if query(opts, "seriesId") == "21" then + return json({ + { id = 210, name = "1", chapters = { { id = 2101, titleName = "上", format = 3, pages = 5 } } }, + { id = 211, name = "2", chapters = { { id = 2102, titleName = "下", format = 3, pages = 5 } } }, + }) + end + return volumes_route(opts) +end +source:openBookAsync( + { source_id = "kavita", stable_id = "21", book = { stable_id = "21", title = "合集21" } }, + nil, function() end) +Stubs.flush() +Themed.choose(Themed.last("list"), 1) +Stubs.flush() +Assert.eq(remembered["21:2101"].authors, "丁", "卷行取重读后的容器行,不用开书时的旧快照") +routes["GET /api/Series/volumes"] = volumes_route +books["21"] = nil + +-- 关掉选卷列表 = 取消。 +source:openBookAsync(multi, nil, function(p, e) opened, oerr = p, e end) +Stubs.flush() +list = Themed.last("list") +Assert.eq(list.items[2].mandatory, "已下载") +list:close() +Stubs.flush() +Assert.matches(oerr, "已取消") + +-- 点开系列 = 立即拉一次最新进度:目录缓存 6 小时内不更新,选卷列表要显示服务器上的已读状态。 +do + tocs["8701"] = { + { chapterId = 87010, title = "第1卷", pages = 100, pagesRead = 0, format = 1 }, + { chapterId = 87011, title = "第2卷", pages = 100, pagesRead = 0, format = 1 }, + } + books["8701"] = { stable_id = "8701", title = "系列87", authors = "作者" } + routes["GET /api/Series/8701"] = json({ id = 8701, name = "系列87", libraryId = 2, format = 1 }) + local base_volumes = routes["GET /api/Series/volumes"] + routes["GET /api/Series/volumes"] = function(opts) + if query(opts, "seriesId") ~= "8701" then return base_volumes(opts) end + return json({ + { id = 870, chapters = { { id = 87010, titleName = "第1卷", format = 1, pages = 100, pagesRead = 100 } } }, + { id = 871, chapters = { { id = 87011, titleName = "第2卷", format = 1, pages = 100, pagesRead = 30 } } }, + }) + end + source:openBookAsync({ source_id = "kavita", stable_id = "8701", book = books["8701"] }, nil, + function() end) + Stubs.flush() + Assert.eq(tocs["8701"][1].pagesRead, 100, "打开系列就拉到最新进度") + Assert.eq(tocs["8701"][2].pagesRead, 30) + local live = Themed.last("list") + Assert.eq(live.items[1].mandatory, "已读", "选卷列表按服务器最新进度显示已读") + Assert.eq(live.items[2].mandatory, "在读") + live:close() + Stubs.flush() + routes["GET /api/Series/volumes"] = base_volumes + books["8701"] = nil +end + +-- 封面:系列行取系列封面,卷行取这一卷自己的封面;chapter-cover 是扫描版第一页,不用。 +local cover = source:coverRequest({ stable_id = "10" }) +Assert.eq(cover.url, "http://kav/api/Image/series-cover?seriesId=10") +Assert.eq(cover.headers["x-api-key"], "k") +Assert.eq(cover.authoritative, true, "源封面压过本地抽页 / 旧封面缓存") +-- 目录里能查到这一卷 → volume-cover(「当前阅读」要显示正在读的那一卷)。 +tocs["70"] = { { chapterId = 7001, volumeId = 701, title = "第一卷", pages = 10 } } +local volume_cover = source:coverRequest({ stable_id = "70:7001" }) +Assert.eq(volume_cover.url, "http://kav/api/Image/volume-cover?volumeId=701", "卷行用卷封面") +Assert.eq(volume_cover.authoritative, true) +-- 目录里查不到这一卷(没拉过目录)→ 退回系列封面。 +Assert.eq(source:coverRequest({ stable_id = "71:7101" }).url, + "http://kav/api/Image/series-cover?seriesId=71", "查不到卷退回系列封面") +tocs["70"] = nil +-- 卷身份折叠:图书馆最近阅读按系列归并,点开再选卷。 +Assert.eq(source:volumeParent("20:2002"), "20") +Assert.is_nil(source:volumeParent("20")) + +-- 拉进度:远端 spine + 锚点 → xpointer;没读过算空。 +local volume = { source_id = "kavita", stable_id = "20:2002" } +local remote = { pageNum = 3, bookScrollId = "//body/div[1]/p[5]" } +routes["GET /api/Reader/get-progress"] = function() return json(remote) end +local pos, _err, meta = run("getProgressAsync", volume) +Assert.eq(pos.locator, "/body/DocFragment[4]/body/div/p[5]") +Assert.eq(pos.fraction, 0.3) +Assert.is_nil(pos.page, "epub 不给页码:Kavita 的页是 spine,不是渲染页") +Assert.is_true(meta and meta.page_level == true, "页级源必须声明 page_level:core 才不按百分比判") +Assert.is_nil(_err) +-- 同一 spine:锚点与本机上次同步的位置不同(网页端在同一条里往后读了几页)→ 用远端坐标, +-- 不能返回本地行——否则 core 的 synced 基线永远看不到「云端动过」。 +progress["20:2002"] = { + locator = "/body/DocFragment[4]/body/p[9]/text().3", + fraction = 0.34, + synced = { locator = "/body/DocFragment[4]/body/p[3]/text().0" }, +} +local moved = run("getProgressAsync", volume) +Assert.eq(moved.locator, "/body/DocFragment[4]/body/div/p[5]", "同 spine 锚点变了就要跟远端") +Assert.eq(moved.fraction, 0.3) +-- 同一 spine 且锚点就是上次同步的位置 → 交回本地行(粒度噪声不当冲突,也不跳) +progress["20:2002"].synced = { locator = "/body/DocFragment[4]/body/div[1]/p[5]" } +Assert.eq(run("getProgressAsync", volume), progress["20:2002"]) +-- 同一 spine 但远端只有 spine 粒度(没带锚点 / 锚点解不出)→ 交回本地行,不把人拽回节首。 +routes["GET /api/Reader/get-progress"] = function() return json({ pageNum = 3 }) end +Assert.eq(run("getProgressAsync", volume), progress["20:2002"]) +-- 旧行没有基线(synced 为空)→ 保守交回本地行,不拿不可比的粒度去判 +routes["GET /api/Reader/get-progress"] = function() return json(remote) end +progress["20:2002"].synced = nil +Assert.eq(run("getProgressAsync", volume), progress["20:2002"]) +remote = { pageNum = 0 } +local empty, _e, meta = run("getProgressAsync", volume) +Assert.is_nil(empty) +Assert.is_true(meta.empty) +routes["GET /api/Reader/get-progress"] = { code = 400, body = "" } +_e, _e, meta = run("getProgressAsync", volume) +Assert.is_true(meta.empty) + +-- 推进度:spine + 章内路径;读完发 pages。 +local sent +routes["POST /api/Reader/progress"] = function(opts) + sent = JSON.decode(opts.body) + return { code = 200, body = "" } +end +Assert.is_true(run("putProgressAsync", volume, { fraction = 0.25, locator = "/body/DocFragment[3]/body/div/p[2]/text().0" })) +Assert.eq(sent.pageNum, 2) +Assert.eq(sent.bookScrollId, "//body/div[1]/p[2]") +Assert.eq(sent.chapterId, 2002) +Assert.eq(sent.volumeId, 201) +Assert.eq(sent.libraryId, 2) +Assert.eq(sent.seriesId, 20) +run("putProgressAsync", volume, { fraction = 1, locator = "/body/DocFragment[10]/body/p" }) +Assert.eq(sent.pageNum, 10) + +-- PDF:按页换算;series 行靠登记的文件名认卷。 +local pdf = { source_id = "kavita", stable_id = "30" } +Assert.eq(run("openBookAsync", pdf, nil), nil, "文件头不是 %PDF") +download.body = "%PDF-1.7" +Assert.eq(run("openBookAsync", pdf, nil), WORK .. "/30/3000.pdf") +run("putProgressAsync", pdf, { fraction = 0.2, page = 11, total_pages = 50 }) +Assert.eq(sent.pageNum, 10) +Assert.is_nil(sent.bookScrollId) +routes["GET /api/Reader/get-progress"] = function() return json({ pageNum = 20 }) end +pos = run("getProgressAsync", pdf) +Assert.eq(pos.page, 21) +Assert.eq(pos.total_pages, 50) +progress["30"] = { page = 21, fraction = 0.41 } +Assert.eq(run("getProgressAsync", pdf), progress["30"]) + +-- 离线且目录过期:卷信息退回旧目录,进度照样能推(推送本身由队列等网)。 +toc_fresh, online = false, false +stale["20"] = JSON.encode(tocs["20"]) +Assert.is_true(run("putProgressAsync", volume, { fraction = 0.5, locator = "/body/DocFragment[6]/body/p" })) +Assert.eq(sent.pageNum, 5) +toc_fresh, online = true, true + +-- 推送(spec §8):先按章对账一次,再逐条新建 / 更新;用 do 收住局部变量(Lua 单函数 200 个上限)。 +do + -- 注解:推送前先按章对账一次(一批一次 GET),create 必须拿到 id,写失败整批留脏。 + -- 远端仓库 / 当前用户 / 服务端落库行为全部打桩,断言只看向外的请求与回填。 + local epub = { + ["META-INF/container.xml"] = [[春眠不觉晓
处处闻啼鸟
]], + } + package.loaded["ffi/archiver"] = { Reader = { new = function() + return { + open = function(_self, file) return file == WORK .. "/20:2002/2002.epub" end, + iterate = function() return function() end end, + extractToMemory = function(_self, name) return epub[name] end, + close = function() end, + } + end } } + -- 坐标守卫 / 远端赢只留日志:收起来断言,不弹窗也不干扰别的断言。 + local push_warnings = {} + do + local log = require("utils.log") + log.warn = function(...) push_warnings[#push_warnings + 1] = table.concat({ ... }, " ") end + end + local function warned(text) + for _idx, line in ipairs(push_warnings) do + if line:find(text, 1, true) then return true end + end + return false + end + + -- 远端注解仓库:GET all 读它,create / update 往里写,bulk-delete 从它删;属主固定成当前用户。 + local USER, next_id = 5, 101 + local remote, created, updated, deleted = {}, {}, {}, {} + local fail_list, fail_create, fail_update, blank_create, drop_create, create_fail_at + local fail_delete, reject_delete, list_calls = false, false, 0 + routes["GET /api/Users/me"] = json({ id = USER }) + routes["GET /api/Annotation/all"] = function(opts) + list_calls = list_calls + 1 + if fail_list then return { code = 500, body = "" } end + local chapter = tonumber(query(opts, "chapterId")) or 0 + local out = {} + for _idx, item in ipairs(remote[chapter] or {}) do out[#out + 1] = item end + return json(out) + end + --- 服务端落库:create 分配 id;update 只覆盖可写四字段(坐标改不了,与 Kavita 一致)。 + local function persist(body, is_update) + local chapter = tonumber(body.chapterId) or 0 + remote[chapter] = remote[chapter] or {} + local item + if is_update then + for _idx, row in ipairs(remote[chapter]) do + if tonumber(row.id) == tonumber(body.id) then item = row end + end + else + body.id, next_id = next_id, next_id + 1 + body.ownerUserId = USER + item = body + remote[chapter][#remote[chapter] + 1] = item + end + if item then + item.comment, item.commentHtml = body.comment, body.commentHtml + item.selectedSlotIndex, item.containsSpoiler = body.selectedSlotIndex, body.containsSpoiler + end + return item + end + routes["POST /api/Annotation/create"] = function(opts) + local body = JSON.decode(opts.body) + created[#created + 1] = body + if fail_create or (create_fail_at and #created >= create_fail_at) then return { code = 500, body = "" } end + local item + if not drop_create then item = persist(body, false) end + -- blank_create:反代吞掉 DTO(2xx 空体),但服务端确实建成了。 + if blank_create or not item then return { code = 200, body = "" } end + return json({ id = item.id }) + end + routes["POST /api/Annotation/update"] = function(opts) + local body = JSON.decode(opts.body) + updated[#updated + 1] = body + if fail_update then return { code = 500, body = "" } end + persist(body, true) + return json({ id = body.id }) + end + -- 删除:body 是裸 id 数组;不存在的 id 静默忽略(与 Kavita 一致)。 + -- reject_delete 用来模拟「不是你的 / 服务端拒绝」的 400 分支。 + routes["POST /api/Annotation/bulk-delete"] = function(opts) + local ids = JSON.decode(opts.body) + deleted[#deleted + 1] = ids + if fail_delete then return { code = 500, body = "" } end + if reject_delete then return { code = 400, body = "" } end + local wanted = {} + for _idx, id in ipairs(ids) do wanted[tonumber(id)] = true end + for _chapter, rows in pairs(remote) do + for i = #rows, 1, -1 do + if wanted[tonumber(rows[i].id)] then table.remove(rows, i) end + end + end + return { code = 200, body = "" } + end + --- 每个场景从干净状态开始:远端仓库、写请求计数、故障开关。 + local function resetPush() + remote, next_id, created, updated, deleted = {}, 101, {}, {}, {} + fail_list, fail_create, fail_update = false, false, false + blank_create, drop_create, create_fail_at = false, false, nil + fail_delete, reject_delete, list_calls = false, false, 0 + push_warnings = {} + end + + -- 非 epub:零请求,pushed=0(核心据此不谎报「同步过」)。 + resetPush() + local calls_before = #calls + local ok_epub, _err_epub, data_epub = run("pushNotesAsync", pdf, + { { drawer = "lighten", text = "图", pos0 = "x" } }) + Assert.is_true(ok_epub) + Assert.eq(data_epub.pushed, 0) + Assert.eq(#calls, calls_before, "非 epub 一个请求都不发") + + -- 对账 GET 失败:宁可这轮不推,也不盲建重复;一个写请求都不发。 + resetPush() + fail_list = true + local ok_net, err_net = run("pushNotesAsync", volume, + { { drawer = "lighten", text = "春眠\n不觉晓", note = "好诗", pos0 = "/body/DocFragment[1]/body/p[1]/text().0" } }) + Assert.is_nil(ok_net) + Assert.matches(err_net, "500") + Assert.len(created, 0) + Assert.len(updated, 0) + + -- 新建:请求体按 §5.1 的 Web 兼容形态;成功判据是 DTO 里有 id,id 原地回填给核心落库。 + resetPush() + local anns = { + { drawer = "lighten", text = "春眠\n不觉晓", note = "好诗", pos0 = "/body/DocFragment[1]/body/p[1]/text().0" }, + { drawer = "underscore", text = "处处闻啼鸟", pos0 = "/body/DocFragment[1]/body/p[2]/text().0" }, + } + local ok_new, err_new, data_new = run("pushNotesAsync", volume, anns) + Assert.is_true(ok_new) + Assert.is_nil(err_new) + Assert.eq(data_new.pushed, 2) + Assert.eq(data_new.adopted, 0) + Assert.len(created, 2) + Assert.len(updated, 0) + Assert.eq(created[1].xPath, "//body/p[1]") + Assert.eq(created[1].endingXPath, "//body/p[1]") + Assert.eq(created[1].pageNumber, 0) + Assert.eq(created[1].selectedText, "春眠\n不觉晓") + Assert.eq(created[1].highlightCount, 6, "按 UTF-16 码元计") + Assert.eq(created[1].chapterId, 2002) + Assert.eq(created[1].volumeId, 201) + Assert.eq(created[1].libraryId, 2) + Assert.eq(created[1].seriesId, 20) + Assert.eq(JSON.decode(created[1].comment).ops[1].insert, "好诗\n", "备注写 Quill Delta,网页端才打得开") + Assert.eq(created[1].commentHtml, "好诗
") + Assert.eq(created[2].comment, "{}", "空备注写空 Delta(网页端 JSON.parse 不崩)") + Assert.eq(created[2].commentHtml, "") + Assert.eq(anns[1].kavita_id, 101) + Assert.eq(anns[1].kavita_note, "好诗") + Assert.eq(anns[1].kavita_xpath, "//body/p[1]", "远端坐标回填给诊断与坐标守卫") + Assert.eq(anns[2].kavita_id, 102) + Assert.eq(anns[2].kavita_note, "", "空备注的基线是空串,不是 nil(否则每轮都判改过)") + + -- 再推一轮:没有改动 → 零请求,pushed=0。 + created, updated = {}, {} + local ok_same, _err_same, data_same = run("pushNotesAsync", volume, anns) + Assert.is_true(ok_same) + Assert.eq(data_same.pushed, 0) + Assert.len(created, 0, "推过的不重建") + Assert.len(updated, 0) + + -- 改备注且远端没变 → 一次 update(整条替换);未改动的槽位 / 剧透回传远端原值。 + anns[1].kavita_slot, anns[1].kavita_spoiler = 3, true + anns[1].note = "改了" + local ok_up, _err_up, data_up = run("pushNotesAsync", volume, anns) + Assert.is_true(ok_up) + Assert.eq(data_up.pushed, 1) + Assert.eq(data_up.adopted, 0, "update 是写入,只算 pushed;adopted 只数「认到 id 但没写」") + Assert.eq(data_up.conflicts, 0) + Assert.len(updated, 1) + Assert.eq(updated[1].id, 101) + Assert.eq(updated[1].xPath, "//body/p[1]", "update 也带坐标(服务端忽略,形状要对)") + Assert.eq(JSON.decode(updated[1].comment).ops[1].insert, "改了\n") + Assert.eq(updated[1].selectedSlotIndex, 3, "颜色不回传就会被服务端清成默认") + Assert.eq(updated[1].containsSpoiler, true) + Assert.eq(anns[1].kavita_note, "改了") + + -- 坐标守卫:现算锚点与远端记录不一致 → 跳过 update 并留日志(服务端改不了坐标,硬发会写到旧位置)。 + anns[1].note = "坐标漂了" + anns[1].kavita_xpath = "//body/p[9]" + local ok_guard, _err_guard, data_guard = run("pushNotesAsync", volume, anns) + Assert.is_true(ok_guard) + Assert.eq(data_guard.pushed, 0) + Assert.len(updated, 1, "坐标不一致不 update") + Assert.is_true(warned("drifted"), "跳过的原因要能在日志里定位") + Assert.eq(anns[1].kavita_note, "改了", "没写成功,基线不能动") + anns[1].kavita_xpath = nil + + -- 双方都改过:远端赢,零写请求;本地文本存 kavita_local_note 备查,基线不动(等下轮 pull 采纳远端)。 + anns[1].note, anns[1].kavita_note = "设备改的", "上次同步" + remote[2002][1].comment, remote[2002][1].commentHtml = nil, "网页改的
" + local ok_lose, _err_lose, data_lose = run("pushNotesAsync", volume, anns) + Assert.is_true(ok_lose) + Assert.eq(data_lose.pushed, 0) + Assert.eq(data_lose.conflicts, 1) + Assert.len(updated, 1) + Assert.eq(anns[1].kavita_local_note, "设备改的") + Assert.eq(anns[1].kavita_note, "上次同步") + Assert.is_true(warned("remote"), "远端赢要留日志") + + -- 对账列表按 ownerUserId 收窄:账号开了「查看他人注解」后混进来的条目不能被认领 / 改写。 + resetPush() + remote[2002] = { { id = 5, ownerUserId = 99, chapterId = 2002, xPath = "//body/p[1]", endingXPath = "//body/p[1]", + selectedText = "春眠\n不觉晓", commentHtml = "别人
" } } + local mine = { drawer = "lighten", text = "春眠\n不觉晓", pos0 = "/body/DocFragment[1]/body/p[1]/text().0" } + Assert.is_true(run("pushNotesAsync", volume, { mine })) + Assert.eq(mine.kavita_id, 101, "别人的同键注解不认领") + Assert.len(created, 1) + + -- 首次认领:本地没 id、远端同键已有 → 采纳(同键多条取 id 最小),不新建。 + resetPush() + remote[2002] = { + { id = 43, ownerUserId = USER, chapterId = 2002, xPath = "//body/p[1]", endingXPath = "//body/p[1]", + selectedText = "春眠\n不觉晓", commentHtml = "重复
" }, + { id = 37, ownerUserId = USER, chapterId = 2002, xPath = "//body/p[1]", endingXPath = "//body/p[1]", + selectedText = "春眠 不觉晓", commentHtml = "网页写的
" }, + } + local claimed = { drawer = "lighten", text = "春眠\n不觉晓", pos0 = "/body/DocFragment[1]/body/p[1]/text().0" } + local ok_claim, _err_claim, data_claim = run("pushNotesAsync", volume, { claimed }) + Assert.is_true(ok_claim) + Assert.eq(claimed.kavita_id, 37, "同键多条取 id 最小") + Assert.is_nil(claimed.kavita_note, "远端备注不当基线:本地 note 还是空的,等 pull 采纳") + Assert.eq(data_claim.pushed, 0) + Assert.eq(data_claim.adopted, 1, "只认领 id、没写远端 → adopted") + Assert.len(created, 0) + Assert.len(updated, 0, "首次认领不覆盖远端非空备注") + + -- 认领过的那条再推(本地 note 仍空、pull 还没跑)→ 零写请求。 + -- 基线若被写成远端文本,这里就会被判成「用户清空了备注」,一次 update 抹掉网页作者的内容。 + local ok_again, _err_again, data_again = run("pushNotesAsync", volume, { claimed }) + Assert.is_true(ok_again) + Assert.eq(data_again.pushed, 0) + Assert.len(updated, 0, "认领后不能反手把远端的备注覆盖成空") + + -- 认领后、pull 之前用户补了备注 → 这是真实编辑,直接 update(没有基线不等于冲突)。 + local later = { drawer = "lighten", text = "春眠\n不觉晓", note = "补的备注", kavita_id = 37, + pos0 = "/body/DocFragment[1]/body/p[1]/text().0" } + Assert.is_true(run("pushNotesAsync", volume, { later })) + Assert.eq(updated[#updated].id, 37) + Assert.eq(JSON.decode(updated[#updated].comment).ops[1].insert, "补的备注\n") + Assert.eq(later.kavita_note, "补的备注") + + -- 首次认领时本地备注非空且不同 → 认到 id 后 update 那一条(设备侧确实改了备注)。 + local named = { drawer = "lighten", text = "春眠\n不觉晓", note = "我的备注", + pos0 = "/body/DocFragment[1]/body/p[1]/text().0" } + Assert.is_true(run("pushNotesAsync", volume, { named })) + Assert.eq(named.kavita_id, 37) + Assert.eq(updated[#updated].id, 37, "首次认领不新建") + Assert.eq(JSON.decode(updated[#updated].comment).ops[1].insert, "我的备注\n") + Assert.eq(named.kavita_note, "我的备注") + + -- 有 id、远端已无该 id(网页端删了)→ 不重建、不复活(交给 pull 的 dropped 通道)。 + local ghost = { drawer = "lighten", text = "春眠\n不觉晓", note = "改过", kavita_id = 99, kavita_note = "旧", + pos0 = "/body/DocFragment[1]/body/p[1]/text().0" } + local writes_before = #created + #updated + Assert.is_true(run("pushNotesAsync", volume, { ghost })) + Assert.eq(#created + #updated, writes_before, "远端删了不重建") + Assert.eq(ghost.kavita_id, 99) + Assert.is_nil(ghost.kavita_local_note) + + -- 本批墓碑的 id 先剔出对账列表:删了又原地划一条同键的,不能认领到「即将删除」的那条。 + -- 先写后删:新建成功后一次 bulk-delete 删掉旧 id,远端最终只剩新建的那条。 + remote[2002] = { { id = 37, ownerUserId = USER, chapterId = 2002, xPath = "//body/p[1]", endingXPath = "//body/p[1]", + selectedText = "春眠\n不觉晓", commentHtml = "旧
" } } + local tomb = { kavita_id = 37, kavita_deleted = true, datetime = "2026-10-01" } + local redo = { drawer = "lighten", text = "春眠\n不觉晓", note = "新的", pos0 = "/body/DocFragment[1]/body/p[1]/text().0" } + local redo_batch = { tomb, redo } + Assert.is_true(run("pushNotesAsync", volume, redo_batch)) + Assert.is_true(redo.kavita_id ~= 37, "墓碑那条不在认领范围内") + Assert.eq(redo.kavita_id, 101, "同键的划线重建一条") + Assert.eq(#deleted, 1) + Assert.eq(deleted[1][1], 37, "body 是裸 id 数组") + Assert.eq(#redo_batch, 1, "删除成功后墓碑从 payload 出列") + Assert.eq(redo_batch[1], redo) + Assert.eq(#remote[2002], 1, "删一条 + 原地划一条同键:远端只剩新建的那条") + Assert.eq(remote[2002][1].id, 101) + + -- 删除高亮:墓碑单独一批也能推(没有 create/update),200 即出列、远端少一条; + -- 墓碑出列后再推一轮是零请求。 + resetPush() + remote[2002] = { { id = 51, ownerUserId = USER, chapterId = 2002, selectedText = "旧划线", + commentHtml = "", comment = "" } } + local only_tomb = { { kavita_id = 51, kavita_deleted = true, datetime = "2026-10-01" } } + local ok_del, _err_del, data_del = run("pushNotesAsync", volume, only_tomb) + Assert.is_true(ok_del) + Assert.eq(data_del.pushed, 0) + Assert.eq(data_del.deleted, 1, "deleted 如实计数") + Assert.eq(deleted[1][1], 51) + Assert.len(only_tomb, 0, "墓碑出列") + Assert.len(remote[2002], 0, "远端确实少一条") + local quiet_before = #calls + local ok_quiet, _err_quiet, data_quiet = run("pushNotesAsync", volume, only_tomb) + Assert.is_true(ok_quiet) + Assert.eq(data_quiet.deleted, 0) + Assert.eq(#calls, quiet_before, "墓碑已出列,再推零请求") + + -- 远端早就没有这个 id(别处删过 / 从没推成功):bulk-delete 回 200 一样出列,不报错。 + resetPush() + local ghost_tomb = { { kavita_id = 999, kavita_deleted = true, datetime = "d" } } + local ok_idem, _err_idem, data_idem = run("pushNotesAsync", volume, ghost_tomb) + Assert.is_true(ok_idem) + Assert.eq(data_idem.deleted, 1) + Assert.len(ghost_tomb, 0, "远端已删的墓碑幂等出列") + + -- 删除失败(非 400):整批 cb(nil),墓碑留在 payload 里;下轮重试成功才出列。 + resetPush() + remote[2002] = { { id = 52, ownerUserId = USER, chapterId = 2002, selectedText = "旧", + commentHtml = "", comment = "" } } + local retry_tomb = { { kavita_id = 52, kavita_deleted = true, datetime = "d" } } + fail_delete = true + local ok_retry, err_retry = run("pushNotesAsync", volume, retry_tomb) + Assert.is_nil(ok_retry) + Assert.matches(err_retry, "500") + Assert.len(retry_tomb, 1, "失败时墓碑保留,快照留脏") + Assert.len(remote[2002], 1) + fail_delete = false + local ok_again_del, _err_again_del, data_again_del = run("pushNotesAsync", volume, retry_tomb) + Assert.is_true(ok_again_del) + Assert.eq(data_again_del.deleted, 1, "重试成功") + Assert.len(retry_tomb, 0) + Assert.len(remote[2002], 0) + + -- 写失败时一个删除都不发:先写后删,写入不留半成品删除。 + resetPush() + remote[2002] = { { id = 53, ownerUserId = USER, chapterId = 2002, selectedText = "旧", + commentHtml = "", comment = "" } } + fail_create = true + local write_fail_batch = { + { kavita_id = 53, kavita_deleted = true, datetime = "d" }, + { drawer = "lighten", text = "春眠\n不觉晓", note = "a", pos0 = "/body/DocFragment[1]/body/p[1]/text().0" }, + } + local ok_wf, err_wf = run("pushNotesAsync", volume, write_fail_batch) + Assert.is_nil(ok_wf) + Assert.matches(err_wf, "500") + Assert.len(deleted, 0, "create 失败就不发删除") + Assert.len(write_fail_batch, 2, "墓碑保留") + + -- 400(服务端拒绝 / 不是你的)→ 重拉一次该章列表,仍在那里的丢弃墓碑并记日志,不无限重试。 + resetPush() + remote[2002] = { { id = 54, ownerUserId = USER, chapterId = 2002, selectedText = "删不掉", + commentHtml = "", comment = "" } } + reject_delete = true + local rejected_tomb = { { kavita_id = 54, kavita_deleted = true, datetime = "d" } } + local ok_rej, _err_rej, data_rej = run("pushNotesAsync", volume, rejected_tomb) + Assert.is_true(ok_rej, "400 按对账结果收尾,不让整批反复失败") + Assert.eq(data_rej.deleted, 0, "远端还在,不算删成功") + Assert.len(rejected_tomb, 0, "仍在列表里的墓碑丢弃,下轮不再重试") + Assert.is_true(warned("delete rejected"), "丢弃要有日志") + Assert.eq(list_calls, 2, "400 后重拉一次该章列表") + Assert.len(remote[2002], 1, "远端那条原样保留") + local after_rej = #calls + Assert.is_true(run("pushNotesAsync", volume, rejected_tomb)) + Assert.eq(#calls, after_rej, "不再有墓碑就零请求") + + -- 400 且 id 已不在列表里 → 目标态已达成,墓碑出列并计入 deleted。 + resetPush() + reject_delete = true + local gone_tomb = { { kavita_id = 55, kavita_deleted = true, datetime = "d" } } + local ok_gone, _err_gone, data_gone = run("pushNotesAsync", volume, gone_tomb) + Assert.is_true(ok_gone) + Assert.eq(data_gone.deleted, 1, "不在列表里 = 已经删掉") + Assert.len(gone_tomb, 0) + + -- create 回空体(反代吞了 DTO):§8.3 的补偿只查**同一轮**对账列表(一批一次 GET), + -- 那份列表是创建前取的、里面没有刚建的这条 → 无法确认,该条失败留脏,不为它再补发一次 GET。 + resetPush() + blank_create = true + local lone = { drawer = "lighten", text = "春眠\n不觉晓", note = "n", pos0 = "/body/DocFragment[1]/body/p[1]/text().0" } + local ok_blank, err_blank = run("pushNotesAsync", volume, { lone }) + Assert.is_nil(ok_blank, "无 id 的 2xx 不算成功") + Assert.not_nil(err_blank) + Assert.is_nil(lone.kavita_id, "没确认到 id 就不回填") + Assert.eq(list_calls, 1, "一批只对一次账:回空体不再补发 GET") + -- 下一轮对账就能看到服务端其实落了那条:按 key 认领,不重复建。 + blank_create = false + created = {} + Assert.is_true(run("pushNotesAsync", volume, { lone })) + Assert.eq(lone.kavita_id, 101, "下轮对账按 key 认领,回填 id") + Assert.len(created, 0, "认到同键就不新建") + Assert.len(remote[2002], 1, "远端最终只有一条") + + -- 回查也找不到(服务端真没落库)→ 该条失败、整批 cb(nil) 留脏,绝不当成功。 + resetPush() + drop_create = true + local dropped_ann = { drawer = "lighten", text = "春眠\n不觉晓", note = "n", + pos0 = "/body/DocFragment[1]/body/p[1]/text().0" } + local ok_drop, err_drop = run("pushNotesAsync", volume, { dropped_ann }) + Assert.is_nil(ok_drop) + Assert.not_nil(err_drop) + Assert.is_nil(dropped_ann.kavita_id) + + -- 全有或全无:一条写失败 → 整批 cb(nil);已建成的条目下轮由对账认领,不会重复。 + resetPush() + local first = { drawer = "lighten", text = "春眠\n不觉晓", note = "a", pos0 = "/body/DocFragment[1]/body/p[1]/text().0" } + local second = { drawer = "lighten", text = "处处闻啼鸟", note = "b", pos0 = "/body/DocFragment[1]/body/p[2]/text().0" } + create_fail_at = 2 + local ok_fail, err_fail = run("pushNotesAsync", volume, { first, second }) + Assert.is_nil(ok_fail) + Assert.matches(err_fail, "500") + Assert.eq(first.kavita_id, 101) + Assert.is_nil(second.kavita_id) + first.kavita_id = nil -- cb(nil) 后核心不落库,这条 id 就丢了 + create_fail_at = nil + created, updated = {}, {} + Assert.is_true(run("pushNotesAsync", volume, { first, second })) + Assert.eq(first.kavita_id, 101, "上轮已建成的条目由对账按 key 认领") + Assert.len(created, 1, "只补建真正缺的那条") + Assert.eq(second.kavita_id, 102) + + -- 锚点失败(找不回段落):不带空 xPath 发出去(会跟别的空锚点挤成同键),整批不发送、留脏重试。 + resetPush() + local good = { drawer = "lighten", text = "春眠\n不觉晓", note = "a", pos0 = "/body/DocFragment[1]/body/p[1]/text().0" } + local lost = { drawer = "lighten", text = "𠀀找不到", pos0 = "/body/DocFragment[3]/body/p/text().0" } + local ok_lost, err_lost = run("pushNotesAsync", volume, { good, lost }) + Assert.is_nil(ok_lost) + Assert.not_nil(err_lost) + Assert.len(created, 0, "锚点不齐就一个都不发") + Assert.len(updated, 0) + + -- 书签(没有 drawer)不推,也不算失败。 + resetPush() + local ok_mark, _err_mark, data_mark = run("pushNotesAsync", volume, + { { text = "书签", pos0 = "/body/DocFragment[1]/body/p" } }) + Assert.is_true(ok_mark) + Assert.eq(data_mark.pushed, 0) + Assert.len(created, 0) + + -- 快照:清洗保留 Kavita 全字段(白名单漏一个就静默消失),保存时按 pos0 从上一版接过 id。 + local clean = source:cleanAnnotations({ + { datetime = "d", page = 1, drawer = "lighten", text = "x", pos0 = "p", kavita_id = 71, kavita_note = "n", junk = 1, + pageNumber = 3, + kavita_comment = "{}", kavita_comment_html = "", kavita_slot = 0, kavita_spoiler = false, + kavita_modified = "m", kavita_xpath = "//body/p[1]", kavita_ending_xpath = "//body/p[1]", + kavita_unlocated = true, kavita_local_note = "被远端覆盖的旧文本" }, + { text = "没有时间的丢掉" }, + }, 10) + Assert.len(clean, 1) + Assert.eq(clean[1].kavita_id, 71) + Assert.eq(clean[1].pageNumber, 3, "pageNumber 不是 kavita_ 前缀,但也必须过白名单(定位提示)") + Assert.eq(clean[1].kavita_note, "n") + Assert.eq(clean[1].kavita_comment, "{}") + Assert.eq(clean[1].kavita_comment_html, "") + Assert.eq(clean[1].kavita_slot, 0) + Assert.eq(clean[1].kavita_spoiler, false) + Assert.eq(clean[1].kavita_modified, "m") + Assert.eq(clean[1].kavita_xpath, "//body/p[1]") + Assert.eq(clean[1].kavita_ending_xpath, "//body/p[1]") + Assert.is_true(clean[1].kavita_unlocated) + Assert.eq(clean[1].kavita_local_note, "被远端覆盖的旧文本") + Assert.eq(clean[1].total_pages, 10) + Assert.is_nil(clean[1].junk, "白名单外的字段仍丢弃") + + -- 无 page 的两类条目必须放行:未定位(只有 xPath)、墓碑(只有 kavita_deleted)。 + -- 靠「构造期用 xPath / 墓碑标记当占位」过 Normalize.clean,清洗后把占位清空。 + local unlocated = source:cleanAnnotations({ + { datetime = "d", text = "云端条", note = "", kavita_id = 72, kavita_xpath = "//body/p[9]" }, + { datetime = "d", kavita_id = 73, kavita_deleted = true }, + { datetime = "d", text = "没有任何坐标" }, + }, 10) + Assert.len(unlocated, 2, "无时间 / 无坐标的条目仍然丢掉") + Assert.eq(unlocated[1].kavita_id, 72) + Assert.eq(unlocated[1].kavita_xpath, "//body/p[9]", "未定位条目保留全部 kavita_* 字段") + Assert.is_nil(unlocated[1].page, "占位只在构造期用,清洗后清空") + Assert.eq(unlocated[1].total_pages, 10) + Assert.eq(unlocated[2].kavita_id, 73) + Assert.is_true(unlocated[2].kavita_deleted) + Assert.is_nil(unlocated[2].page) + + -- 保存时:pos0 对得上的接过 id;没有 pos0 的未定位条目原样搬进新快照, + -- 否则一次普通保存就把「数据在、画不出」的云端条目洗掉。 + local previous = { + { pos0 = "p", kavita_id = 71, kavita_note = "n" }, + { pos0 = "gone", kavita_id = 9, datetime = "d-gone" }, + { datetime = "d", text = "云端条", kavita_id = 72, kavita_note = "", kavita_xpath = "//body/p[9]" }, + } + local current = source:prepareLocalAnnotations(previous, + { { pos0 = "p", note = "新" }, { pos0 = "q" } }) + Assert.eq(current[1].kavita_id, 71) + Assert.eq(current[1].kavita_note, "n", "备注差异留给推送时比对") + Assert.is_nil(current[2].kavita_id) + Assert.eq(#current, 3, "未定位条目搬进新快照") + Assert.eq(current[3].kavita_id, 72) + Assert.eq(current[3].kavita_xpath, "//body/p[9]") + Assert.is_nil(current[3].pos0) + local deduped = source:prepareLocalAnnotations(previous, + { { pos0 = "p", note = "新" }, { kavita_id = 72, text = "已经在快照里" } }) + Assert.eq(#deduped, 2, "快照里已有的 id 不重复搬") + + -- 本地删除(spec §9.1):被删条目按 pos0 在上一版里找到、且那条有 id → 追加墓碑。 + -- 墓碑不带 pos/page(画不出来),但带 id 与基线备注;阅读器与 doc_settings 都不画它。 + local with_id = source:prepareLocalAnnotations(previous, + { { pos0 = "p", note = "新" } }, { pos0 = "gone", text = "删了" }) + Assert.eq(#with_id, 3, "剩余条目 + 未定位条目 + 墓碑") + local tomb = with_id[3] + Assert.is_true(tomb.kavita_deleted) + Assert.eq(tomb.kavita_id, 9, "墓碑按 pos0 取上一版那条的 id") + Assert.is_nil(tomb.pos0, "墓碑没有坐标") + Assert.eq(tomb.datetime, "d-gone") + + -- 被删的是划线转笔记 / 只删备注:条目还在,删除事件判据不成立(changed 传 nil)→ 无墓碑。 + local note_change = source:prepareLocalAnnotations(previous, + { { pos0 = "p", note = "改成笔记" }, { pos0 = "gone", note = "还在" } }) + Assert.eq(#note_change, 3, "条目仍在快照里,不产生墓碑") + for _idx, item in ipairs(note_change) do Assert.is_nil(item.kavita_deleted) end + + -- 没 id 的本地划线被删:本来就没推到远端 → 不产生墓碑;pos0 对不上 / 没 pos0 同理(只漏删不误删)。 + local no_id_previous = { { pos0 = "local", text = "纯本地", datetime = "d" } } + local no_id = source:prepareLocalAnnotations(no_id_previous, {}, + { pos0 = "local", text = "纯本地" }) + Assert.len(no_id, 0, "无 id 的删除不生成墓碑") + local no_pos = source:prepareLocalAnnotations(previous, {}, { text = "没有坐标" }) + Assert.len(no_pos, 1, "没有 pos0:只剩未定位条目,不生成墓碑") + local miss = source:prepareLocalAnnotations(previous, {}, { pos0 = "other", text = "对不上" }) + Assert.len(miss, 1, "pos0 在上一版找不到就不生成墓碑") + + -- 后续保存从上一版重新接上墓碑,直到推送成功把它清掉;已有 id 的不重复搬。 + local with_tomb_previous = { + { pos0 = "p", kavita_id = 71, kavita_note = "n" }, + { datetime = "d", kavita_id = 9, kavita_deleted = true }, + } + local reattached = source:prepareLocalAnnotations(with_tomb_previous, + { { pos0 = "p", note = "新" } }) + Assert.eq(#reattached, 2) + Assert.is_true(reattached[2].kavita_deleted) + Assert.eq(reattached[2].kavita_id, 9) +end + +-- 远端删除回流(spec §9.2):seen 按远端**全量** id 建,未定位条目仍占位; +-- 输出只画可渲染的远端条目;本地带 id 但远端没有 → 丢弃并计入 dropped。 +do + local remote = { + { datetime = "d1", page = "/body/p[1].0", pos0 = "/body/p[1].0", pos1 = "/body/p[1].5", + drawer = "lighten", text = "远端还在", kavita_id = 1 }, + { datetime = "d2", kavita_id = 2, kavita_xpath = "//body/p[2]", kavita_unlocated = true }, + } + local current = { + { datetime = "d1", page = "/body/p[1].0", pos0 = "/body/p[1].0", pos1 = "/body/p[1].5", + drawer = "lighten", text = "远端还在", kavita_id = 1 }, + { datetime = "d2", page = "/body/p[2].0", pos0 = "/body/p[2].0", pos1 = "/body/p[2].5", + drawer = "lighten", text = "本地定位过", kavita_id = 2 }, + { datetime = "d3", page = "/body/p[3].0", pos0 = "/body/p[3].0", pos1 = "/body/p[3].5", + drawer = "lighten", text = "远端删了", kavita_id = 3 }, + { datetime = "d4", page = "/body/p[4].0", pos0 = "/body/p[4].0", pos1 = "/body/p[4].5", + drawer = "lighten", text = "纯本地" }, + } + local merged, dropped = source:mergeAnnotations(remote, current, nil, false) + Assert.eq(#merged, 3, "远端已定位 1 条 + 未定位的本地副本 + 纯本地 1 条") + Assert.eq(merged[1].kavita_id, 1) + Assert.eq(merged[2].kavita_id, 2, "未定位远端不画,但本地已定位的那条保留") + Assert.is_nil(merged[3].kavita_id) + Assert.eq(dropped, 1, "只有远端确实没有的 id 算 dropped") + for _idx, item in ipairs(merged) do Assert.is_true(item.kavita_id ~= 3) end + + -- 远端条目与本地同 id 只画远端那份(本地被替换),不算删除。 + local replaced, replaced_dropped = source:mergeAnnotations( + { remote[1] }, { { datetime = "d1", page = "old", pos0 = "old", pos1 = "old", + drawer = "lighten", text = "本地旧坐标", kavita_id = 1 } }, nil, false) + Assert.eq(#replaced, 1) + Assert.eq(replaced[1].page, "/body/p[1].0") + Assert.eq(replaced_dropped, 0) + + -- 离线 / 未定位全败:远端列表为空但本地都没有 id 时一条都不丢。 + local kept, kept_dropped = source:mergeAnnotations({}, { + { datetime = "d4", page = "/body/p[4].0", pos0 = "/body/p[4].0", pos1 = "/body/p[4].5", + drawer = "lighten", text = "纯本地" }, + }, nil, false) + Assert.eq(#kept, 1) + Assert.eq(kept_dropped, 0, "离线没有 id 集合时不判删除") +end + +-- 远端同键重复(历史推送窗口的产物:真书 7460:11285 的 id 37 / 43 同 xPath 同文本, +-- spec §6「同键多条取 id 最小」/ §13.1 B):只画 id 最小那条,其余不渲染、也不当远端已删。 +do + local XPATH = "//body/DocFragment[24]/body/div[3]/p[2]" + local function remoteAnn(id, over) + local item = { + datetime = "d", page = "/body/p[24].0", pos0 = "/body/p[24].0", pos1 = "/body/p[24].5", + drawer = "lighten", text = "既替余以蕙纕兮", kavita_id = id, + kavita_xpath = XPATH, kavita_ending_xpath = XPATH, + } + for key, value in pairs(over or {}) do item[key] = value end + return item + end + local a37, a43 = remoteAnn(37), remoteAnn(43) + + local one, one_dropped, one_deduped = source:mergeAnnotations({ a37, a43 }, {}, nil, false) + Assert.eq(#one, 1, "同键两条只画一条") + Assert.eq(one[1].kavita_id, 37, "同键取 id 最小") + Assert.eq(one_dropped, 0, "去重不是远端删除") + Assert.eq(one_deduped, 1, "被抑制的远端条数走第三返回值") + + local reversed, r_dropped, r_deduped = source:mergeAnnotations({ a43, a37 }, {}, nil, false) + Assert.eq(#reversed, 1) + Assert.eq(reversed[1].kavita_id, 37, "倒序输入仍取 id 最小") + Assert.eq(r_dropped, 0) + Assert.eq(r_deduped, 1) + + -- 不同键的两条都保留(去重键不能退化成「一章一条」)。 + local other = remoteAnn(44, { + kavita_xpath = "//body/DocFragment[24]/body/div[3]/p[3]", + kavita_ending_xpath = "//body/DocFragment[24]/body/div[3]/p[3]", + text = "另一段划线", + }) + local both, both_dropped, both_deduped = source:mergeAnnotations({ a37, other }, {}, nil, false) + Assert.eq(#both, 2) + Assert.eq(both_dropped, 0) + Assert.eq(both_deduped, 0) + + -- 旧 doc_settings 里还留着一条带 43 的本地副本:远端 43 被抑制(id 仍在全量集合里), + -- 本地那份不能再画一遍,也不能算 dropped —— 否则合法去重会被条数保护当成远端删除。 + local local43 = { + datetime = "d", page = "/body/old.0", pos0 = "/body/old.0", pos1 = "/body/old.5", + drawer = "lighten", text = "既替余以蕙纕兮", kavita_id = 43, + } + local single, s_dropped, s_deduped = source:mergeAnnotations({ a37, a43 }, { local43 }, nil, false) + Assert.eq(#single, 1, "本地 43 不重复渲染") + Assert.eq(single[1].kavita_id, 37, "画的是 id 最小那条") + Assert.eq(s_dropped, 0, "远端 43 只是被抑制,不算远端已删") + Assert.eq(s_deduped, 1) +end + +-- 拉取:开书时把云端 epub 注解落库(入库不定位)。每章一次 GET,按 ownerUserId 收窄; +-- authoritative 恒 false(远端为空不代表本地该清空),失败就 cb(nil, err),快照不动。 +local ann_calls = {} +local remote_anns = { + { -- 网页端写的:Delta + HTML + 纯文本都有;颜色槽 2 = blue。 + id = 501, ownerUserId = 5, chapterId = 2002, + xPath = "//body/p[1]", endingXPath = "//body/p[1]", + selectedText = "春眠不觉晓", + comment = '{"ops":[{"insert":"记一笔\\n"}]}', + commentHtml = "记一笔
", commentPlainText = "记一笔", + selectedSlotIndex = 2, containsSpoiler = true, + createdUtc = os.date("!%Y-%m-%dT%H:%M:%S", 1790000000) .. ".789", + lastModifiedUtc = "2026-10-04T05:06:07.890", + pageNumber = 17, + }, + { -- 别人的注解:账号开了「查看他人注解」时接口会混进来,拉取必须按 owner 过滤。 + id = 502, ownerUserId = 9, chapterId = 2002, + xPath = "//body/p[2]", endingXPath = "//body/p[2]", selectedText = "别人的划线", + comment = "", commentHtml = "", selectedSlotIndex = 0, + createdUtc = "2026-10-03T05:00:00", + }, + { -- 裸高亮:没有备注,槽位越界 → yellow。 + id = 503, ownerUserId = 5, chapterId = 2002, + xPath = "//body/p[2]", endingXPath = "//body/p[3]", + selectedText = "处处闻啼鸟", + comment = "", commentHtml = "", commentPlainText = "", + selectedSlotIndex = 9, containsSpoiler = false, + createdUtc = "2026-10-03T05:00:00", + }, +} +routes["GET /api/Users/me"] = json({ id = 5, username = "me" }) +routes["GET /api/Annotation/all"] = function(opts) + ann_calls[#ann_calls + 1] = opts + return json(remote_anns) +end +local pulled, perr, pmeta = run("pullNotesAsync", volume) +Assert.eq(#ann_calls, 1, "每章一次 GET") +Assert.eq(query(ann_calls[1], "chapterId"), "2002") +Assert.eq(#pulled, 2, "只留自己的注解") +Assert.is_nil(perr) +Assert.is_false(pmeta.authoritative, "authoritative 恒 false:远端为空不清本地") + +local web = pulled[1] +Assert.eq(web.kavita_id, 501) +Assert.eq(web.text, "春眠不觉晓") +Assert.eq(web.note, "记一笔") +Assert.eq(web.kavita_note, web.note, "kavita_note 与 note 必须字节相同,否则每轮判改过") +Assert.eq(web.datetime, os.date("%Y-%m-%d %H:%M:%S", 1790000000), "createdUtc → 本地墙钟") +Assert.eq(web.color, "blue", "槽位 2 → blue") +Assert.eq(web.drawer, "lighten") +Assert.eq(web.kavita_comment, remote_anns[1].comment) +Assert.eq(web.kavita_comment_html, "记一笔
") +Assert.eq(web.kavita_slot, 2) +Assert.eq(web.kavita_spoiler, true) +Assert.eq(web.kavita_modified, "2026-10-04T05:06:07.890") +Assert.eq(web.kavita_xpath, "//body/p[1]") +Assert.eq(web.kavita_ending_xpath, "//body/p[1]") +-- spine 提示必须落库:开书定位只按 pageNumber(+1)挑 DocFragment,丢了它多 spine epub 全定位失败。 +Assert.eq(web.pageNumber, 17, "DTO pageNumber 原样进 payload(0-based spine 提示)") +Assert.is_nil(web.pos0, "pull 不写坐标") +Assert.is_nil(web.pos1) +Assert.is_nil(web.page, "page 是定位阶段产物") +Assert.is_nil(web.pageno) +Assert.is_nil(web.chapter_idx, "整本桶") + +local bare = pulled[2] +-- KOReader 的 getBookmarkType 用 `if bookmark.note then return "note"`:Lua 里 "" 为真, +-- 默认 bookmarks_items_text_type = "note" 就会把空备注写成「高亮与笔记」列表里的空行。 +Assert.is_nil(bare.note, "空备注落 nil(不是空串),否则被当成 note 类型渲染空行") +Assert.is_nil(bare.kavita_note, "基线与 note 同源:空备注也是 nil(sameNote(nil, \"\") 仍判等)") +Assert.eq(bare.color, "yellow", "槽位越界回落 yellow") +Assert.eq(bare.pageNumber, 0, "DTO 缺 pageNumber 回落 0(只会试前两个 DocFragment)") + +-- 清洗(保存快照前的白名单)不能把空备注的 nil 变回空串。 +local cleaned_bare = source:cleanAnnotations(pulled, 10) +Assert.is_nil(cleaned_bare[2].note, "cleanAnnotations 后仍为 nil") +Assert.is_nil(cleaned_bare[2].kavita_note) +Assert.eq(cleaned_bare[1].note, "记一笔", "非空备注不受影响") + +-- createdUtc 解析不出(Kavita 的 0001 占位)就用当前时间,仍然要落库。 +routes["GET /api/Annotation/all"] = json({ { + id = 504, ownerUserId = 5, xPath = "//body/p[4]", endingXPath = "//body/p[4]", + selectedText = "无时间", comment = "", selectedSlotIndex = 0, createdUtc = "0001-01-01T00:00:00", +} }) +local fallback = run("pullNotesAsync", volume) +Assert.eq(#fallback, 1) +local wall = fallback[1].datetime +local wy, wmo, wd, wh, wmi, ws = wall:match("^(%d+)-(%d+)-(%d+) (%d+):(%d+):(%d+)$") +Assert.not_nil(wy, "datetime 必须是可读墙钟:YYYY-MM-DD HH:MM:SS") +Assert.is_true(math.abs(os.time({ year = tonumber(wy), month = tonumber(wmo), day = tonumber(wd), + hour = tonumber(wh), min = tonumber(wmi), sec = tonumber(ws) }) - os.time()) <= 2, + "解析失败回退当前时间") + +-- 同章重复拉取幂等:payload 逐字段稳定(owner 已缓存,不再请求 /Users/me)。 +routes["GET /api/Annotation/all"] = function(opts) + ann_calls[#ann_calls + 1] = opts + return json(remote_anns) +end +local function flatten(list) + local out = {} + for _idx, item in ipairs(list) do + local keys = {} + for key in pairs(item) do keys[#keys + 1] = key end + table.sort(keys) + local parts = {} + for _j, key in ipairs(keys) do parts[#parts + 1] = key .. "=" .. tostring(item[key]) end + out[#out + 1] = table.concat(parts, "&") + end + return table.concat(out, "||") +end +ann_calls = {} +local again = run("pullNotesAsync", volume) +Assert.eq(#ann_calls, 1, "owner 已缓存,不再请求 /Users/me") +Assert.eq(flatten(again), flatten(pulled), "重复拉取 payload 稳定") + +-- 空文本的远端条目画不出来,但它的 id 必须进远端全量集合(spec §7 unlocated / §9.2): +-- 丢在 annotationPayload 里,mergeAnnotations 就看不到这个 id,会把本地带该 id 的那条当成 +-- 「远端已删」抹掉(反之远端还在,本地却消失)。 +routes["GET /api/Annotation/all"] = json({ { + id = 7, ownerUserId = 5, chapterId = 2002, + xPath = "//body/p[7]", endingXPath = "//body/p[7]", + selectedText = " ", comment = "", selectedSlotIndex = 0, + createdUtc = "2026-10-03T05:00:00", +} }) +local blank_pulled = run("pullNotesAsync", volume) +Assert.eq(#blank_pulled, 1, "有 id 就保留占位(只有没 id 才真丢)") +Assert.eq(tonumber(blank_pulled[1].kavita_id), 7) +Assert.is_true(blank_pulled[1].kavita_unlocated, "空文本定位不出来:标记未定位") +Assert.is_nil(blank_pulled[1].drawer, "未定位占位不画、不进列表") +local local_seven = { datetime = "d7", page = "/body/p[7].0", pos0 = "/body/p[7].0", + pos1 = "/body/p[7].5", drawer = "lighten", text = "本地定位过", kavita_id = 7 } +local merged_seven, dropped_seven = source:mergeAnnotations(blank_pulled, { local_seven }, nil, false) +Assert.eq(dropped_seven, 0, "空文本的远端条目仍占 id:本地那条不算远端已删") +Assert.eq(#merged_seven, 1, "远端不画,本地那份保留") +Assert.eq(merged_seven[1], local_seven) +-- 恢复后续用例用的三条 fixture。 +routes["GET /api/Annotation/all"] = function(opts) + ann_calls[#ann_calls + 1] = opts + return json(remote_anns) +end + +-- 取不到当前用户(/api/Users/me 不可用)→ 不过滤 + 记日志,不能因此不落库。 +routes["GET /api/Users/me"] = { code = 404, body = "" } +local fresh = require("moonsource_kavita.source").new() +local warned = {} +local log = require("utils.log") +local real_warn = log.warn +log.warn = function(...) warned[#warned + 1] = table.concat({ ... }, " ") end +local unfiltered, ferr +fresh:pullNotesAsync(volume, function(a, e) unfiltered, ferr = a, e end) +Stubs.flush() +log.warn = real_warn +Assert.is_nil(ferr) +Assert.eq(#unfiltered, 3, "拿不到 owner 就不做属主过滤") +Assert.is_true(#warned >= 1, "降级要留一条日志") + +-- GET 失败 → cb(nil, err);核心拿到 nil 直接收尾(note.lua 的 finish(nil, err)),不会写桶, +-- 本地快照(含 sync_status=0 的脏行)保持原样。脏行保护在 NoteDB.upsertRemote +-- (`WHERE notes.sync_status=1`)与 note_sync_spec 里已覆盖,源侧不碰 notes 表。 +routes["GET /api/Annotation/all"] = { code = 500, body = "" } +local fail_list, fail_err = run("pullNotesAsync", volume) +Assert.is_nil(fail_list) +Assert.matches(fail_err, "500") +routes["GET /api/Annotation/all"] = nil + +-- 非 epub(PDF / 漫画)没有 Kavita 注解:空数组 + authoritative=false,一个请求都不发。 +local before_pull = #calls +local none_pulled, none_err, none_meta = run("pullNotesAsync", pdf) +Assert.eq(#none_pulled, 0) +Assert.is_nil(none_err) +Assert.is_false(none_meta.authoritative) +Assert.eq(#calls, before_pull, "非 epub 零请求") + +-- 详情:卷行取所属 series 的 metadata,写回这一行。 +routes["GET /api/Series/metadata"] = function(opts) + Assert.eq(query(opts, "seriesId"), "20") + return json({ summary = "卷简介", writers = { { name = "丁" } } }) +end +local detail = run("getDetailAsync", { source_id = "kavita", stable_id = "20:2002" }) +Assert.eq(detail.intro, "第二卷简介", "详情补简介不能把卷摘要盖成整部简介") +Assert.eq(remembered["20:2002"].authors, "丁") +-- 目录里没有这一卷 / 这一卷没有摘要:保留行里已有的简介,最后才退回系列简介。 +tocs["20"][2].summary = nil +books["20:2002"] = { intro = "已有卷简介" } +Assert.eq(run("getDetailAsync", { source_id = "kavita", stable_id = "20:2002" }).intro, "已有卷简介", + "没有卷摘要时不清空已有简介") +books["20:2002"] = nil +Assert.eq(run("getDetailAsync", { source_id = "kavita", stable_id = "20:2002" }).intro, "卷简介", + "确认没有卷摘要才退回系列简介") +-- 旧目录缓存不认识卷摘要(升级前拉的目录):问一次单章接口,几 KB。 +routes["GET /api/Series/chapter"] = function(opts) + Assert.eq(query(opts, "chapterId"), "2002") + return json({ id = 2002, summary = "单章摘要" }) +end +Assert.eq(run("getDetailAsync", { source_id = "kavita", stable_id = "20:2002" }).intro, "单章摘要", + "目录没带卷摘要时用单章接口补") +routes["GET /api/Series/chapter"] = nil + +-- 漫画打开路径:判定 / 起始页 / 离线全归 kamare cache(03 A1/A2/A6),moon 只做路由与兜底。 +-- 关查看器写卷行 + 容器聚合(06 A1/A2),章末续读按回调 id 回目录(03 A7)。 +do + routes["GET /api/Series/metadata"] = metadata_route + routes["GET /api/Series/60"] = json({ id = 60, name = "漫画", libraryId = 3 }) + local volumes_route = routes["GET /api/Series/volumes"] + routes["GET /api/Series/volumes"] = function(opts) + if query(opts, "seriesId") ~= "60" then return volumes_route(opts) end + return json({ + { id = 600, chapters = { { id = 6000, titleName = "第1话", format = 1, pages = 30 } } }, + { id = 601, chapters = { { id = 6001, titleName = "第2话", format = 1, pages = 20 } } }, + }) + end + + -- 增强版:open 由 spec 控制返回;register_server 只用于镜像,不参与断言。 + local Cache = require("moonsource_kavita.cache") + local opened, reply = {}, nil + package.loaded["kamarecache"] = { + api_version = 1, + capabilities = { open = true, server = true }, + register_server = function() return "kav", nil end, + open = function(opts) + opened[#opened + 1] = opts + return reply(opts) + end, + } + Cache.reset() + + local toc = { + { idx = 6000, uid = 6000, title = "第1话", chapterId = 6000, volumeId = 600, libraryId = 3, + seriesId = 60, format = "cbz", pages = 30, pagesRead = 0 }, + { idx = 6001, uid = 6001, title = "第2话", chapterId = 6001, volumeId = 601, libraryId = 3, + seriesId = 60, format = "cbz", pages = 20, pagesRead = 0 }, + } + tocs["60"] = toc + books["60"] = { stable_id = "60", title = "漫画", authors = "甲", intro = "简介", category = "漫画" } + local ref = { source_id = "kavita", stable_id = "60:6001", book = books["60"] } + + -- 阅读统计只由 core 落库:源这一路碰都不该碰。 + local stats_read = false + package.loaded["book.stats_db"] = setmetatable({}, { + __index = function() + stats_read = true + return function() end + end, + }) + + --- 直接走一卷:同步回调不泵队列;返回实际发出的请求数。 + ---@return table { path, err, meta, http } + local NO_TOC = {} + local function open(entry, toc_arg, ref_arg) + local got + local list = toc_arg == NO_TOC and nil or (toc_arg or toc) + local before = #calls + source:openEntry(ref_arg or ref, entry, list, "漫画", function(path, err, meta) + got = { path = path, err = err, meta = meta } + end) + Stubs.flush() + got = got or {} + got.http = #calls - before + return got + end + + -- 成功:同步回调 handled;开书先问一次云端进度,把「另一台设备读到哪」直接当起始页。 + reply = function() return { kind = "viewer" } end + routes["GET /api/Reader/get-progress"] = json({ pageNum = 12 }) + local ok = open(toc[2]) + Assert.is_nil(ok.path) + Assert.is_nil(ok.err) + Assert.is_true(ok.meta and ok.meta.handled, "可见查看器:起始页 GET 回来后才回调 handled") + Assert.eq(ok.http, 1, "增强版开书只多问一次云端进度(起始页)") + Assert.len(opened, 1) + Assert.eq(opened[1].entry, toc[2]) + Assert.eq(opened[1].title, "漫画") + Assert.eq(opened[1].base_url, "http://kav", "地址去尾斜杠") + Assert.eq(opened[1].api_key, "k", "Key 去空白") + Assert.eq(opened[1].start_page, 13, "云端 pageNum 12 → 第 13 页:第一帧就落在云端位置") + + -- on_close:卷行写物理页 / 物理总数 / 现在;容器行写聚合 fraction + 最近阅读时间。 + written, remembered = {}, {} + -- 缺行不等于未读:卷行齐全(哪怕值是 0)才算得出聚合。 + progress["60:6000"] = { fraction = 0 } + opened[1].on_close(10, 20) + local volume = written["60:6001"] + Assert.eq(volume.page, 10, "卷行是唯一真实位置:物理页") + Assert.eq(volume.total_pages, 20, "物理总数来自 kamare 回调") + Assert.eq(volume.fraction, 0.5) + Assert.is_true((volume.updated_at or 0) > 0, "卷行用当前时间,进最近阅读") + local container = written["60"] + Assert.eq(container.fraction, 0.25, "聚合 = (0 个读完卷 + 本卷 0.5) / 2 卷") + Assert.is_true((container.updated_at or 0) > 0, "容器行带最近阅读时间:读完一卷系列行立刻浮上来") + Assert.eq(written_opts["60"] and written_opts["60"].reset_updated_at, true, + "容器行允许回落时间戳:旧版本存的未来时间要能被纠正") + Assert.is_nil(written_opts["60:6001"], "卷行走 MAX,修订号单调") + Assert.is_nil(container.page, "容器行只写聚合 fraction") + Assert.is_nil(container.total_pages) + Assert.eq(remembered["60:6001"].title, "漫画 · 第2话", "卷行缺书时用目录卷名补元数据") + Assert.eq(remembered["60:6001"].authors, "甲", "卷行继承容器作者") + Assert.eq(#dirty, 0, "不产生 dirty 行(sync_status=0 才进推送队列)") + Assert.eq(#require("book.progress_db").unsynced("kavita"), 0, "身份不在 unsynced 里") + Assert.is_false(stats_read, "不产生 reading_stats 行") + + -- 读完当前卷也只按卷数聚合:全卷读完才 100%。 + written = {} + progress["60:6000"] = { fraction = 1 } + opened[1].on_close(20, 20) + Assert.eq(written["60"].fraction, 1, "两卷都读完 = 100%") + progress["60:6000"] = nil + + -- 目录拿不到 / 本地缺卷行:算不出聚合就不动容器(缺行 ≠ 未读,低报比不更新更糟)。 + written, opened = {}, {} + progress["60"] = nil + reply = function() return {} end + local solo = open(toc[2], NO_TOC) + Assert.is_true(solo.meta and solo.meta.handled) + opened[1].on_close(10, 20) + Assert.is_nil(written["60"], "聚合算不出来时不写容器行(保留原值)") + progress["60"] = { fraction = 0.4 } + opened[1].on_close(10, 20) + Assert.eq(written["60"].fraction, 0.4, "有旧聚合就只刷新时间,不低报") + progress["60"] = nil + + -- 已有卷行:不重写元数据。 + books["60:6001"] = { stable_id = "60:6001", title = "已有" } + remembered, written = {}, {} + reply = function() return {} end + open(toc[2]) + opened[#opened].on_close(10, 20) + Assert.is_nil(remembered["60:6001"], "已有卷行不重复补元数据") + + -- on_next:只按回调 id 在 toc 找卷,再走同一条 Cache.open;找不到提示。 + written, opened = {}, {} + reply = function() return {} end + open(toc[2]) + local first = opened[1] + first.on_next(6000) + Assert.len(opened, 2, "按回调 id 打开下一卷") + Assert.eq(opened[2].entry.chapterId, 6000) + opened[2].on_close(30, 30) + Assert.eq(written["60:6000"].page, 30, "下一卷进度写下一卷行") + Assert.is_nil(written["60:6001"], "进度不串到上一卷") + local toasts = #Themed.all("toast") + first.on_next(9999) + Assert.len(opened, 2, "目录里没有的 id 不另开查看器") + Assert.eq(#Themed.all("toast"), toasts + 1) + Assert.eq(Themed.last("toast").text, "下一卷不在目录里") + + -- 单卷漫画:从书架行(stable_id = seriesId)打开,卷身份仍是 seriesId:chapterId。 + -- 关查看器写「卷行真实位置 + 带时间的容器行」,卷行元数据补齐(US 22 / 06 A2)。 + local single_toc, single_two = { toc[1] }, tocs["60"] + tocs["60"] = single_toc + books["60:6000"] = nil + written, remembered, opened = {}, {}, {} + reply = function() return { kind = "viewer" } end + local single_path, single_err, single_meta + source:openBookAsync({ source_id = "kavita", stable_id = "60", book = books["60"] }, nil, + function(p, e, m) single_path, single_err, single_meta = p, e, m end) + Stubs.flush() + Assert.is_nil(single_path) + Assert.is_nil(single_err) + Assert.is_true(single_meta and single_meta.handled, "单卷直接进查看器,不弹选卷") + Assert.eq(opened[1].entry.chapterId, 6000) + opened[1].on_close(5, 30) + Assert.eq(written["60:6000"].page, 5, "单卷也把真实位置写进卷行") + Assert.is_true((written["60:6000"].updated_at or 0) > 0, "卷行带时间戳,最近阅读能看到") + Assert.is_true((written["60"].updated_at or 0) > 0, "容器行带最近阅读时间") + Assert.eq(written["60"].fraction, 5 / 30, "容器行聚合百分比,书架有量级") + Assert.not_nil(remembered["60:6000"], "卷行元数据补齐:ProgressDB.recent 的 EXISTS books 过得去") + Assert.eq(remembered["60:6000"].title, "漫画 · 第1话") + tocs["60"] = single_two + + -- offline_not_cached + 无旧 cbz:提示,不落到下载。 + books["60:6001"] = nil + reply = function() return nil, "offline_not_cached", "这一卷还没缓存,联网后可下载" end + local offline = open(toc[2]) + Assert.is_nil(offline.path) + Assert.eq(offline.err, "这一卷还没缓存,联网后可下载") + Assert.eq(offline.http, 1, "未缓存离线:只问过一次起始页") + + -- 旧 cbz:kamare 缓存优先;offline_not_cached 时回退到本地文件。 + os.execute("mkdir -p '" .. WORK .. "/60:6001'") + local old_cbz = WORK .. "/60:6001/6001.cbz" + local old_file = assert(io.open(old_cbz, "wb")) + old_file:write("PK\3\4cbz") + old_file:close() + books["60:6001"] = { stable_id = "60:6001", path = old_cbz } + local comic = { source_id = "kavita", stable_id = "60", book = books["60"] } + + opened = {} + reply = function() return {} end + local before_book = #calls + local cpath, cerr, cmeta + source:openBookAsync(comic, nil, function(p, e, m) cpath, cerr, cmeta = p, e, m end) + Stubs.flush() + Themed.choose(Themed.last("list"), 2) + Stubs.flush() + Assert.is_nil(cpath) + Assert.is_nil(cerr) + Assert.is_true(cmeta and cmeta.handled, "kamare 缓存优先于旧 cbz") + Assert.eq(opened[1].entry.chapterId, 6001) + -- 目录命中缓存也照样拉一次「最新进度」(点开系列 = 想看服务器上的已读状态): + -- 只问 series(libraryId)+ volumes(各卷 pagesRead),不重拉 metadata。 + Assert.eq(#calls, before_book + 3, "开书:目录刷新 2 次 + 起始页 1 次") + Assert.matches(calls[before_book + 1].url, "^http://kav/api/Series/60$") + Assert.matches(calls[before_book + 2].url, "^http://kav/api/Series/volumes%?seriesId=60") + Assert.matches(calls[before_book + 3].url, "^http://kav/api/Reader/get%-progress") + Assert.not_nil(io.open(old_cbz), "旧 cbz 静默保留,不删用户数据") + + reply = function() return nil, "offline_not_cached", "这一卷还没缓存,联网后可下载" end + local offline_path, offline_err = run("openBookAsync", + { source_id = "kavita", stable_id = "60:6001", book = books["60"] }, nil) + Assert.eq(offline_path, old_cbz, "未缓存离线:先用盘上的旧 cbz") + Assert.is_nil(offline_err) + + -- viewer_running:绝不回退(旧 cbz 在盘上也不开,不下载)。 + reply = function() return nil, "viewer_running", "漫画阅读器已在运行" end + local running = open(toc[2]) + Assert.is_nil(running.path) + Assert.eq(running.err, "漫画阅读器已在运行") + Assert.eq(running.http, 1, "查看器已在运行:不下载(起始页那一次 GET 早已发出)") + + -- 未知失败 / 流式失败:在线 cbz 回退下载;image 报错。 + os.remove(old_cbz) + books["60:6001"] = nil + download.body, download.code = "PK\3\4cbz", 200 + reply = function() return nil, "open_failed", "打开漫画阅读器失败" end + local fallback + source:openEntry(ref, toc[2], toc, "漫画", function(p, e, m) fallback = { path = p, err = e, meta = m } end) + Stubs.flush() + Assert.eq(fallback.path, old_cbz, "kamare 失败:cbz 退回下载") + Assert.is_nil(fallback.err) + + local image = { chapterId = 6001, volumeId = 601, libraryId = 3, seriesId = 60, format = "image", pages = 20 } + local img_before = #calls + local img = open(image) + Assert.is_nil(img.path) + Assert.not_nil(img.err, "image 下载不了:报错") + Assert.eq(#calls, img_before + 1, "image 失败不回退下载(只有起始页那一次 GET)") + + reply = function() return nil, "no_pages", "这一卷没有可显示的页面" end + local empty = open(toc[2]) + Assert.is_nil(empty.path) + Assert.eq(empty.err, "这一卷没有可显示的页面") + Assert.eq(empty.http, 1) + + reply = function() return nil, "settings_write_failed", "无法写入 kamare 配置" end + local bad_settings = open(toc[2]) + Assert.is_nil(bad_settings.path) + Assert.eq(bad_settings.err, "无法写入 kamare 配置") + Assert.eq(bad_settings.http, 1) + + -- journal 与云端谁更靠后:起始页取 journal 更靠后的那一个;关书落库以 journal 为准。 + -- (journal 自己已经做过「服务端更靠后 → 抬升」的合并,moon 复用它落库就不会出现 + -- 「书架 50%、打开 30%」这种两份事实打架。) + local kamare = package.loaded["kamarecache"] + kamare.capabilities.resume = true + local resume_reply = { page = 15, source = "journal" } + kamare.resume_page = function() return resume_reply end + Cache.reset() + routes["GET /api/Reader/get-progress"] = json({ pageNum = 5 }) + opened = {} + reply = function() return { kind = "viewer" } end + local ahead = open(toc[2]) + Assert.is_true(ahead.meta and ahead.meta.handled) + Assert.eq(opened[#opened].start_page, 6, "把云端位置当提示传给 kamare(journal 合并在那边做)") + written = {} + opened[#opened].on_close(9, 20) + Assert.eq(written["60:6001"].page, 15, "关书落库以 journal 为准(不写回调的瞬时页)") + -- snapshot 是下载时的服务端快照,可能已经很旧:不许它覆盖关书写回的位置。 + resume_reply = { page = 3, source = "snapshot" } + written = {} + opened[#opened].on_close(9, 20) + Assert.eq(written["60:6001"].page, 9, "snapshot 不覆盖关书回调页") + kamare.capabilities.resume = nil + kamare.resume_page = nil + Cache.reset() + + -- 没有增强版(未装 / 官方版):旧回退照旧,图片目录仍是「需要安装 kamare」。 + package.loaded["kamarecache"] = nil + package.loaded["kamareimageviewer"] = nil + Cache.reset() + local degraded, degraded_before = nil, #calls + source:openEntry(ref, image, toc, "漫画", function(path, err) degraded = { path = path, err = err } end) + Stubs.flush() + Assert.is_nil(degraded.path) + Assert.eq(degraded.err, "图片目录格式需要安装 kamare 插件在线阅读") + Assert.eq(#calls, degraded_before, "没有缓存接口时图片目录不下载") + + -- 恢复增强版桩:后续段只用到 HTTP / 进度,不依赖缓存路径,但别把状态留给别的用例。 + package.loaded["kamarecache"] = { + api_version = 1, + capabilities = { open = true, server = true }, + register_server = function() return "kav", nil end, + open = function() return {} end, + } + Cache.reset() + package.loaded["book.stats_db"] = nil +end + +-- 官方 / 旧版 kamare(无 kamarecache):没有 journal,起始页由 moon 补: +-- 本地卷行(关查看器时写的真实页)优先,本机没读过才问 Kavita(03 A2 降级通道)。 +do + local Cache = require("moonsource_kavita.cache") + local legacy_shown = {} + package.loaded["kamarecache"] = nil + package.loaded["kamareimageviewer"] = { new = function(_self, spec) return spec end } + package.loaded["kavitaclient"] = { streamChapter = function() return { { pageNumber = 1 } } end } + local UIManager = require("ui/uimanager") + local real_show = UIManager.show + UIManager.show = function(_, widget) legacy_shown[#legacy_shown + 1] = widget end + Cache.reset() + + local entry = { chapterId = 6001, volumeId = 601, libraryId = 3, seriesId = 60, + format = "cbz", pages = 20, title = "第2话" } + local legacy_ref = { source_id = "kavita", stable_id = "60:6001" } + + ---@return table got, table|nil job, table|nil viewer + local function openLegacy() + local got + local job = source:openEntry(legacy_ref, entry, { entry }, "漫画", function(path, err, meta) + got = { path = path, err = err, meta = meta } + end) + Stubs.flush() + return got or {}, job, legacy_shown[#legacy_shown] + end + + -- 云端有进度:跟云端(跨设备读到哪就从哪续)。 + progress["60:6001"] = { page = 7, total_pages = 20 } + routes["GET /api/Reader/get-progress"] = json({ pageNum = 9 }) + local before = #calls + local got, _, viewer = openLegacy() + Assert.is_true(got.meta and got.meta.handled) + Assert.eq(#calls, before + 1, "官方通道开书先问一次云端进度") + Assert.eq(viewer.metadata.startPage, 10, "云端 pageNum 0-based → 第 10 页(比本地新就跟云端)") + + -- 本机没读过(换设备 / 重装):同样用云端 pageNum + 1。 + progress["60:6001"] = nil + routes["GET /api/Reader/get-progress"] = json({ pageNum = 3 }) + viewer = select(3, openLegacy()) + Assert.eq(viewer.metadata.startPage, 4, "没有本地进度:云端 pageNum + 1") + + -- 本机比云端靠后(云端进度被别处改旧了 / 刚在本地读了几页):用本机,不往回拽。 + progress["60:6001"] = { page = 7, total_pages = 20 } + routes["GET /api/Reader/get-progress"] = json({ pageNum = 3 }) + viewer = select(3, openLegacy()) + Assert.eq(viewer.metadata.startPage, 7, "本机更靠后:起始页用本机") + progress["60:6001"] = nil + + -- 云端也没读过:不给起始页,查看器从第 1 页开始。 + routes["GET /api/Reader/get-progress"] = json({ pageNum = 0 }) + viewer = select(3, openLegacy()) + Assert.is_nil(viewer.metadata.startPage, "云端无进度:不硬塞页码") + + -- 云端请求失败:本机关书写的卷行兜底,不把人丢回第 1 页。 + progress["60:6001"] = { page = 7, total_pages = 20 } + routes["GET /api/Reader/get-progress"] = { code = 500, body = "" } + viewer = select(3, openLegacy()) + Assert.eq(viewer.metadata.startPage, 7, "云端失败:用本地卷行续读") + + -- 云端页码超过当前总页数(服务器重排过):夹到总页数。 + routes["GET /api/Reader/get-progress"] = json({ pageNum = 30 }) + viewer = select(3, openLegacy()) + Assert.eq(viewer.metadata.startPage, 20, "页码夹到总页数") + + -- 离线:不问网络,直接用本地卷行;没有就第 1 页。 + online = false + before = #calls + viewer = select(3, openLegacy()) + Assert.eq(#calls, before, "离线不请求") + Assert.eq(viewer.metadata.startPage, 7, "离线用本地卷行续读") + progress["60:6001"] = nil + viewer = select(3, openLegacy()) + Assert.is_nil(viewer.metadata.startPage, "离线且本机没读过:第 1 页") + online = true + + -- 恢复增强版桩,别把状态留给后面的用例。 + progress["60:6001"] = nil + package.loaded["kamareimageviewer"] = nil + UIManager.show = real_show + package.loaded["kamarecache"] = { + api_version = 1, + capabilities = { open = true, server = true }, + register_server = function() return "kav", nil end, + open = function() return {} end, + } + Cache.reset() +end + +-- 漫画 cbz 用内置阅读器时进度同样上报:页级 0-based,读完发 pages(Kavita 据此标已读)。 +sent = nil +local cbz = { source_id = "kavita", stable_id = "60:6000" } +Assert.is_true(run("putProgressAsync", cbz, { fraction = 0.1, page = 4, total_pages = 30 })) +Assert.eq(sent.pageNum, 3, "cbz 页码 1-based → Kavita 0-based") +Assert.eq(sent.chapterId, 6000) +Assert.eq(sent.volumeId, 600) +Assert.eq(sent.libraryId, 3) +Assert.eq(sent.seriesId, 60) +Assert.is_nil(sent.bookScrollId, "非 epub 不带锚点") +run("putProgressAsync", cbz, { fraction = 1, page = 30, total_pages = 30 }) +Assert.eq(sent.pageNum, 30, "读完发 pages") +run("putProgressAsync", cbz, { fraction = 0, page = 1, total_pages = 30 }) +Assert.eq(sent.pageNum, 0, "第一页是 0(Kavita 页号 0-based)") +os.remove(require("datastorage"):getSettingsDir() .. "/moonsource_kavita_meta.lua") + +-- 服务端已读回填:网页端 / 别的设备读过的 epub 也要进「最近阅读」并可能标已读。 +-- series 级 pagesRead/pages 对 epub 只是 spine 比例,只补本地没有进度的书,绝不覆盖精确位置。 +local shelf_route = routes["POST /api/Series/all-v2"] +local read_route = json({ + { id = 700, name = "读过一半", libraryName = "书籍", format = 3, pages = 200, pagesRead = 50, + -- Kavita 同时给本地与 UTC 两个口径:差值 = 服务器时区(这里 UTC+8)。 + lastChapterAdded = "2026-02-03T11:05:06.1", lastChapterAddedUtc = "2026-02-03T03:05:06.1", + latestReadDate = "2026-02-03T04:05:06.123" }, + { id = 701, name = "读完了", libraryName = "书籍", format = 3, pages = 10, pagesRead = 10, + lastChapterAdded = "2026-02-03T11:05:06.1", lastChapterAddedUtc = "2026-02-03T03:05:06.1", + latestReadDate = "2026-02-03T04:05:06.123" }, + { id = 710, name = "多卷书", libraryName = "书籍", format = 3, pages = 300, pagesRead = 90, + lastChapterAdded = "2026-02-03T11:05:06.1", lastChapterAddedUtc = "2026-02-03T03:05:06.1", + latestReadDate = "2026-02-03T04:05:06.123" }, +}) +-- 多卷 series:卷行上已经有进度 → 容器行改写服务端 series 级 fraction + 最近阅读时间, +-- 不 drop(06 A1)。图书馆「最近阅读」列系列行(点开再选卷),首页「当前阅读」取卷行。 +tocs["710"] = { { chapterId = 7101, title = "上" }, { chapterId = 7102, title = "下" } } +progress["710:7101"] = { fraction = 0.3, updated_at = os.time() - 3600 } +progress["710"] = { fraction = 0.5, updated_at = os.time() - 3600 } +books["710"] = { title = "多卷书", authors = "甲", intro = "简介", category = "书籍" } +routes["POST /api/Series/all-v2"] = read_route +written = {} +local vol_result = run("syncBooksAsync", { force = true }) +Assert.eq(written["700"].fraction, 0.25) +Assert.is_nil(written["700"].page, "epub 不写页码:Kavita 的页是 spine") +-- latestReadDate 是服务器本地时间(04:05 CST = 20:05Z 前一天),不是 UTC; +-- 按 UTC 解析会存成 1770091506(8 小时后的未来),刚读完的书就会被它压在下面。 +Assert.eq(written["700"].updated_at, 1770062706, "latestReadDate 按服务器时区换成真 epoch") +Assert.eq(written["701"].fraction, 1, "读完的写满比例,进步进「已读」") +Assert.eq(written["710"].fraction, 0.3, + "本地缺「下」卷行 → 退回服务端 pagesRead/pages(缺行不等于未读,宁可两套口径也不低报)") +Assert.eq(written["710"].updated_at, 1770062706, "容器行带最近阅读时间,图书馆按系列行排序") +Assert.eq(written_opts["710"] and written_opts["710"].reset_updated_at, true, + "回填聚合要能回落时间戳(旧版本存过未来时间 / 0)") +Assert.is_nil(written["710"].page, "容器行只写聚合 fraction") +Assert.eq(remembered["710:7101"].authors, "甲", "读过的卷行继承容器作者,不再显示未知作者") +Assert.eq(remembered["710:7101"].title, "多卷书 · 上") +Assert.eq(remembered["710:7101"].category, "书籍") +-- 对齐必须算进同步变更:pulled 全 0 时桌面不发 shelf_changed,首页「当前阅读」不重画, +-- 卡片会一直停在未知作者(对账 3 本 + 回填 700/701 各 1 + 卷行对齐 1 + 容器聚合 1)。 +Assert.eq(vol_result.pulled, 7, "卷行元数据对齐算一次变更,首页才会重画") +-- 卷行按真实书库落库后(rememberMany 会写库),重复同步不再是变更,否则每次同步都白刷首页。 +books["710:7101"] = remembered["710:7101"] +local vol_again = run("syncBooksAsync", { force = true }) +Assert.eq(vol_result.pulled - vol_again.pulled, 1, "已对齐的卷行不再重复计入变更") +-- 卷行齐全时容器行按卷级聚合(不是服务端页比):(0 读完 + 在读卷 0.3) / 2 卷 = 0.15 +progress["710:7102"] = { fraction = 0 } +written = {} +run("syncBooksAsync", { force = true }) +Assert.eq(written["710"].fraction, 0.15, "卷行齐全 → 容器行按卷级聚合") +progress["710:7102"] = nil + +-- 目录缓存过期不能让身份翻回容器行:过期目录照样算数,否则容器行会重新拿到 +-- 单书位置(整部书当成一卷)而不是聚合。 +toc_fresh, written = false, {} +run("syncBooksAsync", { force = true }) +Assert.eq(written["710"].updated_at, 1770062706, "过期目录也认卷身份:容器行仍写系列级时间") +Assert.eq(written["710"].fraction, 0.3, "目录过期时同样退回服务端比例(仍缺「下」卷行)") +Assert.is_nil(written["710"].page, "容器行只写聚合 fraction") +toc_fresh = true +written = {} +progress["700"] = { fraction = 0.4 } +run("syncBooksAsync", { force = true }) +Assert.is_nil(written["700"], "本地有进度就不回填,不覆盖精确位置") + +-- 旧版已经写进库的未来时间:同步时拉回真实时间(只降不升)。 +written, fixed = {}, {} +progress["700"] = { fraction = 0.4, updated_at = os.time() + 8 * 3600 } +run("syncBooksAsync", { force = true }) +Assert.eq(fixed["700"], 1770062706, "库里的未来时间被拉回 Kavita 的真实阅读时间") +progress["700"] = nil +routes["POST /api/Series/all-v2"] = shelf_route + +-- 另一台设备读的新卷:series 级只有聚合(pagesRead),本机没有那一卷的卷行, +-- 首页「当前阅读」会停在旧卷。continue-point 才知道「当前读的是哪一章 / 哪一卷」。 +do + routes["POST /api/Series/all-v2"] = json({ + { id = 8901, name = "系列甲", libraryName = "漫画", format = 1, pages = 400, pagesRead = 207, + lastChapterAdded = "2026-02-03T11:05:06.1", lastChapterAddedUtc = "2026-02-03T03:05:06.1", + latestReadDate = "2026-02-03T04:05:06.123" }, + { id = 8902, name = "系列乙", libraryName = "漫画", format = 1, pages = 200, pagesRead = 200, + lastChapterAdded = "2026-02-03T11:05:06.1", lastChapterAddedUtc = "2026-02-03T03:05:06.1", + latestReadDate = "2026-02-03T04:05:06.123" }, + { id = 8903, name = "系列丙", libraryName = "漫画", format = 1, pages = 200, pagesRead = 0, + lastChapterAdded = "2026-02-03T11:05:06.1", lastChapterAddedUtc = "2026-02-03T03:05:06.1" }, + }) + local asked = {} + routes["GET /api/Reader/continue-point"] = function(opts) + local sid = query(opts, "seriesId") + asked[#asked + 1] = sid + if sid == "8901" then + -- 第 2 卷读到第 7 页:这就是「正在读」的那一卷。 + return json({ id = 89010, volumeId = 9901, title = "-100000", titleName = "第2卷", + pages = 200, pagesRead = 7, summary = "第2卷摘要", + lastReadingProgressUtc = "2026-02-02T20:05:06.1" }) + end + -- 读完一卷后给的是「下一章」,pagesRead = 0:那不是正在读。 + return json({ id = 89020, volumeId = 9902, titleName = "第1卷", pages = 200, pagesRead = 0 }) + end + books["8901"] = { title = "系列甲", authors = "甲", category = "漫画" } + books["8902"] = { title = "系列乙", authors = "乙", category = "漫画" } + books["8903"] = { title = "系列丙", authors = "丙", category = "漫画" } + written, remembered = {}, {} + run("syncBooksAsync", { force = true }) + -- 只问「读过、还没读完」的漫画:读完的(8902)和没读过的(8903)都不需要当前卷。 + Assert.eq(table.concat(asked, ","), "8901") + local row = written["8901:89010"] + Assert.not_nil(row, "服务器说在读的那一卷补成本地卷行") + Assert.eq(row.page, 8, "Kavita pageNum 是 0-based:本地 page 要 +1") + Assert.eq(row.fraction, 8 / 200, "fraction 与 page 同口径(1-based)") + Assert.eq(row.total_pages, 200) + Assert.eq(row.updated_at, 1770062706, "用章节的 UTC 阅读时间(换算成本地 epoch)") + Assert.eq(remembered["8901:89010"].title, "系列甲 · 第2卷", "卷行继承容器元数据,标题带卷名") + Assert.eq(remembered["8901:89010"].intro, "第2卷摘要", "卷简介用这一卷的摘要,不用整部简介") + Assert.is_nil(written["8902:89020"], "读完的卷不补:continue-point 给的是下一章") + -- 同一份服务端进度不重复写:每 5 分钟重写同一行会白刷首页。 + progress["8901:89010"] = { page = 8, fraction = 8 / 200, updated_at = 1770062706 } + written = {} + run("syncBooksAsync", { force = true }) + Assert.is_nil(written["8901:89010"], "服务端没更新就不重写") + -- 另一台设备接着读了:服务器时间更新 → 采纳服务器的位置(服务器优先)。 + routes["GET /api/Reader/continue-point"] = json({ id = 89010, volumeId = 9901, + titleName = "第2卷", pages = 200, pagesRead = 120, + lastReadingProgressUtc = "2026-02-03T01:05:06.1" }) + written = {} + run("syncBooksAsync", { force = true }) + Assert.eq(written["8901:89010"].page, 121, "服务器更靠后:121 页(pageNum 120 + 1)") + Assert.eq(written["8901:89010"].fraction, 121 / 200, "百分比跟着页走,不和服务端差一页") + progress["8901:89010"] = nil + routes["POST /api/Series/all-v2"] = shelf_route +end + +-- 阅读期进度心跳:Kavita 的阅读会话时长按相邻两次进度写入的间隔算,只在关书推一次, +-- Kavita 那边就是一个 StartTime == EndTime 的 0 秒会话。翻页 / 切章 / 唤醒起心跳:位置一变 +-- 就补推(节流合并密集翻页),另有兜底定时拍照顾慢读;离线或上一拍未回就跳过这一拍; +-- 关书 / 休眠 / 关源即停。 +do + local UIManager = require("ui/uimanager") + local real_in, real_un, real_time = UIManager.scheduleIn, UIManager.unschedule, os.time + local scheduled = {} + UIManager.scheduleIn = function(_self, delay, fn) scheduled[#scheduled + 1] = { delay = delay, fn = fn } end + UIManager.unschedule = function(_self, fn) + for i = #scheduled, 1, -1 do + if scheduled[i].fn == fn then table.remove(scheduled, i) end + end + end + local now = 1800000000 + os.time = function(t) return t and real_time(t) or now end + local function advance(seconds) now = now + seconds end + local function fire() table.remove(scheduled, 1).fn(); Stubs.flush() end + + sent = nil + source:onEvent("page_changed", { + identity = volume, + position = { fraction = 0.4, locator = "/body/DocFragment[5]/body/div/p[1]/text().0" }, + }) + source:onEvent("page_changed", { + identity = volume, + position = { fraction = 0.5, locator = "/body/DocFragment[6]/body/div/p[2]/text().0" }, + }) + Assert.len(scheduled, 1, "同一本书只有一个心跳") + Assert.eq(scheduled[1].delay, 30, "拍间隔就是设置的心跳间隔(默认 30 秒)") + Assert.is_nil(sent, "起心跳不当场发请求(避开开书拉取)") + + local Progress = require("book.progress") + local decision = Progress.decision(volume) + decision.phase = "choosing" + advance(31) + source:onEvent("page_changed", { + identity = volume, + position = { fraction = 0.54, locator = "/body/DocFragment[6]/body/div/p[2]/text().0" }, + }) + Assert.is_nil(sent, "未决议时心跳不能绕过门禁") + decision.phase = "ready" + fire() + Assert.eq(sent.pageNum, 5, "解锁后下一拍补推保留的位置") + Assert.eq(sent.bookScrollId, "//body/div[1]/p[2]") + + -- 位置一变就补推:Kavita 认的是两次写入之间的跨度,必须真的把新位置写上去。 + advance(31) + source:onEvent("page_changed", { + identity = volume, + position = { fraction = 0.55, locator = "/body/DocFragment[6]/body/div/p[3]/text().0" }, + }) + Stubs.flush() + Assert.eq(sent.pageNum, 5, "翻页后推新位置(spine)") + Assert.eq(sent.bookScrollId, "//body/div[1]/p[3]") + Assert.len(scheduled, 1, "补推不另起定时器") + + -- 距上次不足 MIN_PUSH_GAP 的翻页:合并,交给下一拍,不每页一发。 + sent = nil + advance(10) + source:onEvent("page_changed", { + identity = volume, + position = { fraction = 0.6, locator = "/body/DocFragment[7]/body/p[1]/text().0" }, + }) + Assert.is_nil(sent, "翻页密集时合并") + + -- 兜底定时拍到点:推最近一次的位置。 + advance(120) + fire() + Assert.eq(sent.pageNum, 6, "定时拍推最近位置") + Assert.len(scheduled, 1, "一拍结束后重排下一拍") + + -- 位置没变的兜底拍:跳过,别白推(Kavita 对同位置也会 early-return)。 + sent = nil + advance(200) + fire() + Assert.is_nil(sent, "位置没变不推") + Assert.len(scheduled, 1) + + -- 离线只跳过这一拍,不补报,但心跳继续(重排已经发生)。 + online, sent = false, nil + advance(200) + fire() + Assert.is_nil(sent, "离线不发") + Assert.len(scheduled, 1) + online = true + + -- 上一拍回包还没落地:busy 未清,本拍跳过,不重复发也不丢位置。 + local before = #calls + advance(61) + source:onEvent("page_changed", { + identity = volume, + position = { fraction = 0.7, locator = "/body/DocFragment[8]/body/p[1]/text().0" }, + }) + Assert.is_true(source._heartbeat.busy, "第一拍在飞") + sent = nil + advance(61) + source:onEvent("page_changed", { + identity = volume, + position = { fraction = 0.8, locator = "/body/DocFragment[9]/body/p[1]/text().0" }, + }) + Stubs.flush() + Assert.eq(#calls, before + 1, "上一拍未回,本拍不发") + Assert.eq(sent.pageNum, 7, "推的是飞出去那一拍的位置") + Assert.is_true(not source._heartbeat.busy, "回包落地后 busy 复位") + + -- 换书:停旧心跳,为新书重排。 + local other = { source_id = "kavita", stable_id = "20:2001" } + source:onEvent("page_changed", { identity = other, position = { fraction = 0.1 } }) + Assert.len(scheduled, 1, "换书只留一个心跳") + Assert.eq(source._heartbeat.identity.stable_id, "20:2001") + + -- 关书 / 休眠停掉,不再有调度。 + source:onEvent("reading_stopped", { identity = other }) + Assert.len(scheduled, 0, "关书 / 休眠停心跳") + Assert.is_nil(source._heartbeat) + + -- 关源也要停(换源时旧实例可能还挂着)。 + source:onEvent("chapter_changed", { identity = volume, position = { fraction = 0.2 } }) + Assert.len(scheduled, 1) + source:close() + Assert.len(scheduled, 0, "关源停心跳") + + -- 心跳间隔可配置:调大后按新间隔节流,兜底拍跟着放大;0 = 关闭阅读期心跳。 + cfg.heartbeat_interval = 120 + source:onEvent("page_changed", { identity = volume, position = { fraction = 0.9 } }) + Assert.len(scheduled, 1, "改间隔后起心跳") + Assert.eq(scheduled[1].delay, 120, "兜底拍跟到新间隔,不白醒") + sent = nil + advance(31) + source:onEvent("page_changed", { + identity = volume, + position = { fraction = 0.91, locator = "/body/DocFragment[6]/body/p[9]/text().0" }, + }) + Stubs.flush() + Assert.is_nil(sent, "120s 间隔内不推") + advance(100) + source:onEvent("page_changed", { + identity = volume, + position = { fraction = 0.92, locator = "/body/DocFragment[6]/body/p[10]/text().0" }, + }) + Stubs.flush() + Assert.is_true(sent ~= nil, "超过 120s 后补推") + + cfg.heartbeat_interval = 0 + source:onEvent("page_changed", { identity = volume, position = { fraction = 0.93 } }) + Assert.len(scheduled, 0, "0 = 关闭心跳,不再调度") + Assert.is_nil(source._heartbeat) + cfg.heartbeat_interval = nil + + UIManager.scheduleIn, UIManager.unschedule, os.time = real_in, real_un, real_time +end + +-- 统计钩子:能力申报 + 推送 = 纯本地确认。Kavita 侧的阅读历史由服务端自己记录(会话 × 系列, +-- 带章节明细),本机没有对应的上报接口;确认后这些行不再是脏行,展示仍按 +-- 「云端快照 + 拉取后本地新读」合并。 +do + local SourceCapabilities = require("source.base").SourceCapabilities + Assert.is_true(source:capabilities().stats_pull, "申报可拉取统计") + Assert.is_true(SourceCapabilities.supportsStatsPull(source), "框架入口据此调 pullStatsAsync") + + local confirmed, returned + local before_calls = #calls + returned = source:pushStatsAsync({ { id = 7 }, { id = 8 } }, function(data) confirmed = data end) + Assert.is_nil(confirmed, "当场能回的结果也下一帧回调(源契约:defer,cancel 句柄先于回调成立)") + Assert.not_nil(returned and returned.cancel, "返回可取消句柄(在飞取消是契约的一部分)") + Stubs.flush() + Assert.eq(confirmed.synced_ids[1], 7, "确认回本批行 id(框架据此标 sync_status=1)") + Assert.eq(confirmed.synced_ids[2], 8) + Assert.eq(#calls, before_calls, "本地确认不发请求") + confirmed = nil + source:pushStatsAsync(nil, function(data) confirmed = data end) + Stubs.flush() + Assert.eq(#confirmed.synced_ids, 0, "空批次也回空表,不报错") + + -- 取消:下一帧之前取消,回调不再到达。 + local reached = false + returned = source:pushStatsAsync({ { id = 9 } }, function() reached = true end) + returned:cancel() + Stubs.flush() + Assert.is_false(reached, "取消后不回调") +end + +-- 拉取全量阅读历史:按分页头展开两页;参数形态(Libraries 重复键 / TimeZoneId / PageSize=200 / +-- 不带日期范围);身份判定命中目录缓存(4 章 = 多卷 → 逐卷身份);替换指令与核心对账基线一致。 +local warnings = {} +do + local log = require("utils.log") + log.warn = function(...) warnings[#warnings + 1] = table.concat({ ... }, " ") end +end +--- 记录某次拉取里出现过「跳过系列」的警告(按 seriesId 找)。 +local function warnedAbout(series_id) + for _idx, text in ipairs(warnings) do + if text:find(series_id, 1, true) then return true end + end + return false +end +local function readFile(path) + local file = io.open(path, "r") + if not file then return nil end + local content = file:read("*a") + file:close() + return content +end +local history = dofile((debug.getinfo(1, "S").source:match("^@(.*)/")) .. "/fixtures/history_7453.lua") +local history_pages = { {}, {} } +for _idx, entry in ipairs(history) do + local page = #history_pages[1] < 50 and 1 or 2 + history_pages[page][#history_pages[page] + 1] = entry +end +local history_calls = {} +--- 分页头与响应体同一套往返桩:client 读到的就是「JSON 串 → 表」这条路。 +local function pagination_header(page, pages) + return JSON.encode({ currentPage = page, itemsPerPage = 50, totalItems = 64, totalPages = pages }) +end +routes["GET /api/Stats/reading-history"] = function(opts) + local page = tonumber(query(opts, "PageNumber")) + history_calls[#history_calls + 1] = opts.url + return json(history_pages[page], { Pagination = pagination_header(page, 2) }) +end +tocs["7453"] = { { chapterId = 11270 }, { chapterId = 11271 }, { chapterId = 11272 }, { chapterId = 11273 } } +-- 未选书库:与书架同步同类的配置错误,零请求(配置好了自然会重拉)。 +cfg.libraries = {} +local nolibs_before = #calls +local nolibs, nolibs_err = run("pullStatsAsync") +Assert.is_nil(nolibs) +Assert.matches(nolibs_err, "选择书库") +Assert.eq(#calls, nolibs_before, "未配置不发请求") +cfg.libraries = { ["2"] = true, ["1"] = true } +local pulled = run("pullStatsAsync") +Assert.len(history_calls, 2, "分页头说两页就拉两页") +Assert.matches(history_calls[1], "Libraries=1&Libraries=2", "库集合是重复键") +Assert.matches(history_calls[1], "TimeZoneId=Asia%%2FShanghai", "设备时钟 POSIX → IANA") +Assert.matches(history_calls[1], "PageSize=200") +Assert.matches(history_calls[1], "PageNumber=1&", "从第 1 页开始") +Assert.is_nil(history_calls[1]:match("StartDate"), "全量重拉不带日期范围") +Assert.matches(history_calls[2], "PageNumber=2&") +local pulled_total +for _idx, row in ipairs(pulled.rows) do + if row.record_type == "total" then pulled_total = row end +end +Assert.eq(pulled_total.duration, 14237, "两页合并后与样本书基线一致") +Assert.eq(pulled_total.source_id, "kavita") +Assert.eq(pulled.replace.mode, "ranges") +Assert.len(pulled.replace.books, 2, "本次身份(7453 的 4 章里读过两卷)") +Assert.contains(pulled.replace.books, "7453:11273") +Assert.not_nil(pulled.commit, "落库成功后由核心回调 commit") +Assert.len(history_calls, 2, "目录命中缓存,不为身份判定多请求") + +-- 设备时钟的 POSIX 串映射不出 IANA 时区(自定义 / 未知)时回退 UTC:服务端只认 IANA, +-- 宁可与设备差一天,不静默用错时区。 +setTZ("NOPE-1") +history_calls = {} +Assert.not_nil(run("pullStatsAsync")) +Assert.matches(history_calls[1], "TimeZoneId=UTC", "无法识别的时区回退 UTC") +setTZ("CST-8") + +-- 身份判定:目录缓存里没有的系列走 Source:toc(在线拉目录)后逐卷记;目录拿不到的系列整条跳过 +-- (不猜单卷 / 多卷),不中断其它系列。判定结果随 commit 记进状态文件,下一轮不再请求目录。 +do + local stats_history = { + { seriesId = 8661, localDate = "2026-10-10T00:00:00", + chapters = { { chapterId = 12763, durationSeconds = 600, pagesRead = 3 } } }, + { seriesId = 10560, localDate = "2026-10-10T00:00:00", + chapters = { { chapterId = 16493, durationSeconds = 300, pagesRead = 0 } } }, + { seriesId = 999, localDate = "2026-10-10T00:00:00", + chapters = { { chapterId = 5, durationSeconds = 111, pagesRead = 0 } } }, + } + routes["GET /api/Stats/reading-history"] = function() + return json(stats_history, { Pagination = pagination_header(1, 1) }) + end + local volumes_route = routes["GET /api/Series/volumes"] + routes["GET /api/Series/8661"] = json({ id = 8661, name = "人类简史", libraryId = 1 }) + routes["GET /api/Series/10560"] = json({ id = 10560, name = "镖人", libraryId = 1 }) + routes["GET /api/Series/999"] = { code = 404, body = "" } + routes["GET /api/Series/volumes"] = function(opts) + if query(opts, "seriesId") == "8661" then + return json({ { id = 86610, chapters = { { id = 12763, titleName = "全", format = 3, pages = 10 } } } }) + end + if query(opts, "seriesId") == "10560" then + return json({ + { id = 105600, chapters = { { id = 16493, titleName = "一", format = 1, pages = 20 } } }, + { id = 105601, chapters = { { id = 16494, titleName = "二", format = 1, pages = 20 } } }, + { id = 105602, chapters = { { id = 16495, titleName = "三", format = 1, pages = 20 } } }, + }) + end + return volumes_route(opts) + end + tocs["8661"] = { { chapterId = 12763 } } + + local before = #calls + local pulled = run("pullStatsAsync") + local day = os.time({ year = 2026, month = 10, day = 10, hour = 0 }) + local function findBook(rows, record_type, stable_id, start_time) + for _idx, row in ipairs(rows) do + if row.record_type == record_type and row.stable_id == stable_id + and (not start_time or row.start_time == start_time) then return row end + end + end + Assert.eq(findBook(pulled.rows, "book_day", "8661", day).duration, 600, "1 章 = 单卷,读在 series 行") + Assert.eq(findBook(pulled.rows, "book_day", "10560:16493", day).duration, 300, "3 章 = 多卷,读在卷行") + Assert.eq(findBook(pulled.rows, "total", "__kv:total").duration, 900, "判不出身份的系列不进总量") + for _idx, row in ipairs(pulled.rows) do + Assert.is_nil(row.stable_id:match("^999"), "目录拿不到的系列不猜身份") + end + local series_calls = {} + for idx = before + 1, #calls do + local sid = calls[idx].url:match("^http://kav/api/Series/(%d+)$") + if sid then series_calls[#series_calls + 1] = sid end + end + Assert.eq(table.concat(series_calls, ","), "10560,999", "缓存里有 8661,只判 10560 与 999") + Assert.is_true(warnedAbout("999"), "跳过的系列要能被日志定位") + + pulled.commit() + local state = require("luasettings"):open(STATS_STATE) + Assert.eq(state:readSetting("volumes")["8661"], 1, "单卷判定入状态文件") + Assert.eq(state:readSetting("volumes")["10560"], 3, "多卷判定入状态文件") + Assert.is_nil(state:readSetting("volumes")["999"], "判不出的系列不落状态,下轮还会再试") + local identities = state:readSetting("identities") + Assert.len(identities, 2) + Assert.contains(identities, "8661") + Assert.contains(identities, "10560:16493") + + -- 第二轮:目录缓存清空(再走判定就得发请求),但状态文件里有章数 → 一行请求都不发。 + tocs["8661"], tocs["10560"] = nil, nil + routes["GET /api/Series/10560"] = { code = 404, body = "" } + routes["GET /api/Series/volumes"] = function() return { code = 404, body = "" } end + before = #calls + local again = run("pullStatsAsync") + Assert.eq(findBook(again.rows, "book_day", "8661", day).duration, 600, "身份判定走状态文件,结果不变") + Assert.eq(findBook(again.rows, "book_day", "10560:16493", day).duration, 300) + series_calls = {} + for idx = before + 1, #calls do + local sid = calls[idx].url:match("^http://kav/api/Series/(%d+)$") + if sid then series_calls[#series_calls + 1] = sid end + end + Assert.eq(table.concat(series_calls, ","), "999", "已判定的系列不再请求目录") + Assert.len(again.replace.books, 2, "上次身份 ∪ 本次身份,旧身份的孤儿行照样清") + again.commit() + routes["GET /api/Series/volumes"] = volumes_route +end + +-- 缺行卷物化:云端读过、本机没有书行的卷(seriesId:chapterId)补一条轻量身份行 —— 标题 +-- 「系列 · 卷名」、继承容器行的作者 / 简介 / 分类 / 系列,不写封面。洞察「当日书单」、单书详情、 +-- 锁屏账单才有书名而不是裸 ID。隐藏身份行(库里落成 deleted=1 + sync_status=1)不上架、 +-- 不触发书架对账、不进书架同步结果,写库只由本次统计同步的 stats_changed 带走; +-- 容器行缺失时跳过物化(统计行照写)。 +do + local day = os.time({ year = 2026, month = 10, day = 10, hour = 0 }) + local function findRow(rows, record_type, stable_id) + for _idx, row in ipairs(rows) do + if row.record_type == record_type and row.stable_id == stable_id then return row end + end + end + routes["GET /api/Stats/reading-history"] = function() + return json({ + { seriesId = 8801, localDate = "2026-10-10T00:00:00", + chapters = { { chapterId = 88010, durationSeconds = 600, pagesRead = 1 } } }, + { seriesId = 8802, localDate = "2026-10-10T00:00:00", + chapters = { { chapterId = 88020, durationSeconds = 300, pagesRead = 0 } } }, + { seriesId = 8803, localDate = "2026-10-10T00:00:00", + chapters = { { chapterId = 88030, durationSeconds = 120, pagesRead = 0 } } }, + { seriesId = 8804, localDate = "2026-10-10T00:00:00", + chapters = { { chapterId = 88040, durationSeconds = 60, pagesRead = 0 } } }, + }, { Pagination = pagination_header(1, 1) }) + end + tocs["8801"] = { { chapterId = 88010, title = "第二卷" }, { chapterId = 88011, title = "第三卷" } } + tocs["8802"] = { { chapterId = 88020, title = "上" }, { chapterId = 88021, title = "下" } } + tocs["8803"] = { { chapterId = 88030, title = "全" } } + -- 卷名拿不到的老目录(只剩 chapterId):物化标题的卷名退容器名,不留裸 ID / 空标题。 + tocs["8804"] = { { chapterId = 88040 }, { chapterId = 88041 } } + books["8801"] = { title = "合集", authors = "甲", intro = "简介", category = "书籍" } + books["8803"] = { title = "单卷书", authors = "乙", category = "书籍" } + books["8804"] = { title = "太空漫游", authors = "丙", category = "书籍" } + + reconciled, remembered = nil, {} + local pulled = run("pullStatsAsync") + local material = remembered["8801:88010"] + Assert.eq(material and material.title, "合集 · 第二卷", "标题 = 系列 · 卷名(卷名取目录条目)") + Assert.eq(material and material.authors, "甲", "作者继承容器行") + Assert.eq(material and material.intro, "简介", "简介继承容器行") + Assert.eq(material and material.category, "书籍", "分类继承容器行") + Assert.eq(material and material.series, "合集", "系列列继承容器行") + Assert.is_nil(material and material.cover, "封面不写:卷封面走源既有取图链路") + Assert.is_nil(material and material.path, "不是下载行") + Assert.is_nil(material and material.deleted, "不带书架成员标记 → 落库即隐藏身份行,不上架") + Assert.is_nil(remembered["8801:88011"], "本次没读到的卷不物化") + Assert.is_nil(remembered["8802:88020"], "容器行缺失 → 跳过物化") + Assert.eq(findRow(pulled.rows, "book_day", "8802:88020").duration, 300, "容器缺失不影响统计行(照写)") + Assert.is_nil(remembered["8803"], "单卷系列读在容器行上,不另补行") + Assert.eq(remembered["8804:88040"] and remembered["8804:88040"].title, "太空漫游 · 太空漫游", + "目录条目没有卷名时退容器名(fetchToc 给不出时也别留裸 ID)") + Assert.is_nil(reconciled, "物化不触发书架对账") + Assert.is_nil(pulled.pulled, "物化不进书架同步结果(只由 stats_changed 刷新展示)") + + -- 物化后卷行真实入库(rememberMany 会落库):下一轮已存在且无变更 → 不重写(幂等)。 + -- 第二轮必须让核心调 commit 推进状态(真实链路:入库成功才 commit)。状态不前进的话 + -- 章数判定不落盘、目录每轮重读,测不出「第二轮拿不到卷名」的标题回退(旧用例的盲区)。 + books["8801:88010"] = remembered["8801:88010"] + local state_before_commit = readFile(STATS_STATE) + Assert.not_nil(state_before_commit, "前一段已经写过状态文件") + pulled.commit() + + -- 第二轮起目录缓存全清(目录接口也不可用):卷名只能来自状态文件里的持久化卷名。 + tocs["8801"], tocs["8802"], tocs["8803"], tocs["8804"] = nil, nil, nil, nil + local history_route = routes["GET /api/Stats/reading-history"] + routes["GET /api/Stats/reading-history"] = function() + return json({ + { seriesId = 8801, localDate = "2026-10-10T00:00:00", + chapters = { + { chapterId = 88010, durationSeconds = 600, pagesRead = 1 }, + -- 本轮新读到的卷:本机还没有书行,标题只能靠持久化卷名 + { chapterId = 88011, durationSeconds = 300, pagesRead = 0 }, + } }, + }, { Pagination = pagination_header(1, 1) }) + end + remembered = {} + run("pullStatsAsync") + Assert.is_nil(remembered["8801:88010"], "已存在的卷行不重写") + Assert.eq(remembered["8801:88011"] and remembered["8801:88011"].title, "合集 · 第三卷", + "第二轮物化标题取状态文件里的持久化卷名,不退容器名") + local committed = require("luasettings"):open(STATS_STATE) + local committed_titles = committed:readSetting("titles") + Assert.eq(committed_titles and committed_titles["8801"] and committed_titles["8801"]["88011"], "第三卷", + "身份判定时顺带记下的卷名落进状态文件(下次不用再读目录)") + routes["GET /api/Stats/reading-history"] = history_route + + -- 本地脏行(sync_status=0,本地改过):物化不动它(沿用卷行先例的 untouched 守卫)。 + books["8801:88010"] = { title = "本地改名", authors = "本地作者", sync_status = 0 } + remembered = {} + run("pullStatsAsync") + Assert.is_nil(remembered["8801:88010"], "本地脏行不重写") + Assert.eq(books["8801:88010"].title, "本地改名", "本地改的标题留着") + + -- 干净行但字段缺(容器后补的作者还没对齐):按容器补齐 —— 已存在且**有**变更照写, + -- 否则首次物化之后容器才补上的作者永远传不到卷行上。 + books["8801:88010"] = { title = "合集 · 第二卷", sync_status = 1 } + remembered = {} + run("pullStatsAsync") + Assert.eq(remembered["8801:88010"] and remembered["8801:88010"].authors, "甲", + "字段与容器不一致的行对齐一次") + + -- 兜底标题只用于新行:目录 / 状态都给不出卷名时,不能拿容器名盖既有行的真实标题 + -- (升级路径:老状态文件只有章数、没有卷名)。 + books["8804:88040"] = { title = "太空漫游 · 1001", sync_status = 1 } + remembered = {} + run("pullStatsAsync") + Assert.is_nil(remembered["8804:88040"], "无卷名时兜底标题不改写既有标题") + Assert.eq(books["8804:88040"].title, "太空漫游 · 1001", "既有真实标题保留") + + books["8801"], books["8801:88010"], books["8804:88040"] = nil, nil, nil + tocs["8801"], tocs["8802"], tocs["8803"], tocs["8804"] = nil, nil, nil, nil + books["8803"], books["8804"] = nil, nil + -- 状态恢复成这次 commit 之前的样子:后面的用例(落库时序 / 失败 / 取消)断言的是上段状态。 + local restore = assert(io.open(STATS_STATE, "w")) + restore:write(state_before_commit) + restore:close() + routes["GET /api/Stats/reading-history"] = function() + return json({ { seriesId = 8661, localDate = "2026-10-10T00:00:00", + chapters = { { chapterId = 12763, durationSeconds = 60, pagesRead = 0 } } } }, + { Pagination = pagination_header(1, 1) }) + end +end + +-- 落库时序 / 失败 / 取消 / 页数上限:状态只由 commit 推进,失败与取消都不动它。 +do + local day = os.time({ year = 2026, month = 10, day = 10, hour = 0 }) + local before_state = readFile(STATS_STATE) + Assert.not_nil(before_state, "前一段已经写过状态文件") + + -- 结果交回核心时还没落库:状态先一动不动,等核心入库成功调 commit 才前进。 + routes["GET /api/Stats/reading-history"] = function() + return json({ { seriesId = 8661, localDate = "2026-10-10T00:00:00", + chapters = { { chapterId = 12763, durationSeconds = 600, pagesRead = 0 } } } }, + { Pagination = pagination_header(1, 1) }) + end + local pulled = run("pullStatsAsync") + Assert.eq(readFile(STATS_STATE), before_state, "落库前不改状态(失败时身份不前进,孤儿行下次还能清)") + Assert.len(pulled.replace.books, 2, "replace.books = 上次身份 ∪ 本次身份") + Assert.contains(pulled.replace.books, "10560:16493") + Assert.contains(pulled.replace.books, "8661") + pulled.commit() + Assert.is_true(readFile(STATS_STATE) ~= before_state, "commit 之后才写状态") + + -- 失败:cb(nil, err),状态不前进、不建重试队列;本地统计不受影响(核心只记日志)。 + before_state = readFile(STATS_STATE) + routes["GET /api/Stats/reading-history"] = function() return { code = 500, body = "" } end + local failed, ferr = run("pullStatsAsync") + Assert.is_nil(failed) + Assert.matches(ferr, "500") + Assert.eq(readFile(STATS_STATE), before_state, "失败不前进状态") + + -- 取消也一样:第二页在飞时取消,迟到的回包不回调、不写状态。 + routes["GET /api/Stats/reading-history"] = function(opts) + if query(opts, "PageNumber") == "2" then + return { hold = true, reply = json({}, { Pagination = pagination_header(2, 2) }) } + end + return json({ { seriesId = 8661, localDate = "2026-10-10T00:00:00", + chapters = { { chapterId = 12763, durationSeconds = 60, pagesRead = 0 } } } }, + { Pagination = pagination_header(1, 2) }) + end + local called = false + local job = source:pullStatsAsync(function() called = true end) + Stubs.flush() + Assert.len(held, 1, "第二页在飞") + job:cancel() + held[#held]() + Stubs.flush() + Assert.is_false(called, "取消后不回调") + Assert.eq(readFile(STATS_STATE), before_state, "取消也不写状态") + + -- 分页头乱报(说 999 页):页数上限兜底,不无限循环,已经拿到的条目照常入库。 + local capped = 0 + routes["GET /api/Stats/reading-history"] = function() + capped = capped + 1 + return json({ { seriesId = 8661, localDate = "2026-10-10T00:00:00", + chapters = { { chapterId = 12763, durationSeconds = 60, pagesRead = 0 } } } }, + { Pagination = pagination_header(1, 999) }) + end + local result = run("pullStatsAsync") + Assert.eq(capped, 50, "页数上限兜底") + Assert.not_nil(result, "上限只是停止续拉,不是失败") + Assert.eq(result.rows[1].start_time, day, "已经拉到的页照常入库") +end + +-- 框架集成:一次统计同步 = 先本地确认(push)再拉取(pull)落库;dirty_only(推脏)只推不拉。 +do + local pending_stats = { { + id = 21, source_id = "kavita", stable_id = "8661", record_type = "page", page = 3, + start_time = 1000, duration = 30, total_pages = 10, + } } + local events, marked, replaced = {}, nil, nil + package.loaded["book.stats_db"] = { + unsyncedBySource = function() return pending_stats end, + markSynced = function(ids) + marked = ids + events[#events + 1] = "mark" + pending_stats = {} + return true + end, + replaceSynced = function(source_id, replace, rows) + events[#events + 1] = "replace" + replaced = { source_id = source_id, replace = replace, rows = rows } + return { imported = #rows, skipped = 0 } + end, + compactSynced = function() return 0 end, + } + routes["GET /api/Stats/reading-history"] = function() + events[#events + 1] = "http" + return json({ + { seriesId = 8661, localDate = "2026-10-10T00:00:00", + chapters = { { chapterId = 12763, durationSeconds = 120, pagesRead = 0 } } }, + -- 云端读过、本机没有书行的卷:同一次同步的拉取照常物化补身份行(12 号票语义)。 + { seriesId = 10560, localDate = "2026-10-10T00:00:00", + chapters = { { chapterId = 16493, durationSeconds = 60, pagesRead = 0 } } }, + }, { Pagination = pagination_header(1, 1) }) + end + books["10560"] = { title = "镖人", authors = "丰" } + remembered = {} + + local result = run("syncStatsAsync", nil) + Assert.eq(marked[1], 21, "先本地确认本地待同步行") + Assert.eq(replaced.source_id, "kavita") + local pulled_8661 = false + for _idx, row in ipairs(replaced.rows) do + if row.stable_id == "8661" then pulled_8661 = true end + end + Assert.is_true(pulled_8661, "拉取的行按云端快照入库") + Assert.not_nil(replaced.replace, "替换指令一并交给核心") + Assert.eq(events[1], "mark", "先推后拉:确认落在拉取之前") + Assert.eq(events[#events], "replace", "最后是落库") + Assert.eq(result.pushed, 1) + Assert.eq(result.pulled, #replaced.rows) + Assert.eq(remembered["10560:16493"] and remembered["10560:16493"].title, "镖人 · 一", + "物化标题取状态文件里的持久化卷名") + + -- dirty_only(推脏队列):只做本地确认,不发请求——拉取挂在打开 / 切换与手动刷新上。 + pending_stats = { { + id = 22, source_id = "kavita", stable_id = "8661", record_type = "page", page = 4, + start_time = 1100, duration = 30, total_pages = 10, + } } + marked, replaced, events = nil, nil, {} + local before_calls = #calls + run("syncStatsAsync", { dirty_only = true }) + Assert.eq(marked[1], 22, "推脏照样确认本地行") + Assert.is_nil(replaced, "dirty_only 不拉取、不覆盖") + Assert.eq(table.concat(events, ","), "mark", "dirty_only 只做本地确认") + Assert.eq(#calls, before_calls, "dirty_only 零请求") +end + +-- 状态文件被写坏(volumes / identities 不是表):当作没判过,本轮重新判定并从空表重建, +-- 不让存档损坏把整次拉取打断。 +do + local state = require("luasettings"):open(STATS_STATE) + state:saveSetting("volumes", 42) + state:saveSetting("identities", "坏") + state:flush() + + local before_calls = #calls + local recovered = run("pullStatsAsync") + Assert.not_nil(recovered, "损坏的状态文件不影响拉取") + local series_calls = 0 + for idx = before_calls + 1, #calls do + if calls[idx].url:match("^http://kav/api/Series/8661$") then series_calls = series_calls + 1 end + end + Assert.eq(series_calls, 1, "坏档当没判过:重新请求目录判定身份") + Assert.len(recovered.replace.books, 1, "坏档的 identities 不参与替换范围") + Assert.contains(recovered.replace.books, "8661") + recovered.commit() + state = require("luasettings"):open(STATS_STATE) + Assert.eq(state:readSetting("volumes")["8661"], 1, "判定结果从空表重建后写回") +end + +-- 定位:pull 只落数据,开书时按 DocumentFragment 滑窗把 cloud 划线变成 crengine xpointer。 +-- 假文档只实现定位用到的四个接口,语义按真机:`text()[k]` 逐个枚举、偏移按 codepoint 计。 +do + local function cp_len(s) + local n = 0 + for ch in s:gmatch("[%z\1-\127\194-\244][\128-\191]*") do n = n + 1 end + return n + end + + local function cp_sub(s, from, to) + local function byte_pos(count) + local seen, i = 0, 1 + while seen < count and i <= #s do + local b = s:byte(i) + i = i + (b < 0x80 and 1 or b < 0xE0 and 2 or b < 0xF0 and 3 or 4) + seen = seen + 1 + end + return i - 1 + end + return s:sub(byte_pos(from - 1) + 1, byte_pos(to)) + end + + ---@param fragments table[] 每项是一页(DocFragment)的段落列表;段落是字符串或文本节点数组。 + ---@param file string|nil + local function fakeDocument(fragments, file) + local elements, nodes, pages = {}, {}, {} + local order, fragment_text, node_offset = {}, {}, {} + for f, paragraphs in ipairs(fragments) do + local prefix = "/body/DocFragment[" .. f .. "]/body" + order[f] = order[f] or {} + for p, item in ipairs(paragraphs) do + local elem = prefix .. "/p[" .. p .. "]" + local texts = type(item) == "table" and item or { item } + elements[elem] = table.concat(texts) + for k, text in ipairs(texts) do + local path = elem .. "/text()[" .. k .. "]" + nodes[path] = text + order[f][#order[f] + 1] = path + end + pages[elem] = f * 10 + end + end + for f, paths in pairs(order) do + local acc, offsets, parts = 0, {}, {} + for _idx, path in ipairs(paths) do + offsets[path] = acc + acc = acc + cp_len(nodes[path]) + parts[#parts + 1] = nodes[path] + end + fragment_text[f] = table.concat(parts) + node_offset[f] = offsets + end + + local document = { file = file } + function document:getTextFromXPointer(xp) + local path = xp:gsub("%.%d+$", "") + return nodes[path] or elements[path] + end + function document:isXPointerInDocument(xp) + local path, off = xp:match("^(.*)%.(%d+)$") + path = path or xp + local text = nodes[path] + if text then + return off == nil or tonumber(off) <= cp_len(text) + end + return off == nil and elements[path] ~= nil + end + function document:getNormalizedXPointer(xp) + return self:isXPointerInDocument(xp) and xp or false + end + -- 真机语义:pos1 是「选区后第一个字符」的偏移(不含),跨文本节点时按片段拼接。 + function document:getTextFromXPointers(pos0, pos1) + local path0, off0 = pos0:match("^(.*)%.(%d+)$") + local path1, off1 = pos1:match("^(.*)%.(%d+)$") + if not path0 or not path1 then return nil end + local f = tonumber(path0:match("DocFragment%[(%d+)%]")) + if not f or not node_offset[f] or not node_offset[f][path0] or not node_offset[f][path1] then + return nil + end + return cp_sub(fragment_text[f], node_offset[f][path0] + tonumber(off0) + 1, + node_offset[f][path1] + tonumber(off1)) + end + function document:getPageFromXPointer(xp) + local elem = xp:match("^(.*)/text%(%)%[%d+%]%.%d+$") + return pages[elem] or pages[xp] or 1 + end + return document + end + + os.execute("mkdir -p '" .. WORK .. "'") + local book_path = WORK .. "/15-localize.epub" + local fh = assert(io.open(book_path, "wb")) + fh:write("PK\3\4epub") + fh:close() + + local document = fakeDocument({ + { + "春眠不觉晓,处处闻啼鸟。", + "夜来风雨声,花落知多少。", + { "春眠", "不觉晓" }, + { "第一段。", "第二段在同一 p 里。" }, + "去空白\194\160重试", + }, + { + "另一个 DocFragment 的正文。", + "滑窗命中的句子。", + }, + -- 多 spine 书(本票的真实形态):第 5 个片段里这句只在 pageNumber = 4 的提示下才找得到。 + { "第三个片段的噪音。" }, + { "第四个片段的噪音。" }, + { "第五个片段里才有的一句。", "第五个片段的第二段。" }, + }, book_path) + + local anns = { + { -- 普通命中:段内偏移按 codepoint 算,page 与 reader 一致填 pos0 字符串。 + kavita_id = 601, datetime = "2026-10-01 00:00:00", text = "处处闻啼鸟", note = "好诗", + kavita_note = "好诗", kavita_xpath = "//body/p[1]", kavita_ending_xpath = "//body/p[1]", + pageNumber = 0, + }, + { -- 多文本节点:Kavita 的 text() 下标只当提示,按 crengine 的节点枚举重新映射。 + kavita_id = 602, text = "不觉晓", kavita_xpath = "//body/p[3]", + kavita_ending_xpath = "//body/p[3]", pageNumber = 0, + }, + { -- pageNumber 差一位(旧推送窗口):spine 提示失败,靠 +1 滑窗命中。 + kavita_id = 603, text = "滑窗命中的句子", kavita_xpath = "//body/p[2]", + kavita_ending_xpath = "//body/p[2]", pageNumber = 0, + }, + { -- 跨段:起点取贴段尾的最长前缀,终点取贴段首的最长后缀。 + kavita_id = 604, text = "啼鸟。夜来", kavita_xpath = "//body/p[1]", + kavita_ending_xpath = "//body/p[2]", pageNumber = 0, + }, + { -- 元素下标失配(Kavita 的 p 数与 crengine 不同):同片段同级回扫。 + kavita_id = 605, text = "第二段在同一 p 里。", kavita_xpath = "//body/p[9]", + kavita_ending_xpath = "//body/p[9]", pageNumber = 0, + }, + { -- 单条失败不能拖累同书其它条:标 unlocated,不写占位坐标。 + kavita_id = 606, text = "这句话不在书里", kavita_xpath = "//body/p[2]", + kavita_ending_xpath = "//body/p[2]", pageNumber = 0, + }, + { -- 同一 kavita_id 已有通过校验的坐标:直接复用,避免每次开书重算。 + kavita_id = 607, text = "这句也找不到", kavita_xpath = "//body/p[1]", + kavita_ending_xpath = "//body/p[1]", pageNumber = 0, + }, + { -- 旧坐标已失效(偏移越界):不复用,重算失败照常标 unlocated。 + kavita_id = 608, text = "哪里都没有", kavita_xpath = "//body/p[1]", + kavita_ending_xpath = "//body/p[1]", pageNumber = 0, + }, + { -- 空白折叠差异(crengine 保留 NBSP,Kavita 存普通空格):去空白重试后回算偏移。 + kavita_id = 609, text = "去空白 重试", kavita_xpath = "//body/p[5]", + kavita_ending_xpath = "//body/p[5]", pageNumber = 0, + }, + } + local current = { + { kavita_id = 607, pos0 = "/body/DocFragment[1]/body/p[1]/text()[1].0", + pos1 = "/body/DocFragment[1]/body/p[1]/text()[1].2", page = "旧", pageno = 9 }, + { kavita_id = 608, pos0 = "/body/DocFragment[1]/body/p[1]/text()[1].999", + pos1 = "/body/DocFragment[1]/body/p[1]/text()[1].1000", page = "越界" }, + } + + local localized = source:localizeAnnotations(document, anns, book_path, current) + Assert.len(localized, #anns, "返回全量:定位失败的也在列表里") + Assert.eq(localized[1].kavita_id, 601) + Assert.eq(localized[1].pos0, "/body/DocFragment[1]/body/p[1]/text()[1].6") + Assert.eq(localized[1].pos1, "/body/DocFragment[1]/body/p[1]/text()[1].11") + Assert.eq(localized[1].page, localized[1].pos0, "page 填 pos0 字符串,不能填数字") + Assert.eq(localized[1].pageno, 10) + Assert.eq(localized[1].note, "好诗", "定位只补坐标,不动 pull 落的字段") + Assert.eq(localized[1].kavita_note, "好诗") + Assert.is_nil(localized[1].kavita_unlocated) + + Assert.eq(localized[2].pos0, "/body/DocFragment[1]/body/p[3]/text()[2].0", + "span 内文本按 crengine 的 text()[k] 重新编号") + Assert.eq(localized[2].pos1, "/body/DocFragment[1]/body/p[3]/text()[2].3") + + Assert.eq(localized[3].pos0, "/body/DocFragment[2]/body/p[2]/text()[1].0", "pageNumber 只当提示,+1 滑窗命中") + Assert.eq(localized[3].pageno, 20) + + Assert.eq(localized[4].pos0, "/body/DocFragment[1]/body/p[1]/text()[1].9", "跨段起点贴段尾") + Assert.eq(localized[4].pos1, "/body/DocFragment[1]/body/p[2]/text()[1].2", "跨段终点贴段首") + + Assert.eq(localized[5].pos0, "/body/DocFragment[1]/body/p[4]/text()[2].0", "p[9] 不存在时回扫同级") + + Assert.is_true(localized[6].kavita_unlocated, "文本匹配不到就标未定位") + Assert.is_nil(localized[6].pos0, "未定位不写占位坐标") + Assert.is_nil(localized[6].pos1) + Assert.is_nil(localized[6].page) + + Assert.eq(localized[7].pos0, "/body/DocFragment[1]/body/p[1]/text()[1].0", "复用 current 的有效坐标") + Assert.eq(localized[7].pos1, "/body/DocFragment[1]/body/p[1]/text()[1].2") + Assert.is_nil(localized[7].kavita_unlocated) + + Assert.is_true(localized[8].kavita_unlocated, "旧坐标越界不能复用") + Assert.is_nil(localized[8].pos0) + + Assert.eq(localized[9].pos0, "/body/DocFragment[1]/body/p[5]/text()[1].0", "NBSP 与普通空格差异靠去空白重试") + Assert.eq(localized[9].pos1, "/body/DocFragment[1]/body/p[5]/text()[1].6") + Assert.is_nil(localized[9].kavita_unlocated) + + -- 本票的链路回归(pull → cleanAnnotations → localize):三国演义这种多 spine epub 的注解在 + -- pageNumber 17/23/24(0-based),没有这个提示就只试 DocFragment[1]/[2], + -- 第 3 个片段之后全部 text-not-found → kavita_unlocated,一条都不画。 + routes["GET /api/Annotation/all"] = json({ { + id = 701, ownerUserId = 5, chapterId = 2002, + xPath = "//body/p[1]", endingXPath = "//body/p[1]", + selectedText = "第五个片段里才有的一句", + comment = "", commentHtml = "", commentPlainText = "", + selectedSlotIndex = 0, createdUtc = "2026-10-03T05:00:00", + pageNumber = 4, + } }) + local chain_pulled = run("pullNotesAsync", volume) + Assert.eq(chain_pulled[1].pageNumber, 4, "pull 保留 DTO 的 spine 提示") + local chain_clean = source:cleanAnnotations(chain_pulled, 0) + Assert.eq(chain_clean[1].pageNumber, 4, "cleanAnnotations 不能把提示洗掉") + local chain_located = source:localizeAnnotations(document, chain_clean, book_path, nil) + Assert.eq(chain_located[1].pos0, "/body/DocFragment[5]/body/p[1]/text()[1].0", + "pageNumber = 4 → 先试 DocFragment[5] 命中") + Assert.eq(chain_located[1].pos1, "/body/DocFragment[5]/body/p[1]/text()[1].11") + Assert.is_nil(chain_located[1].kavita_unlocated) + + -- 回归锁:同一份条目抹掉 pageNumber → 只试前两个片段 → 定位失败(真实 bug 的形态)。 + local no_hint = {} + for key, value in pairs(chain_clean[1]) do no_hint[key] = value end + no_hint.pageNumber = nil + local orphan = source:localizeAnnotations(document, { no_hint }, book_path, nil) + Assert.is_true(orphan[1].kavita_unlocated, "没有 spine 提示时第 3 个片段之后的文本定位不到") + Assert.is_nil(orphan[1].pos0) + Assert.is_nil(orphan[1].page) + + -- 无文档 / html_path 缺失 / 文件不存在 / 文档不是这本书 → nil(core 据此放弃应用,不覆盖 doc_settings)。 + Assert.is_nil(source:localizeAnnotations(nil, anns, book_path, current)) + Assert.is_nil(source:localizeAnnotations(document, anns, nil, current)) + Assert.is_nil(source:localizeAnnotations(document, anns, "", current)) + Assert.is_nil(source:localizeAnnotations(document, anns, WORK .. "/missing.epub", current)) + local other = fakeDocument({ { "别的书" } }, WORK .. "/other.epub") + Assert.is_nil(source:localizeAnnotations(other, anns, book_path, current), "document.file 与 html_path 不一致") +end + +---------------------------------------------------------------------- +-- 已删除的「多设备统计合并」开关:旧配置残留的键在源实例化时清掉。 +---------------------------------------------------------------------- +do + local Cache = require("moonsource_kavita.cache") + local original = { + probe = Cache.probe, queueState = Cache.queueState, + chapters = Cache.chapters, resumePage = Cache.resumePage, + } + Cache.probe = function() return { ok = true, capabilities = { chapters = true, queue = true } } end + Cache.queueState = function() return { state = "idle", entries = {} } end + local chapter_calls = 0 + Cache.chapters = function() + chapter_calls = chapter_calls + 1 + return { { chapterId = 9901, pages = 100, read = true, bytes = 1024 } } + end + Cache.resumePage = function() end + local series = { source_id = "kavita", stable_id = "9900", title = "续读测试", authors = "作者" } + local toc = { + { chapterId = 9901, title = "卷一", pages = 100, pagesRead = 1 }, + { chapterId = 9902, title = "卷二", pages = 100, pagesRead = 0 }, + } + tocs["9900"], toc_fresh = toc, true + progress["9900:9901"] = { fraction = 0.01, page = 1, total_pages = 100 } + local meta = source:readingTarget(series, { meta_only = true }) + Assert.eq(meta.select_text, "选择卷") + Assert.eq(chapter_calls, 0, "meta_only 不扫缓存") + local before = #calls + local target = source:readingTarget(series) + Assert.is_true(chapter_calls > 0, "完整目标才读 kamare 缓存") + local list_target = require("moonsource_kavita.volume_list").continueTarget(series, toc) + Assert.eq(target.book.stable_id, "9900:" .. list_target.entry.chapterId, + "详情目标与列表同源;kamare 完成事实优先于本机回顾进度") + Assert.eq(target.book.stable_id, "9900:9902") + Assert.eq(target.book.authors, "作者", "目标卷继承容器元数据") + Assert.eq(target.text, "继续阅读 · 卷二") + Assert.eq(target.select_text, "选择卷") + Assert.eq(#calls, before, "读取续读目标不发网络请求") + Assert.is_nil(source:readingTarget(target.book), "单卷不重新计算容器续读目标") + Assert.is_nil(source:readingTarget({ source_id = "kavita", stable_id = "9909" }), + "没有本地目录就保留原开书流程") + for name, method in pairs(original) do Cache[name] = method end +end + +cfg.merge_local_stats = true +require("moonsource_kavita.source").new() +Assert.is_nil(cfg.merge_local_stats, "旧开关残留键不能让核心继续按开启合并") + +os.execute("rm -rf '" .. WORK .. "'") diff --git a/tests/kavita/stats_spec.lua b/tests/kavita/stats_spec.lua new file mode 100644 index 0000000..a068cfa --- /dev/null +++ b/tests/kavita/stats_spec.lua @@ -0,0 +1,664 @@ +--[[-- +moonsource_kavita.stats:reading-history 条目 → reading_stats 行 / 替换指令 / 身份与时区映射。 + +对账基线 = research-kavita-stats-pull.md §3(样本 series 7453:64 条会话 / 14,237s)。 + +@module tests.moonsource_kavita.stats_spec +--]] + +local Assert = require("support.assert") +local Config = require("support.config") + +-- 日 / 时归属按进程时区(POSIX TZ)计算:钉死 CST-8,与 fixture 拉取时用的 Asia/Shanghai 对齐, +-- 断言就不会随宿主机时区漂移。 +local ffi = require("ffi") +ffi.cdef[[ int setenv(const char*, const char*, int); void tzset(void); ]] +ffi.C.setenv("TZ", "CST-8", 1) +ffi.C.tzset() + +local warnings = {} +package.preload["utils.log"] = function() + return { + dbg = function() end, + info = function() end, + warn = function(...) warnings[#warnings + 1] = table.concat({ ... }, " ") end, + error = function() end, + } +end + +local PLUGIN = (debug.getinfo(1, "S").source:match("^@(.-)/tests/") .. "/moonsource-kavita.koplugin/moonsource_kavita") +package.preload["moonsource_kavita.stats"] = function() + return dofile(PLUGIN .. "/stats.lua") +end +local Stats = require("moonsource_kavita.stats") + +-- 固定拉取时刻(2026-10-16T12:00:00Z,晚于样本最后一天):last_time / book_total.start_time 都对它断言 +local FETCHED = 1792152000 + +--- 当天设备本地零点。日期本身来自服务端;期望时差另有 research §3 表兜底。 +local function dayTs(y, m, d) + return os.time({ year = y, month = m, day = d, hour = 0 }) +end + +--- 当天设备本地整点(时段桶键)。 +local function hourTs(y, m, d, h) + return os.time({ year = y, month = m, day = d, hour = h }) +end + +--- 按记录身份找行(不依赖 rows 顺序)。 +local function find(rows, record_type, stable_id, start_time) + for _idx, row in ipairs(rows) do + if row.record_type == record_type and row.stable_id == stable_id + and (start_time == nil or row.start_time == start_time) then + return row + end + end +end + +--- 需要跨日断言时看日归属是否真是「服务端那一天」。 +local function ymd(ts) + return os.date("%Y-%m-%d", ts) +end + +do + -- 对账:样本《太空漫游 · 2010》64 条会话。逐日时长 / 页数为 research §3 的已知值。 + local history = dofile((debug.getinfo(1, "S").source:match("^@(.*)/")) .. "/fixtures/history_7453.lua") + local result = Stats.fromHistory(history, { + source_id = "kavita", + fetched_at = FETCHED, + volumes = { [7453] = 4 }, + seen = { "7453:11270" }, + }) + + local total = find(result.rows, "total", "__kv:total", 0) + Assert.not_nil(total, "账户累计行必须存在") + Assert.eq(total.duration, 14237, "样本全量时长") + Assert.eq(total.last_time, FETCHED, "累计行 last_time = 拉取时刻") + + local days = { + { 2026, 9, 29, 316, 2 }, + { 2026, 10, 5, 195, 0 }, + { 2026, 10, 7, 503, 0 }, + { 2026, 10, 8, 2036, 0 }, + { 2026, 10, 11, 512, 0 }, + { 2026, 10, 13, 979, 0 }, + { 2026, 10, 14, 6734, 0 }, -- 当天 +1 / -1 分属两条会话:先求和再钳制,相抵为净 0 页 + { 2026, 10, 15, 2962, 16 }, + } + local day_rows = 0 + local day_sum = 0 + local day_ts = {} + for _idx, d in ipairs(days) do + local ts = dayTs(d[1], d[2], d[3]) + day_ts[ts] = true + local row = find(result.rows, "day", "__kv:day:" .. ts, ts) + Assert.not_nil(row, "缺少日桶 " .. d[1] .. "-" .. d[2] .. "-" .. d[3]) + Assert.eq(row.duration, d[4], "日桶时长 " .. ymd(ts)) + Assert.eq(row.event_count, d[5], "日桶页数增量 " .. ymd(ts)) + Assert.eq(row.last_time, FETCHED, "日桶 last_time = 拉取时刻") + day_rows = day_rows + 1 + day_sum = day_sum + row.duration + end + Assert.eq(day_rows, 8, "只有有有效时长的日子落桶") + Assert.eq(day_sum, 14237, "账户累计 = 各日之和") + + -- 时段桶:每条活动行按自己的本地起始小时归档(跨零点的活动行取小时、仍记在条目那天)。 + local hour_rows, hour_total = 0, 0 + local hour_by_day = {} + for _idx, row in ipairs(result.rows) do + if row.record_type == "hour" then + hour_rows = hour_rows + 1 + hour_total = hour_total + row.duration + Assert.eq(row.stable_id, "__kv:hour:" .. row.start_time, "时段桶按整点做身份") + Assert.eq(row.last_time, FETCHED, "时段桶 last_time = 拉取时刻") + local d = os.date("%Y-%m-%d", row.start_time) + hour_by_day[d] = (hour_by_day[d] or 0) + row.duration + end + end + Assert.eq(hour_rows, 27, "样本 27 个整点有阅读") + Assert.eq(hour_total, 14237, "时段之和 = 账户累计") + Assert.eq(find(result.rows, "hour", "__kv:hour:" .. hourTs(2026, 10, 14, 11)).duration, 1352, "10-14 11 点") + Assert.eq(find(result.rows, "hour", "__kv:hour:" .. hourTs(2026, 10, 14, 14)).duration, 1812, "10-14 14 点") + Assert.eq(find(result.rows, "hour", "__kv:hour:" .. hourTs(2026, 9, 29, 18)).duration, 316, "9-29 18 点") + Assert.eq(find(result.rows, "hour", "__kv:hour:" .. hourTs(2026, 10, 15, 21)).duration, 845, "10-15 21 点") + -- 日页面「标题时长 = 时段图逐格之和」:逐日必须对得上 + for _idx, d in ipairs(days) do + Assert.eq(hour_by_day[ymd(dayTs(d[1], d[2], d[3]))], d[4], + "时段逐日之和 = 日桶 " .. d[1] .. "-" .. d[2] .. "-" .. d[3]) + end + -- 零时长会话(10-06 的 4 条等)整条丢弃,不留日桶 + for _idx, d in ipairs({ { 2026, 10, 6 }, { 2026, 10, 9 }, { 2026, 10, 10 }, { 2026, 10, 12 } }) do + local ts = dayTs(d[1], d[2], d[3]) + Assert.is_nil(find(result.rows, "day", "__kv:day:" .. ts, ts), "零时长日不留桶") + end + + -- 多卷系列:章节 4 卷 → 逐卷身份;11271 只在 9-29 读过,11273 是其余各日。 + local book_total = find(result.rows, "book_total", "7453:11273", FETCHED) + Assert.not_nil(book_total, "卷累计行") + Assert.eq(book_total.duration, 13921) + Assert.eq(find(result.rows, "book_total", "7453:11271", FETCHED).duration, 316) + + Assert.eq(find(result.rows, "book_day", "7453:11271", dayTs(2026, 9, 29)).duration, 316) + local book_days, book_totals = 0, 0 + for _idx, row in ipairs(result.rows) do + if row.record_type == "book_day" then + book_days = book_days + 1 + Assert.is_true(row.duration > 0, "单书日行也必须正时长") + Assert.is_true(day_ts[row.start_time] == true, "单书日行 start_time = 服务端那天的本地零点") + elseif row.record_type == "book_total" then + book_totals = book_totals + 1 + Assert.eq(row.start_time, FETCHED, "单书累计行的 start_time = 拉取时刻") + end + -- 云端快照没有页坐标,所有行 page / total_pages 恒为 0 + Assert.eq(row.page, 0, "云端行 page=0") + Assert.eq(row.total_pages, 0, "云端行 total_pages=0") + Assert.eq(row.source_id, "kavita") + end + Assert.eq(book_days, 8, "11271 一天 + 11273 七天") + Assert.eq(book_totals, 2, "每卷一条累计快照") + + -- 本次身份:持久化后下次当「上次身份」用于清孤儿行。 + Assert.eq(#result.identities, 2) + Assert.contains(result.identities, "7453:11271") + Assert.contains(result.identities, "7453:11273") + + -- 替换:账户桶按前缀 + 覆盖全量重拉窗口的时间窗;单书按上次 ∪ 本次身份精确清。 + Assert.eq(result.replace.mode, "ranges") + Assert.eq(#result.replace.ranges, 3) + local ranges = {} + for _idx, range in ipairs(result.replace.ranges) do ranges[range.stable_prefix] = range end + local day_range, hour_range, total_range = + ranges["__kv:day:"], ranges["__kv:hour:"], ranges["__kv:total"] + Assert.not_nil(day_range, "日桶清理范围") + Assert.not_nil(hour_range, "时段桶清理范围") + Assert.not_nil(total_range, "总量行清理范围") + Assert.eq(day_range.from_ts, 0) + Assert.eq(day_range.to_ts, FETCHED) + Assert.eq(hour_range.from_ts, 0) + Assert.eq(hour_range.to_ts, FETCHED) + Assert.eq(total_range.from_ts, 0) + Assert.eq(total_range.to_ts, 0) + -- 全量重拉的清理窗口必须盖住本次写出的每个桶,否则消失的桶会残留 + for _idx, row in ipairs(result.rows) do + if row.record_type == "day" then + Assert.is_true(row.start_time <= day_range.to_ts, "日桶落在清理窗口内") + elseif row.record_type == "hour" then + Assert.is_true(row.start_time <= hour_range.to_ts, "时段桶落在清理窗口内") + end + end + Assert.eq(#result.replace.books, 3, "上次身份 ∪ 本次身份(含漂移孤儿)") + Assert.contains(result.replace.books, "7453:11270") + Assert.contains(result.replace.books, "7453:11271") + Assert.contains(result.replace.books, "7453:11273") +end + +do + -- 多章会话(跨卷)按章拆到各卷;单卷系列读在 series 行(research §5 的身份约定)。 + local result = Stats.fromHistory({ + { seriesId = 55, localDate = "2026-10-10T00:00:00", chapters = { + { chapterId = 11, durationSeconds = 100, pagesRead = 2 }, + { chapterId = 12, durationSeconds = 50, pagesRead = -1 }, + } }, + { seriesId = 66, localDate = "2026-10-10T00:00:00", chapters = { + { chapterId = 21, durationSeconds = 70, pagesRead = 0 }, + } }, + }, { source_id = "kavita", fetched_at = 2000, volumes = { [55] = 2, [66] = 1 } }) + local day = dayTs(2026, 10, 10) + Assert.eq(find(result.rows, "book_day", "55:11", day).duration, 100) + Assert.eq(find(result.rows, "book_day", "55:12", day).duration, 50) + Assert.eq(find(result.rows, "book_day", "66", day).duration, 70, "单卷记 series 身份") + Assert.eq(find(result.rows, "book_total", "55:11", 2000).duration, 100) + Assert.eq(find(result.rows, "book_total", "66", 2000).duration, 70) + local day_row = find(result.rows, "day", "__kv:day:" .. day, day) + Assert.eq(day_row.duration, 220, "账户日是各章之和") + Assert.eq(day_row.event_count, 1, "当天页数先求和:2 + (-1) + 0") + Assert.eq(find(result.rows, "total", "__kv:total", 0).duration, 220) + -- 没有 startTimeUtc 的条目退回 localDate 分日;造不出小时就不造,绝不凭空补一个整点。 + for _idx, row in ipairs(result.rows) do + Assert.is_true(row.record_type ~= "hour", "缺 startTimeUtc 不造时段桶") + end + Assert.len(result.identities, 3) + Assert.contains(result.identities, "55:11") + Assert.contains(result.identities, "55:12") + Assert.contains(result.identities, "66") +end + +do + -- 分日 / 分时按服务端 UTC 时刻在设备本地(CST-8)换算,不信服务端按请求时区给的 localDate。 + local result = Stats.fromHistory({ + -- 本地 10-16 07:59(UTC 10-15 23:59):服务端若按 UTC 算 localDate 会给 10-15,差一天。 + { seriesId = 31, startTimeUtc = "2026-10-15T23:59:00.1", localDate = "2026-10-15T00:00:00", + chapters = { { chapterId = 1, startTimeUtc = "2026-10-15T23:59:00.1", durationSeconds = 60, pagesRead = 1 } } }, + -- 本地 10-17 00:30 起、23:50 又读了一段:日桶在 10-17,两个时段格也都算 10-17 这天。 + { seriesId = 32, startTimeUtc = "2026-10-16T16:30:00", localDate = "2026-10-17T00:00:00", + chapters = { + { chapterId = 1, startTimeUtc = "2026-10-16T16:30:00", durationSeconds = 40, pagesRead = 0 }, + { chapterId = 1, startTimeUtc = "2026-10-17T15:50:00", durationSeconds = 60, pagesRead = 0 }, + } }, + }, { source_id = "kavita", fetched_at = FETCHED, volumes = { [31] = 2, [32] = 2, [33] = 2 } }) + local d16, d17 = dayTs(2026, 10, 16), dayTs(2026, 10, 17) + Assert.eq(find(result.rows, "day", "__kv:day:" .. d16, d16).duration, 60, "本地 07:59 落本地当天") + Assert.eq(find(result.rows, "hour", "__kv:hour:" .. hourTs(2026, 10, 16, 7)).duration, 60, "本地 7 点格") + Assert.eq(find(result.rows, "day", "__kv:day:" .. d17, d17).duration, 100, "本地 0:30 起的那条落 10-17") + Assert.eq(find(result.rows, "hour", "__kv:hour:" .. hourTs(2026, 10, 17, 0)).duration, 40, "0 点格") + Assert.eq(find(result.rows, "hour", "__kv:hour:" .. hourTs(2026, 10, 17, 23)).duration, 60, "23 点格") + Assert.is_nil(find(result.rows, "hour", "__kv:hour:" .. hourTs(2026, 10, 18, 0)), + "跨零点前的活动行不另起一天") +end + +do + -- 负页数:按天先求和再钳制。逐条钳制会让 +5 / -5 相抵的日子凭空多出 5 页。 + local d1, d2 = dayTs(2026, 10, 1), dayTs(2026, 10, 2) + local result = Stats.fromHistory({ + { seriesId = 7, localDate = "2026-10-01T00:00:00", chapters = { + { chapterId = 1, durationSeconds = 10, pagesRead = 5 } } }, + { seriesId = 7, localDate = "2026-10-01T00:00:00", chapters = { + { chapterId = 1, durationSeconds = 10, pagesRead = -5 } } }, + { seriesId = 7, localDate = "2026-10-02T00:00:00", chapters = { + { chapterId = 1, durationSeconds = 10, pagesRead = -3 }, + { chapterId = 1, durationSeconds = 10, pagesRead = -4 } } }, + }, { source_id = "kavita", fetched_at = 3000, volumes = { [7] = 2 } }) + Assert.eq(find(result.rows, "day", "__kv:day:" .. d1, d1).event_count, 0, "正负相抵为净 0") + Assert.eq(find(result.rows, "day", "__kv:day:" .. d2, d2).event_count, 0, "负和钳制到 0") + Assert.eq(find(result.rows, "day", "__kv:day:" .. d1, d1).duration, 20) + Assert.eq(find(result.rows, "day", "__kv:day:" .. d2, d2).duration, 20) +end + +do + -- 时区回退(UTC)下服务端的「日」可能晚于设备本地的拉取时刻(设备为负偏移): + -- 日桶清理窗口的上界要盖到最后观测日的日终,否则当天桶清不掉,会残留到下一轮。 + local last_day = dayTs(2026, 10, 16) + local fetched = last_day - 600 -- 设备本地 23:50,比最后观测日的零点还早 + local result = Stats.fromHistory({ + { seriesId = 21, localDate = "2026-10-16T00:00:00", + chapters = { { chapterId = 1, durationSeconds = 300, pagesRead = 1 } } }, + }, { source_id = "kavita", fetched_at = fetched, volumes = { [21] = 2 } }) + local day_range + for _idx, range in ipairs(result.replace.ranges) do + if range.stable_prefix == "__kv:day:" then day_range = range end + end + Assert.not_nil(day_range) + Assert.eq(day_range.from_ts, 0, "窗口下界仍是 0(全量重拉)") + Assert.eq(day_range.to_ts, last_day + 86399, "上界盖到最后观测日的日终") + for _idx, row in ipairs(result.rows) do + if row.record_type == "day" then + Assert.is_true(row.start_time <= day_range.to_ts, "日桶落在清理窗口内") + end + end + Assert.eq(day_range.stable_prefix:sub(1, 5), "__kv:", "范围只匹配本源的合成行,本地记录不受影响") +end + +do + -- 零时长条目整条丢弃(连页数一起):Kavita 会给「打开没读」建 0 时长会话。 + -- 本次身份照交回,好让 replace.books 清掉它上次留下的行。 + local d = dayTs(2026, 10, 3) + local before = #warnings + local result = Stats.fromHistory({ + { seriesId = 8, localDate = "2026-10-03T00:00:00", chapters = { + { chapterId = 1, durationSeconds = 0, pagesRead = 9 } } }, + { seriesId = 8, localDate = "2026-10-03T00:00:00", chapters = { + { chapterId = 1, durationSeconds = 60, pagesRead = 0 } } }, + -- 目录拿不到章数的系列判不出身份:整体跳过,不猜单卷 / 多卷 + { seriesId = 999, localDate = "2026-10-03T00:00:00", chapters = { + { chapterId = 1, durationSeconds = 100, pagesRead = 1 } } }, + }, { source_id = "kavita", fetched_at = 4000, volumes = { [8] = 2 }, seen = { "8:1" } }) + Assert.eq(find(result.rows, "book_day", "8:1", d).duration, 60) + Assert.eq(find(result.rows, "day", "__kv:day:" .. d, d).event_count, 0, "零时长条目的页数不算") + Assert.eq(find(result.rows, "total", "__kv:total", 0).duration, 60, "跳过的系列不进总量") + Assert.eq(#result.identities, 1) + Assert.contains(result.identities, "8:1") + Assert.eq(#result.replace.books, 1) + Assert.contains(result.replace.books, "8:1") + local mentioned = false + for i = before + 1, #warnings do + if warnings[i]:find("999", 1, true) then mentioned = true end + end + Assert.is_true(mentioned, "跳过的系列要能被日志定位") + + -- 空回包不炸:仍给出完整的替换指令(全量重拉窗口照旧清) + local empty = Stats.fromHistory(nil, { source_id = "kavita", fetched_at = 4000 }) + Assert.len(empty.rows, 0) + Assert.len(empty.identities, 0) + Assert.len(empty.replace.books, 0) + Assert.eq(#empty.replace.ranges, 3) +end + +do + -- seen 的重复 / 空串不进 books;并集按 stable_id 精确去重(4 / 42 互为前缀,不能用 LIKE) + local result = Stats.fromHistory({ + { seriesId = 9, localDate = "2026-10-04T00:00:00", chapters = { + { chapterId = 1, durationSeconds = 5, pagesRead = 0 } } }, + }, { source_id = "kavita", fetched_at = 5000, volumes = { [9] = 2 }, + seen = { "9:1", "", "9:1", "stale" } }) + Assert.eq(#result.replace.books, 2) + Assert.contains(result.replace.books, "9:1") + Assert.contains(result.replace.books, "stale") +end + +do + -- 时区映射全表:设备时钟的 19 项 POSIX 串 → IANA(Kavita 的 TimeZoneId) + local expected = { + ["HST10"] = "Pacific/Honolulu", + ["AKST9AKDT,M3.2.0,M11.1.0"] = "America/Anchorage", + ["PST8PDT,M3.2.0,M11.1.0"] = "America/Los_Angeles", + ["MST7MDT,M3.2.0,M11.1.0"] = "America/Denver", + ["CST6CDT,M3.2.0,M11.1.0"] = "America/Chicago", + ["EST5EDT,M3.2.0,M11.1.0"] = "America/New_York", + ["<-03>3"] = "America/Sao_Paulo", + ["UTC0"] = "UTC", + ["GMT0BST,M3.5.0/1,M10.5.0"] = "Europe/London", + ["CET-1CEST,M3.5.0,M10.5.0/3"] = "Europe/Berlin", + ["EET-2EEST,M3.5.0/3,M10.5.0/4"] = "Europe/Athens", + ["MSK-3"] = "Europe/Moscow", + ["<+04>-4"] = "Asia/Dubai", + ["IST-5:30"] = "Asia/Kolkata", + ["<+07>-7"] = "Asia/Bangkok", + ["CST-8"] = "Asia/Shanghai", + ["JST-9"] = "Asia/Tokyo", + ["AEST-10AEDT,M10.1.0,M4.1.0/3"] = "Australia/Sydney", + ["NZST-12NZDT,M9.5.0,M4.1.0/3"] = "Pacific/Auckland", + } + local n = 0 + for posix, iana in pairs(expected) do + n = n + 1 + Assert.eq(Stats.ianaTimezone(posix), iana, posix) + end + Assert.eq(n, 19) + + -- 与设置页的时区表保持同步(读源码不 require UI 依赖):时钟加项时必须同步映射 + local file = assert(io.open(Config.root() .. "/book.koplugin/features/clock/init.lua", "r")) + local source = file:read("*a") + file:close() + local in_block, covered = false, 0 + for line in source:gmatch("[^\n]+") do + if line:match("Clock%.TIMEZONES%s*=") then + in_block = true + elseif in_block then + if line:match("^}") then break end + local posix = line:match('tz%s*=%s*"([^"]*)"') + if posix and posix ~= "" then + covered = covered + 1 + Assert.not_nil(expected[posix], "时钟时区缺少 IANA 映射:" .. posix) + end + end + end + Assert.eq(covered, 19, "时钟时区表全部覆盖") + + -- 未知 / 空串(跟随系统)回退 UTC 并 warn,不做地区默认 + local before = #warnings + Assert.eq(Stats.ianaTimezone(""), "UTC") + Assert.eq(Stats.ianaTimezone("NOPE-1"), "UTC") + Assert.eq(Stats.ianaTimezone(nil), "UTC") + Assert.eq(#warnings, before + 3, "每次回退都记一条日志") +end + +do + -- 阅读会话行:每个「会话 × 章」切片的真实起始时刻 / 时长 / 页数,供详情「阅读记录」列出时段。 + -- 它只进列表,不参与日 / 时段 / 总量汇总。 + local day = dayTs(2026, 10, 10) + local result = Stats.fromHistory({ + { seriesId = 66, startTimeUtc = "2026-10-10T09:00:00.0000000", chapters = { + { chapterId = 1, durationSeconds = 600, pagesRead = 12, + startTimeUtc = "2026-10-10T09:00:00.0000000" }, + { chapterId = 2, durationSeconds = 300, pagesRead = 3, + startTimeUtc = "2026-10-10T09:20:00.0000000" }, + } }, + }, { source_id = "kavita", fetched_at = 2000, volumes = { [66] = 1 } }) + + local first = find(result.rows, "cloud_session", "66", hourTs(2026, 10, 10, 17)) + Assert.not_nil(first, "会话行按章切片的本地起始时刻落行") + Assert.eq(first.duration, 600) + Assert.eq(first.event_count, 12, "页数记在 event_count") + Assert.eq(first.last_time, 2000, "会话行 last_time = 拉取时刻") + local second = find(result.rows, "cloud_session", "66", hourTs(2026, 10, 10, 17) + 20 * 60) + Assert.not_nil(second) + Assert.eq(second.duration, 300) + Assert.eq(second.event_count, 3) + + -- 会话行不影响任何汇总桶:日桶 / 总量仍是 900,且不会多出 hour 之外的重复 + Assert.eq(find(result.rows, "day", "__kv:day:" .. day, day).duration, 900) + Assert.eq(find(result.rows, "total", "__kv:total", 0).duration, 900) + Assert.eq(find(result.rows, "book_day", "66", day).duration, 900) + + -- 零时长会话不落会话行 + local zero = Stats.fromHistory({ + { seriesId = 66, startTimeUtc = "2026-10-10T10:00:00.0000000", chapters = { + { chapterId = 1, durationSeconds = 0, pagesRead = 0, + startTimeUtc = "2026-10-10T10:00:00.0000000" }, + } }, + }, { source_id = "kavita", fetched_at = 2000, volumes = { [66] = 1 } }) + Assert.is_nil(find(zero.rows, "cloud_session", "66"), "打开没读的会话不落行") +end + +do + -- 漫画(seriesFormat 0 Image / 1 Archive)的会话行补真实页坐标:page = endPage(读到哪)、 + -- total_pages = chapter.totalPages(卷级,汇总处继续 MAX);event_count 是**本次新推进的页数** + -- (不是 pagesRead —— 重读会重复计入,见下方进度用例)。pagesRead = 0 是合法值,不是缺数据。 + local result = Stats.fromHistory({ + { seriesId = 70, seriesFormat = 0, startTimeUtc = "2026-10-10T09:00:00.0000000", chapters = { + { chapterId = 1, durationSeconds = 300, pagesRead = 12, startPage = 3, endPage = 15, + totalPages = 194, startTimeUtc = "2026-10-10T09:00:00.0000000" }, + } }, + -- Archive 同样算漫画;同一系列两卷各自的卷级总页数不同,不能被条目级 totalPages 抹平。 + { seriesId = 71, seriesFormat = 1, startTimeUtc = "2026-10-10T10:00:00.0000000", chapters = { + { chapterId = 2, durationSeconds = 60, pagesRead = 0, startPage = 1, endPage = 1, + totalPages = 40, startTimeUtc = "2026-10-10T10:00:00.0000000" }, + { chapterId = 3, durationSeconds = 90, pagesRead = 7, startPage = 20, endPage = 30, + totalPages = 52, startTimeUtc = "2026-10-10T10:30:00.0000000" }, + } }, + -- epub 的 Chapter.Pages 是 spine 数、与渲染页无关:页坐标保持 0,不因带 endPage 就填。 + { seriesId = 72, seriesFormat = 3, startTimeUtc = "2026-10-10T11:00:00.0000000", chapters = { + { chapterId = 4, durationSeconds = 600, pagesRead = 7, startPage = 15, endPage = 15, + totalPages = 22, startTimeUtc = "2026-10-10T11:00:00.0000000" }, + } }, + }, { source_id = "kavita", fetched_at = 2000, volumes = { [70] = 1, [71] = 1, [72] = 1 } }) + + local image = find(result.rows, "cloud_session", "70", hourTs(2026, 10, 10, 17)) + Assert.not_nil(image, "Image 漫画的会话行") + Assert.eq(image.page, 15, "page = chapter.endPage") + Assert.eq(image.total_pages, 194, "total_pages = chapter.totalPages") + Assert.eq(image.event_count, 15, "event_count = 本次新推进的页数(0 → 15)") + + local archive_zero = find(result.rows, "cloud_session", "71", hourTs(2026, 10, 10, 18)) + Assert.not_nil(archive_zero, "Archive 漫画的会话行") + Assert.eq(archive_zero.page, 1, "page = endPage(未翻页也合法)") + Assert.eq(archive_zero.total_pages, 40, "卷级总页数") + Assert.eq(archive_zero.event_count, 1, "推进到第 1 页即 1 页,与 pagesRead = 0 无关") + local archive_more = find(result.rows, "cloud_session", "71", hourTs(2026, 10, 10, 18) + 30 * 60) + Assert.not_nil(archive_more, "同一条目里的第二卷") + Assert.eq(archive_more.page, 30) + Assert.eq(archive_more.total_pages, 52, "逐章取自己的卷级总页数") + Assert.eq(archive_more.event_count, 29, "1 → 30 只推进 29 页(不是 pagesRead 7)") + + local epub = find(result.rows, "cloud_session", "72", hourTs(2026, 10, 10, 19)) + Assert.not_nil(epub, "epub 的会话行照旧落") + Assert.eq(epub.page, 0, "epub 不填 page") + Assert.eq(epub.total_pages, 0, "epub 不填 total_pages") + Assert.eq(epub.event_count, 7, "epub 仍用 pagesRead") + + -- 页坐标只加在会话行上:日 / 单书桶维持「云端快照没有页坐标」的语义(汇总另算)。 + local day = dayTs(2026, 10, 10) + for _idx, row in ipairs(result.rows) do + if row.record_type ~= "cloud_session" then + Assert.eq(row.page, 0, row.record_type .. " 行 page 仍为 0") + Assert.eq(row.total_pages, 0, row.record_type .. " 行 total_pages 仍为 0") + end + end + -- 当天页数 = 15(70)+ 1(71 卷 2)+ 29(71 卷 3)+ 7(epub 仍是 pagesRead) + Assert.eq(find(result.rows, "day", "__kv:day:" .. day, day).event_count, 52) + Assert.eq(find(result.rows, "book_day", "70", day).duration, 300) +end + +do + -- 漫画的已读页数按「最远进度」算,不按页次累加:pagesRead 是「这次翻了多少页」, + -- 重读会重复计入(实测 194 页的卷 6 条会话 pagesRead 合计 284,已读页数超过了总页数)。 + -- 样本:大剑 Vol.10,总 194 页;依次读到 3 → 91 → 42(重读)→ 94 → 126 → 194。 + local sessions = { + { end_page = 3, pages_read = 3 }, + { end_page = 91, pages_read = 87 }, + { end_page = 42, pages_read = 42 }, + { end_page = 94, pages_read = 48 }, + { end_page = 126, pages_read = 34 }, + { end_page = 194, pages_read = 70 }, + } + local expected = { 3, 88, 0, 3, 32, 68 } -- 每次都只是「比此前更远」的那一段;合计 194 + + local function history() + local entries = {} + for i, s in ipairs(sessions) do + -- UTC 01..06 点 → 本地(CST-8)09..14 点,同一本地的天。 + local utc = string.format("2026-10-10T%02d:00:00", i) + entries[#entries + 1] = { seriesId = 100, seriesFormat = 0, startTimeUtc = utc, chapters = { + { chapterId = 1, durationSeconds = 60, pagesRead = s.pages_read, startPage = 0, + endPage = s.end_page, totalPages = 194, startTimeUtc = utc } } } + end + return entries + end + + local day = dayTs(2026, 10, 10) + local function check(entries, label) + local result = Stats.fromHistory(entries, + { source_id = "kavita", fetched_at = 2000, volumes = { [100] = 1 } }) + local sum = 0 + local session_rows = 0 + for _idx, row in ipairs(result.rows) do + if row.record_type == "cloud_session" and row.stable_id == "100" then + session_rows = session_rows + 1 + end + end + Assert.eq(session_rows, #sessions, label .. ":每条有时长的会话各落一行,不多不少") + for i, want in ipairs(expected) do + local row = find(result.rows, "cloud_session", "100", hourTs(2026, 10, 10, 8 + i)) + Assert.not_nil(row, label .. ":第 " .. i .. " 条会话行") + Assert.eq(row.event_count, want, label .. ":第 " .. i .. " 条只算新推进的页数") + -- 重读(第 3 条 endPage 42 < 已到达 91)页数为 0,但 page 仍如实记 42。 + Assert.eq(row.page, sessions[i].end_page, label .. ":第 " .. i .. " 条 page 仍记 endPage") + Assert.eq(row.total_pages, 194, label .. ":第 " .. i .. " 条卷级总页数") + sum = sum + row.event_count + end + Assert.eq(sum, 194, label .. ":合计 = 读到的最远页码 = 总页数") + Assert.eq(find(result.rows, "day", "__kv:day:" .. day, day).event_count, 194, + label .. ":当天页数也是进度而不是页次") + end + + check(history(), "正序") + -- 回包可能是新→旧:按章起始时刻排序,结果不受遍历顺序影响。 + local reversed = {} + local forward = history() + for i = #forward, 1, -1 do reversed[#reversed + 1] = forward[i] end + check(reversed, "倒序") +end + +do + -- durationSeconds = 0 但有推进的章行照样发行:Kavita 的会话是「两次进度写入之间」, + -- 只写一次就是 0 秒,可推进的页数是真的(详情页「已读页数 / 上次阅读」靠它)。 + -- 它同时要参与进度序列与当天页数,否则这段跳读会从当天页面消失、 + -- 而后续会话又因为 reached 更高而少算,合计就对不上读到的最远页码。 + local d = dayTs(2026, 10, 11) + local result = Stats.fromHistory({ + { seriesId = 101, seriesFormat = 0, startTimeUtc = "2026-10-11T02:00:00", chapters = { + { chapterId = 1, durationSeconds = 0, pagesRead = 20, startPage = 5, endPage = 60, + totalPages = 100, startTimeUtc = "2026-10-11T02:00:00" } } }, + { seriesId = 101, seriesFormat = 0, startTimeUtc = "2026-10-11T03:00:00", chapters = { + { chapterId = 1, durationSeconds = 120, pagesRead = 5, startPage = 60, endPage = 70, + totalPages = 100, startTimeUtc = "2026-10-11T03:00:00" } } }, + }, { source_id = "kavita", fetched_at = 2000, volumes = { [101] = 1 } }) + + local jump = find(result.rows, "cloud_session", "101", hourTs(2026, 10, 11, 10)) + Assert.not_nil(jump, "零时长但有推进的章行也发行(页数是真推进)") + Assert.eq(jump.duration, 0) + Assert.eq(jump.event_count, 60) + local read = find(result.rows, "cloud_session", "101", hourTs(2026, 10, 11, 11)) + Assert.not_nil(read) + Assert.eq(read.event_count, 10, "跳读已把进度推到 60,本次只推进 10 页") + Assert.eq(read.page, 70) + Assert.eq(find(result.rows, "day", "__kv:day:" .. d, d).event_count, 70, + "当天页数 = 最远页码(含零时长跳读推进的 60)") + + -- 登记身份用于清孤儿行:零时长条目照旧算见过(它上次可能留下过行)。 + Assert.contains(result.identities, "101") +end + +do + -- endPage 超过总页数(不同版本页数不一致)时钳到总页数:已读页数不可能超过总页数。 + local d = dayTs(2026, 10, 12) + local result = Stats.fromHistory({ + { seriesId = 102, seriesFormat = 1, startTimeUtc = "2026-10-12T02:00:00", chapters = { + { chapterId = 1, durationSeconds = 60, pagesRead = 40, startPage = 0, endPage = 250, + totalPages = 194, startTimeUtc = "2026-10-12T02:00:00" } } }, + }, { source_id = "kavita", fetched_at = 2000, volumes = { [102] = 1 } }) + local row = find(result.rows, "cloud_session", "102", hourTs(2026, 10, 12, 10)) + Assert.not_nil(row) + Assert.eq(row.event_count, 194, "推进钳到总页数") + Assert.eq(row.total_pages, 194) + Assert.eq(find(result.rows, "day", "__kv:day:" .. d, d).event_count, 194, "当天页数也被钳") + + -- 拿不到总页数(totalPages = 0 / 缺字段)时不假设上界:按 endPage 原样算。 + local unknown = Stats.fromHistory({ + { seriesId = 103, seriesFormat = 0, startTimeUtc = "2026-10-12T05:00:00", chapters = { + { chapterId = 1, durationSeconds = 60, pagesRead = 9, endPage = 77, + startTimeUtc = "2026-10-12T05:00:00" } } }, + }, { source_id = "kavita", fetched_at = 2000, volumes = { [103] = 1 } }) + local no_total = find(unknown.rows, "cloud_session", "103", hourTs(2026, 10, 12, 13)) + Assert.not_nil(no_total) + Assert.eq(no_total.event_count, 77, "缺总页数就照 endPage 算") + Assert.eq(no_total.total_pages, 0) +end + +do + -- 多卷:每卷(stable_id = seriesId:chapterId)各自从 0 起算进度,互不影响; + -- 合计 = 各卷进度之和(≤ 各卷总页数之和)。 + local d = dayTs(2026, 10, 13) + local result = Stats.fromHistory({ + { seriesId = 80, seriesFormat = 0, startTimeUtc = "2026-10-13T02:00:00", chapters = { + { chapterId = 1, durationSeconds = 60, pagesRead = 10, endPage = 10, totalPages = 40, + startTimeUtc = "2026-10-13T02:00:00" } } }, + { seriesId = 80, seriesFormat = 0, startTimeUtc = "2026-10-13T03:00:00", chapters = { + { chapterId = 1, durationSeconds = 60, pagesRead = 20, endPage = 30, totalPages = 40, + startTimeUtc = "2026-10-13T03:00:00" } } }, + { seriesId = 80, seriesFormat = 0, startTimeUtc = "2026-10-13T04:00:00", chapters = { + { chapterId = 2, durationSeconds = 60, pagesRead = 5, endPage = 5, totalPages = 60, + startTimeUtc = "2026-10-13T04:00:00" } } }, + { seriesId = 80, seriesFormat = 0, startTimeUtc = "2026-10-13T05:00:00", chapters = { + { chapterId = 2, durationSeconds = 60, pagesRead = 45, endPage = 50, totalPages = 60, + startTimeUtc = "2026-10-13T05:00:00" } } }, + }, { source_id = "kavita", fetched_at = 2000, volumes = { [80] = 2 } }) + + Assert.eq(find(result.rows, "cloud_session", "80:1", hourTs(2026, 10, 13, 10)).event_count, 10) + Assert.eq(find(result.rows, "cloud_session", "80:1", hourTs(2026, 10, 13, 11)).event_count, 20) + Assert.eq(find(result.rows, "cloud_session", "80:2", hourTs(2026, 10, 13, 12)).event_count, 5) + Assert.eq(find(result.rows, "cloud_session", "80:2", hourTs(2026, 10, 13, 13)).event_count, 45) + Assert.eq(find(result.rows, "day", "__kv:day:" .. d, d).event_count, 80, "10 + 20 + 5 + 45") + Assert.eq(find(result.rows, "cloud_session", "80:1", hourTs(2026, 10, 13, 10)).total_pages, 40) + Assert.eq(find(result.rows, "cloud_session", "80:2", hourTs(2026, 10, 13, 13)).total_pages, 60) +end + +do + -- epub / PDF 不受进度口径影响:pagesRead 照旧累加(重读同一页也算,这是「翻页数」语义), + -- 页坐标仍为 0。 + local d = dayTs(2026, 10, 14) + local result = Stats.fromHistory({ + { seriesId = 202, seriesFormat = 3, startTimeUtc = "2026-10-14T02:00:00", chapters = { + { chapterId = 1, durationSeconds = 60, pagesRead = 7, startPage = 15, endPage = 15, + totalPages = 22, startTimeUtc = "2026-10-14T02:00:00" } } }, + { seriesId = 202, seriesFormat = 3, startTimeUtc = "2026-10-14T03:00:00", chapters = { + { chapterId = 1, durationSeconds = 60, pagesRead = 7, startPage = 15, endPage = 15, + totalPages = 22, startTimeUtc = "2026-10-14T03:00:00" } } }, + -- PDF(4)同样不是渲染页,口径与 epub 一致。 + { seriesId = 203, seriesFormat = 4, startTimeUtc = "2026-10-14T04:00:00", chapters = { + { chapterId = 1, durationSeconds = 60, pagesRead = 4, endPage = 99, + totalPages = 120, startTimeUtc = "2026-10-14T04:00:00" } } }, + }, { source_id = "kavita", fetched_at = 2000, volumes = { [202] = 1, [203] = 1 } }) + + local first = find(result.rows, "cloud_session", "202", hourTs(2026, 10, 14, 10)) + local again = find(result.rows, "cloud_session", "202", hourTs(2026, 10, 14, 11)) + Assert.eq(first.event_count, 7, "epub 仍是 pagesRead") + Assert.eq(again.event_count, 7, "epub 重读不折成 0(不是进度口径)") + Assert.eq(first.page, 0) + Assert.eq(first.total_pages, 0) + local pdf = find(result.rows, "cloud_session", "203", hourTs(2026, 10, 14, 12)) + Assert.eq(pdf.event_count, 4, "PDF 仍是 pagesRead") + Assert.eq(pdf.page, 0) + Assert.eq(pdf.total_pages, 0) + Assert.eq(find(result.rows, "day", "__kv:day:" .. d, d).event_count, 18, "7 + 7 + 4") +end diff --git a/tests/kavita/tasks_e2e_spec.lua b/tests/kavita/tasks_e2e_spec.lua new file mode 100644 index 0000000..00ba240 --- /dev/null +++ b/tests/kavita/tasks_e2e_spec.lua @@ -0,0 +1,282 @@ +--[[-- +端到端:卷列表里「缓存整部」→ 真实缓存适配层 → 真实后台任务队列 → 顶栏读到的任务 → 收尾提示。 + +用假的 kamare 模块(真缓存适配层 + 真队列 + 真卷列表 + 真轮询),只把「下载」外包出去, +其余全走产品代码:这是跨仓 E2E 在离线环境里能做到的最大范围(模拟器 / 真机另做手工冒烟)。 + +@module tests.moonsource_kavita.tasks_e2e_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, inject-field, redundant-parameter + +local Assert = require("support.assert") +local Config = require("support.config") +local Kit = require("support.widget_stubs") +Kit.install("paper") +local Themed = require("support.theme_stubs") +Themed.install() +-- 真实的卷列表与二级菜单:Themed 的 list 桩会把 item.widget 丢掉,也就点不了行。 +package.preload["ui.themes.widgets.list"] = nil +package.loaded["ui.themes.widgets.list"] = nil + +local PLUGIN = (debug.getinfo(1, "S").source:match("^@(.-)/tests/") .. "/moonsource-kavita.koplugin/moonsource_kavita") + +-- 源配置:真 cache.lua 只读 base_url / api_key;其余键仍走 Kit 的主题设置桩。 +local cfg = { base_url = "http://kavita.local", api_key = "key" } +package.preload["utils.settings"] = function() + return { + get = function(owner) + local name = owner:match("[^.]+$") + if name == "ui" then return Kit.display end + return Kit.sections[name] + end, + getSource = function() return cfg end, + saveSource = function() end, + } +end +package.preload["utils.log"] = function() + return { info = function() end, warn = function() end, err = function() end, dbg = function() end } +end +package.preload["ui/network/manager"] = function() + return { isConnected = function() return true end } +end +package.preload["ui.guard"] = function() + return { + call = function(_label, fn, ...) return fn(...) end, + wrap = function(_label, fn) return fn end, + } +end + +-- 假 kamare:队列与章状态都在内存里,由用例推进。 +local statuses, queue = {}, {} +--- 重置假 kamare 的队列与章状态。 +local function resetKamare() + statuses, queue = {}, {} + queue = { state = "idle", entries = {} } +end +local kamare = { + api_version = 1, + capabilities = { + status = true, resume_page = true, queue = true, queue_control = true, + index = true, enqueue = true, delete = true, estimate = true, server = true, + }, +} +function kamare.register_server() return "server-key" end +function kamare.status(_base_url, chapter_id) return statuses[tostring(chapter_id)] end +function kamare.queue_state() return queue end +function kamare.estimate(_base_url, entries) + return { ok = true, chapters = #entries, bytes = #entries * 1024 * 1024, + available = 4096 * 1024 * 1024 } +end +function kamare.enqueue(_base_url, entries) + for _idx, entry in ipairs(entries) do + queue.entries[tostring(entry.chapterId)] = { chapterId = entry.chapterId, state = "queued" } + end + queue.state = "downloading" + return true, nil, { chapters = #entries } +end +package.loaded["kamarecache"] = kamare + +--- kamare 开始下某一卷。 +local function startChapter(id) + queue.entries[tostring(id)] = { chapterId = id, state = "downloading" } + queue.current_chapter_id = id + queue.state = "downloading" +end + +--- kamare 下完某一卷:章状态变 complete,队列项消失。 +local function finishChapter(id) + statuses[tostring(id)] = { state = "complete", bytes = 1024 * 1024 } + queue.entries[tostring(id)] = nil + queue.current_chapter_id = nil + if next(queue.entries) == nil then queue.state = "idle" end +end + +package.preload["moonsource_kavita.cache"] = function() + return dofile(PLUGIN .. "/cache.lua") +end +package.preload["moonsource_kavita.cache_task"] = function() + return dofile(PLUGIN .. "/cache_task.lua") +end +package.preload["moonsource_kavita.volume_list"] = function() + return dofile(PLUGIN .. "/volume_list.lua") +end + +local Cache = require("moonsource_kavita.cache") +local Tasks = require("workers.tasks") +local VolumeList = require("moonsource_kavita.volume_list") + +local series = { stable_id = "900", title = "测试系列" } +local function entry(id, title, pages_read) + return { chapterId = id, volumeId = id, seriesId = 900, libraryId = 1, format = 1, + title = title, pages = 100, pagesRead = pages_read or 0 } +end +local toc = { entry(601, "第 1 卷", 100), entry(602, "第 2 卷", 40), entry(603, "第 3 卷", 0) } + +--- Kit 的 unschedule 只记录、不从已排列表里删;真实 UIManager 会删,这里按记录过滤。 +---@param item table +---@return boolean +local function alive(item) + for _idx, fn in ipairs(Kit.unscheduled) do + if fn == item.fn then return false end + end + return true +end + +--- 结清队列的变更拍(pause_auto_suspend)。 +local function changes() + while true do + local fired = false + for index, item in ipairs(Kit.scheduled) do + if item.delay < 1 and alive(item) then + table.remove(Kit.scheduled, index) + item.fn() + fired = true + break + end + end + if not fired then return end + end +end + +--- 跑一拍所有 1 秒以上的定时器(页面轮询 + 后台任务轮询各一拍)。 +local function round() + local now, rest = {}, {} + for _idx, item in ipairs(Kit.scheduled) do + if item.delay >= 1 and alive(item) then now[#now + 1] = item else rest[#rest + 1] = item end + end + Kit.scheduled = rest + for _idx, item in ipairs(now) do item.fn() end +end + +--- 顶栏「后台任务」的读数(与 desktop/topbar 同一口径:running / 未结束总数)。 +local function topbarText() + local list = Tasks.tasks() + if #list == 0 then return "空闲" end + local running = 0 + for _idx, task in ipairs(list) do + if task.state == "running" then running = running + 1 end + end + return running .. "/" .. #list +end + +---@param list table +---@param widget table +local function tap(list, widget) + local size = widget.dimen + local ges = Kit.tap(size.x + math.floor(size.w / 2), size.y + math.floor(size.h / 2)) + ges.ges = "tap" + list:handleEvent(require("ui/event"):new("Gesture", ges)) +end + +--- 打开卷列表并走「缓存整部」(菜单第一项)。第 1 卷已缓存,本批只下 2 卷。 +local function openAndCacheAll() + statuses["601"] = { state = "complete", bytes = 1024 } + local list = assert(VolumeList.pick(series, toc, function() end)) + list:show() + list:paintTo(Kit.canvas(), 0, 0) + list.left_callback() + local menu = Kit.shown[#Kit.shown] + menu:paintTo(Kit.canvas(), 0, 0) + local rows = Kit.taps(menu) + Assert.is_true(#rows >= 1, "有「缓存整部」") + tap(menu, rows[1]) + local confirm = Themed.last("confirm") + Assert.not_nil(confirm, "确认框") + confirm.ok_callback() + return list +end + +local function cleanup() + for _idx, item in ipairs(Tasks.tasks()) do + local live = Tasks.get(item.key) + if live then live.cancel() end + end + changes() + Kit.scheduled, Kit.unscheduled = {}, {} + Themed.made = {} + Cache.reset() + resetKamare() +end + +-- 页面开着:入队 → 顶栏看得到 → 进度跟着 kamare 走 → 页面自己的进度框收尾(只提示一次)。 +do + cleanup() + local list = openAndCacheAll() + + local tracked = Tasks.tasks() + Assert.len(tracked, 1, "缓存进了后台任务队列") + Assert.eq(tracked[1].kind, "cache") + Assert.eq(tracked[1].title, "测试系列") + Assert.eq(topbarText(), "1/1", "顶栏读到「1/1」") + changes() + Assert.is_true(require("pluginshare").pause_auto_suspend, "缓存期间不自动休眠") + + startChapter(602) + round() + Assert.eq(Tasks.tasks()[1].text, "第 2 卷", "任务说明行跟 kamare 的当前卷") + Assert.eq(Tasks.tasks()[1].total, 2, "只数本批(601 已缓存)") + + finishChapter(602) + startChapter(603) + round() + Assert.eq(Tasks.tasks()[1].count, 1, "下完一卷进度 +1") + + finishChapter(603) + round() + Assert.len(Tasks.tasks(), 0, "全部落地后离开队列") + Assert.eq(topbarText(), "空闲") + changes() + Assert.is_false(require("pluginshare").pause_auto_suspend, "结束放行自动休眠") + local toasts = Themed.all("toast") + Assert.eq(#toasts, 1, "页面进度框收尾,只提示一次") + Assert.eq(toasts[1].text, "已缓存 2 卷") + list:close() +end + +-- 页面提前关掉:后台任务继续跑,完成时由任务提示(不再有页面轮询)。 +do + cleanup() + local list = openAndCacheAll() + startChapter(602) + round() + list:close() + Assert.is_true(#Kit.unscheduled > 0, "关页撤掉页面轮询") + + finishChapter(602) + startChapter(603) + round() + Assert.eq(Tasks.tasks()[1].count, 1, "关页后任务仍在推进") + + finishChapter(603) + round() + Assert.len(Tasks.tasks(), 0) + local toasts = Themed.all("toast") + Assert.eq(#toasts, 1, "关页后由任务报完成") + Assert.eq(toasts[1].text, "已缓存 2 卷") + Assert.eq(topbarText(), "空闲") +end + +-- 队列因空间不足暂停:任务留在列表里、报暂停原因、不再压制自动休眠;恢复后继续。 +do + cleanup() + local list = openAndCacheAll() + startChapter(602) + round() + queue.state = "paused" + queue.pause_reason = "low_space" + round() + Assert.eq(Tasks.tasks()[1].text, "空间不足,已暂停") + changes() + Assert.is_false(require("pluginshare").pause_auto_suspend, "暂停时允许自动休眠") + + queue.state = "downloading" + queue.pause_reason = nil + round() + changes() + Assert.is_true(require("pluginshare").pause_auto_suspend, "恢复后继续撑住") + finishChapter(602) + finishChapter(603) + round() + Assert.len(Tasks.tasks(), 0, "恢复后照常收尾") + list:close() +end diff --git a/tests/kavita/volume_list_spec.lua b/tests/kavita/volume_list_spec.lua new file mode 100644 index 0000000..53845f9 --- /dev/null +++ b/tests/kavita/volume_list_spec.lua @@ -0,0 +1,1213 @@ +--[[-- +Kavita 卷列表:真实 list 的行尾控件命中(04 A9)、状态字优先级、批量预设 +(整部 / 从当前进度 / 后 N 卷,默认 3)、删除保护、暂停 / 恢复与进度框收尾。 + +真实 list 与 Kit 一起用:A9 的「点图标不关窗」只能靠真行 / 真按钮的事件顺序证明。 +Themed 只负责记录弹窗参数;装完把它的 list 桩摘掉,require 真组件。 + +@module tests.moonsource_kavita.volume_list_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, inject-field + +local Assert = require("support.assert") +local Config = require("support.config") +local Kit = require("support.widget_stubs") +Kit.install("paper") + +local Themed = require("support.theme_stubs") +Themed.install() +-- 真实的 list:Themed 的桩会把 item.widget 丢掉,A9 就无从验证。 +package.preload["ui.themes.widgets.list"] = nil +package.loaded["ui.themes.widgets.list"] = nil + +-- 缓存层另有 cache_spec;这里只关心 UI 传了什么、显示了什么。 +package.loaded["utils.log"] = { + info = function() end, warn = function() end, err = function() end, dbg = function() end, +} +local offline = false +local local_progress = {} +local progress_list_calls = 0 +package.loaded["ui/network/manager"] = { isConnected = function() return not offline end } +-- 本地卷进度(ProgressDB):卷行在阅读器关闭时写回,比 toc 快照新。 +package.loaded["book.progress_db"] = { + get = function(_source_id, stable_id) return local_progress[stable_id] end, + list = function(_source_id, series_id) + progress_list_calls = progress_list_calls + 1 + local out = {} + local prefix = tostring(series_id) .. ":" + for stable, row in pairs(local_progress) do + if stable:sub(1, #prefix) == prefix then out[stable] = row end + end + return out + end, +} +package.loaded["source.registry"] = { + resolve = function() + return { coverRequest = function() end } + end, +} + +local PLUGIN = (debug.getinfo(1, "S").source:match("^@(.-)/tests/") .. "/moonsource-kavita.koplugin/moonsource_kavita") +local RealCache = dofile(PLUGIN .. "/cache.lua") + +local st, calls = {}, {} +--- 后台任务句柄的记录(stub 与 reset 共用同一个 upvalue)。 +local tracked = {} +local function reset(overrides) + calls = { enqueue = {}, delete = {}, retry = {}, pause = 0, resume = 0, resume_page = 0, chapters = 0 } + local_progress = {} + progress_list_calls = 0 + tracked = {} + st.probe = { ok = true, state = "enhanced", capabilities = { + status = true, queue = true, queue_control = true, + enqueue = true, delete = true, estimate = true, + } } + st.queue = { state = "idle", entries = {}, percent = 0, bytes_done = 0, bytes_total = 0 } + st.queue_code = nil + st.statuses, st.resumes = {}, {} + st.plan = nil + st.open_chapter = nil + st.estimate = { chapters = 1, bytes = 100 * 1024 * 1024, available = 2000 * 1024 * 1024, ok = true } + st.enqueue_ok, st.enqueue_code, st.enqueue_message, st.enqueue_detail = true, nil, nil, nil + st.delete_ok, st.delete_code, st.delete_message = true, nil, nil + st.pause_ok, st.resume_ok, st.retry_ok = true, true, true + st.pause_reason = "user" + st.retry_code = nil + st.pause_code = nil + st.resume_code = nil + offline = false + for key, value in pairs(overrides or {}) do st[key] = value end +end + +local Cache = setmetatable({}, { __index = RealCache }) +function Cache.probe() return st.probe end +function Cache.queueState() return st.queue, st.queue_code end +function Cache.status(chapter_id) return st.statuses[tostring(chapter_id)] end +function Cache.resumePage(chapter_id) + calls.resume_page = calls.resume_page + 1 + return st.resumes[tostring(chapter_id)] +end +function Cache.isChapterOpen(chapter_id) + return st.open_chapter ~= nil and tostring(st.open_chapter) == tostring(chapter_id) +end +function Cache.estimate(entries) + calls.estimate = entries + return st.estimate +end +function Cache.enqueue(entries) + calls.enqueue[#calls.enqueue + 1] = entries + if st.enqueue_ok then return true end + return nil, st.enqueue_code, st.enqueue_message, st.enqueue_detail +end +function Cache.delete(ids) + calls.delete[#calls.delete + 1] = ids + if st.delete_ok then + -- 真 kamare 删完 index 里就没有这一章了:刷新后行要变回「未缓存 / 已读」。 + local wanted = {} + for _idx, id in ipairs(ids) do + wanted[tostring(id)] = true + st.statuses[tostring(id)] = nil + end + if st.plan then + local kept = {} + for _idx, item in ipairs(st.plan) do + if not wanted[tostring(item.chapterId)] then kept[#kept + 1] = item end + end + st.plan = kept + end + + return true + end + return nil, st.delete_code, st.delete_message +end +function Cache.chapters(series_id) + calls.chapters = calls.chapters + 1 + calls.chapters_series = series_id + return st.plan +end +function Cache.queuePause() + calls.pause = calls.pause + 1 + if st.pause_ok then + st.queue.state = "paused" + st.queue.pause_reason = st.pause_reason or "user" + end + return st.pause_ok, st.pause_code +end +function Cache.queueResume() + calls.resume = calls.resume + 1 + if st.resume_ok then + st.queue.pause_reason = nil + st.queue.state = "idle" + end + return st.resume_ok, st.resume_code +end +function Cache.queueRetry(ids) + calls.retry[#calls.retry + 1] = ids + return st.retry_ok, st.retry_code +end +package.preload["moonsource_kavita.cache"] = function() return Cache end +-- 后台任务登记:这里只记调用与静音状态;真实轮询见 cache_task_spec 与 tasks_e2e_spec。 +package.preload["moonsource_kavita.cache_task"] = function() + local CacheTask = dofile(PLUGIN .. "/cache_task.lua") + CacheTask.track = function(opts) + local handle = { opts = opts, adds = {} } + handle.mute = function(value) handle.muted = value ~= false end + handle.add = function(entries) handle.adds[#handle.adds + 1] = entries end + tracked[#tracked + 1] = handle + return handle + end + return CacheTask +end +package.preload["moonsource_kavita.volume_list"] = function() + return dofile(PLUGIN .. "/volume_list.lua") +end +package.preload["moonsource_kavita.busy"] = function() + return dofile(PLUGIN .. "/busy.lua") +end + +local VolumeList = require("moonsource_kavita.volume_list") + +---@param id integer +---@param title string +---@param pages integer +---@param read integer +---@return table +local function entry(id, title, pages, read) + return { chapterId = id, volumeId = id, seriesId = 900, libraryId = 1, format = 1, + title = title, pages = pages, pagesRead = read or 0 } +end + +local toc = { + entry(601, "第 1 卷", 100, 100), + entry(602, "第 2 卷", 100, 40), + entry(603, "第 3 卷", 100, 0), +} +local series = { source_id = "kavita", stable_id = "900", title = "测试系列" } + +--- 子串断言:Assert.contains 只认数组,文案用这个。 +---@param haystack string +---@param needle string +---@param msg string|nil +local function textContains(haystack, needle, msg) + Assert.is_true(type(haystack) == "string" and haystack:find(needle, 1, true) ~= nil, + (msg or "text") .. ":" .. needle .. " 不在 " .. tostring(haystack)) +end + +--- 打开卷列表;返回 list、选中回调的接收表。 +---@param volumes table[]|nil 缺省用共享的 toc(全读退化等用例换一份目录) +---@return table, table +local function open(volumes, opts) + local picked = {} + local list = assert(VolumeList.pick(series, volumes or toc, + function(value) picked.value = value end, opts)) + list:show() + list:paintTo(Kit.canvas(), 0, 0) + return list, picked +end + +--- 所有行尾按钮(排除标题栏的 left / close)。 +---@param list table +---@return table[] +local function tails(list) + local first = Kit.taps(list)[1] + local top = first and first.dimen.y or 0 + local out = {} + for _idx, button in ipairs(Kit.buttons(list)) do + if button.dimen.y >= top + and (button.icon == "download" or button.icon == "delete" or button.icon == "refresh" + or button.icon == "pause" or button.icon == "play_arrow") then + out[#out + 1] = button + end + end + return out +end + +--- 按 04 A9 的路径点一个控件:坐标落在按钮上,事件从窗口一路下发。 +---@param list table +---@param widget table +local function tap(list, widget) + local size = widget.dimen + local ges = Kit.tap(size.x + math.floor(size.w / 2), size.y + math.floor(size.h / 2)) + ges.ges = "tap" + list:handleEvent(require("ui/event"):new("Gesture", ges)) +end + +--- 按行标题找控件:续读卡也在控件树里,固定下标会被它挤偏。 +---@param list table +---@param title string +---@return table|nil +local function findRow(list, title) + for _idx, w in ipairs(Kit.taps(list)) do + if w.row_title == title then return w end + end +end + +--- 按行标题点按。 +---@param list table +---@param title string +local function tapRow(list, title) + local row = findRow(list, title) + if not row then error("row not found: " .. tostring(title)) end + tap(list, row) +end + + +--- 这个窗口被 UIManager 关过吗(真实组件不写 `.closed`,只能看桩的关闭记录)。 +---@param widget table +---@return boolean +local function wasClosed(widget) + for _idx, w in ipairs(Kit.closed) do + if w == widget then return true end + end + return false +end + +--- 标题栏左钮 → 二级菜单;返回菜单控件(真实 list,与卷列表分开的窗口)。 +---@param list table +---@return table +local function openMenu(list) + local before = #Kit.shown + list.left_callback() + Assert.is_true(#Kit.shown > before, "左钮弹二级菜单") + local menu = Kit.shown[#Kit.shown] + Assert.is_true(menu ~= list, "菜单不是卷列表本身") + menu:paintTo(Kit.canvas(), 0, 0) + return menu +end + +--- 菜单第 index 项;越界即断言失败。 +---@param menu table +---@param index integer +local function chooseMenu(menu, index) + local rows = Kit.taps(menu) + Assert.is_true(#rows >= index, "菜单有第 " .. index .. " 项") + tap(menu, rows[index]) +end + +--- 标题栏左钮 → 「缓存整部」(菜单第一项)。 +---@param list table +local function batchAll(list) + chooseMenu(openMenu(list), 1) +end + +--- 入队对象的章 id,逗号拼接:断言「选了哪几卷」。 +---@param entries table[]|nil +---@return string +local function idsText(entries) + local out = {} + for _idx, entry in ipairs(entries or {}) do out[#out + 1] = entry.chapterId end + return table.concat(out, ",") +end + +-- A9:点行尾按钮被按钮吃掉,不关窗、不选中,只弹该卷的确认框。 +reset() +st.statuses["601"] = { state = "complete", bytes = 80 * 1024 * 1024 } +local list, picked = open() +local delete_buttons = {} +for _idx, button in ipairs(tails(list)) do + if button.icon == "delete" then delete_buttons[#delete_buttons + 1] = button end +end +Assert.len(delete_buttons, 1, "只有已缓存的第 1 卷有删除按钮") +local closed_before = #Kit.closed +tap(list, delete_buttons[1]) +Assert.eq(#Kit.closed, closed_before, "点行尾按钮不关窗") +Assert.is_nil(picked.value, "点行尾按钮不触发行选中") +local confirm = Themed.last("confirm") +Assert.not_nil(confirm, "删除走确认框") +textContains(confirm.text, "将释放") +textContains(confirm.text, "离线不可读") +Assert.eq(confirm.title, "删除缓存") +confirm.ok_callback() +Assert.eq(calls.delete[1][1], 601, "只删这一卷") + +-- 行状态字:已读 · 已缓存 / 在读 / 未缓存;图标各归各位。 +st.statuses["601"] = { state = "complete", bytes = 80 * 1024 * 1024 } +st.resumes["602"] = { page = 41, status = "pending" } +list, picked = open() +local text = table.concat(Kit.texts(list), "\n") +textContains(text, "已读 · 已缓存") +textContains(text, "在读 · 待同步") +textContains(text, "未缓存") +local icons = {} +for _idx, button in ipairs(tails(list)) do icons[#icons + 1] = button.icon end +Assert.eq(table.concat(icons, ","), "delete,download,download") + +-- 点标题区域仍然是选中(关窗后回调)。 +tapRow(list, "第 2 卷") +Assert.eq(picked.value and picked.value.chapterId, 602) + +reset() +st.statuses["601"] = { state = "stale", bytes = 1 } +st.statuses["602"] = { state = "complete", bytes = 1 } +st.statuses["603"] = { state = "complete", bytes = 1 } +list = open() +text = table.concat(Kit.texts(list), "\n") +textContains(text, "已读 · 已缓存") +textContains(text, "在读 · 已缓存") +textContains(text, "已缓存") +Assert.eq(#tails(list), 3) + +-- 打开列表时队列已经在跑(不是本页发起的批次):也要排拍刷新, +-- 不能停在打开那一瞬的「下载中 32%」。 +reset() +Kit.scheduled = {} +st.queue = { state = "downloading", entries = { [602] = { chapterId = 602, state = "downloading", + bytes_done = 32, bytes_total = 100 } }, bytes_done = 32, bytes_total = 100 } +list = open() +textContains(table.concat(Kit.texts(list), "\n"), "下载中 32%", "打开时看到的是队列快照") +local poll +for index, item in ipairs(Kit.scheduled) do + if item.delay == 1 then poll = item; table.remove(Kit.scheduled, index); break end +end +Assert.not_nil(poll, "队列在跑时打开列表也要排 1 秒轮询") +st.queue = { state = "idle", entries = {} } +st.statuses["602"] = { state = "complete", bytes = 1 } +poll.fn() +textContains(table.concat(Kit.texts(list), "\n"), "在读 · 已缓存", "收尾后行就地刷新") +local repoll = false +for _idx, item in ipairs(Kit.scheduled) do if item.delay == 1 then repoll = true end end +Assert.is_false(repoll, "队列停了就不再多排拍") + +-- 标题栏左钮=批量预设菜单(04 A9 的 C 变体):整部 / 未读 / 后 N 卷。 +-- 菜单是独立的 list 窗口,点菜单行不会被当成选卷;「缓存整部」仍然只选未缓存 +-- (跳过已缓存 / 排队中),先 estimate 再确认。 +reset() +st.statuses["601"] = { state = "complete", bytes = 1 } +st.queue = { state = "downloading", entries = { [603] = { chapterId = 603, state = "downloading", + bytes_done = 50, bytes_total = 100 } }, bytes_done = 50, bytes_total = 100 } +st.estimate = { chapters = 1, bytes = 120 * 1024 * 1024, available = 2000 * 1024 * 1024, ok = true } +list, picked = open() +local title = Kit.buttons(list)[1] +Assert.eq(title.icon, "download", "标题栏左钮是下载图标") +Assert.is_true(title.dimen.y < Kit.taps(list)[1].dimen.y, "左钮在标题栏里,不是行尾") +local menu = openMenu(list) +local menu_items = {} +for _idx, item in ipairs(menu.items) do menu_items[#menu_items + 1] = item.text end +Assert.eq(menu.title, "批量操作", "菜单标题") +Assert.eq(table.concat(menu_items, "|"), "缓存整部|缓存未读|缓存后 N 卷…", "菜单三项与顺序") +Assert.is_nil(picked.value, "开菜单不选卷") +chooseMenu(menu, 1) +Assert.is_true(wasClosed(menu), "选完关菜单") +Assert.is_false(wasClosed(list), "点菜单不关卷列表") +Assert.is_nil(picked.value, "点菜单行不选卷") +Assert.len(calls.estimate, 1, "先估算") +Assert.eq(calls.estimate[1].chapterId, 602, "只估算未缓存的第 2 卷") +confirm = Themed.last("confirm") +Assert.not_nil(confirm, "估算通过后弹确认框") +Assert.eq(confirm.title, "缓存这一卷") +textContains(confirm.text, "第 2 卷") +textContains(confirm.text, "预计占用 120.0 MB(峰值)") +textContains(confirm.text, "设备可用 2000.0 MB") +textContains(confirm.text, "完成后剩余 1880.0 MB") +Assert.eq(confirm.ok_text, "开始缓存") +confirm.ok_callback() +Assert.len(calls.enqueue, 1) +Assert.eq(calls.enqueue[1][1].chapterId, 602) +local progress = Themed.last("progress_dialog") +Assert.not_nil(progress, "入队后开进度框") +Assert.eq(progress.title, "正在缓存") +Assert.eq(progress.cancel_text, "暂停", "按钮是暂停,不是取消") +Assert.not_nil(progress.on_cancel) +Assert.not_nil(progress.on_background, "后台运行") +Assert.is_true(#calls.retry == 0, "没有失败项就不调 queue_retry") + +-- 预设「缓存未读」:没读完的卷都算(含正在读的一卷),已读跳过; +-- 已缓存 / 已排队照旧跳过,也不逐卷调 resume_page。 +local preset_toc = { + entry(701, "第 1 卷", 100, 100), + entry(702, "第 2 卷", 100, 40), + entry(703, "第 3 卷", 100, 0), + entry(704, "第 4 卷", 100, 0), +} +reset() +st.statuses["703"] = { state = "complete", bytes = 1 } +st.queue = { state = "downloading", entries = { [704] = { chapterId = 704, state = "downloading", + bytes_done = 10, bytes_total = 100 } }, bytes_done = 10, bytes_total = 100 } +list = open(preset_toc) +local probes = calls.resume_page +menu = openMenu(list) +chooseMenu(menu, 2) +Assert.eq(idsText(calls.estimate), "702", "在读的第 2 卷算未读:跳过已读完 / 已缓存 / 已排队") +Assert.eq(calls.resume_page, probes, "预设不逐卷调 resume_page") +confirm = Themed.last("confirm") +Assert.eq(confirm.title, "缓存这一卷") +textContains(confirm.text, "第 2 卷") +confirm.ok_callback() +Assert.eq(idsText(calls.enqueue[1]), "702", "只入队选中的未缓存卷") +Assert.eq(#calls.retry, 0) + +-- 全部都读完:没有未读卷,只提示,不再退化成整部。 +local all_read = { + entry(711, "第 1 卷", 100, 100), + entry(712, "第 2 卷", 100, 100), + entry(713, "第 3 卷", 100, 100), +} +reset() +local read_list = open(all_read) +local read_menu = openMenu(read_list) +local all_read_confirms = #Themed.all("confirm") +chooseMenu(read_menu, 2) +Assert.is_nil(calls.estimate, "全部已读不估算") +textContains(Themed.last("toast").text, "没有未读的卷") +Assert.eq(#Themed.all("confirm"), all_read_confirms, "全部已读不弹确认") + +-- 预设也没有对象:与「缓存整部」同一条 toast,不弹框。 +reset() +for _idx, item_entry in ipairs(preset_toc) do + st.statuses[tostring(item_entry.chapterId)] = { state = "complete", bytes = 1 } +end +list = open(preset_toc) +local no_object_confirms = #Themed.all("confirm") +menu = openMenu(list) +chooseMenu(menu, 2) +Assert.is_nil(calls.estimate, "没有对象不估算") +textContains(Themed.last("toast").text, "全部已缓存") +Assert.eq(#Themed.all("confirm"), no_object_confirms, "空选择不弹框") + +-- toc 是带 TTL 的快照:刚读完 / 刚开读的卷在服务端可能还是旧进度(大剑 Vol.17 的现场: +-- toc 仍是 117/196,本地已经 196/196)。本地卷进度(ProgressDB)比快照新,必须一起算, +-- 否则「后 N 卷」会从已经读完的卷重新缓存。 +local stale_toc = { + entry(801, "第 1 卷", 196, 196), + entry(802, "第 2 卷", 196, 117), -- toc 还是 60%,本地已读完 + entry(803, "第 3 卷", 196, 0), -- toc 没有进度,本地刚开读 + entry(804, "第 4 卷", 196, 0), +} +reset() +local_progress["900:802"] = { fraction = 1.0, page = 196, total_pages = 196 } +local_progress["900:803"] = { fraction = 0.015, page = 3, total_pages = 196 } +list = open(stale_toc) +local rows_text = table.concat(Kit.texts(list), "\n") +textContains(rows_text, "第 2 卷", "行还在") +Assert.is_true(rows_text:find("已读", 1, true) ~= nil, "本地读完的卷显示已读") +local stale_menu = openMenu(list) +chooseMenu(stale_menu, 2) +Assert.eq(idsText(calls.estimate), "803,804", "已读完的卷跳过,在读的 803 仍算未读") +Assert.is_true(rows_text:find("在读", 1, true) ~= nil, "本地刚开读的卷显示在读") + +-- 「缓存未读」不是连续后缀:中间已读的卷不打包,正在读的卷照收。 +local unread_toc = { + entry(721, "第 1 卷", 100, 100), -- 已读 + entry(722, "第 2 卷", 100, 30), -- 在读:算未读 + entry(723, "第 3 卷", 100, 0), -- 未读 + entry(724, "第 4 卷", 100, 0), -- 未读但已缓存 + entry(725, "第 5 卷", 100, 100), -- 已读(乱序,排在后面) + entry(726, "第 6 卷", 100, 0), -- 未读 +} +reset() +st.statuses["724"] = { state = "complete", bytes = 1 } +st.estimate = { chapters = 3, bytes = 30 * 1024 * 1024, available = 1000 * 1024 * 1024, ok = true } +list = open(unread_toc) +menu = openMenu(list) +chooseMenu(menu, 2) +Assert.eq(idsText(calls.estimate), "722,723,726", "在读算未读;已读与已缓存跳过") +confirm = Themed.last("confirm") +Assert.eq(confirm.title, "缓存 3 卷") +textContains(confirm.text, "第 2 卷") +Assert.is_true(not confirm.text:find("第 5 卷", 1, true), "后面已读的卷不打包进来") + +-- 预设「缓存后 N 卷…」:默认 3(不足 3 取剩余);0 / 非数字不动作;N 超过剩余卷数时截断。 +reset() +list = open(preset_toc) +menu = openMenu(list) +chooseMenu(menu, 3) +local input = Themed.last("spin") +Assert.not_nil(input, "后 N 卷走主题加减控件,不是文本输入") +Assert.eq(input.title, "缓存后 N 卷") +Assert.eq(input.fields[1].label, "卷数") +Assert.eq(input.fields[1].min, 1, "最少 1 卷") +Assert.eq(input.fields[1].max, 3, "最多到末卷(进度起点之后还有 3 卷)") +Assert.eq(input.fields[1].value, 3, "默认 3 卷(正好等于剩余卷数)") +Assert.is_nil(calls.estimate, "选之前不估算") +input.callback(1) +Assert.eq(idsText(calls.estimate), "702", "N=1 从进度起点取一卷") +confirm = Themed.last("confirm") +Assert.eq(confirm.title, "缓存这一卷") +st.estimate = { chapters = 3, bytes = 10 * 1024 * 1024, available = 1000 * 1024 * 1024, ok = true } +input.callback(9) +Assert.eq(idsText(calls.estimate), "702,703,704", "N 超过剩余卷数时截断到末卷") +confirm = Themed.last("confirm") +Assert.eq(confirm.title, "缓存 3 卷") +confirm.ok_callback() +Assert.eq(idsText(calls.enqueue[1]), "702,703,704", "三个入口共用同一确认与入队") +textContains(Themed.last("progress_dialog").text, "1/3 卷", "三个入口共用同一进度框") +Assert.eq(#calls.retry, 0) + +-- 剩余不足 3 卷:默认值取剩余卷数。 +local short_toc = { + entry(741, "第 1 卷", 100, 100), + entry(742, "第 2 卷", 100, 40), + entry(743, "第 3 卷", 100, 0), +} +reset() +list = open(short_toc) +menu = openMenu(list) +chooseMenu(menu, 3) +local short_input = Themed.last("spin") +Assert.eq(short_input.fields[1].max, 2, "剩 2 卷") +Assert.eq(short_input.fields[1].value, 2, "不足 3 卷时默认取剩余卷数") + +-- 「后 N 卷」同样跳过已缓存 / 已排队,不重复入队。 +reset() +st.queue = { state = "downloading", entries = { [703] = { chapterId = 703, state = "downloading", + bytes_done = 10, bytes_total = 100 } }, bytes_done = 10, bytes_total = 100 } +list = open(preset_toc) +menu = openMenu(list) +chooseMenu(menu, 3) +Themed.last("spin").callback(9) +Assert.eq(idsText(calls.estimate), "702,704", "已排队的卷不再入队") + +-- 「后 N 卷」没有对象:同一条 toast。 +reset() +for _idx, item_entry in ipairs(preset_toc) do + st.statuses[tostring(item_entry.chapterId)] = { state = "complete", bytes = 1 } +end +list = open(preset_toc) +local empty_confirms = #Themed.all("confirm") +menu = openMenu(list) +chooseMenu(menu, 3) +Themed.last("spin").callback(2) +Assert.is_nil(calls.estimate, "没有对象不估算") +textContains(Themed.last("toast").text, "全部已缓存") +Assert.eq(#Themed.all("confirm"), empty_confirms, "空选择不弹框") + +-- 全部已缓存:不估算,直接 toast。 +reset() +for _idx, item_entry in ipairs(toc) do + st.statuses[tostring(item_entry.chapterId)] = { state = "complete", bytes = 1 } +end +list = open() +local confirms = #Themed.all("confirm") +batchAll(list) +Assert.is_nil(calls.estimate, "没有对象不估算") +textContains(Themed.last("toast").text, "全部已缓存") +Assert.eq(#Themed.all("confirm"), confirms, "全部已缓存不弹框") + +-- estimate 说没事可做:toast,不弹框。 +reset() +st.estimate = { chapters = 0, bytes = 0, available = 1, ok = false, reason = "nothing_to_do" } +list = open() +batchAll(list) +textContains(Themed.last("toast").text, "全部已缓存或正在下载") +Assert.eq(#Themed.all("confirm"), confirms, "没事可做只 toast") + +-- 空间不足:确认框就地换成「空间不足」,主按钮只 toast,不入队。 +reset() +st.estimate = { chapters = 3, bytes = 849 * 1024 * 1024, available = 480 * 1024 * 1024, ok = false, reason = "space" } +list = open() +batchAll(list) +confirm = Themed.last("confirm") +Assert.not_nil(confirm) +textContains(confirm.text, "空间不足:需要 849.0 MB,可用 480.0 MB") +Assert.eq(confirm.ok_text, "去清理空间") +confirm.ok_callback() +Assert.len(calls.enqueue, 0, "空间不足不入队") +textContains(Themed.last("toast").text, "空间不足") + +-- 低水位:同样不给「开始缓存」。 +reset() +st.estimate = { chapters = 3, bytes = 1, available = 400 * 1024 * 1024, ok = false, reason = "low_water" } +list = open() +batchAll(list) +confirm = Themed.last("confirm") +textContains(confirm.text, "可用空间不足(剩余 400.0 MB)") +Assert.eq(confirm.ok_text, "去清理空间") + +-- 队列已暂停:确认框要说清「开始缓存会恢复整个队列」(07 A5)。 +reset() +st.queue = { state = "paused", pause_reason = "user", entries = {}, bytes_done = 0, bytes_total = 0 } +st.estimate = { chapters = 3, bytes = 10 * 1024 * 1024, available = 2000 * 1024 * 1024, ok = true } +list = open() +batchAll(list) +textContains(Themed.last("confirm").text, "当前下载已暂停,开始缓存会恢复整个队列") + +-- 批量里含失败项:入队未缓存的,再逐条重试失败的,进度框算上两项。 +reset() +st.statuses["601"] = { state = "complete", bytes = 1 } +st.estimate = { chapters = 1, bytes = 10 * 1024 * 1024, available = 2000 * 1024 * 1024, ok = true } +st.queue = { state = "idle", entries = { + [602] = { chapterId = 602, state = "failed", bytes_done = 0, bytes_total = 100, last_error = "http 403" }, +}, bytes_done = 0, bytes_total = 0 } +list = open() +batchAll(list) +confirm = Themed.last("confirm") +textContains(confirm.text, "另有 1 卷失败将重试") +confirm.ok_callback() +Assert.eq(calls.enqueue[1][1].chapterId, 603) +Assert.eq(calls.retry[1][1], 602) +progress = Themed.last("progress_dialog") +textContains(progress.text, "1/2 卷", "进度框按「入队 + 重试」算总数") + +-- 只有失败项:直接给「重试缓存」,文案用 lastError 映射后的说法。 +reset() +st.statuses["603"] = { state = "complete", bytes = 1 } +st.queue = { state = "idle", entries = { + [601] = { chapterId = 601, state = "failed", last_error = "http 403" }, + [602] = { chapterId = 602, state = "failed", last_error = "socket closed" }, +}, bytes_done = 0, bytes_total = 0 } +list = open() +batchAll(list) +Assert.is_nil(calls.estimate, "没有要下载的就不估算") +confirm = Themed.last("confirm") +Assert.eq(confirm.title, "重试缓存") +textContains(confirm.text, "服务器拒绝下载(403),检查 API Key / 权限") +textContains(confirm.text, "网络中断或服务器不可达") +confirm.ok_callback() +Assert.eq(table.concat(calls.retry[1], ","), "601,602") +Assert.len(calls.enqueue, 0, "没有未缓存的项就不入队") + +-- 删除下载中的卷:确认文案多一句「会取消这一卷的下载」(07 A4)。行尾只有一个动作槽, +-- 下载中显示暂停;确认文案本身是可复用的纯函数,供将来二级菜单 / 系列清理复用。 +reset() +st.statuses["601"] = { state = "complete", bytes = 1 } +st.queue = { state = "downloading", entries = { [602] = { chapterId = 602, state = "downloading", + bytes_done = 30, bytes_total = 100 } }, bytes_done = 30, bytes_total = 100 } +list = open() +text = table.concat(Kit.texts(list), "\n") +textContains(text, "下载中 30%") +local row_buttons = tails(list) +Assert.eq(row_buttons[1].icon, "delete") +Assert.eq(row_buttons[2].icon, "pause") +textContains(VolumeList.deleteText(toc[2], 30 * 1024 * 1024, true), "删除会取消这一卷的下载。") + +-- 删除后重画:这一卷回到「在读」(缓存动作变回 download)。 +row_buttons[1]:onTapThemeButton() +Themed.last("confirm").ok_callback() +row_buttons = tails(list) +Assert.eq(row_buttons[1].icon, "download", "删完变回下载") +textContains(table.concat(Kit.texts(list), "\n"), "已读", "删缓存不动阅读进度") + +-- 正在读的卷:删除钮置灰,点按只 toast,不弹确认框、不选中(07 A1)。 +reset() +st.statuses["602"] = { state = "complete", bytes = 1 } +st.open_chapter = 602 +list, picked = open() +local disabled +for _idx, button in ipairs(tails(list)) do + if button.icon == "delete" then disabled = button end +end +Assert.is_false(disabled.enabled, "删除钮置灰") +confirms = #Themed.all("confirm") +tap(list, disabled) +Assert.eq(#Themed.all("confirm"), confirms, "置灰的删除钮不弹确认框") +textContains(Themed.last("toast").text, "正在阅读这一卷,关闭后可以删除") +Assert.is_nil(picked.value, "点置灰按钮不选中") + +-- 离线 + 未缓存:行仍可点,但只提示,不关窗也不选中(04 A7)。 +reset() +offline = true +list, picked = open() +textContains(table.concat(Kit.texts(list), "\n"), "未缓存 · 离线") +tapRow(list, "第 3 卷") +Assert.is_nil(picked.value, "离线未缓存行不选中") +textContains(Themed.last("toast").text, "这一卷还没缓存,联网后可下载") + +-- unknown_server:缓存状态整块不显示,只剩阅读状态,缓存动作全部隐藏(02 A9)。 +reset() +st.queue_code = "unknown_server" +st.queue = nil +list = open() +Assert.len(tails(list), 0, "没有行尾动作") +Assert.is_nil(list.left_icon, "没有缓存整部") +Assert.is_true(table.concat(Kit.texts(list), "\n"):find("缓存", 1, true) == nil, "不出现缓存状态字") + +-- 缺 queue_control:下载中只显示百分比,不出暂停 / 重试(02 A4)。 +reset() +st.probe = { ok = true, state = "enhanced", capabilities = { + status = true, queue = true, enqueue = true, delete = true, estimate = true, +} } +st.statuses["601"] = { state = "complete", bytes = 1 } +st.queue = { state = "downloading", entries = { [602] = { chapterId = 602, state = "downloading", + bytes_done = 62, bytes_total = 100 } }, bytes_done = 62, bytes_total = 100 } +list = open() +textContains(table.concat(Kit.texts(list), "\n"), "下载中 62%") +Assert.len(tails(list), 2, "只剩已缓存的删除钮与未缓存的下载钮") + +-- 暂停原因:行显示「已暂停 + 百分比 + play」,动作按 07 A5 分派。 +reset() +st.statuses["601"] = { state = "complete", bytes = 1 } +local function pausedQueue(reason, extra) + local entries = extra or {} + return { state = "paused", pause_reason = reason, entries = entries, + bytes_done = 0, bytes_total = 0 } +end +-- user / restored / offline / wifi:直接 resume。 +for _idx, reason in ipairs({ "user", "restored", "offline", "wifi" }) do + reset() + st.statuses["601"] = { state = "complete", bytes = 1 } + st.queue = pausedQueue(reason, { [602] = { chapterId = 602, state = "queued", + bytes_done = 62, bytes_total = 100 } }) + list = open() + textContains(table.concat(Kit.texts(list), "\n"), "已暂停 62%") + local play + for _i, button in ipairs(tails(list)) do + if button.icon == "play_arrow" then play = button end + end + Assert.not_nil(play, reason .. " 有继续钮") + play:onTapThemeButton() + Assert.eq(calls.resume, 1, reason .. " 直接继续") + Assert.len(calls.retry, 0, reason .. " 不重试") +end + +-- network:先重试本服务器的失败项,再继续。 +reset() +st.statuses["601"] = { state = "complete", bytes = 1 } +st.queue = pausedQueue("network", { + [602] = { chapterId = 602, state = "failed", last_error = "socket closed" }, + [603] = { chapterId = 603, state = "queued" }, +}) +list = open() +for _idx, button in ipairs(tails(list)) do + if button.icon == "play_arrow" then button:onTapThemeButton() end +end +Assert.eq(table.concat(calls.retry[1], ","), "602") +Assert.eq(calls.resume, 1) + +-- low_space:不给继续,只 toast 清理提示。 +reset() +st.statuses["601"] = { state = "complete", bytes = 1 } +st.queue = pausedQueue("low_space", { [602] = { chapterId = 602, state = "queued" } }) +list = open() +for _idx, button in ipairs(tails(list)) do + if button.icon == "play_arrow" then button:onTapThemeButton() end +end +Assert.eq(calls.resume, 0, "空间不足不恢复") +textContains(Themed.last("toast").text, "空间不足,已暂停") + +-- 进度框:入队后 1 秒轮询,暂停 → 已暂停收尾;继续 → 再开进度框。 +--- 走一遍「缓存整部」到出进度框;返回进度框与已排的 tick 数。 +---@return table +local function batchProgress() + reset() + st.statuses["601"] = { state = "complete", bytes = 1 } + st.estimate = { chapters = 2, bytes = 10 * 1024 * 1024, available = 1000 * 1024 * 1024, ok = true } + list = open() + batchAll(list) + Themed.last("confirm").ok_callback() + return Themed.last("progress_dialog") +end + +--- 跑下一拍(1 秒)。 +local function tick() + local scheduled = Kit.scheduled[#Kit.scheduled] + Assert.not_nil(scheduled, "有下一拍") + Assert.eq(scheduled.delay, 1, "每秒轮询") + scheduled.fn() +end + +local progress_dialog = batchProgress() +Assert.eq(progress_dialog.sets and #progress_dialog.sets or 0, 0, "刚开还没走过一拍") +-- 下载中:聚合百分比 + 当前卷。 +st.queue = { state = "downloading", percent = 0.5, entries = { + [602] = { chapterId = 602, state = "downloading", bytes_done = 50, bytes_total = 100 }, +}, bytes_done = 50, bytes_total = 100, current_chapter_id = 602 } +local resume_page_calls = calls.resume_page +tick() +Assert.is_true(#progress_dialog.sets > 0, "轮询后更新说明行") +Assert.eq(calls.resume_page, resume_page_calls, "轮询不重复读 journal 的 resume_page") +local last_set = progress_dialog.sets[#progress_dialog.sets] +textContains(last_set[1], "第 2 卷") +Assert.eq(last_set[2], 50, "进度条用本服务器的聚合 percentage") + +-- 暂停:进度框按钮走 queue_pause;下一拍收尾成「已暂停」,按钮是继续 / 关闭。 +progress_dialog.on_cancel() +Assert.eq(calls.pause, 1) +tick() +confirm = Themed.last("confirm") +Assert.eq(confirm.title, "已暂停") +textContains(confirm.text, "已暂停") +Assert.eq(confirm.ok_text, "继续") +Assert.eq(confirm.cancel_text, "关闭") +-- 继续:先 resume,再开回进度框。 +local dialogs = #Themed.all("progress_dialog") +confirm.ok_callback() +Assert.eq(calls.resume, 1) +Assert.eq(#Themed.all("progress_dialog"), dialogs + 1, "继续后重开进度框") + +-- 全部完成:自动关窗 + toast「已缓存 N 卷」,不再排下一拍。 +progress_dialog = Themed.last("progress_dialog") +st.queue = { state = "idle", entries = {}, bytes_done = 0, bytes_total = 0 } +local before = #Kit.scheduled +tick() +Assert.is_true(progress_dialog.closed, "全成关窗") +textContains(Themed.last("toast").text, "已缓存 2 卷") +Assert.eq(#Kit.scheduled, before, "收尾后不再轮询") + +-- 部分失败:说明行写成功 / 失败数并列出失败原因,按钮「查看失败原因」。 +progress_dialog = batchProgress() +st.queue = { state = "idle", entries = { + [602] = { chapterId = 602, state = "failed", last_error = "not an archive: html" }, +}, bytes_done = 0, bytes_total = 0 } +tick() +confirm = Themed.last("confirm") +Assert.eq(confirm.title, "部分失败") +textContains(confirm.text, "1 卷成功,1 卷失败") +textContains(confirm.text, "下载内容不完整或不是有效压缩包") +Assert.eq(confirm.ok_text, "查看失败原因") +confirm.ok_callback() +Assert.is_true(progress_dialog.closed) + +-- 断网暂停:文案带原因,按钮继续。 +progress_dialog = batchProgress() +st.queue = { state = "paused", pause_reason = "offline", entries = { + [602] = { chapterId = 602, state = "queued" }, +}, bytes_done = 0, bytes_total = 0 } +tick() +confirm = Themed.last("confirm") +Assert.eq(confirm.title, "已暂停") +textContains(confirm.text, "已暂停(断网)") +Assert.eq(confirm.ok_text, "继续") +Assert.eq(confirm.cancel_text, "关闭") + +-- 其余暂停原因:文案与主按钮都来自 07 A5 的表。 +for reason, expected in pairs({ + user = "已暂停", + restored = "已暂停(启动恢复)", + wifi = "已暂停(仅 Wi-Fi 下载)", +}) do + progress_dialog = batchProgress() + st.queue = { state = "paused", pause_reason = reason, entries = { + [602] = { chapterId = 602, state = "queued" }, + }, bytes_done = 0, bytes_total = 0 } + tick() + confirm = Themed.last("confirm") + Assert.eq(confirm.title, "已暂停", reason) + textContains(confirm.text, expected, reason) + Assert.eq(confirm.ok_text, "继续", reason) + Assert.eq(confirm.cancel_text, "关闭", reason) +end + +-- 空间不足暂停:没有继续,只有清理提示。 +progress_dialog = batchProgress() +st.queue = { state = "paused", pause_reason = "low_space", entries = { + [602] = { chapterId = 602, state = "queued" }, +}, bytes_done = 0, bytes_total = 0 } +tick() +confirm = Themed.last("confirm") +textContains(confirm.text, "空间不足,已暂停") +Assert.eq(confirm.ok_text, "去清理空间") +confirm.ok_callback() +textContains(Themed.last("toast").text, "空间不足") +Assert.eq(calls.resume, 0, "低水位不给继续") + +-- 连续失败暂停:主按钮「重试失败项并继续」,点了先逐条重试再恢复。 +progress_dialog = batchProgress() +st.queue = { state = "paused", pause_reason = "network", entries = { + [602] = { chapterId = 602, state = "failed", last_error = "http 403" }, +}, bytes_done = 0, bytes_total = 0 } +tick() +confirm = Themed.last("confirm") +textContains(confirm.text, "已暂停(连续下载失败)") +Assert.eq(confirm.ok_text, "重试失败项并继续") +confirm.ok_callback() +Assert.eq(table.concat(calls.retry[1], ","), "602") +Assert.eq(calls.resume, 1) +Assert.not_nil(Themed.last("progress_dialog")) + +-- 后台运行:关窗不影响队列,列表继续轮询;后台期间不再弹收尾框。 +progress_dialog = batchProgress() +progress_dialog.on_background() +st.queue = { state = "downloading", percent = 0.9, entries = { + [602] = { chapterId = 602, state = "downloading", bytes_done = 90, bytes_total = 100 }, +}, bytes_done = 90, bytes_total = 100, current_chapter_id = 602 } +local confirms_before = #Themed.all("confirm") +tick() +Assert.eq(#Themed.all("confirm"), confirms_before, "后台不弹窗") +st.queue = { state = "idle", entries = {}, bytes_done = 0, bytes_total = 0 } +tick() +Assert.eq(#Themed.all("confirm"), confirms_before, "后台收尾也不弹窗") + +-- 失败行:refresh 走单卷确认,文案是 lastError 映射后的说法(07 A7),没有 moon 侧重试。 +reset() +st.statuses["601"] = { state = "complete", bytes = 1 } +st.queue = { state = "idle", entries = { + [602] = { chapterId = 602, state = "failed", last_error = "http 403" }, +}, bytes_done = 0, bytes_total = 0 } +list = open() +local refresh_button +for _idx, button in ipairs(tails(list)) do + if button.icon == "refresh" then refresh_button = button end +end +Assert.not_nil(refresh_button) +tap(list, refresh_button) +confirm = Themed.last("confirm") +Assert.eq(confirm.title, "重试缓存") +textContains(confirm.text, "服务器拒绝下载(403),检查 API Key / 权限") +confirm.ok_callback() +Assert.eq(table.concat(calls.retry[1], ","), "602") +Assert.eq(calls.resume, 0, "queue_retry 由 kamare 自己恢复,moon 不再补 resume") + +-- 删除失败:kamare 的 code / message 原样提示。 +reset() +st.statuses["601"] = { state = "complete", bytes = 1 } +st.delete_ok, st.delete_code, st.delete_message = false, "write_failed", "删除失败:磁盘错误" +list = open() +tap(list, tails(list)[1]) +Themed.last("confirm").ok_callback() +textContains(Themed.last("toast").text, "删除失败:磁盘错误") + +-- 关列表即停轮询(04 A8)。 +batchProgress() +Assert.is_true(#Kit.scheduled > 0) +list:close() +Assert.is_true(#Kit.unscheduled > 0, "关窗时撤掉定时器") + +-- 后台任务:入队就登记一条 passive 任务,页面自己的进度框在时静音(收尾只提示一次)。 +reset() +progress_dialog = batchProgress() +local handle = tracked[1] +Assert.not_nil(handle, "入队后登记后台任务") +Assert.eq(handle.opts.series, series, "任务按这一部书") +Assert.eq(#handle.opts.entries, 2, "任务只数本批的卷") +Assert.eq(handle.opts.entries[1].chapterId, 602) +Assert.is_true(handle.muted, "进度框开着时任务静音") +progress_dialog.on_background() +Assert.is_false(handle.muted, "转后台后由任务收尾提示") + +-- 关列表同样取消静音:页面不再轮询,完成提示归任务。 +reset() +progress_dialog = batchProgress() +handle = tracked[1] +Assert.is_true(handle.muted) +list:close() +Assert.is_false(handle.muted, "关列表后由任务收尾提示") + +-- 缺 queue:没有可轮询的队列,不登记任务(不能让后台任务永远挂着)。 +reset() +st.probe = { ok = true, state = "enhanced", capabilities = { + status = true, enqueue = true, delete = true, estimate = true, +} } +st.estimate = { chapters = 2, bytes = 1, available = 1000, ok = true } +list = open() +batchAll(list) +Themed.last("confirm").ok_callback() +Assert.len(tracked, 0, "缺 queue 不登记任务") + +-- 缺 queue_control:进度框只留后台运行。 +reset() +st.probe = { ok = true, state = "enhanced", capabilities = { + status = true, queue = true, enqueue = true, delete = true, estimate = true, +} } +st.statuses["601"] = { state = "complete", bytes = 1 } +st.estimate = { chapters = 2, bytes = 1, available = 1000, ok = true } +list = open() +batchAll(list) +Themed.last("confirm").ok_callback() +progress_dialog = Themed.last("progress_dialog") +Assert.is_nil(progress_dialog.on_cancel, "没有暂停钮") +Assert.not_nil(progress_dialog.on_background, "仍可后台运行") + +-- 缺 queue:没有进度可轮询,行显示「已排队」且不能凭缺席的队列宣布完成(02 A4)。 +reset() +st.probe = { ok = true, state = "enhanced", capabilities = { + status = true, enqueue = true, delete = true, estimate = true, +} } +st.statuses["601"] = { state = "complete", bytes = 1 } +st.estimate = { chapters = 2, bytes = 10 * 1024 * 1024, available = 1000 * 1024 * 1024, ok = true } +local scheduled_before = #Kit.scheduled +local toasts_before = #Themed.all("toast") +list = open() +batchAll(list) +Themed.last("confirm").ok_callback() +progress_dialog = Themed.last("progress_dialog") +Assert.not_nil(progress_dialog, "缺 queue 也确认已入队") +Assert.eq(progress_dialog.text, "已排队", "没有百分比可写") +Assert.eq(#Kit.scheduled, scheduled_before, "没有 queue 可轮询:不排下一拍") +Assert.eq(#Themed.all("toast"), toasts_before, "不凭缺席的队列宣布完成") +local no_queue_text = table.concat(Kit.texts(list), "\n") +textContains(no_queue_text, "已排队", "行内显示排队") +Assert.is_nil(no_queue_text:find("已缓存 2 卷", 1, true), "不能谎报已缓存") + +-- 行内暂停是全局动作:文案要说清暂停的是整个队列(04 A3)。 +reset() +st.statuses["601"] = { state = "complete", bytes = 1 } +st.queue = { state = "downloading", entries = { [602] = { chapterId = 602, state = "downloading", + bytes_done = 30, bytes_total = 100 } }, bytes_done = 30, bytes_total = 100 } +list = open() +local pause_button +for _idx, button in ipairs(tails(list)) do + if button.icon == "pause" then pause_button = button end +end +Assert.not_nil(pause_button) +local toasts_used = #Themed.all("toast") +pause_button:onTapThemeButton() +Assert.eq(calls.pause, 1, "点暂停即 queue_pause") +Assert.eq(#Themed.all("toast"), toasts_used + 1, "暂停后提示") +textContains(Themed.last("toast").text, "整个下载队列", "说明作用于全局队列") + + +-- 系列清理:一次 chapters(series_id)、菜单计数、确认后批量删、就地刷新。 +reset() +st.probe = { ok = true, state = "enhanced", capabilities = { + status = true, queue = true, queue_control = true, enqueue = true, + delete = true, estimate = true, chapters = true, +} } +st.plan = { + { chapterId = 601, pages = 100, read = true, bytes = 1024, stale = false, queued = false }, + { chapterId = 602, pages = 100, read = false, bytes = 2048, stale = false, queued = false }, +} +list = open() +Assert.eq(calls.chapters, 1, "一次 chapters(series_id) 取代逐章 status") +Assert.eq(calls.chapters_series, "900", "按当前 seriesId 取计划") +textContains(table.concat(Kit.texts(list), "\n"), "已读 · 已缓存", "kamare 的已读进入行状态") + +menu = openMenu(list) +local cleanup_labels = {} +for _idx, item in ipairs(menu.items) do cleanup_labels[#cleanup_labels + 1] = item.text end +Assert.eq(table.concat(cleanup_labels, "|"), + "缓存整部|缓存未读|缓存后 N 卷…|清理本系列|清理本系列已读", + "清理项在批量菜单底部") +Assert.eq(menu.items[4].mandatory, "2 卷", "本系列缓存计数") +Assert.eq(menu.items[5].mandatory, "1 卷", "本系列已读计数") + +chooseMenu(menu, 5) +local cleanup_confirm = Themed.last("confirm") +Assert.not_nil(cleanup_confirm, "清理前确认") +textContains(cleanup_confirm.text, "将删除本系列 1 卷已读完的缓存") +textContains(cleanup_confirm.text, "阅读进度与 kamare journal 保留") +cleanup_confirm.ok_callback() +local busy = Themed.last("progress_dialog") +Assert.not_nil(busy, "同步删除先弹忙碌窗") +Assert.eq(busy.title, "清理本系列已读") +Assert.eq(busy.text, "正在清理…") +Assert.is_true(busy.shown and busy.closed, "先显示、删完关闭") +Assert.eq(#calls.delete, 1, "清理本系列已读只调一次 delete") +Assert.eq(#calls.delete[1], 1, "只删已读完的那一卷") +Assert.eq(calls.delete[1][1], 601, "删的是已读卷") +Assert.eq(calls.chapters, 2, "删后重取一次 chapters 比对残留") +textContains(Themed.last("toast").text, "已清理 1 卷") + +-- 0 个对象:菜单项置灰,点了也不会弹确认。 +reset() +st.probe = { ok = true, state = "enhanced", capabilities = { + status = true, enqueue = true, delete = true, estimate = true, chapters = true, +} } +st.plan = { { chapterId = 602, pages = 100, read = false, bytes = 2048 } } +list = open() +menu = openMenu(list) +Assert.is_false(menu.items[5].enabled, "没有已读完的卷时置灰") +Assert.eq(menu.items[5].mandatory, "无") +Assert.is_true(menu.items[4].enabled, "还有未读的缓存:整系列清理仍可点") +Assert.eq(menu.items[4].mandatory, "1 卷") + +-- 点开系列时后台刷新目录:服务器最新的 pagesRead 原地反映到行里(不用关掉重开)。 +reset() +local fresh_toc = { entry(631, "第 1 卷", 100, 0), entry(632, "第 2 卷", 100, 0) } +local live = open(fresh_toc) +Assert.not_nil(live.refreshToc, "列表暴露刷新入口") +live.refreshToc({ entry(631, "第 1 卷", 100, 100), entry(632, "第 2 卷", 100, 40) }) +live:paintTo(Kit.canvas(), 0, 0) +local live_text = table.concat(Kit.texts(live), "\n") +Assert.is_true(live_text:find("已读", 1, true) ~= nil, "服务器说读完的卷立刻变已读") +Assert.is_true(live_text:find("在读", 1, true) ~= nil, "服务器说读到一半的卷立刻变在读") +-- 空目录 / 已关的列表直接丢弃回包,不把列表清空。 +live.refreshToc({}) +live:paintTo(Kit.canvas(), 0, 0) +textContains(table.concat(Kit.texts(live), "\n"), "第 1 卷", "空回包不清空列表") +live.closed = true +live.refreshToc({ entry(631, "第 1 卷", 100, 0) }) +Assert.eq(#live.items, 2, "关掉的列表不再吃回包") + +-- 续读卡:主线 = 最远有进度的卷,标题写卷名 + 页数;点卡片直接选中它。 +reset() +local cover_hits = {} +list, picked = open(nil, { + cover = function(e) + cover_hits[#cover_hits + 1] = e.chapterId + return "http://cover/" .. e.chapterId .. ".jpg", { ["x-api-key"] = "k" } + end, +}) +local card = findRow(list, "继续阅读 · 第 2 卷") +Assert.not_nil(card, "续读卡写明是哪一卷") +Assert.eq(card.row_subtitle, "第 40/100 页 · 40%") +Assert.eq(#cover_hits, 3, "每一卷都取了封面(卡片复用同一张,不重复取)") +tap(list, card) +Assert.eq(picked.value and picked.value.chapterId, 602, "点卡片直接开第 2 卷") +Assert.is_true(wasClosed(list), "点卡片关列表") + +-- 回顾旧卷:主线仍是第 2 卷,第 1 卷只标「上次翻阅」。 +reset() +local_progress["900:601"] = { fraction = 1, page = 100, total_pages = 100, updated_at = 500 } +local_progress["900:602"] = { fraction = 0.4, page = 40, total_pages = 100, updated_at = 100 } +list = open() +Assert.not_nil(findRow(list, "继续阅读 · 第 2 卷"), "回顾旧卷不劫持主线") +Assert.eq(findRow(list, "第 1 卷").row_subtitle, "上次翻阅") +Assert.eq(findRow(list, "第 2 卷").row_subtitle, "第 40/100 页 · 40%") + +-- 全部读完:卡片写「已读完 · 共 N 卷」,点它重读第一卷。 +reset() +list, picked = open({ + entry(661, "第 1 卷", 100, 100), + entry(662, "第 2 卷", 100, 100), +}) +local done = findRow(list, "已读完 · 共 2 卷") +Assert.not_nil(done, "读完的系列有重读入口") +Assert.eq(done.row_subtitle, "重读 · 第 1 卷") +tap(list, done) +Assert.eq(picked.value and picked.value.chapterId, 661, "重读回到第一卷") + +-- 卷名缺失 / 退化成系列名:兜底「第 N 卷」。 +reset() +list = open({ + { idx = 1, chapterId = 671, volumeId = 1, seriesId = 900, libraryId = 1, + title = "测试系列", pages = 100, pagesRead = 0 }, +}) +Assert.not_nil(findRow(list, "第 1 卷"), "标题退化成系列名时用第 N 卷") + + +-- 服务端已读完、本机重新打开留下 1/194:行仍显示「已读」,不显示 1%,主线跳过它。 +reset() +local_progress["900:682"] = { fraction = 0.005, page = 1, total_pages = 194, updated_at = 999 } +list = open({ + entry(681, "第 1 卷", 210, 210), + entry(682, "第 2 卷", 194, 194), + entry(683, "第 3 卷", 200, 0), +}) +Assert.eq(findRow(list, "第 2 卷").row_subtitle, "上次翻阅", "已读完的卷不再显示 1/194") +Assert.not_nil(findRow(list, "继续阅读 · 第 3 卷"), "主线跳过已读完的第 2 卷") + +-- 离线续读卡和普通卷行使用同一套选择保护。 +reset() +offline = true +list, picked = open() +local offline_card = findRow(list, "继续阅读 · 第 2 卷") +tap(list, offline_card) +Assert.is_nil(picked.value, "未缓存卷不能从续读卡绕过离线保护") +Assert.is_false(wasClosed(list), "离线失败后保留卷列表,仍能挑别的缓存卷") +Assert.eq(Themed.last("toast").text, "这一卷还没缓存,联网后可下载") + +reset() +offline = true +st.statuses["602"] = { state = "complete", bytes = 2048 } +list, picked = open() +tap(list, findRow(list, "继续阅读 · 第 2 卷")) +Assert.eq(picked.value.chapterId, 602, "已缓存的续读卷离线照常打开") +Assert.is_true(wasClosed(list)) + +-- kamare 完成状态参与列表与对外目标计算;刷新后卡片也必须顺延。 +reset() +st.probe.capabilities.chapters = true +st.plan = { { chapterId = 602, pages = 100, read = false, bytes = 2048 } } +list = open() +Assert.not_nil(findRow(list, "继续阅读 · 第 2 卷")) +st.plan[1].read = true +list.refreshToc({ unpack(toc) }) +list:paintTo(Kit.canvas(), 0, 0) +Assert.not_nil(findRow(list, "继续阅读 · 第 3 卷"), "最新完成状态不能被刷新前的 ctx 遮住") +Assert.eq(VolumeList.continueTarget(series, toc).entry.chapterId, 603, + "对外目标和列表使用同一套 kamare 完成事实") + +-- 目标计算不逐卷读 resumePage(那是列表行「待同步」才需要的)。 +reset() +st.plan = { { chapterId = 601, pages = 100, read = true, bytes = 1 } } +VolumeList.continueTarget(series, toc) +Assert.eq(calls.resume_page, 0, "续读目标不读 resume_page") + + +-- 卷进度整列一次查询,不再逐卷 get。 +reset() +list = open() +Assert.eq(progress_list_calls, 1, "打开列表只读一次整列进度") + + +return true diff --git a/tools/package.sh b/tools/package.sh new file mode 100755 index 0000000..8c53048 --- /dev/null +++ b/tools/package.sh @@ -0,0 +1,25 @@ +#!/bin/sh +# 打包本仓库的书源插件:moonsource-<名字>.koplugin-