🚚 (split): 从月读拆出独立仓库,沿用原书源 id
Release / release (push) Successful in 11s

This commit is contained in:
Garfield committed 2026-11-27 08:08:01 +08:00
commit df896cbe3b
28 files changed
+3586

No files matched your search

+170
View File
@@ -0,0 +1,170 @@
--[[--
reader3 本地 EPUB:正文资源与图片的成功、失败、取消及同步回调接力。
@module tests.moonsource_legado.source_content_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch, assign-type-mismatch
local Assert = require("support.assert")
local JSONStub = require("support.json_stub")
local Paths = require("utils.paths")
local cfg = { server_address = "http://reader.example/reader3" }
local requests, sync_replies, writes = {}, {}, {}
local payload, reason, calls
local write_failed = false
package.preload["utils.settings"] = function()
return { getSource = function() return cfg end }
end
package.preload["json"] = function()
return { encode = JSONStub.encode, decode = JSONStub.decode }
end
package.preload["http.request"] = function()
local function request(url, cb)
local entry = { url = url, cb = cb, cancelled = false }
requests[#requests + 1] = entry
local reply = table.remove(sync_replies, 1)
if reply then cb(reply.body, reply.err) end
return { cancel = function() entry.cancelled = true end }
end
return {
get = function(url, _opts, cb) return request(url, cb) end,
post = function(url, _body, _opts, cb) return request(url, cb) end,
}
end
package.preload["source.chapter"] = function()
return {
prefetchAsync = function(identity, _book, toc, _from, _count, ops, cb)
return ops.fetchContent(identity, toc[1], cb)
end,
}
end
for _idx, name in ipairs({ "utils.settings", "json", "http.request", "source.chapter",
"source.assets", "moonsource_legado.source", "moonsource_legado.client" }) do
package.loaded[name] = nil
end
local Assets = require("source.assets")
Assets.materializeImage = function(dir, data)
writes[#writes + 1] = { dir = dir, data = data }
if write_failed then return nil end
return "images/fixture.png"
end
local source = require("moonsource_legado.source").new()
local identity = { source_id = "legado", stable_id = "legado-content-fixture", book = {} }
local toc = { { idx = 1, uid = "0", title = "章" } }
local resource = "/book-assets/book/Text/chapter%20one.xhtml"
local image_body = '<body><img src = "../Images/cover%20one.png"/></body>'
local function wire(text) return JSONStub.encode({ isSuccess = true, data = text }) end
local function start(replies)
requests, writes, sync_replies = {}, {}, replies or {}
payload, reason, calls, write_failed = nil, nil, 0, false
return source:prefetchChaptersAsync(identity, toc, 1, 1, function(value, err)
payload, reason, calls = value, err, calls + 1
end)
end
-- 普通正文不能因为以 .html 结尾而被当作资源,包括 App 和轻阅读。
for _idx, address in ipairs({ "http://reader.example/reader3", "http://reader.example", "http://reader.example/api/5" }) do
cfg.server_address = address
start()
requests[1].cb(wire("Documentation is at index.html"))
Assert.eq(payload.html, address == "http://reader.example"
and '<h1>章</h1>\n<p id="moon-legado-paragraph-1">Documentation is at index.html</p>'
or "<h1>章</h1>\n<p>Documentation is at index.html</p>")
Assert.len(requests, 1)
end
cfg.server_address = "http://reader.example/reader3"
-- 资源路径保留已有编码;合法的 src = 属性在图片落地后不再留下远程引用。
do
start()
requests[1].cb(wire(resource))
Assert.eq(requests[2].url, "http://reader.example" .. resource)
requests[2].cb(image_body)
Assert.eq(requests[3].url, "http://reader.example/book-assets/book/Images/cover%20one.png")
requests[3].cb("image data")
Assert.eq(payload.html, '<h1>章</h1>\n<img src="images/fixture.png"/>')
Assert.eq(writes[1].dir, Paths.bookWorkDir(identity.stable_id, identity.source_id) .. "/images")
Assert.eq(calls, 1)
end
-- 资源 GET 的错误直接上报;标题和空白实体不能让空正文成功。
do
start()
requests[1].cb(wire(resource))
requests[2].cb(nil, "HTTP 404")
Assert.is_nil(payload)
Assert.eq(reason, "HTTP 404")
start()
requests[1].cb(wire(resource))
requests[2].cb("<body><div>&nbsp; &#160;</div></body>")
Assert.is_nil(payload)
Assert.eq(reason, "阅读章节内容为空")
start()
requests[1].cb(wire(resource))
requests[2].cb("<body><div>&amp;</div></body>")
Assert.eq(payload.html, "<h1>章</h1>\n<div>&amp;</div>")
end
-- 下载失败、不识别的图片或图片写盘失败,均不得返回成功章节。
for _idx, failure in ipairs({ "network", "invalid", "write" }) do
start()
requests[1].cb(wire(resource))
requests[2].cb(image_body)
if failure == "network" then
requests[3].cb(nil, "HTTP 404")
else
if failure == "invalid" then
local materialize = Assets.materializeImage
Assets.materializeImage = function() return nil end
requests[3].cb("<html>not an image</html>")
Assets.materializeImage = materialize
else
write_failed = true
requests[3].cb("image data")
end
end
Assert.is_nil(payload)
Assert.eq(reason, failure == "network" and "HTTP 404" or "阅读插图下载失败,请重试")
Assert.eq(calls, 1)
end
-- 三个阶段分别取消;即使底层桩强行投递迟到响应也不能继续或落地图片。
for phase = 1, 3 do
local job = start()
if phase > 1 then requests[1].cb(wire(resource)) end
if phase > 2 then requests[2].cb(image_body) end
job.cancel()
Assert.is_true(requests[phase].cancelled)
requests[phase].cb(phase == 1 and wire(resource) or phase == 2 and image_body or "image data")
Assert.len(requests, phase)
Assert.len(writes, 0)
Assert.eq(calls, 0)
end
-- 同步 API / XHTML 回调不能把旧句柄写回,取消必须命中仍在飞的下一阶段。
for phase = 2, 3 do
local replies = { { body = wire(resource) } }
if phase == 3 then replies[2] = { body = image_body } end
local job = start(replies)
job.cancel()
Assert.is_true(requests[phase].cancelled)
Assert.is_false(requests[1].cancelled)
Assert.eq(calls, 0)
end
-- 已登录时 XHTML 和同服务器图片都带令牌,CDN 图片不带服务器令牌。
do
cfg.username, cfg.password = "fixture-user", "fixture-password"
start()
requests[1].cb(wire({ accessToken = "fixture-token" }))
requests[2].cb(wire(resource))
Assert.eq(requests[3].url, "http://reader.example" .. resource .. "?accessToken=fixture-token")
requests[3].cb('<body><img src="../Images/cover.png"/><img src="//cdn.example/cover.png"/></body>')
Assert.eq(requests[4].url, "http://reader.example/book-assets/book/Images/cover.png?accessToken=fixture-token")
requests[4].cb("image data")
Assert.eq(requests[5].url, "http://cdn.example/cover.png")
requests[5].cb("cdn image data")
Assert.is_nil(reason)
Assert.eq(calls, 1)
end
+70
View File
@@ -0,0 +1,70 @@
--[[--
阅读(Legado)进度推送:返回的句柄要能取消真正在飞的 saveBookProgress 请求,取消后不再回调。
@module tests.moonsource_legado.source_progress_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local Stubs = require("support.stubs")
Stubs.install()
Stubs.reset()
local row = { bookUrl = "u1", name = "书", author = "人", durChapterIndex = 0, durChapterPos = 0 }
local saves = {}
package.preload["moonsource_legado.client"] = function()
return {
base = function() return "http://h" end,
shelfAsync = function(cb)
cb({ row })
return { cancel = function() end }
end,
saveProgressAsync = function(_row, pos, cb)
local req = { pos = pos, cb = cb, cancelled = false }
req.cancel = function() req.cancelled = true end
saves[#saves + 1] = req
return req
end,
}
end
package.preload["moonsource_legado.mapper"] = function()
return { readPos = function() return { index = 0, offset = 3 } end }
end
package.preload["source.toc"] = function()
return { read = function() return { { uid = "c1", idx = 1, title = "一" }, { uid = "c2", idx = 2, title = "二" } } end }
end
for _idx, name in ipairs({ "moonsource_legado.source", "moonsource_legado.client", "moonsource_legado.mapper", "source.toc" }) do
package.loaded[name] = nil
end
local Legado = require("moonsource_legado.source")
local identity = { source_id = "legado", stable_id = "u1" }
-- 正常:推到第二章,回调 ok
do
local src = Legado.new()
local got_ok, got_err
src:putProgressAsync(identity, { chapter_idx = 2 }, function(ok, err) got_ok, got_err = ok, err end)
Stubs.flush()
Assert.len(saves, 1)
Assert.eq(saves[1].pos.index, 1)
Assert.eq(saves[1].pos.offset, 0, "换章 offset 归零")
saves[1].cb(true)
Assert.is_true(got_ok, got_err)
saves = {}
end
-- 取消:传到在飞的保存请求;迟到的回包不再投递
do
local src = Legado.new()
local called = false
local handle = src:putProgressAsync(identity, { chapter_idx = 1 }, function() called = true end)
Stubs.flush()
Assert.len(saves, 1)
Assert.eq(saves[1].pos.offset, 3, "同章保留 offset")
handle.cancel()
Assert.is_true(saves[1].cancelled, "取消没有传到保存请求")
saves[1].cb(true)
Assert.is_false(called, "取消后不能再回调")
saves = {}
end
+242
View File
@@ -0,0 +1,242 @@
--[[--
阅读 App 换 IP:网段枚举、书架回包、失败分类,以及非阻塞端口扫描。
@module tests.moonsource_legado.source_scan_spec
--]]
---@diagnostic disable: undefined-field, missing-fields
local Assert = require("support.assert")
local JSONStub = require("support.json_stub")
local Stubs = require("support.stubs")
package.loaded["json"] = { decode = JSONStub.decode, encode = JSONStub.encode }
local cfg = { server_address = "http://192.168.1.8:1122" }
package.loaded["utils.settings"] = {
getSource = function() return cfg end,
saveSource = function() end,
}
package.loaded["moonsource_legado.client"] = {
mode = function()
local base = cfg.server_address or ""
if base:find("/reader3", 1, true) then return "reader3" end
if base:find("/api/%d+$") then return "qread" end
return "app"
end,
base = function()
local addr = cfg.server_address
if type(addr) ~= "string" or addr == "" then return nil end
if not addr:match("^https?://") then addr = "http://" .. addr end
return (addr:gsub("/+$", ""))
end,
}
local tcp_count = 0
local now = 1000
local no_ip = false
local open_at = {}
local blackhole = {}
local immediate = false
local requests = {}
local function installNet()
package.loaded["socket"] = {
udp = function()
return {
setpeername = function()
if no_ip then return nil end
return 1
end,
getsockname = function() return "192.168.1.50", 1 end,
close = function() end,
}
end,
tcp = function()
tcp_count = tcp_count + 1
local sock = {}
function sock:settimeout() end
function sock:close() self.closed = true end
function sock:connect(host, port)
self.host, self.port = host, port
if self.tried then
if open_at[host] then return 1 end
return nil, "connection refused"
end
self.tried = true
if immediate then return 1 end
if open_at[host] or blackhole[host] then
self.open = open_at[host] == true
return nil, "timeout"
end
return nil, "connection refused"
end
return sock
end,
select = function(_recv, sendt)
local ready = {}
for _idx, sock in ipairs(sendt or {}) do
if sock.open then ready[#ready + 1] = sock end
end
if #ready == 0 then now = now + 1 end
return {}, ready
end,
gettime = function() return now end,
}
package.loaded["http.request"] = {
get = function(url, _opts, cb)
requests[#requests + 1] = url
local body = url:find("192.168.1.9:", 1, true)
and '{"isSuccess":true,"errorMsg":"","data":[{"bookUrl":"u"}]}'
or "<html>"
cb(body)
return { cancel = function() end }
end,
}
end
installNet()
package.loaded["moonsource_legado.scan"] = nil
local Scan = require("moonsource_legado.scan")
local function resetScan()
tcp_count = 0
now = 1000
no_ip = false
open_at = {}
blackhole = {}
immediate = false
requests = {}
cfg.server_address = "http://192.168.1.8:1122"
end
-- 网段:去掉自己和网络号 / 广播,254 - 1 = 253。
do
local hosts = Scan.hosts("192.168.1.50")
Assert.eq(#hosts, 253)
Assert.eq(hosts[1], "192.168.1.1")
Assert.eq(hosts[49], "192.168.1.49")
Assert.eq(hosts[50], "192.168.1.51")
Assert.eq(hosts[253], "192.168.1.254")
Assert.eq(#Scan.hosts("0.1.1.1"), 0)
Assert.eq(#Scan.hosts("999.1.1.1"), 0)
Assert.eq(#Scan.hosts("phone.lan"), 0)
end
-- 只有书架形状的回包算命中。
do
Assert.is_true(Scan.isShelf('{"isSuccess":true,"errorMsg":"","data":[]}'))
Assert.is_true(Scan.isShelf('{"isSuccess":true,"errorMsg":"","data":[{"bookUrl":"u"}]}'))
Assert.is_false(Scan.isShelf('{"isSuccess":true,"errorMsg":"","data":{"a":1}}'))
Assert.is_false(Scan.isShelf('{"isSuccess":true,"errorMsg":"","data":["x"]}'))
Assert.is_false(Scan.isShelf('{"isSuccess":false,"errorMsg":"x","data":[]}'))
Assert.is_false(Scan.isShelf('{"isSuccess":true,"data":[]}'))
Assert.is_false(Scan.isShelf("<html>"))
Assert.is_false(Scan.isShelf(nil))
end
-- 本机地址来自路由表。没有路由就扫不了。
do
resetScan()
Assert.eq(Scan.localIP(), "192.168.1.50")
no_ip = true
Assert.is_nil(Scan.localIP())
end
-- 一台端口通且回包是书架:只校验这一台。
do
resetScan()
open_at["192.168.1.9"] = true
local found, err
Scan.find(function(list, reason) found, err = list, reason end)
Stubs.flush()
Assert.is_nil(err)
Assert.len(found, 1)
Assert.eq(found[1], "http://192.168.1.9:1122")
Assert.len(requests, 1)
Assert.eq(requests[1], "http://192.168.1.9:1122/getBookshelf?refresh=0")
end
-- 保存的端口不是 1122 时,探测和结果都用这个端口。
do
resetScan()
cfg.server_address = "http://192.168.1.8:1234"
open_at["192.168.1.9"] = true
local found
Scan.find(function(list) found = list end)
Stubs.flush()
Assert.eq(found[1], "http://192.168.1.9:1234")
Assert.eq(requests[1], "http://192.168.1.9:1234/getBookshelf?refresh=0")
cfg.server_address = "http://192.168.1.8:1122"
end
-- 回包不像书架的端口丢掉。
do
resetScan()
open_at["192.168.1.10"] = true
open_at["192.168.1.9"] = true
package.loaded["http.request"].get = function(url, _opts, cb)
requests[#requests + 1] = url
local host = url:match("http://([^:]+)")
local body = host == "192.168.1.10"
and '<html>'
or '{"isSuccess":true,"errorMsg":"","data":[{"bookUrl":"u"}]}'
cb(body)
return { cancel = function() end }
end
local found
Scan.find(function(list) found = list end)
Stubs.flush()
Assert.len(found, 1)
Assert.eq(found[1], "http://192.168.1.9:1122")
end
-- 没有阅读服务。端口全通(多于 8 台)不当成结果,也不发 HTTP。
do
resetScan()
local found
Scan.find(function(list) found = list end)
Stubs.flush()
Assert.len(found, 0)
Assert.len(requests, 0)
resetScan()
immediate = true
Scan.find(function(list) found = list end)
Stubs.flush()
Assert.len(found, 0)
Assert.len(requests, 0)
end
-- 没路由:不探端口。
do
resetScan()
no_ip = true
local found, err
Scan.find(function(list, reason) found, err = list, reason end)
Stubs.flush()
Assert.is_nil(found)
Assert.eq(err, "no-ip")
Assert.eq(tcp_count, 0)
end
-- 取消后不再回调,也还没探端口。
do
resetScan()
local called = false
local handle = Scan.find(function() called = true end)
handle.cancel()
Stubs.flush()
Assert.is_false(called)
Assert.eq(tcp_count, 0)
end
-- 黑掉的地址等到超时就丢掉,不发 HTTP。
do
resetScan()
blackhole["192.168.1.9"] = true
local found
Scan.find(function(list) found = list end)
Stubs.flush()
Assert.len(found, 0)
Assert.len(requests, 0)
end
+402
View File
@@ -0,0 +1,402 @@
--[[--
阅读(Legado)Web 服务:地址归一、回包解码、请求形状与映射离线用例。
@module tests.moonsource_legado.source_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, redundant-parameter, missing-parameter, inject-field, assign-type-mismatch, param-type-mismatch, cast-type-mismatch, return-type-mismatch, cast-local-type
local Assert = require("support.assert")
local JSONStub = require("support.json_stub")
package.preload["json"] = function()
return { decode = JSONStub.decode, encode = JSONStub.encode }
end
local cfg = { server_address = "192.168.1.8:1122/" }
package.preload["utils.settings"] = function()
return { getSource = function() return cfg end }
end
local requests, replies = {}, {}
package.preload["http.request"] = function()
return {
get = function(url, opts, cb)
requests[#requests + 1] = { method = "GET", url = url, opts = opts }
cb(table.remove(replies, 1))
return { cancel = function() end }
end,
post = function(url, body, opts, cb)
requests[#requests + 1] = { method = "POST", url = url, body = body, opts = opts }
cb(table.remove(replies, 1))
return { cancel = function() end }
end,
}
end
package.loaded["moonsource_legado.client"] = nil
package.loaded["moonsource_legado.mapper"] = nil
local Client = require("moonsource_legado.client")
local Mapper = require("moonsource_legado.mapper")
-- 地址缺协议头补 http、去尾斜杠;没配置为 nil。
do
Assert.eq(Client.base(), "http://192.168.1.8:1122")
cfg.server_address = "https://legado.lan:1122"
Assert.eq(Client.base(), "https://legado.lan:1122")
cfg.server_address = ""
Assert.is_nil(Client.base())
cfg.server_address = "http://h:1122"
end
-- 书架:GET /getBookshelf,isSuccess=false 带出 errorMsg。
do
replies = { '{"isSuccess":true,"errorMsg":"","data":[{"bookUrl":"u1"}]}' }
local rows, err
Client.shelfAsync(function(v, e) rows, err = v, e end)
Assert.is_nil(err)
Assert.len(rows, 1)
Assert.matches(requests[1].url, "^http://h:1122/getBookshelf%?refresh=0$")
replies = { '{"isSuccess":false,"errorMsg":"没有权限","data":null}' }
rows, err = nil, nil
Client.shelfAsync(function(v, e) rows, err = v, e end)
Assert.is_nil(rows)
Assert.eq(err, "没有权限")
replies = { "<html>" }
Client.shelfAsync(function(v, e) rows, err = v, e end)
Assert.eq(err, "响应无效")
end
-- 校验新库使用显式配置:地址与登录凭据不落盘,也不替换当前配置。
do
requests = {}
replies = {
'{"isSuccess":true,"data":{"accessToken":"probe-token"}}',
'{"isSuccess":true,"data":[{"bookUrl":"probe-book"}]}',
}
local rows, err
Client.shelfAsync(function(value, reason) rows, err = value, reason end, {
server_address = "https://probe.test/reader3", username = "probe-user", password = "probe-password",
})
Assert.is_nil(err)
Assert.eq(rows[1].bookUrl, "probe-book")
Assert.matches(requests[1].url, "^https://probe.test/reader3/login$")
Assert.matches(requests[1].body, '"username":"probe%-user"')
Assert.matches(requests[2].url, "^https://probe.test/reader3/getBookshelf%?")
Assert.matches(requests[2].url, "accessToken=probe%-token")
Assert.eq(Client.base(), "http://h:1122", "探测新库时当前客户端仍读旧库配置")
requests, replies = {}, { '{"isSuccess":true,"data":[]}' }
Client.shelfAsync(function() end)
Assert.matches(requests[1].url, "^http://h:1122/getBookshelf%?")
Assert.is_nil(requests[1].url:find("probe%-token"), "探测令牌不能污染旧库请求")
end
-- 正文:index 0 基、url 编码;空正文报错。
do
requests = {}
replies = { '{"isSuccess":true,"data":"第一段\\n第二段"}' }
local text
Client.contentAsync("https://a.b/c?d=1", 3, nil, function(v) text = v end)
Assert.eq(text, "第一段\n第二段")
Assert.matches(requests[1].url, "/getBookContent%?")
Assert.matches(requests[1].url, "index=3")
Assert.matches(requests[1].url, "url=https%%3A%%2F%%2Fa%.b%%2Fc%%3Fd%%3D1")
replies = { '{"isSuccess":true,"data":""}' }
local err
Client.contentAsync("u", 0, nil, function(_, e) err = e end)
Assert.eq(err, "阅读章节内容为空 #1")
end
-- 进度上报:JSON 体带 0 基章序号。
do
requests = {}
replies = { '{"isSuccess":true,"data":""}' }
local ok
Client.saveProgressAsync({ name = "书", author = "作者", bookUrl = "u1" },
{ index = 4, title = "第5章", offset = 12 }, function(v) ok = v end)
Assert.is_true(ok)
Assert.eq(requests[1].method, "POST")
Assert.matches(requests[1].url, "/saveBookProgress$")
Assert.eq(requests[1].opts.content_type, "application/json")
Assert.matches(requests[1].body, '"durChapterIndex":4')
Assert.matches(requests[1].body, '"url":"u1"')
end
-- 正文夹 <img>:真图留成标签、svg 懒加载占位丢弃、src 尾部请求头剥掉,其余文字照旧转义
do
local html = Mapper.chapterHtml("章", 'a<b>\n<img src="data:image/svg+xml;base64,PHN2Zy8+">\n'
.. '<img src="http://h/x.jpg?a=1&amp;b=2,{&quot;h&quot;:1}" alt="x">', function(src) return src end)
Assert.eq(html, '<h1>章</h1>\n<p>a&lt;b&gt;</p>\n<p><img src="http://h/x.jpg?a=1&amp;b=2"/></p>')
end
-- 映射:bookUrl 是身份,封面走 /cover 代理,自定义封面优先;没有 bookUrl 的行丢弃。
do
local books = Mapper.shelfList(function(path) return "http://h:1122/cover?path=" .. require("utils.text").urlEncode(path) end, {
{ bookUrl = "u1", name = "书", author = "作者", coverUrl = "http://img/a.jpg", kind = "玄幻", durChapterTime = 1700000000000 },
{ bookUrl = "u2", name = "二", customCoverUrl = "/local/b.jpg", coverUrl = "x" },
{ name = "无地址" },
})
Assert.len(books, 2)
Assert.eq(books[1].stable_id, "u1")
Assert.eq(books[1].cover, "http://h:1122/cover?path=http%3A%2F%2Fimg%2Fa.jpg")
Assert.eq(books[1].category, "玄幻")
Assert.eq(books[1].read_at, 1700000000)
Assert.is_true(books[1].inserted_at > books[2].inserted_at)
Assert.eq(books[2].cover, "http://h:1122/cover?path=%2Flocal%2Fb.jpg")
end
-- 有书架分组时分类取分组名(位掩码,可多组;没分组=未分类且权威),不再用网站抓来的 kind。
do
local rows = {
{ bookUrl = "a", kind = "玄幻", group = 5 },
{ bookUrl = "b", kind = "玄幻", group = 0 },
}
rows.groups = { { groupId = -1, groupName = "全部" }, { groupId = 1, groupName = "追更" },
{ groupId = 2, groupName = "完结" }, { groupId = 4, groupName = "收藏" } }
local books = Mapper.shelfList(function(p) return p end, rows)
Assert.eq(books[1].category, "追更,收藏")
Assert.is_nil(books[2].category)
Assert.is_true(books[2].category_authoritative)
end
-- 阅读位置与目录:durChapterIndex 0 基;没读过为 nil;目录 uid 是 0 基序号。
do
local pos = Mapper.readPos({ durChapterIndex = 2, durChapterPos = 30, durChapterTitle = "第3章", durChapterTime = 1 })
Assert.eq(pos.index, 2)
Assert.eq(pos.offset, 30)
Assert.eq(pos.title, "第3章")
Assert.is_nil(Mapper.readPos({ durChapterIndex = 0, durChapterTime = 0 }))
Assert.is_nil(Mapper.readPos(nil))
local toc = Mapper.toc({ { index = 0, title = "序" }, { index = 1, title = "一" } })
Assert.eq(toc[2].idx, 2)
Assert.eq(toc[2].uid, "1")
end
-- reader3:配了账号密码先 POST /login 取 accessToken,请求带上;令牌过期(NEED_LOGIN)重登一次。
do
cfg.server_address, cfg.username, cfg.password = "http://h:8080/reader3", "u", "p"
requests = {}
replies = {
'{"isSuccess":true,"data":{"accessToken":"T1"}}',
'{"isSuccess":true,"data":[{"bookUrl":"u1"}]}',
'{"isSuccess":false,"errorMsg":"NEED_LOGIN","data":"NEED_LOGIN"}',
'{"isSuccess":true,"data":{"accessToken":"T2"}}',
'{"isSuccess":true,"data":[]}',
}
local rows
Client.shelfAsync(function(v) rows = v end)
Assert.len(rows, 1)
Assert.matches(requests[1].url, "^http://h:8080/reader3/login$")
Assert.matches(requests[1].body, '"username":"u"')
Assert.matches(requests[2].url, "/reader3/getBookshelf%?.*accessToken=T1")
Assert.matches(Client.coverUrl("x"), "accessToken=T1")
Client.shelfAsync(function(v) rows = v end)
Assert.len(rows, 0)
Assert.matches(requests[5].url, "accessToken=T2")
cfg.username, cfg.password = nil, nil
end
-- reader3:相对图片 / 封面补成服务根 + accessToken;章节与正文走 POST JSON。
do
cfg.server_address, cfg.username, cfg.password = "http://h:8080/reader3", "u", "p"
Assert.eq(Client.mode(), "reader3")
Assert.eq(Client.imageUrl("__API_ROOT__/book-assets/a b.png"), "http://h:8080/book-assets/a b.png?accessToken=T2")
Assert.eq(Client.imageUrl("https://x/y.jpg"), "https://x/y.jpg")
local resource = "http://h:8080/proxy/book-assets/Text/chapter.xhtml?accessToken=T2"
Assert.eq(Client.imageUrl("../Images/cover%20one.png", resource),
"http://h:8080/proxy/book-assets/Images/cover%20one.png?accessToken=T2")
Assert.eq(Client.imageUrl("../Images/cover.png?v=1#cover", resource),
"http://h:8080/proxy/book-assets/Images/cover.png?v=1&accessToken=T2#cover")
Assert.eq(Client.imageUrl("//cdn.example/cover.png", resource), "http://cdn.example/cover.png")
Assert.eq(Client.imageUrl("data:image/png;base64,AAAA", resource), "data:image/png;base64,AAAA")
requests = {}
replies = { '{"isSuccess":true,"data":[{"index":0,"title":"序"}]}' }
local rows
Client.chaptersAsync("bu", nil, function(v) rows = v end)
Assert.len(rows, 1)
Assert.eq(requests[1].method, "POST")
Assert.matches(requests[1].url, "/reader3/getChapterList%?accessToken=T2$")
Assert.matches(requests[1].body, '"url":"bu"')
-- 重登仍失败:标记登录失效,给人看的中文说明(放在复用 T2 的用例之后)。
local Auth = require("source.auth")
Auth.reset()
requests, replies = {}, {
'{"isSuccess":false,"errorMsg":"NEED_LOGIN","data":"NEED_LOGIN"}',
'{"isSuccess":false,"errorMsg":"bad password"}',
}
local err
Client.shelfAsync(function(_v, e) err = e end)
Assert.matches(err, "阅读服务地址")
Assert.is_true(Auth.expired("legado"))
Auth.reset()
cfg.username, cfg.password = nil, nil
end
-- EPUB 正文不靠 <p> 判空;保留实体文本、转换 SVG、规范化图片属性及 URL。
do
local base = "http://h/book-assets/Text/chapter.xhtml"
local function imageUrl(src, document_url) return require("utils.text").absoluteUrl(document_url, src) end
local html = Mapper.assetHtml("章", '<?xml version="1.0"?><html><head><title>壳</title></head>'
.. '<body><style>p{color:red}</style><script>alert(1)</script><div>&amp;</div></body></html>', base, imageUrl)
Assert.eq(html, "<h1>章</h1>\n<div>&amp;</div>")
Assert.is_nil(Mapper.assetHtml("只有标题", "<body><div>&nbsp; &#160;</div></body>", base, imageUrl))
html = Mapper.assetHtml("图", '<body><svg><image xlink:href="../Images/封 面%20图.png"/></svg>'
.. "<img src = '../Images/a.png?a=1&amp;b=2'/></body>", base, imageUrl)
Assert.matches(html, 'src="http://h/book%-assets/Images/%%E5%%B0%%81%%20%%E9%%9D%%A2%%20%%E5%%9B%%BE%.png"')
Assert.matches(html, 'src="http://h/book%-assets/Images/a%.png%?a=1&amp;b=2"')
Assert.is_nil(html:find("<svg", 1, true))
end
-- 轻阅读:/api/N 后缀;表单 POST,登录带 model=web,目录 / 正文带书源,正文回包是 { text }。
do
cfg.server_address, cfg.username, cfg.password = "http://h:1122/api/5", "u", "p"
Assert.eq(Client.mode(), "qread")
requests = {}
replies = {
'{"isSuccess":true,"data":{"accessToken":"Q1"}}',
'{"isSuccess":true,"data":[{"bookUrl":"u1","origin":"src1"}]}',
'{"isSuccess":true,"data":{"rules":{},"text":"正文"}}',
'{"isSuccess":true,"data":""}',
}
local rows, text, ok
Client.shelfAsync(function(v) rows = v end)
Assert.eq(rows[1].origin, "src1")
Assert.eq(requests[1].opts.content_type, "application/x-www-form-urlencoded")
Assert.matches(requests[1].body, "model=web")
Assert.matches(requests[2].url, "/api/5/getBookshelf%?accessToken=Q1$")
Assert.eq(requests[2].body, "version=3.2.1")
Client.contentAsync("u1", 2, "src1", function(v) text = v end)
Assert.eq(text, "正文")
Assert.matches(requests[3].body, "bookSourceUrl=src1")
Assert.matches(requests[3].body, "index=2")
Client.saveProgressAsync({ bookUrl = "u1" }, { index = 2, title = "T", offset = 5 }, function(v) ok = v end)
Assert.is_true(ok)
Assert.eq(requests[4].body, "index=2&pos=5&title=T&url=u1")
Assert.eq(Client.imageUrl("baseurl/proxypng?url=a"), "http://h:1122/api/5/proxypng?url=a&accessToken=Q1")
Assert.eq(Client.coverUrl("/c.jpg"), "http://h:1122/api/5/proxypng?url=%2Fc.jpg&accessToken=Q1")
cfg.server_address, cfg.username, cfg.password = "http://h:1122", nil, nil
end
-- 地址是连接位置,不是书籍身份:换 IP / 清空后重连保留进度,换账号仍走清库边界。
do
local Themed = require("support.theme_stubs")
local ProgressDB = require("book.progress_db")
local stable_id = "legado-address-progress-spec"
assert(ProgressDB.upsert("legado", stable_id, { fraction = 0.63, chapter_idx = 8 }))
assert(ProgressDB.setDecisionPending("legado", stable_id, true))
Themed.install()
package.loaded["ui.themes.widgets.row"] = { widget = function(opts) return opts end }
cfg = { server_address = "http://old/reader3", username = "old-user", password = "old-password" }
local saved, reloaded, cleaned, aborted, cleanup_ok = 0, 0, 0, 0, true
package.loaded["utils.settings"] = {
getSource = function() return cfg end,
saveSource = function() saved = saved + 1 end,
}
package.loaded["source.registry"] = { reload = function() reloaded = reloaded + 1 end }
package.loaded["source.logout"] = {
row = require("source.logout").row,
abort = function(id)
Assert.eq(id, "legado")
aborted = aborted + 1
end,
replaceLibrary = function(_id, commit)
cleaned = cleaned + 1
if not cleanup_ok then return false end
commit()
require("source.registry").reload()
return true
end,
}
package.loaded["ui/network/manager"] = { runWhenConnected = function(_self, fn) fn() end }
local pending, candidate
local shelf = Client.shelfAsync
Client.shelfAsync = function(cb, settings)
pending, candidate = cb, settings
return { cancel = function() end }
end
local Setting = require("moonsource_legado.setting")
Setting.rows()[1](300).callback()
Themed.last("input").callback("http://new/reader3", "old-user", "old-password")
Assert.eq(candidate.server_address, "http://new/reader3")
Assert.eq(candidate.username, "old-user")
Assert.eq(cfg.server_address, "http://old/reader3", "校验期间当前源仍握着旧库")
Assert.eq(saved, 0)
pending(nil, "network failed")
Assert.eq(cfg.server_address, "http://old/reader3")
Assert.eq(saved, 0)
Assert.eq(reloaded, 0)
Assert.eq(Themed.last("toast").text, "network failed")
Setting.rows()[1](300).callback()
Themed.last("input").callback("http://new/reader3", "old-user", "old-password")
pending({ { bookUrl = stable_id } })
local progress = ProgressDB.get("legado", stable_id)
Assert.is_true(progress ~= nil, "更换地址不能删除阅读进度")
Assert.eq(progress.chapter_idx, 8)
Assert.eq(progress.fraction, 0.63)
Assert.eq(progress.sync_status, 0)
Assert.eq(progress.decision_pending, 1)
Assert.eq(cfg.server_address, "http://new/reader3")
Assert.eq(saved, 1)
Assert.eq(reloaded, 1)
Assert.eq(cleaned, 0)
Assert.eq(aborted, 1)
-- 先清空旧地址再填新地址也不是登出,不能在这一步清掉数据或账号身份。
Setting.rows()[1](300).callback()
Themed.last("input").callback("", "", "")
Assert.is_nil(cfg.server_address)
Assert.eq(cfg.username, "old-user")
Assert.eq(cfg.password, "old-password")
Assert.eq(ProgressDB.get("legado", stable_id).chapter_idx, 8)
Assert.eq(cleaned, 0)
Assert.eq(aborted, 2)
-- 局域网扫描同样走保存地址流程;重新找到服务后继续用原账号与进度。
package.loaded["moonsource_legado.scan"] = {
find = function(cb)
cb({ "http://lan/reader3" })
return { cancel = function() end }
end,
}
Setting.rows()[2](300).callback()
Assert.eq(candidate.username, "old-user")
pending({ { bookUrl = stable_id } })
Assert.eq(cfg.server_address, "http://lan/reader3")
Assert.eq(ProgressDB.get("legado", stable_id).chapter_idx, 8)
Assert.eq(cleaned, 0)
-- 换账号只准备同步;准备失败不能提交新账号,也不能删除进度。
saved, reloaded, cleanup_ok = 0, 0, false
Setting.rows()[1](300).callback()
Themed.last("input").callback("http://new/reader3", "new-user", "new-password")
pending({ { bookUrl = "new-book" } })
Assert.eq(cfg.server_address, "http://lan/reader3")
Assert.eq(cfg.username, "old-user")
Assert.eq(saved, 0)
Assert.eq(reloaded, 0)
Assert.eq(Themed.last("toast").text, "准备本地同步失败")
Assert.eq(ProgressDB.get("legado", stable_id).chapter_idx, 8)
cleanup_ok = true
Setting.rows()[1](300).callback()
Themed.last("input").callback("http://new/reader3", "new-user", "new-password")
pending({ { bookUrl = "new-book" } })
Assert.eq(cfg.server_address, "http://new/reader3")
Assert.eq(cfg.username, "new-user")
Assert.eq(saved, 1)
Assert.eq(reloaded, 1)
Assert.eq(ProgressDB.get("legado", stable_id).chapter_idx, 8)
Assert.eq(ProgressDB.get("legado", stable_id).fraction, 0.63)
Assert.eq(ProgressDB.get("legado", stable_id).decision_pending, 1)
Client.shelfAsync = shelf
end
+245
View File
@@ -0,0 +1,245 @@
--[[--
阅读 App 段评:真实客户端回包、源接口、离线缓存与段落定位。
@module tests.moonsource_legado.reviews_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch, inject-field, assign-type-mismatch
local Assert = require("support.assert")
local Stubs = require("support.stubs")
local JSON = require("support.json_stub")
Stubs.install()
local cfg = { server_address = "http://legado.example:1122" }
local connected, delayed_toc, toc_callback, toc_cancelled = true, false, nil, false
local requests = {}
package.preload["json"] = function() return { encode = JSON.encode, decode = JSON.decode } end
package.preload["utils.settings"] = function()
return { getSource = function() return cfg end, saveSource = function() end }
end
package.preload["ui/network/manager"] = function()
return { isConnected = function() return connected end,
isOnline = function() error("不能用同步 DNS 检查联网") end }
end
package.preload["http.request"] = function()
return {
get = function(url, _opts, cb)
local request = { url = url, cb = cb, cancelled = false }
requests[#requests + 1] = request
return { cancel = function() request.cancelled = true end }
end,
post = function() error("阅读 App 段评必须 GET") end,
}
end
for _idx, name in ipairs({ "json", "utils.settings", "ui/network/manager", "http.request",
"moonsource_legado.source", "moonsource_legado.client", "moonsource_legado.mapper", "moonsource_legado.reviews", "book.review_cache" }) do
package.loaded[name] = nil
end
local Client = require("moonsource_legado.client")
local Reviews = require("moonsource_legado.reviews")
local Mapper = require("moonsource_legado.mapper")
local Cache = require("book.review_cache")
local source = require("moonsource_legado.source").new()
local identity = { source_id = "legado", stable_id = "https://books.example/a?b=1&c=2", chapter_idx = 2 }
Cache.removeIdentity(identity.source_id, identity.stable_id)
function source:loadTocAsync(_identity, cb)
if delayed_toc then toc_callback = cb else cb({ {}, { uid = "7", title = "章" } }) end
return { cancel = function() toc_cancelled = true end }
end
local function answer(data, err)
requests[#requests].cb(data and JSON.encode({ isSuccess = true, data = data }), err)
end
local summary = { counts = { ["-1"] = 4, ["0"] = 9, ["1"] = 5, ["3"] = 2, ["8"] = 0 },
keys = { ["1"] = 'key&中文:"\n', ["3"] = "other" } }
local value, reason
local function receive(data, err) value, reason = data, err end
-- 开关默认关闭;reader3 / 轻阅读不宣称支持 Android App 的专用接口。
Assert.is_false(source:paragraphReviewsEnabled())
require("source.review_setting").set("legado", true)
Assert.is_true(source:paragraphReviewsEnabled())
for _idx, address in ipairs({ "http://legado.example/reader3", "http://legado.example/api/5" }) do
cfg.server_address = address
Assert.is_false(source:paragraphReviewsEnabled())
Client.reviewSummaryAsync(identity.stable_id, 7, receive)
Stubs.flush()
Assert.is_nil(value)
Assert.eq(reason, "段评仅支持阅读 App 的 Web 服务")
Assert.len(requests, 0)
end
cfg.server_address = "http://legado.example:1122"
-- 请求使用目录 uid(7),不是月读的章序号(2)减一;摘要标识原样保留。
source:paragraphHotspotsAsync(identity, receive)
Assert.matches(requests[1].url, "/getReviewSummary%?")
Assert.matches(requests[1].url, "index=7")
Assert.matches(requests[1].url, "url=https%%3A%%2F%%2Fbooks%.example%%2Fa%%3Fb%%3D1%%26c%%3D2")
answer(summary)
Assert.is_nil(reason)
Assert.len(value, 2)
local hotspots = value
Assert.eq(hotspots[1].paragraph, 1)
Assert.eq(Reviews.context(hotspots[1].range)[2], summary.keys["1"])
Assert.eq(hotspots[2].paragraph, 3)
-- 图片段占段号;开头空段、连续换行、被丢弃的 SVG 占位也不能导致后文错位。
local html = Mapper.chapterHtml("章", '第一段原文。\n<img src="https://images.example/p.png">\n第三段原文。',
function(src) return src end, true)
Assert.matches(html, 'id="moon%-legado%-paragraph%-2"><img')
local spots = source:locateHotspots(hotspots, html)
Assert.len(spots, 2)
Assert.eq(spots[2].text, "第三段原文。")
Assert.eq(spots[2].range, hotspots[2].range)
local marked = Mapper.chapterHtml("章", '\n首段。\n\n<img src="data:image/svg+xml;base64,x">\n后段。',
function(src) return src end, true)
Assert.matches(marked, 'id="moon%-legado%-paragraph%-2">首段。')
Assert.matches(marked, 'id="moon%-legado%-paragraph%-4">后段。')
Assert.is_nil(marked:find("\2", 1, true))
Assert.len(source:locateHotspots(hotspots, "<h1>旧缓存</h1><p>未编号正文</p>"), 0,
"旧缓存不能靠猜测段序把评论挂错段")
source:chapterReviewHotspotsAsync(identity, receive)
answer(summary)
Assert.len(value, 1)
Assert.eq(Reviews.context(value[1].range)[1], -1)
Assert.eq(value[1].total, 4)
Assert.eq(value[1].anchor, require("book.review_locate").CHAPTER_ANCHOR)
-- 正文与回复的 id 是不透明字符串,大整数及同一段的 paraData 不得丢失。
source:paragraphReviewPageAsync(identity, hotspots[1].range, 0, receive)
Assert.matches(requests[#requests].url, "/getReviewDetail%?")
Assert.matches(requests[#requests].url, "page=1")
Assert.matches(requests[#requests].url, "paraIndex=1")
Assert.matches(requests[#requests].url, "paraData=key%%26%%E4%%B8%%AD%%E6%%96%%87%%3A%%22%%0A")
local original_id = "18446744073709551617"
answer({ items = { { id = original_id, name = "作者", content = "<b>评论 &amp; 内容</b>",
time = "2026-11-13", likeCount = 7, replyCount = 9, imageUrl = "https://images.example/comment.png" } },
hasMore = true, nextCursor = "cursor&%" })
Assert.is_nil(reason)
local first_page = value
Assert.eq(first_page.items[1].content, "评论 & 内容")
Assert.eq(first_page.items[1].author, "作者")
Assert.eq(first_page.items[1].likes, 7)
Assert.eq(first_page.items[1].replies, 9)
Assert.eq(first_page.items[1].images[1].url, "https://images.example/comment.png")
Assert.eq(Reviews.context(first_page.items[1].id, true)[3], original_id)
Assert.is_nil(first_page.total, "接口没给总数,不能伪造成本页条数")
Assert.is_true(first_page.more)
source:paragraphReviewPageAsync(identity, hotspots[1].range, first_page.max_idx, receive)
Assert.matches(requests[#requests].url, "page=2")
Assert.matches(requests[#requests].url, "cursor=cursor%%26%%25")
answer({ items = {}, hasMore = false })
Assert.is_false(value.more)
Assert.eq(value.total, 0)
source:paragraphReviewRepliesAsync(identity, first_page.items[1].id, 0, receive)
Assert.matches(requests[#requests].url, "/getReviewReplies%?")
Assert.matches(requests[#requests].url, "reviewId=" .. original_id)
Assert.matches(requests[#requests].url, "paraIndex=1")
answer({ items = { { id = "reply", name = "乙", content = "回复", replyToName = "丙" } }, hasMore = true })
local replies_page = value
Assert.eq(value.items[1].reply_to, "丙")
source:paragraphReviewRepliesAsync(identity, first_page.items[1].id, replies_page.max_idx, receive)
Assert.matches(requests[#requests].url, "page=2")
answer({ items = {}, hasMore = false })
-- JS 书源的更多页只有 page 信号,没有 cursor,同样按递增页号续拉。
local js_page = Reviews.page({ items = { { id = "js", content = "评论" } }, hasMore = true },
Reviews.context(hotspots[1].range), 1)
local page, cursor = Reviews.pagination(js_page.max_idx)
Assert.eq(page, 2)
Assert.is_nil(cursor)
Assert.is_true(js_page.more)
Assert.eq(Reviews.page({ items = { { content = "没有 ID", replyCount = 3 } }, hasMore = false },
Reviews.context(hotspots[1].range), 1).items[1].replies, 0)
-- HTTP 200 的业务失败及损坏回包不能变成空评论成功,也不能清掉旧缓存。
source:paragraphHotspotsAsync(identity, receive)
requests[#requests].cb('{"isSuccess":false,"errorMsg":"段评规则未配置"}')
Assert.is_nil(value)
Assert.eq(reason, "段评规则未配置")
source:paragraphHotspotsAsync(identity, receive)
requests[#requests].cb("<html>old app</html>")
Assert.is_nil(value)
Assert.eq(reason, "响应无效")
Assert.is_nil(Reviews.hotspots({ counts = {} }))
Assert.is_nil(Reviews.hotspots({ counts = { ["x"] = 1 }, keys = {} }))
Assert.is_nil(Reviews.page({ items = {}, hasMore = "yes" }, {}, 1))
Assert.is_nil(Reviews.page({ items = { bad = {} }, hasMore = false }, {}, 1))
-- 离线只保留首页评论已缓存的标记;正文页和回复均可从缓存读取,不发网络。
connected = false
local count = #requests
source:paragraphHotspotsAsync(identity, receive)
Stubs.flush()
Assert.is_nil(reason)
Assert.len(value, 1)
Assert.eq(value[1].range, hotspots[1].range)
source:paragraphReviewPageAsync(identity, hotspots[1].range, 0, receive)
Stubs.flush()
Assert.eq(value.items[1].author, "作者")
source:paragraphReviewRepliesAsync(identity, first_page.items[1].id, 0, receive)
Stubs.flush()
Assert.eq(value.items[1].content, "回复")
Assert.len(requests, count)
local missing = { source_id = "legado", stable_id = "legado-review-no-cache", chapter_idx = 2 }
Cache.removeIdentity(missing.source_id, missing.stable_id)
source:paragraphHotspotsAsync(missing, receive)
Stubs.flush()
Assert.is_nil(value)
Assert.eq(reason, "未联网,无法加载段评")
Assert.len(requests, count)
-- 请求阶段和目录阶段都可取消;迟到响应不得写缓存或启动后续请求。
connected = true
local calls = 0
local job = source:paragraphHotspotsAsync(missing, function() calls = calls + 1 end)
job.cancel()
Assert.is_true(requests[#requests].cancelled)
answer(summary)
Assert.eq(calls, 0)
Assert.is_nil(Cache.hotspots(missing))
delayed_toc, toc_cancelled = true, false
count = #requests
job = source:paragraphHotspotsAsync(missing, function() calls = calls + 1 end)
job.cancel()
Assert.is_true(toc_cancelled)
toc_callback({ {}, { uid = "7" } })
Assert.len(requests, count)
Assert.eq(calls, 0)
source:paragraphReviewPageAsync(identity, "broken", 0, receive)
Stubs.flush()
Assert.is_nil(value)
Assert.eq(reason, "阅读段评位置无效")
source:paragraphReviewPageAsync(identity, hotspots[1].range, "broken", receive)
Stubs.flush()
Assert.is_nil(value)
Assert.eq(reason, "阅读段评分页位置无效")
-- 源的真实正文路径保留段号并预留章评入口;关闭段评也保留段号,以便以后就地开启。
delayed_toc = false
package.loaded["source.chapter"] = nil
package.preload["source.chapter"] = function()
return {
openAsync = function(_source, ref, _book, _opts, ops, cb)
Assert.eq(type(ops.reuse), "function")
return ops.fetchContent(ref, { uid = "7", title = "章" }, cb)
end,
prefetchAsync = function(ref, _book, _toc, _from, _count, ops, cb)
Assert.is_nil(ops.reuse)
return ops.fetchContent(ref, { uid = "7", title = "章" }, cb)
end,
}
end
source:openBookAsync(identity, { chapter_idx = 2 }, receive)
answer("一段。\n二段。")
Assert.matches(value.html, 'id="moon%-legado%-paragraph%-2">二段。')
Assert.matches(value.html, 'id="moon%-chapter%-reviews"')
cfg.show_paragraph_reviews = false
source:prefetchChaptersAsync(identity, {}, 2, 1, receive)
answer("一段。\n二段。")
Assert.matches(value.html, 'id="moon%-legado%-paragraph%-2">二段。')
Assert.is_nil(value.html:find("moon-chapter-reviews", 1, true))
Cache.removeIdentity(identity.source_id, identity.stable_id)
Cache.removeIdentity(missing.source_id, missing.stable_id)