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

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

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

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
# 得到
| 能力 | 是否支持 | 备注 |
| --- | --- | --- |
| 手机短信登录 | 支持 | 中国大陆手机号;未注册号码可能自动注册,发送前需确认协议 |
| 短信安全验证 | 部分支持 | 手机访问远程网页完成官方易盾滑块;触发验证后的完整续发流程未实测 |
| App 扫码登录 | 已实现,未实测 | 得到 App 扫码,不是微信扫码 |
| 浏览器登录与 Cookie 导入 | 支持 | 保留官网登录及粘贴入口 |
| 设备密码登录 | 不支持 | 未接入 |
| 书架拉取 | 支持 | 分页读取“已购”电子书集合,过滤课程、听书和自上传内容 |
| 加入与移出远端集合 | 已实现,未实测 | 本地先生效,再同步;移出不撤销购买 |
| 搜索与分类书城 | 支持 | 动态分类、子分类、排序和筛选,支持后续页,默认聚合约 60 本 |
| 详情与目录 | 支持 | 目录需阅读 token;真实登录后的读取尚待验证 |
| 正文与全本缓存 | 已实现,未实测 | SVG 解密与文字还原,需有效阅读权限;真实登录阅读链路未验证 |
| 离线阅读 | 支持 | 仅已成功缓存的目录与正文 |
| 阅读进度同步 | 部分支持 | 仅章节位置,无精确章内位置;真实远端写入未实测 |
| 笔记与统计同步 | 不支持 | 仅本地保存 |
| 整书书评 | 支持 | 读取真实书评列表,支持客户端分页去重 |
| 章评、段评与回复 | 不支持 | 未接入可验证的公共评论接口;原版笔记及笔记回复不是章/段评 |
| 评论写操作 | 不支持 | 不发评、不点赞、不删评 |
| 账号切换 | 部分支持 | 已绑定账号时拒绝直接换号;须先退出清理,旧配置迁移隔离有限 |
+5
View File
@@ -0,0 +1,5 @@
local _ = require("gettext")
return {
fullname = _("月读书源:得到"),
description = _("给月读增加「得到」书源。需要同时安装月读,与平台官方无关。"),
}
+9
View File
@@ -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,
}
+15
View File
@@ -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"),
}
@@ -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 = { _("搜索与发现"), _("书架同步"), _("进度同步"), _("书评"), _("手机号验证码登录"), _("扫码登录"), _("浏览器登录") },
}
@@ -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<string, string>|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<string, string>|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<string, string>|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<string, string>|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<string, string>|nil
---@return string|nil
local function csrf(login_jar)
return (login_jar or jar).csrfToken
end
---@param extra table|nil
---@param login_jar table<string, string>|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<string, string>|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<string, string>|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<string, string>|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<string, string>
---@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<string, string>
---@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<string, string>
---@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
@@ -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",
}
@@ -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 並啟用遠端管理功能",
["验证已取消"] = "驗證已取消",
["验证失败,请重新滑动验证"] = "驗證失敗,請重新滑動驗證",
["验证凭据无效"] = "驗證憑據無效",
["正在提交验证…"] = "正在提交驗證…",
["请填写验证码"] = "請填寫驗證碼",
["重试"] = "重試",
["书架同步"] = "書架同步",
["搜索与发现"] = "搜尋與發現",
["进度同步"] = "進度同步",
["得到"] = "得到",
}
@@ -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
@@ -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("</?hl>", "")))
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("</?hl>", ""))
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("<text([^>]*)>(.-)</text>") 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
@@ -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
@@ -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<string, string>
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
@@ -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<string, string|integer|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
@@ -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<string, DedaoVerification>
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
@@ -0,0 +1,25 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="referrer" content="no-referrer">
<title>月读</title>
<link rel="stylesheet" href="/style.css">
<style>
main{max-width:520px;margin:12vh auto;padding:24px}
.panel{padding:24px}#captcha-element{min-height:180px;margin:24px 0}
#status{overflow-wrap:anywhere}button[hidden]{display:none}
</style>
</head>
<body>
<main><section class="panel">
<h1 id="title">月读</h1>
<p id="instruction"></p>
<div id="captcha-element"></div>
<p id="status" role="status" aria-live="polite"></p>
<button id="retry" type="button" hidden></button>
</section></main>
<script src="/dedao_verify.js"></script>
</body>
</html>
@@ -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);
})();