✨ 初始提交:月读第三方书源插件集合

每个书源一个独立插件目录,含微信读书公众号订阅、书架导入等完整功能。

Co-authored-by: Copilot <[email protected]>
This commit is contained in:
GarfieldandCopilot committed 2026-11-16 12:08:03 +08:00
commit 818a3d9067
22 files changed
+4165

No files matched your search

@@ -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("&amp;", "&") 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