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

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

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

No files matched your search

+293
View File
@@ -0,0 +1,293 @@
--[[--
番茄书架详情:网页端查无此书的用书号占位保留;详情请求本身失败则整次失败(保留本地书架);
并发有上限;book_shelf_info 上的 group_name 挂到详情行。
@module tests.moonsource_fanqie.client_spec
--]]
local Assert = require("support.assert")
package.loaded["json"] = nil
package.preload["json"] = function()
local stub = require("support.json_stub")
return { decode = stub.decode, encode = stub.encode }
end
local SHELF_IDS = { "1", "2", "3" }
-- book_id → group_name;空表 = 书架项不带分组字段(和没建文件夹的账号一致)。
local SHELF_GROUPS = {}
local SHELF_OPERATE, SHELF_ADDED = {}, {}
local fail_ids = {}
local gone_ids = {}
local requests = 0
-- 异步桩:详情请求先挂起,由 drain 逐个回包,才量得出并发。
local held = {}
local no_multi = false
local in_flight, peak = 0, 0
package.loaded["http.request"] = nil
package.preload["http.request"] = function()
return {
header = function() return nil end,
ok = function(code) return code >= 200 and code < 300 end,
request = function(opts, cb)
requests = requests + 1
if opts.url:find("/bookshelf/info/", 1, true) then
local list = {}
for _idx, id in ipairs(SHELF_IDS) do
local item = '{"book_id":"' .. id .. '"'
if SHELF_GROUPS[id] then
item = item .. ',"group_id":"7","group_name":"' .. SHELF_GROUPS[id] .. '"'
end
if SHELF_OPERATE[id] then
item = item .. ',"last_operate_time":' .. SHELF_OPERATE[id]
end
if SHELF_ADDED[id] then
item = item .. ',"add_shelf_time":' .. SHELF_ADDED[id]
end
list[#list + 1] = item .. "}"
end
cb({ code = 200, body = '{"code":0,"data":{"book_shelf_info":[' .. table.concat(list, ",") .. ']}}' })
return { cancel = function() end }
end
if opts.url:find("/multidetail", 1, true) then
local bid = opts.body:match('"book_id":"(%d+)"')
cb({ code = 200, body = no_multi and '{"code":0,"data":{"detail_list":[]}}'
or '{"code":0,"data":{"detail_list":[{"book_id":"' .. bid .. '","book_name":"架上' .. bid .. '"}]}}' })
return { cancel = function() end }
end
local id = opts.url:match("bookId=(%d+)")
in_flight = in_flight + 1
if in_flight > peak then peak = in_flight end
held[#held + 1] = function()
in_flight = in_flight - 1
if fail_ids[id] then
cb(nil, "timeout")
elseif gone_ids[id] then
cb({ code = 200, body = '{"code":-1,"message":"book not found"}' })
else
local metadata = id == "1"
and ',"author":"年轻熊","abstract":"真正的书籍简介","description":"作者签名"'
or ',"author":"","authorName":"兼容作者","abstract":"另一份简介","description":"仍是作者签名"'
cb({ code = 200, body = '{"code":0,"data":{"bookName":"书' .. id .. '","thumbUri":"x"' .. metadata .. '}}' })
end
end
return { cancel = function() end }
end,
}
end
local function drain()
while #held > 0 do table.remove(held, 1)() end
end
package.preload["ui/uimanager"] = function()
return { nextTick = function(_, f) f() end }
end
package.loaded["ui/uimanager"] = nil
package.loaded["moonsource_fanqie.client"] = nil
local Client = require("moonsource_fanqie.client")
local settings = {
get = function(_, _key, default) return default end,
set = function() end,
flush = function() end,
}
local client = Client:new(settings)
-- 一本超时:整次失败,不能把这本书从本地书架藏起来;失败结果不进缓存。
fail_ids["2"] = true
local data, err
client:fetchShelfDetailAsync(false, function(d, e) data, err = d, e end)
drain()
Assert.is_nil(data)
Assert.eq(err, "timeout")
-- 一本查无此书:占位保留,其余照常返回,不报错。
fail_ids["2"] = nil
gone_ids["3"] = true
requests = 0
client:fetchShelfDetailAsync(false, function(d, e) data, err = d, e end)
drain()
Assert.eq(requests, 5, "上次失败没进缓存,这次必须重新请求")
Assert.is_nil(err)
Assert.len(data.data.detail_list, 3)
Assert.eq(data.data.detail_list[1].book_name, "书1")
Assert.eq(data.data.detail_list[2].book_id, "2")
Assert.eq(data.data.detail_list[1].author_name, "年轻熊", "第三方版权书只返回 author")
Assert.eq(data.data.detail_list[1].abstract, "真正的书籍简介", "description 是作者签名,不能当书简介")
Assert.eq(data.data.detail_list[2].author_name, "兼容作者")
Assert.eq(data.data.detail_list[2].abstract, "另一份简介")
Assert.eq(data.data.detail_list[3].book_name, "架上3", "网页查无此书时用书架 multidetail 取书名")
-- 结果进缓存:再拉直接命中,不再发请求。
requests = 0
client:fetchShelfDetailAsync(false, function(d) data = d end)
Assert.eq(requests, 0)
Assert.len(data.data.detail_list, 3)
-- 强制刷新绕过缓存:恢复后按书架顺序拿全。
gone_ids["3"] = nil
client:fetchShelfDetailAsync(true, function(d, e) data, err = d, e end)
drain()
Assert.is_nil(err)
Assert.len(data.data.detail_list, 3)
Assert.eq(data.data.detail_list[3].book_id, "3")
-- 全部查无此书且 multidetail 也没有:全部书号占位,不报错。
gone_ids = { ["1"] = true, ["2"] = true, ["3"] = true }
no_multi = true
client:fetchShelfDetailAsync(true, function(d, e) data, err = d, e end)
drain()
Assert.is_nil(err)
Assert.len(data.data.detail_list, 3)
Assert.eq(data.data.detail_list[1].book_name, "番茄书籍 1")
no_multi = false
-- 大书架:详情请求并发不超过 4,全部拿到后按书架顺序返回。
gone_ids = {}
SHELF_IDS = {}
for i = 1, 10 do SHELF_IDS[i] = tostring(100 + i) end
peak = 0
client:fetchShelfDetailAsync(true, function(d, e) data, err = d, e end)
Assert.eq(in_flight, 4)
drain()
Assert.eq(peak, 4)
Assert.is_nil(err)
Assert.len(data.data.detail_list, 10)
Assert.eq(data.data.detail_list[10].book_id, "110")
do -- 书架分组:book_shelf_info 上的 group_name 挂到详情行(没进组的不写)
SHELF_IDS = { "1", "2", "3" }
SHELF_GROUPS = { ["1"] = "追更", ["3"] = "追更" }
gone_ids = {}
client:fetchShelfDetailAsync(true, function(d, e) data, err = d, e end)
drain()
Assert.is_nil(err)
Assert.eq(data.data.detail_list[1]._group_name, "追更")
Assert.is_nil(data.data.detail_list[2]._group_name, "没进组不算分组")
Assert.eq(data.data.detail_list[3]._group_name, "追更")
SHELF_GROUPS = {}
SHELF_OPERATE = { ["1"] = 1793017940, ["2"] = 1788754903 }
SHELF_ADDED = { ["1"] = 1789912130 }
client:fetchShelfDetailAsync(true, function(d, e) data, err = d, e end)
drain()
Assert.is_nil(err)
Assert.eq(data.data.detail_list[1].last_operate_time, 1793017940)
Assert.eq(data.data.detail_list[1].add_shelf_time, 1789912130)
Assert.eq(data.data.detail_list[2].last_operate_time, 1788754903)
Assert.is_nil(data.data.detail_list[2].add_shelf_time, "没给加入时间就不写")
SHELF_OPERATE, SHELF_ADDED = {}, {}
end
do
client:fetchBookDetailAsync("1", function(d, e) data, err = d, e end)
drain()
Assert.is_nil(err)
Assert.eq(data.author_name, "年轻熊")
Assert.eq(data.abstract, "真正的书籍简介")
fail_ids["1"] = true
client:fetchBookDetailAsync("1", function(d, e) data, err = d, e end)
drain()
Assert.is_nil(data)
Assert.eq(err, "timeout")
fail_ids["1"] = nil
gone_ids["1"] = true
client:fetchBookDetailAsync("1", function(d, e) data, err = d, e end)
drain()
Assert.is_nil(data)
Assert.matches(err, "book not found")
gone_ids["1"] = nil
end
do -- Set-Cookie 值没变不落盘;变了才 flush 一次
local set_cookie = "ttwid=a; Path=/"
package.loaded["http.request"] = {
header = function(_res, name) if name == "Set-Cookie" then return set_cookie end end,
ok = function(code) return code >= 200 and code < 300 end,
request = function(_opts, cb)
cb({ code = 200, body = '{"code":0,"data":{}}' })
return { cancel = function() end }
end,
}
package.loaded["moonsource_fanqie.client"] = nil
local C = require("moonsource_fanqie.client")
local store, flushes = {}, 0
local s = {
get = function(_, key, default) return store[key] or default end,
set = function(_, key, value) store[key] = value end,
flush = function() flushes = flushes + 1 end,
}
local c = C:new(s)
c:fetchReadProgressAsync(function() end)
c:fetchReadProgressAsync(function() end)
Assert.eq(flushes, 1, "同值 Set-Cookie 不重复写设置")
set_cookie = "ttwid=b; Path=/"
c:fetchReadProgressAsync(function() end)
Assert.eq(flushes, 2)
Assert.eq(store.cookies.ttwid, "b")
package.loaded["http.request"] = nil
package.loaded["moonsource_fanqie.client"] = nil
end
do -- 搜索免登录(不带 Cookie、App UA);书架加 / 删走网页接口并校验业务码
local seen, reply, reply_code
package.loaded["http.request"] = {
header = function() return nil end,
ok = function(code) return code >= 200 and code < 300 end,
request = function(opts, cb)
seen = opts
cb({ code = reply_code or 200, body = reply })
return { cancel = function() end }
end,
}
package.loaded["moonsource_fanqie.client"] = nil
local C = require("moonsource_fanqie.client")
local c = C:new({ get = function(_, _key, default) return default end, set = function() end, flush = function() end })
local d, e
reply = '{"code":0,"data":{"ret_data":[]}}'
c:searchAsync("斗 破", function(r, err) d, e = r, err end)
Assert.matches(seen.url, "q=%%E6%%96%%97")
Assert.matches(seen.headers["User-Agent"], "com%.dragon%.read")
Assert.is_nil(seen.headers["Cookie"])
Assert.not_nil(d)
reply = '{"code":1,"message":"bad"}'
c:searchAsync("x", function(r, err) d, e = r, err end)
Assert.is_nil(d)
Assert.matches(e, "番茄搜索失败")
reply = '{"code":0}'
c:shelfActionAsync("add", "42", function(r, err) d, e = r, err end)
Assert.matches(seen.url, "/bookshelf/add/")
Assert.matches(seen.body, '"book_id":"42"')
Assert.matches(seen.body, "add_book_source")
Assert.not_nil(d)
c:shelfActionAsync("delete", "42", function(r, err) d, e = r, err end)
Assert.matches(seen.url, "/bookshelf/delete/")
Assert.is_nil(seen.body:find("add_book_source", 1, true))
reply = '{"code":101108,"message":"无用户信息"}'
local Auth = require("source.auth")
Auth.reset()
c:shelfActionAsync("delete", "42", function(r, err) d, e = r, err end)
Assert.is_nil(d)
Assert.matches(e, "重新登录")
Assert.is_true(Auth.expired("ext.fanqie"))
Auth.reset()
-- HTTP 错误给用户只留短句:诊断串(URL/状态码拼接)只进日志;
-- 非 JSON 回包(风控 HTML 页)同样只报「响应无效」。
reply_code = 500
reply = "<html><title>blocked</title></html>"
c:searchAsync("x", function(r, err) d, e = r, err end)
Assert.is_nil(d)
Assert.eq(e, "请求失败 (HTTP 500)")
reply = '{"code":500,"message":"服务繁忙"}'
c:searchAsync("x", function(r, err) d, e = r, err end)
Assert.eq(e, "服务繁忙")
reply_code = 200
reply = "<html>not json</html>"
c:searchAsync("x", function(r, err) d, e = r, err end)
Assert.is_nil(d)
Assert.eq(e, "响应无效")
package.loaded["http.request"] = nil
package.loaded["moonsource_fanqie.client"] = nil
end
return true
+36
View File
@@ -0,0 +1,36 @@
--[[--
番茄漫画章节:JSON 页清单 → 页图地址,页图 AES-GCM 解密(只解 CTR 流)。
@module tests.moonsource_fanqie.comic_spec
--]]
local Assert = require("support.assert")
package.preload["json"] = function()
local J = require("support.json_stub")
return { encode = J.encode, decode = J.decode }
end
package.loaded["json"] = nil
local Aes = require("crypto.aes")
local Comic = require("moonsource_fanqie.comic")
local key_hex = string.rep("00", 32)
local urls, key = Comic.parse('{"picInfos":[{"picUrl":"https://x/a.jpg?a=1&b=2"},{"picUrl":"https://x/b.jpg"}],'
.. '"encrypt":true,"encrypt_key":"' .. key_hex .. '"}')
Assert.len(urls, 2)
Assert.eq(urls[1], "https://x/a.jpg?a=1&b=2")
Assert.eq(urls[2], "https://x/b.jpg")
Assert.eq(key, string.rep("\0", 32))
local _, plain_key = Comic.parse('{"picInfos":[{"picUrl":"https://x/a.jpg"}]}')
Assert.is_nil(plain_key)
Assert.is_nil(Comic.parse("<p>正文</p>"))
Assert.is_nil(Comic.parse('{"picInfos":[]}'))
-- NIST GCM 测试向量 2:全零 128 位密钥与 IV,明文 16 个零字节
local iv = string.rep("\0", 12)
local sealed = iv .. Aes.from_hex("0388dace60b6a392f328c2b971b2fe78" .. "ab6e47d42cec13bdf53a67b21257bddf")
Assert.eq(Comic.decrypt(sealed, string.rep("\0", 16)), string.rep("\0", 16))
Assert.eq(Comic.decrypt("raw", nil), "raw")
Assert.is_nil(Comic.decrypt("short", string.rep("\0", 16)))
+121
View File
@@ -0,0 +1,121 @@
--[[--
番茄 PUA 解码:真实章节片段必须解成可读中文。
@module tests.moonsource_fanqie.content_spec
--]]
local Assert = require("support.assert")
package.loaded["moonsource_fanqie.content"] = nil
local Content = require("moonsource_fanqie.content")
-- /api/reader/full 第1章首段原始字节(含 PUA)
local sample = "\227\128\144\238\144\178\232\176\162\230\130\168\238\146\168\229\135\187\238\147\184\238\147\186\233\152\133\232\175\187\239\188\140\238\147\175\238\146\142\238\147\179\238\147\131\238\148\170\238\145\138\238\144\182\239\188\140\231\174\128\228\187\139\238\145\141\238\144\142\238\146\128\227\128\145"
local decoded = Content.decode_pua_content(sample)
Assert.eq(decoded, "【感谢您点击进来阅读,其他的就不说了,简介里都有】")
-- 官方目录:分卷二维数组优先,平铺且跳过没有 itemId 的行
local by_volume = Content.normalize_chapters({ data = {
chapterListWithVolume = {
{ { itemId = "1", title = "封面" }, { itemId = "2", title = "第1章" } },
{ { title = "无 id" }, { itemId = "3", title = "第2章" } },
},
chapterList = { { itemId = "x" } },
} })
Assert.len(by_volume, 3)
Assert.eq(by_volume[3].itemId, "3")
Assert.eq(by_volume[1].depth, 1, "无卷名时不编造卷标题,章仍为第 1 层")
Assert.eq(by_volume[3].depth, 1)
Assert.len(Content.readable_chapters(by_volume), 2)
-- 没有分卷时用 chapterList
local flat = Content.normalize_chapters({ data = { chapterListWithVolume = {}, chapterList = { { itemId = "9" } } } })
Assert.eq(flat[1].itemId, "9")
Assert.eq(flat[1].depth, 1)
-- 只有 allItemIds:按序号起标题
local ids = Content.normalize_chapters({ data = { allItemIds = { "7", "8" } } })
Assert.eq(ids[2].itemId, "8")
Assert.eq(ids[2].title, "第2章")
Assert.eq(ids[2].depth, 1)
-- 回包缺 data:空目录
Assert.len(Content.normalize_chapters({ code = 0 }), 0)
Assert.len(Content.normalize_chapters(nil), 0)
-- normalize 保留上游字数字段(有则估全书页码)
do
local rows = Content.normalize_chapters({ data = { chapterList = {
{ itemId = "1", title = "A", wordCount = 1200 },
{ itemId = "2", title = "B", word_count = 800 },
} } })
Assert.eq(tonumber(rows[1].wordCount), 1200)
Assert.eq(tonumber(rows[2].word_count), 800)
end
-- 有卷名:章 depth=2 并带 volume,不额外占 idx
do
local rows = Content.normalize_chapters({ data = {
chapterListWithVolume = {
{ volumeName = "第一卷", chapterList = { { itemId = "1", title = "第1章" }, { itemId = "2", title = "第2章" } } },
{ volume_name = "第二卷", { itemId = "3", title = "第3章" } },
},
} })
Assert.len(rows, 3)
Assert.eq(rows[1].depth, 2)
Assert.eq(rows[1].volume, "第一卷")
Assert.eq(rows[2].volume, "第一卷")
Assert.eq(rows[3].itemId, "3")
Assert.eq(rows[3].depth, 2)
Assert.eq(rows[3].volume, "第二卷")
end
-- 官方子节点收成 anchors,不另开一章
do
local rows = Content.normalize_chapters({ data = { chapterList = {
{ itemId = "10", title = "正文", children = {
{ title = "第一节", anchor = "toc_1" },
{ title = "第二节", id = "toc_2" },
} },
} } })
Assert.len(rows, 1)
Assert.len(rows[1].anchors, 2)
Assert.eq(rows[1].anchors[1].title, "第一节")
Assert.eq(rows[1].anchors[1].id, "toc_1")
Assert.eq(rows[1].anchors[1].depth, 2)
Assert.eq(rows[1].anchors[2].id, "toc_2")
end
-- HTML toc_*:有可见标题用原文,纯图片锚点回退 #N
do
local html = [[<h1>正文</h1>
<h2 id="toc_1">第一节 相遇</h2><p>文字</p>
<p class="picture" id="toc_2"><img src="a.jpg"/></p>
<p id="toc_11"><img src="b.jpg"/></p>
<p id="toc_2">重复 id 忽略</p>]]
local anchors = Content.html_anchors(html, 2)
Assert.len(anchors, 3)
Assert.eq(anchors[1].id, "toc_1")
Assert.eq(anchors[1].title, "第一节 相遇")
Assert.eq(anchors[1].depth, 2)
Assert.eq(anchors[2].id, "toc_2")
Assert.eq(anchors[2].title, "#2")
Assert.eq(anchors[3].id, "toc_11")
Assert.eq(anchors[3].title, "#11")
Assert.len(Content.html_anchors(""), 0)
Assert.len(Content.html_anchors(nil), 0)
end
-- merge_anchors:按 id 去重,已有标题不被回退覆盖
do
local chapter = { idx = 3, title = "正文", anchors = { { title = "官方第一节", depth = 2, id = "toc_1" } } }
Assert.is_true(Content.merge_anchors(chapter, {
{ title = "#1", depth = 2, id = "toc_1" },
{ title = "#2", depth = 2, id = "toc_2" },
}))
Assert.len(chapter.anchors, 2)
Assert.eq(chapter.anchors[1].title, "官方第一节")
Assert.eq(chapter.anchors[2].id, "toc_2")
Assert.is_false(Content.merge_anchors(chapter, { { title = "#2", depth = 2, id = "toc_2" } }))
end
+476
View File
@@ -0,0 +1,476 @@
--[[--
source.fanqie 门面离线用例。
@module tests.source.fanqie_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, redundant-parameter, missing-parameter, inject-field, assign-type-mismatch, param-type-mismatch, cast-type-mismatch, return-type-mismatch, cast-local-type
local Assert = require("support.assert")
local queue = {}
package.preload["ui/uimanager"] = function()
return {
nextTick = function(_, f) queue[#queue + 1] = f end,
}
end
local function drain()
while #queue > 0 do table.remove(queue, 1)() end
end
package.loaded["source.base"] = nil
local progress_wire = { data = {} }
local put_args, put_wire = nil, { code = 0 }
local shelf_actions, pending_adds = {}, {}
local detail_error
local detail_writable = true
local search_wire = { code = 0, data = { ret_data = {
{ book_id = "111", title = "搜到的书", author = "某人", abstract = "简介", category = "玄幻",
thumb_url = "https://p6-tt.bytecdn.cn/novel-pic/abc~tplv-shrink:640:0.image" },
{ title = "没有书号" },
} } }
local source_cfg = {}
package.preload["utils.settings"] = function()
return {
getSource = function() return source_cfg end,
saveSource = function(_, values)
if values and values ~= source_cfg then
for k in pairs(source_cfg) do source_cfg[k] = nil end
for k, v in pairs(values) do source_cfg[k] = v end
end
end,
}
end
package.preload["moonsource_fanqie.settings"] = function()
return {
new = function()
return {
is_cookie_configured = function() return true end,
get = function(_, key, default)
local v = source_cfg[key]
if v == nil then return default end
return v
end,
set = function(_, key, value) source_cfg[key] = value end,
flush = function() end,
}
end,
}
end
package.preload["moonsource_fanqie.client"] = function()
return {
new = function()
return {
fetchBookDetailAsync = function(_self, book_id, cb)
require("ui/uimanager"):nextTick(function()
if detail_error then cb(nil, detail_error); return end
cb({
book_id = book_id, book_name = "详情书名",
author_name = "详情作者", abstract = "<p>详情简介</p>",
thumb_url = "https://p6-novel.byteimg.com/novel-pic/x~tplv-shrink:320:0.image",
})
end)
return { cancel = function() end }
end,
fetchShelfDetailAsync = function(_, _force, cb)
require("ui/uimanager"):nextTick(function()
cb({
data = {
detail_list = {
{
book_id = "1234567890123456789",
book_name = "测试",
author_name = "作者",
thumb_url = "https://p6-novel.byteimg.com/novel-pic/x~tplv-shrink:320:0.image",
abstract = "简介",
_group_name = "追更",
last_operate_time = 1793017940,
add_shelf_time = 1789912130,
},
{
book_id = "9876543210987654321",
book_name = "未分组书",
author_name = "作者乙",
thumb_url = "https://p6-novel.byteimg.com/novel-pic/y~tplv-shrink:320:0.image",
abstract = "简介乙",
last_operate_time = 1788754903,
add_shelf_time = 1788754903000,
},
},
},
})
end)
return { cancel = function() end }
end,
fetchChapterDirectoryAsync = function(_, _id, cb)
require("ui/uimanager"):nextTick(function()
cb({
data = {
chapterList = {
{ itemId = "9876543210987654321", title = "第一章" },
},
},
})
end)
return { cancel = function() end }
end,
officialGetContentAsync = function(_, _bid, _iid, cb)
require("ui/uimanager"):nextTick(function()
cb({ title = "第一章", content = "<p>测试正文</p>" })
end)
return { cancel = function() end }
end,
shelfActionAsync = function(_, action, book_id, cb)
shelf_actions[#shelf_actions + 1] = action .. ":" .. book_id
require("ui/uimanager"):nextTick(function() cb({ code = 0 }) end)
return { cancel = function() end }
end,
searchAsync = function(_, _keyword, cb)
require("ui/uimanager"):nextTick(function() cb(search_wire) end)
return { cancel = function() end }
end,
fetchReadProgressAsync = function(_, cb)
require("ui/uimanager"):nextTick(function()
cb(progress_wire)
end)
return { cancel = function() end }
end,
updateReadProgressAsync = function(_, book_id, item_id, index, progress, cb)
put_args = { book_id = book_id, item_id = item_id, index = index, progress = progress }
require("ui/uimanager"):nextTick(function()
cb(put_wire)
end)
return { cancel = function() end }
end,
}
end,
}
end
package.preload["libs/libkoreader-lfs"] = function()
return { attributes = function() return nil end }
end
package.preload["utils.paths"] = function()
return {
imageDir = function() return "missing" end,
coverPath = function() return "missing/cover.jpg" end,
ensureLayout = function() end,
bookWorkDir = function() return "work" end,
ensureBookWork = function() end,
}
end
local stored
package.preload["book.books_db"] = function()
return {
reconcile = function(id, books)
Assert.eq(id, "ext.fanqie")
stored = books
return true, 0
end,
pendingDeleteIds = function() return {} end,
pendingShelfAddIds = function() return pending_adds end,
markSynced = function() return true end,
upsertRemote = function(book)
if not detail_writable then return false end
stored = { book }
return true
end,
get = function(_source_id, stable_id)
return stored and stored[1] and stored[1].stable_id == stable_id and stored[1] or nil
end,
}
end
local toc
local toc_writable = true
package.preload["source.toc"] = function()
return {
read = function() return toc end,
index = function(_source_id, _stable_id, uid)
for _idx, ch in ipairs(toc or {}) do
if ch.uid == uid then return ch.idx end
end
end,
put = function(_, _, v)
if not toc_writable then return false end
toc = v
return true
end,
}
end
package.preload["source.chapter"] = function()
return {
openAsync = function(_, id, book, opts, ops, cb)
ops.loadToc(id, function(chapters)
Assert.eq(chapters[1].uid, "9876543210987654321")
cb("ready.html")
end)
end,
openWithUi = function()
error("chapter transition must not open a progress dialog")
end,
prefetchAsync = function(_, _, _, _, count, ops, cb)
Assert.eq(count, 3)
Assert.eq(ops.interval_seconds, 6)
cb()
end,
cacheAllAsync = function(source, identity, fetchContent, on_progress, cb, interval)
Assert.eq(source.id, "ext.fanqie")
Assert.eq(interval, 6)
on_progress(1, 1)
fetchContent(identity, { idx = 1, uid = "9876543210987654321", title = "第一章" }, function(payload)
Assert.eq(payload.html, "<p>测试正文</p>")
cb(true, 1, nil, 1, 0)
end)
return { cancel = function() end }
end,
}
end
package.loaded["moonsource_fanqie.source"] = nil
local src = require("moonsource_fanqie.source").new()
local settings = src.settings
Assert.is_true(src:configured())
Assert.eq(src.settings, settings)
local count = 0
src:syncBooksAsync({}, function(r, e)
Assert.not_nil(r)
Assert.is_nil(e)
count = r.pulled
end)
drain()
Assert.eq(count, 2)
Assert.eq(stored[1].stable_id, "1234567890123456789")
Assert.eq(stored[1].authors, "作者")
Assert.eq(stored[1].title, "测试")
Assert.eq(stored[1].category, "追更", "默认开:进组书分类用分组名")
Assert.is_true(stored[1].category_authoritative, "书架快照声明分类口径")
Assert.eq(stored[1].read_at, 1793017940, "最后打开时间进最近阅读")
Assert.eq(stored[1].inserted_at, 1789912130, "加入书架时间进最近添加")
Assert.matches(stored[1].cover, "p6%-novel%.byteimg%.com")
Assert.eq(stored[2].stable_id, "9876543210987654321")
Assert.is_nil(stored[2].category, "没进组不写分类")
Assert.is_true(stored[2].category_authoritative)
Assert.eq(stored[2].read_at, 1788754903)
Assert.eq(stored[2].inserted_at, 1788754903, "毫秒加入时间折成秒")
-- 关掉「使用自定义分组代替分类」后再同步:番茄书架不带题材,分类清空。
do
source_cfg.category_as_group = false
local again = 0
src:syncBooksAsync({ force = true }, function(r, e)
Assert.not_nil(r)
Assert.is_nil(e)
again = r.pulled
end)
drain()
Assert.eq(again, 2)
Assert.is_nil(stored[1].category, "关:进组也不写分组名")
Assert.is_nil(stored[2].category, "关:没进组不写分类")
source_cfg.category_as_group = nil
end
local ref = { source_id = "ext.fanqie", stable_id = "1234567890123456789" }
src:openBookAsync(ref, { chapter_idx = 1 }, function(path)
Assert.eq(path, "ready.html")
count = count + 1
end)
drain()
Assert.eq(count, 3)
local cancelled = src:syncBooksAsync({}, function()
error("cancelled callback delivered")
end)
cancelled.cancel()
drain()
src:prefetchChaptersAsync(ref, {}, 1, 3, function()
count = count + 1
end)
Assert.eq(count, 4)
-- 整本下载:走公共 cacheAllAsync,正文用番茄接口,间隔与预取一致(风控)
do
local progressed, ok, cached
src:cacheAllChaptersAsync(ref, function(done, total) progressed = { done, total } end,
function(success, n) ok, cached = success, n end)
drain()
Assert.eq(progressed[1], 1)
Assert.is_true(ok)
Assert.eq(cached, 1)
end
-- 漫画章节归档已就绪:不联网直接回文件;返回的句柄取消后回调不再投递(之前句柄丢了,取消是空操作)
do
local Chapter = package.loaded["source.chapter"]
local real_cache_all = Chapter.cacheAllAsync
local fetchContent
Chapter.cacheAllAsync = function(_source, _identity, fetcher) fetchContent = fetcher; return { cancel = function() end } end
src:cacheAllChaptersAsync(ref, function() end, function() end)
Chapter.cacheAllAsync = real_cache_all
local Cbz = package.loaded["source.cbz"]
local real_ready = Cbz.ready
Cbz.ready = function(path) return path == "work/777.cbz" end
local chapter = { idx = 1, uid = "777", title = "漫画一" }
local got
fetchContent(ref, chapter, function(payload) got = payload end)
drain()
Assert.eq(got.file, "work/777.cbz")
got = nil
local handle = fetchContent(ref, chapter, function(payload) got = payload end)
handle.cancel()
drain()
Assert.is_nil(got, "取消后不能再回调")
Cbz.ready = real_ready
end
do
toc = nil
toc_writable = false
local chapters, err
src:loadTocAsync(ref, function(value, reason)
chapters, err = value, reason
end)
drain()
Assert.is_nil(chapters)
Assert.eq(err, "章节目录保存失败")
Assert.is_nil(toc)
toc_writable = true
src:loadTocAsync(ref, function(value) chapters = value end)
drain()
Assert.eq(chapters[1].uid, "9876543210987654321")
Assert.eq(chapters[1].depth, 1)
local called = false
local cached = src:loadTocAsync(ref, function() called = true end)
cached:cancel()
drain()
Assert.is_false(called)
end
do
local result
src:syncBooksAsync({ dirty_only = true }, function(r) result = r end)
Assert.is_nil(result)
drain()
Assert.eq(result.pushed, 0)
Assert.len(shelf_actions, 0)
-- 本地新加架的书经网页接口上行
pending_adds = { "555" }
src:syncBooksAsync({ dirty_only = true }, function(r) result = r end)
drain()
Assert.eq(result.pushed, 1)
Assert.eq(shelf_actions[1], "add:555")
pending_adds = {}
end
-- 书城搜索:只留有书号的行,封面归一到手机 CDN
do
local res
src:searchAsync("关键字", function(r) res = r end)
drain()
Assert.len(res.data, 1)
Assert.eq(res.data[1].stable_id, "111")
Assert.eq(res.data[1].authors, "某人")
Assert.eq(res.data[1].category, "玄幻")
Assert.matches(res.data[1].cover, "p6%-novel%.byteimg%.com")
end
-- 封面走基类:查书库 cover(同步书架时写入的手机 CDN 地址)
Assert.matches(src:coverRequest(ref).url, "p6%-novel%.byteimg%.com")
-- 官方网页进度只有章节;read_progress 不是章内比例。
toc = {
{ idx = 1, uid = "a" }, { idx = 2, uid = "b" }, { idx = 3, uid = "c" }, { idx = 4, uid = "d" },
}
do
progress_wire = { code = 0, data = {
{ book_id = "other", item_id = "a" },
{ book_id = ref.stable_id, item_id = "c", read_progress = 5000 },
} }
local pos, err
src:getProgressAsync(ref, function(p, e) pos, err = p, e end)
drain()
Assert.is_nil(err)
Assert.eq(pos.chapter_idx, 3)
Assert.is_nil(pos.chapter_fraction, "不能把章节 order 当成万分比")
Assert.eq(pos.fraction, 0.5)
Assert.eq(pos.extra.chapter_uid, "c")
-- 章节不在目录 / 云端没这本书:空进度,不是错误
progress_wire.data[2].item_id = "gone"
local meta
src:getProgressAsync(ref, function(p, e, m) pos, err, meta = p, e, m end)
drain()
Assert.is_nil(pos)
Assert.is_nil(err)
Assert.is_true(meta.empty)
progress_wire = { code = 0, data = {} }
meta = nil
src:getProgressAsync(ref, function(p, e, m) pos, err, meta = p, e, m end)
drain()
Assert.is_true(meta.empty)
end
-- 进度上传:章节序号 → uid + 0 起 index,不伪造网页不支持的章内位置。
do
local ok, err
src:putProgressAsync(ref, { chapter_idx = 2, chapter_fraction = 1.5 }, function(r, e) ok, err = r, e end)
drain()
Assert.is_true(ok)
Assert.is_nil(err)
Assert.eq(put_args.book_id, ref.stable_id)
Assert.eq(put_args.item_id, "b")
Assert.eq(put_args.index, 1)
Assert.eq(put_args.progress, 0)
-- 没有章节位置:不发请求,直接报错
put_args = nil
src:putProgressAsync(ref, { fraction = 0.3 }, function(r, e) ok, err = r, e end)
drain()
Assert.is_nil(ok)
Assert.eq(err, "缺少番茄章节位置")
Assert.is_nil(put_args)
-- 业务码非 0:上传失败
put_wire = { code = 1001 }
src:putProgressAsync(ref, { chapter_idx = 1 }, function(r, e) ok, err = r, e end)
drain()
Assert.is_nil(ok)
Assert.eq(err, "番茄进度上传失败")
end
do
local detail, err
stored[1].deleted = 1
src:getDetailAsync({ source_id = src.id, stable_id = ref.stable_id, book = { intro = "" } },
function(book, reason) detail, err = book, reason end)
Assert.is_nil(detail, "详情不能同步返回旧的本地行")
drain()
Assert.is_nil(err)
Assert.eq(detail.authors, "详情作者")
Assert.eq(detail.intro, "详情简介")
Assert.eq(detail.deleted, 1, "补详情不能复活墓碑")
detail_error = "network failed"
src:getDetailAsync(ref, function(book, reason) detail, err = book, reason end)
drain()
Assert.is_nil(detail)
Assert.eq(err, "network failed")
Assert.eq(stored[1].intro, "详情简介")
detail_error = nil
detail_writable = false
src:getDetailAsync(ref, function(book, reason) detail, err = book, reason end)
drain()
Assert.is_nil(detail)
Assert.eq(err, "书籍信息保存失败")
detail_writable = true
local previous = stored[1]
local job = src:getDetailAsync(ref, function() error("cancelled detail callback delivered") end)
job:cancel()
drain()
Assert.eq(stored[1], previous, "关闭详情后到达的回包不能写库")
end
+13
View File
@@ -0,0 +1,13 @@
--[[--
番茄正文入口:client 直调 reading API。
@module tests.moonsource_fanqie.official_spec
--]]
local Assert = require("support.assert")
package.loaded["moonsource_fanqie.official"] = nil
package.loaded["moonsource_fanqie.reading"] = nil
local Reading = require("moonsource_fanqie.reading")
Assert.eq(type(Reading.fetchAsync), "function")
+123
View File
@@ -0,0 +1,123 @@
--[[--
moonsource_fanqie.qrlogin:预热 → 取码 → 轮询 → 跟跳拿 sessionid → 落盘;过期与取消不落盘。
@module tests.moonsource_fanqie.qrlogin_spec
--]]
local Assert = require("support.assert")
local Stubs = require("support.stubs")
require("source.logout").replaceLibrary = function(id, commit)
Assert.eq(id, "ext.fanqie")
commit()
return true
end
package.preload["json"] = function()
return { decode = require("support.json_stub").decode, encode = function() return "{}" end }
end
-- 按 URL 前缀排队的罐头响应
local script, requested = {}, {}
local function respond(prefix, res) script[#script + 1] = { prefix = prefix, res = res } end
package.preload["http.request"] = function()
return {
request = function(opts, cb)
requested[#requested + 1] = opts
for i, item in ipairs(script) do
if opts.url:sub(1, #item.prefix) == item.prefix then
table.remove(script, i)
require("ui/uimanager"):nextTick(function()
if item.res.hook then item.res.hook() end
cb(item.res)
end)
return { cancel = function() end }
end
end
require("ui/uimanager"):nextTick(function() cb(nil, "no script") end)
return { cancel = function() end }
end,
header = function(res, name) return res and res.headers and res.headers[name] end,
}
end
local shown = {}
local function widget(kind)
return function()
return { new = function(_, o)
o.kind = kind
function o:show() shown[#shown + 1] = self end
function o:close() self.closed = true; if self.close_callback then self.close_callback() end end
return o
end }
end
end
package.preload["ui.themes.widgets.qr"] = widget("qr")
package.preload["ui.themes.widgets.confirm"] = widget("confirm")
package.preload["ui.themes.widgets.toast"] = widget("toast")
local QRLogin = require("moonsource_fanqie.qrlogin")
local function newLogin()
local saved = {}
local settings = { set = function(_, k, v) saved[k] = v end, flush = function() saved.flushed = true end }
local plugin = { showBusy = function() end, closeBusy = function() end,
onLoginSuccess = function() saved.success = true end }
return QRLogin:new(settings, plugin), saved
end
local function find(kind)
for i = #shown, 1, -1 do if shown[i].kind == kind then return shown[i] end end
end
local QR_OK = { code = 200, headers = { ["Set-Cookie"] = "ttwid=t; Path=/" },
body = '{"message":"success","data":{"token":"tok","qrcode_index_url":"https://qr/x"}}' }
do -- 成功:确认后 redirect_url 第二跳下发 sessionid(相对 Location 拼回原 host)
script, requested, shown = {}, {}, {}
respond("https://fanqienovel.com/main/writer/login",
{ code = 200, headers = { ["Set-Cookie"] = "passport_csrf_token=c1; Path=/; HttpOnly" } })
respond("https://fanqienovel.com/passport/web/get_qrcode/", QR_OK)
respond("https://fanqienovel.com/passport/web/check_qrconnect/",
{ code = 200, body = '{"data":{"status":"scanned"}}' })
respond("https://fanqienovel.com/passport/web/check_qrconnect/",
{ code = 200, body = '{"data":{"status":"confirmed","redirect_url":"https://sso.fanqie/a"}}' })
respond("https://sso.fanqie/a", { code = 302, headers = { Location = "/b" } })
respond("https://sso.fanqie/b", { code = 200, headers = { ["Set-Cookie"] = "sessionid=S; Path=/; Secure" } })
local login, saved = newLogin()
login:start()
Stubs.flush()
Assert.eq(find("qr").text, "https://qr/x")
Assert.eq(saved.cookies.sessionid, "S")
Assert.eq(saved.cookies.passport_csrf_token, "c1")
Assert.is_nil(saved.cookies.Path, "Set-Cookie 属性不当 cookie 存")
Assert.is_true(saved.success)
Assert.is_true(find("qr").closed)
-- 轮询带上 csrf 头
Assert.eq(requested[3].headers["x-tt-passport-csrf-token"], "c1")
Assert.len(script, 0)
end
do -- 过期:弹重试框,不落盘
script, requested, shown = {}, {}, {}
respond("https://fanqienovel.com/main/writer/login", { code = 200, headers = {} })
respond("https://fanqienovel.com/passport/web/get_qrcode/", QR_OK)
respond("https://fanqienovel.com/passport/web/check_qrconnect/",
{ code = 200, body = '{"data":{"status":"expired"}}' })
local login, saved = newLogin()
login:start()
Stubs.flush()
Assert.is_nil(saved.cookies)
Assert.eq(find("confirm").ok_text ~= nil, true)
end
do -- 用户关掉二维码(轮询在途时):迟到的 sessionid 不落盘,也不再轮询
script, requested, shown = {}, {}, {}
respond("https://fanqienovel.com/main/writer/login", { code = 200, headers = {} })
respond("https://fanqienovel.com/passport/web/get_qrcode/", QR_OK)
respond("https://fanqienovel.com/passport/web/check_qrconnect/",
{ code = 200, headers = { ["Set-Cookie"] = "sessionid=LATE" }, hook = function() find("qr"):close() end })
local login, saved = newLogin()
login:start()
Stubs.flush()
Assert.is_nil(saved.cookies)
Assert.eq(#requested, 3, "关闭后不再轮询")
end
+32
View File
@@ -0,0 +1,32 @@
--[[--
番茄网页榜单解析离线用例:内嵌状态(含裸 undefined)、PUA 书名解码、封面。
@module tests.moonsource_fanqie.rank_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, redundant-parameter, missing-parameter, inject-field, assign-type-mismatch, param-type-mismatch, cast-type-mismatch, return-type-mismatch, cast-local-type
local Assert = require("support.assert")
local JSONStub = require("support.json_stub")
package.preload["json"] = function()
return { decode = JSONStub.decode, encode = JSONStub.encode }
end
package.loaded["moonsource_fanqie.rank"] = nil
local Rank = require("moonsource_fanqie.rank")
local html = '<script>(function(){window.__INITIAL_STATE__={"rank":{"book_list":[{"bookId":"7654593151348247614",'
.. '"bookName":"\u{E4C2}\u{E3E9}诡异","author":"糕","abstract":"\u{E3E9}简介","pos_category_id":undefined,'
.. '"thumbUri":"https://p3-reading-sign.fqnovelpic.com/novel-pic/abc~tplv-resize:225:0.image?x=1"}],'
.. '"rankCategoryTypeList":{"male":[{"id":"1141","name":"西方奇幻"}],"female":[]}}};\n})()\n</script><script>x</script>'
do
local rank = Rank.state(html)
Assert.eq(rank.rankCategoryTypeList.male[1].name, "西方奇幻")
local books = Rank.books(rank, "ext.fanqie")
Assert.len(books, 1)
Assert.eq(books[1].stable_id, "7654593151348247614")
Assert.matches(books[1].title, "在诡异$")
Assert.eq(books[1].intro, "在简介")
Assert.matches(books[1].cover, "novel%-pic/abc")
Assert.is_nil(Rank.state("<html>人机验证</html>"))
end
+58
View File
@@ -0,0 +1,58 @@
--[[--
番茄 reading crypto 向量(离线)。
@module tests.moonsource_fanqie.reading_crypto_spec
--]]
local Assert = require("support.assert")
-- 设备上 z_stream / inflate 可能已被其他模块以不同签名声明,解压不能因此失效。
pcall(require("ffi").cdef, [[
typedef struct z_stream_s { void *p; } z_stream;
int inflate(z_stream *, int);
]])
package.loaded["moonsource_fanqie.reading.crypto"] = nil
package.loaded["crypto.aes"] = nil
local Aes = require("crypto.aes")
local Crypto = require("moonsource_fanqie.reading.crypto")
local key = Aes.from_hex(Crypto.HARDCODED_KEY_HEX)
local iv = "1234567890123456"
local pt = Aes.from_hex("2b5dbca76c4902000000000000000000")
local ct = Aes.cbc_encrypt(pt, key, iv, true)
Assert.eq(Aes.to_hex(ct), "64fd9775e48333728345235490bca65492c8c2ccd7832564732fb54839593fe2")
local content = Crypto.build_register_content(643680972856619, 0, "1234567890123456")
Assert.eq(content, "MTIzNDU2Nzg5MDEyMzQ1NmT9l3XkgzNyg0UjVJC8plSSyMLM14MlZHMvtUg5WT/i")
-- 19 位 device_id 串超过 2^53:小端 8 字节必须逐位精确
do
local b64 = Crypto.build_register_content("7342475219212192830", 0, "1234567890123456")
local raw = require("utils.text").base64Decode(b64)
local plain_id = Aes.cbc_decrypt(raw:sub(17), key, raw:sub(1, 16), true)
Assert.eq(Aes.to_hex(plain_id:sub(1, 8)), "3e4c404d4fb6e565")
Assert.eq(Crypto.build_register_content("643680972856619", 0, "1234567890123456"), content)
end
-- decrypt_server_key roundtrip
local session = Aes.from_hex("00112233445566778899aabbccddeeff")
local iv2 = "0123456789abcdef"
local blob = require("utils.text").base64Encode(iv2 .. Aes.cbc_encrypt(session, key, iv2, true))
Assert.eq(Crypto.decrypt_server_key(blob), "00112233445566778899AABBCCDDEEFF")
local q = Crypto.build_batch_full_query({
install_id = "1", device_id = "2", version_code = "73733", version_name = "7.3.7.33",
}, "7342475219212192830", { "7463695105224884760" }, 1000)
local qs = Crypto.encode_query(q)
Assert.matches(qs, "item_ids=7463695105224884760")
Assert.is_true(not qs:find("%%2C", 1, true))
Assert.matches(qs, "book_id=7342475219212192830")
local plain = string.rep("番茄正文", 20)
Assert.eq(Crypto.maybe_decompress(Aes.from_hex(
"1f8b08000000000002ff7b3e75d58b9e96676b173f9bd6fe7c04b00161f60cc9f0000000"), 1), plain)
Assert.eq(Crypto.maybe_decompress(Aes.from_hex(
"789c7b3e75d58b9e96676b173f9bd6fe7c04b001a6cea6cd"), 1), plain)
Assert.eq(Crypto.maybe_decompress("plain", 0), "plain")
+213
View File
@@ -0,0 +1,213 @@
--[[--
番茄设备身份:本地画像唯一 + device_register 落盘(HTTP 打桩)。
@module tests.moonsource_fanqie.reading_device_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, redundant-parameter, missing-parameter, inject-field, assign-type-mismatch, param-type-mismatch, cast-type-mismatch, return-type-mismatch, cast-local-type
local Assert = require("support.assert")
local Stubs = require("support.stubs")
local state = {
cfg = {},
saved = nil,
request_impl = nil,
}
package.preload["utils.settings"] = function()
return {
getSource = function() return state.cfg end,
saveSource = function(_, value)
state.saved = value
state.cfg = value
end,
}
end
package.preload["http.request"] = function()
return {
ok = function(code)
local n = tonumber(code)
return n ~= nil and n >= 200 and n < 300
end,
header = function() return nil end,
request = function(opts, cb)
return state.request_impl(opts, cb)
end,
}
end
package.preload["json"] = function()
return {
encode = function(t)
-- 足够 register body 冒烟:只要发出去
Assert.eq(type(t), "table")
Assert.eq(t.magic_tag, "ss_app_log")
return '{"magic_tag":"ss_app_log"}'
end,
decode = function(s)
if type(s) ~= "string" or s == "" then error("empty") end
-- 极简:只解析我们罐装的响应
local did = s:match('"device_id_str"%s*:%s*"(%d+)"')
or s:match('"device_id"%s*:%s*(%d+)')
local iid = s:match('"install_id_str"%s*:%s*"(%d+)"')
or s:match('"install_id"%s*:%s*(%d+)')
if not did or not iid then error("bad json") end
return {
device_id = tonumber(did),
install_id = tonumber(iid),
device_id_str = did,
install_id_str = iid,
new_user = 1,
}
end,
}
end
for _, name in ipairs({
"utils.settings", "http.request", "json",
"moonsource_fanqie.reading.device", "moonsource_fanqie.settings",
}) do
package.loaded[name] = nil
end
local Device = require("moonsource_fanqie.reading.device")
local Settings = require("moonsource_fanqie.settings")
-- normalize:缺 id 一律拒绝(禁止半残共享身份)
Assert.is_nil(Device.normalize(nil))
Assert.is_nil(Device.normalize({}))
Assert.is_nil(Device.normalize({ device_id = "1" }))
Assert.is_nil(Device.normalize({ install_id = "1" }))
-- 本地画像每次唯一
local a = Device.newLocalProfile()
local b = Device.newLocalProfile()
Assert.is_true(a.cdid ~= b.cdid)
Assert.is_true(a.openudid ~= b.openudid)
Assert.eq(#a.openudid, 16)
Assert.matches(a.cdid, "^%x%x%x%x%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%x%x%x%x%x%x%x%x$")
Assert.is_nil(a.device_id)
Assert.is_nil(a.install_id)
local ok = Device.normalize({
device_id = "123",
install_id = "456",
device_profile = { device_type = "Pixel", cdid = a.cdid, openudid = a.openudid },
})
Assert.eq(ok.device_id, "123")
Assert.eq(ok.install_id, "456")
Assert.eq(ok.device_type, "Pixel")
Assert.eq(ok.cdid, a.cdid)
Assert.is_nil(Device.DEFAULT)
-- registerAsync:打桩 HTTP,校验 URL / 落盘
state.cfg = {}
state.saved = nil
local settings = Settings:new()
local seen_url
state.request_impl = function(opts, cb)
seen_url = opts.url
Assert.eq(opts.method, "POST")
Assert.matches(opts.url, "log%.snssdk%.com/service/2/device_register/")
Assert.matches(opts.url, "aid=1967")
Assert.matches(opts.url, "app_name=novelapp")
Assert.eq(opts.headers["Content-Type"], "application/json; charset=utf-8")
require("ui/uimanager"):nextTick(function()
cb({
code = 200,
body = '{"device_id_str":"516130687997515","install_id_str":"516130688001611","new_user":1}',
})
end)
return { cancel = function() end }
end
local got, reg_err
Device.registerAsync(settings, function(device, err)
got, reg_err = device, err
end)
Stubs.flush()
Assert.is_nil(reg_err)
Assert.eq(got.device_id, "516130687997515")
Assert.eq(got.install_id, "516130688001611")
Assert.is_true(type(got.cdid) == "string" and got.cdid ~= "")
Assert.matches(seen_url, "openudid=")
Assert.eq(state.saved.reading_device.device_id, "516130687997515")
Assert.eq(state.saved.reading_device.install_id, "516130688001611")
-- ensureAsync:已有身份不再请求网络
local net_hits = 0
state.request_impl = function(_, cb)
net_hits = net_hits + 1
cb(nil, "should not call")
return { cancel = function() end }
end
local cached, cache_err
Device.ensureAsync(settings, function(device, err)
cached, cache_err = device, err
end)
Stubs.flush()
Assert.is_nil(cache_err)
Assert.eq(cached.device_id, "516130687997515")
Assert.eq(net_hits, 0)
-- ensureAsync:无身份则注册
state.cfg = {}
state.saved = nil
settings = Settings:new()
state.request_impl = function(_, cb)
require("ui/uimanager"):nextTick(function()
cb({
code = 200,
body = '{"device_id":999001,"install_id":999002,"new_user":1}',
})
end)
return { cancel = function() end }
end
local ensured
Device.ensureAsync(settings, function(device, err)
ensured, cache_err = device, err
end)
Stubs.flush()
Assert.is_nil(cache_err)
Assert.eq(ensured.device_id, "999001")
Assert.eq(ensured.install_id, "999002")
-- 传输错误:res 表还在,但 err 才是超时原因,不能报成 HTTP nil
state.cfg = {}
state.saved = nil
settings = Settings:new()
state.request_impl = function(_, cb)
require("ui/uimanager"):nextTick(function()
cb({ error = { code = -6, message = "Request timed out after 20 secs" } },
"Request timed out after 20 secs")
end)
return { cancel = function() end }
end
local timed
Device.registerAsync(settings, function(device, err)
timed = err
Assert.is_nil(device)
end)
Stubs.flush()
Assert.eq(timed, "Request timed out after 20 secs")
Assert.is_nil(state.saved)
-- Kindle 出网拦 log.snssdk.com:英文原句换成能看懂的中文
state.cfg = {}
state.saved = nil
settings = Settings:new()
state.request_impl = function(_, cb)
require("ui/uimanager"):nextTick(function()
cb(nil, "Could not connect: connection refused")
end)
return { cancel = function() end }
end
local blocked
Device.registerAsync(settings, function(device, err)
blocked = err
Assert.is_nil(device)
end)
Stubs.flush()
Assert.eq(blocked, "番茄正文需要注册设备,当前网络拦了 log.snssdk.com")
Assert.is_nil(state.saved)
+256
View File
@@ -0,0 +1,256 @@
--[[--
番茄 reading.fetchAsync:ensure 设备 → registerkey → batch_full(全打桩)。
@module tests.moonsource_fanqie.reading_fetch_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, redundant-parameter, missing-parameter, inject-field, assign-type-mismatch, param-type-mismatch, cast-type-mismatch, return-type-mismatch, cast-local-type
local Assert = require("support.assert")
local Stubs = require("support.stubs")
local state = {
cfg = {
reading_device = {
device_id = "516130687997515",
install_id = "516130688001611",
device_profile = {
channel = "43536163a",
version_code = "73733",
version_name = "7.3.7.33",
device_type = "P30",
device_brand = "HUAWEI",
language = "zh",
os_api = "31",
os_version = "12",
resolution = "1280*720",
dpi = "240",
host_abi = "arm64-v8a",
cdid = "8550abb6-a07b-4b77-9edd-6710f414828b",
openudid = "733b78130c0d0098",
rom_version = "S643.217451.03386707",
},
},
},
urls = {},
}
package.preload["utils.settings"] = function()
return {
getSource = function() return state.cfg end,
saveSource = function(_, value) state.cfg = value end,
}
end
-- registerkey / batch_full 都要编解码 JSON
package.preload["json"] = function()
local J = require("support.json_stub")
return { encode = J.encode, decode = J.decode }
end
package.loaded["json"] = nil
-- 用真实 crypto 解一把已知向量,给 fetch 罐装响应
package.loaded["crypto.aes"] = nil
package.loaded["moonsource_fanqie.reading.crypto"] = nil
local Aes = require("crypto.aes")
local Crypto = require("moonsource_fanqie.reading.crypto")
local Text = require("utils.text")
-- 构造假 v1_key 与假章节密文
local v1_bin = Aes.from_hex("00112233445566778899aabbccddeeff")
local v1_hex = Aes.to_hex(v1_bin):upper()
local iv = "0123456789abcdef"
local plain = "<?xml version=\"1.0\"?><html><body>第776章 养女如母 测试正文内容足够长</body></html>"
-- compress_status=0:不解压
local enc = Aes.cbc_encrypt(plain, v1_bin, iv, true)
local content_b64 = Text.base64Encode(iv .. enc)
local key_blob = Text.base64Encode(iv .. Aes.cbc_encrypt(v1_bin, Aes.from_hex(Crypto.HARDCODED_KEY_HEX), iv, true))
package.preload["http.request"] = function()
return {
ok = function(code)
local n = tonumber(code)
return n ~= nil and n >= 200 and n < 300
end,
header = function() return nil end,
request = function(opts, cb)
state.urls[#state.urls + 1] = opts.url
require("ui/uimanager"):nextTick(function()
if opts.url:find("/reading/crypt/registerkey", 1, true) then
Assert.eq(opts.method, "POST")
Assert.is_true(opts.headers["X-Argus"] ~= nil)
Assert.is_true(opts.headers["X-Ladon"] ~= nil)
cb({
code = 200,
body = '{"code":0,"data":{"key":"' .. key_blob .. '","keyver":1},"message":"ok"}',
})
return
end
if opts.url:find("/reading/reader/batch_full", 1, true) then
Assert.eq(opts.method, "GET")
Assert.matches(opts.url, "item_ids=7463695105224884760")
Assert.matches(opts.url, "book_id=7342475219212192830")
Assert.is_true(not opts.url:find("%%2C", 1, true))
cb({
code = 200,
body = '{"code":0,"data":{"7463695105224884760":{'
.. '"title":"第776章 养女如母",'
.. '"crypt_status":0,"compress_status":0,'
.. '"content":"' .. content_b64 .. '"}}}',
})
return
end
cb(nil, "unexpected url " .. tostring(opts.url))
end)
return { cancel = function() end }
end,
}
end
for _, name in ipairs({
"http.request", "utils.settings", "json",
"moonsource_fanqie.reading",
"moonsource_fanqie.reading.device", "moonsource_fanqie.settings",
"moonsource_fanqie.reading.sign",
}) do
package.loaded[name] = nil
end
local Reading = require("moonsource_fanqie.reading")
local Settings = require("moonsource_fanqie.settings")
local row, fetch_err
Reading.fetchAsync(Settings:new(), "7342475219212192830", "7463695105224884760", function(data, err)
row, fetch_err = data, err
end)
Stubs.flush()
Assert.is_nil(fetch_err)
Assert.eq(row.title, "第776章 养女如母")
Assert.eq(row.source, "reading_batch_full")
Assert.matches(row.content, "养女如母")
Assert.eq(#state.urls, 2)
Assert.matches(state.urls[1], "registerkey")
Assert.matches(state.urls[2], "batch_full")
-- 无设备身份时先走 device_register
state.cfg = {}
state.urls = {}
package.loaded["moonsource_fanqie.reading"] = nil
package.loaded["moonsource_fanqie.reading.device"] = nil
package.loaded["moonsource_fanqie.settings"] = nil
local register_hits = 0
package.preload["http.request"] = function()
return {
ok = function(code)
local n = tonumber(code)
return n ~= nil and n >= 200 and n < 300
end,
header = function() return nil end,
request = function(opts, cb)
state.urls[#state.urls + 1] = opts.url
require("ui/uimanager"):nextTick(function()
if opts.url:find("device_register", 1, true) then
register_hits = register_hits + 1
cb({
code = 200,
body = '{"device_id_str":"111","install_id_str":"222","new_user":1}',
})
return
end
if opts.url:find("registerkey", 1, true) then
cb({
code = 200,
body = '{"code":0,"data":{"key":"' .. key_blob .. '","keyver":1}}',
})
return
end
if opts.url:find("batch_full", 1, true) then
cb({
code = 200,
body = '{"code":0,"data":{"1":{"title":"T","crypt_status":0,"compress_status":0,"content":"'
.. content_b64 .. '"}}}',
})
return
end
cb(nil, "bad url")
end)
return { cancel = function() end }
end,
}
end
package.loaded["http.request"] = nil
Reading = require("moonsource_fanqie.reading")
Settings = require("moonsource_fanqie.settings")
row, fetch_err = nil, nil
Reading.fetchAsync(Settings:new(), "99", "1", function(data, err)
row, fetch_err = data, err
end)
Stubs.flush()
Assert.is_nil(fetch_err)
Assert.eq(register_hits, 1)
Assert.eq(row.title, "T")
Assert.eq(state.cfg.reading_device.device_id, "111")
-- registerkey 超时:res 非 nil,err 必须原样回到打开流程
state.urls = {}
package.preload["http.request"] = function()
return {
ok = function(code)
local n = tonumber(code)
return n ~= nil and n >= 200 and n < 300
end,
header = function() return nil end,
request = function(opts, cb)
state.urls[#state.urls + 1] = opts.url
require("ui/uimanager"):nextTick(function()
cb({ error = { code = -6 } }, "Request timed out after 20 secs")
end)
return { cancel = function() end }
end,
}
end
package.loaded["http.request"] = nil
package.loaded["moonsource_fanqie.reading"] = nil
package.loaded["moonsource_fanqie.reading.device"] = nil
package.loaded["moonsource_fanqie.settings"] = nil
Reading = require("moonsource_fanqie.reading")
Settings = require("moonsource_fanqie.settings")
row, fetch_err = nil, nil
Reading.fetchAsync(Settings:new(), "99", "1", function(data, err)
row, fetch_err = data, err
end)
Stubs.flush()
Assert.is_nil(row)
Assert.eq(fetch_err, "Request timed out after 20 secs")
Assert.eq(#state.urls, 1)
Assert.matches(state.urls[1], "registerkey")
-- 设备已缓存时取消:句柄必须落到在飞的 registerkey 上,而不是 ensureAsync 的空句柄
local held_cancels = 0
package.preload["http.request"] = function()
return {
ok = function() return true end,
header = function() return nil end,
request = function()
return { cancel = function() held_cancels = held_cancels + 1 end }
end,
}
end
package.loaded["http.request"] = nil
package.loaded["moonsource_fanqie.reading"] = nil
Reading = require("moonsource_fanqie.reading")
local delivered = false
local handle = Reading.fetchAsync(Settings:new(), "99", "1", function() delivered = true end)
Stubs.flush()
handle.cancel()
Assert.eq(held_cancels, 1)
Assert.is_false(delivered)
-- 非法 ID:下一帧回错误,不在 fetchAsync 返回前同步回调
local id_err
Reading.fetchAsync(Settings:new(), "abc", "1", function(_data, err) id_err = err end)
Assert.is_nil(id_err)
Stubs.flush()
Assert.eq(id_err, "章节 ID 无效")
+31
View File
@@ -0,0 +1,31 @@
--[[--
番茄 reading 签名向量(离线)。
@module tests.moonsource_fanqie.reading_sign_spec
--]]
local Assert = require("support.assert")
package.loaded["moonsource_fanqie.reading.sign"] = nil
package.loaded["crypto.aes"] = nil
package.loaded["crypto.sm3"] = nil
local Aes = require("crypto.aes")
local Sm3 = require("crypto.sm3")
local Sign = require("moonsource_fanqie.reading.sign")
Assert.eq(Sm3.hex(""), "1ab21d8355cfa17f8e61194831e81a8f22bec8c728fefb747ed035eb5082aa2b")
Assert.eq(Sm3.hex("abc"), "66c7f0f462eeedd9d1f2d46bdc10e4e24167c4875cf2f7a2297da02b8f4ba8e0")
Assert.eq(Aes.to_hex(Sign.derive_inner_key()):sub(1, 32), "fc78e0a9657a0c748ce51559903ccf03")
local ladon = Sign.encrypt_ladon(1789957197, Aes.from_hex("1b98ce68"))
Assert.eq(ladon, "G5jOaLRVvJuv4+NwKK5O28l5Otk8CtR/oS5UUASQ16HNqKIl")
local helios = Sign.encrypt_ladon(1789957197, Aes.from_hex("9af455f3"))
Assert.eq(helios, "mvRV81hWfK8mji4oDqkBUaKNIcydz7kADrxZKHO7vEnxeFQ/")
local argus = Sign.encrypt_argus(
"aid=1967&device_id=1", 1789949275, "3405654380789289", { rand_val = 1 })
local raw = require("utils.text").base64Decode(argus)
Assert.eq(raw:sub(1, 2), string.char(0xf2, 0x81))
Assert.eq(#raw, 194)
+227
View File
@@ -0,0 +1,227 @@
--[[--
番茄段评:统计 → 热点、评论页 → 展示项(游标翻页)、段落定位到章节 HTML。
@module tests.moonsource_fanqie.reviews_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, redundant-parameter, missing-parameter, inject-field, assign-type-mismatch, param-type-mismatch, cast-type-mismatch, return-type-mismatch, cast-local-type
local Assert = require("support.assert")
package.preload["json"] = function()
local J = require("support.json_stub")
return { encode = J.encode, decode = J.decode }
end
package.loaded["json"] = nil
local calls, reply, reply_err = {}, nil, nil
package.preload["moonsource_fanqie.reading.device"] = function()
return { ensureAsync = function(_, cb) cb({ device_id = "1", install_id = "2" }) return { cancel = function() end } end }
end
package.preload["moonsource_fanqie.reading"] = function()
return {
signedAsync = function(_device, name, path, build_query, build_body, cb)
calls[#calls + 1] = { name = name, path = path, query = build_query({}, 1), body = build_body and build_body() }
cb(reply, reply_err)
return { cancel = function() end }
end,
}
end
package.preload["moonsource_fanqie.reading.crypto"] = function()
return { build_common_query = function() return { aid = "1967" } end }
end
package.loaded["moonsource_fanqie.reviews"] = nil
local Reviews = require("moonsource_fanqie.reviews")
-- 统计:只留评论数 > 0 的段,按段序排
do
reply = { data = { data = { ["12"] = { count = 5 }, ["3"] = { count = 2 }, ["7"] = { count = 0 } } } }
local hotspots
Reviews.hotspotsAsync({}, "900", function(list) hotspots = list end)
Assert.eq(calls[1].path, "/novel/commentapi/idea/list/900/v1/")
Assert.eq(calls[1].query.compliance_status, "0")
Assert.is_nil(calls[1].body)
Assert.len(hotspots, 2)
Assert.eq(hotspots[1].range, "3")
Assert.eq(hotspots[2].total, 5)
reply, reply_err = nil, "comment_stats 空响应"
local err
Reviews.hotspotsAsync({}, "900", function(list, e) Assert.is_nil(list) err = e end)
Assert.eq(err, "comment_stats 空响应")
reply_err = nil
for _idx, data in ipairs({ {}, { data = { ["1"] = {} } } }) do
reply = { data = data }
Reviews.hotspotsAsync({}, "900", function(list, e) Assert.is_nil(list); err = e end)
Assert.matches(err, "统计", "坏响应不能覆盖缓存成空热点")
end
end
-- 评论页:POST body 带段序与游标;毫秒时间归一成秒;has_more 且游标前进才算还有
do
reply = { data = {
data_list = { { comment = {
comment_id = "c1",
common = { user_info = { base_info = { user_name = "书友" } }, content = { text = "好看", image_data_list = { image_data = {
{ web_url = "https://p3-novel.byteimg.com/tos-cn-i-abc/xyz~tplv-q:300:0.awebp?sig=1" },
{ web_url = "https://p3-novel.byteimg.com/tos-cn-i-abc/up123~tplv-q-jpeg.heic?sig=2" },
} } },
create_timestamp = 1700000000000 },
stat = { digg_count = 9, reply_count = 4 },
} } },
common_list_info = { cursor = "20", has_more = true, total = 33 },
} }
local page
Reviews.pageAsync({}, "111", "900", 12, 0, function(p) page = p end)
local call = calls[#calls]
Assert.eq(call.path, "/novel/commentapi/comment/list/900/v1/")
Assert.matches(call.body, '"para_index":12')
Assert.matches(call.body, '"cursor":""')
Assert.eq(page.items[1].author, "书友")
Assert.eq(page.items[1].content, "好看")
Assert.eq(page.items[1].likes, 9)
Assert.eq(page.items[1].replies, 4)
Assert.len(page.items[1].images, 2)
Assert.matches(page.items[1].images[1].url, "awebp%?sig=1")
Assert.eq(page.items[1].images[2].url,
"https://p3-novel.byteimg.com/tos-cn-i-abc/up123~tplv-1yzifmftcy-expand:800:0:0.webp")
Assert.eq(page.items[1].time, 1700000000)
Assert.eq(page.total, 33)
Assert.eq(page.max_idx, 20)
Assert.is_true(page.more)
Reviews.pageAsync({}, "111", "900", 12, 20, function(p) page = p end)
Assert.matches(calls[#calls].body, '"cursor":"20"')
-- 游标没前进:停,免得无限翻
Reviews.pageAsync({}, "111", "900", 12, 20, function(p) page = p end)
Assert.is_false(page.more)
-- code 为 0 却没有 data_list:风控,报错而不是「0 条」
reply = { data = { common_list_info = {} } }
local err
Reviews.pageAsync({}, "111", "900", 12, 0, function(p, e) Assert.is_nil(p) err = e end)
Assert.matches(err, "data_list")
reply = { data = { data_list = {}, common_list_info = { total = 3 } } }
Reviews.pageAsync({}, "111", "900", 12, 0, function(p, e) Assert.is_nil(p); err = e end)
Assert.matches(err, "为空", "风控空成功不删除已有热点")
reply.data.common_list_info.total = 0
Reviews.pageAsync({}, "111", "900", 12, 0, function(p) page = p end)
Assert.len(page.items, 0, "真正空列表正常返回")
Assert.is_false(page.more)
reply = { data = { data_list = { { comment = { common = {
content = { text = "甲[笑]乙[哭][笑][因果]😀" },
} } } }, common_list_info = { total = 1 } } }
Reviews.pageAsync({}, "111", "900", 12, 0, function(p) page = p end)
Assert.eq(page.items[1].content, "甲[笑]乙[哭][笑][因果]😀", "原文供引用、复制与缓存,不做破坏性替换")
Assert.matches(page.items[1].inline_images["[笑]"].url, "/1f604%.png$")
Assert.matches(page.items[1].inline_images["[哭]"].url, "/1f622%.png$")
Assert.is_nil(page.items[1].inline_images["[因果]"], "书中术语不是表情")
end
-- 回复:comment_source 必须是 5;楼中楼记被回复者;空列表且 total>0 不当成功
do
reply = { data = {
reply_list = { {
reply_id = "rp1",
reply_to_user_info = { base_info = { user_name = "楼主" } },
Common = { user_info = { base_info = { user_name = "路人" } },
content = { text = "确实[吃瓜]" }, create_timestamp = 1700000000 },
stat = { digg_count = 2, reply_count = 9 },
} },
comment_list_info = { cursor = "20", has_more = true, total = 6 },
} }
local page
Reviews.repliesAsync({}, "c1", 0, function(p) page = p end)
local call = calls[#calls]
Assert.eq(call.name, "reply_list")
Assert.eq(call.path, "/novel/commentapi/reply/list/c1/v1/")
Assert.matches(call.body, '"comment_source":5')
Assert.matches(call.body, '"cursor":""')
Assert.eq(page.items[1].author, "路人")
Assert.eq(page.items[1].content, "确实[吃瓜]")
Assert.matches(page.items[1].inline_images["[吃瓜]"].url, "/1f349%.png$", "回复与主评论共用表情映射")
Assert.eq(page.items[1].reply_to, "楼主")
Assert.eq(page.items[1].replies, 0, "回复页不再往下开")
Assert.eq(page.items[1].likes, 2)
Assert.eq(page.total, 6)
Assert.eq(page.max_idx, "20")
Assert.is_true(page.more)
Reviews.repliesAsync({}, "c1", "20", function(p) page = p end)
Assert.matches(calls[#calls].body, '"cursor":"20"')
Assert.is_false(page.more, "游标停住就不再翻")
reply = { data = { reply_list = {}, comment_list_info = { total = 3, has_more = false, cursor = "" } } }
local err
Reviews.repliesAsync({}, "c1", 0, function(p, e) Assert.is_nil(p) err = e end)
Assert.matches(err, "为空")
reply = { data = {} }
Reviews.repliesAsync({}, "c1", 0, function(p, e) Assert.is_nil(p) err = e end)
Assert.matches(err, "reply_list")
end
do -- 同步设备桩不能把正在请求的句柄覆盖掉;关闭后忽略迟到回包。
local Device = require("moonsource_fanqie.reading.device")
local Reading = require("moonsource_fanqie.reading")
local ensure, signed = Device.ensureAsync, Reading.signedAsync
local pending_device, pending_response
local registration_cancelled, request_cancelled, received = false, false, false
local signed_calls = 0
Reading.signedAsync = function(_device, _name, _path, _query, _body, cb)
signed_calls = signed_calls + 1
pending_response = cb
return { cancel = function() request_cancelled = true end }
end
local job = Reviews.hotspotsAsync({}, "900", function() received = true end)
job.cancel()
Assert.is_true(request_cancelled, "同步注册回调后取消实际段评请求")
pending_response({ data = { data = {} } })
Assert.is_false(received, "窗口关闭后不接受迟到响应")
Device.ensureAsync = function(_settings, cb)
pending_device = cb
return { cancel = function() registration_cancelled = true end }
end
request_cancelled = false
job = Reviews.hotspotsAsync({}, "900", function() received = true end)
job.cancel()
Assert.is_true(registration_cancelled)
pending_device({})
Assert.is_false(request_cancelled)
Assert.eq(signed_calls, 1, "取消注册后迟到回调不得启动段评请求")
Assert.is_false(received)
job = Reviews.hotspotsAsync({}, "900", function() received = true end)
pending_device({})
Assert.eq(signed_calls, 2, "异步注册正常进入段评请求")
job.cancel()
Assert.is_true(request_cancelled, "异步注册完成后取消当前请求")
pending_response({ data = { data = {} } })
Assert.is_false(received)
Device.ensureAsync, Reading.signedAsync = ensure, signed
end
-- 定位:按段序找 blk p_idx 对应段落,xpointer 覆盖整段;整段原文作引用
do
local html = '<html><body>'
.. '<p idx="0" p_idx="40000"><blk p_idx="0">开头一段话。</blk></p>'
.. '<p idx="1" p_idx="40001"><blk p_idx="1">第二段里有一句被很多人评论的话。</blk></p>'
.. '</body></html>'
local spots = Reviews.locate({
{ range = "1", text = "", total = 4 },
{ range = "9", text = "", total = 1 },
}, html)
Assert.len(spots, 1)
Assert.eq(spots[1].range, "1")
Assert.eq(spots[1].total, 4)
Assert.eq(spots[1].badge, "4")
Assert.eq(spots[1].text, "第二段里有一句被很多人评论的话。")
Assert.matches(spots[1].pos0, "%.%d+$")
Assert.matches(spots[1].pos1, "%.%d+$")
end
return true
+30
View File
@@ -0,0 +1,30 @@
--[[--
番茄设置页:扫码入口与段评开关,不含 Cookie / 浏览器登录。
@module tests.moonsource_fanqie.setting_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
package.loaded["ui.themes.widgets.row"] = { widget = function(spec) return spec end }
local cfg = {}
package.loaded["utils.settings"] = {
getSource = function() return cfg end,
saveSource = function(_id, value) if value then cfg = value end end,
}
package.loaded["source.category_setting"] = {
row = function() return function(iw) return { title = "分类", width = iw } end end,
}
package.loaded["moonsource_fanqie.setting"] = nil
local Setting = require("moonsource_fanqie.setting")
Assert.is_nil(Setting.browser)
local rows = Setting.rows()
Assert.eq(rows[1](400).title, "番茄账号与登录")
Assert.eq(rows[2](400).title, "显示段评")
for _idx, factory in ipairs(rows) do
local row = factory(400)
Assert.is_true(row.title ~= "浏览器登录" and row.title ~= "粘贴 Cookie")
end
+27
View File
@@ -0,0 +1,27 @@
--[[--
番茄 settings:登录判定必须以 sessionid 为准。
@module tests.moonsource_fanqie.settings_spec
--]]
local Assert = require("support.assert")
local cfg = {}
package.preload["utils.settings"] = function()
return {
getSource = function() return cfg end,
saveSource = function(_, value) cfg = value end,
}
end
package.loaded["moonsource_fanqie.settings"] = nil
local Settings = require("moonsource_fanqie.settings")
cfg = { cookies = { novel_web_id = "1", s_v_web_id = "2" } }
Assert.is_true(not Settings:new():is_cookie_configured())
cfg = { cookies = { sessionid = "" } }
Assert.is_true(not Settings:new():is_cookie_configured())
cfg = { cookies = { sessionid = "abc", novel_web_id = "1" } }
Assert.is_true(Settings:new():is_cookie_configured())
+152
View File
@@ -0,0 +1,152 @@
--[[--
番茄目录:读缓存和刷新都不再扫章节 HTML;锚点只在新下正文时写入,刷新时按 uid 保留。
@module tests.moonsource_fanqie.toc_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, redundant-parameter, missing-parameter, inject-field, assign-type-mismatch, param-type-mismatch, cast-type-mismatch, return-type-mismatch, cast-local-type
local Assert = require("support.assert")
local Stubs = require("support.stubs")
local Paths = require("utils.paths")
local Toc = require("source.toc")
local html_reads = 0
local open = io.open
io.open = function(path, mode, ...)
if type(path) == "string" and path:match("/%d+%.html$") and (mode == nil or tostring(mode):match("^r")) then
html_reads = html_reads + 1
end
return open(path, mode, ...)
end
local directory, content
local src = require("moonsource_fanqie.source").new()
src.client.fetchChapterDirectoryAsync = function(_self, _id, cb)
require("ui/uimanager"):nextTick(function() cb(directory) end)
return { cancel = function() end }
end
src.client.officialGetContentAsync = function(_self, _bid, _iid, cb)
require("ui/uimanager"):nextTick(function() cb(content) end)
return { cancel = function() end }
end
local identity = { source_id = "ext.fanqie", stable_id = "fanqie-toc-anchors" }
local poison = '<h2 id="toc_99">不该扫到</h2><p>旧正文</p>'
local function writeChapterHtml(idx, html)
Paths.ensureBookWork(identity.stable_id, identity.source_id)
local file = assert(open(Paths.chapterPath(identity.stable_id, idx, identity.source_id), "w"))
file:write(html)
file:close()
end
local function loadToc()
local toc, err
src:loadTocAsync(identity, function(value, reason) toc, err = value, reason end)
Stubs.flush()
return toc, err
end
local function refreshToc()
local toc, err
src:refreshTocAsync(identity, function(value, reason) toc, err = value, reason end)
Stubs.flush()
return toc, err
end
local function fetchContent(chapter)
local Chapter = require("source.chapter")
local ops
local orig = Chapter.openAsync
Chapter.openAsync = function(_source, _identity, _book, _opts, options, cb)
ops = options
if cb then cb("ok") end
return { cancel = function() end }
end
src:openBookAsync(identity, { chapter_idx = 1 }, function() end)
Chapter.openAsync = orig
local payload, err
ops.fetchContent(identity, chapter, function(value, reason) payload, err = value, reason end)
Stubs.flush()
return payload, err
end
Toc.drop(identity.source_id, identity.stable_id)
writeChapterHtml(1, poison)
writeChapterHtml(2, poison)
-- 有缓存时 loadToc 直接返回,不读章节 HTML,也不为回填锚点写库。
Assert.is_true(Toc.put(identity.source_id, identity.stable_id, {
{ idx = 1, uid = "10", title = "正文", depth = 1 },
{ idx = 2, uid = "20", title = "第二章", depth = 1 },
}))
html_reads = 0
local puts = 0
local orig_put = Toc.put
Toc.put = function(...)
puts = puts + 1
return orig_put(...)
end
local cached, load_err = loadToc()
Toc.put = orig_put
Assert.is_nil(load_err)
Assert.eq(cached[1].uid, "10")
Assert.is_nil(cached[1].anchors, "读缓存不能靠扫 HTML 补锚点")
Assert.is_nil(cached[2].anchors)
Assert.eq(html_reads, 0, "有缓存时不能打开章节 HTML")
Assert.eq(puts, 0, "读缓存目录不必 Toc.put")
-- 刷新保留库里已有的 HTML 锚点,同时收下官方锚点,且不扫 HTML。
Assert.is_true(orig_put(identity.source_id, identity.stable_id, {
{
idx = 1, uid = "10", title = "正文", depth = 1,
anchors = {
{ title = "已缓存第一节", depth = 2, id = "toc_1" },
{ title = "HTML锚点", depth = 2, id = "toc_8" },
},
},
{ idx = 2, uid = "20", title = "第二章", depth = 1, anchors = { { title = "旧章锚点", depth = 2, id = "toc_9" } } },
}))
directory = { data = { chapterList = {
{ itemId = "10", title = "正文", children = {
{ title = "官方第一节", anchor = "toc_1" },
{ title = "官方第二节", id = "toc_2" },
} },
{ itemId = "20", title = "第二章" },
{ itemId = "30", title = "第三章" },
} } }
html_reads = 0
local refreshed, refresh_err = refreshToc()
Assert.is_nil(refresh_err)
Assert.eq(html_reads, 0, "刷新目录不能打开章节 HTML")
Assert.len(refreshed, 3)
Assert.eq(refreshed[1].anchors[1].title, "官方第一节", "同 id 保留官方标题")
Assert.eq(refreshed[1].anchors[2].id, "toc_2")
Assert.eq(refreshed[1].anchors[3].id, "toc_8", "库里已有的 HTML 锚点不能被刷新冲掉")
Assert.eq(refreshed[1].anchors[3].title, "HTML锚点")
Assert.len(refreshed[1].anchors, 3)
Assert.eq(refreshed[2].anchors[1].id, "toc_9")
Assert.eq(refreshed[2].anchors[1].title, "旧章锚点")
Assert.is_nil(refreshed[3].anchors, "新章没有旧锚点")
local stored = Toc.read(identity.source_id, identity.stable_id)
Assert.eq(stored[1].anchors[1].title, "官方第一节")
Assert.eq(stored[1].anchors[3].id, "toc_8")
Assert.eq(stored[2].anchors[1].id, "toc_9")
-- 拉正文后 persistAnchorsFromHtml 仍按章把锚点写进目录。
content = { title = "第二章", content = '<h2 id="toc_3">新下的节</h2><p>新正文</p><h2 id="toc_4"></h2>' }
html_reads = 0
local payload, fetch_err = fetchContent({ idx = 2, uid = "20", title = "第二章", depth = 1 })
Assert.is_nil(fetch_err)
Assert.matches(payload.html, "新下的节")
local after = Toc.read(identity.source_id, identity.stable_id)
Assert.eq(after[2].anchors[1].id, "toc_9", "按章写入不能丢掉已有锚点")
Assert.eq(after[2].anchors[2].id, "toc_3")
Assert.eq(after[2].anchors[2].title, "新下的节")
Assert.eq(after[2].anchors[3].id, "toc_4")
Assert.eq(after[2].anchors[3].title, "#4")
Assert.eq(after[1].anchors[3].id, "toc_8", "只写本章,不动其它章")
Assert.eq(html_reads, 0, "按章写入走内存 HTML,不必再读落盘文件")
Toc.drop(identity.source_id, identity.stable_id)
io.open = open