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

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

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
+80
View File
@@ -0,0 +1,80 @@
--[[-- QQ阅读进度多阶段取消与换号竞态。 @module tests.moonsource_qqreader.async_spec --]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local cookie, detail_delay, push_delay, late = "111", false, false, nil
local cancelled, pushed = {}, 0
local toc = { { uid = "1", title = "one" }, { uid = "2", title = "two" } }
package.preload["source.toc"] = function() return { index = function() return 2 end } end
package.preload["moonsource_qqreader.client"] = function()
return {
cookie = function() return cookie end,
detailAsync = function(_id, cb)
local function done() cb({ title = "fixture", inShelf = 1, lastReadChapterId = 2 }) end
if detail_delay then late = done else done() end
return { cancel = function() cancelled.detail = true end }
end,
updateReadAsync = function(_id, _chapter, cb)
pushed = pushed + 1
if push_delay then late = function() cb(true) end else cb(true) end
return { cancel = function() cancelled.push = true end }
end,
bookCommentsAsync = function(_id, cb)
cb({ commentCount = 32, comments = {
{ commentId = "c1", content = "fixture", user = { nickname = "author" } },
} })
return { cancel = function() end }
end,
}
end
local source = require("moonsource_qqreader.source").new()
local identity = { source_id = "ext.qqreader", stable_id = "9" }
do
source.loadTocAsync = function(_self, _identity, cb)
late = function() cb(toc) end
return { cancel = function() cancelled.toc = true end }
end
local called = false
local job = source:getProgressAsync(identity, function() called = true end)
job.cancel()
Assert.is_true(cancelled.toc)
Assert.is_nil(cancelled.detail, "同步详情不能覆盖下一阶段句柄")
late()
Assert.is_false(called)
end
for _idx, stage in ipairs({ "detail", "push" }) do
cancelled, detail_delay, push_delay = {}, stage == "detail", stage == "push"
source.loadTocAsync = function(_self, _identity, cb)
cb(toc)
return { cancel = function() cancelled.toc = true end }
end
local called = false
local job = source:putProgressAsync(identity, { chapter_idx = 2 }, function() called = true end)
job.cancel()
Assert.is_true(cancelled[stage])
Assert.is_nil(cancelled.toc)
late()
Assert.is_false(called)
end
do
cookie, detail_delay, pushed = "111", true, 0
local result, err
source:putProgressAsync(identity, { chapter_idx = 2 }, function(value, reason) result, err = value, reason end)
cookie = "222"
late()
Assert.is_nil(result)
Assert.matches(err, "账号已变化")
Assert.eq(pushed, 0)
end
do
local page
source:bookReviewsAsync(identity, function(value) page = value end)
Assert.len(page.items, 1)
Assert.eq(page.total, 32)
Assert.is_true(page.more)
Assert.matches(page.title, "预览 1/32")
end
+85
View File
@@ -0,0 +1,85 @@
--[[-- QQ阅读动态分类、筛选、旧节点、多页和取消回归。 @module tests.moonsource_qqreader.browse_spec --]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local Stubs = require("support.stubs")
local requests, cancelled, delayed, late = {}, {}, false, nil
local KEYS = { "categoryId2", "categoryId3", "finishStatus", "priceStatus", "words", "updateTime", "orderBy", "pageNo" }
package.preload["moonsource_qqreader.client"] = function()
return { categoryAsync = function(path, cb)
requests[#requests + 1] = path
local idx = #requests
local params, position = {}, 0
for value in path:gmatch("[^-]+") do position = position + 1; params[KEYS[position]] = tonumber(value) end
local data = { total = 0, params = params, books = {}, categoryList = {
{ name = "男生", subCategories = { { value = 20001, text = "玄幻" } } },
{ name = "女生", subCategories = { { value = 30013, text = "古言" } } },
{ name = "出版", subCategories = { { value = 13100, text = "小说" } } },
} }
for _idx, key in ipairs({ "categoryId3", "finishStatus", "priceStatus", "words", "updateTime", "orderBy" }) do
data[key] = { title = key == "priceStatus" and "属性" or key, items = {
{ value = 0, text = "全部" }, { value = 3, text = "付费" },
} }
end
cb(data)
return { cancel = function() cancelled[idx] = true end }
end,
listAsync = function(url, cb)
local path = url:match("^/book%-cate/(.+)$")
requests[#requests + 1] = path
local idx, page = #requests, tonumber(path:match("(%d+)$"))
local books = {}
for item = 1, 20 do books[item] = { source_id = "ext.qqreader", stable_id = tostring((page - 1) * 20 + item) } end
if delayed and page == 2 then late = function() cb(books) end else cb(books) end
return { cancel = function() cancelled[idx] = true end }
end }
end
local Library = require("moonsource_qqreader.browse")
do
local result, err
Library.run({ node = "cate:20001", limit = 60 }, function(value, reason) result, err = value, reason end)
Assert.is_nil(err)
Assert.len(result.data, 60)
Assert.len(requests, 4)
Assert.eq(requests[1], "20001-0-0-0-0-0-0-1")
Assert.eq(requests[4], "20001-0-0-0-0-0-0-3")
Assert.eq(result.groups[1].title, "男生分类")
Assert.eq(result.groups[2].title, "女生分类")
Assert.eq(result.groups[3].title, "出版分类")
Assert.eq(result.groups[4].title, "筛选")
local found = false
for _idx, group in ipairs(result.groups) do
if group.title == "属性" then
for _i, chip in ipairs(group.chips) do
if chip.title == "付费" then
found = true
Assert.eq(chip.id, "cate:20001-0-0-3-0-0-0-1")
end
end
end
end
Assert.is_true(found, "属性筛选项单独成组,标题不再拼选中标记")
end
do
requests, cancelled, delayed = {}, {}, true
local called = false
local job = Library.run({ node = "cate:20001-20002-1-3-2-1-2-1" }, function() called = true end)
Assert.eq(requests[1], "20001-20002-1-3-2-1-2-1")
job.cancel()
Assert.is_true(cancelled[3])
late()
Assert.is_false(called)
Assert.len(requests, 3)
end
do
requests = {}
local result, err
Library.run({ node = "cate:20001--0" }, function(value, reason) result, err = value, reason end)
Stubs.flush()
Assert.is_nil(result)
Assert.matches(err, "分类条件无效")
Assert.len(requests, 0)
end
+207
View File
@@ -0,0 +1,207 @@
--[[-- QQ阅读正文取消、身份快照、权限复查与坏响应回归。 @module tests.moonsource_qqreader.client_spec --]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local CookieOf = require("support.cookie")
local JSON = require("support.json_stub")
local cfg, requests, replies, late, cancelled = {}, {}, {}, nil, {}
local fock_delay, fock_called, fock_cancelled, fock_uid = false, 0, false, nil
local expired
package.preload["json"] = function() return JSON end
package.preload["utils.settings"] = function() return { getSource = function() return cfg end } end
package.preload["source.auth"] = function()
return { ok = function() end, expire = function(_id, msg) expired = msg; return msg end }
end
package.preload["http.request"] = function()
return { get = function(url, opts, cb)
local idx = #requests + 1
requests[idx] = { url = url, opts = opts }
local reply = table.remove(replies, 1)
local function done()
if reply.before then reply.before() end
cb(reply.body, reply.err, reply.res)
end
if reply.delay then late = done else done() end
return { cancel = function() cancelled[idx] = true end }
end }
end
package.preload["moonsource_qqreader.fock"] = function()
return { chapterAsync = function(_info, _font, _chapter, _pool, _version, uid, cb)
fock_called, fock_uid = fock_called + 1, uid
local function done() cb("decoded fixture") end
if fock_delay then late = done else done() end
return { cancel = function() fock_cancelled = true end }
end }
end
local Client = require("moonsource_qqreader.client")
local Mapper = require("moonsource_qqreader.mapper")
local encrypted = '{"code":0,"data":{"content":"encrypted","encrypt":true,"fontEncrypt":true,'
.. '"chapterVipFlag":1,"authStatus":1,"fontResponse":{"fixedFontTtf":"https://example.invalid/font.ttf"}}}'
local piracy = '{"code":0,"data":{"fkp":"d2luZG93Lm9ua2V5Zm9jdXMoImtleXBvb2wiLCAyKQ==","fuid":1234567890123456}}'
local function reset()
cfg.cookie = "ywguid=111"
requests, replies, late, cancelled = {}, {}, nil, {}
fock_delay, fock_called, fock_cancelled, fock_uid, expired = false, 0, false, nil, nil
end
for stage = 1, 5 do
reset()
replies = { { body = encrypted }, { body = piracy }, { body = encrypted }, { body = "font fixture" } }
if stage <= 4 then replies[stage].delay = true else fock_delay = true end
local called = false
local job = Client.contentAsync("9", "1", function() called = true end)
local count = #requests
Assert.eq(count, math.min(stage, 4))
job.cancel()
if stage <= 4 then Assert.is_true(cancelled[stage]) else Assert.is_true(fock_cancelled) end
late()
Assert.is_false(called, "取消后迟到回调不能返回正文")
Assert.eq(#requests, count, "取消后不能启动下一阶段")
end
do
reset()
replies = {
{ body = encrypted, before = function() cfg.cookie = "ywguid=222" end },
{ body = piracy }, { body = encrypted }, { body = "font fixture" },
}
local text, err
Client.contentAsync("9", "1", function(value, reason) text, err = value, reason end)
Assert.eq(text, "decoded fixture")
Assert.is_nil(err)
for idx = 1, 3 do Assert.eq(CookieOf(requests[idx]), "ywguid=111") end
Assert.matches(requests[3].url, "fuid=1234567890123456")
Assert.eq(fock_uid, "1234567890123456")
Assert.is_nil(requests[4].opts.headers, "字体请求不带账号 Cookie")
end
do
reset()
replies = { { body = encrypted }, { body = piracy },
{ body = '{"code":0,"data":{"content":"preview","chapterVipFlag":1,"authStatus":0}}' } }
local text, err, kind
Client.contentAsync("9", "1", function(value, reason, result) text, err, kind = value, reason, result end)
Assert.is_nil(text)
Assert.eq(kind, "unpaid")
Assert.matches(err, "未购买")
Assert.eq(fock_called, 0)
Assert.is_true(Mapper.locked({ chapterVipFlag = 1, authStatus = 3 }))
end
do
reset()
replies = { { body = '{"code":0}' } }
local text, err
Client.contentAsync("9", "1", function(value, reason) text, err = value, reason end)
Assert.is_nil(text)
Assert.matches(err, "章节内容为空")
end
for _idx, body in ipairs({
'{"code":0}', '{"code":0,"data":{}}',
'{"code":0,"data":{"bookList":[false]}}',
'{"code":0,"data":{"bookList":[],"hasNext":true}}',
}) do
reset()
replies = { { body = body } }
local rows, err
Client.shelfAsync(cfg.cookie, function(value, reason) rows, err = value, reason end)
Assert.is_nil(rows, "坏书架不能当合法空快照 reconcile")
Assert.is_true(type(err) == "string")
end
do
reset()
replies = {
{ body = '{"code":0,"data":{"bookList":[{"bid":1}],"hasNext":true}}' },
{ body = '{"code":0,"data":{"bookList":[{"bid":2}],"hasNext":false}}', delay = true },
}
local called = false
local job = Client.shelfAsync(cfg.cookie, function() called = true end)
job.cancel()
Assert.is_true(cancelled[2], "同步第一页不能覆盖第二页取消句柄")
late()
Assert.is_false(called)
end
do
reset()
local ok, err, account
replies = { { body = '{"code":0,"data":{"nickname":"fixture"}}' } }
Client.loginCheckAsync("uid=123; usid=fixture", function(value, reason, id) ok, err, account = value, reason, id end)
Assert.is_true(ok)
Assert.eq(account.id, "123")
replies = { { body = '{"code":0,"data":{"nickname":"fixture"}}' } }
Client.loginCheckAsync("ywguid=123; uid=456", function(value, reason) ok, err = value, reason end)
Assert.is_nil(ok)
Assert.matches(err, "账号标识缺失")
replies = { { err = "redirect", res = { code = 302 } } }
Client.loginCheckAsync(cfg.cookie, function(value, reason) ok, err = value, reason end)
Assert.is_nil(ok)
Assert.eq(expired, err)
expired = nil
replies = { { err = "offline" } }
Client.loginCheckAsync(cfg.cookie, function(value, reason) ok, err = value, reason end)
Assert.eq(err, "offline")
Assert.is_nil(expired, "网络失败不能注销有效账号")
end
do
reset()
replies = { { body = '{"code":0,"data":{"bookList":[{"bid":9,"title":"fixture"}],"hasNext":true}}' } }
local rows, err, more
Client.searchAsync("fixture", function(value, reason, next_page) rows, err, more = value, reason, next_page end, 2)
Assert.len(rows, 1)
Assert.is_nil(err)
Assert.is_true(more)
Assert.matches(requests[1].url, "keyWord=fixture")
Assert.matches(requests[1].url, "pageNo=2")
Assert.is_nil(CookieOf(requests[1]))
Assert.is_nil(requests[1].opts.headers.Origin, "同源 GET 不发送 Origin")
replies = { { body = '{"code":0,"data":{}}' } }
Client.searchAsync("fixture", function(value, reason) rows, err = value, reason end)
Assert.is_nil(rows)
Assert.matches(err, "搜索响应无效")
replies = { { body = '<html id="__nuxt">challenge</html>' } }
Client.listAsync("/book-rank/male-sell/cycle-1", function(value, reason) rows, err = value, reason end)
Assert.is_nil(rows)
Assert.matches(err, "列表响应无效")
end
do
reset()
local filters = "20001-0-0-0-0-0-0-1"
replies = { { body = '{"code":0,"data":{"categoryList":[],"books":[],"total":0,"params":'
.. '{"categoryId2":20001,"categoryId3":0,"finishStatus":0,"priceStatus":0,"words":0,"updateTime":0,"orderBy":0,"pageNo":1}}}' } }
local data, err
Client.categoryAsync(filters, function(value, reason) data, err = value, reason end)
Assert.is_nil(err)
Assert.is_true(type(data) == "table")
Assert.eq(requests[1].opts.headers.Referer, "https://book.qq.com/book-cate/" .. filters)
Assert.is_nil(requests[1].opts.headers.Origin)
replies = { { body = '<div class="book-cate main"><a title="fixture" href="/book-detail/9">'
.. '<p class="intro">fixture</p></a></div></div>' } }
Client.listAsync("/book-cate/" .. filters, function(value, reason) data, err = value, reason end)
Assert.is_nil(err)
Assert.len(data, 1, "JSON 假空不代表官网 SSR 分类没有书")
end
do
reset()
replies = { { body = '{"code":0,"data":{"commentCount":32,"cursor":"","comments":'
.. '[{"commentId":"c1","title":"title","content":"fixture","user":{"nickname":"author"},"createTime":1620000000000}]}}' } }
local data
Client.bookCommentsAsync("9", function(value) data = value end)
local items = Mapper.bookComments(data.comments)
Assert.eq(items[1].author, "author")
Assert.eq(items[1].text, "title\nfixture")
Assert.eq(items[1].time, 1620000000)
Assert.eq(data.commentCount, 32)
Assert.is_nil(CookieOf(requests[1]))
replies = { { body = '{"code":0,"data":{"commentCount":1,"comments":[false]}}' } }
local err
Client.bookCommentsAsync("9", function(value, reason) data, err = value, reason end)
Assert.is_nil(data)
Assert.matches(err, "书评响应无效")
end
+31
View File
@@ -0,0 +1,31 @@
--[[--
QQ阅读已购 VIP 章节解密(Fock 转译版)与乱序还原离线用例。
@module tests.source.qqreader_fock_spec
--]]
---@diagnostic disable: undefined-field
local Assert = require("support.assert")
local Sample = require("support.qqreader_fock_sample")
local Fock = require("moonsource_qqreader.fock")
local Scramble = require("moonsource_qqreader.yuewen_fonts.scramble")
local plain, err = Fock.decrypt(Sample.content, Sample.chapter_id, Sample.keypool, Sample.version, Sample.fuid)
Assert.is_nil(err)
Assert.eq(#plain, 20816)
Assert.eq(plain:sub(1, 15), '<p class="p0"><')
-- 乱序还原:order 重排、first-letter 藏字 + ::after / attr() 补字、sy-0 占位丢弃、其余码位按字形表替换
local css = "yb{order:1;}ya{order:2;}yc{order:3;}"
.. ".p1 ya::first-letter{font-size:0}.p1 ya::after{content:'乙'}"
.. ".p1 yc::after{content:attr(k)}"
local html = '<p class="p1"><ya>X</ya><yc k="丙"></yc><yb>甲</yb></p>'
.. '<p>  <y class="sy-0">占</y>正<y class="sy-1">䤉</y>文䨀</p>'
local paragraphs = Scramble.paragraphs(html, css)
Assert.eq(paragraphs[1], "甲乙丙")
local rare, han = Scramble.codes(paragraphs)
Assert.eq(#rare, 2)
Assert.eq(#han, 5)
-- randomFont:认得的换、认不出的 □;fixedFont:认得的换、认不出的 □、字体里没有的码位(nil)原样留
Assert.eq(Scramble.text(paragraphs, { [0x4909] = "来" }, { [0x6B63] = "对", [0x6587] = false }),
"甲乙丙\n  对来□□")
+237
View File
@@ -0,0 +1,237 @@
--[[--
QQ阅读书架分页、目录 / 正文映射与 Cookie 解析离线用例。
@module tests.source.qqreader_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local CookieOf = require("support.cookie")
local JSONStub = require("support.json_stub")
package.preload["json"] = function()
return { decode = JSONStub.decode, encode = JSONStub.encode }
end
local cfg = {}
package.preload["utils.settings"] = function()
return { getSource = function() return cfg end }
end
local expired
package.preload["source.auth"] = function()
return { expire = function(_, msg) expired = msg; return msg end, ok = function() end }
end
local requests, replies = {}, {}
package.preload["http.request"] = function()
return {
get = function(url, opts, cb)
requests[#requests + 1] = { method = "GET", url = url, opts = opts }
local reply = table.remove(replies, 1)
cb(reply.body, reply.err, reply.res)
return { cancel = function() end }
end,
post = function(url, body, opts, cb)
requests[#requests + 1] = { method = "POST", url = url, body = body, opts = opts }
local reply = table.remove(replies, 1)
cb(reply.body, reply.err, reply.res)
return { cancel = function() end }
end,
}
end
package.loaded["moonsource_qqreader.client"] = nil
package.loaded["moonsource_qqreader.mapper"] = nil
package.loaded["moonsource_qqreader.setting"] = nil
local Client = require("moonsource_qqreader.client")
local Mapper = require("moonsource_qqreader.mapper")
local Setting = require("moonsource_qqreader.setting")
do
local book = Mapper.book({
bid = 54425396, title = "大生意人", author = "赵之羽",
category2Name = "小说", category3Name = "影视小说",
totalWords = 452453, intro = "生意人", cover = "",
})
Assert.eq(book.stable_id, "54425396")
Assert.eq(book.category, "影视小说")
Assert.eq(book.cover, "https://wfqqreader-1252317822.image.myqcloud.com/cover/396/54425396/b_54425396.jpg")
Assert.eq(book.meta.words, 452453)
Assert.eq(Mapper.book({ bid = 1, title = "甲", category2Name = "小说" }).category, "小说")
end
do
local books = Mapper.shelfList({
{ bid = 1, title = "短", info = { bid = 1, title = "全名", author = "甲", totalWords = 3 } },
{ bid = 2, title = "截断", local_book = { stable_id = "2", title = "本地", cover = "" } },
{ bid = 3, title = "兜底", author = "乙" },
})
Assert.eq(books[1].title, "全名")
Assert.eq(books[2].cover, "https://wfqqreader-1252317822.image.myqcloud.com/cover/2/2/b_2.jpg")
Assert.eq(books[3].title, "兜底")
Assert.eq(books[3].authors, "乙")
end
do
local toc = Mapper.toc({
{ cid = 1, chapterName = "第1章", free = 1 },
{ cid = 5, chapterName = "第5章", free = 0 },
})
Assert.len(toc, 2)
Assert.eq(toc[1].uid, "1")
Assert.is_false(toc[1].vip)
Assert.eq(toc[2].idx, 2)
Assert.is_true(toc[2].vip)
Assert.is_nil(Mapper.readChapter({ lastReadChapterId = 0 }))
Assert.eq(Mapper.readChapter({ lastReadChapterId = 5 }).uid, "5")
Assert.is_false(Mapper.onShelf({ inShelf = 0 }))
Assert.is_true(Mapper.onShelf({ inShelf = 1 }))
end
do
local preview = { chapterVipFlag = 1, authStatus = 0, content = "预览", encrypt = false, fontEncrypt = false }
Assert.is_true(Mapper.locked(preview))
Assert.is_false(Mapper.encrypted(preview))
Assert.is_false(Mapper.locked({ chapterVipFlag = 1, authStatus = 1, content = "已购" }))
Assert.is_false(Mapper.locked({ chapterVipFlag = 1, authStatus = 2, content = "会员" }))
Assert.is_false(Mapper.locked({ chapterVipFlag = 0, authStatus = 1, content = "免费" }))
Assert.is_true(Mapper.encrypted({ encrypt = true, content = "乱码" }))
Assert.is_true(Mapper.encrypted({ fontEncrypt = 1 }))
end
do
Assert.eq(Setting.parseCookie("ywguid=g; ywTicket=t; bad name=1"), "ywTicket=t; ywguid=g")
Assert.eq(Setting.browser.domain, "book.qq.com")
Assert.eq(Setting.browser.login:match("^https://([^/]+)"), Setting.browser.domain)
Assert.eq(Setting.browser.check:match("^https://([^/]+)"), Setting.browser.domain)
Assert.eq(Setting.browser.login:match("^https://"), "https://")
Assert.eq(Setting.fromPayload({ cookies = {
{ domain = ".qq.com", name = "ywguid", value = "g" },
{ domain = "book.qq.com", name = "ywTicket", value = "t" },
{ domain = "yuewen.com", name = "x", value = "y" },
} }), "ywTicket=t; ywguid=g")
end
-- 置顶和普通列表拼在一起,翻页直到 hasNext 为假。同号去重。
do
cfg.cookie = "ywguid=g"
requests, replies = {}, {
{ body = '{"code":0,"data":{"topBookList":[{"bid":1,"title":"甲"}],"bookList":[{"bid":2,"title":"乙"}],"hasNext":true}}' },
{ body = '{"code":0,"data":{"topBookList":[],"bookList":[{"bid":2,"title":"乙"},{"bid":3,"title":"丙"}],"hasNext":false}}' },
}
local rows, err
Client.shelfAsync(cfg.cookie, function(v, e) rows, err = v, e end)
Assert.is_nil(err)
Assert.len(rows, 3)
Assert.eq(rows[3].bid, 3)
Assert.matches(requests[1].url, "pageNo=1")
Assert.matches(requests[1].url, "pageSize=100")
Assert.eq(CookieOf(requests[1]), "ywguid=g")
Assert.matches(requests[2].url, "pageNo=2")
end
-- 分页没有页数上限:超过 50 页照样翻到底
do
requests, replies = {}, {}
for i = 1, 60 do
replies[#replies + 1] = { body = ('{"code":0,"data":{"topBookList":[],"bookList":[{"bid":%d,"title":"书"}],"hasNext":%s}}')
:format(i, i < 60 and "true" or "false") }
end
local rows, err
Client.shelfAsync(cfg.cookie, function(v, e) rows, err = v, e end)
Assert.is_nil(err)
Assert.len(rows, 60)
Assert.len(requests, 60)
end
-- 已保存的 Cookie 收到 -4 才标失效。校验新 Cookie 不污染旧登录态。
do
expired = nil
cfg.cookie = "ywguid=old"
requests, replies = {}, { { body = '{"code":-4,"msg":"登陆鉴权失败"}' } }
local ok, err
Client.loginCheckAsync("ywguid=123", function(v, e) ok, err = v, e end)
Assert.is_nil(ok)
Assert.matches(err, "扫一扫")
Assert.is_nil(expired)
requests, replies, expired = {}, { { body = '{"code":-4,"msg":"登陆鉴权失败"}' } }, nil
Client.loginCheckAsync(cfg.cookie, function(v, e) ok, err = v, e end)
Assert.matches(err, "扫一扫")
Assert.eq(expired, err)
requests, replies = {}, { { body = '{"code":0,"data":{"nickname":"甲"}}' } }
Client.loginCheckAsync("ywguid=123", function(v, e) ok, err = v, e end)
Assert.is_true(ok)
end
-- 加入 / 删除 / 进度都是 JSON。进度不传章内偏移。
do
cfg.cookie = "ywguid=g"
requests, replies = {}, { { body = '{"code":0}' } }
local ok
Client.addAsync("9", function(v) ok = v end)
Assert.is_true(ok)
Assert.eq(requests[1].url, "https://book.qq.com/api/bookshelf/add")
Assert.eq(JSONStub.decode(requests[1].body).bid, 9)
Assert.eq(requests[1].opts.content_type, "application/json")
requests, replies = {}, { { body = '{"code":0}' } }
Client.removeAsync("9", function(v) ok = v end)
Assert.is_true(ok)
Assert.eq(JSONStub.decode(requests[1].body).bids[1], 9)
requests, replies = {}, { { body = '{"code":0}' } }
Client.updateReadAsync("9", "11", function(v) ok = v end)
Assert.is_true(ok)
local body = JSONStub.decode(requests[1].body)
Assert.eq(body.bid, 9)
Assert.eq(body.lastReadChapterId, 11)
Assert.is_nil(body.lastReadOffset)
end
-- 付费预览和字体加密都不当正文,哪怕 content 非空。
do
cfg.cookie = "ywguid=g"
requests, replies = {}, {
{ body = '{"code":0,"data":{"content":"预览两百字","chapterVipFlag":1,"authStatus":0,"encrypt":false,"fontEncrypt":false}}' },
}
local text, err
Client.contentAsync("9", "5", function(v, e) text, err = v, e end)
Assert.is_nil(text)
Assert.eq(err, "QQ阅读 VIP 章节未购买")
-- 加密章:先读(发现加密)→ piracy 取 fuid / fkp → 带 fuid 重读;fkp 无效就明确失败
local enc = '{"code":0,"data":{"content":"乱码","encrypt":true,"fontEncrypt":false,"chapterVipFlag":0,"authStatus":1}}'
requests, replies = {}, {
{ body = enc },
{ body = '{"code":0,"data":{"fkp":"","fuid":"u1"}}' },
{ body = enc },
}
Client.contentAsync("9", "1", function(v, e) text, err = v, e end)
Assert.is_nil(text)
Assert.eq(err, "QQ阅读章节解密失败")
Assert.matches(requests[2].url, "/user/index/piracy")
Assert.matches(requests[3].url, "fuid=u1")
requests, replies = {}, {
{ body = '{"code":0,"data":{"content":"  甲\\r\\n  乙","chapterVipFlag":0,"authStatus":1,"encrypt":false}}' },
}
Client.contentAsync("9", "1", function(v, e) text, err = v, e end)
Assert.eq(text, "  甲\r\n  乙")
Assert.is_nil(err)
end
do
local item = '<a title="%s" href="//book.qq.com/book-detail/%s" class="wrap"><p class="intro">简&amp;介</p>'
.. '<a href="//book.qq.com/book-writer/1"><span>%s</span></a></a></div>'
local books = Mapper.searchHtml(item:format("甲", "11", "乙") .. item:format("丙", "12", "丁...")
.. item:format("甲", "11", "乙"))
Assert.len(books, 2)
Assert.eq(books[1].stable_id, "11")
Assert.eq(books[1].authors, "乙")
Assert.eq(books[1].intro, "简&介")
Assert.is_nil(books[2].authors)
Assert.eq(books[1].cover, "https://wfqqreader-1252317822.image.myqcloud.com/cover/11/11/b_11.jpg")
end
+51
View File
@@ -0,0 +1,51 @@
--[[-- QQ阅读:新账号直接替换,不查旧登录、不弹换号确认。 @module tests.moonsource_qqreader.setting_spec --]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local Theme = require("support.theme_stubs")
Theme.install()
local cfg, prepared = {}, 0
package.preload["utils.settings"] = function()
return { getSource = function() return cfg end, saveSource = function() end }
end
package.preload["moonsource_qqreader.client"] = function()
return {
cookie = function() return cfg.cookie end,
loginCheckAsync = function(cookie, cb)
Assert.is_true(cookie ~= "old")
cb(true, nil, { id = cookie == "same" and "111" or "222" })
return { cancel = function() end }
end,
}
end
package.preload["source.registry"] = function()
return { reload = function() end, invalidate = function() end,
resolve = function() return { capabilities = function() return { shelf_add = true } end } end }
end
package.preload["reader.session"] = function() return { current = function() return nil end } end
package.preload["book.books_db"] = function()
return { prepareAccountSync = function(id, shelf_add)
Assert.eq(id, "ext.qqreader")
Assert.is_true(shelf_add)
Assert.eq(cfg.cookie, "old")
prepared = prepared + 1
return true
end }
end
require("source.cookie_login").fromPayload = function(payload) return payload.cookie end
local Setting = require("moonsource_qqreader.setting")
local function apply(cookie)
local ok
Setting.browser.apply({ cookie = cookie }, function(result) ok = result end)
Assert.is_true(ok)
end
cfg = { cookie = "old", account_id = "111" }
apply("same")
Assert.eq(prepared, 0)
cfg = { cookie = "old", account_id = "111" }
apply("new")
Assert.eq(prepared, 1)
Assert.eq(cfg.account_id, "222")
Assert.is_nil(Theme.last("confirm"))
cfg = { cookie = "old" }
apply("same")
Assert.eq(prepared, 2)
+13
View File
@@ -0,0 +1,13 @@
--[[--
QQ阅读已购 VIP 章节的真实密文样本(只有密文,明文不入库)。fuid 是 piracy 接口给的样本值。
@module tests.support.qqreader_fock_sample
--]]
return {
content = "/DLEN3ulhPrMfHQMzglxajqOePvETNEGTphq19KkLXm16e4yU1CeWaUM7yMboNYNNFgcl5i1u6tKiN/0ERNFJeu7fPRdyOfFochBJ3Qnpf8oA6W+m668WNm+mcXV3/radDp4OaueWJ2EC+Y0oUK5GMFjcZTYqaDKwMxCoe32QKzDyMSviL3rlXNfNEwegY6dxgFUqbE5FxKcoiPnLQNFze2UczkrLQQDCtTj2Wqawceka05dL61iNgs42xOmFOra6N+jd+7FINxLyKgsZzaEM+fW0yZUnVlA9OVpApPRFnr4xoa0d4VSBOlBx2bURlv15d6+CldYPTUe8F+AVF3F9+2xacNL0TfE65kC9FlXiXt8V/Omgeeb4jxFNIhE7164tWCiZViWON3JwfWkKJux/aDs1E68Umm2W7H7r1pipODmzHq04HCpl7oDjcsSZutY9jh22fYBTeaXUk4+zj5wH1ydd1e01uR/Hp8dSCDSB6CPcVn7wvVeWBTYR7E9ZG+PxxFpjfXsbkRIJnJripHzd+MURohcpGaOA8YdB7+J+mof/eRyIE5s8A61dYZR/MNoIxIM97mGzyOuI/h+pJfDeIIjthFVbm2Yn9T3WmkO0gCmpfOXLr2l/liBHOg4kgvrwW6Fon536lkXKoUQc2jdmrZyGFPY1Lx5hbzbWYKBoUZTsLkPoK2Zc4X+YHoR/qYes3aylJI1jcTvR2Z5wZ6z/uffsLawnYpXd5pH50TXFDC00gw7X3EzyekZnRBNzpR0y6pDDLSaQw096SIIPWmxeeKZgKEuHId7eqCXphTL3L0bGqPfTN8uUEIFeo0Jw7mFVVrf75AOfIKYGekVKhOZu14yBWiCC21W4bxC1Tgq1lS9jQLgP5ct0oyMEiBKblwUeVwncEvLfIU/03ISwthdA+yN9UzgPrvOWDmWM8ME6z7kqKwgVa1V4TnL2IMe24HYrmCrJy5MtspNto+jsio/+g8OIuH6Av++6cFLxkTJysYKSJSSmnTktHI3Od6z1aI/lBCrfdgtqHfp1mDirvqG+H3nAm93luk3JES3l+RV4xtVfyboILm0idtOdeQxzDAeSGNr+54D+J4zJqsuq531upfuITMEJJ/kAGfL9FmAmrczlBQRuZQnYl54jWMfxXQxu5ZI2whdkzWbcsRW2bDtmrjL6KCnzhb7hD0WR+B+EWqHbrHQZ3ag0ystj8JS1K9bYBN9EYKeoeH8Hg1Wd3aABgQ1H7FbIvhNuGyNGCec6fewPa91qWzHrxb955LJJAh8F7OZ2eNdIy9/Ou+g9xspwsttP0PaJLCB+HTRVVYVN3RuUoSxsLWYZvy4jKZfKuseZeHa2JiIfUNXhbZt7Mn7VoWCQ3n//Mjd/olZBX3L+ZOzhsZ4rVNipx+P60s1dHO33tIoWCS0X1Ps/QDfpR1w2OVSvZk90Hai1lmXc0R8nAL4PAtjv1eJp8L2DioAT1qIljKAefvJOwuroICj9qq3m4JBKF/ZUvuuT3qYlIDjCuLTrGSq5wM5zV0znzBiVj9ZLwKl6igHt9oMXBxeEvRH1ffpqrAyjir/EcwXKhAk5wx9J0+JNfWr4t3n2RK3fsMjJ+d6Lwpmae8stLG1WLLHITfv5+ueMcGH5gHnl4tJaYd8aLPy7wkYRWNexYPnvx2YQXMJep/c3V0JdrirlA9jZcSXL+HEvMihGAX9P6lAvL6V4ocTqZKauDh/orw10vdNpQbVrOs0uPB51U1XCQ7wsnssrdGpxdycq0WxBH+CG527TCbTl83v3hVpYfSvvfFbnB/K2edSZjJNn20ur5R7cQbUPHocsp3202KfbltC8PbhJcdK0iPAWz5aSKVJMzmv+zZUah+jdnmhjLhuHgBHdz3wy74NBm/8ZL9YogKzqLDwDG/+LuQv9nHamNCUBt1CpS86zIy18Gb7TPLrGSx9RFrKVlyejYuC4EmNI+588oTfRkdxaniMgNS+/6/YXIVeQRxjgGwCzD94nZY5WJoJpj1XhDnKtNUN2rg+nGsgj9sODW4QUeqcSjmLJX9f8V8i7HpbBbrVrqgOJixz++0EGK+cOOuE7RwTzORA8CNw4amTHjb4jLIVJZ2a6DvdYSveIDL3vOeyN55efmIQqegScWzOEiq9tq9R6nZXXUGqVJ1/OA3JMGmjNY6S3eLFbJlNqQmxIyVIhwOlZiy6ZBgTd7aswhMPFLSnknz8ZjHMAh473GDKW7YCSfzEpu2QklyG88V3qLgNGvhqnz3gpOWLF7sDTydr2Y2D1FuoMRRn2f1sGdoU2o4HUYhi9Pb+EmnGeXRRTQeUoCy+VS1GqFZUZznwIF7GROnnUnfPon5lETsUvfGHB6inL5PgYCkVerNs4BoQwob5OixsZVm+Hud3TObbqSmvU/sRGV/0gV5Nm7m3cJfl12cPEzNsz1/t4G3FAf7fymA0UMpjijK5RfFuFwV06tDjBTRNPKvksX047bsh0Ii/9fdkuWFcbIUSMXYvRCvmMP9Lrkx5GtnDKMQ9cPq8oRxwwkFBSri6MS4al30oZDvKD8jUzKNgkzuJ9IqnLQRSo5zrPqvcQD1IfU4G+VquPHjOngWTa4hgnliQ3rpMvUGk2xkdlykRkiZVwZyWN1cFvNFbEKkuFpLgXfc6WTNU/q5znGlrTKeZalkVN9o7d41+SC/lNtx5i2eBRLqwlY4XLZi/dK9YM0zJjtYhsaOc9K7wESlZq3YOwuUEDl0VpZbjnHA3bIeTsSsiCN03o6ITrMPL5CGU3gUpRoDY7X+8rHC63/lTGaZrQ9zKJs11AbLvP29yg53hLQ+71FODF2dpabPK273JWVh0zK6Y5zg4MH1QUlXiMaZddsNjyk6FqkNeDclpKG7ZegbNb4BMrWVvGZ5qBwGnYVRUqyEIisM2mrisTzA8fnRDGIhciCLocAmQjY29w+FK2dHSviZKihcZ3/TRUA92k0sfPw2cZV9DHjXiNiT6eIkON69WXZViTjPR4Rqbv01U1hTVwLThWC2PhaRjPAmSrjqSMuA4P9obtkr6KOnhkSEksXYSSDsiRor2tY+bS7bSy+j6UCr16Ey+QWQ8lmfy/Eo3fEMR7vdRM08tnR3uBtVMXZn2uMSkL1bWViZttbHqG8eOHx8V4ZusMP8ZZtMdQEXRbUoQu6RgZZrN7kZSM5yoRBvUEXJd8JjpE//pZ+2U9TtId4cmbsHWeAZe80M7WkRlLQat9KQHGNTCuSS90sWgAGNyZbCnwaoeRfX2uIXVfnW1SHN6YiyL7UiK8yFoRs3Z9BmeOgyzWY6AXJrxpxKRYQ/CEN0o8bw4FF/UnUZYvTzsBhXWlmUaR8wlOPw17JfYIs79wWYdZW8Epq/NmNLX4i0ovn4YNxe/A0NtZaEKjZi1OhWnTJdXb/jucEGpPvlcfXHjmZi4xgiuBCHssueWobfbcxYiXNFw/PTXvePF/hRZ/iPgl97nedb/E2wQlV9W2+1pxpxLE+JSbPxTzUwgo1rgIE4jqdguulXacUi/ky8LXpOf9bqj5AtWmogq6Iuf+V+BU7wc1OPMKt8uaJW62DSX1wbc/pxbK5LV2EmYp29iOTr+kxKGmN30wTL+JZPgf+b0gr1EuGAGWFWUNYL4n+Z1oL1NWxMpmzlpSVCrpX6TkQ7VVZfvhlNgS4/BWGORPBl5uNNrlURjcD8/vvLnlYremu/ZEWy2JJCuhRfVJhJueOZjLIYZyl2SnX+OJenReBULXgl2Pfh5fNjXrjoe53lg8jtXxrrqatLcKnzdHEDXJrwJkxzzw8iIfDw0CrLUEx1Pn1mdbiHC0XjWV2RaXKfs8bQIh54XXfZs2uzO84ORz5B5BjZJ+WJUX6MYz1ORlEs4ixnawNgP3vxEt9K8zTFbjMRwiFo8yjYdaRRarbbgokQUa5lTZTZ7GTrIU9n18hghdYJIzDR1xAnc8HbbZtQ0VAu0efK73Z8dTqZljILXaT1p81PjTSBJZUy1UmGiF4LK/pPF3OsforcVO6HBE5k1j8/PMa+G/R/AKgjhdvmb6U6olmvKcFOYnUfB8cLqmk/jNudZimyPb0Btaj9vPXFOo5eLeU1K6LvjxenELPYwMpGxpFIfutJVZLnPQJ9IffdVGXLDKr1xVXCtv3sT4dy0yNoIoD/VU9eZQrlOXjeISelQ6lEPpaLU9DLcO3lI92YGLDc9/O9AVa8a54Nn6UJlaVh46nCmJyyG+7DAY+ldoR1rgo95EBbTFNP6xYdj2DEDNwQp1KOlJ7J+Bw7cz7Agm8kEECdhVXVguHFavHTmMtvBAKCWBZ3PclA1eYXzcYUA+wnU6bhuHTbHNLb0vqU1v/ObLAZzybtSb4k8dCisL7rghVFMcgIN/QU6qKSt4TQTi9IMdBgvJ9At9bWGZ++hvm0pCHL+GcFFcu9dpink6yB1+WbjKDmYb881aEcoaBqcUwUbnanUl/J98sIgFQULCx8uWXamiXFQhSza9guhNpd7lR+2Y3gYLhn4VSVn3mhgf6foT5YdIso2seWV20++BPkLZA4sqTIKYycnp1u3pAZDySS8L5ohuX8Gcw9h3KsRtdiUgwCPYQ/U/kLaBdC31+lz6exlx4OhF1dMdLWYYtnwlg9y6mDdoScP7hR9/noSTgAHZfebW07Xi9KLfVg+f886BwSH6hbIGKo3xCXYK/uvqJgNCH4Vf6/AJTZnbVv7syYHakyzz3P4lpkJu+Rj3D8gm++fSyIFhlsVyp6CrDoqrsKUyF65uYskw+5OFmMpG+ARaPYp4+Kmzhjame2JRLWFYQ4xntepTMZz/uITrv1rD/6zzjmdJoBJYSGuAIMudbe57safutr4b377/WQC52mAtpmubGeSdIyBk9rh25JkqW+n5skIsM87TiwKX5ktku8ahSubA35dREbPEQA2/SI5u4TPrzQzAscTQLh6+SMXWZgy7S/AbdeH3I1+zGqibXpg8fo7IFbOYmiMKD+Y3eSIRZ4Uwonhbj5QLine truncated
chapter_id = "81",
keypool = "CThTsnaVikSatcpdJeU9GwsLgsYBQYsZthdXsd5qyjNaey1iiieZfo58MECq7yWrS/w894HPGzB74nn+33VUxnxpkJ9GD69YdRxEs2mDr5I5zMlsyPtLPtSD/brtAj+C",
version = "1642763424",
fuid = "d0fec41098a7491f940157245a0d8740",
}
+666
View File
@@ -0,0 +1,666 @@
#!/usr/bin/env node
/*
* 起点 Fock(wasm2js 产物)→ LuaJIT 转译器。开发期工具,运行时不用。
*
* 用法:node tools/gen_fock.js <Fock.js> <输出.lua>
* 依赖:npm i acorn(仅开发机)。
*
* 只认 wasm2js 产出的 asm.js 子集:int32 运算、七种堆视图、labeled block /
* switch / for 循环、函数表 call_indirect。表达式里的赋值 / 逗号 / 三目 / 短路
* 提成语句并按求值顺序落临时变量;break / continue 用 goto。
*/
"use strict";
const acorn = require("acorn");
const fs = require("fs");
const [, , srcPath, outPath] = process.argv;
const src = fs.readFileSync(srcPath, "utf8");
const a = src.indexOf("this.exports=function(A){");
const e = src.search(/\}\(A\)\}\(\w+\)\},instantiate/);
if (a < 0 || e < 0) throw new Error("找不到 wasm2js 导出函数");
const code = "(" + src.slice(a + "this.exports=".length, e + "}(A)}".length) + ")";
const ast = acorn.parse(code, { ecmaVersion: 2020 });
const outer = ast.body[0].expression;
const inner = outer.body.body.find((n) => n.type === "ReturnStatement").argument.callee;
const top = inner.body.body;
// 变量名每个构建都不同:从模块头的 var 声明按位置推。顺序固定为
// 七个堆视图、imul、abs、clz32、abort、导入 b..f、栈指针 B、一个恒 0 的全局 Iv。
const HEAP_KIND = { Int8Array: "I8", Int16Array: "I16", Int32Array: "I32", Uint8Array: "U8", Uint16Array: "U16", Uint32Array: "U32", Float64Array: "F64" };
const HEAP = {};
const TOPVAR = { a: "rf_a", u: "rf_u", c: "rf_c", s: "rf_s" };
let STACK_INIT = 0;
(function header() {
const decl = top.find((s) => s.type === "VariableDeclaration");
const plain = [];
for (const d of decl.declarations) {
const init = d.init;
if (init && init.type === "NewExpression" && HEAP_KIND[init.callee.name]) HEAP[d.id.name] = HEAP_KIND[init.callee.name];
else if (init && init.type === "MemberExpression" && init.object.type === "Identifier" && init.object.name === "A" && init.property.name !== "buffer") TOPVAR[d.id.name] = init.property.name === "abort" ? "abort" : "imp_" + init.property.name;
else if (init && init.type === "MemberExpression" && init.object.name === "Math") TOPVAR[d.id.name] = "math.abs";
else if (init && init.type === "Identifier") plain.push(d.id.name);
else if (init && init.type === "Literal") plain.push(d);
}
const idents = plain.filter((x) => typeof x === "string");
TOPVAR[idents[0]] = "imul";
TOPVAR[idents[1]] = "clz32";
const lits = plain.filter((x) => typeof x !== "string");
TOPVAR[lits[0].id.name] = "B";
STACK_INIT = lits[0].init.value;
TOPVAR[lits[1].id.name] = "Iv";
})();
const tableDecl = top.find((s) => s.type === "VariableDeclaration" && s.declarations.length === 2 && !s.declarations[0].init);
const TABLE = new Set(tableDecl.declarations.map((d) => d.id.name));
const fnNames = new Set(top.filter((s) => s.type === "FunctionDeclaration").map((s) => s.id.name));
const fnRef = (n) => "F.f" + n.replace(/\$/g, "S_");
let tmpCount = 0;
let labelCount = 0;
function collectVars(fn) {
const names = new Set(fn.params.map((p) => p.name));
const vars = new Set();
(function walk(n) {
if (!n || typeof n.type !== "string") return;
if (n !== fn && (n.type === "FunctionExpression" || n.type === "FunctionDeclaration")) return;
if (n.type === "VariableDeclarator") vars.add(n.id.name);
for (const k of Object.keys(n)) {
const v = n[k];
if (Array.isArray(v)) v.forEach(walk);
else if (v && typeof v.type === "string") walk(v);
}
})(fn.body);
for (const p of names) vars.delete(p);
return { params: [...names], vars: [...vars], all: new Set([...names, ...vars]) };
}
class Fn {
constructor(node) {
this.scope = collectVars(node);
this.node = node;
this.out = [];
this.targets = [];
}
name(id) {
if (this.scope.all.has(id)) return "v_" + id;
if (HEAP[id]) throw new Error("heap view used as value: " + id);
if (TOPVAR[id]) return TOPVAR[id];
if (TABLE.has(id)) return "UA";
if (fnNames.has(id)) return fnRef(id);
throw new Error("unresolved identifier " + id);
}
isHeap(id) {
return HEAP[id] && !this.scope.all.has(id);
}
tmp() {
return "t" + ++tmpCount;
}
push(s) {
this.out.push(s);
}
// ---- 类型转换 ----
num(r) {
return r.t === "b" ? `(${r.s} and 1 or 0)` : r.s;
}
cond(r) {
return r.t === "b" ? r.s : `(${r.s} ~= 0)`;
}
// 带小数的值(除法结果)转 int32 前先截断
int(r) {
const s = this.num(r);
return r.frac ? `toint(${s})` : s;
}
// 按顺序求值一组表达式;后面的操作数产生了语句时,把前面的结果落到临时变量里
operands(nodes, discards) {
const res = [];
for (const node of nodes) {
const mark = this.out.length;
const r = this.emit(node);
if (this.out.length > mark) {
let at = mark;
for (const prev of res) {
if (!prev.lit && !prev.tmp) {
const t = this.tmp();
this.out.splice(at++, 0, `local ${t} = ${prev.t === "b" ? prev.s : this.num(prev)}`);
prev.s = t;
prev.tmp = true;
prev.frac = prev.frac;
prev.call = false;
}
}
}
res.push(r);
}
return res;
}
// ---- 表达式 ----
emit(node, discard) {
switch (node.type) {
case "Literal":
if (typeof node.value !== "number") throw new Error("非数字字面量 " + node.raw);
return { s: String(node.value), t: "n", lit: true };
case "Identifier":
if (node.name === "undefined") return { s: "nil", t: "u", lit: true };
return { s: this.name(node.name), t: "n" };
case "MemberExpression":
return this.member(node);
case "CallExpression":
return this.call(node);
case "UnaryExpression":
return this.unary(node);
case "BinaryExpression":
return this.binary(node);
case "LogicalExpression":
return this.logical(node, discard);
case "ConditionalExpression":
return this.conditional(node, discard);
case "AssignmentExpression":
return this.assign(node, discard);
case "UpdateExpression":
return this.update(node, discard);
case "SequenceExpression":
return this.sequence(node, discard);
default:
throw new Error("不支持的表达式 " + node.type);
}
}
member(node) {
if (!node.computed) {
if (node.property.name === "byteLength") return { s: "16777216", t: "n" };
throw new Error("非计算成员访问 " + code.slice(node.start, node.end));
}
const idx = this.operands([node.property])[0];
if (node.object.type === "Identifier" && this.isHeap(node.object.name)) {
return { s: `${HEAP[node.object.name]}[${this.int(idx)}]`, t: "n" };
}
return { s: `${this.emit(node.object).s}[${this.int(idx)}]`, t: "n", call: false };
}
call(node) {
let callee;
const argNodes = node.arguments;
if (node.callee.type === "Identifier") {
const n = node.callee.name;
if (this.scope.all.has(n)) throw new Error("调用局部变量 " + n);
callee = this.name(n);
} else if (node.callee.type === "MemberExpression") {
const r = this.operands([node.callee.property, ...argNodes]);
const idx = this.int(r.shift());
return { s: `${this.emit(node.callee.object).s}[${idx}](${r.map((x) => this.num(x)).join(", ")})`, t: "n", call: true };
} else {
throw new Error("不支持的调用目标 " + node.callee.type);
}
const r = this.operands(argNodes);
return { s: `${callee}(${r.map((x) => this.num(x)).join(", ")})`, t: "n", call: true };
}
unary(node) {
const op = node.operator;
if (op === "void") {
this.flush(this.emit(node.argument, true));
return { s: "nil", t: "u", lit: true };
}
const r = this.emit(node.argument);
if (op === "!") return { s: `(not ${this.cond(r)})`, t: "b" };
if (op === "-") return { s: `(-${this.num(r)})`, t: "n", frac: r.frac };
if (op === "+") return { s: this.num(r), t: "n", frac: true };
if (op === "~") return { s: `bnot(${this.int(r)})`, t: "n" };
throw new Error("不支持的一元运算 " + op);
}
binary(node) {
const [l, r] = this.operands([node.left, node.right]);
const op = node.operator;
const L = this.num(l);
const R = this.num(r);
switch (op) {
case "+": return { s: `(${L} + ${R})`, t: "n" };
case "-": return { s: `(${L} - ${R})`, t: "n" };
case "*": return { s: `(${L} * ${R})`, t: "n" };
case "/": return { s: `(${L} / ${R})`, t: "n", frac: true };
case "%": return { s: `fmod(${L}, ${R})`, t: "n" };
case "|":
if (node.right.type === "Literal" && node.right.value === 0) return { s: `tobit(${this.int(l)})`, t: "n" };
return { s: `bor(${this.int(l)}, ${this.int(r)})`, t: "n" };
case "&": return { s: `band(${this.int(l)}, ${this.int(r)})`, t: "n" };
case "^": return { s: `bxor(${this.int(l)}, ${this.int(r)})`, t: "n" };
case "<<": return { s: `lshift(${this.int(l)}, ${this.int(r)})`, t: "n" };
case ">>": return { s: `arshift(${this.int(l)}, ${this.int(r)})`, t: "n" };
case ">>>":
if (node.right.type === "Literal" && node.right.value === 0) return { s: `(tobit(${this.int(l)}) % 4294967296)`, t: "n" };
return { s: `(rshift(${this.int(l)}, ${this.int(r)}) % 4294967296)`, t: "n" };
case "<": case "<=": case ">": case ">=":
return { s: `(${L} ${op} ${R})`, t: "b" };
case "==": case "===": return { s: `(${L} == ${R})`, t: "b" };
case "!=": case "!==": return { s: `(${L} ~= ${R})`, t: "b" };
default: throw new Error("不支持的二元运算 " + op);
}
}
// 子表达式落到独立缓冲,返回 [语句, 结果]
sub(fn) {
const saved = this.out;
this.out = [];
const r = fn();
const stmts = this.out;
this.out = saved;
return [stmts, r];
}
// 条件上下文:返回 Lua 布尔表达式
condOf(node) {
if (node.type === "LogicalExpression") {
const l = this.condOf(node.left);
const [stmts, rc] = this.sub(() => this.condOf(node.right));
const and = node.operator === "&&";
if (!stmts.length) return `(${l} ${and ? "and" : "or"} ${rc})`;
const t = this.tmp();
this.push(`local ${t} = ${l}`);
this.push(`if ${and ? t : "not " + t} then`);
this.out.push(...stmts);
this.push(`${t} = ${rc}`);
this.push("end");
return t;
}
return this.cond(this.emit(node));
}
logical(node, discard) {
const and = node.operator === "&&";
if (discard) {
const l = this.condOf(node.left);
const [stmts] = this.sub(() => this.flush(this.emit(node.right, true)));
this.push(`if ${and ? l : "not " + l} then`);
this.out.push(...stmts);
this.push("end");
return { s: "nil", t: "u" };
}
const l = this.emit(node.left);
const t = this.tmp();
this.push(`local ${t} = ${this.num(l)}`);
const [stmts, r] = this.sub(() => this.emit(node.right));
this.push(`if ${t} ${and ? "~=" : "=="} 0 then`);
this.out.push(...stmts);
this.push(`${t} = ${this.num(r)}`);
this.push("end");
return { s: t, t: "n", tmp: true };
}
conditional(node, discard) {
const c = this.condOf(node.test);
const [sa, ra] = this.sub(() => this.emit(node.consequent, discard));
const [sb, rb] = this.sub(() => this.emit(node.alternate, discard));
if (discard) {
this.push(`if ${c} then`);
this.out.push(...sa);
this.flush(ra);
this.push("else");
this.out.push(...sb);
this.flush(rb);
this.push("end");
return { s: "nil", t: "u" };
}
if (!sa.length && !sb.length) return { s: `(${c} and ${this.num(ra)} or ${this.num(rb)})`, t: "n", frac: ra.frac || rb.frac };
const t = this.tmp();
this.push(`local ${t}`);
this.push(`if ${c} then`);
this.out.push(...sa);
this.push(`${t} = ${this.num(ra)}`);
this.push("else");
this.out.push(...sb);
this.push(`${t} = ${this.num(rb)}`);
this.push("end");
return { s: t, t: "n", tmp: true };
}
sequence(node, discard) {
const list = node.expressions;
for (let k = 0; k < list.length - 1; k++) this.flush(this.emit(list[k], true));
return this.emit(list[list.length - 1], discard);
}
// 表达式作为语句:只有调用有副作用
flush(r) {
if (r && r.call) this.push(r.s);
}
storeCoerce(view, s) {
return view === "F64" ? s : `tobit(${s})`;
}
assign(node, discard) {
let op = node.operator;
const left = node.left;
let right = node.right;
if (op !== "=") {
if (left.type !== "Identifier") throw new Error("复合赋值目标不是变量");
right = { type: "BinaryExpression", operator: op.slice(0, -1), left, right };
}
if (left.type === "Identifier") {
const target = this.name(left.name);
const r = this.emit(right);
this.push(`${target} = ${this.num(r)}`);
return { s: target, t: "n", frac: r.frac };
}
const isHeap = left.object.type === "Identifier" && this.isHeap(left.object.name);
const [idx, r] = this.operands([left.property, right]);
const lhsBase = isHeap ? HEAP[left.object.name] : this.emit(left.object).s;
const idxS = this.int(idx);
if (discard) {
this.push(`${lhsBase}[${idxS}] = ${isHeap ? this.storeCoerce(lhsBase, this.int(r)) : this.num(r)}`);
return { s: "nil", t: "u" };
}
const t = this.tmp();
const ti = this.tmp();
this.push(`local ${ti} = ${idxS}`);
this.push(`local ${t} = ${this.num(r)}`);
this.push(`${lhsBase}[${ti}] = ${isHeap ? this.storeCoerce(lhsBase, t) : t}`);
return { s: t, t: "n", tmp: true };
}
update(node, discard) {
if (node.argument.type !== "Identifier") throw new Error("自增目标不是变量");
const target = this.name(node.argument.name);
const delta = node.operator === "++" ? "+" : "-";
if (discard || node.prefix) {
this.push(`${target} = ${target} ${delta} 1`);
return { s: target, t: "n" };
}
const t = this.tmp();
this.push(`local ${t} = ${target}`);
this.push(`${target} = ${target} ${delta} 1`);
return { s: t, t: "n", tmp: true };
}
// ---- 语句 ----
stmt(node) {
const before = tmpCount;
const mark = this.out.length;
this.stmtInner(node);
if (tmpCount !== before) {
this.out.splice(mark, 0, "do");
this.out.push("end");
}
}
stmts(list) {
for (const s of list) this.stmt(s);
}
stmtInner(node) {
switch (node.type) {
case "EmptyStatement":
return;
case "ExpressionStatement":
this.flush(this.emit(node.expression, true));
return;
case "VariableDeclaration":
for (const d of node.declarations) {
if (d.init) this.flush(this.emit({ type: "AssignmentExpression", operator: "=", left: d.id, right: d.init }, true));
}
return;
case "BlockStatement":
this.stmts(node.body);
return;
case "ReturnStatement": {
if (!node.argument) { this.push("do return end"); return; }
const r = this.emit(node.argument);
this.push(r.t === "u" ? "do return end" : `do return ${this.num(r)} end`);
return;
}
case "IfStatement":
this.ifStmt(node);
return;
case "ForStatement":
this.loop(node, null);
return;
case "WhileStatement":
this.loop({ type: "ForStatement", init: null, test: node.test, update: null, body: node.body }, null);
return;
case "LabeledStatement":
this.labeled(node);
return;
case "BreakStatement":
this.jump(node.label ? node.label.name : null, "brk");
return;
case "ContinueStatement":
this.jump(node.label ? node.label.name : null, "cont");
return;
case "SwitchStatement":
this.switchStmt(node, null);
return;
default:
throw new Error("不支持的语句 " + node.type);
}
}
ifStmt(node) {
const c = this.condOf(node.test);
this.push(`if ${c} then`);
this.stmt(node.consequent);
if (node.alternate) {
this.push("else");
this.stmt(node.alternate);
}
this.push("end");
}
jump(label, kind) {
for (let k = this.targets.length - 1; k >= 0; k--) {
const t = this.targets[k];
let to = null;
if (label) {
if (t.label === label) to = kind === "brk" ? t.brk : t.cont;
} else if (kind === "brk" ? t.loop || t.sw : t.loop) {
to = kind === "brk" ? t.brk : t.cont;
}
if (to) {
this.push(`goto ${to}`);
return;
}
}
throw new Error("找不到跳转目标 " + label + " " + kind);
}
labeled(node) {
const label = node.label.name;
const body = node.body;
if (body.type === "ForStatement" || body.type === "WhileStatement") {
this.loop(body.type === "WhileStatement"
? { type: "ForStatement", init: null, test: body.test, update: null, body: body.body }
: body, label);
} else if (body.type === "SwitchStatement") {
this.switchStmt(body, label);
} else {
const brk = "L" + ++labelCount;
this.targets.push({ label, brk });
this.push("do");
this.stmt(body);
this.push("end");
this.targets.pop();
this.push(`::${brk}::`);
}
}
loop(node, label) {
const id = ++labelCount;
const t = { label, loop: true, brk: "B" + id, cont: "C" + id };
this.push("do");
if (node.init) this.stmt(node.init.type === "VariableDeclaration" ? node.init : { type: "ExpressionStatement", expression: node.init });
this.push("while true do");
if (node.test) {
const before = tmpCount;
const mark = this.out.length;
const c = this.condOf(node.test);
this.push(`if not ${c} then goto ${t.brk} end`);
if (tmpCount !== before) {
this.out.splice(mark, 0, "do");
this.push("end");
}
}
this.targets.push(t);
this.push("do");
this.stmt(node.body);
this.push("end");
this.targets.pop();
this.push(`::${t.cont}::`);
if (node.update) this.stmt({ type: "ExpressionStatement", expression: node.update });
this.push("end");
this.push("end");
this.push(`::${t.brk}::`);
}
switchStmt(node, label) {
const id = ++labelCount;
const end = "S" + id;
const d = this.emit(node.discriminant);
const sv = "sw" + id;
this.push("do");
this.push(`local ${sv} = ${this.int(d)}`);
const cases = node.cases;
let first = true;
let def = null;
cases.forEach((c, k) => {
if (!c.test) { def = k; return; }
const tv = this.emit(c.test);
this.push(`${first ? "if" : "elseif"} ${sv} == ${tv.s} then goto K${id}_${k}`);
first = false;
});
if (first) this.push(`goto ${def === null ? end : "K" + id + "_" + def}`);
else this.push(`else goto ${def === null ? end : "K" + id + "_" + def} end`);
this.targets.push({ label, sw: true, brk: end });
cases.forEach((c, k) => {
this.push(`::K${id}_${k}::`);
this.push("do");
this.stmts(c.consequent);
this.push("end");
});
this.targets.pop();
this.push("end");
this.push(`::${end}::`);
}
body() {
this.stmts(this.node.body.body);
return this.out;
}
render(header) {
const body = this.body();
const locals = this.scope.vars.length
? `local ${this.scope.vars.map((v) => "v_" + v).join(", ")} = ${this.scope.vars.map(() => "0").join(", ")}`
: "";
return `${header}(${this.scope.params.map((p) => "v_" + p).join(", ")})\n${locals}\n${body.join("\n")}\nend`;
}
}
function fnSource(node, header) {
return new Fn(node).render(header);
}
const lines = [];
lines.push("-- 由 tools/gen_fock.js 从起点 / QQ阅读的 Fock(wasm2js)转译生成,勿手改。");
lines.push("-- 运行环境见 fock.lua;env = { mem = ffi uint8_t*, imp = { b, c, d, e, f, abort } }。");
lines.push("local bit = require(\"bit\")");
lines.push("local ffi = require(\"ffi\")");
lines.push("local tobit, band, bor, bxor, bnot = bit.tobit, bit.band, bit.bor, bit.bxor, bit.bnot");
lines.push("local lshift, rshift, arshift = bit.lshift, bit.rshift, bit.arshift");
lines.push("local fmod = math.fmod");
lines.push("");
lines.push("local function toint(x)");
lines.push(" return tobit(x >= 0 and math.floor(x) or -math.floor(-x))");
lines.push("end");
lines.push("");
lines.push("local function imul(a, b)");
lines.push(" a, b = tobit(a), tobit(b)");
lines.push(" return tobit(band(a, 65535) * b + lshift(tobit(rshift(a, 16) * b), 16))");
lines.push("end");
lines.push("");
lines.push("local function clz32(x)");
lines.push(" x = tobit(x)");
lines.push(" if x == 0 then return 32 end");
lines.push(" if x < 0 then return 0 end");
lines.push(" local n = 0");
lines.push(" while x > 0 do x = lshift(x, 1); n = n + 1 end");
lines.push(" return n");
lines.push("end");
lines.push("");
lines.push("return function(env)");
lines.push("local mem = env.mem");
lines.push("local abort, imp_b, imp_c, imp_d, imp_e, imp_f = env.imp.abort, env.imp.b, env.imp.c, env.imp.d, env.imp.e, env.imp.f");
lines.push("local I8, I16, I32 = ffi.cast(\"int8_t*\", mem), ffi.cast(\"int16_t*\", mem), ffi.cast(\"int32_t*\", mem)");
lines.push("local U8, U16, U32 = ffi.cast(\"uint8_t*\", mem), ffi.cast(\"uint16_t*\", mem), ffi.cast(\"uint32_t*\", mem)");
lines.push("local F64 = ffi.cast(\"double*\", mem)");
lines.push(`local B, Iv = ${STACK_INIT}, 0`);
lines.push("local scratch = ffi.new(\"int32_t[4]\")");
lines.push("local scratch_f = ffi.cast(\"double*\", scratch)");
lines.push("local function rf_a(i) return scratch[i] end");
lines.push("local function rf_u(i, v) scratch[i] = v end");
lines.push("local function rf_c() return scratch_f[0] end");
lines.push("local function rf_s(v) scratch_f[0] = v end");
lines.push("local F = {}");
lines.push("local UA = { [0] = false }");
lines.push("local YA = UA");
lines.push("");
for (const s of top) {
if (s.type === "FunctionDeclaration") {
lines.push(fnSource(s, fnRef(s.id.name) + " = function"));
lines.push("");
}
}
// 函数表
let arrayNode = null;
(function find(n) {
if (!n || typeof n.type !== "string" || arrayNode) return;
if (n.type === "ArrayExpression") { arrayNode = n; return; }
for (const k of Object.keys(n)) {
const v = n[k];
if (Array.isArray(v)) v.forEach(find);
else if (v && typeof v.type === "string") find(v);
}
})(tableDecl.declarations[1].init);
arrayNode.elements.forEach((el, k) => {
if (el === null || el.type === "Literal") return;
if (el.type === "Identifier") lines.push(`UA[${k}] = ${fnRef(el.name)}`);
else lines.push(fnSource(el, `UA[${k}] = function`));
});
lines.push("");
// 数据段
const dataStmt = top.find((s) => s.type === "ExpressionStatement" && [].concat(s.expression.type === "SequenceExpression" ? s.expression.expressions : [s.expression]).every((c) => c.type === "CallExpression" && c.arguments.length === 3 && c.arguments[2].type === "Literal" && typeof c.arguments[2].value === "string"));
const calls = dataStmt.expression.type === "SequenceExpression" ? dataStmt.expression.expressions : [dataStmt.expression];
lines.push("local DATA = {");
for (const c of calls) {
const off = c.arguments[1].value;
const b64 = c.arguments[2].value;
lines.push(` { ${off}, "${b64}" },`);
}
lines.push("}");
lines.push("");
// 导出
const ret = top.find((s) => s.type === "ReturnStatement");
lines.push("local exports = {}");
for (const p of ret.argument.properties) {
const key = p.key.name;
if (p.value.type === "FunctionExpression") lines.push(fnSource(p.value, `exports.${key} = function`));
else if (p.value.type === "Identifier" && TABLE.has(p.value.name)) lines.push(`exports.${key} = UA`);
else if (p.value.type === "Identifier") lines.push(`exports.${key} = ${fnRef(p.value.name)}`);
else throw new Error("不支持的导出 " + key);
}
lines.push("return exports, DATA, function(v) B = v end, function() return B end");
lines.push("end");
fs.writeFileSync(outPath, lines.join("\n") + "\n");
console.log("generated", outPath, fs.statSync(outPath).size, "bytes");