✨ 初始提交:月读第三方书源插件集合
每个书源一个独立插件目录,含微信读书公众号订阅、书架导入等完整功能。 Co-authored-by: Copilot <[email protected]>
This commit is contained in:
commit
ed44254f1c
54 files changed
+15615
No files matched your search
@@ -0,0 +1,69 @@
|
||||
--[[--
|
||||
moonsource_weread.app 离线用例:签名对照官方 App 抓包,小时分桶。
|
||||
|
||||
@module tests.wechat.app_spec
|
||||
--]]
|
||||
---@diagnostic disable: undefined-field
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local App = require("moonsource_weread.app")
|
||||
|
||||
-- HAR 里官方 App 的一条 /book/read:同样的输入必须得到同样的 signature。
|
||||
local payload = table.concat({
|
||||
"393727764", "35645832171399234841676621530100678335", "35645832171399234841676621530100678335",
|
||||
"CB_00K1XI1aSDlZ76f75hG9n7JG", "0", "+08:00", "81", "0",
|
||||
}, "_") .. "_1792317600_+08:00_81_0"
|
||||
Assert.eq(
|
||||
App.sign({ "5ecdcfd7f", "821", "1792318161", payload }),
|
||||
"dfd6f2ceb1e4a5d1152c6d19fd9c9f84115cad69989ee799faec377d05d8a833"
|
||||
)
|
||||
|
||||
-- 跨整点的区间拆进两个小时桶,按整点升序。
|
||||
local hours = App.hours({
|
||||
{ start_time = 7300, duration = 10 },
|
||||
{ start_time = 3590, duration = 20 },
|
||||
}, "+08:00")
|
||||
Assert.len(hours, 3)
|
||||
Assert.eq(hours[1].startOfHour, 0)
|
||||
Assert.eq(hours[1].readingTime, 10)
|
||||
Assert.eq(hours[2].startOfHour, 3600)
|
||||
Assert.eq(hours[2].readingTime, 10)
|
||||
Assert.eq(hours[3].startOfHour, 7200)
|
||||
Assert.eq(hours[3].readingTime, 10)
|
||||
|
||||
-- 离线批量的外层签名是 sha256(timestamp + token + random),不是单本 guest 签名。
|
||||
local sha256 = require("ffi/sha2").sha256
|
||||
local batch = App.batchBody({ { bookId = "1" } }, "trouble")
|
||||
Assert.eq(batch.books[1].bookId, "1")
|
||||
Assert.eq(batch.recordCreateTimeZone, App.timeZone())
|
||||
Assert.eq(batch.signature, sha256(tostring(batch.timestamp) .. "trouble" .. tostring(batch.random)))
|
||||
|
||||
-- 没有小时桶时 payload 以 _ 结尾,和 App generatePayLoad 一致。有小时桶时这个 _ 就是分隔符,不能再多一个。
|
||||
local old_time, old_random = os.time, math.random
|
||||
os.time = function() return 1700000000 end
|
||||
math.random = function() return 7 end
|
||||
local empty = App.readBody({
|
||||
vid = "1", device_id = "d", install_id = "i", guest_token = "gt",
|
||||
book_id = "b", chapter_uid = 1, chapter_idx = 1, chapter_offset = 0,
|
||||
chapter_progress = 0, current_progress = 0, progress = 0, hours = {},
|
||||
})
|
||||
local empty_payload = table.concat({ "1", "d", "d", "b", "0", App.timeZone(), "0", "0" }, "_") .. "_"
|
||||
Assert.eq(empty.signature, App.sign({ "gt", "7", "1700000000", empty_payload }))
|
||||
Assert.is_nil(empty.readUpdateTime)
|
||||
Assert.is_nil(empty.isResendReadingInfo)
|
||||
local spanned = App.readBody({
|
||||
vid = "1", device_id = "d", install_id = "i", guest_token = "gt",
|
||||
book_id = "b", chapter_uid = 1, chapter_idx = 1, chapter_offset = 0,
|
||||
chapter_progress = 0, current_progress = 40, progress = 99,
|
||||
hours = { { startOfHour = 3600, readingTime = 5, timeZone = "+08:00", ttsTime = 0 } },
|
||||
resend = 1, read_update = 1699990000,
|
||||
})
|
||||
local spanned_payload = table.concat({
|
||||
"1", "d", "d", "b", "0", App.timeZone(), "5", "0", "3600", "+08:00", "5", "0",
|
||||
}, "_")
|
||||
Assert.eq(spanned.signature, App.sign({ "gt", "7", "1700000000", spanned_payload }))
|
||||
Assert.eq(spanned.progress, 99)
|
||||
Assert.eq(spanned.currentProgress, 40)
|
||||
Assert.eq(spanned.readUpdateTime, 1699990000)
|
||||
Assert.eq(spanned.isResendReadingInfo, 1)
|
||||
os.time, math.random = old_time, old_random
|
||||
@@ -0,0 +1,236 @@
|
||||
--[[--
|
||||
moonsource_weread.assets 离线用例
|
||||
|
||||
@module tests.moonsource_weread.assets_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")
|
||||
|
||||
package.preload["moonsource_weread.assets"] = nil
|
||||
package.loaded["moonsource_weread.assets"] = nil
|
||||
package.preload["moonsource_weread.auth"] = nil
|
||||
package.loaded["moonsource_weread.auth"] = nil
|
||||
|
||||
local Assets = require("moonsource_weread.assets")
|
||||
|
||||
local function noStyle()
|
||||
error("不该拉样式表")
|
||||
end
|
||||
|
||||
do
|
||||
local html = '<img src="foo.jpg"/><img src="https://cdn/x.png?w=1"/>'
|
||||
local out = require("source.assets").rewriteImageSources(html, {
|
||||
["foo.jpg"] = "images/aaa.png",
|
||||
["https://cdn/x.png"] = "images/bbb.png",
|
||||
})
|
||||
Assert.matches(out, 'src="images/aaa.png"')
|
||||
Assert.matches(out, 'src="images/bbb.png"')
|
||||
end
|
||||
|
||||
local function tarHeader(name, size)
|
||||
local h = string.rep("\0", 512)
|
||||
local function poke(off, s)
|
||||
h = h:sub(1, off - 1) .. s .. h:sub(off + #s)
|
||||
end
|
||||
poke(1, name:sub(1, 100))
|
||||
poke(125, string.format("%011o", size))
|
||||
poke(157, "0")
|
||||
poke(258, "ustar\x00")
|
||||
poke(264, "00")
|
||||
local sum = 0
|
||||
for i = 1, 512 do
|
||||
sum = sum + h:byte(i)
|
||||
end
|
||||
poke(149, string.format("%06o\0 ", sum))
|
||||
return h
|
||||
end
|
||||
|
||||
local function makeTar(name, data)
|
||||
local padded = data .. string.rep("\0", (512 - (#data % 512)) % 512)
|
||||
return tarHeader(name, #data) .. padded .. string.rep("\0", 1024)
|
||||
end
|
||||
|
||||
do
|
||||
local png = "\137PNG\r\n\026\n" .. string.rep("x", 32)
|
||||
local tar = makeTar("pic.png", png)
|
||||
package.preload["moonsource_weread.auth"] = function()
|
||||
return {
|
||||
webGetAsync = function(url, _opts, cb)
|
||||
if url:find("/tar/", 1, true) then
|
||||
cb(tar)
|
||||
else
|
||||
cb(nil, "unexpected url")
|
||||
end
|
||||
end,
|
||||
}
|
||||
end
|
||||
package.loaded["moonsource_weread.auth"] = nil
|
||||
package.loaded["moonsource_weread.assets"] = nil
|
||||
Assets = require("moonsource_weread.assets")
|
||||
|
||||
local done, html_out = false, nil
|
||||
Assets.localizeAsync("book-1", {
|
||||
uid = "u1",
|
||||
tar = "/web/book/chapter/tar/abc",
|
||||
}, '<img src="pic.png"/>', "https://weread.qq.com/web/reader/1/u1", noStyle, function(html)
|
||||
done = true
|
||||
html_out = html
|
||||
end)
|
||||
Assert.is_true(done)
|
||||
Assert.matches(html_out, 'src="images/[0-9a-f]+%.png"')
|
||||
end
|
||||
|
||||
do
|
||||
local png = "\137PNG\r\n\026\n" .. string.rep("y", 16)
|
||||
local remote = "https://res.weread.qq.com/wrepub/CB_test.png"
|
||||
package.preload["moonsource_weread.auth"] = function()
|
||||
return {
|
||||
webGetAsync = function(url, opts, cb)
|
||||
Assert.eq(url, remote)
|
||||
Assert.is_true(opts.skip_auth_retry)
|
||||
Assert.is_true(opts.allow_redirects)
|
||||
Assert.eq(opts.headers["Referer"], "https://weread.qq.com/")
|
||||
cb(png)
|
||||
end,
|
||||
}
|
||||
end
|
||||
package.loaded["moonsource_weread.auth"] = nil
|
||||
package.loaded["moonsource_weread.assets"] = nil
|
||||
Assets = require("moonsource_weread.assets")
|
||||
|
||||
local sample = string.format(
|
||||
'<div class="bodyPic1"><img src="%s" data-w="720px"/></div>',
|
||||
remote
|
||||
)
|
||||
local done, html_out = false, nil
|
||||
Assets.localizeAsync("book-2", { uid = "u2" }, sample, "https://weread.qq.com/web/reader/2/u2", noStyle,
|
||||
function(html)
|
||||
done = true
|
||||
html_out = html
|
||||
end)
|
||||
Assert.is_true(done)
|
||||
Assert.matches(html_out, 'src="images/[0-9a-f]+%.png"')
|
||||
Assert.is_false(require("utils.text").hasRemoteImageSrc(html_out))
|
||||
end
|
||||
|
||||
-- 脚注图标 + 整书样式表:只改 src / href,其余字节原样;样式表每本书只拉一次。
|
||||
-- 拉不到时去掉坏相对 link,注入 .content 兜底缩进(否则段首顶格)。
|
||||
do
|
||||
local Paths = require("utils.paths")
|
||||
local work_dir = Paths.bookWorkDir("book-3", "ext.weread")
|
||||
os.remove(work_dir .. "/stylesheets.css")
|
||||
local head = '<?xml version="1.0"?><html><head><title></title>'
|
||||
local link = '<link href="../Styles/stylesheets.css" rel="stylesheet" type="text/css" />'
|
||||
local abs = '<link href="https://cdn/x.css" rel="stylesheet" />'
|
||||
local fix = "<style>h1 + h1, .moon-title h1 { page-break-before: avoid; }"
|
||||
.. " body.bgimg-1 { background-image: none; }"
|
||||
.. " .moon-title { background-image: url(images/bq.jpg); background-size: cover;"
|
||||
.. " background-position: center bottom; height: 90vh; padding-top: 30vh;"
|
||||
.. " page-break-before: always; page-break-after: always; }</style>"
|
||||
local fallback = "<style type=\"text/css\">"
|
||||
.. ".content,.content1{text-indent:2em;text-align:justify}"
|
||||
.. ".bold,.firstTitle,.secondTitle,.thirdTitle,.contentCR,.contentCR1,.contentCR2{text-indent:0}"
|
||||
.. "</style>"
|
||||
local body = '</head><body><p class="content">正文<img class="qqreader-footnote" alt="注文" '
|
||||
.. 'src="../Images/note.png" /></p></body></html>'
|
||||
local sample = head .. link .. abs .. body
|
||||
|
||||
local fetches = 0
|
||||
local function fetchStyle(css)
|
||||
return function(done)
|
||||
fetches = fetches + 1
|
||||
done(css)
|
||||
return { cancel = function() end }
|
||||
end
|
||||
end
|
||||
local function run(fetch)
|
||||
local out
|
||||
Assets.localizeAsync("book-3", { uid = "u3" }, sample, nil, fetch, function(html) out = html end)
|
||||
return out
|
||||
end
|
||||
|
||||
local failed = run(fetchStyle(nil))
|
||||
Assert.eq(fetches, 1)
|
||||
Assert.is_nil(failed:find(link, 1, true), "拉不到样式表去掉坏相对 link")
|
||||
Assert.is_true(failed:find(abs, 1, true) ~= nil, "绝对 css link 保留")
|
||||
Assert.is_true(failed:find("text-indent:2em", 1, true) ~= nil, "注入兜底缩进")
|
||||
Assert.is_true(failed:find(fallback, 1, true) ~= nil, "兜底样式整段写入")
|
||||
Assert.is_nil(io.open(work_dir .. "/stylesheets.css", "rb"))
|
||||
|
||||
local out = run(fetchStyle(".content{text-indent:2em}"))
|
||||
Assert.eq(fetches, 2)
|
||||
local icon = out:match('src="(images/[0-9a-f]+%.png)"')
|
||||
Assert.is_true(icon ~= nil, "脚注图标落地")
|
||||
local f = assert(io.open(work_dir .. "/" .. icon, "rb"))
|
||||
Assert.eq(f:read(4), "\137PNG")
|
||||
f:close()
|
||||
Assert.eq(out, head .. '<link href="stylesheets.css" rel="stylesheet" type="text/css" />' .. abs .. fix
|
||||
.. body:gsub("%.%./Images/note%.png", icon))
|
||||
f = assert(io.open(work_dir .. "/stylesheets.css", "rb"))
|
||||
Assert.eq(f:read("*a"), ".content{text-indent:2em}")
|
||||
f:close()
|
||||
|
||||
Assert.eq(run(fetchStyle("不该再拉")), out, "已缓存直接改链接")
|
||||
Assert.eq(fetches, 2)
|
||||
end
|
||||
|
||||
-- 章首页:body.bgimg-1 的开头出血图丢掉,连续 h1 包进整页容器;样式表里 ../Images/ 改指工作目录 images/
|
||||
do
|
||||
local Paths = require("utils.paths")
|
||||
local work_dir = Paths.bookWorkDir("book-4", "ext.weread")
|
||||
Paths.ensureDir(work_dir)
|
||||
os.remove(work_dir .. "/stylesheets.css")
|
||||
local src = '<html><head><link href="../Styles/stylesheets.css" rel="stylesheet" /></head>'
|
||||
.. '<body class="bgimg-1">\n<p class="bleed-pic"><img src="a.png" /></p>\n'
|
||||
.. '<h1 class="firstTitle">第</h1>\n<h1 class="firstTitle">一</h1>\n<p class="content">正文</p></body></html>'
|
||||
local out
|
||||
Assets.localizeAsync("book-4", { uid = "u4" }, src, nil, function(done)
|
||||
done("a{background:url(../Images/bq.jpg)}")
|
||||
return { cancel = function() end }
|
||||
end, function(html) out = html end)
|
||||
Assert.is_true(out:find('<body class="bgimg-1">\n<div class="moon-title"><h1 class="firstTitle">第</h1>\n'
|
||||
.. '<h1 class="firstTitle">一</h1>\n</div><p class="content">正文</p>', 1, true) ~= nil, out)
|
||||
Assert.is_nil(out:find("bleed-pic", 1, true))
|
||||
local f = assert(io.open(work_dir .. "/stylesheets.css", "rb"))
|
||||
Assert.eq(f:read("*a"), "a{background:url(images/bq.jpg)}")
|
||||
f:close()
|
||||
end
|
||||
|
||||
-- 脚注图标路径不统一:qqreader-footnote 或任意 note.png 都注入自带「注」标,不要求写成 ../Images/note.png
|
||||
do
|
||||
local Paths = require("utils.paths")
|
||||
local cases = {
|
||||
{ book = "book-fn-bare", src = "note.png" },
|
||||
{ book = "book-fn-images", src = "Images/note.png" },
|
||||
{ book = "book-fn-parent", src = "../Images/note.png" },
|
||||
{ book = "book-fn-noclass", src = "note.png", plain = true },
|
||||
}
|
||||
local icons = {}
|
||||
for _, case in ipairs(cases) do
|
||||
local html
|
||||
if case.plain then
|
||||
html = string.format('<p><img alt="注文" src="%s" /></p>', case.src)
|
||||
else
|
||||
html = string.format(
|
||||
'<p><img class="qqreader-footnote" alt="注文" src="%s" /></p>',
|
||||
case.src
|
||||
)
|
||||
end
|
||||
local out
|
||||
Assets.localizeAsync(case.book, { uid = "u" }, html, nil, noStyle, function(result)
|
||||
out = result
|
||||
end)
|
||||
local icon = out:match('src="(images/[0-9a-f]+%.png)"')
|
||||
Assert.is_true(icon ~= nil, "脚注图标落地: " .. case.src)
|
||||
Assert.is_nil(out:find(case.src, 1, true), "原路径被改写: " .. case.src)
|
||||
local work_dir = Paths.bookWorkDir(case.book, "ext.weread")
|
||||
local f = assert(io.open(work_dir .. "/" .. icon, "rb"))
|
||||
Assert.eq(f:read(4), "\137PNG")
|
||||
f:close()
|
||||
icons[#icons + 1] = icon
|
||||
end
|
||||
for i = 2, #icons do
|
||||
Assert.eq(icons[i], icons[1], "同一自带图标,内容寻址复用")
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,537 @@
|
||||
--[[--
|
||||
moonsource_weread.auth 离线用例:会话请求头 / 登录门禁 / 自动续期重试。
|
||||
|
||||
每个用例用 freshAuth() 重 require 隔离。
|
||||
登录态 = Eink 会话(wr_skey + eink.refresh_token),扫码与续期细节见 eink_spec。
|
||||
|
||||
@module tests.wechat_auth_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 original_json_preload = package.preload["json"]
|
||||
|
||||
-- 可变测试状态:settings / Request.request / json.decode 全部走这里
|
||||
local state = {
|
||||
cfg = {},
|
||||
saved = nil,
|
||||
request_impl = nil,
|
||||
json_map = {},
|
||||
}
|
||||
|
||||
package.preload["utils.settings"] = function()
|
||||
return {
|
||||
getSource = function()
|
||||
return state.cfg
|
||||
end,
|
||||
saveSource = function(_id, c)
|
||||
state.saved = c
|
||||
end,
|
||||
}
|
||||
end
|
||||
|
||||
package.preload["http.request"] = function()
|
||||
return {
|
||||
-- 语义对齐 http/request.lua 的 Request.ok
|
||||
ok = function(code)
|
||||
local n = tonumber(code)
|
||||
return n ~= nil and n >= 200 and n < 300
|
||||
end,
|
||||
header = function(res, name)
|
||||
local headers = res and res.headers
|
||||
if not headers then
|
||||
return nil
|
||||
end
|
||||
return headers[name] or headers[name:lower()]
|
||||
end,
|
||||
request = function(opts, cb)
|
||||
return state.request_impl(opts, cb)
|
||||
end,
|
||||
}
|
||||
end
|
||||
|
||||
package.preload["json"] = function()
|
||||
return {
|
||||
encode = function()
|
||||
return "{}"
|
||||
end,
|
||||
-- 罐装映射:未登记的串视为非法 JSON(与真实 decode 报错同路径)
|
||||
decode = function(s)
|
||||
local v = state.json_map[s]
|
||||
if v == nil then
|
||||
error("invalid json")
|
||||
end
|
||||
return v
|
||||
end,
|
||||
}
|
||||
end
|
||||
|
||||
-- http.header 用真实模块(纯 Lua,header_spec 已验证可独立加载)
|
||||
|
||||
-- 全量跑时前面的 spec 可能已把 stub 版 json/http.request 留在 package.loaded,
|
||||
-- 这里强制清掉,让上面的 package.preload 生效
|
||||
for _, name in ipairs({ "json", "http.request", "utils.settings" }) do
|
||||
package.loaded[name] = nil
|
||||
end
|
||||
|
||||
--- 重 require auth,重置包级续期状态;eink 为 nil 时用真实 moonsource_weread.eink。
|
||||
---@param cfg table|nil
|
||||
---@param eink table|nil
|
||||
---@return table
|
||||
local function freshAuth(cfg, eink)
|
||||
state.cfg = cfg or {}
|
||||
state.saved = nil
|
||||
package.loaded["moonsource_weread.auth"] = nil
|
||||
if eink and not eink.refreshing then
|
||||
-- 真实 Eink.refreshAsync 自带单飞(并发续期共用一次 /login);桩照此包一层。
|
||||
local raw, waiters = eink.refreshAsync, nil
|
||||
eink.refreshing = function() return waiters ~= nil end
|
||||
eink.refreshAsync = function(cb)
|
||||
if waiters then waiters[#waiters + 1] = cb return end
|
||||
waiters = { cb }
|
||||
raw(function(ok, err, rejected)
|
||||
local list = waiters
|
||||
waiters = nil
|
||||
for _idx, w in ipairs(list) do w(ok, err, rejected) end
|
||||
end)
|
||||
end
|
||||
end
|
||||
package.loaded["moonsource_weread.eink"] = eink
|
||||
return require("moonsource_weread.auth")
|
||||
end
|
||||
|
||||
--- Eink 扫码会话:wr_skey + refresh_token 才算登录。
|
||||
---@param extra table|nil
|
||||
---@return table
|
||||
local function loggedIn(extra)
|
||||
local cfg = { wr_vid = "1", wr_skey = "s", eink = { refresh_token = "rt", device_id = "dev" } }
|
||||
for k, v in pairs(extra or {}) do cfg[k] = v end
|
||||
return cfg
|
||||
end
|
||||
|
||||
------------------------------------------------------------------------
|
||||
-- Auth.sessionHeaders:Cookie 只拼 Eink 会话的 wr_vid / wr_skey;旧网页残留字段不发
|
||||
------------------------------------------------------------------------
|
||||
|
||||
do
|
||||
local auth = freshAuth(loggedIn({ wr_vid = "88", wr_skey = "sk", wr_gid = "g", wr_fp = "f", wr_rt = "r" }))
|
||||
local h = auth.sessionHeaders({ ["X-Custom"] = "c" })
|
||||
Assert.eq(h["Cookie"], "wr_vid=88; wr_skey=sk; wr_ql=0")
|
||||
Assert.eq(h["X-Vid"], "88")
|
||||
Assert.eq(h["X-Skey"], "sk")
|
||||
Assert.eq(h["X-Custom"], "c")
|
||||
-- 浏览器默认头
|
||||
Assert.eq(h["Referer"], "https://weread.qq.com/")
|
||||
Assert.not_nil(h["User-Agent"])
|
||||
|
||||
-- extra 覆盖默认 Referer
|
||||
local h2 = auth.sessionHeaders({ ["Referer"] = "https://example.com/" })
|
||||
Assert.eq(h2["Referer"], "https://example.com/")
|
||||
|
||||
-- 无 Eink 会话(含旧网页会话):只有浏览器头
|
||||
for _, cfg in ipairs({ {}, { wr_vid = "1", wr_skey = "s", wr_gid = "g" } }) do
|
||||
local h3 = freshAuth(cfg).sessionHeaders()
|
||||
Assert.is_nil(h3["Cookie"])
|
||||
Assert.is_nil(h3["X-Vid"])
|
||||
Assert.is_nil(h3["X-Skey"])
|
||||
Assert.not_nil(h3["User-Agent"])
|
||||
end
|
||||
end
|
||||
|
||||
------------------------------------------------------------------------
|
||||
-- hasSession / userLabel
|
||||
------------------------------------------------------------------------
|
||||
|
||||
do
|
||||
Assert.is_true(freshAuth(loggedIn()).hasSession())
|
||||
-- 只有网页会话(旧网页扫码登录)不算:必须重新 Eink 扫码
|
||||
Assert.is_false(freshAuth({ wr_skey = "s", wr_vid = "1" }).hasSession(), "旧网页会话需重新登录")
|
||||
Assert.is_false(freshAuth(loggedIn({ wr_skey = "" })).hasSession())
|
||||
Assert.is_false(freshAuth({ cookie = "wr_gid=1; wr_skey=abc" }).hasSession(), "整段 cookie 串不算会话")
|
||||
Assert.is_false(freshAuth({}).hasSession())
|
||||
|
||||
Assert.eq(freshAuth({ user_name = "阿明", user_id = "9" }).userLabel(), "阿明")
|
||||
-- user_name 空 → 回退 user_id
|
||||
Assert.eq(freshAuth({ user_name = "", user_id = 9 }).userLabel(), "9")
|
||||
Assert.is_nil(freshAuth({}).userLabel())
|
||||
end
|
||||
|
||||
------------------------------------------------------------------------
|
||||
-- clearSession
|
||||
------------------------------------------------------------------------
|
||||
|
||||
do
|
||||
local cfg = {
|
||||
wr_vid = "v", wr_skey = "s", wr_rt = "r",
|
||||
wr_gid = "g", wr_fp = "f", wr_ql = "1",
|
||||
user_id = "u", user_name = "n",
|
||||
api_key = "k", skill_version = "sv", cookie = "c", other = "keep",
|
||||
}
|
||||
local auth = freshAuth(cfg)
|
||||
auth.clearSession()
|
||||
for _, k in ipairs({
|
||||
"wr_vid", "wr_skey", "wr_rt",
|
||||
"wr_gid", "wr_fp", "wr_ql", "user_id", "user_name",
|
||||
"api_key", "skill_version", "cookie",
|
||||
}) do
|
||||
Assert.eq(cfg[k], "")
|
||||
end
|
||||
-- 无关字段不动
|
||||
Assert.eq(cfg.other, "keep")
|
||||
-- 已落盘
|
||||
Assert.eq(state.saved, cfg)
|
||||
end
|
||||
|
||||
-- Eink 扫码会话:退出同时清 refresh_token,设备 ID 保留(重登沿用同一设备)
|
||||
do
|
||||
local cfg = loggedIn()
|
||||
freshAuth(cfg).clearSession()
|
||||
Assert.is_nil(cfg.eink.refresh_token)
|
||||
Assert.eq(cfg.eink.device_id, "dev")
|
||||
end
|
||||
|
||||
-- 退出清掉进程内 reader 状态:否则换号后同章不再发进入阅读,时长不计。
|
||||
do
|
||||
local auth = freshAuth(loggedIn())
|
||||
local Context = require("moonsource_weread.context")
|
||||
Context.reader("b1", "c1").entered = true
|
||||
auth.clearSession()
|
||||
Assert.is_nil(Context.reader("b1", "c1").entered)
|
||||
end
|
||||
|
||||
------------------------------------------------------------------------
|
||||
-- webGetAsync:会话门禁 / 原文透传 / HTTP 错误
|
||||
--
|
||||
-- JSON 解码与 errcode 判定在 client 层,这里只确认回包原样透传。
|
||||
------------------------------------------------------------------------
|
||||
|
||||
do
|
||||
-- 未登录:直接回调错误,不发请求
|
||||
local auth = freshAuth({})
|
||||
state.request_impl = function()
|
||||
error("request must not be called")
|
||||
end
|
||||
local data, err
|
||||
auth.webGetAsync("https://weread.qq.com/web/test", nil, function(d, e)
|
||||
data, err = d, e
|
||||
end)
|
||||
Assert.is_nil(data)
|
||||
Assert.eq(err, "请先扫码登录微信读书")
|
||||
|
||||
-- 已登录:URL 拼接 + JSON 成功
|
||||
auth = freshAuth(loggedIn())
|
||||
local got_url
|
||||
state.json_map = { ['{"errcode":0,"ok":1}'] = { errcode = 0, ok = 1 } }
|
||||
state.request_impl = function(opts, cb)
|
||||
got_url = opts.url
|
||||
cb({ code = 200, body = '{"errcode":0,"ok":1}' })
|
||||
return { cancel = function() end }
|
||||
end
|
||||
data, err = nil, nil
|
||||
auth.webGetAsync("https://weread.qq.com/web/test?x=1", nil, function(d, e)
|
||||
data, err = d, e
|
||||
end)
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(got_url, "https://weread.qq.com/web/test?x=1")
|
||||
Assert.eq(data, '{"errcode":0,"ok":1}')
|
||||
|
||||
-- HTTP 非 2xx
|
||||
state.request_impl = function(_opts, cb)
|
||||
cb({ code = 500, body = "x" })
|
||||
return { cancel = function() end }
|
||||
end
|
||||
data, err = nil, nil
|
||||
auth.webGetAsync("https://weread.qq.com/web/t", nil, function(d, e)
|
||||
data, err = d, e
|
||||
end)
|
||||
Assert.is_nil(data)
|
||||
Assert.eq(err, "HTTP 500")
|
||||
|
||||
-- 网络错误透传
|
||||
state.request_impl = function(_opts, cb)
|
||||
cb(nil, "timeout")
|
||||
return { cancel = function() end }
|
||||
end
|
||||
data, err = nil, nil
|
||||
auth.webGetAsync("https://weread.qq.com/web/t", nil, function(d, e)
|
||||
data, err = d, e
|
||||
end)
|
||||
Assert.is_nil(data)
|
||||
Assert.eq(err, "timeout")
|
||||
end
|
||||
|
||||
------------------------------------------------------------------------
|
||||
-- webPostAsync:Content-Type 默认
|
||||
------------------------------------------------------------------------
|
||||
|
||||
do
|
||||
local auth = freshAuth(loggedIn())
|
||||
local got_opts
|
||||
state.json_map = { ['{"errcode":0}'] = { errcode = 0 } }
|
||||
state.request_impl = function(opts, cb)
|
||||
got_opts = opts
|
||||
cb({ code = 200, body = '{"errcode":0}' })
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local data, err
|
||||
auth.webPostAsync("https://weread.qq.com/web/sync", "{}", nil, function(d, e)
|
||||
data, err = d, e
|
||||
end)
|
||||
Assert.is_nil(err)
|
||||
Assert.not_nil(data)
|
||||
Assert.eq(got_opts.method, "POST")
|
||||
Assert.eq(got_opts.url, "https://weread.qq.com/web/sync")
|
||||
Assert.eq(got_opts.headers["Content-Type"], "application/json")
|
||||
end
|
||||
|
||||
------------------------------------------------------------------------
|
||||
-- 会话失效自动续期(Eink refreshToken)+ 重试一次,重试用新 Cookie
|
||||
------------------------------------------------------------------------
|
||||
|
||||
do
|
||||
local refreshed = 0
|
||||
local auth = freshAuth(loggedIn({ wr_skey = "old" }), {
|
||||
hasSession = function() return true end,
|
||||
credentials = function() return { vid = state.cfg.wr_vid, access_token = state.cfg.wr_skey } end,
|
||||
refreshAsync = function(cb)
|
||||
refreshed = refreshed + 1
|
||||
state.cfg.wr_skey = "newkey"
|
||||
cb(true)
|
||||
end,
|
||||
})
|
||||
local cookies = {}
|
||||
state.json_map = {
|
||||
['{"errcode":-2012,"errmsg":"登录态失效"}'] = { errcode = -2012, errmsg = "登录态失效" },
|
||||
['{"errcode":0,"ok":1}'] = { errcode = 0, ok = 1 },
|
||||
}
|
||||
state.request_impl = function(opts, cb)
|
||||
cookies[#cookies + 1] = opts.headers["Cookie"]
|
||||
if #cookies == 1 then
|
||||
cb({ code = 200, body = '{"errcode":-2012,"errmsg":"登录态失效"}' })
|
||||
else
|
||||
cb({ code = 200, body = '{"errcode":0,"ok":1}' })
|
||||
end
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local data, err, resp
|
||||
auth.webGetAsync("https://weread.qq.com/web/retry", nil, function(d, e, r)
|
||||
data, err, resp = d, e, r
|
||||
end)
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(data, '{"errcode":0,"ok":1}')
|
||||
Assert.eq(resp.json.ok, 1, "判失效时解过的 JSON 经 res.json 交给调用方,不必再解")
|
||||
Assert.eq(refreshed, 1)
|
||||
Assert.eq(#cookies, 2)
|
||||
Assert.is_true(cookies[1]:find("wr_skey=old", 1, true) ~= nil)
|
||||
Assert.is_true(cookies[2]:find("wr_skey=newkey", 1, true) ~= nil)
|
||||
end
|
||||
|
||||
-- 续期冷却:冷却内再遇失效回包(如 WAF 403)不再打 /login,只用现有令牌重试一次。
|
||||
do
|
||||
local refreshed = 0
|
||||
local auth = freshAuth(loggedIn(), {
|
||||
hasSession = function() return true end,
|
||||
credentials = function() return { vid = state.cfg.wr_vid, access_token = state.cfg.wr_skey } end,
|
||||
refreshAsync = function(cb)
|
||||
refreshed = refreshed + 1
|
||||
cb(true)
|
||||
end,
|
||||
})
|
||||
local requests = 0
|
||||
state.json_map = {}
|
||||
state.request_impl = function(_opts, cb)
|
||||
requests = requests + 1
|
||||
cb({ code = 403, body = "<html>blocked</html>" })
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local errs = {}
|
||||
for _i = 1, 3 do
|
||||
auth.webGetAsync("https://weread.qq.com/web/x", nil, function(_raw, e) errs[#errs + 1] = e end)
|
||||
end
|
||||
Assert.eq(refreshed, 1, "冷却内只续期一次")
|
||||
Assert.eq(requests, 6, "每个请求仍各重试一次")
|
||||
Assert.eq(errs[3], "HTTP 403")
|
||||
end
|
||||
|
||||
-- 错误信息只含「超时」不是会话失效,不续期。
|
||||
do
|
||||
local refreshed = 0
|
||||
local auth = freshAuth(loggedIn(), {
|
||||
hasSession = function() return true end,
|
||||
credentials = function() return { vid = state.cfg.wr_vid, access_token = state.cfg.wr_skey } end,
|
||||
refreshAsync = function(cb)
|
||||
refreshed = refreshed + 1
|
||||
cb(true)
|
||||
end,
|
||||
})
|
||||
state.json_map = { ['{"errcode":-1,"errmsg":"请求超时"}'] = { errcode = -1, errmsg = "请求超时" } }
|
||||
state.request_impl = function(_opts, cb)
|
||||
cb({ code = 200, body = '{"errcode":-1,"errmsg":"请求超时"}' })
|
||||
return { cancel = function() end }
|
||||
end
|
||||
auth.webGetAsync("https://weread.qq.com/web/t", nil, function() end)
|
||||
Assert.eq(refreshed, 0)
|
||||
end
|
||||
|
||||
-- 续期等待中取消:不再发重试请求,也不回调;取消落到当前这次请求上。
|
||||
do
|
||||
local finish_refresh
|
||||
local auth = freshAuth(loggedIn({ wr_skey = "old" }), {
|
||||
hasSession = function() return true end,
|
||||
credentials = function() return { vid = state.cfg.wr_vid, access_token = state.cfg.wr_skey } end,
|
||||
refreshAsync = function(cb) finish_refresh = cb end,
|
||||
})
|
||||
state.json_map = {
|
||||
['{"errcode":-2012,"errmsg":"登录态失效"}'] = { errcode = -2012, errmsg = "登录态失效" },
|
||||
}
|
||||
local requests = 0
|
||||
state.request_impl = function(_opts, cb)
|
||||
requests = requests + 1
|
||||
cb({ code = 200, body = '{"errcode":-2012,"errmsg":"登录态失效"}' })
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local called = false
|
||||
local job = auth.webGetAsync("https://weread.qq.com/web/cancel", nil, function() called = true end)
|
||||
job.cancel()
|
||||
finish_refresh(true)
|
||||
Assert.eq(requests, 1)
|
||||
Assert.is_false(called)
|
||||
end
|
||||
|
||||
-- 续期失败:不重试,Eink 的续期错误原样回给调用方。
|
||||
do
|
||||
local auth = freshAuth(loggedIn(), {
|
||||
hasSession = function() return true end,
|
||||
credentials = function() return { vid = state.cfg.wr_vid, access_token = state.cfg.wr_skey } end,
|
||||
refreshAsync = function(cb) cb(false, "登录失败 -2013") end,
|
||||
})
|
||||
state.json_map = {
|
||||
['{"errcode":-2012,"errmsg":"登录态失效"}'] = { errcode = -2012, errmsg = "登录态失效" },
|
||||
}
|
||||
local requests = 0
|
||||
state.request_impl = function(_opts, cb)
|
||||
requests = requests + 1
|
||||
cb({ code = 200, body = '{"errcode":-2012,"errmsg":"登录态失效"}' })
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local data, err
|
||||
auth.webGetAsync("https://weread.qq.com/web/fail", nil, function(d, e) data, err = d, e end)
|
||||
Assert.eq(requests, 1)
|
||||
Assert.is_nil(data)
|
||||
Assert.eq(err, "登录失败 -2013")
|
||||
end
|
||||
|
||||
-- 只有真失效才判登录失效:记下 expire 调用(替身,用完还原)
|
||||
local real_source_auth = package.loaded["source.auth"]
|
||||
local expired = {}
|
||||
package.loaded["source.auth"] = {
|
||||
expire = function(id, msg) expired[#expired + 1] = id; return msg end,
|
||||
ok = function() end,
|
||||
}
|
||||
local AUTH_FAIL = '{"errcode":-2012,"errmsg":"登录态失效"}'
|
||||
|
||||
-- 续期失败的归因:服务器明确拒绝才判登录失效;超时 / 断网只回错误。
|
||||
for _idx, case in ipairs({ { rejected = true, expect = 1 }, { rejected = nil, expect = 0 } }) do
|
||||
expired = {}
|
||||
local auth = freshAuth(loggedIn({ wr_skey = "old" }), {
|
||||
hasSession = function() return true end,
|
||||
credentials = function() return { vid = state.cfg.wr_vid, access_token = state.cfg.wr_skey } end,
|
||||
refreshAsync = function(cb) cb(false, "boom", case.rejected) end,
|
||||
})
|
||||
state.json_map = { [AUTH_FAIL] = { errcode = -2012, errmsg = "登录态失效" } }
|
||||
state.request_impl = function(_opts, cb)
|
||||
cb({ code = 200, body = AUTH_FAIL })
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local err
|
||||
auth.webGetAsync("https://weread.qq.com/web/x", nil, function(_d, e) err = e end)
|
||||
-- 明确拒绝:中文失效文案(接口原文 boom 只打日志);超时/断网原样回错误。
|
||||
if case.rejected then Assert.matches(err, "扫一扫") else Assert.eq(err, "boom") end
|
||||
Assert.len(expired, case.expect)
|
||||
end
|
||||
|
||||
-- 并发竞态(日志 22:14:17):A 回失效触发续期,续期在飞时 B 也回失效。
|
||||
-- B 必须等续期结果再用新令牌重试;以前冷却直接让 B 拿旧令牌重试 → 再失效 → 误判登录失效。
|
||||
do
|
||||
local finish, refreshed = nil, 0
|
||||
local auth = freshAuth(loggedIn({ wr_skey = "old" }), {
|
||||
hasSession = function() return true end,
|
||||
credentials = function() return { vid = state.cfg.wr_vid, access_token = state.cfg.wr_skey } end,
|
||||
refreshAsync = function(cb) refreshed = refreshed + 1; finish = cb end,
|
||||
})
|
||||
state.json_map = { [AUTH_FAIL] = { errcode = -2012, errmsg = "登录态失效" } }
|
||||
local cookies = {}
|
||||
state.request_impl = function(opts, cb)
|
||||
cookies[#cookies + 1] = opts.headers["Cookie"]
|
||||
cb({ code = 200, body = opts.headers["Cookie"]:find("wr_skey=old", 1, true) and AUTH_FAIL or "ok" })
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local got = {}
|
||||
auth.webGetAsync("https://weread.qq.com/web/shelf/sync", nil, function(d, e) got[#got + 1] = d or e end)
|
||||
auth.webGetAsync("https://weread.qq.com/web/mp/articles", nil, function(d, e) got[#got + 1] = d or e end)
|
||||
Assert.eq(refreshed, 1, "只续期一次")
|
||||
Assert.len(got, 0, "B 在等续期,没有拿旧令牌重试")
|
||||
state.cfg.wr_skey = "newkey"
|
||||
finish(true)
|
||||
Assert.eq(table.concat(got, ","), "ok,ok")
|
||||
Assert.len(cookies, 4)
|
||||
Assert.len(expired, 0, "没有误判登录失效")
|
||||
end
|
||||
|
||||
-- 请求在飞时令牌已被别的请求续期换掉:回失效就直接用新令牌重试,不再打 /login
|
||||
do
|
||||
local refreshed = 0
|
||||
local auth = freshAuth(loggedIn({ wr_skey = "old" }), {
|
||||
hasSession = function() return true end,
|
||||
credentials = function() return { vid = state.cfg.wr_vid, access_token = state.cfg.wr_skey } end,
|
||||
refreshAsync = function(cb) refreshed = refreshed + 1; cb(true) end,
|
||||
})
|
||||
state.json_map = { [AUTH_FAIL] = { errcode = -2012, errmsg = "登录态失效" } }
|
||||
local pending = {}
|
||||
state.request_impl = function(opts, cb)
|
||||
pending[#pending + 1] = { cookie = opts.headers["Cookie"], cb = cb }
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local data
|
||||
auth.webGetAsync("https://weread.qq.com/web/x2", nil, function(d) data = d end)
|
||||
state.cfg.wr_skey = "rotated"
|
||||
pending[1].cb({ code = 200, body = AUTH_FAIL })
|
||||
Assert.eq(refreshed, 0)
|
||||
Assert.is_true(pending[2].cookie:find("wr_skey=rotated", 1, true) ~= nil)
|
||||
pending[2].cb({ code = 200, body = "fine" })
|
||||
Assert.eq(data, "fine")
|
||||
end
|
||||
|
||||
-- no_expire(公众号接口):续期重试后仍回失效 errcode → 只回错误,不判整个微信读书登录失效
|
||||
do
|
||||
local auth = freshAuth(loggedIn(), {
|
||||
hasSession = function() return true end,
|
||||
credentials = function() return { vid = state.cfg.wr_vid, access_token = state.cfg.wr_skey } end,
|
||||
refreshAsync = function(cb) cb(true) end,
|
||||
})
|
||||
state.json_map = { [AUTH_FAIL] = { errcode = -2012, errmsg = "登录态失效" } }
|
||||
state.request_impl = function(_opts, cb)
|
||||
cb({ code = 200, body = AUTH_FAIL })
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local err
|
||||
auth.webGetAsync("https://weread.qq.com/web/mp/articles", { no_expire = true }, function(_d, e) err = e end)
|
||||
Assert.eq(err, "微信读书拒绝了请求,请稍后再试")
|
||||
Assert.len(expired, 0)
|
||||
-- 普通接口照旧判失效
|
||||
auth.webGetAsync("https://weread.qq.com/web/shelf/sync", nil, function(_d, e) err = e end)
|
||||
Assert.matches(err, "扫一扫")
|
||||
Assert.eq(table.concat(expired, ","), "ext.weread")
|
||||
end
|
||||
package.loaded["source.auth"] = real_source_auth
|
||||
|
||||
------------------------------------------------------------------------
|
||||
-- 清理:恢复本文件改动的 preload / loaded,避免污染同进程后续用例
|
||||
------------------------------------------------------------------------
|
||||
|
||||
for _, name in ipairs({ "utils.settings", "http.request", "json", "moonsource_weread.auth", "moonsource_weread.eink" }) do
|
||||
package.preload[name] = nil
|
||||
package.loaded[name] = nil
|
||||
end
|
||||
package.preload["json"] = original_json_preload
|
||||
@@ -0,0 +1,510 @@
|
||||
--[[--
|
||||
微信章节正文的 range 坐标原文与 reader 状态回归测试。
|
||||
|
||||
@module tests.moonsource_weread.chapter_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")
|
||||
|
||||
package.preload["json"] = function()
|
||||
return {
|
||||
encode = require("support.json_stub").encode,
|
||||
decode = require("support.json_stub").decode,
|
||||
}
|
||||
end
|
||||
|
||||
local queries = {}
|
||||
local app_err = nil
|
||||
local trial = false
|
||||
local bom = false
|
||||
local txt_zip = false
|
||||
local zip_text_missing = false
|
||||
local info_requests = {}
|
||||
local app_response
|
||||
|
||||
package.preload["workers.job"] = function()
|
||||
return {
|
||||
run = function(fn, opts)
|
||||
opts.on_done(fn())
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
end
|
||||
|
||||
package.preload["http.request"] = function()
|
||||
return {
|
||||
header = function() return "encrypt-key" end,
|
||||
ok = function(code) return type(code) == "number" and code >= 200 and code < 300 end,
|
||||
}
|
||||
end
|
||||
|
||||
package.preload["moonsource_weread.eink"] = function()
|
||||
return {
|
||||
credentials = function() return { vid = "42" } end,
|
||||
callAsync = function(method, path, opts, cb)
|
||||
if path == "/book/info" then
|
||||
info_requests[#info_requests + 1] = opts.query
|
||||
else
|
||||
queries[#queries + 1] = opts.query
|
||||
end
|
||||
if app_response then return app_response(method, path, opts, cb) end
|
||||
if path == "/book/info" then
|
||||
cb({ book = { version = 7 } })
|
||||
return { cancel = function() end }
|
||||
end
|
||||
if app_err then
|
||||
cb(nil, app_err)
|
||||
else
|
||||
local body
|
||||
if opts.query.bookType == "txt" and not txt_zip then
|
||||
body = string.rep("\0", 257) .. "ustar"
|
||||
else
|
||||
body = "PK"
|
||||
end
|
||||
cb({ body = body, code = 200 })
|
||||
end
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
end
|
||||
|
||||
package.preload["moonsource_weread.auth"] = function()
|
||||
return {
|
||||
hasSession = function() return true end,
|
||||
webPostAsync = function() error("chapter download must not fall back to the web reader") end,
|
||||
webGetAsync = function() error("chapter download must not fall back to the web reader") end,
|
||||
}
|
||||
end
|
||||
|
||||
local FULL = '<?xml version="1.0"?><html><head><title></title>'
|
||||
.. '<link href="../Styles/stylesheets.css" rel="stylesheet" type="text/css" /></head>'
|
||||
.. '<body><h2 class="secondTitle">1</h2><p class="content"><span class="wr-underline">正文</span>'
|
||||
.. '<img class="qqreader-footnote" alt="注" src="../Images/note.png" /></p>'
|
||||
.. '<img src="https://res.weread.qq.com/x.png" /></body></html>\n'
|
||||
.. '<?xml version="1.0"?><html><head><title></title></head><body><p>第二段文档</p></body></html>'
|
||||
local PLAIN = "\239\187\191第一行 <b>\n 第二行"
|
||||
local TRIAL = "“第四路,已过浔阳!”\n这是李善德发明的脚程格眼。..."
|
||||
|
||||
package.preload["moonsource_weread.protocol"] = function()
|
||||
return {
|
||||
readerUrl = function() return "https://weread.qq.com/web/reader/id" end,
|
||||
}
|
||||
end
|
||||
|
||||
package.preload["moonsource_weread.package"] = function()
|
||||
return {
|
||||
password = function() return "pw" end,
|
||||
unzipNeed = function() return 0 end,
|
||||
formatChaptersParam = function(uids)
|
||||
uids = uids or {}
|
||||
if #uids == 0 then return "0" end
|
||||
local nums = {}
|
||||
for i, u in ipairs(uids) do
|
||||
local n = tonumber(u)
|
||||
if not n then
|
||||
local parts = { "0" }
|
||||
for _idx, x in ipairs(uids) do parts[#parts + 1] = tostring(x) end
|
||||
return table.concat(parts, ",")
|
||||
end
|
||||
nums[i] = n
|
||||
end
|
||||
local ok = true
|
||||
for i = 2, #nums do if nums[i] ~= nums[i - 1] + 1 then ok = false break end end
|
||||
if ok then
|
||||
local a, b = nums[1], nums[#nums]
|
||||
if a == 1 then return "0-" .. b end
|
||||
if a == b then return "0," .. a end
|
||||
return "0," .. a .. "-" .. b
|
||||
end
|
||||
local parts = { "0" }
|
||||
for _idx, n in ipairs(nums) do parts[#parts + 1] = tostring(n) end
|
||||
return table.concat(parts, ",")
|
||||
end,
|
||||
extractChapters = function(files, _book, uids, book_type)
|
||||
local out, style = {}, files["Styles/stylesheets.css"]
|
||||
for _idx, uid in ipairs(uids) do
|
||||
local html = FULL
|
||||
if trial then html = TRIAL elseif bom then html = "98791" .. FULL end
|
||||
-- keep real BOM via bytes below in separate fix
|
||||
out[tostring(uid)] = { text = html, format = book_type == "txt" and "txt" or "html" }
|
||||
end
|
||||
return out, style
|
||||
end,
|
||||
unzip = function()
|
||||
local q = queries[#queries]
|
||||
local ch = tostring(q.chapters or "")
|
||||
if ch == "0" or ch:find("^0%-") or ch:find("^0,") then
|
||||
return { ["Styles/stylesheets.css"] = ".content{text-indent:2em}", dummy = true }
|
||||
end
|
||||
return { dummy = true }
|
||||
end,
|
||||
pickStyle = function(files)
|
||||
return files["Styles/stylesheets.css"] or files["Styles/stylesheet.css"]
|
||||
end,
|
||||
chapterHtml = function()
|
||||
if txt_zip then error("TXT ZIP with text entry must not fall back to chapterHtml") end
|
||||
if trial then return TRIAL end
|
||||
if bom then return "\239\187\191" .. FULL end
|
||||
return FULL
|
||||
end,
|
||||
chapterText = function() return PLAIN end,
|
||||
chapterZipText = function()
|
||||
if txt_zip and not zip_text_missing then return PLAIN end
|
||||
return nil
|
||||
end,
|
||||
}
|
||||
end
|
||||
|
||||
package.preload["moonsource_weread.assets"] = function()
|
||||
return {
|
||||
localizeAsync = function(_book, _chapter, html, _referer, fetch_style, cb)
|
||||
return fetch_style(function(css)
|
||||
Assert.eq(css, ".content{text-indent:2em}")
|
||||
cb((html:gsub("https://res%.weread%.qq%.com/x%.png", "images/x.png")))
|
||||
end)
|
||||
end,
|
||||
}
|
||||
end
|
||||
|
||||
for _, name in ipairs({
|
||||
"workers.job", "http.request", "moonsource_weread.eink", "moonsource_weread.package", "moonsource_weread.chapter",
|
||||
}) do
|
||||
package.loaded[name] = nil
|
||||
end
|
||||
local Chapter = require("moonsource_weread.chapter")
|
||||
local Context = require("moonsource_weread.context")
|
||||
Context.clear()
|
||||
Context.rememberBookVersion("book", 7)
|
||||
|
||||
do
|
||||
-- EPUB:解码后的 xhtml 原样交出,不抽 body、不删虚线 / title、不改脚注;range 坐标原文同一份。
|
||||
local html_out, range_source, format
|
||||
Chapter.fetchHtmlAsync("book", { uid = "chapter" }, function(html, err, raw, fmt)
|
||||
Assert.is_nil(err)
|
||||
html_out, range_source, format = html, raw, fmt
|
||||
end)
|
||||
Assert.eq(html_out, FULL)
|
||||
Assert.eq(range_source, FULL)
|
||||
Assert.eq(format, "html")
|
||||
Assert.eq(#queries, 1)
|
||||
Assert.eq(queries[1].bookType, "epub")
|
||||
Assert.eq(queries[1].chapters, "chapter")
|
||||
Assert.eq(queries[1].bookVersion, 7)
|
||||
Assert.eq(queries[1].offline, "0", "单章在线阅读 offline=0")
|
||||
end
|
||||
|
||||
do
|
||||
-- TXT:bookType=txt,range 按包内纯文本逐 rune 计,段落化后的 HTML 只用于显示。
|
||||
local body, range_source, format
|
||||
Chapter.fetchHtmlAsync("book", { uid = "c2", format = "txt" }, function(html, err, raw, fmt)
|
||||
Assert.is_nil(err)
|
||||
body, range_source, format = html, raw, fmt
|
||||
end)
|
||||
Assert.eq(range_source, PLAIN)
|
||||
Assert.eq(format, "txt")
|
||||
Assert.is_true(body:find("<p>", 1, true) ~= nil)
|
||||
-- 段首空白只在显示用 HTML 里剥掉,缩进统一由 CSS 给。
|
||||
Assert.is_true(body:find("<p>第二行</p>", 1, true) ~= nil)
|
||||
Assert.eq(queries[#queries].bookType, "txt")
|
||||
Assert.eq(queries[#queries].chapters, "c2")
|
||||
end
|
||||
|
||||
do
|
||||
-- 交给宿主:EPUB 是整份 document,只改资源引用;TXT 仍是 html 片段走外壳。
|
||||
local payload
|
||||
local before = #queries
|
||||
Chapter.fetchContentAsync("book", { idx = 1, uid = "chapter", title = "第一章" }, function(p) payload = p end)
|
||||
-- 正文一次,样式表一次(chapters=0),没有网页分片。
|
||||
Assert.eq(queries[before + 1].chapters, "chapter")
|
||||
Assert.eq(queries[before + 1].bookType, "epub")
|
||||
Assert.eq(queries[before + 2].chapters, "0")
|
||||
Assert.is_nil(payload.html)
|
||||
local note = '<img class="qqreader-footnote" alt="注" src="../Images/note.png" />'
|
||||
local expected = FULL:gsub("https://res%.weread%.qq%.com/x%.png", "images/x.png")
|
||||
:gsub(note:gsub("%p", "%%%0"), '<a href="#wr-fn1" id="wr-fnref1" epub:type="noteref">'
|
||||
.. '<img class="qqreader-footnote" alt="注" src="../Images/note.png" style="height:0.8em;width:auto;vertical-align:super;border:0" /></a>')
|
||||
-- 两份拼接文档:aside 进最后一个 body;epub:type 让 KOReader 页内脚注 / 弹窗都能认。
|
||||
:gsub("<p>第二段文档</p></body>",
|
||||
'<p>第二段文档</p><aside id="wr-fn1" epub:type="footnote">[1] 注 <a href="#wr-fnref1">↩</a></aside>\n</body>')
|
||||
Assert.eq(payload.document, expected)
|
||||
-- 脚注图标尺寸不依赖整书样式表:行内 style 压到 0.8em 上标,原有 style 被替换。
|
||||
Assert.is_true(payload.document:find('height:0.8em', 1, true) ~= nil)
|
||||
|
||||
Chapter.fetchContentAsync("book", { idx = 2, uid = "c2", format = "txt", title = "第2章 想<整>我" }, function(p) payload = p end)
|
||||
Assert.is_nil(payload.document)
|
||||
-- TXT 正文不带章名:章首补 h1(转义),EPUB 原文自带标题不补。
|
||||
local heading = "<h1>第2章 想<整>我</h1>"
|
||||
Assert.eq(payload.html:sub(1, #heading), heading)
|
||||
Assert.is_true(payload.html:find("<p>", 1, true) ~= nil)
|
||||
end
|
||||
|
||||
do
|
||||
-- 脚注链接带原文件名:锚点在本章里就改成 #锚点,不在的(跨章)只留文字
|
||||
local saved = FULL
|
||||
FULL = FULL:gsub("</body></html>\n<%?xml", '<p><a href="part0012.html#note_1">[1]</a><a href="../Text/zhushi.xhtml#zhu116">[2]</a></p>'
|
||||
.. '<p id="note_1">注文</p></body></html>\n<?xml', 1)
|
||||
local payload
|
||||
Chapter.fetchContentAsync("book", { idx = 1, uid = "chapter", title = "第一章" }, function(p) payload = p end)
|
||||
FULL = saved
|
||||
Assert.is_true(payload.document:find('<a href="#note_1">[1]</a>', 1, true) ~= nil)
|
||||
Assert.is_nil(payload.document:find("zhushi", 1, true))
|
||||
Assert.is_true(payload.document:find("[2]", 1, true) ~= nil)
|
||||
end
|
||||
|
||||
do
|
||||
-- 跨章注释链接里的图标:找不到注文也要限制尺寸,否则样式表缺规则时显示成大方块
|
||||
local saved = FULL
|
||||
FULL = FULL:gsub("</body></html>\n<%?xml", '<p>总之<a href="../Text/zhushi.xhtml#zhu9"><img class="x" src="n.png"/></a></p></body></html>\n<?xml', 1)
|
||||
local payload
|
||||
Chapter.fetchContentAsync("book", { idx = 1, uid = "chapter", title = "第一章" }, function(p) payload = p end)
|
||||
FULL = saved
|
||||
Assert.is_true(payload.document:find('<img class="x" src="n.png" style="height:0.8em', 1, true) ~= nil)
|
||||
end
|
||||
|
||||
do
|
||||
-- 进度定位缓存写盘失败(磁盘满):正文已到手,照常交出,不当成章节失败
|
||||
local Position = require("moonsource_weread.progress")
|
||||
local saved = Position.remember
|
||||
Position.remember = function() return nil, "disk full" end
|
||||
local payload, err
|
||||
Chapter.fetchContentAsync("book", { idx = 1, uid = "chapter", title = "第一章" }, function(p, e) payload, err = p, e end)
|
||||
Position.remember = saved
|
||||
Assert.is_nil(err)
|
||||
Assert.is_true(payload.document ~= nil)
|
||||
end
|
||||
|
||||
do
|
||||
-- 注释章:锚点 id → 注文(去掉 [n] 序号与标签,保留实体转义)
|
||||
local notes = Chapter._noteTexts('<p class="noteContent"><a href="../Text/chapter32.xhtml#zw116" id="zhu116">[116]</a>当时多用沙子&吸干墨迹。</p>'
|
||||
.. '<p>无锚点</p><p class="noteContent"><a id="zhu117">[117]</a></p>')
|
||||
Assert.eq(notes.zhu116, "当时多用沙子&吸干墨迹。")
|
||||
Assert.is_nil(notes.zhu117)
|
||||
end
|
||||
|
||||
do
|
||||
-- 无权阅读的付费章:EPUB 通道回纯文本试读片段,必须报错,不能当正文落盘。
|
||||
trial = true
|
||||
local payload, err = "untouched", nil
|
||||
Chapter.fetchContentAsync("book", { idx = 2, uid = "paid", title = "第二章" }, function(p, e) payload, err = p, e end)
|
||||
trial = false
|
||||
Assert.is_nil(payload)
|
||||
Assert.matches(err, "试读")
|
||||
end
|
||||
|
||||
do
|
||||
-- 服务端给 XHTML 带 UTF-8 BOM:是正文,不能当试读片段拒掉。
|
||||
bom = true
|
||||
local payload, err = nil, nil
|
||||
Chapter.fetchContentAsync("book", { idx = 1, uid = "bom", title = "第一章" }, function(p, e) payload, err = p, e end)
|
||||
bom = false
|
||||
Assert.is_nil(err)
|
||||
Assert.is_true(payload ~= nil)
|
||||
end
|
||||
|
||||
do
|
||||
-- App 通道失败就结束,不再改走网页。
|
||||
app_err = "加载失败"
|
||||
local n = #queries
|
||||
local html_out, err
|
||||
Chapter.fetchHtmlAsync("book", { uid = "flaky" }, function(h, e) html_out, err = h, e end)
|
||||
app_err = nil
|
||||
Assert.is_nil(html_out)
|
||||
Assert.eq(err, "加载失败")
|
||||
Assert.eq(#queries, n + 1)
|
||||
end
|
||||
|
||||
do
|
||||
-- 部分 TXT 章回包是加密 ZIP(非 ustar):走 chapterZipText,不按 HTML 清单解析。
|
||||
txt_zip = true
|
||||
local body, range_source, format, err
|
||||
Chapter.fetchHtmlAsync("book", { uid = "1595", format = "txt" }, function(html, e, raw, fmt)
|
||||
body, err, range_source, format = html, e, raw, fmt
|
||||
end)
|
||||
txt_zip = false
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(range_source, PLAIN)
|
||||
Assert.eq(format, "txt")
|
||||
Assert.is_true(body:find("<p>", 1, true) ~= nil)
|
||||
Assert.eq(queries[#queries].bookType, "txt")
|
||||
end
|
||||
|
||||
do
|
||||
-- 未缓存的书先拿真实版本,下一章直接复用,不把 0 当通用版本。
|
||||
local before = #info_requests
|
||||
Chapter.fetchHtmlAsync("fresh-book", { uid = "1" }, function(html, err)
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(html, FULL)
|
||||
end)
|
||||
Assert.eq(queries[#queries].bookVersion, 7)
|
||||
Chapter.fetchHtmlAsync("fresh-book", { uid = "2" }, function(html, err)
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(html, FULL)
|
||||
end)
|
||||
Assert.eq(#info_requests, before + 1)
|
||||
end
|
||||
|
||||
do
|
||||
-- -2063 的 info.bookVersion 直接用于唯一一次重试,不额外拉详情。
|
||||
local attempts, callbacks, before = 0, 0, #info_requests
|
||||
Context.rememberBookVersion("updated-book", 3)
|
||||
app_response = function(_method, path, opts, cb)
|
||||
Assert.eq(path, "/book/chapterdownload")
|
||||
attempts = attempts + 1
|
||||
if attempts == 1 then
|
||||
Assert.eq(opts.query.bookVersion, 3)
|
||||
cb(nil, "version expired", { errcode = -2063, body = { info = { bookVersion = "8" } } })
|
||||
else
|
||||
Assert.eq(opts.query.bookVersion, 8)
|
||||
cb({ body = "PK", code = 200 })
|
||||
end
|
||||
return { cancel = function() end }
|
||||
end
|
||||
Chapter.fetchHtmlAsync("updated-book", { uid = "1" }, function(html, err)
|
||||
callbacks = callbacks + 1
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(html, FULL)
|
||||
end)
|
||||
app_response = nil
|
||||
Assert.eq(attempts, 2)
|
||||
Assert.eq(callbacks, 1)
|
||||
Assert.eq(#info_requests, before)
|
||||
Assert.eq(Context.bookVersion("updated-book"), 8)
|
||||
end
|
||||
|
||||
do
|
||||
-- 回包没有可用新版本(包括 0)时刷新详情;第二次过期直接失败。
|
||||
for i, info in ipairs({ {}, { bookVersion = "0" }, { bookVersion = "bad" }, { bookVersion = "4" } }) do
|
||||
local book_id = "expired-book-" .. i
|
||||
local attempts, details, callbacks = 0, 0, 0
|
||||
Context.rememberBookVersion(book_id, 4)
|
||||
app_response = function(_method, path, opts, cb)
|
||||
if path == "/book/info" then
|
||||
details = details + 1
|
||||
cb({ book = { version = 9 } })
|
||||
else
|
||||
attempts = attempts + 1
|
||||
Assert.eq(opts.query.bookVersion, attempts == 1 and 4 or 9)
|
||||
cb(nil, "version expired", { errcode = -2063, body = { info = info } })
|
||||
end
|
||||
return { cancel = function() end }
|
||||
end
|
||||
Chapter.fetchHtmlAsync(book_id, { uid = "1" }, function(html, err)
|
||||
callbacks = callbacks + 1
|
||||
Assert.is_nil(html)
|
||||
Assert.eq(err, "version expired")
|
||||
end)
|
||||
app_response = nil
|
||||
Assert.eq(attempts, 2)
|
||||
Assert.eq(details, 1)
|
||||
Assert.eq(callbacks, 1)
|
||||
end
|
||||
end
|
||||
|
||||
do
|
||||
-- 获取版本失败或详情缺字段,必须交出错误,不能假装成功或盲发版本 0。
|
||||
for i, reply in ipairs({ { err = "network failed" }, { wire = {}, err = "缺少书籍版本" } }) do
|
||||
local before = #queries
|
||||
app_response = function(_method, path, _opts, cb)
|
||||
Assert.eq(path, "/book/info")
|
||||
cb(reply.wire, reply.wire and nil or reply.err)
|
||||
return { cancel = function() end }
|
||||
end
|
||||
Chapter.fetchHtmlAsync("bad-info-" .. i, { uid = "1" }, function(html, err)
|
||||
Assert.is_nil(html)
|
||||
Assert.eq(err, reply.err)
|
||||
end)
|
||||
app_response = nil
|
||||
Assert.eq(#queries, before)
|
||||
end
|
||||
end
|
||||
|
||||
do
|
||||
-- 详情获取与过期恢复都能取消;迟来的回调不能继续下载或通知结果。
|
||||
for _idx, phase in ipairs({ "initial-info", "retry-download", "refresh-info" }) do
|
||||
local book_id = "cancel-" .. phase
|
||||
local pending, cancelled_path, callbacks
|
||||
callbacks = 0
|
||||
if phase ~= "initial-info" then Context.rememberBookVersion(book_id, 4) end
|
||||
local attempts = 0
|
||||
app_response = function(_method, path, _opts, cb)
|
||||
if path == "/book/chapterdownload" then
|
||||
attempts = attempts + 1
|
||||
if attempts == 1 then
|
||||
local info = phase == "retry-download" and { bookVersion = 9 } or {}
|
||||
cb(nil, "version expired", { errcode = -2063, body = { info = info } })
|
||||
return { cancel = function() error("cancelled stale request") end }
|
||||
end
|
||||
end
|
||||
pending = cb
|
||||
return { cancel = function() cancelled_path = path end }
|
||||
end
|
||||
local handle = Chapter.fetchHtmlAsync(book_id, { uid = "1" }, function() callbacks = callbacks + 1 end)
|
||||
Assert.not_nil(pending)
|
||||
handle:cancel()
|
||||
Assert.eq(cancelled_path, phase == "retry-download" and "/book/chapterdownload" or "/book/info")
|
||||
local before = #queries
|
||||
if phase == "retry-download" then pending({ body = "PK", code = 200 })
|
||||
else pending({ book = { version = 9 } }) end
|
||||
Assert.eq(#queries, before)
|
||||
Assert.eq(callbacks, 0)
|
||||
app_response = nil
|
||||
end
|
||||
end
|
||||
|
||||
do
|
||||
-- 已开始解包也能取消,Job 的迟到完成/失败不能再交出结果。
|
||||
local Job = require("workers.job")
|
||||
local run = Job.run
|
||||
for _idx, format in ipairs({ "epub", "txt" }) do
|
||||
local pending, cancelled, callbacks = nil, false, 0
|
||||
Job.run = function(_fn, opts)
|
||||
pending = opts
|
||||
return { cancel = function() cancelled = true end }
|
||||
end
|
||||
local handle = Chapter.fetchHtmlAsync("book", { uid = "1", format = format }, function()
|
||||
callbacks = callbacks + 1
|
||||
end)
|
||||
Assert.not_nil(pending)
|
||||
handle:cancel()
|
||||
Assert.is_true(cancelled)
|
||||
pending.on_done({ text = format == "txt" and PLAIN or FULL })
|
||||
pending.on_failed("late failure")
|
||||
Assert.eq(callbacks, 0)
|
||||
end
|
||||
Job.run = run
|
||||
end
|
||||
|
||||
do
|
||||
-- TXT ZIP 缺正文就报包错误,不能退回 EPUB 清单。
|
||||
txt_zip, zip_text_missing = true, true
|
||||
Chapter.fetchHtmlAsync("book", { uid = "1595", format = "txt" }, function(html, err)
|
||||
Assert.is_nil(html)
|
||||
Assert.matches(err, "zip: chapter 1595 not in package")
|
||||
end)
|
||||
txt_zip, zip_text_missing = false, false
|
||||
end
|
||||
|
||||
do
|
||||
-- 批量:prime 五章 offline=1、chapters=0-5;随后 fetchHtml 不再打网。
|
||||
Context.rememberBookVersion("batch-book", 7)
|
||||
local before = #queries
|
||||
local chapters = {}
|
||||
for i = 1, 5 do chapters[i] = { uid = tostring(i), idx = i } end
|
||||
local ok_out, err_out
|
||||
Chapter.primeBatchAsync("batch-book", chapters, { offline = true }, function(ok, err)
|
||||
ok_out, err_out = ok, err
|
||||
end)
|
||||
Assert.is_true(ok_out)
|
||||
Assert.is_nil(err_out)
|
||||
Assert.eq(queries[before + 1].chapters, "0-5")
|
||||
Assert.eq(queries[before + 1].offline, "1")
|
||||
local after_prime = #queries
|
||||
local html_out
|
||||
Chapter.fetchHtmlAsync("batch-book", { uid = "3" }, function(html, err)
|
||||
Assert.is_nil(err)
|
||||
html_out = html
|
||||
end)
|
||||
Assert.eq(#queries, after_prime, "primed 章不得再次请求 chapterdownload")
|
||||
Assert.eq(html_out, FULL)
|
||||
end
|
||||
@@ -0,0 +1,446 @@
|
||||
--[[--
|
||||
moonsource_weread.client 离线用例:各接口的 URL 与请求体
|
||||
|
||||
@module tests.moonsource_weread.client_spec
|
||||
--]]
|
||||
|
||||
local Assert = require("support.assert")
|
||||
|
||||
local captured = {}
|
||||
local posted = {}
|
||||
|
||||
package.preload["json"] = function()
|
||||
return {
|
||||
encode = require("support.json_stub").encode,
|
||||
decode = require("support.json_stub").decode,
|
||||
}
|
||||
end
|
||||
package.loaded["json"] = nil
|
||||
|
||||
-- 网页接口回原始 JSON 串:解码与 errcode 校验在 client 里真跑
|
||||
local web_replies = {}
|
||||
package.preload["moonsource_weread.auth"] = function()
|
||||
local decode = require("support.json_stub").decode
|
||||
return {
|
||||
webGetAsync = function(url, _opts, cb)
|
||||
captured[#captured + 1] = url
|
||||
for pattern, raw in pairs(web_replies) do
|
||||
if url:find(pattern, 1, true) then
|
||||
cb(raw)
|
||||
return { cancel = function() end }
|
||||
end
|
||||
end
|
||||
if url:find("/web/shelf/sync", 1, true) then
|
||||
cb('{"pureBookCount":1,"bookCount":1,"synckey":0}')
|
||||
elseif url:find("/web/book/getProgress", 1, true) then
|
||||
cb('{"bookId":"42","book":{"chapterUid":1,"progress":10}}')
|
||||
elseif url:find("/web/book/underlines", 1, true) then
|
||||
cb('{"underlines":[]}')
|
||||
end
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
webPostAsync = function(url, body, opts, cb)
|
||||
posted.url = url
|
||||
posted.raw = body
|
||||
posted.referer = opts and opts.headers and opts.headers.Referer
|
||||
local ok, decoded = pcall(decode, body)
|
||||
posted.body = ok and decoded or nil
|
||||
if url:find("/review/add", 1, true) then
|
||||
cb('{"reviewId":"rv-1"}')
|
||||
elseif url:find("/web/book/read", 1, true) then
|
||||
cb(posted.web_read_reply or '{"succ":1}')
|
||||
else
|
||||
cb('{"succ":1}')
|
||||
end
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
end
|
||||
package.preload["moonsource_weread.eink"] = function()
|
||||
return {
|
||||
callAsync = function(method, path, opts, cb)
|
||||
posted.eink = { method = method, path = path, query = opts.query, body = opts.body }
|
||||
if path == "/shelf/sync" then
|
||||
cb(posted.shelf_reply or { books = {}, archive = {} })
|
||||
elseif path == "/book/getProgress" then
|
||||
cb({ bookId = "42", book = { chapterUid = 1, progress = 10 } })
|
||||
elseif path == "/book/underlines" then
|
||||
cb({ underlines = {} })
|
||||
elseif path == "/review/add" then
|
||||
cb({ reviewId = "rv-1" })
|
||||
elseif path == "/feature" then
|
||||
cb({ feature = { guest_token = "gt" } })
|
||||
elseif path == "/book/read" then
|
||||
cb(posted.read_reply or { succ = 1 })
|
||||
elseif path:find("^/book/%a+[Bb]ookmark$") or path:find("^/shelf/") or path == "/review/useredit"
|
||||
or path == "/review/delete" then
|
||||
cb({ succ = 1 })
|
||||
elseif path == "/book/bookmarklist" then
|
||||
cb({
|
||||
synckey = 1,
|
||||
updated = {
|
||||
{ chapterUid = 4, range = "303-332", markText = "原文", type = 1 },
|
||||
},
|
||||
chapters = { { chapterUid = 4, chapterIdx = 4 } },
|
||||
})
|
||||
elseif path == "/review/list" and opts.query.bookId == "77" then
|
||||
-- 翻页:hasMore=1 带 maxIdx 续拉,重复 reviewId 去重
|
||||
if opts.query.maxIdx == nil then
|
||||
cb({ totalCount = 2, hasMore = 1, maxIdx = 5,
|
||||
reviews = { { review = { reviewId = "a", range = "1-2", content = "甲" } } } })
|
||||
else
|
||||
cb({ hasMore = 0, reviews = {
|
||||
{ review = { reviewId = "a", range = "1-2", content = "甲" } },
|
||||
{ review = { reviewId = "b", range = "3-4", content = "乙" } },
|
||||
} })
|
||||
end
|
||||
elseif path == "/review/list" and opts.query.bookId == "88" then
|
||||
-- App 同款参数被拒(-2003),listType=11 能通
|
||||
if opts.query.listType == 1 then
|
||||
cb(nil, "-2003 参数格式错误")
|
||||
else
|
||||
cb({ hasMore = 0, reviews = { { review = { reviewId = "c", content = "丙" } } } })
|
||||
end
|
||||
elseif path == "/store/search" then
|
||||
cb(posted.search_reply or { data = { { bookInfo = { bookId = "9", title = "三体" } } } })
|
||||
elseif path == "/review/list" then
|
||||
cb({
|
||||
totalCount = 3,
|
||||
reviews = {
|
||||
{ review = { bookId = "99", range = "1-2", content = "本书" } },
|
||||
{ review = { bookId = "3300107657", range = "464-466", content = "别的书" } },
|
||||
{ review = { range = "5-6", content = "无 bookId 保留" } },
|
||||
},
|
||||
})
|
||||
else
|
||||
cb({
|
||||
readLongest = {
|
||||
{ book = { bookId = "1" }, readTime = 3600 },
|
||||
},
|
||||
})
|
||||
end
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
end
|
||||
package.loaded["moonsource_weread.eink"] = nil
|
||||
package.preload["moonsource_weread.client"] = nil
|
||||
package.loaded["moonsource_weread.client"] = nil
|
||||
|
||||
local client = require("moonsource_weread.client")
|
||||
|
||||
do
|
||||
-- 书架 / 进度 / 详情 / 目录 / 想法 / 划线全走 App 协议
|
||||
local function call(fn, ...)
|
||||
posted = {}
|
||||
fn(...)
|
||||
return posted.eink
|
||||
end
|
||||
local wire
|
||||
local req = call(client.shelfSyncAsync, client, function(d) wire = d end)
|
||||
Assert.eq(req.method .. req.path, "GET/shelf/sync")
|
||||
Assert.eq(req.query.album, 1)
|
||||
Assert.not_nil(wire)
|
||||
|
||||
-- 增量索引:带游标与本地计数,只要 id 不要元数据
|
||||
req = call(client.shelfSyncIdsAsync, client, 100, 18, function(d) wire = d end)
|
||||
Assert.eq(req.method .. req.path, "GET/shelf/sync")
|
||||
Assert.eq(req.query.synckey, 100)
|
||||
Assert.eq(req.query.onlyBookid, 1)
|
||||
Assert.eq(req.query.localBookCount, 18)
|
||||
|
||||
-- 变更补详情:POST /shelf/syncbook 带 bookIds
|
||||
req = call(client.shelfSyncBooksAsync, client, { "b1", "b2" }, function() end)
|
||||
Assert.eq(req.method .. req.path, "POST/shelf/syncbook")
|
||||
Assert.eq(req.body.bookIds[1], "b1")
|
||||
Assert.eq(req.body.bookIds[2], "b2")
|
||||
|
||||
req = call(client.getProgressAsync, client, "42", function(d) wire = d end)
|
||||
Assert.eq(req.path, "/book/getProgress")
|
||||
Assert.eq(req.query.bookId, "42")
|
||||
Assert.eq(wire.book.progress, 10)
|
||||
|
||||
req = call(client.chapterInfosAsync, client, "42", function() end)
|
||||
Assert.eq(req.path, "/book/chapterInfos")
|
||||
Assert.eq(req.body.synckeys[1], 0)
|
||||
Assert.eq(req.body.bookIds[1], "42")
|
||||
|
||||
req = call(client.bookInfoAsync, client, "42", function() end)
|
||||
Assert.eq(req.path, "/book/info")
|
||||
Assert.eq(req.query.bookId, "42")
|
||||
|
||||
req = call(client.addToShelfAsync, client, "123", function() end)
|
||||
Assert.eq(req.path, "/shelf/add")
|
||||
Assert.eq(req.body.bookIds[1], "123")
|
||||
req = call(client.removeFromShelfAsync, client, "123", function() end)
|
||||
Assert.eq(req.path, "/shelf/delete")
|
||||
Assert.eq(req.body.bookIds[1], "123")
|
||||
|
||||
req = call(client.saveArchiveAsync, client, 7, "科幻", { "1", "2" }, function() end)
|
||||
Assert.eq(req.path, "/shelf/archive")
|
||||
Assert.eq(req.body.archiveId, 7)
|
||||
Assert.eq(req.body.name, "科幻")
|
||||
Assert.eq(req.body.bookIds[2], "2")
|
||||
|
||||
req = call(client.addReviewAsync, client, { bookId = "99", content = "想法", range = "1-2" },
|
||||
function(d) wire = d end)
|
||||
Assert.eq(req.path, "/review/add")
|
||||
Assert.eq(wire.reviewId, "rv-1")
|
||||
req = call(client.editReviewAsync, client, { reviewId = "rv-1", content = "修改" }, function() end)
|
||||
Assert.eq(req.path, "/review/useredit")
|
||||
req = call(client.deleteReviewAsync, client, "rv-1", function() end)
|
||||
Assert.eq(req.path, "/review/delete")
|
||||
Assert.eq(req.body.reviewId, "rv-1")
|
||||
|
||||
req = call(client.addBookmarkAsync, client, "99", 8, { bookId = "99", range = "1-6" }, function() end)
|
||||
Assert.eq(req.path, "/book/addBookmark")
|
||||
Assert.eq(req.body.range, "1-6")
|
||||
req = call(client.updateBookmarkAsync, client, { bookmarkId = "bm-1" }, function() end)
|
||||
Assert.eq(req.path, "/book/updateBookmark")
|
||||
req = call(client.removeBookmarkAsync, client, "bm-1", function() end)
|
||||
Assert.eq(req.path, "/book/removeBookmark")
|
||||
Assert.eq(req.body.bookmarkIds[1], "bm-1", "App 版删除接收 bookmarkIds 数组")
|
||||
|
||||
req = call(client.underlinesAsync, client, "3300055092", "4", function(d) wire = d end)
|
||||
Assert.eq(req.path, "/book/underlines")
|
||||
Assert.eq(req.query.chapterUid, "4")
|
||||
Assert.eq(#wire.underlines, 0)
|
||||
req = call(client.readReviewsAsync, client, "3300055092", "4",
|
||||
{ { range = "386-407", maxIdx = 0, count = 1, synckey = 0 } }, function() end)
|
||||
Assert.eq(req.path, "/book/readreviews")
|
||||
Assert.eq(req.body.chapterUid, 4)
|
||||
Assert.eq(req.body.reviews[1].range, "386-407")
|
||||
|
||||
req = call(client.searchAsync, client, "三体", function(d) wire = d end)
|
||||
Assert.eq(req.path, "/store/search")
|
||||
Assert.eq(req.query.keyword, "三体")
|
||||
Assert.eq(req.query.v, 2)
|
||||
Assert.eq(req.query.type, 0)
|
||||
Assert.eq(wire.books[1].bookInfo.bookId, "9")
|
||||
end
|
||||
|
||||
do
|
||||
-- 个人划线走 Eink:Web 会话打 /web/book/bookmarklist 恒返回 {}
|
||||
captured = {}
|
||||
posted = {}
|
||||
local wire
|
||||
client:bookmarkListAsync("99", function(data) wire = data end)
|
||||
Assert.eq(#captured, 0)
|
||||
Assert.eq(posted.eink.method, "GET")
|
||||
Assert.eq(posted.eink.path, "/book/bookmarklist")
|
||||
Assert.eq(posted.eink.query.bookId, "99")
|
||||
Assert.eq(posted.eink.query.synckey, 0)
|
||||
Assert.eq(#wire.updated, 1)
|
||||
Assert.eq(wire.chapters[1].chapterIdx, 4)
|
||||
end
|
||||
|
||||
do
|
||||
posted = {}
|
||||
local wire
|
||||
client:myReviewsAsync("99", function(data) wire = data end)
|
||||
Assert.eq(posted.eink.path, "/review/list")
|
||||
Assert.eq(posted.eink.query.bookId, "99")
|
||||
Assert.eq(posted.eink.query.mine, 1)
|
||||
Assert.eq(posted.eink.query.listType, 1)
|
||||
-- 别的书的想法剔掉,否则会按 range 挂进这本书(串书)
|
||||
Assert.eq(#wire.reviews, 2)
|
||||
Assert.eq(wire.reviews[1].review.content, "本书")
|
||||
Assert.eq(wire.reviews[2].review.content, "无 bookId 保留")
|
||||
Assert.eq(wire.totalCount, 3, "全量判定保留服务端口径")
|
||||
Assert.not_nil(wire)
|
||||
|
||||
client:myReviewsAsync("77", function(data) wire = data end)
|
||||
Assert.eq(posted.eink.query.maxIdx, 5, "hasMore=1 时按回包 maxIdx 续拉")
|
||||
Assert.eq(#wire.reviews, 2)
|
||||
Assert.eq(wire.reviews[2].review.content, "乙")
|
||||
Assert.eq(wire.hasMore, 0)
|
||||
|
||||
client:myReviewsAsync("88", function(data) wire = data end)
|
||||
Assert.eq(posted.eink.query.listType, 11, "首页被拒改用 listType=11 重试")
|
||||
Assert.eq(wire.reviews[1].review.content, "丙")
|
||||
end
|
||||
|
||||
do
|
||||
captured = {}
|
||||
posted = {}
|
||||
local wire, err
|
||||
client:readStatsAsync("monthly", nil, function(data, e) wire, err = data, e end)
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(posted.eink.path, "/readdata/detail")
|
||||
Assert.eq(posted.eink.query.mode, "monthly")
|
||||
Assert.is_nil(posted.eink.query.baseTime)
|
||||
Assert.eq(#(wire.readLongest or {}), 1)
|
||||
end
|
||||
|
||||
do
|
||||
-- 进度走 App /book/read:本地坐标,阅读时长为 0。时长在统计上报里,不在这里重计。
|
||||
local Eink = require("moonsource_weread.eink")
|
||||
local orig_call = Eink.callAsync
|
||||
Eink.credentials = function() return { vid = "1", device_id = "d", refresh_token = "r" } end
|
||||
Eink.installId = function() return "i" end
|
||||
Eink.setGuestToken = function() end
|
||||
local fail_read = false
|
||||
Eink.callAsync = function(method, path, opts, cb)
|
||||
posted.eink = { method = method, path = path, body = opts and opts.body, query = opts and opts.query }
|
||||
if path == "/feature" then
|
||||
cb({ feature = { guest_token = "gt" } })
|
||||
elseif path == "/book/read" then
|
||||
cb(fail_read and { succ = 0 } or { succ = 1 })
|
||||
else
|
||||
cb({})
|
||||
end
|
||||
return { cancel = function() end }
|
||||
end
|
||||
posted = {}
|
||||
local ok, err
|
||||
client:putProgressAsync("99", {
|
||||
progress = 50, chapter_uid = 8, chapter_idx = 3, chapter_offset = 24000, chapter_fraction = 0.5,
|
||||
}, function(data, e) ok, err = data, e end)
|
||||
Assert.eq(posted.eink.path, "/book/read")
|
||||
Assert.eq(posted.eink.method, "POST")
|
||||
Assert.eq(posted.eink.body.bookId, "99")
|
||||
Assert.eq(posted.eink.body.chapterUid, 8)
|
||||
Assert.eq(posted.eink.body.chapterIdx, 3)
|
||||
Assert.eq(posted.eink.body.chapterOffset, 24000)
|
||||
Assert.eq(posted.eink.body.chapterProgress, 50)
|
||||
Assert.eq(posted.eink.body.progress, 50)
|
||||
Assert.eq(posted.eink.body.currentProgress, 50)
|
||||
Assert.eq(posted.eink.body.readingTime, 0)
|
||||
Assert.eq(#posted.eink.body.hours, 0)
|
||||
Assert.is_nil(posted.eink.body.readUpdateTime, "单条 /book/read 不带进度时间")
|
||||
Assert.is_nil(posted.eink.body.isResendReadingInfo)
|
||||
Assert.not_nil(posted.eink.body.signature)
|
||||
Assert.not_nil(ok)
|
||||
Assert.is_nil(err)
|
||||
Assert.is_nil(posted.url, "进度不再打网页阅读接口")
|
||||
|
||||
client:putProgressAsync("99", {
|
||||
progress = 50, chapter_uid = 8, chapter_idx = 3, chapter_offset = 24000,
|
||||
chapter_fraction = 0.5,
|
||||
hours = { { startOfHour = 3600, readingTime = 15, timeZone = "+08:00", ttsTime = 0 } },
|
||||
}, function(data, e) ok, err = data, e end)
|
||||
Assert.eq(posted.eink.body.readingTime, 15, "时长随进度一起报,服务端才改坐标")
|
||||
Assert.eq(posted.eink.body.hours[1].startOfHour, 3600)
|
||||
Assert.eq(posted.eink.body.chapterOffset, 24000)
|
||||
Assert.not_nil(ok)
|
||||
|
||||
fail_read = true
|
||||
ok, err = nil, nil
|
||||
client:putProgressAsync("99", { progress = 50, chapter_uid = 8 },
|
||||
function(data, e) ok, err = data, e end)
|
||||
Assert.is_nil(ok)
|
||||
Assert.not_nil(err)
|
||||
|
||||
-- 跨小时走离线批量。-2054 丢掉 /config token,换新 token 再签一次。
|
||||
local sha256 = require("ffi/sha2").sha256
|
||||
local configs, batches, reject = 0, {}, true
|
||||
Eink.callAsync = function(method, path, opts, cb)
|
||||
posted.eink = { method = method, path = path, body = opts and opts.body, query = opts and opts.query }
|
||||
if path == "/feature" then
|
||||
cb({ feature = { guest_token = "gt" } })
|
||||
elseif path == "/config" then
|
||||
configs = configs + 1
|
||||
cb({ token = "t" .. configs })
|
||||
elseif path == "/book/batchUploadProgress" then
|
||||
batches[#batches + 1] = opts.body
|
||||
if reject then
|
||||
reject = false
|
||||
cb(nil, "expired", { errcode = -2054 })
|
||||
else
|
||||
cb({ succ = 1 })
|
||||
end
|
||||
elseif path == "/book/read" then
|
||||
cb({ succ = 1 })
|
||||
else
|
||||
cb({})
|
||||
end
|
||||
return { cancel = function() end }
|
||||
end
|
||||
ok, err = nil, nil
|
||||
client:putProgressAsync("99", {
|
||||
progress = 50, chapter_uid = 8, chapter_idx = 3, chapter_offset = 24000,
|
||||
hours = {
|
||||
{ startOfHour = 0, readingTime = 10, timeZone = "+08:00", ttsTime = 0 },
|
||||
{ startOfHour = 3600, readingTime = 15, timeZone = "+08:00", ttsTime = 0 },
|
||||
},
|
||||
}, function(data, e) ok, err = data, e end)
|
||||
Assert.not_nil(ok)
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(configs, 2, "-2054 之后重新取 token")
|
||||
Assert.eq(#batches, 2)
|
||||
Assert.eq(posted.eink.path, "/book/batchUploadProgress")
|
||||
Assert.eq(posted.eink.query, nil)
|
||||
Assert.eq(batches[1].books[1].isResendReadingInfo, 0, "实时跨小时不是补报积压")
|
||||
Assert.eq(batches[1].books[1].readingTime, 25)
|
||||
Assert.eq(#batches[1].books[1].hours, 2)
|
||||
Assert.eq(batches[1].books[1].chapterOffset, 24000)
|
||||
Assert.eq(batches[1].books[1].readUpdateTime, batches[1].books[1].timestamp)
|
||||
Assert.eq(#batches[1].books[1].signature, 64, "每本仍用 guest 签名")
|
||||
local function outer(batch, token)
|
||||
return sha256(tostring(batch.timestamp) .. token .. tostring(batch.random))
|
||||
end
|
||||
Assert.eq(batches[1].signature, outer(batches[1], "t1"))
|
||||
Assert.eq(batches[2].signature, outer(batches[2], "t2"))
|
||||
Assert.is_true(batches[1].signature ~= batches[2].signature)
|
||||
|
||||
local marked
|
||||
Eink.callAsync = function(_method, path, opts, cb)
|
||||
if path == "/book/markstatus" then
|
||||
marked = opts.body
|
||||
cb({ status = 4 })
|
||||
else
|
||||
cb(nil, "no")
|
||||
end
|
||||
return { cancel = function() end }
|
||||
end
|
||||
ok, err = nil, nil
|
||||
client:markFinishedAsync("99", function(data, e) ok, err = data, e end)
|
||||
Assert.eq(marked.bookId, "99")
|
||||
Assert.eq(marked.status, 4)
|
||||
Assert.eq(marked.finishInfo, 0)
|
||||
Assert.eq(marked.isCancel, 0)
|
||||
Assert.eq(marked.auto, 1)
|
||||
Assert.eq(ok.status, 4)
|
||||
Assert.is_nil(err)
|
||||
Eink.callAsync = orig_call
|
||||
end
|
||||
|
||||
-- bookCount 大于 books 条数也原样交回(专辑、公众号不在这三份列表里)
|
||||
do
|
||||
local data, err
|
||||
posted = { shelf_reply = { bookCount = 3, books = { { bookId = "1" }, { bookId = "2" } }, archive = {} } }
|
||||
client:shelfSyncAsync(function(d, e) data, err = d, e end)
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(data.bookCount, 3)
|
||||
Assert.eq(#data.books, 2)
|
||||
posted = {}
|
||||
end
|
||||
|
||||
-- Web reader session supplies the token for a zero-duration presence heartbeat only.
|
||||
do
|
||||
web_replies["/web/reader/"] = '<html>{"psvts":"ps","pclts":"pc","token":"tk"}</html>'
|
||||
local state, state_err
|
||||
client:readerStateAsync("99", function(value, err) state, state_err = value, err end)
|
||||
Assert.eq(state.psvts, "ps")
|
||||
Assert.eq(state.pclts, "pc")
|
||||
Assert.eq(state.token, "tk")
|
||||
Assert.is_nil(state_err)
|
||||
Assert.is_true(captured[#captured]:find("/web/reader/", 1, true) ~= nil)
|
||||
|
||||
posted.web_read_reply = '{"succ":1}'
|
||||
local result, report_err
|
||||
client:reportReadAsync({ rt = 0 }, "https://weread.qq.com/web/reader/99",
|
||||
function(value, err) result, report_err = value, err end)
|
||||
Assert.eq(posted.url, "https://weread.qq.com/web/book/read")
|
||||
Assert.eq(posted.body.rt, 0)
|
||||
Assert.eq(posted.referer, "https://weread.qq.com/web/reader/99")
|
||||
Assert.not_nil(result)
|
||||
Assert.is_nil(report_err)
|
||||
|
||||
posted.web_read_reply = "{}"
|
||||
result, report_err = nil, nil
|
||||
client:reportReadAsync({ rt = 0 }, nil, function(value, err) result, report_err = value, err end)
|
||||
Assert.is_nil(result)
|
||||
Assert.not_nil(report_err)
|
||||
web_replies["/web/reader/"] = nil
|
||||
end
|
||||
@@ -0,0 +1,81 @@
|
||||
--[[--
|
||||
moonsource_weread.context 离线用例:reader 状态本地生成、会话内固定、过期重建
|
||||
|
||||
@module tests.wechat_context_spec
|
||||
--]]
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local Protocol = require("moonsource_weread.protocol")
|
||||
local Context = require("moonsource_weread.context")
|
||||
|
||||
local real_time = os.time
|
||||
local now = 1700000000
|
||||
os.time = function(t) return t and real_time(t) or now end
|
||||
|
||||
-- 未缓存:按当前时间生成;psvts 模拟更早的出页时间,不能与 pclts 相同。
|
||||
do
|
||||
Context.clear()
|
||||
local reader = Context.reader("b1", "c1")
|
||||
Assert.eq(reader.psvts, Protocol.encode(now - 1))
|
||||
Assert.eq(reader.pclts, Protocol.encode(now))
|
||||
end
|
||||
|
||||
-- 会话内固定:进入阅读与之后的时长上报必须共用同一个 pc,entered 标记也要留住。
|
||||
do
|
||||
Context.clear()
|
||||
local reader = Context.reader("b1", "c1")
|
||||
reader.entered = true
|
||||
local enter = Protocol.makeEnterReadPayload({
|
||||
book_id = "b1", chapter_uid = "c1", psvts = reader.psvts, pclts = reader.pclts,
|
||||
})
|
||||
now = now + 45
|
||||
local again = Context.reader("b1", "c1")
|
||||
Assert.is_true(again == reader, "TTL 内复用同一状态")
|
||||
local read = Protocol.makeReadPayload({
|
||||
book_id = "b1", chapter_uid = "c1", psvts = again.psvts, pclts = again.pclts,
|
||||
elapsed_seconds = 45,
|
||||
})
|
||||
Assert.eq(enter.pc, read.pc, "enter 与时长上报的 pc 必须一致")
|
||||
Assert.eq(enter.ps, read.ps)
|
||||
end
|
||||
|
||||
-- 按章隔离;过 TTL 重建,entered 清掉以重新发进入阅读。
|
||||
do
|
||||
Context.clear()
|
||||
local c1 = Context.reader("b1", "c1")
|
||||
c1.entered = true
|
||||
Assert.is_nil(Context.reader("b1", "c2").entered)
|
||||
now = now + 15 * 60
|
||||
local fresh = Context.reader("b1", "c1")
|
||||
Assert.is_nil(fresh.entered)
|
||||
Assert.eq(fresh.pclts, Protocol.encode(now))
|
||||
end
|
||||
|
||||
-- 在读会话按书缓存真实网页参数;强制刷新后必须重新 enter。
|
||||
do
|
||||
Context.clear()
|
||||
local fetches = 0
|
||||
local client = {
|
||||
readerStateAsync = function(_, book_id, cb)
|
||||
Assert.eq(book_id, "b1")
|
||||
fetches = fetches + 1
|
||||
cb({ psvts = "ps" .. fetches, pclts = "pc" .. fetches, token = "token" })
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
local first
|
||||
Context.sessionAsync(client, "b1", false, function(session) first = session end)
|
||||
first.entered = true
|
||||
local cached
|
||||
Context.sessionAsync(client, "b1", false, function(session) cached = session end)
|
||||
Assert.is_true(cached == first)
|
||||
Assert.eq(fetches, 1)
|
||||
|
||||
local fresh
|
||||
Context.sessionAsync(client, "b1", true, function(session) fresh = session end)
|
||||
Assert.eq(fetches, 2)
|
||||
Assert.eq(fresh.psvts, "ps2")
|
||||
Assert.is_nil(fresh.entered)
|
||||
end
|
||||
|
||||
os.time = real_time
|
||||
@@ -0,0 +1,276 @@
|
||||
--[[--
|
||||
moonsource_weread.eink 离线用例:设备 ID、登录签名与请求体、版本/鉴权请求头、
|
||||
401 / -2012 续期重放语义、-2041 不重试、令牌落网页会话字段(wr_vid/wr_skey)。
|
||||
|
||||
@module tests.wechat_eink_spec
|
||||
--]]
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local JsonStub = require("support.json_stub")
|
||||
local sha256 = require("ffi/sha2").sha256
|
||||
|
||||
local state = { cfg = {}, requests = {}, responder = nil }
|
||||
local switches = 0
|
||||
require("source.logout").replaceLibrary = function(id, commit)
|
||||
Assert.eq(id, "ext.weread")
|
||||
switches = switches + 1
|
||||
commit()
|
||||
return true
|
||||
end
|
||||
|
||||
package.preload["utils.settings"] = function()
|
||||
return {
|
||||
getSource = function() return state.cfg end,
|
||||
saveSource = function(_, c) state.cfg = c end,
|
||||
}
|
||||
end
|
||||
package.preload["http.request"] = function()
|
||||
return {
|
||||
ok = function(code) return code ~= nil and code >= 200 and code < 300 end,
|
||||
request = function(opts, cb)
|
||||
state.requests[#state.requests + 1] = opts
|
||||
local res = state.responder(opts)
|
||||
cb(res)
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
end
|
||||
package.preload["json"] = function()
|
||||
return { encode = JsonStub.encode, decode = JsonStub.decode }
|
||||
end
|
||||
for _, name in ipairs({ "json", "http.request", "utils.settings", "moonsource_weread.eink" }) do
|
||||
package.loaded[name] = nil
|
||||
end
|
||||
|
||||
local Eink = require("moonsource_weread.eink")
|
||||
|
||||
local function reply(code, body)
|
||||
return { code = code, body = JsonStub.encode(body) }
|
||||
end
|
||||
|
||||
local function reset(cfg)
|
||||
state.cfg = cfg or {}
|
||||
state.requests = {}
|
||||
end
|
||||
|
||||
local function logged_in()
|
||||
reset({ wr_vid = "42", wr_skey = "at-1", eink = { refresh_token = "rt-1", device_id = "dev-1", guest_token = "gt" } })
|
||||
end
|
||||
|
||||
-- 设备 ID:前缀 + 19 位数字,首次生成后落盘并复用。
|
||||
do
|
||||
reset()
|
||||
local id = Eink.deviceId()
|
||||
Assert.matches(id, "^[1-9]%d+$")
|
||||
Assert.eq(#id, 38)
|
||||
Assert.eq(Eink.deviceId(), id, "设备 ID 落盘后复用")
|
||||
Assert.eq(state.cfg.eink.device_id, id)
|
||||
end
|
||||
|
||||
-- 旧版 "eink…" 设备 ID 登录时换成数字 ID(手机渠道配它续期会被风控)。
|
||||
do
|
||||
reset({ eink = { device_id = "eink3346912251234" } })
|
||||
local id = Eink.deviceId()
|
||||
Assert.matches(id, "^[1-9]%d+$")
|
||||
Assert.eq(state.cfg.eink.device_id, id)
|
||||
end
|
||||
|
||||
-- 签名 = sha256(毫秒时间戳 .. deviceId .. random),时间戳不能出现科学计数法。
|
||||
do
|
||||
Assert.eq(Eink.signature(1790000000123, "dev", 7), sha256("1790000000123dev7"))
|
||||
end
|
||||
|
||||
-- 扫码换令牌:请求体字段与签名自洽,令牌落 wr_vid/wr_skey,续期令牌落 cfg.eink。
|
||||
do
|
||||
reset({ eink = { device_id = "99" } })
|
||||
state.responder = function()
|
||||
return reply(200, { vid = 1001, accessToken = "at", refreshToken = "rt" })
|
||||
end
|
||||
local Context = require("moonsource_weread.context")
|
||||
Context.reader("b1", "c1").entered = true
|
||||
local user
|
||||
Eink.completeQrLoginAsync({ wx_code = "code-1" }, function(u) user = u end)
|
||||
Assert.is_nil(Context.reader("b1", "c1").entered, "登录可能换号:清掉上个账号的进入阅读状态")
|
||||
local req = state.requests[1]
|
||||
Assert.eq(req.url, "https://i.weread.qq.com/login")
|
||||
Assert.eq(req.method, "POST")
|
||||
Assert.eq(req.headers.basever, "10.2.2.10167650")
|
||||
Assert.matches(req.headers["User-Agent"], "WeRead/10.2.2")
|
||||
local body = JsonStub.decode(req.body)
|
||||
Assert.eq(body.code, "code-1")
|
||||
Assert.eq(body.deviceId, "99")
|
||||
Assert.eq(body.deviceType, 1)
|
||||
Assert.eq(body.isFromQrcode, 1)
|
||||
Assert.eq(body.signature, Eink.signature(body.timestamp, "99", body.random))
|
||||
Assert.eq(user.user_id, "1001")
|
||||
Assert.eq(state.cfg.wr_skey, "at")
|
||||
Assert.eq(state.cfg.wr_vid, "1001")
|
||||
Assert.eq(state.cfg.user_id, "1001")
|
||||
Assert.eq(state.cfg.eink.refresh_token, "rt")
|
||||
Assert.eq(state.cfg.eink.device_id, "99")
|
||||
Assert.eq(switches, 1)
|
||||
Assert.eq(Eink.credentials().access_token, "at")
|
||||
end
|
||||
|
||||
-- 登录回包缺令牌按失败,不落盘。
|
||||
do
|
||||
reset({ eink = { device_id = "99" } })
|
||||
state.responder = function() return reply(200, { errCode = -1, errMsg = "bad" }) end
|
||||
local user, err
|
||||
Eink.completeQrLoginAsync({ wx_code = "c" }, function(u, e) user, err = u, e end)
|
||||
Assert.is_nil(user)
|
||||
Assert.matches(err, "bad")
|
||||
Assert.is_nil(state.cfg.wr_skey)
|
||||
Assert.is_false(Eink.hasSession())
|
||||
end
|
||||
|
||||
-- 正常调用:带 vid/accessToken 与版本头,query 拼进 URL。
|
||||
do
|
||||
logged_in()
|
||||
state.responder = function() return reply(200, { books = {} }) end
|
||||
local data, err, meta
|
||||
Eink.callAsync("GET", "/shelf/sync", { query = { synckey = 0 } }, function(d, e, m)
|
||||
data, err, meta = d, e, m
|
||||
end)
|
||||
local req = state.requests[1]
|
||||
Assert.eq(req.url, "https://i.weread.qq.com/shelf/sync?synckey=0")
|
||||
Assert.eq(req.headers.vid, "42")
|
||||
Assert.eq(req.headers.accessToken, "at-1")
|
||||
Assert.eq(req.headers.appver, "10.2.2.10167650")
|
||||
Assert.is_nil(err)
|
||||
Assert.not_nil(data.books)
|
||||
Assert.eq(meta.status, 200)
|
||||
end
|
||||
|
||||
-- GET 遇 -2012:续期(refreshToken + kickType)后用新令牌重放一次,新凭据落盘。
|
||||
do
|
||||
logged_in()
|
||||
state.cfg.eink.install_id = "inst"
|
||||
local calls = 0
|
||||
state.responder = function(opts)
|
||||
if opts.url:find("/login", 1, true) then
|
||||
return reply(200, { vid = 42, accessToken = "at-2", refreshToken = "rt-2" })
|
||||
end
|
||||
calls = calls + 1
|
||||
if calls == 1 then return reply(200, { errCode = -2012, errMsg = "expired" }) end
|
||||
return reply(200, { ok = 1 })
|
||||
end
|
||||
local data
|
||||
Eink.callAsync("GET", "/book/getProgress", { query = { bookId = "b" } }, function(d) data = d end)
|
||||
Assert.eq(#state.requests, 3, "原请求 + 续期 + 重放")
|
||||
local mint = JsonStub.decode(state.requests[2].body)
|
||||
Assert.eq(mint.refreshToken, "rt-1")
|
||||
Assert.eq(mint.kickType, 1)
|
||||
local App = require("moonsource_weread.app")
|
||||
Assert.eq(mint.signature, App.sign({ "gt", "dev-1", string.format("%.0f", mint.timestamp), tostring(mint.random), "rt-1" }))
|
||||
Assert.is_nil(mint.deviceType, "App 续期体没有 deviceType")
|
||||
Assert.eq(mint.wxToken, 0)
|
||||
Assert.eq(mint.refCgi, "")
|
||||
Assert.eq(state.requests[3].headers.accessToken, "at-2")
|
||||
Assert.eq(data.ok, 1)
|
||||
Assert.eq(state.cfg.wr_skey, "at-2")
|
||||
Assert.eq(state.cfg.eink.refresh_token, "rt-2")
|
||||
Assert.eq(state.cfg.eink.device_id, "dev-1")
|
||||
Assert.eq(state.cfg.eink.install_id, "inst", "续期不丢安装 ID")
|
||||
end
|
||||
|
||||
-- 公众号授权:同一次 /login,wxToken=1,refCgi 是失败的那次请求。
|
||||
do
|
||||
logged_in()
|
||||
state.responder = function() return reply(200, { vid = 42, accessToken = "at-wx", refreshToken = "rt-wx" }) end
|
||||
local ok
|
||||
Eink.refreshAsync(function(o) ok = o end, { wxToken = 1, refCgi = "https://weread.qq.com/web/mp/articles?bookId=MP_WXS_1" })
|
||||
local mint = JsonStub.decode(state.requests[1].body)
|
||||
Assert.is_true(ok)
|
||||
Assert.eq(mint.wxToken, 1)
|
||||
Assert.eq(mint.refCgi, "https://weread.qq.com/web/mp/articles?bookId=MP_WXS_1")
|
||||
Assert.eq(mint.kickType, 1)
|
||||
Assert.eq(state.cfg.eink.refresh_token, "rt-wx")
|
||||
end
|
||||
|
||||
-- 续期回包不带 refreshToken(线上常态):沿用旧 refreshToken,仍算成功。
|
||||
do
|
||||
logged_in()
|
||||
state.responder = function() return reply(200, { vid = 42, accessToken = "at-3" }) end
|
||||
local ok, err
|
||||
Eink.refreshAsync(function(o, e) ok, err = o, e end)
|
||||
Assert.is_true(ok)
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(state.cfg.wr_skey, "at-3")
|
||||
Assert.eq(state.cfg.eink.refresh_token, "rt-1")
|
||||
end
|
||||
|
||||
-- 扫码登录回包缺 refreshToken 仍按失败。
|
||||
do
|
||||
reset({ eink = { device_id = "99" } })
|
||||
state.responder = function() return reply(200, { vid = 1, accessToken = "at" }) end
|
||||
local user
|
||||
Eink.completeQrLoginAsync({ wx_code = "c" }, function(u) user = u end)
|
||||
Assert.is_nil(user)
|
||||
Assert.is_nil(state.cfg.wr_skey)
|
||||
end
|
||||
|
||||
-- POST 遇 401:只续期不重放(写可能已落地),回调失败。
|
||||
do
|
||||
logged_in()
|
||||
state.responder = function(opts)
|
||||
if opts.url:find("/login", 1, true) then
|
||||
return reply(200, { vid = 42, accessToken = "at-2", refreshToken = "rt-2" })
|
||||
end
|
||||
return { code = 401, body = "" }
|
||||
end
|
||||
local data, err
|
||||
Eink.callAsync("POST", "/book/read", { body = { a = 1 } }, function(d, e) data, err = d, e end)
|
||||
Assert.eq(#state.requests, 2, "原请求 + 续期,不重放")
|
||||
Assert.is_nil(data)
|
||||
Assert.not_nil(err)
|
||||
Assert.eq(state.cfg.wr_skey, "at-2", "续期仍然落盘,下个请求可用")
|
||||
Assert.eq(state.requests[1].headers["Content-Type"], "application/json; charset=UTF-8")
|
||||
end
|
||||
|
||||
-- -2041 人机验证:不续期、不重试。
|
||||
do
|
||||
logged_in()
|
||||
state.responder = function() return reply(200, { errCode = -2041 }) end
|
||||
local err, meta
|
||||
Eink.callAsync("GET", "/shelf/sync", nil, function(_, e, m) err, meta = e, m end)
|
||||
Assert.eq(#state.requests, 1)
|
||||
Assert.matches(err, "%-2041")
|
||||
Assert.eq(meta.errcode, -2041)
|
||||
end
|
||||
|
||||
-- 官方 10.2.2:errMsg 等于错误码时不原样展示。-2025 进阅读错误页「加载失败」;有中文说明则保留。
|
||||
do
|
||||
logged_in()
|
||||
state.responder = function() return { code = 499, body = '{"errCode":-2025,"errMsg":"-2025"}' } end
|
||||
local err, meta
|
||||
Eink.callAsync("GET", "/book/chapterdownload", nil, function(_, e, m) err, meta = e, m end)
|
||||
Assert.eq(err, "加载失败")
|
||||
Assert.eq(meta.errcode, -2025)
|
||||
Assert.eq(Eink.userMessage(-2030, "-2030"), "本书已下架")
|
||||
Assert.eq(Eink.userMessage(-2112, ""), "余额不足")
|
||||
Assert.eq(Eink.userMessage(-2223, "-2223", 402), "试读结束")
|
||||
Assert.eq(Eink.userMessage(-2281, "-2281"), "章节价格已更新,请重新购买")
|
||||
Assert.eq(Eink.userMessage(-2202, nil), "章节已经购买过,请勿重复购买")
|
||||
Assert.eq(Eink.userMessage(-1, "服务器忙"), "服务器忙")
|
||||
Assert.eq(Eink.userMessage(nil, "", 500), "HTTP 500")
|
||||
end
|
||||
|
||||
-- 未登录直接失败,不发请求;退出登录保留设备 ID。
|
||||
-- 只有网页会话、没有 refresh_token 也不算 Eink 会话(网页扫码的老用户)。
|
||||
do
|
||||
reset({ wr_vid = "42", wr_skey = "web" })
|
||||
Assert.is_false(Eink.hasSession())
|
||||
end
|
||||
|
||||
do
|
||||
logged_in()
|
||||
Eink.clearSession()
|
||||
Assert.is_false(Eink.hasSession())
|
||||
Assert.eq(state.cfg.eink.device_id, "dev-1")
|
||||
Assert.is_nil(state.cfg.eink.refresh_token)
|
||||
local err
|
||||
Eink.callAsync("GET", "/shelf/sync", nil, function(_, e) err = e end)
|
||||
Assert.not_nil(err)
|
||||
Assert.eq(#state.requests, 0)
|
||||
end
|
||||
@@ -0,0 +1,511 @@
|
||||
--[[--
|
||||
moonsource_weread.mapper 离线用例
|
||||
|
||||
@module tests.moonsource_weread.mapper_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")
|
||||
|
||||
package.preload["moonsource_weread.mapper"] = nil
|
||||
package.loaded["moonsource_weread.mapper"] = nil
|
||||
package.preload["source.contract"] = nil
|
||||
-- contract 可能仍在 loaded,保留即可
|
||||
|
||||
local Mapper = require("moonsource_weread.mapper")
|
||||
|
||||
do
|
||||
local _b, cover = Mapper.book({ bookId = "wx-2", cover = "https://cdn.weread.qq.com/weread/cover/80/y_1/s_y_1.jpg" })
|
||||
Assert.eq(cover, "https://cdn.weread.qq.com/weread/cover/80/y_1/t7_y_1.jpg")
|
||||
end
|
||||
|
||||
do
|
||||
local b, cover = Mapper.book({
|
||||
bookId = "wx-1",
|
||||
bookName = "三体",
|
||||
author = "刘慈欣",
|
||||
cover = "http://x/c.jpg",
|
||||
progressPercent = 42,
|
||||
})
|
||||
Assert.eq(b.source_id, "ext.weread")
|
||||
Assert.eq(b.stable_id, "wx-1")
|
||||
Assert.eq(b.title, "三体")
|
||||
Assert.eq(b.percent, 42)
|
||||
Assert.eq(cover, "http://x/c.jpg")
|
||||
Assert.is_nil(b.id)
|
||||
end
|
||||
|
||||
-- 空封面必须视为缺失,不能参与远端 upsert 覆盖本地已有封面。
|
||||
do
|
||||
local b, cover = Mapper.book({ bookId = "wx-empty", title = "保留封面", cover = "" })
|
||||
Assert.is_nil(b.cover)
|
||||
Assert.is_nil(cover)
|
||||
end
|
||||
|
||||
-- bookInfo 扩展元数据原样交给 meta(规范化在 BookDB 入库时做),newRating 千分制折成十分制
|
||||
do
|
||||
local b = Mapper.book({
|
||||
bookId = "wx-meta", publisher = "湖南文艺出版社", publishTime = "2022-01-01 00:00:00",
|
||||
isbn = "9787572606878", language = "zh", totalWords = 68000, newRating = 955,
|
||||
})
|
||||
Assert.eq(b.meta.publisher, "湖南文艺出版社")
|
||||
Assert.eq(b.meta.published, "2022-01-01 00:00:00")
|
||||
Assert.eq(b.meta.isbn, "9787572606878")
|
||||
Assert.eq(b.meta.language, "zh")
|
||||
Assert.eq(b.meta.words, 68000)
|
||||
Assert.eq(b.meta.rating.score, 9.55)
|
||||
Assert.eq(b.meta.rating.by, "weread")
|
||||
end
|
||||
|
||||
-- 微信作品完结 finished=1 不当作用户读完。连载判断要的 payType / type / 完结留下。
|
||||
do
|
||||
local b = Mapper.book({ bookId = "1", finished = 1, progress = 20, payType = 2, type = 0 })
|
||||
Assert.eq(b.percent, 20)
|
||||
Assert.eq(b.meta.source["ext.weread"].pay_type, 2)
|
||||
Assert.eq(b.meta.source["ext.weread"].book_type, 0)
|
||||
Assert.eq(b.meta.source["ext.weread"].ended, true)
|
||||
end
|
||||
|
||||
do
|
||||
local shelf = {
|
||||
books = { { bookId = "1", title = "A" } },
|
||||
recentBooks = { { bookId = "2", title = "B" } },
|
||||
finishReadBooks = { { bookId = "1", title = "A dup" }, { bookId = "3", title = "C" } },
|
||||
bookProgress = { { bookId = "1", progress = 33 } },
|
||||
albums = {},
|
||||
}
|
||||
local list = Mapper.shelfList(shelf)
|
||||
Assert.eq(#list.data, 3)
|
||||
local ids = {}
|
||||
for _, b in ipairs(list.data) do ids[b.stable_id] = b.title end
|
||||
Assert.eq(ids["1"], "A")
|
||||
Assert.eq(ids["2"], "B")
|
||||
Assert.eq(ids["3"], "C")
|
||||
Assert.eq(list.data[1].percent, 33)
|
||||
end
|
||||
|
||||
do
|
||||
local shelf = {
|
||||
books = { { bookId = "1", title = "A" } },
|
||||
bookProgress = { { bookId = "1", progress = 33 } },
|
||||
albums = {},
|
||||
}
|
||||
local list = Mapper.shelfList(shelf)
|
||||
Assert.eq(#list.data, 1)
|
||||
Assert.eq(list.data[1].percent, 33)
|
||||
end
|
||||
|
||||
do
|
||||
local Settings = require("utils.settings")
|
||||
local cfg = Settings.getSource("ext.weread")
|
||||
cfg.category_as_group = true
|
||||
Settings.saveSource("ext.weread", cfg)
|
||||
local list = Mapper.shelfList({
|
||||
books = {
|
||||
{ bookId = "1", title = "A", category = "官方" },
|
||||
{ bookId = "2", title = "B", category = "官方" },
|
||||
},
|
||||
archive = {
|
||||
{ name = "我的", bookIds = { 1 } },
|
||||
{ name = "其它", bookIds = { 1 } },
|
||||
},
|
||||
})
|
||||
Assert.eq(list.data[1].category, "我的", "开:进组用分组名")
|
||||
Assert.is_nil(list.data[2].category, "开:没进组不写题材,避免混合")
|
||||
Assert.is_true(list.data[1].category_authoritative)
|
||||
Assert.is_true(list.data[2].category_authoritative, "没进组也是这次快照的分类口径")
|
||||
cfg.category_as_group = false
|
||||
Settings.saveSource("ext.weread", cfg)
|
||||
local genre = Mapper.shelfList({
|
||||
books = {
|
||||
{ bookId = "1", title = "A", category = "官方" },
|
||||
{ bookId = "2", title = "B", category = "官方" },
|
||||
},
|
||||
archive = { { name = "我的", bookIds = { 1 } } },
|
||||
})
|
||||
Assert.eq(genre.data[1].category, "官方", "关:只用题材")
|
||||
Assert.eq(genre.data[2].category, "官方", "关:忽略分组")
|
||||
end
|
||||
|
||||
do
|
||||
local chapters = Mapper.chapters({
|
||||
data = {
|
||||
{
|
||||
bookId = "1",
|
||||
updated = {
|
||||
{ chapterIdx = 2, chapterUid = "u2", title = "二", wordCount = 10, level = 2 },
|
||||
{
|
||||
chapterIdx = 1, chapterUid = "u1", title = "一", wordCount = 10, level = 1,
|
||||
anchors = { { title = "第一章", level = 2 } },
|
||||
},
|
||||
{ chapterIdx = 3, chapterUid = "u3", title = "封面", wordCount = 10 },
|
||||
},
|
||||
},
|
||||
},
|
||||
}, "1")
|
||||
Assert.eq(#chapters, 2)
|
||||
Assert.eq(chapters[1].idx, 1)
|
||||
Assert.eq(chapters[1].uid, "u1")
|
||||
Assert.eq(chapters[1].depth, 1)
|
||||
Assert.eq(chapters[1].anchors[1].title, "第一章")
|
||||
Assert.eq(chapters[1].anchors[1].depth, 2)
|
||||
Assert.eq(chapters[1].toc_version, 5)
|
||||
Assert.not_nil(chapters[1].words, "带字数:关联书按篇幅对齐")
|
||||
Assert.eq(chapters[2].title, "二", "出版书(epub)章名原样")
|
||||
Assert.eq(chapters[2].depth, 2)
|
||||
end
|
||||
|
||||
|
||||
do
|
||||
-- 微信给每章挂的同名同层自锚点(就是章首)不是章内小节,丢掉;同名更深与异名小节保留。
|
||||
local chapters = Mapper.chapters({
|
||||
data = {
|
||||
{
|
||||
bookId = "1",
|
||||
updated = {
|
||||
{ chapterIdx = 1, chapterUid = "u1", title = "龙卷风", wordCount = 10, level = 2,
|
||||
anchors = { { title = "龙卷风", level = 2 } } },
|
||||
{ chapterIdx = 2, chapterUid = "u2", title = "序", wordCount = 10, level = 1,
|
||||
anchors = { { title = "序", level = 2 }, { title = "小节", level = 2 } } },
|
||||
},
|
||||
},
|
||||
},
|
||||
}, "1")
|
||||
Assert.is_nil(chapters[1].anchors, "同名同层自锚点丢弃,目录不再一章两行")
|
||||
Assert.eq(#chapters[2].anchors, 2, "同名更深与异名小节保留")
|
||||
end
|
||||
do
|
||||
-- 网文(book.format=txt,chapterInfos 实测字段):按 chapterIdx 补「第 N 章」,已带序号的不重复补,空章名只留序号。
|
||||
local chapters = Mapper.chapters({
|
||||
data = {
|
||||
{
|
||||
bookId = "820954",
|
||||
book = { bookId = "820954", format = "txt" },
|
||||
updated = {
|
||||
{ chapterIdx = 1, chapterUid = 1, title = "万年之后", wordCount = 1290 },
|
||||
{ chapterIdx = 2, chapterUid = 2, title = "第二章 想整我?", wordCount = 1430 },
|
||||
{ chapterIdx = 3, chapterUid = 3, title = "第一次见面", wordCount = 10 },
|
||||
{ chapterIdx = 4, chapterUid = 4, title = "", wordCount = 10 },
|
||||
{ chapterIdx = 5, chapterUid = 5, title = "第12章", wordCount = 10 },
|
||||
},
|
||||
},
|
||||
},
|
||||
}, "820954")
|
||||
local titles = {}
|
||||
for i, ch in ipairs(chapters) do titles[i] = ch.title end
|
||||
Assert.eq(table.concat(titles, "|"), "第1章 万年之后|第二章 想整我?|第3章 第一次见面|第4章|第12章")
|
||||
Assert.eq(chapters[1].format, "txt")
|
||||
end
|
||||
|
||||
do
|
||||
local chapters = Mapper.chapters({
|
||||
data = {
|
||||
{
|
||||
bookId = "1",
|
||||
updated = {
|
||||
{ chapterIdx = 1, chapterUid = "u1", title = "图章", wordCount = 10, tar = "/web/tar/1" },
|
||||
},
|
||||
},
|
||||
},
|
||||
}, "1")
|
||||
Assert.eq(chapters[1].tar, "/web/tar/1")
|
||||
end
|
||||
|
||||
do
|
||||
local pos = Mapper.progress({ progress = 50, chapterUid = "u1" })
|
||||
Assert.eq(pos.fraction, 0.5)
|
||||
end
|
||||
|
||||
do
|
||||
local pos, uid = Mapper.progress({
|
||||
bookId = "42",
|
||||
book = { chapterUid = "u7", progress = 77, chapterOffset = 5000 },
|
||||
})
|
||||
Assert.eq(uid, "u7")
|
||||
Assert.eq(pos.fraction, 0.77)
|
||||
Assert.is_nil(pos.chapter_fraction, "原文偏移不是章内万分比")
|
||||
Assert.eq(pos.extra.chapter_offset, 5000)
|
||||
end
|
||||
|
||||
do
|
||||
local pos = Mapper.progress({ book = { chapterUid = "u7", progress = 1, chapterOffset = 1 } })
|
||||
Assert.is_nil(pos.chapter_fraction)
|
||||
Assert.eq(pos.extra.chapter_offset, 1)
|
||||
pos = Mapper.progress({ book = { chapterUid = "u7", progress = 1, chapterOffset = 0 } })
|
||||
Assert.is_nil(pos.chapter_fraction)
|
||||
Assert.eq(pos.extra.chapter_offset, 0)
|
||||
pos = Mapper.progress({ book = { chapterUid = "u7", progress = 1 } })
|
||||
Assert.is_nil(pos.chapter_fraction)
|
||||
end
|
||||
|
||||
-- 云端最近阅读时间:书行 readUpdateTime 与 bookProgress.updateTime 取较新的
|
||||
do
|
||||
local b = Mapper.book({ bookId = "wx-r", title = "R", readUpdateTime = 1700000000 })
|
||||
Assert.eq(b.read_at, 1700000000)
|
||||
Mapper.applyProgress(b, { bookId = "wx-r", progress = 10, updateTime = 1700000500 })
|
||||
Assert.eq(b.read_at, 1700000500)
|
||||
Mapper.applyProgress(b, { bookId = "wx-r", progress = 10, updateTime = 1600000000 })
|
||||
Assert.eq(b.read_at, 1700000500, "旧的不覆盖新的")
|
||||
local list = Mapper.shelfList({
|
||||
books = { { bookId = "a", title = "A" } },
|
||||
bookProgress = { { bookId = "a", progress = 5, updateTime = 1234 } },
|
||||
})
|
||||
Assert.eq(list.data[1].read_at, 1234)
|
||||
|
||||
-- 公众号只走订阅导入,书架同步不收进书库
|
||||
local mixed = Mapper.shelfList({ books = { { bookId = "a", title = "A" }, { bookId = "MP_WXS_1", title = "号" } } })
|
||||
Assert.len(mixed.data, 1)
|
||||
Assert.eq(mixed.data[1].stable_id, "a")
|
||||
end
|
||||
do -- 书城目录:榜单与带子分类的分类,其余丢弃
|
||||
local tree = Mapper.storeTree({ data = {
|
||||
{ categories = {
|
||||
{ CategoryId = "rising", title = "飙升榜", ranklist = 1, sublist = {} },
|
||||
{ CategoryId = "6200", title = "有声小说榜", sublist = {} },
|
||||
} },
|
||||
{ categories = {
|
||||
{ CategoryId = 700000, title = "计算机", sublist = { { CategoryId = 700001, title = "软件学习" } } },
|
||||
} },
|
||||
} })
|
||||
Assert.len(tree.rankings, 1)
|
||||
Assert.eq(tree.rankings[1].id, "rising")
|
||||
Assert.len(tree.categories, 1)
|
||||
Assert.eq(tree.categories[1].id, "700000")
|
||||
Assert.eq(tree.categories[1].subs[1].id, "700001")
|
||||
end
|
||||
|
||||
--[[--
|
||||
moonsource_weread.mapper 离线用例
|
||||
|
||||
@module tests.moonsource_weread.mapper_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")
|
||||
|
||||
package.preload["moonsource_weread.mapper"] = nil
|
||||
package.loaded["moonsource_weread.mapper"] = nil
|
||||
package.preload["source.contract"] = nil
|
||||
-- contract 可能仍在 loaded,保留即可
|
||||
|
||||
local Mapper = require("moonsource_weread.mapper")
|
||||
|
||||
do
|
||||
local b, cover = Mapper.book({
|
||||
bookId = "wx-1",
|
||||
bookName = "三体",
|
||||
author = "刘慈欣",
|
||||
cover = "http://x/c.jpg",
|
||||
progressPercent = 42,
|
||||
})
|
||||
Assert.eq(b.source_id, "ext.weread")
|
||||
Assert.eq(b.stable_id, "wx-1")
|
||||
Assert.eq(b.title, "三体")
|
||||
Assert.eq(b.percent, 42)
|
||||
Assert.eq(cover, "http://x/c.jpg")
|
||||
Assert.is_nil(b.id)
|
||||
end
|
||||
|
||||
-- 空封面必须视为缺失,不能参与远端 upsert 覆盖本地已有封面。
|
||||
do
|
||||
local b, cover = Mapper.book({ bookId = "wx-empty", title = "保留封面", cover = "" })
|
||||
Assert.is_nil(b.cover)
|
||||
Assert.is_nil(cover)
|
||||
end
|
||||
|
||||
-- bookInfo 扩展元数据原样交给 meta(规范化在 BookDB 入库时做),newRating 千分制折成十分制
|
||||
do
|
||||
local b = Mapper.book({
|
||||
bookId = "wx-meta", publisher = "湖南文艺出版社", publishTime = "2022-01-01 00:00:00",
|
||||
isbn = "9787572606878", language = "zh", totalWords = 68000, newRating = 955,
|
||||
})
|
||||
Assert.eq(b.meta.publisher, "湖南文艺出版社")
|
||||
Assert.eq(b.meta.published, "2022-01-01 00:00:00")
|
||||
Assert.eq(b.meta.isbn, "9787572606878")
|
||||
Assert.eq(b.meta.language, "zh")
|
||||
Assert.eq(b.meta.words, 68000)
|
||||
Assert.eq(b.meta.rating.score, 9.55)
|
||||
Assert.eq(b.meta.rating.by, "weread")
|
||||
end
|
||||
|
||||
-- 微信作品完结 finished=1 不当作用户读完。连载判断要的 payType / type / 完结留下。
|
||||
do
|
||||
local b = Mapper.book({ bookId = "1", finished = 1, progress = 20, payType = 2, type = 0 })
|
||||
Assert.eq(b.percent, 20)
|
||||
Assert.eq(b.meta.source["ext.weread"].pay_type, 2)
|
||||
Assert.eq(b.meta.source["ext.weread"].book_type, 0)
|
||||
Assert.eq(b.meta.source["ext.weread"].ended, true)
|
||||
end
|
||||
|
||||
do
|
||||
local shelf = {
|
||||
books = { { bookId = "1", title = "A" } },
|
||||
recentBooks = { { bookId = "2", title = "B" } },
|
||||
finishReadBooks = { { bookId = "1", title = "A dup" }, { bookId = "3", title = "C" } },
|
||||
bookProgress = { { bookId = "1", progress = 33 } },
|
||||
albums = {},
|
||||
}
|
||||
local list = Mapper.shelfList(shelf)
|
||||
Assert.eq(#list.data, 3)
|
||||
local ids = {}
|
||||
for _, b in ipairs(list.data) do ids[b.stable_id] = b.title end
|
||||
Assert.eq(ids["1"], "A")
|
||||
Assert.eq(ids["2"], "B")
|
||||
Assert.eq(ids["3"], "C")
|
||||
Assert.eq(list.data[1].percent, 33)
|
||||
end
|
||||
|
||||
do
|
||||
local shelf = {
|
||||
books = { { bookId = "1", title = "A" } },
|
||||
bookProgress = { { bookId = "1", progress = 33 } },
|
||||
albums = {},
|
||||
}
|
||||
local list = Mapper.shelfList(shelf)
|
||||
Assert.eq(#list.data, 1)
|
||||
Assert.eq(list.data[1].percent, 33)
|
||||
end
|
||||
|
||||
do
|
||||
local Settings = require("utils.settings")
|
||||
local cfg = Settings.getSource("ext.weread")
|
||||
cfg.category_as_group = true
|
||||
Settings.saveSource("ext.weread", cfg)
|
||||
local list = Mapper.shelfList({
|
||||
books = {
|
||||
{ bookId = "1", title = "A", category = "官方" },
|
||||
{ bookId = "2", title = "B", category = "官方" },
|
||||
},
|
||||
archive = {
|
||||
{ name = "我的", bookIds = { 1 } },
|
||||
{ name = "其它", bookIds = { 1 } },
|
||||
},
|
||||
})
|
||||
Assert.eq(list.data[1].category, "我的", "开:进组用分组名")
|
||||
Assert.is_nil(list.data[2].category, "开:没进组不写题材,避免混合")
|
||||
Assert.is_true(list.data[1].category_authoritative)
|
||||
Assert.is_true(list.data[2].category_authoritative, "没进组也是这次快照的分类口径")
|
||||
cfg.category_as_group = false
|
||||
Settings.saveSource("ext.weread", cfg)
|
||||
local genre = Mapper.shelfList({
|
||||
books = {
|
||||
{ bookId = "1", title = "A", category = "官方" },
|
||||
{ bookId = "2", title = "B", category = "官方" },
|
||||
},
|
||||
archive = { { name = "我的", bookIds = { 1 } } },
|
||||
})
|
||||
Assert.eq(genre.data[1].category, "官方", "关:只用题材")
|
||||
Assert.eq(genre.data[2].category, "官方", "关:忽略分组")
|
||||
end
|
||||
|
||||
do
|
||||
local chapters = Mapper.chapters({
|
||||
data = {
|
||||
{
|
||||
bookId = "1",
|
||||
updated = {
|
||||
{ chapterIdx = 2, chapterUid = "u2", title = "二", wordCount = 10, level = 2 },
|
||||
{
|
||||
chapterIdx = 1, chapterUid = "u1", title = "一", wordCount = 10, level = 1,
|
||||
anchors = { { title = "第一章", level = 2 } },
|
||||
},
|
||||
{ chapterIdx = 3, chapterUid = "u3", title = "封面", wordCount = 10 },
|
||||
},
|
||||
},
|
||||
},
|
||||
}, "1")
|
||||
Assert.eq(#chapters, 2)
|
||||
Assert.eq(chapters[1].idx, 1)
|
||||
Assert.eq(chapters[1].uid, "u1")
|
||||
Assert.eq(chapters[1].depth, 1)
|
||||
Assert.eq(chapters[1].anchors[1].title, "第一章")
|
||||
Assert.eq(chapters[1].anchors[1].depth, 2)
|
||||
Assert.eq(chapters[1].toc_version, 5)
|
||||
Assert.not_nil(chapters[1].words, "带字数:关联书按篇幅对齐")
|
||||
Assert.eq(chapters[2].title, "二", "出版书(epub)章名原样")
|
||||
Assert.eq(chapters[2].depth, 2)
|
||||
end
|
||||
|
||||
do
|
||||
-- 网文(book.format=txt,chapterInfos 实测字段):按 chapterIdx 补「第 N 章」,已带序号的不重复补,空章名只留序号。
|
||||
local chapters = Mapper.chapters({
|
||||
data = {
|
||||
{
|
||||
bookId = "820954",
|
||||
book = { bookId = "820954", format = "txt" },
|
||||
updated = {
|
||||
{ chapterIdx = 1, chapterUid = 1, title = "万年之后", wordCount = 1290 },
|
||||
{ chapterIdx = 2, chapterUid = 2, title = "第二章 想整我?", wordCount = 1430 },
|
||||
{ chapterIdx = 3, chapterUid = 3, title = "第一次见面", wordCount = 10 },
|
||||
{ chapterIdx = 4, chapterUid = 4, title = "", wordCount = 10 },
|
||||
{ chapterIdx = 5, chapterUid = 5, title = "第12章", wordCount = 10 },
|
||||
},
|
||||
},
|
||||
},
|
||||
}, "820954")
|
||||
local titles = {}
|
||||
for i, ch in ipairs(chapters) do titles[i] = ch.title end
|
||||
Assert.eq(table.concat(titles, "|"), "第1章 万年之后|第二章 想整我?|第3章 第一次见面|第4章|第12章")
|
||||
Assert.eq(chapters[1].format, "txt")
|
||||
end
|
||||
|
||||
do
|
||||
local chapters = Mapper.chapters({
|
||||
data = {
|
||||
{
|
||||
bookId = "1",
|
||||
updated = {
|
||||
{ chapterIdx = 1, chapterUid = "u1", title = "图章", wordCount = 10, tar = "/web/tar/1" },
|
||||
},
|
||||
},
|
||||
},
|
||||
}, "1")
|
||||
Assert.eq(chapters[1].tar, "/web/tar/1")
|
||||
end
|
||||
|
||||
do
|
||||
local pos = Mapper.progress({ progress = 50, chapterUid = "u1" })
|
||||
Assert.eq(pos.fraction, 0.5)
|
||||
end
|
||||
|
||||
do
|
||||
local pos, uid = Mapper.progress({
|
||||
bookId = "42",
|
||||
book = { chapterUid = "u7", progress = 77, chapterOffset = 5000 },
|
||||
})
|
||||
Assert.eq(uid, "u7")
|
||||
Assert.eq(pos.fraction, 0.77)
|
||||
Assert.is_nil(pos.chapter_fraction)
|
||||
Assert.eq(pos.extra.chapter_offset, 5000)
|
||||
end
|
||||
|
||||
do
|
||||
local pos = Mapper.progress({ book = { chapterUid = "u7", progress = 1, chapterOffset = 1 } })
|
||||
Assert.is_nil(pos.chapter_fraction)
|
||||
Assert.eq(pos.extra.chapter_offset, 1)
|
||||
pos = Mapper.progress({ book = { chapterUid = "u7", progress = 1, chapterOffset = 0 } })
|
||||
Assert.is_nil(pos.chapter_fraction)
|
||||
Assert.eq(pos.extra.chapter_offset, 0)
|
||||
pos = Mapper.progress({ book = { chapterUid = "u7", progress = 1 } })
|
||||
Assert.is_nil(pos.chapter_fraction)
|
||||
end
|
||||
|
||||
-- 云端最近阅读时间:书行 readUpdateTime 与 bookProgress.updateTime 取较新的
|
||||
do
|
||||
local b = Mapper.book({ bookId = "wx-r", title = "R", readUpdateTime = 1700000000 })
|
||||
Assert.eq(b.read_at, 1700000000)
|
||||
Mapper.applyProgress(b, { bookId = "wx-r", progress = 10, updateTime = 1700000500 })
|
||||
Assert.eq(b.read_at, 1700000500)
|
||||
Mapper.applyProgress(b, { bookId = "wx-r", progress = 10, updateTime = 1600000000 })
|
||||
Assert.eq(b.read_at, 1700000500, "旧的不覆盖新的")
|
||||
local list = Mapper.shelfList({
|
||||
books = { { bookId = "a", title = "A" } },
|
||||
bookProgress = { { bookId = "a", progress = 5, updateTime = 1234 } },
|
||||
})
|
||||
Assert.eq(list.data[1].read_at, 1234)
|
||||
|
||||
-- 公众号只走订阅导入,书架同步不收进书库
|
||||
local mixed = Mapper.shelfList({ books = { { bookId = "a", title = "A" }, { bookId = "MP_WXS_1", title = "号" } } })
|
||||
Assert.len(mixed.data, 1)
|
||||
Assert.eq(mixed.data[1].stable_id, "a")
|
||||
end
|
||||
@@ -0,0 +1,324 @@
|
||||
--[[-- moonsource_weread.mp:公众号文章列表(新到旧)、书架里的公众号与分组、文章页 → 正文、图片改写。 --]]
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local Stubs = require("support.stubs")
|
||||
Stubs.install()
|
||||
package.loaded["json"] = { decode = require("support.json_stub").decode }
|
||||
|
||||
local pages, urls = {}, {}
|
||||
local localized = {}
|
||||
local renewals = 0
|
||||
local wx_refreshes = {}
|
||||
package.loaded["moonsource_weread.auth"] = {
|
||||
sessionHeaders = function(extra)
|
||||
local h = { Cookie = "wr_vid=1; wr_skey=2" }
|
||||
if extra then for k, v in pairs(extra) do h[k] = v end end
|
||||
return h
|
||||
end,
|
||||
webPostAsync = function(url, _body, _opts, cb)
|
||||
renewals = renewals + 1
|
||||
Assert.matches(url, "/web/login/renewal")
|
||||
cb("{}", nil, { headers = { ["X-WR-Ticket"] = "T1", ["x-wrpa-0"] = "W1" } })
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
webGetAsync = function(url, _opts, cb)
|
||||
urls[#urls + 1] = url
|
||||
cb(pages[url:match("reviewId=(.*)$") or "list"])
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
-- 正文改走 Request.stream:按 reviewId 吐 pages,超大页边吐边让调用方断开。
|
||||
local stream_override = nil
|
||||
package.loaded["http.request"] = {
|
||||
stream = function(opts, h)
|
||||
if stream_override then return stream_override(opts, h) end
|
||||
local job = { stopped = false }
|
||||
function job:cancel() self.stopped = true end
|
||||
urls[#urls + 1] = opts.url
|
||||
local key = opts.url:match("reviewId=(.*)$") or "list"
|
||||
local body = pages[key]
|
||||
if body == nil then
|
||||
if h.on_headers then h.on_headers(404, {}) end
|
||||
h.on_done("HTTP 404")
|
||||
return job
|
||||
end
|
||||
if h.on_headers then h.on_headers(200, {}) end
|
||||
local CHUNK = 256 * 1024
|
||||
for i = 1, #body, CHUNK do
|
||||
if job.stopped then break end
|
||||
h.on_data(body:sub(i, i + CHUNK - 1))
|
||||
end
|
||||
h.on_done(job.stopped and "cancelled" or nil)
|
||||
return job
|
||||
end,
|
||||
header = function(res, name)
|
||||
local headers = res and res.headers
|
||||
if not headers then return nil end
|
||||
if type(headers.get) == "function" then return headers:get(name, true) end
|
||||
local lower = name:lower()
|
||||
for k, v in pairs(headers) do
|
||||
if type(k) == "string" and k:lower() == lower then return v end
|
||||
end
|
||||
end,
|
||||
}
|
||||
package.loaded["http.timeout"] = { net = function() return 1 end }
|
||||
package.loaded["http.request.header"] = { forRequest = function(e) return e or {} end, merge = function(a, b)
|
||||
local o = {}
|
||||
for k, v in pairs(b or {}) do o[k] = v end
|
||||
for k, v in pairs(a or {}) do o[k] = v end
|
||||
return o
|
||||
end }
|
||||
package.loaded["moonsource_weread.assets"] = {
|
||||
localizeArticleAsync = function(dir, html, cb)
|
||||
localized[#localized + 1] = dir
|
||||
cb(html)
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
package.loaded["moonsource_weread.eink"] = {
|
||||
refreshAsync = function(cb, opts)
|
||||
wx_refreshes[#wx_refreshes + 1] = opts
|
||||
cb(true)
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
callAsync = function(_method, path, opts, cb)
|
||||
local q = opts and opts.query or {}
|
||||
urls[#urls + 1] = path .. "?" .. require("utils.text").formEncode(q)
|
||||
local raw = pages.list
|
||||
if type(raw) ~= "string" then
|
||||
cb(nil, "微信读书拒绝了请求,请稍后再试", { errcode = -2041 })
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local data = package.loaded["json"].decode(raw)
|
||||
if type(data) == "table" and (data.errcode or data.errCode) then
|
||||
cb(nil, data.errmsg or data.errMsg, { errcode = tonumber(data.errcode or data.errCode) })
|
||||
else
|
||||
cb(data)
|
||||
end
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
package.loaded["moonsource_weread.mp"] = nil
|
||||
local Mp = require("moonsource_weread.mp")
|
||||
|
||||
local function wire(items)
|
||||
local subs = {}
|
||||
for i, item in ipairs(items) do
|
||||
subs[i] = { reviewId = item[1], review = { reviewId = item[1], createTime = item[2], mpInfo = { title = item[3] } } }
|
||||
end
|
||||
return { reviews = { { createTime = 0, subReviews = subs } } }
|
||||
end
|
||||
|
||||
-- 文章列表:新到旧、去重、无标题用日期。
|
||||
local list = Mp.articles(wire({ { "r1", 100, "一" }, { "r2", 200, "" }, { "r1", 100, "一" } }))
|
||||
Assert.len(list, 2)
|
||||
Assert.eq(list[1].guid, "r2")
|
||||
Assert.eq(list[1].title, os.date("%Y-%m-%d", 200))
|
||||
Assert.eq(list[2].title, "一")
|
||||
Assert.len(Mp.articles({}), 0)
|
||||
local flat = Mp.articles({ data = {
|
||||
{ reviewId = "a", createTime = 10, mpInfo = { title = "甲" } },
|
||||
{ reviewId = "b", createTime = 30, mpInfo = { title = "" } },
|
||||
{ reviewId = "a", createTime = 10, mpInfo = { title = "甲" } },
|
||||
} })
|
||||
Assert.len(flat, 2)
|
||||
Assert.eq(flat[1].guid, "b")
|
||||
Assert.eq(flat[1].title, os.date("%Y-%m-%d", 30))
|
||||
Assert.eq(flat[2].title, "甲")
|
||||
|
||||
-- 分页:App /mp/chapters,offset 与第三个回调都是篇数。
|
||||
pages.list = '{"data":[{"reviewId":"r9","createTime":9,"mpInfo":{"title":"九"}}]}'
|
||||
local got, groups
|
||||
Mp.fetchArticlesAsync("MP_WXS_1", 40, function(items, _e, n) got, groups = items, n end)
|
||||
Assert.eq(got[1].guid, "r9")
|
||||
Assert.eq(groups, 1)
|
||||
Assert.matches(urls[#urls], "/mp/chapters?")
|
||||
Assert.matches(urls[#urls], "offset=40")
|
||||
Assert.matches(urls[#urls], "count=20")
|
||||
pages.list = '{"errcode":-2010,"errmsg":"登录超时"}'
|
||||
local err
|
||||
Mp.fetchArticlesAsync("MP_WXS_1", 0, function(items, e) got, err = items, e end)
|
||||
Assert.eq(got, nil)
|
||||
Assert.eq(err, "登录超时")
|
||||
-- -2041:wxToken=1 后续一次仍被拒,换成公众号授权失效。
|
||||
pages.list = nil
|
||||
renewals = 0
|
||||
wx_refreshes = {}
|
||||
Mp.fetchArticlesAsync("MP_WXS_1", 0, function(items, e) got, err = items, e end)
|
||||
Assert.eq(got, nil)
|
||||
Assert.eq(err, Mp.AUTH_EXPIRED)
|
||||
Assert.eq(renewals, 1, "wxToken=1 成功后补一次网页头")
|
||||
Assert.eq(#wx_refreshes, 1)
|
||||
Assert.eq(wx_refreshes[1].wxToken, 1)
|
||||
Assert.matches(wx_refreshes[1].refCgi, "/mp/chapters")
|
||||
|
||||
-- 书架里的公众号:books 行、mp.book 单对象、data.officialAccounts 都收,去重;分组取 archive 名。
|
||||
local accounts = Mp.accounts({
|
||||
books = { { bookId = "1", title = "书" }, { bookId = "MP_WXS_3", title = "号三" } },
|
||||
mp = { book = { bookId = "MP_WXS_1", title = "号一" }, show = 1 },
|
||||
data = { officialAccounts = { { bookId = "MP_WXS_2", title = "号二" }, { bookId = "MP_WXS_1", title = "重复" } } },
|
||||
archive = { { name = "科技", bookIds = { "MP_WXS_1", "1" } } },
|
||||
})
|
||||
local by = {}
|
||||
for _idx, a in ipairs(accounts) do by[a.id] = a end
|
||||
Assert.len(accounts, 3)
|
||||
Assert.eq(by["MP_WXS_1"].title, "号一")
|
||||
Assert.eq(by["MP_WXS_1"].group, "科技")
|
||||
Assert.eq(by["MP_WXS_2"].group, "")
|
||||
Assert.eq(by["1"], nil, "普通书不收")
|
||||
Assert.eq(Mp.isMp("MP_WXS_9"), true)
|
||||
Assert.eq(Mp.isMp("3300"), false)
|
||||
|
||||
-- 正文:只取 js_content,去脚本 / svg,剥内联字号(两种引号),懒加载图换 src 并降档。
|
||||
local html = '<html><body><div id="js_content" style="visibility:hidden">'
|
||||
.. '<p style="font-size: 15px;color:red">正文</p><span style=\'font-size:17px\'>二</span>'
|
||||
.. '<svg viewBox="0 0 1 1"><rect/></svg><script>x()</script>'
|
||||
.. '<img data-src="https://mmbiz.qpic.cn/mmbiz_jpg/abc/0?wx_fmt=jpeg&tp=webp" src="data:x" width="1080" style="width:1080px">'
|
||||
.. '</div><script>var a</script></body></html>'
|
||||
local body = Mp.extractBody(html)
|
||||
Assert.not_nil(body:find("<p style=\"color:red\">正文</p>", 1, true), "字号剥掉、其余样式保留")
|
||||
Assert.not_nil(body:find("<span>二</span>", 1, true), "单引号样式也剥")
|
||||
Assert.is_nil(body:find("svg", 1, true))
|
||||
Assert.is_nil(body:find("script", 1, true))
|
||||
Assert.not_nil(body:find('<img src="https://mmbiz.qpic.cn/mmbiz_jpg/abc/640?wx_fmt=jpeg"/>', 1, true), body)
|
||||
Assert.eq(Mp.extractBody("<html>没有正文</html>"), nil)
|
||||
local many = '<div id="js_content">' .. string.rep('<img data-src="https://x/a.png">', 40) .. "</div><script>"
|
||||
local _n, imgs = Mp.extractBody(many):gsub("<img", "")
|
||||
Assert.eq(imgs, 40, "图片不设上限")
|
||||
|
||||
-- 实测页面形状(脱敏):class 在 id 前、属性跨行、正文前有几百 KB 脚本;正文后的 JS 里另有一份 content_noencode。
|
||||
local real = "<!DOCTYPE html>\n<html class=\"\n\">\n<head><script>" .. string.rep("var a=1;", 20000) .. "</script></head><body>\n"
|
||||
.. '<div class="rich_media_content js_underline_content\n autoTypeSetting24psection\n "\n'
|
||||
.. ' id="js_content" style="visibility: hidden; opacity: 0; "><section><span leaf="">图文正文</span></section>\n'
|
||||
.. "</div>\n<script>var x = { content_noencode: '\\x3cp\\x3e不该用这份\\x3c/p\\x3e' };</script></body></html>"
|
||||
Assert.matches(Mp.extractBody(real), "图文正文")
|
||||
Assert.is_nil(Mp.extractBody(real):find("不该用这份", 1, true))
|
||||
|
||||
-- 图片 / 纯文字消息没有 js_content:正文取脚本里的 content_noencode(解 \x / \u / \n 转义),图片取 picture_page_info_list。
|
||||
local picture = "<html><body><div id=\"js_image_content\"></div><script>var data = {\n"
|
||||
.. " title: '标题',\n content_noencode: '第一行\\n\\u7b2c\\u4e8c\\u884c \\x26 \\'引号\\'',\n"
|
||||
.. " picture_page_info_list: [ { cdn_url: 'https://mmbiz.qpic.cn/sz_mmbiz_jpg/a/0?wx_fmt=jpeg', width: '1080' },\n"
|
||||
.. " { cdn_url: 'https://mmbiz.qpic.cn/sz_mmbiz_png/b/0?wx_fmt=png', watermark_info: { x: 1 } } ],\n"
|
||||
.. " other_list: [ { cdn_url: 'https://evil/c.png' } ]\n};</script></body></html>"
|
||||
local pic = Mp.extractBody(picture)
|
||||
Assert.matches(pic, "第一行")
|
||||
Assert.matches(pic, "第二行 & '引号'")
|
||||
Assert.not_nil(pic:find('<img src="https://mmbiz.qpic.cn/sz_mmbiz_jpg/a/640?wx_fmt=jpeg"/>', 1, true), pic)
|
||||
Assert.not_nil(pic:find("sz_mmbiz_png/b/640", 1, true))
|
||||
Assert.is_nil(pic:find("evil", 1, true), "只取 picture_page_info_list 里的图")
|
||||
Assert.matches(Mp.extractBody("<script>x = { content_noencode: '\\x3cp\\x3eHTML 正文\\x3c/p\\x3e' }</script>"), "<p>HTML 正文</p>")
|
||||
Assert.is_nil(Mp.extractBody("<script>x = { content_noencode: '' }</script>"))
|
||||
local sto = Mp.extractBody("<script>x = { content_noencode: 'a', picture_page_info_list: [{ cdn_url: 'http://320.wxapp.tc.qq.com/s?m=1\\x26amp;k=2' }] }</script>")
|
||||
Assert.not_nil(sto:find('src="http://320.wxapp.tc.qq.com/s?m=1&k=2"', 1, true), sto)
|
||||
|
||||
-- emoji:KOReader 字体画不出,一律去掉(不留方块)。脚本正文里的代理对先合成码点再去掉,不能留下两段非法 UTF-8
|
||||
local GRIN = "\240\159\152\128"
|
||||
Assert.eq(Mp.extractBody("<script>x = { content_noencode: 'A\\uD83D\\uDE00B\\u4E2D' }</script>"), "<p>AB中</p>")
|
||||
Assert.is_nil(Mp.extractBody("<script>x = { content_noencode: 'A\\uD83D\\uDE00B' }</script>"):find("\237", 1, true))
|
||||
-- 正文里的码点(含 ZWJ 序列、肤色、VS16)去掉、★ 保留;雪碧图空 span 删;QQ 表情透明占位图去掉、留 alt
|
||||
local family = "\240\159\145\168\226\128\141\240\159\145\169" -- 👨👩
|
||||
local thumb = "\240\159\145\141\240\159\143\189" -- 👍🏽
|
||||
local emo = Mp.extractBody('<div id="js_content"><p>好' .. GRIN .. family .. thumb .. "\226\157\164\239\184\143" .. "\226\152\133"
|
||||
.. '<span class="emoji emoji1f600"></span>'
|
||||
.. '<img class="qqemoji qqemoji1" alt="[微笑]" src="https://res.wx.qq.com/mpres/pic_blank.gif">'
|
||||
.. '<img class="qqemoji" src="https://res.wx.qq.com/mpres/pic_blank.gif"></p></div><script></script>')
|
||||
Assert.eq(emo, "<p>好\226\157\164\226\152\133[微笑]</p>")
|
||||
|
||||
-- 拉正文:图片交给 assets 落到给定目录;不给目录不落地。
|
||||
pages["r1"] = html
|
||||
Mp.fetchContentAsync("r1", "/tmp/x/images", function(h) got = h end)
|
||||
Assert.matches(got, "正文")
|
||||
Assert.eq(localized[1], "/tmp/x/images")
|
||||
Mp.fetchContentAsync("r1", nil, function(h) got = h end)
|
||||
Assert.len(localized, 1, "不给目录不下图")
|
||||
pages["big"] = html .. string.rep("x", 9 * 1024 * 1024)
|
||||
Mp.fetchContentAsync("big", nil, function(p, e) got, err = p, e end)
|
||||
Assert.matches(got, "正文", "页面大小不设上限")
|
||||
Mp.fetchContentAsync("none", nil, function(p, e) got, err = p, e end)
|
||||
Assert.eq(got, nil)
|
||||
|
||||
-- 「验证」反爬页:重拉,最多 VERIFY_TRIES 次;一直是验证页给专门的提示。
|
||||
local verify_page = "<html><head><title>验证</title></head><body>x</body></html>"
|
||||
local seq = { verify_page, html }
|
||||
local calls = 0
|
||||
stream_override = function(_opts, h)
|
||||
calls = calls + 1
|
||||
local body = seq[calls] or verify_page
|
||||
local job = { cancel = function() end }
|
||||
if h.on_headers then h.on_headers(200, {}) end
|
||||
h.on_data(body)
|
||||
h.on_done(nil)
|
||||
return job
|
||||
end
|
||||
local delays = {}
|
||||
Mp.later = function(sec, fn) delays[#delays + 1] = sec; fn() end
|
||||
got = nil
|
||||
Mp.fetchContentAsync("v", nil, function(h) got = h end)
|
||||
Assert.eq(calls, 2); Assert.matches(got, "正文"); Assert.eq(delays[1], 2, "退避再拉")
|
||||
calls, seq = 0, {}
|
||||
Mp.fetchContentAsync("v", nil, function(p, e) got, err = p, e end)
|
||||
Assert.eq(calls, Mp.VERIFY_TRIES); Assert.eq(got, nil); Assert.matches(err, "验证")
|
||||
stream_override = nil
|
||||
|
||||
-- 正文 -2041:先续网页头再重试,续上了不再打 wxToken=1。
|
||||
do
|
||||
local sent = {}
|
||||
stream_override = function(opts, h)
|
||||
sent[#sent + 1] = opts.headers or {}
|
||||
if h.on_headers then h.on_headers(200, {}) end
|
||||
h.on_data(#sent == 1 and '{"errcode":-2041}' or '<div id="js_content">六</div>')
|
||||
h.on_done(nil)
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local html
|
||||
renewals = 0
|
||||
wx_refreshes = {}
|
||||
Mp.fetchContentAsync("r6", nil, function(h) html = h end)
|
||||
Assert.eq(renewals, 1)
|
||||
Assert.eq(#wx_refreshes, 0, "网页头续上了就不再打 wxToken=1")
|
||||
Assert.matches(html, "六")
|
||||
Assert.eq(sent[2]["x-wr-ticket"], "T1")
|
||||
Assert.eq(sent[2]["x-wrpa-0"], "W1")
|
||||
stream_override = nil
|
||||
end
|
||||
|
||||
-- 网页头续完仍是 -2041:wxToken=1 之后第三次拉到正文。
|
||||
do
|
||||
local sent = 0
|
||||
stream_override = function(_opts, h)
|
||||
sent = sent + 1
|
||||
if h.on_headers then h.on_headers(200, {}) end
|
||||
h.on_data(sent < 3 and '{"errcode":-2041,"errMsg":"-2041"}' or '<div id="js_content">八</div>')
|
||||
h.on_done(nil)
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local html
|
||||
renewals = 0
|
||||
wx_refreshes = {}
|
||||
Mp.fetchContentAsync("r8", nil, function(h) html = h end)
|
||||
Assert.eq(sent, 3)
|
||||
Assert.eq(renewals, 2)
|
||||
Assert.eq(#wx_refreshes, 1)
|
||||
Assert.eq(wx_refreshes[1].wxToken, 1)
|
||||
Assert.matches(wx_refreshes[1].refCgi, "/web/mp/content")
|
||||
Assert.matches(html, "八")
|
||||
stream_override = nil
|
||||
end
|
||||
|
||||
-- 正文先按 id 切片:js_content 之前的大段脚本不参与匹配;属性顺序不同也认。
|
||||
do
|
||||
local page = "<html><script>" .. string.rep("var a='<div id=\"x\">';", 1000) .. "</script>"
|
||||
.. '<div class="rich_media_content" id="js_content" style="visibility:hidden"><p>切片正文</p></div><script>z()</script>'
|
||||
Assert.eq(Mp.extractBody(page), "<p>切片正文</p>")
|
||||
end
|
||||
|
||||
-- 旧版本同步进书库的公众号行:只撕 MP_WXS_ 的,普通书不动。
|
||||
do
|
||||
local removed = {}
|
||||
local n = Mp.dropLegacyBooks({
|
||||
stableIdsBySource = function(source) Assert.eq(source, "ext.weread"); return { "100", "MP_WXS_1", "MP_WXS_2" } end,
|
||||
remove = function(source, id) removed[#removed + 1] = source .. ":" .. id end,
|
||||
})
|
||||
Assert.eq(n, 2)
|
||||
Assert.eq(table.concat(removed, ","), "ext.weread:MP_WXS_1,ext.weread:MP_WXS_2")
|
||||
end
|
||||
@@ -0,0 +1,168 @@
|
||||
--[[--
|
||||
moonsource_weread.notes_push:删除先行、预检失败整轮失败、远端已没有的 bookmarkId 被清掉、取消后不回调。
|
||||
@module tests.moonsource_weread.notes_push_spec
|
||||
--]]
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local Stubs = require("support.stubs")
|
||||
Stubs.install()
|
||||
|
||||
local NotesPush = require("moonsource_weread.notes_push")
|
||||
|
||||
--- 只记调用、按表回包的假客户端(回包走 nextTick,模拟真异步)。
|
||||
local function fakeClient(replies)
|
||||
local calls = {}
|
||||
---@type { calls: string[], [string]: any }
|
||||
local client = { calls = calls }
|
||||
local function method(name)
|
||||
return function(_self, ...)
|
||||
local args = { ... }
|
||||
local cb = args[#args]
|
||||
calls[#calls + 1] = name
|
||||
local reply = replies[name]
|
||||
require("ui/uimanager"):nextTick(function()
|
||||
if type(reply) == "function" then reply = reply() end
|
||||
if reply == false then cb(nil, name .. " failed") else cb(reply or {}) end
|
||||
end)
|
||||
return { cancel = function() calls[#calls + 1] = "cancel:" .. name end }
|
||||
end
|
||||
end
|
||||
for _idx, name in ipairs({ "removeBookmarkAsync", "deleteReviewAsync", "bookmarkListAsync",
|
||||
"myReviewsAsync", "addBookmarkAsync", "updateBookmarkAsync", "editReviewAsync",
|
||||
"addReviewAsync", "bookInfoAsync" }) do
|
||||
client[name] = method(name)
|
||||
end
|
||||
return client
|
||||
end
|
||||
|
||||
local identity = { source_id = "ext.weread", stable_id = "b1", chapter_idx = 1 }
|
||||
|
||||
do -- 删除墓碑:先删想法再删划线,删完从注解里移除,后续无事可做即成功
|
||||
local client = fakeClient({ bookmarkListAsync = { updated = {} }, myReviewsAsync = { reviews = {} } })
|
||||
local annotations = { { wr_deleted = true, wr_bookmark_id = "bm1", wr_review_id = "rv1" } }
|
||||
local ok, err
|
||||
NotesPush.run(client, identity, "c1", "<p>x</p>", annotations, function(o, e) ok, err = o, e end)
|
||||
Stubs.flush()
|
||||
Assert.is_true(ok)
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(client.calls[1], "deleteReviewAsync")
|
||||
Assert.eq(client.calls[2], "removeBookmarkAsync")
|
||||
Assert.len(annotations, 0)
|
||||
end
|
||||
|
||||
do -- 只有想法的墓碑(没记过划线 id):按 range 在远端找到划线一并删掉
|
||||
local client = fakeClient({
|
||||
bookmarkListAsync = { updated = { { chapterUid = "c1", range = "10-20", bookmarkId = "bm9" } } },
|
||||
myReviewsAsync = { reviews = {} },
|
||||
})
|
||||
local annotations = { { wr_deleted = true, wr_review_id = "rv1", wr_range = "10-20" } }
|
||||
local ok
|
||||
NotesPush.run(client, identity, "c1", "<p>x</p>", annotations, function(o) ok = o end)
|
||||
Stubs.flush()
|
||||
Assert.is_true(ok)
|
||||
Assert.eq(client.calls[1], "deleteReviewAsync")
|
||||
Assert.eq(client.calls[2], "bookmarkListAsync")
|
||||
Assert.eq(client.calls[3], "removeBookmarkAsync")
|
||||
Assert.len(annotations, 0)
|
||||
end
|
||||
|
||||
do -- 预检失败:整轮失败,带上错误
|
||||
local client = fakeClient({ bookmarkListAsync = false })
|
||||
local ok, err
|
||||
NotesPush.run(client, identity, "c1", "<p>x</p>", {}, function(o, e) ok, err = o, e end)
|
||||
Stubs.flush()
|
||||
Assert.is_nil(ok)
|
||||
Assert.eq(err, "bookmarkListAsync failed")
|
||||
end
|
||||
|
||||
do -- 远端已没有的 bookmarkId 被清掉(下轮当新划线重传),删除请求失败则停在删除
|
||||
local client = fakeClient({ bookmarkListAsync = { updated = {} }, myReviewsAsync = { reviews = {} } })
|
||||
local item = { drawer = "lighten", text = "t", wr_bookmark_id = "gone" }
|
||||
NotesPush.run(client, identity, "c1", nil, { item }, function() end)
|
||||
Stubs.flush()
|
||||
Assert.is_nil(item.wr_bookmark_id)
|
||||
|
||||
client = fakeClient({ removeBookmarkAsync = false })
|
||||
local ok
|
||||
local annotations = { { wr_deleted = true, wr_bookmark_id = "bm1" } }
|
||||
NotesPush.run(client, identity, "c1", nil, annotations, function(o) ok = o end)
|
||||
Stubs.flush()
|
||||
Assert.is_nil(ok)
|
||||
Assert.len(annotations, 1, "删除失败保留墓碑下轮重试")
|
||||
end
|
||||
|
||||
do -- 取消:在途请求被取消,迟到回包不回调
|
||||
local client = fakeClient({})
|
||||
local called = false
|
||||
local job = NotesPush.run(client, identity, "c1", nil, {}, function() called = true end)
|
||||
job.cancel()
|
||||
Stubs.flush()
|
||||
Assert.is_false(called)
|
||||
Assert.eq(client.calls[2], "cancel:bookmarkListAsync")
|
||||
end
|
||||
|
||||
do -- 想法列表预检失败只跳过想法对账,不阻断划线:已有 review id 保留
|
||||
local client = fakeClient({ bookmarkListAsync = { updated = {} }, myReviewsAsync = false })
|
||||
local item = { drawer = "lighten", text = "t", wr_bookmark_id = "gone", wr_review_id = "rv1" }
|
||||
local ok, err
|
||||
NotesPush.run(client, identity, "c1", nil, { item }, function(o, e) ok, err = o, e end)
|
||||
Stubs.flush()
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(item.wr_review_id, "rv1")
|
||||
Assert.is_nil(item.wr_bookmark_id)
|
||||
end
|
||||
|
||||
do -- 新划线定位:range 原文走 Position 缓存(开书记住的那份),同步命中不重拉整章
|
||||
local Toc = require("moonsource_weread.toc")
|
||||
local Position = require("moonsource_weread.progress")
|
||||
local old_read, old_load = Toc.read, Position.loadAsync
|
||||
Toc.read = function() return { { uid = "c1" } } end
|
||||
local load_calls = 0
|
||||
Position.loadAsync = function(_identity, _chapter, cb)
|
||||
load_calls = load_calls + 1
|
||||
-- 缓存命中:同步回调、返回 nil(与 Position.loadAsync 真实行为一致)
|
||||
cb('<html><head><title>tttttttttt</title></head><body><p>hello world</p></body></html>', "html")
|
||||
return nil
|
||||
end
|
||||
local submitted = false
|
||||
local item = {
|
||||
drawer = "lighten", text = "hello",
|
||||
pos0 = "/html/body/p/text().0", pos1 = "/html/body/p/text().5",
|
||||
}
|
||||
local client = fakeClient({
|
||||
bookmarkListAsync = function()
|
||||
if not submitted then return { updated = {} } end
|
||||
return { updated = { {
|
||||
chapterUid = "c1", range = item.wr_range, bookmarkId = "bm-new",
|
||||
markText = "hello", type = 1,
|
||||
} } }
|
||||
end,
|
||||
myReviewsAsync = { reviews = {} },
|
||||
addBookmarkAsync = function() submitted = true; return { bookmarkId = "bm-new" } end,
|
||||
bookInfoAsync = { book = { version = 7 } },
|
||||
})
|
||||
local ok, err
|
||||
NotesPush.run(client, identity, "c1",
|
||||
"<html><body><p>hello world</p></body></html>", { item },
|
||||
function(o, e) ok, err = o, e end)
|
||||
Stubs.flush()
|
||||
Toc.read, Position.loadAsync = old_read, old_load
|
||||
Assert.is_true(ok)
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(load_calls, 1)
|
||||
-- 53 = wire 原文里 <p> 之前的全部 rune(head/title 计入),与本地壳无关
|
||||
Assert.eq(item.wr_range, "53-58")
|
||||
Assert.eq(item.wr_bookmark_id, "bm-new")
|
||||
end
|
||||
|
||||
do -- 想法清单拿不到:新想法不推(认不回上轮已成功的会重复),报失败留脏;划线与已有想法照常
|
||||
local client = fakeClient({ bookmarkListAsync = { updated = {} }, myReviewsAsync = false })
|
||||
local item = { drawer = "lighten", text = "t", note = "想法", wr_review_only = true, wr_range = "1-2" }
|
||||
local ok, err
|
||||
NotesPush.run(client, identity, "c1", nil, { item }, function(o, e) ok, err = o, e end)
|
||||
Stubs.flush()
|
||||
Assert.is_nil(ok)
|
||||
Assert.not_nil(err)
|
||||
Assert.is_nil(item.wr_review_id)
|
||||
for _, name in ipairs(client.calls) do Assert.is_true(name ~= "addReviewAsync", "不得重复新增想法") end
|
||||
end
|
||||
@@ -0,0 +1,142 @@
|
||||
--[[--
|
||||
moonsource_weread.package:App 章节包口令派生与 ZipCrypto 解包。 --]]
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local Package = require("moonsource_weread.package")
|
||||
|
||||
-- 抓包样本:vid 与响应头 encryptKey → 口令。
|
||||
Assert.eq(Package.password("393727764", "LEyM8AVZMBvMt93WBCFCPw=="), "I1RVbke@p")
|
||||
Assert.is_nil(Package.password("abc", "LEyM8AVZMBvMt93WBCFCPw=="))
|
||||
|
||||
-- zip -P 生成:a.txt 为 deflate、b.txt 为 stored,均带数据描述符。
|
||||
local hex = "504b0304140009000800e5a2565df9129239220000000902000005001c00612e74787455540900032e00da6a2e00da6a75780b000104f50100000400000000905dd2c021a840192b344394132d37f6762d7d7cf1a02473b117f93084642c384d7f504b0708f91292392200000009020000504b03040a0009000000e5a2565d69111fb6120000000600000005001c00622e74787455540900032e00da6a2e00da6a75780b000104f50100000400000000dfd0647c7666697985230063aeed35d06c94504b070869111fb61200000006000000504b01021e03140009000800e5a2565df91292392200000009020000050018000000000001000000a48100000000612e74787455540500032e00da6a75780b000104f50100000400000000504b01021e030a0009000000e5a2565d69111fb61200000006000000050018000000000001000000a48171000000622e74787455540500032e00da6a75780b000104f50100000400000000504b0506000000000200020096000000d20000000000"
|
||||
local zip = hex:gsub("%x%x", function(h) return string.char(tonumber(h, 16)) end)
|
||||
local files = Package.unzip(zip, "I1RVbke@p")
|
||||
Assert.eq(files["a.txt"], ("hello 月读 "):rep(40) .. "\n")
|
||||
Assert.eq(files["b.txt"], "second")
|
||||
|
||||
local need = Package.unzipNeed(zip)
|
||||
local unpacked = #files["a.txt"] + #files["b.txt"]
|
||||
Assert.eq(need, 2 * unpacked + 3 * 34 + 65536,
|
||||
"预检覆盖正文拼接、最大加密条目的三份临时缓冲与 inflate 输出块")
|
||||
Assert.eq(Package.unzipNeed("not a zip"), 3 * #"not a zip")
|
||||
|
||||
local bad, err = Package.unzip(zip, "wrong")
|
||||
Assert.is_nil(bad)
|
||||
Assert.matches(err, "^zip:")
|
||||
local none, err2 = Package.unzip(zip, nil)
|
||||
Assert.is_nil(none)
|
||||
Assert.matches(err2, "password required")
|
||||
|
||||
local info = "info"
|
||||
package.loaded["json"] = {
|
||||
decode = function(raw)
|
||||
Assert.eq(raw, info)
|
||||
return { chapters = { { chapterUid = 27, files = { "Text/S.xhtml", "Text/S_1.xhtml", "Text/S_2.xhtml" } } } }
|
||||
end,
|
||||
}
|
||||
package.loaded["moonsource_weread.package"] = nil
|
||||
local Composed = require("moonsource_weread.package")
|
||||
local book = {
|
||||
["info.txt"] = info,
|
||||
["Text/S.xhtml"] = "<html><body><h1>T</h1></body></html>",
|
||||
["Text/S_1.xhtml"] = "<html><body class=x><p>a</p></body></html>",
|
||||
["Text/S_2.xhtml"] = "<html><body><p>b</p></body></html>",
|
||||
}
|
||||
Assert.eq(Composed.chapterHtml(book, 27), "<html><body><h1>T</h1><p>a</p><p>b</p></body></html>")
|
||||
local miss, merr = Composed.chapterHtml(book, 99)
|
||||
Assert.is_nil(miss)
|
||||
Assert.matches(merr, "not in package")
|
||||
|
||||
-- TXT 走 ZIP 时 info.txt 只有 chapterUid、没有 files:不能再索引 files[1] 崩掉。
|
||||
package.loaded["json"] = {
|
||||
decode = function()
|
||||
return { chapters = { { chapterUid = 1595 } } }
|
||||
end,
|
||||
}
|
||||
package.loaded["moonsource_weread.package"] = nil
|
||||
local NoFiles = require("moonsource_weread.package")
|
||||
local bare, bare_err = NoFiles.chapterHtml({ ["info.txt"] = "bare" }, 1595)
|
||||
Assert.is_nil(bare)
|
||||
Assert.matches(bare_err, "no HTML files")
|
||||
|
||||
-- ZIP 解开后的 map:正文条目 bookId_uid / bookId_uid_o(实机样本)及续篇。
|
||||
local zip_map = {
|
||||
["info.txt"] = '{"chapters":[{"chapterUid":1595}]}',
|
||||
["820954_1595_o"] = "\239\187\191甲",
|
||||
["820954_1595_0001"] = "乙",
|
||||
["820954_1596_o"] = "别章",
|
||||
}
|
||||
Assert.eq(Package.chapterZipText(zip_map, "820954", 1595), "甲乙", "_o 主文件须排在 _0001 续篇前")
|
||||
Assert.is_nil(Package.chapterZipText(zip_map, "820954", 9))
|
||||
Assert.is_nil(Package.chapterZipText({ ["info.txt"] = "{}" }, "820954", 1))
|
||||
|
||||
local function tarHeader(name, size)
|
||||
local h = string.rep("\0", 512)
|
||||
local function poke(off, s)
|
||||
h = h:sub(1, off - 1) .. s .. h:sub(off + #s)
|
||||
end
|
||||
poke(1, name)
|
||||
poke(125, string.format("%011o", size))
|
||||
poke(157, "0")
|
||||
poke(258, "ustar\0")
|
||||
return h
|
||||
end
|
||||
|
||||
local function tarEntry(name, data)
|
||||
local padded = data .. string.rep("\0", (512 - (#data % 512)) % 512)
|
||||
return tarHeader(name, #data) .. padded
|
||||
end
|
||||
|
||||
local tar = tarEntry("info.txt", "{}")
|
||||
.. tarEntry("820954_1", "\239\187\191甲")
|
||||
.. tarEntry("820954_1_0001", "乙")
|
||||
.. tarEntry("820954_12", "别章")
|
||||
.. string.rep("\0", 1024)
|
||||
local text = Package.chapterText(tar, "820954", 1)
|
||||
Assert.eq(text, "甲乙")
|
||||
local absent = Package.chapterText(tar, "820954", 9)
|
||||
Assert.is_nil(absent)
|
||||
|
||||
Assert.eq(Package.pickStyle({ ["Styles/stylesheets.css"] = "a" }), "a")
|
||||
Assert.eq(Package.pickStyle({ ["Styles/stylesheet.css"] = "b" }), "b")
|
||||
Assert.eq(Package.pickStyle({
|
||||
["Styles/extra.css"] = "x",
|
||||
["Styles/stylesheet.css"] = "b",
|
||||
}), "b")
|
||||
Assert.eq(Package.pickStyle({ ["Styles/a.css"] = "1", ["Styles/z.css"] = "2" }), "1")
|
||||
Assert.is_nil(Package.pickStyle({ ["Text/a.xhtml"] = "<p/>" }))
|
||||
|
||||
-- 官方 chapters 批次串:连续合并,首批 0-n,其后 0,a-b。
|
||||
Assert.eq(Package.formatChaptersParam({ 1, 2, 3, 4, 5 }), "0-5")
|
||||
Assert.eq(Package.formatChaptersParam({ 6, 7, 8, 9, 10 }), "0,6-10")
|
||||
Assert.eq(Package.formatChaptersParam({ 96, 97, 98, 99, 100 }), "0,96-100")
|
||||
Assert.eq(Package.formatChaptersParam({ 12 }), "0,12")
|
||||
Assert.eq(Package.formatChaptersParam({}), "0")
|
||||
Assert.eq(Package.formatChaptersParam({ "a", "b" }), "0,a,b")
|
||||
|
||||
-- 批量解包:一次 zip 多章 + 样式。
|
||||
package.loaded["json"] = {
|
||||
decode = function()
|
||||
return { chapters = {
|
||||
{ chapterUid = 1, files = { "Text/c1.xhtml" } },
|
||||
{ chapterUid = 2, files = { "Text/c2.xhtml" } },
|
||||
} }
|
||||
end,
|
||||
}
|
||||
package.loaded["moonsource_weread.package"] = nil
|
||||
local Batch = require("moonsource_weread.package")
|
||||
local batch_files = {
|
||||
["info.txt"] = "info",
|
||||
["Text/c1.xhtml"] = "<html><body><p>一</p></body></html>",
|
||||
["Text/c2.xhtml"] = "<html><body><p>二</p></body></html>",
|
||||
["Styles/stylesheets.css"] = ".x{}",
|
||||
}
|
||||
local extracted, style = Batch.extractChapters(batch_files, "bid", { 1, 2 }, "epub")
|
||||
Assert.eq(style, ".x{}")
|
||||
Assert.eq(extracted["1"].text, "<html><body><p>一</p></body></html>")
|
||||
Assert.eq(extracted["2"].text, "<html><body><p>二</p></body></html>")
|
||||
Assert.is_nil(extracted["1"].err)
|
||||
local miss = Batch.extractChapters(batch_files, "bid", { 9 }, "epub")
|
||||
Assert.not_nil(miss["9"].err)
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
--[[--
|
||||
微信进度原文缓存与章节壳层的坐标回归。
|
||||
|
||||
@module tests.moonsource_weread.progress_spec
|
||||
--]]
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local JSON = require("support.json_stub")
|
||||
package.preload["json"] = function() return JSON end
|
||||
|
||||
local fetched = 0
|
||||
local source = "<html><body><p>原始正文与章节末尾</p></body></html>"
|
||||
package.preload["moonsource_weread.chapter"] = function()
|
||||
return {
|
||||
fetchHtmlAsync = function(_id, _chapter, cb)
|
||||
fetched = fetched + 1
|
||||
cb(source, nil, source, "html")
|
||||
end,
|
||||
}
|
||||
end
|
||||
local Position = require("moonsource_weread.progress")
|
||||
local Paths = require("utils.paths")
|
||||
local identity = { source_id = "ext.weread", stable_id = "progress-coordinate-spec" }
|
||||
local chapter = { idx = 1, uid = "old", title = "章名" }
|
||||
local path = Paths.bookWorkDir(identity.stable_id, identity.source_id) .. "/1.position.json"
|
||||
local local_path = Paths.chapterPath(identity.stable_id, 1, identity.source_id)
|
||||
os.remove(path)
|
||||
os.remove(local_path)
|
||||
|
||||
local ok, err = Position.remember(identity.stable_id, chapter, source, "html")
|
||||
Assert.is_true(ok)
|
||||
Assert.is_nil(err)
|
||||
local raw, format
|
||||
Position.loadAsync(identity, chapter, function(s, f) raw, format = s, f end)
|
||||
Assert.eq(raw, source)
|
||||
Assert.eq(format, "html")
|
||||
Assert.eq(fetched, 0, "相同章节原文命中缓存,不联网")
|
||||
|
||||
chapter.uid = "new"
|
||||
Position.loadAsync(identity, chapter, function(s, f) raw, format = s, f end)
|
||||
Assert.eq(fetched, 1, "章节 uid 变化不能复用旧原文")
|
||||
Assert.eq(raw, source)
|
||||
Position.loadAsync(identity, chapter, function(s) raw = s end)
|
||||
Assert.eq(fetched, 1)
|
||||
|
||||
local pos = { fraction = 0.5, extra = { chapter_offset = 16 } }
|
||||
Assert.is_true(Position.localize(identity, chapter, pos, source, "html"))
|
||||
Assert.eq(pos.locator, "/html/body/p/text().1")
|
||||
Assert.is_nil(pos.chapter_fraction, "字符比不能进章内页比例字段")
|
||||
Assert.not_nil(pos.extra.chapter_char_fraction)
|
||||
Assert.eq(Position.encode(identity, chapter, pos, source, "html"), 16)
|
||||
|
||||
pos = { fraction = 0.5, extra = { chapter_offset = 1 } }
|
||||
Assert.is_true(Position.localize(identity, chapter, pos, "一行正文\n第二行", "txt"))
|
||||
Assert.eq(pos.locator, "/html/body/p[1]/text().1", "TXT 的标题与章节壳层不能改变原文字符坐标")
|
||||
Assert.eq(Position.encode(identity, chapter, pos, "一行正文\n第二行", "txt"), 1)
|
||||
Assert.eq(Position.encode(identity, chapter, { fraction = 0, chapter_fraction = 0 }, source, "html"), 0)
|
||||
Assert.not_nil(Position.encode(identity, chapter, { fraction = 1, chapter_fraction = 1 }, source, "html"))
|
||||
local mid_offset = Position.encode(identity, chapter, { fraction = 0.5, chapter_fraction = 0.25 }, source, "html")
|
||||
local Annotations = require("book.annotations")
|
||||
local wire_end = Annotations.rangeMapping(source, "html").ends
|
||||
wire_end = wire_end[#wire_end] or 0
|
||||
Assert.eq(mid_offset, math.floor(0.25 * wire_end + 0.5), "没有 locator 时按章内比例换算原文偏移")
|
||||
local offset, summary, fraction, reason = Position.encode(identity, chapter, { fraction = 0.5 }, source, "html")
|
||||
Assert.eq(offset, 0, "没有定位和章内比例时按章首上报")
|
||||
Assert.eq(summary, "")
|
||||
Assert.eq(fraction, 0)
|
||||
Assert.is_nil(reason)
|
||||
Assert.eq(Position.encode(identity, chapter, {
|
||||
fraction = 0.5, locator = "/html/body/div/text().0", extra = { chapter_idx = 1, chapter_offset = 16 },
|
||||
}, source, "html"), 16, "对不上时回退同章旧偏移")
|
||||
Assert.eq(Position.encode(identity, chapter, {
|
||||
fraction = 0.5, locator = "/html/body/div/text().0", extra = { chapter_idx = 9, chapter_offset = 16 },
|
||||
}, source, "html"), 0, "旧偏移属于别的章时不能复用")
|
||||
Assert.eq(Position.encode(identity, chapter, {
|
||||
fraction = 0.5, chapter_fraction = 0.25, locator = "/html/body/div/text().0",
|
||||
extra = { chapter_idx = 1, chapter_offset = 16 },
|
||||
}, source, "html"), mid_offset, "对不上时优先章内比例,不用陈旧 extra 偏移")
|
||||
|
||||
local open = io.open
|
||||
io.open = function(filename, mode)
|
||||
if filename == path .. ".part" then return nil, "read-only cache" end
|
||||
return open(filename, mode)
|
||||
end
|
||||
ok, err = Position.remember(identity.stable_id, chapter, source, "html")
|
||||
io.open = open
|
||||
Assert.is_nil(ok)
|
||||
Assert.eq(err, "read-only cache")
|
||||
os.remove(path)
|
||||
|
||||
do
|
||||
local comic = '<html><body>'
|
||||
.. '<div><img class="qqreader-fullimg" src="a.jpg"/></div>'
|
||||
.. '<div><img class="qqreader-fullimg" src="b.jpg"/></div>'
|
||||
.. '</body></html>'
|
||||
local comic_id = { source_id = "ext.weread", stable_id = "progress-comic-spec" }
|
||||
local comic_chapter = { idx = 4, uid = "29", title = "向日葵花园" }
|
||||
local comic_local = Paths.chapterPath(comic_id.stable_id, 4, comic_id.source_id)
|
||||
Paths.ensureDir(comic_local:match("(.+)/[^/]+$"))
|
||||
local out = assert(io.open(comic_local, "wb"))
|
||||
out:write(comic)
|
||||
out:close()
|
||||
local pos = {
|
||||
locator = "/html/body/div[2]/img.0",
|
||||
chapter_fraction = 0.5,
|
||||
extra = {},
|
||||
}
|
||||
local offset, summary, fraction, err = Position.encode(comic_id, comic_chapter, pos, comic, "html")
|
||||
Assert.is_nil(err)
|
||||
Assert.not_nil(offset)
|
||||
Assert.is_true(offset > 0, "第二张图不应落在文档开头")
|
||||
Assert.eq(summary, "")
|
||||
Assert.eq(fraction, 0.5, "纯图章沿用阅读器章内页比例")
|
||||
local frag_offset, frag_summary, frag_fraction, frag_err = Position.encode(comic_id, comic_chapter, {
|
||||
locator = "/body/DocFragment[1]/body/div[2]/img.0",
|
||||
chapter_fraction = 0.5,
|
||||
extra = {},
|
||||
}, comic, "html")
|
||||
Assert.is_nil(frag_err)
|
||||
Assert.eq(frag_offset, offset, "纯图章 DocFragment 路径应映到同一偏移")
|
||||
Assert.eq(frag_summary, "")
|
||||
Assert.eq(frag_fraction, 0.5)
|
||||
local raw_len = 0
|
||||
do
|
||||
local i, len = 1, #comic
|
||||
while i <= len do
|
||||
local byte = comic:byte(i)
|
||||
i = i + (byte < 0x80 and 1 or byte < 0xe0 and 2 or byte < 0xf0 and 3 or 4)
|
||||
raw_len = raw_len + 1
|
||||
end
|
||||
end
|
||||
local fb_offset, fb_summary, fb_fraction, fb_err = Position.encode(comic_id, comic_chapter, {
|
||||
locator = "/html/body/div[9]/img.0",
|
||||
chapter_fraction = 0.25,
|
||||
extra = {},
|
||||
}, comic, "html")
|
||||
Assert.is_nil(fb_err)
|
||||
Assert.eq(fb_offset, math.floor(0.25 * raw_len + 0.5), "纯图章对不上时按原文 HTML 长度比例回退")
|
||||
Assert.eq(fb_summary, "")
|
||||
Assert.eq(fb_fraction, 0.25)
|
||||
-- 正文回归:原有文本章 encode 不被破坏
|
||||
Assert.eq(Position.encode(identity, chapter, {
|
||||
locator = "/html/body/p/text().1", fraction = 0.5, extra = { chapter_offset = 16 },
|
||||
}, source, "html"), 16)
|
||||
os.remove(comic_local)
|
||||
end
|
||||
@@ -0,0 +1,199 @@
|
||||
--[[--
|
||||
moonsource_weread.protocol 离线用例(依赖本机 koreader/base 的 ffi/sha2)
|
||||
|
||||
@module tests.wechat_protocol_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 md5 = require("ffi/sha2").md5
|
||||
local Protocol = require("moonsource_weread.protocol")
|
||||
|
||||
-- encode:数字 vs 非数字路径不同;结果确定性
|
||||
do
|
||||
Assert.eq(Protocol.encode("123"), "2023270027b202cb962a56f")
|
||||
Assert.eq(Protocol.encode("abc"), "900427206616263900156d7")
|
||||
-- 同一输入多次一致
|
||||
Assert.eq(Protocol.encode("3300022941"), Protocol.encode("3300022941"))
|
||||
end
|
||||
|
||||
-- sortedQuery:按 key 排序,跳过 s,做 urlencode
|
||||
do
|
||||
Assert.eq(Protocol.sortedQuery({ b = 2, a = 1, s = "drop" }), "a=1&b=2")
|
||||
Assert.eq(Protocol.sortedQuery({ q = "a b" }), "q=a%20b")
|
||||
Assert.eq(Protocol.sortedQuery({ t = true, f = false }), "f=false&t=true")
|
||||
end
|
||||
|
||||
-- sign:对 query 串确定性哈希
|
||||
do
|
||||
Assert.eq(Protocol.sign("a=1&b=2"), "2a0a2922")
|
||||
Assert.eq(Protocol.sign(""), Protocol.sign(""))
|
||||
end
|
||||
|
||||
-- readerUrl
|
||||
do
|
||||
local url = Protocol.readerUrl("3300022941")
|
||||
Assert.is_true(url:find("^https://weread%.qq%.com/web/reader/", 1) ~= nil)
|
||||
Assert.is_true(url:find("k", 1, true) == nil)
|
||||
|
||||
local with_ch = Protocol.readerUrl("3300022941", "100")
|
||||
Assert.is_true(with_ch:find("k" .. Protocol.encode("100"), 1, true) ~= nil)
|
||||
Assert.is_true(with_ch:find(Protocol.encode("3300022941"), 1, true) ~= nil)
|
||||
end
|
||||
|
||||
-- contentParams:结构完整,s 与 sortedQuery 自洽;固定时间/随机
|
||||
do
|
||||
local real_time, real_random = os.time, math.random
|
||||
os.time = function()
|
||||
return 1700000000
|
||||
end
|
||||
math.random = function()
|
||||
return 3
|
||||
end
|
||||
local psvts = "not-matching"
|
||||
local params = Protocol.contentParams("bid", "cuid", psvts, { style = true, sc = 2 })
|
||||
os.time = real_time
|
||||
math.random = real_random
|
||||
|
||||
Assert.eq(params.b, Protocol.encode("bid"))
|
||||
Assert.eq(params.c, Protocol.encode("cuid"))
|
||||
Assert.eq(params.ps, psvts)
|
||||
Assert.eq(params.sc, 2)
|
||||
Assert.eq(params.st, 1)
|
||||
Assert.eq(params.prevChapter, false)
|
||||
Assert.not_nil(params.s)
|
||||
local expect_s = Protocol.sign(Protocol.sortedQuery(params))
|
||||
Assert.eq(params.s, expect_s)
|
||||
end
|
||||
|
||||
-- contentParams:encode(ct)==psvts 时 ct 递增
|
||||
do
|
||||
local ct0 = 1700000001
|
||||
local real_time, real_random = os.time, math.random
|
||||
os.time = function()
|
||||
return ct0
|
||||
end
|
||||
math.random = function()
|
||||
return 1
|
||||
end
|
||||
local psvts = Protocol.encode(ct0)
|
||||
local params = Protocol.contentParams("b", "c", psvts)
|
||||
os.time = real_time
|
||||
math.random = real_random
|
||||
Assert.eq(params.ct, tostring(ct0 + 1))
|
||||
Assert.eq(params.pc, Protocol.encode(ct0 + 1))
|
||||
end
|
||||
|
||||
-- decodeShards:错误路径
|
||||
do
|
||||
local t, err = Protocol.decodeShards()
|
||||
Assert.is_nil(t)
|
||||
Assert.eq(err, "empty shards")
|
||||
|
||||
t, err = Protocol.decodeShards("too-short")
|
||||
Assert.is_nil(t)
|
||||
Assert.eq(err, "shard too short")
|
||||
|
||||
t, err = Protocol.decodeShards(string.rep("0", 32) .. "body-with-bad-md5!!!!")
|
||||
Assert.is_nil(t)
|
||||
Assert.eq(err, "shard md5 mismatch")
|
||||
end
|
||||
|
||||
-- decodeShards:长正文(swapPositions 多位置分支)
|
||||
--
|
||||
-- 反向构造:从明文 base64 出发,按 reverseSwaps 的交换序列倒序施加得到混淆串,
|
||||
-- 解码后必须还原。交换下标恒小于 len-n-1,不会碰到 swapPositions 读取的尾部字节,
|
||||
-- 所以位置表可以直接从明文 base64 上算。
|
||||
do
|
||||
local function upvalue(fn, name)
|
||||
local i = 1
|
||||
while true do
|
||||
local n, v = debug.getupvalue(fn, i)
|
||||
if n == nil then
|
||||
return nil
|
||||
end
|
||||
if n == name then
|
||||
return v
|
||||
end
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
local decodeEncodedBody = upvalue(Protocol.decodeShards, "decodeEncodedBody")
|
||||
Assert.not_nil(decodeEncodedBody)
|
||||
local swapPositions = upvalue(decodeEncodedBody, "swapPositions")
|
||||
Assert.not_nil(swapPositions)
|
||||
|
||||
local plain = string.rep("微信读书章节正文 weread chapter body. ", 20)
|
||||
local b64 = require("utils.text").base64Encode(plain)
|
||||
Assert.is_true(#b64 > 200)
|
||||
|
||||
local positions = swapPositions(b64)
|
||||
Assert.is_true(#positions > 2, "长输入应走多位置分支")
|
||||
Assert.eq(#positions % 2, 0)
|
||||
|
||||
-- reverseSwaps 实际执行的交换序列
|
||||
local ops = {}
|
||||
for i = #positions, 1, -2 do
|
||||
for k = 1, 0, -1 do
|
||||
ops[#ops + 1] = { positions[i] + k + 1, positions[i - 1] + k + 1 }
|
||||
end
|
||||
end
|
||||
local chars = {}
|
||||
for i = 1, #b64 do
|
||||
chars[i] = b64:sub(i, i)
|
||||
end
|
||||
for i = #ops, 1, -1 do
|
||||
local a, b = ops[i][1], ops[i][2]
|
||||
chars[a], chars[b] = chars[b], chars[a]
|
||||
end
|
||||
local body = "x" .. table.concat(chars)
|
||||
local text, err = Protocol.decodeShards(md5(body):upper() .. body)
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(text, plain)
|
||||
end
|
||||
|
||||
-- decodeShards:合法分片 → hello
|
||||
do
|
||||
-- 构造:对 base64("hello") 做与 reverseSwaps 相反的交换(len<11 → positions {0,2})
|
||||
local b64 = "aGVsbG8="
|
||||
local chars = {}
|
||||
for i = 1, #b64 do
|
||||
chars[i] = b64:sub(i, i)
|
||||
end
|
||||
local function swap(i, j)
|
||||
chars[i], chars[j] = chars[j], chars[i]
|
||||
end
|
||||
swap(3, 1)
|
||||
swap(4, 2)
|
||||
local body = "x" .. table.concat(chars)
|
||||
local shard = md5(body):upper() .. body
|
||||
local text, err = Protocol.decodeShards(shard)
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(text, "hello")
|
||||
end
|
||||
|
||||
-- makeReadPayload:rt/ts/rn/sg 字段齐全
|
||||
do
|
||||
local real_time, real_random = os.time, math.random
|
||||
os.time = function() return 1700000000 end
|
||||
math.random = function() return 42 end
|
||||
local payload = Protocol.makeReadPayload({
|
||||
book_id = "123",
|
||||
chapter_uid = "9",
|
||||
chapter_idx = 1,
|
||||
progress = 50,
|
||||
summary = "章节",
|
||||
psvts = "abc",
|
||||
elapsed_seconds = 30,
|
||||
})
|
||||
os.time = real_time
|
||||
math.random = real_random
|
||||
Assert.eq(payload.pr, 50)
|
||||
Assert.eq(payload.rt, 30)
|
||||
Assert.eq(payload.sm, "章节")
|
||||
-- 摘要按码点截 20 个,不切断多字节字符;非法字节处停住
|
||||
Assert.eq(Protocol.makeReadPayload({ summary = string.rep("书", 25) }).sm, string.rep("书", 20))
|
||||
Assert.eq(Protocol.makeReadPayload({ summary = "ab\255cd" }).sm, "ab")
|
||||
Assert.not_nil(payload.sg)
|
||||
Assert.not_nil(payload.s)
|
||||
end
|
||||
@@ -0,0 +1,265 @@
|
||||
--[[--
|
||||
moonsource_weread.reviews 离线用例:热点定位、批量请求与分页映射。
|
||||
|
||||
@module tests.moonsource_weread.reviews_spec
|
||||
--]]
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local Stubs = require("support.stubs")
|
||||
Stubs.install()
|
||||
package.preload["json"] = function() return require("support.json_stub") end
|
||||
package.loaded["json"] = nil
|
||||
local Reviews = require("moonsource_weread.reviews")
|
||||
|
||||
local html = table.concat({
|
||||
"<html><body><h1>一</h1>",
|
||||
"<p>我在森崎书店的日子,是从夏初到翌年的初春。</p>",
|
||||
"<p>重复句。</p><p>重复句。</p>",
|
||||
"<p>第一段结尾</p><p>第二段开头</p>",
|
||||
"</body></html>",
|
||||
})
|
||||
|
||||
---@param range string
|
||||
---@param abstract string
|
||||
---@param total integer
|
||||
local function entry(range, abstract, total)
|
||||
return {
|
||||
range = range,
|
||||
totalCount = total,
|
||||
maxIdx = 1,
|
||||
hasMore = 1,
|
||||
pageReviews = { {
|
||||
reviewId = "r-" .. range,
|
||||
likesCount = 21,
|
||||
review = { abstract = abstract, content = "点评", createTime = 1788166709, author = { name = "橘枳" } },
|
||||
} },
|
||||
}
|
||||
end
|
||||
|
||||
do
|
||||
local hotspots = Reviews.hotspots({ reviews = {
|
||||
entry("386-407", "我在森崎书店的日子,是从夏初到翌年的初春。", 83),
|
||||
-- 重复原句无法消歧:不画错位置,直接丢。
|
||||
entry("500-504", "重复句。", 5),
|
||||
-- 跨段原句带换行:按段落边界规范化后仍能定位。
|
||||
entry("600-611", "第一段结尾\n第二段开头", 7),
|
||||
entry("700-710", "正文里没有的句子", 3),
|
||||
-- 没有段评的热点不标。
|
||||
entry("800-810", "我在森崎书店的日子", 0),
|
||||
} })
|
||||
Assert.len(hotspots, 4)
|
||||
Assert.is_nil(rawget(hotspots[1], "pos0"), "拉取不定位")
|
||||
local spots = Reviews.locate(hotspots, html)
|
||||
Assert.len(spots, 2)
|
||||
Assert.eq(spots[1].range, "386-407")
|
||||
Assert.eq(spots[1].total, 83)
|
||||
Assert.eq(spots[1].pos0, "/html/body/p[1]/text().0")
|
||||
Assert.eq(spots[1].pos1, "/html/body/p[1]/text().21")
|
||||
Assert.eq(spots[2].range, "600-611")
|
||||
Assert.eq(spots[2].pos0, "/html/body/p[4]/text().0")
|
||||
Assert.eq(spots[2].pos1, "/html/body/p[5]/text().5")
|
||||
Assert.len(Reviews.hotspots({}), 0)
|
||||
Assert.len(Reviews.locate({}, html), 0)
|
||||
-- 同一批热点可在另一份 HTML 上重新定位(整本 EPUB 的各分片)。
|
||||
local other = Reviews.locate(hotspots, "<DocFragment><body><p>前文。我在森崎书店的日子,是从夏初到翌年的初春。</p></body></DocFragment>")
|
||||
Assert.len(other, 1)
|
||||
Assert.eq(other[1].pos0, "/docfragment/body/p/text().3")
|
||||
end
|
||||
|
||||
do
|
||||
local item = Reviews.item(entry("1-2", "x", 1).pageReviews[1])
|
||||
Assert.eq(item.id, "r-1-2")
|
||||
Assert.eq(item.author, "橘枳")
|
||||
Assert.eq(item.content, "点评")
|
||||
Assert.eq(item.likes, 21)
|
||||
Assert.eq(item.replies, 0)
|
||||
Assert.eq(item.time, 1788166709)
|
||||
local with_replies = Reviews.item({
|
||||
reviewId = "r", likesCount = 1, commentsCount = 4,
|
||||
review = { content = "点评", createTime = 1, author = { name = "甲" } },
|
||||
})
|
||||
Assert.eq(with_replies.replies, 4)
|
||||
end
|
||||
|
||||
do -- 想法下的评论页:楼中楼只记被回复者;空列表但声称有条数是失败;游标不前进就停
|
||||
local page = Reviews.comments({
|
||||
commentsCount = 3,
|
||||
commentsHasMore = 1,
|
||||
commentsMaxIdx = 2,
|
||||
comments = {
|
||||
{ commentId = "c1", content = "说得对", createTime = 10, likesCount = 2, author = { name = "乙" } },
|
||||
{ commentId = "c2", content = "同意", createTime = 11, author = { name = "丙" },
|
||||
replyUser = { name = "乙" } },
|
||||
},
|
||||
}, 0)
|
||||
Assert.len(page.items, 2)
|
||||
Assert.eq(page.items[1].id, "c1")
|
||||
Assert.eq(page.items[1].author, "乙")
|
||||
Assert.eq(page.items[1].likes, 2)
|
||||
Assert.eq(page.items[1].replies, 0)
|
||||
Assert.is_nil(page.items[1].reply_to)
|
||||
Assert.eq(page.items[2].reply_to, "乙")
|
||||
Assert.eq(page.total, 3)
|
||||
Assert.eq(page.max_idx, 2)
|
||||
Assert.is_true(page.more)
|
||||
|
||||
local again = Reviews.comments({ commentsCount = 3, commentsHasMore = 1, commentsMaxIdx = 2, comments = {
|
||||
{ commentId = "c3", content = "还有", createTime = 12, author = { name = "丁" } },
|
||||
} }, 2)
|
||||
Assert.is_false(again.more, "游标停在原地就不再翻")
|
||||
|
||||
local _empty, err = Reviews.comments({ commentsCount = 4, comments = {} }, 0)
|
||||
Assert.is_nil(_empty)
|
||||
Assert.eq(err, "无法获取回复")
|
||||
_empty, err = Reviews.comments({ commentsCount = 1 }, 0)
|
||||
Assert.is_nil(_empty)
|
||||
Assert.eq(err, "无法获取回复")
|
||||
|
||||
local none = Reviews.comments({ commentsCount = 0, commentsHasMore = 0 }, 0)
|
||||
Assert.len(none.items, 0)
|
||||
Assert.is_false(none.more)
|
||||
end
|
||||
|
||||
--- 回调由测试手动触发的假 client:每个请求的回调按发出顺序留在 calls 里。
|
||||
local function fakeClient()
|
||||
local client = { calls = {}, cancelled = {} }
|
||||
function client:underlinesAsync(book_id, chapter_uid, cb)
|
||||
self.calls[#self.calls + 1] = { "underlines", book_id, chapter_uid, cb = cb }
|
||||
self.underlines_cb = cb
|
||||
return { cancel = function() self.cancelled[#self.cancelled + 1] = "underlines" end }
|
||||
end
|
||||
function client:readReviewsAsync(book_id, chapter_uid, reviews, cb)
|
||||
local n = #self.calls + 1
|
||||
self.calls[n] = { "readReviews", book_id, chapter_uid, reviews, cb = cb }
|
||||
self.reviews_cb = cb
|
||||
return { cancel = function() self.cancelled[#self.cancelled + 1] = n end }
|
||||
end
|
||||
return client
|
||||
end
|
||||
|
||||
local hit_entry = entry("386-407", "我在森崎书店的日子,是从夏初到翌年的初春。", 83)
|
||||
|
||||
do
|
||||
-- underlines → 批量 readReviews(每句 1 条)。
|
||||
local client = fakeClient()
|
||||
local got
|
||||
Reviews.hotspotsAsync(client, "b", "c1", function(spots) got = spots end)
|
||||
client.underlines_cb({ underlines = {
|
||||
{ range = "386-407", count = 935, type = 2 },
|
||||
{ range = "740-758", count = 0, type = 0 },
|
||||
} })
|
||||
local reviews = client.calls[2][4]
|
||||
Assert.eq(client.calls[2][1], "readReviews")
|
||||
Assert.len(reviews, 2)
|
||||
Assert.eq(reviews[2].range, "740-758")
|
||||
Assert.eq(reviews[1].count, 1)
|
||||
Assert.eq(reviews[1].maxIdx, 0)
|
||||
client.reviews_cb({ reviews = { hit_entry } })
|
||||
Assert.len(got, 1)
|
||||
|
||||
-- 热点多时分批(整批过大服务端 3 秒超时):40/40/40/5,同时最多 3 批在飞,结果按批次顺序合并。
|
||||
client = fakeClient()
|
||||
got = nil
|
||||
Reviews.hotspotsAsync(client, "b", "c2", function(spots) got = spots end)
|
||||
local many = {}
|
||||
for i = 1, 125 do many[i] = { range = i .. "-" .. (i + 1) } end
|
||||
client.underlines_cb({ underlines = many })
|
||||
Assert.len(client.calls, 4, "3 批并发")
|
||||
Assert.eq(client.calls[2][4][1].range, "1-2")
|
||||
Assert.eq(client.calls[3][4][1].range, "41-42")
|
||||
Assert.len(client.calls[4][4], 40)
|
||||
client.calls[3].cb({ reviews = { entry("41-42", "第二批", 1) } })
|
||||
Assert.len(client.calls, 5, "回来一批补一批")
|
||||
Assert.len(client.calls[5][4], 5)
|
||||
client.calls[5].cb({ reviews = { entry("121-122", "第四批", 1) } })
|
||||
client.calls[4].cb({ reviews = {} })
|
||||
Assert.is_nil(got)
|
||||
client.calls[2].cb({ reviews = { entry("1-2", "第一批", 1) } })
|
||||
Assert.len(got, 3)
|
||||
Assert.eq(got[1].range, "1-2")
|
||||
Assert.eq(got[2].range, "41-42")
|
||||
Assert.eq(got[3].range, "121-122")
|
||||
|
||||
-- 一批失败:取消其余在飞批次,整章报错、不落盘,迟到的回包不再回调。
|
||||
client = fakeClient()
|
||||
local batch_err, calls = nil, 0
|
||||
got = nil
|
||||
Reviews.hotspotsAsync(client, "b", "c3", function(spots, e)
|
||||
calls, got, batch_err = calls + 1, spots, e
|
||||
end)
|
||||
client.underlines_cb({ underlines = many })
|
||||
client.calls[3].cb(nil, "timeout of 3000ms exceeded")
|
||||
Assert.len(client.calls, 4, "失败后不再发新批")
|
||||
Assert.len(client.cancelled, 2)
|
||||
Assert.is_nil(got)
|
||||
Assert.eq(batch_err, "timeout of 3000ms exceeded")
|
||||
client.calls[2].cb({ reviews = {} })
|
||||
Assert.eq(calls, 1)
|
||||
client = fakeClient()
|
||||
Reviews.hotspotsAsync(client, "b", "c3", function() end)
|
||||
Assert.len(client.calls, 1, "失败不落盘")
|
||||
|
||||
-- 本章没有热点:不发 readReviews。
|
||||
client = fakeClient()
|
||||
got = nil
|
||||
Reviews.hotspotsAsync(client, "b", "c4", function(spots) got = spots end)
|
||||
client.underlines_cb({ underlines = {} })
|
||||
Assert.len(client.calls, 1)
|
||||
Assert.len(got, 0)
|
||||
|
||||
-- 失败原样回传错误。
|
||||
client = fakeClient()
|
||||
local err
|
||||
Reviews.hotspotsAsync(client, "b", "c5", function(spots, e) got, err = spots, e end)
|
||||
client.underlines_cb(nil, "boom")
|
||||
Assert.is_nil(got)
|
||||
Assert.eq(err, "boom")
|
||||
|
||||
-- 取消:取消在飞的批次,迟到的回包不再回调。
|
||||
client = fakeClient()
|
||||
local called = false
|
||||
local job = Reviews.hotspotsAsync(client, "b", "c6", function() called = true end)
|
||||
client.underlines_cb({ underlines = { { range = "386-407" } } })
|
||||
job.cancel()
|
||||
Assert.eq(client.cancelled[1], 2)
|
||||
client.reviews_cb({ reviews = {} })
|
||||
Assert.is_false(called)
|
||||
end
|
||||
|
||||
do
|
||||
local client = fakeClient()
|
||||
local page, err
|
||||
Reviews.pageAsync(client, "b", "4", "386-407", 2, function(p, e) page, err = p, e end)
|
||||
local req = client.calls[1][4][1]
|
||||
Assert.eq(req.range, "386-407")
|
||||
Assert.eq(req.maxIdx, 2)
|
||||
Assert.eq(req.count, 30)
|
||||
client.reviews_cb({ reviews = { entry("386-407", "x", 83) } })
|
||||
Assert.is_nil(err)
|
||||
Assert.len(page.items, 1)
|
||||
Assert.eq(page.total, 83)
|
||||
Assert.eq(page.max_idx, 1)
|
||||
Assert.is_true(page.more)
|
||||
|
||||
Reviews.pageAsync(client, "b", "4", "386-407", 0, function(p, e) page, err = p, e end)
|
||||
client.reviews_cb(nil, "offline")
|
||||
Assert.is_nil(page)
|
||||
Assert.eq(err, "offline")
|
||||
end
|
||||
|
||||
do -- 已删除段评(无 review 体)和匿名作者不让整页崩溃
|
||||
local client = fakeClient()
|
||||
local page, err
|
||||
Reviews.pageAsync(client, "b", "4", "1-2", 0, function(p, e) page, err = p, e end)
|
||||
client.reviews_cb({ reviews = { {
|
||||
totalCount = 2, maxIdx = 2, hasMore = 0,
|
||||
pageReviews = {
|
||||
{ reviewId = "gone" },
|
||||
{ reviewId = "anon", review = { content = "hi", createTime = 1 } },
|
||||
},
|
||||
} } })
|
||||
Assert.is_nil(err)
|
||||
Assert.len(page.items, 1)
|
||||
Assert.eq(page.items[1].id, "anon")
|
||||
Assert.eq(page.items[1].author, "")
|
||||
end
|
||||
@@ -0,0 +1,127 @@
|
||||
--[[--
|
||||
微信读书设置页行:账号直接是设置行,登录后才追加续期与退出。
|
||||
|
||||
@module tests.moonsource_weread.setting_spec
|
||||
--]]
|
||||
|
||||
local Assert = require("support.assert")
|
||||
|
||||
local cfg = {}
|
||||
local saved = 0
|
||||
package.preload["utils.settings"] = function()
|
||||
return {
|
||||
getSource = function() return cfg end,
|
||||
saveSource = function(_, value) cfg = value; saved = saved + 1 end,
|
||||
}
|
||||
end
|
||||
local logged_in = false
|
||||
local cleared = false
|
||||
package.preload["moonsource_weread.auth"] = function()
|
||||
return {
|
||||
hasSession = function() return logged_in end,
|
||||
userLabel = function() return "tester" end,
|
||||
clearSession = function() cleared = true; logged_in = false end,
|
||||
}
|
||||
end
|
||||
local Themed = require("support.theme_stubs")
|
||||
Themed.install()
|
||||
package.preload["ui/network/manager"] = function()
|
||||
return { runWhenConnected = function(_, fn) fn() end }
|
||||
end
|
||||
local begin_cb, wait_cb
|
||||
local begin_cancels, wait_cancels = 0, 0
|
||||
package.preload["moonsource_weread.eink"] = function()
|
||||
return {
|
||||
beginQrLoginAsync = function(cb)
|
||||
begin_cb = cb
|
||||
return { cancel = function() begin_cancels = begin_cancels + 1 end }
|
||||
end,
|
||||
waitQrLoginAsync = function(_, cb)
|
||||
wait_cb = cb
|
||||
return { cancel = function() wait_cancels = wait_cancels + 1 end }
|
||||
end,
|
||||
}
|
||||
end
|
||||
package.preload["ui.themes.widgets.row"] = function()
|
||||
return { widget = function(opts) return opts end }
|
||||
end
|
||||
local auth_changed = 0
|
||||
package.preload["source.registry"] = function()
|
||||
return {
|
||||
reload = function() auth_changed = auth_changed + 1 end,
|
||||
invalidate = function() end,
|
||||
}
|
||||
end
|
||||
|
||||
package.loaded["moonsource_weread.setting"] = nil
|
||||
local Setting = require("moonsource_weread.setting")
|
||||
local updates = 0
|
||||
local plugin = { desktop = { updateView = function() updates = updates + 1 end } }
|
||||
|
||||
-- 未登录:账号、合并本地阅读时长、显示段评、自定义分组代替分类四行。
|
||||
local rows = Setting.rows(plugin)
|
||||
Assert.len(rows, 4)
|
||||
Assert.eq(rows[1]().status, "未登录 · 点此扫码")
|
||||
|
||||
-- 合并本地阅读时长默认关(云端优先);点按落盘开启并刷新设置页。
|
||||
local merge = rows[2]()
|
||||
Assert.eq(merge.kind, "toggle")
|
||||
Assert.eq(merge.title, "合并本地阅读时长")
|
||||
Assert.is_false(merge.status_on)
|
||||
merge.callback()
|
||||
Assert.is_true(cfg.merge_local_stats)
|
||||
Assert.eq(saved, 1)
|
||||
Assert.eq(updates, 1)
|
||||
Assert.is_true(rows[2]().status_on)
|
||||
|
||||
-- 段评默认关;点按落盘开启。
|
||||
local reviews = rows[3]()
|
||||
Assert.eq(reviews.title, "显示段评")
|
||||
Assert.is_false(reviews.status_on)
|
||||
reviews.callback()
|
||||
Assert.is_true(cfg.show_paragraph_reviews)
|
||||
Assert.is_true(rows[3]().status_on)
|
||||
|
||||
-- 自定义分组代替分类默认开;点按关闭并清增量游标。
|
||||
local groups = rows[4]()
|
||||
Assert.eq(groups.title, "使用自定义分组代替分类")
|
||||
Assert.is_true(groups.status_on)
|
||||
cfg.shelf_cursor = { vid = "1", synckey = 9 }
|
||||
groups.callback()
|
||||
Assert.is_false(cfg.category_as_group)
|
||||
Assert.is_nil(cfg.shelf_cursor)
|
||||
Assert.is_false(rows[4]().status_on)
|
||||
|
||||
-- 已登录:追加续期与退出;退出先确认,确认后才清会话。
|
||||
logged_in = true
|
||||
rows = Setting.rows(plugin)
|
||||
Assert.len(rows, 6)
|
||||
Assert.eq(rows[1]().status, "tester")
|
||||
Assert.eq(rows[5]().title, "续期会话")
|
||||
local logout = rows[6]()
|
||||
Assert.eq(logout.title, "退出登录")
|
||||
logout.callback()
|
||||
Assert.is_false(cleared, "未确认不退出")
|
||||
local confirm = Themed.last("confirm")
|
||||
Assert.is_true(confirm.shown)
|
||||
confirm.ok_callback()
|
||||
Assert.is_true(cleared)
|
||||
Assert.eq(auth_changed, 1)
|
||||
|
||||
-- 扫码:先出不可取消的进度窗,拿到二维码换成 QR 窗;代码换窗不算取消,用户关窗才取消轮询。
|
||||
logged_in = false
|
||||
Setting.rows(plugin)[1]().callback()
|
||||
local waiting = Themed.last("progress_dialog")
|
||||
Assert.eq(waiting.text, "正在获取二维码…")
|
||||
Assert.eq(waiting.dismissable, false)
|
||||
begin_cb({ uid = "u1", qr_payload = "weread://login?u1" })
|
||||
Assert.is_true(waiting.closed)
|
||||
Assert.eq(begin_cancels, 0)
|
||||
local qr = Themed.last("qr")
|
||||
Assert.eq(qr.text, "weread://login?u1")
|
||||
qr:close()
|
||||
Assert.eq(wait_cancels, 1)
|
||||
local made = #Themed.made
|
||||
wait_cb(nil, "迟到", "error")
|
||||
Assert.eq(#Themed.made, made, "已取消的轮询不再弹提示")
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
--[[--
|
||||
moonsource_weread.shelf_import:大快照落盘、分批入库、收尾对账(书库与游标桩掉)。
|
||||
|
||||
@module tests.moonsource_weread.shelf_import_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 dir = Config.dir() .. "/shelf_import_spec"
|
||||
os.execute("mkdir -p '" .. dir .. "'")
|
||||
|
||||
local upserted, hidden_keep, saved = {}, nil, nil
|
||||
package.loaded["utils.paths"] = {
|
||||
sourceCacheDir = function() return dir end,
|
||||
ensureDir = function() return true end,
|
||||
}
|
||||
package.loaded["book.books_db"] = {
|
||||
upsertRemoteMany = function(rows)
|
||||
for _idx, row in ipairs(rows) do upserted[#upserted + 1] = row end
|
||||
return true
|
||||
end,
|
||||
hideMissing = function(_source_id, keep)
|
||||
hidden_keep = keep
|
||||
return 2
|
||||
end,
|
||||
}
|
||||
local oversize_next = false
|
||||
package.loaded["moonsource_weread.eink"] = {
|
||||
save = function(patch) saved = patch end,
|
||||
callAsync = function(_method, _path, _opts, cb)
|
||||
if oversize_next then
|
||||
oversize_next = false
|
||||
cb({ body = "{}" }, nil, { oversize = true })
|
||||
else
|
||||
cb({})
|
||||
end
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
package.loaded["utils.awake"] = { hold = function() end }
|
||||
package.loaded["utils.settings"] = { getSource = function() return { wr_vid = "v1" } end }
|
||||
package.loaded["moonsource_weread.shelf_import"] = nil
|
||||
package.loaded["moonsource_weread.mapper"] = nil
|
||||
|
||||
local ShelfImport = require("moonsource_weread.shelf_import")
|
||||
|
||||
Assert.is_nil(ShelfImport.size())
|
||||
Assert.is_true(ShelfImport.stash("{}"))
|
||||
Assert.eq(ShelfImport.size(), 2)
|
||||
|
||||
local ids = ShelfImport.ingest({
|
||||
books = { { bookId = "b1", title = "书一" }, { bookId = "b2", title = "书二" } },
|
||||
bookProgress = { { bookId = "b1", progress = 50 } },
|
||||
archive = { { name = "分组", bookIds = { "b1" } } },
|
||||
})
|
||||
Assert.len(ids, 2)
|
||||
Assert.eq(upserted[1].source_id, "ext.weread")
|
||||
Assert.eq(upserted[1].deleted, 0)
|
||||
Assert.eq(upserted[1].percent, 50)
|
||||
|
||||
Assert.eq(ShelfImport.commit(ids, 77), 2)
|
||||
Assert.eq(hidden_keep, ids)
|
||||
Assert.eq(saved.shelf_cursor.synckey, 77)
|
||||
Assert.eq(saved.shelf_cursor.vid, "v1")
|
||||
Assert.is_nil(ShelfImport.size())
|
||||
|
||||
-- 后台同步发现/重试待导入快照时不弹窗;用户手动刷新才打开导入页。
|
||||
do
|
||||
local Client = require("moonsource_weread.client")
|
||||
Assert.is_true(ShelfImport.stash("{}"))
|
||||
local opened = 0
|
||||
require("utils.extension").add("web.open_page", function() opened = opened + 1 end)
|
||||
local got
|
||||
local handle = Client.shelfSyncAsync({}, function(data, err) got = { data, err } end, true, false)
|
||||
Assert.is_true(handle ~= nil)
|
||||
Stubs.flush()
|
||||
Assert.eq(opened, 0, "后台重试不重复弹出待导入页")
|
||||
Assert.is_nil(got[1])
|
||||
Assert.eq(got[2], ShelfImport.TOO_LARGE)
|
||||
|
||||
got = nil
|
||||
handle = Client.shelfSyncAsync({}, function(data, err) got = { data, err } end, true, true)
|
||||
Assert.is_true(handle ~= nil)
|
||||
Stubs.flush()
|
||||
Assert.eq(opened, 1, "手动强制刷新可重新打开待导入页")
|
||||
Assert.is_nil(got[1])
|
||||
Assert.eq(got[2], ShelfImport.TOO_LARGE)
|
||||
ShelfImport.discard()
|
||||
|
||||
-- 首次后台全量超限只保存快照,不能在用户已进入阅读器后突然弹页。
|
||||
oversize_next = true
|
||||
got = nil
|
||||
handle = Client.shelfSyncAsync({}, function(data, err) got = { data, err } end, true, false)
|
||||
Assert.is_true(handle ~= nil)
|
||||
Assert.eq(opened, 1, "后台首次遇到超大书架只保存快照")
|
||||
Assert.is_nil(got[1])
|
||||
Assert.eq(got[2], ShelfImport.TOO_LARGE)
|
||||
Assert.is_true(ShelfImport.size() ~= nil)
|
||||
ShelfImport.discard()
|
||||
|
||||
-- 显式刷新触发的全量超限仍应直接打开导入页。
|
||||
oversize_next = true
|
||||
got = nil
|
||||
handle = Client.shelfSyncAsync({}, function(data, err) got = { data, err } end, true, true)
|
||||
Assert.is_true(handle ~= nil)
|
||||
Assert.eq(opened, 2, "手动刷新遇到超大书架打开导入页")
|
||||
Assert.is_nil(got[1])
|
||||
Assert.eq(got[2], ShelfImport.TOO_LARGE)
|
||||
ShelfImport.discard()
|
||||
end
|
||||
@@ -0,0 +1,89 @@
|
||||
--[[-- moonsource_weread.stats:readdata/detail → reading_stats 行映射。 --]]
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local Stats = require("moonsource_weread.stats")
|
||||
|
||||
do
|
||||
local result = Stats.fromWires("ext.weread", {
|
||||
totalReadTime = 7200,
|
||||
}, { {
|
||||
baseTime = 1704067200,
|
||||
readTimes = {
|
||||
["1704067200"] = 9999,
|
||||
["1704240000"] = 8888,
|
||||
},
|
||||
dailyReadTimes = {
|
||||
["1704067200"] = 900,
|
||||
["1704153600"] = 600,
|
||||
},
|
||||
readLongest = {
|
||||
{ book = { bookId = "42" }, readTime = 1500 },
|
||||
},
|
||||
} }, nil, nil, 1800000000)
|
||||
Assert.eq(result.replace.mode, "ranges")
|
||||
Assert.len(result.replace.ranges, 3)
|
||||
local legacy_week
|
||||
for _, range in ipairs(result.replace.ranges) do
|
||||
if range.stable_prefix == "__wr:week:" then legacy_week = range end
|
||||
end
|
||||
Assert.eq(legacy_week.from_ts, 0, "旧周排行行必须整段清掉")
|
||||
Assert.eq(legacy_week.to_ts, 1800000000)
|
||||
local by_id = {}
|
||||
for _, row in ipairs(result.rows) do by_id[row.stable_id] = row end
|
||||
Assert.eq(by_id[Stats.TOTAL_ID].duration, 7200)
|
||||
Assert.eq(by_id["__wr:day:1704067200"].duration, 900,
|
||||
"年度日明细必须优先于月度分桶")
|
||||
Assert.eq(by_id["__wr:day:1704153600"].duration, 600)
|
||||
Assert.is_nil(by_id["__wr:day:1704240000"],
|
||||
"年度月桶不能伪装成某一天的时长")
|
||||
for _, row in ipairs(result.rows) do
|
||||
Assert.is_true(row.record_type ~= "book", "周期排行不再落库")
|
||||
end
|
||||
end
|
||||
|
||||
do
|
||||
local january = 1704067200
|
||||
local february = 1706745600
|
||||
local annual = {
|
||||
readTimes = {
|
||||
[tostring(january)] = 1200,
|
||||
[tostring(february)] = 0,
|
||||
},
|
||||
}
|
||||
local bases = Stats.monthlyBaseTimes(annual)
|
||||
Assert.len(bases, 1)
|
||||
Assert.eq(bases[1], january)
|
||||
|
||||
local result = Stats.fromWires("ext.weread", {
|
||||
totalReadTime = 1200,
|
||||
}, { annual }, { {
|
||||
readTimes = {
|
||||
[tostring(january + 86400)] = 1200,
|
||||
},
|
||||
} })
|
||||
local by_id = {}
|
||||
for _, row in ipairs(result.rows) do by_id[row.stable_id] = row end
|
||||
Assert.eq(by_id["__wr:day:" .. tostring(january + 86400)].duration, 1200)
|
||||
end
|
||||
|
||||
-- changedBooks:只挑云端累计与本地快照不同的书,按更新时间倒序截断到 limit
|
||||
do
|
||||
local changed = Stats.changedBooks({
|
||||
{ bookId = "a", readingTime = 100, updateTime = 1 },
|
||||
{ bookId = "b", readingTime = 200, updateTime = 3 },
|
||||
{ bookId = "c", readingTime = 300, updateTime = 2 },
|
||||
{ bookId = "same", readingTime = 50, updateTime = 9 },
|
||||
{ bookId = "never", updateTime = 8 },
|
||||
}, { same = 50 }, 2)
|
||||
Assert.len(changed, 2)
|
||||
Assert.eq(changed[1].id, "b")
|
||||
Assert.eq(changed[2].id, "c")
|
||||
Assert.len(Stats.changedBooks(nil, {}, 20), 0)
|
||||
-- 云端清零(缺 readingTime)而本地有快照:也算变化,要去清掉旧明细
|
||||
local cleared = Stats.changedBooks({ { bookId = "gone" } }, { gone = 10 }, 20)
|
||||
Assert.eq(cleared[1].reading_time, 0)
|
||||
local rows = Stats.fromWires("ext.weread", {}, {}, nil, {
|
||||
{ id = "gone", reading_time = 0, wire = {} },
|
||||
}, 1000).rows
|
||||
Assert.len(rows, 0, "累计为 0 不写快照,靠 replace.books 清旧行")
|
||||
end
|
||||
@@ -0,0 +1,506 @@
|
||||
--[[--
|
||||
source.wechat notes/annotations/mapper 离线用例
|
||||
|
||||
@module tests.moonsource_weread.sync_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")
|
||||
|
||||
package.loaded["moonsource_weread.mapper"] = nil
|
||||
package.loaded["moonsource_weread.notes"] = nil
|
||||
package.loaded["book.annotations"] = nil
|
||||
-- 本地目录:书 820954 的微信 uid 4 对应本地第 4 章;其余书未缓存。
|
||||
package.loaded["source.toc"] = {
|
||||
index = function(_source_id, stable_id, uid)
|
||||
return stable_id == "820954" and uid == "4" and 4 or nil
|
||||
end,
|
||||
}
|
||||
|
||||
local Mapper = require("moonsource_weread.mapper")
|
||||
local Notes = require("moonsource_weread.notes")
|
||||
local Annotations = require("book.annotations")
|
||||
|
||||
do
|
||||
local anns = Notes.toAnnotations({
|
||||
updated = {
|
||||
{
|
||||
chapterUid = "9",
|
||||
markText = "hello",
|
||||
range = "0-5",
|
||||
createTime = 100,
|
||||
},
|
||||
},
|
||||
}, "9", {
|
||||
reviews = {
|
||||
{ review = { range = "0-5", content = "想法", reviewId = "rv1" } },
|
||||
{ review = { content = "整本书评,无 range" } },
|
||||
},
|
||||
})
|
||||
Assert.eq(#anns, 1)
|
||||
Assert.eq(anns[1].text, "hello")
|
||||
Assert.eq(anns[1].note, "想法")
|
||||
Assert.eq(anns[1].wr_review_id, "rv1")
|
||||
end
|
||||
|
||||
do
|
||||
-- 真实行为:直接发表选中文本想法时,bookmarklist 没有同 range 划线。
|
||||
local anns = Notes.toAnnotations({
|
||||
updated = {
|
||||
{
|
||||
chapterUid = "41", chapterIdx = 6, bookmarkId = "bm1",
|
||||
type = 1, range = "387-390", markText = "许三观", createTime = 1,
|
||||
},
|
||||
},
|
||||
}, "41", {
|
||||
reviews = {
|
||||
{
|
||||
review = {
|
||||
reviewId = "rv1", chapterUid = 41, chapterIdx = 6,
|
||||
range = "425-431", abstract = "拍打着屁股,", content = "冲冲冲",
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
Assert.eq(#anns, 2)
|
||||
Assert.is_true(anns[2].wr_review_only)
|
||||
Assert.eq(anns[2].note, "冲冲冲")
|
||||
|
||||
-- 单条「许三观」重复无法定位;与后面的唯一想法一起按 range 顺序即可锁定章首。
|
||||
local shell = "<html><body><h1>第二章</h1><p>许三观坐着,拍打着屁股,尘土就在许三观身上。</p>"
|
||||
.. "<p>许三观又站起来。</p></body></html>"
|
||||
local path = os.tmpname()
|
||||
local file = assert(io.open(path, "wb")); file:write(shell); file:close()
|
||||
local localized = Notes.localizeAnnotations(nil, anns, path, {
|
||||
{
|
||||
wr_bookmark_id = "bm1", drawer = "lighten", text = "许三观",
|
||||
page = "/html/body/p[2]/text().0",
|
||||
pos0 = "/html/body/p[2]/text().0", pos1 = "/html/body/p[2]/text().3",
|
||||
},
|
||||
})
|
||||
os.remove(path)
|
||||
Assert.eq(localized[1].pos0, "/html/body/p[1]/text().0")
|
||||
Assert.eq(localized[2].note, "冲冲冲")
|
||||
Assert.is_true(type(localized[2].pos0) == "string")
|
||||
end
|
||||
|
||||
do
|
||||
-- 真实 /book/bookmarklist 回包:markText 明文、chapterIdx 只在 chapters 里
|
||||
local anns = Notes.toAnnotations({
|
||||
synckey = 1787872819,
|
||||
updated = {
|
||||
{
|
||||
bookId = "820954",
|
||||
chapterUid = 4,
|
||||
bookmarkId = "820954_4_303-332",
|
||||
type = 1,
|
||||
colorStyle = 2,
|
||||
createTime = 1601272592,
|
||||
range = "303-332",
|
||||
markText = "“当然不是!”几乎是下意识的,牧云开口回应道。",
|
||||
},
|
||||
},
|
||||
chapters = { { title = "课堂解答", chapterUid = 4, chapterIdx = 4 } },
|
||||
}, nil, nil, "ext.weread", "820954")
|
||||
Assert.eq(#anns, 1)
|
||||
Assert.eq(anns[1].chapter_idx, 4)
|
||||
Assert.eq(anns[1].wr_range, "303-332")
|
||||
Assert.eq(anns[1].wr_bookmark_id, "820954_4_303-332")
|
||||
Assert.eq(anns[1].text, "“当然不是!”几乎是下意识的,牧云开口回应道。")
|
||||
Assert.is_nil(anns[1].note)
|
||||
Assert.eq(anns[1].color, "green")
|
||||
end
|
||||
|
||||
do
|
||||
local wire = {
|
||||
updated = {
|
||||
{ chapterUid = "9", markText = "hello", range = "0-5", createTime = 100, type = 1 },
|
||||
{ chapterUid = "9", markText = "skip", range = "1-2", createTime = 101, type = 0 },
|
||||
},
|
||||
items = {
|
||||
{ chapterUid = "9", markText = "popular", range = "2-5", userVid = "999" },
|
||||
},
|
||||
}
|
||||
Assert.eq(#Notes.toAnnotations(wire, "9"), 1)
|
||||
Assert.eq(#Notes.toAnnotations({ items = wire.items }, "9"), 0)
|
||||
-- 本地目录映射不到:原始 chapterIdx / wire.chapters 都不是本地章号,留空。
|
||||
Assert.is_nil(Notes.toAnnotations({
|
||||
updated = {
|
||||
{ chapterUid = "8", chapterIdx = 8, markText = "x", range = "0-1", type = 1, createTime = 1 },
|
||||
},
|
||||
}, nil, nil, "ext.weread", "1")[1].chapter_idx)
|
||||
Assert.is_nil(Notes.toAnnotations({
|
||||
chapters = { { chapterUid = "9", chapterIdx = 9 } },
|
||||
updated = {
|
||||
{ chapterUid = "9", markText = "x", range = "0-1", type = 1, createTime = 1 },
|
||||
},
|
||||
}, nil, nil, "ext.weread", "1")[1].chapter_idx)
|
||||
end
|
||||
|
||||
--- 单条划线走 locateBatch,返回 pos0, pos1;定位不到返回 nil。
|
||||
local function locate(html, text, range)
|
||||
local item = { text = text, wr_range = range }
|
||||
local hit = Annotations.locateBatch(html, { item })[item]
|
||||
if hit then return hit.pos0, hit.pos1 end
|
||||
end
|
||||
|
||||
do
|
||||
-- 章节壳:<h1> 不占 p 编号;段首缩进折叠为 1 空格,故 p[2] 从 offset 1 起。
|
||||
-- 期望值取自 KOReader 自己写出的 xpointer(pos1 是半开上界)。
|
||||
local shell = table.concat({
|
||||
"<html><head><title>指婚</title></head><body><h1>指婚</h1>",
|
||||
"<p>莫问毕竟是六星炼丹师。</p>\n",
|
||||
"<p> 要是牧钱反应过来。</p>\n",
|
||||
"<p>重复段落文本。</p>\n",
|
||||
"<p>重复段落文本。</p>",
|
||||
"</body></html>",
|
||||
})
|
||||
|
||||
local pos0, pos1 = locate(shell, "莫问毕竟是六星炼丹师。")
|
||||
Assert.eq(pos0, "/html/body/p[1]/text().0")
|
||||
Assert.eq(pos1, "/html/body/p[1]/text().11")
|
||||
|
||||
pos0, pos1 = locate(shell, "要是牧钱反应过来。")
|
||||
Assert.eq(pos0, "/html/body/p[2]/text().1")
|
||||
Assert.eq(pos1, "/html/body/p[2]/text().10")
|
||||
|
||||
-- markText 带换行/多空格时按 crengine 规则折叠后再比
|
||||
Assert.eq(locate(shell, " 莫问毕竟是六星炼丹师。\n"), "/html/body/p[1]/text().0")
|
||||
|
||||
-- wire range 与本地壳不是同一坐标系;重复文本不能靠 range 猜,宁可不画错位置。
|
||||
Assert.is_nil(locate(shell, "重复段落文本。"))
|
||||
Assert.is_nil(locate(shell, "重复段落文本。", "34-41"))
|
||||
|
||||
Assert.is_nil(locate(shell, "正文里不存在的句子"))
|
||||
Assert.is_nil(locate(shell, ""))
|
||||
|
||||
-- 已同步条目即使文本重复,也按 bookmarkId 复用原生坐标并接受远端笔记更新。
|
||||
local path = os.tmpname()
|
||||
local file = assert(io.open(path, "wb")); file:write(shell); file:close()
|
||||
local localized = Notes.localizeAnnotations(nil, {
|
||||
{ drawer = "lighten", text = "重复段落文本。", note = "远端新想法", wr_bookmark_id = "bm-2" },
|
||||
}, path, {
|
||||
{
|
||||
drawer = "lighten", text = "重复段落文本。", note = "旧想法", wr_bookmark_id = "bm-2",
|
||||
page = "/html/body/p[4]/text().0",
|
||||
pos0 = "/html/body/p[4]/text().0", pos1 = "/html/body/p[4]/text().7",
|
||||
},
|
||||
})
|
||||
os.remove(path)
|
||||
Assert.eq(localized[1].pos0, "/html/body/p[4]/text().0")
|
||||
Assert.eq(localized[1].note, "远端新想法")
|
||||
end
|
||||
|
||||
do
|
||||
-- 本地图片 URL、章节壳与 wire HTML 不同,range 仍必须落在 wire rune 坐标。
|
||||
local wire = "\239\187\191<p>A&B</p>"
|
||||
.. '<p><img src="https://remote/a.jpg"/>重复</p><p>重复</p>'
|
||||
local shell = "<html><body><h1>标题</h1><p>A&B</p>"
|
||||
.. '<p><img src="/tmp/a.jpg"/>重复</p><p>重复</p></body></html>'
|
||||
local mapping, flow = Annotations.rangeMapping(wire), Annotations.flow(shell)
|
||||
local range, err = Annotations.toWireRange(
|
||||
mapping, flow, "重复", "/html/body/p[3]/text().0", "/html/body/p[3]/text().2"
|
||||
)
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(range, "59-61")
|
||||
local first = Annotations.toWireRange(
|
||||
mapping, flow, "A&B", "/html/body/p[1]/text().0", "/html/body/p[1]/text().3"
|
||||
)
|
||||
Assert.eq(first, "3-10")
|
||||
local ambiguous, ambiguous_err = Annotations.toWireRange(mapping, flow, "重复")
|
||||
Assert.is_nil(ambiguous)
|
||||
Assert.eq(ambiguous_err, "ambiguous local highlight")
|
||||
Assert.eq(Annotations.wireMapping("<p>x</p><style>bad</style><p>y</p>").text, "xy")
|
||||
end
|
||||
|
||||
do
|
||||
-- range 基准是完整解码 xhtml:head 与 xml 声明计入偏移,但其中文字不参与匹配。
|
||||
local wire = '<?xml version="1.0"?><html><head><title>正文</title></head><body><p>正文</p></body></html>'
|
||||
local shell = "<html><body><p>正文</p></body></html>"
|
||||
local prefix = wire:sub(1, wire:find("<p>正文", 1, true) + 2)
|
||||
local start = select(2, prefix:gsub("[^\128-\191]", ""))
|
||||
local range = Annotations.toWireRange(Annotations.rangeMapping(wire, "html"),
|
||||
Annotations.flow(shell), "正文", "/html/body/p/text().0", "/html/body/p/text().2")
|
||||
Assert.eq(range, string.format("%d-%d", start, start + 2))
|
||||
end
|
||||
|
||||
do
|
||||
-- TXT:range 对纯文本逐 rune 计(BOM 不计,"<" 不是标签),与 weread 的 Source.plain 一致。
|
||||
local plain = "\239\187\191甲<&乙\n 丙丁"
|
||||
local shell = "<html><body>" .. require("utils.text").textToBody(plain:sub(4)) .. "</body></html>"
|
||||
local flow = Annotations.flow(shell)
|
||||
Assert.eq(Annotations.toWireRange(Annotations.rangeMapping(plain, "txt"), flow,
|
||||
"<&", "/html/body/p[1]/text().1", "/html/body/p[1]/text().3"), "1-3")
|
||||
Assert.eq(Annotations.toWireRange(Annotations.rangeMapping(plain, "txt"), flow,
|
||||
"丙丁", "/html/body/p[2]/text().0", "/html/body/p[2]/text().2"), "7-9")
|
||||
end
|
||||
|
||||
do
|
||||
-- KOReader 跨段选区在段间带换行与缩进;微信正文段间也有缩进空白。都必须能定位。
|
||||
local wire = "<body><p> 第一段结尾</p>\n<p> 第二段开头</p></body>"
|
||||
local shell = "<html><body><p> 第一段结尾</p><p> 第二段开头</p></body></html>"
|
||||
local range, err = Annotations.toWireRange(Annotations.rangeMapping(wire), Annotations.flow(shell),
|
||||
"结尾\n 第二", "/html/body/p[1]/text().5", "/html/body/p[2]/text().4")
|
||||
Assert.is_nil(err)
|
||||
local head = wire:find("结尾", 1, true)
|
||||
local runes_before = select(2, wire:sub(1, head - 1):gsub("[^\128-\191]", ""))
|
||||
Assert.eq(range:match("^(%d+)"), tostring(runes_before))
|
||||
|
||||
-- 起点 xpointer 对不上(旧版按扁平 p[N] 写出的坐标)时靠唯一文本定位,不拿终点去比。
|
||||
Assert.eq(Annotations.toWireRange(Annotations.rangeMapping(wire), Annotations.flow(shell),
|
||||
"第二段", "/html/body/div/p[9]/span/text().0", "/html/body/div/p[9]/text().3") ~= nil, true)
|
||||
end
|
||||
|
||||
do
|
||||
-- xpointer 与 crengine 写法逐字一致(期望值由 crengine getTextFromXPointers 反查确认):
|
||||
-- 同名兄弟唯一时不带 [k],拼接的多份文档是 html[k],内联元素把文本拆成 text()[k],脚注正文不参与匹配。
|
||||
local shell = table.concat({
|
||||
'<?xml version="1.0" encoding="utf-8"?><html xmlns:epub="http://www.idpf.org/2007/ops">',
|
||||
'<head><title>a</title></head><body>',
|
||||
'<div class="c"><p>第一段<a epub:type="noteref" href="#n1"><img src="x.png"/></a>注后文字</p>\n<p>第二段</p></div>',
|
||||
'<aside epub:type="footnote" id="n1"><p>脚注正文</p></aside>',
|
||||
'</body></html>',
|
||||
'<?xml version="1.0" encoding="utf-8"?><html><head><title>b</title></head><body>',
|
||||
'<p>次文档首段</p><p>次文档 <b>粗体</b> 尾巴</p>',
|
||||
'</body></html>',
|
||||
})
|
||||
local cases = {
|
||||
{ "注后文字", "/html[1]/body/div/p[1]/text()[2].0", "/html[1]/body/div/p[1]/text()[2].4" },
|
||||
{ "第二段", "/html[1]/body/div/p[2]/text().0", "/html[1]/body/div/p[2]/text().3" },
|
||||
{ "次文档首段", "/html[2]/body/p[1]/text().0", "/html[2]/body/p[1]/text().5" },
|
||||
{ "尾巴", "/html[2]/body/p[2]/text()[2].1", "/html[2]/body/p[2]/text()[2].3" },
|
||||
{ "粗体", "/html[2]/body/p[2]/b/text().0", "/html[2]/body/p[2]/b/text().2" },
|
||||
}
|
||||
for _idx, case in ipairs(cases) do
|
||||
local pos0, pos1 = locate(shell, case[1])
|
||||
Assert.eq(pos0, case[2])
|
||||
Assert.eq(pos1, case[3])
|
||||
end
|
||||
Assert.is_nil(locate(shell, "脚注正文"))
|
||||
Assert.eq(locate("<html><body><p>正文</p></body></html>", "正文"), "/html/body/p/text().0")
|
||||
end
|
||||
|
||||
do
|
||||
-- 跨段划线:微信 markText 直接跨 <p> 边界,段首缩进与段间换行都不在其中
|
||||
local shell = table.concat({
|
||||
"<html><body><h1>课堂解答</h1>",
|
||||
'<p> “当然不是!”</p>\n',
|
||||
"<p> 几乎是下意识的,牧云开口回应道。</p>",
|
||||
"</body></html>",
|
||||
})
|
||||
local pos0, pos1 = locate(shell, "“当然不是!”几乎是下意识的,牧云开口回应道。")
|
||||
Assert.eq(pos0, "/html/body/p[1]/text().1")
|
||||
Assert.eq(pos1, "/html/body/p[2]/text().17")
|
||||
|
||||
-- 单段仍按原样定位,不受跨段流影响
|
||||
Assert.eq(locate(shell, "牧云开口回应道。"), "/html/body/p[2]/text().9")
|
||||
end
|
||||
|
||||
do
|
||||
-- 定位失败的远端划线不能进 doc_settings:drawSavedHighlight 会解 pos0 并抛错
|
||||
local localized = Notes.localizeAnnotations(nil, {
|
||||
{ drawer = "lighten", text = "找不到的原文", wr_range = "0-6" },
|
||||
}, nil)
|
||||
Assert.eq(#localized, 1)
|
||||
Assert.is_nil(localized[1].pos0)
|
||||
end
|
||||
|
||||
do
|
||||
-- range 是原始 HTML 索引(含标签),不能按可见文本切片。旧实现先用 textAtRange
|
||||
-- 把 "0-4" 当成可见文本偏移切成 "AAAA",导致划线定位被错误覆盖。
|
||||
local html = '<html><head><title>t</title></head><body><h1>t</h1>'
|
||||
.. '<p><span class="x">AAAA</span>作者:罗贯<span>BBBB</span></p>'
|
||||
.. '</body></html>'
|
||||
local path = os.tmpname()
|
||||
local f = assert(io.open(path, "wb")); f:write(html); f:close()
|
||||
local localized = Notes.localizeAnnotations(nil, {
|
||||
{ drawer = "lighten", text = "作者:罗贯", wr_range = "0-4" },
|
||||
}, path)
|
||||
os.remove(path)
|
||||
Assert.eq(#localized, 1)
|
||||
Assert.eq(localized[1].pos0, "/html/body/p/text().0")
|
||||
Assert.eq(localized[1].pos1, "/html/body/p/text().5")
|
||||
end
|
||||
|
||||
do
|
||||
Assert.eq(Notes.decodeMarkText("5L2c6ICF77ya572X6LSv"), "作者:罗贯")
|
||||
Assert.eq(require("utils.text").base64Encode("作者:罗贯"), "5L2c6ICF77ya572X6LSv")
|
||||
local body = Notes.toBookmarkBody("1", 9, 2, 395275575, {
|
||||
text = "hello",
|
||||
drawer = "lighten",
|
||||
wr_range = "0-5",
|
||||
})
|
||||
Assert.eq(body.bookId, "1")
|
||||
Assert.eq(body.chapterUid, 9)
|
||||
Assert.eq(body.bookVersion, 395275575)
|
||||
Assert.eq(body.range, "0-5")
|
||||
Assert.eq(body.markText, "hello")
|
||||
Assert.eq(#Notes.pushCandidates({
|
||||
{ drawer = "lighten", text = "a" },
|
||||
{ drawer = "lighten", text = "note", note = "想法" },
|
||||
{ drawer = "lighten", text = "b", wr_bookmark_id = 1 },
|
||||
}), 1)
|
||||
Assert.eq(#Notes.notePushCandidates({
|
||||
{ note = "想法", wr_range = "0-1", wr_bookmark_id = "bm1" },
|
||||
{ note = "独立想法", wr_range = "2-3", wr_review_only = true },
|
||||
{ note = "未修改", wr_range = "3-4", wr_review_id = "rv1" },
|
||||
{ note = "已修改", wr_range = "4-5", wr_review_id = "rv2", wr_update_review = true },
|
||||
{ note = "无划线", wr_range = "0-1" },
|
||||
}), 3)
|
||||
local review_body = Notes.toReviewBody("1", 9, {
|
||||
note = "想法",
|
||||
text = "原文",
|
||||
wr_range = "0-5",
|
||||
})
|
||||
Assert.eq(review_body.bookId, "1")
|
||||
Assert.eq(review_body.content, "想法")
|
||||
Assert.eq(review_body.abstract, "原文")
|
||||
Assert.eq(review_body.range, "0-5")
|
||||
Assert.eq(review_body.chapterUid, 9)
|
||||
local pending = {
|
||||
text = "原文", note = "想法", wr_range = "0-5", wr_review_only = true,
|
||||
}
|
||||
local confirmed = Notes.reconcileReviews({ pending }, {
|
||||
reviews = { { review = {
|
||||
reviewId = "rv-recovered", range = "9-14", abstract = "原文", content = "想法",
|
||||
} } },
|
||||
})
|
||||
Assert.eq(pending.wr_review_id, "rv-recovered")
|
||||
Assert.is_true(confirmed[pending])
|
||||
local current = Notes.prepareLocalAnnotations({
|
||||
{
|
||||
datetime = "old", page = "/body/a", drawer = "lighten",
|
||||
note = "旧笔记", wr_bookmark_id = "bm1", wr_review_id = "rv1",
|
||||
},
|
||||
{
|
||||
datetime = "old", page = "/body/b", drawer = "lighten",
|
||||
wr_bookmark_id = "bm2",
|
||||
},
|
||||
}, {
|
||||
{
|
||||
datetime = "new", page = "/body/a", drawer = "lighten",
|
||||
wr_bookmark_id = "bm1",
|
||||
},
|
||||
})
|
||||
Assert.is_true(current[1].wr_delete_review)
|
||||
Assert.is_true(current[2].wr_deleted)
|
||||
Assert.eq(current[2].wr_bookmark_id, "bm2")
|
||||
|
||||
local remote_note = { {
|
||||
page = "/body/n", datetime = "r", text = "原文", note = "想法",
|
||||
wr_range = "100-102", wr_review_id = "rv1",
|
||||
} }
|
||||
local local_note = { {
|
||||
page = "/body/n", datetime = "l", text = "原文", note = "想法",
|
||||
wr_range = "300-302",
|
||||
} }
|
||||
Assert.len(Notes.mergeAnnotations(remote_note, local_note, false, true), 1)
|
||||
|
||||
local twins = {
|
||||
{ page = "/body/a", text = "同一处", wr_range = "10-20", wr_bookmark_id = "b1" },
|
||||
{ page = "/body/a", text = "同一处", wr_range = "10-20", wr_bookmark_id = "b2" },
|
||||
}
|
||||
Assert.len(Notes.mergeAnnotations(twins, { { page = "/body/a", text = "同一处", wr_range = "10-20", wr_bookmark_id = "b2" } }, false, true), 1)
|
||||
-- 上传后确认没回来的本地划线(无 id / range)与远端同坐标:只留一条
|
||||
local unconfirmed = { { page = "/body/a", pos0 = "/p.0", pos1 = "/p.9", text = "同一处", drawer = "lighten" } }
|
||||
local pulled = { { page = "/body/a", pos0 = "/p.0", pos1 = "/p.9", text = "同一处", wr_range = "10-20", wr_bookmark_id = "b1" } }
|
||||
local merged = Notes.mergeAnnotations(pulled, unconfirmed, false, true)
|
||||
Assert.len(merged, 1)
|
||||
Assert.eq(merged[1].wr_bookmark_id, "b1")
|
||||
local version = Mapper.bookVersion({ book = { version = 123 } })
|
||||
Assert.eq(version, 123)
|
||||
end
|
||||
|
||||
do -- 同文、同备注或同范围不能覆盖不同位置的真实划线。
|
||||
local first = {
|
||||
page = "/p[1]", pos0 = "/p[1].0", pos1 = "/p[1].4",
|
||||
text = "重复原文", note = "想法一", drawer = "lighten",
|
||||
}
|
||||
local second = {
|
||||
page = "/p[8]", pos0 = "/p[8].0", pos1 = "/p[8].4",
|
||||
text = first.text, note = "想法二", drawer = "lighten",
|
||||
}
|
||||
local merged, dropped, deduped = Notes.mergeAnnotations({}, { first, second }, false, false)
|
||||
Assert.len(merged, 2)
|
||||
Assert.eq(dropped, 0)
|
||||
Assert.eq(deduped, 0)
|
||||
Assert.eq(merged[2].note, "想法二")
|
||||
second.note = first.note
|
||||
Assert.len(Notes.mergeAnnotations({ first }, { second }, false, false), 2)
|
||||
first.wr_range, second.wr_range = "0-4", "0-4"
|
||||
Assert.len(Notes.mergeAnnotations({ first, second }, {}, false, false), 2)
|
||||
Assert.len(Notes.mergeAnnotations({ first, second }, { first, second }, false, false), 2)
|
||||
end
|
||||
|
||||
do -- 想法列表没拿到:本地已有的想法接回拉下来的划线,review-only 条目保留
|
||||
local anns = {
|
||||
{ text = "a", wr_bookmark_id = "b1" },
|
||||
{ text = "c", wr_bookmark_id = "b2" },
|
||||
}
|
||||
local out = Notes.keepLocalReviews(anns, {
|
||||
{ text = "a", note = "想法A", wr_bookmark_id = "b1", wr_review_id = "r1" },
|
||||
{ text = "x", note = "只有想法", wr_review_id = "r2", wr_review_only = true },
|
||||
{ text = "gone", note = "无关", wr_review_id = "r3" },
|
||||
})
|
||||
Assert.eq(out[1].note, "想法A")
|
||||
Assert.eq(out[1].wr_review_id, "r1")
|
||||
Assert.is_nil(out[2].note)
|
||||
Assert.eq(#out, 3)
|
||||
Assert.eq(out[3].wr_review_id, "r2")
|
||||
end
|
||||
|
||||
do -- 无 text/range 的位置记录:合并时按内容键去重,不能在开书时再翻倍
|
||||
local marker = {
|
||||
datetime = "2026-11-03 14:54:54",
|
||||
page = "/html/body/div[2]/p[431]/text()[1].37",
|
||||
pageno = 45,
|
||||
total_pages = 448,
|
||||
}
|
||||
local highlight = {
|
||||
datetime = "2026-11-04 10:00:00",
|
||||
page = "/html/body/div[2]/p[2]/text()[1].0",
|
||||
pos0 = "/html/body/div[2]/p[2]/text()[1].0",
|
||||
pos1 = "/html/body/div[2]/p[2]/text()[1].6",
|
||||
drawer = "lighten",
|
||||
text = "合法高亮",
|
||||
wr_range = "10-20",
|
||||
wr_bookmark_id = "bm-keep",
|
||||
}
|
||||
local review = {
|
||||
datetime = "2026-11-04 10:01:00",
|
||||
page = "/html/body/div[2]/p[3]/text()[1].0",
|
||||
pos0 = "/html/body/div[2]/p[3]/text()[1].0",
|
||||
pos1 = "/html/body/div[2]/p[3]/text()[1].4",
|
||||
drawer = "lighten",
|
||||
text = "带想法的原文",
|
||||
note = "一条想法",
|
||||
wr_range = "30-40",
|
||||
wr_review_id = "rv-keep",
|
||||
wr_review_only = true,
|
||||
}
|
||||
local bloated = {}
|
||||
for _i = 1, 4096 do bloated[#bloated + 1] = marker end
|
||||
bloated[#bloated + 1] = highlight
|
||||
bloated[#bloated + 1] = review
|
||||
|
||||
local cleaned = Notes.cleanAnnotations(bloated, 448)
|
||||
Assert.len(cleaned, 3, "清洗后应只剩 1 条位置记录 + 高亮 + 想法")
|
||||
local texts = {}
|
||||
for _idx, item in ipairs(cleaned) do texts[item.text or ""] = true end
|
||||
Assert.is_true(texts["合法高亮"])
|
||||
Assert.is_true(texts["带想法的原文"])
|
||||
|
||||
local merged, dropped, deduped = Notes.mergeAnnotations(bloated, bloated, false, false)
|
||||
Assert.eq(dropped, 0)
|
||||
Assert.len(merged, 3, "远端和本地各有 4096 份拷贝时合并不得膨胀")
|
||||
Assert.is_true(deduped >= 4096)
|
||||
local again = Notes.mergeAnnotations(merged, merged, false, false)
|
||||
Assert.len(again, 3, "再合并一次仍是 3 条")
|
||||
local kept = {}
|
||||
for _idx, item in ipairs(merged) do
|
||||
if item.wr_bookmark_id then kept.highlight = item end
|
||||
if item.wr_review_id then kept.review = item end
|
||||
end
|
||||
Assert.eq(kept.highlight.wr_bookmark_id, "bm-keep")
|
||||
Assert.eq(kept.review.wr_review_id, "rv-keep")
|
||||
end
|
||||
@@ -0,0 +1,130 @@
|
||||
--[[--
|
||||
moonsource_weread.toc:目录缓存读取与按 idx/uid 定位。 --]]
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local Config = require("support.config")
|
||||
local db_path = Config.dir() .. "/wechat_toc_spec.sqlite3"
|
||||
for _idx, suffix in ipairs({ "", "-wal", "-shm" }) do os.remove(db_path .. suffix) end
|
||||
package.preload["utils.paths"] = function() return { dbPath = function() return db_path end } end
|
||||
|
||||
local store = {}
|
||||
local upserted = {}
|
||||
local reads = 0
|
||||
local now = 1000
|
||||
local original_time = os.time
|
||||
os.time = function() return now end
|
||||
local writes = true
|
||||
package.preload["book.books_db"] = function()
|
||||
return {
|
||||
getToc = function(_source_id, stable_id, max_age)
|
||||
reads = reads + 1
|
||||
local row = store[stable_id]
|
||||
if not row or (max_age and now - row.at >= max_age) then return nil end
|
||||
return row.payload, row.at
|
||||
end,
|
||||
setToc = function(_source_id, stable_id, payload)
|
||||
if not writes then return false end
|
||||
upserted[stable_id] = payload
|
||||
store[stable_id] = { payload = payload, at = now }
|
||||
return true
|
||||
end,
|
||||
}
|
||||
end
|
||||
package.preload["json"] = function()
|
||||
return {
|
||||
decode = require("support.json_stub").decode,
|
||||
encode = function(value) return "encoded:" .. tostring(#value) end,
|
||||
}
|
||||
end
|
||||
|
||||
package.loaded["moonsource_weread.toc"] = nil
|
||||
local Toc = require("moonsource_weread.toc")
|
||||
local readToc = require("book.toc_db").read
|
||||
require("book.toc_db").read = function(...)
|
||||
reads = reads + 1
|
||||
return readToc(...)
|
||||
end
|
||||
|
||||
do
|
||||
Assert.is_nil(Toc.read("ext.weread", "missing"))
|
||||
Assert.is_nil(Toc.read("ext.weread", "broken"))
|
||||
end
|
||||
|
||||
do
|
||||
-- payload 是目录数组(与 Mapper.chapters 输出一致),按数组索引定位。
|
||||
store["b2"] = { payload = [[
|
||||
[{"idx":1,"source_idx":2,"uid":"u1","toc_version":3},{"idx":2,"source_idx":4,"uid":"u2"}]
|
||||
]], at = now }
|
||||
Assert.eq(Toc.uid("ext.weread", "b2", 1), "u1")
|
||||
Assert.eq(Toc.uid("ext.weread", "b2", 2), "u2")
|
||||
Assert.is_nil(Toc.uid("ext.weread", "b2", 99))
|
||||
Assert.eq(Toc.index("ext.weread", "b2", "u2"), 2)
|
||||
Assert.is_nil(Toc.index("ext.weread", "b2", "u9"))
|
||||
Assert.eq(Toc.sourceIndex("ext.weread", "b2", 1), 2)
|
||||
Assert.eq(Toc.sourceIndex("ext.weread", "b2", 2), 4)
|
||||
Assert.is_nil(Toc.sourceIndex("ext.weread", "b2", 99))
|
||||
end
|
||||
|
||||
do
|
||||
store["old"] = { payload = [[{"idx":1,"source_idx":2,"uid":"old"}]], at = now }
|
||||
local old = Toc.read("ext.weread", "old")
|
||||
Assert.not_nil(old, "旧目录仍须支持离线读取")
|
||||
Assert.is_false(Toc.isCurrent(old))
|
||||
end
|
||||
|
||||
do
|
||||
-- 解码结果进内存:库里的行没了也照样命中,翻页/按章补报不再反复 decode 整份目录。
|
||||
local before = reads
|
||||
store["b2"] = nil
|
||||
require("utils.db").removeIdentity("toc_entries", "ext.weread", "b2")
|
||||
require("utils.db").removeIdentity("toc_snapshots", "ext.weread", "b2")
|
||||
Assert.eq(Toc.uid("ext.weread", "b2", 1), "u1")
|
||||
Assert.eq(Toc.index("ext.weread", "b2", "u2"), 2)
|
||||
Assert.eq(reads, before, "命中内存缓存时不得再查库")
|
||||
|
||||
-- clear 后回落到库(此时库里已无数据)
|
||||
Toc.clear()
|
||||
Assert.is_nil(Toc.read("ext.weread", "b2"))
|
||||
Assert.is_true(reads > before)
|
||||
end
|
||||
|
||||
do
|
||||
-- put 落库并直接接管缓存,无需再 decode 一遍
|
||||
local list = { { idx = 1, uid = "p1" }, { idx = 2, uid = "p2" }, { idx = 3, uid = "p3" } }
|
||||
Toc.put("ext.weread", "b3", list)
|
||||
Assert.is_nil(upserted["b3"], "不再写旧 JSON 列")
|
||||
local before = reads
|
||||
Assert.eq(Toc.uid("ext.weread", "b3", 3), "p3")
|
||||
Assert.eq(Toc.index("ext.weread", "b3", "p2"), 2)
|
||||
Assert.eq(reads, before)
|
||||
|
||||
-- 章内进度 + 章节序号 → 全书 fraction
|
||||
Assert.eq(Toc.wholeFraction("ext.weread", "b3", 1, 0), 0)
|
||||
Assert.eq(Toc.wholeFraction("ext.weread", "b3", 2, 0.5), 0.5)
|
||||
Assert.eq(Toc.wholeFraction("ext.weread", "b3", 3, 1), 1)
|
||||
Assert.is_nil(Toc.wholeFraction("ext.weread", "unknown", 1, 0))
|
||||
|
||||
local cached_reads = reads
|
||||
Assert.eq(Toc.uid("ext.weread", "b3", 1), "p1")
|
||||
Assert.eq(reads, cached_reads)
|
||||
Toc.clear()
|
||||
Toc.read("ext.weread", "b3")
|
||||
Assert.is_true(reads > cached_reads, "clear 后必须回库")
|
||||
end
|
||||
|
||||
do
|
||||
local list = { { idx = 1, uid = "failed" } }
|
||||
writes = false
|
||||
Assert.is_false(Toc.put("ext.weread", "failed", list))
|
||||
Assert.is_nil(Toc.read("ext.weread", "failed"))
|
||||
writes = true
|
||||
-- 清内存后直接从逐章表恢复。
|
||||
Toc.clear()
|
||||
Assert.eq(Toc.read("ext.weread", "b3")[1].uid, "p1")
|
||||
now = now + 6 * 60 * 60
|
||||
Assert.eq(Toc.read("ext.weread", "b3")[1].uid, "p1", "目录不做时间保鲜,旧缓存仍可用")
|
||||
end
|
||||
|
||||
os.time = original_time
|
||||
require("utils.db").close()
|
||||
for _idx, suffix in ipairs({ "", "-wal", "-shm" }) do os.remove(db_path .. suffix) end
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user