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

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

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

No files matched your search

@@ -0,0 +1,17 @@
--[[--
书源元信息。
知乎盐选没有云端书架。榜单匿名可读。正文折叠时是未购买。
@module moonsource_zhihu._meta
--]]
local _ = require("l10n").get("moonsource_zhihu")
return {
id = "ext.zhihu",
name = _("知乎盐选"),
type = "chapter",
description = _("知乎盐选在线阅读"),
abilities = { _("搜索与发现"), _("VIP 章节"), _("登录"), _("进度同步"), _("他人段评") },
}
@@ -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<string, string>
---@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<string, string>
---@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<string, string>
---@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<string, string>
---@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
@@ -0,0 +1,100 @@
--[[--
盐选正文:移除备案号,保留原文节点顺序,在末尾留出章评区。
@module moonsource_zhihu.content
--]]
local Content = {}
Content.ANCHOR = "moon-chapter-reviews"
Content.FOOTER = '<div id="' .. Content.ANCHOR .. '" style="height:4em;page-break-inside:avoid"></div>'
---@param html string
---@return string
function Content.prepare(html)
html = html:gsub("<span%s[^>]-id%s*=%s*([\"'])vipyxcode%1[^>]*>.-</span>", "")
if html:find('id="' .. Content.ANCHOR .. '"', 1, true) then return html end
local ending = html:find("</body>", 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("<span%s[^>]-id%s*=%s*([\"'])vipyxcode%1[^>]*>(.-)</span>")
if watermark then
watermark = Text.stripHtml(watermark)
updated = updated:gsub("(<p[^>]*>)(.-)</p>", function(open, inner)
return open .. (Text.stripHtml(inner) == watermark and "" or inner) .. "</p>"
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
@@ -0,0 +1,89 @@
--[[--
知乎官方表情占位符与静态图地址,仅在评论确实用到时下载。
来源:https://unpkg.zhimg.com/@cfe/[email protected]/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",
}
@@ -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
@@ -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",
}
@@ -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 章節",
["搜索与发现"] = "搜尋與發現",
["进度同步"] = "進度同步",
["言情"] = "言情",
["脑洞"] = "腦洞",
["现实情感"] = "現實情感",
["甜宠"] = "甜寵",
["爽文"] = "爽文",
["虐恋"] = "虐戀",
["权谋"] = "權謀",
["古言"] = "古言",
["现言"] = "現言",
["恐怖惊悚"] = "恐怖驚悚",
["大女主"] = "大女主",
["追妻火葬场"] = "追妻火葬場",
["家庭"] = "家庭",
["复仇"] = "復仇",
}
@@ -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
@@ -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("<img%s[^>]*>", 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("<img[^>]-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
@@ -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
@@ -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
@@ -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<string, string>
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
@@ -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
@@ -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("<h([1-6])[^>]*>(.-)</h%1>") 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("<!--moon:temp-->", 1, true) then finish(path); return end
html = Text.htmlBodyFragment(html)
if html:lower():find("<img%f[%s/>]") 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
@@ -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<string, ZhihuVerification>
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
@@ -0,0 +1,25 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="referrer" content="no-referrer">
<title>月读</title>
<link rel="stylesheet" href="/style.css">
<style>
main{max-width:520px;margin:12vh auto;padding:24px}
.panel{padding:24px}#captcha-element{min-height:48px;margin:24px 0}
#status{overflow-wrap:anywhere}button[hidden]{display:none}
</style>
</head>
<body>
<main><section class="panel">
<h1 id="title">月读</h1>
<p id="instruction"></p>
<div id="captcha-element"></div>
<p id="status" role="status" aria-live="polite"></p>
<button id="retry" type="button" hidden>重试</button>
</section></main>
<script src="/zhihu_verify.js"></script>
</body>
</html>
@@ -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);
})();