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

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

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

No files matched your search

+84
View File
@@ -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 = [[
<div class="lkLine"><span>频道</span>
<a href="/store/98-a-0-15-a-20-p-1-909" class="current">男频文创</a>
<a href="/store/122-a-0-15-a-20-p-1-122">女频</a>
<!--<a href="/store/79-a-0-15-a-20-p-1-79">出版</a>-->
</div>
<div class="lkLine"><span>分类</span><div>
<a href="/store/98-a-0-15-a-20-p-1-909" class="current">全部</a>
<a href="/store/99-a-0-15-a-20-p-1-909">东方玄幻</a>
</div></div>
<div class="lkLine" hidden=""><span>属性</span>
<a href="/store/98-a-0-15-a-20-p-1-909">全部</a></div>
<div class="tabList">
<div class="tab current"><span onclick="window.location.href='/store/98-a-0-15-a-20-p-1-909'">默认排序</span></div>
<a href="/store/98-a-0-12-a-20-p-1-909" class="tab">周人气</a>
<div class="rtIcon"></div></div>
]]
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('<a href="?pgNum=20">', 1))
Assert.is_nil(Mapper.listPage("<title>服务器维护</title>"))
Assert.len(Mapper.listPage('<ul class="bookList"></ul>'), 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] = '<a href="/book/' .. id .. '/" class="bookImg"><img data-src="https://img.test/' .. id .. '.jpg"></a>'
.. '<a href="/book/' .. id .. '/" class="bookNm">书' .. id .. '</a>'
.. '<a class="bookIntro">简介</a><a class="authorNm"><i></i>作者</a>'
end
cb(filters .. table.concat(cards) .. (page < 3 and '<a href="/store/' .. Mapper.storePage(root, page + 1) .. '">下一页</a>' 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)
+214
View File
@@ -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('<img src="/connect/qrcode/abc123">'), "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 = [[
<a href="/book/988420/" class="bookImg"><img data-src="https://img/a.jpg" /></a>
<a href="/book/988420/" class="bookNm"><span class="orange">三体</span>宇宙</a>
<a href="/book/988420/" class="bookIntro">星际</a>
<div class="authorNm"><i></i>刘慈欣</div>
]]
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("<title>小说,小说网-塔读小说网|免费阅读最新热门小说</title>")
Assert.is_nil(home)
Assert.eq(home_err, "未登录塔读")
local empty = Mapper.shelfPage("<title>我的书架</title><p>您还没有收藏</p>")
Assert.eq(#empty, 0)
local kong = Mapper.shelfPage('<title>个人中心-塔读文学网</title><div class="bookrack_table_kong"></div>')
Assert.eq(#kong, 0)
local gone = Mapper.shelfPage("<title>出错了-塔读文学网</title>")
Assert.is_nil(gone)
local row = Mapper.shelf([[
<tr class="td_con">
<td class="checkbox"><a class="check_btn" data-bookid="9"></a></td>
<td class="entry"><a class="linkBlock" href="/book/9/">一书</a></td>
<td class="table_author"><p>作者甲</p></td>
</tr>
]])
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([[
<tr class="td_con">
<td class="checkbox"><a data-bookid='9' class="check_btn"></a></td>
<td class="entry"><a href="/book/9/" class="linkBlock">一书</a></td>
<td class="new_chapter"><a href="/book/9/1/" class="linkBlock">第1章</a></td>
<td class="table_author"><p>作者甲</p></td>
</tr>
]])
Assert.eq(quoted[1].title, "一书")
Assert.eq(quoted[1].authors, "作者甲")
Assert.is_true(Mapper.shelfHasNext('<a href="/tadu/space/reader?pgNum=2">', 1))
Assert.is_true(Mapper.shelfHasNext('<a href="/tadu/space/my-bookshelf/2">', 1))
Assert.is_true(not Mapper.shelfHasNext('<a href="/tadu/space/reader?pgNum=1">', 1))
local detail = Mapper.detail([[
<a class="bookImg"><img data-src="https://img/cover_a.jpg" /></a>
<a class="bkNm" data-name="系统劈腿,判给我半个系统">系统劈腿,判给我半个系统</a>
<span class="author">小小怪 著</span>
<p class="intro">曾经。</p>
]], "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([[
<a href="/book/1034377/102154602/">第1章 要留清白在人间</a>
<a href="/book/1034377/102154603/">第2章 系统脚踏两条船</a>
<a href="/book/1034377/102154602/">第1章 要留清白在人间</a>
]])
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 = '<p>正文中提及塔读</p><p data-limit="OQ==">隐藏</p><p>下一段</p>' },
}, "9")
Assert.eq(text, "<p>正文中提及塔读</p><p>下一段</p>")
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 '<img src="/connect/qrcode/abc123">'
end
if url:find("/webchat/invoke/", 1, true) then return "<html>ok</html>", { "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 '<title>个人中心-塔读文学网</title><div class="bookrack_table_kong"></div>' end
return '<title>个人中心-塔读文学网</title><a class="check_btn" data-bookid="9"></a><a class="linkBlock" href="/book/9/">一书</a><a href="/tadu/space/reader?pgNum=2">'
end
if url:find("pgNum=2", 1, true) then
return '<title>个人中心-塔读文学网</title><a class="check_btn" data-bookid="8"></a><a class="linkBlock" href="/book/8/">二书</a>'
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 '<input id="bookPartResourceUrl" value="/getPartContentByCodeTable/1034377/1">'
end
if url:find("/getPartContentByCodeTable/", 1, true) then
return Json.encode({ status = 200, data = { content = '<p>正文</p><p data-limit="OQ==">塔读APP</p>' } })
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, "<p>正文</p>")
Assert.is_true(requests[#requests].url:find("/getPartContentByCodeTable/1034377/1", 1, true) ~= nil)
+219
View File
@@ -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 = '<p title="的">的&amp;&#x7684;<b>原</b></p>'
local decoded = '<p title="的">甲&amp;甲<b>原</b></p>'
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, '<p title="的">' .. ch .. '&amp;' .. ch .. '<b>原</b></p>',
"二分查找覆盖首尾、共享前缀及非 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 = "<html>CDN error</html>"
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, "<title>书名</title>")
Assert.is_nil(document:match("@font%-face"), "缓存是普通 Unicode,不依赖嵌入字体")
+100
View File
@@ -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([[
<h1>作品评论区</h1>
<div class="commentIntro"><h4>甲</h4><h5>标题</h5><p>评论一</p><span class="time">今天</span></div>
<div class="commentIntro"><h4>乙</h4><h5></h5><p>评论二</p><span class="time">昨天</span></div>
<a href="/v4/book/comment/9/1/3">3</a>
]])
Assert.len(items, 2)
Assert.eq(items[2].text, "评论二")
Assert.eq(pages, 3)
Assert.len(Mapper.reviews("<h1>作品评论区</h1>"), 0)
Assert.is_nil(Mapper.reviews("<title>故障</title>"))
local content, content_err, font = Mapper.content({ status = 200, data = { content = "<p>编码正文</p>", url = "https://font.test/font.ttf" } })
Assert.is_nil(content, "未解码字体不能写成成功缓存")
Assert.matches(content_err, "字体还原")
Assert.eq(font.html, "<p>编码正文</p>")
+76
View File
@@ -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 = '<title>个人中心</title><a data-bookid="9"></a><a class="linkBlock">测试书</a>'
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("<title>免费阅读最新热门小说</title>")
elseif mode == "expired" then
cb(row .. '<a href="?pgNum=2">下一页</a>')
elseif mode == "missing" then
cb('<title>个人中心</title><div class="bookrack_table_kong"></div>')
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")
+40
View File
@@ -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)
+229
View File
@@ -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("<p>字体正文</p>") 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 = '<input id="bookPartResourceUrl" value="/getPartContentByCodeTable/9/96">'
local gate = '<div class="appQrCode" data-url="/qrcode/invoke" data-status="/qrcode/check">'
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 "<html>error</html>" or page .. (gated and gate or ""))
elseif url:find("/getPartContentByCodeTable/", 1, true) then
cb(JSON.encode({ status = 200, data = { content = "<p>完整正文</p>",
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 .. "<!--" .. gate .. "-->", "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, "<p>完整正文</p>")
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, "<p>完整正文</p>")
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, "<p>字体正文</p>", "通过权限后必须下载字体并交付正文")
Assert.is_nil(result_style, "解码后的正文不能依赖字体样式")
Assert.matches(requests[#requests].url, "/font/chapter.ttf")
gated = true
open(true)
Assert.eq(result, "<p>字体正文</p>", "扫码授权回读也必须还原正文")
Assert.is_nil(result_style)
font_wait = true
handle = open(true)
handle.cancel()
Assert.is_true(font_cancelled, "字体阶段取消必须调用 Job:cancel")
font_callback("<p>迟到正文</p>")
Assert.eq(calls, 0)
open(false)
cfg.cookie = "account=changed-during-font"
font_callback("<p>旧账号正文</p>")
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)