From f7c9afb9ca33033ddc701e09b721d1c30dc84733 Mon Sep 17 00:00:00 2001 From: Garfield Date: Mon, 16 Nov 2026 12:07:59 +0800 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20=E5=88=9D=E5=A7=8B=E6=8F=90?= =?UTF-8?q?=E4=BA=A4=EF=BC=9A=E6=9C=88=E8=AF=BB=E7=AC=AC=E4=B8=89=E6=96=B9?= =?UTF-8?q?=E4=B9=A6=E6=BA=90=E6=8F=92=E4=BB=B6=E9=9B=86=E5=90=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 每个书源一个独立插件目录,含微信读书公众号订阅、书架导入等完整功能。 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- moonsource-dedao.koplugin/README.md | 21 + moonsource-dedao.koplugin/_meta.lua | 5 + moonsource-dedao.koplugin/main.lua | 9 + moonsource-dedao.koplugin/moon_source.lua | 15 + .../moonsource_dedao/_meta.lua | 17 + .../moonsource_dedao/client.lua | 696 ++++++++++++++++++ .../moonsource_dedao/l10n/en.lua | 50 ++ .../moonsource_dedao/l10n/zh_TW.lua | 50 ++ .../moonsource_dedao/loadmeta.lua | 5 + .../moonsource_dedao/mapper.lua | 315 ++++++++ .../moonsource_dedao/qrlogin.lua | 141 ++++ .../moonsource_dedao/setting.lua | 251 +++++++ .../moonsource_dedao/source.lua | 280 +++++++ .../moonsource_dedao/verify.lua | 116 +++ .../moonsource_dedao/web/dedao_verify.html | 25 + .../moonsource_dedao/web/dedao_verify.js | 94 +++ tests/dedao/browse_spec.lua | 146 ++++ tests/dedao/client_spec.lua | 295 ++++++++ tests/dedao/operations_spec.lua | 251 +++++++ tests/dedao/qrlogin_spec.lua | 65 ++ tests/dedao/setting_spec.lua | 156 ++++ tests/dedao/verify_spec.lua | 101 +++ 22 files changed, 3104 insertions(+) create mode 100644 moonsource-dedao.koplugin/README.md create mode 100644 moonsource-dedao.koplugin/_meta.lua create mode 100644 moonsource-dedao.koplugin/main.lua create mode 100644 moonsource-dedao.koplugin/moon_source.lua create mode 100644 moonsource-dedao.koplugin/moonsource_dedao/_meta.lua create mode 100644 moonsource-dedao.koplugin/moonsource_dedao/client.lua create mode 100644 moonsource-dedao.koplugin/moonsource_dedao/l10n/en.lua create mode 100644 moonsource-dedao.koplugin/moonsource_dedao/l10n/zh_TW.lua create mode 100644 moonsource-dedao.koplugin/moonsource_dedao/loadmeta.lua create mode 100644 moonsource-dedao.koplugin/moonsource_dedao/mapper.lua create mode 100644 moonsource-dedao.koplugin/moonsource_dedao/qrlogin.lua create mode 100644 moonsource-dedao.koplugin/moonsource_dedao/setting.lua create mode 100644 moonsource-dedao.koplugin/moonsource_dedao/source.lua create mode 100644 moonsource-dedao.koplugin/moonsource_dedao/verify.lua create mode 100644 moonsource-dedao.koplugin/moonsource_dedao/web/dedao_verify.html create mode 100644 moonsource-dedao.koplugin/moonsource_dedao/web/dedao_verify.js create mode 100644 tests/dedao/browse_spec.lua create mode 100644 tests/dedao/client_spec.lua create mode 100644 tests/dedao/operations_spec.lua create mode 100644 tests/dedao/qrlogin_spec.lua create mode 100644 tests/dedao/setting_spec.lua create mode 100644 tests/dedao/verify_spec.lua diff --git a/moonsource-dedao.koplugin/README.md b/moonsource-dedao.koplugin/README.md new file mode 100644 index 0000000..b578d03 --- /dev/null +++ b/moonsource-dedao.koplugin/README.md @@ -0,0 +1,21 @@ +# 得到 + +| 能力 | 是否支持 | 备注 | +| --- | --- | --- | +| 手机短信登录 | 支持 | 中国大陆手机号;未注册号码可能自动注册,发送前需确认协议 | +| 短信安全验证 | 部分支持 | 手机访问远程网页完成官方易盾滑块;触发验证后的完整续发流程未实测 | +| App 扫码登录 | 已实现,未实测 | 得到 App 扫码,不是微信扫码 | +| 浏览器登录与 Cookie 导入 | 支持 | 保留官网登录及粘贴入口 | +| 设备密码登录 | 不支持 | 未接入 | +| 书架拉取 | 支持 | 分页读取“已购”电子书集合,过滤课程、听书和自上传内容 | +| 加入与移出远端集合 | 已实现,未实测 | 本地先生效,再同步;移出不撤销购买 | +| 搜索与分类书城 | 支持 | 动态分类、子分类、排序和筛选,支持后续页,默认聚合约 60 本 | +| 详情与目录 | 支持 | 目录需阅读 token;真实登录后的读取尚待验证 | +| 正文与全本缓存 | 已实现,未实测 | SVG 解密与文字还原,需有效阅读权限;真实登录阅读链路未验证 | +| 离线阅读 | 支持 | 仅已成功缓存的目录与正文 | +| 阅读进度同步 | 部分支持 | 仅章节位置,无精确章内位置;真实远端写入未实测 | +| 笔记与统计同步 | 不支持 | 仅本地保存 | +| 整书书评 | 支持 | 读取真实书评列表,支持客户端分页去重 | +| 章评、段评与回复 | 不支持 | 未接入可验证的公共评论接口;原版笔记及笔记回复不是章/段评 | +| 评论写操作 | 不支持 | 不发评、不点赞、不删评 | +| 账号切换 | 部分支持 | 已绑定账号时拒绝直接换号;须先退出清理,旧配置迁移隔离有限 | diff --git a/moonsource-dedao.koplugin/_meta.lua b/moonsource-dedao.koplugin/_meta.lua new file mode 100644 index 0000000..39fc56a --- /dev/null +++ b/moonsource-dedao.koplugin/_meta.lua @@ -0,0 +1,5 @@ +local _ = require("gettext") +return { + fullname = _("月读书源:得到"), + description = _("给月读增加「得到」书源。需要同时安装月读,与平台官方无关。"), +} diff --git a/moonsource-dedao.koplugin/main.lua b/moonsource-dedao.koplugin/main.lua new file mode 100644 index 0000000..9d44d12 --- /dev/null +++ b/moonsource-dedao.koplugin/main.lua @@ -0,0 +1,9 @@ +--[[-- +KOReader 只认带 main.lua 的插件目录;书源本身不需要任何插件钩子,月读读取旁边的 moon_source.lua。 +--]] +local WidgetContainer = require("ui/widget/container/widgetcontainer") + +return WidgetContainer:extend{ + name = "moonsource_dedao", + is_doc_only = false, +} diff --git a/moonsource-dedao.koplugin/moon_source.lua b/moonsource-dedao.koplugin/moon_source.lua new file mode 100644 index 0000000..169fa20 --- /dev/null +++ b/moonsource-dedao.koplugin/moon_source.lua @@ -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_dedao.source").meta() end, + new = function() return require("moonsource_dedao.source").new() end, + setting = lazy("moonsource_dedao.setting"), +} diff --git a/moonsource-dedao.koplugin/moonsource_dedao/_meta.lua b/moonsource-dedao.koplugin/moonsource_dedao/_meta.lua new file mode 100644 index 0000000..bd09cd4 --- /dev/null +++ b/moonsource-dedao.koplugin/moonsource_dedao/_meta.lua @@ -0,0 +1,17 @@ +--[[-- +书源元信息:id / 名称 / 类型,加上启用页展示用的说明与能力清单。`init.lua` 的 `meta()` 直接返回本表。 + +得到 PC(www.dedao.cn)支持短信和 App 扫码。书架是「已购 - 电子书」,正文为加密 SVG。 + +@module moonsource_dedao._meta +--]] + +local _ = require("l10n").get("moonsource_dedao") + +return { + id = "ext.dedao", + name = _("得到阅读"), + type = "chapter", + description = _("得到电子书书架与在线阅读"), + abilities = { _("搜索与发现"), _("书架同步"), _("进度同步"), _("书评"), _("手机号验证码登录"), _("扫码登录"), _("浏览器登录") }, +} diff --git a/moonsource-dedao.koplugin/moonsource_dedao/client.lua b/moonsource-dedao.koplugin/moonsource_dedao/client.lua new file mode 100644 index 0000000..f577041 --- /dev/null +++ b/moonsource-dedao.koplugin/moonsource_dedao/client.lua @@ -0,0 +1,696 @@ +--[[-- +得到网页接口。 + +登录可用短信或得到 App 扫码,会话由 Set-Cookie 建立。 +短信候选会话归登录窗口所有,不覆盖正在使用的账号。书架是已购电子书。 + +@module moonsource_dedao.client +--]] + +local JSON = require("json") +local Mapper = require("moonsource_dedao.mapper") +local Request = require("http.request") +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_dedao") + +local Client = {} + +local SOURCE_ID = "ext.dedao" +local ORIGIN = "https://www.dedao.cn" +local LOGIN_EXPIRED = "得到登录已失效,请点「重新登录」,用得到 App 扫码。" + +local PAGE = { + density = 1, + direction = 1, + font_name = "yahei", + font_scale = 1, + font_size = 20, + height = 1600, + line_height = "2em", + margin_bottom = 100, + margin_left = 90, + margin_right = 90, + margin_top = 0, + paragraph_space = "1em", + platform = 0, + width = 900, +} + +local jar = {} + +--- 同步回调也可能发起下一步,返回较晚的旧句柄不能覆盖它。 +local function sequence() + local state = { serial = 0, cancelled = false } + function state.cancel() + state.cancelled = true + state.serial = state.serial + 1 + if state.job then state.job.cancel() end + state.job = nil + end + function state.run(start, ...) + if state.cancelled then return end + state.serial = state.serial + 1 + local serial = state.serial + state.job = nil + local job = start(...) + if state.cancelled then + if job then job.cancel() end + elseif state.serial == serial then + state.job = job + end + end + return state +end + +---@param header string|nil +---@param login_jar table|nil +local function remember(header, login_jar) + local target = login_jar or jar + if type(header) ~= "string" or header == "" then return end + for part in header:gmatch("[^;]+") do + local name, value = part:match("^%s*([^=;%s]+)=([^%s].*)$") + if not name then name, value = part:match("^%s*([^=;%s]+)=(.*)$") end + if name and value and name ~= "Path" and name ~= "Domain" and name ~= "Expires" + and name ~= "Max-Age" and name ~= "SameSite" then + target[name] = value + end + end +end + +function Client.reset() + jar = {} +end + +function Client.load() + Client.reset() + remember(require("utils.settings").getSource(SOURCE_ID).cookie) +end + +---@param login_jar table|nil +---@return string|nil +function Client.cookie(login_jar) + local target = login_jar or jar + local names = {} + for name in pairs(target) do names[#names + 1] = name end + table.sort(names) + if #names == 0 then return nil end + local parts = {} + for _idx, name in ipairs(names) do parts[#parts + 1] = name .. "=" .. target[name] end + return table.concat(parts, "; ") +end + +---@return boolean +function Client.loggedIn() + local cfg = require("utils.settings").getSource(SOURCE_ID) + return cfg.logged_in == true and cfg.cookie ~= nil and cfg.cookie ~= "" +end + +---@param login_jar table|nil +function Client.persist(login_jar) + local settings = require("utils.settings") + if login_jar then jar = login_jar end + settings.getSource(SOURCE_ID).cookie = Client.cookie(login_jar) + settings.saveSource(SOURCE_ID) +end + +---@param res table|nil +---@param login_jar table|nil +local function absorb(res, login_jar) + if not res then return end + for _idx, line in ipairs(Request.headerAll(res, "Set-Cookie")) do remember(line, login_jar) end +end + +---@param login_jar table|nil +---@return string|nil +local function csrf(login_jar) + return (login_jar or jar).csrfToken +end + +---@param extra table|nil +---@param login_jar table|nil +---@return table +local function headers(extra, login_jar) + local out = { + ["Xi-DT"] = "web", + Accept = "application/json", + } + local token = csrf(login_jar) + if token then out["Xi-Csrf-Token"] = token end + local cookie = Client.cookie(login_jar) + if cookie then out.Cookie = cookie end + for key, value in pairs(extra or {}) do out[key] = value end + return out +end + +---@param wire table +---@param authed boolean +---@return table|nil +---@return string|nil +local function payload(wire, authed) + local head = type(wire.h) == "table" and wire.h or nil + local code = tonumber(head and head.c or wire.errCode) + if not code then return nil, _("响应无效") end + if code ~= 0 then + if authed and code == 401 then + return nil, require("source.auth").expire(SOURCE_ID, _(LOGIN_EXPIRED)) + end + local message = head and head.e + return nil, type(message) == "string" and message ~= "" and message or _("请求失败") + end + if authed and code == 0 then require("source.auth").ok(SOURCE_ID) end + if wire.c ~= nil then return wire.c end + return wire +end + +---@param method string +---@param path string +---@param body string|nil +---@param extra table|nil +---@param content_type string|nil +---@param cb fun(body: any, err: string|nil, res: table|nil) +---@param login_jar table|nil +---@return HttpJob +local function call(method, path, body, extra, content_type, cb, login_jar) + local url = path:find("^https?://") and path or ORIGIN .. path + local target = login_jar or jar + local account_cookie = not login_jar and require("utils.settings").getSource(SOURCE_ID).cookie + local opts = { + accept = "application/json", + headers = headers(extra, target), + timeout = require("http.timeout").net(), + } + if content_type then opts.content_type = content_type end + local function done(raw, err, res) + absorb(res, target) + local authed = not login_jar and Client.loggedIn() + and account_cookie == require("utils.settings").getSource(SOURCE_ID).cookie + if authed and res and tonumber(res.code) == 401 then + cb(nil, require("source.auth").expire(SOURCE_ID, _(LOGIN_EXPIRED)), res) + return + end + if not raw then + local message = err and tostring(err):lower() or "" + local timed_out = message:find("timeout", 1, true) or message:find("timed out", 1, true) + require("utils.log").warn("dedao request failed", method, path:match("^[^?]+"), + timed_out and "timeout" or "network_error", "timeout_seconds", opts.timeout, + "status", res and tonumber(res.code)) + cb(nil, err and tostring(err) or _("请求失败"), res) + return + end + local ok, wire = pcall(JSON.decode, raw) + if not ok or type(wire) ~= "table" then cb(nil, _("响应无效"), res); return end + local data, reason = payload(wire, authed) + cb(data, reason, res) + end + if method == "POST" then return Request.post(url, body, opts, done) end + return Request.get(url, opts, done) +end + +---@param cb fun(ok: boolean|nil, err: string|nil) +---@param login_jar table|nil +---@return HttpJob +function Client.bootstrapAsync(cb, login_jar) + if not login_jar then Client.load() end + if csrf(login_jar) then return require("source.base").defer(cb, true) end + local target = login_jar or jar + return Request.get(ORIGIN .. "/", { + headers = headers(nil, target), + accept = "text/html", + timeout = require("http.timeout").net(), + }, function(_raw, err, res) + absorb(res, target) + if not csrf(target) then cb(nil, err and tostring(err) or _("请求失败")); return end + if not login_jar and target == jar then Client.persist() end + cb(true) + end) +end + +---@param cb fun(token: string|nil, err: string|nil) +---@param login_jar table|nil +---@return { cancel: fun() } +function Client.accessTokenAsync(cb, login_jar) + local handle = sequence() + handle.run(Client.bootstrapAsync, function(ok, err) + if handle.cancelled then return end + if not ok then cb(nil, err); return end + handle.run(Request.post, ORIGIN .. "/loginapi/getAccessToken", "", { + headers = headers(nil, login_jar), + accept = "application/json", + content_type = "application/json", + timeout = require("http.timeout").net(0.5), + }, function(raw, reason, res) + if handle.cancelled then return end + absorb(res, login_jar) + if not raw then cb(nil, reason and tostring(reason) or _("获取二维码失败")); return end + local decoded, wire = pcall(JSON.decode, raw) + local token = decoded and wire or Text.trim(raw) + if type(token) == "table" then + local data, err = payload(token, false) + reason = err + token = type(data) == "table" and data.token or data + end + if type(token) ~= "string" or token == "" then cb(nil, reason or _("获取二维码失败")); return end + cb(token) + end) + end, login_jar) + return handle +end + +---@class DedaoSMSLoginSession +---@field current fun(): boolean 本次登录尝试仍属于当前账号 +---@field oauth string +---@field jar table +---@field phone string +---@class DedaoSMSChallenge +---@field session DedaoSMSLoginSession +---@field captcha_id string + +---@param session DedaoSMSLoginSession +---@param captcha table|nil +---@param cb fun(ok: boolean|nil, err: string|nil, captcha_id: string|nil) +function Client.sendSessionCodeAsync(session, captcha, cb) + return call("POST", "/oauth/api/embedded/auth_code/send", JSON.encode({ + areaCode = "86", phone = session.phone, sysCode = "4", pname = "", scene = "", captcha = captcha, + }), { ["X-Oauth-Access-Token"] = session.oauth }, "application/json", function(body, err) + local data = type(body) == "table" and body.data or nil + if type(data) ~= "table" then cb(nil, err or _("发送验证码失败")); return end + if data.needCaptcha then + if type(data.captchaId) ~= "string" or data.captchaId == "" then + cb(nil, _("响应无效")) + return + end + cb(nil, nil, data.captchaId) + return + end + cb(true) + end, session.jar) +end + +---@param phone string +---@param cb fun(session: DedaoSMSLoginSession|nil, err: string|nil, challenge: DedaoSMSChallenge|nil) +---@return { cancel: fun() } +function Client.sendCodeAsync(phone, cb) + local current = require("source.auth").beginLogin(SOURCE_ID) + local login_jar = {} + local handle = sequence() + handle.run(Client.accessTokenAsync, function(token, err) + if handle.cancelled then return end + if not current() then cb(nil, _("账号已变化,请重新登录")); return end + if not token then cb(nil, err); return end + local session = { oauth = token, jar = login_jar, phone = phone, current = current } + handle.run(Client.sendSessionCodeAsync, session, nil, function(ok, reason, captcha_id) + if handle.cancelled then return end + if not current() then cb(nil, _("账号已变化,请重新登录")); return end + if captcha_id then + cb(nil, nil, { session = session, captcha_id = captcha_id }) + return + end + if not ok then cb(nil, reason); return end + cb(session) + end) + end, login_jar) + return handle +end + +---@param login_jar table +---@param cb fun(user: table|nil, err: string|nil) +function Client.checkLoginAsync(login_jar, cb) + return call("GET", "/api/pc/user/info", nil, nil, nil, function(user, reason) + if type(user) ~= "table" or type(user.uid_hazy) ~= "string" or user.uid_hazy == "" then + cb(nil, reason or _("登录失败")) + return + end + cb(user) + end, login_jar) +end + +---@param login_jar table +---@param cb fun(ok: boolean|nil, err: string|nil) +---@param current (fun(): boolean)|nil +function Client.confirmLoginAsync(login_jar, cb, current) + current = current or require("source.auth").beginLogin(SOURCE_ID) + local cfg = require("utils.settings").getSource(SOURCE_ID) + local previous, previous_uid = cfg.cookie, cfg.uid + return Client.checkLoginAsync(login_jar, function(user, reason) + if not current() or cfg.cookie ~= previous or cfg.uid ~= previous_uid then + cb(nil, _("账号已变化,请重新登录")); return + end + if not user then cb(nil, reason); return end + if (cfg.uid or cfg.cookie or cfg.logged_in) and cfg.uid ~= user.uid_hazy then + local cleared = require("source.logout").clear(SOURCE_ID, function() + cfg.cookie, cfg.uid, cfg.logged_in = nil, nil, nil + require("utils.settings").saveSource(SOURCE_ID) + Client.reset() + end) + if not cleared then cb(nil, _("准备本地同步失败")); return end + end + cfg.uid, cfg.logged_in = user.uid_hazy, true + Client.persist(login_jar) + cb(true) + end) +end + +---@param session DedaoSMSLoginSession +---@param code string +---@param cb fun(ok: boolean|nil, err: string|nil) +---@return { cancel: fun() } +function Client.smsLoginAsync(session, code, cb) + local handle = sequence() + handle.run(call, "POST", "/oauth/api/embedded/auth_code/check", JSON.encode({ + code = code, autoRegister = true, withUser = false, channelType = "iget_web", + authByGW = true, expireTime = "2592000", + }), { ["X-Oauth-Access-Token"] = session.oauth }, "application/json", function(body, err) + if handle.cancelled then return end + local data = type(body) == "table" and body.data or nil + if type(data) ~= "table" then cb(nil, err or _("登录失败")); return end + if type(data.errorMessage) == "string" and data.errorMessage ~= "" then cb(nil, data.errorMessage); return end + handle.run(Client.confirmLoginAsync, session.jar, function(ok, reason) + if not handle.cancelled then cb(ok, reason) end + end, session.current) + end, session.jar) + return handle +end + +---@param oauth string +---@param cb fun(code: string|nil, err: string|nil) +---@return HttpJob +function Client.qrCreateAsync(oauth, cb, login_jar) + return call("GET", "/oauth/api/embedded/qrcode", nil, { ["X-Oauth-Access-Token"] = oauth }, nil, function(body, err) + local data = type(body) == "table" and body.data or nil + local code = type(data) == "table" and data.qrCodeString or nil + if type(code) ~= "string" or code == "" then cb(nil, err or _("获取二维码失败")); return end + cb(code) + end, login_jar) +end + +---@param oauth string +---@param code string +---@param cb fun(wire: table|nil, err: string|nil) +---@return HttpJob +function Client.qrPollAsync(oauth, code, cb, login_jar) + return call("POST", "/oauth/api/embedded/qrcode/check_login", JSON.encode({ + qrCode = code, keepLogin = true, + }), { ["X-Oauth-Access-Token"] = oauth }, "application/json", function(body, err) + if type(body) ~= "table" or body.data == nil then cb(nil, err or _("请求失败")); return end + cb(body, err) + end, login_jar) +end + +local function authed(cb) + Client.load() + if Client.loggedIn() then return nil end + return require("source.base").defer(cb, nil, _("未登录得到")) +end + +---@param cb fun(body: table|nil, err: string|nil) +---@return { cancel: fun() } +function Client:shelfSyncAsync(cb) + local denied = authed(cb) + if denied then return denied end + local handle, rows, seen = sequence(), {}, {} + local function nextPage(page) + handle.run(call, "POST", "/api/hades/v2/product/list", JSON.encode({ + category = "ebook", + display_group = true, + filter = "all", + filter_complete = 0, + group_id = 0, + order = "study", + page = page, + page_size = 18, + sort_type = "desc", + }), nil, "application/json", function(body, err) + if handle.cancelled then return end + if type(body) ~= "table" or type(body.list) ~= "table" then cb(nil, err or _("响应无效")); return end + local added = 0 + for _idx, row in ipairs(body.list) do + if type(row) ~= "table" or type(row.enid) ~= "string" or row.enid == "" then + cb(nil, _("响应无效")) + return + end + if not seen[row.enid] then + seen[row.enid] = true + rows[#rows + 1], added = row, added + 1 + end + end + if body.is_more == true or body.is_more == 1 then + if added == 0 then cb(nil, _("响应无效")); return end + nextPage(page + 1) + return + end + cb({ list = rows, is_more = false }) + end) + end + nextPage(1) + return handle +end + +---@param stable_id string +---@param cb fun(ok: boolean|nil, err: string|nil) +---@return HttpJob|{ cancel: fun() } +function Client:addToShelfAsync(stable_id, cb) + local denied = authed(cb) + if denied then return denied end + return call("POST", "/api/pc/ebook2/v1/bookshelf/add", JSON.encode({ + book_enids = { stable_id }, ptype = 2, + }), nil, "application/json", function(body, err) + local result = type(body) == "table" and (body.data or body) or nil + local count = type(result) == "table" and tonumber(result.n) or nil + if not count or count <= 0 then cb(nil, err or _("请求失败")); return end + cb(true) + end) +end + +---@param stable_id string +---@param cb fun(ok: boolean|nil, err: string|nil) +---@return HttpJob|{ cancel: fun() } +function Client:removeFromShelfAsync(stable_id, cb) + local denied = authed(cb) + if denied then return denied end + return call("POST", "/api/pc/hades/v1/product/pcremove", JSON.encode({ + data = { { pid = stable_id, ptype = 2 } }, + }), nil, "application/json", function(body, err) + local result = type(body) == "table" and (body.data or body) or nil + local count = type(result) == "table" and tonumber(result.n) or nil + if not count or count < 0 then cb(nil, err or _("请求失败")); return end + cb(true) + end) +end + +---@param keyword string +---@param cb fun(body: table|nil, err: string|nil) +---@return { cancel: fun() } +function Client.searchAsync(keyword, cb, page) + local handle = sequence() + handle.run(Client.bootstrapAsync, function(ok, err) + if handle.cancelled then return end + if not ok then cb(nil, err); return end + handle.run(call, "POST", "/api/search/pc/tophits", JSON.encode({ + content = keyword, page = page or 1, page_size = 20, search_type = 0, tab_type = 2, + }), nil, "application/json", function(body, reason) + if handle.cancelled then return end + if type(body) ~= "table" or type(body.data) ~= "table" or type(body.data.moduleList) ~= "table" then + cb(nil, reason or _("响应无效")) + return + end + cb(body) + end) + end) + return handle +end + +---@param stable_id string +---@param cb fun(body: table|nil, err: string|nil) +---@return { cancel: fun() } +function Client.detailAsync(stable_id, cb) + local handle = sequence() + handle.run(Client.bootstrapAsync, function(ok, err) + if handle.cancelled then return end + if not ok then cb(nil, err); return end + handle.run(call, "GET", "/pc/ebook2/v1/pc/detail?" .. Text.formEncode({ id = stable_id, ptype = 2 }), nil, nil, nil, function(body, reason) + if not handle.cancelled then cb(body, reason) end + end) + end) + return handle +end + +---@param stable_id string +---@param cb fun(token: string|nil, err: string|nil) +---@return HttpJob|{ cancel: fun() } +function Client.readTokenAsync(stable_id, cb) + local denied = authed(cb) + if denied then return denied end + return call("POST", "/api/pc/ebook2/v1/pc/read/token", JSON.encode({ id = stable_id }), nil, "application/json", function(body, err) + local token = type(body) == "table" and body.token or nil + if type(token) ~= "string" or token == "" then cb(nil, err or _("请求失败")); return end + cb(token) + end) +end + +---@param stable_id string +---@param cb fun(info: table|nil, err: string|nil) +---@return { cancel: fun() } +function Client.bookInfoAsync(stable_id, cb) + local handle = sequence() + handle.run(Client.readTokenAsync, stable_id, function(token, err) + if handle.cancelled then return end + if not token then cb(nil, err); return end + handle.run(call, "GET", "/ebk_web/v1/get_book_info?" .. Text.formEncode({ token = token }), nil, nil, nil, function(body, reason) + if not handle.cancelled then cb(body, reason) end + end) + end) + return handle +end + +---@param token string +---@param chapter_id string +---@param index integer +---@param cb fun(body: table|nil, err: string|nil) +---@return HttpJob +local function pages(token, chapter_id, index, cb) + return call("POST", "/ebk_web_go/v2/get_pages", JSON.encode({ + chapter_id = chapter_id, + config = PAGE, + count = 20, + index = index, + offset = 0, + orientation = 0, + token = token, + }), nil, "application/json", cb) +end + +---@param stable_id string +---@param chapter_id string +---@param cb fun(text: string|nil, err: string|nil, kind: "unpaid"|nil) +---@return { cancel: fun() } +function Client.contentAsync(stable_id, chapter_id, cb) + local handle = sequence() + handle.run(Client.readTokenAsync, stable_id, function(token, err) + if handle.cancelled then return end + if not token then cb(nil, err); return end + local parts = {} + local function nextIndex(index, guard) + if guard > 40 then cb(nil, _("响应无效")); return end + handle.run(pages, token, chapter_id, index, function(body, reason) + if handle.cancelled then return end + if type(body) ~= "table" then + if reason == "user no legal!" then cb(nil, _("本章未购买"), "unpaid"); return end + cb(nil, reason or _("响应无效")) + return + end + local list = body.pages + if type(list) ~= "table" then cb(nil, _("响应无效")); return end + for _idx, page in ipairs(list) do + local text = type(page) == "table" and Mapper.pageText(page.svg) or nil + if text == nil then cb(nil, _("响应无效")); return end + if text ~= "" then parts[#parts + 1] = text end + end + local last = list[#list] + if body.is_end == true or (type(last) == "table" and last.is_last == true) then + if #parts == 0 then cb(nil, _("响应无效")); return end + cb(table.concat(parts, "\n\n")) + return + end + if #list == 0 then cb(nil, _("响应无效")); return end + nextIndex(index + #list, guard + 1) + end) + end + nextIndex(0, 1) + end) + return handle +end + +---@param query table +---@param cb fun(body: table|nil, err: string|nil) +function Client.browseFiltersAsync(query, cb) + local handle = sequence() + handle.run(Client.bootstrapAsync, function(ok, err) + if handle.cancelled then return end + if not ok then cb(nil, err); return end + handle.run(call, "POST", "/pc/label/v2/algo/pc/filter/list", JSON.encode(query), nil, "application/json", function(body, reason) + if not handle.cancelled then cb(body, reason) end + end) + end) + return handle +end + +---@param query table +---@param page integer +---@param cb fun(body: table|nil, err: string|nil) +function Client.browsePageAsync(query, page, cb) + local data = {} + for key, value in pairs(query) do data[key] = value end + data.page = page - 1 + return call("POST", "/pc/label/v2/algo/pc/product/list", JSON.encode(data), nil, "application/json", cb) +end + +---@param stable_id string +---@param cb fun(body: table|nil, err: string|nil) +function Client.reviewsAsync(stable_id, cb) + local handle = sequence() + handle.run(Client.bootstrapAsync, function(ok, err) + if handle.cancelled then return end + if not ok then cb(nil, err); return end + local rows, seen = {}, {} + local function nextPage(page) + handle.run(call, "POST", "/pc/ebook2/v1/comment/list", JSON.encode({ + enid = stable_id, page = page, page_size = 20, sort = "like_count", ptype = 2, + }), nil, "application/json", function(body, reason) + if handle.cancelled then return end + local total = type(body) == "table" and tonumber(body.total) or nil + if not total or total < 0 or type(body.list) ~= "table" then + cb(nil, reason or _("响应无效")) + return + end + local added = 0 + for _idx, row in ipairs(body.list) do + if type(row) ~= "table" or type(row.note_id_hazy) ~= "string" then + cb(nil, _("响应无效")) + return + end + if not seen[row.note_id_hazy] then + seen[row.note_id_hazy] = true + rows[#rows + 1], added = row, added + 1 + end + end + if #rows < math.min(total, 60) then + if added == 0 then cb(nil, _("响应无效")); return end + nextPage(page + 1) + return + end + cb({ list = rows, total = total }) + end) + end + nextPage(1) + end) + return handle +end + +---@param stable_id string +---@param cb fun(item: table|nil, err: string|nil) +---@return HttpJob|{ cancel: fun() } +function Client.progressAsync(stable_id, cb) + local denied = authed(cb) + if denied then return denied end + return call("POST", "/api/pc/ebook2/v1/pc/getread", JSON.encode({ id = stable_id }), nil, "application/json", function(body, err) + if type(body) ~= "table" then cb(nil, err); return end + cb(body.data or body) + end) +end + +---@param stable_id string +---@param chapter_id string +---@param summary string +---@param cb fun(ok: boolean|nil, err: string|nil) +---@return HttpJob|{ cancel: fun() } +function Client.putProgressAsync(stable_id, chapter_id, summary, cb) + local denied = authed(cb) + if denied then return denied end + return call("POST", "/api/pc/ebook2/v1/pc/addread", JSON.encode({ + findex = chapter_id, windex = 0, id = stable_id, summary = summary, + }), nil, "application/json", function(body, err) + cb(body and true or nil, err) + end) +end + +return Client diff --git a/moonsource-dedao.koplugin/moonsource_dedao/l10n/en.lua b/moonsource-dedao.koplugin/moonsource_dedao/l10n/en.lua new file mode 100644 index 0000000..8842225 --- /dev/null +++ b/moonsource-dedao.koplugin/moonsource_dedao/l10n/en.lua @@ -0,0 +1,50 @@ +return { + ["得到登录 Cookie"] = "Dedao login Cookie", + ["滑块加载失败,请检查网络后刷新网页"] = "Could not load the slider. Check your connection and refresh the page.", + ["短信验证码"] = "SMS code", + ["获取验证码"] = "Get code", + ["正在发送短信…"] = "Sending the SMS…", + ["得到阅读"] = "Dedao Reading", + ["得到电子书书架与在线阅读"] = "Dedao ebook shelf and online reading", + ["得到扫码登录"] = "Dedao QR sign-in", + ["用得到 App 扫一扫"] = "Scan with the Dedao app", + ["未登录得到"] = "Not signed in to Dedao", + ["得到目录为空"] = "Dedao chapter list is empty", + ["得到登录已失效,请点「重新登录」,用得到 App 扫码。"] = "Dedao sign-in has expired. Tap Sign in again and scan with the Dedao app.", + ["确定退出得到账号?"] = "Sign out of Dedao?", + ["得到账号"] = "Dedao account", + ["得到安全验证"] = "Dedao security verification", + ["手机号验证码登录"] = "Sign in with an SMS code", + ["手机号验证码或得到 App 扫码登录"] = "Sign in with an SMS code or the Dedao app", + ["请先获取验证码"] = "Request a verification code first", + ["发送验证码失败"] = "Could not send the verification code", + ["发送验证码即同意得到的用户服务协议与隐私政策,未注册手机号将自动注册。"] = "Requesting a code means accepting Dedao's terms of service and privacy policy. Unregistered phone numbers will be registered automatically.", + ["扫码登录"] = "Sign in with QR code", + ["请先退出当前账号,再登录其他账号"] = "Sign out of the current account before signing in to another account", + ["本书未购买,或试读额度已用完。\n请先在得到购买本书或开通电子书会员。"] = "This book is not purchased, or the trial allowance has been used up.\nPurchase the book or activate an ebook membership on Dedao.", + ["缺少得到章节位置"] = "Missing Dedao chapter position", + ["本章未购买"] = "This chapter has not been purchased", + ["验证已过期,请重新发起验证"] = "Verification expired. Please start again", + ["未登录 · 点此扫码"] = "Not signed in · tap to scan", + ["正在登录…"] = "Signing in…", + ["章节目录保存失败"] = "Failed to save chapter list", + ["拖动下方滑块完成拼图"] = "Drag the slider below to complete the puzzle", + ["用同一 Wi-Fi 下的手机扫码,只完成滑块;短信验证码请回到设备填写。"] = "Scan with a phone on the same Wi-Fi to solve only the slider. Enter the SMS code on the device.", + ["验证通过,短信已发送,请回到设备填写验证码。"] = "Verified. The SMS has been sent. Enter the code on the device.", + ["短信已发送,请在设备上填写验证码"] = "SMS sent. Enter the code on the device", + ["手机号"] = "Phone number", + ["请填写正确的手机号"] = "Enter a valid phone number", + ["同意并继续"] = "Agree and continue", + ["按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"] = "Press F12, open Network, refresh, and copy the entire Cookie request header", + ["无法打开远程验证,请先连接 Wi-Fi 并启用远程管理功能"] = "Cannot open remote verification. Connect to Wi-Fi and enable Remote management first.", + ["验证已取消"] = "Verification cancelled", + ["验证失败,请重新滑动验证"] = "Verification failed. Try the slider again.", + ["验证凭据无效"] = "Invalid verification proof", + ["正在提交验证…"] = "Submitting verification…", + ["请填写验证码"] = "Enter the verification code", + ["重试"] = "Retry", + ["书架同步"] = "Shelf sync", + ["搜索与发现"] = "Search and discover", + ["进度同步"] = "Progress sync", + ["得到"] = "Dedao", +} diff --git a/moonsource-dedao.koplugin/moonsource_dedao/l10n/zh_TW.lua b/moonsource-dedao.koplugin/moonsource_dedao/l10n/zh_TW.lua new file mode 100644 index 0000000..36eb295 --- /dev/null +++ b/moonsource-dedao.koplugin/moonsource_dedao/l10n/zh_TW.lua @@ -0,0 +1,50 @@ +return { + ["得到登录 Cookie"] = "得到登入 Cookie", + ["滑块加载失败,请检查网络后刷新网页"] = "滑塊載入失敗,請檢查網路後重新整理網頁", + ["短信验证码"] = "簡訊驗證碼", + ["获取验证码"] = "取得驗證碼", + ["正在发送短信…"] = "正在發送簡訊…", + ["得到阅读"] = "得到閱讀", + ["得到电子书书架与在线阅读"] = "得到電子書書架與線上閱讀", + ["得到扫码登录"] = "得到掃碼登入", + ["用得到 App 扫一扫"] = "用得到 App 掃一掃", + ["未登录得到"] = "未登入得到", + ["得到目录为空"] = "得到目錄為空", + ["得到登录已失效,请点「重新登录」,用得到 App 扫码。"] = "得到登入已失效,請點「重新登入」,用得到 App 掃碼。", + ["确定退出得到账号?"] = "確定退出得到帳號?", + ["得到账号"] = "得到帳號", + ["得到安全验证"] = "得到安全驗證", + ["手机号验证码登录"] = "手機號碼驗證碼登入", + ["手机号验证码或得到 App 扫码登录"] = "手機號碼驗證碼或得到 App 掃碼登入", + ["请先获取验证码"] = "請先取得驗證碼", + ["发送验证码失败"] = "傳送驗證碼失敗", + ["发送验证码即同意得到的用户服务协议与隐私政策,未注册手机号将自动注册。"] = "傳送驗證碼即同意得到的使用者服務協議與隱私政策,未註冊手機號碼將自動註冊。", + ["扫码登录"] = "掃碼登入", + ["请先退出当前账号,再登录其他账号"] = "請先退出目前帳號,再登入其他帳號", + ["本书未购买,或试读额度已用完。\n请先在得到购买本书或开通电子书会员。"] = "本書未購買,或試讀額度已用完。\n請先在得到購買本書或開通電子書會員。", + ["缺少得到章节位置"] = "缺少得到章節位置", + ["本章未购买"] = "本章未購買", + ["验证已过期,请重新发起验证"] = "驗證已過期,請重新發起驗證", + ["未登录 · 点此扫码"] = "未登入 · 點此掃碼", + ["正在登录…"] = "正在登入…", + ["章节目录保存失败"] = "章節目錄儲存失敗", + ["拖动下方滑块完成拼图"] = "拖動下方滑塊完成拼圖", + ["用同一 Wi-Fi 下的手机扫码,只完成滑块;短信验证码请回到设备填写。"] = "用同一 Wi-Fi 下的手機掃碼,只完成滑塊;簡訊驗證碼請回到裝置填寫。", + ["验证通过,短信已发送,请回到设备填写验证码。"] = "驗證通過,簡訊已傳送,請回到裝置填寫驗證碼。", + ["短信已发送,请在设备上填写验证码"] = "簡訊已傳送,請在裝置上填寫驗證碼", + ["手机号"] = "手機號碼", + ["请填写正确的手机号"] = "請填寫正確的手機號碼", + ["同意并继续"] = "同意並繼續", + ["按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"] = "按鍵盤 F12,點「網路」,重新整理網頁,複製請求標頭裡的整段 Cookie", + ["无法打开远程验证,请先连接 Wi-Fi 并启用远程管理功能"] = "無法打開遠端驗證,請先連接 Wi-Fi 並啟用遠端管理功能", + ["验证已取消"] = "驗證已取消", + ["验证失败,请重新滑动验证"] = "驗證失敗,請重新滑動驗證", + ["验证凭据无效"] = "驗證憑據無效", + ["正在提交验证…"] = "正在提交驗證…", + ["请填写验证码"] = "請填寫驗證碼", + ["重试"] = "重試", + ["书架同步"] = "書架同步", + ["搜索与发现"] = "搜尋與發現", + ["进度同步"] = "進度同步", + ["得到"] = "得到", +} diff --git a/moonsource-dedao.koplugin/moonsource_dedao/loadmeta.lua b/moonsource-dedao.koplugin/moonsource_dedao/loadmeta.lua new file mode 100644 index 0000000..d38ea32 --- /dev/null +++ b/moonsource-dedao.koplugin/moonsource_dedao/loadmeta.lua @@ -0,0 +1,5 @@ +return function() + local copy = {} + for k, v in pairs(require("moonsource_dedao._meta")) do copy[k] = v end + return copy +end diff --git a/moonsource-dedao.koplugin/moonsource_dedao/mapper.lua b/moonsource-dedao.koplugin/moonsource_dedao/mapper.lua new file mode 100644 index 0000000..d863157 --- /dev/null +++ b/moonsource-dedao.koplugin/moonsource_dedao/mapper.lua @@ -0,0 +1,315 @@ +--[[-- +得到网页响应 → 领域对象。纯函数,不发请求。 + +正文 SVG 是 AES-256-CBC。密钥和 IV 写在阅读器脚本的 decrypt 里,和网页同一套。 + +@module moonsource_dedao.mapper +--]] + +local Aes = require("crypto.aes") +local Text = require("utils.text") + +local Mapper = {} + +local SOURCE_ID = "ext.dedao" +Mapper.TOC_VERSION = 1 + +local SVG_KEY = "3e4r06tjkpjcevlbslr3d96gdb5ahbmo" +local SVG_IV = "6fd89a1b3a7f48fb" +local QR_URL = "https://m.igetget.com/oauth/qrcode/v2/authorize?token=%s&source=igetweb&dv=" + +---@param value any +---@return string +local function clean(value) + if type(value) ~= "string" then return "" end + return Text.trim(Text.xmlDecode(value:gsub("", ""))) +end + +---@param id string +---@param title string|nil +---@param author string|nil +---@param intro string|nil +---@param cover string|nil +---@return Book +local function book(id, title, author, intro, cover) + local picture = type(cover) == "string" and cover ~= "" and cover or nil + return { + source_id = SOURCE_ID, + stable_id = id, + title = clean(title), + authors = clean(author), + intro = clean(intro), + cover = picture, + } +end + +--- 扫码内容。网页把 qrCodeString 编进这张 URL,得到 App 认的是这张图。 +---@param code string|nil +---@return string|nil +function Mapper.qrText(code) + if type(code) ~= "string" or code == "" then return nil end + return string.format(QR_URL, code) +end + +--- 轮询 data.status:0 继续等,1 成功,2 二维码失效。 +---@param wire table|nil +---@return "wait"|"ok"|"fail" +function Mapper.login(wire) + local data = type(wire) == "table" and wire.data or nil + local status = type(data) == "table" and tonumber(data.status) or nil + if status == 0 then return "wait" end + if status == 1 then return "ok" end + return "fail" +end + +--- 已购电子书。听书、课程、本地上传不在这张书架里。 +---@param wire table|nil +---@return Book[] +function Mapper.shelf(wire) + local out = {} + local rows = type(wire) == "table" and wire.list or nil + if type(rows) ~= "table" then return out end + for _idx, row in ipairs(rows) do + if type(row) == "table" and tonumber(row.type) == 2 and type(row.enid) == "string" and row.enid ~= "" then + local item = book(row.enid, row.title, row.author, row.intro, row.icon) + if item.title ~= "" then out[#out + 1] = item end + end + end + return out +end + +--- 搜索 tab 电子书。标题里的高亮标签丢掉。 +---@param wire table|nil +---@return Book[] +function Mapper.search(wire) + local out, seen = {}, {} + local data = type(wire) == "table" and wire.data or nil + local modules = type(data) == "table" and data.moduleList or nil + if type(modules) ~= "table" then return out end + for _m, mod in ipairs(modules) do + local rows = type(mod) == "table" and mod.layerDataList or nil + if type(rows) == "table" then + for _idx, row in ipairs(rows) do + local extra = type(row) == "table" and row.extra or nil + local enid = type(extra) == "table" and extra.enid or nil + if type(enid) == "string" and enid ~= "" and tonumber(row.type) == 2 and not seen[enid] then + seen[enid] = true + local item = book(enid, row.Title or row.title, row.author, row.content, row.image) + if item.title ~= "" then out[#out + 1] = item end + end + end + end + end + return out +end + +---@param body table|nil +---@return Book[]|nil +function Mapper.catalog(body) + if type(body) ~= "table" or type(body.product_list) ~= "table" then return nil end + local out = {} + for _idx, row in ipairs(body.product_list) do + if tonumber(row.item_type) == 2 and type(row.id_out) == "string" and row.id_out ~= "" then + local authors = type(row.author_list) == "table" and table.concat(row.author_list, "、") or "" + local item = book(row.id_out, row.name, authors, row.intro or row.introduction, row.index_img) + if item.title ~= "" then out[#out + 1] = item end + end + end + return out +end + +---@param body table +---@return table[] +function Mapper.reviews(body) + local out = {} + for _idx, row in ipairs(body.list) do + local text = Text.stripHtml(row.note_line) + local note = Text.stripHtml(row.note) + if note ~= "" then text = text ~= "" and text .. "\n" .. note or note end + if text == "" then text = Text.stripHtml(row.content) end + if text ~= "" then + local owner = type(row.notes_owner) == "table" and row.notes_owner or {} + local extra = type(row.extra) == "table" and row.extra or {} + local created = tonumber(row.create_time) + out[#out + 1] = { + id = row.note_id_hazy, + author = owner.name or "", + text = text, + time = created and os.date("%Y-%m-%d", created) or nil, + grade = tonumber(extra.score_str), + } + end + end + return out +end + +---@param body table|nil +---@param stable_id string +---@return Book|nil +function Mapper.detail(body, stable_id) + if type(body) ~= "table" then return nil end + local id = type(body.enid) == "string" and body.enid ~= "" and body.enid or stable_id + -- 详情里 title 经常是空字符串,书名在 operating_title。 + local title = type(body.title) == "string" and body.title ~= "" and body.title or body.operating_title + local item = book(id, title, body.book_author, body.book_intro, body.cover) + if item.title == "" then return nil end + return item +end + +--- 阅读器目录。href 里 # 前面是 epub 路径,orders 把它换成 get_pages 要的章节号。 +---@param info table|nil +---@return BookChapter[] +function Mapper.chapters(info) + local book_info = type(info) == "table" and info.bookInfo or nil + if type(book_info) ~= "table" then return {} end + local by_path = {} + local orders = type(book_info.orders) == "table" and book_info.orders or {} + for _idx, row in ipairs(orders) do + if type(row) == "table" and row.pathInEpub and row.chapterId then + by_path[row.pathInEpub] = tostring(row.chapterId) + end + end + local rows = {} + local toc = type(book_info.toc) == "table" and book_info.toc or {} + for _idx, row in ipairs(toc) do rows[#rows + 1] = row end + table.sort(rows, function(a, b) + return (tonumber(a.playOrder) or 0) < (tonumber(b.playOrder) or 0) + end) + local out = {} + for _idx, row in ipairs(rows) do + if type(row) == "table" and type(row.href) == "string" and row.href ~= "" then + local path = row.href:match("^([^#]+)") or row.href + local uid = by_path[path] or path + local level = tonumber(row.level) or 0 + out[#out + 1] = { + uid = uid, + title = clean(row.text), + depth = level + 1, + } + end + end + for idx, chapter in ipairs(out) do chapter.idx = idx end + if out[1] then out[1].toc_version = Mapper.TOC_VERSION end + return out +end + +--- 进度 findex 就是章节号。 +---@param findex string|nil +---@return string|nil +function Mapper.progressUid(findex) + if type(findex) ~= "string" or findex == "" then return nil end + return findex +end + +local FULL_SLACK = 36 +local INDENT = 15 + +---@param tag string +---@param name string +---@return number|nil +local function attrNum(tag, name) + local value = tag:match(name .. '%s*=%s*"([%-%d%.]+)"') + or tag:match(name .. "%s*=%s*'([%-%d%.]+)'") + return tonumber(value) +end + +--- 一个字一个 text。空白字要留着,英文单词靠它隔开。 +---@param inner string +---@return string|nil +local function glyphText(inner) + local text = Text.xmlDecode(inner:gsub("<[^>]+>", ""):gsub("", "")) + if text == "" then return nil end + if Text.trim(text) == "" then return " " end + return text +end + +---@param buf string +---@param row string +---@return string +local function joinLine(buf, row) + local prev, nxt = buf:byte(-1), row:byte(1) + if prev and nxt and prev < 128 and nxt < 128 and buf:match("[%w]$") and row:match("^[%w]") then + return buf .. " " .. row + end + return buf .. row +end + +--- 同一基线是一行。没排满的行结束上一段;相对页边缩进的行另起一段。 +---@param glyphs { text: string, x: number, y: number, i: integer }[] +---@return string +local function flow(glyphs) + local lines = {} + for _, g in ipairs(glyphs) do + local last = lines[#lines] + if last and math.abs(g.y - last.y) <= 2 then + last.glyphs[#last.glyphs + 1] = g + if g.x < last.x0 then last.x0 = g.x end + if g.x > last.x1 then last.x1 = g.x end + else + lines[#lines + 1] = { y = g.y, x0 = g.x, x1 = g.x, glyphs = { g } } + end + end + local margin, right, min_gap = lines[1].x0, lines[1].x1, nil + for idx, line in ipairs(lines) do + if line.x0 < margin then margin = line.x0 end + if line.x1 > right then right = line.x1 end + local gap = idx > 1 and line.y - lines[idx - 1].y or 0 + if gap > 2 and (not min_gap or gap < min_gap) then min_gap = gap end + end + local paras, buf, prev = {}, "", nil + for _, line in ipairs(lines) do + table.sort(line.glyphs, function(a, b) + if a.x == b.x then return a.i < b.i end + return a.x < b.x + end) + local parts = {} + for _, g in ipairs(line.glyphs) do parts[#parts + 1] = g.text end + local row = table.concat(parts) + local gap = prev and line.y - prev.y or 0 + local fresh = not prev + or line.x0 > margin + INDENT + or prev.x1 < right - FULL_SLACK + or (min_gap and gap > min_gap * 1.5) + if fresh then + if buf ~= "" then paras[#paras + 1] = buf end + buf = row + else + buf = joinLine(buf, row) + end + prev = line + end + if buf ~= "" then paras[#paras + 1] = buf end + return table.concat(paras, "\n") +end + +--- 解开一页 SVG,抽出文字;空白页返回空串,解密失败返回 nil。 +--- 没有坐标的 text 仍是一段一个节点。有 x/y 的按基线排回段落。 +---@param cipher string|nil +---@return string|nil +function Mapper.pageText(cipher) + if type(cipher) ~= "string" or cipher == "" then return nil end + local raw = Text.base64Decode(cipher) + if #raw == 0 or #raw % 16 ~= 0 then return nil end + local ok, svg = pcall(Aes.cbc_decrypt, raw, SVG_KEY, SVG_IV) + if not ok or type(svg) ~= "string" or svg == "" then return nil end + local glyphs, positioned = {}, true + local index = 0 + for tag, inner in svg:gmatch("]*)>(.-)") do + local text = glyphText(inner) + if text then + index = index + 1 + local y = attrNum(tag, "y") + if not y then positioned = false end + glyphs[#glyphs + 1] = { text = text, x = attrNum(tag, "x") or 0, y = y or 0, i = index } + end + end + if #glyphs == 0 then return "" end + if not positioned then + local parts = {} + for _, g in ipairs(glyphs) do parts[#parts + 1] = Text.trim(g.text) end + return table.concat(parts, "\n") + end + return flow(glyphs) +end + +return Mapper diff --git a/moonsource-dedao.koplugin/moonsource_dedao/qrlogin.lua b/moonsource-dedao.koplugin/moonsource_dedao/qrlogin.lua new file mode 100644 index 0000000..a50df68 --- /dev/null +++ b/moonsource-dedao.koplugin/moonsource_dedao/qrlogin.lua @@ -0,0 +1,141 @@ +--[[-- +得到扫码登录。 + +先要匿名 Cookie 和 /loginapi/getAccessToken。二维码内容是 +m.igetget.com 的 authorize 链接,轮询 check_login。status 0 继续等,1 成功,2 过期。 + +@module moonsource_dedao.qrlogin +--]] + +local Client = require("moonsource_dedao.client") +local Mapper = require("moonsource_dedao.mapper") +local _ = require("l10n").get("moonsource_dedao") + +local QRLogin = {} +QRLogin.__index = QRLogin + +local POLL_INTERVAL = 1.5 +local POLL_LIMIT = 160 + +---@param on_user fun() +---@return table +function QRLogin:new(on_user) + return setmetatable({ on_user = on_user, generation = 0 }, QRLogin) +end + +function QRLogin:cancel() + self.generation = self.generation + 1 + if self.job and self.job.cancel then self.job.cancel() end + self.job = nil +end + +---@param text string +function QRLogin:toast(text) + require("ui.themes.widgets.toast"):new{ text = text, timeout = 3 }:show() +end + +---@param text string +function QRLogin:_retry(text) + self:cancel() + local dialog = self.dialog + self.dialog = nil + if dialog then dialog:close() end + require("ui.themes.widgets.confirm"):new{ + text = text, + ok_text = _("重新获取"), + ok_callback = function() self:start() end, + }:show() +end + +---@param gen integer +---@param oauth string +---@param code string +---@param polls integer +function QRLogin:_poll(gen, oauth, code, polls) + if gen ~= self.generation then return end + if polls > POLL_LIMIT then + self:_retry(_("二维码已过期")) + return + end + local pending = true + local job = Client.qrPollAsync(oauth, code, function(wire, err) + pending = false + if gen ~= self.generation then return end + self.job = nil + if not wire then + self:_retry(err or _("请求失败")) + return + end + local kind = Mapper.login(wire) + if kind == "ok" then + local confirming = true + local confirm = Client.confirmLoginAsync(self.jar, function(ok, reason) + confirming = false + if gen ~= self.generation then return end + if not ok then self:_retry(reason or _("登录失败")); return end + self:cancel() + local dialog = self.dialog + self.dialog = nil + if dialog then dialog:close() end + self.on_user() + end, self.current) + if confirming then self.job = confirm end + return + end + if kind ~= "wait" then + self:_retry(_("二维码已过期")) + return + end + require("ui/uimanager"):scheduleIn(POLL_INTERVAL, function() + if gen == self.generation then self:_poll(gen, oauth, code, polls + 1) end + end) + end, self.jar) + if pending then self.job = job end +end + +function QRLogin:start() + self:cancel() + local gen = self.generation + local current = require("source.auth").beginLogin("ext.dedao") + self.current = function() return gen == self.generation and current() end + self.jar = {} + local pending = true + local initial = Client.accessTokenAsync(function(oauth, err) + pending = false + if gen ~= self.generation then return end + if not oauth then + self:toast(err or _("获取二维码失败")) + return + end + local creating = true + local created = Client.qrCreateAsync(oauth, function(code, reason) + creating = false + if gen ~= self.generation then return end + self.job = nil + if not code then + self:toast(reason or _("获取二维码失败")) + return + end + local dialog + dialog = require("ui.themes.widgets.qr"):new{ + title = _("得到扫码登录"), + text = Mapper.qrText(code), + caption = _("用得到 App 扫一扫"), + close_callback = function() + if self.dialog == dialog then + self.dialog = nil + self:cancel() + self:toast(_("已取消登录")) + end + end, + } + self.dialog = dialog + dialog:show() + self:_poll(gen, oauth, code, 1) + end, self.jar) + if creating then self.job = created end + end, self.jar) + if pending then self.job = initial end +end + +return QRLogin diff --git a/moonsource-dedao.koplugin/moonsource_dedao/setting.lua b/moonsource-dedao.koplugin/moonsource_dedao/setting.lua new file mode 100644 index 0000000..8036136 --- /dev/null +++ b/moonsource-dedao.koplugin/moonsource_dedao/setting.lua @@ -0,0 +1,251 @@ +--[[-- +得到账号:手机号短信验证码、得到 App 扫码、官网浏览器登录及 Cookie 导入。 + +@module moonsource_dedao.setting +--]] + +local _ = require("l10n").get("moonsource_dedao") +local CookieLogin = require("source.cookie_login") + +local SOURCE_ID = "ext.dedao" +local Setting = {} +local LOGIN_URL = "https://www.dedao.cn/" + +---@return boolean +local function loggedIn() + return require("moonsource_dedao.client").loggedIn() +end + +--- Cookie 请求头 → 得到 client 用的 jar。 +---@param header string +---@return table +local function jarFromHeader(header) + local jar = {} + for part in tostring(header):gmatch("[^;]+") do + local name, value = part:match("^%s*([^=;%s]+)=([^%s].*)$") + if not name then name, value = part:match("^%s*([^=;%s]+)=(.*)$") end + if name and value and name ~= "Path" and name ~= "Domain" and name ~= "Expires" + and name ~= "Max-Age" and name ~= "SameSite" then + jar[name] = value + end + end + return jar +end + +local function save() + local settings = require("utils.settings") + local cfg = settings.getSource(SOURCE_ID) + cfg.logged_in = true + settings.saveSource(SOURCE_ID) + require("source.auth").ok(SOURCE_ID) + require("source.registry").reload() + require("ui.themes.widgets.toast"):new{ text = _("登录成功"), timeout = 2 }:show() +end + +---@return string, boolean +function Setting.rowStatus() + local on = loggedIn() + return on and _("已登录") or _("未登录 · 点此扫码"), on +end + +local function qrLogin() + require("ui/network/manager"):runWhenConnected(function() + require("moonsource_dedao.qrlogin"):new(save):start() + end) +end + +local function phoneLogin() + local Text = require("utils.text") + local Client = require("moonsource_dedao.client") + local Toast = require("ui.themes.widgets.toast") + local session, pending, waiting, dialog + local closed = false + local function validPhone(phone) + if #phone == 11 and phone:match("^1[3-9]%d+$") then return true end + Toast:new{ text = _("请填写正确的手机号") }:show() + return false + end + local function sendCode(phone) + require("ui/network/manager"):runWhenConnected(function() + if closed then return end + if pending then pending:cancel(); pending = nil end + if waiting then waiting:close() end + session = nil + local function received(value, err) + pending = nil + if closed then return end + if value then session = value end + Toast:new{ text = value and _("短信已发送,请在设备上填写验证码") or err or _("发送验证码失败") }:show() + end + waiting = require("ui.themes.widgets.progress_dialog"):new{ + title = _("得到账号"), text = _("正在发送短信…"), + on_cancel = function() if pending then pending:cancel(); pending = nil end end, + } + waiting:show() + local requesting = true + local request = Client.sendCodeAsync(phone, function(value, err, challenge) + requesting = false + pending = nil + waiting:close() + waiting = nil + if closed then return end + if challenge then + local verifying = true + local verification = require("moonsource_dedao.verify").new(challenge, function(result, reason) + verifying = false + received(result, reason) + end) + if verifying then pending = verification end + return + end + received(value, err) + end) + if requesting then pending = request end + end) + end + dialog = require("ui.themes.widgets.input"):new{ + title = _("得到账号"), + keep_open = true, + fields = { + { label = _("手机号"), input_type = "number" }, + { label = _("短信验证码"), input_type = "number" }, + }, + ok_text = _("登录"), + close_callback = function() + closed = true + if pending then pending:cancel() end + if waiting then waiting:close() end + end, + actions = { { text = _("获取验证码"), callback = function(phone) + phone = Text.trim(phone) + if not validPhone(phone) then return end + require("ui.themes.widgets.confirm"):new{ + title = _("得到账号"), + text = _("发送验证码即同意得到的用户服务协议与隐私政策,未注册手机号将自动注册。") + .. "\n\nhttps://zt.igetget.com/visual/1Onn4gr8OJT0QjGzq0O6.html" + .. "\nhttps://www.igetget.com/html/p/9MGZRxz/QlqnY8M8RzcKWG77q7Ln.html", + ok_text = _("同意并继续"), + ok_callback = function() sendCode(phone) end, + }:show() + end } }, + validate = function(phone, code) + phone, code = Text.trim(phone), Text.trim(code) + if not validPhone(phone) then return false end + if not session or session.phone ~= phone then + Toast:new{ text = _("请先获取验证码") }:show() + return false + end + if code == "" or not code:match("^%d+$") then + Toast:new{ text = _("请填写验证码") }:show() + return false + end + return true + end, + callback = function(_phone, code) + require("ui/network/manager"):runWhenConnected(function() + if closed then return end + if pending then pending:cancel(); pending = nil end + waiting = require("ui.themes.widgets.progress_dialog"):new{ + title = _("得到账号"), text = _("正在登录…"), + on_cancel = function() if pending then pending:cancel(); pending = nil end end, + } + waiting:show() + local requesting = true + local request = Client.smsLoginAsync(assert(session), Text.trim(code), function(ok, err) + requesting = false + pending = nil + waiting:close() + waiting = nil + if closed then return end + if ok then dialog:close(); save() else Toast:new{ text = err or _("登录失败") }:show() end + end) + if requesting then pending = request end + end) + end, + } + dialog:show() +end + +function Setting.open() + require("ui.themes.widgets.sheet"):new{ + title = _("得到账号"), + items = { + { text = _("手机号验证码登录"), callback = phoneLogin }, + { text = _("扫码登录"), callback = qrLogin }, + }, + }:show() +end + +local SPEC = { + id = SOURCE_ID, title = _("得到账号"), cookie_title = _("得到登录 Cookie"), + cookie_hint = _("按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"), + logout_text = _("确定退出得到账号?"), + loggedIn = loggedIn, + checkAsync = function(cookie, cb) + local jar = jarFromHeader(cookie) + if not next(jar) then return cb(false, _("没有读到 Cookie")) end + return require("moonsource_dedao.client").checkLoginAsync(jar, function(user, err) + cb(user ~= nil, err, user) + end) + end, + commit = function(cookie, user, cb, current) + local Settings = require("utils.settings") + local cfg = Settings.getSource(SOURCE_ID) + if not current() then return cb(false, _("账号已变化,请重新登录")) end + if (cfg.uid or cfg.cookie or cfg.logged_in) and cfg.uid ~= user.uid_hazy then + local cleared = require("source.logout").clear(SOURCE_ID, function() + cfg.cookie, cfg.uid, cfg.logged_in = nil, nil, nil + Settings.saveSource(SOURCE_ID) + require("moonsource_dedao.client").reset() + end) + if not cleared then return cb(false, _("准备本地同步失败")) end + end + cfg.cookie, cfg.logged_in, cfg.uid = cookie, true, user.uid_hazy + Settings.saveSource(SOURCE_ID) + require("moonsource_dedao.client").reset() + require("source.auth").ok(SOURCE_ID) + require("source.registry").reload() + cb(true) + end, + clear = function(cfg) + cfg.cookie, cfg.logged_in, cfg.uid = nil, nil, nil + require("moonsource_dedao.client").reset() + end, +} + +Setting.browser = { + domain = "www.dedao.cn", scope = "cookie", login = LOGIN_URL, + check = "https://www.dedao.cn/api/pc/user/info", + icon = "https://www.dedao.cn/apple-touch-icon.png", + isAuthorized = function() return CookieLogin.authorized(SPEC) end, + apply = function(payload, cb) + return CookieLogin.save(SPEC, CookieLogin.fromPayload(payload, "dedao.cn"), cb) + end, +} + +---@return table[] +function Setting.rows() + local Row = require("ui.themes.widgets.row") + local rows = { + function(iw) + local status, status_on = Setting.rowStatus() + return Row.widget({ + width = iw, chevron = true, kind = "nav", icon = "account_circle", + title = SPEC.title, + subtitle = _("手机号验证码或得到 App 扫码登录"), + status = status, status_on = status_on, + callback = function() Setting.open() end, + }) + end, + CookieLogin.browserRow(), + CookieLogin.pasteRow(SPEC), + } + if loggedIn() then + rows[#rows + 1] = CookieLogin.logoutRow(SPEC) + end + return rows +end + +Setting.login = Setting.open + +return Setting diff --git a/moonsource-dedao.koplugin/moonsource_dedao/source.lua b/moonsource-dedao.koplugin/moonsource_dedao/source.lua new file mode 100644 index 0000000..8f02938 --- /dev/null +++ b/moonsource-dedao.koplugin/moonsource_dedao/source.lua @@ -0,0 +1,280 @@ +--[[-- +得到数据源。 + +扫码登录后同步已购电子书。目录和正文要阅读 token,正文是网页同款加密 SVG。 + +@module moonsource_dedao +--]] + +local Client = require("moonsource_dedao.client") +local Mapper = require("moonsource_dedao.mapper") +local Shelf = require("source.shelf") +local SourceBase = require("source.base") +local Toc = require("source.toc") +local Text = require("utils.text") +local Browse = require("source.browse") +local JSON = require("json") +local _ = require("l10n").get("moonsource_dedao") + +local Dedao = {} + +---@return BookSourceMeta +function Dedao.meta() + return require("moonsource_dedao.loadmeta")() +end + +---@class DedaoSource : SourceBase +local Source = setmetatable({ shelf_add = true }, { __index = SourceBase }) +Source.__index = Source + +---@return DedaoSource +function Dedao.new() + local meta = Dedao.meta() + return setmetatable({ id = meta.id, name = meta.name, type = meta.type }, Source) +end + +---@return boolean +function Source:configured() + return Client.loggedIn() +end + +function Source:syncBooksAsync(opts, cb) + if not self:configured() then return SourceBase.skipped(cb, "dedao not logged in") end + return Shelf.syncAsync(self.id, Client, Mapper.shelf, opts, cb) +end + +---@param keyword string +---@param cb fun(res: { data: Book[] }|nil, err: string|nil) +function Source:searchAsync(keyword, cb) + return Browse.pages(function(page, done) + return Client.searchAsync(keyword, function(body, err) + if not body then done(nil, err); return end + done(Mapper.search(body), nil, body.data.isMore == true or body.data.isMore == 1) + end, page) + end, 60, {}, cb) +end + +local BROWSE_KEYS = { + "classfc_name", "label_id", "navigation_id", "sort_strategy", + "buy_strategy", "progress_strategy", "tags_ids", +} + +local function browseQuery(values) + ---@type table + local query = { nav_type = 0, product_types = "2", page = 0, page_size = 20 } + for _idx, key in ipairs(BROWSE_KEYS) do + local value = values[key] + if type(value) == "string" or key == "tags_ids" and type(value) == "table" and #value > 0 then + query[key] = value + end + end + return query +end + +local function browseGroups(filters, request) + local groups = {} + local function add(options, key, active, title) + local group = { title = title, chips = {} } + for _idx, option in ipairs(options) do + local value = browseQuery(request) + value[key] = option.value + if key == "navigation_id" then value.label_id = nil end + if key == "tags_ids" then value.tags_ids = { option.value } end + local id = JSON.encode(value) + group.chips[#group.chips + 1] = { id = id, title = option.name } + if option.value == active then group.active = id end + end + groups[#groups + 1] = group + end + local navigation = filters.navigations + add(navigation.options, "navigation_id", request.navigation_id, navigation.title) + for _idx, option in ipairs(navigation.options) do + if option.value == request.navigation_id and type(option.sub_options) == "table" and #option.sub_options > 0 then + add(option.sub_options, "label_id", request.label_id, navigation.title) + end + end + for _idx, key in ipairs({ "sort_strategy", "buy_strategy", "progress_strategy", "tags" }) do + local filter = filters[key] + if type(filter) == "table" and not filter.is_hide and type(filter.options) == "table" then + local field = key == "tags" and "tags_ids" or key + local active = field == "tags_ids" and request.tags_ids and request.tags_ids[1] or request[field] + add(filter.options, field, active or (filter.options[1] and filter.options[1].value), filter.title) + end + end + return groups +end + +function Source:browseAsync(opts, cb) + opts = opts or {} + local values = {} + if opts.node then + local decoded, node = pcall(JSON.decode, opts.node) + if not decoded or type(node) ~= "table" then return SourceBase.defer(cb, nil, _("响应无效")) end + values = node + end + local cancelled, pending, job = false, true, nil + local initial = Client.browseFiltersAsync(browseQuery(values), function(body, err) + pending = false + if cancelled then return end + if type(body) ~= "table" or type(body.request) ~= "table" or type(body.filter) ~= "table" + or type(body.filter.navigations) ~= "table" or type(body.filter.navigations.options) ~= "table" then + cb(nil, err or _("响应无效")) + return + end + local query = browseQuery(body.request) + local groups = browseGroups(body.filter, query) + job = Browse.pages(function(page, done) + return Client.browsePageAsync(query, page, function(data, reason) + local list = Mapper.catalog(data) + if not list then done(nil, reason or _("响应无效")); return end + query.request_id = data.request_id + done(list, nil, data.is_more == true or data.is_more == 1) + end) + end, opts.limit or 60, groups, cb) + end) + if pending then job = initial end + return { cancel = function() + cancelled = true + if job then job.cancel() end + end } +end + +function Source:bookReviewsAsync(book, cb) + return Client.reviewsAsync(book.stable_id, function(body, err) + if not body then cb(nil, err); return end + cb({ items = Mapper.reviews(body), total = body.total }) + end) +end + +function Source:getDetailAsync(identity, cb) + return Client.detailAsync(identity.stable_id, function(body, err) + local detail = Mapper.detail(body, identity.stable_id) + if detail then cb(require("book.store").rememberDetail(detail)); return end + local row = identity.book or require("book.books_db").get(self.id, identity.stable_id) + if row then cb(row); return end + cb(nil, err or _("请求失败")) + end) +end + +---@param self DedaoSource +---@param identity BookIdentity +---@param cb fun(toc: BookChapter[]|nil, err: string|nil) +local function fetchTocAsync(self, identity, cb) + return Client.bookInfoAsync(identity.stable_id, function(info, err) + if not info then cb(nil, err); return end + local toc = Mapper.chapters(info) + if #toc == 0 then cb(nil, _("得到目录为空")); return end + if not Toc.put(self.id, identity.stable_id, toc) then cb(nil, _("章节目录保存失败")); return end + cb(toc) + end) +end + +function Source:loadTocAsync(identity, cb, force) + if not force then + local cached = Toc.read(self.id, identity.stable_id) + if cached and #cached > 0 then + return SourceBase.defer(cb, cached) + end + end + return fetchTocAsync(self, identity, cb) +end + +Source.refreshTocAsync = fetchTocAsync + +local FLOW_MARK = "dedao-flow:1" + +---@param open boolean +---@return ChapterFetchContent +local function fetcher(open) + return function(identity, chapter, done) + return Client.contentAsync(identity.stable_id, chapter.uid, function(text, err, kind) + if text and not err then + done({ title = chapter.title, html = text, mark = FLOW_MARK }) + elseif open and kind == "unpaid" then + local notice = _("本书未购买,或试读额度已用完。\n请先在得到购买本书或开通电子书会员。") + done({ + title = chapter.title, + html = Text.chapterHtml(chapter.title, notice), + temporary = true, + }) + else + done(nil, err) + end + end) + end +end + +function Source:openBookAsync(identity, opts, cb) + local Chapter = require("source.chapter") + local open = opts and opts.chapter_idx and Chapter.openAsync or Chapter.openWithUi + return open(self, identity, identity.book, opts, { + loadToc = function(ref, done) return self:loadTocAsync(ref, done) end, + fetchContent = fetcher(true), + }, cb) +end + +function Source:prefetchChaptersAsync(identity, toc, from_idx, count, cb) + local Chapter = require("source.chapter") + return Chapter.prefetchAsync(identity, identity.book, toc, from_idx, count, { + fetchContent = fetcher(false), + }, cb) +end + +function Source:cacheAllChaptersAsync(identity, on_progress, cb, range) + local Chapter = require("source.chapter") + return Chapter.cacheAllAsync(self, identity, fetcher(false), on_progress, cb, nil, range) +end + +function Source:getProgressAsync(identity, cb) + if not self:configured() then return SourceBase.defer(cb, nil, _("未登录得到")) end + local cancelled, pending, job = false, true, nil + local initial = Client.progressAsync(identity.stable_id, function(item, err) + pending = false + if cancelled then return end + if err then cb(nil, err); return end + local uid = type(item) == "table" and Mapper.progressUid(item.findex) or nil + if not uid then cb(nil, nil, { empty = true }); return end + job = self:loadTocAsync(identity, function(toc, reason) + if cancelled then return end + if not toc or #toc == 0 then cb(nil, reason or _("得到目录为空")); return end + local idx = Toc.index(self.id, identity.stable_id, uid) + if not idx then cb(nil, nil, { empty = true }); return end + local fraction = (idx - 1) / #toc + cb({ + chapter_idx = idx, + chapter_title = toc[idx].title, + fraction = fraction, + extra = { chapter_uid = uid, chapter_idx = idx }, + }) + end) + end) + if pending then job = initial end + return { cancel = function() + cancelled = true + if job and job.cancel then job.cancel() end + end } +end + +function Source:putProgressAsync(identity, pos, cb) + if not self:configured() then return SourceBase.defer(cb, nil, _("未登录得到")) end + local cancelled, pending, job = false, true, nil + local initial = self:loadTocAsync(identity, function(toc, err) + pending = false + if cancelled then return end + if not toc then cb(nil, err); return end + local idx = tonumber(pos.chapter_idx) or tonumber(identity.chapter_idx) + local chapter = idx and toc[idx] + if not chapter then cb(nil, _("缺少得到章节位置")); return end + job = Client.putProgressAsync(identity.stable_id, chapter.uid, chapter.title, function(ok, perr) + if cancelled then return end + cb(ok and true or nil, perr) + end) + end) + if pending then job = initial end + return { cancel = function() + cancelled = true + if job and job.cancel then job.cancel() end + end } +end + +return Dedao diff --git a/moonsource-dedao.koplugin/moonsource_dedao/verify.lua b/moonsource-dedao.koplugin/moonsource_dedao/verify.lua new file mode 100644 index 0000000..ad64c50 --- /dev/null +++ b/moonsource-dedao.koplugin/moonsource_dedao/verify.lua @@ -0,0 +1,116 @@ +--[[-- +得到短信易盾验证。浏览器只交验证凭据,手机号、OAuth 与 Cookie 留在设备。 +五分钟票据绑定原候选登录会话,验证通过并成功发送短信后才继续登录。 + +@module moonsource_dedao.verify +--]] + +local Ext = require("utils.extension") +local Client = require("moonsource_dedao.client") +local _ = require("l10n").get("moonsource_dedao") + +---@class DedaoVerification +---@field ticket string +---@field challenge DedaoSMSChallenge +---@field callback fun(session: DedaoSMSLoginSession|nil, err: string|nil) +---@field expires integer +---@field pending table|nil +---@field dialog BookThemeQR|nil +---@field timeout function +---@field done boolean|nil +local Verification = {} +Verification.__index = Verification +---@type table +local sessions = {} + +function Verification:cancel() + if self.done then return end + self.done = true + sessions[self.ticket] = nil + require("ui/uimanager"):unschedule(self.timeout) + if self.pending and self.pending.job then self.pending.job.cancel() end + local dialog = self.dialog + self.dialog = nil + if dialog then dialog:close() end +end + +function Verification:finish(session, err) + if self.done then return end + self:cancel() + self.callback(session, err) +end + +---@param challenge DedaoSMSChallenge +---@param cb fun(session: DedaoSMSLoginSession|nil, err: string|nil) +---@return DedaoVerification +function Verification.new(challenge, cb) + local self = setmetatable({ + ticket = require("utils.random").hex(24), challenge = challenge, + callback = cb, expires = os.time() + 300, + }, Verification) + self.timeout = require("ui.guard").wrap("dedao verification timeout", function() + self:finish(nil, _("验证已过期,请重新发起验证")) + end) + sessions[self.ticket] = self + require("ui/uimanager"):scheduleIn(300, self.timeout) + self.dialog = Ext.call("web.open_page", "/dedao_verify.html#" .. self.ticket, + _("得到安全验证"), _("用同一 Wi-Fi 下的手机扫码,只完成滑块;短信验证码请回到设备填写。"), { + close_callback = function() self:finish(nil, _("验证已取消")) end, + }) + if not self.dialog then + self:finish(nil, _("无法打开远程验证,请先连接 Wi-Fi 并启用远程管理功能")) + end + return self +end + +local function handle(method, action, params, cb) + local function reply(status, body) + cb(status, body, { "Cache-Control: no-store" }) + end + if method ~= "POST" then return reply(405, { error = "Method Not Allowed" }) end + if action ~= "config" and action ~= "verify" then return reply(404, { error = "Not Found" }) end + local self = type(params.ticket) == "string" and sessions[params.ticket] + if not self or os.time() >= self.expires then + return reply(403, { error = _("验证已过期,请重新发起验证") }) + end + if action == "config" then + return reply(200, { + captcha_id = self.challenge.captcha_id, + title = _("得到安全验证"), instruction = _("拖动下方滑块完成拼图"), + pending = _("正在提交验证…"), + success = _("验证通过,短信已发送,请回到设备填写验证码。"), + failure = _("验证失败,请重新滑动验证"), + load_error = _("滑块加载失败,请检查网络后刷新网页"), retry = _("重试"), + }) + end + if type(params.validate) ~= "string" or params.validate == "" or #params.validate > 16384 then + return reply(400, { error = _("验证凭据无效") }) + end + if self.pending then return reply(409, { error = _("正在提交验证…") }) end + local operation = {} + self.pending = operation + local job = Client.sendSessionCodeAsync(self.challenge.session, { + captchaId = self.challenge.captcha_id, validate = params.validate, + }, function(ok, err, captcha_id) + if self.done then return reply(403, { error = _("验证已过期,请重新发起验证") }) end + if os.time() >= self.expires then + self:finish(nil, _("验证已过期,请重新发起验证")) + return reply(403, { error = _("验证已过期,请重新发起验证") }) + end + self.pending = nil + if captcha_id then self.challenge.captcha_id = captcha_id end + if not ok then return reply(400, { error = err or _("验证失败,请重新滑动验证") }) end + reply(200, { ok = true }) + self:finish(self.challenge.session) + end) + if self.pending == operation then operation.job = job end +end + +local dir = debug.getinfo(1, "S").source:sub(2):match("(.*/)") +Ext.add("web.routes", { + name = "dedao_verify", dir = dir .. "web", + assets = { "dedao_verify.html", "dedao_verify.js" }, + public = { config = true, verify = true }, handle = handle, +}) + +return Verification diff --git a/moonsource-dedao.koplugin/moonsource_dedao/web/dedao_verify.html b/moonsource-dedao.koplugin/moonsource_dedao/web/dedao_verify.html new file mode 100644 index 0000000..68fd439 --- /dev/null +++ b/moonsource-dedao.koplugin/moonsource_dedao/web/dedao_verify.html @@ -0,0 +1,25 @@ + + + + + + +月读 + + + + +
+

月读

+

+
+

+ +
+ + + diff --git a/moonsource-dedao.koplugin/moonsource_dedao/web/dedao_verify.js b/moonsource-dedao.koplugin/moonsource_dedao/web/dedao_verify.js new file mode 100644 index 0000000..42847ec --- /dev/null +++ b/moonsource-dedao.koplugin/moonsource_dedao/web/dedao_verify.js @@ -0,0 +1,94 @@ +(async function () { + 'use strict'; + const ticket = location.hash.slice(1); + const status = document.getElementById('status'); + const retry = document.getElementById('retry'); + let messages, captcha, submitting = false, generation = 0; + async function request(action, body) { + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), 45000); + try { + const response = await fetch('/api/dedao_verify/' + action, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ ...body, ticket }), + signal: controller.signal, + }); + const result = await response.json(); + if (!response.ok) throw new Error(result.error || response.statusText); + return result; + } finally { + clearTimeout(timer); + } + } + function failed(error) { + status.textContent = error.message || (messages && messages.failure) || String(error); + retry.hidden = false; + } + async function verify(error, result) { + if (submitting) return; + if (error || !result || typeof result.validate !== 'string' || !result.validate) { + failed(new Error(messages.failure)); + return; + } + submitting = true; + retry.hidden = true; + status.textContent = messages.pending; + try { + await request('verify', { validate: result.validate }); + if (captcha) captcha.destroy(); + captcha = null; + status.textContent = messages.success; + document.getElementById('captcha-element').hidden = true; + } catch (reason) { + failed(reason); + } finally { + submitting = false; + } + } + async function loadCaptcha() { + const current = ++generation; + retry.hidden = true; + const config = await request('config', {}); + if (current !== generation) return; + messages = config; + document.title = document.getElementById('title').textContent = messages.title; + document.getElementById('instruction').textContent = messages.instruction; + retry.textContent = messages.retry; + status.textContent = ''; + if (captcha) { captcha.destroy(); captcha = null; } + if (!window.initNECaptcha) { + await new Promise((resolve, reject) => { + const script = document.createElement('script'); + const timer = setTimeout(() => reject(new Error(messages.load_error)), 20000); + script.src = 'https://cstaticdun.126.net/load.min.js'; + script.onload = () => { clearTimeout(timer); resolve(); }; + script.onerror = () => { clearTimeout(timer); reject(new Error(messages.load_error)); }; + document.head.appendChild(script); + }); + } + await new Promise((resolve, reject) => { + const timer = setTimeout(() => { + if (current === generation) generation++; + reject(new Error(messages.load_error)); + }, 20000); + window.initNECaptcha({ + captchaId: messages.captcha_id, element: '#captcha-element', + mode: 'popup', width: '250px', apiVersion: 2, + onVerify: (error, result) => { if (current === generation) verify(error, result); }, + onClose: () => { if (current === generation && !submitting) retry.hidden = false; }, + }, instance => { + clearTimeout(timer); + if (current !== generation) { instance.destroy(); return; } + captcha = instance; + instance.verify(); + resolve(); + }, error => { + clearTimeout(timer); + reject(new Error(error && error.message || messages.load_error)); + }); + }); + } + retry.onclick = () => loadCaptcha().catch(failed); + await loadCaptcha().catch(failed); +})(); diff --git a/tests/dedao/browse_spec.lua b/tests/dedao/browse_spec.lua new file mode 100644 index 0000000..5f4c9e3 --- /dev/null +++ b/tests/dedao/browse_spec.lua @@ -0,0 +1,146 @@ +--[[-- +得到书城:服务器分类、子分类、排序、分页和旧目录离线兼容。 + +@module tests.moonsource_dedao.browse_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local Json = require("support.json_stub") +local queries, pages = {}, {} +local progress, pushed, read_cancelled, write_cancelled, async_progress = nil, nil, false, false, true +local cached = { { uid = "legacy-chapter", title = "旧目录" } } + +package.preload["json"] = function() return Json end +package.preload["source.base"] = function() + return { + loadMeta = function() return { id = "ext.dedao", name = "得到阅读", type = "chapter" } end, + defer = function(done, ...) + done(...) + return { cancel = function() end } + end, + } +end +package.preload["source.shelf"] = function() return {} end +package.preload["source.toc"] = function() return { read = function() return cached end } end +package.preload["moonsource_dedao.client"] = function() + return { + loggedIn = function() return true end, + progressAsync = function(_id, done) + progress = done + if not async_progress then done({ findex = "legacy-chapter" }) end + return { cancel = function() read_cancelled = true end } + end, + putProgressAsync = function(_id, _chapter, _title, done) + pushed = done + return { cancel = function() write_cancelled = true end } + end, + browseFiltersAsync = function(query, done) + queries[#queries + 1] = query + done({ + request = { navigation_id = query.navigation_id or "novel", label_id = query.label_id or "all", + sort_strategy = query.sort_strategy or "HOT", tags_ids = {} }, + filter = { + navigations = { title = "分类", options = { + { name = "小说", value = "novel", sub_options = { + { name = "全部", value = "all" }, { name = "推理", value = "mystery" }, + } }, + { name = "历史", value = "history" }, + } }, + sort_strategy = { title = "排序", options = { + { name = "最热", value = "HOT" }, { name = "最新", value = "NEW" }, + } }, + buy_strategy = { is_hide = true, options = {} }, + }, + }) + return { cancel = function() error("cancelled completed filter request") end } + end, + browsePageAsync = function(query, page, done) + pages[#pages + 1] = { query = query, page = page } + local rows = {} + for idx = 1, 20 do + rows[#rows + 1] = { + id_out = tostring((page - 1) * 20 + idx), item_type = 2, + name = "测试书", author_list = { "甲", "乙" }, index_img = "https://example.test/cover", + } + end + done({ product_list = rows, is_more = 1, request_id = "public-page-session" }) + return { cancel = function() end } + end, + searchAsync = function(_keyword, done, page) + done({ data = { isMore = page < 2, moduleList = { { layerDataList = { + { type = 2, title = "搜索书", extra = { enid = "search-" .. page } }, + } } } } }) + return { cancel = function() end } + end, + } +end + +local source = require("moonsource_dedao.source").new() +local result, err +source:browseAsync({}, function(value, reason) result, err = value, reason end) +Assert.is_nil(err) +Assert.len(result.data, 60) +Assert.len(pages, 3) +Assert.len(result.groups, 3) +Assert.eq(result.data[1].authors, "甲、乙") +Assert.eq(result.groups[1].chips[1].title, "小说") +Assert.eq(result.groups[2].chips[2].title, "推理") +Assert.eq(result.groups[3].chips[2].title, "最新") +Assert.eq(pages[2].query.request_id, "public-page-session") +Assert.is_nil(pages[1].query.tags_ids) + +local latest = result.groups[3].chips[2].id +source:browseAsync({ node = latest }, function(value) result = value end) +Assert.eq(queries[#queries].sort_strategy, "NEW") +Assert.eq(queries[#queries].navigation_id, "novel") +Assert.eq(queries[#queries].product_types, "2") + +source:browseAsync({ node = "invalid json" }, function(value, reason) result, err = value, reason end) +Assert.is_nil(result) +Assert.eq(err, "响应无效") + +source:searchAsync("test", function(value) result = value end) +Assert.len(result.data, 2) + +source:loadTocAsync({ stable_id = "legacy-book" }, function(value) result = value end) +Assert.eq(result, cached) + +local progress_result +local job = source:getProgressAsync({ stable_id = "legacy-book" }, function(value) progress_result = value end) +job.cancel() +Assert.is_true(read_cancelled, "读进度的第一步异步请求可取消") +progress({ findex = "legacy-chapter" }) +Assert.is_nil(progress_result) + +local toc_callback, toc_cancelled +source.loadTocAsync = function(_source, _identity, done) + toc_callback = done + return { cancel = function() toc_cancelled = true end } +end +async_progress, read_cancelled = false, false +job = source:getProgressAsync({ stable_id = "legacy-book" }, function(value) progress_result = value end) +job.cancel() +Assert.is_true(toc_cancelled, "同步读进度后应取消异步目录,不是已完成的读进度") +Assert.is_true(not read_cancelled) +toc_callback(cached) +Assert.is_nil(progress_result) + +toc_cancelled = false +job = source:putProgressAsync({ stable_id = "legacy-book" }, { chapter_idx = 1 }, function(value) progress_result = value end) +job.cancel() +Assert.is_true(toc_cancelled, "推送前的异步目录可取消") +toc_callback(cached) +Assert.is_nil(pushed) + +source.loadTocAsync = function(_source, _identity, done) + done(cached) + return { cancel = function() toc_cancelled = true end } +end +toc_cancelled = false +job = source:putProgressAsync({ stable_id = "legacy-book" }, { chapter_idx = 1 }, function(value) progress_result = value end) +job.cancel() +Assert.is_true(write_cancelled, "同步目录后应取消真正的进度写请求") +Assert.is_true(not toc_cancelled) +pushed(true) +Assert.is_nil(progress_result) diff --git a/tests/dedao/client_spec.lua b/tests/dedao/client_spec.lua new file mode 100644 index 0000000..d548b68 --- /dev/null +++ b/tests/dedao/client_spec.lua @@ -0,0 +1,295 @@ +--[[-- +得到:扫码链接、已购书架、搜索、目录章节号、SVG 解密。 + +@module tests.moonsource_dedao.client_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +package.preload["json"] = function() return require("support.json_stub") end +package.preload["ui/uimanager"] = function() + return { nextTick = function(_ui, fn) fn() end, scheduleIn = function(_ui, _delay, fn) fn() end } +end +package.preload["ui.guard"] = function() + return { call = function(_label, fn, ...) return fn(...) end } +end + +local Assert = require("support.assert") +local Json = require("support.json_stub") +local Mapper = require("moonsource_dedao.mapper") + +Assert.eq(Mapper.qrText("igetweb1"), "https://m.igetget.com/oauth/qrcode/v2/authorize?token=igetweb1&source=igetweb&dv=") +Assert.eq(Mapper.login({ data = { status = 0 } }), "wait") +Assert.eq(Mapper.login({ data = { status = 1 } }), "ok") +Assert.eq(Mapper.login({ data = { status = 2 } }), "fail") + +local shelf = Mapper.shelf({ + list = { + { type = 2, enid = "e1", title = "三体", author = "刘慈欣", icon = "https://c" }, + { type = 13, enid = "e2", title = "听书" }, + { type = 230, enid = "e3", title = "本地上传" }, + }, +}) +Assert.eq(#shelf, 1) +Assert.eq(shelf[1].stable_id, "e1") +Assert.eq(shelf[1].source_id, "ext.dedao") + +local found = Mapper.search({ + data = { moduleList = { { layerDataList = { + { type = 2, Title = "三体全集", author = "刘慈欣", image = "https://img", extra = { enid = "e1" } }, + { type = 2, Title = "重复", extra = { enid = "e1" } }, + { type = 66, Title = "课程", extra = { enid = "e9" } }, + } } } }, +}) +Assert.eq(#found, 1) +Assert.eq(found[1].title, "三体全集") +Assert.eq(found[1].cover, "https://img") + +local toc = Mapper.chapters({ + bookInfo = { + orders = { { pathInEpub = "chapter01.xhtml", chapterId = "c1" } }, + toc = { + { href = "chapter01.xhtml#sigil", text = "序", level = 0, playOrder = 2 }, + { href = "chapter02.xhtml", text = "第二章", level = 1, playOrder = 1 }, + }, + }, +}) +Assert.eq(#toc, 2) +Assert.eq(toc[1].uid, "chapter02.xhtml") +Assert.eq(toc[1].toc_version, Mapper.TOC_VERSION) +Assert.eq(toc[2].uid, "c1") +Assert.eq(toc[2].depth, 1) +Assert.eq(Mapper.progressUid("c1"), "c1") +Assert.is_nil(Mapper.progressUid("")) + +local cipher = "UzX9+34+GWS32TeZD7pKPYHRf4jS1JHrdgxu4mR6gj5QxmZ0tAASG61dGrB/0C0+" +Assert.eq(Mapper.pageText(cipher), "第一段\n第二段") + +local settings = { cookie = "csrfToken=c; token=t", logged_in = true } +package.loaded["source.logout"] = { clear = function(_id, clear) clear(); return true end } +local requests = {} +local cookies, qr_status = {}, 0 +local pages_reply, remove_reply +local function reply(url, payload) + if url:find("/loginapi/getAccessToken", 1, true) then return '"oauth-token"' end + if url:find("/qrcode/check_login", 1, true) then + return Json.encode({ errCode = 0, data = { status = qr_status } }) + end + if url:find("/oauth/api/embedded/qrcode", 1, true) then + return Json.encode({ errCode = 0, data = { qrCodeString = "igetweb9" } }) + end + if url:find("/api/hades/v2/product/list", 1, true) then + return Json.encode({ h = { c = 0 }, c = { is_more = false, list = { + { type = 2, enid = "e1", title = "三体", author = "刘慈欣" }, + } } }) + end + if url:find("/bookshelf/add", 1, true) then + return Json.encode({ h = { c = 0 }, c = { data = { n = 1 } } }) + end + if url:find("/product/pcremove", 1, true) then + return remove_reply or Json.encode({ h = { c = 0 }, c = { n = 0 } }) + end + if url:find("/api/pc/user/info", 1, true) then + return Json.encode({ h = { c = 0 }, c = { uid_hazy = "test-user" } }) + end + if url:find("/api/search/pc/tophits", 1, true) then + return Json.encode({ h = { c = 0 }, c = { data = { moduleList = { { layerDataList = { + { type = 2, Title = "三体", author = "刘", extra = { enid = "e1" } }, + } } } } } }) + end + if url:find("/pc/ebook2/v1/pc/detail", 1, true) then + return Json.encode({ h = { c = 0 }, c = { enid = "e1", title = "三体", book_author = "刘慈欣", cover = "https://c" } }) + end + if url:find("/read/token", 1, true) then + return Json.encode({ h = { c = 0 }, c = { token = "read-token" } }) + end + if url:find("/get_pages", 1, true) then + if pages_reply then return pages_reply() end + if payload and payload:find('"chapter_id":"vip"', 1, true) then + return Json.encode({ h = { c = 4000, e = "user no legal!" } }) + end + return Json.encode({ h = { c = 0 }, c = { is_end = true, pages = { { svg = cipher, is_last = true } } } }) + end + if url:find("/getread", 1, true) then + return Json.encode({ h = { c = 0 }, c = { data = { findex = "c1", windex = 0 } } }) + end + if url:find("/addread", 1, true) then + return Json.encode({ h = { c = 0 }, c = { status = 1 } }) + end + return payload +end + +package.preload["utils.settings"] = function() + return { + getSource = function() return settings end, + saveSource = function() end, + } +end +package.preload["http.request"] = function() + return { + headerAll = function() return cookies end, + get = function(url, options, callback) + requests[#requests + 1] = { method = "GET", url = url, headers = options.headers } + callback(reply(url), nil, {}) + return { cancel = function() end } + end, + post = function(url, payload, options, callback) + requests[#requests + 1] = { method = "POST", url = url, body = payload, headers = options.headers } + local raw, err = reply(url, payload) + callback(raw, err, {}) + return { cancel = function() end } + end, + } +end + +local Client = require("moonsource_dedao.client") + +local token +Client.accessTokenAsync(function(value) token = value end) +Assert.eq(token, "oauth-token") +Assert.eq(requests[#requests].headers["Xi-DT"], "web") +Assert.eq(requests[#requests].headers["Xi-Csrf-Token"], "c") + +local code +Client.qrCreateAsync("oauth-token", function(value) code = value end) +Assert.eq(code, "igetweb9") +Assert.eq(requests[#requests].headers["X-Oauth-Access-Token"], "oauth-token") + +local rows +Client:shelfSyncAsync(function(body) rows = Mapper.shelf(body) end) +Assert.eq(#rows, 1) +Assert.is_true(requests[#requests].body:find('"category":"ebook"', 1, true) ~= nil) + +local added +Client:addToShelfAsync("e1", function(ok) added = ok end) +Assert.eq(added, true) +Assert.is_true(requests[#requests].body:find('"book_enids":["e1"]', 1, true) ~= nil) +Assert.is_true(requests[#requests].body:find('"ptype":2', 1, true) ~= nil) + +local books +Client.searchAsync("三体", function(body) books = Mapper.search(body) end) +Assert.eq(books[1].title, "三体") +Assert.is_true(requests[#requests].body:find('"tab_type":2', 1, true) ~= nil) + +local fallback = Mapper.detail({ + title = "", operating_title = "得到书", book_author = "甲", book_intro = "简介", +}, "e1") +Assert.eq(fallback.title, "得到书") +Assert.eq(fallback.authors, "甲") +Assert.eq(fallback.stable_id, "e1") + +local detail +Client.detailAsync("e1", function(body) detail = Mapper.detail(body, "e1") end) +Assert.eq(detail.title, "三体") +Assert.eq(detail.authors, "刘慈欣") + +local text, terr, kind +Client.contentAsync("e1", "c1", function(value, err, content_kind) text, terr, kind = value, err, content_kind end) +Assert.eq(text, "第一段\n第二段") +Assert.is_nil(terr) +Assert.is_true(requests[#requests].url:find("/ebk_web_go/v2/get_pages", 1, true) ~= nil) +Assert.is_true(requests[#requests].body:find('"token":"read-token"', 1, true) ~= nil) + +Client.contentAsync("e1", "vip", function(value, err, content_kind) text, terr, kind = value, err, content_kind end) +Assert.is_nil(text) +Assert.eq(terr, "本章未购买") +Assert.eq(kind, "unpaid") + +local progress +Client.progressAsync("e1", function(item) progress = item end) +Assert.eq(progress.findex, "c1") + +local posted +Client.putProgressAsync("e1", "c1", "序", function(ok) posted = ok end) +Assert.eq(posted, true) +Assert.is_true(requests[#requests].body:find('"findex":"c1"', 1, true) ~= nil) + +cookies, qr_status = { "session=new-login; Path=/" }, 1 +local login +local candidate = { csrfToken = "candidate" } +local old_cookie = settings.cookie +Client.qrPollAsync("oauth-token", "igetweb9", function(wire) login = wire end, candidate) +Assert.eq(login.data.status, 1) +Assert.eq(settings.cookie, old_cookie) +Assert.eq(candidate.session, "new-login") +Client.confirmLoginAsync(candidate, function(ok) Assert.is_true(ok) end) +Assert.matches(settings.cookie, "session=new%-login") +Assert.matches(Client.cookie(), "session=new%-login") +Client.loggedIn() +Assert.matches(Client.cookie(), "session=new%-login") +cookies = {} + +local removed, remove_err +for _idx, bad in ipairs({ "upstream unavailable", "broken", "{}", '{"h":{},"c":{}}', + '{"h":{"c":401},"c":{}}' }) do + remove_reply = bad + Client:removeFromShelfAsync("e1", function(ok, err) removed, remove_err = ok, err end) + Assert.is_nil(removed) + Assert.is_true(remove_err ~= nil) +end +settings.logged_in = true +remove_reply = nil +Client:removeFromShelfAsync("e1", function(ok, err) removed, remove_err = ok, err end) +Assert.is_true(removed) +Assert.is_nil(remove_err) +Assert.eq(Json.decode(requests[#requests].body).data[1].pid, "e1") +Assert.eq(Json.decode(requests[#requests].body).data[1].ptype, 2) + +local function chapterResult() + text, terr = nil, nil + Client.contentAsync("e1", "c1", function(value, err) text, terr = value, err end) +end +local page_count = 0 +pages_reply = function() + page_count = page_count + 1 + if page_count > 1 then return nil, "network timeout" end + return Json.encode({ h = { c = 0 }, c = { pages = { { svg = cipher } } } }) +end +chapterResult() +Assert.is_nil(text) +Assert.eq(terr, "network timeout") + +for _idx, body in ipairs({ + { is_end = true, pages = { { svg = cipher }, { svg = "broken" } } }, + { is_end = true }, + { pages = {} }, +}) do + pages_reply = function() return Json.encode({ h = { c = 0 }, c = body }) end + chapterResult() + Assert.is_nil(text) + Assert.eq(terr, "响应无效") +end + +page_count = 0 +pages_reply = function() + page_count = page_count + 1 + return Json.encode({ h = { c = 0 }, c = { pages = { { svg = cipher } } } }) +end +chapterResult() +Assert.eq(page_count, 40) +Assert.is_nil(text) +Assert.eq(terr, "响应无效") + +local Aes = require("crypto.aes") +local Text = require("utils.text") +local SVG_KEY, SVG_IV = "3e4r06tjkpjcevlbslr3d96gdb5ahbmo", "6fd89a1b3a7f48fb" +local function svgCipher(svg) + return Text.base64Encode(Aes.cbc_encrypt(svg, SVG_KEY, SVG_IV)) +end +local blank = svgCipher("") +Assert.eq(Mapper.pageText(blank), "") +-- 同一基线的字拼成一行。上一行没排满就换段;排满的行和页边续行合成一段。 +Assert.eq(Mapper.pageText(svgCipher('膝盖')), "膝盖") +Assert.eq(Mapper.pageText(svgCipher([[甲 +乙丙。 +下]])), "甲\n乙丙。下") +Assert.eq(Mapper.pageText(svgCipher('AcD')), "Ac D") +page_count = 0 +pages_reply = function() + page_count = page_count + 1 + return Json.encode({ h = { c = 0 }, c = { + is_end = page_count == 2, pages = { { svg = page_count == 1 and blank or cipher } }, + } }) +end +chapterResult() +Assert.eq(text, "第一段\n第二段") +Assert.is_nil(terr) diff --git a/tests/dedao/operations_spec.lua b/tests/dedao/operations_spec.lua new file mode 100644 index 0000000..e0f4d9b --- /dev/null +++ b/tests/dedao/operations_spec.lua @@ -0,0 +1,251 @@ +--[[-- +得到多阶段请求:同步回调、取消、完整书架、账号归属与登录提交。 + +@module tests.moonsource_dedao.operations_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local beginLogin = require("source.auth").beginLogin +local Json = require("support.json_stub") +local cfg = { cookie = "csrfToken=old; session=old", logged_in = true } +local cleared = 0 +package.loaded["source.logout"] = { clear = function(id, clear) + beginLogin(id) + clear() + cleared = cleared + 1 + return true +end } +local fixtures, held, async, requests = {}, {}, {}, {} +local expired = 0 +local warnings = {} +package.preload["utils.log"] = function() + return { warn = function(...) + local fields = {} + for idx = 1, select("#", ...) do fields[idx] = tostring(select(idx, ...)) end + warnings[#warnings + 1] = table.concat(fields, " ") + end } +end +package.loaded["utils.log"] = nil + +package.preload["json"] = function() return Json end +package.preload["utils.settings"] = function() + return { getSource = function() return cfg end, saveSource = function() end } +end +package.loaded["source.auth"] = nil +package.preload["source.auth"] = function() + return { + ok = function() end, + beginLogin = beginLogin, + expire = function(_id, message) expired = expired + 1; return message end, + } +end +package.preload["source.base"] = function() + return { defer = function(done, ...) + done(...) + return { cancel = function() end } + end } +end + +local function wire(body) + return Json.encode({ h = { c = 0 }, c = body }) +end + +local function request(url, body, options, done) + local path = url:match("https://[^/]+([^?]+)") + local item = { path = path, body = body and body ~= "" and Json.decode(body) or nil, options = options, done = done } + requests[#requests + 1] = item + if async[path] then + held[path] = item + else + done(fixtures[path](item.body), nil, path == "/" and { cookies = { "csrfToken=candidate; Path=/" } } or {}) + end + return { cancel = function() item.cancelled = true end } +end + +package.preload["http.request"] = function() + return { + headerAll = function(res) return res.cookies or {} end, + get = function(url, options, done) return request(url, nil, options, done) end, + post = request, + } +end + +local Client = require("moonsource_dedao.client") + +local search_path = "/api/search/pc/tophits" +async[search_path] = true +local completed = false +local job = Client.searchAsync("test", function() completed = true end) +job.cancel() +Assert.is_true(held[search_path].cancelled) +held[search_path].done(wire({ data = { moduleList = {} } }), nil, {}) +Assert.is_false(completed) + +fixtures["/api/pc/ebook2/v1/pc/read/token"] = function(body) + Assert.is_nil(body.ptype) + return wire({ token = "test-token" }) +end +local info_path = "/ebk_web/v1/get_book_info" +async[info_path] = true +completed = false +job = Client.bookInfoAsync("test-book", function() completed = true end) +job.cancel() +Assert.is_true(held[info_path].cancelled) +held[info_path].done(wire({ bookInfo = {} }), nil, {}) +Assert.is_false(completed) + +local oauth_path = "/loginapi/getAccessToken" +async[oauth_path] = true +completed = false +job = Client.accessTokenAsync(function() completed = true end) +job.cancel() +Assert.is_true(held[oauth_path].cancelled) +held[oauth_path].done('"test-oauth"', nil, {}) +Assert.is_false(completed) + +local shelf_path = "/api/hades/v2/product/list" +fixtures[shelf_path] = function(body) + return wire({ list = { { enid = "book-" .. body.page, type = 2 } }, is_more = body.page < 44 }) +end +local shelf, shelf_err +Client:shelfSyncAsync(function(body, err) shelf, shelf_err = body, err end) +Assert.len(shelf.list, 44) +Assert.is_false(shelf.is_more) +Assert.is_nil(shelf_err) + +fixtures[shelf_path] = function() return wire({}) end +Client:shelfSyncAsync(function(body, err) shelf, shelf_err = body, err end) +Assert.is_nil(shelf) +Assert.eq(shelf_err, "响应无效") + +fixtures[shelf_path] = function() + return wire({ list = { { enid = "same", type = 2 } }, is_more = true }) +end +Client:shelfSyncAsync(function(body, err) shelf, shelf_err = body, err end) +Assert.is_nil(shelf) +Assert.eq(shelf_err, "响应无效") + +local progress_path = "/api/pc/ebook2/v1/pc/getread" +async[progress_path] = true +Client.progressAsync("test-book", function() end) +cfg.cookie = "csrfToken=new; session=new" +held[progress_path].done(Json.encode({ h = { c = 401, e = "expired old account" } }), nil, + { cookies = { "session=stale; Path=/" } }) +Assert.eq(expired, 0) +Assert.eq(cfg.cookie, "csrfToken=new; session=new") +Client.load() +Assert.matches(Client.cookie(), "session=new") + +fixtures["/api/pc/user/info"] = function() return wire({ uid_hazy = "user-one" }) end +fixtures["/"] = function() return "" end +local logged, login_err +local candidate = { csrfToken = "candidate", session = "candidate-session" } +Client.confirmLoginAsync(candidate, function(ok, err) logged, login_err = ok, err end) +Assert.is_true(logged) +Assert.is_nil(login_err) +Assert.eq(cfg.uid, "user-one") +Assert.eq(cfg.cookie, "csrfToken=candidate; session=candidate-session") + +fixtures["/api/pc/user/info"] = function() return wire({ uid_hazy = "user-two" }) end +Client.confirmLoginAsync({ session = "other" }, function(ok, err) logged, login_err = ok, err end) +Assert.is_true(logged) +Assert.is_nil(login_err) +Assert.eq(cfg.uid, "user-two") +Assert.eq(cfg.cookie, "session=other") +Assert.eq(cleared, 2, "包括旧配置缺账号标识时,直接清旧源再换号") + +local review_path = "/pc/ebook2/v1/comment/list" +fixtures[review_path] = function(body) + local list = {} + for idx = 1, body.page == 1 and 20 or 3 do + list[#list + 1] = { note_id_hazy = "note-" .. ((body.page - 1) * 20 + idx), note = "test" } + end + return wire({ list = list, total = 23 }) +end +local reviews +Client.reviewsAsync("test-book", function(body) reviews = body end) +Assert.len(reviews.list, 23) +Assert.eq(reviews.total, 23) +Assert.eq(requests[#requests].body.page, 2) +Assert.eq(requests[#requests].body.ptype, 2) + +fixtures[review_path] = function() return wire({ total = 1, list = {} }) end +Client.reviewsAsync("test-book", function(body, err) reviews = body; Assert.eq(err, "响应无效") end) +Assert.is_nil(reviews) + +fixtures["/"] = function() return "" end +async[oauth_path] = false +fixtures[oauth_path] = function() return '"sms-test-oauth"' end +local sms_path = "/oauth/api/embedded/auth_code/send" +fixtures[sms_path] = function(body) + Assert.is_nil(body.captcha) + return Json.encode({ errCode = 0, data = { needCaptcha = true, captchaId = "official-captcha" } }) +end +local sms, sms_err, challenge +local account_cookie = cfg.cookie +Client.sendCodeAsync("13800000000", function(value, err, next_step) sms, sms_err, challenge = value, err, next_step end) +Assert.is_nil(sms, "需要滑块不能当作短信已发送") +Assert.is_nil(sms_err) +Assert.eq(challenge.captcha_id, "official-captcha") +Assert.eq(challenge.session.oauth, "sms-test-oauth") +Assert.eq(cfg.cookie, account_cookie, "候选验证不能替换当前账号") + +fixtures[sms_path] = function(body) + Assert.eq(body.phone, "13800000000") + Assert.eq(body.captcha.captchaId, "official-captcha") + Assert.eq(body.captcha.validate, "test-proof") + return Json.encode({ errCode = 0, data = {} }) +end +Client.sendSessionCodeAsync(challenge.session, { captchaId = challenge.captcha_id, validate = "test-proof" }, + function(ok, err) Assert.is_true(ok); Assert.is_nil(err) end) +Assert.eq(requests[#requests].options.headers["X-Oauth-Access-Token"], "sms-test-oauth") + +fixtures[sms_path] = function() return Json.encode({ errCode = 0, data = { needCaptcha = true } }) end +Client.sendSessionCodeAsync(challenge.session, nil, function(ok, err) + Assert.is_nil(ok) + Assert.eq(err, "响应无效") +end) + +local mapped = require("moonsource_dedao.mapper").reviews({ list = { + { note_id_hazy = "review", note = "", content = "", note_line = "

实际书评

", + notes_owner = { name = "测试作者" }, extra = { score_str = "4.0" } }, +} }) +Assert.len(mapped, 1) +Assert.eq(mapped[1].text, "实际书评") +Assert.eq(mapped[1].grade, 4) + +local failure, failure_err +Client.bookInfoAsync("test-book", function(value, err) failure, failure_err = value, err end) +local timeout_error = "Request timeout: https://www.dedao.cn/ebk_web/v1/get_book_info?token=private-proof" +held[info_path].done(nil, timeout_error, { code = 0 }) +Assert.is_nil(failure) +Assert.eq(failure_err, timeout_error) +Assert.len(warnings, 1) +Assert.matches(warnings[1], "GET /ebk_web/v1/get_book_info timeout") +Assert.matches(warnings[1], "timeout_seconds") +Assert.is_nil(warnings[1]:find("token", 1, true), "失败日志不记录查询参数或原始错误里的凭证") +Assert.is_nil(warnings[1]:find("private-proof", 1, true)) + +-- 校验只交回候选账号;退出使此前的提交请求失效。 +do + local path = "/api/pc/user/info" + async[path] = true + local before_cookie, before_uid = cfg.cookie, cfg.uid + local user + Client.checkLoginAsync({ session = "candidate" }, function(value) user = value end) + held[path].done(wire({ uid_hazy = "late-user" }), nil, {}) + Assert.eq(user.uid_hazy, "late-user") + Assert.eq(cfg.cookie, before_cookie) + Assert.eq(cfg.uid, before_uid) + Client.confirmLoginAsync({ session = "late" }, function(ok, err) logged, login_err = ok, err end) + beginLogin("ext.dedao") + cfg.cookie, cfg.uid, cfg.logged_in = nil, nil, nil + Client.reset() + held[path].done(wire({ uid_hazy = "late-user" }), nil, {}) + Assert.is_nil(logged) + Assert.eq(login_err, "账号已变化,请重新登录") + Assert.is_nil(cfg.cookie) + Assert.is_nil(cfg.uid) + Assert.is_nil(cfg.logged_in) +end diff --git a/tests/dedao/qrlogin_spec.lua b/tests/dedao/qrlogin_spec.lua new file mode 100644 index 0000000..154d3ac --- /dev/null +++ b/tests/dedao/qrlogin_spec.lua @@ -0,0 +1,65 @@ +--[[-- +得到扫码:候选会话归窗口所有,取消停掉当前轮询,校验后才完成登录。 + +@module tests.moonsource_dedao.qrlogin_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local poll, candidate, stopped, signed_in, toast +local statuses = { 0, 1 } + +package.preload["moonsource_dedao.client"] = function() + return { + accessTokenAsync = function(done, jar) + candidate = jar + Assert.is_nil(jar.session) + done("oauth") + return { cancel = function() error("cancelled completed bootstrap") end } + end, + qrCreateAsync = function(_oauth, done, jar) + Assert.eq(jar, candidate) + done("qr") + return { cancel = function() error("cancelled completed QR request") end } + end, + qrPollAsync = function(_oauth, _code, done, jar) + Assert.eq(jar, candidate) + poll = done + return { cancel = function() stopped = true end } + end, + confirmLoginAsync = function(jar, done) + Assert.eq(jar, candidate) + done(true) + return { cancel = function() error("cancelled completed account verification") end } + end, + } +end +package.preload["moonsource_dedao.mapper"] = function() + return { + qrText = function() return "https://example.test/qr" end, + login = function(wire) return wire.data.status == 1 and "ok" or "wait" end, + } +end +package.preload["ui.themes.widgets.qr"] = function() + return { new = function(_class, opts) + return { show = function() end, close = function() opts.close_callback() end } + end } +end +package.preload["ui.themes.widgets.toast"] = function() + return { new = function(_class, opts) toast = opts.text; return { show = function() end } end } +end + +local QRLogin = require("moonsource_dedao.qrlogin") +local login = QRLogin:new(function() signed_in = true end) +login:start() +login:cancel() +Assert.is_true(stopped) +poll({ data = { status = statuses[2] } }) +Assert.is_nil(signed_in) + +stopped = false +login:start() +poll({ data = { status = statuses[2] } }) +Assert.is_true(signed_in) +Assert.is_nil(toast) +Assert.is_nil(login.dialog) diff --git a/tests/dedao/setting_spec.lua b/tests/dedao/setting_spec.lua new file mode 100644 index 0000000..f82e997 --- /dev/null +++ b/tests/dedao/setting_spec.lua @@ -0,0 +1,156 @@ +--[[-- +短信安全验证接回原登录输入窗,保留候选会话并取消真正的在飞步骤。 + +@module tests.moonsource_dedao.setting_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch +local Assert = require("support.assert") +local beginLogin = require("source.auth").beginLogin +local Theme = require("support.theme_stubs") +Theme.install() +local Input = require("ui.themes.widgets.input") +local make_input = Input.new +function Input:new(opts) + local window = make_input(self, opts) + local show = window.show + window.show = function(self) show(self) end + return window +end +local sent, verified, sms_session, sms_code +local login_ok, defer_login, login_callback +local request_cancelled, verification_cancelled +local candidate = { phone = "13800000000", oauth = "test-token", jar = {} } +local cfg, saves, reloads, accepted = {}, 0, 0, 0 +package.preload["utils.settings"] = function() + return { + getSource = function(_id) return cfg end, + saveSource = function(_id) saves = saves + 1 end, + } +end +package.preload["source.registry"] = function() return { reload = function() reloads = reloads + 1 end } end +package.loaded["source.auth"] = nil +package.preload["source.auth"] = function() + return { beginLogin = beginLogin, ok = function(_id) accepted = accepted + 1 end } +end +package.preload["ui/network/manager"] = function() + return { runWhenConnected = function(_network, cb) cb() end } +end +package.preload["moonsource_dedao.client"] = function() + return { + sendCodeAsync = function(_phone, cb) + sent = cb + cb(nil, nil, { session = candidate, captcha_id = "test-id" }) + return { cancel = function() request_cancelled = true end } + end, + smsLoginAsync = function(session, code, cb) + sms_session, sms_code = session, code + login_callback = cb + if not defer_login then cb(login_ok, not login_ok and "test-login-error" or nil) end + return { cancel = function() request_cancelled = true end } + end, + } +end +package.preload["moonsource_dedao.verify"] = function() + return { new = function(challenge, cb) + Assert.eq(challenge.session, candidate) + verified = cb + return { cancel = function() verification_cancelled = true end } + end } +end +local Setting = require("moonsource_dedao.setting") +local function open() + Setting.open() + Theme.choose(Theme.last("sheet"), 1) + local input = Theme.last("input") + input.actions[1].callback("13800000000") + Theme.last("confirm").ok_callback() + return input +end +local input = open() +Assert.is_true(Theme.last("progress_dialog").closed) +Assert.is_nil(Theme.last("toast"), "要求滑块时不能弹短信已发送") +Assert.is_true(not input.closed) +input:close() +Assert.is_true(verification_cancelled, "同步短信回调不能把网页取消句柄覆盖成旧请求") +Assert.is_nil(request_cancelled) +verified(candidate) +Assert.is_nil(Theme.last("toast"), "关输入窗后不显示迟到成功") + +input = open() +verified(candidate) +Assert.eq(Theme.last("toast").text, "短信已发送,请在设备上填写验证码") +Assert.is_true(input.validate("13800000000", "123456")) +Assert.is_true(not input.validate("13900000000", "123456")) +input.callback("13800000000", "123456") +Assert.eq(sms_session, candidate) +Assert.eq(sms_code, "123456") +Assert.eq(Theme.last("toast").text, "test-login-error") +input:close() +Assert.is_nil(request_cancelled, "同步完成登录不留下旧取消句柄") + +login_ok = true +input = open() +verified(candidate) +input.callback("13800000000", "123456") +Assert.is_true(input.closed, "show 不返回窗口时,成功登录仍能关闭真正的输入窗") +Assert.is_true(cfg.logged_in) +Assert.eq(saves, 1) +Assert.eq(reloads, 1) +Assert.eq(accepted, 1) +Assert.eq(Theme.last("toast").text, "登录成功") + +defer_login = true +input = open() +verified(candidate) +input.callback("13800000000", "123456") +Assert.is_true(not input.closed) +login_callback(true) +Assert.is_true(input.closed, "HTTP 异步成功也关闭原输入窗") +Assert.eq(saves, 2) +Assert.eq(reloads, 2) +Assert.eq(Theme.last("toast").text, "登录成功") + +-- Cookie / 浏览器登录行与校验保存 +package.loaded["ui.themes.widgets.row"] = { widget = function(spec) return spec end } +local cookie_calls = {} +package.preload["moonsource_dedao.client"] = function() + return { + loggedIn = function() return cfg.logged_in == true and cfg.cookie ~= nil end, + reset = function() end, + checkLoginAsync = function(jar, cb) + cookie_calls[#cookie_calls + 1] = jar + cb({ uid_hazy = "browser-account" }) + return { cancel = function() end } + end, + sendCodeAsync = function(_phone, cb) + sent = cb + cb(nil, nil, { session = candidate, captcha_id = "test-id" }) + return { cancel = function() request_cancelled = true end } + end, + smsLoginAsync = function(session, code, cb) + sms_session, sms_code = session, code + login_callback = cb + if not defer_login then cb(login_ok, not login_ok and "test-login-error" or nil) end + return { cancel = function() request_cancelled = true end } + end, + } +end +package.loaded["moonsource_dedao.client"] = nil +package.loaded["moonsource_dedao.setting"] = nil +package.loaded["source.cookie_login"] = nil +Setting = require("moonsource_dedao.setting") +Assert.is_true(type(Setting.browser) == "table") +Assert.eq(Setting.browser.domain, "www.dedao.cn") +Assert.is_true(type(Setting.browser.icon) == "string" and Setting.browser.icon:match("^https://")) +cfg = {} +local rows = Setting.rows() +Assert.eq(rows[2](400).title, "浏览器登录") +Assert.eq(rows[3](400).title, "粘贴 Cookie") +rows[3](400).callback() +local paste = Theme.last("input") +Assert.eq(paste.title, "得到登录 Cookie") +paste.callback("csrfToken=abc; token=xyz") +Assert.eq(cookie_calls[1].csrfToken, "abc") +Assert.eq(cookie_calls[1].token, "xyz") +Assert.eq(cfg.cookie, "csrfToken=abc; token=xyz") +Assert.is_true(cfg.logged_in) diff --git a/tests/dedao/verify_spec.lua b/tests/dedao/verify_spec.lua new file mode 100644 index 0000000..748c1f9 --- /dev/null +++ b/tests/dedao/verify_spec.lua @@ -0,0 +1,101 @@ +--[[-- +得到滑块绑定候选会话:只交 validate,不泄露凭证,成功发短信才完成。 + +@module tests.moonsource_dedao.verify_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local Theme = require("support.theme_stubs") +Theme.install() +local Ext = require("utils.extension") +Ext.reset() +local submit, sent_session, proof, cancelled +package.preload["moonsource_dedao.client"] = function() + return { sendSessionCodeAsync = function(session, captcha, done) + sent_session, proof, submit = session, captcha, done + return { cancel = function() cancelled = true end } + end } +end +local timers = {} +package.preload["ui/uimanager"] = function() + return { + scheduleIn = function(_ui, _delay, fn) timers[fn] = true end, + unschedule = function(_ui, fn) timers[fn] = nil end, + } +end +package.preload["ui.guard"] = function() return { wrap = function(_label, fn) return fn end } end +local path +Ext.add("web.open_page", function(url, _title, _text, opts) + path = url + return require("ui.themes.widgets.qr"):new{ close_callback = opts.close_callback }:show() +end) +local Verification = require("moonsource_dedao.verify") +local route = Ext.list("web.routes")[1] +local status, body, headers +local function request(action, params, method) + route.handle(method or "POST", action, params, function(code, data, extra) status, body, headers = code, data, extra end) +end +local login = { phone = "13800000000", oauth = "private-oauth", jar = { session = "private-cookie" } } +local completed, err +local function start() + completed, err = nil, nil + return Verification.new({ session = login, captcha_id = "official-id" }, function(value, reason) completed, err = value, reason end) +end +local verification = start() +local ticket = path:match("#(.+)$") +request("config", { ticket = ticket }) +Assert.eq(status, 200) +Assert.eq(body.captcha_id, "official-id") +Assert.is_nil(body.phone) +Assert.is_nil(body.oauth) +Assert.is_nil(body.jar) +Assert.eq(headers[1], "Cache-Control: no-store") +request("verify", { ticket = "invalid", validate = "proof" }) +Assert.eq(status, 403) +request("verify", { ticket = ticket, validate = {} }) +Assert.eq(status, 400) +request("verify", { ticket = ticket, validate = string.rep("a", 16385) }) +Assert.eq(status, 400) +request("config", { ticket = ticket }, "GET") +Assert.eq(status, 405) +request("unknown", { ticket = ticket }) +Assert.eq(status, 404) +request("verify", { ticket = ticket, validate = "proof", captcha_id = "browser-id", phone = "other-phone" }) +Assert.eq(sent_session, login) +Assert.eq(proof.captchaId, "official-id") +Assert.eq(proof.validate, "proof") +request("verify", { ticket = ticket, validate = "duplicate" }) +Assert.eq(status, 409) +submit(nil, "SMS refused", "new-official-id") +Assert.eq(status, 400) +Assert.is_nil(completed) +request("config", { ticket = ticket }) +Assert.eq(body.captcha_id, "new-official-id") +request("verify", { ticket = ticket, validate = "retry" }) +submit(true) +Assert.eq(status, 200) +Assert.eq(completed, login) +Assert.is_true(verification.dialog == nil) +Assert.is_nil(next(timers)) +request("verify", { ticket = ticket, validate = "replay" }) +Assert.eq(status, 403) + +verification = start() +ticket = path:match("#(.+)$") +request("verify", { ticket = ticket, validate = "pending" }) +verification.dialog:close() +Assert.eq(err, "验证已取消") +Assert.is_true(cancelled) +submit(true) +Assert.eq(status, 403) +Assert.is_nil(completed) + +verification = start() +ticket = path:match("#(.+)$") +verification.expires = os.time() - 1 +request("config", { ticket = ticket }) +Assert.eq(status, 403) +verification.timeout() +Assert.eq(err, "验证已过期,请重新发起验证") +Assert.is_nil(next(timers))