✨ 初始提交:月读第三方书源插件集合
每个书源一个独立插件目录,含微信读书公众号订阅、书架导入等完整功能。 Co-authored-by: Copilot <[email protected]>
This commit is contained in:
commit
818a3d9067
22 files changed
+4165
No files matched your search
@@ -0,0 +1,483 @@
|
||||
--[[--
|
||||
京东扫码登录状态机离线用例。
|
||||
|
||||
@module tests.moonsource_jdread.auth_spec
|
||||
--]]
|
||||
---@diagnostic disable: undefined-field
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local Config = require("support.config")
|
||||
local Stubs = require("support.stubs")
|
||||
local JSONStub = require("support.json_stub")
|
||||
require("source.logout").replaceLibrary = function(id, commit)
|
||||
Assert.eq(id, "ext.jdread")
|
||||
commit()
|
||||
return true
|
||||
end
|
||||
|
||||
package.preload["json"] = function()
|
||||
return { decode = JSONStub.decode, encode = JSONStub.encode }
|
||||
end
|
||||
|
||||
---@type table<string, any>
|
||||
local cfg = {}
|
||||
package.preload["utils.settings"] = function()
|
||||
return {
|
||||
getSource = function() return cfg end,
|
||||
saveSource = function(_, value) cfg = value end,
|
||||
}
|
||||
end
|
||||
package.preload["utils.device_id"] = function()
|
||||
return { ensure = function() return "test-device" end }
|
||||
end
|
||||
|
||||
package.preload["utils.paths"] = function()
|
||||
return {
|
||||
ensureLayout = function() end,
|
||||
imageDir = function() return Config.dir() end,
|
||||
}
|
||||
end
|
||||
|
||||
local calls = 0
|
||||
local ticket_reply = '{"returnCode":0,"url":"https://e.m.jd.com/"}'
|
||||
local session_reply = '{"result_code":0,"data":{"book_ids":[]}}'
|
||||
local session_err, session_held, session_cb
|
||||
local session_cancels = 0
|
||||
-- 配对模式:每张码发不同 token,check 像线上一样校验 token 与 Cookie 里的 wlfstk_smdl 一致。
|
||||
local paired, shows = false, 0
|
||||
-- hop:校验这一跳不带 Set-Cookie,会话在 url / Location 上。
|
||||
local hop_mode = nil
|
||||
local hop_urls = {}
|
||||
local request_urls = {}
|
||||
package.preload["http.request"] = function()
|
||||
local Request = {}
|
||||
function Request.randomUA() return "test-agent" end
|
||||
function Request.header(res, name)
|
||||
return res and res.headers and (res.headers[name] or res.headers[name:lower()])
|
||||
end
|
||||
function Request.get(url, opts, cb)
|
||||
calls = calls + 1
|
||||
request_urls[#request_urls + 1] = url
|
||||
local res = { code = 200, headers = {} }
|
||||
if url:find("/jdread/api/bookshelf/sort", 1, true) then
|
||||
if session_held then
|
||||
session_cb = cb
|
||||
else
|
||||
cb(session_reply, session_err, res)
|
||||
end
|
||||
return { cancel = function() session_cancels = session_cancels + 1 end }
|
||||
elseif url:find("/show?", 1, true) then
|
||||
shows = shows + 1
|
||||
local token = paired and ("token-" .. shows) or "token"
|
||||
res.headers["Set-Cookie"] = {
|
||||
"QRCodeKey=qr-" .. token .. "; HttpOnly",
|
||||
"wlfstk_smdl=" .. token .. "; Domain=.jd.com",
|
||||
}
|
||||
cb("\137PNG\r\n\26\nstub", nil, res)
|
||||
elseif url:find("/check?", 1, true) and paired then
|
||||
local callback = url:match("[?&]callback=([^&]+)")
|
||||
local token = url:match("[?&]token=([^&]+)")
|
||||
local cookie = opts.headers.Cookie or ""
|
||||
local data = cookie:find("wlfstk_smdl=" .. token, 1, true)
|
||||
and ('{"code":200,"ticket":"ticket-' .. token .. '"}')
|
||||
or '{"code":257,"msg":"参数异常,请退出重试"}'
|
||||
cb(callback .. "(" .. data .. ")", nil, res)
|
||||
elseif url:find("/check?", 1, true) then
|
||||
local callback = url:match("[?&]callback=([^&]+)")
|
||||
local code = calls == 2 and 201 or (calls == 3 and 202 or 200)
|
||||
local data = code == 200 and '{"code":200,"ticket":"ticket"}'
|
||||
or ('{"code":' .. code .. ',"msg":"waiting"}')
|
||||
cb(callback .. "(" .. data .. ")", nil, res)
|
||||
elseif url:find("qrCodeTicketValidation", 1, true) then
|
||||
if hop_mode == "merged" then
|
||||
-- 多条 Set-Cookie 被合并成一行,expires 里自带逗号。
|
||||
res.headers["Set-Cookie"] = "thor=session; expires=Wed, 21 Oct 2026 07:28:00 GMT; Domain=.jd.com, "
|
||||
.. "pin=tester; Path=/, pt_key=key; expires=Thu, 22 Oct 2026 07:28:00 GMT"
|
||||
elseif hop_mode == "junk" or hop_mode == "relay" then
|
||||
res.headers["Set-Cookie"] = { "__jda=track; Domain=.jd.com" }
|
||||
elseif not hop_mode then
|
||||
res.headers["Set-Cookie"] = {
|
||||
"thor=session; Domain=.jd.com",
|
||||
"pin=tester; Domain=.jd.com",
|
||||
}
|
||||
end
|
||||
cb(ticket_reply, nil, res)
|
||||
elseif hop_mode == "certified" then
|
||||
res.code = 302
|
||||
res.headers.Location = "//aq.jd.com/certified/index?test=fixture"
|
||||
res.headers["Set-Cookie"] = { "thor=candidate; Domain=.jd.com" }
|
||||
cb(nil, "HTTP 302", res)
|
||||
elseif hop_mode == "failed-hop" then
|
||||
cb(nil, "network unavailable")
|
||||
elseif hop_mode == "loop" then
|
||||
res.code = 302
|
||||
res.headers.Location = url
|
||||
cb(nil, "HTTP 302", res)
|
||||
elseif hop_mode == "junk" then
|
||||
hop_urls[#hop_urls + 1] = url
|
||||
res.headers["Set-Cookie"] = { "__jdb=track; Domain=.jd.com" }
|
||||
cb("<html></html>", nil, res)
|
||||
elseif hop_mode == "relay" and url == "http://passport.jd.com/relay/loginRelay" then
|
||||
res.code = 302
|
||||
res.headers.Location = "https://passport.jd.com/relay/loginRelay"
|
||||
cb(nil, "HTTP 302", res)
|
||||
elseif hop_mode == "relay" and url == "https://passport.jd.com/relay/loginRelay" then
|
||||
cb('<script>window.location.href = "https://e.m.jd.com/relay-done";</script>', nil, res)
|
||||
elseif hop_mode == "relay" and not url:find("relay-done", 1, true) then
|
||||
cb("<html></html>", nil, res)
|
||||
elseif hop_mode == "redirect" and url:find("e.m.jd.com", 1, true) and not url:find("/home", 1, true) then
|
||||
res.code = 302
|
||||
res.headers.Location = "https://e.m.jd.com/home"
|
||||
res.headers["Set-Cookie"] = { "thor=session; Domain=.jd.com" }
|
||||
cb(nil, "HTTP 302", res)
|
||||
else
|
||||
res.headers["Set-Cookie"] = {
|
||||
"thor=session; Domain=.jd.com",
|
||||
"pin=tester; Domain=.jd.com",
|
||||
}
|
||||
cb("<html></html>", nil, res)
|
||||
end
|
||||
return { cancel = function() end }
|
||||
end
|
||||
return Request
|
||||
end
|
||||
|
||||
package.loaded["json"] = nil
|
||||
package.loaded["utils.settings"] = nil
|
||||
package.loaded["utils.paths"] = nil
|
||||
package.loaded["http.request"] = nil
|
||||
package.loaded["moonsource_jdread.auth"] = nil
|
||||
|
||||
local Auth = require("moonsource_jdread.auth")
|
||||
|
||||
do
|
||||
local started
|
||||
Auth.beginQrLoginAsync(function(value) started = value end)
|
||||
Assert.not_nil(started)
|
||||
Assert.eq(started.token, "token")
|
||||
|
||||
local login_info
|
||||
Auth.waitQrLoginAsync(started, function(value, err, status)
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(status, "ok")
|
||||
login_info = value
|
||||
end)
|
||||
Stubs.flush()
|
||||
Assert.eq(login_info.ticket, "ticket")
|
||||
|
||||
local user, complete_err
|
||||
Auth.completeQrLoginAsync(login_info, function(value, err)
|
||||
user, complete_err = value, err
|
||||
end)
|
||||
Assert.is_nil(complete_err)
|
||||
Assert.eq(user.user_name, "tester")
|
||||
Assert.matches(cfg.cookie, "pin=tester")
|
||||
Assert.matches(cfg.cookie, "thor=session")
|
||||
Assert.is_false(cfg.cookie:find("QRCodeKey", 1, true) ~= nil)
|
||||
Assert.is_false(cfg.cookie:find("wlfstk_smdl", 1, true) ~= nil)
|
||||
Assert.matches(cfg.uuid, "^h5%x%x%x%x")
|
||||
Assert.is_true(Auth.hasSession())
|
||||
end
|
||||
|
||||
do
|
||||
local uuid = cfg.uuid
|
||||
Auth.clearSession()
|
||||
Assert.is_false(Auth.hasSession())
|
||||
Assert.eq(cfg.uuid, uuid)
|
||||
end
|
||||
|
||||
-- ticket 校验失败:按官方 returnCode 语义提示并附原始码,不写会话。
|
||||
for reply, expected in pairs({
|
||||
['{"returnCode":80}'] = "京东判定本次扫码存在风险,官方要求改用密码登录 (80)",
|
||||
['{"returnCode":58}'] = "二维码已失效,请重新登录 (58)",
|
||||
['{"returnCode":85}'] = "京东登录校验失败 (85)",
|
||||
["<html>"] = "京东登录校验失败",
|
||||
}) do
|
||||
ticket_reply = reply
|
||||
local user, err
|
||||
Auth.completeQrLoginAsync({ ticket = "ticket", jar = {} }, function(value, e)
|
||||
user, err = value, e
|
||||
end)
|
||||
Assert.is_nil(user)
|
||||
Assert.eq(err, expected)
|
||||
Assert.is_false(Auth.hasSession())
|
||||
end
|
||||
|
||||
-- 两次登录并存(点外部关框后重进 / 连点):旧轮询必须用自己那张码的 Cookie,
|
||||
-- 串用新码的 wlfstk_smdl 时京东回 257“参数异常,请退出重试”。
|
||||
do
|
||||
paired, shows = true, 0
|
||||
local first, second
|
||||
Auth.beginQrLoginAsync(function(value) first = value end)
|
||||
Auth.beginQrLoginAsync(function(value) second = value end)
|
||||
Assert.eq(first.token, "token-1")
|
||||
Assert.eq(second.token, "token-2")
|
||||
|
||||
local results = {}
|
||||
for _, started in ipairs({ first, second }) do
|
||||
Auth.waitQrLoginAsync(started, function(value, err, status)
|
||||
results[#results + 1] = { info = value, err = err, status = status }
|
||||
end)
|
||||
end
|
||||
Stubs.flush()
|
||||
Assert.len(results, 2)
|
||||
for i, result in ipairs(results) do
|
||||
Assert.is_nil(result.err)
|
||||
Assert.eq(result.status, "ok")
|
||||
Assert.eq(result.info.ticket, "ticket-token-" .. i)
|
||||
end
|
||||
Assert.eq(results[1].info.jar.QRCodeKey, "qr-token-1")
|
||||
end
|
||||
|
||||
-- 校验成功但这一跳没会话 cookie:跟 JSON.url 拿 thor。
|
||||
do
|
||||
hop_mode = "url"
|
||||
ticket_reply = '{"returnCode":0,"url":"https://e.m.jd.com/"}'
|
||||
Auth.clearSession()
|
||||
local user, err
|
||||
Auth.completeQrLoginAsync({ ticket = "ticket", jar = { wlfstk_smdl = "token" } }, function(value, e)
|
||||
user, err = value, e
|
||||
end)
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(user.user_name, "tester")
|
||||
Assert.matches(cfg.cookie, "thor=session")
|
||||
Assert.matches(cfg.cookie, "pin=tester")
|
||||
Assert.is_false(cfg.cookie:find("wlfstk_smdl", 1, true) ~= nil)
|
||||
end
|
||||
|
||||
-- 跳转 302 的 Set-Cookie 必须保留,但仍要走完 Location。
|
||||
do
|
||||
hop_mode = "redirect"
|
||||
Auth.clearSession()
|
||||
local user, err
|
||||
Auth.completeQrLoginAsync({ ticket = "ticket", jar = {} }, function(value, e)
|
||||
user, err = value, e
|
||||
end)
|
||||
Assert.is_nil(err)
|
||||
Assert.matches(cfg.cookie, "thor=session")
|
||||
end
|
||||
|
||||
-- 多条 Set-Cookie 合并成一行(逗号分隔,expires 内含逗号):每条都要进 jar。
|
||||
do
|
||||
hop_mode = "merged"
|
||||
ticket_reply = '{"returnCode":0,"url":"https://e.m.jd.com/"}'
|
||||
Auth.clearSession()
|
||||
local user, err
|
||||
Auth.completeQrLoginAsync({ ticket = "ticket", jar = {} }, function(value, e) user, err = value, e end)
|
||||
Assert.is_nil(err)
|
||||
Assert.matches(cfg.cookie, "thor=session")
|
||||
Assert.matches(cfg.cookie, "pin=tester")
|
||||
Assert.matches(cfg.cookie, "pt_key=key")
|
||||
Assert.is_false(cfg.cookie:find("GMT", 1, true) ~= nil)
|
||||
end
|
||||
|
||||
-- 只有埋点 cookie 不算登录成功:跳转有上限,最终报错且不写会话。
|
||||
do
|
||||
hop_mode = "junk"
|
||||
hop_urls = {}
|
||||
Auth.clearSession()
|
||||
local user, err
|
||||
Auth.completeQrLoginAsync({ ticket = "ticket", jar = {} }, function(value, e) user, err = value, e end)
|
||||
Assert.is_nil(user)
|
||||
Assert.eq(err, "登录未拿到会话 Cookie")
|
||||
Assert.is_false(Auth.hasSession())
|
||||
Assert.is_true(#hop_urls <= 5)
|
||||
end
|
||||
|
||||
-- 日志里的真实链路:data.url 是 http relay → 302 https relay → 200 中转页 JS 跳转 → 拿到 thor。
|
||||
do
|
||||
hop_mode = "relay"
|
||||
ticket_reply = '{"returnCode":0,"url":"http://passport.jd.com/relay/loginRelay"}'
|
||||
Auth.clearSession()
|
||||
local user, err
|
||||
Auth.completeQrLoginAsync({ ticket = "ticket", jar = {} }, function(value, e) user, err = value, e end)
|
||||
Assert.is_nil(err)
|
||||
Assert.matches(cfg.cookie, "thor=session")
|
||||
end
|
||||
|
||||
-- 即使 ticket 已给 Cookie,也不能跳过官方 certified 验证;不向验证页或任意域转发设备会话。
|
||||
do
|
||||
for _idx, scenario in ipairs({
|
||||
{ mode = nil, url = "https://aq.jd.com/certified/index?test=fixture", requests = 1 },
|
||||
{ mode = "certified", url = "https://e.m.jd.com/", requests = 2 },
|
||||
}) do
|
||||
hop_mode = scenario.mode
|
||||
ticket_reply = JSONStub.encode({ returnCode = 0, url = scenario.url })
|
||||
cfg = { cookie = "old-session", uuid = "old-uuid", user_name = "old-name" }
|
||||
request_urls = {}
|
||||
local user, err
|
||||
Auth.completeQrLoginAsync({ ticket = "ticket", jar = { thor = "candidate" } }, function(value, e)
|
||||
user, err = value, e
|
||||
end)
|
||||
Assert.is_nil(user)
|
||||
Assert.eq(err, "京东要求账号安全验证,当前扫码流程尚不支持验证续接")
|
||||
Assert.len(request_urls, scenario.requests)
|
||||
Assert.eq(cfg.cookie, "old-session")
|
||||
Assert.eq(cfg.uuid, "old-uuid")
|
||||
Assert.eq(cfg.user_name, "old-name")
|
||||
end
|
||||
|
||||
hop_mode = nil
|
||||
for _idx, target in ipairs({
|
||||
"https://not-jd.example/relay", "//passport.jd.com.evil.test/relay",
|
||||
"https://[email protected]/relay", "javascript:location.href='https://e.m.jd.com/'",
|
||||
}) do
|
||||
ticket_reply = JSONStub.encode({ returnCode = 0, url = target })
|
||||
cfg = { cookie = "old-session", uuid = "old-uuid" }
|
||||
request_urls = {}
|
||||
local user, err
|
||||
Auth.completeQrLoginAsync({ ticket = "ticket", jar = {} }, function(value, e) user, err = value, e end)
|
||||
Assert.is_nil(user)
|
||||
Assert.eq(err, "京东登录跳转地址无效")
|
||||
Assert.len(request_urls, 1)
|
||||
Assert.eq(cfg.cookie, "old-session")
|
||||
end
|
||||
end
|
||||
|
||||
-- Cookie 存在也不能把中转网络错误或循环当成成功。
|
||||
do
|
||||
for _idx, scenario in ipairs({
|
||||
{ mode = "failed-hop", err = "network unavailable" },
|
||||
{ mode = "loop", err = "京东登录校验失败" },
|
||||
}) do
|
||||
hop_mode = scenario.mode
|
||||
ticket_reply = '{"returnCode":0,"url":"https://e.m.jd.com/"}'
|
||||
cfg = { cookie = "old-session", uuid = "old-uuid" }
|
||||
local user, err
|
||||
Auth.completeQrLoginAsync({ ticket = "ticket", jar = { thor = "candidate" } }, function(value, e)
|
||||
user, err = value, e
|
||||
end)
|
||||
Assert.is_nil(user)
|
||||
Assert.eq(err, scenario.err)
|
||||
Assert.eq(cfg.cookie, "old-session")
|
||||
end
|
||||
end
|
||||
|
||||
do
|
||||
Assert.is_false(Auth._hasLoginCookie({ __jda = "x", QRCodeKey = "y" }))
|
||||
Assert.is_true(Auth._hasLoginCookie({ pt_key = "k" }))
|
||||
Assert.eq(Auth._pageRedirect('<meta http-equiv="refresh" content="0;url=https://e.m.jd.com/a?x=1&y=2">'),
|
||||
"https://e.m.jd.com/a?x=1&y=2")
|
||||
-- 协议相对跳转(loginRelay 页里的 //aq.jd.com/...)不能拼到 passport 后面
|
||||
Assert.eq(Auth._absUrl("https://passport.jd.com/relay/loginRelay", "//aq.jd.com/certified/index"),
|
||||
"https://aq.jd.com/certified/index")
|
||||
Assert.eq(Auth._absUrl("https://passport.jd.com/a", "/b"), "https://passport.jd.com/b")
|
||||
Assert.eq(Auth._absUrl("https://passport.jd.com/relay/loginRelay", "../done"),
|
||||
"https://passport.jd.com/done")
|
||||
end
|
||||
|
||||
-- ticket 成功且有 Cookie 仍不等于登录成功:接口拒绝 / 网络失败时不覆盖旧会话。
|
||||
do
|
||||
hop_mode = nil
|
||||
ticket_reply = '{"returnCode":0}'
|
||||
for _idx, response in ipairs({
|
||||
{ body = '{"result_code":3,"message":"NOT.LOGIN"}', expected = "京东登录校验失败" },
|
||||
{ err = "Invalid URL provided.", expected = "Invalid URL provided." },
|
||||
}) do
|
||||
cfg = { cookie = "old-session", uuid = "old-uuid", user_name = "old-name" }
|
||||
session_reply, session_err = response.body, response.err
|
||||
local user, err
|
||||
Auth.completeQrLoginAsync({ ticket = "ticket", jar = {} }, function(value, e)
|
||||
user, err = value, e
|
||||
end)
|
||||
Assert.is_nil(user)
|
||||
Assert.eq(err, response.expected)
|
||||
Assert.eq(cfg.cookie, "old-session")
|
||||
Assert.eq(cfg.uuid, "old-uuid")
|
||||
Assert.eq(cfg.user_name, "old-name")
|
||||
end
|
||||
end
|
||||
|
||||
-- 同步 ticket 回包启动异步 API 校验:取消必须停校验请求,不能被旧 ticket 句柄覆盖。
|
||||
do
|
||||
cfg = { cookie = "old-session", uuid = "old-uuid" }
|
||||
session_reply, session_err, session_held = nil, nil, true
|
||||
local called = false
|
||||
local before = session_cancels
|
||||
local job = Auth.completeQrLoginAsync({ ticket = "ticket", jar = {} }, function()
|
||||
called = true
|
||||
end)
|
||||
Assert.not_nil(session_cb)
|
||||
job.cancel()
|
||||
Assert.eq(session_cancels, before + 1)
|
||||
session_cb('{"result_code":0,"data":{"book_ids":[]}}')
|
||||
Assert.is_false(called)
|
||||
Assert.eq(cfg.cookie, "old-session")
|
||||
session_held = false
|
||||
end
|
||||
|
||||
-- 浏览器授权只导入适用于 e.m.jd.com 的京东会话 Cookie,并先用签名 API 校验。
|
||||
do
|
||||
local request, response, response_err, saved, api_calls = nil, nil, nil, false, 0
|
||||
package.loaded["moonsource_jdread.client"] = nil
|
||||
package.preload["moonsource_jdread.client"] = function()
|
||||
return {
|
||||
new = function(_, options)
|
||||
request = options
|
||||
return {
|
||||
checkSessionAsync = function(_, cb)
|
||||
api_calls = api_calls + 1
|
||||
cb(response, response_err)
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
end,
|
||||
}
|
||||
end
|
||||
package.loaded["utils.settings"] = nil
|
||||
package.preload["utils.settings"] = function()
|
||||
return {
|
||||
getSource = function() return cfg end,
|
||||
saveSource = function(_, value) cfg, saved = value, true end,
|
||||
}
|
||||
end
|
||||
|
||||
cfg = { uuid = "existing-uuid", user_name = "old", other = "kept" }
|
||||
response, response_err, saved = { data = {} }, nil, false
|
||||
local result
|
||||
Auth.importBrowserAsync({ cookies = {
|
||||
{ domain = ".jd.com", name = "thor", value = "session" },
|
||||
{ domain = "e.m.jd.com", name = "pin", value = "reader" },
|
||||
{ domain = ".jd.com", name = "QRCodeKey", value = "temporary" },
|
||||
{ domain = ".evil.jd.com", name = "pt_key", value = "wrong-domain" },
|
||||
"malformed cookie entry",
|
||||
{ domain = ".jd.com", name = "bad", value = "bad;cookie" },
|
||||
} }, function(ok, err)
|
||||
result = ok
|
||||
Assert.is_nil(err)
|
||||
end)
|
||||
Assert.is_true(result)
|
||||
Assert.is_true(saved)
|
||||
Assert.eq(request.uuid, "existing-uuid")
|
||||
Assert.matches(request.cookie, "thor=session")
|
||||
Assert.matches(request.cookie, "pin=reader")
|
||||
Assert.is_false(request.cookie:find("QRCodeKey", 1, true) ~= nil)
|
||||
Assert.is_false(request.cookie:find("wrong-domain", 1, true) ~= nil)
|
||||
Assert.is_false(request.cookie:find("bad=bad", 1, true) ~= nil)
|
||||
Assert.eq(cfg.user_name, "reader")
|
||||
Assert.eq(cfg.other, "kept")
|
||||
|
||||
cfg, saved = { cookie = "old-session", user_name = "old" }, false
|
||||
local previous_calls = api_calls
|
||||
Auth.importBrowserAsync({ cookies = {
|
||||
{ domain = ".evil.jd.com", name = "thor", value = "wrong-domain" },
|
||||
} }, function(ok, err)
|
||||
result = ok
|
||||
Assert.not_nil(err)
|
||||
end)
|
||||
Assert.is_false(result)
|
||||
Assert.is_false(saved)
|
||||
Assert.eq(api_calls, previous_calls)
|
||||
|
||||
cfg = { cookie = "old-session", user_name = "old" }
|
||||
response, response_err, saved, result = nil, "expired session", false, nil
|
||||
Auth.importBrowserAsync({ cookies = {
|
||||
{ domain = ".jd.com", name = "thor", value = "new-session" },
|
||||
} }, function(ok, err)
|
||||
result = ok
|
||||
Assert.not_nil(err)
|
||||
end)
|
||||
Assert.is_false(result)
|
||||
Assert.is_false(saved)
|
||||
Assert.eq(cfg.cookie, "old-session")
|
||||
end
|
||||
@@ -0,0 +1,331 @@
|
||||
--[[--
|
||||
京东读书客户端分页与下载接口离线用例。
|
||||
|
||||
@module tests.moonsource_jdread.client_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 CookieOf = require("support.cookie")
|
||||
local JSONStub = require("support.json_stub")
|
||||
|
||||
package.preload["json"] = function()
|
||||
return { decode = JSONStub.decode, encode = JSONStub.encode }
|
||||
end
|
||||
|
||||
local requests = {}
|
||||
package.preload["http.request"] = function()
|
||||
return {
|
||||
get = function(url, opts, cb)
|
||||
requests[#requests + 1] = { url = url, opts = opts }
|
||||
if url:find("/jdread/api/bookshelf/sort", 1, true) then
|
||||
cb('{"data":{"book_ids":[{"ebook_id":2},{"ebook_id":1}]},"result_code":0}')
|
||||
elseif url:find("/jdread/api/ebooks/lite/2,1", 1, true) then
|
||||
cb('{"data":[{"ebook_id":2,"name":"二"},{"ebook_id":1,"name":"一"}],"result_code":0}')
|
||||
elseif url:find("/recommend", 1, true) then
|
||||
cb('{"data":[{"ebook_id":4,"name":"推荐书"}],"result_code":0}')
|
||||
elseif url:find("/jdread/api/ebook/catalog/v2/30394360", 1, true) then
|
||||
cb('{"data":{"format":"epub","has_more":false,'
|
||||
.. '"chapter_info":[{"chapter_index":0,"chapter_name":"封面"}]},"result_code":0}')
|
||||
elseif url:find("/jdread/api/ebook/catalog/v2/30451107", 1, true) then
|
||||
cb('{"data":{"format":"txt","has_more":false,"chapter_info":[]},"result_code":0}')
|
||||
elseif url:find("/jdread/api/download/chapter/30394360", 1, true) then
|
||||
cb('{"result_code":1,"message":"UNKNOWN_ERROR"}')
|
||||
elseif url:find("/jdread/api/download/chapter/34028897", 1, true) then
|
||||
cb('{"result_code":101,"message":"can not download"}')
|
||||
else
|
||||
cb('{"code":"-1","msg":"stop"}')
|
||||
end
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
post = function(url, body, opts, cb)
|
||||
requests[#requests + 1] = { url = url, body = body, opts = opts }
|
||||
cb('{"data":[],"result_code":0,"message":"SUCCESS"}')
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
end
|
||||
|
||||
package.loaded["json"] = nil
|
||||
package.loaded["http.request"] = nil
|
||||
package.loaded["moonsource_jdread.protocol"] = nil
|
||||
package.loaded["moonsource_jdread.client"] = nil
|
||||
|
||||
local Client = require("moonsource_jdread.client")
|
||||
local client = Client:new{ cookie = "thor=test", uuid = "h5-test" }
|
||||
|
||||
do
|
||||
Assert.is_true(client:configured())
|
||||
local wire, err
|
||||
client:shelfSyncAsync(function(value, e) wire, err = value, e end)
|
||||
Assert.is_nil(err)
|
||||
Assert.len(wire, 2)
|
||||
Assert.eq(wire[1].ebook_id, 2)
|
||||
Assert.matches(requests[1].url, "/jdread/api/bookshelf/sort%?")
|
||||
Assert.matches(requests[2].url, "/jdread/api/ebooks/lite/2,1%?")
|
||||
Assert.eq(CookieOf(requests[1]), "thor=test")
|
||||
end
|
||||
|
||||
do
|
||||
local batched = Client:new{ cookie = "thor=test", uuid = "h5-test" }
|
||||
local paths = {}
|
||||
function batched:apiGetAsync(path, _, cb)
|
||||
paths[#paths + 1] = path
|
||||
if path == "/jdread/api/bookshelf/sort" then
|
||||
local ids = {}
|
||||
for i = 1, 20 do ids[i] = { ebook_id = i } end
|
||||
cb({ data = { book_ids = ids } })
|
||||
else
|
||||
local rows = {}
|
||||
for id in path:match("/ebooks/lite/(.+)$"):gmatch("[^,]+") do
|
||||
rows[#rows + 1] = { ebook_id = tonumber(id) }
|
||||
end
|
||||
cb({ data = rows })
|
||||
end
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local wire
|
||||
batched:shelfSyncAsync(function(value) wire = value end)
|
||||
Assert.len(wire, 20)
|
||||
Assert.matches(paths[2], "/ebooks/lite/1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18$")
|
||||
Assert.matches(paths[3], "/ebooks/lite/19,20$")
|
||||
end
|
||||
|
||||
do
|
||||
local wire, err
|
||||
client:addToShelfAsync("30533530", function(value, e) wire, err = value, e end)
|
||||
local req = requests[#requests]
|
||||
Assert.is_nil(err)
|
||||
Assert.not_nil(wire)
|
||||
Assert.matches(req.url, "/jdread/api/bookshelf/book/sync%?")
|
||||
local body = require("json").decode(req.body)
|
||||
Assert.eq(body.first_sync, 1)
|
||||
Assert.eq(body.items[1].action, 0)
|
||||
Assert.eq(body.items[1].ebook_id, 30533530)
|
||||
end
|
||||
|
||||
-- 非法 ID 跳过、不进 URL;合法 ID 照常分批。全是脏行则空快照成功返回(不下架策略由 shelf 管)。
|
||||
do
|
||||
for _idx, bad in ipairs({ {}, { book_id = 2 }, { ebook_id = false }, "2 3", "" }) do
|
||||
local malformed = Client:new{ cookie = "thor=test", uuid = "h5-test" }
|
||||
local paths = {}
|
||||
function malformed:apiGetAsync(path, _extra, cb)
|
||||
paths[#paths + 1] = path
|
||||
if #paths == 1 then
|
||||
cb({ data = { book_ids = { { ebook_id = 1 }, bad, { ebook_id = 3 } } } })
|
||||
else
|
||||
cb({ data = { { ebook_id = 1, name = "一" }, { ebook_id = 3, name = "三" } } })
|
||||
end
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local wire, err, meta
|
||||
malformed:shelfSyncAsync(function(value, e, m) wire, err, meta = value, e, m end)
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(paths[2], "/jdread/api/ebooks/lite/1,3")
|
||||
Assert.len(wire, 2)
|
||||
Assert.eq(wire[1].ebook_id, 1)
|
||||
Assert.eq(wire[2].ebook_id, 3)
|
||||
Assert.is_true(meta.incomplete, "合法条目可用,但坏 ID 使快照不完整")
|
||||
end
|
||||
end
|
||||
|
||||
do
|
||||
local all_bad = Client:new{ cookie = "thor=test", uuid = "h5-test" }
|
||||
local calls = 0
|
||||
function all_bad:apiGetAsync(_path, _extra, cb)
|
||||
calls = calls + 1
|
||||
cb({ data = { book_ids = { {}, { ebook_id = false }, "" } } })
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local wire, err, meta
|
||||
all_bad:shelfSyncAsync(function(value, e, m) wire, err, meta = value, e, m end)
|
||||
Assert.eq(calls, 1, "全脏行不应发起分批请求")
|
||||
Assert.is_nil(err)
|
||||
Assert.len(wire, 0)
|
||||
Assert.is_true(meta.incomplete)
|
||||
end
|
||||
|
||||
do
|
||||
local mixed = Client:new{ cookie = "thor=test", uuid = "h5-test" }
|
||||
local paths = {}
|
||||
function mixed:apiGetAsync(path, _extra, cb)
|
||||
paths[#paths + 1] = path
|
||||
if #paths == 1 then
|
||||
cb({ data = { book_ids = { 2, { ebook_id = "1" }, "2" } } })
|
||||
else
|
||||
cb({ data = { { ebook_id = 2 }, { ebook_id = 1 } } })
|
||||
end
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local wire
|
||||
mixed:shelfSyncAsync(function(value) wire = value end)
|
||||
Assert.eq(paths[2], "/jdread/api/ebooks/lite/2,1")
|
||||
Assert.len(wire, 2)
|
||||
end
|
||||
|
||||
do
|
||||
local wire, err
|
||||
client:removeFromShelfAsync("30533530", function(value, e) wire, err = value, e end)
|
||||
local body = require("json").decode(requests[#requests].body)
|
||||
Assert.is_nil(err)
|
||||
Assert.not_nil(wire)
|
||||
Assert.eq(body.items[1].action, 1)
|
||||
Assert.eq(body.items[1].ebook_id, 30533530)
|
||||
end
|
||||
|
||||
-- 空目录只回空结果,不再落到任何旧接口
|
||||
do
|
||||
local wire, err
|
||||
local first = #requests + 1
|
||||
client:catalogAsync("30451107", function(value, e) wire, err = value, e end)
|
||||
Assert.matches(requests[first].url, "^https://e%.m%.jd%.com/jdread/api/ebook/catalog/v2/30451107%?")
|
||||
Assert.matches(requests[first].url, "[?&]index=0")
|
||||
Assert.matches(requests[first].url, "[?&]page_size=2000")
|
||||
Assert.len(requests, first)
|
||||
Assert.is_nil(err)
|
||||
Assert.len(wire.data.chapter_info, 0)
|
||||
end
|
||||
|
||||
do
|
||||
local wire, err
|
||||
client:catalogAsync("30394360", function(value, e) wire, err = value, e end)
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(wire.data.chapter_info[1].chapter_name, "封面")
|
||||
end
|
||||
|
||||
do
|
||||
local _, err
|
||||
local first = #requests + 1
|
||||
client:downloadChapterAsync("30394360", { indexes = 0 }, function(value, e) _, err = value, e end)
|
||||
local req = requests[first]
|
||||
Assert.matches(req.url, "^https://e%.m%.jd%.com/jdread/api/download/chapter/30394360%?")
|
||||
Assert.matches(req.url, "[?&]enc=1")
|
||||
Assert.matches(req.url, "[?&]indexes=0")
|
||||
Assert.matches(req.url, "[?&]params=")
|
||||
Assert.eq(err, "UNKNOWN_ERROR")
|
||||
end
|
||||
|
||||
-- txt 网文:网页阅读器协议 type + ids;101 = 未购买且非试读,给出权限文案而非英文原文
|
||||
do
|
||||
local wire, err
|
||||
local first = #requests + 1
|
||||
client:downloadChapterAsync("34028897", { type = 1, ids = "15001647875062768" }, function(value, e)
|
||||
wire, err = value, e
|
||||
end)
|
||||
local req = requests[first]
|
||||
Assert.matches(req.url, "^https://e%.m%.jd%.com/jdread/api/download/chapter/34028897%?")
|
||||
Assert.matches(req.url, "[?&]type=1")
|
||||
Assert.matches(req.url, "[?&]ids=15001647875062768")
|
||||
Assert.is_nil(req.url:find("indexes=", 1, true))
|
||||
Assert.is_nil(wire)
|
||||
Assert.eq(err, "京东读书网页协议读不到本章,请在京东读书 App 内阅读")
|
||||
end
|
||||
|
||||
-- v2 目录按行偏移分页,直到 has_more=false,合并成一份 chapter_info
|
||||
do
|
||||
local paged = Client:new{ cookie = "thor=test", uuid = "h5-test" }
|
||||
local calls = {}
|
||||
function paged:apiGetAsync(path, params, cb)
|
||||
calls[#calls + 1] = { path = path, index = params.index, size = params.page_size }
|
||||
local rows = {}
|
||||
local count = params.index == 0 and 2 or 1
|
||||
for i = 1, count do rows[i] = { chapter_id = tostring(params.index + i), type = 1 } end
|
||||
cb({ data = { format = "txt", has_more = params.index == 0, chapter_info = rows }, result_code = 0 })
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local wire
|
||||
paged:catalogAsync("34028897", function(value) wire = value end)
|
||||
Assert.len(calls, 2)
|
||||
Assert.eq(calls[1].path, "/jdread/api/ebook/catalog/v2/34028897")
|
||||
Assert.eq(calls[1].index, 0)
|
||||
Assert.eq(calls[2].index, 2)
|
||||
Assert.eq(calls[1].size, 2000)
|
||||
Assert.len(wire.data.chapter_info, 3)
|
||||
Assert.eq(wire.data.chapter_info[3].chapter_id, "3")
|
||||
Assert.eq(wire.data.format, "txt")
|
||||
end
|
||||
|
||||
do
|
||||
for _, req in ipairs(requests) do
|
||||
Assert.is_nil(req.url:find("cread.jd.com", 1, true))
|
||||
end
|
||||
end
|
||||
|
||||
do
|
||||
local wire, err
|
||||
client:getProgressAsync("30451107", function(value, e) wire, err = value, e end)
|
||||
local req = requests[#requests]
|
||||
Assert.is_nil(err)
|
||||
Assert.not_nil(wire)
|
||||
Assert.matches(req.url, "^https://e%.m%.jd%.com/jdread/api/marker/sync%?")
|
||||
Assert.eq(req.opts.content_type, "application/json")
|
||||
local body = require("json").decode(req.body)
|
||||
Assert.eq(body[1].ebook_id, 30451107)
|
||||
Assert.eq(body[1].format, 1)
|
||||
end
|
||||
|
||||
-- 推进度与拉进度同一接口,ebook_id 同为数字
|
||||
do
|
||||
client:putProgressAsync("30451107", { data_type = 0 }, function() end)
|
||||
local body = require("json").decode(requests[#requests].body)
|
||||
Assert.eq(body[1].ebook_id, 30451107)
|
||||
Assert.eq(body[1].list[1].data_type, 0)
|
||||
end
|
||||
|
||||
-- NOT.LOGIN:英文错误码也要标登录失效,不能把服务端原串弹给用户。
|
||||
do
|
||||
local expired, oks = {}, 0
|
||||
package.preload["source.auth"] = function()
|
||||
return {
|
||||
expire = function(id, msg) expired[#expired + 1] = { id = id, msg = msg }; return msg end,
|
||||
ok = function() oks = oks + 1 end,
|
||||
}
|
||||
end
|
||||
local bodies = { '{"result_code":1,"message":"NOT.LOGIN"}' }
|
||||
package.loaded["http.request"] = {
|
||||
get = function(_url, _opts, cb)
|
||||
cb(bodies[1])
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
post = function(_url, _body, _opts, cb)
|
||||
cb(bodies[1])
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
package.loaded["source.auth"] = nil
|
||||
package.loaded["moonsource_jdread.client"] = nil
|
||||
local AuthClient = require("moonsource_jdread.client")
|
||||
local c = AuthClient:new{ cookie = "thor=stale", uuid = "h5-test" }
|
||||
local got_err
|
||||
c:apiGetAsync("/jdread/api/bookshelf/sort", nil, function(_wire, err) got_err = err end)
|
||||
Assert.eq(expired[1].id, "ext.jdread")
|
||||
Assert.matches(got_err, "京东 App")
|
||||
Assert.eq(got_err, expired[1].msg)
|
||||
-- 中文「登录」同样走失效路径,文案仍用统一中文,不附原文
|
||||
bodies[1] = '{"result_code":1,"message":"请重新登录"}'
|
||||
c:apiGetAsync("/jdread/api/bookshelf/sort", nil, function(_wire, err) got_err = err end)
|
||||
Assert.matches(got_err, "京东 App")
|
||||
Assert.len(expired, 2)
|
||||
|
||||
-- 匿名请求(没配 Cookie 逛榜单)成功不算登录态有效,不能把「已提示过期」清掉;带 Cookie 的成功才算
|
||||
bodies[1] = '{"result_code":0,"data":{}}'
|
||||
local anon = AuthClient:new{ uuid = "h5-anon" }
|
||||
anon:apiGetAsync("/jdread/api/rank", nil, function() end)
|
||||
Assert.eq(oks, 0, "匿名成功不 Auth.ok")
|
||||
c:apiGetAsync("/jdread/api/bookshelf/sort", nil, function() end)
|
||||
Assert.eq(oks, 1)
|
||||
|
||||
-- 候选会话校验不允许把旧账号标过期,也不能在保存新凭证之前清掉旧过期状态。
|
||||
bodies[1] = '{"result_code":3,"message":"NOT.LOGIN"}'
|
||||
c:checkSessionAsync(function(_wire, err) got_err = err end)
|
||||
Assert.eq(got_err, "京东登录校验失败")
|
||||
Assert.len(expired, 2)
|
||||
bodies[1] = '{"result_code":0,"data":{"book_ids":[]}}'
|
||||
local checked
|
||||
c:checkSessionAsync(function(wire, err)
|
||||
checked = wire
|
||||
Assert.is_nil(err)
|
||||
end)
|
||||
Assert.not_nil(checked)
|
||||
Assert.eq(oks, 1)
|
||||
end
|
||||
@@ -0,0 +1,649 @@
|
||||
--[[--
|
||||
京东读书源书城与本地统计能力离线用例。
|
||||
|
||||
@module tests.source.jdread_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 warnings = {}
|
||||
package.preload["utils.log"] = function()
|
||||
return {
|
||||
warn = function(...)
|
||||
warnings[#warnings + 1] = { ... }
|
||||
end,
|
||||
dbg = function() end,
|
||||
info = function() end,
|
||||
}
|
||||
end
|
||||
|
||||
local fake_client = {
|
||||
configured = function() return true end,
|
||||
}
|
||||
package.preload["moonsource_jdread.client"] = function()
|
||||
return {
|
||||
new = function() return fake_client end,
|
||||
}
|
||||
end
|
||||
package.preload["utils.settings"] = function()
|
||||
return {
|
||||
getSource = function() return {} end,
|
||||
}
|
||||
end
|
||||
|
||||
local remembered
|
||||
local local_library = {}
|
||||
local pending_deletes = {}
|
||||
local pending_adds = {}
|
||||
local finalized = {}
|
||||
package.preload["book.store"] = function()
|
||||
return {
|
||||
rememberMany = function(books) remembered = books; return true end,
|
||||
markDeleted = function() return true end,
|
||||
}
|
||||
end
|
||||
package.preload["book.books_db"] = function()
|
||||
return {
|
||||
reconcile = function(_, books)
|
||||
remembered = books
|
||||
return true, 0
|
||||
end,
|
||||
remove = function(_, stable_id)
|
||||
finalized[#finalized + 1] = stable_id
|
||||
return true
|
||||
end,
|
||||
libraryStableIdsBySource = function() return local_library end,
|
||||
pendingDeleteIds = function() return pending_deletes end,
|
||||
pendingShelfAddIds = function() return pending_adds end,
|
||||
markSynced = function() return true end,
|
||||
getToc = function() return nil end,
|
||||
setToc = function() end,
|
||||
}
|
||||
end
|
||||
|
||||
package.loaded["moonsource_jdread.client"] = nil
|
||||
package.loaded["utils.settings"] = nil
|
||||
package.loaded["book.store"] = nil
|
||||
package.loaded["book.books_db"] = nil
|
||||
package.loaded["moonsource_jdread.source"] = nil
|
||||
|
||||
local Jdread = require("moonsource_jdread.source")
|
||||
|
||||
do
|
||||
local source = Jdread.new()
|
||||
local caps = source:capabilities()
|
||||
Assert.is_false(caps.stats_pull)
|
||||
Assert.is_false(type(source.pushStatsAsync) == "function")
|
||||
end
|
||||
|
||||
-- 图书馆列表行不带 cover:基类按身份查书库取 URL;非 http 或缺失给 nil
|
||||
do
|
||||
local source = Jdread.new()
|
||||
local stored = {
|
||||
["42"] = { cover = "https://img.jd.com/42.jpg" },
|
||||
["43"] = { cover = "${free_list[i].cover}" },
|
||||
}
|
||||
local BookDB = require("book.books_db")
|
||||
BookDB.get = function(source_id, stable_id)
|
||||
Assert.eq(source_id, "ext.jdread")
|
||||
return stored[stable_id]
|
||||
end
|
||||
Assert.eq(source:coverRequest({ stable_id = "42" }).url, "https://img.jd.com/42.jpg")
|
||||
Assert.eq(source:coverRequest({ stable_id = "42", cover = "https://x/y.jpg" }).url, "https://x/y.jpg")
|
||||
local req, err = source:coverRequest({ stable_id = "43" })
|
||||
Assert.is_nil(req)
|
||||
Assert.eq(err, "无封面")
|
||||
Assert.is_nil((source:coverRequest({ stable_id = "44" })))
|
||||
BookDB.get = nil
|
||||
end
|
||||
|
||||
-- syncBooksAsync:本地独有成员上行,pushed 填实
|
||||
do
|
||||
local added, shelf_calls = {}, 0
|
||||
local list_calls = 0
|
||||
fake_client.shelfSyncAsync = function(_, cb)
|
||||
shelf_calls = shelf_calls + 1
|
||||
cb({ { ebook_id = 10, name = "远端" } })
|
||||
return { cancel = function() end }
|
||||
end
|
||||
fake_client.addToShelfAsync = function(_, book_id, cb)
|
||||
added[#added + 1] = tostring(book_id)
|
||||
cb({ ok = true })
|
||||
return { cancel = function() end }
|
||||
end
|
||||
-- 绕过 mapper:直接让 shelfList 返回可控列表
|
||||
local real_mapper = require("moonsource_jdread.mapper")
|
||||
local orig_shelf = real_mapper.shelfList
|
||||
real_mapper.shelfList = function()
|
||||
list_calls = list_calls + 1
|
||||
return { { stable_id = "10", title = "远端" } }
|
||||
end
|
||||
-- 10 已在远端:只标已同步不再请求;99 是本地新加架,上行。
|
||||
pending_adds = { "10", "99" }
|
||||
local synced = {}
|
||||
local db = require("book.books_db")
|
||||
local orig_mark = db.markSynced
|
||||
db.markSynced = function(_, stable_id)
|
||||
synced[#synced + 1] = stable_id
|
||||
return true
|
||||
end
|
||||
local src = Jdread.new()
|
||||
local result, err
|
||||
src:syncBooksAsync(nil, function(r, e) result, err = r, e end)
|
||||
require("support.stubs").flush()
|
||||
Assert.is_nil(err)
|
||||
Assert.not_nil(result)
|
||||
Assert.eq(result.pushed, 1)
|
||||
Assert.eq(#added, 1)
|
||||
Assert.eq(added[1], "99")
|
||||
Assert.eq(table.concat(synced, ","), "10,99")
|
||||
Assert.eq(shelf_calls, 2)
|
||||
Assert.eq(list_calls, 2)
|
||||
|
||||
-- 已同步的本地书云端已移除:不得加回云端,交给 reconcile 软删。
|
||||
added, shelf_calls, list_calls = {}, 0, 0
|
||||
pending_adds = {}
|
||||
local_library = { "10", "77" }
|
||||
remembered = nil
|
||||
src:syncBooksAsync(nil, function(r, e) result, err = r, e end)
|
||||
require("support.stubs").flush()
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(#added, 0)
|
||||
Assert.eq(result.pushed, 0)
|
||||
Assert.eq(shelf_calls, 1)
|
||||
Assert.eq(#remembered, 1)
|
||||
Assert.eq(remembered[1].stable_id, "10")
|
||||
real_mapper.shelfList = orig_shelf
|
||||
db.markSynced = orig_mark
|
||||
local_library = {}
|
||||
end
|
||||
|
||||
-- dirty_only:远端删除失败不撕墓碑,且必须留下日志
|
||||
do
|
||||
warnings = {}
|
||||
finalized = {}
|
||||
pending_deletes = { "gone" }
|
||||
pending_adds = {}
|
||||
fake_client.removeFromShelfAsync = function(_, stable_id, cb)
|
||||
cb(nil, "network")
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local src = Jdread.new()
|
||||
local result, err
|
||||
src:syncBooksAsync({ dirty_only = true }, function(r, e) result, err = r, e end)
|
||||
require("support.stubs").flush()
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(result.pushed, 0)
|
||||
Assert.eq(#finalized, 0)
|
||||
Assert.eq(warnings[1][1], "ext.jdread shelf delete push failed")
|
||||
Assert.eq(warnings[1][2], "gone")
|
||||
pending_deletes = {}
|
||||
end
|
||||
|
||||
-- dirty_only:云端删除成功但本地撕墓碑失败,不得计 pushed
|
||||
do
|
||||
finalized = {}
|
||||
pending_deletes = { "gone" }
|
||||
pending_adds = {}
|
||||
local BookDB = require("book.books_db")
|
||||
BookDB.remove = function(_, stable_id)
|
||||
finalized[#finalized + 1] = stable_id
|
||||
return false
|
||||
end
|
||||
fake_client.removeFromShelfAsync = function(_, _, cb)
|
||||
cb({ ok = true })
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local src = Jdread.new()
|
||||
local result
|
||||
src:syncBooksAsync({ dirty_only = true }, function(r) result = r end)
|
||||
require("support.stubs").flush()
|
||||
Assert.eq(result.pushed, 0)
|
||||
Assert.eq(#finalized, 1)
|
||||
BookDB.remove = function(_, stable_id)
|
||||
finalized[#finalized + 1] = stable_id
|
||||
return true
|
||||
end
|
||||
pending_deletes = {}
|
||||
end
|
||||
|
||||
-- dirty_only:加架失败不 markSynced,且必须留下日志
|
||||
do
|
||||
warnings = {}
|
||||
pending_deletes = {}
|
||||
pending_adds = { "99" }
|
||||
local synced = {}
|
||||
package.loaded["book.books_db"].markSynced = function(_, stable_id)
|
||||
synced[#synced + 1] = stable_id
|
||||
return true
|
||||
end
|
||||
fake_client.addToShelfAsync = function(_, stable_id, cb)
|
||||
cb(nil, "denied")
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local src = Jdread.new()
|
||||
local result
|
||||
src:syncBooksAsync({ dirty_only = true }, function(r) result = r end)
|
||||
require("support.stubs").flush()
|
||||
Assert.eq(result.pushed, 0)
|
||||
Assert.eq(#synced, 0)
|
||||
Assert.eq(warnings[1][1], "ext.jdread shelf push failed")
|
||||
Assert.eq(warnings[1][2], "99")
|
||||
pending_adds = {}
|
||||
end
|
||||
|
||||
-- dirty_only:云端加架成功但本地 markSynced 失败,不得计 pushed
|
||||
do
|
||||
warnings = {}
|
||||
pending_deletes = {}
|
||||
pending_adds = { "99" }
|
||||
package.loaded["book.books_db"].markSynced = function() return false end
|
||||
fake_client.addToShelfAsync = function(_, _, cb)
|
||||
cb({ ok = true })
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local src = Jdread.new()
|
||||
local result
|
||||
src:syncBooksAsync({ dirty_only = true }, function(r) result = r end)
|
||||
require("support.stubs").flush()
|
||||
Assert.eq(result.pushed, 0)
|
||||
Assert.eq(warnings[1][1], "ext.jdread shelf mark synced failed")
|
||||
package.loaded["book.books_db"].markSynced = function() return true end
|
||||
pending_adds = {}
|
||||
end
|
||||
|
||||
do
|
||||
local prefetch_opts
|
||||
package.loaded["source.chapter"] = nil
|
||||
require("source.chapter").prefetchAsync = function(identity, _, toc, from_idx, count, opts, cb)
|
||||
prefetch_opts = opts
|
||||
Assert.eq(from_idx, 0)
|
||||
Assert.eq(count, #toc)
|
||||
opts.progress(1, #toc)
|
||||
opts.fetchContent(identity, toc[1], function(payload)
|
||||
Assert.matches(payload.html, "正文")
|
||||
cb(2, 2, 0)
|
||||
end)
|
||||
return { cancel = function() end }
|
||||
end
|
||||
package.loaded["moonsource_jdread.source"] = nil
|
||||
local Jd = require("moonsource_jdread.source")
|
||||
fake_client.downloadChapterAsync = function(_, _, query, cb)
|
||||
Assert.eq(query.indexes, "0")
|
||||
cb({ data = { chapter = { { content = "<p>正文</p>" } } } })
|
||||
return { cancel = function() end }
|
||||
end
|
||||
|
||||
local source = Jd.new()
|
||||
source.loadTocAsync = function(_, _, cb)
|
||||
cb({
|
||||
{ idx = 1, uid = "0", title = "第一章", toc_version = 5 },
|
||||
{ idx = 2, uid = "1", title = "第二章" },
|
||||
})
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local progressed, ok, cached, total, failed
|
||||
source:cacheAllChaptersAsync(
|
||||
{ source_id = "ext.jdread", stable_id = "10", book = { stable_id = "10" } },
|
||||
function(done, count) progressed = { done, count } end,
|
||||
function(success, count, _, all, failures)
|
||||
ok, cached, total, failed = success, count, all, failures
|
||||
end
|
||||
)
|
||||
Assert.eq(progressed[1], 1)
|
||||
Assert.eq(progressed[2], 2)
|
||||
Assert.is_false(prefetch_opts.persist_book)
|
||||
Assert.eq(prefetch_opts.interval_seconds, 1.5)
|
||||
Assert.is_true(ok)
|
||||
Assert.eq(cached, 2)
|
||||
Assert.eq(total, 2)
|
||||
Assert.eq(failed, 0)
|
||||
end
|
||||
|
||||
-- 目录版本 3(txt 网文)正文按网页阅读器协议 { type = 1, ids = chapter_id } 下载
|
||||
do
|
||||
local Toc = require("source.toc")
|
||||
local orig_read = Toc.read
|
||||
Toc.read = function()
|
||||
return { { idx = 1, uid = "15001647875062768", title = "第一章", toc_version = 3 } }
|
||||
end
|
||||
local asked
|
||||
fake_client.downloadChapterAsync = function(_, book_id, query, cb)
|
||||
asked = { book_id = book_id, query = query }
|
||||
cb({ data = { content_type = "net", chapter = {{ content = " 正文一\r\n正文二" }} } })
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local html
|
||||
require("source.chapter").prefetchAsync = function(identity, _, toc, _, _, opts, cb)
|
||||
opts.fetchContent(identity, toc[1], function(payload) html = payload.html; cb() end)
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local src = Jdread.new()
|
||||
src:prefetchChaptersAsync(
|
||||
{ source_id = "ext.jdread", stable_id = "34028897", book = { stable_id = "34028897" } },
|
||||
{ { idx = 1, uid = "15001647875062768", title = "第一章" } },
|
||||
1, 1, function() end
|
||||
)
|
||||
Assert.eq(asked.book_id, "34028897")
|
||||
Assert.eq(asked.query.type, 1)
|
||||
Assert.eq(asked.query.ids, "15001647875062768")
|
||||
Assert.is_nil(asked.query.indexes)
|
||||
Assert.eq(html, "<p>正文一</p>\n<p>正文二</p>")
|
||||
Toc.read = orig_read
|
||||
end
|
||||
|
||||
-- 失效目录(旧 cread 版本 1)读到即清库重拉;正文按新目录同 idx 的 uid 下载
|
||||
do
|
||||
local Toc = require("source.toc")
|
||||
local orig_read, orig_put = Toc.read, Toc.put
|
||||
local stored = { { idx = 1, uid = "56958326", title = "第一章", toc_version = 1 } }
|
||||
Toc.read = function() return stored end
|
||||
Toc.put = function(_, _, list) stored = list; return true end
|
||||
local cleared = {}
|
||||
package.loaded["book.books_db"].clearToc = function(_, stable_id)
|
||||
cleared[#cleared + 1] = stable_id
|
||||
stored = nil
|
||||
return true
|
||||
end
|
||||
local catalog_calls = 0
|
||||
fake_client.catalogAsync = function(_, _, cb)
|
||||
catalog_calls = catalog_calls + 1
|
||||
cb({ data = { format = "epub", chapter_info = { { chapter_index = 0, chapter_name = "第一章" } } } })
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local asked
|
||||
fake_client.downloadChapterAsync = function(_, _, query, cb)
|
||||
asked = query
|
||||
cb({ data = { chapter = { { content = "<p>新</p>" } } } })
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local html
|
||||
require("source.chapter").prefetchAsync = function(identity, _, toc, _, _, opts, cb)
|
||||
opts.fetchContent(identity, toc[1], function(payload) html = payload.html; cb() end)
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local src = Jdread.new()
|
||||
local old = stored
|
||||
Assert.is_false(src:isTocCurrent(old))
|
||||
Assert.is_false(src:isTocCurrent({ { idx = 1, uid = "0", title = "无版本" } }))
|
||||
Assert.is_false(src:isTocCurrent({}))
|
||||
src:prefetchChaptersAsync(
|
||||
{ source_id = "ext.jdread", stable_id = "30451107", book = { stable_id = "30451107" } },
|
||||
old, 1, 1, function() end
|
||||
)
|
||||
Assert.eq(cleared[1], "30451107")
|
||||
Assert.eq(catalog_calls, 1)
|
||||
Assert.eq(asked.indexes, "0")
|
||||
Assert.matches(html, "<p>新</p>")
|
||||
Assert.eq(stored[1].toc_version, 5)
|
||||
Assert.is_true(src:isTocCurrent(stored))
|
||||
Assert.is_false(src:isTocCurrent({ { idx = 1, uid = "0", title = "旧 EPUB 目录", toc_version = 2 } }))
|
||||
Assert.is_false(src:isTocCurrent({ { idx = 1, uid = "0", title = "无锚点目录", toc_version = 4 } }))
|
||||
|
||||
-- 网页协议判定 can_read=false:提示走 App,不冒充网络/权限错误
|
||||
fake_client.downloadChapterAsync = function(_, _, _, cb)
|
||||
cb({ data = { content_type = "net", chapter = { { chapter_id = "c37", can_read = false } } } })
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local denied
|
||||
require("source.chapter").prefetchAsync = function(identity, _, toc, _, _, opts, cb)
|
||||
opts.fetchContent(identity, toc[1], function(_, err) denied = err; cb() end)
|
||||
return { cancel = function() end }
|
||||
end
|
||||
src:prefetchChaptersAsync(
|
||||
{ source_id = "ext.jdread", stable_id = "30451107", book = { stable_id = "30451107" } },
|
||||
stored, 1, 1, function() end
|
||||
)
|
||||
Assert.eq(denied, "京东读书网页协议读不到本章,请在京东读书 App 内阅读")
|
||||
Toc.read, Toc.put = orig_read, orig_put
|
||||
end
|
||||
|
||||
-- getProgressAsync:目录未缓存时拉到目录后仍按章节标题兜底(JD chapter_id 对不上本地 uid)
|
||||
do
|
||||
local Toc = require("source.toc")
|
||||
local orig_read, orig_put, orig_index = Toc.read, Toc.put, Toc.index
|
||||
local stored
|
||||
Toc.read = function() return stored end
|
||||
Toc.put = function(_, _, list) stored = list; return true end
|
||||
Toc.index = function() return nil end
|
||||
fake_client.getProgressAsync = function(_, _, cb)
|
||||
cb({ data = { { list = { {
|
||||
data_type = 0, version = 2, percent = 0.4,
|
||||
epub_chapter_title = "第二章", chapter_id = "jd-998",
|
||||
} } } } })
|
||||
return { cancel = function() end }
|
||||
end
|
||||
fake_client.catalogAsync = function(_, _, cb)
|
||||
cb({ data = { format = "epub", chapter_info = {
|
||||
{ chapter_index = 0, chapter_name = "第一章" },
|
||||
{ chapter_index = 1, chapter_name = "第二章" },
|
||||
} } })
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local pos
|
||||
Jdread.new():getProgressAsync({ source_id = "ext.jdread", stable_id = "30451107" }, function(v) pos = v end)
|
||||
require("support.stubs").flush()
|
||||
Assert.eq(pos.chapter_idx, 2)
|
||||
Assert.eq(pos.extra.chapter_idx, 2)
|
||||
|
||||
-- 目录已缓存但 uid、标题都对不上:只定位一次,不再空转拉目录
|
||||
stored = { { idx = 1, uid = "0", title = "第一章", toc_version = 5 } }
|
||||
local catalog_calls = 0
|
||||
fake_client.catalogAsync = function(_, _, cb)
|
||||
catalog_calls = catalog_calls + 1
|
||||
cb(nil, "should not fetch")
|
||||
return { cancel = function() end }
|
||||
end
|
||||
pos = nil
|
||||
Jdread.new():getProgressAsync({ source_id = "ext.jdread", stable_id = "30451107" }, function(v) pos = v end)
|
||||
require("support.stubs").flush()
|
||||
Assert.eq(catalog_calls, 0)
|
||||
Assert.eq(pos.fraction, 0.4)
|
||||
Assert.is_nil(pos.chapter_idx)
|
||||
Toc.read, Toc.put, Toc.index = orig_read, orig_put, orig_index
|
||||
end
|
||||
|
||||
-- putProgressAsync:章节 uid 取自目录;缺章节号直接失败,不把进度推到第 1 章
|
||||
do
|
||||
local Toc = require("source.toc")
|
||||
local orig_read = Toc.read
|
||||
Toc.read = function()
|
||||
return {
|
||||
{ idx = 1, uid = "0", title = "第一章", toc_version = 5 },
|
||||
{ idx = 2, uid = "1", title = "第二章" },
|
||||
}
|
||||
end
|
||||
local marker
|
||||
fake_client.putProgressAsync = function(_, _, m, cb)
|
||||
marker = m
|
||||
cb({ result_code = 0 })
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local src = Jdread.new()
|
||||
local identity = { source_id = "ext.jdread", stable_id = "30451107" }
|
||||
local ok, err
|
||||
src:putProgressAsync(identity, { fraction = 0.5, chapter_idx = 2 }, function(v, e) ok, err = v, e end)
|
||||
Assert.is_true(ok)
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(marker.chapter_id, "1")
|
||||
Assert.eq(marker.epub_chapter_title, "第二章")
|
||||
Assert.eq(marker.percent, 0.5)
|
||||
|
||||
marker, ok, err = nil, nil, nil
|
||||
src:putProgressAsync(identity, { fraction = 0.5 }, function(v, e) ok, err = v, e end)
|
||||
Assert.is_nil(ok)
|
||||
Assert.eq(err, "缺少章节信息")
|
||||
Assert.is_nil(marker)
|
||||
|
||||
src:putProgressAsync(identity, { fraction = 0.5, chapter_idx = 9 }, function(v, e) ok, err = v, e end)
|
||||
Assert.eq(err, "缺少章节信息")
|
||||
Assert.is_nil(marker)
|
||||
Toc.read = orig_read
|
||||
end
|
||||
|
||||
-- 封面章:网页版只给空 body,用目录首章挂的封面图补成一页
|
||||
do
|
||||
local Toc = require("source.toc")
|
||||
local orig_read = Toc.read
|
||||
Toc.read = function()
|
||||
return { { idx = 1, uid = "0", title = "封面", toc_version = 5, cover = "https://img.test/c.jpg" } }
|
||||
end
|
||||
fake_client.downloadChapterAsync = function(_, _, _, cb)
|
||||
cb({ data = { content_type = "epub", chapter = { {
|
||||
content = '<?xml version="1.0"?><html><head><title>Cover</title></head><body></body></html>',
|
||||
} } } })
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local html
|
||||
require("source.chapter").prefetchAsync = function(identity, _, toc, _, _, opts, cb)
|
||||
opts.fetchContent(identity, toc[1], function(payload) html = payload.html; cb() end)
|
||||
return { cancel = function() end }
|
||||
end
|
||||
require("source.assets").localizeAsync = function(raw, _, _, done) done(raw) end
|
||||
Jdread.new():prefetchChaptersAsync(
|
||||
{ source_id = "ext.jdread", stable_id = "30982479", book = { stable_id = "30982479" } },
|
||||
{ { idx = 1, uid = "0", title = "封面" } }, 1, 1, function() end
|
||||
)
|
||||
Assert.eq(html, '<p><img src="https://img.test/c.jpg"/></p>')
|
||||
Toc.read = orig_read
|
||||
end
|
||||
|
||||
-- 开书迁移:旧版目录(版本 2)章数和新目录不同,章节文件章号错位,清整本缓存后再开;
|
||||
-- 章数相同保留缓存;目录已是新版不发请求
|
||||
do
|
||||
local Toc = require("source.toc")
|
||||
local orig_read, orig_put = Toc.read, Toc.put
|
||||
local Chapter = require("source.chapter")
|
||||
local orig_open = Chapter.openWithUi
|
||||
local old
|
||||
Toc.read = function() return old end
|
||||
Toc.put = function() return true end
|
||||
local cleared, catalog_calls, opened = {}, 0, 0
|
||||
require("book.store").clearCache = function(_, stable_id)
|
||||
cleared[#cleared + 1] = stable_id
|
||||
return true
|
||||
end
|
||||
fake_client.catalogAsync = function(_, _, cb)
|
||||
catalog_calls = catalog_calls + 1
|
||||
cb({ data = { format = "epub", chapter_info = {
|
||||
{ chapter_index = 0, chapter_name = "封面", chapter_uri = "Text/titlepage.xhtml", is_try = true, is_buy = true },
|
||||
{ chapter_index = 1, chapter_name = "三盏灯", chapter_uri = "Text/a-CD.html", is_try = false, is_buy = true },
|
||||
{ chapter_index = 2, chapter_name = "1", chapter_uri = "Text/a.html#id_1", anchor = "id_1",
|
||||
is_try = true, is_buy = true },
|
||||
} } })
|
||||
return { cancel = function() end }
|
||||
end
|
||||
Chapter.openWithUi = function()
|
||||
opened = opened + 1
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local identity = { source_id = "ext.jdread", stable_id = "30982479" }
|
||||
local src = Jdread.new()
|
||||
|
||||
old = {
|
||||
{ idx = 1, uid = "0", title = "封面", toc_version = 2 },
|
||||
{ idx = 2, uid = "1", title = "三盏灯" },
|
||||
{ idx = 3, uid = "2", title = "1" },
|
||||
}
|
||||
src:openBookAsync(identity, nil, function() end)
|
||||
Assert.eq(catalog_calls, 1)
|
||||
Assert.eq(table.concat(cleared, ","), "30982479")
|
||||
Assert.eq(opened, 1)
|
||||
|
||||
old = { { idx = 1, uid = "0", title = "封面", toc_version = 2 }, { idx = 2, uid = "1", title = "三盏灯" } }
|
||||
src:openBookAsync(identity, nil, function() end)
|
||||
Assert.eq(catalog_calls, 2)
|
||||
Assert.len(cleared, 1)
|
||||
Assert.eq(opened, 2)
|
||||
|
||||
-- v4 已按文件成章、只缺锚点:重拉补小节,章号不变,缓存照用
|
||||
old = { { idx = 1, uid = "0", title = "封面", toc_version = 4 }, { idx = 2, uid = "1", title = "三盏灯" } }
|
||||
src:openBookAsync(identity, nil, function() end)
|
||||
Assert.eq(catalog_calls, 3)
|
||||
Assert.len(cleared, 1)
|
||||
Assert.eq(opened, 3)
|
||||
|
||||
old = { { idx = 1, uid = "0", title = "封面", toc_version = 5 }, { idx = 2, uid = "1", title = "三盏灯" } }
|
||||
src:openBookAsync(identity, nil, function() end)
|
||||
Assert.eq(catalog_calls, 3)
|
||||
Assert.len(cleared, 1)
|
||||
Assert.eq(opened, 4)
|
||||
|
||||
Toc.read, Toc.put, Chapter.openWithUi = orig_read, orig_put, orig_open
|
||||
end
|
||||
|
||||
-- 书城浏览:榜单类别 / 榜单 / 周期 / 分类四行 chip,菜单每次现取(缓存归数据获取层)
|
||||
do
|
||||
local calls, types_calls = {}, 0
|
||||
fake_client.rankTypesAsync = function(_, cb)
|
||||
types_calls = types_calls + 1
|
||||
cb({ data = {
|
||||
{ name = "出版", type = 1, kinds = {
|
||||
{ name = "畅销榜", kind = 1, periods = { { name = "周榜", period = "week" }, { name = "总榜", period = "all" } } },
|
||||
{ name = "飙升榜", kind = 6, periods = { { name = "周榜", period = "week" } } },
|
||||
} },
|
||||
{ name = "男生", type = 2, kinds = { { name = "人气榜", kind = 13, periods = { { name = "周榜", period = "week" } } } } },
|
||||
} })
|
||||
return { cancel = function() end }
|
||||
end
|
||||
fake_client.categoriesAsync = function(_, cb)
|
||||
cb({ data = { category_list = {
|
||||
{ show_name = "出版", sub_category = { { id = 10846, name = "经济管理" } } },
|
||||
{ show_name = "男生", sub_category = { { id = 10944, name = "玄幻频道" } } },
|
||||
} } })
|
||||
return { cancel = function() end }
|
||||
end
|
||||
fake_client.rankAsync = function(_, kind, period, cat, page, size, cb)
|
||||
calls[#calls + 1] = table.concat({ kind, period, cat, page, size }, ",")
|
||||
cb({ data = { { ebook_id = 1, name = "书" } } })
|
||||
return { cancel = function() end }
|
||||
end
|
||||
|
||||
local src = Jdread.new()
|
||||
local res
|
||||
local handle = src:browseAsync({}, function(r) res = r end)
|
||||
Assert.eq(type(handle.cancel), "function")
|
||||
Assert.eq(calls[1], "1,week,,1,20")
|
||||
Assert.len(res.data, 1)
|
||||
Assert.len(res.groups, 4)
|
||||
Assert.eq(res.groups[2].active, "1:1:week:")
|
||||
Assert.eq(res.groups[1].active, "1:1:week:")
|
||||
|
||||
src:browseAsync({ node = "1:1:all:10846" }, function(r) res = r end)
|
||||
Assert.eq(calls[#calls], "1,all,10846,1,20")
|
||||
Assert.eq(res.groups[4].active, "1:1:all:10846")
|
||||
|
||||
-- 切到只有一个周期的男生榜:周期行不出现,分类换成男生的
|
||||
src:browseAsync({ node = "2:13:week:10944" }, function(r) res = r end)
|
||||
Assert.len(res.groups, 3)
|
||||
Assert.eq(res.groups[3].chips[2].title, "玄幻频道")
|
||||
Assert.eq(types_calls, 3, "源不留菜单缓存,每次浏览都现取")
|
||||
|
||||
-- 再次切榜单:返回的句柄仍能取消当前在途请求(菜单两个请求先行、同步回完才发榜单请求)。
|
||||
local cancelled = 0
|
||||
fake_client.rankAsync = function()
|
||||
return { cancel = function() cancelled = cancelled + 1 end }
|
||||
end
|
||||
for _, node in ipairs({ "1:1:all:10846", "2:13:week:10944" }) do
|
||||
handle = src:browseAsync({ node = node }, function() error("请求尚未完成") end)
|
||||
Assert.eq(type(handle.cancel), "function")
|
||||
handle:cancel()
|
||||
end
|
||||
Assert.eq(cancelled, 2)
|
||||
Assert.eq(types_calls, 5)
|
||||
end
|
||||
|
||||
-- 书城搜索:product_search_infos 映射成 Book,源因此出现在书城来源下拉里
|
||||
do
|
||||
fake_client.searchAsync = function(_, keyword, page, size, cb)
|
||||
Assert.eq(keyword .. page .. size, "斗120")
|
||||
cb({ data = { product_search_infos = { { product_id = 7, product_name = "斗破", author = "土豆", content_info = "简介" } } } })
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local res
|
||||
Jdread.new():searchAsync("斗", function(r) res = r end)
|
||||
Assert.eq(res.data[1].stable_id, "7")
|
||||
Assert.eq(res.data[1].title, "斗破")
|
||||
Assert.eq(res.data[1].intro, "简介")
|
||||
end
|
||||
@@ -0,0 +1,248 @@
|
||||
--[[--
|
||||
京东读书 wire 映射离线用例。
|
||||
|
||||
@module tests.moonsource_jdread.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")
|
||||
local Mapper = require("moonsource_jdread.mapper")
|
||||
|
||||
-- ebooks/lite 真实行(抓包)
|
||||
do
|
||||
local books = Mapper.shelfList({
|
||||
{
|
||||
ebook_id = 30451107,
|
||||
name = "H5匠人手册:霸屏H5实战解密",
|
||||
author = "网易传媒设计中心",
|
||||
image_url = "https://img10.360buyimg.com/n12/s280x280_jfs/t1/fb9d03bd56331f5d.jpg.dpg",
|
||||
format = "epub",
|
||||
cate_second_names = { "计算机" },
|
||||
cate_third_names = { "程序设计" },
|
||||
},
|
||||
{ ebook_id = 30394360, name = "无封面无分类" },
|
||||
})
|
||||
Assert.len(books, 2)
|
||||
Assert.eq(books[1].source_id, "ext.jdread")
|
||||
Assert.eq(books[1].stable_id, "30451107")
|
||||
Assert.eq(books[1].title, "H5匠人手册:霸屏H5实战解密")
|
||||
Assert.eq(books[1].authors, "网易传媒设计中心")
|
||||
Assert.eq(books[1].category, "程序设计")
|
||||
Assert.eq(books[1].cover, "https://img10.360buyimg.com/n12/s280x280_jfs/t1/fb9d03bd56331f5d.jpg")
|
||||
Assert.is_nil(books[1].percent)
|
||||
Assert.is_nil(books[2].cover)
|
||||
Assert.is_nil(books[2].category)
|
||||
end
|
||||
|
||||
do
|
||||
Assert.len(Mapper.shelfList({}), 0)
|
||||
end
|
||||
|
||||
-- 旧 cread wire 不再识别
|
||||
do
|
||||
Assert.is_nil(Mapper.chapters({
|
||||
catalogList = {{ sort = 1, catalogId = 11, catalogName = "第一章", level = 0 }},
|
||||
}))
|
||||
Assert.is_nil(Mapper.content({ contentList = {{ content = "<p>一</p>" }} }, "标题"))
|
||||
end
|
||||
|
||||
do
|
||||
local payload = Mapper.content({
|
||||
data = {
|
||||
chapter = {
|
||||
{ content = "<html><body><p>一</p></body></html>" },
|
||||
{ content = "<p>二</p>" },
|
||||
},
|
||||
},
|
||||
}, "标题")
|
||||
Assert.eq(payload.title, "标题")
|
||||
Assert.matches(payload.html, "<p>一</p>")
|
||||
Assert.matches(payload.html, "<p>二</p>")
|
||||
end
|
||||
|
||||
do
|
||||
local toc = Mapper.chapters({
|
||||
data = {
|
||||
format = "epub",
|
||||
chapter_info = {
|
||||
{ chapter_index = 0, chapter_name = "封面", chapter_id = "" },
|
||||
{ chapter_index = 1, chapter_name = "版权信息", chapter_id = "" },
|
||||
},
|
||||
},
|
||||
})
|
||||
Assert.len(toc, 2)
|
||||
Assert.eq(toc[1].uid, "0")
|
||||
Assert.eq(toc[1].toc_version, 5)
|
||||
Assert.eq(toc[2].title, "版权信息")
|
||||
end
|
||||
|
||||
-- 《三盏灯》真实目录(抓包):正文一个文件,小节 1~9 只是锚点;试读版 x.html 与完整版 x-CD.html 同一文件。
|
||||
-- 按文件成章,已购取完整版下标;封面图挂首章
|
||||
do
|
||||
local rows = {
|
||||
{ chapter_index = 0, chapter_name = "封面", chapter_item = "titlepage", is_try = true, is_buy = true,
|
||||
chapter_uri = "Text/titlepage.xhtml" },
|
||||
{ chapter_index = 1, chapter_name = "版权信息", chapter_item = "id22", is_try = true, is_buy = true,
|
||||
chapter_uri = "Text/index_split_000.html" },
|
||||
{ chapter_index = 2, chapter_name = "三盏灯", chapter_item = "id21", is_try = false, is_buy = true,
|
||||
chapter_uri = "Text/index_split_001-CD.html" },
|
||||
{ chapter_index = 3, chapter_name = "1", chapter_item = "id21", anchor = "id_1", is_try = true, is_buy = true,
|
||||
chapter_uri = "Text/index_split_001.html#id_1" },
|
||||
{ chapter_index = 4, chapter_name = "2", chapter_item = "id21", anchor = "id_2", is_try = true, is_buy = true,
|
||||
chapter_uri = "Text/index_split_001.html#id_2" },
|
||||
}
|
||||
for i = 5, 11 do
|
||||
rows[#rows + 1] = { chapter_index = i, chapter_name = tostring(i - 2), chapter_item = "id21",
|
||||
anchor = "id_" .. (i - 2), is_try = false, is_buy = true,
|
||||
chapter_uri = "Text/index_split_001-CD.html#id_" .. (i - 2) }
|
||||
end
|
||||
local toc = Mapper.chapters({ data = {
|
||||
format = "epub",
|
||||
image_url = "https://img10.360buyimg.com/n12/s280x280_jfs/cover.jpg.dpg",
|
||||
chapter_info = rows,
|
||||
} })
|
||||
Assert.len(toc, 3)
|
||||
Assert.eq(toc[1].title, "封面")
|
||||
Assert.eq(toc[1].cover, "https://img10.360buyimg.com/n12/s280x280_jfs/cover.jpg")
|
||||
Assert.eq(toc[2].uid, "1")
|
||||
Assert.eq(toc[3].title, "三盏灯")
|
||||
Assert.eq(toc[3].uid, "2")
|
||||
Assert.eq(toc[3].source_idx, "2")
|
||||
Assert.is_nil(toc[2].cover)
|
||||
Assert.is_nil(toc[2].anchors)
|
||||
-- 小节 1~9 挂成章内锚点,点选按 HTML id 定位
|
||||
Assert.len(toc[3].anchors, 9)
|
||||
Assert.eq(toc[3].anchors[1].title, "1")
|
||||
Assert.eq(toc[3].anchors[1].id, "id_1")
|
||||
Assert.eq(toc[3].anchors[1].depth, 2)
|
||||
Assert.eq(toc[3].anchors[9].id, "id_9")
|
||||
end
|
||||
|
||||
-- 未购买:组内只有试读行可下,取首个试读版;同文件不带锚点的重复行丢弃
|
||||
do
|
||||
local toc = Mapper.chapters({ data = { format = "epub", chapter_info = {
|
||||
{ chapter_index = 0, chapter_name = "正文", chapter_uri = "Text/a-CD.html", is_try = false, is_buy = false },
|
||||
{ chapter_index = 1, chapter_name = "1", chapter_uri = "Text/a.html#id_1", anchor = "id_1",
|
||||
is_try = true, is_buy = false },
|
||||
{ chapter_index = 2, chapter_name = "重复", chapter_uri = "Text/a.html", is_try = true, is_buy = false },
|
||||
{ chapter_index = 3, chapter_name = "后记", chapter_uri = "Text/b.html", is_try = false, is_buy = false },
|
||||
} } })
|
||||
Assert.len(toc, 2)
|
||||
Assert.eq(toc[1].uid, "1")
|
||||
Assert.len(toc[1].anchors, 1, "不带锚点的重复行不进章内目录")
|
||||
Assert.eq(toc[2].title, "后记")
|
||||
Assert.eq(toc[2].uid, "3")
|
||||
end
|
||||
|
||||
-- 封面页空 body:给了封面图就补图,没给保持原样(空串,交给落盘报错)
|
||||
do
|
||||
local wire = { data = { chapter = { { content = "<html><body></body></html>" } } } }
|
||||
Assert.eq(Mapper.content(wire, "封面", 'https://img.test/a"b.jpg').html, '<p><img src="https://img.test/a"b.jpg"/></p>')
|
||||
Assert.eq(Mapper.content(wire, "封面").html, "")
|
||||
local text = Mapper.content({ data = { chapter = { { content = "<html><body><p>正文</p></body></html>" } } } },
|
||||
"正文", "https://img.test/a.jpg")
|
||||
Assert.matches(text.html, "<p>正文</p>")
|
||||
Assert.is_nil(text.html:find("img", 1, true))
|
||||
end
|
||||
|
||||
do
|
||||
local payload = Mapper.content({
|
||||
data = {
|
||||
chapter = {{
|
||||
chapter_index = 0,
|
||||
content = '<?xml version="1.0"?><html><body><p>试读</p></body></html>',
|
||||
}},
|
||||
},
|
||||
}, "封面")
|
||||
Assert.eq(payload.title, "封面")
|
||||
Assert.matches(payload.html, "<p>试读</p>")
|
||||
end
|
||||
|
||||
do
|
||||
Assert.is_nil(Mapper.content({
|
||||
data = { chapter = {{ chapter_index = 14, can_read = false, content = "" }} },
|
||||
}, "锁章"))
|
||||
end
|
||||
|
||||
-- txt 网文 v2 目录:卷标题(type 0,无 chapter_id)不成章,uid = chapter_id
|
||||
do
|
||||
local toc = Mapper.chapters({
|
||||
data = {
|
||||
format = "txt",
|
||||
chapter_info = {
|
||||
{ chapter_name = "庆安才子", type = 0, volume_id = "v1", is_try = true },
|
||||
{ chapter_id = "15001647875062768", chapter_name = "第一章 俊俏少年", type = 1 },
|
||||
{ chapter_id = "15017997720337259", chapter_name = "", type = 1 },
|
||||
{ chapter_name = "第二卷", type = 0, volume_id = "v2" },
|
||||
{ chapter_id = "15039236894456722", chapter_name = "第三章 压寨相公!", type = 1 },
|
||||
},
|
||||
},
|
||||
})
|
||||
Assert.len(toc, 3)
|
||||
Assert.eq(toc[1].toc_version, 3)
|
||||
Assert.eq(toc[1].uid, "15001647875062768")
|
||||
Assert.eq(toc[1].title, "第一章 俊俏少年")
|
||||
Assert.eq(toc[2].title, "第2章")
|
||||
Assert.eq(toc[3].idx, 3)
|
||||
Assert.eq(toc[3].uid, "15039236894456722")
|
||||
end
|
||||
|
||||
do
|
||||
Assert.is_nil(Mapper.chapters({
|
||||
data = { format = "txt", chapter_info = {{ chapter_name = "卷", type = 0, volume_id = "v" }} },
|
||||
}))
|
||||
end
|
||||
|
||||
-- txt 网文正文 content_type=net:\r\n 纯文本分段、转义;
|
||||
-- 京东原文首段无缩进、后续段带全角缩进,统一剥掉交给模板 text-indent
|
||||
do
|
||||
local payload = Mapper.content({
|
||||
data = {
|
||||
ebook_id = 34265072,
|
||||
content_type = "net",
|
||||
chapter = {{
|
||||
chapter_index = -1,
|
||||
chapter_id = "503000000013072393",
|
||||
content = "辽人入京<关我>鸟事。\r\n\r\n 旁边一个中年胖子眼睛一亮。\r\n 石小凡有些挠头。",
|
||||
can_read = true,
|
||||
}},
|
||||
},
|
||||
}, "第一章 楔子")
|
||||
Assert.eq(payload.title, "第一章 楔子")
|
||||
Assert.eq(payload.html,
|
||||
"<p>辽人入京<关我>鸟事。</p>\n<p>旁边一个中年胖子眼睛一亮。</p>\n<p>石小凡有些挠头。</p>")
|
||||
end
|
||||
|
||||
do
|
||||
local payload = Mapper.content({
|
||||
data = {
|
||||
chapter = {{
|
||||
content = '<html><body><p class="img_content">'
|
||||
.. '<img alt="" src="https://img30.360buyimg.com/ebookadmin/jfs/x.jpg" '
|
||||
.. 'href="./image/Images/x.jpg"/></p></body></html>',
|
||||
}},
|
||||
},
|
||||
}, "插图")
|
||||
Assert.matches(payload.html, 'src="https://img30.360buyimg.com/ebookadmin/jfs/x.jpg"')
|
||||
Assert.matches(payload.html, 'href="./image/Images/x.jpg"')
|
||||
end
|
||||
|
||||
do
|
||||
local pos, uid = Mapper.progress({
|
||||
data = {{
|
||||
list = {
|
||||
{ data_type = 1, percent = 0.9, chapter_id = "note", version = 20 },
|
||||
{
|
||||
data_type = 0,
|
||||
percent = 0.25,
|
||||
chapter_id = 12,
|
||||
epub_chapter_title = "第二节",
|
||||
version = 21,
|
||||
},
|
||||
},
|
||||
}},
|
||||
})
|
||||
Assert.eq(pos.fraction, 0.25)
|
||||
Assert.eq(pos.chapter_title, "第二节")
|
||||
Assert.eq(uid, "12")
|
||||
end
|
||||
@@ -0,0 +1,72 @@
|
||||
--[[--
|
||||
京东读书双 MD5 签名与下载 AES 离线用例。
|
||||
|
||||
@module tests.moonsource_jdread.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")
|
||||
|
||||
package.preload["json"] = function()
|
||||
return {
|
||||
decode = require("support.json_stub").decode,
|
||||
encode = require("support.json_stub").encode,
|
||||
}
|
||||
end
|
||||
package.loaded["json"] = nil
|
||||
package.loaded["moonsource_jdread.protocol"] = nil
|
||||
|
||||
local Protocol = require("moonsource_jdread.protocol")
|
||||
|
||||
do
|
||||
local params = Protocol.signedParams(
|
||||
"/jdread/api/marker/sync",
|
||||
"h500000000000000000000000000000000",
|
||||
nil,
|
||||
1700000000123
|
||||
)
|
||||
Assert.eq(params.sign, "6f219d40caff3860cb21cebbfb9ce5c7")
|
||||
end
|
||||
|
||||
do
|
||||
Assert.eq(Protocol.evenTime(1700000000001), 1700000000002)
|
||||
Assert.eq(Protocol.evenTime(1700000000000), 1700000000000)
|
||||
local tm = 1700000000000
|
||||
local query = "app=jdread-m&tm=1700000000000&uuid=h5-test"
|
||||
local enc = Protocol.encryptQuery(query, tm)
|
||||
Assert.is_true(enc:find("[-_A-Za-z0-9]+") ~= nil)
|
||||
Assert.is_nil(enc:find("+", 1, true))
|
||||
Assert.is_nil(enc:find("/", 1, true))
|
||||
local function encrypted(json)
|
||||
return require("utils.text").base64Encode(
|
||||
require("crypto.aes").ecb_encrypt(
|
||||
json,
|
||||
(require("ffi/sha2").md5(tostring(tm) .. "jdread-m"):gsub("(%x%x)", function(pair)
|
||||
return string.char(tonumber(pair, 16))
|
||||
end))
|
||||
)
|
||||
)
|
||||
end
|
||||
local wire, err = Protocol.decodeDownload(
|
||||
encrypted('{"data":{"chapter":[{"content":"<p>一</p>"}]},"result_code":0,"message":"SUCCESS"}'),
|
||||
tm
|
||||
)
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(wire.data.chapter[1].content, "<p>一</p>")
|
||||
|
||||
-- 网页阅读器实测:未购买章节的错误信封同样被加密
|
||||
local denied, denied_err, code = Protocol.decodeDownload(
|
||||
encrypted('{"result_code":101,"message":"can not download"}'),
|
||||
tm
|
||||
)
|
||||
Assert.is_nil(denied)
|
||||
Assert.eq(denied_err, "can not download")
|
||||
Assert.eq(code, 101)
|
||||
end
|
||||
|
||||
do
|
||||
local wire, err, code = Protocol.decodeDownload('{"result_code":1,"message":"UNKNOWN_ERROR"}', 1)
|
||||
Assert.is_nil(wire)
|
||||
Assert.eq(err, "UNKNOWN_ERROR")
|
||||
Assert.eq(code, 1)
|
||||
end
|
||||
@@ -0,0 +1,61 @@
|
||||
--[[-- 京东书评:匿名请求、字段语义、坏响应与离线缓存。 @module tests.moonsource_jdread.reviews_spec --]]
|
||||
local Assert = require("support.assert")
|
||||
local Stubs = require("support.stubs")
|
||||
local JSON = require("support.json_stub")
|
||||
package.loaded.json = JSON
|
||||
local connected, requests, fail = true, {}, false
|
||||
package.loaded["ui/network/manager"] = { isConnected = function() return connected end }
|
||||
package.loaded["http.request"] = {
|
||||
get = function(url, opts, cb)
|
||||
requests[#requests + 1] = { url = url, opts = opts }
|
||||
if fail then cb(nil, "network failed")
|
||||
else cb(JSON.encode({ result_code = 0, data = { total = 21, ebook_comment_infos = {
|
||||
{ id = 1, nickname = "Reader", comment = "Review", created = 1735732800000,
|
||||
like_count = 4, comment_rate = 5 },
|
||||
} } })) end
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
local Source = require("moonsource_jdread.source").new()
|
||||
Source._client.cookie, Source._client.uuid = "test-cookie", "test-uuid"
|
||||
local Mapper = require("moonsource_jdread.mapper")
|
||||
local identity = { source_id = "ext.jdread", stable_id = "review-test", chapter_idx = 1 }
|
||||
---@type table|nil
|
||||
local page
|
||||
local err
|
||||
Source:bookReviewsAsync(identity, function(value, reason) page, err = value, reason end)
|
||||
Assert.is_nil(err)
|
||||
Assert.len(page.items, 1)
|
||||
Assert.eq(page.items[1].id, "1")
|
||||
Assert.eq(page.items[1].text, "Review")
|
||||
Assert.eq(page.items[1].grade, 5)
|
||||
Assert.eq(page.items[1].likes, 4)
|
||||
Assert.eq(page.items[1].time, os.date("%Y-%m-%d", 1735732800))
|
||||
Assert.eq(page.total, 21)
|
||||
Assert.eq(page.title, "书评预览")
|
||||
Assert.is_nil(requests[1].opts.headers.Cookie)
|
||||
Assert.eq(Source._client.cookie, "test-cookie")
|
||||
Assert.matches(requests[1].url, "/ebook/review%-test/comment%?")
|
||||
connected = false
|
||||
identity.chapter_idx = 9
|
||||
---@type table|nil
|
||||
local cached_page
|
||||
Source:bookReviewsAsync(identity, function(value, reason) cached_page, err = value, reason end)
|
||||
Stubs.flush()
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(cached_page.items[1].text, "Review", "整书缓存不随章节复制")
|
||||
Assert.len(requests, 1)
|
||||
connected, fail = true, true
|
||||
Source:bookReviewsAsync(identity, function(value, reason) page, err = value, reason end)
|
||||
Assert.is_nil(page)
|
||||
Assert.eq(err, "network failed", "联网失败不伪装成旧书评成功")
|
||||
local empty = Mapper.bookReviewPage({ data = { total = 0, ebook_comment_infos = {} } })
|
||||
Assert.len(empty.items, 0)
|
||||
for _idx, wire in ipairs({
|
||||
{}, { data = { total = "bad", ebook_comment_infos = {} } },
|
||||
{ data = { total = 1, ebook_comment_infos = { { comment = "missing id" } } } },
|
||||
}) do
|
||||
local value, reason = Mapper.bookReviewPage(wire)
|
||||
Assert.is_nil(value)
|
||||
Assert.eq(reason, "京东读书响应无效")
|
||||
end
|
||||
@@ -0,0 +1,173 @@
|
||||
--[[--
|
||||
京东扫码登录对话框:点击即出占位框,任何方式关框都取消在飞的取码/轮询。
|
||||
|
||||
@module tests.moonsource_jdread.setting_spec
|
||||
--]]
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local Themed = require("support.theme_stubs")
|
||||
Themed.install()
|
||||
|
||||
package.preload["ui/widget/container/centercontainer"] = function()
|
||||
return { new = function(_, o) return { content = o[1] } end }
|
||||
end
|
||||
package.preload["ui/geometry"] = function() return { new = function(_, o) return o end } end
|
||||
package.preload["device"] = function()
|
||||
return { screen = { getWidth = function() return 600 end, getHeight = function() return 800 end } }
|
||||
end
|
||||
package.preload["ui.themes.widgets.text"] = function()
|
||||
return { box = function(_, text, width) return { text = text, width = width } end }
|
||||
end
|
||||
package.preload["ui.themes"] = function()
|
||||
return { current = function() return { dialog = { bg = 0 } } end }
|
||||
end
|
||||
local invalidated
|
||||
package.preload["ui.themes.widgets.image"] = function()
|
||||
return {
|
||||
widget = function(o) return { src = o.src } end,
|
||||
invalidate = function(path) invalidated = path end,
|
||||
}
|
||||
end
|
||||
package.preload["ui/network/manager"] = function()
|
||||
return { runWhenConnected = function(_, fn) fn() end }
|
||||
end
|
||||
package.preload["ui.themes.widgets.row"] = function()
|
||||
return { widget = function(opts) return opts end }
|
||||
end
|
||||
|
||||
local begin_cb, wait_cb, complete_cb, browser_payload
|
||||
local begin_cancels, wait_cancels, begin_count = 0, 0, 0
|
||||
local has_session, cleared = false, false
|
||||
local reloads = 0
|
||||
package.loaded["source.registry"] = {
|
||||
invalidate = function() end,
|
||||
reload = function() reloads = reloads + 1 end,
|
||||
}
|
||||
package.preload["utils.device_id"] = function()
|
||||
return { ensure = function() return "jd-browser-test-device" end }
|
||||
end
|
||||
package.preload["moonsource_jdread.auth"] = function()
|
||||
return {
|
||||
hasSession = function() return has_session end,
|
||||
clearSession = function() cleared = true; has_session = false end,
|
||||
userLabel = function() return nil end,
|
||||
beginQrLoginAsync = function(cb)
|
||||
begin_count = begin_count + 1
|
||||
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,
|
||||
completeQrLoginAsync = function(_, cb)
|
||||
complete_cb = cb
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
importBrowserAsync = function(payload, cb)
|
||||
cb(payload == browser_payload)
|
||||
end,
|
||||
}
|
||||
end
|
||||
|
||||
--- 对话框正文(二维码 / 占位字)。
|
||||
local function content(sheet)
|
||||
return sheet.items[1].widget(500).content
|
||||
end
|
||||
|
||||
package.loaded["moonsource_jdread.setting"] = nil
|
||||
local Setting = require("moonsource_jdread.setting")
|
||||
local login = Setting.rows()[1]().callback
|
||||
|
||||
browser_payload = {}
|
||||
Assert.eq(Setting.browser.domain, "e.m.jd.com")
|
||||
Assert.eq(Setting.browser.scope, "cookie")
|
||||
Assert.matches(Setting.browser.check(), "^https://e%.m%.jd%.com/jdread/api/bookshelf/sort%?")
|
||||
Assert.eq(Setting.browser.check_json.path, "result_code")
|
||||
Assert.eq(Setting.browser.check_json.ok[1], 0)
|
||||
local browser_ok
|
||||
Setting.browser.apply(browser_payload, function(ok) browser_ok = ok end)
|
||||
Assert.is_true(browser_ok)
|
||||
Assert.eq(reloads, 1)
|
||||
Setting.browser.apply({}, function(ok) browser_ok = ok end)
|
||||
Assert.is_false(browser_ok)
|
||||
Assert.eq(reloads, 1, "失败授权不重建源实例")
|
||||
|
||||
-- 点击即同步出占位框盖住入口,不等取码网络往返。
|
||||
login()
|
||||
local placeholder = Themed.last("sheet")
|
||||
Assert.is_true(placeholder.shown)
|
||||
Assert.eq(content(placeholder).text, "正在获取二维码…")
|
||||
Assert.not_nil(begin_cb)
|
||||
|
||||
-- 取码途中点框外 / 返回键 / 取消按钮都是关窗:取消取码,回调迟到也不再弹二维码。
|
||||
placeholder:close()
|
||||
Assert.eq(begin_cancels, 1)
|
||||
begin_cb({ qr_path = "qr.png", token = "t", jar = {} })
|
||||
Assert.len(Themed.all("sheet"), 1)
|
||||
Assert.is_nil(wait_cb)
|
||||
|
||||
-- 二维码出来后换框(旧占位框关掉,不算取消),关新框取消轮询。
|
||||
login()
|
||||
placeholder = Themed.last("sheet")
|
||||
begin_cb({ qr_path = "qr.png", token = "t", jar = {} })
|
||||
local qr = Themed.last("sheet")
|
||||
Assert.is_true(placeholder.closed)
|
||||
Assert.eq(begin_cancels, 1, "代码换框不算用户取消")
|
||||
Assert.eq(content(qr).src, "qr.png")
|
||||
-- 每次登录都复用同一路径,不作废位图缓存会显示上一张已失效的码。
|
||||
Assert.eq(invalidated, "qr.png")
|
||||
Assert.not_nil(wait_cb)
|
||||
qr:close()
|
||||
Assert.eq(wait_cancels, 1)
|
||||
local sheets = #Themed.made
|
||||
wait_cb(nil, "迟到的失败", "error")
|
||||
Assert.eq(#Themed.made, sheets, "已取消的轮询不应再弹提示")
|
||||
|
||||
-- 取码失败:关掉占位框再提示。
|
||||
login()
|
||||
placeholder = Themed.last("sheet")
|
||||
begin_cb(nil, "获取失败")
|
||||
Assert.is_true(placeholder.closed)
|
||||
Assert.eq(Themed.last("toast").text, "获取失败")
|
||||
|
||||
-- 校验成功但没拿到会话:不自动换码,留框显示原因,点「重新获取二维码」才重来。
|
||||
login()
|
||||
begin_cb({ qr_path = "qr-old.png", token = "t", jar = {} })
|
||||
local begins = begin_count
|
||||
wait_cb({ ticket = "ticket", jar = {} }, nil, "ok")
|
||||
Assert.not_nil(complete_cb)
|
||||
complete_cb(nil, "登录未拿到会话 Cookie")
|
||||
Assert.eq(begin_count, begins, "失败后不自动换码")
|
||||
local failed = Themed.last("sheet")
|
||||
Assert.is_true(failed.shown)
|
||||
Assert.is_false(failed.closed == true)
|
||||
Assert.eq(content(failed).text, "登录未拿到会话 Cookie")
|
||||
local retry = failed.items[2]
|
||||
Assert.eq(retry.text, "重新获取二维码")
|
||||
-- 与真实 Sheet 一致:先关框再回调。
|
||||
failed:close()
|
||||
retry.callback()
|
||||
Assert.eq(begin_count, begins + 1)
|
||||
Assert.eq(content(Themed.last("sheet")).text, "正在获取二维码…")
|
||||
|
||||
-- 走真实退出入口,确保设置页提供源 id,确认后确实清凭证与该源本地记录。
|
||||
local cancelled, forgotten = {}, nil
|
||||
package.loaded["workers.tasks"] = {
|
||||
cancelPrefixed = function(prefix) cancelled[#cancelled + 1] = prefix end,
|
||||
}
|
||||
package.loaded["book.store"] = {
|
||||
forgetSource = function(id) forgotten = id; return true end,
|
||||
}
|
||||
has_session = true
|
||||
local rows = Setting.rows()
|
||||
Assert.len(rows, 3)
|
||||
Assert.eq(rows[2](300).title, "浏览器登录")
|
||||
rows[3](300).callback()
|
||||
Assert.is_false(cleared)
|
||||
Themed.last("confirm").ok_callback()
|
||||
Assert.is_true(cleared)
|
||||
Assert.eq(forgotten, "ext.jdread")
|
||||
Assert.eq(cancelled[1], "dirty\0ext.jdread")
|
||||
Assert.eq(reloads, 2)
|
||||
Assert.len(Setting.rows(), 2)
|
||||
@@ -0,0 +1,53 @@
|
||||
--[[--
|
||||
京东书架不完整快照:合法成员可更新,坏 ID 不能让缺席的本地书下架。
|
||||
|
||||
@module tests.moonsource_jdread.shelf_spec
|
||||
--]]
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local Config = require("support.config")
|
||||
local Stubs = require("support.stubs")
|
||||
local path = Config.dir() .. "/jdread-partial-shelf.sqlite3"
|
||||
for _idx, suffix in ipairs({ "", "-wal", "-shm" }) do os.remove(path .. suffix) end
|
||||
package.loaded["utils.paths"] = {
|
||||
dbPath = function() return path end,
|
||||
sanitizeSourceId = function(id) return id end,
|
||||
}
|
||||
local DB = require("utils.db")
|
||||
local BookDB = require("book.books_db")
|
||||
for idx = 1, 3 do
|
||||
Assert.is_true(BookDB.upsertRemote({
|
||||
source_id = "ext.jdread", stable_id = tostring(idx), title = "书" .. idx, deleted = 0,
|
||||
}))
|
||||
end
|
||||
local client = require("moonsource_jdread.client"):new{ cookie = "test", uuid = "test" }
|
||||
local partial = true
|
||||
function client:apiGetAsync(request_path, _query, cb)
|
||||
if request_path == "/jdread/api/bookshelf/sort" then
|
||||
local ids = partial and { { ebook_id = 1 }, { ebook_id = false }, { ebook_id = 3 } }
|
||||
or { { ebook_id = 1 }, { ebook_id = 3 } }
|
||||
cb({ data = { book_ids = ids } })
|
||||
else
|
||||
cb({ data = { { ebook_id = 1, name = "一" }, { ebook_id = 3, name = "三" } } })
|
||||
end
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local function sync()
|
||||
local result, reason
|
||||
require("source.shelf").syncAsync("ext.jdread", client, require("moonsource_jdread.mapper").shelfList,
|
||||
{ force = true }, function(value, err) result, reason = value, err end)
|
||||
Stubs.flush()
|
||||
Assert.is_nil(reason)
|
||||
Assert.not_nil(result)
|
||||
return result
|
||||
end
|
||||
local result = sync()
|
||||
Assert.eq(BookDB.get("ext.jdread", "1").title, "一", "合法成员照常更新")
|
||||
Assert.eq(BookDB.get("ext.jdread", "2").deleted, 0, "坏行不是远端明确移除")
|
||||
Assert.eq(result.hidden, 0)
|
||||
partial = false
|
||||
result = sync()
|
||||
Assert.eq(BookDB.get("ext.jdread", "2").deleted, 1, "完整快照仍按缺席下架")
|
||||
Assert.eq(result.hidden, 1)
|
||||
DB.close()
|
||||
for _idx, suffix in ipairs({ "", "-wal", "-shm" }) do os.remove(path .. suffix) end
|
||||
Reference in new issue
Block a user