From 6379a117c214cb5b01c24a8af52e375ae1c52f3a Mon Sep 17 00:00:00 2001 From: Garfield Date: Mon, 16 Nov 2026 12:07:59 +0800 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20=E5=88=9D=E5=A7=8B=E6=8F=90?= =?UTF-8?q?=E4=BA=A4=EF=BC=9A=E6=9C=88=E8=AF=BB=E7=AC=AC=E4=B8=89=E6=96=B9?= =?UTF-8?q?=E4=B9=A6=E6=BA=90=E6=8F=92=E4=BB=B6=E9=9B=86=E5=90=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 每个书源一个独立插件目录,含微信读书公众号订阅、书架导入等完整功能。 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- moonsource-zhihu.koplugin/README.md | 23 + moonsource-zhihu.koplugin/_meta.lua | 5 + moonsource-zhihu.koplugin/main.lua | 9 + moonsource-zhihu.koplugin/moon_source.lua | 15 + .../moonsource_zhihu/_meta.lua | 17 + .../moonsource_zhihu/client.lua | 716 ++++++++++++++++++ .../moonsource_zhihu/content.lua | 100 +++ .../moonsource_zhihu/emoticons.lua | 89 +++ .../moonsource_zhihu/font.lua | 86 +++ .../moonsource_zhihu/l10n/en.lua | 59 ++ .../moonsource_zhihu/l10n/zh_TW.lua | 59 ++ .../moonsource_zhihu/loadmeta.lua | 5 + .../moonsource_zhihu/mapper.lua | 261 +++++++ .../moonsource_zhihu/qrlogin.lua | 177 +++++ .../moonsource_zhihu/setting.lua | 72 ++ .../moonsource_zhihu/sign.lua | 78 ++ .../moonsource_zhihu/source.lua | 325 ++++++++ .../moonsource_zhihu/story.lua | 125 +++ .../moonsource_zhihu/verify.lua | 128 ++++ .../moonsource_zhihu/web/zhihu_verify.html | 25 + .../moonsource_zhihu/web/zhihu_verify.js | 78 ++ tests/zhihu/browse_spec.lua | 76 ++ tests/zhihu/catalog_spec.lua | 76 ++ tests/zhihu/client_spec.lua | 181 +++++ tests/zhihu/content_layout_spec.lua | 96 +++ tests/zhihu/content_spec.lua | 118 +++ tests/zhihu/detail_spec.lua | 98 +++ tests/zhihu/font_spec.lua | 102 +++ tests/zhihu/login_spec.lua | 245 ++++++ tests/zhihu/progress_client_spec.lua | 114 +++ tests/zhihu/progress_spec.lua | 86 +++ tests/zhihu/qrlogin_spec.lua | 163 ++++ tests/zhihu/reviews_spec.lua | 153 ++++ tests/zhihu/setting_spec.lua | 161 ++++ tests/zhihu/sign_spec.lua | 38 + tests/zhihu/story_spec.lua | 159 ++++ tests/zhihu/verify_client_spec.lua | 101 +++ tests/zhihu/verify_spec.lua | 156 ++++ tests/zhihu/web_spec.js | 82 ++ tests/zhihu/web_spec.lua | 13 + 40 files changed, 4670 insertions(+) create mode 100644 moonsource-zhihu.koplugin/README.md create mode 100644 moonsource-zhihu.koplugin/_meta.lua create mode 100644 moonsource-zhihu.koplugin/main.lua create mode 100644 moonsource-zhihu.koplugin/moon_source.lua create mode 100644 moonsource-zhihu.koplugin/moonsource_zhihu/_meta.lua create mode 100644 moonsource-zhihu.koplugin/moonsource_zhihu/client.lua create mode 100644 moonsource-zhihu.koplugin/moonsource_zhihu/content.lua create mode 100644 moonsource-zhihu.koplugin/moonsource_zhihu/emoticons.lua create mode 100644 moonsource-zhihu.koplugin/moonsource_zhihu/font.lua create mode 100644 moonsource-zhihu.koplugin/moonsource_zhihu/l10n/en.lua create mode 100644 moonsource-zhihu.koplugin/moonsource_zhihu/l10n/zh_TW.lua create mode 100644 moonsource-zhihu.koplugin/moonsource_zhihu/loadmeta.lua create mode 100644 moonsource-zhihu.koplugin/moonsource_zhihu/mapper.lua create mode 100644 moonsource-zhihu.koplugin/moonsource_zhihu/qrlogin.lua create mode 100644 moonsource-zhihu.koplugin/moonsource_zhihu/setting.lua create mode 100644 moonsource-zhihu.koplugin/moonsource_zhihu/sign.lua create mode 100644 moonsource-zhihu.koplugin/moonsource_zhihu/source.lua create mode 100644 moonsource-zhihu.koplugin/moonsource_zhihu/story.lua create mode 100644 moonsource-zhihu.koplugin/moonsource_zhihu/verify.lua create mode 100644 moonsource-zhihu.koplugin/moonsource_zhihu/web/zhihu_verify.html create mode 100644 moonsource-zhihu.koplugin/moonsource_zhihu/web/zhihu_verify.js create mode 100644 tests/zhihu/browse_spec.lua create mode 100644 tests/zhihu/catalog_spec.lua create mode 100644 tests/zhihu/client_spec.lua create mode 100644 tests/zhihu/content_layout_spec.lua create mode 100644 tests/zhihu/content_spec.lua create mode 100644 tests/zhihu/detail_spec.lua create mode 100644 tests/zhihu/font_spec.lua create mode 100644 tests/zhihu/login_spec.lua create mode 100644 tests/zhihu/progress_client_spec.lua create mode 100644 tests/zhihu/progress_spec.lua create mode 100644 tests/zhihu/qrlogin_spec.lua create mode 100644 tests/zhihu/reviews_spec.lua create mode 100644 tests/zhihu/setting_spec.lua create mode 100644 tests/zhihu/sign_spec.lua create mode 100644 tests/zhihu/story_spec.lua create mode 100644 tests/zhihu/verify_client_spec.lua create mode 100644 tests/zhihu/verify_spec.lua create mode 100644 tests/zhihu/web_spec.js create mode 100644 tests/zhihu/web_spec.lua diff --git a/moonsource-zhihu.koplugin/README.md b/moonsource-zhihu.koplugin/README.md new file mode 100644 index 0000000..81c562c --- /dev/null +++ b/moonsource-zhihu.koplugin/README.md @@ -0,0 +1,23 @@ +# 知乎盐选 + +| 能力 | 是否支持 | 备注 | +| --- | --- | --- | +| App 扫码登录 | 支持 | 新会话校验成功后保存 | +| 浏览器登录与 Cookie 导入 | 支持 | 扩展授权或手动粘贴 | +| 设备密码登录 | 不支持 | 其他登录方式交由知乎官网完成 | +| 推荐、榜单与搜索 | 部分支持 | 推荐、热搜及多种盐选榜单;仅首批数据,搜索可能需登录并受风控限制 | +| 详情与评分 | 支持 | 短篇及长篇专栏元数据、评分 | +| 长篇目录 | 支持 | 分页读取并保留章节顺序 | +| 完整正文 | 支持 | 需有效账号及对应权限,恢复动态字体;折叠或未购预览不作完整正文 | +| 短篇阅读 | 支持 | 整篇转为本地 EPUB | +| 章节与全本缓存 | 支持 | 已缓存正文可离线阅读 | +| 云端书架与收藏同步 | 不支持 | 本地书库不代表知乎收藏或购买列表 | +| 远端书架新增与移出 | 不支持 | 本地增删不操作知乎网站内容 | +| 阅读进度同步 | 支持 | 长篇按远端章节及章内比例,短篇按整篇比例 | +| 笔记与统计同步 | 不支持 | 仅本地保存 | +| 整书书评 | 不支持 | 未接入可验证的独立接口 | +| 章评 | 支持 | 真正绑定盐选章节,章末入口、分页和缓存;开关仍叫「显示段评」 | +| 段评 | 不支持 | 评论没有段落定位依据 | +| 评论回复 | 支持 | 支持分页和独立缓存 | +| 评论写操作 | 不支持 | 不发评、不点赞、不删评 | +| 账号切换 | 不支持直接隔离 | 须先退出清理旧数据,未同步记录会丢失 | diff --git a/moonsource-zhihu.koplugin/_meta.lua b/moonsource-zhihu.koplugin/_meta.lua new file mode 100644 index 0000000..49a91c0 --- /dev/null +++ b/moonsource-zhihu.koplugin/_meta.lua @@ -0,0 +1,5 @@ +local _ = require("gettext") +return { + fullname = _("月读书源:知乎盐选"), + description = _("给月读增加「知乎盐选」书源。需要同时安装月读,与平台官方无关。"), +} diff --git a/moonsource-zhihu.koplugin/main.lua b/moonsource-zhihu.koplugin/main.lua new file mode 100644 index 0000000..6e10929 --- /dev/null +++ b/moonsource-zhihu.koplugin/main.lua @@ -0,0 +1,9 @@ +--[[-- +KOReader 只认带 main.lua 的插件目录;书源本身不需要任何插件钩子,月读读取旁边的 moon_source.lua。 +--]] +local WidgetContainer = require("ui/widget/container/widgetcontainer") + +return WidgetContainer:extend{ + name = "moonsource_zhihu", + is_doc_only = false, +} diff --git a/moonsource-zhihu.koplugin/moon_source.lua b/moonsource-zhihu.koplugin/moon_source.lua new file mode 100644 index 0000000..05021a6 --- /dev/null +++ b/moonsource-zhihu.koplugin/moon_source.lua @@ -0,0 +1,15 @@ +--[[-- +月读第三方书源描述:知乎盐选。契约见月读 examples/moonsource-demo.koplugin/moon_source.lua。 +--]] + +local function lazy(module) + return setmetatable({}, { __index = function(_, key) return require(module)[key] end }) +end + +return { + api = 1, + provides = { source = true }, + meta = function() return require("moonsource_zhihu.source").meta() end, + new = function() return require("moonsource_zhihu.source").new() end, + setting = lazy("moonsource_zhihu.setting"), +} diff --git a/moonsource-zhihu.koplugin/moonsource_zhihu/_meta.lua b/moonsource-zhihu.koplugin/moonsource_zhihu/_meta.lua new file mode 100644 index 0000000..e9f7806 --- /dev/null +++ b/moonsource-zhihu.koplugin/moonsource_zhihu/_meta.lua @@ -0,0 +1,17 @@ +--[[-- +书源元信息。 + +知乎盐选没有云端书架。榜单匿名可读。正文折叠时是未购买。 + +@module moonsource_zhihu._meta +--]] + +local _ = require("l10n").get("moonsource_zhihu") + +return { + id = "ext.zhihu", + name = _("知乎盐选"), + type = "chapter", + description = _("知乎盐选在线阅读"), + abilities = { _("搜索与发现"), _("VIP 章节"), _("登录"), _("进度同步"), _("他人段评") }, +} diff --git a/moonsource-zhihu.koplugin/moonsource_zhihu/client.lua b/moonsource-zhihu.koplugin/moonsource_zhihu/client.lua new file mode 100644 index 0000000..ab7d1a5 --- /dev/null +++ b/moonsource-zhihu.koplugin/moonsource_zhihu/client.lua @@ -0,0 +1,716 @@ +--[[-- +知乎盐选网页接口。 + +榜单匿名可用。搜索是 `/api/v4/search_v3?t=km_general`,没有登录态会被风控。 +正文走签名的 VIP JSON 接口,检查购买权限,再异步还原乱序字形。 + +扫码登录沿用匿名会话,确认后校验 Cookie 再保存。 + +@module moonsource_zhihu.client +--]] + +local JSON = require("json") +local Mapper = require("moonsource_zhihu.mapper") +local Sign = require("moonsource_zhihu.sign") +local Request = require("http.request") +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_zhihu") + +local Client = {} + +local API = "https://api.zhihu.com" +local WEB = "https://www.zhihu.com" +local UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" +local SOURCE_ID = "ext.zhihu" +local CAPTCHA = "https://captcha.zhihu.com/api/v1/captcha" +local CAPTCHA_APP = "lsxNQs26Wva2" + +---@class ZhihuQRSession +---@field jar table +---@field token string +---@field link string +---@field expires_at number|nil +---@field challenge_id string|nil + +---@return string|nil +function Client.cookie() + local cookie = require("utils.settings").getSource("ext.zhihu").cookie + return type(cookie) == "string" and cookie ~= "" and cookie or nil +end + +---@param headers table|nil +---@return table +local function opts(headers) + return { + timeout = require("http.timeout").net(1), + headers = require("http.request.header").merge(headers, { ["User-Agent"] = UA }), + } +end + +--- 搜索没有登录态会被风控。Cookie 存在 settings,跟其它源一样随请求带上。 +---@param headers table|nil +---@return table|nil +local function withCookie(headers) + local saved = Client.cookie() + if not saved then return headers end + headers = headers or {} + if not headers.Cookie then headers.Cookie = saved end + return headers +end + +---@param url string +---@param headers table|nil +---@param cb fun(body: string|nil, err: any) +---@return HttpJob +local function get(url, headers, cb) + local cookie = Client.cookie() + return Request.get(url, opts(withCookie(headers)), function(body, err, res) + if res and tonumber(res.code) == 401 and cookie and cookie == Client.cookie() then + cb(nil, require("source.auth").expire("ext.zhihu", _("知乎登录已失效,请重新登录"))) + return + end + cb(body, err) + end) +end + +---@param raw string|nil +---@return table|nil +local function decode(raw) + if not raw or raw == "" then return nil end + local ok, wire = pcall(JSON.decode, raw) + if not ok or type(wire) ~= "table" then return nil end + return wire +end + +---@param cookie string +---@param cb fun(ok: boolean, err: string|nil) +---@return HttpJob +function Client.loginCheckAsync(cookie, cb) + return Request.get(WEB .. "/api/v4/me", opts({ Cookie = cookie, ["User-Agent"] = UA, + Referer = WEB .. "/signin" }), function(raw, err) + local user = decode(raw) + if err or not user or user.error or type(user.id) ~= "string" or user.id == "" then + cb(false, err and tostring(err) or _("知乎登录校验失败,请在浏览器确认已登录并完成安全验证")) + return + end + cb(true) + end) +end + +---@param keyword string +---@param cb fun(books: Book[]|nil, err: string|nil) +---@return HttpJob +function Client.searchAsync(keyword, cb) + local url = WEB .. "/api/v4/search_v3?t=km_general&q=" .. Text.urlEncode(keyword) + .. "&correction=1&offset=0&limit=20&lc_idx=0&show_all_topics=0&search_source=Normal" + return get(url, { ["X-API-Version"] = "3.0.91", ["X-App-Za"] = "OS=Web" }, function(raw, err) + local books = Mapper.search(decode(raw)) + if not books then cb(nil, err and tostring(err) or _("请求失败")); return end + cb(books) + end) +end + +---@param id string 章节 id 或根评论 id +---@param offset integer|string 首页 0,其后原样带回服务端游标 +---@param replies boolean +---@param cb fun(page: WechatReviewPage|nil, err: string|nil) +---@return HttpJob +function Client.reviewsAsync(id, offset, replies, cb) + local path = replies and "/comment/" .. Text.urlEncode(id) .. "/child_comment" + or "/paid_column_section_manuscripts/" .. Text.urlEncode(id) .. "/root_comment" + local url = API .. "/comment_v5" .. path .. "?limit=" .. (replies and 5 or 20) + .. "&order_by=" .. (replies and "ts" or "score") .. "&offset=" .. Text.urlEncode(offset == 0 and "" or offset) + return get(url, { Referer = WEB .. "/" }, function(raw, err) + local page = not err and Mapper.reviewPage(decode(raw), offset) + if not page then cb(nil, err and tostring(err) or _("无法获取段评")); return end + cb(page) + end) +end + +---@param rank string +---@param filter string +---@param cb fun(books: Book[]|nil, err: string|nil, filters: table[]|nil) +---@return HttpJob +function Client.browseAsync(rank, filter, cb) + local url = API .. "/km-vip-zhihu-web/vip_tab/svip_story?modules=billboard" + .. "&billboard_type=" .. Text.urlEncode(rank) .. "&billboard_filter=" .. Text.urlEncode(filter) + .. "&offset=0&limit=10" + return get(url, { Referer = WEB .. "/fiore/h5/vip-web" }, function(raw, err) + local books, filters = Mapper.feed(decode(raw), rank) + if not books then cb(nil, err and tostring(err) or _("请求失败")); return end + cb(books, nil, filters) + end) +end + +---@param stable_id string 长篇专栏 id +---@param cb fun(wire: table|nil, err: string|nil) +---@return { cancel: fun() } +function Client.catalogAsync(stable_id, cb) + local state = { cancelled = false, job = nil } + local catalog = { data = {} } + local function fetch(offset) + local url = API .. "/remix/well/" .. Text.urlEncode(stable_id) + .. "/catalog?is_new_column=true&order_by=global_idx&limit=50&offset=" .. offset + local fired = false + local job = get(url, nil, function(raw, err) + fired = true + if state.cancelled then return end + state.job = nil + local wire = decode(raw) + if err or not wire or wire.error or type(wire.data) ~= "table" or type(wire.paging) ~= "table" then + cb(nil, err and tostring(err) or _("请求失败")) + return + end + if offset == 0 then catalog.extra = wire.extra end + for _idx, row in ipairs(wire.data) do catalog.data[#catalog.data + 1] = row end + local paging = wire.paging + if paging.has_next == true or paging.is_end == false then + local step = tonumber(paging.limit) + if #wire.data == 0 or not step or step <= 0 or tonumber(paging.offset) ~= offset then + cb(nil, _("请求失败")) + return + end + fetch(offset + step) + else + cb(catalog) + end + end) + if not fired then state.job = job end + end + fetch(0) + return { cancel = function() + state.cancelled = true + if state.job and state.job.cancel then state.job.cancel() end + end } +end + +---@param stable_id string 长篇专栏 id +---@param cb fun(book: Book|nil, err: string|nil) +---@return { cancel: fun() } +function Client.detailAsync(stable_id, cb) + local state = { cancelled = false, job = nil } + local fetched = false + local job = get(API .. "/remix/paid_columns/" .. Text.urlEncode(stable_id) + .. "?is_new_column=true&is_web=true", nil, function(raw, err) + fetched = true + if state.cancelled then return end + state.job = nil + local wire = decode(raw) + if not wire then cb(nil, err and tostring(err) or _("请求失败")); return end + local book = Mapper.detail(wire, stable_id) + if not book then cb(nil, err and tostring(err) or _("请求失败")); return end + if type(wire.sku_id) ~= "string" or wire.sku_id == "" then cb(book); return end + local graded = false + local rating_job = get(API .. "/darwin/sku_grading/" .. Text.urlEncode(wire.sku_id), nil, function(body, rating_err) + graded = true + if state.cancelled then return end + state.job = nil + local grading = decode(body) + if rating_err or not grading or grading.error then + require("utils.log").warn("zhihu rating fetch failed", rating_err or "invalid response") + cb(book) + return + end + cb(Mapper.detail(wire, stable_id, grading)) + end) + if not graded then state.job = rating_job end + end) + if not fetched then state.job = job end + return { cancel = function() + state.cancelled = true + if state.job and state.job.cancel then state.job.cancel() end + end } +end + +---@param stable_id string +---@return string|nil +---@return string|nil +local function ids(stable_id) + return tostring(stable_id):match("^(%d+)/(%d+)$") +end + +---@param stable_id string +---@param cb fun(wire: table|nil, err: string|nil) +---@return HttpJob|{ cancel: fun() } +function Client.simpleAsync(stable_id, cb) + local well, section = ids(stable_id) + if not well then + require("ui/uimanager"):nextTick(function() cb(nil, _("请求失败")) end) + return { cancel = function() end } + end + local url = API .. "/remix-web/paid_columns/" .. well .. "/sections/" .. section .. "/manuscript/simple" + return get(url, nil, function(raw, err) + local wire = decode(raw) + if type(wire) ~= "table" or type(wire.section) ~= "table" then + cb(nil, err and tostring(err) or _("请求失败")) + return + end + cb(wire) + end) +end + +---@param stable_id string +---@param cb fun(wire: table|nil, err: string|nil) +---@return HttpJob|{ cancel: fun() } +function Client.manuscriptAsync(stable_id, cb) + local well, section = ids(stable_id) + if not well then + require("ui/uimanager"):nextTick(function() cb(nil, _("请求失败")) end) + return { cancel = function() end } + end + local path = "/remix-web/paid_columns/" .. well .. "/sections/" .. section + .. "/manuscript?v=1&manuscript_version=0" + local headers = Sign.headers(path, Client.cookie()) + headers.Referer = WEB .. "/" + return get(API .. path, headers, function(raw, err) + local wire = decode(raw) + if err or not wire or wire.error then + cb(nil, err and tostring(err) or _("请求失败")); return + end + cb(wire) + end) +end + +--- 只接受未折叠的完整正文,不能把付费预览当成已购章节缓存。 +---@param stable_id string +---@param cb fun(html: string|nil, err: string|nil) +---@return { cancel: fun() } +function Client.contentAsync(stable_id, cb) + local state = { cancelled = false, request = nil, font = nil } + local fired = false + local job = Client.manuscriptAsync(stable_id, function(wire, err) + fired = true + if state.cancelled then return end + state.request = nil + if not wire then cb(nil, err); return end + if wire.is_fold == true or wire.authentication_result == false then + cb(nil, _("本章未购买")); return + end + if wire.is_fold ~= false or type(wire.manuscript) ~= "string" or wire.manuscript == "" then + cb(nil, _("请求失败")); return + end + if wire.use_font ~= true then cb(wire.manuscript); return end + local restored = false + local font_job = require("moonsource_zhihu.font").restoreAsync(wire, function(html, font_err) + restored = true + if state.cancelled then return end + state.font = nil + cb(html, font_err) + end) + if not restored then state.font = font_job end + end) + if not fired then state.request = job end + return { cancel = function() + state.cancelled = true + if state.request then state.request.cancel() end + if state.font then state.font:cancel() end + end } +end + +---@param stable_id string +---@param cb fun(progress: table|nil, err: string|nil, meta: table|nil) +---@return { cancel: fun() } +function Client.progressAsync(stable_id, cb) + if not Client.cookie() then return require("source.base").defer(cb, nil, _("请先登录知乎")) end + local cancelled, active = false, nil + local function readSection(id) + local fired = false + local job = Client.manuscriptAsync(id, function(wire, err) + fired = true + if cancelled then return end + active = nil + if not wire then cb(nil, err); return end + local progress = Mapper.progress(wire) + local _column, section = ids(id) + if not progress or progress.section_id ~= section then cb(nil, _("请求失败")); return end + if progress.fraction == nil then + if stable_id:find("/", 1, true) then cb(nil, nil, { empty = true }); return end + progress.fraction = 0 + end + cb(progress) + end) + if not fired then active = job end + end + if ids(stable_id) then + readSection(stable_id) + elseif stable_id:match("^%d+$") then + local fired = false + local job = get(API .. "/remix/paid_columns/" .. stable_id .. "?is_new_column=true&is_web=true", nil, + function(raw, err) + fired = true + if cancelled then return end + active = nil + local wire = decode(raw) + if err or not wire or wire.error then cb(nil, err and tostring(err) or _("请求失败")); return end + local section = wire.last_learned_section_id + if section == nil or section == JSON.null or section == "0" or section == 0 or section == "" then + cb(nil, nil, { empty = true }); return + end + if type(section) ~= "string" or not section:match("^%d+$") then cb(nil, _("请求失败")); return end + readSection(stable_id .. "/" .. section) + end) + if not fired then active = job end + else + return require("source.base").defer(cb, nil, _("请求失败")) + end + return { cancel = function() + cancelled = true + if active then active.cancel() end + end } +end + +---@param section_id string +---@param fraction number +---@param cb fun(ok: boolean|nil, err: string|nil) +---@return HttpJob|{ cancel: fun() } +function Client.putProgressAsync(section_id, fraction, cb) + local cookie = Client.cookie() + if not cookie then return require("source.base").defer(cb, nil, _("请先登录知乎")) end + if not section_id:match("^%d+$") or fraction ~= fraction or fraction < 0 or fraction > 1 then + return require("source.base").defer(cb, nil, _("缺少知乎阅读位置")) + end + local body = JSON.encode({ { + unit_id = section_id, type = "paid_column", progress = fraction, + client_updated_at = os.time() * 1000, is_finished = fraction == 1, + } }) + return Request.post(API .. "/promus/progress", body, opts(withCookie({ + ["Content-Type"] = "application/json", Referer = WEB .. "/", + })), function(raw, err, res) + if res and tonumber(res.code) == 401 and cookie == Client.cookie() then + cb(nil, require("source.auth").expire("ext.zhihu", _("知乎登录已失效,请重新登录"))) + return + end + local wire = decode(raw) + if err or not wire or wire.error or wire.success ~= true then + cb(nil, err and tostring(err) or _("请求失败")) + return + end + cb(true) + end) +end + +local function remember(jar, header) + if type(header) ~= "string" or header == "" then return end + local name, value = header:match("^%s*([^=;%s]+)=([^;]*)") + if name then jar[name] = value ~= "" and value ~= '""' and value or nil end +end + +local function cookieHeader(jar) + local names = {} + for name in pairs(jar) do names[#names + 1] = name end + table.sort(names) + if #names == 0 then return nil end + local parts = {} + for _idx, name in ipairs(names) do parts[#parts + 1] = name .. "=" .. jar[name] end + return table.concat(parts, "; ") +end + +---@param jar table +---@param res table|nil +local function absorb(jar, res) + for _idx, line in ipairs(Request.headerAll(res, "Set-Cookie")) do remember(jar, line) end +end + +---@param wire table|nil +---@param err any +---@return string +local function failMessage(wire, err) + local detail = type(wire) == "table" and wire.error or nil + if type(detail) == "table" and tonumber(detail.code) == 40352 then + return _("知乎需要安全验证,请在网页完成验证后继续扫码登录") + end + if type(detail) == "table" and type(detail.message) == "string" and detail.message ~= "" then + return detail.message + end + if type(err) == "string" and err ~= "" then return err end + return _("登录失败") +end + +---@param raw string|nil +---@param res table|nil +---@return table|nil +local function wireOf(raw, res) + return decode(raw) or decode(res and res.body) +end + +local function unexpectedResponse(stage, wire, res) + local fields = {} + for _idx, key in ipairs({ "token", "link", "status", "login_status", "cookie", "script", "error" }) do + fields[#fields + 1] = key .. "=" .. type(wire and wire[key]) + end + require("utils.log").warn("zhihu login unexpected response", stage, + "HTTP", res and res.code or "-", "body_bytes", + res and type(res.body) == "string" and #res.body or 0, table.concat(fields, " ")) + return _("知乎登录响应异常,请重新获取二维码") +end + +---@param jar table +---@param extra table|nil +---@return table +local function webHeaders(jar, extra) + extra = extra or {} + local headers = { + ["User-Agent"] = UA, + Accept = "*/*", + Referer = WEB .. "/signin", + Origin = WEB, + ["x-requested-with"] = "fetch", + } + local cookie = cookieHeader(jar) + if cookie then headers.Cookie = cookie end + if extra.post and jar._xsrf then headers["x-xsrftoken"] = jar._xsrf end + if extra.path then + headers["x-zse-93"] = "101_3_3.0" + end + return headers +end + +---@param session ZhihuQRSession +---@param wire table|nil +---@return ZhihuQRSession|nil +local function verification(session, wire) + local detail = wire and wire.error + if type(detail) ~= "table" or tonumber(detail.code) ~= 40352 then return nil end + local redirect = detail.redirect + session.challenge_id = type(redirect) == "string" and Text.urlDecode(redirect:match("[?&]session=([^&]+)")) or nil + return session +end + +--- 首页是文档导航,不带接口用的 fetch 头。302 也会下发 sec_token。 +---@param jar table +---@return table +local function documentHeaders(jar) + local headers = { + ["User-Agent"] = UA, + Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", + ["Accept-Language"] = "zh-CN,zh;q=0.9", + } + local cookie = cookieHeader(jar) + if cookie then headers.Cookie = cookie end + return headers +end + +---@param res table|nil +---@return string|nil +local function unhumanPath(res) + local loc = Request.headerAll(res, "Location")[1] + if type(loc) ~= "string" or loc == "" then return nil end + loc = loc:gsub("^https://www%.zhihu%.com", "") + if not loc:match("^/account/unhuman[?/]") and loc ~= "/account/unhuman" then return nil end + return loc +end + +---@param cb fun(session: ZhihuQRSession|nil, err: string|nil, challenge: ZhihuQRSession|nil) +---@param session ZhihuQRSession|nil 验证后沿用原会话重新出码 +---@return { cancel: fun() } +function Client.qrCreateAsync(cb, session) + session = session or { jar = {} } + local state = { cancelled = false, job = nil } + local steps = { + { path = "/signin", document = true }, + { path = "/udid", body = "{}" }, + { path = "/api/v3/oauth/captcha/v2?type=captcha_sign_in" }, + { path = "/api/v3/account/api/login/qrcode", body = "{}", create = true }, + } + local function advance(index) + local step = steps[index] + if step.create and (not session.jar.d_c0 or not session.jar._xsrf) then + cb(nil, _("知乎未下发登录会话,请重新获取二维码")) + return + end + local options = { + headers = step.document and documentHeaders(session.jar) + or webHeaders(session.jar, { post = step.body ~= nil }), + content_type = step.body and "application/json;charset=UTF-8" or nil, + timeout = require("http.timeout").net(1), + } + local fired = false + local function received(raw, err, res) + fired = true + if state.cancelled then return end + state.job = nil + absorb(session.jar, res) + local wire = wireOf(raw, res) + local path = step.path == "/signin" and unhumanPath(res) + if path and tonumber(res.code) == 302 then + table.insert(steps, index + 1, { path = path, document = true }) + elseif err or (wire and wire.error) then + cb(nil, failMessage(wire, err), verification(session, wire)) + return + end + if index < #steps then advance(index + 1); return end + if not wire or type(wire.token) ~= "string" or wire.token == "" + or type(wire.link) ~= "string" or wire.link == "" then + cb(nil, unexpectedResponse("create", wire, res)) + return + end + session.token = wire.token + -- 网关会把接口路径追加为查询串;token 已在路径里。 + session.link = wire.link:gsub("%?/api/login/qrcode$", "") + session.expires_at = tonumber(wire.expires_at) + cb(session) + end + local job + if step.body then + job = Request.post(WEB .. step.path, step.body, options, received) + else + job = Request.get(WEB .. step.path, options, received) + end + if not fired then state.job = job end + end + advance(1) + return { cancel = function() + state.cancelled = true + if state.job and state.job.cancel then state.job.cancel() end + end } +end + +--- 轮询结果:ok 已校验并保存;wait / scanned 继续;refresh 换码;expired 过期;nil 失败。 +---@param session ZhihuQRSession +---@param cb fun(kind: string|nil, extra: table|nil, err: string|nil) +---@return { cancel: fun() } +function Client.qrPollAsync(session, cb) + local state = { cancelled = false, job = nil } + local path = "/api/v3/account/api/login/qrcode/" .. Text.urlEncode(session.token) .. "/scan_info" + local fired = false + local job = Request.get(WEB .. path, { + headers = webHeaders(session.jar, { path = path }), + timeout = require("http.timeout").net(1), + }, function(raw, err, res) + fired = true + if state.cancelled then return end + state.job = nil + absorb(session.jar, res) + local wire = wireOf(raw, res) + if err or (wire and wire.error) then + local challenge = verification(session, wire) + cb(challenge and "verify" or nil, challenge, failMessage(wire, err)) + return + end + if not wire then cb(nil, nil, unexpectedResponse("poll", wire, res)); return end + remember(session.jar, wire.cookie) + local status = tonumber(wire.status) + local login_status = wire.login_status + local renewed = wire.new_token or wire.newToken + if login_status == "EXPIRED" or (login_status == nil and status == 5) then + if type(renewed) == "table" and type(renewed.token) == "string" and renewed.token ~= "" + and renewed.token ~= session.token and type(renewed.link) == "string" and renewed.link ~= "" then + session.token = renewed.token + session.link = renewed.link:gsub("%?/api/login/qrcode$", "") + session.expires_at = tonumber(renewed.expires_at) + cb("refresh", session) + else + cb("expired") + end + return + end + local oauth_confirmed = status == nil and type(wire.access_token) == "string" and wire.access_token ~= "" + if login_status == "CONFIRMED" or (login_status == nil + and (status == 2 or (status == 1 and session.jar.z_c0) or oauth_confirmed)) then + if not session.jar.z_c0 then cb(nil, nil, unexpectedResponse("confirm", wire, res)); return end + local cookie = cookieHeader(session.jar) + local checked = false + local check_job = Client.loginCheckAsync(cookie, function(ok, check_err) + checked = true + if state.cancelled then return end + state.job = nil + if not ok then cb(nil, nil, check_err); return end + local settings = require("utils.settings") + settings.getSource(SOURCE_ID).cookie = cookie + settings.saveSource(SOURCE_ID) + cb("ok") + end) + if not checked then state.job = check_job end + elseif login_status == "SCANNED" or (login_status == nil and status == 1) then + cb("scanned") + elseif login_status == "WAITING" or (login_status == nil and status == 0) then + cb("wait") + else + cb(nil, nil, unexpectedResponse("poll", wire, res)) + end + end) + if not fired then state.job = job end + return { cancel = function() + state.cancelled = true + if state.job and state.job.cancel then state.job.cancel() end + end } +end + +---@param session ZhihuQRSession +---@param cb fun(config: { scripts: string[], session_id: string }|nil, err: string|nil) +---@return HttpJob +function Client.qrCaptchaAsync(session, cb) + return Request.post(CAPTCHA, '{"appId":"' .. CAPTCHA_APP .. '","data":{}}', { + headers = webHeaders(session.jar), + content_type = "application/json", + timeout = require("http.timeout").net(1), + }, function(raw, err, res) + absorb(session.jar, res) + local wire = wireOf(raw, res) + if err or not wire or wire.error then cb(nil, failMessage(wire, err)); return end + local scripts = wire.script + if type(scripts) ~= "table" or #scripts ~= 2 + or scripts[1] ~= "https://cstaticdun.126.net/load.min.js" + or type(scripts[2]) ~= "string" + or not scripts[2]:match("^https://captcha%.zhihu%.com/api/v1/captcha/js%?") then + cb(nil, unexpectedResponse("captcha", wire, res)) + return + end + local id = scripts[2]:match("[?&]sessionId=([^&]+)") + if not id then cb(nil, unexpectedResponse("captcha", wire, res)); return end + cb({ scripts = scripts, session_id = Text.urlDecode(id) }) + end) +end + +---@param session ZhihuQRSession +---@param session_id string 官方挑战标识,只由设备持有 +---@param result string 用户完成控件后返回的 JSON 票据 +---@param cb fun(ok: boolean, err: string|nil) +---@return { cancel: fun() } +function Client.qrVerifyAsync(session, session_id, result, cb) + local state = { cancelled = false, job = nil } + local appeal = WEB .. "/api/v4/anticrawl/new_captcha_appeal" + local steps = { + { url = CAPTCHA, method = "PUT", body = JSON.encode({ + appId = CAPTCHA_APP, sessionId = session_id, ticket = result, + }) }, + { url = appeal, method = "POST", + body = session.challenge_id and JSON.encode({ session = session.challenge_id }) or "{}" }, + { url = appeal .. "?session=" .. Text.urlEncode(session.challenge_id or ""), method = "GET" }, + } + local function advance(index) + local step = steps[index] + local fired = false + local headers = webHeaders(session.jar, { post = step.method ~= "GET" }) + if step.body then headers["Content-Type"] = "application/json" end + local job = Request.request({ + url = step.url, method = step.method, body = step.body, headers = headers, + timeout = require("http.timeout").net(1), + }, function(res, err) + fired = true + if state.cancelled then return end + state.job = nil + absorb(session.jar, res) + local wire = wireOf(nil, res) + if err or not res or not Request.ok(res.code) or not wire or wire.error then + cb(false, failMessage(wire, err)) + return + end + if index == 1 and wire.success ~= true then cb(false, _("验证失败,请重新验证")); return end + if index == #steps then + local ok = wire.code == 0 or wire.block_level == 0 + cb(ok, not ok and _("验证失败,请重新验证") or nil) + return + end + advance(index + 1) + end) + if not fired then state.job = job end + end + advance(1) + return { cancel = function() + state.cancelled = true + if state.job and state.job.cancel then state.job.cancel() end + end } +end + +return Client diff --git a/moonsource-zhihu.koplugin/moonsource_zhihu/content.lua b/moonsource-zhihu.koplugin/moonsource_zhihu/content.lua new file mode 100644 index 0000000..57912ad --- /dev/null +++ b/moonsource-zhihu.koplugin/moonsource_zhihu/content.lua @@ -0,0 +1,100 @@ +--[[-- +盐选正文:移除备案号,保留原文节点顺序,在末尾留出章评区。 + +@module moonsource_zhihu.content +--]] + +local Content = {} + +Content.ANCHOR = "moon-chapter-reviews" +Content.FOOTER = '
' + +---@param html string +---@return string +function Content.prepare(html) + html = html:gsub("]-id%s*=%s*([\"'])vipyxcode%1[^>]*>.-", "") + if html:find('id="' .. Content.ANCHOR .. '"', 1, true) then return html end + local ending = html:find("", 1, true) + if ending then return html:sub(1, ending - 1) .. Content.FOOTER .. html:sub(ending) end + return html .. Content.FOOTER +end + +--- 原地升级章节缓存,不改原文节点的序号;失败不覆盖旧文件。 +---@param path string +---@return boolean +function Content.reuse(path) + local file = assert(io.open(path, "rb")) + local raw, read_err = file:read("*a") + file:close() + assert(raw, read_err) + local html = Content.prepare(raw) + if html == raw then return true end + local temp = path .. ".part" + file = assert(io.open(temp, "wb")) + local written, write_err = file:write(html) + local closed, close_err = file:close() + if not written or not closed then + os.remove(temp) + error(write_err or close_err) + end + local renamed, rename_err = os.rename(temp, path) + if not renamed then os.remove(temp); error(rename_err) end + return true +end + +--- 仅升级本源由 text2epub 生成的短篇:不重新排版,不动既有正文节点。 +---@param path string +---@param original string 旧章节 HTML,用来精确识别转换前的备案号文字 +---@return boolean|nil, string|nil +function Content.upgradeStory(path, original) + local Archiver = require("ffi/archiver") + local Text = require("utils.text") + local reader = Archiver.Reader:new() + if not reader:open(path) then return nil, reader.err end + local entries, last, last_idx = {}, nil, 0 + for entry in reader:iterate() do + if entry.mode == "file" then + local raw = reader:extractToMemory(entry.path) + if not raw then + local err = reader.err + reader:close() + return nil, err + end + entries[#entries + 1] = { path = entry.path, data = raw } + local idx = tonumber(entry.path:match("^OEBPS/chapter_(%d+)%.xhtml$")) + if idx and idx > last_idx then last, last_idx = entries[#entries], idx end + end + end + local read_err = reader.err + reader:close() + if read_err then return nil, read_err end + if not last then return nil, require("l10n").get("moonsource_zhihu")("无文本内容") end + local updated = Content.prepare(last.data) + local _quote, watermark = original:match("]-id%s*=%s*([\"'])vipyxcode%1[^>]*>(.-)") + if watermark then + watermark = Text.stripHtml(watermark) + updated = updated:gsub("(]*>)(.-)

", function(open, inner) + return open .. (Text.stripHtml(inner) == watermark and "" or inner) .. "

" + end) + end + if updated == last.data then return true end + last.data = updated + local temp = path .. ".part" + local writer = Archiver.Writer:new() + if not writer:open(temp, "epub") then return nil, writer.err end + for _idx, entry in ipairs(entries) do + writer:setZipCompression(entry.path == "mimetype" and "store" or "deflate") + if not writer:addFileFromMemory(entry.path, entry.data, os.time()) then + local err = writer.err + writer:close() + os.remove(temp) + return nil, err + end + end + writer:close() + local renamed, err = os.rename(temp, path) + if not renamed then os.remove(temp); return nil, err end + return true +end + +return Content diff --git a/moonsource-zhihu.koplugin/moonsource_zhihu/emoticons.lua b/moonsource-zhihu.koplugin/moonsource_zhihu/emoticons.lua new file mode 100644 index 0000000..7d5aa8e --- /dev/null +++ b/moonsource-zhihu.koplugin/moonsource_zhihu/emoticons.lua @@ -0,0 +1,89 @@ +--[[-- +知乎官方表情占位符与静态图地址,仅在评论确实用到时下载。 +来源:https://unpkg.zhimg.com/@cfe/emoticon@1.5.0/lib/emoticon.js +同名表情保留官方目录中首先出现的一项。 + +@module moonsource_zhihu.emoticons +--]] + +return { + ["[感谢]"] = "https://pic1.zhimg.com/v2-694cac2ec9f3c63f774e723f77d8c840.png", + ["[哇]"] = "https://picx.zhimg.com/v2-6a766571a6d6d3a4d8d16f433e5b284c.png", + ["[打招呼]"] = "https://picx.zhimg.com/v2-95c560d0c9c0491f6ef404cc010878fc.png", + ["[握手]"] = "https://pic2.zhimg.com/v2-f5aa165e86b5c9ed3b7bee821da59365.png", + ["[知乎益蜂]"] = "https://pica.zhimg.com/v2-11d9b8b6edaae71e992f95007c777446.png", + ["[百分百赞]"] = "https://picx.zhimg.com/v2-27521d5ba23dfc1ea58fd9ebb220e304.png", + ["[为爱发乎]"] = "https://pic1.zhimg.com/v2-609b1f168acfa22d59fa09d3cb0846ee.png", + ["[脑爆]"] = "https://pica.zhimg.com/v2-b6f53e9726998343e7713f564a422575.png", + ["[暗中学习]"] = "https://pica.zhimg.com/v2-5dc88b4f8cbc58d7597e2134a384e392.png", + ["[匿了]"] = "https://pic1.zhimg.com/v2-c1e799b8357888525ec45793e8270306.png", + ["[谢邀]"] = "https://pic2.zhimg.com/v2-6fe2283baa639ae1d7c024487f1d68c7.png", + ["[赞同]"] = "https://pic2.zhimg.com/v2-419a1a3ed02b7cfadc20af558aabc897.png", + ["[蹲]"] = "https://pic4.zhimg.com/v2-66e5de3da039ac969d3b9d4dc5ef3536.png", + ["[爱]"] = "https://pic1.zhimg.com/v2-0942128ebfe78f000e84339fbb745611.png", + ["[耶]"] = "https://pic2.zhimg.com/v2-f3b3b8756af8b42bd3cb534cbfdbe741.png", + ["[惊喜]"] = "https://pic1.zhimg.com/v2-5c9b7521eb16507c9d2f747f3a32a813.png", + ["[思考]"] = "https://pic4.zhimg.com/v2-bffb2bf11422c5ef7d8949788114c2ab.png", + ["[酷]"] = "https://pic4.zhimg.com/v2-c96dd18b15beb196b2daba95d26d9b1c.png", + ["[大笑]"] = "https://pic1.zhimg.com/v2-3ac403672728e5e91f5b2d3c095e415a.png", + ["[微笑]"] = "https://pic1.zhimg.com/v2-3700cc07f14a49c6db94a82e989d4548.png", + ["[捂脸]"] = "https://pic1.zhimg.com/v2-b62e608e405aeb33cd52830218f561ea.png", + ["[捂嘴]"] = "https://pic4.zhimg.com/v2-0e26b4bbbd86a0b74543d7898fab9f6a.png", + ["[飙泪笑]"] = "https://pic4.zhimg.com/v2-3bb879be3497db9051c1953cdf98def6.png", + ["[害羞]"] = "https://pic4.zhimg.com/v2-52f8c87376792e927b6cf0896b726f06.png", + ["[可怜]"] = "https://pic1.zhimg.com/v2-aa15ce4a2bfe1ca54c8bb6cc3ea6627b.png", + ["[好奇]"] = "https://pic2.zhimg.com/v2-72b9696632f66e05faaca12f1f1e614b.png", + ["[流泪]"] = "https://pic4.zhimg.com/v2-dd613c7c81599bcc3085fc855c752950.png", + ["[大哭]"] = "https://pic1.zhimg.com/v2-41f74f3795489083630fa29fde6c1c4d.png", + ["[生气]"] = "https://pic4.zhimg.com/v2-6a976b21fd50b9535ab3e5b17c17adc7.png", + ["[惊讶]"] = "https://pic4.zhimg.com/v2-0d9811a7961c96d84ee6946692a37469.png", + ["[调皮]"] = "https://pic1.zhimg.com/v2-76c864a7fd5ddc110965657078812811.png", + ["[衰]"] = "https://pic1.zhimg.com/v2-d6d4d1689c2ce59e710aa40ab81c8f10.png", + ["[发呆]"] = "https://pic2.zhimg.com/v2-7f09d05d34f03eab99e820014c393070.png", + ["[机智]"] = "https://pic1.zhimg.com/v2-4e025a75f219cf79f6d1fda7726e297f.png", + ["[嘘]"] = "https://pic4.zhimg.com/v2-f80e1dc872d68d4f0b9ac76e8525d402.png", + ["[尴尬]"] = "https://pic3.zhimg.com/v2-b779f7eb3eac05cce39cc33e12774890.png", + ["[小情绪]"] = "https://pic1.zhimg.com/v2-c65aaaa25730c59f5097aca04e606d88.png", + ["[为难]"] = "https://pic1.zhimg.com/v2-132ab52908934f6c3cd9166e51b99f47.png", + ["[吃瓜]"] = "https://pic4.zhimg.com/v2-74ecc4b114fce67b6b42b7f602c3b1d6.png", + ["[语塞]"] = "https://pic2.zhimg.com/v2-58e3ec448b58054fde642914ebb850f9.png", + ["[看看你]"] = "https://pic3.zhimg.com/v2-4e4870fc6e57bb76e7e5924375cb20b6.png", + ["[撇嘴]"] = "https://pic2.zhimg.com/v2-1043b00a7b5776e2e6e1b0af2ab7445d.png", + ["[魔性笑]"] = "https://pic2.zhimg.com/v2-e6270881e74c90fc01994e8cd072bd3a.png", + ["[潜水]"] = "https://pic1.zhimg.com/v2-99bb6a605b136b95e442f5b69efa2ccc.png", + ["[口罩]"] = "https://pic4.zhimg.com/v2-6551348276afd1eaf836551b93a94636.png", + ["[开心]"] = "https://pic2.zhimg.com/v2-c99cdc3629ff004f83ff44a952e5b716.png", + ["[滑稽]"] = "https://pic4.zhimg.com/v2-8a8f1403a93ddd0a458bed730bebe19b.png", + ["[笑哭]"] = "https://pic4.zhimg.com/v2-ca0015e8ed8462cfce839fba518df585.png", + ["[白眼]"] = "https://pic2.zhimg.com/v2-d4f78d92922632516769d3f2ce055324.png", + ["[红心]"] = "https://pic2.zhimg.com/v2-9ab384e3947547851cb45765e6fc1ea8.png", + ["[柠檬]"] = "https://pic4.zhimg.com/v2-a8f46a21217d58d2b4cdabc4568fde15.png", + ["[拜托]"] = "https://pic2.zhimg.com/v2-3e36d546a9454c8964fbc218f0db1ff8.png", + ["[赞]"] = "https://pic1.zhimg.com/v2-c71427010ca7866f9b08c37ec20672e0.png", + ["[发火]"] = "https://pic1.zhimg.com/v2-d5c0ed511a09bf5ceb633387178e0d30.png", + ["[不抬杠]"] = "https://pic4.zhimg.com/v2-395d272d5635143119b1dbc0b51e05e4.png", + ["[种草]"] = "https://pic2.zhimg.com/v2-cb191a92f1296e33308b2aa16f61bfb9.png", + ["[抱抱]"] = "https://pic2.zhimg.com/v2-b2e3fa9e0b6f431bd18d4a9d5d3c6596.png", + ["[doge]"] = "https://pic4.zhimg.com/v2-501ff2e1fb7cf3f9326ec5348dc8d84f.png", + ["[666]"] = "https://pic3.zhimg.com/v2-35808905e85664eda2125a334fc7dff8.png", + ["[闭嘴]"] = "https://pic1.zhimg.com/v2-1b6c8a81fe19f2ceda77241733aadf8b.png", + ["[吃瓜中]"] = "https://pic1.zhimg.com/v2-36ee7432e619319d858b202015a80d3f.png", + ["[打脸]"] = "https://pic4.zhimg.com/v2-bb0c68fefe47605ebc91c55b7f0a167d.png", + ["[哈士奇]"] = "https://pic1.zhimg.com/v2-ffb16dd9ff04470d4efc37130ec82542.png", + ["[加油]"] = "https://pic1.zhimg.com/v2-13d3fcb823a2d323704cd74e48260627.png", + ["[纠结]"] = "https://pic1.zhimg.com/v2-57502a494dceb07009c68de3f98f7c73.png", + ["[哭]"] = "https://pic2.zhimg.com/v2-5507bf46889ec156eb781f60859ae415.png", + ["[流口水]"] = "https://pic2.zhimg.com/v2-43496a438dbde374d53c3e09dafde6c8.png", + ["[社会人]"] = "https://pic2.zhimg.com/v2-43496a438dbde374d53c3e09dafde6c8.png", + ["[生气了]"] = "https://pic2.zhimg.com/v2-76230e3ed1edcc8d3cb7047a5b78ba0e.png", + ["[思考中]"] = "https://pic1.zhimg.com/v2-9de57d1821502441814913e963f502c7.png", + ["[酸了]"] = "https://pic1.zhimg.com/v2-d53a13cbc6dac54eb406b47652fc66b8.png", + ["[偷看]"] = "https://pic1.zhimg.com/v2-a31cd513ddc2b487587805d17629d570.png", + ["[头秃]"] = "https://pic2.zhimg.com/v2-0e52bbdc84106d8a64edd043b53e8775.png", + ["[吐血]"] = "https://pic1.zhimg.com/v2-e9df774ecb65c03f359eadff6872ce02.png", + ["[旺柴]"] = "https://pic4.zhimg.com/v2-56873671e39c80904f745a895d93d0b8.png", + ["[学到了]"] = "https://pic4.zhimg.com/v2-0b0cabfad4695a46347ea494034b2c9c.png", + ["[疑问]"] = "https://pic4.zhimg.com/v2-57d961f9da6b0601c0f48686cbc848aa.png", + ["[晕]"] = "https://pic4.zhimg.com/v2-34af8e9abc783c171bb47496a7773e89.png", + ["[裂开]"] = "https://pic1.zhimg.com/v2-5533319c4f5740bd45897429c1ad3553.png", +} diff --git a/moonsource-zhihu.koplugin/moonsource_zhihu/font.lua b/moonsource-zhihu.koplugin/moonsource_zhihu/font.lua new file mode 100644 index 0000000..de4e90b --- /dev/null +++ b/moonsource-zhihu.koplugin/moonsource_zhihu/font.lua @@ -0,0 +1,86 @@ +--[[-- +盐选章节字体还原。只替换 HTML 文本节点,保留图片、段落和属性。 + +字体写临时文件供 FreeType 读取,识别放在子进程;完成、失败或取消均由父进程清理。 +只复用通用字形识别,不使用其它书源的正文规则。 + +@module moonsource_zhihu.font +--]] + +local Glyph = require("utils.glyph") +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_zhihu") + +local Font = {} + +local function restore(wire, font_path) + local font = type(wire.font) == "table" and wire.font.base64 + local encoded = type(font) == "string" and font:match("^data:font/ttf;[^,]*;base64,(.+)$") + if not encoded then return { err = _("知乎章节字体还原失败,请重试") } end + local bytes = Text.base64Decode(encoded) + if bytes:sub(1, 4) ~= "\0\1\0\0" then return { err = _("知乎章节字体还原失败,请重试") } end + local file = assert(io.open(font_path, "wb")) + assert(file:write(bytes)) + assert(file:close()) + + local codes, seen = {}, {} + for ch in Text.xmlDecode(wire.manuscript):gmatch(Text.UTF8_CHAR) do + local cp = Glyph.codepoint(ch) + if cp > 127 and not seen[cp] then + seen[cp] = true + codes[#codes + 1] = cp + end + end + table.sort(codes) + local ref = require("fontlist").fontdir .. "/noto/NotoSansCJKsc-Regular.otf" + local reference = assert(io.open(ref, "rb")) + local size = reference:seek("end") + reference:close() + local cache = require("utils.paths").cacheDir() .. "/glyph_v1_" .. size .. ".bin" + local map = Glyph.recognize(ref, cache, { { font_path = font_path, codes = codes, limit = 6763 } })[1] + for cp, char in pairs(map) do + if char == false then + require("utils.log").warn("zhihu font glyph not recognized", cp) + return { err = _("知乎章节字体还原失败,请重试") } + end + end + local function textNode(node) + local text = Text.xmlDecode(node):gsub(Text.UTF8_CHAR, function(ch) + return map[Glyph.codepoint(ch)] + end) + return Text.xmlEscape(text) + end + local parts, pos = {}, 1 + for first, after in wire.manuscript:gmatch("()<[^>]*>()") do + parts[#parts + 1] = textNode(wire.manuscript:sub(pos, first - 1)) + parts[#parts + 1] = wire.manuscript:sub(first, after - 1) + pos = after + end + parts[#parts + 1] = textNode(wire.manuscript:sub(pos)) + return { html = table.concat(parts) } +end + +---@param wire table 正文接口数据,use_font=true +---@param cb fun(html: string|nil, err: string|nil) +---@return BookJob +function Font.restoreAsync(wire, cb) + local path = require("utils.paths").tmpname(".font") + return require("workers.job").run(function() + return restore(wire, path) + end, { + name = "zhihu_font", + kind = "light", + timeout = 600, + on_done = function(result) + os.remove(path) + cb(result.html, result.err) + end, + on_failed = function(err) + os.remove(path) + cb(nil, tostring(err)) + end, + on_cancelled = function() os.remove(path) end, + }) +end + +return Font diff --git a/moonsource-zhihu.koplugin/moonsource_zhihu/l10n/en.lua b/moonsource-zhihu.koplugin/moonsource_zhihu/l10n/en.lua new file mode 100644 index 0000000..6ffbf2c --- /dev/null +++ b/moonsource-zhihu.koplugin/moonsource_zhihu/l10n/en.lua @@ -0,0 +1,59 @@ +return { + ["滑块加载失败,请检查网络后刷新网页"] = "Could not load the slider. Check your connection and refresh the page.", + ["章节评论"] = "Chapter comments", + ["知乎盐选在线阅读"] = "Zhihu Salt stories", + ["知乎章节字体还原失败,请重试"] = "Could not restore the Zhihu chapter font. Please try again.", + ["请先登录知乎"] = "Please sign in to Zhihu first", + ["缺少知乎阅读位置"] = "Missing Zhihu reading position", + ["阅读进度保存失败"] = "Failed to save reading progress", + ["已有划线,保留原始排版"] = "Keeping the original layout to preserve existing annotations", + ["短篇含图片,保留原始排版"] = "Keeping the original layout to preserve story images", + ["推荐榜"] = "Recommended", + ["热搜榜"] = "Trending searches", + ["热度榜"] = "Popular", + ["口碑榜"] = "Top rated", + ["长篇榜"] = "Novels", + ["本章未购买"] = "This chapter has not been purchased", + ["验证已过期,请重新发起验证"] = "Verification expired. Please start again", + ["正在获取二维码…"] = "Fetching QR code…", + ["章节目录保存失败"] = "Failed to save chapter list", + ["无法获取段评"] = "Failed to load reviews", + ["按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"] = "Press F12, open Network, refresh, and copy the entire Cookie request header", + ["无法打开远程验证,请先连接 Wi-Fi 并启用远程管理功能"] = "Cannot open remote verification. Connect to Wi-Fi and enable Remote management first.", + ["验证已取消"] = "Verification cancelled", + ["验证凭据无效"] = "Invalid verification proof", + ["正在提交验证…"] = "Submitting verification…", + ["知乎账号"] = "Zhihu account", + ["知乎登录 Cookie"] = "Zhihu sign-in cookie", + ["确定退出知乎账号?"] = "Sign out of Zhihu?", + ["知乎登录已失效,请重新登录"] = "Your Zhihu session has expired. Please sign in again", + ["知乎登录校验失败,请在浏览器确认已登录并完成安全验证"] = "Zhihu sign-in verification failed. Sign in and complete the security check in your browser", + ["知乎扫码登录"] = "Zhihu QR sign-in", + ["用知乎 App 扫一扫"] = "Scan with the Zhihu app", + ["知乎需要安全验证,请在网页完成验证后继续扫码登录"] = "Zhihu requires a security check. Complete it on the web page, then continue QR sign-in", + ["知乎安全验证"] = "Zhihu security check", + ["用同一 Wi-Fi 下的手机扫码完成安全验证,或在本机打开。验证后自动重新显示登录二维码。"] = "Scan with a phone on the same Wi-Fi, or open on this device. A new sign-in QR code will appear after verification.", + ["请完成下方安全验证,验证后回到设备用知乎 App 扫码登录。"] = "Complete the security check below, then scan the sign-in code on your device with the Zhihu app.", + ["验证成功,请回到设备继续扫码登录。"] = "Verified. Return to your device to continue QR sign-in.", + ["验证失败,请重新验证"] = "Verification failed. Please try again", + ["知乎登录响应异常,请重新获取二维码"] = "Unexpected Zhihu sign-in response. Get a new QR code", + ["知乎未下发登录会话,请重新获取二维码"] = "Zhihu did not issue a sign-in session. Get a new QR code", + ["重试"] = "Retry", + ["VIP 章节"] = "VIP chapters", + ["搜索与发现"] = "Search and discover", + ["进度同步"] = "Progress sync", + ["言情"] = "Romance", + ["脑洞"] = "Imaginative", + ["现实情感"] = "Real-life relationships", + ["甜宠"] = "Sweet romance", + ["爽文"] = "Feel-good fiction", + ["虐恋"] = "Angsty romance", + ["权谋"] = "Political intrigue", + ["古言"] = "Historical romance", + ["现言"] = "Contemporary romance", + ["恐怖惊悚"] = "Horror and thriller", + ["大女主"] = "Strong female lead", + ["追妻火葬场"] = "Regretful romance", + ["家庭"] = "Family", + ["复仇"] = "Revenge", +} diff --git a/moonsource-zhihu.koplugin/moonsource_zhihu/l10n/zh_TW.lua b/moonsource-zhihu.koplugin/moonsource_zhihu/l10n/zh_TW.lua new file mode 100644 index 0000000..606cd18 --- /dev/null +++ b/moonsource-zhihu.koplugin/moonsource_zhihu/l10n/zh_TW.lua @@ -0,0 +1,59 @@ +return { + ["滑块加载失败,请检查网络后刷新网页"] = "滑塊載入失敗,請檢查網路後重新整理網頁", + ["章节评论"] = "章節評論", + ["知乎盐选在线阅读"] = "知乎鹽選線上閱讀", + ["知乎章节字体还原失败,请重试"] = "知乎章節字型還原失敗,請重試", + ["请先登录知乎"] = "請先登入知乎", + ["缺少知乎阅读位置"] = "缺少知乎閱讀位置", + ["阅读进度保存失败"] = "閱讀進度儲存失敗", + ["已有划线,保留原始排版"] = "已有劃線,保留原始排版", + ["短篇含图片,保留原始排版"] = "短篇含圖片,保留原始排版", + ["推荐榜"] = "推薦榜", + ["热搜榜"] = "熱搜榜", + ["热度榜"] = "熱度榜", + ["口碑榜"] = "口碑榜", + ["长篇榜"] = "長篇榜", + ["本章未购买"] = "本章未購買", + ["验证已过期,请重新发起验证"] = "驗證已過期,請重新發起驗證", + ["正在获取二维码…"] = "正在取得二維碼…", + ["章节目录保存失败"] = "章節目錄儲存失敗", + ["无法获取段评"] = "無法取得段評", + ["按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"] = "按鍵盤 F12,點「網路」,重新整理網頁,複製請求標頭裡的整段 Cookie", + ["无法打开远程验证,请先连接 Wi-Fi 并启用远程管理功能"] = "無法打開遠端驗證,請先連接 Wi-Fi 並啟用遠端管理功能", + ["验证已取消"] = "驗證已取消", + ["验证凭据无效"] = "驗證憑據無效", + ["正在提交验证…"] = "正在提交驗證…", + ["知乎账号"] = "知乎帳號", + ["知乎登录 Cookie"] = "知乎登入 Cookie", + ["确定退出知乎账号?"] = "確定登出知乎帳號?", + ["知乎登录已失效,请重新登录"] = "知乎登入已失效,請重新登入", + ["知乎登录校验失败,请在浏览器确认已登录并完成安全验证"] = "知乎登入驗證失敗,請在瀏覽器確認已登入並完成安全驗證", + ["知乎扫码登录"] = "知乎掃碼登入", + ["用知乎 App 扫一扫"] = "用知乎 App 掃一掃", + ["知乎需要安全验证,请在网页完成验证后继续扫码登录"] = "知乎需要安全驗證,請在網頁完成驗證後繼續掃碼登入", + ["知乎安全验证"] = "知乎安全驗證", + ["用同一 Wi-Fi 下的手机扫码完成安全验证,或在本机打开。验证后自动重新显示登录二维码。"] = "用同一 Wi-Fi 下的手機掃碼完成安全驗證,或在本機開啟。驗證後自動重新顯示登入二維碼。", + ["请完成下方安全验证,验证后回到设备用知乎 App 扫码登录。"] = "請完成下方安全驗證,驗證後回到裝置用知乎 App 掃碼登入。", + ["验证成功,请回到设备继续扫码登录。"] = "驗證成功,請回到裝置繼續掃碼登入。", + ["验证失败,请重新验证"] = "驗證失敗,請重新驗證", + ["知乎登录响应异常,请重新获取二维码"] = "知乎登入回應異常,請重新取得二維碼", + ["知乎未下发登录会话,请重新获取二维码"] = "知乎未下發登入工作階段,請重新取得二維碼", + ["重试"] = "重試", + ["VIP 章节"] = "VIP 章節", + ["搜索与发现"] = "搜尋與發現", + ["进度同步"] = "進度同步", + ["言情"] = "言情", + ["脑洞"] = "腦洞", + ["现实情感"] = "現實情感", + ["甜宠"] = "甜寵", + ["爽文"] = "爽文", + ["虐恋"] = "虐戀", + ["权谋"] = "權謀", + ["古言"] = "古言", + ["现言"] = "現言", + ["恐怖惊悚"] = "恐怖驚悚", + ["大女主"] = "大女主", + ["追妻火葬场"] = "追妻火葬場", + ["家庭"] = "家庭", + ["复仇"] = "復仇", +} diff --git a/moonsource-zhihu.koplugin/moonsource_zhihu/loadmeta.lua b/moonsource-zhihu.koplugin/moonsource_zhihu/loadmeta.lua new file mode 100644 index 0000000..188ae4e --- /dev/null +++ b/moonsource-zhihu.koplugin/moonsource_zhihu/loadmeta.lua @@ -0,0 +1,5 @@ +return function() + local copy = {} + for k, v in pairs(require("moonsource_zhihu._meta")) do copy[k] = v end + return copy +end diff --git a/moonsource-zhihu.koplugin/moonsource_zhihu/mapper.lua b/moonsource-zhihu.koplugin/moonsource_zhihu/mapper.lua new file mode 100644 index 0000000..da00feb --- /dev/null +++ b/moonsource-zhihu.koplugin/moonsource_zhihu/mapper.lua @@ -0,0 +1,261 @@ +--[[-- +知乎盐选响应到榜单书籍、短篇与长篇目录。 + +搜索页打开 `search?type=km_general`,接口是 `/api/v4/search_v3`。 +短篇 `stable_id` 是专栏 id 加节 id,长篇为专栏 id。`is_fold ~= false` 的节未购买。 + +@module moonsource_zhihu.mapper +--]] + +local Text = require("utils.text") + +local Mapper = {} + +Mapper.TOC_VERSION = 1 +local SOURCE_ID = "ext.zhihu" + +---@param value any +---@return string +local function clean(value) + if type(value) ~= "string" then return "" end + return Text.trim(value:gsub("<[^>]+>", "")) +end + +---@param url string|nil +---@return string|nil +---@return string|nil +local function idsOf(url) + if type(url) ~= "string" then return nil end + local well, section = url:match("/paid_column/(%d+)/section/(%d+)") + if well then return well, section end + return url:match("/paid_column/(%d+)") +end + +---@param value any +---@return string +local function authors(value) + if type(value) == "string" then return clean(value) end + if type(value) ~= "table" then return "" end + local names = {} + for _idx, author in ipairs(value[1] and value or { value }) do + local name = clean(type(author) == "table" and (author.name or author.user and author.user.name) or author) + if name ~= "" then names[#names + 1] = name end + end + return table.concat(names, "、") +end + +---@param value any +---@return string|nil +local function cover(value) + if type(value) == "string" and value ~= "" then return value end + if type(value) ~= "table" then return nil end + local first = value[1] + if type(first) == "string" and first ~= "" then return first end + if type(first) == "table" and type(first.url) == "string" and first.url ~= "" then return first.url end + return nil +end + +---@param row table +---@return Book|nil +local function book(row) + local well, section = idsOf(row.url) + local title = clean(row.title) + if not well or title == "" then return nil end + local body = type(row.body) == "table" and row.body or row + return { + source_id = SOURCE_ID, + stable_id = section and well .. "/" .. section or well, + title = title, + authors = authors(row.producer_name or body.authors or row.authors), + cover = cover(row.artwork or row.tab_artwork or body.images), + intro = section and clean(row.description or body.description) or nil, + } +end + +---@param wire table|nil +---@param rank string +---@return Book[]|nil +---@return table[]|nil +function Mapper.feed(wire, rank) + if type(wire) ~= "table" or type(wire.data) ~= "table" or wire.error then return nil end + for _idx, module in ipairs(wire.data) do + local data = module.module_type == "billboard" and module.module_data and module.module_data.data + for _row_idx, row in ipairs(data and data.data or {}) do + if row.head and row.head.type == rank and type(row.content_list) == "table" + and type(row.head.filters) == "table" then + local out, seen = {}, {} + for _book_idx, entry in ipairs(row.content_list) do + local item = book(entry) + if item and not seen[item.stable_id] then + seen[item.stable_id] = true + out[#out + 1] = item + end + end + return out, row.head.filters + end + end + end + return nil +end + +---@param wire table|nil +---@return Book[]|nil +function Mapper.search(wire) + if type(wire) ~= "table" or type(wire.data) ~= "table" or wire.error then return nil end + local out, seen = {}, {} + for _idx, row in ipairs(wire.data) do + local object = type(row) == "table" and row.object or nil + if type(object) == "table" then + local body = type(object.body) == "table" and object.body or {} + local item = book({ + url = object.url, + title = body.title or object.title, + authors = body.authors, + description = body.description, + artwork = body.images, + }) + if item and not seen[item.stable_id] then + seen[item.stable_id] = true + out[#out + 1] = item + end + end + end + return out +end + +---@param wire table|nil +---@param stable_id string +---@return BookChapter[]|nil +function Mapper.chapters(wire, stable_id) + if stable_id:match("^%d+$") then + if type(wire) ~= "table" or type(wire.data) ~= "table" then return nil end + local chapters = {} + for _idx, row in ipairs(wire.data) do + if row.section_cell and row.section_cell.type == "article" then + local uid, title = row.id, clean(row.title) + if type(uid) ~= "string" or not uid:match("^%d+$") or title == "" then return nil end + local right = row.right or {} + chapters[#chapters + 1] = { + idx = #chapters + 1, uid = uid, title = title, + vip = row.is_free ~= true and right.has_purchased ~= true and right.has_ownership ~= true, + toc_version = Mapper.TOC_VERSION, + } + end + end + return chapters + end + if type(wire) ~= "table" or type(wire.section) ~= "table" then return nil end + local _well, section = tostring(stable_id):match("^(%d+)/(%d+)$") + local title = clean(wire.section.title) + if not section or title == "" then return nil end + return { { + idx = 1, + uid = section, + title = title, + vip = wire.is_fold ~= false, + toc_version = Mapper.TOC_VERSION, + } } +end + +---@param wire table|nil +---@param stable_id string +---@param grading table|nil +---@return Book|nil +function Mapper.detail(wire, stable_id, grading) + if stable_id:match("^%d+$") then + if type(wire) ~= "table" or wire.error or clean(wire.title) == "" then return nil end + local intro = {} + for _idx, value in ipairs({ Text.stripHtml(wire.keypoint), Text.stripHtml(wire.content) }) do + if value ~= "" then intro[#intro + 1] = value end + end + local score = grading and grading.show_score == true and tonumber(grading.score) + return { + source_id = SOURCE_ID, stable_id = stable_id, + title = clean(wire.title), authors = authors(wire.authors), + cover = cover(wire.tab_artwork or wire.artwork), intro = table.concat(intro, "\n\n"), + meta = score and score > 0 and score <= 10 and { rating = { score = score, by = SOURCE_ID } } or nil, + } + end + local chapters = Mapper.chapters(wire, stable_id) + if not chapters then return nil end + local column = type(wire.paid_column) == "table" and wire.paid_column or {} + local section = wire.section + local artwork = clean(section.head_artwork) + if artwork == "" then artwork = clean(column.artwork) end + return { + source_id = SOURCE_ID, + stable_id = tostring(stable_id), + title = chapters[1].title, + authors = "", + cover = artwork ~= "" and artwork or nil, + intro = "", + } +end + +---@param wire table +---@return { section_id: string, fraction?: number, updated_at?: integer }|nil +function Mapper.progress(wire) + local progress = type(wire.cli_progress) == "table" and wire.cli_progress.unit_progress + if type(progress) ~= "table" or type(wire.id) ~= "string" or not wire.id:match("^%d+$") + or progress.unit_id ~= wire.id then return nil end + local fraction = progress.progress + if fraction ~= nil and (type(fraction) ~= "number" or fraction ~= fraction + or fraction < 0 or fraction > 1) then return nil end + if fraction == nil and progress.is_finished == true then fraction = 1 end + local timestamp = progress.client_updated_at + if timestamp ~= nil and (type(timestamp) ~= "number" or timestamp ~= timestamp + or timestamp < 0 or timestamp == math.huge) then return nil end + return { + section_id = wire.id, + fraction = fraction, + updated_at = timestamp and math.floor(timestamp / 1000) or nil, + } +end + +---@param wire table|nil +---@param offset integer|string +---@return WechatReviewPage|nil +function Mapper.reviewPage(wire, offset) + if type(wire) ~= "table" or wire.error or type(wire.data) ~= "table" + or type(wire.paging) ~= "table" or type(wire.paging.is_end) ~= "boolean" then return nil end + local paging = wire.paging + local total = tonumber(type(wire.counts) == "table" and wire.counts.total_counts) or tonumber(paging.totals) + if not total or total < 0 then return nil end + local more = not paging.is_end + local next_offset = type(paging.next) == "string" and paging.next:match("[?&]offset=([^&]+)") + next_offset = next_offset and Text.urlDecode(next_offset) + if more and (#wire.data == 0 or not next_offset or next_offset == "" + or next_offset == (offset == 0 and "" or tostring(offset))) then return nil end + local items = {} + for _idx, row in ipairs(wire.data) do + if type(row) ~= "table" or type(row.id) ~= "string" or type(row.content) ~= "string" then return nil end + local images, inline_images = {}, {} + local emoticons = require("moonsource_zhihu.emoticons") + local content = row.content:gsub("]*>", function(tag) + local _quote, alt = tag:match("alt%s*=%s*([\"'])(.-)%1") + return alt and emoticons[Text.xmlDecode(alt)] and Text.xmlDecode(alt) or tag + end) + for _quote, src in content:gmatch("]-src=([\"'])(.-)%1") do + src = Text.xmlDecode(src) + if src:match("^https?://") then + images[#images + 1] = { url = src, headers = { Referer = "https://www.zhihu.com/" } } + end + end + content = Text.stripHtml(content) + for placeholder in content:gmatch("%b[]") do + local url = emoticons[placeholder] + if url then inline_images[placeholder] = { url = url, headers = { Referer = "https://www.zhihu.com/" } } end + end + items[#items + 1] = { + id = row.id, author = clean(type(row.author) == "table" and row.author.name), + content = content, likes = tonumber(row.like_count) or 0, + inline_images = next(inline_images) and inline_images or nil, + replies = tonumber(row.child_comment_count) or 0, time = tonumber(row.created_time) or 0, + reply_to = type(row.reply_to_author) == "table" and clean(row.reply_to_author.name) or nil, + images = images, + } + end + return { items = items, total = total, max_idx = next_offset or offset, more = more } +end + +return Mapper diff --git a/moonsource-zhihu.koplugin/moonsource_zhihu/qrlogin.lua b/moonsource-zhihu.koplugin/moonsource_zhihu/qrlogin.lua new file mode 100644 index 0000000..8b14fd8 --- /dev/null +++ b/moonsource-zhihu.koplugin/moonsource_zhihu/qrlogin.lua @@ -0,0 +1,177 @@ +--[[-- +知乎 App 扫码登录。 + +POST /api/v3/account/api/login/qrcode 返回 token 和二维码内容。 +每 2 秒轮询 scan_info,手机确认后校验并保存 Cookie。 + +@module moonsource_zhihu.qrlogin +--]] + +local Client = require("moonsource_zhihu.client") +local _ = require("l10n").get("moonsource_zhihu") + +local QRLogin = {} +QRLogin.__index = QRLogin + +local POLL_INTERVAL = 2 +local POLL_LIMIT = 90 + +---@param on_ok fun() +---@return table +function QRLogin:new(on_ok) + return setmetatable({ on_ok = on_ok, generation = 0 }, QRLogin) +end + +function QRLogin:cancel() + self.generation = self.generation + 1 + if self.job and self.job.cancel then self.job.cancel() end + self.job = nil + if self.verification then + self.verification:cancel() + self.verification = nil + end + if self.poll_callback then + require("ui/uimanager"):unschedule(self.poll_callback) + self.poll_callback = nil + end + for _idx, key in ipairs({ "dialog", "busy", "retry_dialog" }) do + local dialog = self[key] + self[key] = nil + if dialog then + dialog.close_callback = nil + dialog:close() + end + end +end + +---@param session ZhihuQRSession +function QRLogin:_verify(session) + self:cancel() + local gen = self.generation + local fired = false + local verification = require("moonsource_zhihu.verify").new(session, function(ok, err) + fired = true + if gen ~= self.generation then return end + self.verification = nil + if ok then self:start(session) else self:_retry(err or _("验证失败,请重新验证")) end + end) + if not fired then self.verification = verification end +end + +---@param text string +function QRLogin:toast(text) + require("ui.themes.widgets.toast"):new{ text = text, timeout = 3 }:show() +end + +---@param text string +function QRLogin:_retry(text) + self:cancel() + self.retry_dialog = require("ui.themes.widgets.confirm"):new{ + text = text, + ok_text = _("重新获取"), + ok_callback = function() self:start() end, + }:show() +end + +---@param link string +function QRLogin:_show(link) + local old = self.dialog + self.dialog = nil + if old then + old.close_callback = nil + old:close() + end + local dialog + dialog = require("ui.themes.widgets.qr"):new{ + title = _("知乎扫码登录"), + text = link, + caption = _("用知乎 App 扫一扫"), + close_callback = function() + if self.dialog ~= dialog then return end + self.dialog = nil + self:cancel() + self:toast(_("已取消登录")) + end, + } + self.dialog = dialog + dialog:show() +end + +---@param gen integer +---@param session ZhihuQRSession +---@param polls integer +function QRLogin:_poll(gen, session, polls) + if gen ~= self.generation then return end + if polls > POLL_LIMIT or (session.expires_at and os.time() >= session.expires_at) then + self:_retry(_("二维码已过期")) + return + end + local fired = false + local job = Client.qrPollAsync(session, function(kind, extra, err) + fired = true + if gen ~= self.generation then return end + self.job = nil + if kind == "ok" then + self:cancel() + self.on_ok() + return + end + if kind == "expired" then self:_retry(_("二维码已过期")); return end + if kind == "verify" and extra then self:_verify(extra); return end + if kind == "refresh" and extra then + session, polls = extra, 0 + self.scanned = false + self:_show(extra.link) + elseif kind == "scanned" then + if not self.scanned then + self.scanned = true + self:toast(_("已扫码,请在手机上确认")) + end + elseif kind ~= "wait" then + self:_retry(err or _("登录失败")) + return + end + self.poll_callback = function() + self.poll_callback = nil + if gen == self.generation then self:_poll(gen, session, polls + 1) end + end + require("ui/uimanager"):scheduleIn(POLL_INTERVAL, self.poll_callback) + end) + if not fired then self.job = job end +end + +---@param session ZhihuQRSession|nil +function QRLogin:start(session) + self:cancel() + local gen = self.generation + self.scanned = false + self.busy = require("ui.themes.widgets.progress_dialog"):new{ + title = _("知乎扫码登录"), + text = _("正在获取二维码…"), + on_cancel = function() self:cancel(); self:toast(_("已取消登录")) end, + close_callback = function() + self:cancel() + end, + } + self.busy:show() + local fired = false + local job = Client.qrCreateAsync(function(created, err, challenge) + fired = true + if gen ~= self.generation then return end + self.job = nil + local busy = self.busy + self.busy = nil + busy.close_callback = nil + busy:close() + if challenge then self:_verify(challenge); return end + if not created then + self:_retry(err or _("获取二维码失败")) + return + end + self:_show(created.link) + self:_poll(gen, created, 1) + end, session) + if not fired then self.job = job end +end + +return QRLogin diff --git a/moonsource-zhihu.koplugin/moonsource_zhihu/setting.lua b/moonsource-zhihu.koplugin/moonsource_zhihu/setting.lua new file mode 100644 index 0000000..673778a --- /dev/null +++ b/moonsource-zhihu.koplugin/moonsource_zhihu/setting.lua @@ -0,0 +1,72 @@ +--[[-- +知乎盐选账号:App 扫码,或浏览器授权 / 粘贴 Cookie。 + +@module koplugin.book.moonsource_zhihu.setting +--]] + +local CookieLogin = require("source.cookie_login") +local _ = require("l10n").get("moonsource_zhihu") + +local Setting = {} + +local function loggedIn() + return require("moonsource_zhihu.client").cookie() ~= nil +end + +---@type CookieLoginSpec +local SPEC = { + id = "ext.zhihu", + title = _("知乎账号"), + cookie_title = _("知乎登录 Cookie"), + cookie_hint = _("按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"), + logout_text = _("确定退出知乎账号?"), + loggedIn = loggedIn, + checkAsync = function(cookie, cb) require("moonsource_zhihu.client").loginCheckAsync(cookie, cb) end, +} + +function Setting.rowStatus() + local on = CookieLogin.authorized(SPEC) + return on and _("已登录") or _("未登录 · 点此登录"), on +end + +Setting.browser = { + domain = "www.zhihu.com", + scope = "cookie", + login = "https://www.zhihu.com/signin", + check = "https://www.zhihu.com/api/v4/me", + icon = "https://www.zhihu.com/favicon.ico", + isAuthorized = function() return CookieLogin.authorized(SPEC) end, + apply = function(payload, cb) + CookieLogin.save(SPEC, CookieLogin.fromPayload(payload, "zhihu.com"), cb) + end, +} + +local function showLogin() + require("ui/network/manager"):runWhenConnected(function() + require("moonsource_zhihu.qrlogin"):new(function() + require("source.auth").ok("ext.zhihu") + require("source.registry").reload() + require("ui.themes.widgets.toast"):new{ text = _("登录成功"), timeout = 2 }:show() + end):start() + end) +end + +function Setting.rows(plugin) + local rows = { + CookieLogin.accountRow(SPEC, { + subtitle = _("用知乎 App 扫一扫"), + callback = showLogin, + }), + CookieLogin.browserRow(), + CookieLogin.pasteRow(SPEC), + require("source.review_setting").row("ext.zhihu", plugin), + } + if loggedIn() then rows[#rows + 1] = CookieLogin.logoutRow(SPEC) end + return rows +end + +function Setting.login() + showLogin() +end + +return Setting diff --git a/moonsource-zhihu.koplugin/moonsource_zhihu/sign.lua b/moonsource-zhihu.koplugin/moonsource_zhihu/sign.lua new file mode 100644 index 0000000..4520571 --- /dev/null +++ b/moonsource-zhihu.koplugin/moonsource_zhihu/sign.lua @@ -0,0 +1,78 @@ +--[[-- +盐选网页 VIP 接口签名(101_3_3.1)。 + +MD5 原文按官网顺序拼版本、完整路径和 d_c0 原值(含引号)。 +分组轮函数复用 SM4,但替换表、轮密钥和输出编码是盐选协议,不是标准 SM4。 + +@module moonsource_zhihu.sign +--]] + +local bit = require("bit") +local Pad = require("crypto.pad") +local Sm4 = require("crypto.sm4") +local md5 = require("ffi/sha2").md5 + +local Sign = {} +local VERSION = "101_3_3.1" +local ALPHABET = "p9Vc6dUJGTu/YXKZPSAlm3j4Lyna+=oHMFz1vtqkBEDghW75O2Nb8xReCfIi0wQsr" +local random = math.random +local ROUND_KEYS = { + -203535452, -89892647, -611010325, -1788458313, 1605777840, -24024647, -1551084381, -648937602, + -410783454, 1611114722, -1473915266, 1319334601, 581282997, 1852100228, 1049921566, -1062880464, + 2128563442, -748483983, -343522048, -1367557827, -79403890, -1710684240, 1697342685, 981842533, + -167308242, 1770909019, 213640201, 817718050, 199423269, 1141645961, -1342602837, 1722529140, +} +local SBOX = { + 23,218,72,119,134,104,62,138,169,177,141,13,204,208,235,184, + 6,60,174,178,129,38,79,179,252,142,103,110,121,139,70,1, + 40,222,213,115,20,101,152,102,117,180,52,17,37,35,229,195, + 69,192,140,147,113,118,135,221,91,200,86,182,82,63,189,148, + 234,155,145,230,233,55,68,46,9,18,131,51,171,236,205,4, + 157,125,153,123,217,75,29,107,241,22,16,211,167,198,226,97, + 154,251,80,181,242,99,216,132,10,50,114,111,116,120,162,207, + 15,32,144,224,124,93,8,215,248,240,187,199,126,206,243,166, + 34,159,228,253,237,47,25,227,185,33,196,24,28,57,19,59, + 239,92,64,214,58,88,136,31,156,197,149,53,247,61,137,76, + 30,193,78,219,5,42,158,163,194,176,89,231,164,11,2,73, + 165,12,45,201,44,49,3,223,67,48,71,151,130,41,21,100, + 143,191,249,160,105,106,98,27,26,0,209,250,255,202,220,85, + 39,43,210,172,112,81,244,150,245,212,203,161,94,14,170,54, + 238,83,66,122,225,190,188,96,183,87,74,84,108,127,109,36, + 7,90,95,146,186,168,65,128,173,232,175,56,246,133,77,254, +} +local IV = ("4548afd21eadee59"):gsub(".", function(char) + return string.char(bit.bxor(char:byte(), 42)) +end) + +---@param path string 完整路径与查询串,顺序必须和 HTTP 请求一致 +---@param cookie string|nil +---@return table +function Sign.headers(path, cookie) + local dc0 = cookie and (";" .. cookie):match(";%s*d_c0=([^;]+)") + local source = VERSION .. "+" .. path .. (dc0 and "+" .. dc0 or "") + local data = Pad.pkcs7_pad(string.char(math.floor(random() * 127), 2) .. md5(source), 16) + local blocks, prev = {}, IV + for offset = 1, #data, 16 do + local mixed = {} + for i = 1, 16 do + mixed[i] = string.char(bit.bxor(data:byte(offset + i - 1), prev:byte(i))) + end + prev = Sm4.block(table.concat(mixed), ROUND_KEYS, SBOX) + blocks[#blocks + 1] = prev + end + local cipher = table.concat(blocks) + cipher = cipher .. string.rep("\0", (3 - #cipher % 3) % 3) + local encoded, group = {}, 0 + for i = #cipher - 2, 1, -3 do + local a, b, c = cipher:byte(i, i + 2) + local word = bit.bxor(a * 65536 + b * 256 + c, bit.lshift(58, group % 4 * 8)) + for shift = 0, 18, 6 do + local at = bit.band(bit.rshift(word, shift), 63) + 1 + encoded[#encoded + 1] = ALPHABET:sub(at, at) + end + group = group + 1 + end + return { ["x-zse-93"] = VERSION, ["x-zse-96"] = "2.0_" .. table.concat(encoded) } +end + +return Sign diff --git a/moonsource-zhihu.koplugin/moonsource_zhihu/source.lua b/moonsource-zhihu.koplugin/moonsource_zhihu/source.lua new file mode 100644 index 0000000..0df6417 --- /dev/null +++ b/moonsource-zhihu.koplugin/moonsource_zhihu/source.lua @@ -0,0 +1,325 @@ +--[[-- +知乎盐选。没有云端书架,只在本地留下打开过的书。 + +短篇一节一篇,长篇按专栏目录阅读。未购买章节只给购买提示,不把预览当正文。 + +@module source.zhihu +--]] + +local Client = require("moonsource_zhihu.client") +local Mapper = require("moonsource_zhihu.mapper") +local SourceBase = require("source.base") +local Browse = require("source.browse") +local Text = require("utils.text") +local Toc = require("source.toc") +local _ = require("l10n").get("moonsource_zhihu") + +local Zhihu = {} + +---@return BookSourceMeta +function Zhihu.meta() + return require("moonsource_zhihu.loadmeta")() +end + +---@class ZhihuSource : SourceBase +local Source = setmetatable({}, { __index = SourceBase }) +Source.__index = Source + +---@return ZhihuSource +function Zhihu.new() + local meta = Zhihu.meta() + return setmetatable({ id = meta.id, name = meta.name, type = meta.type }, Source) +end + +--- 没有可对账的云端书架。 +---@return SourceCapabilities +function Source:capabilities() + local caps = SourceBase.capabilities(self) + caps.shelf_push = false + return caps +end + +---@return boolean +function Source:configured() + return true +end + +function Source:paragraphReviewsEnabled() + return require("source.review_setting").enabled(self.id) +end + +---@param keyword string +---@param cb fun(res: { data: Book[] }|nil, err: string|nil) +function Source:searchAsync(keyword, cb) + return Client.searchAsync(keyword, function(books, err) + if not books then cb(nil, err or _("请求失败")); return end + cb({ data = books }) + end) +end + +local RANKS = { + { type = "recommend", title = _("推荐榜") }, + { type = "hot_search", title = _("热搜榜") }, + { type = "hot", title = _("热度榜") }, + { type = "reputation", title = _("口碑榜") }, + { type = "well", title = _("长篇榜") }, +} + +---@param opts { node?: string }|nil +---@param cb fun(res: { data: Book[], groups: StoreChipGroup[] }|nil, err: string|nil) +function Source:browseAsync(opts, cb) + local rank, filter = (opts and opts.node or "recommend:0"):match("^([%w_]+):(%d+)$") + local ranks, known = {}, false + for _idx, item in ipairs(RANKS) do + ranks[#ranks + 1] = { id = item.type .. ":0", title = item.title } + if item.type == rank then known = true end + end + if not known then rank, filter = "recommend", "0" end + local node = rank .. ":" .. filter + return Client.browseAsync(rank, filter, function(books, err, filters) + if not books then cb(nil, err or _("请求失败")); return end + local categories = {} + for _idx, item in ipairs(filters) do + categories[#categories + 1] = { id = rank .. ":" .. item.key, title = _(Text.trim(item.name)) } + end + cb({ data = books, groups = { Browse.group(ranks, rank .. ":0"), Browse.group(categories, node) } }) + end) +end + +---@param self ZhihuSource +---@param identity BookIdentity +---@param cb fun(wire: table|nil, err: string|nil) +local function loadBook(self, identity, cb) + local fetch = identity.stable_id:match("^%d+$") and Client.catalogAsync or Client.simpleAsync + return fetch(identity.stable_id, function(wire, err) + if not wire then cb(nil, err); return end + local chapters = Mapper.chapters(wire, identity.stable_id) + if not chapters then cb(nil, _("请求失败")); return end + if not Toc.put(self.id, identity.stable_id, chapters) then cb(nil, _("章节目录保存失败")); return end + wire.chapters = chapters + cb(wire) + end) +end + +function Source:getDetailAsync(identity, cb) + local function done(book, err) + if book then + local stored, save_err = require("book.store").rememberDetail(book) + if stored and stored.sync_status == 0 then + local BookDB = require("book.books_db") + if BookDB.fillEmptyMeta(self.id, identity.stable_id, book.authors, book.intro) then + stored = BookDB.get(self.id, identity.stable_id) + end + end + cb(stored, save_err) + return + end + local row = identity.book or require("book.books_db").get(self.id, identity.stable_id) + if row then cb(row); return end + cb(nil, err or _("请求失败")) + end + if identity.stable_id:match("^%d+$") then + return Client.detailAsync(identity.stable_id, done) + end + return loadBook(self, identity, function(wire, err) + done(wire and Mapper.detail(wire, identity.stable_id), err) + end) +end + +function Source:loadTocAsync(identity, cb, force) + if not force then + local cached = Toc.read(self.id, identity.stable_id) + if cached and #cached > 0 and cached[1].toc_version == Mapper.TOC_VERSION then + return SourceBase.defer(cb, cached) + end + end + return loadBook(self, identity, function(wire, err) + if not wire then cb(nil, err); return end + cb(wire.chapters) + end) +end + +Source.refreshTocAsync = function(self, identity, cb) + return self:loadTocAsync(identity, cb, true) +end + +---@param open boolean +---@return ChapterFetchContent +local function fetcher(open) + return function(identity, chapter, done) + local function finish(html, err) + if html then + if chapter.vip then Toc.markPaid("ext.zhihu", identity.stable_id, chapter.uid, true) end + done({ title = chapter.title, html = require("moonsource_zhihu.content").prepare(html) }) + return + end + if not open or err ~= _("本章未购买") then done(nil, err); return end + local notice = string.format(_("这是 VIP 章节,你还没有购买。\n请先在%s购买本章,再回来阅读。"), _("知乎盐选")) + done({ title = chapter.title, html = Text.chapterHtml(chapter.title, notice), temporary = true }) + end + if chapter.vip and not Client.cookie() then return finish(nil, _("本章未购买")) end + local stable_id = identity.stable_id + if stable_id:match("^%d+$") then stable_id = stable_id .. "/" .. chapter.uid end + return Client.contentAsync(stable_id, finish) + end +end + +function Source:openBookAsync(identity, opts, cb) + local Chapter = require("source.chapter") + local ops = { + loadToc = function(ref, done) return self:loadTocAsync(ref, done) end, + fetchContent = fetcher(true), + reuse = require("moonsource_zhihu.content").reuse, + } + if identity.stable_id:find("/", 1, true) then + return require("moonsource_zhihu.story").openAsync(self, identity, opts, ops, cb) + end + local open_fn = opts and opts.chapter_idx and Chapter.openAsync or Chapter.openWithUi + return open_fn(self, identity, identity.book, opts, ops, cb) +end + +function Source:prefetchChaptersAsync(identity, toc, from_idx, count, cb) + return require("source.chapter").prefetchAsync(identity, identity.book, toc, from_idx, count, { + fetchContent = fetcher(false), + }, cb) +end + +function Source:cacheAllChaptersAsync(identity, on_progress, cb, range) + return require("source.chapter").cacheAllAsync(self, identity, fetcher(false), on_progress, cb, nil, range, nil) +end + +function Source:getProgressAsync(identity, cb) + local cancelled, active = false, nil + local fired = false + local job = Client.progressAsync(identity.stable_id, function(record, err, meta) + fired = true + if cancelled then return end + active = nil + if not record then cb(nil, err, meta); return end + if identity.stable_id:find("/", 1, true) then + cb({ + fraction = record.fraction, updated_at = record.updated_at, + chapter_idx = identity.chapter_idx and 1 or nil, + chapter_fraction = identity.chapter_idx and record.fraction or nil, + }) + return + end + local function load(force) + local loaded = false + local toc_job = self:loadTocAsync(identity, function(toc, toc_err) + loaded = true + if cancelled then return end + active = nil + if not toc then cb(nil, toc_err); return end + for idx, chapter in ipairs(toc) do + if chapter.uid == record.section_id then + cb({ + fraction = ((idx - 1) + record.fraction) / #toc, + chapter_idx = idx, chapter_title = chapter.title, + chapter_fraction = record.fraction, updated_at = record.updated_at, + }) + return + end + end + if not force then load(true); return end + cb(nil, _("缺少知乎阅读位置")) + end, force) + if not loaded then active = toc_job end + end + load(false) + end) + if not fired then active = job end + return { cancel = function() + cancelled = true + if active then active.cancel() end + end } +end + +function Source:putProgressAsync(identity, pos, cb) + local _column, section = identity.stable_id:match("^(%d+)/(%d+)$") + -- 短篇 EPUB 的章号是内部小节,不是知乎的 section;整篇比例才是云端章内比例。 + if section then return Client.putProgressAsync(section, pos.fraction, cb) end + local cancelled, active = false, nil + local fired = false + local job = self:loadTocAsync(identity, function(toc, err) + fired = true + if cancelled then return end + active = nil + if not toc then cb(nil, err); return end + local idx = tonumber(pos.chapter_idx) or math.floor(pos.fraction * #toc) + 1 + idx = math.max(1, math.min(#toc, math.floor(idx))) + local chapter = toc[idx] + if not chapter then cb(nil, _("缺少知乎阅读位置")); return end + local within = pos.chapter_fraction + if within == nil then within = math.max(0, math.min(1, pos.fraction * #toc - (idx - 1))) end + local posted = false + local post_job = Client.putProgressAsync(chapter.uid, within, function(ok, post_err) + posted = true + if cancelled then return end + active = nil + cb(ok, post_err) + end) + if not posted then active = post_job end + end) + if not fired then active = job end + return { cancel = function() + cancelled = true + if active then active.cancel() end + end } +end + +---@param identity BookIdentity +---@param cb fun(hotspots: WechatReviewHotspot[]|nil, err: string|nil) +function Source:chapterReviewHotspotsAsync(identity, cb) + return require("book.review_cache").hotspotsAsync(identity, function(done) + local cancelled, active = false, nil + local function load(section, title) + local fired = false + local job = self:paragraphReviewPageAsync(identity, section, 0, function(page, err) + fired = true + if cancelled then return end + active = nil + if not page then done(nil, err); return end + done({ { + range = section, text = title, total = page.total, + badge = tostring(page.total), heading = _("章节评论"), + anchor = require("moonsource_zhihu.content").ANCHOR, + } }) + end) + if not fired then active = job end + end + local _column, section = identity.stable_id:match("^(%d+)/(%d+)$") + if section then + load(section, identity.book and identity.book.title or "") + else + local fired = false + local job = self:loadTocAsync(identity, function(toc, err) + fired = true + if cancelled then return end + active = nil + local chapter = toc and toc[identity.chapter_idx] + if not chapter then done(nil, err or _("缺少知乎阅读位置")); return end + load(chapter.uid, chapter.title) + end) + if not fired then active = job end + end + return { cancel = function() + cancelled = true + if active then active.cancel() end + end } + end, cb) +end + +function Source:paragraphReviewPageAsync(identity, range, max_idx, cb) + return require("book.review_cache").pageAsync(identity, range, max_idx, function(done) + return Client.reviewsAsync(range, max_idx, false, done) + end, cb) +end + +function Source:paragraphReviewRepliesAsync(identity, review_id, max_idx, cb) + return require("book.review_cache").pageAsync(identity, "reply:" .. review_id, max_idx, function(done) + return Client.reviewsAsync(review_id, max_idx, true, done) + end, cb) +end + +return Zhihu diff --git a/moonsource-zhihu.koplugin/moonsource_zhihu/story.lua b/moonsource-zhihu.koplugin/moonsource_zhihu/story.lua new file mode 100644 index 0000000..d16c92c --- /dev/null +++ b/moonsource-zhihu.koplugin/moonsource_zhihu/story.lua @@ -0,0 +1,125 @@ +--[[-- +盐选短篇首次打开前转成整本 EPUB;旧版划线与图文正文保留原文件。 + +@module moonsource_zhihu.story +--]] + +local Paths = require("utils.paths") +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_zhihu") + +local Story = {} + +local function headings(html, text) + local out, numbers = {}, {} + for _level, title in html:gmatch("]*>(.-)") do + out[#out + 1] = Text.stripHtml(title) + end + for line in (text .. "\n"):gmatch("(.-)\n") do + if line:match("^%d%d?%d?$") and tonumber(line) == #numbers + 1 then + numbers[#numbers + 1] = line + end + end + if #numbers > 1 then + for _idx, title in ipairs(numbers) do out[#out + 1] = title end + end + return out +end + +--- 换格式时只带比例,不把 HTML 的 XPointer / 页码套进 EPUB;路径与进度一起提交。 +local function register(path, identity) + local BookDB = require("book.books_db") + local ProgressDB = require("book.progress_db") + local book = BookDB.get(identity.source_id, identity.stable_id) + local previous = book and book.path ~= path and ProgressDB.get(identity.source_id, identity.stable_id) + local reason + local ok = require("utils.db").transaction(function() + local touched, err = require("book.store").touch(path, identity) + if not touched then reason = err; return false end + if previous and not ProgressDB.upsert(identity.source_id, identity.stable_id, { + fraction = previous.fraction, updated_at = require("book.progress").nextRevision(), + }) then + reason = _("阅读进度保存失败") + return false + end + return true + end) + return ok and path or nil, reason or (not ok and _("无法保存章节文件") or nil) +end + +---@param source BookSource +---@param identity BookIdentity +---@param opts table|nil +---@param ops table +---@param cb fun(path: string|nil, err: string|nil) +---@return { cancel: fun() } +function Story.openAsync(source, identity, opts, ops, cb) + local Chapter = require("source.chapter") + local notes = require("book.note_db").get(identity.source_id, identity.stable_id, 1) + if notes and notes.payload ~= "[]" and notes.payload ~= "{}" then + require("ui.themes.widgets.toast"):new{ text = _("已有划线,保留原始排版") }:show() + return Chapter.openWithUi(source, identity, identity.book, opts, ops, cb) + end + local dest = Paths.bookWorkDir(identity.stable_id, identity.source_id) .. "/book.epub" + if require("libs/libkoreader-lfs").attributes(dest, "mode") == "file" then + local original = require("utils.fs").read(Paths.chapterPath(identity.stable_id, 1, identity.source_id)) or "" + local upgraded, upgrade_err = require("moonsource_zhihu.content").upgradeStory(dest, original) + if not upgraded then return require("source.base").defer(cb, nil, upgrade_err) end + local path, err = register(dest, identity) + return require("source.base").defer(cb, path, err) + end + local cancelled, active, dialog = false, nil, nil + local function finish(path, err) + if dialog then dialog:close(); dialog = nil end + if not cancelled then cb(path, err) end + end + local downloaded = false + local download = Chapter.openWithUi(source, identity, identity.book, opts, ops, function(path, err) + downloaded = true + if cancelled then return end + active = nil + if not path then finish(nil, err); return end + local file, open_err = io.open(path, "rb") + if not file then finish(nil, open_err); return end + local html, read_err = file:read("*a") + file:close() + if not html then finish(nil, read_err); return end + if html:find("", 1, true) then finish(path); return end + html = Text.htmlBodyFragment(html) + if html:lower():find("]") then + require("ui.themes.widgets.toast"):new{ text = _("短篇含图片,保留原始排版") }:show() + finish(path) + return + end + local text = Text.stripHtml(html) + if text == "" then finish(nil, _("无文本内容")); return end + local book = require("book.books_db").get(identity.source_id, identity.stable_id) or identity.book + dialog = require("ui.themes.widgets.progress_dialog"):new{ + title = book and book.title, text = _("重新排版"), dismissable = false, + } + local built = false + local job = dialog:showWhile(require("convert.text2epub").build, { + dest = dest, text = text, title = book and book.title, author = book and book.authors, + identifier = "zhihu-" .. identity.stable_id, reflow = true, headings = headings(html, text), + tail_html = require("moonsource_zhihu.content").FOOTER, + }, function(ok, build_err) + built = true + if cancelled then return end + active = nil + if not ok then finish(nil, build_err); return end + finish(register(dest, identity)) + end, function(step, done, total) + if not cancelled and dialog then dialog:update(step, done, total) end + end) + if not built then active = job end + end) + if not downloaded then active = download end + return { cancel = function() + cancelled = true + if active then active.cancel() end + if dialog then dialog:close(); dialog = nil end + os.remove(dest .. ".part") + end } +end + +return Story diff --git a/moonsource-zhihu.koplugin/moonsource_zhihu/verify.lua b/moonsource-zhihu.koplugin/moonsource_zhihu/verify.lua new file mode 100644 index 0000000..97abf0d --- /dev/null +++ b/moonsource-zhihu.koplugin/moonsource_zhihu/verify.lua @@ -0,0 +1,128 @@ +--[[-- +知乎人机验证:浏览器只加载官方控件并交回票据,Cookie 与挑战提交留在设备。 +每次验证持有原扫码会话,临时访问票据五分钟有效,关闭或取消后立即作废。 + +@module moonsource_zhihu.verify +--]] + + +local Client = require("moonsource_zhihu.client") +local Ext = require("utils.extension") +local _ = require("l10n").get("moonsource_zhihu") + +---@class ZhihuVerification +---@field ticket string +---@field session ZhihuQRSession +---@field callback fun(ok: boolean, err: string|nil) +---@field expires integer +---@field session_id string|nil +---@field pending table|nil +---@field dialog BookThemeQR|nil +---@field timeout function +---@field done boolean|nil +local Verification = {} +Verification.__index = Verification + +---@type table +local sessions = {} + +function Verification:cancel() + if self.done then return end + self.done = true + sessions[self.ticket] = nil + require("ui/uimanager"):unschedule(self.timeout) + if self.pending and self.pending.job then self.pending.job.cancel() end + if self.dialog then self.dialog:close() end +end + +function Verification:finish(ok, err) + if self.done then return end + self:cancel() + self.callback(ok, err) +end + +---@param session ZhihuQRSession +---@param cb fun(ok: boolean, err: string|nil) +---@return ZhihuVerification +function Verification.new(session, cb) + local self = setmetatable({ + ticket = require("utils.random").hex(24), session = session, + callback = cb, expires = os.time() + 300, + }, Verification) + self.timeout = require("ui.guard").wrap("zhihu verification timeout", function() + self:finish(false, _("验证已过期,请重新发起验证")) + end) + sessions[self.ticket] = self + require("ui/uimanager"):scheduleIn(300, self.timeout) + self.dialog = Ext.call("web.open_page", "/zhihu_verify.html#" .. self.ticket, + _("知乎安全验证"), _("用同一 Wi-Fi 下的手机扫码完成安全验证,或在本机打开。验证后自动重新显示登录二维码。"), { + close_callback = function() self:finish(false, _("验证已取消")) end, + }) + if not self.dialog then + self:finish(false, _("无法打开远程验证,请先连接 Wi-Fi 并启用远程管理功能")) + end + return self +end + +---@param method string +---@param action string +---@param params table +---@param cb fun(status: integer, body: table, headers: string[]|nil) +local function handle(method, action, params, cb) + local function reply(status, body) + cb(status, body, { "Cache-Control: no-store" }) + end + if method ~= "POST" then return reply(405, { error = "Method Not Allowed" }) end + if action ~= "config" and action ~= "verify" then return reply(404, { error = "Not Found" }) end + local session = type(params.ticket) == "string" and sessions[params.ticket] + if not session or os.time() >= session.expires then + return reply(403, { error = _("验证已过期,请重新发起验证") }) + end + if session.pending then return reply(409, { error = _("正在提交验证…") }) end + if action == "verify" and (not session.session_id or type(params.result) ~= "string" + or params.result == "" or #params.result > 16384) then + return reply(400, { error = _("验证凭据无效") }) + end + local operation = {} + session.pending = operation + local function completed() + if session.done or os.time() >= session.expires then + session:finish(false, _("验证已过期,请重新发起验证")) + reply(403, { error = _("验证已过期,请重新发起验证") }) + return false + end + session.pending = nil + return true + end + if action == "config" then + session.session_id = nil + operation.job = Client.qrCaptchaAsync(session.session, function(config, err) + if not completed() then return end + if not config then return reply(400, { error = err or _("滑块加载失败,请检查网络后刷新网页") }) end + session.session_id = config.session_id + reply(200, { + scripts = config.scripts, + title = _("知乎安全验证"), instruction = _("请完成下方安全验证,验证后回到设备用知乎 App 扫码登录。"), + pending = _("正在提交验证…"), success = _("验证成功,请回到设备继续扫码登录。"), + failure = _("验证失败,请重新验证"), load_error = _("滑块加载失败,请检查网络后刷新网页"), + retry = _("重试"), + }) + end) + else + operation.job = Client.qrVerifyAsync(session.session, session.session_id, params.result, function(ok, err) + if not completed() then return end + if not ok then return reply(400, { error = err or _("验证失败,请重新验证") }) end + reply(200, { ok = true }) + session:finish(true) + end) + end +end + +local dir = debug.getinfo(1, "S").source:sub(2):match("(.*/)") +Ext.add("web.routes", { + name = "zhihu_verify", dir = dir .. "web", + assets = { "zhihu_verify.html", "zhihu_verify.js" }, + public = { config = true, verify = true }, handle = handle, +}) + +return Verification diff --git a/moonsource-zhihu.koplugin/moonsource_zhihu/web/zhihu_verify.html b/moonsource-zhihu.koplugin/moonsource_zhihu/web/zhihu_verify.html new file mode 100644 index 0000000..7d38ea6 --- /dev/null +++ b/moonsource-zhihu.koplugin/moonsource_zhihu/web/zhihu_verify.html @@ -0,0 +1,25 @@ + + + + + + +月读 + + + + +
+

月读

+

+
+

+ +
+ + + diff --git a/moonsource-zhihu.koplugin/moonsource_zhihu/web/zhihu_verify.js b/moonsource-zhihu.koplugin/moonsource_zhihu/web/zhihu_verify.js new file mode 100644 index 0000000..c59db44 --- /dev/null +++ b/moonsource-zhihu.koplugin/moonsource_zhihu/web/zhihu_verify.js @@ -0,0 +1,78 @@ +(async function () { + 'use strict'; + const ticket = location.hash.slice(1); + const status = document.getElementById('status'); + const retry = document.getElementById('retry'); + const element = document.getElementById('captcha-element'); + let messages, captcha; + async function request(action, body) { + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), 45000); + try { + const response = await fetch('/api/zhihu_verify/' + action, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ ...body, ticket }), + signal: controller.signal, + }); + const result = await response.json(); + if (!response.ok) throw new Error(result.error || response.statusText); + return result; + } finally { + clearTimeout(timer); + } + } + function failed(error) { + status.textContent = error.message || (messages && messages.failure) || String(error); + retry.hidden = false; + if (messages) retry.textContent = messages.retry; + } + async function verify(result) { + if (!result || !result.type || !result.result) { + failed(new Error(messages.failure)); + return; + } + status.textContent = messages.pending; + try { + await request('verify', { result: JSON.stringify(result.result) }); + if (captcha) captcha.close(); + element.hidden = true; + retry.hidden = true; + status.textContent = messages.success; + } catch (error) { + failed(error); + } + } + async function loadCaptcha() { + retry.hidden = true; + status.textContent = ''; + if (captcha) { captcha.close(); captcha = null; } + element.replaceChildren(); + messages = await request('config', {}); + document.title = document.getElementById('title').textContent = messages.title; + document.getElementById('instruction').textContent = messages.instruction; + retry.textContent = messages.retry; + for (const url of messages.scripts) { + const parsed = new URL(url); + if (url !== 'https://cstaticdun.126.net/load.min.js' + && !(parsed.origin === 'https://captcha.zhihu.com' && parsed.pathname === '/api/v1/captcha/js')) { + throw new Error(messages.load_error); + } + await new Promise((resolve, reject) => { + const script = document.createElement('script'); + const timer = setTimeout(() => reject(new Error(messages.load_error)), 20000); + script.src = url; + script.onload = () => { clearTimeout(timer); resolve(); }; + script.onerror = () => { clearTimeout(timer); reject(new Error(messages.load_error)); }; + document.head.appendChild(script); + }); + } + captcha = await window.ZS_CAP.init({ + element, callback: verify, enableClose: true, + onClose: () => { retry.hidden = false; }, + }); + captcha.show(); + } + retry.onclick = () => loadCaptcha().catch(failed); + await loadCaptcha().catch(failed); +})(); diff --git a/tests/zhihu/browse_spec.lua b/tests/zhihu/browse_spec.lua new file mode 100644 index 0000000..3f63a86 --- /dev/null +++ b/tests/zhihu/browse_spec.lua @@ -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) diff --git a/tests/zhihu/catalog_spec.lua b/tests/zhihu/catalog_spec.lua new file mode 100644 index 0000000..679c7a5 --- /dev/null +++ b/tests/zhihu/catalog_spec.lua @@ -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) diff --git a/tests/zhihu/client_spec.lua b/tests/zhihu/client_spec.lua new file mode 100644 index 0000000..4bab8d2 --- /dev/null +++ b/tests/zhihu/client_spec.lua @@ -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 = "红包不能抢", 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 = "

甲

" }), 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, "

甲

") +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({ "{}", "登录", '{"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, "

甲

") +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() diff --git a/tests/zhihu/content_layout_spec.lua b/tests/zhihu/content_layout_spec.lua new file mode 100644 index 0000000..dcaaa10 --- /dev/null +++ b/tests/zhihu/content_layout_spec.lua @@ -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 = '

正文里的备案号说明不能删。

' +local watermark = '备美号:YXXBfixture' +local raw = prefix .. "

" .. watermark .. "

" +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("

", 1, true) ~= nil, "保留空段落,不挪动其它节点编号") +Assert.is_true(html:find(Content.FOOTER .. "", 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 = "", mode = "file" }, + { path = "OEBPS/chapter_001.xhtml", data = prefix .. "", mode = "file" }, + { path = "OEBPS/chapter_002.xhtml", + data = '

结尾正文。

备美号:YXXBfixture

', 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('

结尾正文。

', 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"], "") +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) diff --git a/tests/zhihu/content_spec.lua b/tests/zhihu/content_spec.lua new file mode 100644 index 0000000..6e15dea --- /dev/null +++ b/tests/zhihu/content_spec.lua @@ -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("

还原正文

") 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 = "

正文

" }) +fetch() +Assert.eq(value, "

正文

") +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 = "

付费预览

", use_font = true }, + { is_fold = false, authentication_result = false, manuscript = "

付费预览

" }, +}) do + response = Json.encode(denied) + fetch() + Assert.is_nil(value) + Assert.eq(error_message, "本章未购买") +end +Assert.eq(calls, 0, "拒绝权限后不能还原或缓存预览") + +for _idx, invalid in ipairs({ "{}", "风控", + '{"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 = "

乱序

", 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("

迟到正文

") +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, "

还原正文

") +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 diff --git a/tests/zhihu/detail_spec.lua b/tests/zhihu/detail_spec.lua new file mode 100644 index 0000000..4f1309b --- /dev/null +++ b/tests/zhihu/detail_spec.lua @@ -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 = "

宣传语 & 引言

", + content = "

第一段。

第二段:完整简介结尾。

", + 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 diff --git a/tests/zhihu/font_spec.lua b/tests/zhihu/font_spec.lua new file mode 100644 index 0000000..e6d3ade --- /dev/null +++ b/tests/zhihu/font_spec.lua @@ -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 +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 = '的

不&了的<的>

了', + 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, '正

全&。正<正>

。') +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("error") +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) diff --git a/tests/zhihu/login_spec.lua b/tests/zhihu/login_spec.lua new file mode 100644 index 0000000..c5d9d01 --- /dev/null +++ b/tests/zhihu/login_spec.lua @@ -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("", 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") diff --git a/tests/zhihu/progress_client_spec.lua b/tests/zhihu/progress_client_spec.lua new file mode 100644 index 0000000..12c002e --- /dev/null +++ b/tests/zhihu/progress_client_spec.lua @@ -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, "请先登录知乎") diff --git a/tests/zhihu/progress_spec.lua b/tests/zhihu/progress_spec.lua new file mode 100644 index 0000000..2590446 --- /dev/null +++ b/tests/zhihu/progress_spec.lua @@ -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) diff --git a/tests/zhihu/qrlogin_spec.lua b/tests/zhihu/qrlogin_spec.lua new file mode 100644 index 0000000..477782a --- /dev/null +++ b/tests/zhihu/qrlogin_spec.lua @@ -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()) diff --git a/tests/zhihu/reviews_spec.lua b/tests/zhihu/reviews_spec.lua new file mode 100644 index 0000000..fa003ef --- /dev/null +++ b/tests/zhihu/reviews_spec.lua @@ -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 = '

甲 & 乙
下一行

', + 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 = '甲[捂脸][捂脸][未知表情][赞]' + .. '' +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") diff --git a/tests/zhihu/setting_spec.lua b/tests/zhihu/setting_spec.lua new file mode 100644 index 0000000..5ac61b0 --- /dev/null +++ b/tests/zhihu/setting_spec.lua @@ -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 = "

已购正文

", 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("

已购正文

"), + "登录后不能被匿名目录里的 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 = "

长篇章节

", 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") diff --git a/tests/zhihu/sign_spec.lua b/tests/zhihu/sign_spec.lua new file mode 100644 index 0000000..49a5fac --- /dev/null +++ b/tests/zhihu/sign_spec.lua @@ -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 diff --git a/tests/zhihu/story_spec.lua b/tests/zhihu/story_spec.lua new file mode 100644 index 0000000..cf32d2d --- /dev/null +++ b/tests/zhihu/story_spec.lua @@ -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 = "短篇样例" + .. "

序幕

开场文字。

01

第一段。

02

第二段。

" +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("" .. html) +Story.openAsync({}, identity, nil, {}, done) +Assert.eq(result, original) +Assert.eq(#conversions, count, "购买提示不能被打包成永久 EPUB") +reset('

配图

') +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") diff --git a/tests/zhihu/verify_client_spec.lua b/tests/zhihu/verify_client_spec.lua new file mode 100644 index 0000000..b8d8859 --- /dev/null +++ b/tests/zhihu/verify_client_spec.lua @@ -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, "知乎登录响应异常,请重新获取二维码") diff --git a/tests/zhihu/verify_spec.lua b/tests/zhihu/verify_spec.lua new file mode 100644 index 0000000..fd90f69 --- /dev/null +++ b/tests/zhihu/verify_spec.lua @@ -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)) diff --git a/tests/zhihu/web_spec.js b/tests/zhihu/web_spec.js new file mode 100644 index 0000000..1cdf936 --- /dev/null +++ b/tests/zhihu/web_spec.js @@ -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; }); diff --git a/tests/zhihu/web_spec.lua b/tests/zhihu/web_spec.lua new file mode 100644 index 0000000..72f0a74 --- /dev/null +++ b/tests/zhihu/web_spec.lua @@ -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)