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

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

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

No files matched your search

+76
View File
@@ -0,0 +1,76 @@
--[[--
知乎书城榜单与分类节点,长篇目录接入。
@module tests.moonsource_zhihu.browse_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local selected, failure, called, cancelled
local catalog = {
data = { { id = "22", title = "第一章", is_free = true, section_cell = { type = "article" } } },
extra = { title = "长篇标题", tab_artwork = "https://img/column.jpg" },
}
package.loaded["moonsource_zhihu.client"] = {
browseAsync = function(rank, filter, cb)
selected = rank .. ":" .. filter
cb(not failure and { { source_id = "ext.zhihu", stable_id = "1/2", title = "条目" } } or nil, failure, {
{ key = "0", name = "全部" }, { key = "12", name = " 脑洞 " }, { key = "999", name = "新分类" },
})
return { cancel = function() cancelled = true end }
end,
catalogAsync = function(id, cb) called = id; cb(catalog); return {} end,
detailAsync = function(id, cb)
called = "detail:" .. id
cb({ source_id = "ext.zhihu", stable_id = id, title = "长篇标题", authors = "作者",
cover = "https://img/column.jpg", intro = "完整简介", meta = { rating = { score = 8.9, by = "ext.zhihu" } } })
return {}
end,
simpleAsync = function() error("长篇不能调用单节接口") end,
}
local saved
package.loaded["source.toc"] = {
read = function() end,
put = function(source_id, stable_id, chapters)
saved = { source_id = source_id, stable_id = stable_id, chapters = chapters }
return true
end,
}
package.loaded["book.store"] = { rememberDetail = function(book) return book end }
local source = require("moonsource_zhihu.source").new()
local result, err
source:browseAsync(nil, function(value, reason) result, err = value, reason end)
Assert.eq(selected, "recommend:0")
Assert.eq(result.groups[1].active, "recommend:0")
Assert.eq(result.groups[2].active, "recommend:0")
Assert.len(result.data, 1)
local handle = source:browseAsync({ node = "hot_search:12" }, function(value, reason) result, err = value, reason end)
Assert.eq(selected, "hot_search:12")
Assert.eq(result.groups[1].active, "hot_search:0")
Assert.eq(result.groups[2].active, "hot_search:12")
Assert.eq(result.groups[2].chips[2].title, "脑洞")
Assert.eq(result.groups[2].chips[3].id, "hot_search:999", "分类使用官网配置,不维护第二份分类表")
handle.cancel()
Assert.is_true(cancelled)
source:browseAsync({ node = "unknown:0" }, function(value) result = value end)
Assert.eq(selected, "recommend:0")
failure = "network failed"
source:browseAsync({ node = "well:0" }, function(value, reason) result, err = value, reason end)
Assert.is_nil(result)
Assert.eq(err, failure)
failure = nil
local identity = { source_id = "ext.zhihu", stable_id = "11" }
source:loadTocAsync(identity, function(value) result = value end)
Assert.eq(called, "11")
Assert.eq(result[1].uid, "22")
Assert.eq(saved.stable_id, "11")
Assert.eq(saved.source_id, "ext.zhihu")
source:getDetailAsync(identity, function(value) result = value end)
Assert.eq(called, "detail:11", "详情走书籍接口,不用目录的精简元数据或榜单片段")
Assert.eq(result.stable_id, "11")
Assert.eq(result.title, "长篇标题")
Assert.eq(result.cover, "https://img/column.jpg")
Assert.eq(result.authors, "作者")
Assert.eq(result.intro, "完整简介")
Assert.eq(result.meta.rating.score, 8.9)
+76
View File
@@ -0,0 +1,76 @@
--[[--
知乎长篇目录:有序分页、失败原子性、取消与章节权限。
@module tests.moonsource_zhihu.catalog_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_zhihu.mapper")
local function chapter(id, title, extra)
local row = { id = id, title = title, section_cell = { type = "article" } }
for key, value in pairs(extra or {}) do row[key] = value end
return row
end
local first = {
data = { chapter("2", "第一章", { is_free = true }), chapter("3", "第二章") },
extra = { title = "长篇", tab_artwork = "https://img/cover.jpg" },
paging = { offset = 0, limit = 2, has_next = true, is_end = false },
}
local last = {
data = { chapter("4", "第三章", { right = { has_ownership = true } }) },
paging = { offset = 2, limit = 2, has_next = false, is_end = true },
}
local pending, sync_first, cancelled = {}, false, false
package.loaded["http.request"] = {
get = function(url, opts, cb)
if sync_first and url:find("offset=0", 1, true) then
cb(JSON.encode(first), nil, { code = 200 })
return { cancel = function() error("取消不能指向已经完成的第一页") end }
end
pending[#pending + 1] = { url = url, opts = opts, cb = cb }
return { cancel = function() cancelled = true end }
end,
}
local Client = require("moonsource_zhihu.client")
local result, err, calls = nil, nil, 0
local function done(value, reason) result, err, calls = value, reason, calls + 1 end
Client.catalogAsync("1", done)
Assert.matches(pending[1].url, "/remix/well/1/catalog%?")
Assert.matches(pending[1].url, "order_by=global_idx")
pending[1].cb(JSON.encode(first))
Assert.eq(calls, 0, "目录没拉完之前不暴露部分结果")
Assert.matches(pending[2].url, "offset=2$")
pending[2].cb(JSON.encode(last))
Assert.eq(calls, 1)
Assert.is_nil(err)
local toc = Mapper.chapters(result, "1")
Assert.len(toc, 3)
Assert.eq(toc[1].uid, "2")
Assert.eq(toc[3].uid, "4")
Assert.eq(toc[3].idx, 3)
Assert.is_false(toc[1].vip)
Assert.is_true(toc[2].vip)
Assert.is_false(toc[3].vip)
Assert.is_nil(Mapper.chapters({ data = { chapter("", "坏章节") } }, "1"))
Client.catalogAsync("1", done)
pending[#pending].cb(JSON.encode(first))
pending[#pending].cb(nil, "network failed")
Assert.is_nil(result)
Assert.eq(err, "network failed", "后一页失败不能返回前面的半本目录")
Client.catalogAsync("1", done)
local broken = { data = first.data, paging = { has_next = true, offset = 0, limit = 0 } }
pending[#pending].cb(JSON.encode(broken))
Assert.is_nil(result)
Assert.not_nil(err, "分页不前进时必须失败,不能无限请求")
sync_first = true
local handle = Client.catalogAsync("1", done)
local before = calls
handle.cancel()
Assert.is_true(cancelled, "同步完成第一页后,取消仍指向在途的下一页")
pending[#pending].cb(JSON.encode(last))
Assert.eq(calls, before)
+181
View File
@@ -0,0 +1,181 @@
--[[--
知乎盐选:榜单、搜索、折叠判断和签名正文接口。
@module tests.moonsource_zhihu.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_zhihu.mapper")
local story_url = "https://www.zhihu.com/market/paid_column/1580618311758471168/section/1598363011911184384"
local feed = {
data = { {
module_type = "billboard",
module_data = { data = { data = { {
head = { type = "recommend", filters = { { key = "0", name = "全部" } } },
content_list = { {
title = "红包不能抢",
url = story_url,
artwork = "https://img/a.jpg",
description = "预览",
} },
} } } },
} },
}
local found = Mapper.feed(feed, "recommend")
Assert.eq(found[1].stable_id, "1580618311758471168/1598363011911184384")
Assert.eq(found[1].title, "红包不能抢")
Assert.eq(found[1].cover, "https://img/a.jpg")
Assert.eq(found[1].intro, "预览")
Assert.eq(#found, 1)
Assert.is_nil(Mapper.feed({ data = {} }, "recommend"), "缺少榜单不能当作空榜单")
Assert.is_nil(Mapper.feed({ error = { code = 1 } }, "recommend"))
local ranked_rows = feed.data[1].module_data.data.data
ranked_rows[2] = {
head = { type = "hot", filters = {} },
content_list = { { title = "热度榜条目", url = "https://www.zhihu.com/market/paid_column/3/section/4" } },
}
local entries = ranked_rows[1].content_list
entries[2] = { title = "第二名", url = "https://www.zhihu.com/market/paid_column/5/section/6" }
entries[3] = { title = "重复首位", url = story_url }
entries[4] = { title = "长篇", url = "https://www.zhihu.com/xen/market/remix/paid_column/7", description = "正文试读片段" }
feed.data[2] = { module_type = "feed_card", module_data = { data = { content_list = {
{ title = "推荐流", url = "https://www.zhihu.com/market/paid_column/8/section/9" },
} } } }
found = Mapper.feed(feed, "recommend")
Assert.len(found, 3, "只取所选榜单,不混入推荐流或其它榜单")
Assert.eq(found[1].title, "红包不能抢")
Assert.eq(found[2].title, "第二名")
Assert.eq(found[3].stable_id, "7", "长篇不能因没有节 id 被丢掉")
Assert.is_nil(found[3].intro, "长篇榜单给的是正文试读片段,不能存成书籍简介")
Assert.eq(Mapper.feed(feed, "hot")[1].title, "热度榜条目")
ranked_rows[2].content_list = {}
Assert.len(Mapper.feed(feed, "hot"), 0, "合法空榜单保留筛选项")
local searched = Mapper.search({
data = { {
type = "knowledge_ad",
object = {
url = story_url .. "?km_channel=search",
body = { title = "<em>红包</em>不能抢", authors = { { name = "向南天" } }, images = { "https://img/b.jpg" }, description = "简介" },
},
} },
})
Assert.eq(searched[1].title, "红包不能抢")
Assert.eq(searched[1].authors, "向南天")
Assert.eq(searched[1].cover, "https://img/b.jpg")
Assert.eq(searched[1].intro, "简介")
local simple = {
is_fold = false,
section = { id = "1598363011911184384", title = "红包不能抢", head_artwork = "https://img/c.jpg" },
paid_column = { title = "专栏", artwork = "https://img/d.jpg" },
}
local toc = Mapper.chapters(simple, "1580618311758471168/1598363011911184384")
Assert.eq(toc[1].uid, "1598363011911184384")
Assert.eq(toc[1].vip, false)
Assert.eq(toc[1].toc_version, Mapper.TOC_VERSION)
local folded = Mapper.chapters({ is_fold = true, section = { title = "红包不能抢" } }, "1/2")
Assert.eq(folded[1].vip, true)
local detail = Mapper.detail(simple, "1580618311758471168/1598363011911184384")
Assert.eq(detail.cover, "https://img/c.jpg")
Assert.eq(detail.source_id, "ext.zhihu")
local requests = {}
local request_options = {}
local me_body = Json.encode({ id = "fixture-user", name = "甲" })
local me_error
local response_code = 200
package.preload["http.request"] = function()
return {
get = function(url, options, callback)
requests[#requests + 1] = url
request_options[#request_options + 1] = options
if url:find("/api/v4/me", 1, true) then
callback(me_body, me_error, { code = response_code })
elseif response_code == 401 then
callback(nil, "HTTP 401", { code = response_code })
elseif url:find("/api/v4/search_v3", 1, true) then
callback(Json.encode({ data = { { object = { url = story_url, body = { title = "红包不能抢" } } } } }), nil, nil)
elseif url:find("/vip_tab/svip_story", 1, true) then
callback(Json.encode(feed), nil, nil)
elseif url:find("/manuscript/simple", 1, true) then
callback(Json.encode(simple), nil, nil)
elseif url:find("/manuscript?", 1, true) then
callback(Json.encode({ is_fold = false, manuscript = "<p>甲</p>" }), nil, nil)
else
callback(nil, "miss", nil)
end
return { cancel = function() end }
end,
}
end
package.loaded["http.request"] = nil
package.loaded["moonsource_zhihu.client"] = nil
local Client = require("moonsource_zhihu.client")
local books
Client.searchAsync("红包", function(list) books = list end)
Assert.eq(books[1].stable_id, "1580618311758471168/1598363011911184384")
Assert.is_true(requests[#requests]:find("t=km_general", 1, true) ~= nil)
local ranked
Client.browseAsync("recommend", "12", function(list) ranked = list end)
Assert.eq(ranked[1].title, "红包不能抢")
Assert.matches(requests[#requests], "modules=billboard&billboard_type=recommend&billboard_filter=12&offset=0&limit=10$")
Assert.is_nil(requests[#requests]:find("feed_card", 1, true))
Assert.eq(request_options[#request_options].headers.Referer, "https://www.zhihu.com/fiore/h5/vip-web")
local wire
Client.simpleAsync("1580618311758471168/1598363011911184384", function(value) wire = value end)
Assert.eq(wire.section.title, "红包不能抢")
Assert.matches(request_options[#request_options].headers["User-Agent"], "Chrome/")
local content
Client.contentAsync("1580618311758471168/1598363011911184384", function(value) content = value end)
Assert.eq(content, "<p>甲</p>")
Assert.matches(requests[#requests], "/manuscript%?v=1&manuscript_version=0$")
Assert.eq(request_options[#request_options].headers["x-zse-93"], "101_3_3.1")
Assert.matches(request_options[#request_options].headers["x-zse-96"], "^2%.0_.+")
local Settings = require("utils.settings")
local cfg = Settings.getSource("ext.zhihu")
cfg.cookie = "z_c0=saved"
local verified, verify_error
Client.loginCheckAsync("z_c0=candidate", function(ok, err) verified, verify_error = ok, err end)
Assert.is_true(verified)
Assert.is_nil(verify_error)
Assert.eq(request_options[#request_options].headers.Cookie, "z_c0=candidate")
Assert.eq(cfg.cookie, "z_c0=saved", "校验新 Cookie 不能修改已保存的账号")
for _idx, body in ipairs({ "{}", "<html>登录</html>", '{"error":{"code":100}}', '{"id":""}', '{"id":false}' }) do
me_body = body
Client.loginCheckAsync("z_c0=invalid", function(ok, err) verified, verify_error = ok, err end)
Assert.is_false(verified)
Assert.is_true(verify_error ~= nil)
Assert.eq(cfg.cookie, "z_c0=saved")
end
me_body, me_error = nil, "network down"
Client.loginCheckAsync("z_c0=candidate", function(ok, err) verified, verify_error = ok, err end)
Assert.is_false(verified)
Assert.eq(verify_error, "network down")
Client.contentAsync("1580618311758471168/1598363011911184384", function(value) content = value end)
Assert.eq(content, "<p>甲</p>")
Assert.eq(request_options[#request_options].headers.Cookie, "z_c0=saved", "已购正文请求必须携带登录态")
Client.searchAsync("红包", function() end)
Assert.eq(request_options[#request_options].headers.Cookie, "z_c0=saved")
local Auth = require("source.auth")
Auth.reset()
response_code = 401
Client.searchAsync("红包", function(_books, err) verify_error = err end)
Assert.is_true(Auth.expired("ext.zhihu"))
Assert.eq(verify_error, "知乎登录已失效,请重新登录")
cfg.cookie = nil
Settings.saveSource("ext.zhihu")
Auth.reset()
+96
View File
@@ -0,0 +1,96 @@
--[[--
知乎章末排版:备案号清理、缓存升级、正文坐标与失败时的原文件保护。
@module tests.moonsource_zhihu.content_layout_spec
--]]
local Assert = require("support.assert")
local Config = require("support.config")
local Content = require("moonsource_zhihu.content")
local Fs = require("utils.fs")
local prefix = '<html><body><p data-block-key="keep">正文里的备案号说明不能删。</p>'
local watermark = '<span id="vipyxcode" style="opacity:0.5">备美号:YXXBfixture</span>'
local raw = prefix .. "<p>" .. watermark .. "</p></body></html>"
local html = Content.prepare(raw)
Assert.is_true(html:find(prefix, 1, true) ~= nil, "前面的原文节点和属性逐字保留")
Assert.is_nil(html:find("vipyxcode", 1, true))
Assert.is_nil(html:find("YXXBfixture", 1, true), "按稳定的元素 id 清理,不依赖可能被字体扰乱的文字")
Assert.is_true(html:find("<p></p>", 1, true) ~= nil, "保留空段落,不挪动其它节点编号")
Assert.is_true(html:find(Content.FOOTER .. "</body>", 1, true) ~= nil)
Assert.eq(Content.prepare(html), html, "重开书不能重复追加章评区")
local path = Config.dir() .. "/zhihu_layout_fixture.html"
local file = assert(io.open(path, "wb")); assert(file:write(raw)); file:close()
Assert.is_true(Content.reuse(path))
Assert.eq(Fs.read(path), html, "旧章节离线原地升级,不重新下载正文")
Assert.is_true(Content.reuse(path))
Assert.is_nil(io.open(path .. ".part", "rb"))
os.remove(path)
local archive = {
{ path = "mimetype", data = "application/epub+zip", mode = "file" },
{ path = "META-INF/container.xml", data = "<container/>", mode = "file" },
{ path = "OEBPS/chapter_001.xhtml", data = prefix .. "</body></html>", mode = "file" },
{ path = "OEBPS/chapter_002.xhtml",
data = '<html><body><p id="last">结尾正文。</p><p>备美号:YXXBfixture</p></body></html>', mode = "file" },
}
local copied, compression, fail_write, writes = {}, {}, false, 0
package.loaded["ffi/archiver"] = {
Reader = { new = function()
return {
open = function() return true end,
close = function() end,
iterate = function()
local idx = 0
return function() idx = idx + 1; return archive[idx] end
end,
extractToMemory = function(_reader, name)
for _idx, entry in ipairs(archive) do if entry.path == name then return entry.data end end
end,
}
end },
Writer = { new = function()
local writer = {}
function writer:open(dest)
self.path = dest
copied, compression = {}, {}
writes = writes + 1
return true
end
function writer:setZipCompression(method) self.compression = method end
function writer:addFileFromMemory(name, data)
if fail_write then self.err = "disk full"; return false end
copied[name], compression[name] = data, self.compression
return true
end
function writer:close()
local output = assert(io.open(self.path, "wb"))
output:write("rewritten archive"); output:close()
end
return writer
end },
}
path = Config.dir() .. "/zhihu_layout_fixture.epub"
file = assert(io.open(path, "wb")); file:write("original archive"); file:close()
local ok, err = Content.upgradeStory(path, raw)
Assert.is_true(ok)
Assert.is_nil(err)
Assert.eq(compression.mimetype, "store")
Assert.eq(copied["OEBPS/chapter_001.xhtml"], archive[3].data, "原有分片不重新排版")
Assert.is_true(copied["OEBPS/chapter_002.xhtml"]:find('<p id="last">结尾正文。</p>', 1, true) ~= nil)
Assert.is_nil(copied["OEBPS/chapter_002.xhtml"]:find("YXXBfixture", 1, true))
Assert.is_true(copied["OEBPS/chapter_002.xhtml"]:find(Content.FOOTER, 1, true) ~= nil)
Assert.eq(copied["META-INF/container.xml"], "<container/>")
local before = writes
local original_last = archive[4].data
archive[4].data = copied["OEBPS/chapter_002.xhtml"]
Assert.is_true(Content.upgradeStory(path, raw))
Assert.eq(writes, before, "已升级的 EPUB 不再重写")
archive[4].data = original_last
fail_write = true
ok, err = Content.upgradeStory(path, raw)
Assert.is_nil(ok)
Assert.eq(err, "disk full")
Assert.eq(Fs.read(path), "rewritten archive", "失败时不能删掉上一次完整的 EPUB")
Assert.is_nil(io.open(path .. ".part", "rb"))
os.remove(path)
+118
View File
@@ -0,0 +1,118 @@
--[[--
盐选正文权限、错误与 HTTP → 字体任务的取消所有权。
@module tests.moonsource_zhihu.content_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local Json = require("support.json_stub")
package.preload["json"] = function() return Json end
local response, response_err, http_pending, font_pending
local http_cb, font_cb, requested_path, signed_cookie, request_options
local calls, http_cancelled, font_cancelled = 0, 0, 0
package.preload["moonsource_zhihu.sign"] = function()
return { headers = function(path, cookie)
requested_path, signed_cookie = path, cookie
return { ["x-zse-96"] = "fixture" }
end }
end
package.preload["http.request"] = function()
return { get = function(url, options, cb)
request_options = options
Assert.eq(url, "https://api.zhihu.com" .. requested_path)
http_cb = cb
if not http_pending then cb(response, response_err) end
return { cancel = function() http_cancelled = http_cancelled + 1 end }
end }
end
package.preload["moonsource_zhihu.font"] = function()
return { restoreAsync = function(wire, cb)
calls = calls + 1
Assert.eq(wire.use_font, true)
font_cb = cb
if not font_pending then cb("<p>还原正文</p>") end
local job = {}
function job:cancel()
Assert.eq(self, job, "字体 Job 使用冒号取消")
font_cancelled = font_cancelled + 1
end
return job
end }
end
local Settings = require("utils.settings")
Settings.getSource("ext.zhihu").cookie = 'z_c0=saved; d_c0="fixture|1"'
local Client = require("moonsource_zhihu.client")
local value, error_message, completed
local function fetch()
value, error_message, completed = nil, nil, 0
return Client.contentAsync("1/2", function(html, err)
value, error_message = html, err
completed = completed + 1
end)
end
response = Json.encode({ is_fold = false, authentication_result = true, manuscript = "<p>正文</p>" })
fetch()
Assert.eq(value, "<p>正文</p>")
Assert.eq(requested_path, "/remix-web/paid_columns/1/sections/2/manuscript?v=1&manuscript_version=0")
Assert.eq(signed_cookie, Settings.getSource("ext.zhihu").cookie)
Assert.eq(request_options.headers.Cookie, signed_cookie)
Assert.eq(request_options.headers["x-zse-96"], "fixture")
Assert.eq(calls, 0, "没有乱序字体的章节不创建字体任务")
for _idx, denied in ipairs({
{ is_fold = true, manuscript = "<p>付费预览</p>", use_font = true },
{ is_fold = false, authentication_result = false, manuscript = "<p>付费预览</p>" },
}) do
response = Json.encode(denied)
fetch()
Assert.is_nil(value)
Assert.eq(error_message, "本章未购买")
end
Assert.eq(calls, 0, "拒绝权限后不能还原或缓存预览")
for _idx, invalid in ipairs({ "{}", "<html>风控</html>",
'{"is_fold":false,"manuscript":""}', '{"error":{"code":10003}}' }) do
response = invalid
fetch()
Assert.is_nil(value)
Assert.eq(error_message, "请求失败")
end
response, response_err = nil, "HTTP 403"
fetch()
Assert.is_nil(value)
Assert.eq(error_message, "HTTP 403")
response_err = nil
response = Json.encode({ is_fold = false, manuscript = "<p>乱序</p>", use_font = true })
font_pending = true
local handle = fetch()
Assert.eq(completed, 0)
handle.cancel()
Assert.eq(http_cancelled, 0, "同步 HTTP 回调不能用已结束请求覆盖正在还原的 Job")
Assert.eq(font_cancelled, 1)
font_cb("<p>迟到正文</p>")
Assert.eq(completed, 0)
handle = fetch()
font_cb(nil, "字体失败")
Assert.eq(error_message, "字体失败")
Assert.eq(completed, 1)
handle.cancel()
Assert.eq(font_cancelled, 1, "字体完成后不再持有任务")
font_pending = false
handle = fetch()
Assert.eq(value, "<p>还原正文</p>")
handle.cancel()
Assert.eq(font_cancelled, 1, "同步字体回调也不能留下完成句柄")
http_pending = true
handle = fetch()
handle.cancel()
Assert.eq(http_cancelled, 1)
http_cb(response)
Assert.eq(completed, 0, "取消 HTTP 后忽略迟到响应")
Settings.getSource("ext.zhihu").cookie = nil
+98
View File
@@ -0,0 +1,98 @@
--[[--
知乎详情:作者、完整分段简介、SKU 评分,以及异步链取消。
@module tests.moonsource_zhihu.detail_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_zhihu.mapper")
local wire = {
id = "11", sku_id = "99", title = "作品",
authors = { { user = { name = "作者甲" } }, { name = "作者乙" } },
artwork = "https://img/cover.jpg",
keypoint = "<p>宣传语 &amp; 引言</p>",
content = "<p>第一段。</p><p>第二段:完整简介结尾。</p>",
contents = { { title = "第一章", content = "正文试读不是简介" } },
}
local grading = { show_score = true, score = "8.9", grading_count = 902 }
local book = Mapper.detail(wire, "11", grading)
Assert.eq(book.authors, "作者甲、作者乙")
Assert.eq(book.intro, "宣传语 & 引言\n\n第一段。\n第二段:完整简介结尾。")
Assert.eq(book.cover, wire.artwork)
Assert.eq(book.meta.rating.score, 8.9)
Assert.eq(book.meta.rating.by, "ext.zhihu")
Assert.is_nil(Mapper.detail({ error = { code = 1 }, title = "错误" }, "11"))
Assert.is_nil(Mapper.detail(wire, "11", { show_score = false, score = "8.9" }).meta)
Assert.is_nil(Mapper.detail(wire, "11", { show_score = true, score = "11" }).meta)
Assert.eq(Mapper.detail({ title = "无简介", contents = wire.contents }, "11").intro, "",
"不能把试读内容补成简介")
local pending, sync_detail, cancelled = {}, false, false
package.loaded["http.request"] = {
get = function(url, opts, cb)
if sync_detail and url:find("/remix/paid_columns/", 1, true) then
cb(JSON.encode(wire), nil, { code = 200 })
return { cancel = function() error("不能取消已完成的详情请求") end }
end
pending[#pending + 1] = { url = url, opts = opts, cb = cb }
return { cancel = function() cancelled = true end }
end,
}
local Settings = require("utils.settings")
Settings.getSource("ext.zhihu").cookie = "z_c0=fixture"
local Client = require("moonsource_zhihu.client")
local result, err, calls = nil, nil, 0
local function done(value, reason) result, err, calls = value, reason, calls + 1 end
Client.detailAsync("11", done)
Assert.matches(pending[1].url, "/remix/paid_columns/11%?is_new_column=true&is_web=true$")
Assert.eq(pending[1].opts.headers.Cookie, "z_c0=fixture")
pending[1].cb(JSON.encode(wire))
Assert.eq(calls, 0)
Assert.matches(pending[2].url, "/darwin/sku_grading/99$", "评分用 SKU id,不能误用专栏 id")
pending[2].cb(JSON.encode(grading))
Assert.eq(calls, 1)
Assert.is_nil(err)
Assert.eq(result.authors, "作者甲、作者乙")
Assert.eq(result.meta.rating.score, 8.9)
Client.detailAsync("11", done)
pending[#pending].cb(nil, "network down")
Assert.is_nil(result)
Assert.eq(err, "network down")
Client.detailAsync("11", done)
pending[#pending].cb(JSON.encode(wire))
pending[#pending].cb(nil, "rating down")
Assert.eq(result.authors, "作者甲、作者乙", "评分暂时不可用不丢掉已获取的详情")
Assert.is_nil(result.meta)
Assert.is_nil(err)
sync_detail = true
local handle = Client.detailAsync("11", done)
local before = calls
handle.cancel()
Assert.is_true(cancelled, "同步完成详情后,取消仍指向在途的评分请求")
pending[#pending].cb(JSON.encode(grading))
Assert.eq(calls, before, "取消后迟到的评分不能更新详情")
local BookDB = require("book.books_db")
Assert.is_true(BookDB.upsertLocal({ source_id = "ext.zhihu", stable_id = "11", title = "本地书名", category = "本地分类" }))
package.loaded["moonsource_zhihu.client"] = {
detailAsync = function(id, cb) cb(Mapper.detail(wire, id, grading)); return {} end,
}
local source = require("moonsource_zhihu.source").new()
source:getDetailAsync({ source_id = "ext.zhihu", stable_id = "11" }, done)
Assert.eq(result.authors, "作者甲、作者乙", "本地上架的脏行也要补缺失作者")
Assert.eq(result.intro, book.intro, "本地上架时没有简介,详情必须补全并落盘")
Assert.eq(result.title, "本地书名")
Assert.eq(result.category, "本地分类")
Assert.eq(result.sync_status, 0)
Assert.is_true(BookDB.upsertLocal({ source_id = "ext.zhihu", stable_id = "11", title = "自定义书名",
authors = "自定义作者", intro = "自定义简介", category = "本地分类" }))
source:getDetailAsync({ source_id = "ext.zhihu", stable_id = "11" }, done)
Assert.eq(result.authors, "自定义作者")
Assert.eq(result.intro, "自定义简介", "自动补全不能覆盖已编辑的非空字段")
Settings.getSource("ext.zhihu").cookie = nil
+102
View File
@@ -0,0 +1,102 @@
--[[--
盐选字体:只改文本节点、不能缓存未还原的乱码,所有退出路径清理临时文件。
@module tests.moonsource_zhihu.font_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local Config = require("support.config")
local Text = require("utils.text")
local Glyph = require("utils.glyph")
local lfs = require("libs/libkoreader-lfs")
local root = Config.dir() .. "/zhihu-font-fixture"
lfs.mkdir(root)
lfs.mkdir(root .. "/noto")
local reference_path = root .. "/noto/NotoSansCJKsc-Regular.otf"
local reference = assert(io.open(reference_path, "wb"))
reference:write("reference")
reference:close()
package.preload["fontlist"] = function() return { fontdir = root } end
---@type table<integer, string|false>
local map = { [0x7684] = "正", [0x4E0D] = "全", [0x4E86] = "。" }
local tmp_path, options, pending, fail_worker
local Paths = require("utils.paths")
local original_tmpname = Paths.tmpname
Paths.tmpname = function(suffix)
tmp_path = original_tmpname(suffix)
return tmp_path
end
Glyph.recognize = function(ref, _cache, tasks)
Assert.eq(ref, reference_path)
Assert.eq(tasks[1].font_path, tmp_path)
local file = assert(io.open(tmp_path, "rb"))
Assert.eq(file:read("*a"), "\0\1\0\0fixture")
file:close()
Assert.contains(tasks[1].codes, 0x4E86, "数字实体也必须参与识别")
return { map }
end
package.preload["workers.job"] = function()
return { run = function(worker, opts)
options = opts
if not pending then
local ok, result = pcall(worker)
if not ok then opts.on_failed(result)
elseif fail_worker then opts.on_failed("worker failed")
else opts.on_done(result) end
end
local job = {}
function job:cancel() opts.on_cancelled() end
return job
end }
end
local Font = require("moonsource_zhihu.font")
local wire = {
manuscript = '的<p title="的">不&amp;&#x4E86;<b>的</b><img src="https://img/的.png"/>&lt;的&gt;</p>了',
font = { base64 = "data:font/ttf;charset=utf-8;base64," .. Text.base64Encode("\0\1\0\0fixture") },
}
local html, message, completed
local function run()
html, message, completed = nil, nil, 0
return Font.restoreAsync(wire, function(value, err)
html, message = value, err
completed = completed + 1
end)
end
run()
Assert.eq(html, '正<p title="的">全&amp;。<b>正</b><img src="https://img/的.png"/>&lt;正&gt;</p>。')
Assert.is_nil(message)
Assert.eq(options.kind, "light", "字形识别不能阻塞 UI")
Assert.is_nil(io.open(tmp_path, "rb"), "成功后清理字体")
map[0x4E86] = false
run()
Assert.is_nil(html)
Assert.eq(message, "知乎章节字体还原失败,请重试")
Assert.is_nil(io.open(tmp_path, "rb"))
map[0x4E86] = "。"
wire.font.base64 = "data:font/ttf;charset=utf-8;base64," .. Text.base64Encode("<html>error</html>")
run()
Assert.is_nil(html)
Assert.eq(message, "知乎章节字体还原失败,请重试")
Assert.is_nil(io.open(tmp_path, "rb"))
wire.font.base64 = "data:font/ttf;charset=utf-8;base64," .. Text.base64Encode("\0\1\0\0fixture")
fail_worker = true
run()
Assert.eq(message, "worker failed")
Assert.is_nil(io.open(tmp_path, "rb"), "任务失败后清理字体")
pending = true
local handle = run()
local file = assert(io.open(tmp_path, "wb"))
file:write("pending")
file:close()
handle:cancel()
Assert.eq(completed, 0, "取消时不交付正文")
Assert.is_nil(io.open(tmp_path, "rb"), "取消后清理字体")
Paths.tmpname = original_tmpname
os.remove(reference_path)
os.remove(root .. "/noto")
os.remove(root)
+245
View File
@@ -0,0 +1,245 @@
--[[--
知乎扫码会话、状态解析、Cookie 校验与取消。
@module tests.moonsource_zhihu.login_spec
--]]
---@diagnostic disable: undefined-field
package.loaded["json"] = nil
package.preload["json"] = function() return require("support.json_stub") end
local Assert = require("support.assert")
local Json = require("support.json_stub")
local Settings = require("utils.settings")
local Log = require("utils.log")
local original_warn, warnings = Log.warn, {}
Log.warn = function(...)
local parts = {}
for i = 1, select("#", ...) do parts[i] = tostring(select(i, ...)) end
warnings[#warnings + 1] = table.concat(parts, " ")
end
local posts, gets = {}, {}
local response, response_err = { status = 0 }, nil
local poll_cookies
local me = { id = "fixture-user" }
local defer_me, pending_me, cancelled_me
local defer_captcha, pending_captcha, cancelled_captcha
local navigation_error, missing_device, bad_create
local serial = 0
local function cookies(lines)
return { code = 200, headers = { ["Set-Cookie"] = lines } }
end
package.loaded["http.request"] = {
headerAll = function(res, name)
local value = res and res.headers and res.headers[name]
if type(value) == "string" then return { value } end
return value or {}
end,
post = function(url, body, opts, cb)
posts[#posts + 1] = { url = url, body = body, opts = opts }
if url:find("/udid", 1, true) then
cb("not-a-device-cookie", nil, cookies({}))
elseif url:find("/login/qrcode", 1, true) then
cb(Json.encode(bad_create or {
token = "tok" .. serial, link = "https://www.zhihu.com/account/scan/" .. serial .. "?/api/login/qrcode",
expires_at = 1800000000,
}), nil, cookies({}))
else
error("unexpected POST " .. url)
end
return { cancel = function() end }
end,
get = function(url, opts, cb)
gets[#gets + 1] = { url = url, opts = opts }
if url:find("/signin", 1, true) then
serial = serial + 1
if navigation_error then cb(nil, navigation_error); return { cancel = function() end } end
cb(nil, "HTTP 302", {
code = 302, headers = {
Location = "/account/unhuman?type=fixture",
["Set-Cookie"] = { "sec_token=sec" .. serial .. "; Path=/", "_xsrf=xsrf" .. serial .. "; Path=/" },
},
})
elseif url:find("/account/unhuman", 1, true) then
cb("<html></html>", nil, cookies({ "_zap=zapfix; Path=/" }))
elseif url:find("/captcha/v2", 1, true) then
local function reply()
cb("{}", nil, cookies(missing_device and {} or { 'd_c0="dc' .. serial .. '"; Path=/' }))
end
if defer_captcha then
pending_captcha = reply
return { cancel = function() cancelled_captcha = true end }
end
reply()
elseif url:find("/scan_info", 1, true) then
cb(response_err and nil or Json.encode(response), response_err, {
code = response_err and 403 or 200, body = Json.encode(response),
headers = { ["Set-Cookie"] = poll_cookies },
})
elseif url:find("/api/v4/me", 1, true) then
if defer_me then
pending_me = function() cb(Json.encode(me), nil, { code = 200 }) end
return { cancel = function() cancelled_me = true end }
end
cb(Json.encode(me), nil, { code = 200 })
else
error("unexpected GET " .. url)
end
return { cancel = function() end }
end,
}
package.loaded["moonsource_zhihu.client"] = nil
local Client = require("moonsource_zhihu.client")
local cfg = Settings.getSource("ext.zhihu")
local original_cookie = cfg.cookie
cfg.cookie = nil
local session, failure
Client.qrCreateAsync(function(value, err) session, failure = value, err end)
Assert.is_nil(failure)
Assert.eq(session.token, "tok1")
Assert.eq(session.link, "https://www.zhihu.com/account/scan/1")
Assert.eq(session.expires_at, 1800000000)
Assert.eq(posts[1].url, "https://www.zhihu.com/udid")
Assert.eq(posts[1].body, "{}")
Assert.eq(posts[1].opts.headers["x-xsrftoken"], "xsrf1")
Assert.eq(posts[2].body, "{}")
Assert.eq(posts[2].opts.content_type, "application/json;charset=UTF-8")
Assert.eq(posts[2].opts.headers["x-xsrftoken"], "xsrf1")
Assert.is_true(posts[2].opts.headers.Cookie:find('d_c0="dc1"', 1, true) ~= nil)
Assert.is_nil(posts[2].opts.headers["x-zse-83"])
Assert.eq(gets[1].url, "https://www.zhihu.com/signin")
Assert.is_nil(gets[1].opts.headers["x-requested-with"])
Assert.eq(gets[2].url, "https://www.zhihu.com/account/unhuman?type=fixture")
Assert.is_true(posts[2].opts.headers.Cookie:find("_zap=zapfix", 1, true) ~= nil)
local other
Client.qrCreateAsync(function(value) other = value end)
local kind, extra, poll_err
local function poll(value, err)
response, response_err = value, err
return Client.qrPollAsync(session, function(a, b, c) kind, extra, poll_err = a, b, c end)
end
poll({ status = 0 })
Assert.eq(kind, "wait")
Assert.is_nil(poll_err)
Assert.is_true(gets[#gets].opts.headers.Cookie:find('d_c0="dc1"', 1, true) ~= nil, "后建的码不能覆盖旧会话")
Assert.eq(other.jar.d_c0, '"dc2"')
poll({ login_status = "SCANNED", status = 1 })
Assert.eq(kind, "scanned")
Assert.is_nil(cfg.cookie)
poll({ status = 1 })
Assert.eq(kind, "scanned", "已扫码不等于已确认")
poll({ login_status = "CONFIRMED", cookie = "z_c0=confirmed; Path=/; Domain=.zhihu.com" })
Assert.eq(kind, "ok")
Assert.is_true(cfg.cookie:find("z_c0=confirmed", 1, true) ~= nil)
Assert.is_nil(session.jar.Path, "Cookie 属性不能作为凭证发送")
Assert.eq(gets[#gets].url, "https://www.zhihu.com/api/v4/me")
local saved = cfg.cookie
me = { error = { message = "rejected" } }
poll({ login_status = "CONFIRMED", cookie = "z_c0=rejected; Path=/" })
Assert.is_nil(kind)
Assert.is_true(poll_err ~= nil)
Assert.eq(cfg.cookie, saved, "校验失败保留已有登录")
me = { id = "fixture-user" }
poll({ status = 5, new_token = { token = "new", link = "https://www.zhihu.com/scan/new?/api/login/qrcode" } })
Assert.eq(kind, "refresh")
Assert.eq(extra.token, "new")
Assert.eq(extra.link, "https://www.zhihu.com/scan/new")
Assert.eq(extra.jar, session.jar)
poll({ login_status = "EXPIRED" })
Assert.eq(kind, "expired")
poll({ status = 5, new_token = { token = "", link = "" } })
Assert.eq(kind, "expired")
poll({}, "connection reset")
Assert.is_nil(kind)
Assert.eq(poll_err, "connection reset")
poll({ error = { code = 40352, message = "网络环境异常",
redirect = "https://www.zhihu.com/account/unhuman?session=challenge%2Bfixture" } }, "HTTP 403")
Assert.eq(kind, "verify")
Assert.eq(extra, session)
Assert.eq(extra.challenge_id, "challenge+fixture")
Assert.eq(poll_err, "知乎需要安全验证,请在网页完成验证后继续扫码登录")
poll({ login_status = "UNKNOWN", cookie = "z_c0=private-cookie; Path=/" })
Assert.is_nil(kind)
Assert.eq(poll_err, "知乎登录响应异常,请重新获取二维码")
Assert.matches(warnings[#warnings], "poll HTTP 200")
Assert.matches(warnings[#warnings], "login_status=string")
Assert.is_nil(warnings[#warnings]:find("private-cookie", 1, true))
poll_cookies = { "z_c0=header-cookie; Path=/; HttpOnly" }
poll({ status = 1 })
Assert.eq(kind, "ok", "兼容旧版确认状态与 Set-Cookie 凭证")
Assert.is_true(cfg.cookie:find("z_c0=header-cookie", 1, true) ~= nil)
saved = cfg.cookie
poll_cookies = nil
local oauth = {
access_token = "fixture-access", refresh_token = "fixture-refresh",
token_type = "bearer", expires_in = 15552000, uid = "fixture-user", user_id = 123,
}
session.jar.z_c0 = nil
poll(oauth)
Assert.is_nil(kind, "OAuth 令牌不能替代登录 Cookie")
Assert.eq(cfg.cookie, saved)
poll_cookies = { "z_c0=oauth-cookie; Path=/; HttpOnly" }
poll(oauth)
Assert.eq(kind, "ok", "扫码确认直接返回 OAuth 令牌,不带状态字段")
Assert.is_nil(poll_err)
Assert.eq(gets[#gets].url, "https://www.zhihu.com/api/v4/me")
Assert.is_true(cfg.cookie:find("z_c0=oauth-cookie", 1, true) ~= nil)
Assert.is_nil(cfg.cookie:find("fixture-access", 1, true), "不持久化 OAuth 令牌")
saved = cfg.cookie
me = { error = { message = "rejected" } }
poll_cookies = { "z_c0=invalid-oauth-cookie; Path=/; HttpOnly" }
poll(oauth)
Assert.is_nil(kind)
Assert.not_nil(poll_err)
Assert.eq(cfg.cookie, saved, "OAuth 响应仍须校验用户身份")
me = { id = "fixture-user" }
defer_me = true
poll_cookies = { "z_c0=cancelled; Path=/; HttpOnly" }
local handle = poll(oauth)
handle.cancel()
Assert.is_true(cancelled_me, "同步轮询回调后,取消仍然要取消后续校验请求")
pending_me()
Assert.eq(cfg.cookie, saved, "取消校验后不能保存登录")
defer_me = false
poll_cookies = nil
defer_captcha = true
local called = false
handle = Client.qrCreateAsync(function() called = true end)
local count = #posts
handle.cancel()
Assert.is_true(cancelled_captcha, "取消必须指向当前在途请求")
pending_captcha()
Assert.is_false(called)
Assert.eq(#posts, count)
defer_captcha = false
navigation_error = "offline"
Client.qrCreateAsync(function(value, err) session, failure = value, err end)
Assert.is_nil(session)
Assert.eq(failure, "offline")
navigation_error = nil
missing_device = true
Client.qrCreateAsync(function(value, err) session, failure = value, err end)
Assert.is_nil(session)
Assert.eq(failure, "知乎未下发登录会话,请重新获取二维码", "不把 udid 响应正文冒充设备 Cookie")
missing_device = false
bad_create = { token = "private-token", link = "" }
Client.qrCreateAsync(function(value, err) session, failure = value, err end)
Assert.is_nil(session)
Assert.eq(failure, "知乎登录响应异常,请重新获取二维码")
Assert.matches(warnings[#warnings], "create HTTP 200")
Assert.matches(warnings[#warnings], "token=string")
Assert.is_nil(warnings[#warnings]:find("private-token", 1, true))
Log.warn = original_warn
cfg.cookie = original_cookie
Settings.saveSource("ext.zhihu")
+114
View File
@@ -0,0 +1,114 @@
--[[--
知乎云进度协议:长篇最近章节、章内比例、毫秒时间与明确成功确认。
@module tests.moonsource_zhihu.progress_client_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 Stubs = require("support.stubs")
local cfg = require("utils.settings").getSource("ext.zhihu")
cfg.cookie = "z_c0=progress-fixture"
local pending, sync_column = {}, false
local function request(url, options, cb, body)
if sync_column and url:find("?is_new_column=", 1, true) then
cb(JSON.encode({ last_learned_section_id = "3" }))
return { cancel = function() error("已完成的详情请求不能覆盖在途正文请求") end }
end
local item = { url = url, options = options, cb = cb, body = body }
pending[#pending + 1] = item
return { cancel = function() item.cancelled = true end }
end
package.loaded["http.request"] = {
get = request,
post = function(url, body, options, cb) return request(url, options, cb, body) end,
}
local Client = require("moonsource_zhihu.client")
local result, err, meta, calls
calls = 0
local function done(value, reason, info) result, err, meta, calls = value, reason, info, calls + 1 end
local function wire(id, fraction)
return { id = id, cli_progress = { unit_progress = {
unit_id = id, progress = fraction, client_updated_at = 1800000000123, is_finished = false,
} } }
end
Client.progressAsync("1/2", done)
Assert.matches(pending[#pending].url, "/paid_columns/1/sections/2/manuscript%?v=1&manuscript_version=0$")
Assert.eq(pending[#pending].options.headers.Cookie, cfg.cookie)
pending[#pending].cb(JSON.encode(wire("2", .4)))
Assert.eq(result.fraction, .4)
Assert.eq(result.section_id, "2")
Assert.eq(result.updated_at, 1800000000)
Client.progressAsync("1/2", done)
pending[#pending].cb(JSON.encode(wire("2")))
Assert.is_nil(result)
Assert.is_true(meta.empty, "仅 unit_id、无进度值不算读过")
Client.progressAsync("1/2", done)
local finished = wire("2")
finished.cli_progress.unit_progress.is_finished = true
pending[#pending].cb(JSON.encode(finished))
Assert.eq(result.fraction, 1)
for _idx, bad in ipairs({ wire("9", .2), wire("2", 20), wire("2", "invalid"), {} }) do
Client.progressAsync("1/2", done)
pending[#pending].cb(JSON.encode(bad))
Assert.is_nil(result)
Assert.not_nil(err, "不合法的响应不能冒充云端无记录")
Assert.is_nil(meta)
end
Client.progressAsync("1", done)
pending[#pending].cb(JSON.encode({ last_learned_section_id = "3" }))
Assert.matches(pending[#pending].url, "/sections/3/manuscript%?")
pending[#pending].cb(JSON.encode(wire("3")))
Assert.eq(result.fraction, 0, "长篇已知最近章节、没有章内比例时落在该章开头")
Assert.eq(result.section_id, "3")
Client.progressAsync("1", done)
pending[#pending].cb(JSON.encode({ last_learned_section_id = "0" }))
Assert.is_true(meta.empty)
sync_column = true
local job = Client.progressAsync("1", done)
local before = calls
job.cancel()
Assert.is_true(pending[#pending].cancelled)
pending[#pending].cb(JSON.encode(wire("3", .7)))
Assert.eq(calls, before, "取消后迟到结果不能交付")
sync_column = false
Client.putProgressAsync("2", .4, done)
local post = pending[#pending]
Assert.eq(post.url, "https://api.zhihu.com/promus/progress")
Assert.eq(post.options.headers.Cookie, cfg.cookie)
local sent = JSON.decode(post.body)[1]
Assert.eq(sent.unit_id, "2")
Assert.eq(sent.type, "paid_column")
Assert.eq(sent.progress, .4)
Assert.is_false(sent.is_finished)
Assert.eq(sent.client_updated_at % 1000, 0)
post.cb('{"success":true}', nil, { code = 200 })
Assert.is_true(result)
Client.putProgressAsync("2", 1, done)
Assert.is_true(JSON.decode(pending[#pending].body)[1].is_finished)
for _idx, body in ipairs({ "{}", '{"success":false}', '{"error":{"code":1}}', "not json" }) do
pending[#pending].cb(body, nil, { code = 200 })
Assert.is_nil(result)
Assert.not_nil(err, "HTTP 200 不等于进度已确认")
end
Client.putProgressAsync("2", .4, done)
pending[#pending].cb(nil, "network failed")
Assert.eq(err, "network failed")
local Auth = require("source.auth")
Auth.reset()
Client.putProgressAsync("2", .4, done)
pending[#pending].cb(nil, "HTTP 401", { code = 401 })
Assert.is_true(Auth.expired("ext.zhihu"))
Auth.reset()
cfg.cookie = nil
local count = #pending
Client.progressAsync("1/2", done)
Stubs.flush()
Assert.eq(#pending, count)
Assert.eq(err, "请先登录知乎")
+86
View File
@@ -0,0 +1,86 @@
--[[--
知乎源进度映射:整篇 EPUB 与源章节身份分开,长篇支持最近章节及目录刷新。
@module tests.moonsource_zhihu.progress_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local read, posts = {}, {}
package.loaded["moonsource_zhihu.client"] = {
progressAsync = function(id, cb)
read[#read + 1] = { id = id, cb = cb }
return { cancel = function() read[#read].cancelled = true end }
end,
putProgressAsync = function(section, fraction, cb)
local post = { section = section, fraction = fraction, cb = cb }
posts[#posts + 1] = post
return { cancel = function() post.cancelled = true end }
end,
}
local Source = require("moonsource_zhihu.source").new()
local toc_requests = {}
function Source:loadTocAsync(_identity, cb, force)
local item = { cb = cb, force = force }
toc_requests[#toc_requests + 1] = item
return { cancel = function() item.cancelled = true end }
end
local short = { source_id = "ext.zhihu", stable_id = "1/2" }
local long = { source_id = "ext.zhihu", stable_id = "1" }
local toc = { { idx = 1, uid = "2", title = "甲" }, { idx = 2, uid = "3", title = "乙" } }
local result, err, calls = nil, nil, 0
local function done(value, reason) result, err, calls = value, reason, calls + 1 end
Source:getProgressAsync(short, done)
read[#read].cb({ section_id = "2", fraction = .6, updated_at = 12 })
Assert.eq(result.fraction, .6)
Assert.is_nil(result.chapter_idx, "整篇 EPUB 应按整书比例定位,不能跳到内部第 1 小节")
Assert.eq(result.updated_at, 12)
short.chapter_idx = 1
Source:getProgressAsync(short, done)
read[#read].cb({ section_id = "2", fraction = .6 })
Assert.eq(result.chapter_idx, 1)
Assert.eq(result.chapter_fraction, .6)
short.chapter_idx = nil
Source:putProgressAsync(short, { fraction = .6, chapter_idx = 8, chapter_fraction = .2 }, done)
Assert.eq(posts[#posts].section, "2")
Assert.eq(posts[#posts].fraction, .6, "内部 EPUB 章内比例不能当作整篇进度")
posts[#posts].cb(true)
Assert.is_true(result)
Source:getProgressAsync(long, done)
read[#read].cb({ section_id = "3", fraction = .4 })
toc_requests[#toc_requests].cb(toc)
Assert.eq(result.chapter_idx, 2)
Assert.eq(result.chapter_fraction, .4)
Assert.eq(result.fraction, .7)
Source:getProgressAsync(long, done)
read[#read].cb({ section_id = "5", fraction = .4 })
toc_requests[#toc_requests].cb(toc)
Assert.is_true(toc_requests[#toc_requests].force, "云端读到新章时须刷新旧目录")
toc_requests[#toc_requests].cb({ toc[1], toc[2], { idx = 3, uid = "5", title = "丙" } })
Assert.eq(result.chapter_idx, 3)
Assert.is_true(math.abs(result.fraction - .8) < 1e-10)
local job = Source:getProgressAsync(long, done)
read[#read].cb({ section_id = "3", fraction = .4 })
local before = calls
job.cancel()
Assert.is_true(toc_requests[#toc_requests].cancelled)
toc_requests[#toc_requests].cb(toc)
Assert.eq(calls, before)
Source:putProgressAsync(long, { fraction = .8, chapter_idx = 2, chapter_fraction = .6 }, done)
toc_requests[#toc_requests].cb(toc)
Assert.eq(posts[#posts].section, "3")
Assert.eq(posts[#posts].fraction, .6)
posts[#posts].cb(true)
Assert.is_true(result)
Source:putProgressAsync(long, { fraction = 1 }, done)
toc_requests[#toc_requests].cb(toc)
Assert.eq(posts[#posts].section, "3")
Assert.eq(posts[#posts].fraction, 1, "手动已读要推末章读完")
local count = #posts
job = Source:putProgressAsync(long, { fraction = .1 }, done)
job.cancel()
toc_requests[#toc_requests].cb(toc)
Assert.eq(#posts, count)
+163
View File
@@ -0,0 +1,163 @@
--[[--
知乎扫码弹窗:等待手机确认、刷新、失败重试与取消在途请求。
@module tests.moonsource_zhihu.qrlogin_spec
--]]
---@diagnostic disable: undefined-field
local Assert = require("support.assert")
local Themed = require("support.theme_stubs")
Themed.install()
local pending
package.loaded["ui/uimanager"] = {
scheduleIn = function(_self, _seconds, fn) pending = fn end,
unschedule = function(_self, fn) if pending == fn then pending = nil end end,
}
local polls, queue = 0, {}
local defer_create, create_callback, create_cancelled
local defer_poll, poll_callback, poll_cancelled
local create_error, expires_at, create_challenge, resumed
package.loaded["moonsource_zhihu.client"] = {
qrCreateAsync = function(cb, session)
resumed = session
if defer_create then
create_callback = cb
return { cancel = function() create_cancelled = true end }
end
cb(not create_error and not create_challenge and {
token = "tok", link = "https://www.zhihu.com/account/scan", expires_at = expires_at,
} or nil, create_error, create_challenge)
return { cancel = function() end }
end,
qrPollAsync = function(session, cb)
polls = polls + 1
Assert.is_true(type(session.token) == "string")
if defer_poll then
poll_callback = cb
return { cancel = function() poll_cancelled = true end }
end
local result = table.remove(queue, 1)
cb(result.kind, result.extra, result.err)
return { cancel = function() end }
end,
}
package.loaded["moonsource_zhihu.qrlogin"] = nil
local QRLogin = require("moonsource_zhihu.qrlogin")
local function start(results)
queue, polls, pending = results, 0, nil
local done
local qr = QRLogin:new(function() done = true end)
qr:start()
return qr, function() return done end
end
local qr, done = start({ { kind = "ok" } })
Assert.is_true(done())
Assert.eq(Themed.last("qr").text, "https://www.zhihu.com/account/scan")
Assert.eq(Themed.last("qr").title, "知乎扫码登录")
Assert.eq(Themed.last("qr").caption, "用知乎 App 扫一扫")
Assert.is_true(Themed.last("qr").closed)
Assert.is_true(Themed.last("progress_dialog").closed)
Assert.eq(polls, 1)
qr, done = start({
{ kind = "refresh", extra = { token = "tok2", link = "https://www.zhihu.com/account/scan/2" } },
{ kind = "ok" },
})
Assert.is_nil(done(), "换码不能同步递归轮询")
Assert.eq(Themed.last("qr").text, "https://www.zhihu.com/account/scan/2")
pending()
Assert.is_true(done())
Assert.eq(polls, 2)
qr, done = start({ { kind = "scanned" }, { kind = "scanned" }, { kind = "ok" } })
Assert.eq(Themed.last("toast").text, "已扫码,请在手机上确认")
Assert.is_nil(done())
local count = #Themed.all("toast")
pending()
Assert.eq(#Themed.all("toast"), count, "等待确认只提示一次")
pending()
Assert.is_true(done())
qr, done = start({ { kind = "wait" } })
local queued = pending
Themed.last("qr"):close()
Assert.is_nil(pending)
queued()
Assert.eq(polls, 1, "关闭二维码后不再轮询")
Assert.eq(Themed.last("toast").text, "已取消登录")
Assert.is_nil(done())
qr, done = start({ { err = "网络环境异常" } })
Assert.eq(Themed.last("confirm").text, "网络环境异常")
Assert.eq(Themed.last("confirm").ok_text, "重新获取")
Assert.is_true(Themed.last("qr").closed)
queue = { { kind = "ok" } }
Themed.last("confirm").ok_callback()
Assert.is_true(done())
qr, done = start({ { kind = "expired" } })
Assert.eq(Themed.last("confirm").text, "二维码已过期")
Assert.is_nil(done())
expires_at = os.time() - 1
qr, done = start({})
Assert.eq(polls, 0, "已过期的码不再轮询")
Assert.eq(Themed.last("confirm").text, "二维码已过期")
expires_at = nil
create_error = "offline"
qr, done = start({})
Assert.eq(Themed.last("confirm").text, "offline")
Assert.is_true(Themed.last("progress_dialog").closed)
create_error = nil
defer_poll = true
qr, done = start({})
qr:cancel()
Assert.is_true(poll_cancelled, "同步出码回调不能覆盖在途轮询句柄")
Assert.is_true(Themed.last("qr").closed)
poll_callback("ok")
Assert.is_nil(done())
defer_poll = false
local verification_callback, verification_cancelled, verified_session
package.loaded["moonsource_zhihu.verify"] = {
new = function(session, cb)
verified_session, verification_callback = session, cb
return { cancel = function() verification_cancelled = true end }
end,
}
local challenge = { jar = {}, token = "old" }
qr, done = start({ { kind = "verify", extra = challenge } })
Assert.eq(verified_session, challenge)
Assert.is_true(Themed.last("qr").closed)
Assert.is_nil(done(), "安全验证通过之前不能认为登录成功")
queue = { { kind = "ok" } }
verification_callback(true)
Assert.eq(resumed, challenge, "验证后必须沿用原匿名会话重新出码")
Assert.is_true(done())
create_challenge = challenge
qr, done = start({})
Assert.eq(verified_session, challenge, "出码前被拦截也能进入验证")
create_challenge = nil
qr:cancel()
Assert.is_true(verification_cancelled)
local before = #Themed.all("qr")
verification_callback(true)
Assert.eq(#Themed.all("qr"), before, "取消验证后不接受迟到回调")
Assert.is_nil(done())
defer_create = true
qr, done = start({})
Assert.eq(Themed.last("progress_dialog").text, "正在获取二维码…")
Themed.last("progress_dialog").on_cancel()
Assert.is_true(create_cancelled)
Assert.is_true(Themed.last("progress_dialog").closed)
local shown = #Themed.all("qr")
create_callback({ token = "late", link = "https://www.zhihu.com/late" })
Assert.eq(#Themed.all("qr"), shown, "取消出码后不弹迟到的二维码")
Assert.is_nil(done())
+153
View File
@@ -0,0 +1,153 @@
--[[--
知乎章末评论:官方接口、原样游标、回复映射、短篇 / 长篇目标及取消。
@module tests.moonsource_zhihu.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 cfg = require("utils.settings").getSource("ext.zhihu")
cfg.cookie = "z_c0=comment-fixture"
local pending = {}
package.loaded["http.request"] = {
get = function(url, options, cb)
local item = { url = url, options = options, cb = cb }
pending[#pending + 1] = item
return { cancel = function() item.cancelled = true end }
end,
}
local Client = require("moonsource_zhihu.client")
local result, err, calls = nil, nil, 0
local function done(value, reason) result, err, calls = value, reason, calls + 1 end
local function wire()
return {
data = { {
id = "101", content = '<p>甲 &amp; 乙<br>下一行</p><img src="https://pic.test/a.jpg?a=1&amp;b=2">',
author = { name = "读者" }, like_count = 8, child_comment_count = 10, created_time = 1700000000,
reply_to_author = { name = "另一位读者" },
} },
paging = { is_end = false, next = "https://api.zhihu.com/comment_v5/?offset=sr1%3Aabc%2B%2F%3D&limit=10" },
counts = { total_counts = 380 },
}
end
Client.reviewsAsync("22", 0, false, done)
Assert.matches(pending[#pending].url, "/comment_v5/paid_column_section_manuscripts/22/root_comment%?")
Assert.matches(pending[#pending].url, "order_by=score&offset=$", "首页用空游标,旧版评论分页不接受数字 0")
Assert.eq(pending[#pending].options.headers.Cookie, cfg.cookie)
pending[#pending].cb(JSON.encode(wire()))
Assert.eq(result.total, 380)
Assert.is_true(result.more)
Assert.eq(result.max_idx, "sr1:abc+/=", "游标不是数字,不得截断或二次解码")
local item = result.items[1]
Assert.eq(item.id, "101")
Assert.eq(item.content, "甲 & 乙\n下一行")
Assert.eq(item.author, "读者")
Assert.eq(item.likes, 8)
Assert.eq(item.replies, 10)
Assert.eq(item.reply_to, "另一位读者")
Assert.eq(item.time, 1700000000)
Assert.eq(item.images[1].url, "https://pic.test/a.jpg?a=1&b=2")
Assert.eq(item.images[1].headers.Referer, "https://www.zhihu.com/")
Client.reviewsAsync("22", result.max_idx, false, done)
Assert.matches(pending[#pending].url, "offset=sr1%%3Aabc%%2B%%2F%%3D$")
Client.reviewsAsync("101", 0, true, done)
Assert.matches(pending[#pending].url, "/comment/101/child_comment%?limit=5&order_by=ts&offset=$")
local last = wire()
last.paging.is_end = true
last.paging.next = nil
pending[#pending].cb(JSON.encode(last))
Assert.is_false(result.more)
Client.reviewsAsync("22", "0", false, done)
Assert.matches(pending[#pending].url, "offset=0$", "服务端返回的字符串游标仍原样带回")
local emoji = wire()
emoji.data[1].content = '甲[捂脸][捂脸][未知表情]<img alt="[赞]" src="https://pic.test/emoji.png">'
.. '<img src="https://pic.test/photo.jpg">'
Client.reviewsAsync("101", 0, true, done)
pending[#pending].cb(JSON.encode(emoji))
Assert.eq(result.items[1].content, "甲[捂脸][捂脸][未知表情][赞]", "原始文案保留,图片表情的 alt 不丢")
Assert.is_true(result.items[1].inline_images["[捂脸]"] ~= nil, "根段评与回复共用表情映射")
Assert.is_true(result.items[1].inline_images["[赞]"] ~= nil)
Assert.is_nil(result.items[1].inline_images["[未知表情]"], "未知表情保持原文,不编造图片地址")
Assert.len(result.items[1].images, 1, "表情不混入普通配图")
Assert.eq(result.items[1].images[1].url, "https://pic.test/photo.jpg")
for _idx, bad in ipairs({
{}, { error = { code = 1 } }, { data = {}, paging = { is_end = false }, counts = { total_counts = 3 } },
{ data = {}, paging = { is_end = false, next = "https://api.zhihu.com/?offset=0" },
counts = { total_counts = 3 } },
}) do
Client.reviewsAsync("22", 0, false, done)
pending[#pending].cb(JSON.encode(bad))
Assert.is_nil(result)
Assert.eq(err, "无法获取段评", "坏响应不能伪装成无评论")
end
Client.reviewsAsync("22", 0, false, done)
pending[#pending].cb(nil, "network failed")
Assert.eq(err, "network failed")
local Auth = require("source.auth")
Auth.reset()
Client.reviewsAsync("22", 0, false, done)
pending[#pending].cb(nil, "HTTP 401", { code = 401 })
Assert.is_true(Auth.expired("ext.zhihu"))
Auth.reset()
local cache_keys = {}
package.loaded["book.review_cache"] = {
hotspotsAsync = function(_identity, fetch, cb) return fetch(cb) end,
pageAsync = function(identity, range, offset, fetch, cb)
cache_keys[#cache_keys + 1] = { identity, range, offset }
return fetch(cb)
end,
}
local source = require("moonsource_zhihu.source").new()
local short = { source_id = "ext.zhihu", stable_id = "11/22", book = { title = "短篇" } }
source:chapterReviewHotspotsAsync(short, done)
pending[#pending].cb(JSON.encode(wire()))
Assert.len(result, 1)
Assert.eq(result[1].range, "22")
Assert.eq(result[1].text, "短篇")
Assert.eq(result[1].badge, "380")
Assert.eq(result[1].heading, "章节评论")
Assert.eq(cache_keys[#cache_keys][1], short, "整篇 EPUB 不需要伪造 chapter_idx")
local long = { source_id = "ext.zhihu", stable_id = "11", chapter_idx = 2 }
function source:loadTocAsync(_identity, cb)
cb({ { uid = "22", title = "第一章" }, { uid = "33", title = "第二章" } })
return { cancel = function() error("已完成目录请求不能覆盖当前评论请求") end }
end
local job = source:chapterReviewHotspotsAsync(long, done)
Assert.matches(pending[#pending].url, "/paid_column_section_manuscripts/33/root_comment%?")
local before = calls
job.cancel()
Assert.is_true(pending[#pending].cancelled)
pending[#pending].cb(JSON.encode(wire()))
Assert.eq(calls, before, "取消后迟到的评论不得覆盖目标")
source:chapterReviewHotspotsAsync(long, done)
pending[#pending].cb(JSON.encode(wire()))
Assert.eq(result[1].text, "第二章")
local legacy = wire()
legacy.counts.total_counts = 4
legacy.data[1].child_comment_count = 3
legacy.paging = {
is_end = true,
is_start = true,
next = "https://api.zhihu.com/comment_v5/?offset=5_11554576136_0&order_by=score",
}
source:chapterReviewHotspotsAsync(long, done)
Assert.matches(pending[#pending].url, "offset=$", "长篇旧版分页的首页也必须是空游标")
pending[#pending].cb(JSON.encode(legacy))
Assert.eq(result[1].badge, "4", "数量气泡只放数字,且总数包含回复")
source:paragraphReviewRepliesAsync(short, "101", "1700000000_123_0", done)
Assert.eq(cache_keys[#cache_keys][2], "reply:101", "回复缓存与根评论缓存不串")
Assert.eq(cache_keys[#cache_keys][3], "1700000000_123_0")
Assert.matches(pending[#pending].url, "offset=1700000000_123_0$")
local empty = wire()
empty.data, empty.counts.total_counts, empty.paging.is_end = {}, 0, true
source:chapterReviewHotspotsAsync(short, done)
pending[#pending].cb(JSON.encode(empty))
Assert.len(result, 1, "零评论仍保留独立章评入口,与接口失败分开处理")
Assert.eq(result[1].badge, "0")
+161
View File
@@ -0,0 +1,161 @@
--[[--
知乎账号入口、Cookie 授权与登录后重新检查匿名目录里的付费章。
@module tests.moonsource_zhihu.setting_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch, inject-field
local Assert = require("support.assert")
local Settings = require("utils.settings")
local Themed = require("support.theme_stubs")
Themed.install()
package.loaded["ui.themes.widgets.row"] = { widget = function(spec) return spec end }
package.loaded["ui/network/manager"] = { runWhenConnected = function(_self, fn) fn() end }
local cfg = Settings.getSource("ext.zhihu")
cfg.cookie = nil
cfg.show_paragraph_reviews = nil
local checked, allow, reloads = {}, false, 0
package.loaded["source.registry"] = {
reload = function() reloads = reloads + 1 end,
invalidate = function() end,
}
local html, content_error, downloads, content_id = "<p>已购正文</p>", nil, 0, nil
package.loaded["moonsource_zhihu.client"] = {
cookie = function() return cfg.cookie end,
loginCheckAsync = function(cookie, cb)
checked[#checked + 1] = cookie
cb(allow, not allow and "rejected" or nil)
end,
contentAsync = function(id, cb)
downloads = downloads + 1
content_id = id
cb(html, content_error)
return { cancel = function() end }
end,
}
local scanned
package.loaded["moonsource_zhihu.qrlogin"] = {
new = function(_self, on_ok)
return {
start = function() scanned = on_ok end,
cancel = function() scanned = nil end,
}
end,
}
local Setting = require("moonsource_zhihu.setting")
Assert.eq(select(2, Setting.rowStatus()), false)
local row = Setting.rows()[1](400)
Assert.eq(row.subtitle, "用知乎 App 扫一扫")
Assert.eq(Setting.rows()[2](400).title, "浏览器登录")
local review_row = Setting.rows()[4](400)
Assert.eq(review_row.title, "显示段评")
Assert.is_false(review_row.status_on)
review_row.callback()
Assert.is_true(cfg.show_paragraph_reviews)
Assert.is_true(Setting.rows()[4](400).status_on)
Setting.rows()[4](400).callback()
Assert.is_false(cfg.show_paragraph_reviews)
row.callback()
Assert.eq(type(scanned), "function")
Assert.is_nil(Themed.last("input"), "账号入口直接扫码,不再弹手机号表单")
Setting.rows()[3](400).callback()
Assert.eq(Themed.last("input").title, "知乎登录 Cookie")
Themed.last("input").callback(" ")
Assert.eq(Themed.last("toast").text, "没有读到 Cookie")
Assert.len(checked, 0)
local payload = { cookies = {
{ domain = ".zhihu.com", name = "z_c0", value = "fixture" },
{ domain = "zhihu.com.evil.test", name = "other", value = "excluded" },
} }
local accepted, reason
Setting.browser.apply(payload, function(ok, err) accepted, reason = ok, err end)
Assert.is_false(accepted)
Assert.eq(reason, "rejected")
Assert.is_nil(cfg.cookie)
Assert.eq(reloads, 0)
allow = true
Setting.browser.apply(payload, function(ok, err) accepted, reason = ok, err end)
Assert.is_true(accepted)
Assert.is_nil(reason)
Assert.eq(cfg.cookie, "z_c0=fixture")
Assert.eq(checked[#checked], "z_c0=fixture")
Assert.eq(reloads, 1)
Assert.is_true(Setting.browser.isAuthorized())
Assert.eq(select(2, Setting.rowStatus()), true)
Assert.len(Setting.rows(), 5)
allow = false
Setting.browser.apply(payload, function(ok) accepted = ok end)
Assert.is_false(accepted)
Assert.eq(cfg.cookie, "z_c0=fixture", "重新授权失败保留已有登录")
Assert.eq(reloads, 1)
local open_fetch, cache_fetch, paid
package.loaded["source.chapter"] = {
openAsync = function(_source, _identity, _book, _opts, ops) open_fetch = ops.fetchContent end,
cacheAllAsync = function(_source, _identity, fetch) cache_fetch = fetch end,
}
package.loaded["moonsource_zhihu.story"] = {
openAsync = function(_source, _identity, _opts, ops) open_fetch = ops.fetchContent end,
}
package.loaded["source.toc"] = {
markPaid = function(id, stable_id, uid, value)
Assert.eq(id, "ext.zhihu")
Assert.eq(stable_id, "1/2")
Assert.eq(uid, "2")
paid = value
end,
}
local source = require("moonsource_zhihu.source").new()
Assert.is_false(source:paragraphReviewsEnabled())
require("source.review_setting").set("ext.zhihu", true)
Assert.is_true(source:paragraphReviewsEnabled(), "设置页和源实例读同一份开关")
require("source.review_setting").set("ext.zhihu", false)
Assert.is_false(source:paragraphReviewsEnabled(), "开关就地生效,不必重建源实例")
local identity = { source_id = "ext.zhihu", stable_id = "1/2" }
local chapter = { idx = 1, uid = "2", title = "第一节", vip = true }
source:openBookAsync(identity, { chapter_idx = 1 }, function() end)
local result, failure
open_fetch(identity, chapter, function(value, err) result, failure = value, err end)
Assert.eq(result.html, require("moonsource_zhihu.content").prepare("<p>已购正文</p>"),
"登录后不能被匿名目录里的 vip 标记挡住")
Assert.is_nil(result.temporary)
Assert.is_true(paid)
Assert.is_nil(failure)
html, content_error = nil, "本章未购买"
open_fetch(identity, chapter, function(value, err) result, failure = value, err end)
Assert.is_true(result.temporary)
Assert.is_nil(failure)
source:cacheAllChaptersAsync(identity, nil, function() end)
cache_fetch(identity, chapter, function(value, err) result, failure = value, err end)
Assert.is_nil(result)
Assert.eq(failure, "本章未购买", "后台缓存不能把购买提示存成正文")
content_error = "network down"
open_fetch(identity, chapter, function(value, err) result, failure = value, err end)
Assert.is_nil(result)
Assert.eq(failure, "network down")
html, content_error = "<p>长篇章节</p>", nil
open_fetch({ source_id = "ext.zhihu", stable_id = "3" }, { idx = 1, uid = "4", title = "第一节" },
function(value, err) result, failure = value, err end)
Assert.eq(content_id, "3/4", "长篇按当前章节请求正文,不把专栏 id 当作节 id")
Assert.eq(result.html, require("moonsource_zhihu.content").prepare(html))
Assert.is_nil(failure)
local before = downloads
cfg.cookie = nil
open_fetch(identity, chapter, function(value) result = value end)
Assert.is_true(result.temporary)
Assert.eq(downloads, before, "匿名未购买章保持原来的立即提示")
scanned()
Assert.eq(Themed.last("toast").text, "登录成功")
Assert.eq(reloads, 2)
Setting.rows()[1](400).callback()
Assert.eq(type(scanned), "function")
scanned()
Assert.eq(Themed.last("toast").text, "登录成功")
Assert.eq(reloads, 3)
Settings.saveSource("ext.zhihu")
+38
View File
@@ -0,0 +1,38 @@
--[[--
盐选 VIP 3.1 签名:官网签名器的固定随机数对照向量。
@module tests.moonsource_zhihu.sign_spec
--]]
local Assert = require("support.assert")
local original = math.random
math.random = function() return 0.5 end
local Sign = require("moonsource_zhihu.sign")
math.random = original
local path = "/remix-web/paid_columns/1/sections/2/manuscript?v=1&manuscript_version=0"
local headers = Sign.headers(path)
Assert.eq(headers["x-zse-93"], "101_3_3.1")
Assert.eq(headers["x-zse-96"], "2.0_QQJWmQTduUEbH9LV=3hl9n0/3H=n0PdHAJOXWt5VL=gI/gwbiU03vEDdqKn0M/9l")
headers = Sign.headers(path, 'z_c0=fixture; d_c0="fixture-device|123"; _xsrf=other')
Assert.eq(headers["x-zse-96"], "2.0_uY57DBSvHsx=4A=28OOiDGh4IoXNtI6QgZpc+30xb=0Fu5Qp8CtbDtf6EYo+lNu8",
"d_c0 引号不能剥掉,其他 Cookie 不参与签名")
headers = Sign.headers("/remix-web/paid_columns/1/sections/2/manuscript?manuscript_version=0&v=1",
'd_c0="fixture-device|123"')
Assert.eq(headers["x-zse-96"], "2.0_w5tKPLmoSbv/CgSbnymseBni5iZTsax9RNmsXWg=h+fpC+1/M+I0aTR+eYJc0lb6",
"查询串不能重排")
Assert.eq(Sign.headers(path, "other_d_c0=ignored")["x-zse-96"], Sign.headers(path)["x-zse-96"])
local Sha = require("ffi/sha2")
local original_md5 = Sha.md5
for _idx, fixture in ipairs({
{ random = 0, expected = "nZ=ktmDW5Au6W4bg9GDpq3NzqCmhx22uk5CuI+7cYMgnRJedTBkcbvUDVYwYdWQ5" },
{ random = 0.99999, expected = "b=7eGptEnaAJAWWEVqjX7+/+qlDbT/0EE6StfEggw1EieZBtJ6An+OX0=McttU86" },
}) do
package.loaded["moonsource_zhihu.sign"] = nil
math.random = function() return fixture.random end
Sha.md5 = function() return "4cf9d4f0069fc18fb3fcc0a50dceb852" end
local variant = require("moonsource_zhihu.sign")
math.random, Sha.md5 = original, original_md5
Assert.eq(variant.headers("/fixture")["x-zse-96"], "2.0_" .. fixture.expected)
end
+159
View File
@@ -0,0 +1,159 @@
--[[--
短篇 EPUB:源内重排、内部目录、旧进度迁移和原始注解保护。
@module tests.moonsource_zhihu.story_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local Config = require("support.config")
local Stubs = require("support.stubs")
local Themed = require("support.theme_stubs")
Themed.install()
local sqlite_ok = pcall(require, "lua-ljsqlite3/init")
if not sqlite_ok then Assert.skip("当前离线环境没有 ljsqlite3 Lua 模块") end
local JSON = require("support.json_stub")
package.loaded.json = JSON
local db_path = Config.dir() .. "/zhihu_story_spec.sqlite3"
for _idx, suffix in ipairs({ "", "-wal", "-shm" }) do os.remove(db_path .. suffix) end
local Paths = require("utils.paths")
package.loaded["utils.paths"] = setmetatable({ dbPath = function() return db_path end }, { __index = Paths })
local DB = require("utils.db")
local BookDB = require("book.books_db")
local ProgressDB = require("book.progress_db")
local NoteDB = require("book.note_db")
local Store = require("book.store")
local identity = { source_id = "ext.zhihu", stable_id = "910000001/910000002" }
local original = Paths.chapterPath(identity.stable_id, 1, identity.source_id)
local dest = Paths.bookWorkDir(identity.stable_id, identity.source_id) .. "/book.epub"
Assert.is_true(Paths.ensureDir(original:match("(.+)/[^/]+$")))
Assert.is_true(BookDB.upsertLocal({
source_id = identity.source_id, stable_id = identity.stable_id, title = "短篇样例", authors = "作者",
}))
local RealConverter = require("convert.text2epub")
local conversions, downloads = {}, 0
package.loaded["convert.text2epub"] = {
build = function(opts, cb, progress)
local item = { opts = opts, cb = cb, progress = progress }
conversions[#conversions + 1] = item
return { cancel = function() item.cancelled = true end }
end,
}
package.loaded["source.chapter"] = {
openWithUi = function(_source, id, _book, _opts, _ops, cb)
downloads = downloads + 1
Assert.is_true(Store.touch(original, id, { chapter_idx = 1 }))
cb(original)
return { cancel = function() error("已同步完成的下载不能覆盖转换任务") end }
end,
}
local Story = require("moonsource_zhihu.story")
local Content = require("moonsource_zhihu.content")
local upgrade_story = Content.upgradeStory
Content.upgradeStory = function(path)
Assert.eq(path, dest)
return true
end
local result, err, calls = nil, nil, 0
local function done(path, reason) result, err, calls = path, reason, calls + 1 end
local function reset(html)
os.remove(dest)
os.remove(dest .. ".part")
NoteDB.removeIdentity(identity.source_id, identity.stable_id)
ProgressDB.removeIdentity(identity.source_id, identity.stable_id)
BookDB.touchPath(identity.source_id, identity.stable_id, original)
local file = assert(io.open(original, "wb"))
assert(file:write(html))
file:close()
result, err = nil, nil
end
local html = "<html><head><title>短篇样例</title></head><body>"
.. "<h2>序幕</h2><p>开场文字。</p><p>01</p><p>第一段。</p><p>02</p><p>第二段。</p></body></html>"
reset(html)
Assert.is_true(ProgressDB.upsert(identity.source_id, identity.stable_id, {
fraction = .4, chapter_idx = 1, chapter_fraction = .4, locator = "html-pointer", page = 5, total_pages = 12,
}))
Story.openAsync({}, identity, nil, {}, done)
local conversion = conversions[#conversions]
local parsed = RealConverter.parse(conversion.opts.text, conversion.opts)
Assert.len(parsed.chapters, 3)
Assert.eq(parsed.chapters[2].title, "01", "数字小节必须进入 EPUB 自己的目录")
Assert.eq(parsed.chapters[3].title, "02")
Assert.is_true(conversion.opts.reflow)
Assert.eq(conversion.opts.tail_html, Content.FOOTER, "整篇 EPUB 只在文末留章评区,不进入内部目录")
conversion.progress("排版", 1, 3)
Assert.eq(Themed.last("progress_dialog").updates[1][2], 1)
local file = assert(io.open(dest, "wb")); file:write("epub fixture"); file:close()
conversion.cb(true)
Assert.eq(result, dest)
Assert.is_nil(err)
local id = Store.identityFor(dest)
Assert.eq(id.stable_id, identity.stable_id)
Assert.is_nil(id.chapter_idx, "EPUB 是整本身份,不能被源目录覆盖内部小节")
local migrated = ProgressDB.get(identity.source_id, identity.stable_id)
Assert.eq(migrated.fraction, .4)
Assert.is_nil(migrated.locator)
Assert.is_nil(migrated.chapter_idx)
Assert.is_nil(migrated.page)
Assert.is_true(Themed.last("progress_dialog").closed)
local count = downloads
Story.openAsync({}, identity, nil, {}, done)
Stubs.flush()
Assert.eq(downloads, count, "本地 EPUB 快开不联网、不重复转换")
Assert.eq(result, dest)
reset(html)
NoteDB.upsert(identity.source_id, identity.stable_id, 1, '[{"text":"原有划线"}]')
count = #conversions
Story.openAsync({}, identity, nil, {}, done)
Assert.eq(result, original)
Assert.eq(#conversions, count)
Assert.eq(Themed.last("toast").text, "已有划线,保留原始排版")
Assert.matches(NoteDB.get(identity.source_id, identity.stable_id, 1).payload, "原有划线")
reset("<!--moon:temp-->" .. html)
Story.openAsync({}, identity, nil, {}, done)
Assert.eq(result, original)
Assert.eq(#conversions, count, "购买提示不能被打包成永久 EPUB")
reset('<html><body><p>配图</p><img src="data:image/png;base64,fixture"/></body></html>')
Story.openAsync({}, identity, nil, {}, done)
Assert.eq(result, original)
Assert.eq(#conversions, count)
Assert.eq(Themed.last("toast").text, "短篇含图片,保留原始排版")
reset(html)
Story.openAsync({}, identity, nil, {}, done)
conversions[#conversions].cb(nil, "zip failed")
Assert.is_nil(result)
Assert.eq(err, "zip failed")
Assert.eq(BookDB.get(identity.source_id, identity.stable_id).path, original)
Assert.is_true(Themed.last("progress_dialog").closed)
reset(html)
local job = Story.openAsync({}, identity, nil, {}, done)
local before = calls
file = assert(io.open(dest .. ".part", "wb")); file:write("partial"); file:close()
job.cancel()
Assert.is_true(conversions[#conversions].cancelled)
Assert.is_true(Themed.last("progress_dialog").closed)
Assert.is_nil(io.open(dest .. ".part", "rb"))
conversions[#conversions].cb(true)
Assert.eq(calls, before)
reset(html)
ProgressDB.upsert(identity.source_id, identity.stable_id, { fraction = .5, locator = "keep-until-commit" })
Story.openAsync({}, identity, nil, {}, done)
local upsert = ProgressDB.upsert
ProgressDB.upsert = function() return false end
conversions[#conversions].cb(true)
ProgressDB.upsert = upsert
Assert.is_nil(result)
Assert.eq(err, "阅读进度保存失败")
Assert.eq(BookDB.get(identity.source_id, identity.stable_id).path, original, "进度失败须回滚 EPUB 路径登记")
Assert.eq(ProgressDB.get(identity.source_id, identity.stable_id).locator, "keep-until-commit")
DB.close()
Content.upgradeStory = upgrade_story
for _idx, suffix in ipairs({ "", "-wal", "-shm" }) do os.remove(db_path .. suffix) end
os.remove(original)
os.remove(dest)
os.remove(dest .. ".part")
+101
View File
@@ -0,0 +1,101 @@
--[[--
知乎官方挑战创建、票据验证和同会话解除风控。
@module tests.moonsource_zhihu.verify_client_spec
--]]
---@diagnostic disable: undefined-field
package.loaded["json"] = require("support.json_stub")
local Json = require("support.json_stub")
local Assert = require("support.assert")
local calls = {}
local scripts = { "https://cstaticdun.126.net/load.min.js",
"https://captcha.zhihu.com/api/v1/captcha/js?appId=lsxNQs26Wva2&sessionId=challenge%2Bfixture" }
local success, block_code = true, 0
local defer, pending, cancelled, fail_code
local function response(wire, headers, code)
return { code = code or 200, body = Json.encode(wire), headers = headers }
end
package.loaded["http.request"] = {
ok = function(code) return code >= 200 and code < 300 end,
headerAll = function(res, name) return res and res.headers and res.headers[name] or {} end,
post = function(url, body, opts, cb)
calls[#calls + 1] = { url = url, body = body, headers = opts.headers }
cb(Json.encode({ script = scripts }), nil, response({}, { ["Set-Cookie"] = { "captcha_session=issued; Path=/" } }))
return { cancel = function() end }
end,
request = function(opts, cb)
calls[#calls + 1] = opts
if defer then
pending = cb
return { cancel = function() cancelled = true end }
end
if fail_code then cb(response({ error = { message = "rejected" } }, nil, fail_code), "HTTP " .. fail_code)
elseif opts.method == "PUT" then
cb(response({ success = success }, { ["Set-Cookie"] = { "verified=accepted; Path=/" } }))
elseif opts.method == "POST" then cb(response({}))
else cb(response({ code = block_code })) end
return { cancel = function() end }
end,
}
package.loaded["moonsource_zhihu.client"] = nil
local Client = require("moonsource_zhihu.client")
local session = { jar = { d_c0 = "device", _xsrf = "xsrf" }, challenge_id = "appeal+fixture" }
local config, failure
Client.qrCaptchaAsync(session, function(value, err) config, failure = value, err end)
Assert.is_nil(failure)
Assert.eq(config.session_id, "challenge+fixture")
Assert.eq(calls[1].url, "https://captcha.zhihu.com/api/v1/captcha")
Assert.eq(Json.decode(calls[1].body).appId, "lsxNQs26Wva2")
Assert.is_true(calls[1].headers.Cookie:find("d_c0=device", 1, true) ~= nil)
Assert.eq(session.jar.captcha_session, "issued")
local ok
Client.qrVerifyAsync(session, config.session_id, '{"validate":"user-proof"}', function(value, err) ok, failure = value, err end)
Assert.is_true(ok)
Assert.is_nil(failure)
Assert.eq(calls[2].method, "PUT")
Assert.eq(calls[2].url, "https://captcha.zhihu.com/api/v1/captcha")
local body = Json.decode(calls[2].body)
Assert.eq(body.sessionId, "challenge+fixture")
Assert.eq(body.ticket, '{"validate":"user-proof"}')
Assert.eq(calls[3].url, "https://www.zhihu.com/api/v4/anticrawl/new_captcha_appeal")
Assert.eq(calls[3].method, "POST")
Assert.eq(Json.decode(calls[3].body).session, "appeal+fixture")
Assert.eq(calls[3].headers["x-xsrftoken"], "xsrf")
Assert.is_true(calls[3].headers.Cookie:find("verified=accepted", 1, true) ~= nil)
Assert.eq(calls[4].method, "GET")
Assert.eq(calls[4].url, "https://www.zhihu.com/api/v4/anticrawl/new_captcha_appeal?session=appeal%2Bfixture")
success = false
local before = #calls
Client.qrVerifyAsync(session, "id", "{}", function(value, err) ok, failure = value, err end)
Assert.is_false(ok)
Assert.eq(failure, "验证失败,请重新验证")
Assert.eq(#calls, before + 1, "控件验证失败不能继续解除风控")
success = true
block_code = 40352
Client.qrVerifyAsync(session, "id", "{}", function(value, err) ok, failure = value, err end)
Assert.is_false(ok, "官方仍然阻止时不能返回验证成功")
Assert.eq(failure, "验证失败,请重新验证")
block_code = 0
fail_code = 403
Client.qrVerifyAsync(session, "id", "{}", function(value, err) ok, failure = value, err end)
Assert.is_false(ok)
Assert.eq(failure, "rejected")
fail_code = nil
defer = true
local called = false
local handle = Client.qrVerifyAsync(session, "id", "{}", function() called = true end)
before = #calls
handle.cancel()
Assert.is_true(cancelled)
pending(response({ success = true }))
Assert.is_false(called)
Assert.eq(#calls, before)
scripts = { "https://cstaticdun.126.net/load.min.js", "https://captcha.zhihu.com.evil.test/api/v1/captcha/js?sessionId=x" }
Client.qrCaptchaAsync(session, function(value, err) config, failure = value, err end)
Assert.is_nil(config)
Assert.eq(failure, "知乎登录响应异常,请重新获取二维码")
+156
View File
@@ -0,0 +1,156 @@
--[[--
知乎独立验证页:临时票据、同会话提交、失败重试与取消。
@module tests.moonsource_zhihu.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 Ext = require("utils.extension")
Ext.reset()
local timers = {}
package.loaded["ui/uimanager"] = {
scheduleIn = function(_self, _delay, fn) timers[fn] = true end,
unschedule = function(_self, fn) timers[fn] = nil end,
}
package.loaded["ui.guard"] = { wrap = function(_label, fn) return fn end }
local config_done, verify_done, config_cancelled, verify_cancelled
local received_session, received_id, received_result
package.loaded["moonsource_zhihu.client"] = {
qrCaptchaAsync = function(session, cb)
received_session, config_done = session, cb
return { cancel = function() config_cancelled = true end }
end,
qrVerifyAsync = function(session, id, result, cb)
received_session, received_id, received_result, verify_done = session, id, result, cb
return { cancel = function() verify_cancelled = true end }
end,
}
local path
Ext.add("web.open_page", function(url, _title, _text, opts)
path = url
return require("ui.themes.widgets.qr"):new{ close_callback = opts.close_callback }:show()
end)
local Verification = require("moonsource_zhihu.verify")
local route = Ext.list("web.routes")[1]
Assert.eq(route.name, "zhihu_verify")
Assert.eq(route.assets[1], "zhihu_verify.html")
Assert.is_true(route.public.config)
Assert.is_true(route.public.verify)
local status, response, headers
local function request(action, ticket, result, method)
route.handle(method or "POST", action, { ticket = ticket, result = result }, function(code, body, extra)
status, response, headers = code, body, extra
end)
end
local finished, finish_err
local original = { jar = { _xsrf = "device-only", d_c0 = "device-only" }, token = "qr" }
local function newSession()
finished, finish_err = nil, nil
return Verification.new(original, function(ok, err) finished, finish_err = ok, err end)
end
local scripts = { "https://cstaticdun.126.net/load.min.js",
"https://captcha.zhihu.com/api/v1/captcha/js?sessionId=fixture" }
local function configure(ticket)
request("config", ticket)
config_done({ scripts = scripts, session_id = "fixture" })
end
local session = newSession()
local ticket = path:match("#(.+)$")
Assert.matches(path, "^/zhihu_verify%.html#%x+$")
request("config", "wrong")
Assert.eq(status, 403)
request("config", ticket, nil, "GET")
Assert.eq(status, 405)
request("unknown", ticket)
Assert.eq(status, 404)
request("verify", ticket, "{}")
Assert.eq(status, 400, "还没加载挑战不能提交")
request("config", ticket)
Assert.eq(received_session, original)
request("config", ticket)
Assert.eq(status, 409)
config_done(nil, "network failed")
Assert.eq(status, 400)
Assert.eq(response.error, "network failed")
Assert.is_nil(finished)
configure(ticket)
Assert.eq(status, 200)
Assert.eq(response.title, "知乎安全验证")
Assert.eq(response.scripts, scripts)
Assert.is_nil(response.cookie, "Cookie 不发送到验证页面")
Assert.is_nil(response.jar)
Assert.is_nil(response.session_id, "提交时由设备决定挑战标识")
Assert.eq(headers[1], "Cache-Control: no-store")
request("verify", ticket, {})
Assert.eq(status, 400)
request("verify", ticket, string.rep("a", 16385))
Assert.eq(status, 400)
request("verify", ticket, '{"validate":"proof"}')
Assert.eq(received_session, original)
Assert.eq(received_id, "fixture")
Assert.eq(received_result, '{"validate":"proof"}')
request("config", ticket)
Assert.eq(status, 409)
verify_done(false, "not accepted")
Assert.eq(status, 400)
Assert.eq(response.error, "not accepted")
Assert.is_nil(finished)
request("verify", ticket, '{"validate":"retry"}')
verify_done(true)
Assert.eq(status, 200)
Assert.is_true(finished)
Assert.is_nil(finish_err)
Assert.is_true(session.dialog.closed)
Assert.is_nil(next(timers))
request("verify", ticket, "{}")
Assert.eq(status, 403, "成功票据不可重放")
session = newSession()
ticket = path:match("#(.+)$")
request("config", ticket)
session.dialog:close()
Assert.is_false(finished)
Assert.eq(finish_err, "验证已取消")
Assert.is_true(config_cancelled)
config_done({ scripts = scripts, session_id = "late" })
Assert.eq(status, 403)
Assert.is_false(finished)
session = newSession()
ticket = path:match("#(.+)$")
configure(ticket)
request("verify", ticket, "{}")
session:cancel()
Assert.is_true(verify_cancelled)
verify_done(true)
Assert.eq(status, 403)
Assert.is_nil(finished, "主动取消不接受迟到回调")
session = newSession()
ticket = path:match("#(.+)$")
session.timeout()
Assert.is_false(finished)
Assert.eq(finish_err, "验证已过期,请重新发起验证")
request("config", ticket)
Assert.eq(status, 403)
session = newSession()
ticket = path:match("#(.+)$")
request("config", ticket)
session.expires = os.time() - 1
config_done({ scripts = scripts, session_id = "expired" })
Assert.eq(status, 403)
Assert.is_false(finished)
Ext.reset()
session = newSession()
Assert.is_true(session.done)
Assert.is_false(finished)
Assert.eq(finish_err, "无法打开远程验证,请先连接 Wi-Fi 并启用远程管理功能")
Assert.is_nil(next(timers))
+82
View File
@@ -0,0 +1,82 @@
'use strict';
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const path = require('node:path');
const source = fs.readFileSync(path.join(process.argv[2], 'moonsource-zhihu.koplugin/moonsource_zhihu/web/zhihu_verify.js'), 'utf8');
async function page(options = {}) {
const nodes = Object.fromEntries(['title', 'instruction', 'status', 'retry', 'captcha-element'].map(id =>
[id, { textContent: '', hidden: false, replaceChildren() {} }]));
const requests = [], loaded = [];
let callback, closed = 0, shown = 0;
const messages = {
scripts: options.scripts || ['https://cstaticdun.126.net/load.min.js',
'https://captcha.zhihu.com/api/v1/captcha/js?sessionId=fixture'],
title: 'Zhihu', instruction: 'Verify', pending: 'Submitting',
success: 'Verified', failure: 'Rejected', load_error: 'Load failed', retry: 'Retry',
};
const context = {
AbortController, setTimeout, clearTimeout, URL,
location: { hash: '#temporary-ticket' },
document: {
getElementById: id => nodes[id],
createElement: () => ({}),
head: { appendChild(script) { loaded.push(script.src); script.onload(); } },
},
fetch: async (url, request) => {
requests.push({ url, body: JSON.parse(request.body) });
if (options.offline) throw new Error('offline');
if (url.endsWith('/config')) return { ok: true, json: async () => messages };
return { ok: !options.reject, json: async () => options.reject ? { error: 'server rejected' } : { ok: true } };
},
window: { ZS_CAP: { init: async config => {
callback = config.callback;
return { show() { shown++; }, close() { closed++; } };
} } },
};
await vm.runInNewContext(source, context);
return { nodes, requests, loaded, callback, closed: () => closed, shown: () => shown };
}
(async () => {
let p = await page();
assert.equal(p.shown(), 1);
assert.equal(p.loaded.length, 2);
assert.equal(p.nodes.title.textContent, 'Zhihu');
assert.equal(p.requests[0].url, '/api/zhihu_verify/config');
assert.equal(p.requests[0].body.ticket, 'temporary-ticket');
await p.callback({ type: 'vendor', result: { validate: 'user-proof' } });
assert.equal(p.requests[1].url, '/api/zhihu_verify/verify');
assert.equal(p.requests[1].body.result, '{"validate":"user-proof"}');
assert.equal(p.requests[1].body.ticket, 'temporary-ticket');
assert.equal(p.nodes.status.textContent, 'Verified');
assert.equal(p.nodes['captcha-element'].hidden, true);
assert.equal(p.nodes.retry.hidden, true);
assert.equal(p.closed(), 1);
p = await page({ reject: true });
await p.callback({ type: 'vendor', result: { validate: 'bad-proof' } });
assert.equal(p.nodes.status.textContent, 'server rejected');
assert.equal(p.nodes.retry.hidden, false);
await p.nodes.retry.onclick();
assert.equal(p.requests[2].url, '/api/zhihu_verify/config');
assert.equal(p.shown(), 2);
assert.equal(p.closed(), 1);
p = await page();
await p.callback(new Error('SDK failed'));
assert.equal(p.requests.length, 1);
assert.equal(p.nodes.status.textContent, 'Rejected');
p = await page({ scripts: ['https://captcha.zhihu.com.evil.test/api/v1/captcha/js?sessionId=x'] });
assert.equal(p.loaded.length, 0);
assert.equal(p.nodes.status.textContent, 'Load failed');
assert.equal(p.shown(), 0);
p = await page({ offline: true });
assert.equal(p.nodes.status.textContent, 'offline');
assert.equal(p.nodes.retry.hidden, false);
assert.equal(p.shown(), 0);
console.log('zhihu web: OK');
})().catch(error => { console.error(error); process.exitCode = 1; });
+13
View File
@@ -0,0 +1,13 @@
--[[--
知乎独立验证网页回归,无 npm 依赖。
@module tests.moonsource_zhihu.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("zhihu web: OK", 1, true) ~= nil, output)