commit 20ee051d8c4a26b11202d3c6010e67e593c1a043 Author: Garfield Date: Mon Nov 16 12:07:59 2026 +0800 ✨ 初始提交:月读第三方书源插件集合 每个书源一个独立插件目录,含微信读书公众号订阅、书架导入等完整功能。 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> diff --git a/moonsource-tadu.koplugin/README.md b/moonsource-tadu.koplugin/README.md new file mode 100644 index 0000000..eb14660 --- /dev/null +++ b/moonsource-tadu.koplugin/README.md @@ -0,0 +1,22 @@ +# 塔读 + +| 能力 | 是否支持 | 备注 | +| --- | --- | --- | +| 微信扫码登录 | 支持 | 保存前校验账号,失败或取消不覆盖旧登录 | +| 浏览器登录与 Cookie 导入 | 支持 | 官网完成登录后手动粘贴或扩展回传 | +| 设备密码、短信与登录验证码 | 不支持 | 交由官网完成,不跳过验证码 | +| 书架拉取 | 支持 | 登录后分页读取 | +| 书架新增与移出 | 已实现,未实测 | 本地先生效,写后回读确认;失败保留脏行或墓碑 | +| 搜索与分类书城 | 支持 | 动态频道、分类、状态、字数和排序,默认聚合 60 本 | +| 详情与目录 | 支持 | 保留章节 ID、顺序及旧缓存 | +| 普通与特殊字体正文 | 支持 | 字形还原为普通文字;未知字形明确失败 | +| App 扫码阅读授权 | 支持 | 受限章节显示官网二维码,确认后重新核对权限;不等同账号登录 | +| 图片式正文 | 不支持 | 未接入 | +| 付费阅读 | 部分支持 | 以服务端权限为准,不代购;购买流程未实测 | +| 章节与全本缓存 | 支持 | 后台遇授权限制不弹扫码窗,须先开章授权后重试 | +| 离线阅读 | 支持 | 已缓存目录和正文可续读、关书重开 | +| 进度、笔记与统计同步 | 不支持 | 仅本地保存,没有已验证的远端读写协议 | +| 整书书评 | 部分支持 | 仅第一页,提示还有更多;没有后续页交互入口 | +| 章评与段评 | 不支持 | 阅读页评论仍绑定整本书;未找到可验证的章/段评接口 | +| 评论回复与写操作 | 不支持 | 未接入 | +| 账号切换与 Cookie 续期 | 部分支持 | 不同 Cookie 须先退出清理旧数据,未同步记录会丢失 | diff --git a/moonsource-tadu.koplugin/_meta.lua b/moonsource-tadu.koplugin/_meta.lua new file mode 100644 index 0000000..6e632af --- /dev/null +++ b/moonsource-tadu.koplugin/_meta.lua @@ -0,0 +1,5 @@ +local _ = require("gettext") +return { + fullname = _("月读书源:塔读文学"), + description = _("给月读增加「塔读文学」书源。需要同时安装月读,与平台官方无关。"), +} diff --git a/moonsource-tadu.koplugin/main.lua b/moonsource-tadu.koplugin/main.lua new file mode 100644 index 0000000..febeebf --- /dev/null +++ b/moonsource-tadu.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_tadu", + is_doc_only = false, +} diff --git a/moonsource-tadu.koplugin/moon_source.lua b/moonsource-tadu.koplugin/moon_source.lua new file mode 100644 index 0000000..43b19e1 --- /dev/null +++ b/moonsource-tadu.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_tadu.source").meta() end, + new = function() return require("moonsource_tadu.source").new() end, + setting = lazy("moonsource_tadu.setting"), +} diff --git a/moonsource-tadu.koplugin/moonsource_tadu/_meta.lua b/moonsource-tadu.koplugin/moonsource_tadu/_meta.lua new file mode 100644 index 0000000..ece85ee --- /dev/null +++ b/moonsource-tadu.koplugin/moonsource_tadu/_meta.lua @@ -0,0 +1,17 @@ +--[[-- +书源元信息:id / 名称 / 类型,加上启用页展示用的说明与能力清单。`init.lua` 的 `meta()` 直接返回本表。 + +塔读(www.tadu.com)用微信扫码登录。书架、搜索、目录、正文都是网页接口。 + +@module moonsource_tadu._meta +--]] + +local _ = require("l10n").get("moonsource_tadu") + +return { + id = "ext.tadu", + name = _("塔读小说"), + type = "chapter", + description = _("塔读书架与在线阅读"), + abilities = { _("搜索与发现"), _("书架同步"), _("书评"), _("离线缓存") }, +} diff --git a/moonsource-tadu.koplugin/moonsource_tadu/client.lua b/moonsource-tadu.koplugin/moonsource_tadu/client.lua new file mode 100644 index 0000000..19dbbce --- /dev/null +++ b/moonsource-tadu.koplugin/moonsource_tadu/client.lua @@ -0,0 +1,434 @@ +--[[-- +塔读电脑 Web 接口。公开查询不带 Cookie,书架和付费正文使用当前登录。 +扫码兑换的 Cookie 归请求实例所有,校验通过才替换持久会话。 + +@module moonsource_tadu.client +--]] + +local JSON = require("json") +local Mapper = require("moonsource_tadu.mapper") +local Request = require("http.request") +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_tadu") + +local Client = {} +local SOURCE_ID = "ext.tadu" +local ORIGIN = "https://www.tadu.com" + +function Client.cookie() + return require("utils.settings").getSource(SOURCE_ID).cookie +end + +function Client.loggedIn() + local cfg = require("utils.settings").getSource(SOURCE_ID) + return cfg.logged_in == true and type(cfg.cookie) == "string" and cfg.cookie ~= "" + and not require("source.auth").expired(SOURCE_ID) +end + +local function opts(accept, cookie) + return { + accept = accept, cache_ttl = 0, + headers = { Referer = ORIGIN .. "/", Cookie = cookie }, + timeout = require("http.timeout").net(1), + } +end + +local function doneHtml(cb) + return function(raw, err) + if err or not raw or raw == "" then + cb(nil, err and tostring(err) or _("请求失败")) + return + end + cb(raw) + end +end + +local function decoded(raw, err) + if err or not raw then return nil, err and tostring(err) or _("请求失败") end + local ok, wire = pcall(JSON.decode, raw) + if not ok or type(wire) ~= "table" then return nil, _("响应无效") end + return wire +end + +local function expired(cookie) + local reason = _("塔读登录已失效,请在官网重新登录") + if cookie == Client.cookie() then require("source.auth").expire(SOURCE_ID, reason) end + return reason +end + +--- 站点没有稳定账号 ID:凭据变化就直接清旧源记录。 +function Client.commitLogin(cookie, user) + local Settings = require("utils.settings") + local cfg = Settings.getSource(SOURCE_ID) + local old = require("source.cookie_login").parse(Client.cookie() or "") + if old ~= "" and old ~= require("source.cookie_login").parse(cookie) then + local cleared = require("source.logout").clear(SOURCE_ID, function() + cfg.cookie, cfg.logged_in, cfg.name = nil, nil, nil + cfg.read_cookie, cfg.read_cookie_for = nil, nil + Settings.saveSource(SOURCE_ID) + end) + if not cleared then return nil, _("准备本地同步失败") end + end + cfg.cookie, cfg.logged_in, cfg.name = cookie, true, user.name + Settings.saveSource(SOURCE_ID) + return true +end + +function Client.loginCheckAsync(cookie, cb) + local previous = Client.cookie() + return Request.post(ORIGIN .. "/user/info", "", opts("application/json", cookie), function(raw, err) + local wire, reason = decoded(raw, err) + if not wire then cb(false, reason); return end + local user = Mapper.user(wire) + if not user then cb(false, _("未登录塔读")); return end + if Client.cookie() ~= previous then cb(false, _("塔读登录已改变,请重试")); return end + cb(true, nil, user) + end) +end + +function Client.qrCreateAsync(cb) + local url = "https://open.weixin.qq.com/connect/qrconnect?" .. Text.formEncode({ + appid = "wxbb4e499689feeef9", + redirect_uri = ORIGIN .. "/webchat/invoke/", + response_type = "code", scope = "snsapi_login", state = "STATE", + }) + return Request.get(url, { accept = "text/html", cache_ttl = 0, timeout = require("http.timeout").net(1) }, + function(raw, err) + if err then cb(nil, tostring(err)); return end + local uuid = Mapper.qrUuid(raw) + cb(uuid, not uuid and _("获取二维码失败") or nil) + end) +end + +function Client.qrPollAsync(uuid, last, cb) + local query = { f = "json", uuid = uuid, last = last and tostring(last) } + return Request.get("https://long.open.weixin.qq.com/connect/l/qrconnect?" .. Text.formEncode(query), { + accept = "application/json", cache_ttl = 0, timeout = require("http.timeout").net(1.5), + }, function(raw, err) + if err then cb("error", nil, nil, tostring(err)); return end + local kind, code, status = Mapper.wxStatus(raw) + if not status then cb("error", nil, nil, _("响应无效")); return end + cb(kind, code, status) + end) +end + +function Client.exchangeAsync(wx_code, cb) + local handle, cookies, previous = {}, {}, Client.cookie() + local function cookie() + local names, parts = {}, {} + for name in pairs(cookies) do names[#names + 1] = name end + table.sort(names) + for _idx, name in ipairs(names) do parts[#parts + 1] = name .. "=" .. cookies[name] end + return table.concat(parts, "; ") + end + local function request(method, url, done) + local pending = true + local function reply(raw, err, res) + pending = false + if handle.cancelled then return end + handle.job = nil + for _idx, line in ipairs(Request.headerAll(res, "Set-Cookie")) do + local name, value = line:match("^%s*([^=;%s]+)=([^;]*)") + if name then cookies[name] = value ~= "" and value ~= '""' and value or nil end + end + done(raw, err, res) + end + local options = opts(method == "POST" and "application/json" or "text/html", cookie()) + local job + if method == "POST" then job = Request.post(url, "", options, reply) + else job = Request.get(url, options, reply) end + if pending then handle.job = job end + end + local function confirm() + request("POST", ORIGIN .. "/user/info", function(raw, err) + local wire, reason = decoded(raw, err) + local user = wire and Mapper.user(wire) + if not user or cookie() == "" then cb(nil, reason or _("未登录塔读")); return end + if Client.cookie() ~= previous then cb(nil, _("塔读登录已改变,请重试")); return end + local ok, failure = Client.commitLogin(cookie(), user) + if not ok then cb(nil, failure); return end + cb(user) + end) + end + local function follow(url, remaining) + request("GET", url, function(raw, err, res) + local status = res and tonumber(res.code) + if status and status >= 300 and status < 400 then + local location = Request.header(res, "Location") + if location and location:sub(1, 1) == "/" and location:sub(1, 2) ~= "//" then + location = ORIGIN .. location + end + if remaining == 0 or type(location) ~= "string" + or location:sub(1, #ORIGIN + 1) ~= ORIGIN .. "/" then + cb(nil, _("塔读登录回调无效")) + return + end + follow(location, remaining - 1) + return + end + if err or not raw then cb(nil, err and tostring(err) or _("请求失败")); return end + confirm() + end) + end + follow(ORIGIN .. "/webchat/invoke/?" .. Text.formEncode({ code = wx_code, state = "STATE" }), 5) + function handle.cancel() + handle.cancelled = true + if handle.job then handle.job.cancel() end + end + return handle +end + +function Client.shelfAsync(cb) + local handle, chunks, cookie = {}, {}, Client.cookie() + local function page(n) + local pending = true + local job = Request.get(ORIGIN .. "/tadu/space/reader?pgNum=" .. n, opts("text/html", cookie), + function(raw, err) + pending = false + if handle.cancelled then return end + handle.job = nil + if err or not raw then cb(nil, err and tostring(err) or _("请求失败")); return end + if cookie ~= Client.cookie() then cb(nil, _("塔读登录已改变,请重试")); return end + local books, reason = Mapper.shelfPage(raw) + if not books then + cb(nil, reason == "未登录塔读" and expired(cookie) or _("塔读书架页面无法识别")) + return + end + chunks[#chunks + 1] = raw + if Mapper.shelfHasNext(raw, n) then + if n == 1000 then cb(nil, _("塔读书架分页异常")); return end + page(n + 1) + return + end + cb(table.concat(chunks, "\n")) + end) + if pending then handle.job = job end + end + page(1) + function handle.cancel() + handle.cancelled = true + if handle.job then handle.job.cancel() end + end + return handle +end + +local function changeShelf(method, url, body, stable_id, cb) + local cookie = Client.cookie() + local handle, pending = {}, true + local function done(raw, err) + pending = false + if handle.cancelled then return end + handle.job = nil + local wire, reason = decoded(raw, err) + if not wire then cb(nil, reason); return end + if cookie ~= Client.cookie() then cb(nil, _("塔读登录已改变,请重试")); return end + local status = tonumber(wire.status) + if status == 901 then cb(nil, expired(cookie)); return end + if status == 200 or (method == "GET" and status == 902) then + local checking = true + local job = Client.shelfAsync(function(html, shelf_err) + checking = false + if handle.cancelled then return end + handle.job = nil + if cookie ~= Client.cookie() then cb(nil, _("塔读登录已改变,请重试")); return end + if not html then cb(nil, shelf_err); return end + local found = false + for _idx, book in ipairs(Mapper.shelf(html)) do + if book.stable_id == stable_id then found = true; break end + end + if found ~= (method == "GET") then cb(nil, _("塔读书架修改未确认,请稍后重试")); return end + cb(true) + end) + if checking then handle.job = job end + return + end + cb(nil, type(wire.msg) == "string" and wire.msg ~= "" and wire.msg or _("响应无效")) + end + local job + if method == "GET" then job = Request.get(url, opts("application/json", cookie), done) + else job = Request.post(url, body, opts("application/json", cookie), done) end + if pending then handle.job = job end + function handle.cancel() + handle.cancelled = true + if handle.job then handle.job.cancel() end + end + return handle +end + +function Client.addAsync(stable_id, cb) + return changeShelf("GET", ORIGIN .. "/api/v1/favorite/" .. Text.urlEncode(stable_id), nil, stable_id, cb) +end + +function Client.removeAsync(stable_id, cb) + return changeShelf("POST", ORIGIN .. "/tadu/api/v1/delFavorites", "bookId=" .. Text.urlEncode(stable_id), stable_id, cb) +end + +function Client.searchAsync(keyword, cb) + return Request.post(ORIGIN .. "/search", "query=" .. Text.urlEncode(keyword), opts("text/html"), doneHtml(cb)) +end + +function Client.channelAsync(node, cb) + if node ~= nil and not Mapper.storeNode(node) then + return require("source.base").defer(cb, nil, _("响应无效")) + end + return Request.get(ORIGIN .. "/store" .. (node and "/" .. node or ""), opts("text/html"), doneHtml(cb)) +end + +function Client.detailAsync(stable_id, cb) + return Request.get(ORIGIN .. "/book/" .. Text.urlEncode(stable_id), opts("text/html"), doneHtml(cb)) +end + +function Client.chaptersAsync(stable_id, cb) + return Request.get(ORIGIN .. "/book/read/catalogue/" .. Text.urlEncode(stable_id), opts("text/html"), doneHtml(cb)) +end + +---@class TaduReading +---@field stable_id string +---@field chapter_uid string +---@field previous string|nil +---@field cookie string|nil +---@field active table|nil +---@field authorization TaduReadAuth|nil +---@field cancelled boolean|nil +local Reading = {} +Reading.__index = Reading + +function Reading:stop() + local active = self.active + self.active = nil + if active and active.job then active.job.cancel() end +end + +function Reading:cancel() + self.cancelled = true + self:stop() + if self.authorization then self.authorization:cancel() end +end + +function Reading:request(path, accept, cb) + if self.cancelled then return end + local active = {} + self.active = active + active.job = Request.get(ORIGIN .. path, opts(accept, self.cookie), function(raw, err, res) + if self.active ~= active or self.cancelled then return end + self.active = nil + if self.previous ~= Client.cookie() then cb(nil, _("塔读登录已改变,请重试")); return end + if err or not raw then cb(nil, err and tostring(err) or _("请求失败")); return end + local cookies, names, parts = {}, {}, {} + for name, value in (self.cookie or ""):gmatch("([^=;%s]+)=([^;]*)") do cookies[name] = value end + for _idx, line in ipairs(Request.headerAll(res, "Set-Cookie")) do + local name, value = line:match("^%s*([^=;%s]+)=([^;]*)") + if name then cookies[name] = value ~= "" and value ~= '""' and value or nil end + end + for name in pairs(cookies) do names[#names + 1] = name end + table.sort(names) + for _idx, name in ipairs(names) do parts[#parts + 1] = name .. "=" .. cookies[name] end + self.cookie = table.concat(parts, "; ") + cb(raw) + end) +end + +function Reading:qrCreateAsync(cb) + self:request("/qrcode/invoke", "application/json", function(raw, err) + local wire, reason = decoded(raw, err) + local data = wire and wire.data + if not wire or wire.status ~= 200 or type(data) ~= "table" + or type(data.qid) ~= "string" or data.qid == "" + or type(data.token) ~= "string" or data.token == "" + or type(data.qrcode) ~= "string" then + cb(nil, reason or _("获取二维码失败")) + return + end + local encoded = data.qrcode:match("^data:image/png;base64,([A-Za-z0-9+/=]+)$") + local image = encoded and Text.base64Decode(encoded) + if not image or image == "" then cb(nil, _("获取二维码失败")); return end + cb({ qid = data.qid, token = data.token, image = image }) + end) +end + +function Reading:qrPollAsync(ticket, cb) + self:request("/qrcode/check?" .. Text.formEncode({ qid = ticket.qid, token = ticket.token }), + "application/json", function(raw, err) + local wire, reason = decoded(raw, err) + if not wire or type(wire.status) ~= "number" then cb(nil, reason or _("响应无效")); return end + cb(wire.status) + end) +end + +function Reading:complete(html, err, cb) + if self.previous ~= Client.cookie() then cb(nil, _("塔读登录已改变,请重试")); return end + if html then + local settings = require("utils.settings") + local cfg = settings.getSource(SOURCE_ID) + if self.cookie ~= (self.previous or "") + and (cfg.read_cookie ~= self.cookie or cfg.read_cookie_for ~= (self.previous or "")) then + cfg.read_cookie, cfg.read_cookie_for = self.cookie, self.previous or "" + settings.saveSource(SOURCE_ID) + end + end + cb(html, err) +end + +function Reading:fontAsync(font, cb) + if font.url:sub(1, #ORIGIN + 1) ~= ORIGIN .. "/" then + cb(nil, _("塔读章节字体还原失败,请重试")) + return + end + self:request(font.url:sub(#ORIGIN + 1), "application/octet-stream", function(bytes, err) + if not bytes then cb(nil, err); return end + local active = {} + self.active = active + local job = require("moonsource_tadu.font").restoreAsync(font.html, bytes, function(html, reason) + if self.cancelled or self.active ~= active then return end + self.active = nil + self:complete(html, reason, cb) + end) + active.job = { cancel = function() job:cancel() end } + end) +end + +function Reading:contentAsync(cb, interactive) + self:request("/book/" .. Text.urlEncode(self.stable_id) .. "/" .. Text.urlEncode(self.chapter_uid) .. "/", + "text/html", function(page, err) + if not page then cb(nil, err); return end + local reading = Mapper.reading(page, self.stable_id) + if not reading then cb(nil, _("塔读阅读页无法识别")); return end + if reading.gated then + if interactive then + self.authorization = require("moonsource_tadu.read_auth").new(self, cb) + else + cb(nil, _("塔读此章节需要 App 扫码授权,请先打开章节扫码阅读")) + end + return + end + self:request(reading.resource, "application/json", function(raw, content_err) + local wire, reason = decoded(raw, content_err) + if not wire then cb(nil, reason); return end + local html, parse_err, font = Mapper.content(wire, self.chapter_uid) + if font then self:fontAsync(font, cb); return end + self:complete(html, html == nil and parse_err and _(parse_err) or nil, cb) + end) + end) +end + +function Client.contentAsync(stable_id, _part, cb, chapter_uid, interactive) + local previous = Client.cookie() + local cfg = require("utils.settings").getSource(SOURCE_ID) + local reading = setmetatable({ + stable_id = stable_id, chapter_uid = chapter_uid, previous = previous, + cookie = cfg.read_cookie_for == (previous or "") and cfg.read_cookie or previous, + }, Reading) + reading:contentAsync(cb, interactive) + return { cancel = function() reading:cancel() end } +end + +function Client.reviewsAsync(stable_id, cb) + return Request.get(ORIGIN .. "/v4/book/comment/" .. Text.urlEncode(stable_id) .. "/1/1", + opts("text/html"), function(raw, err) + if err or not raw then cb(nil, err and tostring(err) or _("请求失败")); return end + local items, pages = Mapper.reviews(raw) + cb(items, not items and _("响应无效") or nil, pages) + end) +end + +return Client diff --git a/moonsource-tadu.koplugin/moonsource_tadu/font.lua b/moonsource-tadu.koplugin/moonsource_tadu/font.lua new file mode 100644 index 0000000..43006dc --- /dev/null +++ b/moonsource-tadu.koplugin/moonsource_tadu/font.lua @@ -0,0 +1,137 @@ +--[[-- +塔读正文按精确字形指纹还原 Unicode。轮廓起点及排列顺序不影响指纹; +索引只含哈希与码点,不含原字体。仅替换文本节点,未知字形拒绝缓存。 + +@module moonsource_tadu.font +--]] + +local Glyph = require("utils.glyph") +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_tadu") +local TABLE_PATH = debug.getinfo(1, "S").source:sub(2):match("^(.*)/") .. "/font_table.bin" +-- MTF1 + sorted records: 32-byte SHA-256, 3-byte big-endian Unicode codepoint. +local RECORD_SIZE = 35 + +local Font = {} + +local function findCodepoint(index, hash) + local key = hash:gsub("%x%x", function(hex) return string.char(tonumber(hex, 16)) end) + local low, high = 0, (#index - 4) / RECORD_SIZE - 1 + while low <= high do + local mid = math.floor((low + high) / 2) + local pos = 5 + mid * RECORD_SIZE + local candidate = index:sub(pos, pos + 31) + if candidate == key then + local a, b, c = index:byte(pos + 32, pos + 34) + return a * 65536 + b * 256 + c + elseif candidate < key then + low = mid + 1 + else + high = mid - 1 + end + end +end + +local function fingerprint(outline, advance) + local paths, begin = {}, 0 + for contour = 0, outline.n_contours - 1 do + local points = {} + local last = tonumber(outline.contours[contour]) + for i = begin, last do + local point = outline.points[i] + points[#points + 1] = string.format("%d,%d,%d", tonumber(outline.tags[i]) % 2, + math.floor(tonumber(point.x) / 64 + 0.5), math.floor(tonumber(point.y) / 64 + 0.5)) + end + local best + for i = 1, #points do + local rotated = {} + for j = 0, #points - 1 do rotated[#rotated + 1] = points[(i + j - 1) % #points + 1] end + local value = table.concat(rotated, ";") + if not best or value < best then best = value end + end + paths[#paths + 1] = best + begin = last + 1 + end + table.sort(paths) + local shape = math.floor(tonumber(advance) / 64 + 0.5) .. "|" .. table.concat(paths, "|") + return require("ffi/sha2").sha256(shape) +end + +local function restore(html, bytes, path) + if bytes:sub(1, 4) ~= "\0\1\0\0" then return { err = _("塔读章节字体还原失败,请重试") } end + local file = assert(io.open(path, "wb")) + assert(file:write(bytes)) + assert(file:close()) + local index_file = assert(io.open(TABLE_PATH, "rb")) + local index = assert(index_file:read("*a")) + assert(index_file:close()) + assert(index:sub(1, 4) == "MTF1" and (#index - 4) % RECORD_SIZE == 0, "invalid tadu font index") + local font = require("ffi/freetype").newFaceSize(path, 2048) --[[@as FreeTypeSize]] + local ft2 = assert(require("ffi").loadlib)("freetype", "6") + local map, seen = {}, {} + local parts, nodes, pos = {}, {}, 1 + local function textNode(node) + local text = Text.xmlDecode(node) + parts[#parts + 1] = text + nodes[#nodes + 1] = #parts + end + for first, after in html:gmatch("()<[^>]*>()") do + textNode(html:sub(pos, first - 1)) + parts[#parts + 1] = html:sub(first, after - 1) + pos = after + end + textNode(html:sub(pos)) + for _node_idx, part in ipairs(nodes) do + for ch in parts[part]:gmatch(Text.UTF8_CHAR) do + local cp = Glyph.codepoint(ch) + if cp > 127 and not seen[cp] then + seen[cp] = true + if font:hasGlyph(cp) then + -- FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP: design outlines, not screen pixels. + assert(ft2.FT_Load_Char(font.face, cp, 10) == 0, "FreeType glyph load failed") + local glyph = font.face.glyph + if glyph.outline.n_points > 0 then + local decoded = findCodepoint(index, fingerprint(glyph.outline, glyph.advance.x)) + if not decoded then + font:done() + require("utils.log").warn("tadu font glyph not mapped", cp) + return { err = _("塔读章节字体还原失败,请重试") } + end + map[cp] = Text.utf8char(decoded) + end + end + end + end + end + font:done() + for _node_idx, part in ipairs(nodes) do + parts[part] = Text.xmlEscape(parts[part]:gsub(Text.UTF8_CHAR, function(ch) + return map[Glyph.codepoint(ch)] + end)) + end + return { html = table.concat(parts) } +end + +---@param html string +---@param bytes string +---@param cb fun(html: string|nil, err: string|nil) +---@return BookJob +function Font.restoreAsync(html, bytes, cb) + local path = require("utils.paths").tmpname(".font") + return require("workers.job").run(function() + return restore(html, bytes, path) + end, { + name = "tadu_font", kind = "light", timeout = 30, + on_done = function(result) + os.remove(path) + cb(result.html, result.err) + end, + on_failed = function(err) + os.remove(path) + cb(nil, tostring(err)) + end, + on_cancelled = function() os.remove(path) end, + }) +end + +return Font diff --git a/moonsource-tadu.koplugin/moonsource_tadu/font_table.bin b/moonsource-tadu.koplugin/moonsource_tadu/font_table.bin new file mode 100644 index 0000000..695d33d Binary files /dev/null and b/moonsource-tadu.koplugin/moonsource_tadu/font_table.bin differ diff --git a/moonsource-tadu.koplugin/moonsource_tadu/l10n/en.lua b/moonsource-tadu.koplugin/moonsource_tadu/l10n/en.lua new file mode 100644 index 0000000..51d37bc --- /dev/null +++ b/moonsource-tadu.koplugin/moonsource_tadu/l10n/en.lua @@ -0,0 +1,35 @@ +return { + ["塔读登录 Cookie"] = "Tadu login Cookie", + ["塔读登录已失效,请在官网重新登录"] = "Your Tadu session expired. Sign in again on the official website.", + ["塔读登录已改变,请重试"] = "The Tadu session changed. Please retry.", + ["更换塔读登录前,请先退出旧账号;退出会清除本地阅读记录和缓存"] = "Sign out of the old Tadu account before replacing the session. Signing out clears local reading records and caches.", + ["塔读登录回调无效"] = "Invalid Tadu login callback", + ["塔读书架分页异常"] = "Invalid Tadu shelf pagination", + ["塔读书架修改未确认,请稍后重试"] = "The Tadu shelf change could not be confirmed. Please retry later.", + ["塔读章节字体还原失败,请重试"] = "Tadu chapter font decoding failed. Please retry.", + ["塔读阅读页无法识别"] = "Could not recognize the Tadu reading page.", + ["塔读此章节需要 App 扫码授权,请先打开章节扫码阅读"] = "This Tadu chapter requires App scan authorization. Open the chapter first to authorize reading.", + ["塔读 App 扫码阅读"] = "Tadu App reading authorization", + ["打开塔读小说 App,在「我的」页面点扫一扫;授权后自动继续阅读"] = "Open the Tadu Novels App and tap Scan on the Me page. Reading resumes after authorization.", + ["频道"] = "Channel", + ["字数"] = "Word count", + ["离线缓存"] = "Offline caching", + ["塔读小说"] = "Tadu Novel", + ["塔读书架与在线阅读"] = "Tadu shelf and online reading", + ["塔读扫码登录"] = "Tadu QR sign-in", + ["用微信扫一扫"] = "Scan with WeChat", + ["打开微信,扫屏幕上的二维码"] = "Open WeChat and scan the QR code", + ["塔读账号"] = "Tadu account", + ["未登录塔读"] = "Not signed in to Tadu", + ["塔读目录为空"] = "Tadu chapter list is empty", + ["确定退出塔读账号?"] = "Sign out of Tadu?", + ["塔读书架页面无法识别"] = "Tadu shelf page was not recognized", + ["未登录 · 点此扫码"] = "Not signed in · tap to scan", + ["章节目录保存失败"] = "Failed to save chapter list", + ["已在微信中拒绝登录"] = "Login declined in WeChat", + ["按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"] = "Press F12, open Network, refresh, and copy the entire Cookie request header", + ["书架同步"] = "Shelf sync", + ["搜索与发现"] = "Search and discover", + ["刷新"] = "Refresh", + ["塔读"] = "Tadu", +} diff --git a/moonsource-tadu.koplugin/moonsource_tadu/l10n/zh_TW.lua b/moonsource-tadu.koplugin/moonsource_tadu/l10n/zh_TW.lua new file mode 100644 index 0000000..f25ed7e --- /dev/null +++ b/moonsource-tadu.koplugin/moonsource_tadu/l10n/zh_TW.lua @@ -0,0 +1,35 @@ +return { + ["塔读登录 Cookie"] = "塔讀登入 Cookie", + ["塔读登录已失效,请在官网重新登录"] = "塔讀登入已失效,請在官網重新登入", + ["塔读登录已改变,请重试"] = "塔讀登入已改變,請重試", + ["更换塔读登录前,请先退出旧账号;退出会清除本地阅读记录和缓存"] = "更換塔讀登入前,請先登出舊帳號;登出會清除本機閱讀記錄和快取", + ["塔读登录回调无效"] = "塔讀登入回呼無效", + ["塔读书架分页异常"] = "塔讀書架分頁異常", + ["塔读书架修改未确认,请稍后重试"] = "塔讀書架修改未確認,請稍後重試", + ["塔读章节字体还原失败,请重试"] = "塔讀章節字型還原失敗,請重試", + ["塔读阅读页无法识别"] = "無法辨識塔讀閱讀頁面", + ["塔读此章节需要 App 扫码授权,请先打开章节扫码阅读"] = "塔讀此章節需要 App 掃碼授權,請先開啟章節掃碼閱讀", + ["塔读 App 扫码阅读"] = "塔讀 App 掃碼閱讀", + ["打开塔读小说 App,在「我的」页面点扫一扫;授权后自动继续阅读"] = "開啟塔讀小說 App,在「我的」頁面點掃一掃;授權後自動繼續閱讀", + ["频道"] = "頻道", + ["字数"] = "字數", + ["离线缓存"] = "離線快取", + ["塔读小说"] = "塔讀小說", + ["塔读书架与在线阅读"] = "塔讀書架與線上閱讀", + ["塔读扫码登录"] = "塔讀掃碼登入", + ["用微信扫一扫"] = "用微信掃一掃", + ["打开微信,扫屏幕上的二维码"] = "打開微信,掃螢幕上的二維碼", + ["塔读账号"] = "塔讀帳號", + ["未登录塔读"] = "未登入塔讀", + ["塔读目录为空"] = "塔讀目錄為空", + ["确定退出塔读账号?"] = "確定退出塔讀帳號?", + ["塔读书架页面无法识别"] = "塔讀書架頁面無法識別", + ["未登录 · 点此扫码"] = "未登入 · 點此掃碼", + ["章节目录保存失败"] = "章節目錄儲存失敗", + ["已在微信中拒绝登录"] = "已在微信中拒絕登入", + ["按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"] = "按鍵盤 F12,點「網路」,重新整理網頁,複製請求標頭裡的整段 Cookie", + ["书架同步"] = "書架同步", + ["搜索与发现"] = "搜尋與發現", + ["刷新"] = "重新整理", + ["塔读"] = "塔讀", +} diff --git a/moonsource-tadu.koplugin/moonsource_tadu/loadmeta.lua b/moonsource-tadu.koplugin/moonsource_tadu/loadmeta.lua new file mode 100644 index 0000000..83dbad5 --- /dev/null +++ b/moonsource-tadu.koplugin/moonsource_tadu/loadmeta.lua @@ -0,0 +1,5 @@ +return function() + local copy = {} + for k, v in pairs(require("moonsource_tadu._meta")) do copy[k] = v end + return copy +end diff --git a/moonsource-tadu.koplugin/moonsource_tadu/mapper.lua b/moonsource-tadu.koplugin/moonsource_tadu/mapper.lua new file mode 100644 index 0000000..bbd7ddc --- /dev/null +++ b/moonsource-tadu.koplugin/moonsource_tadu/mapper.lua @@ -0,0 +1,357 @@ +--[[-- +塔读网页 → 领域对象。纯函数,不发请求。 + +@module moonsource_tadu.mapper +--]] + +local Text = require("utils.text") + +local Mapper = {} + +local SOURCE_ID = "ext.tadu" + +--- 目录缓存格式。首章携带,变了就当缓存失效。 +Mapper.TOC_VERSION = 1 + +---@param html string|nil +---@return string +local function flat(html) + if type(html) ~= "string" then return "" end + return (html:gsub("", ""):gsub("%s+", " ")) +end + +---@param value string|nil +---@return string +local function clean(value) + if type(value) ~= "string" then return "" end + return Text.trim(Text.xmlDecode(value:gsub("<[^>]+>", ""))) +end + +---@param id string|number +---@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 not cover:find("coverBg", 1, true) + and Text.xmlDecode(cover) or nil + local name = clean(author):gsub("%s*著%s*$", "") + return { + source_id = SOURCE_ID, + stable_id = tostring(id), + title = clean(title), + authors = name, + intro = clean(intro), + cover = picture, + } +end + +--- 微信 qrconnect 页面里的 uuid。二维码内容是 confirm 链接。 +---@param html string|nil +---@return string|nil +function Mapper.qrUuid(html) + if type(html) ~= "string" then return nil end + return html:match("/connect/qrcode/([%w_%-]+)") +end + +---@param uuid string +---@return string +function Mapper.qrText(uuid) + return "https://open.weixin.qq.com/connect/confirm?uuid=" .. Text.urlEncode(uuid) +end + +--- 长轮询回包。405 确认,404 已扫码,408 继续等,403 拒绝,402 过期。 +--- JSON(f=json)和页面里的 `wx_errcode=` 脚本都认。 +---@param body string|nil +---@return "ok"|"wait"|"fail"|"expired" +---@return string|nil wx_code +---@return integer|nil errcode +function Mapper.wxStatus(body) + if type(body) ~= "string" or body == "" then return "expired" end + local code, wx_code + if body:sub(1, 1) == "{" then + local ok, wire = pcall(require("json").decode, body) + if ok and type(wire) == "table" then + code = tonumber(wire.wx_errcode) + wx_code = wire.wx_code + end + end + if not code then + code = tonumber(body:match("wx_errcode%s*=%s*(%-?%d+)")) + wx_code = body:match("wx_code%s*=%s*'([^']*)'") or body:match('wx_code%s*=%s*"([^"]*)"') + end + if code == 405 and type(wx_code) == "string" and wx_code ~= "" then return "ok", wx_code, code end + if code == 404 or code == 408 then return "wait", nil, code end + if code == 403 then return "fail", nil, code end + return "expired", nil, code +end + +--- 登录后的 /user/info。没有 user 就是还没登录。 +---@param wire table|nil +---@return { name: string }|nil +function Mapper.user(wire) + local user = type(wire) == "table" and type(wire.data) == "table" and wire.data.user or nil + if type(user) ~= "table" then return nil end + local name = type(user.nickname) == "string" and user.nickname ~= "" and user.nickname or user.username + if type(name) ~= "string" or name == "" then return nil end + return { name = name } +end + +--- 搜索页和书库页共用的书卡。`bookNm` 里的高亮 span 去掉。 +---@param html string|nil +---@return Book[] +function Mapper.books(html) + local text = flat(html) + local out, seen = {}, {} + local pos = 1 + while true do + local start, stop = text:find('class="bookNm"', pos, true) + if not start then break end + local back = text:sub(math.max(1, start - 800), start) + local id = back:match(".*/book/(%d+)/") + local inner = text:sub(stop + 1):match("^[^>]*>(.-)") + local forward = text:sub(stop, math.min(#text, stop + 500)) + local next_card = forward:find('class="bookNm"', 2, true) + if next_card then forward = forward:sub(1, next_card - 1) end + local author = forward:match('class="authorNm"[^>]*>(.-)') + or forward:match('class="authorNm"[^>]*>(.-)') + local intro = forward:match('class="bookIntro"[^>]*>(.-)') + local cover + for found in back:gmatch('data%-src="([^"]+)"') do cover = found end + if id and not seen[id] and clean(inner) ~= "" then + seen[id] = true + out[#out + 1] = book(id, inner, author, intro, cover) + end + pos = stop + 1 + end + return out +end + +--- 个人中心书架。空架是 `bookrack_table_kong`,有书时行上带 `data-bookid`。 +--- 旧书架页的 `bookNm` 卡片也认。 +---@param html string|nil +---@return Book[] +function Mapper.shelf(html) + local text = flat(html) + if text:find("bookrack_table_kong", 1, true) and not text:find("data-bookid", 1, true) then + return {} + end + local out, seen = {}, {} + local pos = 1 + while true do + local _start, stop, id = text:find('data%-bookid%s*=%s*["\'](%d+)["\']', pos) + if not _start then break end + local window = text:sub(stop, math.min(#text, stop + 1200)) + local title = window:match('class="linkBlock"[^>]*>([^<]+)') + local author = window:match('class="table_author".-]*>([^<]*)') + if not seen[id] and clean(title) ~= "" then + seen[id] = true + out[#out + 1] = book(id, title, author) + end + pos = stop + 1 + end + if out[1] then return out end + return Mapper.books(text) +end + +--- 书架页。未登录时服务端直接回首页,不能当成空书架。 +---@param html string|nil +---@return Book[]|nil +---@return string|nil +function Mapper.shelfPage(html) + local text = flat(html) + local title = text:match("(.-)") or "" + if title:find("免费阅读最新热门小说", 1, true) then return nil, "未登录塔读" end + if title:find("出错了", 1, true) then return nil, "塔读书架页面无法识别" end + local books = Mapper.shelf(text) + if #books > 0 then return books end + if text:find("bookrack_table_kong", 1, true) + or text:find("还没有", 1, true) or text:find("暂无", 1, true) then + return {} + end + return nil, "塔读书架页面无法识别" +end + +---@param html string|nil +---@param page integer +---@return boolean +function Mapper.shelfHasNext(html, page) + if type(html) ~= "string" then return false end + local next_page = tostring(page + 1) + return html:find("pgNum=" .. next_page .. "%D") ~= nil + or html:find("/tadu/space/my%-bookshelf/" .. next_page .. "%D") ~= nil +end + +--- 只接受官网书库的九段节点,禁止把节点当任意路径。 +function Mapper.storeNode(node) + return type(node) == "string" + and node:match("^%d+%-[atfsq]%-[0-9]+%-[0-9]+%-[atf]%-[0-9]+%-[pt]%-[0-9]+%-[0-9]+$") ~= nil +end + +function Mapper.storePage(node, page) + return (node:gsub("%-([pt])%-%d+%-(%d+)$", "-%1-" .. page .. "-%2")) +end + +--- 从实际可见链接取筛选;注释里的出版、资费入口不是可用能力。 +function Mapper.storeGroups(html) + local text, groups = flat(html), {} + for block in text:gmatch('
]*>(.-)
') do + local title = clean(block:match("]*>(.-)")) + local chips, active = {}, nil + for attrs, name in block:gmatch("]+)>(.-)") do + local node = attrs:match('href="/store/([^"]+)"') + if Mapper.storeNode(node) then + chips[#chips + 1] = { id = node, title = clean(name) } + if attrs:find("current", 1, true) then active = node end + end + end + if #chips > 1 then groups[#groups + 1] = { title = title, chips = chips, active = active } end + end + local sort = text:match('
(.-)
') + if sort then + local chips, active = {}, nil + for attrs, name in sort:gmatch("]+)>(.-)") do + local node = attrs:match("/store/([%w%-]+)") + if Mapper.storeNode(node) then + chips[#chips + 1] = { id = node, title = clean(name) } + active = node + end + end + for attrs, name in sort:gmatch("]+)>(.-)") do + local node = attrs:match('href="/store/([^"]+)"') + if Mapper.storeNode(node) then + chips[#chips + 1] = { id = node, title = clean(name) } + if attrs:find("current", 1, true) then active = node end + end + end + if #chips > 1 then groups[#groups + 1] = { title = "排序", chips = chips, active = active } end + end + return groups +end + +function Mapper.storeMore(html, node, page) + return flat(html):find('href="/store/' .. Mapper.storePage(node, page + 1) .. '"', 1, true) ~= nil +end + +--- 列表页必须有结果容器,错误页不是空结果。 +function Mapper.listPage(html) + local text = flat(html) + local books = Mapper.books(text) + if #books > 0 or text:find('class="bookList', 1, true) + or text:find("没有找到", 1, true) then return books end + return nil, "响应无效" +end + +--- 作品评论区绑定 bookId,不是章评。这里只读已核对的网页列表。 +function Mapper.reviews(html) + local text, items = flat(html), {} + local _text, expected = text:gsub('
', "") + for block, date in text:gmatch('
(.-)]*>(.-)') do + local body = clean(block:match("]*>(.-)

")) + local title = clean(block:match("]*>(.-)")) + if body ~= "" or title ~= "" then + items[#items + 1] = { + author = clean(block:match("]*>(.-)")), + text = title ~= "" and title .. "\n" .. body or body, + time = clean(date), + } + end + end + if #items ~= expected then return nil end + if #items == 0 and not text:find("作品评论区", 1, true) + and not text:find("暂无评论", 1, true) then return nil end + local pages = 1 + for page in text:gmatch("/v4/book/comment/%d+/%d+/(%d+)") do pages = math.max(pages, tonumber(page)) end + return items, pages +end + +--- 书籍页。 +---@param html string|nil +---@param id string +---@return Book|nil +function Mapper.detail(html, id) + local text = flat(html) + local title = text:match('class="bkNm"[^>]*data%-name="([^"]+)"') + or text:match('class="bkNm"[^>]*>([^<]+)') + if not title or clean(title) == "" then return nil end + local author = text:match('class="author"[^>]*>([^<]+)') + local intro = text:match('class="intro"[^>]*>(.-)

') + local cover = text:match('class="bookImg"[^>]*>.-data%-src="([^"]+)"') + return book(id, title, author, intro, cover) +end + +--- 阅读页目录。链接顺序就是正文接口的分卷序号。 +---@param html string|nil +---@return BookChapter[] +function Mapper.chapters(html) + local text = flat(html) + local toc, seen = {}, {} + for id, title in text:gmatch('href="%s*/book/%d+/(%d+)/%s*"[^>]*>([^<]+)') do + if not seen[id] and clean(title) ~= "" then + seen[id] = true + local idx = #toc + 1 + toc[idx] = { + idx = idx, + uid = id, + source_idx = tostring(idx), + title = clean(title), + depth = 1, + } + end + end + if toc[1] then toc[1].toc_version = Mapper.TOC_VERSION end + return toc +end + +--- 扫码限制只在阅读页声明;正文接口仍会返回 status=200 的预览。 +---@param html string +---@param stable_id string +---@return table|nil +function Mapper.reading(html, stable_id) + local text, resource, gated = flat(html), nil, false + for tag in text:gmatch("<[^>]+>") do + if tag:match('id="bookPartResourceUrl"') then + resource = tag:match('value="([^"]+)"') + end + local classes = tag:match('class="([^"]+)"') + if classes and (" " .. classes .. " "):find(" appQrCode ", 1, true) then + if tag:match('data%-url="([^"]+)"') ~= "/qrcode/invoke" + or tag:match('data%-status="([^"]+)"') ~= "/qrcode/check" then return nil end + gated = true + end + end + local id, part + if resource then id, part = resource:match("^/getPartContentByCodeTable/(%d+)/(%d+)$") end + if id ~= stable_id or not part then return nil end + return { resource = resource, gated = gated } +end + +--- 正文 JSON。夹带的塔读推广段丢掉。 +---@param wire table|nil +---@return string|nil +---@return string|nil +---@return {url: string, html: string}|nil +function Mapper.content(wire, chapter_uid) + if type(wire) ~= "table" then return nil, "响应无效" end + if tostring(wire.status or "") ~= "200" then + local msg = type(wire.msg) == "string" and wire.msg ~= "" and wire.msg or "响应无效" + return nil, msg + end + local data = wire.data + local html = type(data) == "table" and data.content or nil + if type(html) ~= "string" or html == "" then return nil, "响应无效" end + if chapter_uid then + local hidden = Text.base64Encode(tostring(chapter_uid)) + html = html:gsub(']*)>(.-)

', function(attrs, body) + if attrs:match('data%-limit="([^"]+)"') == hidden then return "" end + return "" .. body .. "

" + end) + end + if type(data.url) == "string" and data.url ~= "" then + return nil, "塔读章节字体还原失败,请重试", { url = data.url, html = html } + end + return html +end + +return Mapper diff --git a/moonsource-tadu.koplugin/moonsource_tadu/qrlogin.lua b/moonsource-tadu.koplugin/moonsource_tadu/qrlogin.lua new file mode 100644 index 0000000..d4d3833 --- /dev/null +++ b/moonsource-tadu.koplugin/moonsource_tadu/qrlogin.lua @@ -0,0 +1,127 @@ +--[[-- +塔读微信扫码登录。 + +打开微信扫 confirm 链接。长轮询本身会挂住,扫上之后再隔 0.2 秒问下一次。 +五分钟还没确认就当二维码过期。 + +@module moonsource_tadu.qrlogin +--]] + +local Client = require("moonsource_tadu.client") +local Mapper = require("moonsource_tadu.mapper") +local _ = require("l10n").get("moonsource_tadu") + +local QRLogin = {} +QRLogin.__index = QRLogin + +local POLL_INTERVAL = 0.2 +local DEADLINE = 5 * 60 + +---@param on_user fun(user: { name: string }) +---@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:_retry(text) + self:cancel() + if self.dialog then + self.dialog:close() + self.dialog = nil + end + require("ui.themes.widgets.confirm"):new{ + text = text, + ok_text = _("重新获取"), + ok_callback = function() self:start() end, + }:show() +end + +---@param gen integer +---@param uuid string +---@param last integer|nil +function QRLogin:_poll(gen, uuid, last) + if gen ~= self.generation then return end + if os.time() > self.deadline then + self:_retry(_("二维码已过期")) + return + end + local pending = true + local job = Client.qrPollAsync(uuid, last, function(kind, wx_code, errcode, reason) + pending = false + if gen ~= self.generation then return end + self.job = nil + if kind == "ok" then + local exchanging = true + local exchange = Client.exchangeAsync(wx_code, function(user, err) + exchanging = false + if gen ~= self.generation then return end + self.job = nil + if not user then + self:_retry(err or _("未登录塔读")) + return + end + self:cancel() + if self.dialog then + self.dialog:close() + self.dialog = nil + end + self.on_user(user) + end) + if exchanging and gen == self.generation then self.job = exchange end + return + end + if kind == "wait" then + require("ui/uimanager"):scheduleIn(POLL_INTERVAL, function() + if gen == self.generation then self:_poll(gen, uuid, errcode) end + end) + return + end + if kind == "fail" then + self:_retry(_("已在微信中拒绝登录")) + return + end + if kind == "error" then + self:_retry(reason or _("请求失败")) + return + end + self:_retry(_("二维码已过期")) + end) + if pending and gen == self.generation then self.job = job end +end + +function QRLogin:start() + self:cancel() + local gen = self.generation + self.deadline = os.time() + DEADLINE + local pending = true + local job = Client.qrCreateAsync(function(uuid, err) + pending = false + if gen ~= self.generation then return end + self.job = nil + if not uuid then + self:_retry(err or _("获取二维码失败")) + return + end + local QR = require("ui.themes.widgets.qr") + self.dialog = QR:new{ + title = _("塔读扫码登录"), + caption = _("用微信扫一扫"), + text = Mapper.qrText(uuid), + close_callback = function() + if gen == self.generation then self:cancel() end + end, + } + self.dialog:show() + self:_poll(gen, uuid, nil) + end) + if pending and gen == self.generation then self.job = job end +end + +return QRLogin diff --git a/moonsource-tadu.koplugin/moonsource_tadu/read_auth.lua b/moonsource-tadu.koplugin/moonsource_tadu/read_auth.lua new file mode 100644 index 0000000..7bf87cf --- /dev/null +++ b/moonsource-tadu.koplugin/moonsource_tadu/read_auth.lua @@ -0,0 +1,109 @@ +--[[-- +塔读官方 App 扫码阅读授权。二维码、票据和轮询归本次开章操作所有。 + +@module moonsource_tadu.read_auth +--]] + +local _ = require("l10n").get("moonsource_tadu") + +---@class TaduReadAuth +---@field session TaduReading +---@field callback fun(html: string|nil, err: string|nil) +---@field generation integer +---@field deadline integer +---@field done boolean|nil +---@field timer function|nil +---@field dialog BookThemeQR|BookThemeConfirm|nil +---@field ticket table|nil +local ReadAuth = {} +ReadAuth.__index = ReadAuth + +function ReadAuth:clear() + self.generation = self.generation + 1 + self.session:stop() + if self.timer then require("ui/uimanager"):unschedule(self.timer); self.timer = nil end + if self.dialog then + local dialog = self.dialog + self.dialog = nil + dialog:close() + end + self.ticket = nil +end + +function ReadAuth:cancel() + if self.done then return end + self.done = true + self:clear() +end + +function ReadAuth:finish(html, err) + if self.done then return end + self:cancel() + self.callback(html, err) +end + +function ReadAuth:retry(err) + self:clear() + self.dialog = require("ui.themes.widgets.confirm"):new{ + text = err, ok_text = _("重新获取"), + ok_callback = function() + self.dialog = nil + self:start() + end, + cancel_callback = function() self:finish(nil, err) end, + } + self.dialog:show() +end + +function ReadAuth:poll(gen) + if self.done or gen ~= self.generation then return end + if os.time() >= self.deadline then self:retry(_("二维码已过期")); return end + self.session:qrPollAsync(self.ticket, function(status, err) + if self.done or gen ~= self.generation then return end + if status == 200 then + self.session:contentAsync(function(html, reason) self:finish(html, reason) end, false) + elseif status == 0 or status == 1 then + self.timer = function() + self.timer = nil + self:poll(gen) + end + require("ui/uimanager"):scheduleIn(1, self.timer) + else + self:retry(err or _("二维码已过期")) + end + end) +end + +function ReadAuth:start() + if self.done then return end + self:clear() + local gen = self.generation + self.deadline = os.time() + 300 + self.session:qrCreateAsync(function(ticket, err) + if self.done or gen ~= self.generation then return end + local image = ticket and require("ui/renderimage"):renderImageData(ticket.image, #ticket.image, false) + if not image then self:retry(err or _("获取二维码失败")); return end + self.ticket = ticket + self.dialog = require("ui.themes.widgets.qr"):new{ + title = _("塔读 App 扫码阅读"), image = image, close_on_tap = false, + caption = _("打开塔读小说 App,在「我的」页面点扫一扫;授权后自动继续阅读"), + actions = { + { text = _("取消"), callback = function() self:finish(nil, _("已取消")) end }, + { text = _("刷新"), callback = function() self:start() end }, + }, + close_callback = function() + if self.dialog and gen == self.generation then self:finish(nil, _("已取消")) end + end, + } + self.dialog:show() + self:poll(gen) + end) +end + +function ReadAuth.new(session, cb) + local self = setmetatable({ session = session, callback = cb, generation = 0 }, ReadAuth) + self:start() + return self +end + +return ReadAuth diff --git a/moonsource-tadu.koplugin/moonsource_tadu/setting.lua b/moonsource-tadu.koplugin/moonsource_tadu/setting.lua new file mode 100644 index 0000000..33a1794 --- /dev/null +++ b/moonsource-tadu.koplugin/moonsource_tadu/setting.lua @@ -0,0 +1,97 @@ +--[[-- +塔读账号:微信扫码、官网浏览器登录及 Cookie 导入。 + +@module moonsource_tadu.setting +--]] + +local _ = require("l10n").get("moonsource_tadu") +local CookieLogin = require("source.cookie_login") + +local SOURCE_ID = "ext.tadu" +local Setting = {} +local LOGIN_URL = "https://www.tadu.com/v3/loginpage" + +---@return boolean +local function loggedIn() + return require("moonsource_tadu.client").loggedIn() +end + +---@param user { name: string } +local function save(user) + local settings = require("utils.settings") + local cfg = settings.getSource(SOURCE_ID) + cfg.logged_in = true + cfg.name = user.name + 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 + +function Setting.open() + if not require("ui/network/manager"):isConnected() then + require("ui.themes.widgets.toast"):new{ text = _("网络不可用,请先连接 Wi-Fi"), timeout = 3 }:show() + return + end + require("moonsource_tadu.qrlogin"):new(save):start() +end + +local SPEC = { + id = SOURCE_ID, title = _("塔读账号"), cookie_title = _("塔读登录 Cookie"), + cookie_hint = _("按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"), + logout_text = _("确定退出塔读账号?"), + loggedIn = loggedIn, + checkAsync = require("moonsource_tadu.client").loginCheckAsync, + commit = function(cookie, user, cb) + local ok, err = require("moonsource_tadu.client").commitLogin(cookie, user) + cb(ok == true, err) + end, + clear = function(cfg) + cfg.cookie, cfg.logged_in, cfg.name = nil, nil, nil + cfg.read_cookie, cfg.read_cookie_for = nil, nil + end, +} + +Setting.browser = { + domain = "www.tadu.com", scope = "cookie", login = LOGIN_URL, + check = "https://www.tadu.com/tadu/space/reader", + icon = "https://media3.tadu.com/web_dubbo_static/images/tadu.ico", + isAuthorized = function() return CookieLogin.authorized(SPEC) end, + apply = function(payload, cb) + return CookieLogin.save(SPEC, CookieLogin.fromPayload(payload, "tadu.com"), 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 = _("塔读账号"), + subtitle = _("打开微信,扫屏幕上的二维码"), + status = status, status_on = status_on, + callback = function() Setting.open() end, + }) + end, + CookieLogin.browserRow(), + CookieLogin.pasteRow(SPEC), + } + local cookie = require("moonsource_tadu.client").cookie() + if type(cookie) == "string" and cookie ~= "" then + rows[#rows + 1] = CookieLogin.logoutRow(SPEC) + end + return rows +end + +Setting.login = Setting.open + +return Setting diff --git a/moonsource-tadu.koplugin/moonsource_tadu/source.lua b/moonsource-tadu.koplugin/moonsource_tadu/source.lua new file mode 100644 index 0000000..202d8fa --- /dev/null +++ b/moonsource-tadu.koplugin/moonsource_tadu/source.lua @@ -0,0 +1,191 @@ +--[[-- +塔读数据源。 + +微信扫码登录后同步网页书架。目录来自阅读页,正文按目录顺序取 +getPartContentByCodeTable。书城搜索和频道不需要登录。 + +@module moonsource_tadu +--]] + +local Browse = require("source.browse") +local Client = require("moonsource_tadu.client") +local Mapper = require("moonsource_tadu.mapper") +local Shelf = require("source.shelf") +local SourceBase = require("source.base") +local Toc = require("source.toc") +local _ = require("l10n").get("moonsource_tadu") + +local Tadu = {} + +local FETCH_INTERVAL = 0.5 + +---@return BookSourceMeta +function Tadu.meta() + return require("moonsource_tadu.loadmeta")() +end + +---@class TaduSource : SourceBase +local Source = setmetatable({ shelf_add = true }, { __index = SourceBase }) +Source.__index = Source + +---@return TaduSource +function Tadu.new() + local meta = Tadu.meta() + return setmetatable({ id = meta.id, name = meta.name, type = meta.type }, Source) +end + +---@return boolean +function Source:configured() + return Client.loggedIn() +end + +local Remote = {} + +function Remote:shelfSyncAsync(cb) return Client.shelfAsync(cb) end + +---@param stable_id string +---@param cb fun(ok: boolean|nil, err: string|nil) +function Remote:addToShelfAsync(stable_id, cb) + return Client.addAsync(stable_id, cb) +end + +---@param stable_id string +---@param cb fun(ok: boolean|nil, err: string|nil) +function Remote:removeFromShelfAsync(stable_id, cb) + return Client.removeAsync(stable_id, cb) +end + +function Source:syncBooksAsync(opts, cb) + if not self:configured() then return SourceBase.skipped(cb, "tadu not logged in") end + return Shelf.syncAsync(self.id, Remote, Mapper.shelf, opts, cb) +end + +---@param keyword string +---@param cb fun(res: { data: Book[] }|nil, err: string|nil) +function Source:searchAsync(keyword, cb) + return Client.searchAsync(keyword, function(html, err) + if not html then cb(nil, err or _("请求失败")); return end + local books = Mapper.listPage(html) + if not books then cb(nil, _("响应无效")); return end + cb({ data = books }) + end) +end + +---@param opts { node?: string, limit?: integer }|nil +---@param cb fun(res: { data: Book[], groups: StoreChipGroup[] }|nil, err: string|nil) +function Source:browseAsync(opts, cb) + local node = opts and opts.node + if not Mapper.storeNode(node) then node = nil end + if node then node = Mapper.storePage(node, 1) end + local handle, pending = {}, true + local first = Client.channelAsync(node, function(html, err) + pending = false + if handle.cancelled then return end + if not html then cb(nil, err or _("请求失败")); return end + local groups = Mapper.storeGroups(html) + local books = Mapper.listPage(html) + if not books or not groups[1] then cb(nil, _("响应无效")); return end + local titles = { + ["频道"] = _("频道"), ["分类"] = _("分类"), ["状态"] = _("状态"), + ["字数"] = _("字数"), ["排序"] = _("排序"), + } + for _idx, group in ipairs(groups) do group.title = titles[group.title] or group.title end + node = node or groups[1].active + if not node then cb(nil, _("响应无效")); return end + handle.inner = Browse.pages(function(page, done) + if page == 1 then + done(books, nil, Mapper.storeMore(html, node, page)) + return + end + return Client.channelAsync(Mapper.storePage(node, page), function(raw, reason) + if not raw then done(nil, reason); return end + local list = Mapper.listPage(raw) + done(list, not list and _("响应无效") or nil, Mapper.storeMore(raw, node, page)) + end) + end, opts and opts.limit or 60, groups, cb) + end) + if pending then handle.inner = first end + function handle.cancel() + handle.cancelled = true + if handle.inner then handle.inner.cancel() end + end + return handle +end + +function Source:getDetailAsync(identity, cb) + return Client.detailAsync(identity.stable_id, function(html, err) + local detail = Mapper.detail(html, identity.stable_id) + if detail then cb(require("book.store").rememberDetail(detail)); return end + cb(nil, err or _("响应无效")) + end) +end + +---@param self TaduSource +---@param identity BookIdentity +---@param cb fun(toc: BookChapter[]|nil, err: string|nil) +local function fetchTocAsync(self, identity, cb) + return Client.chaptersAsync(identity.stable_id, function(html, err) + if not html then cb(nil, err); return end + local toc = Mapper.chapters(html) + 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 and cached[1].toc_version == Mapper.TOC_VERSION then + return SourceBase.defer(cb, cached) + end + end + return fetchTocAsync(self, identity, cb) +end + +Source.refreshTocAsync = fetchTocAsync + +---@return ChapterFetchContent +local function fetcher(interactive) + return function(identity, chapter, done) + local part = chapter.source_idx or tostring(chapter.idx) + return Client.contentAsync(identity.stable_id, part, function(html, err) + if html then + done({ title = chapter.title, html = html }) + return + end + done(nil, err) + end, chapter.uid, interactive) + 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(), + interval_seconds = FETCH_INTERVAL, + }, cb) +end + +function Source:cacheAllChaptersAsync(identity, on_progress, cb, range) + local Chapter = require("source.chapter") + return Chapter.cacheAllAsync(self, identity, fetcher(), on_progress, cb, FETCH_INTERVAL, range) +end + +function Source:bookReviewsAsync(identity, cb) + return Client.reviewsAsync(identity.stable_id, function(items, err, pages) + if not items then cb(nil, err); return end + cb({ items = items, pages = pages }) + end) +end + +return Tadu diff --git a/tests/tadu/browse_spec.lua b/tests/tadu/browse_spec.lua new file mode 100644 index 0000000..9d31947 --- /dev/null +++ b/tests/tadu/browse_spec.lua @@ -0,0 +1,84 @@ +--[[-- +塔读官网分类、分页、坏响应与取消。 + +@module tests.moonsource_tadu.browse_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local Mapper = require("moonsource_tadu.mapper") +local root = "98-a-0-15-a-20-p-1-909" +local category = "99-a-0-15-a-20-p-1-909" +local filters = [[ +
频道 +男频文创 +女频 + +
+
分类
+ +
+
默认排序
+周人气 +
+]] +Assert.is_true(Mapper.storeNode(root)) +Assert.is_true(not Mapper.storeNode("../../user/info")) +Assert.eq(Mapper.storePage(root, 2), "98-a-0-15-a-20-p-2-909") +local groups = Mapper.storeGroups(filters) +Assert.len(groups, 3) +Assert.len(groups[1].chips, 2, "注释里的出版不应展示") +Assert.eq(groups[2].title, "分类") +Assert.eq(groups[2].chips[2].id, category) +Assert.eq(groups[3].title, "排序") +Assert.eq(groups[3].active, root) +Assert.is_true(not Mapper.shelfHasNext('', 1)) +Assert.is_nil(Mapper.listPage("服务器维护")) +Assert.len(Mapper.listPage('
    '), 0) + +local requests, delayed, failed = {}, false, false +package.loaded["http.request"] = { + get = function(url, options, cb) + local request = { url = url, options = options, cb = cb } + requests[#requests + 1] = request + local handle = { cancel = function() request.cancelled = true end } + local page = tonumber(url:match("%-p%-(%d+)%-")) or 1 + if delayed and page == 2 then return handle end + if failed and page == 2 then cb(nil, "network down"); return handle end + local cards = {} + for index = 1, 20 do + local id = (page - 1) * 20 + index + cards[#cards + 1] = '
    ' + .. '书' .. id .. '' + .. '简介作者' + end + cb(filters .. table.concat(cards) .. (page < 3 and '下一页' or "")) + return handle + end, +} +local source = require("moonsource_tadu.source").new() +local result, reason +source:browseAsync({ limit = 60 }, function(value, err) result, reason = value, err end) +Assert.is_nil(reason) +Assert.len(result.data, 60) +Assert.eq(result.data[21].stable_id, "21") +Assert.eq(result.data[1].authors, "作者", "官网作者是 a,不是 div") +Assert.eq(result.data[1].cover, "https://img.test/1.jpg") +Assert.is_nil(requests[1].options.headers.Cookie) +Assert.matches(requests[3].url, "%-p%-3%-") + +failed = true +source:browseAsync({}, function(value, err) result, reason = value, err end) +Assert.is_nil(result) +Assert.eq(reason, "network down", "后续页失败不能当第一页成功") +failed, delayed = false, true +local calls = 0 +local handle = source:browseAsync({}, function() calls = calls + 1 end) +handle:cancel() +Assert.is_true(requests[#requests].cancelled) +requests[#requests].cb(filters) +Assert.eq(calls, 0) diff --git a/tests/tadu/client_spec.lua b/tests/tadu/client_spec.lua new file mode 100644 index 0000000..52bd01d --- /dev/null +++ b/tests/tadu/client_spec.lua @@ -0,0 +1,214 @@ +--[[-- +塔读:微信扫码、书架页、搜索卡片、目录序号、正文去广告。 + +@module tests.moonsource_tadu.client_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +package.preload["json"] = function() return require("support.json_stub") end + +local Assert = require("support.assert") +local Json = require("support.json_stub") +local Mapper = require("moonsource_tadu.mapper") + +Assert.eq(Mapper.qrUuid(''), "abc123") +Assert.eq(Mapper.qrText("abc123"), "https://open.weixin.qq.com/connect/confirm?uuid=abc123") +Assert.eq((Mapper.wxStatus('{"wx_errcode":408}')), "wait") +local kind, wx_code, errcode = Mapper.wxStatus('{"wx_errcode":405,"wx_code":"wx1"}') +Assert.eq(kind, "ok") +Assert.eq(wx_code, "wx1") +Assert.eq(errcode, 405) +Assert.eq((Mapper.wxStatus("window.wx_errcode=403;window.wx_code='';")), "fail") +Assert.eq((Mapper.wxStatus("window.wx_errcode=402;")), "expired") +Assert.eq(Mapper.user({ data = { user = { nickname = "塔" } } }).name, "塔") +Assert.is_nil(Mapper.user({ data = {} })) + +local card = [[ + +三体宇宙 +星际 +
    刘慈欣
    +]] +local found = Mapper.books(card) +Assert.eq(#found, 1) +Assert.eq(found[1].stable_id, "988420") +Assert.eq(found[1].title, "三体宇宙") +Assert.eq(found[1].authors, "刘慈欣") +Assert.eq(found[1].intro, "星际") +Assert.eq(found[1].cover, "https://img/a.jpg") +Assert.eq(found[1].source_id, "ext.tadu") + +local home, home_err = Mapper.shelfPage("小说,小说网-塔读小说网|免费阅读最新热门小说") +Assert.is_nil(home) +Assert.eq(home_err, "未登录塔读") +local empty = Mapper.shelfPage("我的书架

    您还没有收藏

    ") +Assert.eq(#empty, 0) +local kong = Mapper.shelfPage('个人中心-塔读文学网
    ') +Assert.eq(#kong, 0) +local gone = Mapper.shelfPage("出错了-塔读文学网") +Assert.is_nil(gone) +local row = Mapper.shelf([[ + + +一书 +

    作者甲

    + +]]) +Assert.eq(#row, 1) +Assert.eq(row[1].stable_id, "9") +Assert.eq(row[1].title, "一书") +Assert.eq(row[1].authors, "作者甲") +local quoted = Mapper.shelf([[ + + +一书 +第1章 +

    作者甲

    + +]]) +Assert.eq(quoted[1].title, "一书") +Assert.eq(quoted[1].authors, "作者甲") +Assert.is_true(Mapper.shelfHasNext('', 1)) +Assert.is_true(Mapper.shelfHasNext('', 1)) +Assert.is_true(not Mapper.shelfHasNext('', 1)) + +local detail = Mapper.detail([[ + +系统劈腿,判给我半个系统 +小小怪 著 +

    曾经。

    +]], "1034377") +Assert.eq(detail.title, "系统劈腿,判给我半个系统") +Assert.eq(detail.authors, "小小怪") +Assert.eq(detail.intro, "曾经。") +Assert.eq(detail.cover, "https://img/cover_a.jpg") + +local toc = Mapper.chapters([[ +第1章 要留清白在人间 +第2章 系统脚踏两条船 +第1章 要留清白在人间 +]]) +Assert.eq(#toc, 2) +Assert.eq(toc[1].uid, "102154602") +Assert.eq(toc[1].source_idx, "1") +Assert.eq(toc[1].toc_version, Mapper.TOC_VERSION) +Assert.eq(toc[2].title, "第2章 系统脚踏两条船") + +local text = Mapper.content({ + status = 200, + data = { content = '

    正文中提及塔读

    隐藏

    下一段

    ' }, +}, "9") +Assert.eq(text, "

    正文中提及塔读

    下一段

    ") +local denied = select(2, Mapper.content({ status = 500, msg = "请登录" })) +Assert.eq(denied, "请登录") + +local settings = {} +local requests = {} +local deleted = false +local function reply(url, payload) + if url:find("long.open.weixin.qq.com", 1, true) then + return '{"wx_errcode":405,"wx_code":"wx1"}' + end + if url:find("open.weixin.qq.com/connect/qrconnect", 1, true) then + return '' + end + if url:find("/webchat/invoke/", 1, true) then return "ok", { "session=s1" } end + if url:find("/user/info", 1, true) then + return Json.encode({ data = { user = { nickname = "塔" } } }) + end + if url:find("pgNum=1", 1, true) then + if deleted then return '个人中心-塔读文学网
    ' end + return '个人中心-塔读文学网一书' + end + if url:find("pgNum=2", 1, true) then + return '个人中心-塔读文学网二书' + end + if url:find("/api/v1/favorite/", 1, true) then + return Json.encode({ status = 902, msg = "已收藏" }) + end + if url:find("/delFavorites", 1, true) then + deleted = true + return Json.encode({ status = 200 }) + end + if url:find("/search", 1, true) then return card end + if url:find("/book/1034377/9/", 1, true) then + return '' + end + if url:find("/getPartContentByCodeTable/", 1, true) then + return Json.encode({ status = 200, data = { content = '

    正文

    塔读APP

    ' } }) + 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(res) return res and res.cookies or {} end, + get = function(url, options, callback) + requests[#requests + 1] = { method = "GET", url = url, headers = options.headers } + local body, cookies = reply(url) + callback(body, nil, cookies and { cookies = cookies } or 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 body, cookies = reply(url, payload) + callback(body, nil, cookies and { cookies = cookies } or nil) + return { cancel = function() end } + end, + } +end + +local Client = require("moonsource_tadu.client") + +local uuid +Client.qrCreateAsync(function(value) uuid = value end) +Assert.eq(uuid, "abc123") + +local polled, code +Client.qrPollAsync("abc123", 408, function(value, wx) polled, code = value, wx end) +Assert.eq(polled, "ok") +Assert.eq(code, "wx1") +Assert.is_true(requests[#requests].url:find("last=408", 1, true) ~= nil) + +local user +Client.exchangeAsync("wx1", function(value) user = value end) +Assert.eq(user.name, "塔") +Assert.eq(settings.logged_in, true) +Assert.eq(settings.name, "塔") +Assert.is_true(settings.cookie:find("session=s1", 1, true) ~= nil) + +local shelf_html +Client.shelfAsync(function(html) shelf_html = html end) +local shelf = Mapper.shelf(shelf_html) +Assert.eq(#shelf, 2) +Assert.eq(shelf[1].stable_id, "9") +Assert.eq(shelf[2].stable_id, "8") + +local added +Client.addAsync("9", function(ok) added = ok end) +Assert.eq(added, true) + +local removed +Client.removeAsync("9", function(ok) removed = ok end) +Assert.eq(removed, true) +local removal +for _idx, request in ipairs(requests) do + if request.url:find("/delFavorites", 1, true) then removal = request end +end +Assert.eq(removal.body, "bookId=9") + +local books +Client.searchAsync("三体", function(html) books = Mapper.books(html) end) +Assert.eq(books[1].title, "三体宇宙") +Assert.is_true(requests[#requests].body:find("query=", 1, true) ~= nil) + +local chapter +Client.contentAsync("1034377", "1", function(html) chapter = html end, "9") +Assert.eq(chapter, "

    正文

    ") +Assert.is_true(requests[#requests].url:find("/getPartContentByCodeTable/1034377/1", 1, true) ~= nil) diff --git a/tests/tadu/font_spec.lua b/tests/tadu/font_spec.lua new file mode 100644 index 0000000..671373d --- /dev/null +++ b/tests/tadu/font_spec.lua @@ -0,0 +1,219 @@ +--[[-- +精确轮廓还原 Unicode;轮廓起点和次序不影响结果,属性不解码,失败不缓存。 + +@module tests.moonsource_tadu.font_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch, inject-field + +local Assert = require("support.assert") +local Config = require("support.config") +local SHA = require("ffi/sha2") +local ffi = require("ffi") +local original_loadlib = ffi.loadlib +local path = Config.dir() .. "/tadu-font-fixture.ttf" +local Paths = require("utils.paths") +local tmpname = Paths.tmpname +Paths.tmpname = function() return path end +local bytes = "\0\1\0\0fixture" +local original = '

    的&的原

    ' +local decoded = '

    甲&甲原

    ' +local shapes = { + { { 0, 0 }, { 20, 0 }, { 20, 20 }, { 0, 20 } }, + { { 30, 10 }, { 50, 10 }, { 50, 30 }, { 30, 30 } }, +} +local index = { + [SHA.sha256("64|1,0,0;1,20,0;1,20,20;1,0,20|1,30,10;1,50,10;1,50,30;1,30,30")] = 0x7532, + [string.rep("00", 32)] = 0x20000, + [string.rep("00", 31) .. "01"] = 0x4e59, + [string.rep("ff", 32)] = 0x10ffff, +} +local keys, records = {}, { "MTF1" } +for hash in pairs(index) do keys[#keys + 1] = hash end +table.sort(keys) +for _idx, hash in ipairs(keys) do + local cp = index[hash] + records[#records + 1] = hash:gsub("%x%x", function(hex) return string.char(tonumber(hex, 16)) end) + .. string.char(math.floor(cp / 65536), math.floor(cp / 256) % 256, cp % 256) +end +local raw_index = table.concat(records) +local open = io.open +io.open = function(name, mode) + if name:match("/moonsource_tadu/font_table%.bin$") then + Assert.eq(mode, "rb") + return { + read = function(_self, format) + Assert.eq(format, "*a") + return raw_index + end, + close = function() return true end, + } + end + return open(name, mode) +end +local sha256, forced_hash = SHA.sha256, nil +SHA.sha256 = function(shape) return forced_hash or sha256(shape) end +local rotated, unknown, invalid, load_failed, pending +local options, worker_result, closed, html, message, completed +local face = { glyph = { advance = { x = 64 * 64 } } } +ffi.loadlib = function(name, version) + Assert.eq(name, "freetype") + Assert.eq(version, "6") + return { FT_Load_Char = function(value, cp, flags) + Assert.eq(value, face) + Assert.eq(cp, 30340) + Assert.eq(flags, 10, "轮廓不能受像素 hinting 影响") + if load_failed then return 7 end + local outline = { n_contours = 2, n_points = 8, contours = {}, points = {}, tags = {} } + local at = 0 + for i = 1, 2 do + local polygon = shapes[rotated and 3 - i or i] + for j = 1, 4 do + local point = polygon[(j + (rotated and 1 or 0) - 1) % 4 + 1] + outline.points[at] = { x = point[1] * 64, y = point[2] * 64 } + outline.tags[at] = 1 + at = at + 1 + end + outline.contours[i - 1] = at - 1 + end + if unknown then outline.points[0].x = outline.points[0].x + 64 end + face.glyph.outline = outline + return 0 + end } +end +package.loaded["ffi/freetype"] = { + newFaceSize = function(font_path, size) + Assert.eq(font_path, path) + Assert.eq(size, 2048) + local file = assert(io.open(font_path, "rb")) + Assert.eq(file:read("*a"), bytes) + file:close() + if invalid then error("invalid font") end + return { + face = face, + hasGlyph = function(_self, cp) return cp == 30340 end, + done = function() closed = closed + 1 end, + } + end, +} +package.loaded["workers.job"] = { + run = function(worker, opts) + options = opts + local ok, result = pcall(worker) + worker_result = result + if not pending then + if ok then opts.on_done(result) else opts.on_failed(result) end + end + return { cancel = function() opts.on_cancelled() end } + end, +} +local Ext = require("utils.extension") +local hook_count = #Ext.list("reader.doc_settings") +local Font = require("moonsource_tadu.font") +Assert.eq(#Ext.list("reader.doc_settings"), hook_count, "解码不能强制更改阅读器字体设置") +local function run() + html, message, completed, closed = nil, nil, 0, 0 + local job = Font.restoreAsync(original, bytes, function(value, err) + html, message, completed = value, err, completed + 1 + end) + return job +end +local function cleaned() + Assert.is_nil(io.open(path, "rb"), "完成、失败或取消均不保留原字体") +end +run() +Assert.is_nil(message) +Assert.eq(html, decoded, "替换正文及实体,不替换标签属性") +Assert.eq(closed, 1) +Assert.eq(completed, 1) +Assert.eq(options.kind, "light") +cleaned() +rotated = true +run() +Assert.eq(html, decoded, "轮廓换起点、换次序仍是同一字形") +rotated = false +for _idx, hash in ipairs(keys) do + forced_hash = hash + run() + local ch = require("utils.text").utf8char(index[hash]) + Assert.eq(html, '

    ' .. ch .. '&' .. ch .. '原

    ', + "二分查找覆盖首尾、共享前缀及非 BMP 码点") + Assert.is_nil(message) + cleaned() +end +forced_hash = string.rep("00", 31) .. "02" +run() +Assert.is_nil(html, "必须匹配全部 32 字节,不能按指纹前缀猜字") +Assert.matches(message, "字体还原失败") +forced_hash = nil +local valid_index = raw_index +for _idx, malformed in ipairs({ "BAD1" .. raw_index:sub(5), raw_index:sub(1, -2) }) do + raw_index = malformed + run() + Assert.is_nil(html, "损坏索引不能产出正文") + Assert.matches(message, "invalid tadu font index") + cleaned() +end +raw_index = valid_index +unknown = true +run() +Assert.is_nil(html, "未知字形不能保存错码正文") +Assert.matches(message, "字体还原失败") +Assert.eq(closed, 1) +cleaned() +unknown, invalid = false, true +run() +Assert.is_nil(html) +Assert.matches(message, "invalid font") +cleaned() +invalid, load_failed = false, true +run() +Assert.is_nil(html) +Assert.matches(message, "glyph load failed") +cleaned() +load_failed = false +bytes = "CDN error" +run() +Assert.is_nil(html) +Assert.matches(message, "字体还原失败") +cleaned() +bytes = "\0\1\0\0fixture" +local index_open = io.open +io.open = function(name, mode) + if name == path and mode == "wb" then return nil, "permission denied" end + return index_open(name, mode) +end +run() +Assert.is_nil(html) +Assert.matches(message, "permission denied") +io.open = index_open +pending = true +run():cancel() +Assert.is_true(worker_result.html ~= nil) +Assert.eq(completed, 0, "取消不交付成功") +cleaned() +pending = false +ffi.loadlib = original_loadlib +Paths.tmpname = tmpname +io.open = open +SHA.sha256 = sha256 + +package.loaded["moonsource_tadu.client"] = { + contentAsync = function(_id, _part, cb) cb(decoded) end, +} +local Chapter = require("source.chapter") +local open_async = Chapter.openAsync +local document +Chapter.openAsync = function(_source, identity, _book, _opts, ops, cb) + ops.fetchContent(identity, { idx = 1, uid = "1", title = "章名" }, function(payload) + payload.book_title = identity.book.title + document = Chapter.render(payload) + cb("fixture.html") + end) +end +require("moonsource_tadu.source").new():openBookAsync({ + source_id = "ext.tadu", stable_id = "font-fixture", book = { title = "书名" }, +}, { chapter_idx = 1 }, function() end) +Chapter.openAsync = open_async +Assert.is_true(document:find(decoded, 1, true) ~= nil) +Assert.matches(document, "书名") +Assert.is_nil(document:match("@font%-face"), "缓存是普通 Unicode,不依赖嵌入字体") diff --git a/tests/tadu/login_spec.lua b/tests/tadu/login_spec.lua new file mode 100644 index 0000000..c1e82f9 --- /dev/null +++ b/tests/tadu/login_spec.lua @@ -0,0 +1,100 @@ +--[[-- +塔读登录隔离、回调域限制、同步回调取消及旧账号保护。 + +@module tests.moonsource_tadu.login_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local JSON = require("support.json_stub") +package.loaded["json"] = JSON +local cfg, requests, saved = {}, {}, 0 +local cleared = 0 +package.loaded["source.logout"] = { clear = function(_id, clear) + clear(); cleared = cleared + 1; return true +end } +package.loaded["utils.settings"] = { + getSource = function() return cfg end, + saveSource = function() saved = saved + 1 end, +} +local mode = "delayed" +local user = JSON.encode({ data = { user = { nickname = "测试用户" } } }) +package.loaded["http.request"] = { + headerAll = function(res) return res and res.cookies or {} end, + header = function(res) return res and res.location end, + get = function(url, options, cb) + local request = { url = url, options = options, cb = cb } + requests[#requests + 1] = request + local handle = { cancel = function() request.cancelled = true end } + if mode == "redirect" then cb(nil, "HTTP 302", { code = 302, location = "https://evil.test/" }) + else cb("ok", nil, { cookies = { "session=new; Path=/; HttpOnly; SameSite=Lax" } }) end + return handle + end, + post = function(url, body, options, cb) + local request = { url = url, options = options, body = body, cb = cb } + requests[#requests + 1] = request + if mode == "success" then cb(user) end + return { cancel = function() request.cancelled = true end } + end, +} +local Client = require("moonsource_tadu.client") +local calls = 0 +local result, reason +local handle = Client.exchangeAsync("test", function(value, err) calls, result, reason = calls + 1, value, err end) +Assert.eq(requests[1].options.headers.Cookie, "", "匿名兑换不能发送旧账号 Cookie") +Assert.eq(requests[2].options.headers.Cookie, "session=new", "Cookie 属性不是额外 Cookie") +handle:cancel() +Assert.is_true(requests[2].cancelled, "同步兑换回调后取消当前校验请求") +requests[2].cb(user) +Assert.eq(calls, 0) +Assert.eq(saved, 0) + +mode = "success" +Client.exchangeAsync("test", function(value) result = value end) +Assert.eq(result.name, "测试用户") +Assert.eq(cfg.cookie, "session=new") +Assert.eq(saved, 1) + +cfg.cookie = "session=old" +Client.exchangeAsync("test", function(value, err) result, reason = value, err end) +Assert.is_true(result ~= nil) +Assert.is_nil(reason) +Assert.eq(cfg.cookie, "session=new") +Assert.eq(cleared, 1) +Assert.eq(saved, 3) + +mode = "redirect" +Client.exchangeAsync("test", function(value, err) result, reason = value, err end) +Assert.is_nil(result) +Assert.eq(reason, "塔读登录回调无效") +Assert.eq(cfg.cookie, "session=new") + +mode = "delayed" +Client.loginCheckAsync("session=old", function(value, err) result, reason = value, err end) +requests[#requests].cb(nil, "network down") +Assert.eq(result, false) +Assert.eq(reason, "network down") +Assert.eq(cfg.cookie, "session=new") + +Client.loginCheckAsync("session=old", function(value, err) result, reason = value, err end) +cfg.cookie = "session=changed" +requests[#requests].cb(user) +Assert.eq(result, false) +Assert.eq(reason, "塔读登录已改变,请重试") + +local Mapper = require("moonsource_tadu.mapper") +local items, pages = Mapper.reviews([[ +

    作品评论区

    +

    甲

    标题

    评论一

    今天
    +

    乙

    评论二

    昨天
    +3 +]]) +Assert.len(items, 2) +Assert.eq(items[2].text, "评论二") +Assert.eq(pages, 3) +Assert.len(Mapper.reviews("

    作品评论区

    "), 0) +Assert.is_nil(Mapper.reviews("故障")) +local content, content_err, font = Mapper.content({ status = 200, data = { content = "

    编码正文

    ", url = "https://font.test/font.ttf" } }) +Assert.is_nil(content, "未解码字体不能写成成功缓存") +Assert.matches(content_err, "字体还原") +Assert.eq(font.html, "

    编码正文

    ") diff --git a/tests/tadu/operations_spec.lua b/tests/tadu/operations_spec.lua new file mode 100644 index 0000000..93962cd --- /dev/null +++ b/tests/tadu/operations_spec.lua @@ -0,0 +1,76 @@ +--[[-- +塔读书架回读确认、分页失效、取消与失效账号的退出入口。 + +@module tests.moonsource_tadu.operations_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local JSON = require("support.json_stub") +package.loaded["json"] = JSON +local cfg = { cookie = "session=old", logged_in = true } +package.loaded["utils.settings"] = { + getSource = function() return cfg end, saveSource = function() end, +} +local mode, requests, invalidated = "missing", {}, false +package.loaded["source.auth"] = { + expired = function() return invalidated end, + expire = function(_id, msg) invalidated = true; return msg end, +} +local row = '个人中心测试书' +package.loaded["http.request"] = { + get = function(url, options, cb) + local request = { url = url, options = options, cb = cb } + requests[#requests + 1] = request + local handle = { cancel = function() request.cancelled = true end } + if url:find("/favorite/", 1, true) then cb(JSON.encode({ status = 200 })); return handle end + if mode == "delayed" then return handle end + if mode == "expired" and url:find("pgNum=2", 1, true) then + cb("免费阅读最新热门小说") + elseif mode == "expired" then + cb(row .. '下一页') + elseif mode == "missing" then + cb('个人中心
    ') + else + cb(row) + end + return handle + end, + post = function(_url, _body, _options, cb) + cb(JSON.encode({ status = 200 })) + return { cancel = function() end } + end, +} +local Client = require("moonsource_tadu.client") +local result, reason +Client.addAsync("9", function(ok, err) result, reason = ok, err end) +Assert.is_nil(result, "200 但回读没有书不能清脏") +Assert.eq(reason, "塔读书架修改未确认,请稍后重试") +mode = "present" +Client.removeAsync("9", function(ok, err) result, reason = ok, err end) +Assert.is_nil(result, "删除200但仍在书架不能撕墓碑") +mode = "expired" +Client.shelfAsync(function(ok, err) result, reason = ok, err end) +Assert.is_nil(result, "第二页失效不能返回第一页当全量快照") +Assert.is_true(invalidated) +Assert.eq(cfg.cookie, "session=old") +Assert.is_true(not Client.loggedIn()) +Assert.eq(requests[#requests].options.cache_ttl, 0) + +mode = "delayed" +local calls = 0 +local handle = Client.addAsync("9", function() calls = calls + 1 end) +handle:cancel() +Assert.is_true(requests[#requests].cancelled) +requests[#requests].cb(row) +Assert.eq(calls, 0) + +package.loaded["ui.themes.widgets.row"] = { widget = function(spec) return spec end } +local Setting = require("moonsource_tadu.setting") +Assert.len(Setting.rows(), 4, "已失效账号仍必须能退出,否则无法导入新Cookie") +local cookie = require("source.cookie_login").fromPayload({ cookies = { + { domain = ".tadu.com", name = "parent", value = "a" }, + { domain = "www.tadu.com", name = "host", value = "b" }, + { domain = "evil.test", name = "evil", value = "c" }, +} }, "tadu.com") +Assert.eq(cookie, "host=b; parent=a") diff --git a/tests/tadu/qrlogin_spec.lua b/tests/tadu/qrlogin_spec.lua new file mode 100644 index 0000000..a89e1a4 --- /dev/null +++ b/tests/tadu/qrlogin_spec.lua @@ -0,0 +1,40 @@ +--[[-- +扫码同步回调不会覆盖在飞句柄,关闭后忽略迟到结果。 + +@module tests.moonsource_tadu.qrlogin_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local poll, exchange, stopped, signed_in +package.loaded["moonsource_tadu.client"] = { + qrCreateAsync = function(cb) + cb("uuid") + return { cancel = function() error("cancelled completed QR request") end } + end, + qrPollAsync = function(_uuid, _last, cb) + poll = cb + return { cancel = function() stopped = "poll" end } + end, + exchangeAsync = function(_code, cb) + exchange = cb + return { cancel = function() stopped = "exchange" end } + end, +} +package.loaded["ui.themes.widgets.qr"] = { + new = function(_class, spec) + return { show = function() end, close = function() spec.close_callback() end } + end, +} +local login = require("moonsource_tadu.qrlogin"):new(function() signed_in = true end) +login:start() +login:cancel() +Assert.eq(stopped, "poll") +poll("ok", "code", 405) +Assert.is_nil(exchange) +login:start() +poll("ok", "code", 405) +login:cancel() +Assert.eq(stopped, "exchange") +exchange({ name = "测试" }) +Assert.is_nil(signed_in) diff --git a/tests/tadu/reading_spec.lua b/tests/tadu/reading_spec.lua new file mode 100644 index 0000000..6d264aa --- /dev/null +++ b/tests/tadu/reading_spec.lua @@ -0,0 +1,229 @@ +--[[-- +扫码预览不缓存;官方授权重取正文、会话隔离、刷新和关闭取消。 + +@module tests.moonsource_tadu.reading_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch, inject-field + +local Assert = require("support.assert") +local JSON = require("support.json_stub") +local Themed = require("support.theme_stubs") +Themed.install() +package.loaded["json"] = JSON +local cfg, requests, timers = {}, {}, {} +local gated, delayed, malformed = true, false, false +---@type boolean|string +local font = false +local status, create_status = 0, 200 +local grant_clears = true +local font_wait, font_callback, font_cancelled +package.loaded["moonsource_tadu.font"] = { + restoreAsync = function(_html, bytes, cb) + Assert.eq(bytes, "font fixture") + if font_wait then font_callback = cb else cb("

    字体正文

    ") end + return { cancel = function() font_cancelled = true end } + end, +} +local calls, result, reason, saves, result_style = 0, nil, nil, 0, nil +package.loaded["utils.settings"] = { + getSource = function() return cfg end, + saveSource = function() saves = saves + 1 end, +} +package.loaded["ui/uimanager"] = { + scheduleIn = function(_self, _seconds, fn) timers[#timers + 1] = fn end, + unschedule = function(_self, fn) + for i = #timers, 1, -1 do if timers[i] == fn then table.remove(timers, i) end end + end, +} +local valid_image = true +package.loaded["ui/renderimage"] = { + renderImageData = function(_self, raw) + Assert.eq(raw, "png") + return valid_image and {} or nil + end, +} +local page = '' +local gate = '
    ' +package.loaded["http.request"] = { + headerAll = function(res) return res and res.cookies or {} end, + get = function(url, options, cb) + local request = { url = url, options = options, cb = cb } + requests[#requests + 1] = request + local handle = { cancel = function() request.cancelled = true end } + if url:find("/book/", 1, true) then + cb(malformed and "error" or page .. (gated and gate or "")) + elseif url:find("/getPartContentByCodeTable/", 1, true) then + cb(JSON.encode({ status = 200, data = { content = "

    完整正文

    ", + url = type(font) == "string" and font or font and "font.woff" or nil } })) + elseif url:find("/font/chapter.ttf", 1, true) then + cb("font fixture") + elseif url:find("/qrcode/invoke", 1, true) then + cb(JSON.encode({ status = create_status, data = { + qid = "test-id", token = "test-ticket", qrcode = "data:image/png;base64,cG5n", + } }), nil, { cookies = { "scan=pending; Path=/; HttpOnly" } }) + elseif not delayed then + if status == 200 and grant_clears then gated = false end + cb(JSON.encode({ status = status }), nil, status == 200 and { cookies = { "scan=approved; Path=/" } } or nil) + end + return handle + end, +} +local Mapper = require("moonsource_tadu.mapper") +local Client = require("moonsource_tadu.client") +Assert.is_true(Mapper.reading(page .. gate, "9").gated) +Assert.is_false(Mapper.reading(page .. "", "9").gated) +Assert.is_nil(Mapper.reading(page, "8")) +Assert.is_nil(Mapper.reading(page .. gate:gsub("/qrcode/invoke", "//evil.test"), "9")) + +local function callback(html, err, style) + calls, result, reason, result_style = calls + 1, html, err, style +end +local function open(interactive) + calls, result, reason, result_style = 0, nil, nil, nil + return Client.contentAsync("9", "105", callback, "1050", interactive) +end + +open(false) +Assert.is_nil(result) +Assert.eq(reason, "塔读此章节需要 App 扫码授权,请先打开章节扫码阅读") +Assert.len(requests, 1, "限制页不能下载或缓存预览") +Assert.len(Themed.all("qr"), 0, "后台缓存不能弹扫码窗口") +Assert.eq(saves, 0) + +local handle = open(true) +local dialog = Themed.last("qr") +Assert.eq(dialog.title, "塔读 App 扫码阅读") +Assert.is_true(dialog.image ~= nil) +Assert.is_nil(dialog.text, "官方二维码不能把图片地址当二维码内容") +Assert.eq(calls, 0) +Assert.len(timers, 1) +Assert.matches(requests[#requests].options.headers.Cookie, "scan=pending") +Assert.eq(requests[#requests].options.cache_ttl, 0) +handle.cancel() +Assert.is_true(dialog.closed) +Assert.len(timers, 0) +Assert.eq(calls, 0, "外部取消不重新调用开章回调") +Assert.is_nil(cfg.read_cookie, "未授权不保存候选Cookie") + +status = 1 +handle = open(true) +Assert.eq(calls, 0, "status=1仍等待,不能当确认成功") +Themed.last("qr").actions[1].callback() +Assert.eq(calls, 1) +Assert.eq(reason, "已取消") +Assert.len(timers, 0) + +delayed = true +handle = open(true) +local old = requests[#requests] +Themed.last("qr").actions[2].callback() +Assert.is_true(old.cancelled) +old.cb(JSON.encode({ status = 200 })) +Assert.eq(calls, 0, "刷新后旧票据不能授权下一轮") +local current = requests[#requests] +handle.cancel() +Assert.is_true(current.cancelled, "同步创建后的取消必须终止当前轮询") +current.cb(JSON.encode({ status = 200 })) +Assert.eq(calls, 0) + +delayed, status = false, 200 +cfg.cookie, cfg.logged_in = "account=old", true +open(true) +Assert.eq(result, "

    完整正文

    ") +Assert.eq(calls, 1, "同步全流程只交付一次") +Assert.eq(cfg.cookie, "account=old", "阅读授权不能覆盖书架登录") +Assert.matches(cfg.read_cookie, "scan=approved") +Assert.eq(cfg.read_cookie_for, "account=old") +Assert.matches(requests[#requests].url, "/9/96", "正文序号采用阅读页,而不是旧目录位置") +Assert.matches(requests[#requests].options.headers.Cookie, "scan=approved") +Assert.eq(saves, 1) +open(false) +Assert.eq(result, "

    完整正文

    ") +Assert.eq(saves, 1, "未变化的Cookie不重复落盘") +cfg.cookie = "account=new" +open(false) +Assert.is_true(not requests[#requests].options.headers.Cookie:find("scan=approved", 1, true), + "不同登录不能复用旧账号阅读授权") + +gated, delayed = true, true +handle = open(true) +local changed = requests[#requests] +cfg.cookie = "account=another" +changed.cb(JSON.encode({ status = 200 })) +Assert.eq(calls, 0) +Assert.eq(Themed.last("confirm").text, "塔读登录已改变,请重试") +Themed.last("confirm").cancel_callback() +Assert.eq(calls, 1) +Assert.eq(reason, "塔读登录已改变,请重试") + +delayed, status, grant_clears = false, 200, false +local saved_cookie = cfg.read_cookie +open(true) +Assert.is_nil(result, "轮询成功仍须回读权限,限制页不能缓存") +Assert.eq(reason, "塔读此章节需要 App 扫码授权,请先打开章节扫码阅读") +Assert.eq(cfg.read_cookie, saved_cookie) +grant_clears = true + +gated, delayed, font = false, false, true +open(false) +Assert.is_nil(result) +Assert.eq(reason, "塔读章节字体还原失败,请重试") +font = "https://www.tadu.com/font/chapter.ttf" +open(false) +Assert.eq(result, "

    字体正文

    ", "通过权限后必须下载字体并交付正文") +Assert.is_nil(result_style, "解码后的正文不能依赖字体样式") +Assert.matches(requests[#requests].url, "/font/chapter.ttf") +gated = true +open(true) +Assert.eq(result, "

    字体正文

    ", "扫码授权回读也必须还原正文") +Assert.is_nil(result_style) +font_wait = true +handle = open(true) +handle.cancel() +Assert.is_true(font_cancelled, "字体阶段取消必须调用 Job:cancel") +font_callback("

    迟到正文

    ") +Assert.eq(calls, 0) +open(false) +cfg.cookie = "account=changed-during-font" +font_callback("

    旧账号正文

    ") +Assert.eq(reason, "塔读登录已改变,请重试") +font_wait = false +malformed = true +open(false) +Assert.eq(reason, "塔读阅读页无法识别") +malformed, gated, font, status = false, true, false, 402 +open(true) +Assert.eq(Themed.last("confirm").text, "二维码已过期") +Assert.eq(calls, 0) +Themed.last("confirm").cancel_callback() +Assert.eq(calls, 1) +create_status = 500 +open(true) +Assert.eq(Themed.last("confirm").text, "获取二维码失败") +handle = open(true) +handle.cancel() +Assert.eq(calls, 0) + +create_status, valid_image = 200, false +open(true) +Assert.eq(Themed.last("confirm").text, "获取二维码失败") +Themed.last("confirm").cancel_callback() +Assert.eq(calls, 1) + +valid_image, delayed = true, true +handle = open(true) +requests[#requests].cb(nil, "network failure") +Assert.eq(Themed.last("confirm").text, "network failure", "网络失败不能冒充二维码过期") +Themed.last("confirm").cancel_callback() +Assert.eq(calls, 1) + +delayed, status = false, 0 +local time = os.time +open(true) +local waiting = table.remove(timers) +os.time = function() return time() + 301 end +waiting() +os.time = time +Assert.eq(Themed.last("confirm").text, "二维码已过期", "官网一直等待也必须有本地截止时间") +Themed.last("confirm").cancel_callback() +Assert.eq(calls, 1)