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

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

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

No files matched your search

@@ -0,0 +1,16 @@
--[[--
书源元信息:id / 名称 / 类型,加上启用页展示用的说明与能力清单。`init.lua` 的 `meta()` 直接返回本表。
@module moonsource_qidian._meta
--]]
local _ = require("l10n").get("moonsource_qidian")
return {
id = "ext.qidian",
name = _("起点中文网"),
type = "chapter",
description = _("起点中文网书架与在线阅读"),
abilities = { _("扫码登录"), _("手机号验证码登录"), _("搜索与发现"), _("书架同步"),
_("进度同步"), _("VIP 章节"), _("他人段评"), _("章节评论"), _("书友圈帖子预览") },
}
@@ -0,0 +1,154 @@
--[[--
起点分类书库:动态男频分类、官网筛选、匿名分页。节点保留全部已选条件。
@module moonsource_qidian.browse
--]]
local Client = require("moonsource_qidian.client")
local Mapper = require("moonsource_qidian.mapper")
local Browse = require("source.browse")
local Text = require("utils.text")
local _ = require("l10n").get("moonsource_qidian")
local Library = {}
-- 官网动态标签:预译已知标签,未知标签仍沿用 gettext 的原文回退。
local LABELS = {
["100~200万"] = _("100~200万"), ["200万以上"] = _("200万以上"),
["30~50万"] = _("30~50万"), ["30万以下"] = _("30万以下"), ["50~100万"] = _("50~100万"),
["VIP"] = _("VIP"), ["一月内"] = _("一月内"), ["七日内"] = _("七日内"), ["三日内"] = _("三日内"),
["东方玄幻"] = _("东方玄幻"), ["二级分类"] = _("二级分类"), ["人气"] = _("人气"),
["半月内"] = _("半月内"), ["品质"] = _("品质"), ["完本"] = _("完本"), ["属性"] = _("属性"),
["异世大陆"] = _("异世大陆"), ["月票"] = _("月票"), ["点击"] = _("点击"),
["王朝争霸"] = _("王朝争霸"), ["签约作品"] = _("签约作品"), ["精品小说"] = _("精品小说"),
["连载"] = _("连载"), ["高武世界"] = _("高武世界"),
}
local KEYS = { catId = true, subCatId = true, isvip = true, size = true, isfinish = true,
sign = true, update = true, orderBy = true, gender = true }
-- m.qdmm.com 的分类目录目前返回风控页;这些是电脑官网 /all/ 实际公布的女频分类。
local FEMALE = {
{ catId = 80, catName = "古代言情" }, { catId = 81, catName = "仙侠奇缘" },
{ catId = 82, catName = "现代言情" }, { catId = 83, catName = "浪漫青春" },
{ catId = 84, catName = "玄幻言情" }, { catId = 85, catName = "悬疑推理" },
{ catId = 30083, catName = "短篇" }, { catId = 86, catName = "科幻空间" },
{ catId = 88, catName = "游戏竞技" }, { catId = 87, catName = "轻小说" },
{ catId = 30120, catName = "现实生活" },
}
local function node(params)
return "category?" .. Text.formEncode(params)
end
local function change(params, key, value)
local out = {}
for name, current in pairs(params) do out[name] = current end
out[key] = value == "" and nil or tostring(value)
if key == "catId" then out.subCatId = nil end
if key == "gender" then
out.catId = value == "female" and "80" or "21"
out.subCatId = nil
end
return node(out)
end
local function groups(params, categories, data)
local current = node(params)
local channels = Browse.group({
{ id = params.gender == "male" and current or change(params, "gender", "male"), title = _("男频") },
{ id = params.gender == "female" and current or change(params, "gender", "female"), title = _("女频") },
{ id = "yuepiao:-1", title = _("排行榜") },
}, current)
channels.title = _("频道")
local cats = {}
for _idx, cat in ipairs(params.gender == "female" and FEMALE or categories) do
cats[#cats + 1] = { id = change(params, "catId", cat.catId), title = _(cat.catName) }
end
local category = Browse.group(cats, current)
category.title = _("分类")
local out = { channels, category }
local sorts = {}
for _idx, item in ipairs(data.orderBy.items) do
sorts[#sorts + 1] = { id = change(params, "orderBy", item.value), title = LABELS[item.text] or _(item.text) }
end
local sort = Browse.group(sorts, current)
sort.title = _("排序")
out[#out + 1] = sort
for _idx, filter in ipairs(data.filters) do
local chips = {}
for _item, item in ipairs(filter.items) do
local value = tostring(item.value)
chips[#chips + 1] = {
id = change(params, filter.key, value),
title = LABELS[item.text] or _(item.text),
}
end
local group = Browse.group(chips, current)
group.title = filter.key == "subCatId" and _("子分类")
or (LABELS[filter.title] or _(filter.title))
out[#out + 1] = group
end
return out
end
---@param self QidianSource
---@param opts { node?: string, limit?: integer }
---@param cb fun(res: table|nil, err: string|nil)
---@return HttpJob
function Library.run(self, opts, cb)
local params = { gender = "male", catId = "21" }
if opts.node then
for key, value in opts.node:sub(10):gmatch("([^&=]+)=([^&]*)") do
if not KEYS[key] or (key ~= "gender" and not value:match("^%d*$")) then
return require("source.base").defer(cb, nil, _("起点分类条件无效"))
end
params[key] = Text.urlDecode(value)
end
end
if params.gender ~= "male" and params.gender ~= "female" then
return require("source.base").defer(cb, nil, _("起点分类条件无效"))
end
local cancelled, job = false, nil
local function load(categories)
local pending = true
local inner = Client.categoryAsync(params.catId, function(data, err)
pending = false
if cancelled then return end
if not data then cb(nil, err); return end
if type(data.filters) ~= "table" or type(data.orderBy) ~= "table"
or type(data.orderBy.items) ~= "table" then cb(nil, _("起点分类响应无效")); return end
job = Browse.pages(function(page, done)
local query = {}
for key, value in pairs(params) do query[key] = value end
query.pageNum = page
return Client.categoryListAsync(query, function(list, reason)
if not list then done(nil, reason); return end
local more = list.isLast ~= 1 and list.isLast ~= true
and (not tonumber(list.pageMax) or page < tonumber(list.pageMax))
done(Mapper.rank(list), nil, more)
end)
end, opts.limit or 60, groups(params, categories, data), function(result, reason)
if not cancelled then cb(result, reason) end
end)
end)
if pending then job = inner end
end
if self.category_info then
load(self.category_info)
else
local pending = true
local inner = Client.categoryAsync(nil, function(data, err)
pending = false
if cancelled then return end
if not data then cb(nil, err); return end
if type(data.info) ~= "table" or #data.info == 0 then cb(nil, _("起点分类响应无效")); return end
self.category_info = data.info
load(data.info)
end)
if pending then job = inner end
end
return { cancel = function()
cancelled = true
if job then job.cancel() end
end }
end
return Library
@@ -0,0 +1,636 @@
--[[--
起点中文网 HTTP 客户端(仅异步)。
详情、目录、章节走手机站 SSR 页面(m.qidian.com,页面内嵌 pageContext JSON)。
www.qidian.com 有 WAF,不用。书架是 /webcommon/bookshelf/*,要带 Cookie 里的 _csrfToken。
进度是章:拉书架行的 readCid;上传 /webcommon/chapter/updReadStatus。
chapterUpdateTime 必须是章节更新时间的 unix 秒,空字符串会把 getReadStatus 写坏,日期字符串直接 500。
免费章匿名可读(isBuy 仍是 0)。VIP 章 vipStatus=1 且 isBuy 不是 1 时只有预览;已购 VIP 的 content 是密文(cES / fEnS 非 0),由 fock.lua 解密(密钥 = Cookie 的 ywguid + 页面 fkp)。
@module koplugin.book.moonsource_qidian.client
--]]
local Fock = require("moonsource_qidian.fock")
local CookieLogin = require("source.cookie_login")
local JSON = require("json")
local logger = require("utils.log")
local Mapper = require("moonsource_qidian.mapper")
local Request = require("http.request")
local SourceBase = require("source.base")
local Text = require("utils.text")
local _ = require("l10n").get("moonsource_qidian")
local Client = {}
local SOURCE_ID = "ext.qidian"
local WEB = "https://m.qidian.com"
local UA = "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) "
.. "Version/16.0 Mobile/15E148 Safari/604.1"
local PAGE_SIZE = 20
local anon_csrf
local function anonymousCookie()
if not anon_csrf then anon_csrf = "_csrfToken=" .. require("utils.random").hex(16) end
return anon_csrf
end
---@return string|nil
function Client.cookie()
local cookie = require("utils.settings").getSource(SOURCE_ID).cookie
return type(cookie) == "string" and cookie ~= "" and cookie or nil
end
--- Cookie 请求头里的 _csrfToken。没有它书架接口一律 403。
---@param cookie string
---@return string|nil
function Client.csrf(cookie)
local token = type(cookie) == "string" and (
cookie:match("^_csrfToken=([^;]+)") or cookie:match(";%s*_csrfToken=([^;]+)"))
if not token or token == "" then return nil end
return token
end
---@param cookie string|nil
---@return string|nil
function Client.guid(cookie)
local value = type(cookie) == "string" and (cookie:match("^ywguid=([^;]+)")
or cookie:match(";%s*ywguid=([^;]+)"))
return value and value:match("^%d+$") and value or nil
end
---@param cookie string|nil
---@return table
local function headers(cookie)
return {
Cookie = cookie,
["User-Agent"] = UA,
Referer = WEB .. "/bookshelf/my/",
Origin = WEB,
}
end
---@param cookie string
---@param params table|nil
---@return string
local function query(cookie, params)
local parts = {}
for key, value in pairs(params or {}) do
parts[#parts + 1] = Text.urlEncode(key) .. "=" .. Text.urlEncode(value)
end
local token = Client.csrf(cookie)
if token then parts[#parts + 1] = "_csrfToken=" .. Text.urlEncode(token) end
table.sort(parts)
return table.concat(parts, "&")
end
--- 登录态失效只标记当前已保存的 Cookie,校验新 Cookie 时不污染旧登录态。
---@param cookie string
---@param msg string
---@return string
local function expired(cookie, msg)
if cookie ~= "" and cookie == Client.cookie() then
return require("source.auth").expire(SOURCE_ID, msg)
end
return msg
end
---@param cookie string
---@return string
local function loginGone(cookie)
return expired(cookie, _("起点登录已失效,请点「重新登录」,用 QQ阅读或起点 App 扫码。也可在账号设置里粘贴 Cookie。"))
end
---@param path string
---@param cookie string|nil
---@param cb fun(html: string|nil, err: string|nil)
---@return HttpJob
local function webGet(path, cookie, cb, cache_ttl)
return Request.get(WEB .. path, {
headers = headers(cookie),
timeout = require("http.timeout").net(1),
cache_ttl = cache_ttl,
}, function(raw, err, res)
if not raw then
local code = res and tonumber(res.code)
if cookie and cookie ~= "" and (code == 302 or code == 403) then
cb(nil, loginGone(cookie or ""))
else
cb(nil, err and tostring(err) or _("请求失败"))
end
return
end
cb(raw)
end)
end
---@param wire table|nil
---@param cookie string
---@return table|nil data
---@return string|nil err
local function okData(wire, cookie)
if tonumber(wire.code) == 0 and type(wire.data) == "table" then return wire.data end
local msg = type(wire.msg) == "string" and wire.msg ~= "" and wire.msg or _("响应无效")
if tonumber(wire.code) == 1403 then msg = loginGone(cookie) end
return nil, msg
end
---@param path string
---@param params table
---@param cookie string
---@param cb fun(data: table|nil, err: string|nil)
---@return HttpJob
local function apiGet(path, params, cookie, cb)
return Request.get(WEB .. path .. "?" .. query(cookie, params), {
accept = "application/json",
headers = headers(cookie),
timeout = require("http.timeout").net(1),
}, function(raw, err, res)
if not raw then
local code = res and tonumber(res.code)
if cookie:find("ywkey=", 1, true) and (code == 302 or code == 403) then
cb(nil, loginGone(cookie))
else
cb(nil, err and tostring(err) or _("请求失败"))
end
return
end
local ok, wire = pcall(JSON.decode, raw)
if not ok or type(wire) ~= "table" then cb(nil, _("响应无效")); return end
cb(okData(wire, cookie))
end)
end
---@param book_id string
---@param data table|nil
---@return boolean ok
---@return string|nil err
local function bookOk(book_id, data)
local row = type(data) == "table" and (data[book_id] or data[tostring(book_id)])
if type(row) == "table" and tonumber(row.code) ~= 0 then
return false, row.message or _("请求失败")
end
return true
end
--- 拉书架。先拉默认分组,再拉其余有书的分组,按书号去重。
---@param cookie string
---@param cb fun(rows: table[]|nil, err: string|nil)
---@return { cancel: fun() }
function Client.shelfAsync(cookie, cb)
if type(cookie) ~= "string" or cookie == "" then
return SourceBase.defer(cb, nil, _("未登录起点"))
end
if not Client.csrf(cookie) then
return SourceBase.defer(cb, nil, _("起点 Cookie 缺少登录凭证"))
end
local cancelled, job = false, nil
local books, seen, groups = {}, {}, nil
-- 自定义分组:id→名、bookId→分组名(一本书进多个组取第一个,和微信读书同一口径)。
-- 默认分组(-100)不算分组,没进自定义组的书在 Mapper 里保留题材分类。
local group_names, group_by_id = {}, {}
local fetchPage
local function addRows(list)
for _idx, row in ipairs(type(list) == "table" and list or {}) do
local id = row.bid and tostring(row.bid)
if id and not seen[id] then
seen[id] = true
books[#books + 1] = row
end
end
end
local function noteGroup(gid, list)
local name = group_names[gid]
if not name then return end
for _idx, row in ipairs(type(list) == "table" and list or {}) do
local id = row.bid and tostring(row.bid)
if id then group_by_id[id] = group_by_id[id] or name end
end
end
local function finish(err)
if cancelled then return end
if err then cb(nil, err); return end
for _idx, row in ipairs(books) do
row._group_name = group_by_id[tostring(row.bid)]
end
cb(books)
end
local function nextGroup()
local gid = groups and table.remove(groups, 1)
if not gid then finish(); return end
fetchPage(gid, 1)
end
fetchPage = function(gid, page)
if cancelled then return end
job = apiGet("/webcommon/bookshelf/mlist", {
gid = gid, sort = 0, pageNum = page, pageSize = PAGE_SIZE, sortChange = 0,
}, cookie, function(data, err)
if cancelled then return end
if not data then finish(err); return end
addRows(data.list)
if groups == nil then
groups = {}
for _idx, group in ipairs(type(data.groups) == "table" and data.groups or {}) do
local id = tonumber(group.groupId)
if id and id ~= -100 and tonumber(group.bookCount) ~= 0 then
groups[#groups + 1] = id
local name = type(group.groupName) == "string" and group.groupName or ""
if name ~= "" then group_names[id] = name end
end
end
end
noteGroup(gid, data.list)
local info = type(data.page) == "table" and data.page or {}
local list = type(data.list) == "table" and data.list or {}
if info.isLast == 1 or info.isLast == true or #list < PAGE_SIZE then
nextGroup()
else
fetchPage(gid, page + 1)
end
end)
end
fetchPage(-100, 1)
return { cancel = function()
cancelled = true
if job then job.cancel() end
end }
end
--- 校验 Cookie:书架页 200 且 pageData.user.isLogin。cookie 显式传入,登录入口先校验再保存。
--- 扫码会话可以没有 _csrfToken;校验成功后把书架页 Set-Cookie 合并进 account.cookie 再落盘。
---@param cookie string
---@param cb fun(ok: boolean|nil, err: string|nil, account: { id: string, cookie?: string }|nil)
---@return { cancel: fun() }
function Client.loginCheckAsync(cookie, cb)
if type(cookie) ~= "string" or cookie == "" then
return SourceBase.defer(cb, nil, _("没有读到 Cookie"))
end
return Request.get(WEB .. "/bookshelf/my/", {
headers = headers(cookie),
timeout = require("http.timeout").net(1),
cache_ttl = 0,
}, function(raw, err, res)
if not raw then
local code = res and tonumber(res.code)
if code == 302 or code == 403 then
cb(nil, loginGone(cookie))
else
cb(nil, err and tostring(err) or _("请求失败"))
end
return
end
local user = (Mapper.pageData(raw) or {}).user
if not (type(user) == "table" and (user.isLogin == true or user.login == true)) then
cb(nil, loginGone(cookie))
return
end
local guid = user.guid
if type(guid) ~= "number" and type(guid) ~= "string" then
cb(nil, _("起点账号标识缺失")); return
end
local id = type(guid) == "number" and string.format("%.0f", guid) or guid
if not id:match("^%d+$") then cb(nil, _("起点账号标识缺失")); return end
local refreshed = CookieLogin.parse(cookie, Request.headerAll(res, "Set-Cookie"))
if not Client.csrf(refreshed) then
cb(nil, _("起点 Cookie 缺少登录凭证")); return
end
if cookie == Client.cookie() or refreshed == Client.cookie() then
require("source.auth").ok(SOURCE_ID)
end
cb(true, nil, { id = id, cookie = refreshed })
end)
end
---@param book_id string
---@param cb fun(ok: boolean|nil, err: string|nil)
---@return { cancel: fun() }
function Client.addAsync(book_id, cb)
local cookie = Client.cookie()
if not cookie then return SourceBase.defer(cb, nil, _("未登录起点")) end
if not Client.csrf(cookie) then return SourceBase.defer(cb, nil, _("起点 Cookie 缺少登录凭证")) end
return Request.post(WEB .. "/webcommon/bookshelf/addbooks?" .. query(cookie), Text.formEncode({ bookId = book_id }), {
content_type = "application/x-www-form-urlencoded",
headers = headers(cookie),
timeout = require("http.timeout").net(1),
}, function(raw, err)
if not raw then cb(nil, err and tostring(err) or _("请求失败")); return end
local ok, wire = pcall(JSON.decode, raw)
if not ok or type(wire) ~= "table" then cb(nil, _("响应无效")); return end
local data, data_err = okData(wire, cookie)
if not data then cb(nil, data_err); return end
local added, add_err = bookOk(book_id, data)
cb(added and true or nil, add_err)
end)
end
--- 上报读到哪一章。updated 是章节更新时间的 unix 秒,不是「现在」。
---@param book_id string
---@param chapter_id string
---@param chapter_name string|nil
---@param is_vip integer|boolean|nil
---@param updated integer|string
---@param cb fun(ok: boolean|nil, err: string|nil)
---@return { cancel: fun() }
function Client.updateReadAsync(book_id, chapter_id, chapter_name, is_vip, updated, cb)
local cookie = Client.cookie()
if not cookie then return SourceBase.defer(cb, nil, _("未登录起点")) end
if not Client.csrf(cookie) then return SourceBase.defer(cb, nil, _("起点 Cookie 缺少登录凭证")) end
if updated == nil or tostring(updated) == "" then
return SourceBase.defer(cb, nil, _("起点章节时间缺失"))
end
return Request.post(WEB .. "/webcommon/chapter/updReadStatus?" .. query(cookie), Text.formEncode({
bookId = book_id,
chapterId = chapter_id,
chapterName = chapter_name or "",
isVip = (is_vip == true or tonumber(is_vip) == 1) and "1" or "0",
chapterUpdateTime = tostring(updated),
}), {
content_type = "application/x-www-form-urlencoded",
headers = headers(cookie),
timeout = require("http.timeout").net(1),
}, function(raw, err)
if not raw then cb(nil, err and tostring(err) or _("请求失败")); return end
local ok, wire = pcall(JSON.decode, raw)
if not ok or type(wire) ~= "table" then cb(nil, _("响应无效")); return end
-- 成功时 data 不是表(常为空)。不能走 okData,否则 code=0 也会被当成失败。
if tonumber(wire.code) == 0 then cb(true); return end
local msg = type(wire.msg) == "string" and wire.msg ~= "" and wire.msg or _("响应无效")
if tonumber(wire.code) == 1403 then msg = loginGone(cookie) end
cb(nil, msg)
end)
end
---@param book_id string
---@param cb fun(ok: boolean|nil, err: string|nil)
---@return { cancel: fun() }
function Client.removeAsync(book_id, cb)
local cookie = Client.cookie()
if not cookie then return SourceBase.defer(cb, nil, _("未登录起点")) end
return apiGet("/webcommon/bookshelf/delbook", { bids = book_id, gid = -100 }, cookie, function(data, err)
if not data then cb(nil, err); return end
local removed, remove_err = bookOk(book_id, data)
cb(removed and true or nil, remove_err)
end)
end
--- 搜索:匿名双提交 CSRF,首页及后续页同一接口。
---@param keyword string
---@param cb fun(data: table|nil, err: string|nil)
---@param page integer|nil
---@return HttpJob
function Client.searchAsync(keyword, cb, page)
return apiGet("/webcommon/search/list", { kw = keyword, pageNum = page or 1 }, anonymousCookie(), function(data, err)
if not data then cb(nil, err); return end
if type(data.bookInfo) ~= "table" or type(data.bookInfo.records) ~= "table" then
cb(nil, _("起点搜索响应无效")); return
end
cb(data)
end)
end
--- 榜单页(手机网页 SSR,一页 20 本)。path 如 /rank/yuepiao/catid21/。
---@param path string
---@param cb fun(data: table|nil, err: string|nil)
---@return HttpJob
function Client.rankAsync(path, cb)
return webGet(path, nil, function(html, err)
if not html then cb(nil, err); return end
local data = Mapper.pageData(html)
if not data or type(data.records) ~= "table" then cb(nil, _("起点榜单为空")); return end
cb(data)
end)
end
---@param key string
---@param cat string
---@param page integer
---@param cb fun(data: table|nil, err: string|nil)
---@return HttpJob
function Client.rankPageAsync(key, cat, page, cb)
local kind = key == "readindex" and "readIndex" or key
return apiGet("/webcommon/rank/" .. kind .. "list", {
catId = cat, gender = "male", pageNum = page,
}, anonymousCookie(), function(data, err)
if not data then cb(nil, err); return end
if type(data.records) ~= "table" then cb(nil, _("起点榜单响应无效")); return end
cb(data)
end)
end
---@param book_id string
---@param cb fun(info: table|nil, err: string|nil)
---@return HttpJob
function Client.detailAsync(book_id, cb)
return webGet("/book/" .. book_id .. "/", Client.cookie(), function(html, err)
if not html then cb(nil, err); return end
local info = (Mapper.pageData(html) or {}).bookInfo
if type(info) ~= "table" or not info.bookName then
cb(nil, _("起点书籍信息为空"))
return
end
cb(info)
end)
end
---@param book_id string
---@param cb fun(data: table|nil, err: string|nil)
---@return HttpJob
function Client.bookCircleAsync(book_id, cb)
return webGet("/readersCircle/" .. book_id .. "/", nil, function(html, err)
if not html then cb(nil, err); return end
local data = Mapper.pageData(html)
if not data or type(data.bookCirclePost) ~= "table" then
cb(nil, _("起点书友圈响应无效")); return
end
cb(data.bookCirclePost)
end)
end
---@param book_id string
---@param cb fun(data: table|nil, err: string|nil)
---@return HttpJob
function Client.catalogAsync(book_id, cb)
return webGet("/book/" .. book_id .. "/catalog/", Client.cookie(), function(html, err)
if not html then cb(nil, err); return end
local data = Mapper.pageData(html)
if not data then cb(nil, _("起点目录为空")); return end
cb(data)
end)
end
--- 一章正文。未购买的 VIP(vipStatus=1 且 isBuy 不是 1)只有预览,不当正文。
---@param book_id string
---@param chapter_id string
---@param cb fun(text: string|nil, err: string|nil, kind: "unpaid"|nil) kind = "unpaid":这章没买
---@return HttpJob
function Client.contentAsync(book_id, chapter_id, cb)
local cookie, cancelled = Client.cookie(), false
local decrypting, font_job
local function finish_html(content)
local text = Mapper.chapterText(content)
if not text then cb(nil, _("起点章节内容为空")); return end
cb(text)
end
local function finish_text(text)
if type(text) ~= "string" or Text.trim(text) == "" then cb(nil, _("起点章节内容为空")); return end
cb(text)
end
local function decrypt_done(text, derr)
if cancelled then return end
decrypting = nil
if not text then
logger.warn("qidian fock decrypt failed:", derr)
cb(nil, _("起点 VIP 章节解密失败") .. (derr and (":" .. tostring(derr)) or "")); return
end
finish_text(text)
end
local fetch = webGet("/chapter/" .. book_id .. "/" .. chapter_id .. "/", cookie, function(html, err)
if cancelled then return end
if not html then cb(nil, err); return end
local data = Mapper.pageData(html) or {}
local info = data.chapterInfo
if type(info) ~= "table" then cb(nil, _("起点章节内容为空")); return end
if Mapper.locked(info) then cb(nil, _("起点 VIP 章节未购买"), "unpaid"); return end
local content = info.content
local ces = tonumber(info.cES) or 0
if ces ~= 0 and ces ~= 2 then
logger.warn("qidian unknown cES:", ces)
cb(nil, _("起点 VIP 章节加密方式不受支持")); return
end
local fock = Mapper.fockEncrypted(info)
local font_protected = Mapper.fontProtected(info)
if not fock and not font_protected then finish_html(content); return end
local keypool, version, uid
if fock then
local page_guid = type(data.user) == "table" and data.user.guid
uid = type(page_guid) == "number" and string.format("%.0f", page_guid)
or (type(page_guid) == "string" and page_guid or Client.guid(cookie))
if page_guid and uid ~= Client.guid(cookie) then
logger.warn("qidian chapter identity differs from login cookie; using response identity")
end
-- fkp 是 base64 的 `window.onkeyfocus("<密钥池>", <版本>)`,只取参数,不执行
keypool, version = Text.base64Decode(tostring(info.fkp or ""))
:match('onkeyfocus%("([^"]+)",%s*(%d+)%)')
if type(content) ~= "string" or content == "" then
logger.warn("qidian encrypted chapter content empty")
cb(nil, _("起点 VIP 章节正文为空,请退出后重新扫码或改用 Cookie 登录")); return
end
if not (uid and uid:match("^%d+$") and keypool and version) then
logger.warn("qidian decrypt inputs missing: uid", uid ~= nil, "keypool", keypool ~= nil,
"version", version ~= nil)
cb(nil, require("source.cookie_login").relogin(
_("起点中文网"), "https://m.qidian.com/", _("起点中文网 → 起点账号"))); return
end
end
local function run(fixed_font)
local pending = true
local function done(plain, derr)
pending = false
decrypt_done(plain, derr)
end
local job
if font_protected then
if fock then
job = Fock.chapterAsync(info, fixed_font, chapter_id, keypool, version, uid, done)
else
job = Fock.restoreAsync(content, info, fixed_font, done)
end
else
job = Fock.decryptAsync(content, chapter_id, keypool, version, uid, function(plain, derr)
pending = false
if cancelled then return end
decrypting = nil
if not plain then
logger.warn("qidian fock decrypt failed:", derr)
cb(nil, _("起点 VIP 章节解密失败") .. (derr and (":" .. tostring(derr)) or "")); return
end
finish_html(plain)
end)
end
if pending then decrypting = job end
end
if not font_protected then run(nil); return end
local url = info.fixedFontTtf
if type(url) ~= "string" or url == "" or type(info.randomFont) ~= "string" or type(info.css) ~= "string" then
logger.warn("qidian font inputs missing: fixedFontTtf", type(url), "randomFont", type(info.randomFont),
"css", type(info.css))
cb(nil, _("起点 VIP 章节字体解密失败:缺少字体信息")); return
end
font_job = Request.get(url, {
headers = { ["User-Agent"] = UA, ["Referer"] = "https://m.qidian.com/" },
timeout = require("http.timeout").net(3),
}, function(ttf, ferr, res)
if cancelled then return end
font_job = nil
if not ttf or #ttf == 0 then
logger.warn("qidian font download failed:", ferr, "code", res and res.code, "len", ttf and #ttf)
cb(nil, _("起点 VIP 章节字体下载失败")); return
end
if not require("moonsource_qidian.yuewen_fonts").looksLikeFont(ttf) then
logger.warn("qidian font download invalid:", #ttf, tostring(ttf:sub(1, 16)), "code", res and res.code)
cb(nil, _("起点 VIP 章节字体下载失败")); return
end
run(ttf)
end)
end)
return { cancel = function()
cancelled = true
fetch.cancel()
if font_job then font_job:cancel() end
if decrypting then decrypting:cancel() end
end }
end
--- 分类目录或分类首屏(含官网动态筛选元数据),公共请求不带账号。
---@param cat_id string|nil
---@param cb fun(data: table|nil, err: string|nil)
---@return HttpJob
function Client.categoryAsync(cat_id, cb)
return webGet("/category/" .. (cat_id and ("catid" .. cat_id .. "/") or ""), nil, function(html, err)
if not html then cb(nil, err); return end
local data = Mapper.pageData(html)
if not data then cb(nil, _("起点分类响应无效")); return end
cb(data)
end)
end
--- 分类后续页,匿名 CSRF 双提交。
---@param params table
---@param cb fun(data: table|nil, err: string|nil)
---@return HttpJob
function Client.categoryListAsync(params, cb)
return apiGet("/webcommon/category/list", params, anonymousCookie(), function(data, err)
if not data then cb(nil, err); return end
if type(data.records) ~= "table" then cb(nil, _("起点分类响应无效")); return end
cb(data)
end)
end
--- 本章各段评论数;list[].paragraphId 从 1 数,-1 是章末总评;enableReview = 0 表示这本书没开段评。
---@param book_id string
---@param chapter_id string
---@param cb fun(data: table|nil, err: string|nil)
---@return HttpJob
function Client.reviewSummaryAsync(book_id, chapter_id, cb)
return apiGet("/webcommon/chapterreview/reviewsummary4m", { bookId = book_id, chapterId = chapter_id },
Client.cookie() or anonymousCookie(), cb)
end
--- 某段的一页评论(page 从 1 起,每页 10 条左右)。
---@param book_id string
---@param chapter_id string
---@param paragraph_id integer
---@param page integer
---@param cb fun(data: table|nil, err: string|nil)
---@return HttpJob
function Client.reviewListAsync(book_id, chapter_id, paragraph_id, page, cb)
return apiGet("/webcommon/chapterreview/reviewlist4m", {
bookId = book_id, chapterId = chapter_id, paragraphId = paragraph_id, page = page,
}, Client.cookie() or anonymousCookie(), cb)
end
return Client
@@ -0,0 +1,109 @@
--[[--
起点 VIP 章节正文解密(Fock):阅文 wasm 的起点构建参数 + 子进程编排,宿主在 `moonsource_qidian.yuewen_fock`。
网页端用它解密 `chapterInfo.content`。
@module moonsource_qidian.fock
--]]--
local Shared = require("moonsource_qidian.yuewen_fock")
local FontRestore = require("moonsource_qidian.yuewen_fonts")
local JSON = require("json")
local Fock = {}
-- 起点 font 层的字形与参考 Noto 偶有 0.65~0.75 的形近字(如 䵻→对),比 QQ阅读放宽一点。
local FONT_THRESHOLD = 0.65
---@param info table chapterInfo
---@return table
local function fontData(info)
local raw = info.randomFont
assert(type(raw) == "string" and raw ~= "", "qidian randomFont missing")
local ok, random = pcall(JSON.decode, raw)
if not ok or type(random) ~= "table" then
error("qidian randomFont decode failed: " .. tostring(random))
end
return { css = info.css or "", randomFont = random }
end
--- 还原字体层;抛错转成 `{ err }`,不让子进程崩在 on_failed 里丢上下文。
---@return { text: string|nil, err: string|nil }
local function restore(html, info, fixed_font, temp_paths)
local ok, text = pcall(FontRestore.restore, html, fontData(info), fixed_font,
{ dedupe = true, confusions = true, threshold = FONT_THRESHOLD, temp_paths = temp_paths })
if not ok then return { err = "font: " .. tostring(text) } end
return { text = text }
end
local HOST = {
["location.hostname"] = "vipreader.qidian.com",
["location.protocol"] = "https:",
}
---@type YuewenFockBuild
local BUILD = {
wasm = "moonsource_qidian.fock_wasm",
callback = 22685,
stack = 5274992,
exports = { ctors = "g", main = "m", set_uid = "h", set_key = "i", decrypt = "j",
stack_save = "n", stack_restore = "o", alloc = "p", malloc = "q" },
-- 其余是反调试 / 定时器探测:返回 -1(那几个会返回 indexOf 结果)或 0
probe = function(code)
if code == 14394 or code == 14449 or code == 14875 then return 0 end
if code % 709 == 15372 % 709 then return -1 end
return 0
end,
imports = function(env)
return {
f = function() return 0 end,
c = function(a, b) return env.malloc_str(HOST[env.cstr(a) .. "." .. env.cstr(b)] or "undefined") end,
e = function() return env.malloc_str("undefined") end,
}
end,
}
---@param content string base64 密文
---@param chapter_id string|number
---@param keypool string base64 密钥池(fkp 里 onkeyfocus 的第一个参数)
---@param version string
---@param uid string 用户 ywguid
---@return string|nil text
---@return string|nil err
function Fock.decrypt(content, chapter_id, keypool, version, uid)
return Shared.decrypt(BUILD, content, chapter_id, keypool, version, uid)
end
--- 在子进程里解密;回调拿明文或错误。
---@return BookJob
function Fock.decryptAsync(content, chapter_id, keypool, version, uid, cb)
return Shared.jobAsync("qidian_fock", function()
local plain, err = Fock.decrypt(content, chapter_id, keypool, version, uid)
return { text = plain, err = err }
end, cb)
end
--- 在子进程里解密并还原 cES=2 的字体层;回调拿纯文本或错误。
--- 起点会在正文尾部追加一份同长度的诱饵副本,restore 的 dedupe 会丢掉它。
---@param info table chapterInfo
---@param fixed_font string fixedFontTtf 下载下来的字节
---@return BookJob
function Fock.chapterAsync(info, fixed_font, chapter_id, keypool, version, uid, cb)
return Shared.jobAsync("qidian_fock", function(temp_paths)
local plain, err = Fock.decrypt(info.content, chapter_id, keypool, version, uid)
if not plain then return { err = "decrypt: " .. tostring(err) } end
return restore(plain, info, fixed_font, temp_paths)
end, cb)
end
--- 只有字体层(fEnS=0)时直接还原明文 HTML。
---@param html string Fock 明文或页面正文 HTML
---@param info table chapterInfo
---@param fixed_font string
---@return BookJob
function Fock.restoreAsync(html, info, fixed_font, cb)
return Shared.jobAsync("qidian_font", function(temp_paths)
return restore(html, info, fixed_font, temp_paths)
end, cb)
end
return Fock
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,147 @@
return {
["起点书友圈响应无效"] = "Invalid Qidian book community response.",
["书友圈预览(%1/%2)"] = "Book community preview (%1/%2)",
["书友圈帖子预览"] = "Book community post previews",
["完结"] = "Completed",
["起点榜单响应无效"] = "Invalid Qidian ranking response.",
["排行榜"] = "Rankings",
["分类书库"] = "Category library",
["切换账号"] = "Switch account",
["切换起点账号会清除这台设备上起点的书架、阅读进度、笔记和缓存,包括尚未同步的记录。不会删除远端书架。确定继续?"] = "Switching Qidian accounts clears this device's Qidian shelf, progress, notes and cache, including unsynced records. Your remote shelf will not be deleted. Continue?",
["刷新验证码"] = "Refresh verification",
["同意并获取验证码"] = "Agree and send code",
["子分类"] = "Subcategory",
["提交"] = "Submit",
["无法确认旧账号,请先退出旧账号再登录"] = "Cannot identify the previous account. Sign out before signing in again.",
["本章讨论"] = "Chapter discussion",
["筛选"] = "Filters",
["获取验证码前请阅读并同意阅文用户服务协议和隐私政策"] = "Before requesting a code, read and agree to the Yuewen terms of service and privacy policy.",
["请输入验证码"] = "Enter the verification code.",
["起点分类响应无效"] = "Invalid Qidian category response.",
["起点分类条件无效"] = "Invalid Qidian category filters.",
["起点安全验证"] = "Qidian security verification",
["起点手机号验证码登录"] = "Qidian SMS sign-in",
["起点搜索响应无效"] = "Invalid Qidian search response.",
["起点登录响应无效"] = "Invalid Qidian sign-in response.",
["起点登录未获取到本站会话"] = "Could not establish a Qidian website session.",
["起点登录缺少会话兑换凭据"] = "Missing Qidian session exchange credentials.",
["起点登录跳转地址无效"] = "Invalid Qidian sign-in redirect.",
["起点登录跳转过多"] = "Too many Qidian sign-in redirects.",
["起点登录需要未支持的验证"] = "Qidian requires an unsupported verification method.",
["起点短信会话缺失"] = "Missing Qidian SMS session.",
["起点账号标识缺失"] = "Missing Qidian account identity.",
["起点验证码刷新失败"] = "Could not refresh Qidian verification.",
["起点验证码响应无效"] = "Invalid Qidian verification response.",
["起点验证码图片无效"] = "Invalid Qidian verification image.",
["100~200万"] = "1–2 million words",
["200万以上"] = "Over 2 million words",
["30~50万"] = "300–500 thousand words",
["30万以下"] = "Under 300 thousand words",
["50~100万"] = "500 thousand–1 million words",
["VIP"] = "VIP",
["一月内"] = "Within a month",
["七日内"] = "Within a week",
["三日内"] = "Within three days",
["东方玄幻"] = "Eastern fantasy",
["二级分类"] = "Subcategory",
["人气"] = "Popularity",
["仙侠奇缘"] = "Immortal romance",
["半月内"] = "Within two weeks",
["古代言情"] = "Historical romance",
["品质"] = "Quality",
["完本"] = "Completed",
["属性"] = "Access",
["异世大陆"] = "Otherworld fantasy",
["月票"] = "Monthly votes",
["浪漫青春"] = "Teen romance",
["游戏竞技"] = "Gaming and competition",
["点击"] = "Views",
["玄幻言情"] = "Fantasy romance",
["王朝争霸"] = "Dynastic conflict",
["现代言情"] = "Contemporary romance",
["现实生活"] = "Everyday life",
["科幻空间"] = "Sci-fi romance",
["签约作品"] = "Contracted works",
["精品小说"] = "Featured novels",
["连载"] = "Ongoing",
["高武世界"] = "Martial fantasy",
["用同一 Wi-Fi 下的手机扫码完成安全验证;手机号、密码和短信码只在设备填写。"] = "Scan with a phone on the same Wi-Fi to complete security verification. Enter your phone number, password and SMS code only on the device.",
["请完成下方安全验证"] = "Complete the security verification below.",
["验证已提交,请回到设备查看结果。"] = "Verification submitted. Return to the device to see the result.",
["国际区号"] = "Country calling code",
["请输入有效的手机号和国际区号"] = "Enter a valid phone number and country calling code.",
["请稍后再获取验证码"] = "Please wait before requesting another code.",
["验证码已发送"] = "Verification code sent",
["正在获取验证码…"] = "Requesting a verification code…",
["正在处理,请稍候"] = "Processing, please wait.",
["请先获取该手机号的验证码,再填写验证码登录"] = "Request a code for this phone number, then enter it to sign in.",
["频道"] = "Channel",
["章节评论"] = "Chapter comments",
["悬疑推理"] = "Detective fiction",
["获取验证码"] = "Get code",
["手机号验证码登录"] = "Sign in with an SMS code",
["请先获取验证码"] = "Request a verification code first",
["扫码登录"] = "Sign in with QR code",
["起点扫码登录"] = "Qidian QR sign-in",
["起点登录已失效,请点「重新登录」,用 QQ阅读或起点 App 扫码。也可在账号设置里粘贴 Cookie。"] = "Qidian sign-in has expired. Tap Sign in again and scan with QQReader or Qidian. You can also paste a Cookie in account settings.",
["验证已过期,请重新发起验证"] = "Verification expired. Please start again",
["未登录 · 点此扫码"] = "Not signed in · tap to scan",
["正在登录…"] = "Signing in…",
["章节目录保存失败"] = "Failed to save chapter list",
["缺少起点章节位置"] = "Missing Qidian chapter position",
["起点段评响应缺少评论列表"] = "Qidian paragraph comments response has no comment list",
["手机号"] = "Phone number",
["按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"] = "Press F12, open Network, refresh, and copy the entire Cookie request header",
["起点账号"] = "Qidian account",
["起点登录 Cookie"] = "Qidian login cookie",
["起点 Cookie 缺少登录凭证"] = "Qidian Cookie is missing the sign-in token",
["确定退出起点账号?"] = "Sign out of Qidian?",
["未登录起点"] = "Not signed in to Qidian",
["起点书籍信息为空"] = "Qidian book info is empty",
["起点章节内容为空"] = "Qidian chapter is empty",
["起点 VIP 章节未购买"] = "This Qidian VIP chapter is not purchased",
["起点 VIP 章节正文为空,请退出后重新扫码或改用 Cookie 登录"] = "Qidian VIP chapter body is empty. Sign out, scan again, or paste Cookie instead",
["起点 VIP 章节解密失败"] = "Failed to decrypt this Qidian VIP chapter",
["起点 VIP 章节加密方式不受支持"] = "This Qidian VIP chapter uses an unsupported encryption mode",
["起点 VIP 章节字体下载失败"] = "Failed to download the Qidian VIP chapter font",
["起点 VIP 章节字体解密失败:缺少字体信息"] = "Failed to restore the Qidian VIP chapter font: font info missing",
["起点目录为空"] = "Qidian table of contents is empty",
["起点章节时间缺失"] = "Qidian chapter time is missing",
["用 QQ阅读或起点 App 扫一扫"] = "Scan with the QQ Reader or Qidian app",
["起点中文网 → 起点账号"] = "Qidian → Qidian account",
["仙侠"] = "Xianxia",
["体育"] = "Sports",
["全站"] = "All",
["军事"] = "Military",
["历史"] = "History",
["奇幻"] = "Fantasy",
["女频"] = "Female",
["悬疑灵异"] = "Mystery & Supernatural",
["新书榜"] = "New Books",
["新人榜"] = "Rookies",
["新作者榜"] = "New Authors",
["更新榜"] = "Updates",
["月票榜"] = "Monthly Votes",
["武侠"] = "Wuxia",
["玄幻"] = "Xuanhuan",
["现实"] = "Realistic",
["男频"] = "Male",
["畅销榜"] = "Bestsellers",
["短篇"] = "Short Stories",
["科幻"] = "Sci-Fi",
["诸天无限"] = "Infinite Worlds",
["起点榜单为空"] = "Qidian ranking is empty",
["轻小说"] = "Light Novels",
["都市"] = "Urban",
["阅读指数榜"] = "Reading Index",
["无法打开远程验证,请先连接 Wi-Fi 并启用远程管理功能"] = "Cannot open remote verification. Connect to Wi-Fi and enable Remote management first.",
["验证已取消"] = "Verification cancelled",
["验证凭据无效"] = "Invalid verification proof",
["正在提交验证…"] = "Submitting verification…",
["验证失败,请重新验证"] = "Verification failed. Please try again",
["VIP 章节"] = "VIP chapters",
["书架同步"] = "Shelf sync",
["搜索与发现"] = "Search and discover",
["起点中文网书架与在线阅读"] = "Qidian shelf and online reading",
["进度同步"] = "Progress sync",
}
@@ -0,0 +1,147 @@
return {
["起点书友圈响应无效"] = "起點書友圈回應無效",
["书友圈预览(%1/%2)"] = "書友圈預覽(%1/%2)",
["书友圈帖子预览"] = "書友圈帖子預覽",
["完结"] = "完結",
["起点榜单响应无效"] = "起點排行榜回應無效",
["排行榜"] = "排行榜",
["分类书库"] = "分類書庫",
["切换账号"] = "切換帳號",
["切换起点账号会清除这台设备上起点的书架、阅读进度、笔记和缓存,包括尚未同步的记录。不会删除远端书架。确定继续?"] = "切換起點帳號會清除這台裝置上起點的書架、閱讀進度、筆記和快取,包括尚未同步的記錄。不會刪除遠端書架。確定繼續?",
["刷新验证码"] = "重新整理驗證碼",
["同意并获取验证码"] = "同意並取得驗證碼",
["子分类"] = "子分類",
["提交"] = "送出",
["无法确认旧账号,请先退出旧账号再登录"] = "無法確認舊帳號,請先登出舊帳號再登入",
["本章讨论"] = "本章討論",
["筛选"] = "篩選",
["获取验证码前请阅读并同意阅文用户服务协议和隐私政策"] = "取得驗證碼前請閱讀並同意閱文使用者服務協議和隱私政策",
["请输入验证码"] = "請輸入驗證碼",
["起点分类响应无效"] = "起點分類回應無效",
["起点分类条件无效"] = "起點分類條件無效",
["起点安全验证"] = "起點安全驗證",
["起点手机号验证码登录"] = "起點手機號碼驗證碼登入",
["起点搜索响应无效"] = "起點搜尋回應無效",
["起点登录响应无效"] = "起點登入回應無效",
["起点登录未获取到本站会话"] = "起點登入未取得本站工作階段",
["起点登录缺少会话兑换凭据"] = "起點登入缺少工作階段兌換憑據",
["起点登录跳转地址无效"] = "起點登入重新導向位址無效",
["起点登录跳转过多"] = "起點登入重新導向過多",
["起点登录需要未支持的验证"] = "起點登入需要尚未支援的驗證",
["起点短信会话缺失"] = "起點簡訊工作階段缺失",
["起点账号标识缺失"] = "起點帳號識別缺失",
["起点验证码刷新失败"] = "起點驗證碼重新整理失敗",
["起点验证码响应无效"] = "起點驗證碼回應無效",
["起点验证码图片无效"] = "起點驗證碼圖片無效",
["100~200万"] = "100~200 萬字",
["200万以上"] = "200 萬字以上",
["30~50万"] = "30~50 萬字",
["30万以下"] = "30 萬字以下",
["50~100万"] = "50~100 萬字",
["VIP"] = "VIP",
["一月内"] = "一個月內",
["七日内"] = "七日內",
["三日内"] = "三日內",
["东方玄幻"] = "東方玄幻",
["二级分类"] = "次分類",
["人气"] = "人氣",
["仙侠奇缘"] = "仙俠奇緣",
["半月内"] = "半個月內",
["古代言情"] = "古代言情",
["品质"] = "品質",
["完本"] = "完結",
["属性"] = "屬性",
["异世大陆"] = "異世大陸",
["月票"] = "月票",
["浪漫青春"] = "浪漫青春",
["游戏竞技"] = "遊戲競技",
["点击"] = "點擊",
["玄幻言情"] = "玄幻言情",
["王朝争霸"] = "王朝爭霸",
["现代言情"] = "現代言情",
["现实生活"] = "現實生活",
["科幻空间"] = "科幻空間",
["签约作品"] = "簽約作品",
["精品小说"] = "精品小說",
["连载"] = "連載",
["高武世界"] = "高武世界",
["用同一 Wi-Fi 下的手机扫码完成安全验证;手机号、密码和短信码只在设备填写。"] = "用同一 Wi-Fi 下的手機掃碼完成安全驗證;手機號碼、密碼和簡訊碼只在裝置填寫。",
["请完成下方安全验证"] = "請完成下方安全驗證",
["验证已提交,请回到设备查看结果。"] = "驗證已提交,請回到裝置查看結果。",
["国际区号"] = "國際區碼",
["请输入有效的手机号和国际区号"] = "請輸入有效的手機號碼和國際區碼",
["请稍后再获取验证码"] = "請稍後再取得驗證碼",
["验证码已发送"] = "驗證碼已發送",
["正在获取验证码…"] = "正在取得驗證碼…",
["正在处理,请稍候"] = "正在處理,請稍候",
["请先获取该手机号的验证码,再填写验证码登录"] = "請先取得該手機號碼的驗證碼,再填寫驗證碼登入",
["频道"] = "頻道",
["章节评论"] = "章節評論",
["悬疑推理"] = "懸疑推理",
["获取验证码"] = "取得驗證碼",
["手机号验证码登录"] = "手機號碼驗證碼登入",
["请先获取验证码"] = "請先取得驗證碼",
["扫码登录"] = "掃碼登入",
["起点扫码登录"] = "起點掃碼登入",
["起点登录已失效,请点「重新登录」,用 QQ阅读或起点 App 扫码。也可在账号设置里粘贴 Cookie。"] = "起點登入已失效,請點「重新登入」,用 QQ閱讀或起點 App 掃碼。也可在帳號設定裡貼上 Cookie。",
["验证已过期,请重新发起验证"] = "驗證已過期,請重新發起驗證",
["未登录 · 点此扫码"] = "未登入 · 點此掃碼",
["正在登录…"] = "正在登入…",
["章节目录保存失败"] = "章節目錄儲存失敗",
["缺少起点章节位置"] = "缺少起點章節位置",
["起点段评响应缺少评论列表"] = "起點段評回應缺少評論列表",
["手机号"] = "手機號碼",
["按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"] = "按鍵盤 F12,點「網路」,重新整理網頁,複製請求標頭裡的整段 Cookie",
["起点账号"] = "起點帳號",
["起点登录 Cookie"] = "起點登入 Cookie",
["起点 Cookie 缺少登录凭证"] = "起點 Cookie 缺少登入憑證",
["确定退出起点账号?"] = "確定登出起點帳號?",
["未登录起点"] = "未登入起點",
["起点书籍信息为空"] = "起點書籍資訊為空",
["起点章节内容为空"] = "起點章節內容為空",
["起点 VIP 章节未购买"] = "此起點 VIP 章節尚未購買",
["起点 VIP 章节正文为空,请退出后重新扫码或改用 Cookie 登录"] = "起點 VIP 章節正文為空,請登出後重新掃碼或改用 Cookie 登入",
["起点 VIP 章节解密失败"] = "起點 VIP 章節解密失敗",
["起点 VIP 章节加密方式不受支持"] = "此起點 VIP 章節使用不支援的加密方式",
["起点 VIP 章节字体下载失败"] = "起點 VIP 章節字體下載失敗",
["起点 VIP 章节字体解密失败:缺少字体信息"] = "起點 VIP 章節字體解密失敗:缺少字體資訊",
["起点目录为空"] = "起點目錄為空",
["起点章节时间缺失"] = "起點章節時間缺失",
["用 QQ阅读或起点 App 扫一扫"] = "用 QQ閱讀或起點 App 掃一掃",
["起点中文网 → 起点账号"] = "起點中文網 → 起點帳號",
["仙侠"] = "仙俠",
["体育"] = "體育",
["全站"] = "全站",
["军事"] = "軍事",
["历史"] = "歷史",
["奇幻"] = "奇幻",
["女频"] = "女頻",
["悬疑灵异"] = "懸疑靈異",
["新书榜"] = "新書榜",
["新人榜"] = "新人榜",
["新作者榜"] = "新作者榜",
["更新榜"] = "更新榜",
["月票榜"] = "月票榜",
["武侠"] = "武俠",
["玄幻"] = "玄幻",
["现实"] = "現實",
["男频"] = "男頻",
["畅销榜"] = "暢銷榜",
["短篇"] = "短篇",
["科幻"] = "科幻",
["诸天无限"] = "諸天無限",
["起点榜单为空"] = "起點榜單為空",
["轻小说"] = "輕小說",
["都市"] = "都市",
["阅读指数榜"] = "閱讀指數榜",
["无法打开远程验证,请先连接 Wi-Fi 并启用远程管理功能"] = "無法打開遠端驗證,請先連接 Wi-Fi 並啟用遠端管理功能",
["验证已取消"] = "驗證已取消",
["验证凭据无效"] = "驗證憑據無效",
["正在提交验证…"] = "正在提交驗證…",
["验证失败,请重新验证"] = "驗證失敗,請重新驗證",
["VIP 章节"] = "VIP 章節",
["书架同步"] = "書架同步",
["搜索与发现"] = "搜尋與發現",
["起点中文网书架与在线阅读"] = "起點中文網書架與線上閱讀",
["进度同步"] = "進度同步",
}
@@ -0,0 +1,5 @@
return function()
local copy = {}
for k, v in pairs(require("moonsource_qidian._meta")) do copy[k] = v end
return copy
end
@@ -0,0 +1,196 @@
--[[--
起点官方 Web 短信登录会话。图形验证与短信使用不同 sessionKey,不保存手机号或验证码。
@module moonsource_qidian.login
--]]
local JSON = require("json")
local Request = require("http.request")
local Text = require("utils.text")
local CookieLogin = require("source.cookie_login")
local _ = require("l10n").get("moonsource_qidian")
local BASE = "https://ptlogin.yuewen.com"
local UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/131.0.0.0 Safari/537.36"
local LOGIN_KEYS = { ywguid = true, ywkey = true, ywopenid = true }
local HOSTS = { ["ptlogin.yuewen.com"] = true, ["passport.yuewen.com"] = true,
["passport.qidian.com"] = true, ["m.qidian.com"] = true }
---@class QidianLogin
---@field jar table<string, string>
---@field webjar table<string, string>
---@field generation integer
---@field job HttpJob|nil
---@field initialized boolean|nil
---@field challenge_key string|nil
---@field sms_key string|nil
---@field cancelled boolean|nil
local Login = {}
Login.__index = Login
function Login.new()
return setmetatable({ jar = {}, webjar = {}, generation = 0 }, Login)
end
function Login:cancel()
self.cancelled = true
self:interrupt()
self.sms_key, self.challenge_key = nil, nil
self.jar, self.webjar = {}, {}
end
function Login:interrupt()
self.generation = self.generation + 1
if self.job then self.job.cancel() end
self.job = nil
end
local function cookies(jar)
local parts = {}
for name, value in pairs(jar) do parts[#parts + 1] = name .. "=" .. value end
return CookieLogin.parse(table.concat(parts, "; "))
end
function Login:_get(url, cb)
if self.cancelled then return end
local host = url:match("^https://([^/?#]+)")
if not HOSTS[host] then cb(nil, _("起点登录跳转地址无效")); return end
local headers = { ["User-Agent"] = UA, Referer = "https://passport.qidian.com/mobile/login" }
if host == "ptlogin.yuewen.com" then headers.Cookie = cookies(self.jar)
elseif host == "m.qidian.com" then headers.Cookie = cookies(self.webjar) end
local pending, gen = true, self.generation
local job = Request.request({
url = url, method = "GET", headers = headers, allow_redirects = false,
timeout = require("http.timeout").net(1), cache_ttl = 0,
}, function(res, err)
pending = false
if self.cancelled or gen ~= self.generation then return end
self.job = nil
if not res or err then cb(nil, err and tostring(err) or _("请求失败")); return end
local status = tonumber(res.code)
if not status or status < 200 or status >= 400 then cb(nil, "HTTP " .. tostring(res.code)); return end
local set_cookies = Request.headerAll(res, "Set-Cookie")
if host == "ptlogin.yuewen.com" then CookieLogin.absorb(self.jar, set_cookies) end
CookieLogin.absorb(self.webjar, set_cookies, LOGIN_KEYS)
cb(res)
end)
if pending then self.job = job end
end
function Login:baseParams()
return {
appId = "13", areaId = "31", source = "", returnurl = "https://m.qidian.com/",
version = "", imei = "", qimei = "", target = "top", ticket = "1",
autotime = "14", jumpdm = "qidian", ajaxdm = "", auto = self.jar.al or "", sdkversion = "",
format = "json", method = "moonLogin",
}
end
function Login:_json(path, fields, cb)
local params = self:baseParams()
for key, value in pairs(fields) do params[key] = value end
self:_get(BASE .. path .. "?" .. Text.formEncode(params), function(res, err)
if not res then cb(nil, err); return end
local ok, wire = pcall(JSON.decode, res.body)
if not ok or type(wire) ~= "table" then cb(nil, _("起点登录响应无效")); return end
if tonumber(wire.code) ~= 0 then
cb(nil, wire.message or wire.msg or (_("登录失败") .. ":" .. tostring(wire.code))); return
end
if type(wire.data) ~= "table" then cb(nil, _("起点登录响应无效")); return end
cb(wire.data)
end)
end
function Login:beginAsync(cb)
self:_json("/userSdk/getvalidatecode", { force = 1 }, function(data, err)
if not data then cb(nil, err); return end
self.initialized = true
if type(data.imgSrc) == "string" and data.imgSrc ~= "" then self.challenge_key = data.sessionKey end
cb(data)
end)
end
function Login:imageAsync(url, cb)
local target = Text.absoluteUrl(BASE .. "/", url)
if not target then cb(nil, _("起点验证码响应无效")); return end
self:_get(target, function(res, err)
if not res then cb(nil, err); return end
local body = res.body
if type(body) ~= "string" or #body > 1024 * 1024 then cb(nil, _("起点验证码图片无效")); return end
local ext, mime = require("utils.image").ext(body)
if not ext then cb(nil, _("起点验证码图片无效")); return end
cb("data:" .. mime .. ";base64," .. Text.base64Encode(body))
end)
end
function Login:sendCodeAsync(country, phone, proof, cb)
self:_json("/userSdk/sendmsgnew", {
phoneIsAbroad = country == "+86" and 0 or 1, inputUserId = country .. phone,
sessionKey = self.challenge_key or "", type = 1, validateCode = proof or "", needRegister = 0,
}, function(data, err)
if not data then cb(nil, err); return end
local action = tonumber(data.nextAction)
if action == 0 then
if type(data.sessionKey) ~= "string" or data.sessionKey == "" then
cb(nil, _("起点短信会话缺失")); return
end
self.sms_key = data.sessionKey
self.challenge_key = nil
elseif action == 8 or action == 11 then
if type(data.sessionKey) ~= "string" or data.sessionKey == "" or type(data.imgSrc) ~= "string"
or data.imgSrc == "" then cb(nil, _("起点验证码响应无效")); return end
self.challenge_key = data.sessionKey
else
cb(nil, _("起点登录需要未支持的验证") .. ":" .. tostring(data.nextAction)); return
end
cb(data)
end)
end
function Login:_exchange(data, cb)
for name, key in pairs({ ywguid = "ywGuid", ywkey = "ywKey", ywopenid = "ywOpenId" }) do
local value = data[key]
if type(value) == "number" then self.webjar[name] = string.format("%.0f", value)
elseif type(value) == "string" then self.webjar[name] = value end
end
local url = data["302url"]
if not url and type(data.ticket) == "string" and data.ticket ~= "" then
url = "https://m.qidian.com/?" .. Text.formEncode({
ticket = data.ticket, ywguid = self.webjar.ywguid or "", ywOpenId = self.webjar.ywopenid or "",
})
end
if type(url) ~= "string" or url == "" then cb(nil, _("起点登录缺少会话兑换凭据")); return end
local function follow(target, hop)
if hop > 5 then cb(nil, _("起点登录跳转过多")); return end
self:_get(target, function(res, err)
if not res then cb(nil, err); return end
local status = tonumber(res.code)
local location = Request.header(res, "Location")
if status >= 300 then
local next_url = Text.absoluteUrl(target, location)
if not next_url then cb(nil, _("起点登录跳转地址无效")); return end
follow(next_url, hop + 1)
elseif target:match("^https://([^/?#]+)") ~= "m.qidian.com" or not self.webjar.ywguid
or not self.webjar.ywkey then
cb(nil, _("起点登录未获取到本站会话"))
else
-- 真 _csrfToken 由 loginCheck 合并书架页 Set-Cookie 后再落盘,这里不要造假。
cb(cookies(self.webjar))
end
end)
end
follow(url, 1)
end
function Login:verifyAsync(phone, code, cb)
if not self.sms_key then cb(nil, _("请先获取验证码")); return end
self:_json("/userSdk/phonecodelogin", {
inputUserId = phone, sessionKey = self.sms_key, validateCode = code,
}, function(data, err)
if not data then cb(nil, err); return end
if tonumber(data.nextAction) ~= 0 then cb(nil, _("起点登录需要未支持的验证")); return end
self:_exchange(data, cb)
end)
end
return Login
@@ -0,0 +1,233 @@
--[[--
起点中文网数据映射(纯函数):手机网页 pageContext JSON / 书架行 → 领域对象。
@module koplugin.book.moonsource_qidian.mapper
--]]
local JSON = require("json")
local Text = require("utils.text")
local Mapper = {}
local SOURCE_ID = "ext.qidian"
local COVER = "https://bookcover.yuewen.com/qdbimg/349573/%s/180"
--- 封面走阅文 CDN,书号即路径。实测是 JPEG,不强制 gzip。
---@param book_id string|number
---@return string
function Mapper.coverUrl(book_id)
return COVER:format(tostring(book_id))
end
--- 手机网页 SSR 的 pageContext → pageData;不是起点页面返回 nil。
---@param html string
---@return table|nil
function Mapper.pageData(html)
local raw = type(html) == "string"
and html:match('id="vite%-plugin%-ssr_pageContext" type="application/json">(.-)</script>')
if not raw then return nil end
local ok, wire = pcall(JSON.decode, raw)
if not ok or type(wire) ~= "table" then return nil end
local props = (wire.pageContext or wire).pageProps
local data = props and props.pageData
return type(data) == "table" and data or nil
end
--- 详情页 bookInfo → Book。
---@param info table
---@return Book
function Mapper.book(info)
local id = tostring(info.bookId)
local status = type(info.bookStatus) == "string" and info.bookStatus
or type(info.actionStatus) == "string" and info.actionStatus
or tonumber(info.actionStatus) == 1 and "连载"
or tonumber(info.actionStatus) == 2 and "完结"
or nil
local tags = type(info.tagName) == "string" and info.tagName ~= "" and info.tagName
or type(info.tags) == "string" and info.tags ~= "" and info.tags or nil
if tags then tags = (tags:gsub("[,%s;;|/]+", " · ")) end
return {
source_id = SOURCE_ID,
stable_id = id,
title = info.bookName,
authors = info.authorName,
category = info.chanName,
intro = info.desc and Text.stripHtml(info.desc),
cover = Mapper.coverUrl(id),
meta = {
words = tonumber(info.wordsCnt),
status = status,
tags = tags,
},
}
end
--- 搜索页 pageData.bookInfo.records → Book[]。作者名被站点截成「xx...」,不完整就留空等详情补。
---@param data table
---@return Book[]
function Mapper.search(data)
local out = {}
for _idx, row in ipairs((data.bookInfo or {}).records or {}) do
local id = tostring(row.bid)
local author = row.bAuth
out[#out + 1] = {
source_id = SOURCE_ID,
stable_id = id,
title = row.bName,
authors = type(author) == "string" and not author:find("%.%.%.$") and author or nil,
category = row.cat,
intro = row.desc and Text.stripHtml(row.desc),
cover = Mapper.coverUrl(id),
}
end
return out
end
--- 榜单页 pageData.records → Book[](行形状同搜索)。
---@param data table
---@return Book[]
function Mapper.rank(data)
return Mapper.search({ bookInfo = { records = data.records } })
end
--- 书架行 → Book。没有简介,封面按书号拼。
---@param row table
---@return Book
function Mapper.shelfBook(row)
local id = tostring(row.bid)
return {
source_id = SOURCE_ID,
stable_id = id,
title = row.bName,
authors = row.bAuth,
category = row.cateName,
cover = Mapper.coverUrl(id),
}
end
--- 书架行 → Book。有详情用详情,否则沿用本地完整行,都没有才退回书架行。
--- 分类口径见 source.category_setting:开 = 只用自定义分组,关 = 只用题材(cateName / chanName)。
---@param rows table[]
---@return Book[]
function Mapper.shelfList(rows)
local CategorySetting = require("source.category_setting")
local books = {}
for _idx, row in ipairs(rows) do
local book
if row.info then
book = Mapper.book(row.info)
elseif row.local_book then
book = row.local_book
if type(book.cover) ~= "string" or book.cover == "" then
book.cover = Mapper.coverUrl(row.bid or book.stable_id)
end
-- 沿用本地行时 category 可能是上次同步的分组名:先刷回书架题材,再按开关决定。
if type(row.cateName) == "string" and row.cateName ~= "" then
book.category = row.cateName
end
elseif row.bid then
book = Mapper.shelfBook(row)
end
if book then
book.category = CategorySetting.apply(SOURCE_ID, book.category, row._group_name)
book.category_authoritative = true
books[#books + 1] = book
end
end
return books
end
--- 目录 uT(东八区 `YYYY-MM-DD HH:MM:SS`)→ unix 秒。上传进度要这个数,日期字符串服务端直接 500。
---@param text string|nil
---@return integer|nil
function Mapper.chapterTime(text)
if type(text) ~= "string" then return nil end
local year, month, day, hour, minute, second = text:match("^(%d+)%-(%d+)%-(%d+) (%d+):(%d+):(%d+)$")
if not year then
year, month, day, hour, minute = text:match("^(%d+)%-(%d+)%-(%d+) (%d+):(%d+)$")
second = "0"
end
year, month, day = tonumber(year), tonumber(month), tonumber(day)
hour, minute, second = tonumber(hour), tonumber(minute), tonumber(second)
if not year or month < 1 or month > 12 or day < 1 or day > 31 then return nil end
-- Howard Hinnant days_from_civil,再减去东八区。
local y = year - (month <= 2 and 1 or 0)
local era = math.floor((y >= 0 and y or y - 399) / 400)
local yoe = y - era * 400
local doy = math.floor((153 * (month + (month > 2 and -3 or 9)) + 2) / 5) + day - 1
local doe = yoe * 365 + math.floor(yoe / 4) - math.floor(yoe / 100) + doy
local days = era * 146097 + doe - 719468
return days * 86400 + hour * 3600 + minute * 60 + second - 8 * 3600
end
--- 书架行里的阅读位置。没有 readCid 就是没读过。
---@param row table|nil
---@return { uid: string, title: string|nil }|nil
function Mapper.readChapter(row)
if type(row) ~= "table" then return nil end
local uid = row.readCid
if uid == nil or tostring(uid) == "" or tonumber(uid) == 0 then return nil end
local title = row.readCname
return { uid = tostring(uid), title = type(title) == "string" and title or nil }
end
--- 目录页 vs[].cs[] → 目录。卷名不是章;VIP 章(sS=0)也进目录,打开时再看是否已购买。
--- updated 是章节更新时间的 unix 秒,进度上传要带上,空字符串会把阅读状态写坏。
---@param data table|nil
---@return BookChapter[]
function Mapper.toc(data)
local volumes = data and data.vs
local toc = {}
for _idx, volume in ipairs(type(volumes) == "table" and volumes or {}) do
for _ch, row in ipairs(type(volume.cs) == "table" and volume.cs or {}) do
if row.id then
toc[#toc + 1] = {
idx = #toc + 1,
uid = tostring(row.id),
title = row.cN,
words = tonumber(row.cnt),
updated = Mapper.chapterTime(row.uT),
vip = tonumber(row.sS) == 0,
}
end
end
end
return toc
end
--- 未购买的 VIP 只有预览。免费章 isBuy 也是 0,锁章只看 vipStatus。
---@param info table|nil
---@return boolean
function Mapper.locked(info)
return type(info) == "table" and tonumber(info.vipStatus) == 1 and tonumber(info.isBuy) ~= 1
end
--- 已购 VIP 的正文是 Fock 密文(官方前端 fEnS=1)。
---@param info table|nil
---@return boolean
function Mapper.fockEncrypted(info)
return type(info) == "table" and (tonumber(info.fEnS) or 0) ~= 0
end
--- 已购 VIP 的正文还套了一层字体映射(官方前端 cES=2)。
--- TTF 画回真字,`<y class="sy-1">` 还要按 CSS 镜像;正文尾部另有一份诱饵副本。
---@param info table|nil
---@return boolean
function Mapper.fontProtected(info)
return type(info) == "table" and tonumber(info.cES) == 2
end
--- 章节 HTML → 纯文本。起点用 <p> 分段,且不保证闭合。
---@param html string|nil
---@return string|nil
function Mapper.chapterText(html)
if type(html) ~= "string" or html == "" then return nil end
local text = Text.xmlDecode((html
:gsub("<[Pp][^>]*>", "\n")
:gsub("</[Pp]>", "\n")
:gsub("<[Bb][Rr]%s*/?>", "\n")
:gsub("<[^>]*>", "")))
return Text.trim(text) ~= "" and text or nil
end
return Mapper
@@ -0,0 +1,131 @@
--[[--
起点手机号短信登录窗口。取消只终止本窗口的候选会话,不影响已保存账号。
@module moonsource_qidian.phone_login
--]]
local Text = require("utils.text")
local _ = require("l10n").get("moonsource_qidian")
---@class QidianPhoneLogin
---@field session QidianLogin
---@field on_cookie fun(cookie: string)
---@field dialog BookThemeInput
---@field verification QidianVerification|nil
---@field phone string|nil
---@field retry_at integer|nil
---@field agreed boolean|nil
---@field busy boolean|nil
---@field closed boolean|nil
local PhoneLogin = {}
PhoneLogin.__index = PhoneLogin
function PhoneLogin.new(on_cookie)
return setmetatable({ session = require("moonsource_qidian.login").new(), on_cookie = on_cookie }, PhoneLogin)
end
function PhoneLogin:cancel()
self.closed, self.busy = true, false
if self.verification then self.verification:cancel() end
self.session:cancel()
self.phone = nil
end
function PhoneLogin:toast(message)
require("ui.themes.widgets.toast"):new{ text = message, timeout = 3 }:show()
end
function PhoneLogin:available()
if self.closed then return false end
if self.busy then self:toast(_("正在处理,请稍候")); return false end
if not require("ui/network/manager"):isConnected() then
self:toast(_("网络不可用,请先连接 Wi-Fi")); return false
end
return true
end
function PhoneLogin:_send(country, phone, proof)
self.busy = true
self.session:sendCodeAsync(country, phone, proof, function(data, err) self:_sent(country, phone, data, err) end)
end
function PhoneLogin:_sent(country, phone, data, err)
if self.closed then return end
self.busy = false
if not data then self:toast(err or _("请求失败")); return end
if tonumber(data.nextAction) == 0 then
self.phone, self.retry_at = country .. phone, os.time() + 60
self:toast(_("验证码已发送")); return
end
self.busy = true
local verification = require("moonsource_qidian.verify").new(self.session, data, function(proof, done)
self.session:sendCodeAsync(country, phone, proof, done)
end, function(result, reason)
self.verification = nil
self:_sent(country, phone, result, reason)
end)
if not verification.done then self.verification = verification end
end
function PhoneLogin:send(country, phone)
if not self:available() then return end
country, phone = Text.trim(country), Text.trim(phone)
if not country:match("^%+%d+$") or #country > 5 or not phone:match("^%d+$") or #phone < 6 or #phone > 15 then
self:toast(_("请输入有效的手机号和国际区号")); return
end
if self.retry_at and os.time() < self.retry_at then self:toast(_("请稍后再获取验证码")); return end
if not self.agreed then
require("ui.themes.widgets.confirm"):new{
text = _("获取验证码前请阅读并同意阅文用户服务协议和隐私政策")
.. "\nhttps://passport.yuewen.com/terms_of_service.html"
.. "\nhttps://passport.yuewen.com/privacy_policy.html",
ok_text = _("同意并获取验证码"),
ok_callback = function() self.agreed = true; self:send(country, phone) end,
}:show()
return
end
self:toast(_("正在获取验证码…"))
if self.session.initialized then self:_send(country, phone); return end
self.busy = true
self.session:beginAsync(function(data, err)
if self.closed then return end
self.busy = false
if not data then self:toast(err or _("登录失败")); return end
self:_send(country, phone)
end)
end
function PhoneLogin:verify(country, phone, code)
if not self:available() then return end
country, phone, code = Text.trim(country), Text.trim(phone), Text.trim(code)
if country .. phone ~= self.phone or not code:match("^%d+$") then
self:toast(_("请先获取该手机号的验证码,再填写验证码登录")); return
end
self.busy = true
self:toast(_("正在登录…"))
self.session:verifyAsync(phone, code, function(cookie, err)
if self.closed then return end
self.busy = false
if not cookie then self:toast(err or _("登录失败")); return end
self:cancel()
self.dialog:close()
self.on_cookie(cookie)
end)
end
function PhoneLogin:start()
self.dialog = require("ui.themes.widgets.input"):new{
title = _("起点手机号验证码登录"),
fields = {
{ label = _("国际区号"), text = "+86", hint = "+86" },
{ label = _("手机号"), input_type = "number" },
{ label = _("验证码"), input_type = "number" },
},
keep_open = true, ok_text = _("登录"),
actions = { { text = _("获取验证码"), callback = function(country, phone) self:send(country, phone) end } },
callback = function(country, phone, code) self:verify(country, phone, code) end,
cancel_callback = function() self:cancel() end,
}
self.dialog:show()
end
return PhoneLogin
@@ -0,0 +1,151 @@
--[[--
起点段评:本章每段评论数、某段的评论页、把段落定位到章节 HTML。
走手机站接口(m.qidian.com/webcommon/chapterreview/*),匿名可读,见 `Client.reviewSummaryAsync`:
- reviewsummary4m:本章每段评论数;paragraphId 从 1 数,对应章节正文第 n 个 <p>(起点正文每个 <p> 都非空),-1 是章末总评。
- reviewlist4m:某段评论,page 从 1 起。
章节 HTML 的段落是非空行逐个包成 <p>(Text.textToBody),所以第 n 个 <p> 就是 paragraphId = n。
@module koplugin.book.moonsource_qidian.reviews
--]]
local Client = require("moonsource_qidian.client")
local ReviewLocate = require("book.review_locate")
local Text = require("utils.text")
local _ = require("l10n").get("moonsource_qidian")
local T = require("ffi/util").template
local Reviews = {}
--- 整书帖子预览,与段评/章评分开;官网只给前三条,不虚构后续页。
---@param data table
---@return table|nil, string|nil
function Reviews.bookPage(data)
local total = tonumber(data.bookCirclePostCount)
if type(data.bookCirclePostList) ~= "table" or not total then
return nil, _("起点书友圈响应无效")
end
local items = {}
for _idx, row in ipairs(data.bookCirclePostList) do
if type(row) ~= "table" or type(row.title) ~= "string" or type(row.circleReviewDesc) ~= "string"
or (row.userName ~= nil and type(row.userName) ~= "string") then
return nil, _("起点书友圈响应无效")
end
items[#items + 1] = { author = row.userName or "",
text = Text.stripHtml(row.title) .. "\n" .. Text.stripHtml(row.circleReviewDesc) }
end
return { items = items, total = total, title = T(_("书友圈预览(%1/%2)"), #items, total) }
end
---@class QidianReviewHotspot
---@field range string 段落序号(第几个 <p>)
---@field text string
---@field total integer 本段评论数
---- 统计回包 → 有评论的段落与章末(-1);调用方按粒度分开定位。
---@param data table
---@return QidianReviewHotspot[]
function Reviews.hotspots(data)
local out = {}
for _idx, row in ipairs(data.list or {}) do
local pid, total = tonumber(row.paragraphId), tonumber(row.textCount) or 0
if pid and (pid > 0 or pid == -1) and total > 0 then
out[#out + 1] = { range = tostring(pid), text = "", total = total }
end
end
table.sort(out, function(a, b) return tonumber(a.range) < tonumber(b.range) end)
return out
end
--- 表情是「[fn=47]」这样的占位码,没有图可画,去掉。
---@param row table
---@return WechatReview
local function reviewItem(row)
local body = tostring(row.content or ""):gsub("%[fn=%d+%]", "")
local images = {}
if tonumber(row.hasImage) == 1 and type(row.imagePre) == "string" and row.imagePre ~= "" then
images[1] = { url = row.imagePre, width = 0, height = 0 }
end
return {
id = tostring(row.reviewId or ""),
author = tostring(row.nickName or ""),
content = Text.trim(body),
likes = tonumber(row.likeCount) or 0,
replies = tonumber(row.rootReviewReplyCount) or 0,
images = images,
time = tonumber(row.createTimestamp) or math.floor((tonumber(row.createTime) or 0) / 1000),
reply_to = row.quoteNickName,
}
end
---@param row table
---@return WechatReview
function Reviews.item(row)
local item = reviewItem(row)
if type(row.replyList) == "table" then
local preview = {}
for _idx, reply in ipairs(row.replyList) do
if type(reply) == "table" and tonumber(reply.status) ~= 0 then
preview[#preview + 1] = reviewItem(reply)
end
end
if #preview > 0 then
item.reply_preview = preview
item.replies = math.max(item.replies, #preview)
end
end
return item
end
--- 评论回包 → 一页。max_idx 存「已取到第几页」(首页请求带 0),避免依赖每页条数。
---@param data table
---@param page integer
---@return WechatReviewPage|nil, string|nil
function Reviews.page(data, page)
if type(data.list) ~= "table" then return nil, _("起点段评响应缺少评论列表") end
local items = {}
for _idx, row in ipairs(data.list) do
if type(row) == "table" and tonumber(row.status) ~= 0 then items[#items + 1] = Reviews.item(row) end
end
local total = tonumber(data.total) or #items
return { items = items, total = total, max_idx = page,
more = #data.list > 0 and data.isEnd ~= true and tonumber(data.isEnd) ~= 1
and tonumber(data.size) ~= 0 and (page > 1 or #data.list < total) }
end
--- 本章有评论的段落;这本书没开段评(enableReview ≠ 1)当没有。
---@param book_id string
---@param chapter_id string
---@param cb fun(hotspots: QidianReviewHotspot[]|nil, err: string|nil)
---@return HttpJob
function Reviews.hotspotsAsync(book_id, chapter_id, cb)
return Client.reviewSummaryAsync(book_id, chapter_id, function(data, err)
if not data then cb(nil, err); return end
cb(tonumber(data.enableReview) == 1 and Reviews.hotspots(data) or {})
end)
end
--- 某段的一页评论;max_idx 是已取页数(首页 0)。
---@param book_id string
---@param chapter_id string
---@param paragraph_id integer
---@param max_idx integer
---@param cb fun(page: WechatReviewPage|nil, err: string|nil)
---@return HttpJob
function Reviews.pageAsync(book_id, chapter_id, paragraph_id, max_idx, cb)
local page = max_idx + 1
return Client.reviewListAsync(book_id, chapter_id, paragraph_id, page, function(data, err)
if not data then cb(nil, err); return end
cb(Reviews.page(data, page))
end)
end
--- 把有评论的段落定位到章节 HTML。
---@param hotspots QidianReviewHotspot[]
---@param html string
---@return table[]
function Reviews.locate(hotspots, html)
return ReviewLocate.locate(ReviewLocate.paragraphs(html), hotspots, html)
end
return Reviews
@@ -0,0 +1,108 @@
--[[--
起点源设置:登录。
优先在设备上展示阅文二维码,用起点或 QQ阅读 App 扫码;保留浏览器扩展与手动 Cookie 导入。
拿到登录态先拉书架页校验,通过才保存。Cookie 里的 _csrfToken 与请求参数同值。
@module koplugin.book.moonsource_qidian.setting
--]]
local _ = require("l10n").get("moonsource_qidian")
local CookieLogin = require("source.cookie_login")
local SOURCE_ID = "ext.qidian"
local Setting = {}
---@return boolean
local function loggedIn()
return require("moonsource_qidian.client").cookie() ~= nil
end
--- 同账号续期不动同步标记;换号保留本地记录并准备上行。
local function commit(cookie, account, cb, current)
if not account or type(account.id) ~= "string" or not account.id:match("^%d+$") then
cb(false, _("起点账号标识缺失")); return
end
return CookieLogin.commitAccount(SOURCE_ID, cookie, account.id, cb, current)
end
---@type CookieLoginSpec
local SPEC = {
id = SOURCE_ID,
title = _("起点账号"),
cookie_title = _("起点登录 Cookie"),
cookie_hint = _("按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"),
logout_text = _("确定退出起点账号?"),
loggedIn = loggedIn,
checkAsync = require("moonsource_qidian.client").loginCheckAsync,
commit = commit,
clear = function(cfg) cfg.cookie, cfg.account_id = nil, nil end,
}
---@return string, boolean
function Setting.rowStatus()
local on = loggedIn()
return on and _("已登录") or _("未登录 · 点此登录"), on
end
Setting.parseCookie = CookieLogin.parse
--- 浏览器扩展交来的 payload.cookies → Cookie 请求头;只收起点站点的 Cookie。
---@param payload table
---@return string
function Setting.fromPayload(payload)
return CookieLogin.fromPayload(payload, "qidian.com")
end
--- 浏览器扩展登录(features/cookie)。
Setting.browser = {
domain = "m.qidian.com",
scope = "cookie",
-- 扩展要求 login/check 与 domain 同主机。未登录时书架页自己 302 到 passport,登录完回到本站再采集。
login = "https://m.qidian.com/bookshelf/my/",
check = "https://m.qidian.com/bookshelf/my/",
icon = "https://imgservices-1252317822.image.myqcloud.com/coco/s03102023/b7b10602.w663ve.ico",
isAuthorized = function() return CookieLogin.authorized(SPEC) end,
apply = function(payload, cb) return CookieLogin.save(SPEC, Setting.fromPayload(payload), cb) end,
}
local function startQR()
require("ui/network/manager"):runWhenConnected(function()
require("moonsource_qidian.yuewen_qr"):new({
app_id = "13", area_id = "31", return_url = "https://m.qidian.com/",
ticket = "1",
referer = "https://passport.qidian.com/mobile/login",
title = _("起点扫码登录"), caption = _("用 QQ阅读或起点 App 扫一扫"),
}, function(cookie)
-- 不要造假 _csrfToken:loginCheck 会把书架页 Set-Cookie(真 csrf 等)合并后再保存。
CookieLogin.verify(SPEC, cookie)
end):start()
end)
end
---@return table[]
function Setting.rows(plugin)
local rows = {
CookieLogin.accountRow(SPEC, { callback = startQR, off_text = _("未登录 · 点此扫码") }),
function(iw)
return require("ui.themes.widgets.row").widget{
width = iw, chevron = true, kind = "nav", icon = "sms",
title = _("手机号验证码登录"),
callback = function()
require("moonsource_qidian.phone_login").new(function(cookie) CookieLogin.verify(SPEC, cookie) end):start()
end,
}
end,
CookieLogin.browserRow(),
CookieLogin.pasteRow(SPEC),
require("source.review_setting").row(SOURCE_ID, plugin),
require("source.category_setting").row(SOURCE_ID, plugin),
}
if loggedIn() then rows[#rows + 1] = CookieLogin.logoutRow(SPEC) end
return rows
end
--- 登录失效提示的「重新登录」直达入口(desktop.sync.promptLogin)。
Setting.login = startQR
return Setting
@@ -0,0 +1,393 @@
--[[--
起点中文网数据源。
详情 / 目录 / 章节走手机站页面(client.lua)。扫码、短信与浏览器 Cookie 经统一校验保存(setting.lua);
登录后书架双向同步(source.shelf):拉取、本地加入上行、本地删除上行。
进度只到章:开书从书架行的 readCid 拉,关书经 updReadStatus 推。笔记与统计仅本地记录。
VIP 章未购买时打开一页临时提示,目录标注已购 / 未购(打开过才知道)。
@module moonsource_qidian
--]]
local Browse = require("source.browse")
local Client = require("moonsource_qidian.client")
local Mapper = require("moonsource_qidian.mapper")
local ReviewCache = require("book.review_cache")
local Shelf = require("source.shelf")
local SourceBase = require("source.base")
local Toc = require("source.toc")
local _ = require("l10n").get("moonsource_qidian")
local Qidian = {}
-- 章节页不小,预取与整本缓存逐章间隔请求。
local FETCH_INTERVAL = 1
---@return BookSourceMeta
function Qidian.meta()
return require("moonsource_qidian.loadmeta")()
end
---@class QidianSource : SourceBase
---@field category_info table[]|nil 官网男频分类目录
local Source = setmetatable({ shelf_add = true }, { __index = SourceBase })
Source.__index = Source
---@return QidianSource
function Qidian.new()
local meta = Qidian.meta()
return setmetatable({ id = meta.id, name = meta.name, type = meta.type }, Source)
end
---@return boolean
function Source:configured()
return Client.cookie() ~= nil
end
--- 书架行没有简介。本地没有简介或封面的书逐本补拉详情,拉不到就退回书架行。
---@param rows table[]
---@param cb fun(rows: table[])
---@return { cancel: fun() }
local function fillDetails(rows, cb)
local BookDB = require("book.books_db")
local cancelled, job, index = false, nil, 0
local function nextRow()
if cancelled then return end
index = index + 1
local row = rows[index]
if not row then cb(rows); return end
row.local_book = BookDB.get(Qidian.meta().id, tostring(row.bid))
local book = row.local_book
local intro = book and book.intro
local cover = book and book.cover
if intro and intro ~= "" and cover and cover ~= "" then nextRow(); return end
job = Client.detailAsync(row.bid, function(info, err)
if cancelled then return end
if info then
row.info = info
else
require("utils.log").warn("book qidian detail failed", row.bid, err)
end
nextRow()
end)
end
nextRow()
return { cancel = function()
cancelled = true
if job then job.cancel() end
end }
end
--- 书架远端:Shelf.syncAsync 要的三个冒号方法。
local Remote = {}
function Remote:shelfSyncAsync(cb)
local cancelled, job, fill = false, nil, nil
job = Client.shelfAsync(Client.cookie(), function(rows, err)
if cancelled then return end
if not rows then cb(nil, err); return end
fill = fillDetails(rows, cb)
end)
return { cancel = function()
cancelled = true
job.cancel()
if fill then fill.cancel() end
end }
end
function Remote:addToShelfAsync(stable_id, cb)
return Client.addAsync(stable_id, cb)
end
function Remote:removeFromShelfAsync(stable_id, cb)
return Client.removeAsync(stable_id, cb)
end
function Source:syncBooksAsync(opts, cb)
if not self:configured() then return SourceBase.skipped(cb, "qidian not logged in") end
return Shelf.syncAsync(self.id, Remote, Mapper.shelfList, opts, cb)
end
--- 书架行的 readCid 才是用户看到的进度。getReadStatus 在查询章等于已读章时会把章号省掉。
function Source:getProgressAsync(identity, cb)
if not self:configured() then return SourceBase.defer(cb, nil, _("未登录起点")) end
local cancelled, job = false, nil
job = Client.shelfAsync(Client.cookie(), function(rows, err)
if cancelled then return end
if not rows then cb(nil, err); return end
local row
for _idx, item in ipairs(rows) do
if tostring(item.bid) == tostring(identity.stable_id) then row = item; break end
end
local read = Mapper.readChapter(row)
if not read then cb(nil, nil, { empty = true }); return end
job = self:loadTocAsync(identity, function(toc, reason)
if cancelled then return end
if not toc or #toc == 0 then cb(nil, reason or _("起点目录为空")); return end
local idx = Toc.index(self.id, identity.stable_id, read.uid)
if not idx then cb(nil, nil, { empty = true }); return end
cb({
chapter_idx = idx,
chapter_title = read.title,
fraction = (idx - 1) / #toc,
extra = { chapter_uid = read.uid, chapter_idx = idx },
})
end)
end)
return { cancel = function()
cancelled = true
if job and job.cancel then job.cancel() end
end }
end
function Source:putProgressAsync(identity, pos, cb)
if not self:configured() then return SourceBase.defer(cb, nil, _("未登录起点")) end
local cancelled, job = false, nil
local function send(chapter)
if not chapter.updated then
cb(nil, _("起点章节时间缺失"))
return
end
job = Client.updateReadAsync(identity.stable_id, chapter.uid, chapter.title, chapter.vip, chapter.updated,
function(ok, err)
if cancelled then return end
cb(ok and true or nil, err)
end)
end
job = self:loadTocAsync(identity, function(toc, err)
if cancelled then return end
if not toc then cb(nil, err); return end
local idx = tonumber(pos.chapter_idx) or tonumber(identity.chapter_idx)
local chapter = idx and toc[idx]
if not chapter or not chapter.uid then
cb(nil, _("缺少起点章节位置"))
return
end
if chapter.updated then send(chapter); return end
-- 旧目录缓存没有章节更新时间。不带时间上传会把阅读状态写坏,先补拉目录。
job = Client.catalogAsync(identity.stable_id, function(data, reason)
if cancelled then return end
local fresh = data and Mapper.toc(data)
if fresh and #fresh > 0 then Toc.put(self.id, identity.stable_id, fresh) end
local hit
for _ch, item in ipairs(fresh or {}) do
if item.uid == chapter.uid then hit = item; break end
end
if not hit then cb(nil, reason or _("缺少起点章节位置")); return end
if not hit.updated then cb(nil, _("起点章节时间缺失")); return end
send(hit)
end)
end)
return { cancel = function()
cancelled = true
if job and job.cancel then job.cancel() end
end }
end
--- 书城搜索:回包形状同 listStoreAsync。
---@param keyword string
---@param cb fun(res: { data: Book[] }|nil, err: string|nil)
---@return { cancel: fun() }|nil
function Source:searchAsync(keyword, cb)
return Browse.pages(function(page, done)
return Client.searchAsync(keyword, function(data, err)
if not data then done(nil, err); return end
local info = data.bookInfo
done(Mapper.search(data), nil, info.isLast ~= 1 and info.isLast ~= true)
end, page)
end, 200, {}, cb)
end
local RANKS = {
{ key = "yuepiao", title = _("月票榜") },
{ key = "hotsales", title = _("畅销榜") },
{ key = "readindex", title = _("阅读指数榜") },
{ key = "newfans", title = _("新人榜") },
{ key = "update", title = _("更新榜") },
{ key = "newbook", title = _("新书榜") },
{ key = "newauthor", title = _("新作者榜") },
}
local CATS = {
{ id = "-1", title = _("全站") }, { id = "21", title = _("玄幻") }, { id = "1", title = _("奇幻") },
{ id = "2", title = _("武侠") }, { id = "22", title = _("仙侠") }, { id = "4", title = _("都市") },
{ id = "15", title = _("现实") }, { id = "6", title = _("军事") }, { id = "5", title = _("历史") },
{ id = "7", title = _("游戏") }, { id = "8", title = _("体育") }, { id = "9", title = _("科幻") },
{ id = "10", title = _("悬疑灵异") }, { id = "20109", title = _("诸天无限") }, { id = "12", title = _("轻小说") },
}
--- 默认分类书库;兼容「榜单键:分类号」旧节点,分类和榜单均聚合后续页。
---@param opts { node?: string, limit?: integer }
---@param cb fun(res: { data: Book[], groups: StoreChipGroup[] }|nil, err: string|nil)
---@return { cancel: fun() }
function Source:browseAsync(opts, cb)
if not opts.node or opts.node:sub(1, 9) == "category?" then
return require("moonsource_qidian.browse").run(self, opts, cb)
end
local key, cat = (opts.node or RANKS[1].key .. ":-1"):match("^(%w+):(-?%d+)$")
if not key then return SourceBase.defer(cb, nil, _("起点分类条件无效")) end
local ranks, cats = {}, {}
for _idx, rank in ipairs(RANKS) do ranks[#ranks + 1] = { id = rank.key .. ":" .. cat, title = rank.title } end
for _idx, row in ipairs(CATS) do cats[#cats + 1] = { id = key .. ":" .. row.id, title = row.title } end
local node = key .. ":" .. cat
table.insert(ranks, 1, { id = "category?catId=21&gender=male", title = _("分类书库") })
local groups = { Browse.group(ranks, node), Browse.group(cats, node) }
return Browse.pages(function(page, done)
return Client.rankPageAsync(key, cat, page, function(data, err)
if not data then done(nil, err); return end
done(Mapper.rank(data), nil, data.isLast ~= 1 and data.isLast ~= true)
end)
end, opts.limit or 60, groups, cb)
end
function Source:getDetailAsync(identity, cb)
return SourceBase.defer(cb, identity.book or require("book.books_db").get(self.id, identity.stable_id))
end
---@param identity BookIdentity
---@param cb fun(page: table|nil, err: string|nil)
---@return HttpJob
function Source:bookReviewsAsync(identity, cb)
if not require("ui/network/manager"):isConnected() then
return SourceBase.defer(cb, nil, _("网络不可用,请先连接 Wi-Fi"))
end
return Client.bookCircleAsync(identity.stable_id, function(data, err)
if not data then cb(nil, err); return end
cb(require("moonsource_qidian.reviews").bookPage(data))
end)
end
--- 强制拉目录并写回;失败由调用方继续用旧缓存。
---@param identity BookIdentity
---@param cb fun(toc: BookChapter[]|nil, err: string|nil)
---@return { cancel: fun() }
local function fetchTocAsync(self, identity, cb)
local cancelled, job = false, nil
job = Client.catalogAsync(identity.stable_id, function(data, err)
if cancelled then return end
local toc = data and Mapper.toc(data)
if not toc then cb(nil, err); return end
if #toc == 0 then cb(nil, _("起点目录为空")); return end
if not Toc.put(self.id, identity.stable_id, toc) then cb(nil, _("章节目录保存失败")); return end
cb(toc)
end)
return { cancel = function()
cancelled = true
job.cancel()
end }
end
---@param identity BookIdentity
---@param cb fun(toc: BookChapter[]|nil, err: string|nil)
---@param force boolean|nil 真=跳过缓存强制拉
---@return { cancel: fun() }
function Source:loadTocAsync(identity, cb, force)
if not force then
local cached = Toc.read(self.id, identity.stable_id)
if cached and #cached > 0 then
return SourceBase.defer(cb, cached)
end
end
return fetchTocAsync(self, identity, cb)
end
Source.refreshTocAsync = fetchTocAsync
function Source:openBookAsync(identity, opts, cb)
local Chapter = require("source.chapter")
local open = opts and opts.chapter_idx and Chapter.openAsync or Chapter.openWithUi
local locate = require("book.review_locate")
local reviews = self:paragraphReviewsEnabled()
return open(self, identity, identity.book, opts, {
loadToc = function(ref, done) return self:loadTocAsync(ref, done) end,
fetchContent = Chapter.vipFetcher(self, Client.contentAsync, true, reviews and locate.prepareChapterEnd or nil),
reuse = reviews and locate.reuseChapterEnd or nil,
}, cb)
end
function Source:prefetchChaptersAsync(identity, toc, from_idx, count, cb)
local Chapter = require("source.chapter")
local locate = require("book.review_locate")
local reviews = self:paragraphReviewsEnabled()
return Chapter.prefetchAsync(identity, identity.book, toc, from_idx, count, {
fetchContent = Chapter.vipFetcher(self, Client.contentAsync, false, reviews and locate.prepareChapterEnd or nil),
reuse = reviews and locate.reuseChapterEnd or nil,
interval_seconds = FETCH_INTERVAL,
}, cb)
end
function Source:cacheAllChaptersAsync(identity, on_progress, cb, range)
local Chapter = require("source.chapter")
local prepare = self:paragraphReviewsEnabled() and require("book.review_locate").prepareChapterEnd or nil
return Chapter.cacheAllAsync(self, identity, Chapter.vipFetcher(self, Client.contentAsync, false, prepare), on_progress, cb,
FETCH_INTERVAL, range)
end
--- 阅读页是否显示他人段评(设置页开关,默认关)。
---@return boolean
function Source:paragraphReviewsEnabled()
return require("source.review_setting").enabled(self.id)
end
--- 本章有评论的段落(未定位)。
---@param identity BookIdentity
---@param cb fun(hotspots: QidianReviewHotspot[]|nil, err: string|nil)
---@return { cancel: fun() }
local function hotspotsAsync(self, identity, cb)
local withUid = require("source.with_chapter_uid")
return ReviewCache.hotspotsAsync(identity, function(done)
return withUid.run(self, identity, _("缺少起点章节位置"), function(uid, finish)
return require("moonsource_qidian.reviews").hotspotsAsync(identity.stable_id, uid, finish)
end, done)
end, cb)
end
function Source:paragraphHotspotsAsync(identity, cb)
return hotspotsAsync(self, identity, function(list, err)
if not list then cb(nil, err); return end
local paragraphs = {}
for _idx, spot in ipairs(list) do
if tonumber(spot.range) > 0 then paragraphs[#paragraphs + 1] = spot end
end
cb(paragraphs)
end)
end
function Source:chapterReviewHotspotsAsync(identity, cb)
return hotspotsAsync(self, identity, function(list, err)
if not list then cb(nil, err); return end
local ending = {}
for _idx, spot in ipairs(list) do
if spot.range == "-1" then
ending[#ending + 1] = { range = spot.range, text = _("本章讨论"), total = spot.total,
badge = tostring(spot.total), heading = _("章节评论"),
anchor = require("book.review_locate").CHAPTER_ANCHOR }
end
end
cb(ending)
end)
end
--- 段落按段序定位到章节 HTML(子进程里跑,不碰实例状态)。
---@param hotspots QidianReviewHotspot[]
---@param html string
---@return table[]
function Source:locateHotspots(hotspots, html)
return require("moonsource_qidian.reviews").locate(hotspots, html)
end
--- 某段的一页评论;range 是段落序号,max_idx 是已取页数(首页 0)。
---@param identity BookIdentity
---@param range string
---@param max_idx integer
---@param cb fun(page: WechatReviewPage|nil, err: string|nil)
---@return { cancel: fun() }
function Source:paragraphReviewPageAsync(identity, range, max_idx, cb)
local withUid = require("source.with_chapter_uid")
return ReviewCache.pageAsync(identity, range, max_idx, function(done)
return withUid.run(self, identity, _("缺少起点章节位置"), function(uid, finish)
return require("moonsource_qidian.reviews").pageAsync(identity.stable_id, uid, tonumber(range), max_idx, finish)
end, done)
end, cb)
end
return Qidian
@@ -0,0 +1,144 @@
--[[--
起点图形 / 腾讯验证码桥。浏览器只提交验证码凭据,匿名会话、手机号、短信码留在设备。
@module moonsource_qidian.verify
--]]
local Ext = require("utils.extension")
local _ = require("l10n").get("moonsource_qidian")
---@class QidianVerification
---@field session QidianLogin
---@field challenge table
---@field submit fun(proof: string, cb: fun(data: table|nil, err: string|nil))
---@field callback fun(data: table|nil, err: string|nil)
---@field ticket string
---@field expires integer
---@field timeout function
---@field dialog BookThemeQR|nil
---@field done boolean|nil
---@field pending boolean|nil
local Verification = {}
Verification.__index = Verification
local sessions = {}
function Verification:finish(result, err)
if self.done then return end
self.done = true
sessions[self.ticket] = nil
require("ui/uimanager"):unschedule(self.timeout)
local dialog = self.dialog
self.dialog = nil
if dialog then dialog:close() end
self.callback(result, err)
end
function Verification:cancel()
if self.done then return end
self.session:interrupt()
self:finish(nil, _("验证已取消"))
end
function Verification.new(session, challenge, submit, cb)
local self = setmetatable({
session = session, challenge = challenge, submit = submit, callback = cb,
ticket = require("utils.random").hex(24), expires = os.time() + 300,
}, Verification)
self.timeout = require("ui.guard").wrap("qidian verification timeout", function()
self.session:interrupt()
self:finish(nil, _("验证已过期,请重新发起验证"))
end)
sessions[self.ticket] = self
require("ui/uimanager"):scheduleIn(300, self.timeout)
self.dialog = Ext.call("web.open_page", "/qidian_verify.html#" .. self.ticket,
_("起点安全验证"), _("用同一 Wi-Fi 下的手机扫码完成安全验证;手机号、密码和短信码只在设备填写。"), {
close_callback = function() self:cancel() end,
})
if not self.dialog then self:finish(nil, _("无法打开远程验证,请先连接 Wi-Fi 并启用远程管理功能")) end
return self
end
local function handle(method, action, params, cb)
local function reply(status, body) cb(status, body, { "Cache-Control: no-store" }) end
if method ~= "POST" then reply(405, { error = "Method Not Allowed" }); return end
local self = type(params.ticket) == "string" and sessions[params.ticket]
if not self or os.time() >= self.expires then
reply(403, { error = _("验证已过期,请重新发起验证") }); return
end
if self.pending then reply(409, { error = _("正在提交验证…") }); return end
if action == "config" or action == "refresh" then
local function config(challenge, err)
if self.done or os.time() >= self.expires then reply(403, { error = _("验证已过期,请重新发起验证") }); return end
if not challenge then reply(400, { error = err }); return end
local mode = tonumber(challenge.nextAction) == 11 and "tencent" or "image"
local function ready(image, reason)
self.pending = false
if self.done then reply(403, { error = _("验证已取消") }); return end
if mode == "image" and not image then reply(400, { error = reason }); return end
reply(200, {
mode = mode, image = image,
appid = challenge.imgSrc:match("[?&]aid=(%d+)") or "1600000770",
title = _("起点安全验证"), instruction = _("请完成下方安全验证"),
pending = _("正在提交验证…"), success = _("验证已提交,请回到设备查看结果。"),
failure = _("验证失败,请重新验证"), retry = _("刷新验证码"), submit = _("提交"),
})
end
if mode == "tencent" then
if not challenge.imgSrc:find("TCaptcha.js", 1, true) then
self.pending = false
reply(400, { error = _("起点登录需要未支持的验证") }); return
end
ready(nil)
else
self.pending = true
self.session:imageAsync(challenge.imgSrc, ready)
end
end
if action == "refresh" then
self.pending = true
self.session:beginAsync(function(data, err)
self.pending = false
if not data or type(data.imgSrc) ~= "string" or data.imgSrc == "" then
config(nil, err or _("起点验证码刷新失败")); return
end
data.nextAction = data.imgSrc:find("TCaptcha.js", 1, true) and 11 or 8
self.challenge = data
config(data)
end)
else config(self.challenge) end
return
end
if action ~= "verify" then reply(404, { error = "Not Found" }); return end
local proof
if tonumber(self.challenge.nextAction) == 11 then
if type(params.captcha_ticket) ~= "string" or params.captcha_ticket == "" or #params.captcha_ticket > 4096
or params.captcha_ticket:match("^trerror_") or type(params.randstr) ~= "string"
or params.randstr == "" or #params.randstr > 256 then
reply(400, { error = _("验证凭据无效") }); return
end
proof = params.randstr .. ";" .. params.captcha_ticket
else
if type(params.code) ~= "string" or params.code == "" or #params.code > 32 then
reply(400, { error = _("请输入验证码") }); return
end
proof = params.code
end
self.pending = true
self.submit(proof, function(data, err)
if self.done then reply(403, { error = _("验证已取消") }); return end
if os.time() >= self.expires then
self:cancel()
reply(403, { error = _("验证已过期,请重新发起验证") }); return
end
if data and tonumber(data.nextAction) == 0 then reply(200, { ok = true })
else reply(400, { error = err or _("验证失败,请重新验证") }) end
self:finish(data, err)
end)
end
Ext.add("web.routes", {
name = "qidian_verify", dir = debug.getinfo(1, "S").source:sub(2):match("(.*/)") .. "web",
assets = { "qidian_verify.html", "qidian_verify.js" },
public = { config = true, refresh = 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:10vh auto;padding:24px}
.panel{padding:24px}#captcha{min-height:180px;margin:24px 0}
#image{max-width:100%}#code{width:100%;margin:12px 0}
#status{overflow-wrap:anywhere;white-space:pre-line}
</style>
</head>
<body>
<main><section class="panel">
<h1 id="title">月读</h1><p id="instruction"></p>
<div id="captcha"></div>
<form id="image-form" hidden><img id="image" alt=""><input id="code" autocomplete="off"><button id="submit"></button></form>
<p id="status" role="status" aria-live="polite"></p><button id="retry" type="button"></button>
</section></main>
<script src="/qidian_verify.js"></script>
</body>
</html>
@@ -0,0 +1,91 @@
(async function () {
'use strict';
const ticket = location.hash.slice(1);
const status = document.getElementById('status');
const retry = document.getElementById('retry');
let messages, captcha, loading = false, submitting = false, done = false;
async function request(action, fields = {}) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 90000);
try {
const response = await fetch('/api/qidian_verify/' + action, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ...fields, ticket }), signal: controller.signal,
});
const result = await response.json();
if (!response.ok) throw new Error(result.error || response.statusText);
return result;
} finally { clearTimeout(timer); }
}
async function submit(fields) {
if (submitting || done) return;
submitting = true;
status.textContent = messages.pending;
try {
await request('verify', fields);
done = true;
status.textContent = messages.success;
document.getElementById('captcha').hidden = true;
document.getElementById('image-form').hidden = true;
retry.hidden = true;
} catch (error) { status.textContent = error.message; }
finally { submitting = false; }
}
function captchaResult(result) {
if (!result || result.ret !== 0 || result.errorCode || typeof result.ticket !== 'string'
|| !result.ticket || result.ticket.startsWith('trerror_') || typeof result.randstr !== 'string'
|| !result.randstr) {
status.textContent = messages.failure;
return;
}
return submit({ captcha_ticket: result.ticket, randstr: result.randstr });
}
function loadScript() {
if (typeof window.TencentCaptcha === 'function') return Promise.resolve();
return new Promise((resolve, reject) => {
const script = document.createElement('script');
const timer = setTimeout(() => finish(false), 20000);
function finish(ok) {
clearTimeout(timer);
script.onload = script.onerror = null;
if (ok) resolve();
else { script.remove(); reject(new Error(messages.failure)); }
}
script.src = 'https://turing.captcha.qcloud.com/TCaptcha.js';
script.onload = () => finish(typeof window.TencentCaptcha === 'function');
script.onerror = () => finish(false);
document.head.appendChild(script);
});
}
async function load(action) {
if (loading || submitting || done) return;
loading = true;
try {
messages = await request(action);
document.title = document.getElementById('title').textContent = messages.title;
document.getElementById('instruction').textContent = messages.instruction;
retry.textContent = messages.retry;
document.getElementById('submit').textContent = messages.submit;
status.textContent = '';
if (captcha) { captcha.destroy(); captcha = null; }
const container = document.getElementById('captcha');
container.innerHTML = '';
container.hidden = messages.mode !== 'tencent';
document.getElementById('image-form').hidden = messages.mode !== 'image';
document.getElementById('code').value = '';
if (messages.mode === 'image') document.getElementById('image').src = messages.image;
else {
await loadScript();
captcha = new window.TencentCaptcha(container, messages.appid, captchaResult, { type: 'embed' });
captcha.show();
}
} catch (error) { status.textContent = error.message; }
finally { loading = false; }
}
document.getElementById('image-form').onsubmit = event => {
event.preventDefault();
return submit({ code: document.getElementById('code').value });
};
retry.onclick = () => load('refresh');
await load('config');
})();
@@ -0,0 +1,174 @@
--[[--
阅文系(起点 / QQ阅读 / 潇湘)Fock 章节解密的公共宿主。
三家网页端用同一段反盗版 wasm(经 wasm2js 成 asm.js)解密正文,只是各自一个构建:导出名、回调码、栈基址、
宿主探测字符串不同。`tools/gen_fock.js` 把每个构建转译成 `source/<id>/fock_wasm.lua`,本模块提供它们共用的
内存、导入函数与调用顺序(ctors + main,再 set_uid → set_key → decrypt,结果经导入 b 的回调码交回:
三个 int:状态、明文指针、明文长度),源只在 `YuewenFockBuild` 表里填自己那份差异。
解密要 16MB 内存且纯 Lua 解释执行,在主进程做会拖慢 UI、抬高 KOReader 内存峰值(设备上可被系统杀掉重启),
`Fock.jobAsync` 把它放进 fork 子进程,主进程只收结果;转译出的巨型函数会让 ARM 上的 LuaJIT 编译器段错误,
`decrypt` 期间关掉 JIT,完事开回来(之后的字形比对要靠它)。
@module moonsource_qidian.yuewen_fock
--]]--
local ffi = require("ffi")
local Job = require("workers.job")
local Text = require("utils.text")
---@class YuewenFockBuild
---@field wasm string 转译产物模块名(`source.<id>.fock_wasm`)
---@field callback integer 导入 b 交回解密结果的回调码
---@field stack integer set_stack 的栈基址
---@field exports { ctors: string, main: string, set_uid: string, set_key: string, decrypt: string, stack_save: string, stack_restore: string, alloc: string, malloc: string } 导出名
---@field probe fun(code: integer): integer 导入 b 收到非回调码(反调试 / 定时器探测)时的返回值
---@field imports fun(env: YuewenFockEnv): table<string, function> 构建特有的导入(宿主字符串探测 c / e / f)
---@class YuewenFockEnv
---@field mem ffi.cdata* 线性内存
---@field cstr fun(ptr: integer): string 读内存里的 C 字符串
---@field malloc_str fun(s: string): integer 用导出 malloc 放一个 C 字符串,返回指针
local Fock = {}
local MEM_SIZE = 16 * 1024 * 1024
local factories = {}
--- `Fock.decrypt` 的本体,不碰 JIT 开关。
---@param build YuewenFockBuild
---@return string|nil text
---@return string|nil err
local function run(build, content, chapter_id, keypool, version, uid)
local factory = factories[build.wasm]
if not factory then
factory = require(build.wasm)
factories[build.wasm] = factory
end
local names = build.exports
local mem = ffi.new("uint8_t[?]", MEM_SIZE)
local i32 = ffi.cast("int32_t*", mem)
local result, exp
local function cstr(ptr)
local stop = ptr
while mem[stop] ~= 0 do stop = stop + 1 end
return ffi.string(mem + ptr, stop - ptr)
end
local function malloc_str(s)
local ptr = exp[names.malloc](#s + 1)
ffi.copy(mem + ptr, s, #s)
mem[ptr + #s] = 0
return ptr
end
local imp = build.imports({ mem = mem, cstr = cstr, malloc_str = malloc_str })
imp.abort = function() error("fock abort") end
imp.d = function(ptr)
local now = os.time()
if ptr ~= 0 then i32[ptr / 4] = now end
return now
end
imp.b = function(code, _sig, argptr)
if code == build.callback then
local args = argptr / 4
result = { i32[args], i32[args + 1], i32[args + 2] }
return 0
end
return build.probe(code)
end
local data, set_stack
exp, data, set_stack = factory({ mem = mem, imp = imp })
for _idx, seg in ipairs(data) do
local bytes = Text.base64Decode(seg[2])
ffi.copy(mem + seg[1], bytes, #bytes)
end
set_stack(build.stack)
local function with_stack(fn)
local sp = exp[names.stack_save]()
local ok, err = pcall(fn)
exp[names.stack_restore](sp)
if not ok then error(err, 0) end
end
local function put_bytes(s)
local ptr = exp[names.alloc](#s)
ffi.copy(mem + ptr, s, #s)
return ptr
end
local function put_string(s)
local ptr = exp[names.alloc](#s + 1)
ffi.copy(mem + ptr, s, #s)
mem[ptr + #s] = 0
return ptr
end
local ok, err = pcall(function()
exp[names.ctors]()
exp[names.main](0, 0)
with_stack(function()
exp[names.set_uid](put_bytes(uid), #uid)
end)
local pool = Text.base64Decode(keypool)
with_stack(function()
exp[names.set_key](put_bytes(pool), #pool, put_string(version))
end)
local cipher = Text.base64Decode(content)
local cid = tostring(chapter_id)
with_stack(function()
exp[names.decrypt](put_bytes(cipher), #cipher, put_bytes(cid), #cid)
end)
end)
if not ok then return nil, tostring(err) end
if not result then return nil, "no result" end
if result[1] ~= 0 then return nil, "code " .. result[1] end
return ffi.string(mem + result[2], result[3])
end
---@param build YuewenFockBuild
---@param content string base64 密文
---@param chapter_id string|number
---@param keypool string base64 密钥池(fkp 里 onkeyfocus 的第一个参数)
---@param version string
---@param uid string 用户标识(ywguid / fuid)
---@return string|nil text
---@return string|nil err
function Fock.decrypt(build, content, chapter_id, keypool, version, uid)
local jit_was_on = jit.status()
jit.off()
local text, err = run(build, content, chapter_id, keypool, version, uid)
if jit_was_on then jit.on() end
return text, err
end
--- 在子进程里跑 worker(解密 / 字体还原),结果 `{ text, err }` 经 cb(text, err) 交回主进程。
---@param name string 任务名(日志)
---@param worker fun(temp_paths: string[]): { text: string|nil, err: string|nil }
---@param cb fun(text: string|nil, err: string|nil)
---@return BookJob
function Fock.jobAsync(name, worker, cb)
local Paths = require("utils.paths")
local temp_paths = { Paths.tmpname(".font"), Paths.tmpname(".font") }
local job
local function cleanup()
-- SIGKILL 后仍可能在内核里完成创建文件,等子进程退出再收尾。
if job and job.pid and not require("ffi/util").isSubProcessDone(job.pid) then
require("ui/uimanager"):scheduleIn(job.poll, cleanup)
return
end
for _idx, path in ipairs(temp_paths) do os.remove(path) end
end
job = Job.run(function() return worker(temp_paths) end, {
name = name,
kind = "light",
timeout = 600,
on_done = function(res) cleanup(); cb(res.text, res.err) end,
on_failed = function(err) cleanup(); cb(nil, tostring(err)) end,
on_cancelled = cleanup,
})
return job
end
return Fock
@@ -0,0 +1,201 @@
--[[--
阅文系 VIP 章节的乱序字体还原(QQ阅读 / 起点共用)。
Fock 解出的 HTML 里,常用字码位被换成别的字,靠随章下发的 fixedFont 画回真字;
扩展 A 区的生僻码位再靠 randomFont + CSS 排序/伪元素还原。这里把
`utils.glyph` 的字形识别和 `moonsource_qidian.yuewen_fonts.scramble` 的 HTML 解析拼起来。
字体是随章下发的,写临时文件给 FreeType 读;参考字签名会落盘缓存。
@module moonsource_qidian.yuewen_fonts
--]]--
local Text = require("utils.text")
local FontRestore = {}
local RARE_LIMIT, FIXED_LIMIT = 6763, 3755
--- 下载回来的字节是不是字体文件(TTF / OTF / TTC / WOFF 魔数)。CDN 的 HTML 错误页也会 200 回来,
--- 写进缓存会被当字体复用,一章章都解不出来。
---@param bytes string|nil
---@return boolean
function FontRestore.looksLikeFont(bytes)
if type(bytes) ~= "string" or #bytes < 4 then return false end
local head = bytes:sub(1, 4)
return head == "\0\1\0\0" or head == "OTTO" or head == "true" or head == "ttcf" or head == "wOFF"
end
local function writeTemp(bytes, path)
local file = assert(io.open(path, "wb"))
local ok, err = file:write(bytes)
local closed, close_err = file:close()
assert(ok, err)
assert(closed, close_err)
end
local function randomFontBytes(font)
local parts = {}
for idx, byte in ipairs(font and font.data or {}) do parts[idx] = string.char(byte) end
return table.concat(parts)
end
--- 乱序码位 / 互换字形 → 真字。
---@param random_font table|nil fontResponse.randomFont({data={...}})
---@param fixed_font string fixedFontTtf/woff2 下载下来的字节
---@param rare integer[] 扩展 A 区码位
---@param han integer[] 常用汉字码位
---@param opts table { threshold=number, temp_paths=string[]|nil }
---@return table rare_map
---@return table han_map
local function recognize(random_font, fixed_font, rare, han, opts)
local rare_bytes = randomFontBytes(random_font)
local paths, labels, tasks = {}, {}, {}
local function cleanup()
for _idx, path in ipairs(paths) do os.remove(path) end
end
if #rare > 0 and #rare_bytes > 0 then
paths[#paths + 1] = opts.temp_paths and opts.temp_paths[1] or require("utils.paths").tmpname(".font")
writeTemp(rare_bytes, paths[#paths])
labels[#labels + 1] = "rare"
tasks[#tasks + 1] = {
font_path = paths[#paths], codes = rare, limit = RARE_LIMIT, threshold = opts and opts.threshold,
}
end
if #han > 0 and fixed_font and #fixed_font > 0 then
paths[#paths + 1] = opts.temp_paths and opts.temp_paths[2] or require("utils.paths").tmpname(".font")
writeTemp(fixed_font, paths[#paths])
labels[#labels + 1] = "han"
tasks[#tasks + 1] = {
font_path = paths[#paths], codes = han, limit = FIXED_LIMIT, threshold = opts and opts.threshold,
}
end
if #tasks == 0 then return {}, {} end
local ref = require("fontlist").fontdir .. "/noto/NotoSansCJKsc-Regular.otf"
local ref_file, ref_err = io.open(ref, "rb")
if not ref_file then cleanup(); error(ref_err, 0) end
local ref_size = ref_file:seek("end")
ref_file:close()
-- 签名只取决于参考字体和算法参数;参考字体换了(大小变)自动重算。
-- 兼容旧版缓存名(qqreader_glyph_v1_ / glyph_v1_),避免重新渲染 6763 个参考字。
local cache_dir = require("utils.paths").cacheDir()
local cache = cache_dir .. "/yuewen_glyph_v1_" .. ref_size .. ".bin"
for _idx, legacy in ipairs({ "yuewen_glyph_v1_", "qqreader_glyph_v1_", "glyph_v1_" }) do
local path = cache_dir .. "/" .. legacy .. ref_size .. ".bin"
local f = io.open(path, "rb")
if f then
f:close()
cache = path
break
end
end
local ok, maps = pcall(require("utils.glyph").recognize, ref, cache, tasks)
cleanup()
if not ok then error(maps, 0) end
local rare_map, han_map = {}, {}
for idx, label in ipairs(labels) do
if label == "rare" then rare_map = maps[idx] else han_map = maps[idx] end
end
return rare_map, han_map
end
local function utf8len(text)
return #Text.chars(text)
end
local DECOY_SIMILARITY = 0.8
local chars = Text.chars
--- 起点 cES=2 的正文会把同一章再追加一份改了几个字的诱饵副本。
--- 前后两半段落字数一一对应、且逐字位置上 ≥80% 相同才丢后一半,避免把真实的对称段落误删。
---@param paragraphs string[]
---@return string[]
local function dropDecoyHalf(paragraphs)
local n = #paragraphs
if n < 4 or n % 2 ~= 0 then return paragraphs end
local half = n / 2
local same, total = 0, 0
for i = 1, half do
local a, b = chars(paragraphs[i]), chars(paragraphs[i + half])
if #a ~= #b then return paragraphs end
for k = 1, #a do
if a[k] == b[k] then same = same + 1 end
end
total = total + #a
end
if total == 0 or same / total < DECOY_SIMILARITY then return paragraphs end
for i = n, half + 1, -1 do paragraphs[i] = nil end
return paragraphs
end
local fixConfusions
--- 解出的 HTML 段落还原成纯文本。
---@param plain string Fock 解出的正文
---@param font table { css=string, randomFont=table|nil }
---@param fixed_font string|nil fixedFont 下载下来的字节;没有字体加密的章为 nil
---@param opts table|nil { dedupe=boolean, confusions=boolean, threshold=number, temp_paths=string[]|nil }
---@return string
function FontRestore.restore(plain, font, fixed_font, opts)
opts = opts or {}
local Scramble = require("moonsource_qidian.yuewen_fonts.scramble")
local paragraphs = Scramble.paragraphs(plain, font.css or "")
if #paragraphs == 0 then return plain end
if opts.dedupe then paragraphs = dropDecoyHalf(paragraphs) end
local rare, han = Scramble.codes(paragraphs)
local rare_map, han_map = {}, {}
if #rare + #han > 0 then
rare_map, han_map = recognize(font.randomFont, fixed_font, rare, han, opts)
end
local text = Scramble.text(paragraphs, rare_map, han_map)
if opts.confusions then text = fixConfusions(text) end
return text
end
FontRestore.dropDecoyHalf = dropDecoyHalf
-- 起点 fixedFont 里 于/干、责/贵 两组字形太近,16x16 相关度会把“关于/终于/负责”
-- 认成“关干/终干/负贵”。只修这些固定搭配;“对干部/在干活”这类保留干。
local YU_PREFIX = {
["关"] = true, ["终"] = true, ["对"] = true, ["等"] = true, ["至"] = true,
["由"] = true, ["属"] = true, ["便"] = true, ["利"] = true, ["善"] = true,
["敢"] = true, ["勇"] = true, ["难"] = true, ["易"] = true, ["在"] = true,
["位"] = true, ["鉴"] = true,
}
local YU_KEEP_NEXT = {
["部"] = true, ["活"] = true, ["事"] = true, ["劲"] = true, ["什"] = true, ["嘛"] = true, ["啥"] = true,
["吗"] = true, ["吧"] = true, ["净"] = true, ["脆"] = true, ["燥"] = true, ["旱"] = true, ["扰"] = true,
["预"] = true, ["练"] = true, ["掉"] = true, ["架"] = true, ["涸"] = true,
}
local ZE_PREFIX = { ["职"] = true, ["担"] = true, ["负"] = true, ["责"] = true, ["贵"] = true }
-- 少数整词在 fixedFont 里稳定认错(“泮”几乎只出现在“泮池”,不会误伤正文)。
local TEXT_FIXES = {
["同泮"] = "同伴",
["泮随"] = "伴随",
["聚干"] = "聚于",
}
--- 修正两类固定形近字;只在起点字体层启用。
--- Lua 的字符类是字节级,不能直接拿“部/活”做 [^...],这里按 UTF-8 单字扫描。
---@param text string
---@return string
fixConfusions = function(text)
local list = Text.chars(text)
for i = 2, #list do
local ch, prev, nxt = list[i], list[i - 1], list[i + 1]
if ch == "干" and YU_PREFIX[prev] and not (nxt and YU_KEEP_NEXT[nxt]) then
list[i] = "于"
elseif ch == "贵" and (ZE_PREFIX[prev] or nxt == "任") then
list[i] = "责"
end
end
local fixed = table.concat(list)
for from, to in pairs(TEXT_FIXES) do fixed = fixed:gsub(from, to) end
return fixed
end
FontRestore.fixConfusions = fixConfusions
return FontRestore
@@ -0,0 +1,162 @@
--[[--
QQ阅读正文乱序还原:Fock 解出的是带反爬样式的 HTML,真正的字序和字形要靠随章下发的 CSS 才能还原。
- 有 `pN` 类的段落,子元素 `<yXX>` 按 `yXX{order:n}` 重排(网页是 flex 容器),每个元素再按
`.pN yXX::first-letter{font-size:0}`(藏掉原字)与 `::before` / `::after` 的 `content`(字面量或 `attr(x)`)还原;
- `<y class="sy-0">` 是 `font-size:0` 的占位,丢弃;`sy-1` 只是镜像显示,文字照留;
- 其余码位落在 CJK 扩展 A 的字,是 randomFont 画出来的真字,由 `glyph.lua` 认出,这里只负责替换。
@module moonsource_qidian.yuewen_fonts.scramble
--]]--
local Glyph = require("utils.glyph")
local Scramble = {}
local CHAR = require("utils.text").UTF8_CHAR
local UNKNOWN = "□"
local LOW, HIGH = 0x3400, 0x4DBF
local function expand(css)
return (css:gsub("TS%-1", "transform:scaleX(-1)"):gsub("::B", "::before"):gsub("::A", "::after")
:gsub("{O:", "{order:"):gsub("{C:", "{content:"):gsub("'''", "'\\''"))
end
--- content 值:'x' / "x" 字面量或 attr(name)。
local function contentOf(body, attrs)
local value = body:match("content:%s*(.-)%s*;?%s*$")
if not value then return nil end
local name = value:match("^attr%(([%w_-]+)%)$")
if name then return attrs[name] or "" end
return value:match("^'(.*)'$") or value:match('^"(.*)"$') or ""
end
--- 解析 CSS:order[tag] 与 rules[class .. " " .. tag][self|first-letter|before|after] = body。
local function parse(css)
local order, rules = {}, {}
for sel, body in expand(css):gmatch("([^{}]+){([^}]*)}") do
sel = sel:match("^%s*(.-)%s*$")
local tag, n = sel:match("^(y[%w_-]*)$"), body:match("^order:(%d+)")
if tag and n then
order[tag] = tonumber(n)
else
local key, pseudo = sel:match("^%.(p%d+ y[%w_-]*)::([%a-]+)$")
if not key then key, pseudo = sel:match("^%.(p%d+ y[%w_-]*)$"), "self" end
if key then
rules[key] = rules[key] or {}
rules[key][pseudo] = body
end
end
end
return order, rules
end
local function attributes(raw)
local attrs = {}
for name, value in raw:gmatch('([%w_-]+)="([^"]*)"') do attrs[name] = value end
return attrs
end
local function dropFirst(text)
return (text:gsub("^" .. CHAR, "", 1))
end
local function unescape(text)
return (text:gsub("&lt;", "<"):gsub("&gt;", ">"):gsub("&quot;", '"'):gsub("&#39;", "'"):gsub("&amp;", "&"))
end
local function scrambled(cls, children, order, rules)
for idx, child in ipairs(children) do child.idx = idx end
table.sort(children, function(a, b)
local oa, ob = order[a.tag] or math.huge, order[b.tag] or math.huge
if oa ~= ob then return oa < ob end
return a.idx < b.idx
end)
local out = {}
for _idx, child in ipairs(children) do
local rule = rules[cls .. " " .. child.tag] or {}
local attrs = attributes(child.attrs)
local text = child.text
if rule["first-letter"] and rule["first-letter"]:find("font%-size:%s*0") then text = dropFirst(text) end
out[#out + 1] = (rule.before and contentOf(rule.before, attrs) or "") .. text
.. (rule.after and contentOf(rule.after, attrs) or "")
end
return table.concat(out)
end
--- 还原一章的段落文本(字形码位还没替换)。
---@param html string Fock 明文
---@param css string 章节下发的 CSS
---@return string[] paragraphs
function Scramble.paragraphs(html, css)
local order, rules = parse(css)
local paragraphs = {}
for open, body in html:gmatch("<p([^>]*)>(.-)</p>") do
local cls = open:match('class="(p%d+)"')
local text
if cls then
local children = {}
for tag, attrs, inner in body:gmatch("<(y[%w_-]*)([^>]*)>(.-)</%1>") do
children[#children + 1] = { tag = tag, attrs = attrs, text = unescape(inner) }
end
text = scrambled(cls, children, order, rules)
else
text = body:gsub('<y class="sy%-0">.-</y>', ""):gsub("<[^>]+>", "")
text = unescape(text)
end
if text ~= "" then paragraphs[#paragraphs + 1] = text end
end
return paragraphs
end
local function isRare(code)
return (code >= LOW and code <= HIGH) or code == 0xF900
end
local function isHan(code)
return code >= 0x4E00 and code <= 0x9FA5
end
--- 文本里要查字体的码位(去重):rare 走 randomFont,han 走 fixedFont(该字体没有的码位原样保留)。
---@param paragraphs string[]
---@return integer[] rare
---@return integer[] han
function Scramble.codes(paragraphs)
local seen, rare, han = {}, {}, {}
for _idx, text in ipairs(paragraphs) do
for ch in text:gmatch(CHAR) do
local code = Glyph.codepoint(ch)
if not seen[code] then
seen[code] = true
if isRare(code) then rare[#rare + 1] = code elseif isHan(code) then han[#han + 1] = code end
end
end
end
table.sort(rare)
table.sort(han)
return rare, han
end
--- 把码位换成真字,认不出的写 □;返回全文(段落以换行连接)。
---@param paragraphs string[]
---@param rare_map table<integer, string|false> randomFont 的识别结果
---@param han_map table<integer, string|false> fixedFont 的识别结果
---@return string
function Scramble.text(paragraphs, rare_map, han_map)
local out = {}
for idx, text in ipairs(paragraphs) do
out[idx] = (text:gsub(CHAR, function(ch)
local code = Glyph.codepoint(ch)
local real
if isRare(code) then real = rare_map[code] or false
elseif isHan(code) then real = han_map[code]
else return nil end
if real == nil then return nil end
return real or UNKNOWN
end))
end
return table.concat(out, "\n")
end
return Scramble
@@ -0,0 +1,486 @@
--[[--
阅文 App 扫码登录(QQ阅读、起点、潇湘共用)。
阅文自己的码,用 QQ阅读或起点 App 扫,不是手机 QQ。
GET /login/qrcode 拿 sessionKey,二维码内容是固定的 scanlogin URL。
轮询 /login/qrcodelogin。scanStatus 5 时取 ywguid / ywkey;只有 302url 时跟跳收 Set-Cookie。
拿到 Cookie 交给 on_cookie,由设置页走现有账号校验再保存。
@module koplugin.book.moonsource_qidian.yuewen_qr
--]]
require("l10n").apply()
local JSON = require("json")
local Request = require("http.request")
local Text = require("utils.text")
local logger = require("utils.log")
local _ = require("gettext")
local QRLogin = {}
QRLogin.__index = QRLogin
local BASE = "https://ptlogin.yuewen.com"
local POLL_INTERVAL = 3
local POLL_MAX = 40
local DEADLINE = 180
local MAX_HOPS = 5
local UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
.. "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
local KEEP = { ywguid = true, ywkey = true, ywopenid = true }
---@param value any
---@return string|nil
local function text(value)
if type(value) == "string" and value ~= "" then return value end
if type(value) == "number" then return tostring(value) end
end
---@return table
function QRLogin:baseParams()
return {
appId = self.spec.app_id,
areaId = self.spec.area_id,
format = "json",
returnurl = self.spec.return_url,
target = "top",
ticket = self.spec.ticket or "0",
autotime = "14",
auto = "0",
}
end
--- 二维码内容。和官方图里的 URL 同一组参数,顺序无所谓。
---@param session_key string
---@return string
function QRLogin:scanUrl(session_key)
return BASE .. "/mobile/scanlogin?" .. Text.formEncode({
sessionkey = session_key,
appid = self.spec.app_id,
areaid = self.spec.area_id,
bookId = "0",
chapterId = "0",
})
end
---@param jar table
---@return string
local function cookieHeader(jar)
local keys = {}
for key, value in pairs(jar) do
if KEEP[key] and value ~= "" then keys[#keys + 1] = key end
end
table.sort(keys)
local parts = {}
for i, key in ipairs(keys) do parts[i] = key .. "=" .. jar[key] end
return table.concat(parts, "; ")
end
---@param jar table
---@param set_cookie string|table|nil
local function takeCookies(jar, set_cookie)
if type(set_cookie) == "table" then
for _key, value in pairs(set_cookie) do takeCookies(jar, value) end
return
end
if type(set_cookie) ~= "string" or set_cookie == "" then return end
for name, value in set_cookie:gmatch("([%w_]+)=([^;,]*)") do
name = name:lower()
value = value:match("^(.-)%s*$")
if KEEP[name] and value ~= "" then jar[name] = value end
end
end
---@param data table|nil
---@param jar table
local function takeJson(data, jar)
if type(data) ~= "table" then return end
local value = data.ywGuid or data.ywguid
local guid = type(value) == "number" and string.format("%.0f", value) or text(value)
local key = text(data.ywKey or data.ywkey)
local openid = text(data.ywOpenId or data.ywopenid)
if guid then jar.ywguid = guid end
if key then jar.ywkey = key end
if openid then jar.ywopenid = openid end
if type(data.data) == "table" then takeJson(data.data, jar) end
end
---@param jar table
---@return boolean
local function ready(jar)
return jar.ywguid ~= nil and jar.ywguid ~= "" and jar.ywkey ~= nil and jar.ywkey ~= ""
end
---@class YuewenQRSpec
---@field app_id string
---@field area_id string
---@field return_url string
---@field referer string
---@field title string
---@field caption string
---@field ticket string|nil 非 0 时必须兑换本站 Web 会话
---@param spec YuewenQRSpec
---@param on_cookie fun(cookie: string)
function QRLogin.new(_class, spec, on_cookie)
local self = setmetatable({}, QRLogin)
self.spec = spec
self.on_cookie = on_cookie
self.generation = 0
self.jar = {}
self.dialog = nil
self.retry_dialog = nil
self.busy = nil
self.job = nil
self.started = 0
self.polls = 0
self.session = nil
self.login_completed = false
self.scanned_notified = false
return self
end
function QRLogin:toast(text_msg)
require("ui.themes.widgets.toast"):new{ text = tostring(text_msg), timeout = 2 }:show()
end
function QRLogin:closeBusy()
if self.busy then
self.busy:close()
self.busy = nil
end
end
function QRLogin:showBusy(text_msg)
self:closeBusy()
self.busy = require("ui.themes.widgets.progress_dialog"):new{
title = self.spec.title, text = text_msg, dismissable = false,
}
self.busy:show()
end
function QRLogin:_close_dialog()
if self.dialog then
local dialog = self.dialog
self.dialog = nil
dialog:close()
end
end
function QRLogin:_close_retry()
if self.retry_dialog then
local dialog = self.retry_dialog
self.retry_dialog = nil
dialog:close()
end
end
function QRLogin:_cancel_job()
if self.job and self.job.cancel then self.job.cancel() end
self.job = nil
end
function QRLogin:cancel()
self.generation = self.generation + 1
self.login_completed = false
self:_cancel_job()
self:_close_dialog()
self:_close_retry()
self:closeBusy()
self.jar = {}
self.session = nil
self.polls = 0
self.scanned_notified = false
end
---@param url string
---@param cb fun(res: table|nil, err: string|nil)
function QRLogin:_get(url, cb)
local headers = {
["User-Agent"] = UA,
Accept = "application/json, text/javascript, */*",
Referer = self.spec.referer,
}
local host = url:match("^https://([^/?#]+)")
if host == self.spec.return_url:match("^https://([^/?#]+)") then
local cookie = cookieHeader(self.jar)
if cookie ~= "" then headers.Cookie = cookie end
end
local pending, gen = true, self.generation
local job = Request.request({
url = url,
method = "GET",
headers = headers,
timeout = require("http.timeout").net(0.5),
allow_redirects = false,
}, function(res, err)
pending = false
if gen ~= self.generation then return end
self.job = nil
if err or not res then
cb(nil, err and tostring(err) or _("请求失败"))
return
end
local code = tonumber(res.code)
if not code or code < 200 or code >= 400 then
cb(nil, "HTTP " .. tostring(res.code))
return
end
cb(res)
end)
if pending then self.job = job end
end
---@param res table|nil
---@return table|nil
local function decode(res)
local body = res and res.body
if type(body) ~= "string" or body == "" then return nil end
local ok, wire = pcall(JSON.decode, body)
if not ok or type(wire) ~= "table" then return nil end
return wire
end
function QRLogin:_expired()
return self.polls >= POLL_MAX or os.time() - self.started > DEADLINE
end
---@param gen integer
---@param session string
function QRLogin:_later(gen, session)
require("ui/uimanager"):scheduleIn(POLL_INTERVAL, function()
self:_poll(gen, session)
end)
end
---@param gen integer
function QRLogin:_show(gen, session)
if gen ~= self.generation then return end
self:closeBusy()
self.session = session
self.polls = 0
local dialog
dialog = require("ui.themes.widgets.qr"):new{
title = self.spec.title,
text = self:scanUrl(session),
caption = self.spec.caption,
close_callback = function()
if self.dialog == dialog then self.dialog = nil end
if gen == self.generation and not self.login_completed then
self:cancel()
self:toast(_("已取消登录"))
end
end,
}
self.dialog = dialog
dialog:show()
logger.info("[YuewenQR] 二维码已显示")
self:_later(gen, session)
end
function QRLogin:start()
self:cancel()
local gen = self.generation
self.started = os.time()
self.jar = {}
self:showBusy(_("获取二维码中..."))
local params = self:baseParams()
self:_get(BASE .. "/login/qrcode?" .. Text.formEncode(params), function(res, err)
if gen ~= self.generation then return end
local wire = decode(res)
local session = wire and type(wire.data) == "table" and text(wire.data.sessionKey)
if not session or tonumber(wire.code) ~= 0 then
self:closeBusy()
logger.warn("[YuewenQR] 获取二维码失败:", err or (wire and wire.message))
self:show_retry(_("获取二维码失败"))
return
end
self:_show(gen, session)
end)
end
---@param gen integer
---@param jar table
function QRLogin:_done(gen, jar)
if gen ~= self.generation or self.login_completed then return end
if not ready(jar) then
self:show_retry(_("登录失败:未获取到登录态"))
return
end
self.login_completed = true
self.generation = self.generation + 1
self:_cancel_job()
self:_close_dialog()
self:_close_retry()
self:closeBusy()
local cookie = cookieHeader(jar)
logger.info("[YuewenQR] 登录态已拿到")
if self.on_cookie then self.on_cookie(cookie) end
end
---@param gen integer
---@param url string
---@param hop integer
function QRLogin:_follow(gen, url, hop)
if gen ~= self.generation then return end
local host = type(url) == "string" and url:match("^https://([^/?#]+)")
local target = self.spec.return_url:match("^https://([^/?#]+)")
if not host or (host ~= target and host ~= "ptlogin.yuewen.com"
and host ~= "passport.yuewen.com" and host ~= "passport.qidian.com"
and host ~= "login.book.qq.com") or hop > MAX_HOPS then
self:show_retry(_("登录失败:未获取到登录态"))
return
end
self:showBusy(_("正在完成登录..."))
self:_get(url, function(res, err)
if gen ~= self.generation then return end
if not res then
logger.warn("[YuewenQR] 跟跳失败:", err)
self:show_retry(_("登录失败:未获取到登录态"))
return
end
for _idx, value in ipairs(Request.headerAll(res, "Set-Cookie")) do takeCookies(self.jar, value) end
local location = Text.absoluteUrl(url, Request.header(res, "Location"))
if tonumber(res.code) >= 300 then
if not location then
self:show_retry(_("登录失败:未获取到登录态")); return
end
self:_follow(gen, location, hop + 1)
return
end
-- ticket=1 仍要求落到本站 host;本站实际上常常不 Set-Cookie ywkey(只有 abPolicies),
-- 不能把「见到 ywkey Set-Cookie」当成兑换成功条件,否则扫码永远失败。
if ready(self.jar) and (self.spec.ticket ~= "1" or host == target) then
self:_done(gen, self.jar)
return
end
if not location then
self:show_retry(_("登录失败:未获取到登录态"))
return
end
self:_follow(gen, location, hop + 1)
end)
end
---@param gen integer
---@param session string
---@param wire table
---@param res table
function QRLogin:_on_poll(gen, session, wire, res)
for _idx, value in ipairs(Request.headerAll(res, "Set-Cookie")) do takeCookies(self.jar, value) end
local data = type(wire.data) == "table" and wire.data or {}
takeJson(data, self.jar)
takeJson(wire, self.jar)
local status = tonumber(wire.scanStatus)
local code = tonumber(wire.code)
if code == -11033 then
self:show_retry(text(wire.message) or _("登录失败"))
return
end
if status == 5 and code == 0 then
local ticket = text(data.ticket) or text(wire.ticket)
local jump = text(data["302url"]) or text(wire["302url"])
-- 起点 ticket=1:裸 302url(https://m.qidian.com/ 无 ticket)没用,改成本站 ticket 兑换。
-- 若 302url 走 ptlogin 中转,照跟——那才是会带上完整跳转链的路径。
if self.spec.ticket == "1" then
local target = self.spec.return_url:match("^https://([^/?#]+)")
local jump_host = jump and jump:match("^https://([^/?#]+)")
local bare_home = jump_host == target and not jump:find("ticket=", 1, true)
if ticket and (not jump or bare_home) then
jump = self.spec.return_url .. (self.spec.return_url:find("?", 1, true) and "&" or "?")
.. Text.formEncode({
ticket = ticket,
ywguid = self.jar.ywguid or "",
ywOpenId = self.jar.ywopenid or "",
})
elseif not jump then
self:show_retry(_("登录失败:未获取到登录态"))
return
end
self:_follow(gen, jump, 1)
return
end
if jump then
self:_follow(gen, jump, 1)
return
end
if ready(self.jar) then
self:_done(gen, self.jar)
return
end
self:show_retry(_("登录失败:未获取到登录态"))
return
end
if status == 3 then
logger.info("[YuewenQR] 手机取消,刷新二维码")
self.generation = self.generation + 1
self:_close_dialog()
self:start()
return
end
if status == 4 or self:_expired() then
self:show_retry(_("二维码已过期"))
return
end
if status == 1 and not self.scanned_notified then
self.scanned_notified = true
self.polls = 0
self.started = os.time()
self:toast(_("已扫码,请在手机上确认"))
end
self:_later(gen, session)
end
---@param gen integer
---@param session string
function QRLogin:_poll(gen, session)
if gen ~= self.generation or session ~= self.session then return end
if self:_expired() then
self:show_retry(_("二维码已过期"))
return
end
self.polls = self.polls + 1
local params = self:baseParams()
params.qrcode = session
self:_get(BASE .. "/login/qrcodelogin?" .. Text.formEncode(params), function(res, err)
if gen ~= self.generation or session ~= self.session then return end
local wire = decode(res)
if not wire then
if self.polls == 1 or self.polls % 5 == 0 then
logger.warn("[YuewenQR] 轮询失败:", err)
end
if self:_expired() then
self:show_retry(_("二维码已过期"))
return
end
self:_later(gen, session)
return
end
self:_on_poll(gen, session, wire, res)
end)
end
function QRLogin:show_retry(msg)
self.generation = self.generation + 1
self:_cancel_job()
self:_close_dialog()
self:_close_retry()
self:closeBusy()
local dialog
dialog = require("ui.themes.widgets.confirm"):new{
text = tostring(msg),
ok_text = _("重新获取"),
ok_callback = function()
if self.retry_dialog == dialog then self.retry_dialog = nil end
self:start()
end,
cancel_callback = function()
if self.retry_dialog == dialog then self.retry_dialog = nil end
self:cancel()
end,
}
self.retry_dialog = dialog
dialog:show()
end
return QRLogin