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

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

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

No files matched your search

+86
View File
@@ -0,0 +1,86 @@
--[[--
书旗官网书库:动态筛选、分页、旧节点迁移和取消。
@module tests.moonsource_shuqi.browse_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local Mapper = require("moonsource_shuqi.mapper")
local category = "fc=7&st=0&sz=0&tm=0&wd=10"
local filters = [[
<div class="selectview page-width">
<div class="selectarea clear"><h6>作品类型:</h6>
<script>console.log("<a href='/bad'>")</script><ul>
<li class="active"><a href="/store?&amp;sz=0">全部</a></li>
<li class=""><a href="/store?&amp;sz=2">女频</a></li></ul></div>
<div class="selectarea clear filter-container"><h6>作品分类:</h6>
<div class="active default-item"><a href="/store?sz=0&amp;fc=0&amp;wd=10&amp;tm=0&amp;st=0&amp;">不限</a></div><ul>
<li class=""><a href="/store?sz=0&amp;fc=7&amp;wd=10&amp;tm=0&amp;st=0&amp;">都市</a></li>
</ul></div></div><div class="store-content">
]]
local function pageHtml(page, next_page)
local cards = {}
for index = 1, 24 do
local id = (page - 1) * 24 + index
cards[#cards + 1] = '<li><a href="/book/' .. id .. '.html"><img src="//img.test/cover.jpg"><h3>书' .. id
.. '</h3></a><p class="store-tag clear"><a href="/author/name">作者:作者 </a></p>'
.. '<a><p class="store-des">简介&amp;摘要</p></a></li>'
end
return filters .. '<ul class="store-ul clear">' .. table.concat(cards) .. '</ul>'
.. (next_page and '<a href="/store?page=' .. (page + 1) .. '">下一页</a>' or "")
end
local books, groups, more = Mapper.store(pageHtml(1, true))
Assert.len(books, 24)
Assert.eq(books[1].authors, "作者")
Assert.eq(books[1].intro, "简介&摘要")
Assert.eq(books[1].cover, "https://img.test/cover.jpg")
Assert.len(groups, 2)
Assert.eq(groups[1].active, "sz=0")
Assert.eq(groups[2].chips[2].id, category)
Assert.eq(groups[2].active, "fc=0&st=0&sz=0&tm=0&wd=10")
Assert.is_true(more)
Assert.is_nil(Mapper.store("<title>维护</title>"))
Assert.len(Mapper.store(filters .. '<ul class="store-ul"></ul>'), 0)
Assert.is_nil(Mapper.storeNode("sz=0&cookie=secret"))
Assert.is_nil(Mapper.storeNode("sz=0&sz=2"))
Assert.is_nil(Mapper.storeNode("../../myself"))
Assert.eq(Mapper.storeNode("sz=0&fc=34%2C102"), "fc=34%2C102&sz=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("page=(%d+)"))
if delayed and page == 2 then return handle end
if failed and page == 2 then cb(nil, "network down"); return handle end
cb(pageHtml(page, page < 3))
return handle
end,
}
local source = require("moonsource_shuqi.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.is_nil(requests[1].options.headers.Cookie)
Assert.matches(requests[3].url, "page=3$")
requests = {}
source:browseAsync({ node = "都市", limit = 20 }, function(value) result = value end)
Assert.matches(requests[2].url, "fc=7")
Assert.len(result.data, 20)
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(pageHtml(2, true))
Assert.eq(calls, 0)
+241
View File
@@ -0,0 +1,241 @@
--[[--
书旗:搜索签名、正文解密、目录地址、验证码登录和书架同步体。
@module tests.moonsource_shuqi.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_shuqi.mapper")
Assert.eq(Mapper.searchSign("1793900599"), "2988ab30d4114f664a6792c7962c3fdf")
Assert.eq(Mapper.contentSign({ bookId = "8016707", timestamp = "1", user_id = "8000000" }),
"bd9ab4f63403fd63fd3191ff23bc1731")
Assert.eq(Mapper.gatewaySign({ a = "1", b = "2" }, "eefc4798f28ea41622487ad80ef7e81c"),
"11c4ba6147c7d69ab433d71889f3d992")
Assert.eq(Mapper.gatewaySign({ a = "x y" }, "eefc4798f28ea41622487ad80ef7e81c"),
"687e16005410b369cf1f38c4459fbdc5")
Assert.eq(Mapper.javaEncode("x y"), "x+y")
local found = Mapper.searchBooks({
status = 1,
data = { { bid = 8062580, title = "三体", author = "刘慈欣", cover = "//img/a.jpg", desc = "科幻" } },
})
Assert.eq(#found, 1)
Assert.eq(found[1].stable_id, "8062580")
Assert.eq(found[1].title, "三体")
Assert.eq(found[1].authors, "刘慈欣")
Assert.eq(found[1].cover, "https://img/a.jpg")
Assert.eq(found[1].source_id, "ext.shuqi")
Assert.is_nil(Mapper.searchBooks({ status = -1, info = { message = "parameter is missing" } }))
local detail = Mapper.detail({
state = "200",
data = { bookId = 8016707, bookName = "不灭神王", authorName = "观棋", intro = "简介", imgUrl = "https://img/b.jpg" },
})
Assert.eq(detail.stable_id, "8016707")
Assert.eq(detail.title, "不灭神王")
Assert.eq(detail.authors, "观棋")
Assert.eq(detail.intro, "简介")
local described = Mapper.detail({
state = "200",
data = { bookId = 8007543, bookName = "三体", authorName = "刘慈欣", desc = "科幻", imgUrl = "https://img/c.jpg" },
})
Assert.eq(described.intro, "科幻")
local toc = Mapper.chapters({
state = 200,
data = {
freeContUrlPrefix = "https://free/",
chargeContUrlPrefix = "https://charge/",
chapterList = { {
volumeList = {
{ chapterId = 11, chapterName = "第一章", isFreeRead = true, contUrlSuffix = "?a=1", chapterOrdid = 1 },
{ chapterId = 12, chapterName = "第二章", isFreeRead = false, isBuy = false, contUrlSuffix = "?a=2" },
{ chapterId = 13, chapterName = "第三章", isFreeRead = false, isBuy = true, contUrlSuffix = "?a=3" },
},
} },
},
})
Assert.eq(#toc, 3)
Assert.eq(toc[1].uid, "11")
Assert.eq(toc[1].content_url, "https://free/?a=1")
Assert.eq(toc[1].toc_version, Mapper.TOC_VERSION)
Assert.eq(toc[1].vip, false)
Assert.eq(toc[2].vip, true)
Assert.is_nil(toc[2].content_url)
Assert.eq(toc[3].content_url, "https://charge/?a=3")
local text = Mapper.chapterText({
state = 200,
ChapterContent = "CTWlYm7aeXmxhVQzeeH8LaViChrfeBF6wBnhgD==",
})
Assert.eq(text, "第一段\n第二段")
Assert.eq(select(2, Mapper.chapterText({ state = 200 })), "正文为空")
local channels = Mapper.channels({
state = 200,
data = {
male = { groupList = { { showName = "都市" }, { showName = "玄幻" } } },
female = { groupList = { { showName = "现言" } } },
press = { groupList = {} },
cartoon = { groupList = { { showName = "漫画" } } },
},
})
Assert.eq(channels.male[1].id, "都市")
Assert.eq(#channels.female, 1)
Assert.eq(#channels.press, 0)
local session = Mapper.session({
status = 200,
data = { token = "tok", userInfo = { userid = 42, nickName = "旗" } },
})
Assert.eq(session.token, "tok")
Assert.eq(session.user_id, "42")
Assert.eq(session.name, "旗")
Assert.is_nil(Mapper.session({ status = 500, message = "no" }))
Assert.is_true(Mapper.sent({ status = 200 }))
Assert.is_true(not Mapper.sent({ status = 400, message = "bad" }))
local shelf = Mapper.shelf({ detail = { { bid = 9, title = "一书", author = "甲" } } })
local nested = Mapper.shelf({ status = 200, message = "成功", data = { detail = { { bid = 9, title = "一书", author = "甲" } } } })
Assert.eq(nested[1].stable_id, "9")
Assert.eq(nested[1].title, "一书")
Assert.eq(shelf[1].stable_id, "9")
Assert.is_nil(Mapper.shelf({ message = "fail" }))
local mark = Mapper.mark({ detail = { { bid = 9, chapterid = 11, cname = "第一章", percent = 0.25 } } }, "9")
Assert.eq(mark.chapter_id, "11")
Assert.eq(mark.title, "第一章")
Assert.eq(mark.fraction, 0.25)
Assert.is_nil(Mapper.mark({ detail = { { bid = 9, chapterid = 0, percent = 0.25 } } }, "9"))
Assert.eq(Mapper.mark({ detail = { { bid = 9, chapterid = 11, percent = 2500 } } }, "9").fraction, 0.25)
Assert.eq(Mapper.mark({ data = { detail = { { bid = 9, chapterid = 11, cname = "第一章", percent = 0.25 } } } }, "9").chapter_id, "11")
local cfg = {}
local requests = {}
local shelf_rows = { { bid = 9, title = "书架书", author = "丁", chapterid = 11, cname = "第一章", percent = 0.5 } }
package.preload["utils.settings"] = function()
return {
getSource = function() return cfg end,
saveSource = function() end,
get = function() return {} end,
}
end
package.preload["http.request"] = function()
return {
get = function(url, _options, callback)
requests[#requests + 1] = { method = "GET", url = url }
local body = "{}"
if url:find("do=is_search", 1, true) then
body = Json.encode({ status = 1, data = { { bid = 1, title = "三体", author = "刘慈欣" } } })
elseif url:find("is_caterank", 1, true) then
body = Json.encode({ status = 1, data = { { bid = 2, title = "都市书", author = "乙" } } })
elseif url:find("chapterlist", 1, true) then
body = Json.encode({ state = 200, data = { chapterList = {} } })
elseif url:find("https://free/", 1, true) then
body = Json.encode({ state = 200, ChapterContent = "CTWlYm7aeXmxhVQzeeH8LaViChrfeBF6wBnhgD==" })
end
callback(body, nil, nil)
return { cancel = function() end }
end,
post = function(url, payload, _options, callback)
requests[#requests + 1] = { method = "POST", url = url, body = payload }
local body = "{}"
if url:find("sendCode", 1, true) then
body = Json.encode({ status = 200 })
elseif url:find("vcode/login", 1, true) then
body = Json.encode({ status = 200, data = { token = "tok", userInfo = { userid = 7, nickName = "旗" } } })
elseif url:find("book/info", 1, true) then
body = Json.encode({ state = 200, data = { bookId = 3, bookName = "详情", authorName = "丙" } })
elseif url:find("sync/bookmarks", 1, true) then
if payload:find("action%22%3A1", 1, true) then
shelf_rows = { { bid = 9, title = "书架书", author = "丁", chapterid = 11, cname = "第一章", percent = 0.5 } }
elseif payload:find("action%22%3A3", 1, true) then
shelf_rows = {}
elseif payload:find("action%22%3A2", 1, true) then
shelf_rows = { { bid = 9, title = "书架书", chapterid = 11, percent = 0.5 } }
end
body = Json.encode({ detail = shelf_rows })
end
callback(body, nil, nil)
return { cancel = function() end }
end,
}
end
local Client = require("moonsource_shuqi.client")
local books
Client.searchAsync("三体", function(list) books = list end)
Assert.eq(books[1].title, "三体")
local search_url = requests[#requests].url
local timestamp = search_url:match("timestamp=(%d+)")
Assert.eq(search_url:match("sign=([0-9a-f]+)"), Mapper.searchSign(timestamp))
Assert.is_true(search_url:find("platform=3", 1, true) ~= nil)
Assert.is_true(search_url:find("do=is_search", 1, true) ~= nil)
local ranked
Client.rankAsync("都市", function(list) ranked = list end)
Assert.eq(ranked[1].title, "都市书")
Assert.is_true(requests[#requests].url:find("tag=", 1, true) ~= nil)
local detail_book
Client.detailAsync("8016707", function(book) detail_book = book end)
Assert.eq(detail_book.title, "详情")
Assert.is_true(requests[#requests].body:find("platform=0", 1, true) ~= nil)
Assert.is_true(requests[#requests].body:find("sign=", 1, true) ~= nil)
local chapter
Client.contentAsync("https://free/?a=1", function(value) chapter = value end)
Assert.eq(chapter, "第一段\n第二段")
local denied
Client.shelfAsync(function(_books, err) denied = err end)
Assert.eq(denied, "未登录书旗")
local sent
Client.sendCodeAsync("13800138000", "captcha", function(ok) sent = ok end)
Assert.eq(sent, true)
Assert.is_true(requests[#requests].body:find("mobile=13800138000", 1, true) ~= nil)
Assert.is_true(requests[#requests].body:find("type=1010", 1, true) ~= nil)
Assert.is_true(requests[#requests].body:find("key=sq_h5_gateway", 1, true) ~= nil)
local logged
Client.loginAsync("13800138000", "1234", { fingerprint = "fp" }, function(value) logged = value end)
Assert.eq(logged.user_id, "7")
Assert.eq(cfg.logged_in, true)
Assert.eq(cfg.token, "tok")
Assert.eq(cfg.imei, "fp")
Assert.is_true(requests[#requests].body:find("imei=fp", 1, true) ~= nil)
Assert.is_true(requests[#requests].body:find("agent=chrome", 1, true) ~= nil)
local shelf_books
Client.shelfAsync(function(list) shelf_books = list end)
Assert.eq(shelf_books[1].title, "书架书")
Assert.is_true(requests[#requests].body:find("get_data", 1, true) ~= nil)
Assert.is_true(requests[#requests].body:find("userid%22%3A7", 1, true) ~= nil)
local added
Client.addAsync("9", function(ok) added = ok end)
Assert.eq(added, true)
Assert.is_true(requests[#requests - 1].body:find("action%22%3A1", 1, true) ~= nil)
local removed
Client.removeAsync("9", function(ok) removed = ok end)
Assert.eq(removed, true)
Assert.is_true(requests[#requests - 1].body:find("action%22%3A3", 1, true) ~= nil)
local mark_row
shelf_rows = { { bid = 9, chapterid = 11, percent = 0.5 } }
Client.progressAsync("9", function(value) mark_row = value end)
Assert.eq(mark_row.chapter_id, "11")
Assert.eq(mark_row.fraction, 0.5)
local saved
Client.putProgressAsync("9", "11", "第一章", 0.5, function(ok) saved = ok end)
Assert.eq(saved, true)
Assert.is_true(requests[#requests - 1].body:find("action%22%3A2", 1, true) ~= nil)
Assert.is_true(requests[#requests - 1].body:find("percent%22%3A5000", 1, true) ~= nil)
+117
View File
@@ -0,0 +1,117 @@
--[[--
书旗 Cookie 必须经官方账号校验,失败、取消与换号不覆盖旧会话。
@module tests.moonsource_shuqi.cookie_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
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 = {}, {}
local cleared = 0
package.loaded["source.logout"] = { row = require("source.logout").row, clear = function(_id, clear)
clear(); cleared = cleared + 1; return true
end }
package.loaded["utils.settings"] = { getSource = function() return cfg end, saveSource = function() end }
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 Mapper = require("moonsource_shuqi.mapper")
Assert.eq(Mapper.cookieSession("shuqi_user_id=7; shuqi_token=one%2Btwo%3D").token, "one+two=")
Assert.eq(Mapper.cookieSession("shuqi_user_id=7; shuqi_token=one+two").token, "one+two")
Assert.is_nil(Mapper.cookieSession("shuqi_user_id=8000000; shuqi_token=token"))
Assert.is_nil(Mapper.cookieSession("shuqi_user_id=7; shuqi_token=bad%0D%0Atoken"))
Assert.is_nil(Mapper.cookieSession("shuqi_token=token"))
Assert.is_nil(Mapper.account({ status = 200, data = { ["7"] = { userId = 8 } } }, "7"))
local Client = require("moonsource_shuqi.client")
local result, reason
local function answer(token)
return JSON.encode({ status = 200, data = { ["7"] = { userId = 7, nickName = token } } })
end
local function login(token)
return Client.loginCookieAsync("Cookie: shuqi_user_id=7; shuqi_token=" .. token
.. "; shuqi_fingerprint=browser; unrelated=private", function(value, err) result, reason = value, err end)
end
login("first")
local request = requests[#requests]
Assert.eq(request.opts.headers.Authorization, "Bearer first")
Assert.is_nil(request.opts.headers.Cookie)
Assert.eq(request.opts.cache_ttl, 0)
Assert.is_nil(request.url:find("first", 1, true), "令牌不进入 URL")
Assert.matches(request.url, "/userBaseInfo%?")
request.cb(answer("name"))
Assert.eq(cfg.token, "first")
Assert.eq(cfg.user_id, "7")
Assert.eq(cfg.imei, "browser")
Assert.eq(cfg.name, "name")
Assert.is_true(cfg.logged_in)
Assert.is_nil(cfg.cookie, "不保存无关 Cookie")
login("bad")
requests[#requests].cb(nil, "offline")
Assert.eq(reason, "offline")
Assert.eq(cfg.token, "first")
login("bad")
requests[#requests].cb(JSON.encode({ status = 10003, message = "expired" }))
Assert.eq(reason, "expired")
Assert.eq(cfg.token, "first")
login("bad")
requests[#requests].cb("not json")
Assert.eq(reason, "登录响应无效")
Assert.eq(cfg.token, "first")
login("bad")
requests[#requests].cb(answer("wrong"):gsub('"userId":7', '"userId":8'))
Assert.is_nil(result)
Assert.eq(cfg.token, "first")
local calls = 0
local cancelled = Client.loginCookieAsync("shuqi_user_id=7; shuqi_token=cancelled", function() calls = calls + 1 end)
cancelled:cancel()
Assert.is_true(requests[#requests].cancelled)
requests[#requests].cb(answer("cancelled"))
Assert.eq(calls, 0)
Assert.eq(cfg.token, "first")
login("old")
local late = requests[#requests]
login("latest")
requests[#requests].cb(answer("latest"))
late.cb(answer("old"))
Assert.eq(cfg.token, "latest")
Assert.eq(reason, "登录状态已变化,请重试")
Client.loginCookieAsync("shuqi_user_id=8; shuqi_token=other", function(value, err) result, reason = value, err end)
requests[#requests].cb(JSON.encode({ status = 200, data = { ["8"] = { userId = 8 } } }))
Assert.is_true(result ~= nil)
Assert.is_nil(reason)
Assert.eq(cfg.token, "other")
Assert.eq(cleared, 1)
local reloaded = 0
package.loaded["source.auth"] = { ok = function() end, expired = function() return false end }
package.loaded["source.registry"] = { reload = function() reloaded = reloaded + 1 end }
package.loaded["ui/network/manager"] = { isConnected = function() return true end }
package.loaded["ui.themes.widgets.row"] = { widget = function(opts) return opts end }
local Setting = require("moonsource_shuqi.setting")
Setting.browser.apply({ cookies = {
{ domain = ".shuqi.com", name = "shuqi_user_id", value = "7" },
{ domain = ".shuqi.com", name = "shuqi_token", value = "allowed" },
{ domain = "other.shuqi.com", name = "shuqi_token", value = "wrong" },
{ domain = "shuqi.com.evil.test", name = "shuqi_token", value = "wrong" },
} }, function(ok) result = ok end)
Assert.eq(requests[#requests].opts.headers.Authorization, "Bearer allowed")
requests[#requests].cb(answer("allowed"))
Assert.is_true(result)
Assert.eq(reloaded, 1)
local rows = Setting.rows()
Assert.eq(rows[3](400).title, "粘贴 Cookie")
rows[3](400).callback()
Themed.last("input").callback("shuqi_user_id=7; shuqi_token=cancel-ui")
Themed.last("progress_dialog").on_cancel()
requests[#requests].cb(answer("cancel-ui"))
Assert.eq(cfg.token, "allowed")
Assert.eq(reloaded, 1)
+168
View File
@@ -0,0 +1,168 @@
--[[--
书旗写入必须回读确认,取消和换号不能污染旧登录。
@module tests.moonsource_shuqi.operations_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local Stubs = require("support.stubs")
local JSON = require("support.json_stub")
package.loaded["json"] = JSON
local cfg = { logged_in = true, token = "old", user_id = "7" }
package.loaded["utils.settings"] = { getSource = function() return cfg end, saveSource = function() end }
local requests, delayed, rows = {}, false, {}
package.loaded["http.request"] = {
post = function(url, body, _opts, cb)
local request = { cb = cb, url = url, body = body }
requests[#requests + 1] = request
if not delayed then cb(JSON.encode({ detail = rows })) end
return { cancel = function() request.cancelled = true end }
end,
}
local Client = require("moonsource_shuqi.client")
local result, reason
Client.removeAsync("9", function(ok, err) result, reason = ok, err end)
Assert.is_true(result)
Assert.len(requests, 2, "写后另拉书架")
rows = { { bid = 9, chapterid = 11, percent = 0.5 } }
Client.removeAsync("9", function(ok, err) result, reason = ok, err end)
Assert.is_nil(result)
Assert.eq(reason, "同步结果未确认,请重试")
Client.putProgressAsync("9", "12", "", 0.5, function(ok, err) result, reason = ok, err end)
Assert.is_nil(result)
Assert.eq(reason, "同步结果未确认,请重试")
Client.putProgressAsync("9", "11", "", 0.5, function(ok, err) result, reason = ok, err end)
Assert.is_true(result)
rows[1].percent = 0.168
local write_index = #requests + 1
Client.putProgressAsync("9", "11", "", 0.1676, function(ok, err) result, reason = ok, err end)
Assert.is_true(result, "服务端三位小数舍入不能误判为上传失败")
local data = JSON.decode(require("utils.text").urlDecode(requests[write_index].body:match("data=([^&]*)")))
local mark = data.bookmark[1]
Assert.eq(type(mark.last_update), "string")
Assert.eq(tonumber(mark.last_update) * 1000, mark.add_time, "last_update 为秒,add_time 为毫秒")
Client.putProgressAsync("9", "11", "", 0.1675, function(ok, err) result, reason = ok, err end)
Assert.is_true(result, "三位小数半单位舍入边界")
Client.putProgressAsync("9", "11", "", 0.1674, function(ok, err) result, reason = ok, err end)
Assert.is_nil(result, "超出服务端舍入误差仍必须失败")
Assert.eq(reason, "同步结果未确认,请重试")
Client.putProgressAsync("9", "12", "", 0.1676, function(ok, err) result, reason = ok, err end)
Assert.is_nil(result, "比例匹配不能掩盖章节不匹配")
local count = 0
local read_count = 0
package.loaded["http.request"].post = function(_url, _body, _opts, cb)
read_count = read_count + 1
local request = { cb = cb }
requests[#requests + 1] = request
if read_count == 1 then cb(JSON.encode({ detail = rows })) end
return { cancel = function() request.cancelled = true end }
end
local handle = Client.removeAsync("9", function() count = count + 1 end)
handle:cancel()
Assert.is_true(requests[#requests].cancelled)
requests[#requests].cb(JSON.encode({ detail = {} }))
Assert.eq(count, 0)
delayed = true
package.loaded["http.request"].post = function(_url, _body, options, cb)
local request = { cb = cb, options = options }
requests[#requests + 1] = request
return { cancel = function() request.cancelled = true end }
end
local before = #requests
local completed = 0
Client.shelfAsync(function(books) if books then completed = completed + 1 end end)
local cancelled = Client.shelfAsync(function() completed = completed + 10 end)
Client.load()
Client.progressAsync("9", function(pos) if pos then completed = completed + 1 end end)
Assert.len(requests, before + 1, "刷新与进度读取不能同时发书签请求,重新载入同账号也不能拆队列")
cancelled:cancel()
Assert.is_nil(requests[before + 1].cancelled, "取消排队请求不能取消正在执行的请求")
requests[before + 1].cb(JSON.encode({ detail = rows }))
Assert.eq(completed, 1)
Stubs.flush()
Assert.len(requests, before + 2, "取消的排队请求不得发网络请求")
requests[before + 2].cb(JSON.encode({ detail = rows }))
Assert.eq(completed, 2)
before = #requests
completed = 0
local active = Client.shelfAsync(function() completed = completed + 10 end)
local waiting = Client.shelfAsync(function() completed = completed + 10 end)
Client.shelfAsync(function(books) if books then completed = completed + 1 end end)
active:cancel()
Assert.is_true(requests[before + 1].cancelled)
waiting:cancel()
Stubs.flush()
Assert.len(requests, before + 2, "取消正在执行和即将执行的请求后,后续请求仍能继续")
requests[before + 1].cb(JSON.encode({ detail = rows }))
Assert.eq(completed, 0, "忽略已取消请求的迟到回调")
requests[before + 2].cb(JSON.encode({ detail = rows }))
Assert.eq(completed, 1)
before = #requests
Client.shelfAsync(function(books, err) result, reason = books, err end)
Client.shelfAsync(function(books) if books then completed = completed + 1 end end)
requests[before + 1].cb(JSON.encode({ status = 10006, message = "未知状态码错误" }))
Assert.is_nil(result)
Assert.eq(reason, "未知状态码错误 (10006)", "业务错误保留原提示和状态码")
Stubs.flush()
Assert.len(requests, before + 2, "失败必须释放接口,不能把后续刷新挂死")
requests[before + 2].cb(JSON.encode({ detail = rows }))
Assert.eq(completed, 2)
before = #requests
local changed = 0
local function onChanged(books, err)
if not books and err == "登录状态已变化,请重试" then changed = changed + 1 end
end
Client.shelfAsync(onChanged)
Client.shelfAsync(onChanged)
Client.reset()
requests[before + 1].cb(JSON.encode({ detail = rows }))
Stubs.flush()
Assert.len(requests, before + 1, "账号失效后,旧会话排队请求不得再发出")
Assert.eq(changed, 2)
local function session(id)
return JSON.encode({ status = 200, data = { token = "new", userInfo = { userid = id } } })
end
package.loaded["source.logout"] = { clear = function(_id, clear) clear(); return true end }
Client.sendCodeAsync("13800138000", "captcha", function() end, { user_agent = "Test-UA" })
Assert.eq(requests[#requests].options.headers["User-Agent"], "Test-UA")
Client.loginAsync("13800138000", "code", { user_agent = "Test-UA" }, function(ok, err) result, reason = ok, err end)
Assert.eq(requests[#requests].options.headers["User-Agent"], "Test-UA")
requests[#requests].cb(session(8))
Assert.is_true(result ~= nil)
Assert.eq(cfg.token, "new")
Assert.eq(cfg.user_id, "8")
Assert.is_nil(reason)
local login = Client.loginAsync("13800138000", "code", nil, function() count = count + 1 end)
login:cancel()
requests[#requests].cb(session(7))
Assert.eq(cfg.token, "new")
Assert.eq(count, 0)
Client.loginAsync("13800138000", "code", nil, function(ok, err) result, reason = ok, err end)
local late = requests[#requests]
Client.reset()
late.cb(session(7))
Assert.is_nil(result)
Assert.eq(reason, "登录状态已变化,请重试")
Assert.eq(cfg.token, "new")
Client.loginAsync("13800138000", "code", nil, function(ok) result = ok end)
requests[#requests].cb(session(7))
Assert.eq(cfg.token, "new", "同账号续期允许替换令牌")
Client.loginAsync("13800138000", "code", nil, function(ok, err) result, reason = ok, err end)
requests[#requests].cb("<html>verification required</html>")
Assert.is_nil(result)
Assert.matches(reason, "安全验证")
Assert.eq(cfg.token, "new")
Client.loginAsync("13800138000", "code", nil, function(ok, err) result, reason = ok, err end)
requests[#requests].cb(JSON.encode({ status = 10003 }))
Assert.eq(reason, "书旗登录失败(状态:10003)")
+61
View File
@@ -0,0 +1,61 @@
--[[--
书旗进度的各阶段取消:同步桩不能覆盖下一阶段,异步首阶段也必须可取消。
@module tests.moonsource_shuqi.progress_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local pending
local function request(cb)
pending = { cb = cb }
local operation = pending
return { cancel = function() operation.cancelled = true end }
end
local sync = false
local client = {
loggedIn = function() return true end,
progressAsync = function(_id, cb)
if sync then
cb({ chapter_id = "11", fraction = 0.5 })
return { cancel = function() error("stale first handle") end }
end
return request(cb)
end,
putProgressAsync = function(_id, _chapter, _title, fraction, cb)
Assert.eq(fraction, 0.5)
return request(cb)
end,
}
package.loaded["moonsource_shuqi.client"] = client
package.loaded["source.toc"] = { index = function() return 1 end }
local source = require("moonsource_shuqi.source").new()
local toc = { { uid = "11", title = "第一章" }, { uid = "12", title = "第二章" } }
source.loadTocAsync = function(_self, _identity, cb) return request(cb) end
local identity = { source_id = "ext.shuqi", stable_id = "9" }
local calls = 0
local handle = source:getProgressAsync(identity, function() calls = calls + 1 end)
handle:cancel()
Assert.is_true(pending.cancelled, "异步书签请求必须可取消")
pending.cb({ chapter_id = "11", fraction = 0.5 })
Assert.eq(calls, 0)
sync = true
handle = source:getProgressAsync(identity, function() calls = calls + 1 end)
handle:cancel()
Assert.is_true(pending.cancelled, "同步书签回调后取消目录请求")
pending.cb(toc)
Assert.eq(calls, 0)
handle = source:putProgressAsync(identity, { chapter_idx = 1 }, function() calls = calls + 1 end)
handle:cancel()
Assert.is_true(pending.cancelled, "异步目录请求必须可取消")
pending.cb(toc)
Assert.eq(calls, 0)
source.loadTocAsync = function(_self, _identity, cb)
cb(toc)
return { cancel = function() error("stale toc handle") end }
end
handle = source:putProgressAsync(identity, { chapter_idx = 1 }, function() calls = calls + 1 end)
handle:cancel()
Assert.is_true(pending.cancelled)
pending.cb(true)
Assert.eq(calls, 0)
+47
View File
@@ -0,0 +1,47 @@
--[[--
书旗书评仅归属整本书;分页、空列表与坏响应保持不同语义。
@module tests.moonsource_shuqi.reviews_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 Mapper = require("moonsource_shuqi.mapper")
local wire = {
status = "200", info = { total = 21, count = 2 },
data = { { mid = 1, bookId = 9, nickName = "读者", text = "书评&amp;感想", pubTime = 1700000000 } },
}
local page = Mapper.reviews(wire, "9")
Assert.eq(page.items[1].text, "书评&感想")
Assert.eq(page.items[1].author, "读者")
Assert.eq(page.pages, 2)
Assert.is_nil(Mapper.reviews(wire, "10"), "不能把别的书评挂到本书")
Assert.is_nil(Mapper.reviews({ status = 200 }, "9"))
Assert.is_nil(Mapper.reviews({ status = 500, data = {}, info = { total = 0, count = 0 } }, "9"))
Assert.len(Mapper.reviews({ status = 200, data = {}, info = { total = 0, count = 0 } }, "9").items, 0)
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_shuqi.client")
local result, reason
Client.reviewsAsync("9", 2, function(value, err) result, reason = value, err end)
Assert.matches(requests[1].url, "page=2")
Assert.matches(requests[1].url, "bookId=9")
Assert.is_nil(requests[1].opts.headers.Cookie)
requests[1].cb(JSON.encode(wire))
Assert.eq(result.total, 21)
Client.reviewsAsync("9", 1, function(value, err) result, reason = value, err end)
requests[2].cb(nil, "network down")
Assert.is_nil(result)
Assert.eq(reason, "network down")
Client.reviewsAsync("9", 1, function(value, err) result, reason = value, err end)
requests[3].cb("<html>维护</html>")
Assert.is_nil(result)
Assert.eq(reason, "响应无效")
+61
View File
@@ -0,0 +1,61 @@
--[[--
书旗滑块票据隔离、取消与离线登录入口。
@module tests.moonsource_shuqi.verify_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local Themed = require("support.theme_stubs")
Themed.install()
local route, sends = nil, {}
package.loaded["utils.extension"] = {
add = function(_point, provider) route = provider end,
call = function(_point, _path, _title, _text, options)
return { close = function() options.close_callback() end }
end,
}
package.loaded["ui/uimanager"] = { scheduleIn = function() end, unschedule = function() end }
package.loaded["moonsource_shuqi.client"] = {
sendCodeAsync = function(phone, captcha, cb, browser)
local send = { phone = phone, captcha = captcha, cb = cb, browser = browser }
sends[#sends + 1] = send
return { cancel = function() send.cancelled = true end }
end,
}
local Verification = require("moonsource_shuqi.verify")
local finished = 0
local first = Verification.new("13800138000", function() finished = finished + 1 end)
local second = Verification.new("13900139000", function() finished = finished + 1 end)
local status, body
local function reply(code, response) status, body = code, response end
route.handle("POST", "config", { ticket = first.ticket }, reply)
Assert.matches(body.load_error, "可能被广告拦截插件")
Assert.matches(body.load_timeout, "超时")
Assert.matches(body.load_timeout, "可能被广告拦截插件")
route.handle("POST", "verify", { ticket = first.ticket, captcha = "one", fingerprint = "first", user_agent = "Test-UA" }, reply)
route.handle("POST", "verify", { ticket = second.ticket, captcha = "two", user_agent = "bad\r\nheader" }, reply)
Assert.eq(status, 400)
Assert.len(sends, 1)
route.handle("POST", "verify", { ticket = second.ticket, captcha = "two", fingerprint = "second" }, reply)
sends[2].cb(true)
sends[1].cb(true)
Assert.eq(first.browser.fingerprint, "first")
Assert.eq(first.browser.user_agent, "Test-UA")
Assert.eq(sends[1].browser.user_agent, "Test-UA")
Assert.eq(second.browser.fingerprint, "second")
Assert.eq(finished, 2)
route.handle("POST", "verify", { ticket = first.ticket, captcha = "replay" }, reply)
Assert.eq(status, 403)
local cancelled = Verification.new("13800138000", function() finished = finished + 1 end)
route.handle("POST", "verify", { ticket = cancelled.ticket, captcha = "three" }, reply)
cancelled:cancel()
Assert.is_true(sends[3].cancelled)
sends[3].cb(true)
Assert.is_nil(cancelled.browser)
Assert.eq(finished, 2)
Assert.eq(status, 403)
package.loaded["ui/network/manager"] = { isConnected = function() return false end }
require("moonsource_shuqi.setting").login()
Assert.is_nil(Themed.last("input"))
Assert.eq(Themed.last("toast").text, "网络不可用,请先连接 Wi-Fi")
+117
View File
@@ -0,0 +1,117 @@
'use strict';
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const source = fs.readFileSync(process.argv[2] + '/moonsource-shuqi.koplugin/moonsource_shuqi/web/shuqi_verify.js', 'utf8');
async function page(options = {}) {
const nodes = Object.fromEntries(['title', 'instruction', 'status', 'retry', 'captcha-element']
.map(id => [id, { textContent: '', hidden: false }]));
const requests = [], loaded = [], modules = [], scripts = [], timers = [];
let captcha;
const messages = { title: 'Shuqi', pending: 'Sending', success: 'Sent',
failure: 'Failed', retry: 'Retry', environment_error: 'Environment failed',
load_error: 'Script may be blocked by an ad blocker; use Cookie sign-in',
load_timeout: 'Script timeout; may be blocked by an ad blocker; use Cookie sign-in' };
const fingerprintSDK = function() { this.get = cb => cb(options.fingerprint || 'fingerprint'); };
const awscSDK = { use(name, cb) {
modules.push(name);
if (options.sdkFailed) return cb('failed');
cb('loaded', name === 'um' ? { init(_opts, done) { done('success', { tn: 'um-token' }); } }
: { getUA() { return 'wua-proof'; } });
} };
const context = {
AbortController,
setTimeout: options.timeoutScript ? (fn, ms) => { const timer = { fn, ms }; timers.push(timer); return timer; } : setTimeout,
clearTimeout: options.timeoutScript ? timer => { timer.cleared = true; } : clearTimeout,
location: { hash: '#fixture' },
navigator: { userAgent: 'Test-UA' },
document: {
get cookie() { throw new Error('Must not read cookies from the remote-management origin'); },
getElementById: id => nodes[id], createElement: () => ({ remove() { this.removed = true; } }),
head: { appendChild(script) {
loaded.push(script.src);
scripts.push(script);
if (options.blockScript && script.src.includes(options.blockScript)) return script.onerror();
if (options.timeoutScript && script.src.includes(options.timeoutScript)) {
queueMicrotask(() => timers.find(timer => timer.ms === 20000 && !timer.cleared).fn());
return;
}
if (options.slowAwsc && script.src.includes('awsc.js')) {
setTimeout(() => {
context.window.AWSC = awscSDK;
script.onload();
}, 10);
return;
}
if (script.src.includes('fingerprint2.min.js')) context.window.Fingerprint2 = fingerprintSDK;
if (script.src.includes('awsc.js')) context.window.AWSC = awscSDK;
if (script.src.includes('AliyunCaptcha.js')) context.window.initAliyunCaptcha = config => { captcha = config; };
script.onload();
} },
},
window: {
...(options.preloaded ? { Fingerprint2: fingerprintSDK, AWSC: awscSDK } : {}),
},
fetch: async (url, opts) => {
requests.push({ url, body: JSON.parse(opts.body) });
return { ok: !options.rejected || url.endsWith('/config'),
json: async () => url.endsWith('/config') ? messages : options.rejected ? { error: 'Rejected' } : { ok: true } };
},
};
await vm.runInNewContext(source, context);
return { nodes, requests, loaded, modules, scripts, get captcha() { return captcha; } };
}
(async () => {
let p = await page();
assert.deepEqual(p.modules, ['um', 'uab']);
assert.equal(p.loaded.length, 3);
await p.captcha.captchaVerifyCallback('captcha-proof');
assert.deepEqual(p.requests[1].body, { ticket: 'fixture', captcha: 'captcha-proof',
fingerprint: 'fingerprint_shuqi_touch', umidtoken: 'um-token', wua: 'wua-proof', user_agent: 'Test-UA' });
assert.equal(p.nodes.status.textContent, 'Sent');
assert.equal(p.nodes['captcha-element'].hidden, true);
p = await page({ sdkFailed: true });
assert.equal(p.captcha, undefined);
assert.equal(p.nodes.status.textContent, 'Environment failed');
assert.equal(p.requests.length, 1);
assert.equal(p.nodes.retry.hidden, false);
const blocked = { blockScript: 'fingerprint2.min.js', slowAwsc: true };
p = await page(blocked);
assert.match(p.nodes.status.textContent, /may be blocked by an ad blocker/);
assert.match(p.nodes.status.textContent, /render-resource\.11222\.cn\/third\/fingerprint2\/fingerprint2\.min\.js/);
assert.equal(p.requests.length, 1, 'No verification request when a script is blocked');
assert.equal(p.scripts[0].removed, true);
blocked.blockScript = null;
await p.nodes.retry.onclick();
assert.ok(p.captcha, 'Retry can recover after the script is allowed');
assert.equal(p.loaded.filter(src => src.includes('awsc.js')).length, 1, 'Retry reuses the loaded AWSC SDK');
await p.captcha.captchaVerifyCallback('captcha-proof');
assert.equal(p.nodes.status.textContent, 'Sent');
p = await page({ timeoutScript: 'fingerprint2.min.js' });
assert.match(p.nodes.status.textContent, /Script timeout/);
assert.match(p.nodes.status.textContent, /may be blocked by an ad blocker/);
assert.match(p.nodes.status.textContent, /fingerprint2\.min\.js/);
assert.equal(p.requests.length, 1);
assert.equal(p.scripts[0].removed, true);
assert.equal(p.scripts[0].onload, null, 'Timed-out scripts cannot continue the login pipeline');
p = await page({ preloaded: true });
assert.equal(p.loaded.length, 1, 'Already loaded environment SDKs are not fetched again');
p.captcha.getInstance({ refresh() { throw new Error('Refresh failed'); } });
await p.nodes.retry.onclick();
assert.equal(p.nodes.status.textContent, 'Refresh failed');
assert.equal(p.nodes.retry.hidden, false);
p = await page({ rejected: true, fingerprint: 'second' });
await p.captcha.captchaVerifyCallback('captcha-proof');
assert.equal(p.requests[1].body.fingerprint, 'second_shuqi_touch');
assert.equal(p.nodes.status.textContent, 'Rejected');
assert.equal(p.nodes['captcha-element'].hidden, false);
assert.equal(p.nodes.retry.hidden, false);
console.log('shuqi web: OK');
})().catch(error => { console.error(error); process.exitCode = 1; });
+13
View File
@@ -0,0 +1,13 @@
--[[--
书旗滑块页的登录环境初始化与失败反馈,不依赖 npm。
@module tests.moonsource_shuqi.web_spec
--]]
local Assert = require("support.assert")
local status = os.execute("command -v node >/dev/null 2>&1")
if status ~= 0 and status ~= true then Assert.skip("需要 Node 运行网页脚本回归") end
local here = debug.getinfo(1, "S").source:match("^@(.+)/[^/]+$") or "."
local root = here .. "/../.."
local pipe = assert(io.popen('node "' .. here .. '/web_spec.js" "' .. root .. '" 2>&1'))
local output = pipe:read("*a")
pipe:close()
Assert.is_true(output:find("shuqi web: OK", 1, true) ~= nil, output)