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

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

Co-authored-by: Copilot <[email protected]>
This commit is contained in:
GarfieldandCopilot committed 2026-11-16 12:08:03 +08:00
commit 730b2d6d9f
27 files changed
+17665

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
# QQ阅读
| 能力 | 是否支持 | 备注 |
| --- | --- | --- |
| 扫码登录 | 已实现,未实测 | 阅文扫码,保存前校验账号 |
| 浏览器登录与 Cookie 导入 | 支持 | 手动粘贴及扩展回传;扩展完整握手未实测 |
| 设备密码与短信登录 | 不支持 | 未接入 |
| 书架拉取 | 支持 | 分页读取,坏响应不会当成空书架 |
| 书架新增与移出 | 已实现,未实测 | 本地先生效,再同步上行 |
| 搜索与榜单 | 支持 | 搜索最多 200 本;男生、女生、出版榜单默认聚合 60 本 |
| 分类书城 | 部分支持 | 已接动态分类及筛选,但源站列表间歇为空,尚未稳定通过实测 |
| 详情与目录 | 支持 | 保留书号、章节 ID 和目录缓存 |
| 免费正文 | 支持 | 免费章可读,未购预览不当作正文缓存 |
| 已购与会员正文 | 已实现,未实测 | 沿官网权限、解码和字体还原流程 |
| 章节与全本缓存 | 支持 | 缓存正文和目录可离线阅读 |
| 阅读进度同步 | 部分支持 | 仅章节 ID,无章内比例;书已离架时不借上传进度重新加架 |
| 笔记与统计同步 | 不支持 | 仅本地保存 |
| 整书书评 | 部分支持 | 首批预览;官网未返回有效后续游标,未接完整分页 |
| 章评与段评 | 不支持 | 当前 Web 协议未找到可验证接口 |
| 评论图片、回复与写操作 | 不支持 | 尚未接入 |
| 账号切换 | 部分支持 | 同账号可续期;换号须确认清理旧本地数据,未同步记录会丢失 |
+5
View File
@@ -0,0 +1,5 @@
local _ = require("gettext")
return {
fullname = _("月读书源:QQ阅读"),
description = _("给月读增加「QQ阅读」书源。需要同时安装月读,与平台官方无关。"),
}
+9
View File
@@ -0,0 +1,9 @@
--[[--
KOReader 只认带 main.lua 的插件目录;书源本身不需要任何插件钩子,月读读取旁边的 moon_source.lua。
--]]
local WidgetContainer = require("ui/widget/container/widgetcontainer")
return WidgetContainer:extend{
name = "moonsource_qqreader",
is_doc_only = false,
}
@@ -0,0 +1,15 @@
--[[--
月读第三方书源描述:QQ阅读。契约见月读 examples/moonsource-demo.koplugin/moon_source.lua。
--]]
local function lazy(module)
return setmetatable({}, { __index = function(_, key) return require(module)[key] end })
end
return {
api = 1,
provides = { source = true },
meta = function() return require("moonsource_qqreader.source").meta() end,
new = function() return require("moonsource_qqreader.source").new() end,
setting = lazy("moonsource_qqreader.setting"),
}
@@ -0,0 +1,15 @@
--[[--
书源元信息:id / 名称 / 类型,加上启用页展示用的说明与能力清单。`init.lua` 的 `meta()` 直接返回本表。
@module moonsource_qqreader._meta
--]]
local _ = require("l10n").get("moonsource_qqreader")
return {
id = "ext.qqreader",
name = _("QQ阅读"),
type = "chapter",
description = _("QQ阅读书架与在线阅读"),
abilities = { _("扫码登录"), _("搜索与发现"), _("书架同步"), _("VIP 章节"), _("书评"), _("进度同步") },
}
@@ -0,0 +1,103 @@
--[[--
QQ阅读官网动态分类与筛选,兼容旧 cate:分类号节点。
@module moonsource_qqreader.browse
--]]
local Browse = require("source.browse")
local Client = require("moonsource_qqreader.client")
local SourceBase = require("source.base")
local _ = require("l10n").get("moonsource_qqreader")
local Library = {}
local KEYS = { "categoryId2", "categoryId3", "finishStatus", "priceStatus", "words", "updateTime", "orderBy", "pageNo" }
local function path(params)
local parts = {}
for idx, key in ipairs(KEYS) do parts[idx] = tostring(params[key]) end
return table.concat(parts, "-")
end
local function change(params, key, value)
local copy = {}
for name, current in pairs(params) do copy[name] = current end
copy[key], copy.pageNo = value, 1
if key == "categoryId2" then copy.categoryId3 = 0 end
return "cate:" .. path(copy)
end
local function groups(data)
local params, out = data.params, {}
local current = "cate:" .. path(params)
for _idx, category in ipairs(data.categoryList) do
local chips = {}
for _item, item in ipairs(category.subCategories) do
if item.value ~= 0 then chips[#chips + 1] = { id = change(params, "categoryId2", item.value), title = _(item.text) } end
end
local group = Browse.group(chips, current)
group.title = _(category.name) .. _("分类")
out[#out + 1] = group
end
local nav = Browse.group({
{ id = "rank:male-sell", title = _("排行榜") },
{ id = "cate:0", title = _("全部") },
}, current)
nav.title = _("筛选")
out[#out + 1] = nav
for _idx, key in ipairs({ "categoryId3", "finishStatus", "priceStatus", "words", "updateTime", "orderBy" }) do
local filter = data[key]
if type(filter) ~= "table" or type(filter.items) ~= "table" then return nil end
local chips = {}
for _item, item in ipairs(filter.items) do
chips[#chips + 1] = {
id = change(params, key, item.value),
title = _(item.text),
}
end
local group = Browse.group(chips, current)
group.title = key == "orderBy" and _("排序") or _(filter.title)
out[#out + 1] = group
end
return out
end
---@param opts { node?: string, limit?: integer }
---@param cb fun(res: table|nil, err: string|nil)
---@return HttpJob
function Library.run(opts, cb)
local value = (opts.node or "cate:0"):sub(6)
local parts = {}
for part in value:gmatch("[^-]+") do
if not part:match("^%d+$") then return SourceBase.defer(cb, nil, _("QQ阅读分类条件无效")) end
parts[#parts + 1] = tonumber(part)
end
if (#parts ~= 1 and #parts ~= 8) or value:find("--", 1, true)
or value:sub(1, 1) == "-" or value:sub(-1) == "-" then
return SourceBase.defer(cb, nil, _("QQ阅读分类条件无效"))
end
local params = {}
for idx, key in ipairs(KEYS) do params[key] = parts[idx] or (key == "pageNo" and 1 or 0) end
params.pageNo = 1
local cancelled, job, pending = false, nil, true
local inner = Client.categoryAsync(path(params), function(first, err)
pending = false
if cancelled then return end
if not first then cb(nil, err); return end
local chips = groups(first)
if not chips then cb(nil, _("QQ阅读分类响应无效")); return end
-- JSON books 不稳定,元数据可用;书卡沿用官网 SSR,实测限制见 README。
job = Browse.pages(function(page, done)
params.pageNo = page
return Client.listAsync("/book-cate/" .. path(params), done)
end, opts.limit or 60, chips, function(result, reason)
if not cancelled then cb(result, reason) end
end)
end)
if pending then job = inner end
return { cancel = function()
cancelled = true
if job then job.cancel() end
end }
end
return Library
@@ -0,0 +1,463 @@
--[[--
QQ阅读 HTTP 客户端(仅异步)。
接口在 https://book.qq.com/api/ ,code 0 成功,-4 是登录失效(HTTP 仍是 200)。
目录和免费章匿名可读。付费章同样 code 0;authStatus=1 已购、2 会员,其余状态不能缓存预览。
encrypt / fontEncrypt 为真是 Fock 加密 + 乱序字体(已购章),解密见 fock.lua / scramble.lua / glyph.lua。
书架分页 pageNo / pageSize / hasNext,置顶和普通列表拼在一起。
进度只到章:POST bookshelf/update/reading/process,只传 bid 和 lastReadChapterId。
@module koplugin.book.moonsource_qqreader.client
--]]
local Fock = require("moonsource_qqreader.fock")
local JSON = require("json")
local logger = require("utils.log")
local Mapper = require("moonsource_qqreader.mapper")
local Request = require("http.request")
local SourceBase = require("source.base")
local Text = require("utils.text")
local _ = require("l10n").get("moonsource_qqreader")
local Client = {}
local SOURCE_ID = "ext.qqreader"
local WEB = "https://book.qq.com"
local API = WEB .. "/api"
local UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) "
.. "Chrome/120.0.0.0 Safari/537.36"
local PAGE_SIZE = 100
local AUTH_FAIL = -4
---@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
---@param cookie string|nil
---@param referer string|nil
---@return table
local function headers(cookie, referer)
return {
["User-Agent"] = UA,
Referer = referer or WEB .. "/book-shelf",
}
end
---@param params table|nil
---@return string
local function query(params)
local parts = {}
for key, value in pairs(params or {}) do
parts[#parts + 1] = Text.urlEncode(key) .. "=" .. Text.urlEncode(value)
end
table.sort(parts)
return table.concat(parts, "&")
end
--- 书号 / 章号在官方请求里是数字。不是整数就原样当字符串。
---@param id string|number
---@return string|number
local function jsonId(id)
local text = tostring(id)
local n = tonumber(text)
if n and n == math.floor(n) and tostring(math.floor(n)) == text then return n end
return text
end
--- 登录态失效只标记当前已保存的 Cookie。
---@param cookie string|nil
---@param msg string
---@return string
local function expired(cookie, msg)
if cookie and cookie ~= "" and cookie == Client.cookie() then
return require("source.auth").expire(SOURCE_ID, msg)
end
return msg
end
---@return string
local function loginGone()
return _("点这个提示上的「重新登录」。没有按钮就打开「设置 → 书库 → 账号 → QQ阅读 → QQ阅读账号」。二维码出来后,打开手机上的 QQ阅读或起点 App,点扫一扫,对准屏幕,在手机上点确认。")
.. "\n\n" .. _("扫了还是进不去,就改用浏览器,按下面做:") .. "\n"
.. require("source.cookie_login").relogin(_("QQ阅读"), "https://book.qq.com/book-shelf")
end
---@param raw string|nil
---@param err any
---@param cookie string|nil
---@return table|nil wire
---@return string|nil err
local function decode(raw, err, cookie)
if not raw then return nil, err and tostring(err) or _("请求失败") end
local ok, wire = pcall(JSON.decode, raw)
if not ok or type(wire) ~= "table" then return nil, _("响应无效") end
if tonumber(wire.code) == 0 then
if cookie and cookie == Client.cookie() then require("source.auth").ok(SOURCE_ID) end
return wire
end
local msg = type(wire.msg) == "string" and wire.msg ~= "" and wire.msg or _("请求失败")
if tonumber(wire.code) == AUTH_FAIL then msg = expired(cookie, loginGone()) end
return nil, msg
end
---@param method string
---@param path string
---@param params table|nil
---@param body string|nil
---@param cookie string|nil
---@param cb fun(wire: table|nil, err: string|nil)
---@param referer string|nil
---@return HttpJob
local function call(method, path, params, body, cookie, cb, referer)
local url = API .. path
if params then url = url .. "?" .. query(params) end
local opts = {
accept = "application/json",
headers = headers(cookie, referer),
jar = require("http.cookie_jar").session(SOURCE_ID, cookie),
timeout = require("http.timeout").net(1),
}
local function done(raw, err, res)
local status = res and tonumber(res.code)
if not raw and cookie and (status == 302 or status == 401) then
cb(nil, expired(cookie, loginGone()))
return
end
cb(decode(raw, err, cookie))
end
if method == "POST" then
opts.headers.Origin = WEB
opts.content_type = "application/json"
return Request.post(url, body, opts, done)
end
return Request.get(url, opts, done)
end
---@param cookie string
---@param cb fun(ok: boolean|nil, err: string|nil, account: { id: 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 call("GET", "/user/homepage", nil, nil, cookie, function(wire, err)
if not wire or type(wire.data) ~= "table" then
cb(nil, err or loginGone())
return
end
local guid = cookie:match("^ywguid=([^;]+)") or cookie:match(";%s*ywguid=([^;]+)")
local uid = cookie:match("^uid=([^;]+)") or cookie:match(";%s*uid=([^;]+)")
local id = guid or uid
if not id or not id:match("^%d+$") or (guid and uid and guid ~= uid) then
cb(nil, _("QQ阅读账号标识缺失")); return
end
cb(true, nil, { id = id })
end)
end
--- 拉书架。每页拼接置顶和普通列表;hasNext 为真但没有新书时明确失败。
---@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, _("未登录 QQ阅读"))
end
local cancelled, job, books, seen = false, nil, {}, {}
local function add(list)
local n = 0
for _idx, row in ipairs(type(list) == "table" and list or {}) do
if type(row) ~= "table" or not row.bid then return nil end
local id = tostring(row.bid)
if id and not seen[id] then
seen[id] = true
books[#books + 1] = row
n = n + 1
end
end
return n
end
local function page(n)
if cancelled then return end
local pending = true
local inner = call("GET", "/bookshelf/query", { pageNo = n, pageSize = PAGE_SIZE }, nil, cookie, function(wire, err)
pending = false
if cancelled then return end
if not wire then cb(nil, err); return end
local data = wire.data
if type(data) ~= "table" or type(data.bookList) ~= "table"
or (data.topBookList ~= nil and type(data.topBookList) ~= "table") then
cb(nil, _("QQ阅读书架响应无效")); return
end
local top, normal = add(data.topBookList), add(data.bookList)
if not top or not normal then cb(nil, _("QQ阅读书架响应无效")); return end
local added = top + normal
local more = data.hasNext == true or tonumber(data.hasNext) == 1
if more and added == 0 then cb(nil, _("QQ阅读书架分页没有进展")); return end
if not more then cb(books) else page(n + 1) end
end)
if pending then job = inner end
end
page(1)
return { cancel = function()
cancelled = true
if job then job.cancel() end
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, _("未登录 QQ阅读")) end
return call("POST", "/bookshelf/add", nil, JSON.encode({ bid = jsonId(book_id) }), cookie, function(wire, err)
cb(wire and true or nil, err)
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, _("未登录 QQ阅读")) end
return call("POST", "/bookshelf/delete", nil, JSON.encode({ bids = { jsonId(book_id) } }), cookie, function(wire, err)
cb(wire and true or nil, err)
end)
end
--- 上报读到哪一章。不传 lastReadOffset:官方更新也不传。
---@param book_id string
---@param chapter_id string
---@param cb fun(ok: boolean|nil, err: string|nil)
---@return { cancel: fun() }
function Client.updateReadAsync(book_id, chapter_id, cb)
local cookie = Client.cookie()
if not cookie then return SourceBase.defer(cb, nil, _("未登录 QQ阅读")) end
return call("POST", "/bookshelf/update/reading/process", nil, JSON.encode({
bid = jsonId(book_id),
lastReadChapterId = jsonId(chapter_id),
}), cookie, function(wire, err)
cb(wire and true or nil, err)
end)
end
--- 官网 JSON 搜索;匿名,每页十条,hasNext 决定后续页。
---@param keyword string
---@param cb fun(books: Book[]|nil, err: string|nil, more: boolean|nil)
---@param page integer|nil
---@return HttpJob
function Client.searchAsync(keyword, cb, page)
return call("GET", "/booksearch/query", { keyWord = keyword, pageNo = page or 1, pageSize = 10 },
nil, nil, function(wire, err)
if not wire then cb(nil, err); return end
local data = wire.data
if type(data) ~= "table" or type(data.bookList) ~= "table" then
cb(nil, _("QQ阅读搜索响应无效")); return
end
local books = {}
for _idx, row in ipairs(data.bookList) do
if type(row) ~= "table" or not row.bid or type(row.title) ~= "string" then
cb(nil, _("QQ阅读搜索响应无效")); return
end
books[#books + 1] = Mapper.book(row)
end
cb(books, nil, data.hasNext == true or tonumber(data.hasNext) == 1)
end)
end
--- 官网榜单 / 分类 SSR 书卡 → Book[]。
---@param path string
---@param cb fun(books: Book[]|nil, err: string|nil)
---@return HttpJob
function Client.listAsync(path, cb)
return Request.get(WEB .. path, {
accept = "text/html",
headers = headers(nil, WEB .. path),
timeout = require("http.timeout").net(1),
}, function(raw, err)
if not raw then cb(nil, err and tostring(err) or _("请求失败")); return end
if not raw:find('class="book-rank main"', 1, true)
and not raw:find('class="book-cate main"', 1, true) then
cb(nil, _("QQ阅读列表响应无效")); return
end
local books = Mapper.searchHtml(raw)
if #books == 0 and raw:find("/book-detail/%d+") then cb(nil, _("QQ阅读列表响应无效")); return end
cb(books)
end)
end
---@param filters string 官网分类路径的八段条件
---@param cb fun(data: table|nil, err: string|nil)
---@return HttpJob
function Client.categoryAsync(filters, cb)
return call("GET", "/category/" .. filters, nil, nil, nil, function(wire, err)
if not wire then cb(nil, err); return end
local data = wire.data
if type(data) ~= "table" or type(data.books) ~= "table" or type(data.categoryList) ~= "table"
or type(data.params) ~= "table" or not tonumber(data.total) then
cb(nil, _("QQ阅读分类响应无效")); return
end
for _idx, key in ipairs({ "categoryId2", "categoryId3", "finishStatus", "priceStatus", "words", "updateTime", "orderBy", "pageNo" }) do
if not tonumber(data.params[key]) then cb(nil, _("QQ阅读分类响应无效")); return end
end
for _idx, category in ipairs(data.categoryList) do
if type(category) ~= "table" or type(category.name) ~= "string" or type(category.subCategories) ~= "table" then
cb(nil, _("QQ阅读分类响应无效")); return
end
end
for _idx, row in ipairs(data.books) do
if type(row) ~= "table" or not row.bid or type(row.title) ~= "string" then
cb(nil, _("QQ阅读分类响应无效")); return
end
end
cb(data)
end, WEB .. "/book-cate/" .. filters)
end
---@param book_id string
---@param cb fun(data: table|nil, err: string|nil)
---@param cursor string|nil
---@return HttpJob
function Client.bookCommentsAsync(book_id, cb, cursor)
return call("GET", "/bookcomment/list", { bid = book_id, cursor = cursor }, nil, nil, function(wire, err)
if not wire then cb(nil, err); return end
local data = wire.data
if type(data) ~= "table" or type(data.comments) ~= "table" or not tonumber(data.commentCount) then
cb(nil, _("QQ阅读书评响应无效")); return
end
for _idx, row in ipairs(data.comments) do
if type(row) ~= "table" or type(row.content) ~= "string" or type(row.user) ~= "table"
or (row.createTime ~= nil and not tonumber(row.createTime)) then
cb(nil, _("QQ阅读书评响应无效")); return
end
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 call("GET", "/book/detail", { bid = book_id }, nil, Client.cookie(), function(wire, err)
if not wire then cb(nil, err); return end
local info = wire.data
if type(info) ~= "table" or not info.title then cb(nil, _("QQ阅读书籍信息为空")); return end
cb(info)
end)
end
---@param book_id string
---@param cb fun(rows: table|nil, err: string|nil)
---@return HttpJob
function Client.catalogAsync(book_id, cb)
return call("GET", "/book/detail/chapters", { bid = book_id }, nil, Client.cookie(), function(wire, err)
if not wire then cb(nil, err); return end
if type(wire.data) ~= "table" then cb(nil, _("QQ阅读目录为空")); return end
cb(wire.data)
end)
end
---@param book_id string
---@param chapter_id string
---@param fuid string|nil 加密章要带 piracy 给的 fuid,密文跟它绑定
---@param cb fun(info: table|nil, err: string|nil)
---@return HttpJob
local function readAsync(book_id, chapter_id, fuid, cookie, cb)
return call("GET", "/book/read", { bid = book_id, cid = chapter_id, fuid = fuid }, nil, cookie,
function(wire, err)
if not wire then cb(nil, err); return end
if type(wire.data) ~= "table" then cb(nil, _("QQ阅读章节内容为空")); return end
cb(wire.data)
end)
end
--- 一章正文。未授权的付费章只有预览;已购章是 Fock 加密 + 乱序字体,解出后还原成纯文本。
--- 密钥池与 fuid 在 user/index/piracy(网页的 fkp,`window.onkeyfocus("<密钥池>", <版本>)` 的 base64,只取参数不执行)。
---@param book_id string
---@param chapter_id string
---@param cb fun(text: string|nil, err: string|nil, kind: "unpaid"|nil) kind = "unpaid":这章没买
---@return table handle { cancel }
function Client.contentAsync(book_id, chapter_id, cb)
local current, cancelled, cookie = nil, false, Client.cookie()
local function request(start, done)
local pending = true
local job = start(function(...)
pending = false
if cancelled then return end
current = nil
done(...)
end)
if pending then current = job end
end
local function finish(text)
if type(text) ~= "string" or Text.trim(text) == "" then cb(nil, _("QQ阅读章节内容为空")); return end
cb(text)
end
local function decrypt(info, pirate)
local keypool, version = Text.base64Decode(tostring(pirate.fkp or ""))
:match('onkeyfocus%("([^"]+)",%s*(%d+)%)')
local font = type(info.fontResponse) == "table" and info.fontResponse or {}
if not (keypool and version and type(info.content) == "string" and pirate.fuid) then
logger.warn("qqreader decrypt inputs missing: keypool", keypool ~= nil, "version", version ~= nil,
"content", type(info.content), "fuid", pirate.fuid ~= nil)
cb(nil, _("QQ阅读章节解密失败")); return
end
local function run(fixed_font)
request(function(done)
return Fock.chapterAsync(info, fixed_font, chapter_id, keypool, version, pirate.fuid, done)
end,
function(text, derr)
if not text then
logger.warn("qqreader fock decrypt failed:", derr)
cb(nil, _("QQ阅读章节解密失败")); return
end
finish(text)
end)
end
if not Mapper.fontEncrypted(info) then run(nil); return end
if type(font.fixedFontTtf) ~= "string" then
logger.warn("qqreader decrypt: fixedFontTtf missing")
cb(nil, _("QQ阅读章节解密失败")); return
end
request(function(done)
return Request.get(font.fixedFontTtf, { timeout = require("http.timeout").net(1) }, done)
end, function(ttf, ferr)
if not ttf or #ttf < 4 then
logger.warn("qqreader font download failed:", ferr, ttf and #ttf)
cb(nil, _("QQ阅读章节解密失败")); return
end
run(ttf)
end)
end
request(function(done) return readAsync(book_id, chapter_id, nil, cookie, done) end, function(info, err)
if not info then cb(nil, err); return end
if Mapper.locked(info) then cb(nil, _("QQ阅读 VIP 章节未购买"), "unpaid"); return end
if not Mapper.encrypted(info) then finish(info.content); return end
request(function(done) return call("GET", "/user/index/piracy", nil, nil, cookie, done) end, function(wire, perr)
if not wire then cb(nil, perr); return end
local pirate = type(wire.data) == "table" and wire.data or {}
if type(pirate.fuid) ~= "string" and type(pirate.fuid) ~= "number" then
cb(nil, _("QQ阅读章节解密失败")); return
end
pirate.fuid = type(pirate.fuid) == "number" and string.format("%.0f", pirate.fuid) or pirate.fuid
if pirate.fuid == "" then cb(nil, _("QQ阅读章节解密失败")); return end
request(function(done) return readAsync(book_id, chapter_id, pirate.fuid, cookie, done) end, function(enc, rerr)
if not enc then cb(nil, rerr); return end
if Mapper.locked(enc) then cb(nil, _("QQ阅读 VIP 章节未购买"), "unpaid"); return end
if not Mapper.encrypted(enc) then finish(enc.content); return end
decrypt(enc, pirate)
end)
end)
end)
return { cancel = function()
cancelled = true
if current then current:cancel() end
end }
end
return Client
@@ -0,0 +1,60 @@
--[[--
QQ阅读已购 VIP 章节正文解密(Fock):阅文 wasm 的 QQ阅读构建参数 + 子进程编排,宿主在 `moonsource_qqreader.yuewen_fock`。
结果经导入 b 的回调码 21795 交回。
@module moonsource_qqreader.fock
--]]--
local Shared = require("moonsource_qqreader.yuewen_fock")
local FontRestore = require("moonsource_qqreader.yuewen_fonts")
local Fock = {}
local HOST = {
["window.location.hostname"] = "book.qq.com",
["location.hostname"] = "book.qq.com",
}
---@type YuewenFockBuild
local BUILD = {
wasm = "moonsource_qqreader.fock_wasm",
callback = 21795,
stack = 5274112,
exports = { ctors = "f", main = "j", set_uid = "g", set_key = "h", decrypt = "i",
stack_save = "k", stack_restore = "l", alloc = "m", malloc = "n" },
probe = function(code) return code % 709 == 8 and -1 or 0 end,
imports = function(env)
return {
c = function(ptr) return env.malloc_str(HOST[env.cstr(ptr)] or "undefined") end,
e = function() return 0 end,
}
end,
}
---@param content string base64 密文
---@param chapter_id string|number
---@param keypool string base64 密钥池(piracy 接口 fkp 里 onkeyfocus 的第一个参数)
---@param version string
---@param fuid string piracy 接口给的用户标识
---@return string|nil text
---@return string|nil err
function Fock.decrypt(content, chapter_id, keypool, version, fuid)
return Shared.decrypt(BUILD, content, chapter_id, keypool, version, fuid)
end
--- 在子进程里解密并还原乱序,回调拿正文纯文本或错误。
--- 起点、潇湘同一套字体反盗版,共用 `moonsource_qqreader.yuewen_fonts`。
---@param info table /book/read 的 data(content、fontResponse)
---@param fixed_font string|nil fontResponse.fixedFontTtf 下载下来的字节;没有字体加密的章为 nil,不还原字形
---@param chapter_id string|number
---@return BookJob
function Fock.chapterAsync(info, fixed_font, chapter_id, keypool, version, fuid, cb)
return Shared.jobAsync("qqreader_fock", function(temp_paths)
local plain, err = Fock.decrypt(info.content, chapter_id, keypool, version, fuid)
if not plain then return { err = err } end
local font = type(info.fontResponse) == "table" and info.fontResponse or {}
return { text = FontRestore.restore(plain, font, fixed_font, { temp_paths = temp_paths }) }
end, cb)
end
return Fock
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,56 @@
return {
["完结"] = "Completed",
["排行榜"] = "Rankings",
["切换账号"] = "Switch account",
["无法确认旧账号,请先退出旧账号再登录"] = "Cannot identify the previous account. Sign out before signing in again.",
["筛选"] = "Filters",
["连载"] = "Ongoing",
["扫码登录"] = "Sign in with QR code",
["扫了还是进不去,就改用浏览器,按下面做:"] = "If scanning still does not get you in, use a browser and follow the steps below:",
["未登录 · 点此扫码"] = "Not signed in · tap to scan",
["章节目录保存失败"] = "Failed to save chapter list",
["按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"] = "Press F12, open Network, refresh, and copy the entire Cookie request header",
["点这个提示上的「重新登录」。没有按钮就打开「设置 → 书库 → 账号 → QQ阅读 → QQ阅读账号」。二维码出来后,打开手机上的 QQ阅读或起点 App,点扫一扫,对准屏幕,在手机上点确认。"] = "Tap Sign in again on this message. If there is no button, open Settings → Library → Account → QQ Reader → QQ Reader account. When the QR code appears, open the QQ Reader or Qidian app, tap Scan, point it at the screen, and confirm on the phone.",
["QQ阅读"] = "QQ Reader",
["QQ阅读账号"] = "QQ Reader account",
["QQ阅读登录 Cookie"] = "QQ Reader login cookie",
["QQ阅读扫码登录"] = "QQ Reader QR sign-in",
["用 QQ阅读或起点 App 扫一扫"] = "Scan with the QQ Reader or Qidian app",
["确定退出 QQ阅读账号?"] = "Sign out of QQ Reader?",
["未登录 QQ阅读"] = "Not signed in to QQ Reader",
["QQ阅读书籍信息为空"] = "QQ Reader book info is empty",
["QQ阅读章节内容为空"] = "QQ Reader chapter is empty",
["QQ阅读 VIP 章节未购买"] = "This QQ Reader VIP chapter is not purchased",
["QQ阅读章节解密失败"] = "Failed to decrypt this QQ Reader chapter",
["QQ阅读目录为空"] = "QQ Reader table of contents is empty",
["QQ阅读账号标识缺失"] = "QQ Reader account identifier is missing or inconsistent",
["QQ阅读书架响应无效"] = "Invalid QQ Reader bookshelf response",
["QQ阅读书架分页没有进展"] = "QQ Reader bookshelf pagination made no progress",
["QQ阅读搜索响应无效"] = "Invalid QQ Reader search response",
["QQ阅读列表响应无效"] = "Invalid QQ Reader list response",
["QQ阅读分类响应无效"] = "Invalid QQ Reader category response",
["QQ阅读分类条件无效"] = "Invalid QQ Reader category filters",
["QQ阅读书评响应无效"] = "Invalid QQ Reader review response",
["书评(预览 %1/%2)"] = "Reviews (preview %1/%2)",
["切换 QQ阅读账号会清除这台设备上 QQ阅读的书架、阅读进度、笔记和缓存,包括尚未同步的记录。不会删除远端书架。确定继续?"] = "Switching QQ Reader accounts clears this device's QQ Reader bookshelf, progress, notes and cache, including unsynced changes. Your remote bookshelf will not be deleted. Continue?",
["缺少 QQ阅读章节位置"] = "Missing QQ Reader chapter position",
["这本书不在 QQ阅读书架上"] = "This book is not on the QQ Reader shelf",
["出版新书榜"] = "Published New Books",
["出版新知榜"] = "Published Knowledge",
["出版热门榜"] = "Published Hot",
["女生免费榜"] = "Female Free",
["女生完结榜"] = "Female Completed",
["女生封神榜"] = "Female Top",
["女生新书榜"] = "Female New",
["女生热门榜"] = "Female Hot",
["男生免费榜"] = "Male Free",
["男生完结榜"] = "Male Completed",
["男生封神榜"] = "Male Top",
["男生新书榜"] = "Male New",
["男生热门榜"] = "Male Hot",
["QQ阅读书架与在线阅读"] = "QQ Reader shelf and online reading",
["VIP 章节"] = "VIP chapters",
["书架同步"] = "Shelf sync",
["搜索与发现"] = "Search and discover",
["进度同步"] = "Progress sync",
}
@@ -0,0 +1,56 @@
return {
["完结"] = "完結",
["排行榜"] = "排行榜",
["切换账号"] = "切換帳號",
["无法确认旧账号,请先退出旧账号再登录"] = "無法確認舊帳號,請先登出舊帳號再登入",
["筛选"] = "篩選",
["连载"] = "連載",
["扫码登录"] = "掃碼登入",
["扫了还是进不去,就改用浏览器,按下面做:"] = "掃了還是進不去,就改用瀏覽器,按下面做:",
["未登录 · 点此扫码"] = "未登入 · 點此掃碼",
["章节目录保存失败"] = "章節目錄儲存失敗",
["按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"] = "按鍵盤 F12,點「網路」,重新整理網頁,複製請求標頭裡的整段 Cookie",
["点这个提示上的「重新登录」。没有按钮就打开「设置 → 书库 → 账号 → QQ阅读 → QQ阅读账号」。二维码出来后,打开手机上的 QQ阅读或起点 App,点扫一扫,对准屏幕,在手机上点确认。"] = "點這個提示上的「重新登入」。沒有按鈕就打開「設定 → 書庫 → 帳號 → QQ閱讀 → QQ閱讀帳號」。二維碼出來後,打開手機上的 QQ閱讀或起點 App,點掃一掃,對準螢幕,在手機上點確認。",
["QQ阅读"] = "QQ閱讀",
["QQ阅读账号"] = "QQ閱讀帳號",
["QQ阅读登录 Cookie"] = "QQ閱讀登入 Cookie",
["QQ阅读扫码登录"] = "QQ閱讀掃碼登入",
["用 QQ阅读或起点 App 扫一扫"] = "用 QQ閱讀或起點 App 掃一掃",
["确定退出 QQ阅读账号?"] = "確定登出 QQ閱讀帳號?",
["未登录 QQ阅读"] = "未登入 QQ閱讀",
["QQ阅读书籍信息为空"] = "QQ閱讀書籍資訊為空",
["QQ阅读章节内容为空"] = "QQ閱讀章節內容為空",
["QQ阅读 VIP 章节未购买"] = "此 QQ閱讀 VIP 章節尚未購買",
["QQ阅读章节解密失败"] = "QQ閱讀章節解密失敗",
["QQ阅读目录为空"] = "QQ閱讀目錄為空",
["QQ阅读账号标识缺失"] = "QQ閱讀帳號識別碼缺失或不一致",
["QQ阅读书架响应无效"] = "QQ閱讀書架回應無效",
["QQ阅读书架分页没有进展"] = "QQ閱讀書架分頁沒有進展",
["QQ阅读搜索响应无效"] = "QQ閱讀搜尋回應無效",
["QQ阅读列表响应无效"] = "QQ閱讀列表回應無效",
["QQ阅读分类响应无效"] = "QQ閱讀分類回應無效",
["QQ阅读分类条件无效"] = "QQ閱讀分類條件無效",
["QQ阅读书评响应无效"] = "QQ閱讀書評回應無效",
["书评(预览 %1/%2)"] = "書評(預覽 %1/%2)",
["切换 QQ阅读账号会清除这台设备上 QQ阅读的书架、阅读进度、笔记和缓存,包括尚未同步的记录。不会删除远端书架。确定继续?"] = "切換 QQ閱讀帳號會清除此裝置上 QQ閱讀的書架、閱讀進度、筆記和快取,包括尚未同步的紀錄。不會刪除遠端書架。確定繼續?",
["缺少 QQ阅读章节位置"] = "缺少 QQ閱讀章節位置",
["这本书不在 QQ阅读书架上"] = "這本書不在 QQ閱讀書架上",
["出版新书榜"] = "出版新書榜",
["出版新知榜"] = "出版新知榜",
["出版热门榜"] = "出版熱門榜",
["女生免费榜"] = "女生免費榜",
["女生完结榜"] = "女生完結榜",
["女生封神榜"] = "女生封神榜",
["女生新书榜"] = "女生新書榜",
["女生热门榜"] = "女生熱門榜",
["男生免费榜"] = "男生免費榜",
["男生完结榜"] = "男生完結榜",
["男生封神榜"] = "男生封神榜",
["男生新书榜"] = "男生新書榜",
["男生热门榜"] = "男生熱門榜",
["QQ阅读书架与在线阅读"] = "QQ閱讀書架與線上閱讀",
["VIP 章节"] = "VIP 章節",
["书架同步"] = "書架同步",
["搜索与发现"] = "搜尋與發現",
["进度同步"] = "進度同步",
}
@@ -0,0 +1,5 @@
return function()
local copy = {}
for k, v in pairs(require("moonsource_qqreader._meta")) do copy[k] = v end
return copy
end
@@ -0,0 +1,191 @@
--[[--
QQ阅读数据映射(纯函数):详情 / 书架行 / 目录 → 领域对象。
封面不在详情里(cover 为空)。官方 getBookCover 默认尺寸 b,这里固定 jpg:
墨水屏不吃 webp。`cover/{bid%1000}/{bid}/b_{bid}.jpg`。
@module koplugin.book.moonsource_qqreader.mapper
--]]
local Text = require("utils.text")
local Mapper = {}
local SOURCE_ID = "ext.qqreader"
local COVER = "https://wfqqreader-1252317822.image.myqcloud.com/cover/%d/%s/b_%s.jpg"
--- 搜索结果页(SSR HTML)→ Book[]:每条是 `<a title=书名 href=…/book-detail/书号>` 后跟简介段。
--- 作者名被站点截断成「xx...」,只在完整时才用。
---@param html string
---@return Book[]
function Mapper.searchHtml(html)
local out, seen = {}, {}
for title, id, rest in html:gmatch('<a title="([^"]*)" href="[^"]*/book%-detail/(%d+)"(.-)</a></div>') do
if not seen[id] then
seen[id] = true
local intro = rest:match('<p class="intro"[^>]*>(.-)</p>')
local author = rest:match('/book%-writer/%d+"[^>]*>(.-)</a>')
author = author and Text.stripHtml(author)
out[#out + 1] = {
source_id = SOURCE_ID,
stable_id = id,
title = Text.xmlDecode(title),
authors = author and not author:find("%.%.%.$") and author or nil,
intro = intro and Text.stripHtml(intro),
cover = Mapper.coverUrl(id),
}
end
end
return out
end
---@param value any
---@return boolean
local function on(value)
return value == true or tonumber(value) == 1
end
--- 封面走阅文 CDN,书号即路径。实测 b_ 尺寸是 JPEG。
---@param book_id string|number
---@return string
function Mapper.coverUrl(book_id)
local id = tostring(book_id)
local n = tonumber(id)
if not n then return "" end
return COVER:format(n % 1000, id, id)
end
--- 详情 data → Book。分类用三级,没有再退二级。
---@param info table
---@return Book
function Mapper.book(info)
local id = tostring(info.bid)
local category = info.category3Name
if type(category) ~= "string" or category == "" then category = info.category2Name end
local finish = tonumber(info.finishStatus)
local status = finish == 1 and "完结" or finish == 0 and "连载" or nil
return {
source_id = SOURCE_ID,
stable_id = id,
title = info.title,
authors = info.author,
category = category,
intro = info.intro,
cover = Mapper.coverUrl(id),
meta = {
words = tonumber(info.totalWords),
status = status,
},
}
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.title,
authors = row.author,
cover = Mapper.coverUrl(id),
}
end
--- 书架行 → Book。有详情用详情,否则沿用本地完整行,都没有才退回书架行。
---@param rows table[]
---@return Book[]
function Mapper.shelfList(rows)
local books = {}
for _idx, row in ipairs(rows) do
if row.info then
books[#books + 1] = Mapper.book(row.info)
elseif row.local_book then
local book = row.local_book
if type(book.cover) ~= "string" or book.cover == "" then
book.cover = Mapper.coverUrl(row.bid or book.stable_id)
end
books[#books + 1] = book
elseif row.bid then
books[#books + 1] = Mapper.shelfBook(row)
end
end
return books
end
---@param rows table[]
---@return table[]
function Mapper.bookComments(rows)
local items = {}
for _idx, row in ipairs(rows) do
local user = row.user or {}
local title, content = row.title or "", row.content or ""
items[#items + 1] = {
id = row.commentId,
author = user.nickname,
text = title ~= "" and (title .. "\n" .. content) or content,
time = row.createTime and math.floor(row.createTime / 1000) or nil,
}
end
return items
end
--- 详情或书架行里的阅读位置。0 就是没读过。
---@param row table|nil
---@return { uid: string }|nil
function Mapper.readChapter(row)
local uid = type(row) == "table" and row.lastReadChapterId
if uid == nil or tostring(uid) == "" or tonumber(uid) == 0 then return nil end
return { uid = tostring(uid) }
end
--- 详情 inShelf:1 才在书架上。进度上传不在架上就失败,不要加回去。
---@param info table|nil
---@return boolean
function Mapper.onShelf(info)
return type(info) == "table" and on(info.inShelf)
end
--- 目录数组 → 目录。free=0 是付费章,也进目录,打开时再看是否已授权。
---@param rows table|nil
---@return BookChapter[]
function Mapper.toc(rows)
local toc = {}
for _idx, row in ipairs(type(rows) == "table" and rows or {}) do
if row.cid then
toc[#toc + 1] = {
idx = #toc + 1,
uid = tostring(row.cid),
title = row.chapterName,
vip = tonumber(row.free) == 0,
}
end
end
return toc
end
--- Fock 加密 / 乱序字体:content 是密文,要先解密再还原。
---@param info table|nil
---@return boolean
function Mapper.encrypted(info)
return type(info) == "table" and (on(info.encrypt) or on(info.fontEncrypt))
end
--- 正文还套了乱序字体(要下载 fixedFont 还原字形)。
---@param info table
---@return boolean
function Mapper.fontEncrypted(info)
return on(info.fontEncrypt)
end
--- 未授权的付费章接口仍 code=0,并带约 200 字预览。不能看正文非空。authStatus:0 未授权,1 已购,2 会员。
---@param info table|nil
---@return boolean
function Mapper.locked(info)
if type(info) ~= "table" or not on(info.chapterVipFlag) then return false end
local status = tonumber(info.authStatus)
return status ~= 1 and status ~= 2
end
return Mapper
@@ -0,0 +1,93 @@
--[[--
QQ阅读源设置:登录。
设备上扫阅文二维码(QQ阅读或起点 App)。浏览器扩展绑定保留:login/check 必须是
book.qq.com 下的 HTTPS,不能指到 passport。书架页未登录也是 200,扩展会立刻回传 Cookie。
扫码、粘贴、扩展三条路都先打 /api/user/homepage,code 不是 0 就不保存。
@module koplugin.book.moonsource_qqreader.setting
--]]
local _ = require("l10n").get("moonsource_qqreader")
local CookieLogin = require("source.cookie_login")
local SOURCE_ID = "ext.qqreader"
local Setting = {}
---@return boolean
local function loggedIn()
return require("moonsource_qqreader.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, _("QQ阅读账号标识缺失")); return
end
return CookieLogin.commitAccount(SOURCE_ID, cookie, account.id, cb, current)
end
---@type CookieLoginSpec
local SPEC = {
id = SOURCE_ID,
title = _("QQ阅读账号"),
cookie_title = _("QQ阅读登录 Cookie"),
cookie_hint = _("按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"),
logout_text = _("确定退出 QQ阅读账号?"),
loggedIn = loggedIn,
checkAsync = require("moonsource_qqreader.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 请求头;只收 QQ阅读站点的 Cookie。
---@param payload table
---@return string
function Setting.fromPayload(payload)
return CookieLogin.fromPayload(payload, "qq.com")
end
--- 浏览器扩展登录(features/cookie)。
Setting.browser = {
domain = "book.qq.com",
scope = "cookie",
-- 必须是 domain 下的 HTTPS。未登录书架页不跳 passport,校验在 apply 里打账号接口。
login = "https://book.qq.com/book-shelf",
check = "https://book.qq.com/book-shelf",
icon = "https://imgservices-1252317822.file.myqcloud.com/image/090120210101409/3a5c39e0.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_qqreader.yuewen_qr"):new({
app_id = "1450000220", area_id = "1", return_url = "https://book.qq.com/",
referer = "https://login.book.qq.com/login.html",
title = _("QQ阅读扫码登录"), caption = _("用 QQ阅读或起点 App 扫一扫"),
}, function(cookie) CookieLogin.verify(SPEC, cookie) end):start()
end)
end
---@return table[]
function Setting.rows()
local rows = {
CookieLogin.accountRow(SPEC, { callback = startQR, off_text = _("未登录 · 点此扫码") }),
CookieLogin.browserRow(),
CookieLogin.pasteRow(SPEC),
}
if loggedIn() then rows[#rows + 1] = CookieLogin.logoutRow(SPEC) end
return rows
end
--- 登录失效提示的「重新登录」直达入口(desktop.sync.promptLogin)。
Setting.login = startQR
return Setting
@@ -0,0 +1,300 @@
--[[--
QQ阅读数据源。
目录 / 章节走 book.qq.com 的 JSON 接口(client.lua)。登录是浏览器登录态的 Cookie(setting.lua);
登录后书架双向同步(source.shelf):拉取、本地加入上行、本地删除上行。
进度只到章:开书从详情的 lastReadChapterId 拉,关书经 update/reading/process 推。书不在书架上不推,也不加回去。
笔记和统计没有接口。付费章未授权时打开一页临时提示,目录标注已购 / 未购(打开过才知道)。
@module moonsource_qqreader
--]]
local Browse = require("source.browse")
local Client = require("moonsource_qqreader.client")
local Mapper = require("moonsource_qqreader.mapper")
local Shelf = require("source.shelf")
local SourceBase = require("source.base")
local Toc = require("source.toc")
local _ = require("l10n").get("moonsource_qqreader")
local QQReader = {}
-- 章节不小,预取与整本缓存逐章间隔请求。
local FETCH_INTERVAL = 1
---@return BookSourceMeta
function QQReader.meta()
return require("moonsource_qqreader.loadmeta")()
end
---@class QQReaderSource : SourceBase
local Source = setmetatable({ shelf_add = true }, { __index = SourceBase })
Source.__index = Source
---@return QQReaderSource
function QQReader.new()
local meta = QQReader.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[]|nil, err: string|nil)
---@return { cancel: fun() }
local function fillDetails(rows, cb)
local BookDB = require("book.books_db")
local cancelled, job, index, cookie = false, nil, 0, Client.cookie()
local function nextRow()
if cancelled then return end
if Client.cookie() ~= cookie then cb(nil, _("账号已变化,请重新登录")); return end
index = index + 1
local row = rows[index]
if not row then cb(rows); return end
row.local_book = BookDB.get(QQReader.meta().id, tostring(row.bid))
local intro = row.local_book and row.local_book.intro
if intro and intro ~= "" then nextRow(); return end
local pending = true
local inner = Client.detailAsync(row.bid, function(info, err)
pending = false
if cancelled then return end
if Client.cookie() ~= cookie then cb(nil, _("账号已变化,请重新登录")); return end
if info then
row.info = info
else
require("utils.log").warn("book qqreader detail failed", row.bid, err)
end
nextRow()
end)
if pending then job = inner 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, cookie = false, nil, nil, Client.cookie()
job = Client.shelfAsync(cookie, function(rows, err)
if cancelled then return end
if Client.cookie() ~= cookie then cb(nil, _("账号已变化,请重新登录")); 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, "qqreader not logged in") end
return Shelf.syncAsync(self.id, Remote, Mapper.shelfList, opts, cb)
end
--- 详情上的 lastReadChapterId 就是书架行那一章。0 是没读过。
function Source:getProgressAsync(identity, cb)
if not self:configured() then return SourceBase.defer(cb, nil, _("未登录 QQ阅读")) end
local cancelled, job, cookie = false, nil, Client.cookie()
local pending = true
local inner = Client.detailAsync(identity.stable_id, function(info, err)
pending = false
if cancelled then return end
if Client.cookie() ~= cookie then cb(nil, _("账号已变化,请重新登录")); return end
if not info then cb(nil, err); return end
local read = Mapper.readChapter(info)
if not read then cb(nil, nil, { empty = true }); return end
job = self:loadTocAsync(identity, function(toc, reason)
if cancelled then return end
if Client.cookie() ~= cookie then cb(nil, _("账号已变化,请重新登录")); return end
if not toc or #toc == 0 then cb(nil, reason or _("QQ阅读目录为空")); return end
local idx = Toc.index(self.id, identity.stable_id, read.uid)
if not idx then cb(nil, nil, { empty = true }); return end
local chapter = toc[idx]
cb({
chapter_idx = idx,
chapter_title = chapter and chapter.title,
fraction = (idx - 1) / #toc,
extra = { chapter_uid = read.uid, chapter_idx = idx },
})
end)
end)
if pending then job = inner 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, _("未登录 QQ阅读")) end
local cancelled, job = false, nil
local cookie = Client.cookie()
local pending = true
local inner = self:loadTocAsync(identity, function(toc, err)
pending = false
if cancelled then return end
if Client.cookie() ~= cookie then cb(nil, _("账号已变化,请重新登录")); 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, _("缺少 QQ阅读章节位置"))
return
end
local checking = true
local detail = Client.detailAsync(identity.stable_id, function(info, reason)
checking = false
if cancelled then return end
if Client.cookie() ~= cookie then cb(nil, _("账号已变化,请重新登录")); return end
if not info then cb(nil, reason); return end
if not Mapper.onShelf(info) then cb(nil, _("这本书不在 QQ阅读书架上")); return end
job = Client.updateReadAsync(identity.stable_id, chapter.uid, function(ok, push_err)
if cancelled then return end
if Client.cookie() ~= cookie then cb(nil, _("账号已变化,请重新登录")); return end
cb(ok and true or nil, push_err)
end)
end)
if checking then job = detail end
end)
if pending then job = inner 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, done, page) end, 200, {}, cb)
end
local RANKS = {
{ id = "rank:male-sell", title = _("男生热门榜") }, { id = "rank:male-new", title = _("男生新书榜") },
{ id = "rank:male-free", title = _("男生免费榜") }, { id = "rank:male-finish", title = _("男生完结榜") },
{ id = "rank:male-god", title = _("男生封神榜") }, { id = "rank:female-sell", title = _("女生热门榜") },
{ id = "rank:female-new", title = _("女生新书榜") }, { id = "rank:female-free", title = _("女生免费榜") },
{ id = "rank:female-finish", title = _("女生完结榜") }, { id = "rank:female-god", title = _("女生封神榜") },
{ id = "rank:publish-sell", title = _("出版热门榜") }, { id = "rank:publish-new", title = _("出版新书榜") },
{ id = "rank:publish-knowledge", title = _("出版新知榜") },
}
--- 缺省仍为男生热门榜;分类沿用旧 cate:分类号,并支持官网八段筛选节点。
---@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)
local node = opts.node or RANKS[1].id
local kind, name = node:match("^(%a+):(.+)$")
if kind == "cate" then return require("moonsource_qqreader.browse").run(opts, cb) end
local known = false
for _idx, rank in ipairs(RANKS) do if rank.id == node then known = true; break end end
if not known then return SourceBase.defer(cb, nil, _("QQ阅读分类条件无效")) end
local ranks = Browse.group(RANKS, node)
ranks.title = _("排行榜")
local groups = { ranks, Browse.group({ { id = "cate:0", title = _("分类") } }, node) }
return Browse.pages(function(page, done)
local path = "/book-rank/" .. name .. "/cycle-1" .. (page > 1 and "-" .. page or "")
return Client.listAsync(path, done)
end, opts.limit or 60, groups, cb)
end
--- 这是整书书评。官网可能只返回十五条且不给下一页游标,不能冒充完整书评。
function Source:bookReviewsAsync(identity, cb)
return Client.bookCommentsAsync(identity.stable_id, function(data, err)
if not data then cb(nil, err); return end
local items = Mapper.bookComments(data.comments)
local total = tonumber(data.commentCount)
cb({
title = #items < total and require("ffi/util").template(_("书评(预览 %1/%2)"), #items, total) or _("书评"),
items = items,
total = total,
more = #items < total,
})
end)
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(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, _("QQ阅读目录为空")); 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
return open(self, identity, identity.book, opts, {
loadToc = function(ref, done) return self:loadTocAsync(ref, done) end,
fetchContent = Chapter.vipFetcher(self, Client.contentAsync, true),
}, cb)
end
function Source:prefetchChaptersAsync(identity, toc, from_idx, count, cb)
local Chapter = require("source.chapter")
return Chapter.prefetchAsync(identity, identity.book, toc, from_idx, count, {
fetchContent = Chapter.vipFetcher(self, Client.contentAsync, false),
interval_seconds = FETCH_INTERVAL,
}, cb)
end
function Source:cacheAllChaptersAsync(identity, on_progress, cb, range)
local Chapter = require("source.chapter")
return Chapter.cacheAllAsync(self, identity, Chapter.vipFetcher(self, Client.contentAsync, false), on_progress, cb,
FETCH_INTERVAL, range)
end
return QQReader
@@ -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_qqreader.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_qqreader.yuewen_fonts.scramble` 的 HTML 解析拼起来。
字体是随章下发的,写临时文件给 FreeType 读;参考字签名会落盘缓存。
@module moonsource_qqreader.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_qqreader.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_qqreader.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_qqreader.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