✨ 初始提交:月读第三方书源插件集合
每个书源一个独立插件目录,含微信读书公众号订阅、书架导入等完整功能。 Co-authored-by: Copilot <[email protected]>
This commit is contained in:
commit
0907702861
27 files changed
+18687
No files matched your search
@@ -0,0 +1,21 @@
|
||||
# 潇湘书院
|
||||
|
||||
| 能力 | 是否支持 | 备注 |
|
||||
| --- | --- | --- |
|
||||
| 扫码登录 | 已实现,未实测 | 阅文二维码,使用 QQ阅读或起点 App;最终账号登录未完成实测 |
|
||||
| 浏览器登录与 Cookie 导入 | 已实现,未实测 | 保留扩展回传和手动粘贴入口 |
|
||||
| 设备密码与验证码登录 | 不支持 | 可在官网完成登录后导入 Cookie |
|
||||
| 书架拉取 | 支持 | 仅根书架图书,不枚举其他文件夹或资源类型 |
|
||||
| 书架新增与移出 | 已实现,未实测 | 本地先生效,同步上行后回读确认;失败保留脏行或墓碑 |
|
||||
| 搜索 | 支持 | 聚合后续页,默认最多 60 本 |
|
||||
| 分类书城 | 支持 | 动态分类、标签、排序、资费、状态、更新时段和字数筛选 |
|
||||
| 榜单 | 部分支持 | 潇湘票、畅销、完结、阅读、收藏;旧移动榜单仅单页 |
|
||||
| 详情与分卷目录 | 支持 | 保留章节顺序和长整数 ID |
|
||||
| 免费正文 | 支持 | 可匿名读取 |
|
||||
| 已购正文 | 已实现,未实测 | 按官网权限解码;未购预览不作为正文缓存 |
|
||||
| 章节与全本缓存 | 支持 | 支持预取和后台缓存;整本下载未完成实测 |
|
||||
| 离线阅读 | 支持 | 已缓存章节可续读、关书重开 |
|
||||
| 阅读进度同步 | 部分支持 | 仅章节位置,无章内比例;远端写入未实测 |
|
||||
| 笔记与统计同步 | 不支持 | 仅本地保存 |
|
||||
| 书评、章评、段评与回复 | 不支持 | 当前 Web 协议未找到可验证接口,不代表 App 没有评论 |
|
||||
| 账号切换 | 部分支持 | 同账号可续期;换号须确认清理旧本地数据,未同步记录会丢失 |
|
||||
@@ -0,0 +1,5 @@
|
||||
local _ = require("gettext")
|
||||
return {
|
||||
fullname = _("月读书源:潇湘书院"),
|
||||
description = _("给月读增加「潇湘书院」书源。需要同时安装月读,与平台官方无关。"),
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
--[[--
|
||||
KOReader 只认带 main.lua 的插件目录;书源本身不需要任何插件钩子,月读读取旁边的 moon_source.lua。
|
||||
--]]
|
||||
local WidgetContainer = require("ui/widget/container/widgetcontainer")
|
||||
|
||||
return WidgetContainer:extend{
|
||||
name = "moonsource_xiaoxiang",
|
||||
is_doc_only = false,
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
--[[--
|
||||
月读第三方书源描述:潇湘书院。契约见月读 examples/moonsource-demo.koplugin/moon_source.lua。
|
||||
--]]
|
||||
|
||||
local function lazy(module)
|
||||
return setmetatable({}, { __index = function(_, key) return require(module)[key] end })
|
||||
end
|
||||
|
||||
return {
|
||||
api = 1,
|
||||
provides = { source = true },
|
||||
meta = function() return require("moonsource_xiaoxiang.source").meta() end,
|
||||
new = function() return require("moonsource_xiaoxiang.source").new() end,
|
||||
setting = lazy("moonsource_xiaoxiang.setting"),
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
--[[--
|
||||
书源元信息:id / 名称 / 类型,加上启用页展示用的说明与能力清单。`init.lua` 的 `meta()` 直接返回本表。
|
||||
|
||||
@module moonsource_xiaoxiang._meta
|
||||
--]]
|
||||
|
||||
local _ = require("l10n").get("moonsource_xiaoxiang")
|
||||
|
||||
return {
|
||||
id = "ext.xiaoxiang",
|
||||
name = _("潇湘书院"),
|
||||
type = "chapter",
|
||||
description = _("潇湘书院书架与在线阅读"),
|
||||
abilities = { _("搜索与发现"), _("书架同步"), _("进度同步") },
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
--[[--
|
||||
潇湘官网分类库:动态分类与标签,筛选编码沿用官网,顺序聚合分页。
|
||||
|
||||
@module moonsource_xiaoxiang.browse
|
||||
--]]
|
||||
|
||||
local Browse = require("source.browse")
|
||||
local Client = require("moonsource_xiaoxiang.client")
|
||||
local Mapper = require("moonsource_xiaoxiang.mapper")
|
||||
local JSON_NULL = require("json").decode("null")
|
||||
local _ = require("l10n").get("moonsource_xiaoxiang")
|
||||
|
||||
local Library = {}
|
||||
local KEYS = { "state", "charge", "update", "words", "order", "category", "tag" }
|
||||
local DEFAULT = { state = -1, charge = -1, update = -1, words = -1, order = 10, category = 0, tag = -1 }
|
||||
local FILTERS = {
|
||||
{ key = "order", title = _("排序"), items = { { 6, _("综合热度") }, { 10, _("最畅销") }, { 3, _("收藏最多") } } },
|
||||
{ key = "state", title = _("状态"), items = { { -1, _("全部") }, { 0, _("连载") }, { 1, _("完结") } } },
|
||||
{ key = "charge", title = _("价格"), items = { { -1, _("全部") }, { 0, _("免费") }, { 2, _("付费") } } },
|
||||
{ key = "update", title = _("更新"), items = {
|
||||
{ -1, _("全部") }, { 0, _("3天以内") }, { 1, _("7天以内") }, { 2, _("15天以内") }, { 3, _("一个月以内") },
|
||||
} },
|
||||
{ key = "words", title = _("字数"), items = {
|
||||
{ -1, _("全部") }, { 11, _("20万以内") }, { 12, _("20-30万") }, { 3, _("30-50万") },
|
||||
{ 24, _("50-100万") }, { 25, _("100-200万") }, { 26, _("200万以上") },
|
||||
} },
|
||||
}
|
||||
|
||||
local function node(params, key, value)
|
||||
local values = {}
|
||||
for index, name in ipairs(KEYS) do
|
||||
values[index] = tostring(name == key and value
|
||||
or (key == "category" and name == "tag" and -1 or params[name]))
|
||||
end
|
||||
return "cate:" .. table.concat(values, ":")
|
||||
end
|
||||
|
||||
local function group(params, key, title, items)
|
||||
local chips = {}
|
||||
for _idx, item in ipairs(items) do chips[#chips + 1] = { id = node(params, key, item[1]), title = item[2] } end
|
||||
local result = Browse.group(chips, node(params))
|
||||
result.title = title
|
||||
return result
|
||||
end
|
||||
|
||||
function Library.run(opts, cb)
|
||||
opts = opts or {}
|
||||
local params = {}
|
||||
for key, value in pairs(DEFAULT) do params[key] = value end
|
||||
local valid = true
|
||||
if opts.node then
|
||||
local values = { opts.node:match("^cate:(%-?%d+):(%-?%d+):(%-?%d+):(%-?%d+):(%-?%d+):(%-?%d+):(%-?%d+)$") }
|
||||
valid = #values == #KEYS
|
||||
if valid then for index, key in ipairs(KEYS) do params[key] = tonumber(values[index]) end end
|
||||
end
|
||||
for _idx, filter in ipairs(FILTERS) do
|
||||
local found = false
|
||||
for _item, item in ipairs(filter.items) do if params[filter.key] == item[1] then found = true end end
|
||||
valid = valid and found
|
||||
end
|
||||
if not valid then return require("source.base").defer(cb, nil, _("潇湘分类条件无效")) end
|
||||
local cancelled, job, pending = false, nil, true
|
||||
local initial = Client.libraryAsync(params, 1, function(wire, err)
|
||||
pending = false
|
||||
if cancelled then return end
|
||||
local data = wire and wire.data
|
||||
if type(data) ~= "table" or type(data.categoryList) ~= "table" then cb(nil, err or _("响应无效")); return end
|
||||
local categories, tags, selected = {}, { { -1, _("全部") } }, nil
|
||||
for _idx, category in ipairs(data.categoryList) do
|
||||
if type(category) ~= "table" or not tonumber(category.id) or type(category.name) ~= "string" then
|
||||
cb(nil, _("响应无效")); return
|
||||
end
|
||||
categories[#categories + 1] = { tonumber(category.id), _(category.name) }
|
||||
if tonumber(category.id) == params.category then selected = category end
|
||||
end
|
||||
if not selected or type(selected.labelClassList) ~= "table" then cb(nil, _("响应无效")); return end
|
||||
local seen, found = {}, params.tag == -1
|
||||
for _idx, class in ipairs(selected.labelClassList) do
|
||||
if type(class) ~= "table" then cb(nil, _("响应无效")); return end
|
||||
local items = class.tagInfoList
|
||||
if items == JSON_NULL then items = nil end
|
||||
if items ~= nil and type(items) ~= "table" then
|
||||
cb(nil, _("响应无效")); return
|
||||
end
|
||||
for _tag, tag in ipairs(items or {}) do
|
||||
if type(tag) ~= "table" or not tonumber(tag.tagId) or type(tag.tagName) ~= "string" then
|
||||
cb(nil, _("响应无效")); return
|
||||
end
|
||||
local id = tonumber(tag.tagId)
|
||||
if id == params.tag then found = true end
|
||||
if not seen[id] then tags[#tags + 1], seen[id] = { id, _(tag.tagName) }, true end
|
||||
end
|
||||
end
|
||||
if not found then cb(nil, _("潇湘分类条件无效")); return end
|
||||
local groups = { group(params, "category", _("分类"), categories) }
|
||||
groups[1].chips[#groups[1].chips + 1] = { id = "rank", title = _("排行榜") }
|
||||
if #tags > 1 then groups[#groups + 1] = group(params, "tag", _("标签"), tags) end
|
||||
for _idx, filter in ipairs(FILTERS) do groups[#groups + 1] = group(params, filter.key, filter.title, filter.items) end
|
||||
job = Browse.pages(function(index, done)
|
||||
local function receive(result, reason)
|
||||
local page_data = result and result.data
|
||||
if type(page_data) ~= "table" or not tonumber(page_data.total) then
|
||||
done(nil, reason or _("响应无效")); return
|
||||
end
|
||||
local books, failure = Mapper.books(page_data.bookList)
|
||||
done(books, failure, index * 20 < tonumber(page_data.total))
|
||||
end
|
||||
if index == 1 then receive(wire); return end
|
||||
return Client.libraryAsync(params, index, receive)
|
||||
end, opts.limit or 60, groups, cb)
|
||||
end)
|
||||
if pending then job = initial end
|
||||
return { cancel = function()
|
||||
cancelled = true
|
||||
if job then job.cancel() end
|
||||
end }
|
||||
end
|
||||
|
||||
return Library
|
||||
@@ -0,0 +1,440 @@
|
||||
--[[--
|
||||
潇湘书院 HTTP 客户端(仅异步)。
|
||||
|
||||
搜索、分类走新站 JSON;详情走电脑官网 SSR,目录、旧榜单走移动官网(m.xxsy.net,匿名可读)。
|
||||
账号、正文、书架、进度走新站 www.xxsypro.com 的 JSON 接口(阅文通行证,与起点同一套账号体系):请求带登录 Cookie
|
||||
(ywGuid / ywKey 等)和同值的 csrfToken(Cookie 与 `_csrfToken` 查询参数),回包 code 0 为成功。
|
||||
匿名也能调,但书架是访客书架、没买的 VIP 章只回 130 字预览(auth=false),所以带登录态的操作先用 /user/auth/personal 确认 isLogin=1。
|
||||
书 / 章 id 是 17 位整数,超出 double 精度,解码前先加引号。目录页上千章、1MB+,解析放子进程。
|
||||
|
||||
@module koplugin.book.moonsource_xiaoxiang.client
|
||||
--]]
|
||||
|
||||
local Job = require("workers.job")
|
||||
local logger = require("utils.log")
|
||||
local Mapper = require("moonsource_xiaoxiang.mapper")
|
||||
local Request = require("http.request")
|
||||
local Text = require("utils.text")
|
||||
local _ = require("l10n").get("moonsource_xiaoxiang")
|
||||
|
||||
local Client = {}
|
||||
|
||||
--- 已保存的登录 Cookie。
|
||||
---@return string|nil
|
||||
function Client.cookie()
|
||||
local cookie = require("utils.settings").getSource("ext.xiaoxiang").cookie
|
||||
return type(cookie) == "string" and cookie ~= "" and cookie or nil
|
||||
end
|
||||
|
||||
local UA = "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) "
|
||||
.. "Version/16.0 Mobile/15E148 Safari/604.1"
|
||||
|
||||
---@param url string
|
||||
---@param cb fun(html: string|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
local function page(url, cb)
|
||||
return Request.get(url, {
|
||||
headers = { ["User-Agent"] = UA },
|
||||
timeout = require("http.timeout").net(1),
|
||||
}, function(raw, err)
|
||||
if not raw then cb(nil, err and tostring(err) or _("请求失败")); return end
|
||||
cb(raw)
|
||||
end)
|
||||
end
|
||||
|
||||
local SOURCE_ID = "ext.xiaoxiang"
|
||||
local API = "https://www.xxsypro.com/api"
|
||||
|
||||
--- 请求头里的 Cookie:没有 csrfToken 就补一个,网页端要求 Cookie 与 `_csrfToken` 同值。
|
||||
---@param cookie string|nil
|
||||
---@return string cookie
|
||||
---@return string csrf
|
||||
local function withCsrf(cookie)
|
||||
local csrf = cookie and cookie:match("csrfToken=([^;%s]+)")
|
||||
if csrf then return cookie, csrf end
|
||||
csrf = "moon"
|
||||
return (cookie and cookie .. "; " or "") .. "csrfToken=" .. csrf, csrf
|
||||
end
|
||||
|
||||
--- 回包 JSON 解码(17 位 id 先加引号);code 非 0 取 msg 当错误。
|
||||
---@param raw string|nil
|
||||
---@param err any
|
||||
---@param cb fun(wire: table|nil, err: string|nil)
|
||||
local function decode(raw, err, cb)
|
||||
if not raw then cb(nil, err and tostring(err) or _("请求失败")); return end
|
||||
local wire, reason = Mapper.decode(raw)
|
||||
if not wire then cb(nil, reason); return end
|
||||
if wire.code ~= 0 then cb(nil, wire.msg and tostring(wire.msg) or _("响应无效")); return end
|
||||
cb(wire)
|
||||
end
|
||||
|
||||
--- 新站 JSON 接口;body 为 nil 发 GET,否则 POST(body 是已编码的 JSON 串)。
|
||||
---@param path string
|
||||
---@param query string 不含 _csrfToken
|
||||
---@param body string|nil
|
||||
---@param cookie string|nil
|
||||
---@param cb fun(wire: table|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
local function call(path, query, body, cookie, cb)
|
||||
local cookie_header, csrf = withCsrf(cookie)
|
||||
local url = API .. path .. "?" .. (query ~= "" and query .. "&" or "") .. "_csrfToken=" .. Text.urlEncode(csrf)
|
||||
local opts = {
|
||||
accept = "application/json",
|
||||
headers = { Referer = "https://www.xxsypro.com/", ["User-Agent"] = UA },
|
||||
jar = require("http.cookie_jar").session(SOURCE_ID, cookie_header),
|
||||
timeout = require("http.timeout").net(0.5),
|
||||
cache_ttl = 0,
|
||||
}
|
||||
if body then
|
||||
opts.content_type = "application/json"
|
||||
return Request.post(url, body, opts, function(raw, err) decode(raw, err, cb) end)
|
||||
end
|
||||
return Request.get(url, opts, function(raw, err) decode(raw, err, cb) end)
|
||||
end
|
||||
|
||||
--- 账号信息:isLogin=1 才是真登录(失效的 Cookie 仍 code 0,只是 isLogin=0)。cookie 显式传入,登录入口先校验再保存。
|
||||
---@param cookie string
|
||||
---@param cb fun(info: table|nil, err: string|nil, kind: "auth"|nil)
|
||||
---@return HttpJob
|
||||
function Client.userAsync(cookie, cb)
|
||||
local cancelled = false
|
||||
local job = call("/user/auth/personal", "", nil, cookie, function(wire, err)
|
||||
if cancelled then return end
|
||||
local data = wire and wire.data
|
||||
if not wire then cb(nil, err); return end
|
||||
if type(data) ~= "table" then cb(nil, _("响应无效")); return end
|
||||
if tonumber(data.isLogin) == 0 then cb(nil, _("未登录潇湘"), "auth"); return end
|
||||
if tonumber(data.isLogin) ~= 1 then cb(nil, _("响应无效")); return end
|
||||
local guid = type(data.user) == "table" and data.user.guid
|
||||
local id = type(guid) == "number" and guid % 1 == 0 and string.format("%.0f", guid) or guid
|
||||
if type(id) ~= "string" or not id:match("^%d+$") or id:match("^0+$") then
|
||||
cb(nil, _("潇湘账号标识缺失")); return
|
||||
end
|
||||
cb({ isLogin = 1, id = id })
|
||||
end)
|
||||
return { cancel = function()
|
||||
cancelled = true
|
||||
if job then job:cancel() end
|
||||
end }
|
||||
end
|
||||
|
||||
--- 同一 Cookie 校验通过后多久内不再问个人接口:每章翻页都报进度,次次先打一遍个人接口是双倍请求。
|
||||
Client.AUTH_TTL = 10 * 60
|
||||
---@type { cookie: string|nil, at: integer } 最近一次通过校验的 Cookie 与时刻
|
||||
local verified = { cookie = nil, at = 0 }
|
||||
|
||||
--- 带登录态的调用:先确认 isLogin=1(AUTH_TTL 内同一 Cookie 只确认一次),失效就标记登出,免得访客书架被当成真实书架。
|
||||
---@param path string
|
||||
---@param query string
|
||||
---@param body string|nil
|
||||
---@param cb fun(wire: table|nil, err: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
local function authed(path, query, body, cb)
|
||||
local cookie = Client.cookie()
|
||||
if not cookie then return require("source.base").defer(cb, nil, _("未登录潇湘")) end
|
||||
local cancelled, job = false, nil
|
||||
local function done(wire, err)
|
||||
if cancelled then return end
|
||||
if Client.cookie() ~= cookie then cb(nil, _("账号已变化,请重新登录")); return end
|
||||
cb(wire, err)
|
||||
end
|
||||
if cookie and cookie == verified.cookie and os.time() - verified.at < Client.AUTH_TTL then
|
||||
job = call(path, query, body, cookie, done)
|
||||
else
|
||||
local pending = true
|
||||
local check = Client.userAsync(cookie, function(info, err, kind)
|
||||
pending = false
|
||||
if cancelled then return end
|
||||
if Client.cookie() ~= cookie then done(nil); return end
|
||||
if not info then
|
||||
if kind == "auth" then
|
||||
verified.cookie = nil
|
||||
err = require("source.auth").expire(SOURCE_ID,
|
||||
_("潇湘登录已失效,请点「重新登录」,用 QQ阅读或起点 App 扫码。也可在账号设置里粘贴 Cookie。"))
|
||||
end
|
||||
done(nil, err)
|
||||
return
|
||||
end
|
||||
verified.cookie, verified.at = cookie, os.time()
|
||||
require("source.auth").ok(SOURCE_ID)
|
||||
job = call(path, query, body, cookie, done)
|
||||
end)
|
||||
if pending then job = check end
|
||||
end
|
||||
return { cancel = function()
|
||||
cancelled = true
|
||||
if job then job:cancel() end
|
||||
end }
|
||||
end
|
||||
|
||||
--- 书架(只收根目录的书,resType 1),翻页收齐。
|
||||
---@param cb fun(rows: table[]|nil, err: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
function Client.shelfAsync(cb)
|
||||
---@type table[], boolean, CancelHandle|nil
|
||||
local rows, cancelled, job = {}, false, nil
|
||||
local cookie = Client.cookie()
|
||||
local function more(page)
|
||||
local pending = true
|
||||
local request = authed("/bookshelf/pc/page", "pageIndex=" .. page .. "&pageSize=20", nil, function(wire, err)
|
||||
pending = false
|
||||
if cancelled then return end
|
||||
if Client.cookie() ~= cookie then cb(nil, _("账号已变化,请重新登录")); return end
|
||||
local data = wire and wire.data
|
||||
if type(data) ~= "table" or type(data.data) ~= "table" or not tonumber(data.pageCount) then
|
||||
cb(nil, err or _("响应无效")); return
|
||||
end
|
||||
for _idx, row in ipairs(data.data) do
|
||||
if type(row) ~= "table" then cb(nil, _("响应无效")); return end
|
||||
if tonumber(row.restype) == 1 and tonumber(row.groupId) == -100 then
|
||||
if type(row.bookid) ~= "string" or not row.bookid:match("^%d+$") then
|
||||
cb(nil, _("响应无效")); return
|
||||
end
|
||||
rows[#rows + 1] = row
|
||||
end
|
||||
end
|
||||
if page < (tonumber(data.pageCount) or 0) then
|
||||
more(page + 1)
|
||||
return
|
||||
end
|
||||
cb(rows)
|
||||
end)
|
||||
if pending then job = request end
|
||||
end
|
||||
more(1)
|
||||
return { cancel = function()
|
||||
cancelled = true
|
||||
if job then job:cancel() end
|
||||
end }
|
||||
end
|
||||
|
||||
---@param book_id string
|
||||
---@return string
|
||||
local function shelfBody(book_id, extra)
|
||||
return '{"groupInfo":[{"groupId":-100,"books":[{"bookId":"' .. book_id .. '","resType":1' .. extra .. "}]}]}"
|
||||
end
|
||||
|
||||
--- 成功码不够:回读根书架,确认成员或章节确实收敛后才让调用方清脏行。
|
||||
local function confirmShelf(path, query, body, book_id, expected, cb)
|
||||
local cancelled, job, pending = false, nil, true
|
||||
local initial = authed(path, query, body, function(wire, err)
|
||||
pending = false
|
||||
if cancelled then return end
|
||||
if not wire then cb(nil, err); return end
|
||||
job = Client.shelfAsync(function(rows, reason)
|
||||
if cancelled then return end
|
||||
if not rows then cb(nil, reason); return end
|
||||
local matched
|
||||
for _idx, row in ipairs(rows) do if tostring(row.bookid) == book_id then matched = row end end
|
||||
local confirmed = expected == false and not matched
|
||||
or expected == true and matched ~= nil
|
||||
or type(expected) == "string" and matched and tostring(matched.ccid) == expected
|
||||
if not confirmed then cb(nil, _("潇湘远端状态未更新,请稍后重试")); return end
|
||||
cb(wire)
|
||||
end)
|
||||
end)
|
||||
if pending then job = initial end
|
||||
return { cancel = function()
|
||||
cancelled = true
|
||||
if job then job:cancel() end
|
||||
end }
|
||||
end
|
||||
|
||||
---@param book_id string
|
||||
---@param cb fun(wire: table|nil, err: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
function Client.shelfAddAsync(book_id, cb)
|
||||
return confirmShelf("/bookshelf/add", "",
|
||||
shelfBody(book_id, ',"ccid":"0","offset":0,"updatetime":' .. os.time() * 1000), book_id, true, cb)
|
||||
end
|
||||
|
||||
---@param book_id string
|
||||
---@param cb fun(wire: table|nil, err: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
function Client.shelfRemoveAsync(book_id, cb)
|
||||
return confirmShelf("/bookshelf/delete", "", shelfBody(book_id, ""), book_id, false, cb)
|
||||
end
|
||||
|
||||
--- 记「读到这一章」:书架行的 ccid 就是它。
|
||||
---@param book_id string
|
||||
---@param chapter_id string
|
||||
---@param cb fun(wire: table|nil, err: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
function Client.progressAsync(book_id, chapter_id, cb)
|
||||
return confirmShelf("/bookshelf/readingProcess/add", "bookId=" .. book_id, '{"books":[{"resType":1,"bookId":"' .. book_id
|
||||
.. '","updatetime":' .. os.time() * 1000 .. ',"ccid":"' .. chapter_id .. '","offset":0}]}', book_id, chapter_id, cb)
|
||||
end
|
||||
|
||||
---@param keyword string
|
||||
---@param cb fun(books: Book[]|nil, err: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
function Client.searchAsync(keyword, cb)
|
||||
return require("source.browse").pages(function(index, done)
|
||||
return call("/xxsy/bookstore/web/search", "key=" .. Text.urlEncode(keyword)
|
||||
.. "&start=" .. (index - 1) * 20 .. "&n=20", nil, nil, function(wire, err)
|
||||
local data = wire and type(wire.data) == "table" and wire.data.searchData
|
||||
if type(data) ~= "table" or not tonumber(data.total) then done(nil, err or _("响应无效")); return end
|
||||
local books, reason = Mapper.books(data.cardList)
|
||||
done(books, reason, index * 20 < tonumber(data.total))
|
||||
end)
|
||||
end, 60, {}, function(result, err)
|
||||
cb(result and result.data, err)
|
||||
end)
|
||||
end
|
||||
|
||||
function Client.libraryAsync(params, index, cb)
|
||||
local tag = params.tag
|
||||
local filters = { tag, params.state, params.charge, params.update, params.words, params.order }
|
||||
return call("/xxsy/bookstore/library/v1/web/search",
|
||||
"action=" .. (tag == -1 and "category" or "tag") .. "&categoryid=" .. params.category
|
||||
.. "&actionTag=" .. Text.urlEncode(table.concat(filters, ","))
|
||||
.. "&start=" .. (index - 1) * 20 .. "&n=20", nil, nil, cb)
|
||||
end
|
||||
|
||||
function Client.detailAsync(book_id, cb)
|
||||
return page("https://www.xxsypro.com/book/" .. book_id, function(html, err)
|
||||
if not html then cb(nil, err); return end
|
||||
local book, reason = Mapper.detail(html)
|
||||
if book and book.stable_id ~= book_id then cb(nil, _("响应无效")); return end
|
||||
cb(book, reason)
|
||||
end)
|
||||
end
|
||||
|
||||
--- 榜单页(一页 20 本);name 是手机站 /rank/<name>。
|
||||
---@param name string
|
||||
---@param cb fun(books: Book[]|nil, err: string|nil)
|
||||
---@param title string|nil SSR 栏目名,旧调用不传时仍解析 HTML
|
||||
---@return HttpJob
|
||||
function Client.rankAsync(name, cb, title)
|
||||
return page("https://m.xxsy.net/rank/" .. name, function(html, err)
|
||||
if not html then cb(nil, err); return end
|
||||
cb(Mapper.rank(html, title))
|
||||
end)
|
||||
end
|
||||
|
||||
--- 取页面并在子进程里按 parse 解析;parse 返回 nil 以外的值都算成功。
|
||||
---@param url string
|
||||
---@param name string
|
||||
---@param parse fun(html: string): any, string|nil
|
||||
---@param cb fun(value: any, err: string|nil, kind: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
local function parsed(url, name, parse, cb)
|
||||
---@type boolean, CancelHandle|nil
|
||||
local cancelled, job = false, nil
|
||||
local pending = true
|
||||
local request = page(url, function(html, err)
|
||||
pending = false
|
||||
if cancelled then return end
|
||||
if not html then cb(nil, err); return end
|
||||
job = Job.run(function()
|
||||
local value, reason = parse(html)
|
||||
return { value = value, err = reason }
|
||||
end, {
|
||||
name = name,
|
||||
kind = "light",
|
||||
timeout = 60,
|
||||
on_done = function(res)
|
||||
if cancelled then return end
|
||||
cb(res.value, res.err)
|
||||
end,
|
||||
on_failed = function(reason) if not cancelled then cb(nil, tostring(reason)) end end,
|
||||
on_cancelled = function() end,
|
||||
})
|
||||
end)
|
||||
if pending then job = request end
|
||||
return { cancel = function()
|
||||
cancelled = true
|
||||
if job then job:cancel() end
|
||||
end }
|
||||
end
|
||||
|
||||
---@param book_id string
|
||||
---@param cb fun(toc: BookChapter[]|nil, err: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
function Client.chaptersAsync(book_id, cb)
|
||||
return parsed("https://m.xxsy.net/books/" .. book_id .. ".html", "xiaoxiang_toc", Mapper.toc, cb)
|
||||
end
|
||||
|
||||
--- 一章正文(纯文本,段落以换行分隔)。免费章匿名可读;没买的 VIP 章只回预览(auth=false),报 "unpaid"。
|
||||
---@param book_id string
|
||||
---@param chapter_id string
|
||||
---@param cb fun(text: string|nil, err: string|nil, kind: "unpaid"|nil)
|
||||
---@return table handle { cancel }
|
||||
function Client.contentAsync(book_id, chapter_id, cb)
|
||||
local current, cancelled = nil, false
|
||||
local cookie = Client.cookie()
|
||||
local function done(text, err, kind)
|
||||
if cancelled then return end
|
||||
if Client.cookie() ~= cookie then cb(nil, _("账号已变化,请重新登录")); return end
|
||||
cb(text, err, kind)
|
||||
end
|
||||
-- 已购 VIP 章是 Fock 加密 + 乱序字体:fkp 是 `window.onkeyfocus("<密钥池>", <版本>)` 的 base64(只取参数不执行),用户密钥是 Cookie 的 ywGuid
|
||||
local function decrypt(chapter)
|
||||
local keypool, version = Text.base64Decode(tostring(chapter.fkp or ""))
|
||||
:match('onkeyfocus%("([^"]+)",%s*(%d+)%)')
|
||||
local uid = (cookie or ""):lower():match("ywguid=(%d+)")
|
||||
local font = type(chapter.fontResponse) == "table" and chapter.fontResponse or {}
|
||||
if not (keypool and version and uid and type(chapter.chapterContent) == "string") then
|
||||
logger.warn("xiaoxiang decrypt inputs missing: keypool", keypool ~= nil, "version", version ~= nil,
|
||||
"uid", uid ~= nil, "content", type(chapter.chapterContent))
|
||||
done(nil, _("潇湘章节解密失败")); return
|
||||
end
|
||||
local function run(fixed_font)
|
||||
local pending = true
|
||||
local job = require("moonsource_xiaoxiang.fock").chapterAsync(chapter, fixed_font, chapter_id, keypool, version,
|
||||
uid, function(text, derr)
|
||||
pending = false
|
||||
if cancelled then return end
|
||||
current = nil
|
||||
if not text then
|
||||
logger.warn("xiaoxiang fock decrypt failed:", derr)
|
||||
done(nil, _("潇湘章节解密失败")); return
|
||||
end
|
||||
done(text)
|
||||
end)
|
||||
if pending then current = job end
|
||||
end
|
||||
if chapter.font ~= true then run(nil); return end
|
||||
if type(font.fixedFontTtf) ~= "string" then
|
||||
logger.warn("xiaoxiang decrypt: fixedFontTtf missing")
|
||||
done(nil, _("潇湘章节解密失败")); return
|
||||
end
|
||||
local pending = true
|
||||
local request = Request.get(font.fixedFontTtf, { timeout = require("http.timeout").net(1) }, function(ttf, ferr)
|
||||
pending = false
|
||||
if cancelled then return end
|
||||
if Client.cookie() ~= cookie then done(nil); return end
|
||||
if not ttf then done(nil, ferr and tostring(ferr) or _("请求失败")); return end
|
||||
if not require("moonsource_xiaoxiang.yuewen_fonts").looksLikeFont(ttf) then
|
||||
logger.warn("xiaoxiang font download invalid:", #ttf, tostring(ttf:sub(1, 16)))
|
||||
done(nil, _("潇湘章节解密失败")); return
|
||||
end
|
||||
run(ttf)
|
||||
end)
|
||||
if pending then current = request end
|
||||
end
|
||||
local pending = true
|
||||
local request = call("/book/auth/download/v2/chapters", "",
|
||||
'{"cbid":"' .. book_id .. '","ccids":["' .. chapter_id .. '"]}', cookie, function(wire, err)
|
||||
pending = false
|
||||
if cancelled then return end
|
||||
if Client.cookie() ~= cookie then done(nil); return end
|
||||
if not wire then done(nil, err); return end
|
||||
local contents = type(wire.data) == "table" and wire.data.chapterContents
|
||||
local chapter = type(contents) == "table" and contents[1]
|
||||
if type(chapter) ~= "table" or tostring(chapter.ccid) ~= chapter_id then
|
||||
done(nil, _("响应无效")); return
|
||||
end
|
||||
local text, kind, chapter = Mapper.content(wire)
|
||||
if text then done(text); return end
|
||||
if kind == "encrypted" then decrypt(chapter); return end
|
||||
done(nil, (not kind) and _("潇湘章节内容为空") or nil, kind --[[@as "unpaid"|nil]])
|
||||
end)
|
||||
if pending then current = request end
|
||||
return { cancel = function()
|
||||
cancelled = true
|
||||
if current then current:cancel() end
|
||||
end }
|
||||
end
|
||||
|
||||
return Client
|
||||
@@ -0,0 +1,59 @@
|
||||
--[[--
|
||||
潇湘 VIP 章节正文解密(Fock):阅文 wasm 的潇湘构建参数 + 子进程编排,宿主在 `moonsource_xiaoxiang.yuewen_fock`。
|
||||
网页端用它解密 `chapterContents[].chapterContent`。
|
||||
|
||||
@module moonsource_xiaoxiang.fock
|
||||
--]]--
|
||||
|
||||
local Shared = require("moonsource_xiaoxiang.yuewen_fock")
|
||||
|
||||
local Fock = {}
|
||||
|
||||
local HOST = {
|
||||
["location.hostname"] = "www.xxsypro.com",
|
||||
["location.protocol"] = "https:",
|
||||
}
|
||||
|
||||
---@type YuewenFockBuild
|
||||
local BUILD = {
|
||||
wasm = "moonsource_xiaoxiang.fock_wasm",
|
||||
callback = 22353,
|
||||
stack = 5274656,
|
||||
exports = { ctors = "g", main = "l", set_uid = "h", set_key = "i", decrypt = "j",
|
||||
stack_save = "m", stack_restore = "n", alloc = "o", malloc = "p" },
|
||||
-- 其余是反调试 / 定时器探测:返回 -1(那几个会返回 indexOf 结果)或 0
|
||||
probe = function(code) return code % 709 == 151 and -1 or 0 end,
|
||||
imports = function(env)
|
||||
return {
|
||||
f = function() return 0 end,
|
||||
c = function(a, b) return env.malloc_str(HOST[env.cstr(a) .. "." .. env.cstr(b)] or "undefined") end,
|
||||
e = function() return env.malloc_str("undefined") end,
|
||||
}
|
||||
end,
|
||||
}
|
||||
|
||||
---@param content string base64 密文
|
||||
---@param chapter_id string|number
|
||||
---@param keypool string base64 密钥池(fkp 里 onkeyfocus 的第一个参数)
|
||||
---@param version string
|
||||
---@param uid string 用户 ywGuid
|
||||
---@return string|nil text
|
||||
---@return string|nil err
|
||||
function Fock.decrypt(content, chapter_id, keypool, version, uid)
|
||||
return Shared.decrypt(BUILD, content, chapter_id, keypool, version, uid)
|
||||
end
|
||||
|
||||
--- 在子进程里解密并还原乱序字体,回调拿正文纯文本或错误。
|
||||
---@param info table chapterContents 的一项(chapterContent、fontResponse)
|
||||
---@param fixed_font string|nil fontResponse.fixedFontTtf 下载下来的字节;没有字体加密的章为 nil
|
||||
---@return BookJob
|
||||
function Fock.chapterAsync(info, fixed_font, chapter_id, keypool, version, uid, cb)
|
||||
return Shared.jobAsync("xiaoxiang_fock", function(temp_paths)
|
||||
local plain, err = Fock.decrypt(info.chapterContent, chapter_id, keypool, version, uid)
|
||||
if not plain then return { err = err } end
|
||||
local font = type(info.fontResponse) == "table" and info.fontResponse or {}
|
||||
return { text = require("moonsource_xiaoxiang.yuewen_fonts").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,52 @@
|
||||
return {
|
||||
["综合热度"] = "Overall popularity",
|
||||
["最畅销"] = "Best sellers",
|
||||
["收藏最多"] = "Most favorites",
|
||||
["分类库"] = "Library categories",
|
||||
["3天以内"] = "Within 3 days",
|
||||
["7天以内"] = "Within 7 days",
|
||||
["15天以内"] = "Within 15 days",
|
||||
["一个月以内"] = "Within a month",
|
||||
["20万以内"] = "Under 200k words",
|
||||
["20-30万"] = "200-300k words",
|
||||
["30-50万"] = "300-500k words",
|
||||
["50-100万"] = "500k-1m words",
|
||||
["100-200万"] = "1-2m words",
|
||||
["潇湘分类条件无效"] = "Invalid Xiaoxiang library filters.",
|
||||
["潇湘账号标识缺失"] = "Missing Xiaoxiang account ID.",
|
||||
["潇湘远端状态未更新,请稍后重试"] = "The remote Xiaoxiang state has not updated. Please retry later.",
|
||||
["切换潇湘账号会清除这台设备上潇湘的书架、阅读进度、笔记和缓存,包括尚未同步的记录。不会删除远端书架。确定继续?"] = "Switching Xiaoxiang accounts clears this device's Xiaoxiang shelf, progress, notes and cache, including unsynced records. Your remote shelf will not be deleted. Continue?",
|
||||
["完结"] = "Completed",
|
||||
["排行榜"] = "Rankings",
|
||||
["切换账号"] = "Switch account",
|
||||
["无法确认旧账号,请先退出旧账号再登录"] = "Cannot identify the previous account. Sign out before signing in again.",
|
||||
["200万以上"] = "Over 2 million words",
|
||||
["连载"] = "Ongoing",
|
||||
["字数"] = "Word count",
|
||||
["价格"] = "Price",
|
||||
["免费"] = "Free",
|
||||
["付费"] = "Paid",
|
||||
["潇湘扫码登录"] = "Xiaoxiang QR sign-in",
|
||||
["潇湘登录已失效,请点「重新登录」,用 QQ阅读或起点 App 扫码。也可在账号设置里粘贴 Cookie。"] = "Xiaoxiang sign-in has expired. Tap Sign in again and scan with QQReader or Qidian. You can also paste a Cookie in account settings.",
|
||||
["未登录 · 点此扫码"] = "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阅读或起点 App 扫一扫"] = "Scan with the QQ Reader or Qidian app",
|
||||
["畅销榜"] = "Bestsellers",
|
||||
["阅读榜"] = "Reading chart",
|
||||
["潇湘目录为空"] = "Xiaoxiang table of contents is empty",
|
||||
["潇湘章节内容为空"] = "Xiaoxiang chapter is empty",
|
||||
["潇湘章节解密失败"] = "Xiaoxiang chapter decryption failed",
|
||||
["潇湘账号"] = "Xiaoxiang account",
|
||||
["潇湘登录 Cookie"] = "Xiaoxiang login cookie",
|
||||
["确定退出潇湘账号?"] = "Sign out of Xiaoxiang?",
|
||||
["潇湘票榜"] = "Xiaoxiang Ticket Chart",
|
||||
["完结榜"] = "Completed",
|
||||
["收藏榜"] = "Favorites",
|
||||
["未登录潇湘"] = "Not signed in to Xiaoxiang",
|
||||
["缺少潇湘章节位置"] = "Missing Xiaoxiang chapter position",
|
||||
["书架同步"] = "Shelf sync",
|
||||
["搜索与发现"] = "Search and discover",
|
||||
["潇湘书院书架与在线阅读"] = "Xiaoxiang shelf and online reading",
|
||||
["进度同步"] = "Progress sync",
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
return {
|
||||
["综合热度"] = "綜合熱度",
|
||||
["最畅销"] = "最暢銷",
|
||||
["收藏最多"] = "收藏最多",
|
||||
["分类库"] = "分類庫",
|
||||
["3天以内"] = "3天以內",
|
||||
["7天以内"] = "7天以內",
|
||||
["15天以内"] = "15天以內",
|
||||
["一个月以内"] = "一個月以內",
|
||||
["20万以内"] = "20萬以內",
|
||||
["20-30万"] = "20–30萬",
|
||||
["30-50万"] = "30–50萬",
|
||||
["50-100万"] = "50–100萬",
|
||||
["100-200万"] = "100–200萬",
|
||||
["潇湘分类条件无效"] = "瀟湘分類條件無效",
|
||||
["潇湘账号标识缺失"] = "瀟湘帳號識別碼缺失",
|
||||
["潇湘远端状态未更新,请稍后重试"] = "瀟湘遠端狀態尚未更新,請稍後重試",
|
||||
["切换潇湘账号会清除这台设备上潇湘的书架、阅读进度、笔记和缓存,包括尚未同步的记录。不会删除远端书架。确定继续?"] = "切換瀟湘帳號會清除這台裝置上瀟湘的書架、閱讀進度、筆記和快取,包括尚未同步的記錄。不會刪除遠端書架。確定繼續?",
|
||||
["完结"] = "完結",
|
||||
["排行榜"] = "排行榜",
|
||||
["切换账号"] = "切換帳號",
|
||||
["无法确认旧账号,请先退出旧账号再登录"] = "無法確認舊帳號,請先登出舊帳號再登入",
|
||||
["200万以上"] = "200 萬字以上",
|
||||
["连载"] = "連載",
|
||||
["字数"] = "字數",
|
||||
["价格"] = "價格",
|
||||
["免费"] = "免費",
|
||||
["付费"] = "付費",
|
||||
["潇湘扫码登录"] = "瀟湘掃碼登入",
|
||||
["潇湘登录已失效,请点「重新登录」,用 QQ阅读或起点 App 扫码。也可在账号设置里粘贴 Cookie。"] = "瀟湘登入已失效,請點「重新登入」,用 QQ閱讀或起點 App 掃碼。也可在帳號設定裡貼上 Cookie。",
|
||||
["未登录 · 点此扫码"] = "未登入 · 點此掃碼",
|
||||
["章节目录保存失败"] = "章節目錄儲存失敗",
|
||||
["按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"] = "按鍵盤 F12,點「網路」,重新整理網頁,複製請求標頭裡的整段 Cookie",
|
||||
["用 QQ阅读或起点 App 扫一扫"] = "用 QQ閱讀或起點 App 掃一掃",
|
||||
["畅销榜"] = "暢銷榜",
|
||||
["阅读榜"] = "閱讀榜",
|
||||
["潇湘目录为空"] = "瀟湘目錄為空",
|
||||
["潇湘章节内容为空"] = "瀟湘章節內容為空",
|
||||
["潇湘章节解密失败"] = "瀟湘章節解密失敗",
|
||||
["潇湘账号"] = "潇湘帳號",
|
||||
["潇湘登录 Cookie"] = "潇湘登入 Cookie",
|
||||
["确定退出潇湘账号?"] = "確定登出潇湘帳號?",
|
||||
["潇湘票榜"] = "潇湘票榜",
|
||||
["完结榜"] = "完結榜",
|
||||
["收藏榜"] = "收藏榜",
|
||||
["未登录潇湘"] = "未登入瀟湘",
|
||||
["缺少潇湘章节位置"] = "缺少瀟湘章節位置",
|
||||
["书架同步"] = "書架同步",
|
||||
["搜索与发现"] = "搜尋與發現",
|
||||
["潇湘书院书架与在线阅读"] = "瀟湘書院書架與線上閱讀",
|
||||
["进度同步"] = "進度同步",
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
return function()
|
||||
local copy = {}
|
||||
for k, v in pairs(require("moonsource_xiaoxiang._meta")) do copy[k] = v end
|
||||
return copy
|
||||
end
|
||||
@@ -0,0 +1,195 @@
|
||||
--[[--
|
||||
潇湘书院数据映射(纯函数):新站 JSON、官网 SSR 与旧榜单 HTML → 领域对象。
|
||||
|
||||
@module koplugin.book.moonsource_xiaoxiang.mapper
|
||||
--]]
|
||||
|
||||
local JSON = require("json")
|
||||
local Text = require("utils.text")
|
||||
local _ = require("l10n").get("moonsource_xiaoxiang")
|
||||
|
||||
local Mapper = {}
|
||||
|
||||
local SOURCE_ID = "ext.xiaoxiang"
|
||||
|
||||
--- 新站 JSON 的整数身份不能经过 Lua number;不匹配小数、指数或字符串里的转义引号。
|
||||
function Mapper.decode(raw)
|
||||
local encoded = raw:gsub('("[%w_]+"%s*:%s*)(%d+)([,}%]%s])', function(key, value, tail)
|
||||
return key .. (#value >= 16 and ('"' .. value .. '"') or value) .. tail
|
||||
end)
|
||||
local ok, data = pcall(JSON.decode, encoded)
|
||||
if not ok or type(data) ~= "table" then return nil, _("响应无效") end
|
||||
return data
|
||||
end
|
||||
|
||||
--- 电脑与移动官网共用的 SSR 容器,只取公开页面数据。
|
||||
function Mapper.state(html)
|
||||
local raw = html:match('<script[^>]-id="vite%-plugin%-ssr_pageContext"[^>]*>(.-)</script>')
|
||||
if not raw then return nil, _("响应无效") end
|
||||
local data = Mapper.decode(raw)
|
||||
local context = data and data.pageContext
|
||||
local props = type(context) == "table" and context.pageProps
|
||||
local page_data = type(props) == "table" and props.pageData
|
||||
if type(page_data) ~= "table" then return nil, _("响应无效") end
|
||||
return page_data
|
||||
end
|
||||
|
||||
--- 分类库、搜索与详情的公开字段有两套命名,身份始终保留字符串。
|
||||
function Mapper.books(rows)
|
||||
if type(rows) ~= "table" then return nil, _("响应无效") end
|
||||
local books = {}
|
||||
for _idx, row in ipairs(rows) do
|
||||
if type(row) ~= "table" then return nil, _("响应无效") end
|
||||
local id, title = row.cbId or row.cbid, row.bookName or row.title
|
||||
if type(id) ~= "string" or not id:match("^%d+$") or type(title) ~= "string" then
|
||||
return nil, _("响应无效")
|
||||
end
|
||||
books[#books + 1] = {
|
||||
source_id = SOURCE_ID, stable_id = id, title = Text.trim(title),
|
||||
authors = Text.trim(row.authorName or row.author or ""),
|
||||
category = row.cate2Name or row.catel2name or row.categoryShortName,
|
||||
intro = Text.trim(row.intro or ""), words = tonumber(row.totalWords),
|
||||
cover = "https://bookcover.yuewen.com/qdbimg/349573/c_" .. id .. "/180",
|
||||
}
|
||||
end
|
||||
return books
|
||||
end
|
||||
|
||||
function Mapper.detail(html)
|
||||
local data, err = Mapper.state(html)
|
||||
if not data then return nil, err end
|
||||
local detail = data.detailData or data.bookInfo or data
|
||||
local books, reason = Mapper.books({ detail })
|
||||
return books and books[1], reason
|
||||
end
|
||||
|
||||
--- 手机站榜单 SSR 中按栏目名选当前榜单;兼容旧 HTML。
|
||||
---@param html string
|
||||
---@param title string|nil
|
||||
---@return Book[]|nil
|
||||
---@return string|nil
|
||||
function Mapper.rank(html, title)
|
||||
if title and html:find('id="vite-plugin-ssr_pageContext"', 1, true) then
|
||||
local data, err = Mapper.state(html)
|
||||
if not data then return nil, err end
|
||||
for _idx, section in ipairs(data) do
|
||||
if type(section) ~= "table" then return nil, _("响应无效") end
|
||||
local info = section.columnInfo
|
||||
if type(info) == "table" and info.name == title then return Mapper.books(section.bookList) end
|
||||
end
|
||||
return nil, _("响应无效")
|
||||
end
|
||||
local out = {}
|
||||
for id, item in html:gmatch('<a href="/book/(%d+)"[^>]*data%-bookid=.-(<div class="common%-img".-)</a>') do
|
||||
local title = item:match('class="book%-title"[^>]*>([^<]*)<')
|
||||
if title then
|
||||
local module = item:match('class="book%-module"[^>]*>(.-)</p>') or ""
|
||||
local cover = item:match('<img src="([^"]*)"')
|
||||
out[#out + 1] = {
|
||||
source_id = SOURCE_ID,
|
||||
stable_id = id,
|
||||
title = Text.xmlDecode(title),
|
||||
authors = Text.trim(Text.xmlDecode(module:match("^([^<]*)") or "")),
|
||||
intro = Text.trim(Text.xmlDecode(item:match('class="book%-profile"[^>]*>([^<]*)<') or "")),
|
||||
cover = cover and (cover:gsub("^//", "https://")),
|
||||
}
|
||||
end
|
||||
end
|
||||
if #out == 0 then return nil, _("响应无效") end
|
||||
return out
|
||||
end
|
||||
|
||||
--- 目录缓存格式版本。
|
||||
Mapper.TOC_VERSION = 1
|
||||
|
||||
--- 手机站目录页 → 目录。页面内嵌 SSR JSON,`"chapters":[` 之后是扁平对象:type 0 是卷,type 1 是章(price > 0 为 VIP)。
|
||||
---@param html string
|
||||
---@return BookChapter[]|nil
|
||||
---@return string|nil
|
||||
function Mapper.toc(html)
|
||||
local toc = {}
|
||||
local rows
|
||||
if html:find('id="vite-plugin-ssr_pageContext"', 1, true) then
|
||||
local data, err = Mapper.state(html)
|
||||
if not data then return nil, err end
|
||||
rows = data.chapters or data.chapterListData
|
||||
else
|
||||
local raw = html:match('"chapters":%s*(%b[])')
|
||||
rows = raw and Mapper.decode('{"rows":' .. raw .. "}")
|
||||
rows = rows and rows.rows
|
||||
end
|
||||
if type(rows) ~= "table" then return nil, _("响应无效") end
|
||||
for _idx, row in ipairs(rows) do
|
||||
if type(row) ~= "table" or (row.type ~= 0 and row.type ~= 1) then return nil, _("响应无效") end
|
||||
if row.type == 1 then
|
||||
if type(row.ccid) ~= "string" or not row.ccid:match("^%d+$") or type(row.title) ~= "string" then
|
||||
return nil, _("响应无效")
|
||||
end
|
||||
toc[#toc + 1] = {
|
||||
idx = #toc + 1,
|
||||
uid = row.ccid,
|
||||
title = row.title,
|
||||
vip = (tonumber(row.price) or 0) > 0 or nil,
|
||||
}
|
||||
end
|
||||
end
|
||||
if toc[1] then toc[1].toc_version = Mapper.TOC_VERSION end
|
||||
return toc
|
||||
end
|
||||
|
||||
--- 章节接口回包 → 正文纯文本。没买的 VIP 章(价格 > 0 且 auth 不为真)只有 130 字预览,返回 nil, "unpaid"。
|
||||
--- 正文段落以 \r\n 分隔、每段前有全角缩进。
|
||||
---@param wire table
|
||||
---@return string|nil text
|
||||
---@return "unpaid"|"encrypted"|nil kind
|
||||
---@return table|nil encrypted
|
||||
function Mapper.content(wire)
|
||||
local chapters = type(wire.data) == "table" and wire.data.chapterContents
|
||||
local chapter = chapters and chapters[1]
|
||||
if type(chapter) ~= "table" then return nil end
|
||||
local price = tonumber(chapter.chapterPrice)
|
||||
if not price then return nil end
|
||||
if price > 0 and chapter.auth ~= true then return nil, "unpaid" end
|
||||
if chapter.encrypt == true then return nil, "encrypted", chapter end
|
||||
if type(chapter.chapterContent) ~= "string" then return nil end
|
||||
local lines = {}
|
||||
for line in chapter.chapterContent:gmatch("[^\r\n]+") do
|
||||
line = Text.trim(line)
|
||||
while line:sub(1, 3) == "\227\128\128" do line = Text.trim(line:sub(4)) end
|
||||
if line ~= "" then lines[#lines + 1] = line end
|
||||
end
|
||||
if #lines == 0 then return nil end
|
||||
return table.concat(lines, "\n")
|
||||
end
|
||||
|
||||
--- 书架行 → Book[]。封面按书 id 拼(书架接口不给)。
|
||||
---@param rows table[]
|
||||
---@return Book[]
|
||||
function Mapper.shelfList(rows)
|
||||
local out = {}
|
||||
for _idx, row in ipairs(rows) do
|
||||
local id = tostring(row.bookid)
|
||||
out[#out + 1] = {
|
||||
source_id = SOURCE_ID,
|
||||
stable_id = id,
|
||||
title = Text.trim(row.title or ""),
|
||||
authors = Text.trim(row.author or ""),
|
||||
cover = "https://bookcover.yuewen.com/qdbimg/349573/c_" .. id .. "/180",
|
||||
}
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
--- 书架行 → 书 id → 最近读到的章 id(ccid 为 "0" 表示没读过)。
|
||||
---@param rows table[]
|
||||
---@return table<string, string>
|
||||
function Mapper.progress(rows)
|
||||
local out = {}
|
||||
for _idx, row in ipairs(rows) do
|
||||
local ccid = tostring(row.ccid or "0")
|
||||
if ccid ~= "0" then out[tostring(row.bookid)] = ccid end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
return Mapper
|
||||
@@ -0,0 +1,92 @@
|
||||
--[[--
|
||||
潇湘源设置:登录。
|
||||
|
||||
潇湘新站 www.xxsypro.com 使用阅文通行证:设备上展示 App 扫码,保留浏览器扩展与手动 Cookie 导入。
|
||||
拿到 Cookie 先用 personal 接口的 data.isLogin 校验,通过才保存。
|
||||
|
||||
@module koplugin.book.moonsource_xiaoxiang.setting
|
||||
--]]
|
||||
|
||||
local _ = require("l10n").get("moonsource_xiaoxiang")
|
||||
local CookieLogin = require("source.cookie_login")
|
||||
|
||||
local SOURCE_ID = "ext.xiaoxiang"
|
||||
local Setting = {}
|
||||
|
||||
---@return boolean
|
||||
local function loggedIn()
|
||||
return require("moonsource_xiaoxiang.client").cookie() ~= nil
|
||||
end
|
||||
|
||||
local function commit(cookie, account, cb, current)
|
||||
if not account or type(account.id) ~= "string" or not account.id:match("^%d+$") then
|
||||
cb(false, _("潇湘账号标识缺失")); return
|
||||
end
|
||||
return CookieLogin.commitAccount(SOURCE_ID, cookie, account.id, cb, current)
|
||||
end
|
||||
|
||||
---@type CookieLoginSpec
|
||||
local SPEC = {
|
||||
id = SOURCE_ID,
|
||||
title = _("潇湘账号"),
|
||||
cookie_title = _("潇湘登录 Cookie"),
|
||||
cookie_hint = _("按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"),
|
||||
logout_text = _("确定退出潇湘账号?"),
|
||||
loggedIn = loggedIn,
|
||||
checkAsync = function(cookie, cb)
|
||||
local Client = require("moonsource_xiaoxiang.client")
|
||||
local previous = Client.cookie()
|
||||
return Client.userAsync(cookie, function(info, err)
|
||||
if Client.cookie() ~= previous then cb(false, _("账号已变化,请重新登录")); return end
|
||||
cb(info ~= nil, err, info)
|
||||
end)
|
||||
end,
|
||||
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
|
||||
|
||||
--- 浏览器扩展登录(features/cookie)。personal 接口一律 code 0,靠 data.isLogin 判登录。
|
||||
Setting.browser = {
|
||||
domain = "www.xxsypro.com",
|
||||
scope = "cookie",
|
||||
login = "https://www.xxsypro.com/",
|
||||
check = "https://www.xxsypro.com/api/user/auth/personal",
|
||||
check_json = { path = "data.isLogin", ok = { 1 } },
|
||||
icon = "https://www.xxsypro.com/favicon.ico",
|
||||
isAuthorized = function() return CookieLogin.authorized(SPEC) end,
|
||||
apply = function(payload, cb) return CookieLogin.save(SPEC, CookieLogin.fromPayload(payload, "xxsypro.com"), cb) end,
|
||||
}
|
||||
|
||||
local function startQR()
|
||||
require("ui/network/manager"):runWhenConnected(function()
|
||||
require("moonsource_xiaoxiang.yuewen_qr"):new({
|
||||
app_id = "57", area_id = "5", return_url = "https://www.xxsypro.com/",
|
||||
referer = "https://passport.yuewen.com/yuewen.html",
|
||||
title = _("潇湘扫码登录"), 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,219 @@
|
||||
--[[--
|
||||
潇湘书院数据源。
|
||||
|
||||
分类、搜索、账号、正文、书架、进度走新站 JSON;详情、目录、旧榜单走电脑/移动官网 SSR(client.lua)。
|
||||
登录态是新站 Cookie(阅文通行证):App 扫码、浏览器扩展授权,或粘贴 Cookie(setting.lua)。
|
||||
书架双向同步(Shelf.syncAsync),进度按章:读书架行的 ccid,写 readingProcess/add。没买的 VIP 章开章给临时提示页,目录标「未购」。
|
||||
|
||||
@module moonsource_xiaoxiang
|
||||
--]]
|
||||
|
||||
local Client = require("moonsource_xiaoxiang.client")
|
||||
local Mapper = require("moonsource_xiaoxiang.mapper")
|
||||
local SourceBase = require("source.base")
|
||||
local Browse = require("source.browse")
|
||||
local Shelf = require("source.shelf")
|
||||
local Toc = require("source.toc")
|
||||
local _ = require("l10n").get("moonsource_xiaoxiang")
|
||||
|
||||
local Xiaoxiang = {}
|
||||
|
||||
-- 接口按 IP 限流,预取与整本缓存逐章间隔请求。
|
||||
local FETCH_INTERVAL = 1
|
||||
|
||||
---@return BookSourceMeta
|
||||
function Xiaoxiang.meta()
|
||||
return require("moonsource_xiaoxiang.loadmeta")()
|
||||
end
|
||||
|
||||
---@class XiaoxiangSource : SourceBase
|
||||
local Source = setmetatable({ shelf_add = true }, { __index = SourceBase })
|
||||
Source.__index = Source
|
||||
|
||||
---@return XiaoxiangSource
|
||||
function Xiaoxiang.new()
|
||||
local meta = Xiaoxiang.meta()
|
||||
return setmetatable({ id = meta.id, name = meta.name, type = meta.type }, Source)
|
||||
end
|
||||
|
||||
--- 搜索 / 目录 / 榜单匿名可用,书架、进度和已购 VIP 章要登录 Cookie。
|
||||
---@return boolean
|
||||
function Source:configured()
|
||||
return Client.cookie() ~= nil
|
||||
end
|
||||
|
||||
--- 书架远端:Shelf.syncAsync 要的三个冒号方法。
|
||||
local Remote = {}
|
||||
|
||||
function Remote:shelfSyncAsync(cb) return Client.shelfAsync(cb) end
|
||||
|
||||
function Remote:addToShelfAsync(stable_id, cb) return Client.shelfAddAsync(stable_id, cb) end
|
||||
|
||||
function Remote:removeFromShelfAsync(stable_id, cb) return Client.shelfRemoveAsync(stable_id, cb) end
|
||||
|
||||
function Source:syncBooksAsync(opts, cb)
|
||||
if not self:configured() then return SourceBase.skipped(cb, "xiaoxiang not logged in") end
|
||||
return Shelf.syncAsync(self.id, Remote, Mapper.shelfList, opts, cb)
|
||||
end
|
||||
|
||||
--- 进度只到章:读书架行里这本书最近读到的章(ccid)。
|
||||
function Source:getProgressAsync(identity, cb)
|
||||
if not self:configured() then return SourceBase.defer(cb, nil, _("未登录潇湘")) end
|
||||
local cookie = Client.cookie()
|
||||
local cancelled, job = false, nil
|
||||
local pending = true
|
||||
local initial = Client.shelfAsync(function(rows, err)
|
||||
pending = false
|
||||
if cancelled then return end
|
||||
if Client.cookie() ~= cookie then cb(nil, _("账号已变化,请重新登录")); return end
|
||||
if not rows then cb(nil, err); return end
|
||||
local uid = Mapper.progress(rows)[tostring(identity.stable_id)]
|
||||
if not uid 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 _("潇湘目录为空")); return end
|
||||
local idx = Toc.index(self.id, identity.stable_id, uid)
|
||||
if not idx then cb(nil, nil, { empty = true }); return end
|
||||
cb({
|
||||
chapter_idx = idx,
|
||||
chapter_title = toc[idx].title,
|
||||
fraction = (idx - 1) / #toc,
|
||||
extra = { chapter_uid = uid, chapter_idx = idx },
|
||||
})
|
||||
end)
|
||||
end)
|
||||
if pending then job = initial end
|
||||
return { cancel = function()
|
||||
cancelled = true
|
||||
if job and job.cancel then job.cancel() end
|
||||
end }
|
||||
end
|
||||
|
||||
function Source:putProgressAsync(identity, pos, cb)
|
||||
if not self:configured() then return SourceBase.defer(cb, nil, _("未登录潇湘")) end
|
||||
local cookie = Client.cookie()
|
||||
local cancelled, job = false, nil
|
||||
local pending = true
|
||||
local initial = 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 then cb(nil, _("缺少潇湘章节位置")); return end
|
||||
job = Client.progressAsync(identity.stable_id, chapter.uid, function(wire, perr)
|
||||
if not cancelled then cb(wire and true, perr) end
|
||||
end)
|
||||
end)
|
||||
if pending then job = initial end
|
||||
return { cancel = function()
|
||||
cancelled = true
|
||||
if job and job.cancel then job.cancel() end
|
||||
end }
|
||||
end
|
||||
|
||||
---@param keyword string
|
||||
---@param cb fun(res: { data: Book[] }|nil, err: string|nil)
|
||||
---@return { cancel: fun() }|nil
|
||||
function Source:searchAsync(keyword, cb)
|
||||
return Client.searchAsync(keyword, function(books, err)
|
||||
if not books then
|
||||
cb(nil, err)
|
||||
return
|
||||
end
|
||||
cb({ data = books })
|
||||
end)
|
||||
end
|
||||
|
||||
-- 手机站 /rank/<id> 的榜单,顺序同网页。
|
||||
local RANKS = {
|
||||
{ id = "xxyuepiao", title = "潇湘票榜" },
|
||||
{ id = "bestsales", title = "畅销榜" },
|
||||
{ id = "finish", title = "完结榜" },
|
||||
{ id = "reading", title = "阅读榜" },
|
||||
{ id = "collections", title = "收藏榜" },
|
||||
}
|
||||
|
||||
---@param opts { node?: string, limit?: integer }
|
||||
---@param cb fun(res: { data: Book[], groups: StoreChipGroup[] }|nil, err: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
function Source:browseAsync(opts, cb)
|
||||
opts = opts or {}
|
||||
local legacy = opts.node == "rank"
|
||||
for _idx, row in ipairs(RANKS) do if row.id == opts.node then legacy = true end end
|
||||
if not legacy then return require("moonsource_xiaoxiang.browse").run(opts, cb) end
|
||||
local rank = RANKS[1]
|
||||
for _idx, row in ipairs(RANKS) do
|
||||
if row.id == opts.node then rank = row end
|
||||
end
|
||||
local chips = {}
|
||||
for _idx, row in ipairs(RANKS) do chips[#chips + 1] = { id = row.id, title = _(row.title) } end
|
||||
local groups = { Browse.group(chips, rank.id) }
|
||||
groups[1].title = _("排行榜")
|
||||
groups[1].chips[#groups[1].chips + 1] = { id = "cate:-1:-1:-1:-1:10:0:-1", title = _("分类库") }
|
||||
return Client.rankAsync(rank.id, function(books, err)
|
||||
if not books then cb(nil, err); return end
|
||||
if opts.limit then for index = #books, opts.limit + 1, -1 do books[index] = nil end end
|
||||
cb({ data = books, groups = groups })
|
||||
end, rank.title)
|
||||
end
|
||||
|
||||
function Source:getDetailAsync(identity, cb)
|
||||
return Client.detailAsync(identity.stable_id, cb)
|
||||
end
|
||||
|
||||
--- 强制拉目录并写回;失败由调用方继续用旧缓存。
|
||||
---@param identity BookIdentity
|
||||
---@param cb fun(toc: BookChapter[]|nil, err: string|nil)
|
||||
---@return { cancel: fun() }|nil
|
||||
local function fetchTocAsync(self, identity, cb)
|
||||
return Client.chaptersAsync(identity.stable_id, function(toc, err)
|
||||
if not toc then cb(nil, err); return end
|
||||
if #toc == 0 then cb(nil, _("潇湘目录为空")); return end
|
||||
if not Toc.put(self.id, identity.stable_id, toc) then cb(nil, _("章节目录保存失败")); return end
|
||||
cb(toc)
|
||||
end)
|
||||
end
|
||||
|
||||
---@param identity BookIdentity
|
||||
---@param cb fun(toc: BookChapter[]|nil, err: string|nil)
|
||||
---@param force boolean|nil 真=跳过缓存强制拉
|
||||
---@return { cancel: fun() }|nil
|
||||
function Source:loadTocAsync(identity, cb, force)
|
||||
if not force then
|
||||
local cached = Toc.read(self.id, identity.stable_id)
|
||||
if cached and #cached > 0 and cached[1].toc_version == Mapper.TOC_VERSION then
|
||||
return SourceBase.defer(cb, cached)
|
||||
end
|
||||
end
|
||||
return 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 Xiaoxiang
|
||||
@@ -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_xiaoxiang.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_xiaoxiang.yuewen_fonts.scramble` 的 HTML 解析拼起来。
|
||||
|
||||
字体是随章下发的,写临时文件给 FreeType 读;参考字签名会落盘缓存。
|
||||
|
||||
@module moonsource_xiaoxiang.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_xiaoxiang.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_xiaoxiang.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("<", "<"):gsub(">", ">"):gsub(""", '"'):gsub("'", "'"):gsub("&", "&"))
|
||||
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_xiaoxiang.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
|
||||
@@ -0,0 +1,82 @@
|
||||
--[[--
|
||||
潇湘动态分类、标签、完整分页及取消。
|
||||
|
||||
@module tests.moonsource_xiaoxiang.browse_spec
|
||||
--]]
|
||||
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
|
||||
|
||||
local A = require("support.assert")
|
||||
local null = function() end
|
||||
local JSON = require("support.json_stub")
|
||||
package.loaded["json"] = { decode = function(wire)
|
||||
if wire == "null" then return null end
|
||||
return JSON.decode(wire)
|
||||
end }
|
||||
local calls, waiting, stopped, mode = {}, nil, false, "sync"
|
||||
---@type {id: integer, name: string, labelClassList: {name?: string, tagInfoList?: (fun())|string|{tagId: integer, tagName: string}[]}[]}[]
|
||||
local categories = {
|
||||
{ id = 0, name = "全部", labelClassList = {} },
|
||||
{ id = 30013, name = "古代言情", labelClassList = {
|
||||
{ name = "全部标签", tagInfoList = null },
|
||||
{ tagInfoList = { { tagId = 61000007, tagName = "女强" }, { tagId = 61000007, tagName = "女强" } } },
|
||||
} },
|
||||
{ id = 30020, name = "现代言情", labelClassList = {} },
|
||||
}
|
||||
local function reply(index, cb)
|
||||
if mode == "error" and index == 2 then cb(nil, "网络失败"); return end
|
||||
local rows = {}
|
||||
for i = 1, 20 do rows[i] = { cbId = tostring((index - 1) * 20 + i), bookName = "书" } end
|
||||
cb({ data = { categoryList = categories, bookList = rows, total = 100 } })
|
||||
end
|
||||
package.loaded["moonsource_xiaoxiang.client"] = {
|
||||
libraryAsync = function(params, index, cb)
|
||||
calls[#calls + 1] = { params = params, index = index }
|
||||
if mode == "waiting" and index == 2 then waiting = cb else reply(index, cb) end
|
||||
return { cancel = function() stopped = true end }
|
||||
end,
|
||||
}
|
||||
package.loaded["moonsource_xiaoxiang.browse"] = nil
|
||||
local Library = require("moonsource_xiaoxiang.browse")
|
||||
local result, err
|
||||
Library.run({}, function(data, reason) result, err = data, reason end)
|
||||
A.is_nil(err)
|
||||
A.len(result.data, 60)
|
||||
A.len(calls, 3)
|
||||
A.eq(result.data[60].stable_id, "60")
|
||||
A.eq(result.groups[1].title, "分类")
|
||||
local chosen = result.groups[1].chips[2].id
|
||||
A.eq(chosen, "cate:-1:-1:-1:-1:10:30013:-1")
|
||||
Library.run({ node = chosen }, function(data) result = data end)
|
||||
A.eq(result.groups[2].title, "标签")
|
||||
A.len(result.groups[2].chips, 2, "重复标签不重复显示")
|
||||
local tagged = result.groups[2].chips[2].id
|
||||
Library.run({ node = tagged, limit = 20 }, function(data) result = data end)
|
||||
A.eq(calls[#calls].params.tag, 61000007)
|
||||
A.eq(result.groups[1].chips[3].id, "cate:-1:-1:-1:-1:10:30020:-1", "换分类清标签")
|
||||
Library.run({ node = "cate:1:0:2:25:6:30013:-1", limit = 20 }, function(data) result = data end)
|
||||
A.eq(calls[#calls].params.state, 1)
|
||||
A.eq(calls[#calls].params.charge, 0)
|
||||
A.eq(calls[#calls].params.words, 25)
|
||||
A.len(result.data, 20)
|
||||
for _idx, invalid in ipairs({ "invalid", function() end }) do
|
||||
categories[2].labelClassList[1].tagInfoList = invalid
|
||||
Library.run({ node = chosen }, function(data, reason) result, err = data, reason end)
|
||||
A.is_nil(result, "未知函数和坏类型不能冒充 JSON null")
|
||||
A.eq(err, "响应无效")
|
||||
end
|
||||
categories[2].labelClassList[1].tagInfoList = null
|
||||
mode = "error"
|
||||
Library.run({}, function(data, reason) result, err = data, reason end)
|
||||
A.is_nil(result, "中间页失败不能伪装完整列表")
|
||||
A.eq(err, "网络失败")
|
||||
mode, stopped, result = "waiting", false, nil
|
||||
local handle = Library.run({}, function(data) result = data end)
|
||||
handle.cancel()
|
||||
A.is_true(stopped, "同步第一页不能覆盖第二页取消句柄")
|
||||
reply(2, waiting)
|
||||
A.is_nil(result)
|
||||
mode = "sync"
|
||||
Library.run({ node = "cate:-1:-1:-1:-1:99:0:-1" }, function(data, reason) result, err = data, reason end)
|
||||
require("support.stubs").flush()
|
||||
A.is_nil(result)
|
||||
A.eq(err, "潇湘分类条件无效")
|
||||
@@ -0,0 +1,541 @@
|
||||
--[[--
|
||||
长佩 / 潇湘数据映射离线用例:搜索、目录、正文解密与未购识别。
|
||||
|
||||
@module tests.source.changpei_xiaoxiang_spec
|
||||
--]]
|
||||
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
|
||||
|
||||
package.preload["json"] = function() return require("support.json_stub") end
|
||||
package.loaded["moonsource_xiaoxiang.mapper"] = nil
|
||||
|
||||
local Aes = require("crypto.aes")
|
||||
local Assert = require("support.assert")
|
||||
local Text = require("utils.text")
|
||||
|
||||
local Changpei = require("moonsource_changpei.mapper")
|
||||
local Xiaoxiang = require("moonsource_xiaoxiang.mapper")
|
||||
|
||||
local KEY, IV = "u0LRrbu$Enm84koA", "$h$b3!iGzsYnnshj"
|
||||
local function seal(plain) return Text.base64Encode(Aes.cbc_encrypt(plain, KEY, IV)) end
|
||||
|
||||
do
|
||||
local books = Changpei.search({ data = { list = {
|
||||
{ novel_id = 7, novel_name = " 书 ", novel_author = "甲", novel_desc = "简介", novel_type = "架空",
|
||||
novel_cover = "https://x/a.jpg?x-oss-process=style/small", novel_wordnumber = 1000 },
|
||||
{ novel_id = 8, novel_name = "乙", novel_author = "丙", novel_desc = "",
|
||||
novel_cover = "https://x/nocover.jpg?x", novel_type = "" },
|
||||
} } })
|
||||
Assert.len(books, 2)
|
||||
Assert.eq(books[1].stable_id, "7")
|
||||
Assert.eq(books[1].title, "书")
|
||||
Assert.eq(books[1].cover, "https://x/a.jpg")
|
||||
Assert.is_nil(books[2].cover)
|
||||
Assert.is_nil(books[2].category)
|
||||
end
|
||||
|
||||
do
|
||||
local toc = Changpei.toc({ data = { list = {
|
||||
{ type = "item", id = 1, name = "一", price = 0 },
|
||||
{ type = "item", id = 2, name = "二" },
|
||||
{ type = "item", id = 3, name = "三", price = 5 },
|
||||
{ type = "more" },
|
||||
} } })
|
||||
Assert.len(toc, 3)
|
||||
Assert.eq(toc[3].uid, "3")
|
||||
Assert.is_nil(toc[2].vip)
|
||||
Assert.is_true(toc[3].vip)
|
||||
Assert.eq(toc[1].toc_version, Changpei.TOC_VERSION)
|
||||
end
|
||||
|
||||
do
|
||||
local text = Changpei.content({ data = { chapterInfo = { chapterPrice = 0, content = seal(" 第一段\r\n\r\n 第二段\n") } } })
|
||||
Assert.eq(text, " 第一段\n 第二段")
|
||||
local _t, _e, kind = Changpei.content({ data = { chapterInfo = { chapterPrice = 9, isSub = false, content = "" } } })
|
||||
Assert.eq(kind, "unpaid")
|
||||
local _t0, e0, kind0 = Changpei.content({ code = 200, msg = "操作成功",
|
||||
data = { chapterInfo = { chapterPrice = "25", isSub = "0", content = "" } } })
|
||||
Assert.eq(kind0, "unpaid")
|
||||
Assert.is_nil(e0)
|
||||
local bought = Changpei.content({ data = { chapterInfo = { chapterPrice = 9, isSub = true, content = seal("正文") } } })
|
||||
Assert.eq(bought, "正文")
|
||||
local _t2, _e2, verify = Changpei.content({ data = { check = 2, chapterInfo = { chapterPrice = 0, content = seal("乱码") } } })
|
||||
Assert.eq(verify, "verify")
|
||||
local gated, _gated_err, gated_kind = Changpei.content({ data = {
|
||||
check = 2, chapterInfo = { chapterPrice = 0, content = "not-aes" },
|
||||
} })
|
||||
Assert.is_nil(gated, "待验证内容即使形似正文也不能交付")
|
||||
Assert.eq(gated_kind, "verify", "验证前不应尝试解密不可信载荷")
|
||||
local none, err = Changpei.content({ msg = "访问异常" })
|
||||
Assert.is_nil(none)
|
||||
Assert.eq(err, "访问异常")
|
||||
local invalid, invalid_err = Changpei.content({ data = {
|
||||
chapterInfo = { chapterPrice = 0, content = seal("\255\254\128bad") },
|
||||
} })
|
||||
Assert.is_nil(invalid)
|
||||
Assert.eq(invalid_err, "长佩章节解密失败", "解密得到非法 UTF-8 不能当作正文缓存")
|
||||
local control, control_err = Changpei.content({ data = {
|
||||
chapterInfo = { chapterPrice = 0, content = seal("前文\0后文") },
|
||||
} })
|
||||
Assert.is_nil(control)
|
||||
Assert.eq(control_err, "长佩章节解密失败")
|
||||
Assert.eq(Changpei.content({ data = {
|
||||
chapterInfo = { chapterPrice = 0, content = seal("中文🙂\t后文") },
|
||||
} }), "中文🙂\t后文", "合法正文保留 emoji 与制表符")
|
||||
end
|
||||
|
||||
do
|
||||
local html = 'x"chapters":[{"type":0,"isVip":-1,"title":"正文"},'
|
||||
.. '{"type":1,"ccid":"11","title":"第1章","price":0},'
|
||||
.. '{"type":1,"ccid":"12","title":"第2章","price":10}],"other":{"a":1}'
|
||||
local toc = Xiaoxiang.toc(html)
|
||||
Assert.len(toc, 2)
|
||||
Assert.eq(toc[2].uid, "12")
|
||||
Assert.is_nil(toc[1].vip)
|
||||
Assert.is_true(toc[2].vip)
|
||||
local missing, err = Xiaoxiang.toc("<html></html>")
|
||||
Assert.is_nil(missing)
|
||||
Assert.eq(err, "响应无效")
|
||||
end
|
||||
|
||||
do
|
||||
local html = '<a href="/book/25866531901067904" style="" class="details-part" data-bookid="25866531901067904" data-v-1>'
|
||||
.. '<div class="common-img" data-v-1><div><img src="//bookcover.yuewen.com/a/90.webp" alt="x"></div></div>'
|
||||
.. '<div class="common-info"><p class="book-title" data-v-1>来日&有信</p><p class="book-profile" data-v-1>简介</p>'
|
||||
.. '<p class="book-module" data-v-1>千山茶客<span class="pipe">·</span>连载中<span class="pipe">·</span>21万字</p></div></a>'
|
||||
.. '<a href="/book/2" data-bookid="2" data-v-1><div class="common-img"><img src="//c/2.webp"></div>'
|
||||
.. '<div class="common-info"><p class="book-title">乙</p><p class="book-module">丙<span>·</span>完结</p></div></a>'
|
||||
local books = Xiaoxiang.rank(html)
|
||||
Assert.len(books, 2)
|
||||
Assert.eq(books[1].stable_id, "25866531901067904")
|
||||
Assert.eq(books[1].title, "来日&有信")
|
||||
Assert.eq(books[1].authors, "千山茶客")
|
||||
Assert.eq(books[1].cover, "https://bookcover.yuewen.com/a/90.webp")
|
||||
Assert.eq(books[2].title, "乙")
|
||||
Assert.is_nil(Xiaoxiang.rank("<html></html>"))
|
||||
end
|
||||
|
||||
do
|
||||
local function wire(chapter) return { data = { chapterContents = { chapter } } } end
|
||||
Assert.eq(Xiaoxiang.content(wire({ chapterPrice = "0", auth = true, chapterContent = "\r\n\227\128\128甲\r\n\227\128\128\r\n\227\128\128乙" })), "甲\n乙")
|
||||
local free, kind = Xiaoxiang.content(wire({ chapterPrice = "9", auth = false, chapterContent = "预览" }))
|
||||
Assert.is_nil(free)
|
||||
Assert.eq(kind, "unpaid")
|
||||
Assert.eq(Xiaoxiang.content(wire({ chapterPrice = "9", auth = true, chapterContent = "全文" })), "全文")
|
||||
Assert.is_nil((Xiaoxiang.content({ data = {} })))
|
||||
local cipher, ckind, chapter = Xiaoxiang.content(wire({ chapterPrice = "20", auth = true, encrypt = true, chapterContent = "9HHP" }))
|
||||
Assert.is_nil(cipher)
|
||||
Assert.eq(ckind, "encrypted")
|
||||
Assert.eq(chapter.chapterContent, "9HHP")
|
||||
|
||||
local rows = { { bookid = "35554414603847007", title = " 书 ", author = "甲", ccid = "35554414603847008", restype = 1 },
|
||||
{ bookid = "2", title = "乙", author = "丙", ccid = "0" } }
|
||||
local books = Xiaoxiang.shelfList(rows)
|
||||
Assert.eq(books[1].stable_id, "35554414603847007")
|
||||
Assert.eq(books[1].title, "书")
|
||||
Assert.eq(books[1].cover, "https://bookcover.yuewen.com/qdbimg/349573/c_35554414603847007/180")
|
||||
local progress = Xiaoxiang.progress(rows)
|
||||
Assert.eq(progress["35554414603847007"], "35554414603847008")
|
||||
Assert.is_nil(progress["2"])
|
||||
end
|
||||
|
||||
do
|
||||
local seen = {}
|
||||
package.loaded["http.request"] = nil
|
||||
package.preload["http.request"] = function()
|
||||
return {
|
||||
get = function(url, opts, cb)
|
||||
seen.url, seen.headers = url, opts.headers
|
||||
seen.cookie = opts.jar and opts.jar:header(url)
|
||||
cb(seen.reply)
|
||||
return {}
|
||||
end,
|
||||
post = function(url, body, opts, cb)
|
||||
seen.post_url, seen.body, seen.headers = url, body, opts.headers
|
||||
seen.cookie = opts.jar and opts.jar:header(url)
|
||||
cb(seen.reply)
|
||||
return {}
|
||||
end,
|
||||
}
|
||||
end
|
||||
package.loaded["moonsource_xiaoxiang.client"] = nil
|
||||
local Settings = require("utils.settings")
|
||||
local cfg = Settings.getSource("ext.xiaoxiang")
|
||||
cfg.cookie = "csrfToken=C1; ywKey=K"
|
||||
Settings.saveSource("ext.xiaoxiang", cfg)
|
||||
local Client = require("moonsource_xiaoxiang.client")
|
||||
require("source.auth").reset()
|
||||
|
||||
seen.reply = '{"code":0,"data":{"isLogin":0}}'
|
||||
local err
|
||||
Client.shelfRemoveAsync("35554414603847007", function(_wire, e) err = e end)
|
||||
Assert.is_true(require("source.auth").expired("ext.xiaoxiang"))
|
||||
Assert.is_nil(seen.post_url)
|
||||
|
||||
seen.reply = '{"code":0,"data":{"isLogin":1,"user":{"guid":"42"}}}'
|
||||
Client.userAsync("a=1", function(info) seen.info = info end)
|
||||
Assert.eq(seen.info.isLogin, 1)
|
||||
Assert.eq(seen.cookie, "a=1; csrfToken=moon")
|
||||
Assert.matches(seen.url, "_csrfToken=moon")
|
||||
|
||||
local replies = { '{"code":0,"data":{"isLogin":1,"user":{"guid":"42"}}}', '{"code":0,"msg":"ok","data":null}' }
|
||||
package.loaded["source.auth"].reset()
|
||||
seen.reply = nil
|
||||
local n = 0
|
||||
package.loaded["http.request"] = nil
|
||||
package.preload["http.request"] = function()
|
||||
return {
|
||||
get = function(url, opts, cb)
|
||||
seen.url = url
|
||||
if url:find("/bookshelf/pc/page", 1, true) then
|
||||
cb('{"code":0,"data":{"data":[],"pageCount":0}}')
|
||||
else
|
||||
n = n + 1
|
||||
cb(replies[1])
|
||||
end
|
||||
return {}
|
||||
end,
|
||||
post = function(url, body, opts, cb) seen.post_url, seen.body = url, body; cb(replies[2]) return {} end,
|
||||
}
|
||||
end
|
||||
package.loaded["moonsource_xiaoxiang.client"] = nil
|
||||
Client = require("moonsource_xiaoxiang.client")
|
||||
local ok
|
||||
Client.shelfRemoveAsync("35554414603847007", function(wire) ok = wire ~= nil end)
|
||||
Assert.is_true(ok)
|
||||
Assert.matches(seen.post_url, "/bookshelf/delete%?_csrfToken=C1")
|
||||
Assert.matches(seen.body, '"bookId":"35554414603847007"')
|
||||
Assert.eq(n, 1)
|
||||
-- 同一 Cookie AUTH_TTL 内不再每次先打个人接口(每章翻页报进度不再双倍请求)
|
||||
Client.shelfRemoveAsync("35554414603847007", function(wire) ok = wire ~= nil end)
|
||||
Assert.is_true(ok)
|
||||
Assert.eq(n, 1, "校验结果复用")
|
||||
cfg.cookie = "csrfToken=C2; ywKey=K2"
|
||||
Settings.saveSource("ext.xiaoxiang", cfg)
|
||||
Client.shelfRemoveAsync("35554414603847007", function(wire) ok = wire ~= nil end)
|
||||
Assert.eq(n, 2, "换了 Cookie 重新校验")
|
||||
Client.AUTH_TTL = 0
|
||||
Client.shelfRemoveAsync("35554414603847007", function(wire) ok = wire ~= nil end)
|
||||
Assert.eq(n, 4, "过期后写入与回读分别重新校验")
|
||||
Client.AUTH_TTL = 600
|
||||
|
||||
replies[2] = '{"code":0,"data":{"chapterContents":[{"ccid":35554414603847008,"chapterPrice":"0","auth":true,"chapterContent":"甲"}]}}'
|
||||
local text
|
||||
Client.contentAsync("35554414603847007", "35554414603847008", function(t) text = t end)
|
||||
Assert.eq(text, "甲")
|
||||
Assert.matches(seen.body, '"ccids":%["35554414603847008"%]')
|
||||
|
||||
-- 加密章的字体下载回来是 HTML 错误页(CDN 200):不当字体去解,直接报解密失败
|
||||
local fkp = require("utils.text").base64Encode('window.onkeyfocus("pool", 3)')
|
||||
replies[2] = '{"code":0,"data":{"chapterContents":[{"ccid":35554414603847008,"chapterPrice":"0","auth":true,'
|
||||
.. '"encrypt":true,"font":true,"fkp":"' .. fkp .. '","chapterContent":"xx",'
|
||||
.. '"fontResponse":{"fixedFontTtf":"https://cdn.test/f.ttf"}}]}}'
|
||||
replies[1] = "<html>Not Found</html>"
|
||||
cfg.cookie = "csrfToken=C1; ywKey=K; ywGuid=42"
|
||||
Settings.saveSource("ext.xiaoxiang", cfg)
|
||||
local fock_called = false
|
||||
package.loaded["moonsource_xiaoxiang.fock"] = { chapterAsync = function() fock_called = true; return { cancel = function() end } end }
|
||||
local ferr
|
||||
text = nil
|
||||
Client.contentAsync("35554414603847007", "35554414603847008", function(t, e) text, ferr = t, e end)
|
||||
Assert.is_nil(text)
|
||||
Assert.eq(ferr, "潇湘章节解密失败")
|
||||
Assert.is_false(fock_called, "坏字体不进解密")
|
||||
package.loaded["moonsource_xiaoxiang.fock"] = nil
|
||||
cfg.cookie = nil
|
||||
Settings.saveSource("ext.xiaoxiang", cfg)
|
||||
package.loaded["moonsource_xiaoxiang.client"] = nil
|
||||
end
|
||||
|
||||
do
|
||||
local CpSetting = require("moonsource_changpei.setting")
|
||||
Assert.eq(CpSetting.parseCookie("Cookie: PHPSESSID=x; _c_n_=y\n"), "PHPSESSID=x; _c_n_=y")
|
||||
Assert.eq(CpSetting.parseCookie(" "), "")
|
||||
local Settings = require("utils.settings")
|
||||
local Auth = require("source.auth")
|
||||
local cfg = Settings.getSource("ext.changpei")
|
||||
Auth.reset()
|
||||
cfg.cookie = nil
|
||||
Settings.saveSource("ext.changpei", cfg)
|
||||
Assert.eq(#CpSetting.rows(), 4, "未登录:账号 + 浏览器 + 粘贴 + 章评")
|
||||
cfg.cookie = "PHPSESSID=T1"
|
||||
Settings.saveSource("ext.changpei", cfg)
|
||||
Assert.eq(#CpSetting.rows(), 5, "已登录:账号 + 浏览器 + 粘贴 + 退出 + 章评")
|
||||
Auth.expire("ext.changpei", "x")
|
||||
Assert.eq(#CpSetting.rows(), 5, "失效后仍保留浏览器与粘贴入口")
|
||||
cfg.cookie = nil
|
||||
Settings.saveSource("ext.changpei", cfg)
|
||||
Auth.reset()
|
||||
|
||||
local XxSetting = require("moonsource_xiaoxiang.setting")
|
||||
Assert.eq(XxSetting.parseCookie("Cookie: a=1; b=2\n"), "a=1; b=2")
|
||||
Assert.eq(XxSetting.parseCookie("乱七八糟"), "")
|
||||
end
|
||||
|
||||
do
|
||||
local seen, reply = {}, '{"code":9996,"msg":"请先登录","data":[]}'
|
||||
package.loaded["http.request"] = nil
|
||||
package.preload["http.request"] = function()
|
||||
return { get = function(_url, opts, cb) seen.headers = opts.headers; seen.cookie = opts.jar and opts.jar:header(_url); cb(reply) return {} end }
|
||||
end
|
||||
package.loaded["moonsource_changpei.client"] = nil
|
||||
local Settings = require("utils.settings")
|
||||
local cfg = Settings.getSource("ext.changpei")
|
||||
cfg.cookie = "PHPSESSID=T1"
|
||||
Settings.saveSource("ext.changpei", cfg)
|
||||
local Client = require("moonsource_changpei.client")
|
||||
local Auth = require("source.auth")
|
||||
Auth.reset()
|
||||
local err
|
||||
Client.chaptersAsync("1", function(_wire, e) err = e end)
|
||||
Assert.eq(seen.cookie, "PHPSESSID=T1")
|
||||
Assert.eq(seen.headers.Client, "pc")
|
||||
Assert.matches(err, "扫码登录")
|
||||
Assert.is_true(Auth.expired("ext.changpei"))
|
||||
cfg.cookie = nil
|
||||
Settings.saveSource("ext.changpei", cfg)
|
||||
Auth.reset()
|
||||
Client.searchAsync("x", function() end)
|
||||
Assert.is_nil(seen.cookie)
|
||||
Assert.is_true(not Auth.expired("ext.changpei"))
|
||||
package.preload["http.request"] = nil
|
||||
end
|
||||
|
||||
-- 书架 / 阅读历史 / 签名 POST
|
||||
do
|
||||
local Cp = require("moonsource_changpei.mapper")
|
||||
local books = Cp.shelfList({ { id = 7, name = " 书 ", author = "甲", cover = "https://x/a.jpg?x-oss=1" } })
|
||||
Assert.eq(books[1].stable_id, "7")
|
||||
Assert.eq(books[1].title, "书")
|
||||
Assert.eq(books[1].cover, "https://x/a.jpg")
|
||||
local hist = Cp.history({ data = { list = { { list = {
|
||||
{ novel_id = 9, latest_read_cid = 123 }, { novel_id = 8, latest_read_cid = 0 },
|
||||
} } } } })
|
||||
Assert.eq(hist["9"], "123")
|
||||
Assert.is_nil(hist["8"])
|
||||
|
||||
local pages, posted = {}, {}
|
||||
package.loaded["http.request"] = nil
|
||||
package.preload["http.request"] = function()
|
||||
return {
|
||||
get = function(url, _opts, cb)
|
||||
if url:find("system/init", 1, true) then
|
||||
cb('{"code":200,"data":{"timestamp":1792556196}}')
|
||||
else
|
||||
local n = tonumber(url:match("page=(%d+)"))
|
||||
pages[#pages + 1] = n
|
||||
cb(n == 1 and '{"code":200,"data":{"list":[{"type":"novel","id":5},{"type":"shelf","id":1}]}}'
|
||||
or '{"code":200,"data":{"list":[]}}')
|
||||
end
|
||||
return {}
|
||||
end,
|
||||
post = function(url, body, opts, cb)
|
||||
posted = { url = url, body = body, headers = opts.headers }
|
||||
cb('{"code":200,"data":[]}')
|
||||
return {}
|
||||
end,
|
||||
}
|
||||
end
|
||||
package.loaded["moonsource_changpei.client"] = nil
|
||||
local Client = require("moonsource_changpei.client")
|
||||
local rows
|
||||
Client.shelfAsync(function(r) rows = r end)
|
||||
Assert.len(pages, 2)
|
||||
Assert.eq(pages[2], 2)
|
||||
Assert.len(rows, 1)
|
||||
local ok
|
||||
Client.shelfAddAsync("5", function(wire) ok = wire ~= nil end)
|
||||
Assert.is_true(ok)
|
||||
Assert.eq(posted.body, '{"module":"novel","cid":5,"status":1}')
|
||||
Assert.eq(posted.headers.Timestamp, "1792556196")
|
||||
Client.shelfAddAsync("2125021", function() end)
|
||||
Assert.eq(posted.headers["Rand-Str"], "4d427f47b607d1d06ecd0d3a11fbcf7d")
|
||||
Client.shelfRemoveAsync("5", function() end)
|
||||
Assert.eq(posted.body, '{"module":"novel","cid":5,"status":0}')
|
||||
package.preload["http.request"] = nil
|
||||
end
|
||||
|
||||
-- 扫码登录:gRPC-web 帧与 protobuf 顶层字段
|
||||
local QRLogin = require("moonsource_changpei.qrlogin")
|
||||
|
||||
do
|
||||
Assert.eq(QRLogin.frame("Login"), "\0\0\0\0\7\10\5Login")
|
||||
end
|
||||
|
||||
do
|
||||
local token = ("a"):rep(32)
|
||||
local fields = QRLogin.decode("\0\0\0\0\37\10\32" .. token .. "\16\200\1")
|
||||
Assert.eq(fields[1], token)
|
||||
Assert.eq(fields[2], 200)
|
||||
local poll = QRLogin.decode("\0\0\0\0\36\8\4\26\32" .. token)
|
||||
Assert.eq(poll[1], 4)
|
||||
Assert.eq(poll[3], token)
|
||||
Assert.eq(next(QRLogin.decode("")), nil)
|
||||
-- login_res(2){ status 1, web_data(4){ token(1) } }
|
||||
local login = QRLogin.fields("\8\1\34\4\10\2tk")
|
||||
Assert.eq(login[1], 1)
|
||||
Assert.eq(QRLogin.fields(login[4])[1], "tk")
|
||||
end
|
||||
|
||||
do
|
||||
local seen
|
||||
package.loaded["http.request"] = nil
|
||||
package.preload["http.request"] = function()
|
||||
return { get = function(_url, opts, cb) seen = opts.headers; seen.Cookie = opts.jar:header(_url); cb('{"code":200,"data":{}}') return {} end }
|
||||
end
|
||||
package.loaded["moonsource_changpei.client"] = nil
|
||||
require("moonsource_changpei.client").userAsync("PHPSESSID=a; moon_token=TK", function() end)
|
||||
Assert.eq(seen.token, "TK")
|
||||
Assert.eq(seen.Cookie, "PHPSESSID=a")
|
||||
end
|
||||
|
||||
|
||||
-- token 过期(9996):用 refresh_token 换新 token 写回 Cookie 再重发;换不到才算登录失效
|
||||
do
|
||||
local grpc_status, renew_calls, tokens = "0", 0, {}
|
||||
package.loaded["http.request"] = nil
|
||||
package.preload["http.request"] = function()
|
||||
return {
|
||||
header = function(res, name) return res and res[name] end,
|
||||
headerAll = function() return {} end,
|
||||
get = function(_url, opts, cb)
|
||||
tokens[#tokens + 1] = opts.headers.token
|
||||
if opts.headers.token == "OLD" then cb('{"code":9996,"msg":"请先登录"}') else cb('{"code":200,"data":{}}') end
|
||||
return {}
|
||||
end,
|
||||
post = function(url, body, opts, cb)
|
||||
renew_calls = renew_calls + 1
|
||||
Assert.matches(url, "get_token")
|
||||
Assert.eq(body, "\0\0\0\0\4\42\2RF")
|
||||
Assert.eq(opts.headers.imei, "dev")
|
||||
cb("\0\0\0\0\6\26\4NEW1", nil, { ["grpc-status"] = grpc_status })
|
||||
return {}
|
||||
end,
|
||||
}
|
||||
end
|
||||
package.loaded["moonsource_changpei.client"] = nil
|
||||
local Client = require("moonsource_changpei.client")
|
||||
local Auth = require("source.auth")
|
||||
local settings = require("utils.settings")
|
||||
settings.saveSource("ext.changpei", { cookie = "PHPSESSID=a; _c_n_=dev; moon_token=OLD; moon_refresh=RF" })
|
||||
Auth.reset()
|
||||
|
||||
local wire
|
||||
Client.historyAsync(function(w) wire = w end)
|
||||
Assert.not_nil(wire)
|
||||
Assert.eq(renew_calls, 1)
|
||||
Assert.eq(tokens[#tokens], "NEW1")
|
||||
Assert.matches(settings.getSource("ext.changpei").cookie, "moon_token=NEW1")
|
||||
Assert.matches(settings.getSource("ext.changpei").cookie, "moon_refresh=RF")
|
||||
Assert.is_false(Auth.expired("ext.changpei"))
|
||||
|
||||
settings.saveSource("ext.changpei", { cookie = "PHPSESSID=a; _c_n_=dev; moon_token=OLD; moon_refresh=RF" })
|
||||
grpc_status = "16"
|
||||
local failed
|
||||
Client.historyAsync(function(w, err) failed = { w, err } end)
|
||||
Assert.is_nil(failed[1])
|
||||
Assert.matches(failed[2], "moon%-cookie%-storage")
|
||||
Assert.is_true(Auth.expired("ext.changpei"))
|
||||
|
||||
settings.saveSource("ext.changpei", { cookie = "PHPSESSID=a; _c_n_=dev; moon_token=OLD" })
|
||||
Auth.reset()
|
||||
renew_calls = 0
|
||||
Client.historyAsync(function() end)
|
||||
Assert.eq(renew_calls, 0, "没有 refresh_token 不请求")
|
||||
Assert.is_true(Auth.expired("ext.changpei"))
|
||||
settings.saveSource("ext.changpei", {})
|
||||
Auth.reset()
|
||||
package.preload["http.request"] = nil
|
||||
end
|
||||
|
||||
-- 书城榜单:rankingNav → 两行 chip,节点取榜单 + 子榜
|
||||
do
|
||||
package.loaded["http.request"] = nil
|
||||
package.preload["http.request"] = function()
|
||||
return { get = function(url, _opts, cb)
|
||||
if url:find("rankingNav", 1, true) then
|
||||
cb('{"code":200,"data":[{"name":"畅销榜","rank_id":1,"type":[{"name":"昨日","value":1},{"name":"30天","value":3}]},'
|
||||
.. '{"name":"精品榜","rank_id":15,"url":"event/x","type":[]},'
|
||||
.. '{"name":"人气榜","rank_id":3,"type":[{"name":"7天","value":2}]}]}')
|
||||
else
|
||||
cb('{"code":200,"data":{"count":1,"list":[{"novel_id":9,"novel_name":"榜书","novel_author":"甲"}]}}')
|
||||
end
|
||||
return {}
|
||||
end }
|
||||
end
|
||||
package.loaded["moonsource_changpei.client"] = nil
|
||||
package.loaded["moonsource_changpei.source"] = nil
|
||||
local source = require("moonsource_changpei.source").new()
|
||||
local res
|
||||
source:browseAsync({ node = "1:3" }, function(r) res = r end)
|
||||
Assert.eq(res.data[1].stable_id, "9")
|
||||
Assert.len(res.groups[1].chips, 3)
|
||||
Assert.eq(res.groups[1].active, "1:1")
|
||||
Assert.eq(res.groups[2].active, "1:3")
|
||||
package.preload["http.request"] = nil
|
||||
end
|
||||
|
||||
-- 长佩:分页没有页数上限,超过 50 页照样翻到空页
|
||||
do
|
||||
local pages = {}
|
||||
package.loaded["http.request"] = nil
|
||||
package.preload["http.request"] = function()
|
||||
return {
|
||||
get = function(url, _opts, cb)
|
||||
if url:find("system/init", 1, true) then
|
||||
cb('{"code":200,"data":{"timestamp":1792556196}}')
|
||||
else
|
||||
local n = tonumber(url:match("page=(%d+)"))
|
||||
pages[#pages + 1] = n
|
||||
cb(n > 60 and '{"code":200,"data":{"list":[]}}'
|
||||
or ('{"code":200,"data":{"list":[{"type":"novel","id":%d}]}}'):format(n))
|
||||
end
|
||||
return {}
|
||||
end,
|
||||
post = function(_url, _body, _opts, cb) cb('{"code":200,"data":[]}') return {} end,
|
||||
}
|
||||
end
|
||||
package.loaded["moonsource_changpei.client"] = nil
|
||||
local Deep = require("moonsource_changpei.client")
|
||||
local rows, err
|
||||
Deep.shelfAsync(function(r, e) rows, err = r, e end)
|
||||
Assert.is_nil(err)
|
||||
Assert.len(rows, 60)
|
||||
Assert.len(pages, 61)
|
||||
package.preload["http.request"] = nil
|
||||
end
|
||||
|
||||
-- 潇湘:分页没有页数上限,pageCount 多少就翻多少页
|
||||
do
|
||||
local pages = 0
|
||||
package.loaded["http.request"] = nil
|
||||
package.preload["http.request"] = function()
|
||||
return {
|
||||
get = function(url, _opts, cb)
|
||||
if url:find("/bookshelf/pc/page", 1, true) then
|
||||
pages = pages + 1
|
||||
cb('{"code":0,"data":{"pageCount":60,"data":[{"restype":1,"groupId":-100,"bookid":"1","title":"甲"}]}}')
|
||||
else
|
||||
cb('{"code":0,"data":{"isLogin":1,"user":{"guid":"42"}}}')
|
||||
end
|
||||
return {}
|
||||
end,
|
||||
post = function(_url, _body, _opts, cb) cb('{"code":0,"data":{"isLogin":1}}') return {} end,
|
||||
}
|
||||
end
|
||||
local Settings = require("utils.settings")
|
||||
local cfg = Settings.getSource("ext.xiaoxiang")
|
||||
cfg.cookie = "csrfToken=C1; ywKey=K"
|
||||
Settings.saveSource("ext.xiaoxiang", cfg)
|
||||
package.loaded["moonsource_xiaoxiang.client"] = nil
|
||||
local Deep = require("moonsource_xiaoxiang.client")
|
||||
require("source.auth").reset()
|
||||
local rows, err
|
||||
Deep.shelfAsync(function(r, e) rows, err = r, e end)
|
||||
Assert.is_nil(err)
|
||||
Assert.len(rows, 60)
|
||||
Assert.eq(pages, 60)
|
||||
cfg.cookie = nil
|
||||
Settings.saveSource("ext.xiaoxiang", cfg)
|
||||
package.loaded["moonsource_xiaoxiang.client"] = nil
|
||||
package.preload["http.request"] = nil
|
||||
end
|
||||
@@ -0,0 +1,91 @@
|
||||
--[[--
|
||||
潇湘账号失效、换号竞态、写后确认和多阶段取消。
|
||||
|
||||
@module tests.moonsource_xiaoxiang.client_spec
|
||||
--]]
|
||||
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
|
||||
|
||||
local A = require("support.assert")
|
||||
package.loaded["json"] = require("support.json_stub")
|
||||
local cfg = { cookie = "csrfToken=x%26; ywguid=42" }
|
||||
package.loaded["utils.settings"] = { getSource = function() return cfg end }
|
||||
local network, pending, posts, cancelled, shelf = "sync", nil, 0, false, {}
|
||||
local function json(value) return require("json").encode(value) end
|
||||
package.loaded["http.request"] = {
|
||||
get = function(url, opts, cb)
|
||||
A.eq(opts.cache_ttl, 0)
|
||||
if url:find("/user/auth/personal", 1, true) then
|
||||
if network == "wait" then pending = cb
|
||||
elseif network == "failure" then cb(nil, "timeout")
|
||||
elseif network == "expired" then cb('{"code":0,"data":{"isLogin":0}}')
|
||||
else cb('{"code":0,"data":{"isLogin":1,"user":{"guid":42}}}') end
|
||||
else
|
||||
if network == "shelf-wait" then pending = cb
|
||||
else cb(json({ code = 0, data = { data = shelf, pageCount = 1 } })) end
|
||||
end
|
||||
return { cancel = function() cancelled = true end }
|
||||
end,
|
||||
post = function(url, _body, opts, cb)
|
||||
posts = posts + 1
|
||||
A.matches(url, "_csrfToken=x%%2526")
|
||||
A.eq(opts.cache_ttl, 0)
|
||||
cb('{"code":0,"data":null}')
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
package.loaded["moonsource_xiaoxiang.client"] = nil
|
||||
local C = require("moonsource_xiaoxiang.client")
|
||||
local Auth = require("source.auth")
|
||||
Auth.reset()
|
||||
local info, err, result
|
||||
C.userAsync(cfg.cookie, function(value) info = value end)
|
||||
A.eq(info.id, "42")
|
||||
network = "failure"
|
||||
C.shelfAsync(function(value, reason) result, err = value, reason end)
|
||||
A.is_nil(result)
|
||||
A.eq(err, "timeout")
|
||||
A.is_false(Auth.expired("ext.xiaoxiang"), "暂时网络失败保留登录")
|
||||
network = "expired"
|
||||
C.shelfAsync(function(value, reason) result, err = value, reason end)
|
||||
A.is_true(Auth.expired("ext.xiaoxiang"))
|
||||
A.eq(posts, 0)
|
||||
Auth.reset()
|
||||
network = "wait"
|
||||
C.shelfAsync(function(value, reason) result, err = value, reason end)
|
||||
cfg.cookie = "csrfToken=new; ywguid=43"
|
||||
pending('{"code":0,"data":{"isLogin":0}}')
|
||||
A.is_false(Auth.expired("ext.xiaoxiang"), "旧请求不能注销新账号")
|
||||
A.eq(err, "账号已变化,请重新登录")
|
||||
cfg.cookie = "csrfToken=x%26; ywguid=42"
|
||||
network, cancelled, info = "wait", false, nil
|
||||
local user = C.userAsync(cfg.cookie, function(value) info = value end)
|
||||
user.cancel()
|
||||
pending('{"code":0,"data":{"isLogin":1,"user":{"guid":42}}}')
|
||||
A.is_nil(info)
|
||||
A.is_true(cancelled)
|
||||
network = "sync"
|
||||
shelf = { { bookid = "123", ccid = "77", restype = 1, groupId = -100 } }
|
||||
C.shelfAddAsync("123", function(value, reason) result, err = value, reason end)
|
||||
A.is_true(result ~= nil)
|
||||
C.shelfRemoveAsync("123", function(value, reason) result, err = value, reason end)
|
||||
A.is_nil(result)
|
||||
A.eq(err, "潇湘远端状态未更新,请稍后重试")
|
||||
C.progressAsync("123", "77", function(value) result = value end)
|
||||
A.is_true(result ~= nil)
|
||||
C.progressAsync("123", "78", function(value, reason) result, err = value, reason end)
|
||||
A.is_nil(result)
|
||||
A.eq(err, "潇湘远端状态未更新,请稍后重试")
|
||||
shelf = {}
|
||||
C.shelfRemoveAsync("123", function(value) result = value end)
|
||||
A.is_true(result ~= nil)
|
||||
network, cancelled, result = "shelf-wait", false, nil
|
||||
local writing = C.shelfRemoveAsync("123", function(value) result = value end)
|
||||
writing.cancel()
|
||||
A.is_true(cancelled, "同步 POST 后取消实际回读请求")
|
||||
pending('{"code":0,"data":{"data":[],"pageCount":1}}')
|
||||
A.is_nil(result)
|
||||
network = "sync"
|
||||
shelf = { { restype = 1, groupId = -100, title = "缺身份" } }
|
||||
C.shelfAsync(function(value, reason) result, err = value, reason end)
|
||||
A.is_nil(result)
|
||||
A.eq(err, "响应无效", "坏书架行不能变成身份为 nil 的书")
|
||||
@@ -0,0 +1,57 @@
|
||||
--[[--
|
||||
正文归属、扫码 Cookie 大小写与取消后的迟到响应。
|
||||
|
||||
@module tests.moonsource_xiaoxiang.content_spec
|
||||
--]]
|
||||
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
|
||||
|
||||
local A = require("support.assert")
|
||||
local JSON = require("support.json_stub")
|
||||
package.loaded["json"] = JSON
|
||||
local cfg, mode, post_cb, decrypt_cb, stopped = { cookie = "ywguid=42" }, "sync", nil, nil, false
|
||||
package.loaded["utils.settings"] = { getSource = function() return cfg end }
|
||||
local chapter = { ccid = "123", chapterPrice = 20, auth = true, encrypt = true, font = false,
|
||||
chapterContent = "encrypted", fkp = require("utils.text").base64Encode('window.onkeyfocus("pool", 3)') }
|
||||
package.loaded["http.request"] = {
|
||||
post = function(_url, _body, _opts, cb)
|
||||
post_cb = cb
|
||||
if mode == "sync" then cb(JSON.encode({ code = 0, data = { chapterContents = { chapter } } })) end
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
package.loaded["moonsource_xiaoxiang.fock"] = {
|
||||
chapterAsync = function(_chapter, _font, _id, _pool, _version, uid, cb)
|
||||
A.eq(uid, "42", "官网同时接受 ywGuid 与扫码生成的小写 ywguid")
|
||||
decrypt_cb = cb
|
||||
local handle = {}
|
||||
function handle:cancel() A.eq(self, handle); stopped = true end
|
||||
return handle
|
||||
end,
|
||||
}
|
||||
package.loaded["moonsource_xiaoxiang.client"] = nil
|
||||
local C = require("moonsource_xiaoxiang.client")
|
||||
local result, err
|
||||
local handle = C.contentAsync("book", "123", function(text, reason) result, err = text, reason end)
|
||||
handle.cancel()
|
||||
A.is_true(stopped, "同步正文请求不能覆盖解密句柄")
|
||||
decrypt_cb("迟到正文")
|
||||
A.is_nil(result)
|
||||
mode, result = "wait", nil
|
||||
handle = C.contentAsync("book", "123", function(text) result = text end)
|
||||
handle.cancel()
|
||||
post_cb(JSON.encode({ code = 0, data = { chapterContents = { chapter } } }))
|
||||
A.is_nil(result)
|
||||
C.contentAsync("book", "123", function(text, reason) result, err = text, reason end)
|
||||
cfg.cookie = "ywguid=43"
|
||||
post_cb(JSON.encode({ code = 0, data = { chapterContents = { chapter } } }))
|
||||
A.is_nil(result)
|
||||
A.eq(err, "账号已变化,请重新登录")
|
||||
mode, cfg.cookie = "sync", "ywguid=42"
|
||||
chapter.ccid = "456"
|
||||
C.contentAsync("book", "123", function(text, reason) result, err = text, reason end)
|
||||
A.is_nil(result)
|
||||
A.eq(err, "响应无效", "错误章节不能落入请求章节缓存")
|
||||
chapter.ccid, chapter.auth = "123", false
|
||||
C.contentAsync("book", "123", function(text, reason, kind) result, err = text, kind or reason end)
|
||||
A.is_nil(result)
|
||||
A.eq(err, "unpaid")
|
||||
@@ -0,0 +1,54 @@
|
||||
--[[--
|
||||
潇湘新站结构、长整数身份及旧目录兼容。
|
||||
|
||||
@module tests.moonsource_xiaoxiang.mapper_spec
|
||||
--]]
|
||||
|
||||
local A = require("support.assert")
|
||||
package.loaded["json"] = require("support.json_stub")
|
||||
local M = require("moonsource_xiaoxiang.mapper")
|
||||
|
||||
---@type {cbId: string, ccid: string, ratio: number, exp: number, text: string}|nil
|
||||
local decoded = M.decode('{"cbId" : 27760376302677004, "ccid":35554414603847008,"ratio":1.5,"exp":12345678901234567e2,'
|
||||
.. '"text":"{\\"cbId\\":27760376302677004}"}')
|
||||
A.eq(decoded.cbId, "27760376302677004")
|
||||
A.eq(decoded.ccid, "35554414603847008")
|
||||
A.eq(decoded.ratio, 1.5)
|
||||
A.eq(decoded.exp, 12345678901234567e2)
|
||||
A.eq(decoded.text, '{"cbId":27760376302677004}')
|
||||
A.is_nil(M.decode("not JSON"))
|
||||
|
||||
local function page(data)
|
||||
return '<script id="vite-plugin-ssr_pageContext" type="application/json">'
|
||||
.. '{"pageContext":{"pageProps":{"pageData":' .. data .. '}}}</script>'
|
||||
end
|
||||
local book = M.detail(page('{"detailData":{"cbid":"27760376302677004","title":" 灯花笑 ","author":"千山茶客",'
|
||||
.. '"intro":"简介","categoryShortName":"古代言情","totalWords":1200}}'))
|
||||
A.eq(book.stable_id, "27760376302677004")
|
||||
A.eq(book.title, "灯花笑")
|
||||
A.eq(book.category, "古代言情")
|
||||
A.eq(book.words, 1200)
|
||||
A.is_nil(M.detail("<html>维护</html>"))
|
||||
A.is_nil(M.books({ { title = "缺身份" } }))
|
||||
A.len(M.books({}), 0)
|
||||
local books = M.books({ { cbId = "123", bookName = "书", authorName = "作者", cate2Name = "分类" } })
|
||||
A.eq(books[1].authors, "作者")
|
||||
|
||||
local toc = M.toc(page('{"chapters":[{"type":0,"title":"正文卷"},'
|
||||
.. '{"type":1,"ccid":35554414603847008,"title":"第1章","price":0},'
|
||||
.. '{"type":1,"ccid":"35554414603847009","title":"第2章","price":25}]}'))
|
||||
A.len(toc, 2)
|
||||
A.eq(toc[1].uid, "35554414603847008")
|
||||
A.eq(toc[2].idx, 2)
|
||||
A.is_nil(toc[1].vip)
|
||||
A.is_true(toc[2].vip)
|
||||
A.eq(toc[1].toc_version, 1)
|
||||
A.is_nil(M.toc(page('{"chapters":[{"type":1,"title":"缺身份"}]}')))
|
||||
local legacy = M.toc('x"chapters":[{"type":0},{"type":1,"ccid":"42","title":"旧章","price":0}]')
|
||||
A.eq(legacy[1].uid, "42")
|
||||
A.len(M.toc(page('{"chapters":[]}')), 0)
|
||||
local ranks = page('[{"columnInfo":{"name":"潇湘票榜"},"bookList":[]},'
|
||||
.. '{"columnInfo":{"name":"收藏榜"},"bookList":[{"cbid":"123","title":"收藏书"}]}]')
|
||||
A.len(M.rank(ranks, "潇湘票榜"), 0, "真实空榜单与坏页面分别处理")
|
||||
A.eq(M.rank(ranks, "收藏榜")[1].title, "收藏书")
|
||||
A.is_nil(M.rank(ranks, "不存在的榜单"))
|
||||
@@ -0,0 +1,58 @@
|
||||
--[[--
|
||||
进度编排保护同步取消句柄与目录返回前的账号变更。
|
||||
|
||||
@module tests.moonsource_xiaoxiang.progress_spec
|
||||
--]]
|
||||
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
|
||||
|
||||
local A = require("support.assert")
|
||||
local cookie, delayed, toc_cb, write_cb, stopped, writes = "old", false, nil, nil, false, 0
|
||||
local toc = { { uid = "77", title = "第一章" }, { uid = "78", title = "第二章" } }
|
||||
package.loaded["moonsource_xiaoxiang.client"] = {
|
||||
cookie = function() return cookie end,
|
||||
shelfAsync = function(cb)
|
||||
cb({ { bookid = "123", ccid = "78" } })
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
progressAsync = function(_book, _chapter, cb)
|
||||
writes = writes + 1
|
||||
write_cb = cb
|
||||
return { cancel = function() stopped = true end }
|
||||
end,
|
||||
}
|
||||
package.loaded["source.toc"] = { index = function() return 2 end }
|
||||
package.loaded["moonsource_xiaoxiang.source"] = nil
|
||||
local source = require("moonsource_xiaoxiang.source").new()
|
||||
function source:loadTocAsync(_identity, cb)
|
||||
toc_cb = cb
|
||||
if not delayed then cb(toc) end
|
||||
return { cancel = function() stopped = true end }
|
||||
end
|
||||
local identity = { source_id = "ext.xiaoxiang", stable_id = "123" }
|
||||
local result, err
|
||||
source:getProgressAsync(identity, function(data) result = data end)
|
||||
A.eq(result.chapter_idx, 2)
|
||||
A.eq(result.fraction, 0.5)
|
||||
delayed, stopped, result = true, false, nil
|
||||
local handle = source:getProgressAsync(identity, function(data) result = data end)
|
||||
handle.cancel()
|
||||
A.is_true(stopped)
|
||||
toc_cb(toc)
|
||||
A.is_nil(result)
|
||||
source:getProgressAsync(identity, function(data, reason) result, err = data, reason end)
|
||||
cookie = "new"
|
||||
toc_cb(toc)
|
||||
A.is_nil(result)
|
||||
A.eq(err, "账号已变化,请重新登录")
|
||||
cookie, delayed, stopped = "old", false, false
|
||||
handle = source:putProgressAsync(identity, { chapter_idx = 2 }, function(data) result = data end)
|
||||
handle.cancel()
|
||||
A.is_true(stopped)
|
||||
write_cb({})
|
||||
A.is_nil(result)
|
||||
delayed = true
|
||||
source:putProgressAsync(identity, { chapter_idx = 2 }, function(data, reason) result, err = data, reason end)
|
||||
cookie = "new"
|
||||
toc_cb(toc)
|
||||
A.eq(writes, 1, "不能把旧书进度推到新账号")
|
||||
A.eq(err, "账号已变化,请重新登录")
|
||||
@@ -0,0 +1,51 @@
|
||||
--[[-- 潇湘账号:续期不动同步状态,换号保留本地记录。 @module tests.moonsource_xiaoxiang.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_xiaoxiang.client"] = function()
|
||||
return {
|
||||
cookie = function() return cfg.cookie end,
|
||||
userAsync = function(cookie, cb)
|
||||
Assert.is_true(cookie ~= "session=old")
|
||||
cb({ id = cookie == "session=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.xiaoxiang")
|
||||
Assert.is_true(shelf_add)
|
||||
Assert.eq(cfg.cookie, "session=old")
|
||||
prepared = prepared + 1
|
||||
return true
|
||||
end }
|
||||
end
|
||||
local Setting = require("moonsource_xiaoxiang.setting")
|
||||
local function apply(value)
|
||||
local ok
|
||||
Setting.browser.apply({ cookies = { { name = "session", value = value, domain = ".xxsypro.com" } } },
|
||||
function(result) ok = result end)
|
||||
Assert.is_true(ok)
|
||||
end
|
||||
cfg = { cookie = "session=old", account_id = "111" }
|
||||
apply("same")
|
||||
Assert.eq(prepared, 0)
|
||||
cfg = { cookie = "session=old", account_id = "111" }
|
||||
apply("new")
|
||||
Assert.eq(prepared, 1)
|
||||
Assert.eq(cfg.account_id, "222")
|
||||
Assert.is_nil(Theme.last("confirm"))
|
||||
cfg = { cookie = "session=old" }
|
||||
apply("same")
|
||||
Assert.eq(prepared, 2)
|
||||
@@ -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");
|
||||
Reference in new issue
Block a user