✨ 初始提交:月读第三方书源插件集合
每个书源一个独立插件目录,含微信读书公众号订阅、书架导入等完整功能。 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,18 @@
|
|||||||
|
# 京东读书
|
||||||
|
|
||||||
|
| 能力 | 是否支持 | 备注 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 京东 App 扫码登录 | 部分支持 | 兑换后校验书架;需要安全验证时明确拒绝,尚不能在验证后续接原扫码会话 |
|
||||||
|
| 浏览器扩展登录 | 已实现,未实测 | 官网完成登录后回传;需要浏览器扩展握手 |
|
||||||
|
| 书架拉取 | 支持 | 读取排序并分批补齐详情 |
|
||||||
|
| 书架新增与移出 | 已实现,未实测 | 本地先生效,联网后推送,失败保留脏行或墓碑 |
|
||||||
|
| 搜索与书城 | 支持 | 搜索、分类及不同周期榜单 |
|
||||||
|
| 详情与目录 | 支持 | EPUB、TXT 网文目录,按源站分页获取 |
|
||||||
|
| 免费与已购正文 | 部分支持 | 受试读、购买和会员权限限制;真实账号阅读未完成实测 |
|
||||||
|
| 章节缓存与离线阅读 | 支持 | 仅已缓存内容,未缓存正文需要联网 |
|
||||||
|
| 阅读进度同步 | 部分支持 | 章节及全书比例;本地 HTML 不对应远端段落坐标 |
|
||||||
|
| 笔记与统计同步 | 不支持 | 仅本地保存 |
|
||||||
|
| 整书书评 | 部分支持 | 匿名首批 20 条预览,整书缓存不随切章复制;界面没有远端续页入口 |
|
||||||
|
| 章评、段评与回复 | 不支持 | 当前 Web 协议未找到可验证接口,不代表 App 不支持 |
|
||||||
|
| 评论写操作 | 不支持 | 不发评、不点赞、不删评 |
|
||||||
|
| 账号切换 | 不支持直接隔离 | 须先退出清理旧数据,未同步记录会丢失 |
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
local _ = require("gettext")
|
||||||
|
return {
|
||||||
|
fullname = _("月读书源:京东读书"),
|
||||||
|
description = _("给月读增加「京东读书」书源。需要同时安装月读,与平台官方无关。"),
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
--[[--
|
||||||
|
KOReader 只认带 main.lua 的插件目录;书源本身不需要任何插件钩子,月读读取旁边的 moon_source.lua。
|
||||||
|
--]]
|
||||||
|
local WidgetContainer = require("ui/widget/container/widgetcontainer")
|
||||||
|
|
||||||
|
return WidgetContainer:extend{
|
||||||
|
name = "moonsource_jdread",
|
||||||
|
is_doc_only = false,
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
--[[--
|
||||||
|
月读第三方书源描述:京东读书。契约见月读 examples/moonsource-demo.koplugin/moon_source.lua。
|
||||||
|
--]]
|
||||||
|
|
||||||
|
local function lazy(module)
|
||||||
|
return setmetatable({}, { __index = function(_, key) return require(module)[key] end })
|
||||||
|
end
|
||||||
|
|
||||||
|
return {
|
||||||
|
api = 1,
|
||||||
|
provides = { source = true },
|
||||||
|
meta = function() return require("moonsource_jdread.source").meta() end,
|
||||||
|
new = function() return require("moonsource_jdread.source").new() end,
|
||||||
|
setting = lazy("moonsource_jdread.setting"),
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
--[[--
|
||||||
|
书源元信息:id / 名称 / 类型,加上启用页展示用的说明与能力清单。`init.lua` 的 `meta()` 直接返回本表。
|
||||||
|
|
||||||
|
@module moonsource_jdread._meta
|
||||||
|
--]]
|
||||||
|
|
||||||
|
local _ = require("l10n").get("moonsource_jdread")
|
||||||
|
|
||||||
|
return {
|
||||||
|
id = "ext.jdread",
|
||||||
|
name = _("京东读书"),
|
||||||
|
type = "chapter",
|
||||||
|
description = _("京东读书书架与在线阅读"),
|
||||||
|
abilities = { _("搜索与发现"), _("书架同步"), _("进度同步"), _("书评") },
|
||||||
|
}
|
||||||
@@ -0,0 +1,536 @@
|
|||||||
|
--[[--
|
||||||
|
京东账号扫码登录:二维码 PNG → 状态轮询 → ticket 换取 .jd.com 会话。
|
||||||
|
|
||||||
|
@module koplugin.book.moonsource_jdread.auth
|
||||||
|
--]]
|
||||||
|
|
||||||
|
local JSON = require("json")
|
||||||
|
local Request = require("http.request")
|
||||||
|
local Image = require("utils.image")
|
||||||
|
local Text = require("utils.text")
|
||||||
|
local _ = require("l10n").get("moonsource_jdread")
|
||||||
|
local logger = require("utils.log")
|
||||||
|
|
||||||
|
local Auth = {}
|
||||||
|
|
||||||
|
local LOGIN_PAGE = "https://passport.jd.com/new/login.aspx?ReturnUrl=https%3A%2F%2Fe.m.jd.com%2F"
|
||||||
|
local HOME = "https://e.m.jd.com/"
|
||||||
|
local LOGIN_UA = Request.randomUA()
|
||||||
|
local QR_COOKIE_KEYS = { "QRCodeKey", "wlfstk_smdl", "guid" }
|
||||||
|
-- 候选会话 Cookie;是否登录仍须由书架 API 确认。
|
||||||
|
local LOGIN_COOKIE_KEYS = { "thor", "pt_key", "pin", "pt_pin" }
|
||||||
|
local MAX_HOPS = 5
|
||||||
|
local qr_seq = 0
|
||||||
|
local qr_file
|
||||||
|
|
||||||
|
-- qrCodeTicketValidation 的 returnCode 语义,取自官方 login.qrcode.2024.js。
|
||||||
|
local TICKET_ERRORS = {
|
||||||
|
[58] = "二维码已失效,请重新登录",
|
||||||
|
[59] = "二维码已失效,请重新登录",
|
||||||
|
[60] = "京东登录失败",
|
||||||
|
[70] = "京东登录失败",
|
||||||
|
[80] = "京东判定本次扫码存在风险,官方要求改用密码登录",
|
||||||
|
}
|
||||||
|
|
||||||
|
---@return table
|
||||||
|
local function cfg()
|
||||||
|
return require("utils.settings").getSource("ext.jdread")
|
||||||
|
end
|
||||||
|
|
||||||
|
---@param patch table
|
||||||
|
local function saveCfg(patch)
|
||||||
|
local Settings = require("utils.settings")
|
||||||
|
local current = Settings.getSource("ext.jdread")
|
||||||
|
for key, value in pairs(patch) do current[key] = value end
|
||||||
|
Settings.saveSource("ext.jdread", current)
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 全部 Set-Cookie 行:优先 Request.headerAll(Turbo 多值 / 合并行都拆好),否则退回单值读取。
|
||||||
|
---@param res table|nil
|
||||||
|
---@return string[]
|
||||||
|
local function setCookieLines(res)
|
||||||
|
if Request.headerAll then return Request.headerAll(res, "Set-Cookie") end
|
||||||
|
local values = Request.header(res, "Set-Cookie")
|
||||||
|
local out = {}
|
||||||
|
local split = require("http.request.header").splitSetCookie
|
||||||
|
for _idx, value in ipairs(type(values) == "table" and values or { values }) do
|
||||||
|
for _j, line in ipairs(split(value)) do out[#out + 1] = line end
|
||||||
|
end
|
||||||
|
return out
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 合并响应里的每一条 Set-Cookie;返回本跳设置的 cookie 名(只名字,不含值,供日志)。
|
||||||
|
---@param jar table
|
||||||
|
---@param res table|nil
|
||||||
|
---@return string[] names
|
||||||
|
local function mergeCookies(jar, res)
|
||||||
|
local names = {}
|
||||||
|
for _idx, line in ipairs(setCookieLines(res)) do
|
||||||
|
local key, value = line:match("^%s*([^=;]+)=([^;]*)")
|
||||||
|
if key then
|
||||||
|
key = key:match("^%s*(.-)%s*$")
|
||||||
|
if value == "" or value == "deleted" then jar[key] = nil else jar[key] = value end
|
||||||
|
names[#names + 1] = key
|
||||||
|
end
|
||||||
|
end
|
||||||
|
return names
|
||||||
|
end
|
||||||
|
|
||||||
|
---@param jar table
|
||||||
|
---@return string|nil
|
||||||
|
local function cookieHeader(jar)
|
||||||
|
local keys = {}
|
||||||
|
for key, value in pairs(jar) do
|
||||||
|
if type(value) == "string" and value ~= "" then keys[#keys + 1] = key end
|
||||||
|
end
|
||||||
|
table.sort(keys)
|
||||||
|
if #keys == 0 then return nil end
|
||||||
|
local parts = {}
|
||||||
|
for _idx, key in ipairs(keys) do parts[#parts + 1] = key .. "=" .. jar[key] end
|
||||||
|
return table.concat(parts, "; ")
|
||||||
|
end
|
||||||
|
|
||||||
|
---@param jar table
|
||||||
|
---@return table
|
||||||
|
local function browserHeaders(jar)
|
||||||
|
return {
|
||||||
|
["Accept"] = "application/json, text/javascript, */*; q=0.01",
|
||||||
|
["Cookie"] = cookieHeader(jar),
|
||||||
|
["Referer"] = LOGIN_PAGE,
|
||||||
|
["User-Agent"] = LOGIN_UA,
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
---@return string
|
||||||
|
local function timestamp()
|
||||||
|
return tostring(os.time() * 1000 + math.random(0, 999))
|
||||||
|
end
|
||||||
|
|
||||||
|
local function clearQrFile()
|
||||||
|
if qr_file then
|
||||||
|
os.remove(qr_file)
|
||||||
|
qr_file = nil
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 每次换新文件名:同一路径会被位图缓存成上一张已作废的码。
|
||||||
|
---@return string
|
||||||
|
local function nextQrFile()
|
||||||
|
clearQrFile()
|
||||||
|
local Paths = require("utils.paths")
|
||||||
|
Paths.ensureLayout("ext.jdread")
|
||||||
|
qr_seq = qr_seq + 1
|
||||||
|
qr_file = Paths.imageDir("ext.jdread") .. "/login-qr-" .. qr_seq .. ".png"
|
||||||
|
return qr_file
|
||||||
|
end
|
||||||
|
|
||||||
|
local function dropQrCookies(jar)
|
||||||
|
for _idx, key in ipairs(QR_COOKIE_KEYS) do
|
||||||
|
jar[key] = nil
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
local LOGIN_HOSTS = { ["passport.jd.com"] = true, ["e.m.jd.com"] = true, ["aq.jd.com"] = true }
|
||||||
|
|
||||||
|
---@param url string|nil
|
||||||
|
---@return string|nil
|
||||||
|
local function loginUrl(url)
|
||||||
|
if type(url) ~= "string" then return nil end
|
||||||
|
local host, tail = url:match("^https?://([^/?#]+)(.*)$")
|
||||||
|
if not host then return nil end
|
||||||
|
host = host:lower():gsub(":443$", "")
|
||||||
|
if not LOGIN_HOSTS[host] then return nil end
|
||||||
|
-- 官方仍返回 http relay;直接走已验证的 HTTPS 中转,不能明文发送候选会话。
|
||||||
|
return "https://" .. host .. tail
|
||||||
|
end
|
||||||
|
|
||||||
|
---@return boolean
|
||||||
|
function Auth.hasSession()
|
||||||
|
local cookie = cfg().cookie
|
||||||
|
return type(cookie) == "string" and cookie ~= ""
|
||||||
|
end
|
||||||
|
|
||||||
|
---@return string|nil
|
||||||
|
function Auth.userLabel()
|
||||||
|
local current = cfg()
|
||||||
|
if type(current.user_name) == "string" and current.user_name ~= "" then
|
||||||
|
return current.user_name
|
||||||
|
end
|
||||||
|
return nil
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 清除账号会话,保留设备 UUID。
|
||||||
|
function Auth.clearSession()
|
||||||
|
saveCfg({ cookie = "", user_name = "", account_id = "" })
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 获取二维码 PNG 及轮询所需 Cookie。
|
||||||
|
--- jar 归本次登录独占:check 要求 token 与同一张码的 wlfstk_smdl/QRCodeKey 配对,串用即 257“参数异常”。
|
||||||
|
---@param cb fun(data: { qr_path: string, token: string, jar: table }|nil, err: string|nil)
|
||||||
|
---@return { cancel: fun() }
|
||||||
|
function Auth.beginQrLoginAsync(cb)
|
||||||
|
local jar = {}
|
||||||
|
local path = nextQrFile()
|
||||||
|
local cancelled = false
|
||||||
|
local url = "https://qr.m.jd.com/show?" .. Text.formEncode({
|
||||||
|
appid = 133,
|
||||||
|
size = 147,
|
||||||
|
t = timestamp(),
|
||||||
|
})
|
||||||
|
local job = Request.get(url, {
|
||||||
|
headers = browserHeaders(jar),
|
||||||
|
cache_ttl = 0,
|
||||||
|
timeout = require("http.timeout").net(1),
|
||||||
|
}, function(body, err, res)
|
||||||
|
if cancelled then return end
|
||||||
|
mergeCookies(jar, res)
|
||||||
|
local token = jar.wlfstk_smdl
|
||||||
|
if not body or Image.ext(body) ~= ".png"
|
||||||
|
or type(token) ~= "string" or token == "" then
|
||||||
|
cb(nil, err or _("获取京东登录二维码失败"))
|
||||||
|
return
|
||||||
|
end
|
||||||
|
local file, open_err = io.open(path, "wb")
|
||||||
|
if not file then cb(nil, open_err or _("无法保存登录二维码")); return end
|
||||||
|
local wrote, write_err = file:write(body)
|
||||||
|
local closed = file:close()
|
||||||
|
if not wrote or not closed then
|
||||||
|
clearQrFile()
|
||||||
|
cb(nil, write_err or _("无法保存登录二维码"))
|
||||||
|
return
|
||||||
|
end
|
||||||
|
cb({ qr_path = path, token = token, jar = jar })
|
||||||
|
end)
|
||||||
|
return { cancel = function()
|
||||||
|
cancelled = true
|
||||||
|
job.cancel()
|
||||||
|
clearQrFile()
|
||||||
|
end }
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 轮询京东扫码状态,最多等待 120 秒。
|
||||||
|
---@param login { token: string, jar: table } beginQrLoginAsync 的结果
|
||||||
|
---@param cb fun(data: { ticket: string, jar: table }|nil, err: string|nil, status: string)
|
||||||
|
---@return { cancel: fun() }
|
||||||
|
function Auth.waitQrLoginAsync(login, cb)
|
||||||
|
local token, jar = login.token, login.jar
|
||||||
|
local cancelled = false
|
||||||
|
local deadline = os.time() + 120
|
||||||
|
local request_job
|
||||||
|
|
||||||
|
local function poll()
|
||||||
|
if cancelled then return end
|
||||||
|
local callback = "jQuery" .. tostring(math.random(1000000, 9999999))
|
||||||
|
local url = "https://qr.m.jd.com/check?" .. Text.formEncode({
|
||||||
|
callback = callback,
|
||||||
|
appid = 133,
|
||||||
|
token = token,
|
||||||
|
_ = timestamp(),
|
||||||
|
})
|
||||||
|
request_job = Request.get(url, {
|
||||||
|
headers = browserHeaders(jar),
|
||||||
|
cache_ttl = 0,
|
||||||
|
timeout = require("http.timeout").net(2 / 3),
|
||||||
|
}, function(raw, err, res)
|
||||||
|
if cancelled then return end
|
||||||
|
mergeCookies(jar, res)
|
||||||
|
if (not raw or err) and os.time() < deadline then
|
||||||
|
require("ui/uimanager"):scheduleIn(3, poll)
|
||||||
|
return
|
||||||
|
end
|
||||||
|
if not raw then
|
||||||
|
clearQrFile()
|
||||||
|
cb(nil, err or _("二维码已失效,请重新登录"), "error")
|
||||||
|
return
|
||||||
|
end
|
||||||
|
local payload = raw:match("^%s*" .. callback .. "%s*%((.*)%)%s*;?%s*$")
|
||||||
|
local ok, data = pcall(JSON.decode, payload or "")
|
||||||
|
if not ok or type(data) ~= "table" then
|
||||||
|
clearQrFile()
|
||||||
|
cb(nil, _("京东扫码状态无效"), "error")
|
||||||
|
return
|
||||||
|
end
|
||||||
|
local code = tonumber(data.code)
|
||||||
|
if code == 200 and type(data.ticket) == "string" and data.ticket ~= "" then
|
||||||
|
cb({ ticket = data.ticket, jar = jar }, nil, "ok")
|
||||||
|
elseif (code == 201 or code == 202) and os.time() < deadline then
|
||||||
|
require("ui/uimanager"):scheduleIn(3, poll)
|
||||||
|
else
|
||||||
|
clearQrFile()
|
||||||
|
cb(nil, data.msg or _("二维码已失效,请重新登录"), "error")
|
||||||
|
end
|
||||||
|
end)
|
||||||
|
end
|
||||||
|
poll()
|
||||||
|
return { cancel = function()
|
||||||
|
cancelled = true
|
||||||
|
if request_job then request_job.cancel() end
|
||||||
|
clearQrFile()
|
||||||
|
end }
|
||||||
|
end
|
||||||
|
|
||||||
|
---@param jar table
|
||||||
|
---@return boolean
|
||||||
|
local function hasLoginCookie(jar)
|
||||||
|
for _idx, key in ipairs(LOGIN_COOKIE_KEYS) do
|
||||||
|
local value = jar[key]
|
||||||
|
if type(value) == "string" and value ~= "" then return true end
|
||||||
|
end
|
||||||
|
return false
|
||||||
|
end
|
||||||
|
Auth._hasLoginCookie = hasLoginCookie
|
||||||
|
|
||||||
|
--- jar 里的 cookie 名(排序),日志用,绝不含值。
|
||||||
|
---@param jar table
|
||||||
|
---@return string
|
||||||
|
local function cookieNames(jar)
|
||||||
|
local keys = {}
|
||||||
|
for key in pairs(jar) do keys[#keys + 1] = key end
|
||||||
|
table.sort(keys)
|
||||||
|
return table.concat(keys, ",")
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 去掉 query / fragment(ticket 等敏感参数在 query 里)。
|
||||||
|
---@param url string|nil
|
||||||
|
---@return string
|
||||||
|
local function safeUrl(url)
|
||||||
|
if type(url) ~= "string" then return "-" end
|
||||||
|
return (url:gsub("[?#].*$", ""))
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 200 中转页里的 JS / meta 跳转目标。
|
||||||
|
---@param body string|nil
|
||||||
|
---@return string|nil
|
||||||
|
local function pageRedirect(body)
|
||||||
|
if type(body) ~= "string" or body == "" then return nil end
|
||||||
|
local target = body:match("[Hh][Tt][Tt][Pp]%-[Ee][Qq][Uu][Ii][Vv]%s*=%s*[\"']?[Rr]efresh[\"']?[^>]-[Uu][Rr][Ll]%s*=%s*([^\"'>%s]+)")
|
||||||
|
or body:match("location%.replace%s*%(%s*[\"']([^\"']+)[\"']")
|
||||||
|
or body:match("location%.href%s*=%s*[\"']([^\"']+)[\"']")
|
||||||
|
or body:match("location%s*=%s*[\"']([^\"']+)[\"']")
|
||||||
|
if target then target = target:gsub("&", "&") end
|
||||||
|
return target
|
||||||
|
end
|
||||||
|
Auth._pageRedirect = pageRedirect
|
||||||
|
Auth._absUrl = Text.absoluteUrl
|
||||||
|
|
||||||
|
--- 扫码和浏览器授权共用:书架接口确认会话有效后才替换持久凭证。
|
||||||
|
---@param jar table
|
||||||
|
---@param cb fun(ok: boolean, err: string|nil)
|
||||||
|
---@return { cancel: fun() }
|
||||||
|
local function saveSessionAsync(jar, cb)
|
||||||
|
local current = cfg()
|
||||||
|
local uuid = current.uuid
|
||||||
|
if type(uuid) ~= "string" or uuid == "" then
|
||||||
|
uuid = "h5" .. require("ffi/sha2").md5(require("utils.device_id").ensure())
|
||||||
|
end
|
||||||
|
local cookie = cookieHeader(jar)
|
||||||
|
local previous_cookie, previous_id = current.cookie, current.account_id
|
||||||
|
local account_id = jar.pin or jar.pt_pin
|
||||||
|
local client = require("moonsource_jdread.client"):new{ cookie = cookie, uuid = uuid }
|
||||||
|
local cancelled = false
|
||||||
|
local job = client:checkSessionAsync(function(wire, err)
|
||||||
|
if cancelled then return end
|
||||||
|
if not wire then
|
||||||
|
cb(false, err or _("京东登录校验失败"))
|
||||||
|
return
|
||||||
|
end
|
||||||
|
current = require("utils.settings").getSource("ext.jdread")
|
||||||
|
local function commit()
|
||||||
|
current.cookie, current.uuid, current.account_id = cookie, uuid, account_id
|
||||||
|
current.user_name = Text.urlDecode(jar.unick or jar.pin or jar.pt_pin or "") or ""
|
||||||
|
require("utils.settings").saveSource("ext.jdread", current)
|
||||||
|
end
|
||||||
|
if previous_id ~= account_id or not previous_id and previous_cookie ~= cookie then
|
||||||
|
if not require("source.logout").replaceLibrary("ext.jdread", commit) then
|
||||||
|
cb(false, _("准备本地同步失败"))
|
||||||
|
return
|
||||||
|
end
|
||||||
|
else
|
||||||
|
commit()
|
||||||
|
end
|
||||||
|
require("source.auth").ok("ext.jdread")
|
||||||
|
cb(true)
|
||||||
|
end)
|
||||||
|
return { cancel = function()
|
||||||
|
cancelled = true
|
||||||
|
job.cancel()
|
||||||
|
end }
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 使用扫码 ticket 换取登录 Cookie 并原子保存源配置。
|
||||||
|
--- 先走完官方跳转,再用书架接口校验;Cookie 不能跳过账号安全验证。
|
||||||
|
--- 风控或 certified 页面明确失败,不覆盖原会话。
|
||||||
|
---@param info { ticket: string, jar: table } waitQrLoginAsync 的结果
|
||||||
|
---@param cb fun(user: { user_name: string }|nil, err: string|nil)
|
||||||
|
---@return { cancel: fun() }
|
||||||
|
function Auth.completeQrLoginAsync(info, cb)
|
||||||
|
local jar = info.jar
|
||||||
|
local cancelled = false
|
||||||
|
local job
|
||||||
|
local seq = 0
|
||||||
|
local hops = 0
|
||||||
|
local visited = {}
|
||||||
|
|
||||||
|
---@param step string
|
||||||
|
---@param res table|nil
|
||||||
|
---@param names string[]
|
||||||
|
---@param extra string|nil
|
||||||
|
local function trace(step, url, res, names, extra)
|
||||||
|
logger.dbg("jdread login", step, safeUrl(url), "status", res and res.code or "-",
|
||||||
|
"set-cookie", #names, "names", table.concat(names, ","),
|
||||||
|
"location", safeUrl(Request.header(res, "Location")), extra or "")
|
||||||
|
end
|
||||||
|
|
||||||
|
local function persist()
|
||||||
|
dropQrCookies(jar)
|
||||||
|
if not hasLoginCookie(jar) then
|
||||||
|
logger.warn("jdread login no session cookie", "hops", hops, "jar", cookieNames(jar))
|
||||||
|
clearQrFile()
|
||||||
|
cb(nil, _("登录未拿到会话 Cookie"))
|
||||||
|
return
|
||||||
|
end
|
||||||
|
seq = seq + 1
|
||||||
|
local mine = seq
|
||||||
|
local handle = saveSessionAsync(jar, function(ok, err)
|
||||||
|
if cancelled then return end
|
||||||
|
clearQrFile()
|
||||||
|
if not ok then
|
||||||
|
logger.warn("jdread login session check failed", tostring(err))
|
||||||
|
cb(nil, err)
|
||||||
|
return
|
||||||
|
end
|
||||||
|
logger.info("jdread login ok", "hops", hops, "jar", cookieNames(jar))
|
||||||
|
cb({ user_name = Auth.userLabel() or "" })
|
||||||
|
end)
|
||||||
|
if seq == mine then job = handle end
|
||||||
|
end
|
||||||
|
|
||||||
|
local follow
|
||||||
|
--- 只有没有跳转且没有候选会话时才补首页,不能吞掉跳转错误。
|
||||||
|
local function nextUrl(base, body, res)
|
||||||
|
local redirect = Request.header(res, "Location") or pageRedirect(body)
|
||||||
|
if redirect then return Text.absoluteUrl(base, redirect) end
|
||||||
|
if not hasLoginCookie(jar) and not visited[HOME] then return HOME end
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 不走 Request.allow_redirects,302 的 Set-Cookie 在 res 里。
|
||||||
|
follow = function(url)
|
||||||
|
url = loginUrl(url)
|
||||||
|
if not url then
|
||||||
|
clearQrFile()
|
||||||
|
cb(nil, _("京东登录跳转地址无效"))
|
||||||
|
return
|
||||||
|
end
|
||||||
|
local path = url:match("^https://aq%.jd%.com([^?#]*)")
|
||||||
|
if path == "/certified" or (path and path:find("^/certified/")) then
|
||||||
|
clearQrFile()
|
||||||
|
cb(nil, _("京东要求账号安全验证,当前扫码流程尚不支持验证续接"))
|
||||||
|
return
|
||||||
|
end
|
||||||
|
if visited[url] or hops >= MAX_HOPS then
|
||||||
|
clearQrFile()
|
||||||
|
cb(nil, _("京东登录校验失败"))
|
||||||
|
return
|
||||||
|
end
|
||||||
|
hops = hops + 1
|
||||||
|
visited[url] = true
|
||||||
|
seq = seq + 1
|
||||||
|
local mine = seq
|
||||||
|
local handle = Request.get(url, {
|
||||||
|
headers = browserHeaders(jar),
|
||||||
|
cache_ttl = 0,
|
||||||
|
timeout = require("http.timeout").net(1),
|
||||||
|
}, function(body, err, res)
|
||||||
|
if cancelled then return end
|
||||||
|
local names = mergeCookies(jar, res)
|
||||||
|
trace("hop " .. hops, url, res, names)
|
||||||
|
if not body and not Request.header(res, "Location") then
|
||||||
|
clearQrFile()
|
||||||
|
cb(nil, err or _("京东登录校验失败"))
|
||||||
|
return
|
||||||
|
end
|
||||||
|
local next_url = nextUrl(url, body, res)
|
||||||
|
if next_url then
|
||||||
|
follow(next_url)
|
||||||
|
return
|
||||||
|
end
|
||||||
|
persist()
|
||||||
|
end)
|
||||||
|
if seq == mine then job = handle end
|
||||||
|
end
|
||||||
|
|
||||||
|
local url = "https://passport.jd.com/uc/qrCodeTicketValidation?" .. Text.formEncode({
|
||||||
|
t = info.ticket,
|
||||||
|
ReturnUrl = HOME,
|
||||||
|
})
|
||||||
|
seq = seq + 1
|
||||||
|
local mine = seq
|
||||||
|
local handle = Request.get(url, {
|
||||||
|
headers = browserHeaders(jar),
|
||||||
|
cache_ttl = 0,
|
||||||
|
timeout = require("http.timeout").net(1),
|
||||||
|
}, function(raw, err, res)
|
||||||
|
if cancelled then return end
|
||||||
|
local names = mergeCookies(jar, res)
|
||||||
|
local ok, data = pcall(JSON.decode, raw or "")
|
||||||
|
local code = ok and type(data) == "table" and tonumber(data.returnCode) or nil
|
||||||
|
trace("validate", url, res, names, "returnCode " .. tostring(code)
|
||||||
|
.. " url " .. safeUrl(type(data) == "table" and data.url or nil))
|
||||||
|
if not raw then
|
||||||
|
logger.warn("jdread login validate failed", tostring(err))
|
||||||
|
clearQrFile()
|
||||||
|
cb(nil, err or _("京东登录校验失败"))
|
||||||
|
return
|
||||||
|
end
|
||||||
|
if code ~= 0 then
|
||||||
|
logger.warn("jdread login validate rejected", "returnCode", tostring(code))
|
||||||
|
clearQrFile()
|
||||||
|
local msg = _(TICKET_ERRORS[code] or "京东登录校验失败")
|
||||||
|
cb(nil, code and (msg .. " (" .. code .. ")") or msg)
|
||||||
|
return
|
||||||
|
end
|
||||||
|
if type(data.url) == "string" and data.url ~= "" then
|
||||||
|
follow(Text.absoluteUrl(url, data.url))
|
||||||
|
elseif hasLoginCookie(jar) then
|
||||||
|
persist()
|
||||||
|
else
|
||||||
|
follow(HOME)
|
||||||
|
end
|
||||||
|
end)
|
||||||
|
if seq == mine then job = handle end
|
||||||
|
return { cancel = function()
|
||||||
|
cancelled = true
|
||||||
|
if job then job.cancel() end
|
||||||
|
clearQrFile()
|
||||||
|
end }
|
||||||
|
end
|
||||||
|
|
||||||
|
--- Validate and save a browser-captured JD session without replacing the QR login flow.
|
||||||
|
---@param payload table
|
||||||
|
---@param cb fun(ok: boolean, err: string|nil)
|
||||||
|
---@return { cancel: fun() }|nil
|
||||||
|
function Auth.importBrowserAsync(payload, cb)
|
||||||
|
local cookies = type(payload.cookies) == "table" and payload.cookies or {}
|
||||||
|
local jar = {}
|
||||||
|
for _idx, cookie in ipairs(cookies) do
|
||||||
|
if type(cookie) == "table" then
|
||||||
|
local domain = type(cookie.domain) == "string" and cookie.domain:gsub("^%.", ""):lower()
|
||||||
|
local name, value = cookie.name, cookie.value
|
||||||
|
local jd_domain = domain == "jd.com" or domain == "e.m.jd.com"
|
||||||
|
if jd_domain and type(name) == "string" and name:match("^[%w_%-]+$")
|
||||||
|
and type(value) == "string" and value ~= ""
|
||||||
|
and not value:find("[;\r\n]") then
|
||||||
|
jar[name] = value
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
dropQrCookies(jar)
|
||||||
|
if not hasLoginCookie(jar) then
|
||||||
|
cb(false, _("登录未拿到会话 Cookie"))
|
||||||
|
return nil
|
||||||
|
end
|
||||||
|
|
||||||
|
return saveSessionAsync(jar, cb)
|
||||||
|
end
|
||||||
|
|
||||||
|
return Auth
|
||||||
@@ -0,0 +1,404 @@
|
|||||||
|
--[[--
|
||||||
|
京东读书 HTTP 客户端:只返回 wire,不做领域转换。
|
||||||
|
|
||||||
|
@module koplugin.book.moonsource_jdread.client
|
||||||
|
--]]
|
||||||
|
|
||||||
|
local JSON = require("json")
|
||||||
|
local Protocol = require("moonsource_jdread.protocol")
|
||||||
|
local Request = require("http.request")
|
||||||
|
local Text = require("utils.text")
|
||||||
|
local _ = require("l10n").get("moonsource_jdread")
|
||||||
|
local logger = require("utils.log")
|
||||||
|
|
||||||
|
---@class JdreadClient
|
||||||
|
---@field cookie string|nil
|
||||||
|
---@field uuid string|nil
|
||||||
|
local Client = {}
|
||||||
|
Client.__index = Client
|
||||||
|
|
||||||
|
local API = "https://e.m.jd.com"
|
||||||
|
local CATALOG_PAGE_SIZE = 2000
|
||||||
|
-- ebooks/lite 每次最多取的书数。
|
||||||
|
local SHELF_BATCH = 18
|
||||||
|
-- download/chapter 对未购买且非试读章节返回 {"result_code":101,"message":"can not download"}。
|
||||||
|
local DOWNLOAD_DENIED = 101
|
||||||
|
|
||||||
|
--- 京东会话失效文案:网页 Cookie 无续期,只能引导重新扫码。
|
||||||
|
local function authExpired()
|
||||||
|
return require("source.auth").expire("ext.jdread", _("点这个提示上的「重新登录」。二维码出来以后,打开手机京东 App,找到「扫一扫」,对准屏幕上的二维码,在手机上点确认。"))
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 响应 message 是否表示未登录 / 会话失效。
|
||||||
|
--- 中文「登录」与英文错误码(实测书架同步会回 NOT.LOGIN)都算。
|
||||||
|
---@param message any
|
||||||
|
---@return boolean
|
||||||
|
local function isLoginFailure(message)
|
||||||
|
local msg = tostring(message or "")
|
||||||
|
if msg == "" then return false end
|
||||||
|
if msg:find("登录", 1, true) then return true end
|
||||||
|
local upper = msg:upper()
|
||||||
|
return upper:find("NOT.LOGIN", 1, true) ~= nil
|
||||||
|
or upper:find("NOT_LOGIN", 1, true) ~= nil
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 匿名请求(搜索 / 榜单不带 Cookie 也成功)不能算「登录态有效」:登录过期弹窗后逛一次书城就把
|
||||||
|
--- 「已提示过期」清掉,下次又弹。只有带着已保存 Cookie 的请求成功才 Auth.ok。
|
||||||
|
---@param raw string|nil
|
||||||
|
---@param err any
|
||||||
|
---@param authed boolean 请求带了登录态
|
||||||
|
---@return table|nil, string|nil
|
||||||
|
local function decodeApi(raw, err, authed)
|
||||||
|
if not raw then return nil, err end
|
||||||
|
local ok, wire = pcall(JSON.decode, raw)
|
||||||
|
if not ok or type(wire) ~= "table" then return nil, _("京东读书响应无效") end
|
||||||
|
if tonumber(wire.result_code) ~= 0 then
|
||||||
|
if isLoginFailure(wire.message) then
|
||||||
|
return nil, authed and authExpired() or _("京东登录校验失败")
|
||||||
|
end
|
||||||
|
return nil, wire.message or (_("京东读书错误 ") .. tostring(wire.result_code))
|
||||||
|
end
|
||||||
|
if authed then require("source.auth").ok("ext.jdread") end
|
||||||
|
return wire
|
||||||
|
end
|
||||||
|
|
||||||
|
---@param o { cookie: string|nil, uuid: string|nil }
|
||||||
|
---@return JdreadClient
|
||||||
|
function Client:new(o)
|
||||||
|
return setmetatable(o, self)
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 签名用的 uuid:没登录也要能逛榜单,缺省用设备派生值(登录时存的也是它)。
|
||||||
|
---@return string
|
||||||
|
function Client:signUuid()
|
||||||
|
if type(self.uuid) == "string" and self.uuid ~= "" then return self.uuid end
|
||||||
|
return "h5" .. require("ffi/sha2").md5(require("utils.device_id").ensure())
|
||||||
|
end
|
||||||
|
|
||||||
|
---@return boolean
|
||||||
|
function Client:configured()
|
||||||
|
return type(self.cookie) == "string" and self.cookie ~= ""
|
||||||
|
and type(self.uuid) == "string" and self.uuid ~= ""
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 会话罐:保存的 Cookie 打底,服务端轮换的会话 Cookie 留在罐里。
|
||||||
|
---@return CookieJar|nil
|
||||||
|
function Client:jar()
|
||||||
|
return require("http.cookie_jar").session("ext.jdread", self.cookie)
|
||||||
|
end
|
||||||
|
|
||||||
|
---@param referer string
|
||||||
|
---@return table
|
||||||
|
function Client:headers(referer)
|
||||||
|
return {
|
||||||
|
["Referer"] = referer,
|
||||||
|
["Origin"] = "https://e.m.jd.com",
|
||||||
|
["Accept"] = "application/json, text/plain, */*",
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
---@param path string
|
||||||
|
---@param extra table|nil
|
||||||
|
---@return string
|
||||||
|
function Client:apiUrl(path, extra)
|
||||||
|
local query = Text.formEncode(Protocol.signedParams(path, self:signUuid(), extra))
|
||||||
|
return API .. path .. "?" .. query
|
||||||
|
end
|
||||||
|
|
||||||
|
---@param path string
|
||||||
|
---@param extra table|nil
|
||||||
|
---@param cb fun(data: table|nil, err: string|nil)
|
||||||
|
---@return { cancel: fun() }
|
||||||
|
function Client:apiGetAsync(path, extra, cb)
|
||||||
|
return Request.get(self:apiUrl(path, extra), {
|
||||||
|
headers = self:headers(API .. "/"),
|
||||||
|
jar = self:jar(),
|
||||||
|
}, function(raw, err)
|
||||||
|
cb(decodeApi(raw, err, self:configured()))
|
||||||
|
end)
|
||||||
|
end
|
||||||
|
|
||||||
|
---@param book_id string
|
||||||
|
---@param page integer
|
||||||
|
---@param cb fun(wire: table|nil, err: string|nil)
|
||||||
|
function Client:bookCommentsAsync(book_id, page, cb)
|
||||||
|
local headers = self:headers(API .. "/")
|
||||||
|
return Request.get(self:apiUrl("/jdread/api/ebook/" .. Text.urlEncode(book_id) .. "/comment", {
|
||||||
|
page = page, page_size = 20, sort = 0,
|
||||||
|
}), { headers = headers }, function(raw, err)
|
||||||
|
cb(decodeApi(raw, err, false))
|
||||||
|
end)
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 新登录会话的校验不改变旧账号的过期状态;成功后由登录流程保存凭证。
|
||||||
|
---@param cb fun(data: table|nil, err: string|nil)
|
||||||
|
---@return { cancel: fun() }
|
||||||
|
function Client:checkSessionAsync(cb)
|
||||||
|
return Request.get(self:apiUrl("/jdread/api/bookshelf/sort"), {
|
||||||
|
headers = self:headers(API .. "/"),
|
||||||
|
jar = self:jar(),
|
||||||
|
cache_ttl = 0,
|
||||||
|
}, function(raw, err)
|
||||||
|
cb(decodeApi(raw, err, false))
|
||||||
|
end)
|
||||||
|
end
|
||||||
|
|
||||||
|
---@param path string
|
||||||
|
---@param body table
|
||||||
|
---@param cb fun(data: table|nil, err: string|nil)
|
||||||
|
---@return { cancel: fun() }
|
||||||
|
function Client:apiPostAsync(path, body, cb)
|
||||||
|
return Request.post(self:apiUrl(path), JSON.encode(body), {
|
||||||
|
headers = self:headers(API .. "/reader/"),
|
||||||
|
jar = self:jar(),
|
||||||
|
content_type = "application/json",
|
||||||
|
}, function(raw, err)
|
||||||
|
cb(decodeApi(raw, err, self:configured()))
|
||||||
|
end)
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 拉取个人书架;坏 ID 跳过,但不完整快照不能作为下架依据。
|
||||||
|
---@param cb fun(rows: table[]|nil, err: string|nil, meta: { incomplete: boolean }|nil)
|
||||||
|
---@return { cancel: fun() }
|
||||||
|
function Client:shelfSyncAsync(cb)
|
||||||
|
local cancelled, active = false, nil
|
||||||
|
local ids, books, index = {}, {}, 1
|
||||||
|
local incomplete = false
|
||||||
|
|
||||||
|
local function nextBatch()
|
||||||
|
if index > #ids then
|
||||||
|
cb(books, nil, { incomplete = incomplete })
|
||||||
|
return
|
||||||
|
end
|
||||||
|
local batch = {}
|
||||||
|
for i = index, math.min(#ids, index + SHELF_BATCH - 1) do
|
||||||
|
batch[#batch + 1] = ids[i]
|
||||||
|
end
|
||||||
|
index = index + #batch
|
||||||
|
local mine = index
|
||||||
|
local handle = self:apiGetAsync(
|
||||||
|
"/jdread/api/ebooks/lite/" .. table.concat(batch, ","),
|
||||||
|
nil,
|
||||||
|
function(wire, err)
|
||||||
|
if cancelled then return end
|
||||||
|
if not wire then cb(nil, err); return end
|
||||||
|
local page = type(wire.data) == "table" and wire.data or {}
|
||||||
|
for _idx, row in ipairs(page) do books[#books + 1] = row end
|
||||||
|
nextBatch()
|
||||||
|
end
|
||||||
|
)
|
||||||
|
-- 回调同步触发时已发出下一个请求,不能用旧句柄覆盖它(同 http/mirror)。
|
||||||
|
if index == mine then active = handle end
|
||||||
|
end
|
||||||
|
|
||||||
|
local first = self:apiGetAsync("/jdread/api/bookshelf/sort", nil, function(wire, err)
|
||||||
|
if cancelled then return end
|
||||||
|
if not wire then cb(nil, err); return end
|
||||||
|
local data = type(wire.data) == "table" and wire.data or {}
|
||||||
|
local seen = {}
|
||||||
|
-- 脏行跳过:不能把 table 地址拼进 URL,但一条坏 ID 不能拖死整架。
|
||||||
|
for row_idx, row in ipairs(data.book_ids or {}) do
|
||||||
|
local id = row
|
||||||
|
if type(row) == "table" then id = row.ebook_id end
|
||||||
|
id = id ~= nil and tostring(id) or ""
|
||||||
|
if not id:match("^%d+$") then
|
||||||
|
incomplete = true
|
||||||
|
logger.warn("jdread shelf skip invalid ebook_id", "row", row_idx,
|
||||||
|
"type", type(row),
|
||||||
|
type(row) == "table" and ("ebook_id=" .. tostring(row.ebook_id)) or id)
|
||||||
|
elseif not seen[id] then
|
||||||
|
seen[id] = true
|
||||||
|
ids[#ids + 1] = id
|
||||||
|
end
|
||||||
|
end
|
||||||
|
nextBatch()
|
||||||
|
end)
|
||||||
|
-- 同步回包时 nextBatch 已登记了分批请求,不能用书架排序的旧句柄覆盖。
|
||||||
|
if not active then active = first end
|
||||||
|
return { cancel = function()
|
||||||
|
cancelled = true
|
||||||
|
active.cancel()
|
||||||
|
end }
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 关键词搜索(不带 order_by,网页端带分号的排序值需要特殊编码)。
|
||||||
|
---@param keyword string
|
||||||
|
---@param page integer
|
||||||
|
---@param page_size integer
|
||||||
|
---@param cb fun(data: table|nil, err: string|nil)
|
||||||
|
---@return { cancel: fun() }
|
||||||
|
function Client:searchAsync(keyword, page, page_size, cb)
|
||||||
|
return self:apiGetAsync("/jdread/api/search/v2", {
|
||||||
|
keyword = keyword, page = page, page_size = page_size, cv = "3.4.0",
|
||||||
|
}, cb)
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 榜单菜单:出版 / 男生 / 女生,每类下是榜单及其周期。
|
||||||
|
---@param cb fun(data: table|nil, err: string|nil)
|
||||||
|
---@return { cancel: fun() }
|
||||||
|
function Client:rankTypesAsync(cb)
|
||||||
|
return self:apiGetAsync("/jdread/api/rank/type", nil, cb)
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 分类树:根节点按出版 / 男生原创 / 女生原创分开,榜单的 catid 只认根下一级。
|
||||||
|
---@param cb fun(data: table|nil, err: string|nil)
|
||||||
|
---@return { cancel: fun() }
|
||||||
|
function Client:categoriesAsync(cb)
|
||||||
|
return self:apiGetAsync("/jdread/api/category", nil, cb)
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 榜单一页;catid 为空表示不按分类筛。
|
||||||
|
---@param kind string|number
|
||||||
|
---@param period string week / mouth / all(京东原拼写)
|
||||||
|
---@param catid string|nil
|
||||||
|
---@param page integer
|
||||||
|
---@param page_size integer
|
||||||
|
---@param cb fun(data: table|nil, err: string|nil)
|
||||||
|
---@return { cancel: fun() }
|
||||||
|
function Client:rankAsync(kind, period, catid, page, page_size, cb)
|
||||||
|
return self:apiGetAsync("/jdread/api/rank/" .. tostring(kind), {
|
||||||
|
period = period,
|
||||||
|
catid = catid ~= "" and catid or nil,
|
||||||
|
page = page,
|
||||||
|
page_size = page_size,
|
||||||
|
}, cb)
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 拉取书籍元数据。
|
||||||
|
---@param book_id string|number
|
||||||
|
---@param cb fun(data: table|nil, err: string|nil)
|
||||||
|
---@return { cancel: fun() }
|
||||||
|
function Client:bookInfoAsync(book_id, cb)
|
||||||
|
local path = "/jdread/api/ebook/lite/" .. tostring(book_id)
|
||||||
|
return self:apiGetAsync(path, nil, cb)
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 书架同步协议:action=0 加入,action=1 移除(与官方客户端一致)。
|
||||||
|
---@param client JdreadClient
|
||||||
|
---@param book_id string|number
|
||||||
|
---@param action integer
|
||||||
|
---@param cb fun(data: table|nil, err: string|nil)
|
||||||
|
---@return { cancel: fun() }
|
||||||
|
local function shelfActionAsync(client, book_id, action, cb)
|
||||||
|
return client:apiPostAsync("/jdread/api/bookshelf/book/sync", {
|
||||||
|
version = os.time() * 1000,
|
||||||
|
first_sync = 1,
|
||||||
|
items = {
|
||||||
|
{ action = action, ebook_id = tonumber(book_id) },
|
||||||
|
},
|
||||||
|
}, cb)
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 将书城书籍加入京东书架。
|
||||||
|
---@param book_id string|number
|
||||||
|
---@param cb fun(data: table|nil, err: string|nil)
|
||||||
|
---@return { cancel: fun() }
|
||||||
|
function Client:addToShelfAsync(book_id, cb)
|
||||||
|
return shelfActionAsync(self, book_id, 0, cb)
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 从京东书架移除。
|
||||||
|
---@param book_id string|number
|
||||||
|
---@param cb fun(data: table|nil, err: string|nil)
|
||||||
|
---@return { cancel: fun() }
|
||||||
|
function Client:removeFromShelfAsync(book_id, cb)
|
||||||
|
return shelfActionAsync(self, book_id, 1, cb)
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 拉取完整目录(与网页阅读器同一 v2 接口,index 为行偏移分页)。
|
||||||
|
--- EPUB / 会员书 / txt 网文都走这条。
|
||||||
|
---@param book_id string|number
|
||||||
|
---@param cb fun(data: table|nil, err: string|nil)
|
||||||
|
---@return { cancel: fun() }
|
||||||
|
function Client:catalogAsync(book_id, cb)
|
||||||
|
local path = "/jdread/api/ebook/catalog/v2/" .. tostring(book_id)
|
||||||
|
local cancelled, rows = false, {}
|
||||||
|
---@type { cancel: fun() }
|
||||||
|
local active
|
||||||
|
|
||||||
|
local seq = 0
|
||||||
|
local function nextPage()
|
||||||
|
seq = seq + 1
|
||||||
|
local mine = seq
|
||||||
|
local handle = self:apiGetAsync(path, { page_size = CATALOG_PAGE_SIZE, index = #rows }, function(wire, err)
|
||||||
|
if cancelled then return end
|
||||||
|
if not wire then cb(nil, err); return end
|
||||||
|
local data = type(wire.data) == "table" and wire.data or {}
|
||||||
|
local page = type(data.chapter_info) == "table" and data.chapter_info or {}
|
||||||
|
for _idx, row in ipairs(page) do rows[#rows + 1] = row end
|
||||||
|
if data.has_more and #page > 0 then
|
||||||
|
nextPage()
|
||||||
|
return
|
||||||
|
end
|
||||||
|
data.chapter_info = rows
|
||||||
|
wire.data = data
|
||||||
|
cb(wire)
|
||||||
|
end)
|
||||||
|
-- 回调同步触发时已发出下一个请求,不能用旧句柄覆盖它(同 http/mirror)。
|
||||||
|
if seq == mine then active = handle end
|
||||||
|
end
|
||||||
|
nextPage()
|
||||||
|
return { cancel = function()
|
||||||
|
cancelled = true
|
||||||
|
active.cancel()
|
||||||
|
end }
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 拉取章节正文。EPUB 传 { indexes = 0-based 序号 },txt 网文传 { type = 1, ids = chapter_id }。
|
||||||
|
---@param book_id string|number
|
||||||
|
---@param query table
|
||||||
|
---@param cb fun(data: table|nil, err: string|nil)
|
||||||
|
---@return { cancel: fun() }
|
||||||
|
function Client:downloadChapterAsync(book_id, query, cb)
|
||||||
|
local path = "/jdread/api/download/chapter/" .. tostring(book_id)
|
||||||
|
local tm = Protocol.evenTime()
|
||||||
|
local signed = Protocol.signedParams(path, self:signUuid(), nil, tm)
|
||||||
|
local params = {
|
||||||
|
enc = 1,
|
||||||
|
app = "jdread-m",
|
||||||
|
tm = tm,
|
||||||
|
params = Protocol.encryptQuery(Text.formEncode(signed), tm),
|
||||||
|
}
|
||||||
|
for key, value in pairs(query) do params[key] = value end
|
||||||
|
return Request.get(API .. path .. "?" .. Text.formEncode(params), {
|
||||||
|
headers = self:headers(API .. "/reader/"),
|
||||||
|
jar = self:jar(),
|
||||||
|
}, function(raw, err)
|
||||||
|
if not raw then cb(nil, err); return end
|
||||||
|
local wire, decode_err, code = Protocol.decodeDownload(raw, tm)
|
||||||
|
if code == DOWNLOAD_DENIED then
|
||||||
|
decode_err = _("京东读书网页协议读不到本章,请在京东读书 App 内阅读")
|
||||||
|
elseif isLoginFailure(decode_err) then
|
||||||
|
decode_err = authExpired()
|
||||||
|
end
|
||||||
|
cb(wire, decode_err)
|
||||||
|
end)
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 拉取云端阅读位置。
|
||||||
|
---@param book_id string|number
|
||||||
|
---@param cb fun(data: table|nil, err: string|nil)
|
||||||
|
---@return { cancel: fun() }
|
||||||
|
function Client:getProgressAsync(book_id, cb)
|
||||||
|
return self:apiPostAsync("/jdread/api/marker/sync", {
|
||||||
|
{ ebook_id = tonumber(book_id), format = 1 },
|
||||||
|
}, cb)
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 覆盖云端阅读位置。
|
||||||
|
---@param book_id string|number
|
||||||
|
---@param marker table
|
||||||
|
---@param cb fun(data: table|nil, err: string|nil)
|
||||||
|
---@return { cancel: fun() }
|
||||||
|
function Client:putProgressAsync(book_id, marker, cb)
|
||||||
|
return self:apiPostAsync("/jdread/api/marker/sync", {
|
||||||
|
{
|
||||||
|
version = 0,
|
||||||
|
ebook_id = tonumber(book_id),
|
||||||
|
format = 1,
|
||||||
|
list = { marker },
|
||||||
|
},
|
||||||
|
}, cb)
|
||||||
|
end
|
||||||
|
|
||||||
|
return Client
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
return {
|
||||||
|
["书评预览"] = "Book comment previews",
|
||||||
|
["书籍详情为空"] = "Empty book details",
|
||||||
|
["二维码已失效,请重新登录"] = "QR code expired, sign in again",
|
||||||
|
["京东判定本次扫码存在风险,官方要求改用密码登录"] = "JD flagged this QR sign-in as risky and requires password sign-in",
|
||||||
|
["京东要求账号安全验证,当前扫码流程尚不支持验证续接"] = "JD requires account verification; continuing verification is not yet supported by this QR sign-in flow",
|
||||||
|
["京东登录跳转地址无效"] = "Invalid JD sign-in redirect",
|
||||||
|
["京东扫码状态无效"] = "Invalid JD QR sign-in status",
|
||||||
|
["京东扫码登录"] = "Sign in to JD with QR code",
|
||||||
|
["京东登录失败"] = "JD sign-in failed",
|
||||||
|
["京东登录校验失败"] = "JD sign-in validation failed",
|
||||||
|
["重新获取二维码"] = "Get a new QR code",
|
||||||
|
["京东读书响应无效"] = "Invalid JD Read response",
|
||||||
|
["点这个提示上的「重新登录」。二维码出来以后,打开手机京东 App,找到「扫一扫」,对准屏幕上的二维码,在手机上点确认。"] = "Tap Sign in again on this message. When the QR code appears, open the JD app on your phone, tap Scan, point it at the code, and confirm on the phone.",
|
||||||
|
["京东读书网页协议读不到本章,请在京东读书 App 内阅读"] = "This chapter is not available via the JD Read web protocol. Please read it in the JD Read app.",
|
||||||
|
["京东读书账号"] = "JD Read account",
|
||||||
|
["京东读书错误 "] = "JD Read error ",
|
||||||
|
["确定退出京东读书账号?"] = "Sign out of JD Read?",
|
||||||
|
["无法保存登录二维码"] = "Failed to save sign-in QR code",
|
||||||
|
["未登录 · 点此扫码"] = "Not signed in · tap to scan",
|
||||||
|
["正在获取二维码…"] = "Fetching QR code…",
|
||||||
|
["登录未拿到会话 Cookie"] = "No session Cookie returned after sign-in",
|
||||||
|
["章节目录保存失败"] = "Failed to save chapter list",
|
||||||
|
["缺少章节信息"] = "Missing chapter info",
|
||||||
|
["获取京东登录二维码失败"] = "Failed to get JD sign-in QR code",
|
||||||
|
["书架同步"] = "Shelf sync",
|
||||||
|
["京东读书书架与在线阅读"] = "JD Read shelf and online reading",
|
||||||
|
["搜索与发现"] = "Search and discover",
|
||||||
|
["进度同步"] = "Progress sync",
|
||||||
|
["京东判定本次扫码存在风险,请稍后重试"] = "JD flagged this QR sign-in as risky, try again later",
|
||||||
|
["京东要求先完成账号安全验证,请在京东 App 或网页登录一次完成验证后再扫码"] = "JD requires an account security check first. Sign in once in the JD app or website to complete it, then scan again",
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
return {
|
||||||
|
["书评预览"] = "書評預覽",
|
||||||
|
["书籍详情为空"] = "書籍詳情為空",
|
||||||
|
["二维码已失效,请重新登录"] = "二維碼已失效,請重新登入",
|
||||||
|
["京东判定本次扫码存在风险,官方要求改用密码登录"] = "京東判定本次掃碼存在風險,官方要求改用密碼登入",
|
||||||
|
["京东要求账号安全验证,当前扫码流程尚不支持验证续接"] = "京東要求帳號安全驗證,目前掃碼流程尚不支援驗證續接",
|
||||||
|
["京东登录跳转地址无效"] = "京東登入跳轉位址無效",
|
||||||
|
["京东扫码状态无效"] = "京東掃碼狀態無效",
|
||||||
|
["京东扫码登录"] = "京東掃碼登入",
|
||||||
|
["京东登录失败"] = "京東登入失敗",
|
||||||
|
["京东登录校验失败"] = "京東登入驗證失敗",
|
||||||
|
["重新获取二维码"] = "重新取得二維碼",
|
||||||
|
["京东读书响应无效"] = "京東讀書回應無效",
|
||||||
|
["点这个提示上的「重新登录」。二维码出来以后,打开手机京东 App,找到「扫一扫」,对准屏幕上的二维码,在手机上点确认。"] = "點這個提示上的「重新登入」。二維碼出來以後,打開手機京東 App,找到「掃一掃」,對準螢幕上的二維碼,在手機上點確認。",
|
||||||
|
["京东读书网页协议读不到本章,请在京东读书 App 内阅读"] = "京東讀書網頁協議讀不到本章,請在京東讀書 App 內閱讀",
|
||||||
|
["京东读书账号"] = "京東讀書帳號",
|
||||||
|
["京东读书错误 "] = "京東讀書錯誤 ",
|
||||||
|
["确定退出京东读书账号?"] = "確定登出京東讀書帳號?",
|
||||||
|
["无法保存登录二维码"] = "無法儲存登入二維碼",
|
||||||
|
["未登录 · 点此扫码"] = "未登入 · 點此掃碼",
|
||||||
|
["正在获取二维码…"] = "正在取得二維碼…",
|
||||||
|
["登录未拿到会话 Cookie"] = "登入未取得工作階段 Cookie",
|
||||||
|
["章节目录保存失败"] = "章節目錄儲存失敗",
|
||||||
|
["缺少章节信息"] = "缺少章節資訊",
|
||||||
|
["获取京东登录二维码失败"] = "取得京東登入二維碼失敗",
|
||||||
|
["书架同步"] = "書架同步",
|
||||||
|
["京东读书书架与在线阅读"] = "京東讀書書架與線上閱讀",
|
||||||
|
["搜索与发现"] = "搜尋與發現",
|
||||||
|
["进度同步"] = "進度同步",
|
||||||
|
["京东判定本次扫码存在风险,请稍后重试"] = "京東判定本次掃碼存在風險,請稍後重試",
|
||||||
|
["京东要求先完成账号安全验证,请在京东 App 或网页登录一次完成验证后再扫码"] = "京東要求先完成帳號安全驗證,請在京東 App 或網頁登入一次完成驗證後再掃碼",
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
return function()
|
||||||
|
local copy = {}
|
||||||
|
for k, v in pairs(require("moonsource_jdread._meta")) do copy[k] = v end
|
||||||
|
return copy
|
||||||
|
end
|
||||||
@@ -0,0 +1,228 @@
|
|||||||
|
--[[--
|
||||||
|
京东读书 wire → 领域对象。
|
||||||
|
|
||||||
|
@module koplugin.book.moonsource_jdread.mapper
|
||||||
|
--]]
|
||||||
|
|
||||||
|
local Progress = require("book.progress")
|
||||||
|
local Text = require("utils.text")
|
||||||
|
local _ = require("l10n").get("moonsource_jdread")
|
||||||
|
|
||||||
|
local Mapper = {}
|
||||||
|
local SOURCE_ID = "ext.jdread"
|
||||||
|
|
||||||
|
--- 京东图片地址带 .dpg 后缀(图床转 webp),去掉取原图。
|
||||||
|
---@param value any
|
||||||
|
---@return string|nil
|
||||||
|
local function imageUrl(value)
|
||||||
|
return type(value) == "string" and (value:gsub("%.dpg$", "")) or nil
|
||||||
|
end
|
||||||
|
|
||||||
|
--- ebook/lite、ebooks/lite 的一行 → Book。
|
||||||
|
--- 实际字段只有 ebook_id/name/author/image_url/cate_third_names(详情另有 word_count);没有简介与进度。
|
||||||
|
---@param row table
|
||||||
|
---@return Book
|
||||||
|
function Mapper.book(row)
|
||||||
|
return {
|
||||||
|
source_id = SOURCE_ID,
|
||||||
|
stable_id = tostring(row.ebook_id),
|
||||||
|
title = row.name,
|
||||||
|
authors = row.author,
|
||||||
|
category = type(row.cate_third_names) == "table" and table.concat(row.cate_third_names, ", ") or nil,
|
||||||
|
cover = imageUrl(row.image_url),
|
||||||
|
intro = row.info,
|
||||||
|
meta = { words = row.word_count },
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
--- search/v2 的 product_search_infos → Book[]。
|
||||||
|
---@param wire table
|
||||||
|
---@return Book[]
|
||||||
|
function Mapper.search(wire)
|
||||||
|
local books = {}
|
||||||
|
for _idx, row in ipairs(wire.data and wire.data.product_search_infos or {}) do
|
||||||
|
books[#books + 1] = Mapper.book({
|
||||||
|
ebook_id = row.product_id,
|
||||||
|
name = row.product_name,
|
||||||
|
author = row.author,
|
||||||
|
image_url = row.logo,
|
||||||
|
info = row.content_info,
|
||||||
|
word_count = row.word_count,
|
||||||
|
cate_third_names = row.cate_third_names,
|
||||||
|
})
|
||||||
|
end
|
||||||
|
return books
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 京东书架 ebooks/lite 行数组 → Book[]。
|
||||||
|
---@param rows table[]
|
||||||
|
---@return Book[]
|
||||||
|
function Mapper.shelfList(rows)
|
||||||
|
local books = {}
|
||||||
|
for _idx, row in ipairs(rows) do books[#books + 1] = Mapper.book(row) end
|
||||||
|
return books
|
||||||
|
end
|
||||||
|
|
||||||
|
--- EPUB 目录 /jdread/api/ebook/catalog/v2/{id} → BookChapter[],与网页阅读器同一成章规则:
|
||||||
|
--- 一个文件一章(chapter_uri 去掉 #锚点,试读版 x.html 与完整版 x-CD.html 算同一文件),
|
||||||
|
--- 带锚点的小节并入所在文件,同文件不带锚点的行丢弃。小节各自下载会拿到整份文件,正文重复。
|
||||||
|
--- 下载只认 0-based indexes:组内首个已购完整版,没有再取首个试读版,都没有取组首行;uid 就是它。
|
||||||
|
--- 封面页正文是空 body,首章挂上封面图供补页。
|
||||||
|
---@param rows table
|
||||||
|
---@param cover string|nil
|
||||||
|
---@return BookChapter[]|nil
|
||||||
|
local function downloadChapters(rows, cover)
|
||||||
|
local chapters, by_file, full, try = {}, {}, {}, {}
|
||||||
|
for pos, row in ipairs(rows) do
|
||||||
|
local index = tonumber(row.chapter_index) or pos - 1
|
||||||
|
local file = row.chapter_uri and (row.chapter_uri:gsub("#.*$", ""):gsub("%-CD%.", "."))
|
||||||
|
or row.chapter_item or tostring(index)
|
||||||
|
local title = row.chapter_name ~= nil and tostring(row.chapter_name) or ""
|
||||||
|
local chapter = by_file[file]
|
||||||
|
if not chapter then
|
||||||
|
chapter = {
|
||||||
|
idx = #chapters + 1,
|
||||||
|
source_idx = tostring(index),
|
||||||
|
title = title ~= "" and title or ("第" .. (index + 1) .. "章"),
|
||||||
|
depth = 1,
|
||||||
|
}
|
||||||
|
by_file[file] = chapter
|
||||||
|
chapters[#chapters + 1] = chapter
|
||||||
|
elseif row.anchor then
|
||||||
|
chapter.anchors = chapter.anchors or {}
|
||||||
|
chapter.anchors[#chapter.anchors + 1] = { title = title, depth = 2, id = tostring(row.anchor) }
|
||||||
|
else
|
||||||
|
chapter = nil
|
||||||
|
end
|
||||||
|
if chapter then
|
||||||
|
local idx = chapter.idx
|
||||||
|
if not row.is_try and row.is_buy then
|
||||||
|
full[idx] = full[idx] or index
|
||||||
|
elseif row.is_try then
|
||||||
|
try[idx] = try[idx] or index
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
if #chapters == 0 then return nil end
|
||||||
|
for idx, chapter in ipairs(chapters) do
|
||||||
|
chapter.uid = tostring(full[idx] or try[idx] or chapter.source_idx)
|
||||||
|
end
|
||||||
|
chapters[1].toc_version = 5
|
||||||
|
chapters[1].cover = cover
|
||||||
|
return chapters
|
||||||
|
end
|
||||||
|
|
||||||
|
--- txt 网文目录:type 0 是卷标题(无 chapter_id,不计入 total_count),type 1 是正文章。
|
||||||
|
--- 下载按 { type = 1, ids = chapter_id },故 uid 就是 chapter_id。
|
||||||
|
---@param rows table
|
||||||
|
---@return BookChapter[]|nil
|
||||||
|
local function netChapters(rows)
|
||||||
|
local chapters = {}
|
||||||
|
for _idx, row in ipairs(rows) do
|
||||||
|
if tonumber(row.type) == 1 and row.chapter_id ~= nil and tostring(row.chapter_id) ~= "" then
|
||||||
|
local title = row.chapter_name
|
||||||
|
if title == nil or tostring(title) == "" then
|
||||||
|
title = "第" .. (#chapters + 1) .. "章"
|
||||||
|
end
|
||||||
|
chapters[#chapters + 1] = {
|
||||||
|
idx = #chapters + 1,
|
||||||
|
uid = tostring(row.chapter_id),
|
||||||
|
title = tostring(title),
|
||||||
|
depth = 1,
|
||||||
|
}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
if #chapters == 0 then return nil end
|
||||||
|
chapters[1].toc_version = 3
|
||||||
|
return chapters
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 目录 wire → BookChapter[]。
|
||||||
|
---@param wire table
|
||||||
|
---@return BookChapter[]|nil
|
||||||
|
function Mapper.chapters(wire)
|
||||||
|
local root = type(wire.data) == "table" and wire.data or wire
|
||||||
|
if type(root.chapter_info) ~= "table" then return nil end
|
||||||
|
if root.format == "txt" then return netChapters(root.chapter_info) end
|
||||||
|
return downloadChapters(root.chapter_info, imageUrl(root.image_url))
|
||||||
|
end
|
||||||
|
|
||||||
|
--- download/chapter 正文 wire → 标准章节内容。
|
||||||
|
--- txt 网文正文 content_type = "net",是 \r\n 分段的纯文本,
|
||||||
|
--- 行首全角缩进时有时无,textToBody 统一剥掉,交给章节模板的 text-indent。
|
||||||
|
--- 网页版封面页去掉了图只剩空 body,传入 cover 时用封面图补成一页,否则落盘会报章节内容为空。
|
||||||
|
---@param wire table
|
||||||
|
---@param title string|nil
|
||||||
|
---@param cover string|nil
|
||||||
|
---@return ChapterContentPayload|nil
|
||||||
|
function Mapper.content(wire, title, cover)
|
||||||
|
local data = type(wire.data) == "table" and wire.data or wire
|
||||||
|
local parts = data.chapter
|
||||||
|
if type(parts) ~= "table" then return nil end
|
||||||
|
local toBody = data.content_type == "net" and Text.textToBody or Text.htmlBodyFragment
|
||||||
|
local html = {}
|
||||||
|
for _idx, part in ipairs(parts) do
|
||||||
|
if type(part) == "table" and part.can_read == false then
|
||||||
|
return nil
|
||||||
|
end
|
||||||
|
local content = type(part) == "table" and part.content or part
|
||||||
|
if type(content) == "string" and content ~= "" then
|
||||||
|
html[#html + 1] = toBody(content)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
if #html == 0 then return nil end
|
||||||
|
local body = table.concat(html, "\n")
|
||||||
|
if cover and not body:find("%S") then
|
||||||
|
body = '<p><img src="' .. Text.xmlEscape(cover) .. '"/></p>'
|
||||||
|
end
|
||||||
|
return { title = title, html = body }
|
||||||
|
end
|
||||||
|
|
||||||
|
--- marker/sync wire → ProgressPosition 与章节 uid。
|
||||||
|
---@param wire table
|
||||||
|
---@return ProgressPosition|nil, string|nil
|
||||||
|
function Mapper.progress(wire)
|
||||||
|
local groups = wire.data
|
||||||
|
local markers = type(groups) == "table" and groups[1] and groups[1].list
|
||||||
|
if type(markers) ~= "table" then return nil end
|
||||||
|
local current
|
||||||
|
for _idx, marker in ipairs(markers) do
|
||||||
|
if type(marker) == "table" and tonumber(marker.data_type) == 0
|
||||||
|
and (not current or (tonumber(marker.version) or 0) > (tonumber(current.version) or 0)) then
|
||||||
|
current = marker
|
||||||
|
end
|
||||||
|
end
|
||||||
|
if not current then return nil end
|
||||||
|
return {
|
||||||
|
fraction = Progress.clampFraction(current.percent),
|
||||||
|
chapter_title = current.epub_chapter_title,
|
||||||
|
updated_at = tonumber(current.version or current.created_at),
|
||||||
|
}, current.chapter_id and tostring(current.chapter_id) or nil
|
||||||
|
end
|
||||||
|
|
||||||
|
---@param wire table
|
||||||
|
---@return table|nil, string|nil
|
||||||
|
function Mapper.bookReviewPage(wire)
|
||||||
|
local data = type(wire) == "table" and wire.data
|
||||||
|
local rows = type(data) == "table" and data.ebook_comment_infos
|
||||||
|
local total = type(data) == "table" and tonumber(data.total)
|
||||||
|
if type(rows) ~= "table" or not total or total < 0 then
|
||||||
|
return nil, _("京东读书响应无效")
|
||||||
|
end
|
||||||
|
local items = {}
|
||||||
|
for _idx, row in ipairs(rows) do
|
||||||
|
if type(row) ~= "table" or row.id == nil or type(row.comment) ~= "string"
|
||||||
|
or type(row.created) ~= "number" then
|
||||||
|
return nil, _("京东读书响应无效")
|
||||||
|
end
|
||||||
|
items[#items + 1] = {
|
||||||
|
id = tostring(row.id), author = type(row.nickname) == "string" and row.nickname or "",
|
||||||
|
text = row.comment, time = os.date("%Y-%m-%d", math.floor(row.created / 1000)),
|
||||||
|
likes = tonumber(row.like_count), grade = tonumber(row.comment_rate),
|
||||||
|
}
|
||||||
|
end
|
||||||
|
return { items = items, total = total, pages = math.max(1, math.ceil(total / 20)),
|
||||||
|
more = #items < total, title = #items < total and _("书评预览") or _("书评") }
|
||||||
|
end
|
||||||
|
|
||||||
|
return Mapper
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
--[[--
|
||||||
|
京东读书协议:e.m.jd.com 请求签名与下载接口 AES 编解码。
|
||||||
|
|
||||||
|
@module koplugin.book.moonsource_jdread.protocol
|
||||||
|
--]]
|
||||||
|
|
||||||
|
local sha2 = require("ffi/sha2")
|
||||||
|
local md5 = sha2.md5
|
||||||
|
local JSON = require("json")
|
||||||
|
local Aes = require("crypto.aes")
|
||||||
|
local Text = require("utils.text")
|
||||||
|
local _ = require("l10n").get("moonsource_jdread")
|
||||||
|
|
||||||
|
local Protocol = {}
|
||||||
|
|
||||||
|
local APP = "jdread-m"
|
||||||
|
|
||||||
|
--- AES 密钥 = md5(时间戳 .. APP) 的原始 16 字节
|
||||||
|
---@param tm integer
|
||||||
|
---@return string
|
||||||
|
local function aesKey(tm)
|
||||||
|
return sha2.hex_to_bin(sha2.md5(tostring(tm) .. APP))
|
||||||
|
end
|
||||||
|
|
||||||
|
---@return string
|
||||||
|
local function scalar(value)
|
||||||
|
if value == nil then return "" end
|
||||||
|
if type(value) == "boolean" then return value and "true" or "false" end
|
||||||
|
return tostring(value)
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 为 e.m.jd.com 接口生成公共参数和双 MD5 签名。
|
||||||
|
---@param path string
|
||||||
|
---@param uuid string
|
||||||
|
---@param extra table|nil
|
||||||
|
---@param tm integer|nil
|
||||||
|
---@return table
|
||||||
|
function Protocol.signedParams(path, uuid, extra, tm)
|
||||||
|
tm = tm or (os.time() * 1000 + math.random(0, 999))
|
||||||
|
local params = {
|
||||||
|
app = APP,
|
||||||
|
tm = tm,
|
||||||
|
team_id = "",
|
||||||
|
uuid = uuid,
|
||||||
|
client = "pc",
|
||||||
|
os = "web",
|
||||||
|
ov = "1.0",
|
||||||
|
}
|
||||||
|
for key, value in pairs(extra or {}) do params[key] = value end
|
||||||
|
|
||||||
|
local keys = {}
|
||||||
|
for key in pairs(params) do keys[#keys + 1] = key end
|
||||||
|
table.sort(keys)
|
||||||
|
local canonical = {}
|
||||||
|
for _idx, key in ipairs(keys) do
|
||||||
|
canonical[#canonical + 1] = key .. "=" .. scalar(params[key])
|
||||||
|
end
|
||||||
|
local inner = md5(APP .. tostring(tm) .. uuid)
|
||||||
|
params.sign = md5(inner .. path .. table.concat(canonical, "&"))
|
||||||
|
return params
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 下载接口强制偶数时间戳,只走 AES,避开 DES 分支。
|
||||||
|
---@param tm integer|nil
|
||||||
|
---@return integer
|
||||||
|
function Protocol.evenTime(tm)
|
||||||
|
tm = tm or (os.time() * 1000 + math.random(0, 998))
|
||||||
|
if tm % 2 ~= 0 then
|
||||||
|
tm = tm + 1
|
||||||
|
end
|
||||||
|
return tm
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 加密 e.m.jd.com 下载接口的已签名 query。
|
||||||
|
---@param query string
|
||||||
|
---@param tm integer
|
||||||
|
---@return string
|
||||||
|
function Protocol.encryptQuery(query, tm)
|
||||||
|
local raw = Aes.ecb_encrypt(query, aesKey(tm))
|
||||||
|
return (Text.base64Encode(raw):gsub("%+", "-"):gsub("/", "_"))
|
||||||
|
end
|
||||||
|
|
||||||
|
---@param envelope table
|
||||||
|
---@return table|nil, string|nil, integer|nil
|
||||||
|
local function checkDownload(envelope)
|
||||||
|
local code = tonumber(envelope.result_code)
|
||||||
|
if code ~= 0 then
|
||||||
|
return nil, envelope.message or (_("京东读书错误 ") .. tostring(envelope.result_code)), code
|
||||||
|
end
|
||||||
|
return envelope
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 解开 /jdread/api/download/chapter 的 AES 正文。明文和密文都可能是错误信封。
|
||||||
|
---@param raw string
|
||||||
|
---@param tm integer
|
||||||
|
---@return table|nil, string|nil, integer|nil result_code
|
||||||
|
function Protocol.decodeDownload(raw, tm)
|
||||||
|
if type(raw) ~= "string" or raw == "" then
|
||||||
|
return nil, _("京东读书响应无效")
|
||||||
|
end
|
||||||
|
if raw:sub(1, 1) == "{" then
|
||||||
|
local ok, envelope = pcall(JSON.decode, raw)
|
||||||
|
if ok and type(envelope) == "table" then
|
||||||
|
return checkDownload(envelope)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
local ok, text = pcall(Aes.ecb_decrypt, Text.base64Decode(raw), aesKey(tm))
|
||||||
|
if not ok or type(text) ~= "string" or text == "" then
|
||||||
|
return nil, _("京东读书响应无效")
|
||||||
|
end
|
||||||
|
local decoded_ok, decoded = pcall(JSON.decode, text)
|
||||||
|
if not decoded_ok or type(decoded) ~= "table" then
|
||||||
|
return nil, _("京东读书响应无效")
|
||||||
|
end
|
||||||
|
return checkDownload(decoded)
|
||||||
|
end
|
||||||
|
|
||||||
|
return Protocol
|
||||||
@@ -0,0 +1,190 @@
|
|||||||
|
--[[--
|
||||||
|
京东读书源设置。
|
||||||
|
|
||||||
|
@module koplugin.book.moonsource_jdread.setting
|
||||||
|
--]]
|
||||||
|
|
||||||
|
local _ = require("l10n").get("moonsource_jdread")
|
||||||
|
|
||||||
|
local Setting = {}
|
||||||
|
|
||||||
|
---@return string, boolean
|
||||||
|
function Setting.rowStatus()
|
||||||
|
local Auth = require("moonsource_jdread.auth")
|
||||||
|
return Auth.hasSession() and (Auth.userLabel() or _("已登录")) or _("未登录 · 点此扫码"),
|
||||||
|
Auth.hasSession()
|
||||||
|
end
|
||||||
|
|
||||||
|
local function showQrLogin()
|
||||||
|
local Auth = require("moonsource_jdread.auth")
|
||||||
|
local NetworkMgr = require("ui/network/manager")
|
||||||
|
local CenterContainer = require("ui/widget/container/centercontainer")
|
||||||
|
local Geom = require("ui/geometry")
|
||||||
|
local Screen = require("device").screen
|
||||||
|
local Image = require("ui.themes.widgets.image")
|
||||||
|
local Sheet = require("ui.themes.widgets.sheet")
|
||||||
|
local Text = require("ui.themes.widgets.text")
|
||||||
|
local Theme = require("ui.themes")
|
||||||
|
local Toast = require("ui.themes.widgets.toast")
|
||||||
|
|
||||||
|
NetworkMgr:runWhenConnected(function()
|
||||||
|
local cancelled = false
|
||||||
|
local dialog, begin_job, wait_job, complete_job, showFailure
|
||||||
|
local qr_size = math.floor(math.min(Screen:getWidth(), Screen:getHeight()) * 0.55)
|
||||||
|
|
||||||
|
--- 代码主动关窗:先摘掉引用,close_callback 就不会当成用户取消。
|
||||||
|
local function closeDialog()
|
||||||
|
local d = dialog
|
||||||
|
dialog = nil
|
||||||
|
if d then d:close() end
|
||||||
|
end
|
||||||
|
|
||||||
|
-- 取消按钮、点框外、返回键都走这里,否则后台轮询会一直跑到超时。
|
||||||
|
local function cancel()
|
||||||
|
cancelled = true
|
||||||
|
if begin_job then
|
||||||
|
begin_job.cancel()
|
||||||
|
begin_job = nil
|
||||||
|
end
|
||||||
|
if wait_job then
|
||||||
|
wait_job.cancel()
|
||||||
|
wait_job = nil
|
||||||
|
end
|
||||||
|
if complete_job then
|
||||||
|
complete_job.cancel()
|
||||||
|
complete_job = nil
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
-- 原因可能很长(风控提示),单行会溢出弹窗:按弹窗内宽折行居中。
|
||||||
|
local function message(text, width)
|
||||||
|
return Text.box("body", text, width, { align = "center", bg = Theme.current().dialog.bg })
|
||||||
|
end
|
||||||
|
|
||||||
|
---@param content fun(width: number): table
|
||||||
|
---@param retry fun()|nil 有值时在取消前加「重新获取二维码」
|
||||||
|
local function showDialog(content, retry)
|
||||||
|
closeDialog()
|
||||||
|
local items = {
|
||||||
|
{ widget = function(width)
|
||||||
|
return CenterContainer:new{ dimen = Geom:new{ w = width, h = qr_size }, content(width) }
|
||||||
|
end },
|
||||||
|
}
|
||||||
|
if retry then
|
||||||
|
items[#items + 1] = { text = _("重新获取二维码"), variant = "primary", callback = retry }
|
||||||
|
end
|
||||||
|
items[#items + 1] = { text = _("取消") }
|
||||||
|
local d
|
||||||
|
d = Sheet:new{
|
||||||
|
title = _("京东扫码登录"),
|
||||||
|
items = items,
|
||||||
|
close_callback = function()
|
||||||
|
if dialog ~= d then return end
|
||||||
|
dialog = nil
|
||||||
|
cancel()
|
||||||
|
end,
|
||||||
|
}
|
||||||
|
dialog = d
|
||||||
|
d:show()
|
||||||
|
end
|
||||||
|
|
||||||
|
local startLogin
|
||||||
|
--- 失败留框:显示原因 + 重新获取二维码。按钮会先关框(触发 cancel),再重置 cancelled 重新开始。
|
||||||
|
---@param reason string
|
||||||
|
showFailure = function(reason)
|
||||||
|
showDialog(function(width) return message(reason, width) end, function()
|
||||||
|
cancelled = false
|
||||||
|
startLogin()
|
||||||
|
end)
|
||||||
|
end
|
||||||
|
|
||||||
|
startLogin = function()
|
||||||
|
-- 点击即出框盖住入口:二维码要等一次网络往返,没有反馈用户会连点出多个登录流程。
|
||||||
|
showDialog(function(width) return message(_("正在获取二维码…"), width) end)
|
||||||
|
begin_job = Auth.beginQrLoginAsync(function(started, err)
|
||||||
|
begin_job = nil
|
||||||
|
if cancelled then return end
|
||||||
|
if not started then
|
||||||
|
closeDialog()
|
||||||
|
Toast:new{ text = err or _("获取京东登录二维码失败") }:show()
|
||||||
|
return
|
||||||
|
end
|
||||||
|
|
||||||
|
Image.invalidate(started.qr_path)
|
||||||
|
showDialog(function()
|
||||||
|
return Image.widget({ src = started.qr_path, width = qr_size, height = qr_size })
|
||||||
|
end)
|
||||||
|
|
||||||
|
wait_job = Auth.waitQrLoginAsync(started, function(info, wait_err, status)
|
||||||
|
wait_job = nil
|
||||||
|
if cancelled then return end
|
||||||
|
if status ~= "ok" or not info then
|
||||||
|
showFailure(wait_err or _("二维码已失效,请重新登录"))
|
||||||
|
return
|
||||||
|
end
|
||||||
|
complete_job = Auth.completeQrLoginAsync(info, function(user, complete_err)
|
||||||
|
complete_job = nil
|
||||||
|
if cancelled then return end
|
||||||
|
if not user then
|
||||||
|
-- 不自动换码:留在框里讲清原因,由用户点「重新获取二维码」。
|
||||||
|
showFailure(complete_err or _("京东登录校验失败"))
|
||||||
|
return
|
||||||
|
end
|
||||||
|
closeDialog()
|
||||||
|
Toast:new{ text = _("登录成功"), timeout = 2 }:show()
|
||||||
|
require("source.registry").reload()
|
||||||
|
end)
|
||||||
|
end)
|
||||||
|
end)
|
||||||
|
end
|
||||||
|
startLogin()
|
||||||
|
end)
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 浏览器扩展登录是扫码之外的备用入口;只申请京东站点 Cookie,成功后由 API 验证再保存。
|
||||||
|
Setting.browser = {
|
||||||
|
domain = "e.m.jd.com",
|
||||||
|
scope = "cookie",
|
||||||
|
login = "https://e.m.jd.com/",
|
||||||
|
check = function()
|
||||||
|
local client = require("moonsource_jdread.client"):new{}
|
||||||
|
return client:apiUrl("/jdread/api/bookshelf/sort")
|
||||||
|
end,
|
||||||
|
check_json = { path = "result_code", ok = { 0 } },
|
||||||
|
icon = "https://e.m.jd.com/toc-web/ico.png",
|
||||||
|
isAuthorized = function()
|
||||||
|
return require("moonsource_jdread.auth").hasSession()
|
||||||
|
and not require("source.auth").expired("ext.jdread")
|
||||||
|
end,
|
||||||
|
apply = function(payload, cb)
|
||||||
|
return require("moonsource_jdread.auth").importBrowserAsync(payload, function(ok, err)
|
||||||
|
if ok then require("source.registry").reload() end
|
||||||
|
cb(ok, err)
|
||||||
|
end)
|
||||||
|
end,
|
||||||
|
}
|
||||||
|
|
||||||
|
--- 设置页行:账号(扫码);已登录时追加退出。
|
||||||
|
---@return table[]
|
||||||
|
function Setting.rows()
|
||||||
|
local Row = require("ui.themes.widgets.row")
|
||||||
|
local Auth = require("moonsource_jdread.auth")
|
||||||
|
local CookieLogin = require("source.cookie_login")
|
||||||
|
local rows = {
|
||||||
|
function(iw)
|
||||||
|
local status, status_on = Setting.rowStatus()
|
||||||
|
return Row.widget({ width = iw, chevron = true, kind = "nav", icon = "account_circle", title = _("京东读书账号"),
|
||||||
|
status = status, status_on = status_on,
|
||||||
|
callback = function() showQrLogin() end })
|
||||||
|
end,
|
||||||
|
CookieLogin.browserRow(),
|
||||||
|
}
|
||||||
|
if not Auth.hasSession() then return rows end
|
||||||
|
rows[#rows + 1] = require("source.logout").row("ext.jdread", _("确定退出京东读书账号?"), Auth.clearSession)
|
||||||
|
return rows
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 登录失效提示的「重新登录」直达入口(desktop.sync.promptLogin)。
|
||||||
|
Setting.login = showQrLogin
|
||||||
|
|
||||||
|
return Setting
|
||||||
@@ -0,0 +1,488 @@
|
|||||||
|
--[[--
|
||||||
|
京东读书数据源门面。
|
||||||
|
|
||||||
|
cookie + 设备 uuid,签名与章节 AES 在 protocol.lua。书架用 source.shelf;进度双向,无笔记、无统计。
|
||||||
|
目录只认下载协议版本 5(EPUB 按文件成章)和 3(网文),其余版本作废重拉。没有 ebook_id 的详情不进缓存。
|
||||||
|
段评借用微信读书同一本书(chapter_links),只在本章自己没有段评时借。
|
||||||
|
|
||||||
|
@module moonsource_jdread
|
||||||
|
--]]
|
||||||
|
|
||||||
|
local Client = require("moonsource_jdread.client")
|
||||||
|
local Mapper = require("moonsource_jdread.mapper")
|
||||||
|
local Toc = require("source.toc")
|
||||||
|
local Assets = require("source.assets")
|
||||||
|
local Paths = require("utils.paths")
|
||||||
|
local Request = require("http.request")
|
||||||
|
local SourceBase = require("source.base")
|
||||||
|
local Shelf = require("source.shelf")
|
||||||
|
local Browse = require("source.browse")
|
||||||
|
local Progress = require("book.progress")
|
||||||
|
local logger = require("utils.log")
|
||||||
|
local _ = require("l10n").get("moonsource_jdread")
|
||||||
|
|
||||||
|
local Jdread = {}
|
||||||
|
|
||||||
|
---@return BookSourceMeta
|
||||||
|
function Jdread.meta()
|
||||||
|
return require("moonsource_jdread.loadmeta")()
|
||||||
|
end
|
||||||
|
|
||||||
|
---@class JdreadSource : SourceBase
|
||||||
|
---@field _client JdreadClient
|
||||||
|
local Source = setmetatable({}, { __index = SourceBase })
|
||||||
|
Source.__index = Source
|
||||||
|
|
||||||
|
---@return JdreadSource
|
||||||
|
function Jdread.new()
|
||||||
|
local cfg = require("utils.settings").getSource("ext.jdread")
|
||||||
|
local meta = Jdread.meta()
|
||||||
|
return setmetatable({
|
||||||
|
id = meta.id,
|
||||||
|
name = meta.name,
|
||||||
|
type = meta.type,
|
||||||
|
_client = Client:new{ cookie = cfg.cookie, uuid = cfg.uuid },
|
||||||
|
}, Source)
|
||||||
|
end
|
||||||
|
|
||||||
|
---@return SourceCapabilities
|
||||||
|
function Source:capabilities()
|
||||||
|
return {
|
||||||
|
scrape = false,
|
||||||
|
edit = false,
|
||||||
|
stats_pull = false,
|
||||||
|
shelf_add = true,
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
---@return boolean
|
||||||
|
function Source:configured()
|
||||||
|
return self._client:configured()
|
||||||
|
end
|
||||||
|
|
||||||
|
---@param opts { dirty_only?: boolean, force?: boolean }|nil
|
||||||
|
---@param cb fun(result: SyncResult|nil, err: string|nil)
|
||||||
|
---@return { cancel: fun() }
|
||||||
|
function Source:syncBooksAsync(opts, cb)
|
||||||
|
return Shelf.syncAsync(self.id, self._client, Mapper.shelfList, opts, cb)
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 书城搜索:只取第一页。
|
||||||
|
---@param keyword string
|
||||||
|
---@param cb fun(res: { data: Book[] }|nil, err: string|nil)
|
||||||
|
---@return { cancel: fun() }
|
||||||
|
function Source:searchAsync(keyword, cb)
|
||||||
|
return self._client:searchAsync(keyword, 1, 20, function(wire, err)
|
||||||
|
if not wire then cb(nil, err); return end
|
||||||
|
cb({ data = Mapper.search(wire) })
|
||||||
|
end)
|
||||||
|
end
|
||||||
|
|
||||||
|
local RANK_PAGE = 20
|
||||||
|
|
||||||
|
--- 书城浏览:榜单类别(出版 / 男生 / 女生)、榜单、周期、分类四行 chip,节点是「类别:榜单:周期:分类」,
|
||||||
|
--- 缺省出版首个榜单的周榜。菜单与分类树每次现取,新鲜度由数据获取层缓存(source.store_cache)管;分类 id 只认对应类别根下一级。
|
||||||
|
---@param opts { node?: string, limit?: integer }
|
||||||
|
---@param cb fun(res: { data: Book[], groups: StoreChipGroup[] }|nil, err: string|nil)
|
||||||
|
---@return { cancel: fun() }
|
||||||
|
function Source:browseAsync(opts, cb)
|
||||||
|
local handle = {}
|
||||||
|
function handle.cancel()
|
||||||
|
if handle.inner then handle.inner.cancel() end
|
||||||
|
end
|
||||||
|
-- 回调同步完成时已在 show 里换上在途句柄,外层赋值不能再覆盖(同 client 书架分批的 mine 记法)。
|
||||||
|
local step = 0
|
||||||
|
local function show(menu)
|
||||||
|
step = step + 1
|
||||||
|
local tid, kid, period, cat = (opts.node or ""):match("^(%d+):(%d+):(%a+):(%d*)$")
|
||||||
|
local function pick(rows, key, want)
|
||||||
|
for _idx, row in ipairs(rows) do
|
||||||
|
if tostring(row[key]) == want then return row end
|
||||||
|
end
|
||||||
|
return rows[1]
|
||||||
|
end
|
||||||
|
local rtype = pick(menu.types, "type", tid)
|
||||||
|
local kind = pick(rtype.kinds, "kind", kid)
|
||||||
|
local per = pick(kind.periods, "period", period)
|
||||||
|
cat = cat or ""
|
||||||
|
local function id(t, k, p, c)
|
||||||
|
return t.type .. ":" .. k.kind .. ":" .. p.period .. ":" .. c
|
||||||
|
end
|
||||||
|
local node = id(rtype, kind, per, cat)
|
||||||
|
local types, kinds, periods = {}, {}, {}
|
||||||
|
for _idx, t in ipairs(menu.types) do
|
||||||
|
types[#types + 1] = { id = id(t, t.kinds[1], t.kinds[1].periods[1], ""), title = t.name }
|
||||||
|
end
|
||||||
|
for _idx, k in ipairs(rtype.kinds) do
|
||||||
|
kinds[#kinds + 1] = { id = id(rtype, k, pick(k.periods, "period", per.period), cat), title = k.name }
|
||||||
|
end
|
||||||
|
for _idx, p in ipairs(kind.periods) do
|
||||||
|
periods[#periods + 1] = { id = id(rtype, kind, p, cat), title = p.name }
|
||||||
|
end
|
||||||
|
local cats = { { id = id(rtype, kind, per, ""), title = _("全部") } }
|
||||||
|
for _idx, sub in ipairs(menu.categories[rtype.name] or {}) do
|
||||||
|
cats[#cats + 1] = { id = id(rtype, kind, per, tostring(sub.id)), title = sub.name }
|
||||||
|
end
|
||||||
|
local groups = {
|
||||||
|
Browse.group(types, id(rtype, rtype.kinds[1], rtype.kinds[1].periods[1], "")),
|
||||||
|
Browse.group(kinds, node),
|
||||||
|
Browse.group(cats, node),
|
||||||
|
}
|
||||||
|
if #periods > 1 then table.insert(groups, 3, Browse.group(periods, node)) end
|
||||||
|
handle.inner = Browse.pages(function(page, done)
|
||||||
|
return self._client:rankAsync(kind.kind, per.period, cat, page, RANK_PAGE, function(wire, err)
|
||||||
|
if not wire then
|
||||||
|
done(nil, err)
|
||||||
|
return
|
||||||
|
end
|
||||||
|
local rows = type(wire.data) == "table" and wire.data or {}
|
||||||
|
done(Mapper.shelfList(rows), nil, #rows >= RANK_PAGE)
|
||||||
|
end)
|
||||||
|
end, opts.limit or 40, groups, cb)
|
||||||
|
end
|
||||||
|
local first = self._client:rankTypesAsync(function(types, err)
|
||||||
|
if not types then cb(nil, err); return end
|
||||||
|
local mine = step
|
||||||
|
local second = self._client:categoriesAsync(function(tree, err2)
|
||||||
|
if not tree then cb(nil, err2); return end
|
||||||
|
local categories = {}
|
||||||
|
for _idx, root in ipairs(tree.data.category_list) do
|
||||||
|
categories[root.show_name] = root.sub_category
|
||||||
|
end
|
||||||
|
show({ types = types.data, categories = categories })
|
||||||
|
end)
|
||||||
|
if step == mine then handle.inner = second end
|
||||||
|
end)
|
||||||
|
if step == 0 then handle.inner = first end
|
||||||
|
return handle
|
||||||
|
end
|
||||||
|
|
||||||
|
---@param identity BookIdentity
|
||||||
|
---@param cb fun(book: Book|nil, err: string|nil)
|
||||||
|
---@return CancelHandle|nil
|
||||||
|
function Source:getDetailAsync(identity, cb)
|
||||||
|
return self._client:bookInfoAsync(identity.stable_id, function(wire, err)
|
||||||
|
if not wire then cb(nil, err); return end
|
||||||
|
-- 没有 ebook_id 时 Mapper.book 会得到 stable_id "nil",不能写进缓存。
|
||||||
|
if type(wire.data) ~= "table" or wire.data.ebook_id == nil then cb(nil, _("书籍详情为空")); return end
|
||||||
|
local book = Mapper.book(wire.data)
|
||||||
|
local existing = require("book.books_db").get(self.id, book.stable_id)
|
||||||
|
if existing then
|
||||||
|
book.deleted = existing.deleted
|
||||||
|
end
|
||||||
|
local progress = require("book.progress_db").get(self.id, book.stable_id)
|
||||||
|
if progress then
|
||||||
|
book.percent = Progress.clampPercent(progress.fraction, false, true)
|
||||||
|
end
|
||||||
|
require("book.store").rememberMany({ book })
|
||||||
|
cb(book)
|
||||||
|
end)
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 目录版本 → download/chapter 查询参数(见 Mapper.chapters)。
|
||||||
|
--- 版本 5 是按文件成章、锚点小节挂 anchors 的 EPUB 目录;版本 2(一条目录一章)会把同一文件
|
||||||
|
--- 下载多遍,版本 4 丢了小节,均已失效。
|
||||||
|
local DOWNLOAD_QUERY = {
|
||||||
|
[3] = function(uid) return { type = 1, ids = uid } end,
|
||||||
|
[5] = function(uid) return { indexes = uid } end,
|
||||||
|
}
|
||||||
|
|
||||||
|
--- 只认下载协议目录;旧 cread 目录(版本 1)、旧 EPUB 目录(版本 2/4)与无版本目录一律失效。
|
||||||
|
---@param toc BookChapter[]|nil
|
||||||
|
---@return boolean
|
||||||
|
function Source:isTocCurrent(toc)
|
||||||
|
return type(toc) == "table" and type(toc[1]) == "table"
|
||||||
|
and DOWNLOAD_QUERY[toc[1].toc_version] ~= nil
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 读有效目录缓存;失效格式当场清掉库里那份,交给调用方重新拉取。
|
||||||
|
---@param self JdreadSource
|
||||||
|
---@param identity BookIdentity
|
||||||
|
---@return BookChapter[]|nil
|
||||||
|
local function currentToc(self, identity)
|
||||||
|
local toc = Toc.read(identity.source_id, identity.stable_id)
|
||||||
|
if toc == nil or self:isTocCurrent(toc) then return toc end
|
||||||
|
Toc.drop(identity.source_id, identity.stable_id)
|
||||||
|
return nil
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 强制拉取目录并写回缓存。
|
||||||
|
---@param self JdreadSource
|
||||||
|
---@param identity BookIdentity
|
||||||
|
---@param cb fun(toc: BookChapter[]|nil, err: string|nil)
|
||||||
|
---@return { cancel: fun() }
|
||||||
|
local function fetchTocAsync(self, identity, cb)
|
||||||
|
return self._client:catalogAsync(identity.stable_id, function(wire, err)
|
||||||
|
if not wire then cb(nil, err); return end
|
||||||
|
local chapters = Mapper.chapters(wire)
|
||||||
|
if not chapters then cb(nil, _("章节列表为空")); return end
|
||||||
|
if not Toc.put(identity.source_id, identity.stable_id, chapters) then
|
||||||
|
cb(nil, _("章节目录保存失败"))
|
||||||
|
return
|
||||||
|
end
|
||||||
|
cb(chapters)
|
||||||
|
end)
|
||||||
|
end
|
||||||
|
|
||||||
|
---@param identity BookIdentity
|
||||||
|
---@param cb fun(toc: BookChapter[]|nil, err: string|nil)
|
||||||
|
---@return { cancel: fun() }|nil
|
||||||
|
function Source:loadTocAsync(identity, cb)
|
||||||
|
local cached = currentToc(self, identity)
|
||||||
|
if cached then
|
||||||
|
local cancelled = false
|
||||||
|
require("ui/uimanager"):nextTick(function()
|
||||||
|
if not cancelled then cb(cached) end
|
||||||
|
end)
|
||||||
|
return { cancel = function() cancelled = true end }
|
||||||
|
end
|
||||||
|
return fetchTocAsync(self, identity, cb)
|
||||||
|
end
|
||||||
|
|
||||||
|
Source.refreshTocAsync = fetchTocAsync
|
||||||
|
|
||||||
|
---@param url string
|
||||||
|
---@param cb fun(data: string|nil, err: any)
|
||||||
|
---@return { cancel: fun() }|nil
|
||||||
|
local function downloadImage(url, cb)
|
||||||
|
return Request.get(url, {
|
||||||
|
accept = "image/avif,image/webp,image/apng,image/*,*/*;q=0.8",
|
||||||
|
headers = {
|
||||||
|
["Referer"] = "https://e.m.jd.com/",
|
||||||
|
},
|
||||||
|
timeout = require("http.timeout").net(3),
|
||||||
|
allow_redirects = true,
|
||||||
|
}, function(raw, err)
|
||||||
|
if not raw or raw == "" then
|
||||||
|
logger.dbg("jdread image download failed", url, err)
|
||||||
|
cb(nil, err)
|
||||||
|
else
|
||||||
|
cb(raw)
|
||||||
|
end
|
||||||
|
end)
|
||||||
|
end
|
||||||
|
|
||||||
|
---@param self JdreadSource
|
||||||
|
---@param identity BookIdentity
|
||||||
|
---@param chapter BookChapter
|
||||||
|
---@param cb fun(payload: ChapterContentPayload|nil, err: string|nil)
|
||||||
|
---@return CancelHandle|nil
|
||||||
|
local function fetchContent(self, identity, chapter, cb)
|
||||||
|
local cancelled, fetch_job, asset_job, cover = false, nil, nil, nil
|
||||||
|
local done = function(wire, err)
|
||||||
|
if cancelled then return end
|
||||||
|
if not wire then cb(nil, err); return end
|
||||||
|
local payload = Mapper.content(wire, chapter.title, cover)
|
||||||
|
if not payload then
|
||||||
|
cb(nil, err or _("京东读书网页协议读不到本章,请在京东读书 App 内阅读"))
|
||||||
|
return
|
||||||
|
end
|
||||||
|
asset_job = Assets.localizeAsync(
|
||||||
|
payload.html,
|
||||||
|
Paths.bookWorkDir(identity.stable_id, "ext.jdread") .. "/images",
|
||||||
|
downloadImage,
|
||||||
|
function(html)
|
||||||
|
if cancelled then return end
|
||||||
|
payload.html = html
|
||||||
|
cb(payload)
|
||||||
|
end
|
||||||
|
)
|
||||||
|
end
|
||||||
|
-- 调用方手里的 chapter 可能来自失效目录,uid 只从有效目录按 idx 取。
|
||||||
|
local function download(toc)
|
||||||
|
local target = toc[chapter.idx]
|
||||||
|
if not target then cb(nil, _("缺少章节信息")); return end
|
||||||
|
cover = target.cover
|
||||||
|
local query = DOWNLOAD_QUERY[toc[1].toc_version](target.uid)
|
||||||
|
fetch_job = self._client:downloadChapterAsync(identity.stable_id, query, done)
|
||||||
|
end
|
||||||
|
local toc = currentToc(self, identity)
|
||||||
|
if toc then
|
||||||
|
download(toc)
|
||||||
|
else
|
||||||
|
fetch_job = self:loadTocAsync(identity, function(fresh, err)
|
||||||
|
if cancelled then return end
|
||||||
|
if not fresh then cb(nil, err); return end
|
||||||
|
download(fresh)
|
||||||
|
end)
|
||||||
|
end
|
||||||
|
return { cancel = function()
|
||||||
|
cancelled = true
|
||||||
|
if fetch_job then fetch_job.cancel() end
|
||||||
|
if asset_job then asset_job.cancel() end
|
||||||
|
end }
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 绑定实例的正文下载函数,供 source.chapter 调用。
|
||||||
|
---@param self JdreadSource
|
||||||
|
---@return ChapterFetchContent
|
||||||
|
local function contentFetcher(self)
|
||||||
|
return function(ref, chapter, done)
|
||||||
|
return fetchContent(self, ref, chapter, done)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 旧目录一条一章,带锚点小节的书改成按文件成章后章号错位,已缓存的章节文件会对不上。
|
||||||
|
--- 开书前(书还没打开,删章节文件安全)在线比一次章数:变了就清整本缓存,没变的旧缓存照用。
|
||||||
|
---@param self JdreadSource
|
||||||
|
---@param identity BookIdentity
|
||||||
|
---@param cb fun()
|
||||||
|
---@return { cancel: fun() }|nil
|
||||||
|
local function migrateLayout(self, identity, cb)
|
||||||
|
local old = Toc.read(self.id, identity.stable_id)
|
||||||
|
if not old or #old == 0 or self:isTocCurrent(old)
|
||||||
|
or not require("ui/network/manager"):isConnected() then
|
||||||
|
cb()
|
||||||
|
return nil
|
||||||
|
end
|
||||||
|
return fetchTocAsync(self, identity, function(toc)
|
||||||
|
if toc and #toc ~= #old then
|
||||||
|
require("book.store").clearCache(self.id, identity.stable_id)
|
||||||
|
end
|
||||||
|
cb()
|
||||||
|
end)
|
||||||
|
end
|
||||||
|
|
||||||
|
---@param identity BookIdentity
|
||||||
|
---@param opts table|nil
|
||||||
|
---@param cb fun(path: string|nil, err: string|nil)
|
||||||
|
---@return { cancel: fun() }
|
||||||
|
function Source:openBookAsync(identity, opts, cb)
|
||||||
|
local cancelled, open_job = false, nil
|
||||||
|
local migrate_job = migrateLayout(self, identity, function()
|
||||||
|
if cancelled then return end
|
||||||
|
open_job = require("source.chapter").openWithUi(self, identity, identity.book, opts, {
|
||||||
|
loadToc = function(ref, done) return self:loadTocAsync(ref, done) end,
|
||||||
|
fetchContent = contentFetcher(self),
|
||||||
|
}, cb)
|
||||||
|
end)
|
||||||
|
return { cancel = function()
|
||||||
|
cancelled = true
|
||||||
|
if migrate_job then migrate_job.cancel() end
|
||||||
|
if open_job then open_job.cancel() end
|
||||||
|
end }
|
||||||
|
end
|
||||||
|
|
||||||
|
---@param identity BookIdentity
|
||||||
|
---@param toc BookChapter[]
|
||||||
|
---@param from_idx integer
|
||||||
|
---@param count integer
|
||||||
|
---@param cb fun()|nil
|
||||||
|
---@return { cancel: fun() }
|
||||||
|
function Source:prefetchChaptersAsync(identity, toc, from_idx, count, cb)
|
||||||
|
return require("source.chapter").prefetchAsync(identity, identity.book, toc, from_idx, count, {
|
||||||
|
fetchContent = contentFetcher(self),
|
||||||
|
}, cb)
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 缓存整本章节正文;已落盘章节由公共实现自动跳过。
|
||||||
|
---@param identity BookIdentity
|
||||||
|
---@param on_progress fun(done: integer, total: integer)|nil
|
||||||
|
---@param cb fun(ok: boolean, cached: integer, err: string|nil, total: integer, failed: integer)
|
||||||
|
---@return { cancel: fun() }
|
||||||
|
function Source:cacheAllChaptersAsync(identity, on_progress, cb, range)
|
||||||
|
return require("source.chapter").cacheAllAsync(self, identity, contentFetcher(self), on_progress, cb,
|
||||||
|
nil, range)
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 拉取云端进度,以章节 uid(对不上时用标题)映射本地连续章节号。
|
||||||
|
---@param identity BookIdentity
|
||||||
|
---@param cb fun(pos: ProgressPosition|nil, err: string|nil, meta: table|nil)
|
||||||
|
---@return { cancel: fun() }
|
||||||
|
function Source:getProgressAsync(identity, cb)
|
||||||
|
local cancelled, toc_job
|
||||||
|
local request = self._client:getProgressAsync(identity.stable_id, function(wire, err)
|
||||||
|
if cancelled then return end
|
||||||
|
if not wire then cb(nil, err); return end
|
||||||
|
local pos, uid = Mapper.progress(wire)
|
||||||
|
if not pos then cb(nil, nil, { empty = true }); return end
|
||||||
|
--- 按 uid 定位章节;JD 上报的 chapter_id 常对不上本地目录 uid,再按标题兜底。
|
||||||
|
---@param toc BookChapter[]|nil
|
||||||
|
local function locate(toc)
|
||||||
|
local idx = toc and Toc.index(identity.source_id, identity.stable_id, uid)
|
||||||
|
if not idx and pos.chapter_title then
|
||||||
|
for _idx, chapter in ipairs(toc or {}) do
|
||||||
|
if chapter.title == pos.chapter_title then
|
||||||
|
idx = chapter.idx
|
||||||
|
uid = chapter.uid
|
||||||
|
break
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
if idx then
|
||||||
|
pos.chapter_idx = idx
|
||||||
|
pos.extra = { chapter_uid = uid, chapter_idx = idx }
|
||||||
|
end
|
||||||
|
cb(pos)
|
||||||
|
end
|
||||||
|
local toc = currentToc(self, identity)
|
||||||
|
if toc then locate(toc); return end
|
||||||
|
toc_job = self:loadTocAsync(identity, function(fresh)
|
||||||
|
if cancelled then return end
|
||||||
|
locate(fresh)
|
||||||
|
end)
|
||||||
|
end)
|
||||||
|
return { cancel = function()
|
||||||
|
cancelled = true
|
||||||
|
request.cancel()
|
||||||
|
if toc_job then toc_job.cancel() end
|
||||||
|
end }
|
||||||
|
end
|
||||||
|
|
||||||
|
--- 推送全书比例和当前章节 uid。本地章节 HTML 与京东段落坐标不对应,故从章节起点恢复。
|
||||||
|
---@param identity BookIdentity
|
||||||
|
---@param pos ProgressPosition
|
||||||
|
---@param cb fun(ok: boolean|nil, err: string|nil)
|
||||||
|
---@return { cancel: fun() }
|
||||||
|
function Source:putProgressAsync(identity, pos, cb)
|
||||||
|
local cancelled, toc_job, push_job
|
||||||
|
local chapter_idx = pos.chapter_idx or identity.chapter_idx
|
||||||
|
|
||||||
|
local function push(toc)
|
||||||
|
local chapter = chapter_idx and toc[chapter_idx]
|
||||||
|
if not chapter then cb(nil, _("缺少章节信息")); return end
|
||||||
|
push_job = self._client:putProgressAsync(identity.stable_id, {
|
||||||
|
action = "create",
|
||||||
|
data_type = 0,
|
||||||
|
force = 2,
|
||||||
|
para_idx = 0,
|
||||||
|
offset_in_para = 0,
|
||||||
|
chapter_id = chapter.uid,
|
||||||
|
epub_chapter_title = pos.chapter_title or chapter.title,
|
||||||
|
quote_text = "",
|
||||||
|
percent = Progress.clampFraction(pos.fraction),
|
||||||
|
created_at = os.time(),
|
||||||
|
}, function(wire, err)
|
||||||
|
if cancelled then return end
|
||||||
|
cb(wire and true or nil, err)
|
||||||
|
end)
|
||||||
|
end
|
||||||
|
|
||||||
|
local toc = currentToc(self, identity)
|
||||||
|
if toc then
|
||||||
|
push(toc)
|
||||||
|
else
|
||||||
|
toc_job = self:loadTocAsync(identity, function(value, err)
|
||||||
|
if cancelled then return end
|
||||||
|
if not value then cb(nil, err); return end
|
||||||
|
push(value)
|
||||||
|
end)
|
||||||
|
end
|
||||||
|
return { cancel = function()
|
||||||
|
cancelled = true
|
||||||
|
if toc_job then toc_job.cancel() end
|
||||||
|
if push_job then push_job.cancel() end
|
||||||
|
end }
|
||||||
|
end
|
||||||
|
|
||||||
|
function Source:bookReviewsAsync(identity, cb)
|
||||||
|
local ref = { source_id = self.id, stable_id = identity.stable_id }
|
||||||
|
return require("book.review_cache").pageAsync(ref, "book", 0, function(done)
|
||||||
|
return self._client:bookCommentsAsync(identity.stable_id, 1, function(wire, err)
|
||||||
|
if not wire then done(nil, err); return end
|
||||||
|
done(Mapper.bookReviewPage(wire))
|
||||||
|
end)
|
||||||
|
end, cb)
|
||||||
|
end
|
||||||
|
|
||||||
|
return Jdread
|
||||||
@@ -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