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

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

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

No files matched your search

+122
View File
@@ -0,0 +1,122 @@
--[[--
掌阅取消在途下一阶段、坏响应与旧会话认证状态隔离。
@module tests.moonsource_ireader.async_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 = { usr = "old", zysid = "old-session" }
package.loaded["utils.settings"] = { getSource = function() return cfg end }
local requests, mode = {}, "delayed"
package.loaded["http.request"] = {
get = function(url, opts, cb)
local request = { url = url, opts = opts, cb = cb }
requests[#requests + 1] = request
if url:find("/bookshelf/list", 1, true) and mode == "sync-shelf" then
cb(JSON.encode({ code = 0, body = { data = {}, current_version = 1 } }))
elseif url:find("page=1", 1, true) and mode == "sync-toc" then
cb(JSON.encode({ code = 0, body = { list = { { id = 1 } }, page = { totalPage = 2 } } }))
end
return { cancel = function() request.cancelled = true end }
end,
post = function(url, body, opts, cb)
local request = { url = url, body = body, opts = opts, cb = cb }
requests[#requests + 1] = request
return { cancel = function() request.cancelled = true end }
end,
}
local Client = require("moonsource_ireader.client")
local result, reason, calls = nil, nil, 0
local function done(value, err) result, reason, calls = value, err, calls + 1 end
Client.qrCreateAsync(done)
Assert.is_nil(requests[#requests].url:find("usr=old", 1, true))
Assert.eq(requests[#requests].opts.cache_ttl, 0)
Client.qrPollAsync("test-code", done)
Assert.is_nil(requests[#requests].url:find("old-session", 1, true))
Assert.eq(requests[#requests].opts.cache_ttl, 0)
mode = "sync-shelf"
local handle = Client.addAsync("42", "书", done)
local pending = requests[#requests]
local before = calls
handle:cancel()
Assert.is_true(pending.cancelled)
pending.cb(JSON.encode({ code = 0, body = true }))
Assert.eq(calls, before)
mode = "delayed"
Client.addAsync("42", "书", done)
pending = requests[#requests]
local count = #requests
cfg.usr, cfg.zysid = "new", "new-session"
pending.cb(JSON.encode({ code = 0, body = { data = {}, current_version = 1 } }))
Assert.eq(#requests, count, "会话变化不能用旧账号发加架请求")
Assert.is_nil(result)
Assert.eq(reason, "登录状态已变化,请重试")
local Auth = require("source.auth")
Auth.reset()
Client.get("/old-response", nil, done)
pending = requests[#requests]
cfg.zysid = "renewed"
pending.cb(JSON.encode({ code = 600001 }))
Assert.is_true(not Auth.expired("ext.ireader"))
Assert.is_nil(result)
Client.get("/expired", nil, done)
requests[#requests].cb(JSON.encode({ code = 600001 }))
Assert.is_true(Auth.expired("ext.ireader"))
Client.get("/stale-success", nil, done)
pending = requests[#requests]
cfg.zysid = "latest"
pending.cb(JSON.encode({ code = 0, body = {} }))
Assert.is_true(Auth.expired("ext.ireader"), "旧会话成功不能清新会话的失效标记")
mode = "sync-toc"
handle = Client.chaptersAsync("42", done)
pending = requests[#requests]
before = calls
handle:cancel()
Assert.is_true(pending.cancelled)
pending.cb(JSON.encode({ code = 0, body = { list = {}, page = { totalPage = 2 } } }))
Assert.eq(calls, before)
mode = "delayed"
Client.chaptersAsync("42", done)
requests[#requests].cb(JSON.encode({ code = 0, body = {} }))
Assert.is_nil(result)
Assert.eq(reason, "响应无效")
Client.chaptersAsync("42", done)
requests[#requests].cb(JSON.encode({ code = 0, body = { list = {}, page = { totalPage = 3 } } }))
Assert.is_nil(result)
Assert.eq(reason, "响应无效")
Client.contentAsync("42", "1", done)
requests[#requests].cb(JSON.encode({ code = 0, body = true }))
Assert.is_nil(result)
Assert.eq(reason, "响应无效")
Client.shelfAsync(done)
requests[#requests].cb(JSON.encode({ code = 0, body = {} }))
Assert.is_nil(result)
Assert.eq(reason, "响应无效")
Auth.expire("ext.ireader", "测试失效状态")
Client.checkSessionAsync({ usr = "candidate", zysid = "candidate-session" }, done)
Assert.is_true(requests[#requests].url:find("usr=candidate", 1, true) ~= nil)
requests[#requests].cb(JSON.encode({ code = 0, body = { data = {} } }))
Assert.is_true(result)
Assert.is_true(Auth.expired("ext.ireader"), "候选登录校验不改变现有账号的认证状态")
local catalog_opts = { parent = "10", category = "11", order = "score", status = "0" }
Client.catalogAsync(catalog_opts, 2, done)
Assert.is_true(requests[#requests].url:find("currentPage=2", 1, true) ~= nil)
requests[#requests].cb(JSON.encode({ code = 0, html = "", body = { current_page = 2, page_total = 2 } }))
Assert.len(result, 0)
Client.catalogAsync(catalog_opts, 2, done)
requests[#requests].cb(JSON.encode({ code = 0, html = "<html>captcha</html>", body = { current_page = 2, page_total = 3 } }))
Assert.is_nil(result)
Assert.eq(reason, "响应无效")
Client.catalogAsync(catalog_opts, 2, done)
requests[#requests].cb(nil, "network failed")
Assert.eq(reason, "network failed")
+101
View File
@@ -0,0 +1,101 @@
--[[--
掌阅真实分类结构、频道切换、分页去重和失败传播。
@module tests.moonsource_ireader.browse_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local Mapper = require("moonsource_ireader.mapper")
local html = [[
<script>var parentId = '10',categoryId = '11';</script>
<a href="https://m.zhangyue.com/category/10/10?currentPage=1">男频</a>
<a href="https://m.zhangyue.com/category/68/68?currentPage=1">女频</a>
<a href="https://m.zhangyue.com/category/92/92?currentPage=1">出版</a>
<a href="https://m.zhangyue.com/category/10/11?currentPage=1">玄幻</a>
<a href="https://m.zhangyue.com/category/10/27?currentPage=1">都市</a>
<span data-order="download">热门书籍</span><span data-order="score">评分最高</span>
<span data-status="0">全部</span><span data-status="3">完结</span>
]]
local page = Mapper.categories(html)
Assert.eq(page.parent, "10")
Assert.eq(page.category, "11")
Assert.len(page.channels, 3)
Assert.len(page.categories, 2)
Assert.eq(page.categories[2].id, "27")
Assert.eq(page.orders[2].id, "score")
Assert.is_nil(Mapper.categories("<html>captcha</html>"))
local card = [[
<li data-type="book" data-id="42"><a><img data-src="https://img/42?a=1&amp;b=2">
<dl><dt>书名</dt><dd class="author">作者</dd><dd class="content ellipsis2">简介</dd></dl></a></li>
]]
local books = Mapper.catalog(card .. card)
Assert.len(books, 1)
Assert.eq(books[1].title, "书名")
Assert.eq(books[1].authors, "作者")
Assert.eq(books[1].intro, "简介")
Assert.eq(books[1].cover, "https://img/42?a=1&b=2")
local requests, mode = {}, "ok"
package.loaded["moonsource_ireader.client"] = {
categoriesAsync = function(parent, category, cb)
requests[#requests + 1] = { parent = parent, category = category }
if mode == "invalid" then cb(nil, "bad catalog"); return end
local current = Mapper.categories(html)
if parent == "92" then
current.parent, current.category = "92", "93"
current.categories = { { id = "93", title = "小说" } }
current.statuses = { { id = "0", title = "全部" } }
elseif category == "27" then current.category = category end
cb(current)
return { cancel = function() end }
end,
catalogAsync = function(opts, index, cb)
local request = { opts = opts, page = index, cb = cb }
requests[#requests + 1] = request
if mode == "delayed" and index == 2 then
return { cancel = function() request.cancelled = true end }
end
if mode == "failed" and index == 2 then cb(nil, "network failed"); return end
cb({
{ source_id = "ext.ireader", stable_id = tostring(index), title = "书" },
{ source_id = "ext.ireader", stable_id = "duplicate", title = "重复" },
}, nil, index < 3)
return { cancel = function() request.cancelled = true end }
end,
}
local source = require("moonsource_ireader.source").new()
local result, reason, calls = nil, nil, 0
local function done(value, err) result, reason, calls = value, err, calls + 1 end
source:browseAsync({ node = "h5_ch_female", limit = 4 }, done)
Assert.eq(requests[1].parent, "68", "兼容旧频道节点")
Assert.len(result.data, 4)
Assert.is_nil(reason)
Assert.len(result.groups, 4)
Assert.eq(result.groups[2].title, "分类")
Assert.eq(result.groups[3].chips[2].id, "10:11:score:0")
source:browseAsync({ node = "10:27:score:3", limit = 2 }, done)
Assert.eq(requests[#requests].opts.category, "27")
Assert.eq(requests[#requests].opts.order, "score")
Assert.eq(requests[#requests].opts.status, "3")
Assert.eq(result.groups[1].chips[3].id, "92:92:score:0", "出版不保留不支持的完结筛选")
source:browseAsync({ node = "92:92:score:3", limit = 2 }, done)
Assert.eq(requests[#requests].opts.status, "0")
Assert.eq(requests[#requests].opts.category, "93")
mode = "failed"
source:browseAsync({ limit = 4 }, done)
Assert.is_nil(result)
Assert.eq(reason, "network failed", "中间页失败不能伪装完整列表")
mode = "invalid"
source:browseAsync({}, done)
Assert.eq(reason, "bad catalog")
mode = "delayed"
local handle = source:browseAsync({ limit = 4 }, done)
local pending = requests[#requests]
local before = calls
handle:cancel()
Assert.is_true(pending.cancelled, "同步首阶段后取消当前分页请求")
pending.cb({}, nil, false)
Assert.eq(calls, before)
+233
View File
@@ -0,0 +1,233 @@
--[[--
掌阅:网页封套、扫码、书架插入位置、目录分页、正文计费、进度章节号。
@module tests.moonsource_ireader.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_ireader.mapper")
Assert.eq(Mapper.qrCode('"abc"'), "abc", "扫码 body 是带引号的 JSON 字符串")
Assert.eq(Mapper.qrCode("abc"), "abc")
Assert.is_nil(Mapper.qrCode(""))
local waiting = select(2, Mapper.login({ code = 30059, msg = "随机码未授权" }))
Assert.eq(waiting, "wait")
local user = Mapper.login({
code = 0,
body = { name = "usr1", session_id = "sid1", nick = "读者", avatar = "http://a" },
})
Assert.eq(user.usr, "usr1")
Assert.eq(user.zysid, "sid1")
Assert.eq(user.name, "读者")
Assert.eq(select(2, Mapper.login({ code = 1, msg = "失败" })), "fail")
local shelf = Mapper.shelf({
data = {
{ book_id = 1, book_name = "在架", dtype = 0, is_local_book = false },
{ book_id = 2, book_name = "文件夹", dtype = 1 },
{ book_id = 3, book_name = "本地上传", dtype = 0, is_local_book = true },
},
})
Assert.eq(#shelf, 1)
Assert.eq(shelf[1].stable_id, "1")
Assert.eq(shelf[1].source_id, "ext.ireader")
local found = Mapper.search([[
<div data-id="42" data-src="https://img/a.jpg"><span class="name">三体</span>
<span class="author">刘慈欣</span><p class="brief">科幻</p></div>
<div data-id="42" data-src="https://img/dup.jpg"><span class="name">重复</span></div>
]])
Assert.eq(#found, 1)
Assert.eq(found[1].title, "三体")
Assert.eq(found[1].authors, "刘慈欣")
Assert.eq(found[1].cover, "https://img/a.jpg")
local channel = Mapper.channel([[
{"cli_res_id": 9, "cli_res_name": "好书"} <img src="https://img/c.jpg">
{"cli_res_id": 9, "cli_res_name": "好书"} <img src="https://img/c2.jpg">
]])
Assert.eq(#channel, 1)
Assert.eq(channel[1].stable_id, "9")
Assert.eq(channel[1].title, "好书")
Assert.eq(channel[1].cover, "https://img/c.jpg")
local toc = Mapper.chapters({
{ id = 1, name = "卷一", children = { { id = 2, name = "第一章" } } },
{ id = 3, name = "第二章" },
})
Assert.eq(#toc, 3)
Assert.eq(toc[1].uid, "1")
Assert.eq(toc[2].uid, "2")
Assert.eq(toc[2].depth, 2)
Assert.eq(toc[2].idx, 2)
Assert.eq(toc[1].toc_version, Mapper.TOC_VERSION)
Assert.eq(Mapper.progressUid(0), "1")
Assert.eq(Mapper.progressUid("4"), "5")
Assert.is_nil(Mapper.progressUid("nope"))
local settings = {}
local requests = {}
local function reply(url, payload)
if url:find("m.zhangyue.com/search", 1, true) then return "search-page" end
if url:find("/qrcode/get", 1, true) then
return Json.encode({ code = 0, body = '"abc"' })
end
if url:find("/qrcode/result", 1, true) then
return Json.encode({ code = 30059, msg = "随机码未授权" })
end
if url:find("/bookshelf/list", 1, true) then
return Json.encode({ code = 0, body = { data = { { order = 10, top = 0 }, { order = 3, top = 1 } }, current_version = 7 } })
end
if url:find("/bookshelf/upsert", 1, true) then
return Json.encode({ code = 100011, msg = "已在书架" })
end
if url:find("/book/detail", 1, true) then
if url:find("book_id=locked", 1, true) then
return Json.encode({ code = 100001, msg = "用户名不能为空" })
end
return Json.encode({ code = 0, body = { id = "9", name = "好书", fee_unit = 10, author = "作者" } })
end
if url:find("/chapter/web/list", 1, true) then
local page = url:match("page=(%d+)")
local row = page == "1" and { id = 1, name = "第一章" } or { id = 2, name = "第二章" }
return Json.encode({ code = 0, body = { list = { row }, page = { totalPage = 2 } } })
end
if url:find("/chapter-content", 1, true) then
if url:find("chapter_id=vip", 1, true) then
return Json.encode({ code = 0, body = { bookContent = "<p>锁</p>", charging_info = { price = 1, is_buy = false } } })
end
if url:find("chapter_id=owned", 1, true) then
return Json.encode({ code = 0, body = { bookContent = "<p>已购</p>", charging_info = { is_buy = true } } })
end
if url:find("chapter_id=free", 1, true) then
return Json.encode({ code = 0, body = { bookContent = "<p>免费</p>", charging_info = nil } })
end
return Json.encode({ code = 0, body = { bookContent = "<p>正文</p>" } })
end
if url:find("/getProgress", 1, true) then
return Json.encode({ code = 0, body = { ["9"] = { readProcess = { chapterId = 4, readPercent = 50 } } } })
end
if url:find("/book/progress", 1, true) then
return Json.encode({ code = 0, body = true })
end
if url:find("/expired", 1, true) then
return Json.encode({ code = 600001, msg = "登录已失效" })
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 {
get = function(url, _options, callback)
requests[#requests + 1] = { method = "GET", url = url }
callback(reply(url))
return { cancel = function() end }
end,
post = function(url, payload, _options, callback)
requests[#requests + 1] = { method = "POST", url = url, body = payload }
callback(reply(url, payload))
return { cancel = function() end }
end,
}
end
local Client = require("moonsource_ireader.client")
Assert.eq((Client.shelfCursor({ { order = 10, top = 0 }, { order = 3, top = 1 } }, 7)), 9)
Assert.eq(select(2, Client.shelfCursor({}, nil)), 0)
Assert.eq((Client.shelfCursor(nil, nil)), 999998)
local code, qerr = nil, "unset"
Client.qrCreateAsync(function(value, err) code, qerr = value, err end)
Assert.eq(code, "abc")
Assert.is_nil(qerr)
Assert.is_true(requests[1].url:find("p29=zye5b814", 1, true) ~= nil, "设备号 p29")
Assert.is_true(requests[1].url:find("p33=com.chaozh.iReaderFree", 1, true) ~= nil, "包名 p33")
Assert.is_true(requests[1].url:find("https://api-pc.zhangyue.com/bookstore/open/user/qrcode/get?", 1, true) == 1)
local polled
Client.qrPollAsync("abc", function(wire) polled = wire end)
Assert.eq(polled.code, 30059)
Assert.is_true(requests[#requests].url:find("code=abc", 1, true) ~= nil)
---@type table|string|nil
local anon_body = "x"
local anon_err
Client.detailAsync("locked", function(body, err) anon_body, anon_err = body, err end)
Assert.is_nil(anon_body)
Assert.eq(anon_err, "未登录掌阅")
settings.usr, settings.zysid = "usr1", "sid1"
local detail
Client.detailAsync("9", function(body) detail = body end)
Assert.eq(detail.name, "好书")
Assert.eq(Mapper.detail(detail, "9").title, "好书")
Assert.eq(Mapper.detail(detail, "9").stable_id, "9")
local html, herr, kind
Client.contentAsync("9", "1", function(body, err, content_kind) html, herr, kind = body, err, content_kind end)
Assert.eq(html, "<p>正文</p>")
Assert.is_nil(herr)
Assert.is_true(requests[#requests].url:find("https://pc.ireader.com/nsr/chapter-content?", 1, true) == 1)
Assert.is_true(requests[#requests].url:find("is_whole_book=true", 1, true) ~= nil, "按本计费整本标记")
Client.contentAsync("9", "vip", function(body, err, content_kind) html, herr, kind = body, err, content_kind end)
Assert.is_nil(html)
Assert.eq(herr, "本章未购买")
Assert.eq(kind, "unpaid")
Client.contentAsync("9", "free", function(body, err, content_kind) html, herr, kind = body, err, content_kind end)
Assert.eq(html, "<p>免费</p>")
Assert.is_nil(herr)
Client.contentAsync("9", "owned", function(body, err, content_kind) html, herr, kind = body, err, content_kind end)
Assert.eq(html, "<p>已购</p>")
Assert.is_nil(herr)
local rows
Client.chaptersAsync("9", function(list) rows = list end)
Assert.eq(#rows, 2)
Assert.eq(rows[2].name, "第二章")
local added, aerr
Client.addAsync("9", "好书", function(ok, err) added, aerr = ok, err end)
Assert.eq(added, true)
Assert.is_nil(aerr)
local upsert = requests[#requests]
Assert.eq(upsert.method, "POST")
Assert.is_true(upsert.body:find('name="type"', 1, true) ~= nil)
Assert.is_true(upsert.body:find("\r\n\r\n1\r\n", 1, true) ~= nil, "插入 type=1")
Assert.is_true(upsert.body:find('"order":9', 1, true) ~= nil)
Assert.is_true(upsert.body:find('"is_local_book":false', 1, true) ~= nil)
local progress
Client.progressAsync("9", function(item) progress = item end)
Assert.eq(progress.readProcess.chapterId, 4)
Assert.eq(Mapper.progressUid(progress.readProcess.chapterId), "5")
local posted
Client.putProgressAsync("9", "5", 20, function(ok) posted = ok end)
Assert.eq(posted, true)
Assert.is_true(requests[#requests].body:find('"chapterId":"4"', 1, true) ~= nil, "进度存的是列表 id 减一")
Assert.is_true(requests[#requests].body:find('"deviceName":"掌阅网页"', 1, true) ~= nil)
local expired
Client.get("/expired", nil, function(_body, err) expired = err end)
Assert.eq(expired, "掌阅登录已失效,请点「重新登录」,用掌阅 App 扫码。")
local search_html
Client.searchAsync("三体", function(raw) search_html = raw end)
Assert.eq(search_html, "search-page")
Assert.is_true(requests[#requests].url:find("https://m.zhangyue.com/search?", 1, true) == 1)
Assert.is_true(requests[#requests].url:find("keyWord=", 1, true) ~= nil)
+174
View File
@@ -0,0 +1,174 @@
--[[--
掌阅补充私用字码、正文插图、分阶段取消与旧章节离线升级。
@module tests.moonsource_ireader.content_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local Config = require("support.config")
local JSON = require("support.json_stub")
local Text = require("utils.text")
local Mapper = require("moonsource_ireader.mapper")
local Fs = require("utils.fs")
local encoded = {}
for cp = 0xF0000, 0xF0009 do encoded[#encoded + 1] = Text.utf8char(cp) end
for cp = 0xF0010, 0xF0019 do encoded[#encoded + 1] = Text.utf8char(cp) end
local attributes = ' id="keep" data-book="original"'
Assert.eq(Mapper.content("<p" .. attributes .. ">" .. table.concat(encoded) .. "</p>"),
"<p" .. attributes .. ">的一是了在有他我这们来去说就事你对也还但</p>")
Assert.eq(Mapper.content("<p>普通字、标点 &amp; 😀</p>"), "<p>普通字、标点 &amp; 😀</p>")
Assert.is_nil(Mapper.content("<p>" .. Text.utf8char(0xF001A) .. "</p>"), "新字码不能静默留下问号")
local requests, content_async, images_sync = {}, false, false
local wire, image_data, image_error
local png = "\137PNG\r\n\026\n" .. string.rep("x", 32)
local url = "https://bookbk.img.zhangyue01.com/fixture.png?v=one&amp;t=two"
local raw = '<html><body><p id="keep">人' .. Text.utf8char(0xF0009) .. Text.utf8char(0xF0004)
.. '阅读。</p><img src="' .. url .. '"/><img src="' .. url .. '"/></body></html>'
package.loaded["json"] = JSON
package.loaded["utils.settings"] = { getSource = function() return { usr = "test", zysid = "test" } end }
package.loaded["http.request"] = {
get = function(target, opts, cb)
local request = { url = target, opts = opts, cb = cb }
requests[#requests + 1] = request
if target:find("/nsr/chapter-content", 1, true) then
if not content_async then cb(JSON.encode(wire)) end
elseif images_sync then
cb(image_data, image_error)
end
return { cancel = function() request.cancelled = true end }
end,
}
local captured_ops, captured_reuse
local identity = { source_id = "ext.ireader", stable_id = "content-fixture" }
local chapter = { idx = 1, uid = "1", title = "正文" }
package.loaded["source.chapter"] = {
openAsync = function(_source, ref, _book, _opts, ops, cb)
captured_ops = ops
return ops.fetchContent(ref, chapter, cb)
end,
prefetchAsync = function(ref, _book, _toc, _from, _count, ops, cb)
captured_ops = ops
return ops.fetchContent(ref, chapter, cb)
end,
cacheAllAsync = function(_source, ref, fetch, _progress, cb, _interval, _range, cache_reuse)
captured_reuse = cache_reuse
return fetch(ref, chapter, cb)
end,
}
local source = require("moonsource_ireader.source").new()
local Client = require("moonsource_ireader.client")
local payload, reason, calls = nil, nil, 0
local function done(value, err) payload, reason, calls = value, err, calls + 1 end
local function reset()
requests, payload, reason, calls = {}, nil, nil, 0
content_async, images_sync = false, false
image_data, image_error = png, nil
wire = { code = 0, body = { bookContent = raw } }
end
local function open()
return source:openBookAsync(identity, { chapter_idx = 1 }, done)
end
reset()
open()
Assert.eq(#requests, 2, "正文同步返回后转入插图下载")
local image = requests[2]
Assert.eq(image.url, (url:gsub("&amp;", "&")))
Assert.eq(image.opts.headers.Referer, "https://pc.ireader.com/")
Assert.is_nil(image.opts.headers.Cookie)
Assert.is_nil(image.url:find("zysid=", 1, true))
Assert.is_nil(image.url:find("usr=", 1, true), "正文凭证不发送到图片 CDN")
Assert.eq(calls, 0, "图片完成前不交出成功正文")
image.cb(png)
Assert.eq(calls, 1)
Assert.is_nil(reason)
Assert.eq(payload.title, chapter.title)
Assert.is_true(payload.html:find("人们在阅读。", 1, true) ~= nil)
Assert.is_false(Text.hasRemoteImageSrc(payload.html))
Assert.eq(#requests, 2, "同一图片只下载一次")
local href = payload.html:match('src="([^"]+)"')
Assert.matches(href, "^images/[a-f0-9]+%.png$")
Assert.eq(Fs.read(require("utils.paths").bookWorkDir(identity.stable_id, "ext.ireader") .. "/" .. href), png)
reset()
local handle = open()
image = requests[2]
handle:cancel()
Assert.is_true(image.cancelled, "正文同步回调不能用旧请求覆盖图片取消句柄")
image.cb(png)
Assert.eq(calls, 0)
reset()
content_async = true
handle = open()
local initial = requests[1]
handle:cancel()
Assert.is_true(initial.cancelled)
initial.cb(JSON.encode(wire))
Assert.eq(#requests, 1, "取消后的正文回包不能再下载插图")
Assert.eq(calls, 0)
reset()
images_sync, image_data, image_error = true, nil, "network failed"
open()
Assert.is_nil(payload)
Assert.eq(reason, "network failed", "图片网络失败不能算全章缓存成功")
reset()
images_sync, image_data = true, "<html>not an image</html>"
open()
Assert.is_nil(payload)
Assert.eq(reason, "掌阅插图下载失败,请重试")
reset()
wire.body.bookContent = "<p>" .. Text.utf8char(0xF001A) .. "</p>"
Client.contentAsync("content-fixture", "1", done)
Assert.is_nil(payload)
Assert.eq(reason, "掌阅正文含未知字码,请更新插件后重试")
reset()
wire.body = { bookContent = raw, charging_info = { is_buy = false } }
source:prefetchChaptersAsync(identity, { chapter }, 0, 1, done)
Assert.is_nil(payload)
Assert.eq(reason, "本章未购买")
Assert.eq(#requests, 1, "未购正文不能开始下载资源")
reset()
wire.body.bookContent = '<p id="keep">' .. Text.utf8char(0xF0000) .. "正文。</p>"
open()
local cache_reuse = captured_ops.reuse
local old = '<html><head><title>书名</title></head><body><p id="keep">旧'
.. Text.utf8char(0xF0000) .. "正文。</p></body></html>"
local fixed = old:gsub(Text.utf8char(0xF0000), "的")
local path = Config.dir() .. "/ireader_content_fixture.html"
local function writeOld()
local file = assert(io.open(path, "wb")); assert(file:write(old)); assert(file:close())
end
writeOld()
Assert.is_true(cache_reuse(path))
Assert.eq(Fs.read(path), fixed, "不联网、不删目录、不改节点,原地修复旧缓存")
Assert.is_true(cache_reuse(path))
Assert.eq(Fs.read(path), fixed, "升级幂等")
Assert.is_nil(io.open(path .. ".part", "rb"))
writeOld()
local rename = os.rename
os.rename = function() return nil, "rename blocked" end
Assert.errors(function() cache_reuse(path) end, "rename blocked")
os.rename = rename
Assert.eq(Fs.read(path), old, "落盘失败保留旧正文")
Assert.is_nil(io.open(path .. ".part", "rb"))
source:prefetchChaptersAsync(identity, { chapter }, 0, 1, done)
Assert.is_true(captured_ops.reuse(path))
Assert.eq(Fs.read(path), fixed, "阅读预取也升级旧缓存")
writeOld()
source:cacheAllChaptersAsync(identity, nil, done)
Assert.is_true(captured_reuse(path))
Assert.eq(Fs.read(path), fixed, "全本缓存不能把旧字码当作已处理")
os.remove(path)
+88
View File
@@ -0,0 +1,88 @@
--[[--
掌阅章节进度、离线旧目录、写入失败与同步回调取消。
@module tests.moonsource_ireader.progress_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local requests, connected, read_async, toc_async = {}, false, false, false
package.loaded["ui/network/manager"] = { isConnected = function() return connected end }
local toc = { { uid = "1", title = "甲", toc_version = 0 }, { uid = "2", title = "乙" } }
package.loaded["source.toc"] = {
read = function() return toc end,
index = function(_sid, _bid, uid) return uid == "2" and 2 or nil end,
}
package.loaded["moonsource_ireader.client"] = {
session = function() return { usr = "test", zysid = "test" } end,
progressAsync = function(_id, cb)
if read_async then
local item = { cb = cb }
requests[#requests + 1] = item
return { cancel = function() item.cancelled = true end }
end
cb({ readProcess = { chapterId = "1", readPercent = "0.2" } })
return { cancel = function() end }
end,
putProgressAsync = function(_id, uid, total, cb)
local item = { uid = uid, total = total, cb = cb }
requests[#requests + 1] = item
return { cancel = function() item.cancelled = true end }
end,
}
local source = require("moonsource_ireader.source").new()
local result, reason, calls = nil, nil, 0
local function done(value, err) result, reason, calls = value, err, calls + 1 end
local identity = { source_id = "ext.ireader", stable_id = "test", chapter_idx = 2 }
source:loadTocAsync(identity, done)
require("support.stubs").flush()
Assert.eq(result, toc, "离线不强制刷新旧目录")
function source:loadTocAsync(_identity, cb)
if toc_async then
local item = { cb = cb }
requests[#requests + 1] = item
return { cancel = function() item.cancelled = true end }
end
cb(toc)
return { cancel = function() end }
end
source:getProgressAsync(identity, done)
Assert.eq(result.chapter_idx, 2)
Assert.eq(result.fraction, .5, "章式正文不使用只属于 TXT/PDF 的 readPercent")
local handle = source:putProgressAsync(identity, {}, done)
local pending = requests[#requests]
local before = calls
handle:cancel()
Assert.is_true(pending.cancelled)
pending.cb(true)
Assert.eq(calls, before)
source:putProgressAsync(identity, {}, done)
requests[#requests].cb(nil, "network failed")
Assert.is_nil(result)
Assert.eq(reason, "network failed")
Assert.eq(requests[#requests].uid, "2")
Assert.eq(requests[#requests].total, 2)
read_async = true
handle = source:getProgressAsync(identity, done)
pending = requests[#requests]
before = calls
handle:cancel()
Assert.is_true(pending.cancelled, "取消初始异步进度查询")
pending.cb({ readProcess = { chapterId = "1" } })
Assert.eq(calls, before)
read_async, toc_async = false, true
handle = source:getProgressAsync(identity, done)
pending = requests[#requests]
handle:cancel()
Assert.is_true(pending.cancelled, "同步进度查询后取消异步目录")
pending.cb(toc)
Assert.eq(calls, before)
handle = source:putProgressAsync(identity, {}, done)
pending = requests[#requests]
handle:cancel()
Assert.is_true(pending.cancelled, "取消上传前的异步目录")
pending.cb(toc)
Assert.eq(calls, before)
+86
View File
@@ -0,0 +1,86 @@
--[[--
掌阅扫码校验、刷新、失败、取消和同步回调的句柄所有权。
@module tests.moonsource_ireader.qrlogin_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local Themed = require("support.theme_stubs")
local Stubs = require("support.stubs")
Themed.install()
local connected, mode, requests, logged = true, "delayed", {}, 0
package.loaded["ui/network/manager"] = { isConnected = function() return connected end }
local function request(kind, cb)
local item = { kind = kind, cb = cb }
requests[#requests + 1] = item
if kind == "create" and mode == "sync" then cb("test-code") end
return { cancel = function() item.cancelled = true end }
end
package.loaded["moonsource_ireader.client"] = {
qrCreateAsync = function(cb) return request("create", cb) end,
qrPollAsync = function(_code, cb) return request("poll", cb) end,
checkSessionAsync = function(_user, cb) return request("check", cb) end,
}
local QR = require("moonsource_ireader.qrlogin")
local window = QR:new(function() logged = logged + 1 end)
local login = { code = 0, body = { name = "test-user", session_id = "test-session" } }
mode = "sync"
window:start()
local poll = requests[#requests]
Assert.eq(poll.kind, "poll")
window:cancel()
Assert.is_true(poll.cancelled)
poll.cb(login)
Assert.eq(logged, 0)
window:start()
requests[#requests].cb({ code = 30059 })
Stubs.flush()
Assert.eq(requests[#requests].kind, "poll")
requests[#requests].cb(login)
local checking = requests[#requests]
Assert.eq(checking.kind, "check")
Assert.eq(logged, 0, "校验成功前不保存新账号")
local dialog = Themed.last("qr")
checking.cb(true)
Assert.eq(logged, 1)
Assert.is_true(dialog.closed)
Assert.is_nil(Themed.last("toast"), "成功关闭二维码不能误报已取消")
window:start()
dialog = Themed.last("qr")
dialog.actions[1].callback()
Assert.is_true(dialog.closed)
local old_poll = poll
old_poll.cb(login)
Assert.eq(logged, 1)
requests[#requests].cb(nil, "network failed")
Assert.eq(Themed.last("confirm").text, "network failed")
window:start()
requests[#requests].cb(login)
checking = requests[#requests]
dialog = Themed.last("qr")
dialog:close()
Assert.is_true(checking.cancelled)
checking.cb(true)
Assert.eq(logged, 1)
window:start()
window.deadline = os.time() - 1
requests[#requests].cb({ code = 30059 })
Stubs.flush()
Assert.eq(Themed.last("confirm").text, "二维码已过期")
connected = false
local count = #requests
window:start()
Assert.eq(#requests, count)
Assert.eq(Themed.last("toast").text, "网络不可用,请先连接 Wi-Fi")
connected, mode = true, "delayed"
window:start()
local creating = requests[#requests]
window:cancel()
creating.cb("late-code")
Assert.is_nil(window.dialog)
Assert.eq(logged, 1)
+73
View File
@@ -0,0 +1,73 @@
--[[--
掌阅公开整书书评:只取首屏 HTML、异常与取消;不读取电脑账号。
@module tests.moonsource_ireader.reviews_spec
--]]
local Assert = require("support.assert")
local Mapper = require("moonsource_ireader.mapper")
local card = [[<li><div class="sns_user"><div class="info"><i class="vm">读者 &amp; 甲</i>
<div class="stars sns_stars"><span class="cur r8"></span></div></div></div>
<p class="con_dec">好书<br>值得&lt;b&gt;再读&lt;/b&gt;。</p>
<span class="sns_time">昨天</span></li>]]
local first = '<ul class="sns_commentlist" rel="" curpage="1" totalpage="13">' .. card .. '</ul>'
local parsed = Mapper.reviews("<nav><li>导航</li></nav>" .. first)
Assert.len(parsed.items, 1)
Assert.eq(parsed.items[1].author, "读者 & 甲")
Assert.eq(parsed.items[1].text, "好书\n值得 再读 。")
Assert.eq(parsed.items[1].time, "昨天")
Assert.eq(parsed.items[1].grade, 8)
Assert.len(Mapper.reviews('<ul class="sns_commentlist" curpage="1" totalpage="0"></ul>').items, 0)
Assert.is_nil(Mapper.reviews("<html>captcha</html>"))
Assert.len(Mapper.reviews('<ul class="sns_commentlist">' .. card .. '</ul>').items, 1,
"不依赖未使用的分页元数据")
Assert.is_nil(Mapper.reviews('<ul class="sns_commentlist"><li>坏卡片</li></ul>'))
Assert.is_nil(Mapper.reviews('<ul class="sns_commentlist">' .. card .. '<li>坏卡片</li></ul>'),
"不返回部分成功列表")
Assert.is_nil(Mapper.reviews('<ul class="sns_commentlist">bad response</ul>'))
local requests = {}
package.loaded["http.request"] = {
get = function(url, opts, cb)
local request = { url = url, opts = opts, cb = cb }
requests[#requests + 1] = request
return { cancel = function() request.cancelled = true end }
end,
}
local Client = require("moonsource_ireader.client")
Client.session = function() error("公开书评不能读取电脑账号") end
local source = require("moonsource_ireader.source").new()
---@type IReaderReviewPage|nil
local result
local reason, calls = nil, 0
local identity = { source_id = "ext.ireader", stable_id = "42" }
local function done(page, err) result, reason, calls = page, err, calls + 1 end
source:bookReviewsAsync(identity, done)
local request = requests[#requests]
Assert.eq(request.url, "https://m.zhangyue.com/comment/42")
Assert.eq(request.opts.accept, "text/html")
Assert.is_nil(request.opts.headers.Cookie)
Assert.is_true(request.opts.headers["User-Agent"]:find("Mobile", 1, true) ~= nil)
request.cb(first)
Assert.is_nil(reason)
Assert.eq(result.items[1].author, "读者 & 甲")
Assert.len(requests, 1, "官网还有后续页也只请求一次")
request.cb("<html>captcha</html>")
Assert.is_nil(result)
Assert.eq(reason, "响应无效")
request.cb(nil, "网络不可用,请先连接 Wi-Fi")
Assert.eq(reason, "网络不可用,请先连接 Wi-Fi")
request.cb(first, "网络失败")
Assert.is_nil(result)
Assert.eq(reason, "网络失败")
local handle = source:bookReviewsAsync(identity, done)
request = requests[#requests]
local before = calls
handle.cancel()
Assert.is_true(request.cancelled)
request.cb(first)
Assert.eq(calls, before)
for _idx, name in ipairs({ "paragraphHotspotsAsync", "chapterReviewHotspotsAsync" }) do
Assert.is_nil(source[name], "整书书评不伪装为章评或段评")
end
+96
View File
@@ -0,0 +1,96 @@
--[[--
掌阅同账号续期与换号保护;浏览器 / Cookie 从 `_zypps` 取 usr/zysid。
@module tests.moonsource_ireader.setting_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local beginLogin = require("source.auth").beginLogin
local Themed = require("support.theme_stubs")
Themed.install()
package.loaded["ui.themes.widgets.row"] = { widget = function(spec) return spec end }
local cfg, saved, reloaded, callback = { usr = "old", zysid = "original" }, 0, 0, nil
local cleared = 0
package.loaded["source.logout"] = { row = require("source.logout").row, clear = function(_id, clear)
clear(); cleared = cleared + 1; return true
end }
local checks = {}
package.loaded["utils.settings"] = {
getSource = function() return cfg end,
saveSource = function() saved = saved + 1 end,
}
package.loaded["source.registry"] = { reload = function() reloaded = reloaded + 1 end }
package.loaded["source.auth"] = {
beginLogin = beginLogin,
ok = function() end,
expired = function() return false end,
}
package.loaded["ui/network/manager"] = {
runWhenConnected = function(_network, cb) cb() end,
isConnected = function() return true end,
}
package.loaded["moonsource_ireader.qrlogin"] = {
new = function(_class, cb)
callback = cb
return { start = function() end }
end,
}
package.loaded["moonsource_ireader.client"] = {
session = function()
if cfg.usr and cfg.zysid then return { usr = cfg.usr, zysid = cfg.zysid } end
end,
checkSessionAsync = function(user, cb)
checks[#checks + 1] = user
cb(true)
return { cancel = function() end }
end,
}
package.loaded["moonsource_ireader.setting"] = nil
package.loaded["source.cookie_login"] = nil
local Setting = require("moonsource_ireader.setting")
Setting.open()
callback({ usr = "other", zysid = "candidate" })
Assert.eq(cfg.usr, "other")
Assert.eq(cfg.zysid, "candidate")
Assert.eq(cleared, 1)
Assert.is_nil(Themed.last("confirm"))
callback({ usr = "other", zysid = "renewed" })
Assert.eq(cfg.zysid, "renewed")
Assert.eq(saved, 3)
Assert.eq(reloaded, 2)
Assert.eq(cleared, 1, "同账号续期不清本地")
Assert.eq(Themed.last("toast").text, "登录成功")
Assert.is_true(type(Setting.browser) == "table")
Assert.eq(Setting.browser.domain, "pc.ireader.com")
Assert.is_true(type(Setting.browser.icon) == "string" and Setting.browser.icon:match("^https://"))
local user = Setting.userFromCookie("_zypps=usr%3Dold%26zysid%3Dfromcookie%26name%3D%E6%B5%8B")
Assert.eq(user.usr, "old")
Assert.eq(user.zysid, "fromcookie")
cfg = { usr = "old", zysid = "original" }
saved, reloaded = 0, 0
local rows = Setting.rows()
Assert.eq(rows[2](400).title, "浏览器登录")
Assert.eq(rows[3](400).title, "粘贴 Cookie")
rows[3](400).callback()
local input = Themed.last("input")
Assert.eq(input.title, "掌阅登录 Cookie")
input.callback("Cookie: _zypps=usr%3Dold%26zysid%3Dpasted%26name%3Dx")
Assert.eq(checks[1].usr, "old")
Assert.eq(checks[1].zysid, "pasted")
Assert.eq(cfg.zysid, "pasted")
Assert.eq(saved, 1)
cfg = {}
Setting.browser.apply({ cookies = {
{ domain = ".zhangyue.com", name = "_zypps", value = "usr=new&zysid=browser" },
{ domain = "evil.com", name = "_zypps", value = "usr=x&zysid=y" },
} }, function(ok) Assert.is_true(ok) end)
Assert.eq(cfg.usr, "new")
Assert.eq(cfg.zysid, "browser")