✨ 初始提交:月读第三方书源插件集合
每个书源一个独立插件目录,含微信读书公众号订阅、书架导入等完整功能。 Co-authored-by: Copilot <[email protected]>
This commit is contained in:
commit
0956063d06
44 files changed
+21495
No files matched your search
@@ -0,0 +1,22 @@
|
||||
# 起点中文网
|
||||
|
||||
| 能力 | 是否支持 | 备注 |
|
||||
| --- | --- | --- |
|
||||
| 扫码登录 | 支持 | 完成官方站点兑换后再校验账号;新扫码已购流程仍需实测 |
|
||||
| 手机短信登录 | 已实现,未实测 | 支持图片验证码及腾讯验证桥,安全验证由用户完成 |
|
||||
| 浏览器登录与 Cookie 导入 | 支持 | 支持扩展回传及手动粘贴 |
|
||||
| 设备密码登录 | 不支持 | 短信登录不是密码登录 |
|
||||
| 书架拉取 | 支持 | 分组、分页及书号去重 |
|
||||
| 书架新增与移出 | 已实现,未实测 | 本地先生效,联网后推送;远端写入回读未完成 |
|
||||
| 分类书城 | 支持 | 男/女频、子分类、资费、字数、状态、签约、更新时间和排序 |
|
||||
| 榜单与搜索 | 支持 | 七种榜单;列表默认聚合 60 本,搜索最多 200 本 |
|
||||
| 详情与分卷目录 | 支持 | 保留章节 ID 和已有目录缓存 |
|
||||
| 免费与已购正文 | 支持 | 按官网权限解码,不购买或绕过权限 |
|
||||
| 章节与全本缓存 | 支持 | 已缓存章节可离线打开;未购提示不计入正文缓存 |
|
||||
| 阅读进度同步 | 部分支持 | 仅章节位置,无章内比例;远端写后回读未实测 |
|
||||
| 笔记与统计同步 | 不支持 | 仅本地保存 |
|
||||
| 整书书友圈 | 部分支持 | 详情展示最多三条帖子预览,不是完整列表 |
|
||||
| 章评与段评 | 支持 | 真正章末评论与段落评论共存,支持定位、分页及缓存 |
|
||||
| 评论回复 | 部分支持 | 仅服务器附带的二级预览,可本地翻阅;没有完整回复分页 |
|
||||
| 评论写操作 | 不支持 | 不发评、不点赞、不删评 |
|
||||
| 账号切换 | 部分支持 | 同账号可续期;换号须确认清理旧本地数据,未同步记录会丢失 |
|
||||
@@ -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_qidian",
|
||||
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_qidian.source").meta() end,
|
||||
new = function() return require("moonsource_qidian.source").new() end,
|
||||
setting = lazy("moonsource_qidian.setting"),
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
--[[--
|
||||
书源元信息:id / 名称 / 类型,加上启用页展示用的说明与能力清单。`init.lua` 的 `meta()` 直接返回本表。
|
||||
|
||||
@module moonsource_qidian._meta
|
||||
--]]
|
||||
|
||||
local _ = require("l10n").get("moonsource_qidian")
|
||||
|
||||
return {
|
||||
id = "ext.qidian",
|
||||
name = _("起点中文网"),
|
||||
type = "chapter",
|
||||
description = _("起点中文网书架与在线阅读"),
|
||||
abilities = { _("扫码登录"), _("手机号验证码登录"), _("搜索与发现"), _("书架同步"),
|
||||
_("进度同步"), _("VIP 章节"), _("他人段评"), _("章节评论"), _("书友圈帖子预览") },
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
--[[--
|
||||
起点分类书库:动态男频分类、官网筛选、匿名分页。节点保留全部已选条件。
|
||||
|
||||
@module moonsource_qidian.browse
|
||||
--]]
|
||||
|
||||
local Client = require("moonsource_qidian.client")
|
||||
local Mapper = require("moonsource_qidian.mapper")
|
||||
local Browse = require("source.browse")
|
||||
local Text = require("utils.text")
|
||||
local _ = require("l10n").get("moonsource_qidian")
|
||||
|
||||
local Library = {}
|
||||
-- 官网动态标签:预译已知标签,未知标签仍沿用 gettext 的原文回退。
|
||||
local LABELS = {
|
||||
["100~200万"] = _("100~200万"), ["200万以上"] = _("200万以上"),
|
||||
["30~50万"] = _("30~50万"), ["30万以下"] = _("30万以下"), ["50~100万"] = _("50~100万"),
|
||||
["VIP"] = _("VIP"), ["一月内"] = _("一月内"), ["七日内"] = _("七日内"), ["三日内"] = _("三日内"),
|
||||
["东方玄幻"] = _("东方玄幻"), ["二级分类"] = _("二级分类"), ["人气"] = _("人气"),
|
||||
["半月内"] = _("半月内"), ["品质"] = _("品质"), ["完本"] = _("完本"), ["属性"] = _("属性"),
|
||||
["异世大陆"] = _("异世大陆"), ["月票"] = _("月票"), ["点击"] = _("点击"),
|
||||
["王朝争霸"] = _("王朝争霸"), ["签约作品"] = _("签约作品"), ["精品小说"] = _("精品小说"),
|
||||
["连载"] = _("连载"), ["高武世界"] = _("高武世界"),
|
||||
}
|
||||
local KEYS = { catId = true, subCatId = true, isvip = true, size = true, isfinish = true,
|
||||
sign = true, update = true, orderBy = true, gender = true }
|
||||
-- m.qdmm.com 的分类目录目前返回风控页;这些是电脑官网 /all/ 实际公布的女频分类。
|
||||
local FEMALE = {
|
||||
{ catId = 80, catName = "古代言情" }, { catId = 81, catName = "仙侠奇缘" },
|
||||
{ catId = 82, catName = "现代言情" }, { catId = 83, catName = "浪漫青春" },
|
||||
{ catId = 84, catName = "玄幻言情" }, { catId = 85, catName = "悬疑推理" },
|
||||
{ catId = 30083, catName = "短篇" }, { catId = 86, catName = "科幻空间" },
|
||||
{ catId = 88, catName = "游戏竞技" }, { catId = 87, catName = "轻小说" },
|
||||
{ catId = 30120, catName = "现实生活" },
|
||||
}
|
||||
|
||||
local function node(params)
|
||||
return "category?" .. Text.formEncode(params)
|
||||
end
|
||||
|
||||
local function change(params, key, value)
|
||||
local out = {}
|
||||
for name, current in pairs(params) do out[name] = current end
|
||||
out[key] = value == "" and nil or tostring(value)
|
||||
if key == "catId" then out.subCatId = nil end
|
||||
if key == "gender" then
|
||||
out.catId = value == "female" and "80" or "21"
|
||||
out.subCatId = nil
|
||||
end
|
||||
return node(out)
|
||||
end
|
||||
|
||||
local function groups(params, categories, data)
|
||||
local current = node(params)
|
||||
local channels = Browse.group({
|
||||
{ id = params.gender == "male" and current or change(params, "gender", "male"), title = _("男频") },
|
||||
{ id = params.gender == "female" and current or change(params, "gender", "female"), title = _("女频") },
|
||||
{ id = "yuepiao:-1", title = _("排行榜") },
|
||||
}, current)
|
||||
channels.title = _("频道")
|
||||
local cats = {}
|
||||
for _idx, cat in ipairs(params.gender == "female" and FEMALE or categories) do
|
||||
cats[#cats + 1] = { id = change(params, "catId", cat.catId), title = _(cat.catName) }
|
||||
end
|
||||
local category = Browse.group(cats, current)
|
||||
category.title = _("分类")
|
||||
local out = { channels, category }
|
||||
local sorts = {}
|
||||
for _idx, item in ipairs(data.orderBy.items) do
|
||||
sorts[#sorts + 1] = { id = change(params, "orderBy", item.value), title = LABELS[item.text] or _(item.text) }
|
||||
end
|
||||
local sort = Browse.group(sorts, current)
|
||||
sort.title = _("排序")
|
||||
out[#out + 1] = sort
|
||||
for _idx, filter in ipairs(data.filters) do
|
||||
local chips = {}
|
||||
for _item, item in ipairs(filter.items) do
|
||||
local value = tostring(item.value)
|
||||
chips[#chips + 1] = {
|
||||
id = change(params, filter.key, value),
|
||||
title = LABELS[item.text] or _(item.text),
|
||||
}
|
||||
end
|
||||
local group = Browse.group(chips, current)
|
||||
group.title = filter.key == "subCatId" and _("子分类")
|
||||
or (LABELS[filter.title] or _(filter.title))
|
||||
out[#out + 1] = group
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
---@param self QidianSource
|
||||
---@param opts { node?: string, limit?: integer }
|
||||
---@param cb fun(res: table|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
function Library.run(self, opts, cb)
|
||||
local params = { gender = "male", catId = "21" }
|
||||
if opts.node then
|
||||
for key, value in opts.node:sub(10):gmatch("([^&=]+)=([^&]*)") do
|
||||
if not KEYS[key] or (key ~= "gender" and not value:match("^%d*$")) then
|
||||
return require("source.base").defer(cb, nil, _("起点分类条件无效"))
|
||||
end
|
||||
params[key] = Text.urlDecode(value)
|
||||
end
|
||||
end
|
||||
if params.gender ~= "male" and params.gender ~= "female" then
|
||||
return require("source.base").defer(cb, nil, _("起点分类条件无效"))
|
||||
end
|
||||
local cancelled, job = false, nil
|
||||
local function load(categories)
|
||||
local pending = true
|
||||
local inner = Client.categoryAsync(params.catId, function(data, err)
|
||||
pending = false
|
||||
if cancelled then return end
|
||||
if not data then cb(nil, err); return end
|
||||
if type(data.filters) ~= "table" or type(data.orderBy) ~= "table"
|
||||
or type(data.orderBy.items) ~= "table" then cb(nil, _("起点分类响应无效")); return end
|
||||
job = Browse.pages(function(page, done)
|
||||
local query = {}
|
||||
for key, value in pairs(params) do query[key] = value end
|
||||
query.pageNum = page
|
||||
return Client.categoryListAsync(query, function(list, reason)
|
||||
if not list then done(nil, reason); return end
|
||||
local more = list.isLast ~= 1 and list.isLast ~= true
|
||||
and (not tonumber(list.pageMax) or page < tonumber(list.pageMax))
|
||||
done(Mapper.rank(list), nil, more)
|
||||
end)
|
||||
end, opts.limit or 60, groups(params, categories, data), function(result, reason)
|
||||
if not cancelled then cb(result, reason) end
|
||||
end)
|
||||
end)
|
||||
if pending then job = inner end
|
||||
end
|
||||
if self.category_info then
|
||||
load(self.category_info)
|
||||
else
|
||||
local pending = true
|
||||
local inner = Client.categoryAsync(nil, function(data, err)
|
||||
pending = false
|
||||
if cancelled then return end
|
||||
if not data then cb(nil, err); return end
|
||||
if type(data.info) ~= "table" or #data.info == 0 then cb(nil, _("起点分类响应无效")); return end
|
||||
self.category_info = data.info
|
||||
load(data.info)
|
||||
end)
|
||||
if pending then job = inner end
|
||||
end
|
||||
return { cancel = function()
|
||||
cancelled = true
|
||||
if job then job.cancel() end
|
||||
end }
|
||||
end
|
||||
|
||||
return Library
|
||||
@@ -0,0 +1,636 @@
|
||||
--[[--
|
||||
起点中文网 HTTP 客户端(仅异步)。
|
||||
|
||||
详情、目录、章节走手机站 SSR 页面(m.qidian.com,页面内嵌 pageContext JSON)。
|
||||
www.qidian.com 有 WAF,不用。书架是 /webcommon/bookshelf/*,要带 Cookie 里的 _csrfToken。
|
||||
进度是章:拉书架行的 readCid;上传 /webcommon/chapter/updReadStatus。
|
||||
chapterUpdateTime 必须是章节更新时间的 unix 秒,空字符串会把 getReadStatus 写坏,日期字符串直接 500。
|
||||
免费章匿名可读(isBuy 仍是 0)。VIP 章 vipStatus=1 且 isBuy 不是 1 时只有预览;已购 VIP 的 content 是密文(cES / fEnS 非 0),由 fock.lua 解密(密钥 = Cookie 的 ywguid + 页面 fkp)。
|
||||
|
||||
@module koplugin.book.moonsource_qidian.client
|
||||
--]]
|
||||
|
||||
local Fock = require("moonsource_qidian.fock")
|
||||
local CookieLogin = require("source.cookie_login")
|
||||
local JSON = require("json")
|
||||
local logger = require("utils.log")
|
||||
local Mapper = require("moonsource_qidian.mapper")
|
||||
local Request = require("http.request")
|
||||
local SourceBase = require("source.base")
|
||||
local Text = require("utils.text")
|
||||
local _ = require("l10n").get("moonsource_qidian")
|
||||
|
||||
local Client = {}
|
||||
|
||||
local SOURCE_ID = "ext.qidian"
|
||||
local WEB = "https://m.qidian.com"
|
||||
local UA = "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) "
|
||||
.. "Version/16.0 Mobile/15E148 Safari/604.1"
|
||||
local PAGE_SIZE = 20
|
||||
local anon_csrf
|
||||
|
||||
local function anonymousCookie()
|
||||
if not anon_csrf then anon_csrf = "_csrfToken=" .. require("utils.random").hex(16) end
|
||||
return anon_csrf
|
||||
end
|
||||
|
||||
---@return string|nil
|
||||
function Client.cookie()
|
||||
local cookie = require("utils.settings").getSource(SOURCE_ID).cookie
|
||||
return type(cookie) == "string" and cookie ~= "" and cookie or nil
|
||||
end
|
||||
|
||||
--- Cookie 请求头里的 _csrfToken。没有它书架接口一律 403。
|
||||
---@param cookie string
|
||||
---@return string|nil
|
||||
function Client.csrf(cookie)
|
||||
local token = type(cookie) == "string" and (
|
||||
cookie:match("^_csrfToken=([^;]+)") or cookie:match(";%s*_csrfToken=([^;]+)"))
|
||||
if not token or token == "" then return nil end
|
||||
return token
|
||||
end
|
||||
|
||||
---@param cookie string|nil
|
||||
---@return string|nil
|
||||
function Client.guid(cookie)
|
||||
local value = type(cookie) == "string" and (cookie:match("^ywguid=([^;]+)")
|
||||
or cookie:match(";%s*ywguid=([^;]+)"))
|
||||
return value and value:match("^%d+$") and value or nil
|
||||
end
|
||||
|
||||
---@param cookie string|nil
|
||||
---@return table
|
||||
local function headers(cookie)
|
||||
return {
|
||||
Cookie = cookie,
|
||||
["User-Agent"] = UA,
|
||||
Referer = WEB .. "/bookshelf/my/",
|
||||
Origin = WEB,
|
||||
}
|
||||
end
|
||||
|
||||
---@param cookie string
|
||||
---@param params table|nil
|
||||
---@return string
|
||||
local function query(cookie, params)
|
||||
local parts = {}
|
||||
for key, value in pairs(params or {}) do
|
||||
parts[#parts + 1] = Text.urlEncode(key) .. "=" .. Text.urlEncode(value)
|
||||
end
|
||||
local token = Client.csrf(cookie)
|
||||
if token then parts[#parts + 1] = "_csrfToken=" .. Text.urlEncode(token) end
|
||||
table.sort(parts)
|
||||
return table.concat(parts, "&")
|
||||
end
|
||||
|
||||
--- 登录态失效只标记当前已保存的 Cookie,校验新 Cookie 时不污染旧登录态。
|
||||
---@param cookie string
|
||||
---@param msg string
|
||||
---@return string
|
||||
local function expired(cookie, msg)
|
||||
if cookie ~= "" and cookie == Client.cookie() then
|
||||
return require("source.auth").expire(SOURCE_ID, msg)
|
||||
end
|
||||
return msg
|
||||
end
|
||||
|
||||
---@param cookie string
|
||||
---@return string
|
||||
local function loginGone(cookie)
|
||||
return expired(cookie, _("起点登录已失效,请点「重新登录」,用 QQ阅读或起点 App 扫码。也可在账号设置里粘贴 Cookie。"))
|
||||
end
|
||||
|
||||
---@param path string
|
||||
---@param cookie string|nil
|
||||
---@param cb fun(html: string|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
local function webGet(path, cookie, cb, cache_ttl)
|
||||
return Request.get(WEB .. path, {
|
||||
headers = headers(cookie),
|
||||
timeout = require("http.timeout").net(1),
|
||||
cache_ttl = cache_ttl,
|
||||
}, function(raw, err, res)
|
||||
if not raw then
|
||||
local code = res and tonumber(res.code)
|
||||
if cookie and cookie ~= "" and (code == 302 or code == 403) then
|
||||
cb(nil, loginGone(cookie or ""))
|
||||
else
|
||||
cb(nil, err and tostring(err) or _("请求失败"))
|
||||
end
|
||||
return
|
||||
end
|
||||
cb(raw)
|
||||
end)
|
||||
end
|
||||
|
||||
---@param wire table|nil
|
||||
---@param cookie string
|
||||
---@return table|nil data
|
||||
---@return string|nil err
|
||||
local function okData(wire, cookie)
|
||||
if tonumber(wire.code) == 0 and type(wire.data) == "table" then return wire.data end
|
||||
local msg = type(wire.msg) == "string" and wire.msg ~= "" and wire.msg or _("响应无效")
|
||||
if tonumber(wire.code) == 1403 then msg = loginGone(cookie) end
|
||||
return nil, msg
|
||||
end
|
||||
|
||||
---@param path string
|
||||
---@param params table
|
||||
---@param cookie string
|
||||
---@param cb fun(data: table|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
local function apiGet(path, params, cookie, cb)
|
||||
return Request.get(WEB .. path .. "?" .. query(cookie, params), {
|
||||
accept = "application/json",
|
||||
headers = headers(cookie),
|
||||
timeout = require("http.timeout").net(1),
|
||||
}, function(raw, err, res)
|
||||
if not raw then
|
||||
local code = res and tonumber(res.code)
|
||||
if cookie:find("ywkey=", 1, true) and (code == 302 or code == 403) then
|
||||
cb(nil, loginGone(cookie))
|
||||
else
|
||||
cb(nil, err and tostring(err) or _("请求失败"))
|
||||
end
|
||||
return
|
||||
end
|
||||
local ok, wire = pcall(JSON.decode, raw)
|
||||
if not ok or type(wire) ~= "table" then cb(nil, _("响应无效")); return end
|
||||
cb(okData(wire, cookie))
|
||||
end)
|
||||
end
|
||||
|
||||
---@param book_id string
|
||||
---@param data table|nil
|
||||
---@return boolean ok
|
||||
---@return string|nil err
|
||||
local function bookOk(book_id, data)
|
||||
local row = type(data) == "table" and (data[book_id] or data[tostring(book_id)])
|
||||
if type(row) == "table" and tonumber(row.code) ~= 0 then
|
||||
return false, row.message or _("请求失败")
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
--- 拉书架。先拉默认分组,再拉其余有书的分组,按书号去重。
|
||||
---@param cookie string
|
||||
---@param cb fun(rows: table[]|nil, err: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
function Client.shelfAsync(cookie, cb)
|
||||
if type(cookie) ~= "string" or cookie == "" then
|
||||
return SourceBase.defer(cb, nil, _("未登录起点"))
|
||||
end
|
||||
if not Client.csrf(cookie) then
|
||||
return SourceBase.defer(cb, nil, _("起点 Cookie 缺少登录凭证"))
|
||||
end
|
||||
local cancelled, job = false, nil
|
||||
local books, seen, groups = {}, {}, nil
|
||||
-- 自定义分组:id→名、bookId→分组名(一本书进多个组取第一个,和微信读书同一口径)。
|
||||
-- 默认分组(-100)不算分组,没进自定义组的书在 Mapper 里保留题材分类。
|
||||
local group_names, group_by_id = {}, {}
|
||||
local fetchPage
|
||||
local function addRows(list)
|
||||
for _idx, row in ipairs(type(list) == "table" and list or {}) do
|
||||
local id = row.bid and tostring(row.bid)
|
||||
if id and not seen[id] then
|
||||
seen[id] = true
|
||||
books[#books + 1] = row
|
||||
end
|
||||
end
|
||||
end
|
||||
local function noteGroup(gid, list)
|
||||
local name = group_names[gid]
|
||||
if not name then return end
|
||||
for _idx, row in ipairs(type(list) == "table" and list or {}) do
|
||||
local id = row.bid and tostring(row.bid)
|
||||
if id then group_by_id[id] = group_by_id[id] or name end
|
||||
end
|
||||
end
|
||||
local function finish(err)
|
||||
if cancelled then return end
|
||||
if err then cb(nil, err); return end
|
||||
for _idx, row in ipairs(books) do
|
||||
row._group_name = group_by_id[tostring(row.bid)]
|
||||
end
|
||||
cb(books)
|
||||
end
|
||||
local function nextGroup()
|
||||
local gid = groups and table.remove(groups, 1)
|
||||
if not gid then finish(); return end
|
||||
fetchPage(gid, 1)
|
||||
end
|
||||
fetchPage = function(gid, page)
|
||||
if cancelled then return end
|
||||
job = apiGet("/webcommon/bookshelf/mlist", {
|
||||
gid = gid, sort = 0, pageNum = page, pageSize = PAGE_SIZE, sortChange = 0,
|
||||
}, cookie, function(data, err)
|
||||
if cancelled then return end
|
||||
if not data then finish(err); return end
|
||||
addRows(data.list)
|
||||
if groups == nil then
|
||||
groups = {}
|
||||
for _idx, group in ipairs(type(data.groups) == "table" and data.groups or {}) do
|
||||
local id = tonumber(group.groupId)
|
||||
if id and id ~= -100 and tonumber(group.bookCount) ~= 0 then
|
||||
groups[#groups + 1] = id
|
||||
local name = type(group.groupName) == "string" and group.groupName or ""
|
||||
if name ~= "" then group_names[id] = name end
|
||||
end
|
||||
end
|
||||
end
|
||||
noteGroup(gid, data.list)
|
||||
local info = type(data.page) == "table" and data.page or {}
|
||||
local list = type(data.list) == "table" and data.list or {}
|
||||
if info.isLast == 1 or info.isLast == true or #list < PAGE_SIZE then
|
||||
nextGroup()
|
||||
else
|
||||
fetchPage(gid, page + 1)
|
||||
end
|
||||
end)
|
||||
end
|
||||
fetchPage(-100, 1)
|
||||
return { cancel = function()
|
||||
cancelled = true
|
||||
if job then job.cancel() end
|
||||
end }
|
||||
end
|
||||
|
||||
--- 校验 Cookie:书架页 200 且 pageData.user.isLogin。cookie 显式传入,登录入口先校验再保存。
|
||||
--- 扫码会话可以没有 _csrfToken;校验成功后把书架页 Set-Cookie 合并进 account.cookie 再落盘。
|
||||
---@param cookie string
|
||||
---@param cb fun(ok: boolean|nil, err: string|nil, account: { id: string, cookie?: string }|nil)
|
||||
---@return { cancel: fun() }
|
||||
function Client.loginCheckAsync(cookie, cb)
|
||||
if type(cookie) ~= "string" or cookie == "" then
|
||||
return SourceBase.defer(cb, nil, _("没有读到 Cookie"))
|
||||
end
|
||||
return Request.get(WEB .. "/bookshelf/my/", {
|
||||
headers = headers(cookie),
|
||||
timeout = require("http.timeout").net(1),
|
||||
cache_ttl = 0,
|
||||
}, function(raw, err, res)
|
||||
if not raw then
|
||||
local code = res and tonumber(res.code)
|
||||
if code == 302 or code == 403 then
|
||||
cb(nil, loginGone(cookie))
|
||||
else
|
||||
cb(nil, err and tostring(err) or _("请求失败"))
|
||||
end
|
||||
return
|
||||
end
|
||||
local user = (Mapper.pageData(raw) or {}).user
|
||||
if not (type(user) == "table" and (user.isLogin == true or user.login == true)) then
|
||||
cb(nil, loginGone(cookie))
|
||||
return
|
||||
end
|
||||
local guid = user.guid
|
||||
if type(guid) ~= "number" and type(guid) ~= "string" then
|
||||
cb(nil, _("起点账号标识缺失")); return
|
||||
end
|
||||
local id = type(guid) == "number" and string.format("%.0f", guid) or guid
|
||||
if not id:match("^%d+$") then cb(nil, _("起点账号标识缺失")); return end
|
||||
local refreshed = CookieLogin.parse(cookie, Request.headerAll(res, "Set-Cookie"))
|
||||
if not Client.csrf(refreshed) then
|
||||
cb(nil, _("起点 Cookie 缺少登录凭证")); return
|
||||
end
|
||||
if cookie == Client.cookie() or refreshed == Client.cookie() then
|
||||
require("source.auth").ok(SOURCE_ID)
|
||||
end
|
||||
cb(true, nil, { id = id, cookie = refreshed })
|
||||
end)
|
||||
end
|
||||
|
||||
---@param book_id string
|
||||
---@param cb fun(ok: boolean|nil, err: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
function Client.addAsync(book_id, cb)
|
||||
local cookie = Client.cookie()
|
||||
if not cookie then return SourceBase.defer(cb, nil, _("未登录起点")) end
|
||||
if not Client.csrf(cookie) then return SourceBase.defer(cb, nil, _("起点 Cookie 缺少登录凭证")) end
|
||||
return Request.post(WEB .. "/webcommon/bookshelf/addbooks?" .. query(cookie), Text.formEncode({ bookId = book_id }), {
|
||||
content_type = "application/x-www-form-urlencoded",
|
||||
headers = headers(cookie),
|
||||
timeout = require("http.timeout").net(1),
|
||||
}, function(raw, err)
|
||||
if not raw then cb(nil, err and tostring(err) or _("请求失败")); return end
|
||||
local ok, wire = pcall(JSON.decode, raw)
|
||||
if not ok or type(wire) ~= "table" then cb(nil, _("响应无效")); return end
|
||||
local data, data_err = okData(wire, cookie)
|
||||
if not data then cb(nil, data_err); return end
|
||||
local added, add_err = bookOk(book_id, data)
|
||||
cb(added and true or nil, add_err)
|
||||
end)
|
||||
end
|
||||
|
||||
--- 上报读到哪一章。updated 是章节更新时间的 unix 秒,不是「现在」。
|
||||
---@param book_id string
|
||||
---@param chapter_id string
|
||||
---@param chapter_name string|nil
|
||||
---@param is_vip integer|boolean|nil
|
||||
---@param updated integer|string
|
||||
---@param cb fun(ok: boolean|nil, err: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
function Client.updateReadAsync(book_id, chapter_id, chapter_name, is_vip, updated, cb)
|
||||
local cookie = Client.cookie()
|
||||
if not cookie then return SourceBase.defer(cb, nil, _("未登录起点")) end
|
||||
if not Client.csrf(cookie) then return SourceBase.defer(cb, nil, _("起点 Cookie 缺少登录凭证")) end
|
||||
if updated == nil or tostring(updated) == "" then
|
||||
return SourceBase.defer(cb, nil, _("起点章节时间缺失"))
|
||||
end
|
||||
return Request.post(WEB .. "/webcommon/chapter/updReadStatus?" .. query(cookie), Text.formEncode({
|
||||
bookId = book_id,
|
||||
chapterId = chapter_id,
|
||||
chapterName = chapter_name or "",
|
||||
isVip = (is_vip == true or tonumber(is_vip) == 1) and "1" or "0",
|
||||
chapterUpdateTime = tostring(updated),
|
||||
}), {
|
||||
content_type = "application/x-www-form-urlencoded",
|
||||
headers = headers(cookie),
|
||||
timeout = require("http.timeout").net(1),
|
||||
}, function(raw, err)
|
||||
if not raw then cb(nil, err and tostring(err) or _("请求失败")); return end
|
||||
local ok, wire = pcall(JSON.decode, raw)
|
||||
if not ok or type(wire) ~= "table" then cb(nil, _("响应无效")); return end
|
||||
-- 成功时 data 不是表(常为空)。不能走 okData,否则 code=0 也会被当成失败。
|
||||
if tonumber(wire.code) == 0 then cb(true); return end
|
||||
local msg = type(wire.msg) == "string" and wire.msg ~= "" and wire.msg or _("响应无效")
|
||||
if tonumber(wire.code) == 1403 then msg = loginGone(cookie) end
|
||||
cb(nil, msg)
|
||||
end)
|
||||
end
|
||||
|
||||
---@param book_id string
|
||||
---@param cb fun(ok: boolean|nil, err: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
function Client.removeAsync(book_id, cb)
|
||||
local cookie = Client.cookie()
|
||||
if not cookie then return SourceBase.defer(cb, nil, _("未登录起点")) end
|
||||
return apiGet("/webcommon/bookshelf/delbook", { bids = book_id, gid = -100 }, cookie, function(data, err)
|
||||
if not data then cb(nil, err); return end
|
||||
local removed, remove_err = bookOk(book_id, data)
|
||||
cb(removed and true or nil, remove_err)
|
||||
end)
|
||||
end
|
||||
|
||||
--- 搜索:匿名双提交 CSRF,首页及后续页同一接口。
|
||||
---@param keyword string
|
||||
---@param cb fun(data: table|nil, err: string|nil)
|
||||
---@param page integer|nil
|
||||
---@return HttpJob
|
||||
function Client.searchAsync(keyword, cb, page)
|
||||
return apiGet("/webcommon/search/list", { kw = keyword, pageNum = page or 1 }, anonymousCookie(), function(data, err)
|
||||
if not data then cb(nil, err); return end
|
||||
if type(data.bookInfo) ~= "table" or type(data.bookInfo.records) ~= "table" then
|
||||
cb(nil, _("起点搜索响应无效")); return
|
||||
end
|
||||
cb(data)
|
||||
end)
|
||||
end
|
||||
|
||||
--- 榜单页(手机网页 SSR,一页 20 本)。path 如 /rank/yuepiao/catid21/。
|
||||
---@param path string
|
||||
---@param cb fun(data: table|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
function Client.rankAsync(path, cb)
|
||||
return webGet(path, nil, function(html, err)
|
||||
if not html then cb(nil, err); return end
|
||||
local data = Mapper.pageData(html)
|
||||
if not data or type(data.records) ~= "table" then cb(nil, _("起点榜单为空")); return end
|
||||
cb(data)
|
||||
end)
|
||||
end
|
||||
|
||||
---@param key string
|
||||
---@param cat string
|
||||
---@param page integer
|
||||
---@param cb fun(data: table|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
function Client.rankPageAsync(key, cat, page, cb)
|
||||
local kind = key == "readindex" and "readIndex" or key
|
||||
return apiGet("/webcommon/rank/" .. kind .. "list", {
|
||||
catId = cat, gender = "male", pageNum = page,
|
||||
}, anonymousCookie(), function(data, err)
|
||||
if not data then cb(nil, err); return end
|
||||
if type(data.records) ~= "table" then cb(nil, _("起点榜单响应无效")); return end
|
||||
cb(data)
|
||||
end)
|
||||
end
|
||||
|
||||
---@param book_id string
|
||||
---@param cb fun(info: table|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
function Client.detailAsync(book_id, cb)
|
||||
return webGet("/book/" .. book_id .. "/", Client.cookie(), function(html, err)
|
||||
if not html then cb(nil, err); return end
|
||||
local info = (Mapper.pageData(html) or {}).bookInfo
|
||||
if type(info) ~= "table" or not info.bookName then
|
||||
cb(nil, _("起点书籍信息为空"))
|
||||
return
|
||||
end
|
||||
|
||||
cb(info)
|
||||
end)
|
||||
end
|
||||
|
||||
---@param book_id string
|
||||
---@param cb fun(data: table|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
function Client.bookCircleAsync(book_id, cb)
|
||||
return webGet("/readersCircle/" .. book_id .. "/", nil, function(html, err)
|
||||
if not html then cb(nil, err); return end
|
||||
local data = Mapper.pageData(html)
|
||||
if not data or type(data.bookCirclePost) ~= "table" then
|
||||
cb(nil, _("起点书友圈响应无效")); return
|
||||
end
|
||||
cb(data.bookCirclePost)
|
||||
end)
|
||||
end
|
||||
|
||||
---@param book_id string
|
||||
---@param cb fun(data: table|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
function Client.catalogAsync(book_id, cb)
|
||||
return webGet("/book/" .. book_id .. "/catalog/", Client.cookie(), function(html, err)
|
||||
if not html then cb(nil, err); return end
|
||||
local data = Mapper.pageData(html)
|
||||
if not data then cb(nil, _("起点目录为空")); return end
|
||||
cb(data)
|
||||
end)
|
||||
end
|
||||
|
||||
--- 一章正文。未购买的 VIP(vipStatus=1 且 isBuy 不是 1)只有预览,不当正文。
|
||||
---@param book_id string
|
||||
---@param chapter_id string
|
||||
---@param cb fun(text: string|nil, err: string|nil, kind: "unpaid"|nil) kind = "unpaid":这章没买
|
||||
---@return HttpJob
|
||||
function Client.contentAsync(book_id, chapter_id, cb)
|
||||
local cookie, cancelled = Client.cookie(), false
|
||||
local decrypting, font_job
|
||||
local function finish_html(content)
|
||||
local text = Mapper.chapterText(content)
|
||||
if not text then cb(nil, _("起点章节内容为空")); return end
|
||||
cb(text)
|
||||
end
|
||||
local function finish_text(text)
|
||||
if type(text) ~= "string" or Text.trim(text) == "" then cb(nil, _("起点章节内容为空")); return end
|
||||
cb(text)
|
||||
end
|
||||
local function decrypt_done(text, derr)
|
||||
if cancelled then return end
|
||||
decrypting = nil
|
||||
if not text then
|
||||
logger.warn("qidian fock decrypt failed:", derr)
|
||||
cb(nil, _("起点 VIP 章节解密失败") .. (derr and (":" .. tostring(derr)) or "")); return
|
||||
end
|
||||
finish_text(text)
|
||||
end
|
||||
local fetch = webGet("/chapter/" .. book_id .. "/" .. chapter_id .. "/", cookie, function(html, err)
|
||||
if cancelled then return end
|
||||
if not html then cb(nil, err); return end
|
||||
local data = Mapper.pageData(html) or {}
|
||||
local info = data.chapterInfo
|
||||
if type(info) ~= "table" then cb(nil, _("起点章节内容为空")); return end
|
||||
if Mapper.locked(info) then cb(nil, _("起点 VIP 章节未购买"), "unpaid"); return end
|
||||
local content = info.content
|
||||
local ces = tonumber(info.cES) or 0
|
||||
if ces ~= 0 and ces ~= 2 then
|
||||
logger.warn("qidian unknown cES:", ces)
|
||||
cb(nil, _("起点 VIP 章节加密方式不受支持")); return
|
||||
end
|
||||
local fock = Mapper.fockEncrypted(info)
|
||||
local font_protected = Mapper.fontProtected(info)
|
||||
if not fock and not font_protected then finish_html(content); return end
|
||||
|
||||
local keypool, version, uid
|
||||
if fock then
|
||||
local page_guid = type(data.user) == "table" and data.user.guid
|
||||
uid = type(page_guid) == "number" and string.format("%.0f", page_guid)
|
||||
or (type(page_guid) == "string" and page_guid or Client.guid(cookie))
|
||||
if page_guid and uid ~= Client.guid(cookie) then
|
||||
logger.warn("qidian chapter identity differs from login cookie; using response identity")
|
||||
end
|
||||
-- fkp 是 base64 的 `window.onkeyfocus("<密钥池>", <版本>)`,只取参数,不执行
|
||||
keypool, version = Text.base64Decode(tostring(info.fkp or ""))
|
||||
:match('onkeyfocus%("([^"]+)",%s*(%d+)%)')
|
||||
if type(content) ~= "string" or content == "" then
|
||||
logger.warn("qidian encrypted chapter content empty")
|
||||
cb(nil, _("起点 VIP 章节正文为空,请退出后重新扫码或改用 Cookie 登录")); return
|
||||
end
|
||||
if not (uid and uid:match("^%d+$") and keypool and version) then
|
||||
logger.warn("qidian decrypt inputs missing: uid", uid ~= nil, "keypool", keypool ~= nil,
|
||||
"version", version ~= nil)
|
||||
cb(nil, require("source.cookie_login").relogin(
|
||||
_("起点中文网"), "https://m.qidian.com/", _("起点中文网 → 起点账号"))); return
|
||||
end
|
||||
end
|
||||
|
||||
local function run(fixed_font)
|
||||
local pending = true
|
||||
local function done(plain, derr)
|
||||
pending = false
|
||||
decrypt_done(plain, derr)
|
||||
end
|
||||
local job
|
||||
if font_protected then
|
||||
if fock then
|
||||
job = Fock.chapterAsync(info, fixed_font, chapter_id, keypool, version, uid, done)
|
||||
else
|
||||
job = Fock.restoreAsync(content, info, fixed_font, done)
|
||||
end
|
||||
else
|
||||
job = Fock.decryptAsync(content, chapter_id, keypool, version, uid, function(plain, derr)
|
||||
pending = false
|
||||
if cancelled then return end
|
||||
decrypting = nil
|
||||
if not plain then
|
||||
logger.warn("qidian fock decrypt failed:", derr)
|
||||
cb(nil, _("起点 VIP 章节解密失败") .. (derr and (":" .. tostring(derr)) or "")); return
|
||||
end
|
||||
finish_html(plain)
|
||||
end)
|
||||
end
|
||||
if pending then decrypting = job end
|
||||
end
|
||||
|
||||
if not font_protected then run(nil); return end
|
||||
|
||||
local url = info.fixedFontTtf
|
||||
if type(url) ~= "string" or url == "" or type(info.randomFont) ~= "string" or type(info.css) ~= "string" then
|
||||
logger.warn("qidian font inputs missing: fixedFontTtf", type(url), "randomFont", type(info.randomFont),
|
||||
"css", type(info.css))
|
||||
cb(nil, _("起点 VIP 章节字体解密失败:缺少字体信息")); return
|
||||
end
|
||||
font_job = Request.get(url, {
|
||||
headers = { ["User-Agent"] = UA, ["Referer"] = "https://m.qidian.com/" },
|
||||
timeout = require("http.timeout").net(3),
|
||||
}, function(ttf, ferr, res)
|
||||
if cancelled then return end
|
||||
font_job = nil
|
||||
if not ttf or #ttf == 0 then
|
||||
logger.warn("qidian font download failed:", ferr, "code", res and res.code, "len", ttf and #ttf)
|
||||
cb(nil, _("起点 VIP 章节字体下载失败")); return
|
||||
end
|
||||
if not require("moonsource_qidian.yuewen_fonts").looksLikeFont(ttf) then
|
||||
logger.warn("qidian font download invalid:", #ttf, tostring(ttf:sub(1, 16)), "code", res and res.code)
|
||||
cb(nil, _("起点 VIP 章节字体下载失败")); return
|
||||
end
|
||||
run(ttf)
|
||||
end)
|
||||
end)
|
||||
return { cancel = function()
|
||||
cancelled = true
|
||||
fetch.cancel()
|
||||
if font_job then font_job:cancel() end
|
||||
if decrypting then decrypting:cancel() end
|
||||
end }
|
||||
end
|
||||
|
||||
--- 分类目录或分类首屏(含官网动态筛选元数据),公共请求不带账号。
|
||||
---@param cat_id string|nil
|
||||
---@param cb fun(data: table|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
function Client.categoryAsync(cat_id, cb)
|
||||
return webGet("/category/" .. (cat_id and ("catid" .. cat_id .. "/") or ""), nil, function(html, err)
|
||||
if not html then cb(nil, err); return end
|
||||
local data = Mapper.pageData(html)
|
||||
if not data then cb(nil, _("起点分类响应无效")); return end
|
||||
cb(data)
|
||||
end)
|
||||
end
|
||||
|
||||
--- 分类后续页,匿名 CSRF 双提交。
|
||||
---@param params table
|
||||
---@param cb fun(data: table|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
function Client.categoryListAsync(params, cb)
|
||||
return apiGet("/webcommon/category/list", params, anonymousCookie(), function(data, err)
|
||||
if not data then cb(nil, err); return end
|
||||
if type(data.records) ~= "table" then cb(nil, _("起点分类响应无效")); return end
|
||||
cb(data)
|
||||
end)
|
||||
end
|
||||
|
||||
--- 本章各段评论数;list[].paragraphId 从 1 数,-1 是章末总评;enableReview = 0 表示这本书没开段评。
|
||||
---@param book_id string
|
||||
---@param chapter_id string
|
||||
---@param cb fun(data: table|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
function Client.reviewSummaryAsync(book_id, chapter_id, cb)
|
||||
return apiGet("/webcommon/chapterreview/reviewsummary4m", { bookId = book_id, chapterId = chapter_id },
|
||||
Client.cookie() or anonymousCookie(), cb)
|
||||
end
|
||||
|
||||
--- 某段的一页评论(page 从 1 起,每页 10 条左右)。
|
||||
---@param book_id string
|
||||
---@param chapter_id string
|
||||
---@param paragraph_id integer
|
||||
---@param page integer
|
||||
---@param cb fun(data: table|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
function Client.reviewListAsync(book_id, chapter_id, paragraph_id, page, cb)
|
||||
return apiGet("/webcommon/chapterreview/reviewlist4m", {
|
||||
bookId = book_id, chapterId = chapter_id, paragraphId = paragraph_id, page = page,
|
||||
}, Client.cookie() or anonymousCookie(), cb)
|
||||
end
|
||||
|
||||
return Client
|
||||
@@ -0,0 +1,109 @@
|
||||
--[[--
|
||||
起点 VIP 章节正文解密(Fock):阅文 wasm 的起点构建参数 + 子进程编排,宿主在 `moonsource_qidian.yuewen_fock`。
|
||||
网页端用它解密 `chapterInfo.content`。
|
||||
|
||||
@module moonsource_qidian.fock
|
||||
--]]--
|
||||
|
||||
local Shared = require("moonsource_qidian.yuewen_fock")
|
||||
local FontRestore = require("moonsource_qidian.yuewen_fonts")
|
||||
local JSON = require("json")
|
||||
|
||||
local Fock = {}
|
||||
|
||||
-- 起点 font 层的字形与参考 Noto 偶有 0.65~0.75 的形近字(如 䵻→对),比 QQ阅读放宽一点。
|
||||
local FONT_THRESHOLD = 0.65
|
||||
|
||||
---@param info table chapterInfo
|
||||
---@return table
|
||||
local function fontData(info)
|
||||
local raw = info.randomFont
|
||||
assert(type(raw) == "string" and raw ~= "", "qidian randomFont missing")
|
||||
local ok, random = pcall(JSON.decode, raw)
|
||||
if not ok or type(random) ~= "table" then
|
||||
error("qidian randomFont decode failed: " .. tostring(random))
|
||||
end
|
||||
return { css = info.css or "", randomFont = random }
|
||||
end
|
||||
|
||||
--- 还原字体层;抛错转成 `{ err }`,不让子进程崩在 on_failed 里丢上下文。
|
||||
---@return { text: string|nil, err: string|nil }
|
||||
local function restore(html, info, fixed_font, temp_paths)
|
||||
local ok, text = pcall(FontRestore.restore, html, fontData(info), fixed_font,
|
||||
{ dedupe = true, confusions = true, threshold = FONT_THRESHOLD, temp_paths = temp_paths })
|
||||
if not ok then return { err = "font: " .. tostring(text) } end
|
||||
return { text = text }
|
||||
end
|
||||
|
||||
local HOST = {
|
||||
["location.hostname"] = "vipreader.qidian.com",
|
||||
["location.protocol"] = "https:",
|
||||
}
|
||||
|
||||
---@type YuewenFockBuild
|
||||
local BUILD = {
|
||||
wasm = "moonsource_qidian.fock_wasm",
|
||||
callback = 22685,
|
||||
stack = 5274992,
|
||||
exports = { ctors = "g", main = "m", set_uid = "h", set_key = "i", decrypt = "j",
|
||||
stack_save = "n", stack_restore = "o", alloc = "p", malloc = "q" },
|
||||
-- 其余是反调试 / 定时器探测:返回 -1(那几个会返回 indexOf 结果)或 0
|
||||
probe = function(code)
|
||||
if code == 14394 or code == 14449 or code == 14875 then return 0 end
|
||||
if code % 709 == 15372 % 709 then return -1 end
|
||||
return 0
|
||||
end,
|
||||
imports = function(env)
|
||||
return {
|
||||
f = function() return 0 end,
|
||||
c = function(a, b) return env.malloc_str(HOST[env.cstr(a) .. "." .. env.cstr(b)] or "undefined") end,
|
||||
e = function() return env.malloc_str("undefined") end,
|
||||
}
|
||||
end,
|
||||
}
|
||||
|
||||
---@param content string base64 密文
|
||||
---@param chapter_id string|number
|
||||
---@param keypool string base64 密钥池(fkp 里 onkeyfocus 的第一个参数)
|
||||
---@param version string
|
||||
---@param uid string 用户 ywguid
|
||||
---@return string|nil text
|
||||
---@return string|nil err
|
||||
function Fock.decrypt(content, chapter_id, keypool, version, uid)
|
||||
return Shared.decrypt(BUILD, content, chapter_id, keypool, version, uid)
|
||||
end
|
||||
|
||||
--- 在子进程里解密;回调拿明文或错误。
|
||||
---@return BookJob
|
||||
function Fock.decryptAsync(content, chapter_id, keypool, version, uid, cb)
|
||||
return Shared.jobAsync("qidian_fock", function()
|
||||
local plain, err = Fock.decrypt(content, chapter_id, keypool, version, uid)
|
||||
return { text = plain, err = err }
|
||||
end, cb)
|
||||
end
|
||||
|
||||
--- 在子进程里解密并还原 cES=2 的字体层;回调拿纯文本或错误。
|
||||
--- 起点会在正文尾部追加一份同长度的诱饵副本,restore 的 dedupe 会丢掉它。
|
||||
---@param info table chapterInfo
|
||||
---@param fixed_font string fixedFontTtf 下载下来的字节
|
||||
---@return BookJob
|
||||
function Fock.chapterAsync(info, fixed_font, chapter_id, keypool, version, uid, cb)
|
||||
return Shared.jobAsync("qidian_fock", function(temp_paths)
|
||||
local plain, err = Fock.decrypt(info.content, chapter_id, keypool, version, uid)
|
||||
if not plain then return { err = "decrypt: " .. tostring(err) } end
|
||||
return restore(plain, info, fixed_font, temp_paths)
|
||||
end, cb)
|
||||
end
|
||||
|
||||
--- 只有字体层(fEnS=0)时直接还原明文 HTML。
|
||||
---@param html string Fock 明文或页面正文 HTML
|
||||
---@param info table chapterInfo
|
||||
---@param fixed_font string
|
||||
---@return BookJob
|
||||
function Fock.restoreAsync(html, info, fixed_font, cb)
|
||||
return Shared.jobAsync("qidian_font", function(temp_paths)
|
||||
return restore(html, info, fixed_font, temp_paths)
|
||||
end, cb)
|
||||
end
|
||||
|
||||
return Fock
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,147 @@
|
||||
return {
|
||||
["起点书友圈响应无效"] = "Invalid Qidian book community response.",
|
||||
["书友圈预览(%1/%2)"] = "Book community preview (%1/%2)",
|
||||
["书友圈帖子预览"] = "Book community post previews",
|
||||
["完结"] = "Completed",
|
||||
["起点榜单响应无效"] = "Invalid Qidian ranking response.",
|
||||
["排行榜"] = "Rankings",
|
||||
["分类书库"] = "Category library",
|
||||
["切换账号"] = "Switch account",
|
||||
["切换起点账号会清除这台设备上起点的书架、阅读进度、笔记和缓存,包括尚未同步的记录。不会删除远端书架。确定继续?"] = "Switching Qidian accounts clears this device's Qidian shelf, progress, notes and cache, including unsynced records. Your remote shelf will not be deleted. Continue?",
|
||||
["刷新验证码"] = "Refresh verification",
|
||||
["同意并获取验证码"] = "Agree and send code",
|
||||
["子分类"] = "Subcategory",
|
||||
["提交"] = "Submit",
|
||||
["无法确认旧账号,请先退出旧账号再登录"] = "Cannot identify the previous account. Sign out before signing in again.",
|
||||
["本章讨论"] = "Chapter discussion",
|
||||
["筛选"] = "Filters",
|
||||
["获取验证码前请阅读并同意阅文用户服务协议和隐私政策"] = "Before requesting a code, read and agree to the Yuewen terms of service and privacy policy.",
|
||||
["请输入验证码"] = "Enter the verification code.",
|
||||
["起点分类响应无效"] = "Invalid Qidian category response.",
|
||||
["起点分类条件无效"] = "Invalid Qidian category filters.",
|
||||
["起点安全验证"] = "Qidian security verification",
|
||||
["起点手机号验证码登录"] = "Qidian SMS sign-in",
|
||||
["起点搜索响应无效"] = "Invalid Qidian search response.",
|
||||
["起点登录响应无效"] = "Invalid Qidian sign-in response.",
|
||||
["起点登录未获取到本站会话"] = "Could not establish a Qidian website session.",
|
||||
["起点登录缺少会话兑换凭据"] = "Missing Qidian session exchange credentials.",
|
||||
["起点登录跳转地址无效"] = "Invalid Qidian sign-in redirect.",
|
||||
["起点登录跳转过多"] = "Too many Qidian sign-in redirects.",
|
||||
["起点登录需要未支持的验证"] = "Qidian requires an unsupported verification method.",
|
||||
["起点短信会话缺失"] = "Missing Qidian SMS session.",
|
||||
["起点账号标识缺失"] = "Missing Qidian account identity.",
|
||||
["起点验证码刷新失败"] = "Could not refresh Qidian verification.",
|
||||
["起点验证码响应无效"] = "Invalid Qidian verification response.",
|
||||
["起点验证码图片无效"] = "Invalid Qidian verification image.",
|
||||
["100~200万"] = "1–2 million words",
|
||||
["200万以上"] = "Over 2 million words",
|
||||
["30~50万"] = "300–500 thousand words",
|
||||
["30万以下"] = "Under 300 thousand words",
|
||||
["50~100万"] = "500 thousand–1 million words",
|
||||
["VIP"] = "VIP",
|
||||
["一月内"] = "Within a month",
|
||||
["七日内"] = "Within a week",
|
||||
["三日内"] = "Within three days",
|
||||
["东方玄幻"] = "Eastern fantasy",
|
||||
["二级分类"] = "Subcategory",
|
||||
["人气"] = "Popularity",
|
||||
["仙侠奇缘"] = "Immortal romance",
|
||||
["半月内"] = "Within two weeks",
|
||||
["古代言情"] = "Historical romance",
|
||||
["品质"] = "Quality",
|
||||
["完本"] = "Completed",
|
||||
["属性"] = "Access",
|
||||
["异世大陆"] = "Otherworld fantasy",
|
||||
["月票"] = "Monthly votes",
|
||||
["浪漫青春"] = "Teen romance",
|
||||
["游戏竞技"] = "Gaming and competition",
|
||||
["点击"] = "Views",
|
||||
["玄幻言情"] = "Fantasy romance",
|
||||
["王朝争霸"] = "Dynastic conflict",
|
||||
["现代言情"] = "Contemporary romance",
|
||||
["现实生活"] = "Everyday life",
|
||||
["科幻空间"] = "Sci-fi romance",
|
||||
["签约作品"] = "Contracted works",
|
||||
["精品小说"] = "Featured novels",
|
||||
["连载"] = "Ongoing",
|
||||
["高武世界"] = "Martial fantasy",
|
||||
["用同一 Wi-Fi 下的手机扫码完成安全验证;手机号、密码和短信码只在设备填写。"] = "Scan with a phone on the same Wi-Fi to complete security verification. Enter your phone number, password and SMS code only on the device.",
|
||||
["请完成下方安全验证"] = "Complete the security verification below.",
|
||||
["验证已提交,请回到设备查看结果。"] = "Verification submitted. Return to the device to see the result.",
|
||||
["国际区号"] = "Country calling code",
|
||||
["请输入有效的手机号和国际区号"] = "Enter a valid phone number and country calling code.",
|
||||
["请稍后再获取验证码"] = "Please wait before requesting another code.",
|
||||
["验证码已发送"] = "Verification code sent",
|
||||
["正在获取验证码…"] = "Requesting a verification code…",
|
||||
["正在处理,请稍候"] = "Processing, please wait.",
|
||||
["请先获取该手机号的验证码,再填写验证码登录"] = "Request a code for this phone number, then enter it to sign in.",
|
||||
["频道"] = "Channel",
|
||||
["章节评论"] = "Chapter comments",
|
||||
["悬疑推理"] = "Detective fiction",
|
||||
["获取验证码"] = "Get code",
|
||||
["手机号验证码登录"] = "Sign in with an SMS code",
|
||||
["请先获取验证码"] = "Request a verification code first",
|
||||
["扫码登录"] = "Sign in with QR code",
|
||||
["起点扫码登录"] = "Qidian QR sign-in",
|
||||
["起点登录已失效,请点「重新登录」,用 QQ阅读或起点 App 扫码。也可在账号设置里粘贴 Cookie。"] = "Qidian sign-in has expired. Tap Sign in again and scan with QQReader or Qidian. You can also paste a Cookie in account settings.",
|
||||
["验证已过期,请重新发起验证"] = "Verification expired. Please start again",
|
||||
["未登录 · 点此扫码"] = "Not signed in · tap to scan",
|
||||
["正在登录…"] = "Signing in…",
|
||||
["章节目录保存失败"] = "Failed to save chapter list",
|
||||
["缺少起点章节位置"] = "Missing Qidian chapter position",
|
||||
["起点段评响应缺少评论列表"] = "Qidian paragraph comments response has no comment list",
|
||||
["手机号"] = "Phone number",
|
||||
["按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"] = "Press F12, open Network, refresh, and copy the entire Cookie request header",
|
||||
["起点账号"] = "Qidian account",
|
||||
["起点登录 Cookie"] = "Qidian login cookie",
|
||||
["起点 Cookie 缺少登录凭证"] = "Qidian Cookie is missing the sign-in token",
|
||||
["确定退出起点账号?"] = "Sign out of Qidian?",
|
||||
["未登录起点"] = "Not signed in to Qidian",
|
||||
["起点书籍信息为空"] = "Qidian book info is empty",
|
||||
["起点章节内容为空"] = "Qidian chapter is empty",
|
||||
["起点 VIP 章节未购买"] = "This Qidian VIP chapter is not purchased",
|
||||
["起点 VIP 章节正文为空,请退出后重新扫码或改用 Cookie 登录"] = "Qidian VIP chapter body is empty. Sign out, scan again, or paste Cookie instead",
|
||||
["起点 VIP 章节解密失败"] = "Failed to decrypt this Qidian VIP chapter",
|
||||
["起点 VIP 章节加密方式不受支持"] = "This Qidian VIP chapter uses an unsupported encryption mode",
|
||||
["起点 VIP 章节字体下载失败"] = "Failed to download the Qidian VIP chapter font",
|
||||
["起点 VIP 章节字体解密失败:缺少字体信息"] = "Failed to restore the Qidian VIP chapter font: font info missing",
|
||||
["起点目录为空"] = "Qidian table of contents is empty",
|
||||
["起点章节时间缺失"] = "Qidian chapter time is missing",
|
||||
["用 QQ阅读或起点 App 扫一扫"] = "Scan with the QQ Reader or Qidian app",
|
||||
["起点中文网 → 起点账号"] = "Qidian → Qidian account",
|
||||
["仙侠"] = "Xianxia",
|
||||
["体育"] = "Sports",
|
||||
["全站"] = "All",
|
||||
["军事"] = "Military",
|
||||
["历史"] = "History",
|
||||
["奇幻"] = "Fantasy",
|
||||
["女频"] = "Female",
|
||||
["悬疑灵异"] = "Mystery & Supernatural",
|
||||
["新书榜"] = "New Books",
|
||||
["新人榜"] = "Rookies",
|
||||
["新作者榜"] = "New Authors",
|
||||
["更新榜"] = "Updates",
|
||||
["月票榜"] = "Monthly Votes",
|
||||
["武侠"] = "Wuxia",
|
||||
["玄幻"] = "Xuanhuan",
|
||||
["现实"] = "Realistic",
|
||||
["男频"] = "Male",
|
||||
["畅销榜"] = "Bestsellers",
|
||||
["短篇"] = "Short Stories",
|
||||
["科幻"] = "Sci-Fi",
|
||||
["诸天无限"] = "Infinite Worlds",
|
||||
["起点榜单为空"] = "Qidian ranking is empty",
|
||||
["轻小说"] = "Light Novels",
|
||||
["都市"] = "Urban",
|
||||
["阅读指数榜"] = "Reading Index",
|
||||
["无法打开远程验证,请先连接 Wi-Fi 并启用远程管理功能"] = "Cannot open remote verification. Connect to Wi-Fi and enable Remote management first.",
|
||||
["验证已取消"] = "Verification cancelled",
|
||||
["验证凭据无效"] = "Invalid verification proof",
|
||||
["正在提交验证…"] = "Submitting verification…",
|
||||
["验证失败,请重新验证"] = "Verification failed. Please try again",
|
||||
["VIP 章节"] = "VIP chapters",
|
||||
["书架同步"] = "Shelf sync",
|
||||
["搜索与发现"] = "Search and discover",
|
||||
["起点中文网书架与在线阅读"] = "Qidian shelf and online reading",
|
||||
["进度同步"] = "Progress sync",
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
return {
|
||||
["起点书友圈响应无效"] = "起點書友圈回應無效",
|
||||
["书友圈预览(%1/%2)"] = "書友圈預覽(%1/%2)",
|
||||
["书友圈帖子预览"] = "書友圈帖子預覽",
|
||||
["完结"] = "完結",
|
||||
["起点榜单响应无效"] = "起點排行榜回應無效",
|
||||
["排行榜"] = "排行榜",
|
||||
["分类书库"] = "分類書庫",
|
||||
["切换账号"] = "切換帳號",
|
||||
["切换起点账号会清除这台设备上起点的书架、阅读进度、笔记和缓存,包括尚未同步的记录。不会删除远端书架。确定继续?"] = "切換起點帳號會清除這台裝置上起點的書架、閱讀進度、筆記和快取,包括尚未同步的記錄。不會刪除遠端書架。確定繼續?",
|
||||
["刷新验证码"] = "重新整理驗證碼",
|
||||
["同意并获取验证码"] = "同意並取得驗證碼",
|
||||
["子分类"] = "子分類",
|
||||
["提交"] = "送出",
|
||||
["无法确认旧账号,请先退出旧账号再登录"] = "無法確認舊帳號,請先登出舊帳號再登入",
|
||||
["本章讨论"] = "本章討論",
|
||||
["筛选"] = "篩選",
|
||||
["获取验证码前请阅读并同意阅文用户服务协议和隐私政策"] = "取得驗證碼前請閱讀並同意閱文使用者服務協議和隱私政策",
|
||||
["请输入验证码"] = "請輸入驗證碼",
|
||||
["起点分类响应无效"] = "起點分類回應無效",
|
||||
["起点分类条件无效"] = "起點分類條件無效",
|
||||
["起点安全验证"] = "起點安全驗證",
|
||||
["起点手机号验证码登录"] = "起點手機號碼驗證碼登入",
|
||||
["起点搜索响应无效"] = "起點搜尋回應無效",
|
||||
["起点登录响应无效"] = "起點登入回應無效",
|
||||
["起点登录未获取到本站会话"] = "起點登入未取得本站工作階段",
|
||||
["起点登录缺少会话兑换凭据"] = "起點登入缺少工作階段兌換憑據",
|
||||
["起点登录跳转地址无效"] = "起點登入重新導向位址無效",
|
||||
["起点登录跳转过多"] = "起點登入重新導向過多",
|
||||
["起点登录需要未支持的验证"] = "起點登入需要尚未支援的驗證",
|
||||
["起点短信会话缺失"] = "起點簡訊工作階段缺失",
|
||||
["起点账号标识缺失"] = "起點帳號識別缺失",
|
||||
["起点验证码刷新失败"] = "起點驗證碼重新整理失敗",
|
||||
["起点验证码响应无效"] = "起點驗證碼回應無效",
|
||||
["起点验证码图片无效"] = "起點驗證碼圖片無效",
|
||||
["100~200万"] = "100~200 萬字",
|
||||
["200万以上"] = "200 萬字以上",
|
||||
["30~50万"] = "30~50 萬字",
|
||||
["30万以下"] = "30 萬字以下",
|
||||
["50~100万"] = "50~100 萬字",
|
||||
["VIP"] = "VIP",
|
||||
["一月内"] = "一個月內",
|
||||
["七日内"] = "七日內",
|
||||
["三日内"] = "三日內",
|
||||
["东方玄幻"] = "東方玄幻",
|
||||
["二级分类"] = "次分類",
|
||||
["人气"] = "人氣",
|
||||
["仙侠奇缘"] = "仙俠奇緣",
|
||||
["半月内"] = "半個月內",
|
||||
["古代言情"] = "古代言情",
|
||||
["品质"] = "品質",
|
||||
["完本"] = "完結",
|
||||
["属性"] = "屬性",
|
||||
["异世大陆"] = "異世大陸",
|
||||
["月票"] = "月票",
|
||||
["浪漫青春"] = "浪漫青春",
|
||||
["游戏竞技"] = "遊戲競技",
|
||||
["点击"] = "點擊",
|
||||
["玄幻言情"] = "玄幻言情",
|
||||
["王朝争霸"] = "王朝爭霸",
|
||||
["现代言情"] = "現代言情",
|
||||
["现实生活"] = "現實生活",
|
||||
["科幻空间"] = "科幻空間",
|
||||
["签约作品"] = "簽約作品",
|
||||
["精品小说"] = "精品小說",
|
||||
["连载"] = "連載",
|
||||
["高武世界"] = "高武世界",
|
||||
["用同一 Wi-Fi 下的手机扫码完成安全验证;手机号、密码和短信码只在设备填写。"] = "用同一 Wi-Fi 下的手機掃碼完成安全驗證;手機號碼、密碼和簡訊碼只在裝置填寫。",
|
||||
["请完成下方安全验证"] = "請完成下方安全驗證",
|
||||
["验证已提交,请回到设备查看结果。"] = "驗證已提交,請回到裝置查看結果。",
|
||||
["国际区号"] = "國際區碼",
|
||||
["请输入有效的手机号和国际区号"] = "請輸入有效的手機號碼和國際區碼",
|
||||
["请稍后再获取验证码"] = "請稍後再取得驗證碼",
|
||||
["验证码已发送"] = "驗證碼已發送",
|
||||
["正在获取验证码…"] = "正在取得驗證碼…",
|
||||
["正在处理,请稍候"] = "正在處理,請稍候",
|
||||
["请先获取该手机号的验证码,再填写验证码登录"] = "請先取得該手機號碼的驗證碼,再填寫驗證碼登入",
|
||||
["频道"] = "頻道",
|
||||
["章节评论"] = "章節評論",
|
||||
["悬疑推理"] = "懸疑推理",
|
||||
["获取验证码"] = "取得驗證碼",
|
||||
["手机号验证码登录"] = "手機號碼驗證碼登入",
|
||||
["请先获取验证码"] = "請先取得驗證碼",
|
||||
["扫码登录"] = "掃碼登入",
|
||||
["起点扫码登录"] = "起點掃碼登入",
|
||||
["起点登录已失效,请点「重新登录」,用 QQ阅读或起点 App 扫码。也可在账号设置里粘贴 Cookie。"] = "起點登入已失效,請點「重新登入」,用 QQ閱讀或起點 App 掃碼。也可在帳號設定裡貼上 Cookie。",
|
||||
["验证已过期,请重新发起验证"] = "驗證已過期,請重新發起驗證",
|
||||
["未登录 · 点此扫码"] = "未登入 · 點此掃碼",
|
||||
["正在登录…"] = "正在登入…",
|
||||
["章节目录保存失败"] = "章節目錄儲存失敗",
|
||||
["缺少起点章节位置"] = "缺少起點章節位置",
|
||||
["起点段评响应缺少评论列表"] = "起點段評回應缺少評論列表",
|
||||
["手机号"] = "手機號碼",
|
||||
["按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"] = "按鍵盤 F12,點「網路」,重新整理網頁,複製請求標頭裡的整段 Cookie",
|
||||
["起点账号"] = "起點帳號",
|
||||
["起点登录 Cookie"] = "起點登入 Cookie",
|
||||
["起点 Cookie 缺少登录凭证"] = "起點 Cookie 缺少登入憑證",
|
||||
["确定退出起点账号?"] = "確定登出起點帳號?",
|
||||
["未登录起点"] = "未登入起點",
|
||||
["起点书籍信息为空"] = "起點書籍資訊為空",
|
||||
["起点章节内容为空"] = "起點章節內容為空",
|
||||
["起点 VIP 章节未购买"] = "此起點 VIP 章節尚未購買",
|
||||
["起点 VIP 章节正文为空,请退出后重新扫码或改用 Cookie 登录"] = "起點 VIP 章節正文為空,請登出後重新掃碼或改用 Cookie 登入",
|
||||
["起点 VIP 章节解密失败"] = "起點 VIP 章節解密失敗",
|
||||
["起点 VIP 章节加密方式不受支持"] = "此起點 VIP 章節使用不支援的加密方式",
|
||||
["起点 VIP 章节字体下载失败"] = "起點 VIP 章節字體下載失敗",
|
||||
["起点 VIP 章节字体解密失败:缺少字体信息"] = "起點 VIP 章節字體解密失敗:缺少字體資訊",
|
||||
["起点目录为空"] = "起點目錄為空",
|
||||
["起点章节时间缺失"] = "起點章節時間缺失",
|
||||
["用 QQ阅读或起点 App 扫一扫"] = "用 QQ閱讀或起點 App 掃一掃",
|
||||
["起点中文网 → 起点账号"] = "起點中文網 → 起點帳號",
|
||||
["仙侠"] = "仙俠",
|
||||
["体育"] = "體育",
|
||||
["全站"] = "全站",
|
||||
["军事"] = "軍事",
|
||||
["历史"] = "歷史",
|
||||
["奇幻"] = "奇幻",
|
||||
["女频"] = "女頻",
|
||||
["悬疑灵异"] = "懸疑靈異",
|
||||
["新书榜"] = "新書榜",
|
||||
["新人榜"] = "新人榜",
|
||||
["新作者榜"] = "新作者榜",
|
||||
["更新榜"] = "更新榜",
|
||||
["月票榜"] = "月票榜",
|
||||
["武侠"] = "武俠",
|
||||
["玄幻"] = "玄幻",
|
||||
["现实"] = "現實",
|
||||
["男频"] = "男頻",
|
||||
["畅销榜"] = "暢銷榜",
|
||||
["短篇"] = "短篇",
|
||||
["科幻"] = "科幻",
|
||||
["诸天无限"] = "諸天無限",
|
||||
["起点榜单为空"] = "起點榜單為空",
|
||||
["轻小说"] = "輕小說",
|
||||
["都市"] = "都市",
|
||||
["阅读指数榜"] = "閱讀指數榜",
|
||||
["无法打开远程验证,请先连接 Wi-Fi 并启用远程管理功能"] = "無法打開遠端驗證,請先連接 Wi-Fi 並啟用遠端管理功能",
|
||||
["验证已取消"] = "驗證已取消",
|
||||
["验证凭据无效"] = "驗證憑據無效",
|
||||
["正在提交验证…"] = "正在提交驗證…",
|
||||
["验证失败,请重新验证"] = "驗證失敗,請重新驗證",
|
||||
["VIP 章节"] = "VIP 章節",
|
||||
["书架同步"] = "書架同步",
|
||||
["搜索与发现"] = "搜尋與發現",
|
||||
["起点中文网书架与在线阅读"] = "起點中文網書架與線上閱讀",
|
||||
["进度同步"] = "進度同步",
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
return function()
|
||||
local copy = {}
|
||||
for k, v in pairs(require("moonsource_qidian._meta")) do copy[k] = v end
|
||||
return copy
|
||||
end
|
||||
@@ -0,0 +1,196 @@
|
||||
--[[--
|
||||
起点官方 Web 短信登录会话。图形验证与短信使用不同 sessionKey,不保存手机号或验证码。
|
||||
|
||||
@module moonsource_qidian.login
|
||||
--]]
|
||||
|
||||
local JSON = require("json")
|
||||
local Request = require("http.request")
|
||||
local Text = require("utils.text")
|
||||
local CookieLogin = require("source.cookie_login")
|
||||
local _ = require("l10n").get("moonsource_qidian")
|
||||
|
||||
local BASE = "https://ptlogin.yuewen.com"
|
||||
local UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/131.0.0.0 Safari/537.36"
|
||||
local LOGIN_KEYS = { ywguid = true, ywkey = true, ywopenid = true }
|
||||
local HOSTS = { ["ptlogin.yuewen.com"] = true, ["passport.yuewen.com"] = true,
|
||||
["passport.qidian.com"] = true, ["m.qidian.com"] = true }
|
||||
|
||||
---@class QidianLogin
|
||||
---@field jar table<string, string>
|
||||
---@field webjar table<string, string>
|
||||
---@field generation integer
|
||||
---@field job HttpJob|nil
|
||||
---@field initialized boolean|nil
|
||||
---@field challenge_key string|nil
|
||||
---@field sms_key string|nil
|
||||
---@field cancelled boolean|nil
|
||||
local Login = {}
|
||||
Login.__index = Login
|
||||
|
||||
function Login.new()
|
||||
return setmetatable({ jar = {}, webjar = {}, generation = 0 }, Login)
|
||||
end
|
||||
|
||||
function Login:cancel()
|
||||
self.cancelled = true
|
||||
self:interrupt()
|
||||
self.sms_key, self.challenge_key = nil, nil
|
||||
self.jar, self.webjar = {}, {}
|
||||
end
|
||||
|
||||
function Login:interrupt()
|
||||
self.generation = self.generation + 1
|
||||
if self.job then self.job.cancel() end
|
||||
self.job = nil
|
||||
end
|
||||
|
||||
local function cookies(jar)
|
||||
local parts = {}
|
||||
for name, value in pairs(jar) do parts[#parts + 1] = name .. "=" .. value end
|
||||
return CookieLogin.parse(table.concat(parts, "; "))
|
||||
end
|
||||
|
||||
function Login:_get(url, cb)
|
||||
if self.cancelled then return end
|
||||
local host = url:match("^https://([^/?#]+)")
|
||||
if not HOSTS[host] then cb(nil, _("起点登录跳转地址无效")); return end
|
||||
local headers = { ["User-Agent"] = UA, Referer = "https://passport.qidian.com/mobile/login" }
|
||||
if host == "ptlogin.yuewen.com" then headers.Cookie = cookies(self.jar)
|
||||
elseif host == "m.qidian.com" then headers.Cookie = cookies(self.webjar) end
|
||||
local pending, gen = true, self.generation
|
||||
local job = Request.request({
|
||||
url = url, method = "GET", headers = headers, allow_redirects = false,
|
||||
timeout = require("http.timeout").net(1), cache_ttl = 0,
|
||||
}, function(res, err)
|
||||
pending = false
|
||||
if self.cancelled or gen ~= self.generation then return end
|
||||
self.job = nil
|
||||
if not res or err then cb(nil, err and tostring(err) or _("请求失败")); return end
|
||||
local status = tonumber(res.code)
|
||||
if not status or status < 200 or status >= 400 then cb(nil, "HTTP " .. tostring(res.code)); return end
|
||||
local set_cookies = Request.headerAll(res, "Set-Cookie")
|
||||
if host == "ptlogin.yuewen.com" then CookieLogin.absorb(self.jar, set_cookies) end
|
||||
CookieLogin.absorb(self.webjar, set_cookies, LOGIN_KEYS)
|
||||
cb(res)
|
||||
end)
|
||||
if pending then self.job = job end
|
||||
end
|
||||
|
||||
function Login:baseParams()
|
||||
return {
|
||||
appId = "13", areaId = "31", source = "", returnurl = "https://m.qidian.com/",
|
||||
version = "", imei = "", qimei = "", target = "top", ticket = "1",
|
||||
autotime = "14", jumpdm = "qidian", ajaxdm = "", auto = self.jar.al or "", sdkversion = "",
|
||||
format = "json", method = "moonLogin",
|
||||
}
|
||||
end
|
||||
|
||||
function Login:_json(path, fields, cb)
|
||||
local params = self:baseParams()
|
||||
for key, value in pairs(fields) do params[key] = value end
|
||||
self:_get(BASE .. path .. "?" .. Text.formEncode(params), function(res, err)
|
||||
if not res then cb(nil, err); return end
|
||||
local ok, wire = pcall(JSON.decode, res.body)
|
||||
if not ok or type(wire) ~= "table" then cb(nil, _("起点登录响应无效")); return end
|
||||
if tonumber(wire.code) ~= 0 then
|
||||
cb(nil, wire.message or wire.msg or (_("登录失败") .. ":" .. tostring(wire.code))); return
|
||||
end
|
||||
if type(wire.data) ~= "table" then cb(nil, _("起点登录响应无效")); return end
|
||||
cb(wire.data)
|
||||
end)
|
||||
end
|
||||
|
||||
function Login:beginAsync(cb)
|
||||
self:_json("/userSdk/getvalidatecode", { force = 1 }, function(data, err)
|
||||
if not data then cb(nil, err); return end
|
||||
self.initialized = true
|
||||
if type(data.imgSrc) == "string" and data.imgSrc ~= "" then self.challenge_key = data.sessionKey end
|
||||
cb(data)
|
||||
end)
|
||||
end
|
||||
|
||||
function Login:imageAsync(url, cb)
|
||||
local target = Text.absoluteUrl(BASE .. "/", url)
|
||||
if not target then cb(nil, _("起点验证码响应无效")); return end
|
||||
self:_get(target, function(res, err)
|
||||
if not res then cb(nil, err); return end
|
||||
local body = res.body
|
||||
if type(body) ~= "string" or #body > 1024 * 1024 then cb(nil, _("起点验证码图片无效")); return end
|
||||
local ext, mime = require("utils.image").ext(body)
|
||||
if not ext then cb(nil, _("起点验证码图片无效")); return end
|
||||
cb("data:" .. mime .. ";base64," .. Text.base64Encode(body))
|
||||
end)
|
||||
end
|
||||
|
||||
function Login:sendCodeAsync(country, phone, proof, cb)
|
||||
self:_json("/userSdk/sendmsgnew", {
|
||||
phoneIsAbroad = country == "+86" and 0 or 1, inputUserId = country .. phone,
|
||||
sessionKey = self.challenge_key or "", type = 1, validateCode = proof or "", needRegister = 0,
|
||||
}, function(data, err)
|
||||
if not data then cb(nil, err); return end
|
||||
local action = tonumber(data.nextAction)
|
||||
if action == 0 then
|
||||
if type(data.sessionKey) ~= "string" or data.sessionKey == "" then
|
||||
cb(nil, _("起点短信会话缺失")); return
|
||||
end
|
||||
self.sms_key = data.sessionKey
|
||||
self.challenge_key = nil
|
||||
elseif action == 8 or action == 11 then
|
||||
if type(data.sessionKey) ~= "string" or data.sessionKey == "" or type(data.imgSrc) ~= "string"
|
||||
or data.imgSrc == "" then cb(nil, _("起点验证码响应无效")); return end
|
||||
self.challenge_key = data.sessionKey
|
||||
else
|
||||
cb(nil, _("起点登录需要未支持的验证") .. ":" .. tostring(data.nextAction)); return
|
||||
end
|
||||
cb(data)
|
||||
end)
|
||||
end
|
||||
|
||||
function Login:_exchange(data, cb)
|
||||
for name, key in pairs({ ywguid = "ywGuid", ywkey = "ywKey", ywopenid = "ywOpenId" }) do
|
||||
local value = data[key]
|
||||
if type(value) == "number" then self.webjar[name] = string.format("%.0f", value)
|
||||
elseif type(value) == "string" then self.webjar[name] = value end
|
||||
end
|
||||
local url = data["302url"]
|
||||
if not url and type(data.ticket) == "string" and data.ticket ~= "" then
|
||||
url = "https://m.qidian.com/?" .. Text.formEncode({
|
||||
ticket = data.ticket, ywguid = self.webjar.ywguid or "", ywOpenId = self.webjar.ywopenid or "",
|
||||
})
|
||||
end
|
||||
if type(url) ~= "string" or url == "" then cb(nil, _("起点登录缺少会话兑换凭据")); return end
|
||||
local function follow(target, hop)
|
||||
if hop > 5 then cb(nil, _("起点登录跳转过多")); return end
|
||||
self:_get(target, function(res, err)
|
||||
if not res then cb(nil, err); return end
|
||||
local status = tonumber(res.code)
|
||||
local location = Request.header(res, "Location")
|
||||
if status >= 300 then
|
||||
local next_url = Text.absoluteUrl(target, location)
|
||||
if not next_url then cb(nil, _("起点登录跳转地址无效")); return end
|
||||
follow(next_url, hop + 1)
|
||||
elseif target:match("^https://([^/?#]+)") ~= "m.qidian.com" or not self.webjar.ywguid
|
||||
or not self.webjar.ywkey then
|
||||
cb(nil, _("起点登录未获取到本站会话"))
|
||||
else
|
||||
-- 真 _csrfToken 由 loginCheck 合并书架页 Set-Cookie 后再落盘,这里不要造假。
|
||||
cb(cookies(self.webjar))
|
||||
end
|
||||
end)
|
||||
end
|
||||
follow(url, 1)
|
||||
end
|
||||
|
||||
function Login:verifyAsync(phone, code, cb)
|
||||
if not self.sms_key then cb(nil, _("请先获取验证码")); return end
|
||||
self:_json("/userSdk/phonecodelogin", {
|
||||
inputUserId = phone, sessionKey = self.sms_key, validateCode = code,
|
||||
}, function(data, err)
|
||||
if not data then cb(nil, err); return end
|
||||
if tonumber(data.nextAction) ~= 0 then cb(nil, _("起点登录需要未支持的验证")); return end
|
||||
self:_exchange(data, cb)
|
||||
end)
|
||||
end
|
||||
|
||||
return Login
|
||||
@@ -0,0 +1,233 @@
|
||||
--[[--
|
||||
起点中文网数据映射(纯函数):手机网页 pageContext JSON / 书架行 → 领域对象。
|
||||
|
||||
@module koplugin.book.moonsource_qidian.mapper
|
||||
--]]
|
||||
|
||||
local JSON = require("json")
|
||||
local Text = require("utils.text")
|
||||
|
||||
local Mapper = {}
|
||||
|
||||
local SOURCE_ID = "ext.qidian"
|
||||
local COVER = "https://bookcover.yuewen.com/qdbimg/349573/%s/180"
|
||||
|
||||
--- 封面走阅文 CDN,书号即路径。实测是 JPEG,不强制 gzip。
|
||||
---@param book_id string|number
|
||||
---@return string
|
||||
function Mapper.coverUrl(book_id)
|
||||
return COVER:format(tostring(book_id))
|
||||
end
|
||||
|
||||
--- 手机网页 SSR 的 pageContext → pageData;不是起点页面返回 nil。
|
||||
---@param html string
|
||||
---@return table|nil
|
||||
function Mapper.pageData(html)
|
||||
local raw = type(html) == "string"
|
||||
and html:match('id="vite%-plugin%-ssr_pageContext" type="application/json">(.-)</script>')
|
||||
if not raw then return nil end
|
||||
local ok, wire = pcall(JSON.decode, raw)
|
||||
if not ok or type(wire) ~= "table" then return nil end
|
||||
local props = (wire.pageContext or wire).pageProps
|
||||
local data = props and props.pageData
|
||||
return type(data) == "table" and data or nil
|
||||
end
|
||||
|
||||
--- 详情页 bookInfo → Book。
|
||||
---@param info table
|
||||
---@return Book
|
||||
function Mapper.book(info)
|
||||
local id = tostring(info.bookId)
|
||||
local status = type(info.bookStatus) == "string" and info.bookStatus
|
||||
or type(info.actionStatus) == "string" and info.actionStatus
|
||||
or tonumber(info.actionStatus) == 1 and "连载"
|
||||
or tonumber(info.actionStatus) == 2 and "完结"
|
||||
or nil
|
||||
local tags = type(info.tagName) == "string" and info.tagName ~= "" and info.tagName
|
||||
or type(info.tags) == "string" and info.tags ~= "" and info.tags or nil
|
||||
if tags then tags = (tags:gsub("[,%s;;|/]+", " · ")) end
|
||||
return {
|
||||
source_id = SOURCE_ID,
|
||||
stable_id = id,
|
||||
title = info.bookName,
|
||||
authors = info.authorName,
|
||||
category = info.chanName,
|
||||
intro = info.desc and Text.stripHtml(info.desc),
|
||||
cover = Mapper.coverUrl(id),
|
||||
meta = {
|
||||
words = tonumber(info.wordsCnt),
|
||||
status = status,
|
||||
tags = tags,
|
||||
},
|
||||
}
|
||||
end
|
||||
|
||||
--- 搜索页 pageData.bookInfo.records → Book[]。作者名被站点截成「xx...」,不完整就留空等详情补。
|
||||
---@param data table
|
||||
---@return Book[]
|
||||
function Mapper.search(data)
|
||||
local out = {}
|
||||
for _idx, row in ipairs((data.bookInfo or {}).records or {}) do
|
||||
local id = tostring(row.bid)
|
||||
local author = row.bAuth
|
||||
out[#out + 1] = {
|
||||
source_id = SOURCE_ID,
|
||||
stable_id = id,
|
||||
title = row.bName,
|
||||
authors = type(author) == "string" and not author:find("%.%.%.$") and author or nil,
|
||||
category = row.cat,
|
||||
intro = row.desc and Text.stripHtml(row.desc),
|
||||
cover = Mapper.coverUrl(id),
|
||||
}
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
--- 榜单页 pageData.records → Book[](行形状同搜索)。
|
||||
---@param data table
|
||||
---@return Book[]
|
||||
function Mapper.rank(data)
|
||||
return Mapper.search({ bookInfo = { records = data.records } })
|
||||
end
|
||||
|
||||
--- 书架行 → Book。没有简介,封面按书号拼。
|
||||
---@param row table
|
||||
---@return Book
|
||||
function Mapper.shelfBook(row)
|
||||
local id = tostring(row.bid)
|
||||
return {
|
||||
source_id = SOURCE_ID,
|
||||
stable_id = id,
|
||||
title = row.bName,
|
||||
authors = row.bAuth,
|
||||
category = row.cateName,
|
||||
cover = Mapper.coverUrl(id),
|
||||
}
|
||||
end
|
||||
|
||||
--- 书架行 → Book。有详情用详情,否则沿用本地完整行,都没有才退回书架行。
|
||||
--- 分类口径见 source.category_setting:开 = 只用自定义分组,关 = 只用题材(cateName / chanName)。
|
||||
---@param rows table[]
|
||||
---@return Book[]
|
||||
function Mapper.shelfList(rows)
|
||||
local CategorySetting = require("source.category_setting")
|
||||
local books = {}
|
||||
for _idx, row in ipairs(rows) do
|
||||
local book
|
||||
if row.info then
|
||||
book = Mapper.book(row.info)
|
||||
elseif row.local_book then
|
||||
book = row.local_book
|
||||
if type(book.cover) ~= "string" or book.cover == "" then
|
||||
book.cover = Mapper.coverUrl(row.bid or book.stable_id)
|
||||
end
|
||||
-- 沿用本地行时 category 可能是上次同步的分组名:先刷回书架题材,再按开关决定。
|
||||
if type(row.cateName) == "string" and row.cateName ~= "" then
|
||||
book.category = row.cateName
|
||||
end
|
||||
elseif row.bid then
|
||||
book = Mapper.shelfBook(row)
|
||||
end
|
||||
if book then
|
||||
book.category = CategorySetting.apply(SOURCE_ID, book.category, row._group_name)
|
||||
book.category_authoritative = true
|
||||
books[#books + 1] = book
|
||||
end
|
||||
end
|
||||
return books
|
||||
end
|
||||
|
||||
--- 目录 uT(东八区 `YYYY-MM-DD HH:MM:SS`)→ unix 秒。上传进度要这个数,日期字符串服务端直接 500。
|
||||
---@param text string|nil
|
||||
---@return integer|nil
|
||||
function Mapper.chapterTime(text)
|
||||
if type(text) ~= "string" then return nil end
|
||||
local year, month, day, hour, minute, second = text:match("^(%d+)%-(%d+)%-(%d+) (%d+):(%d+):(%d+)$")
|
||||
if not year then
|
||||
year, month, day, hour, minute = text:match("^(%d+)%-(%d+)%-(%d+) (%d+):(%d+)$")
|
||||
second = "0"
|
||||
end
|
||||
year, month, day = tonumber(year), tonumber(month), tonumber(day)
|
||||
hour, minute, second = tonumber(hour), tonumber(minute), tonumber(second)
|
||||
if not year or month < 1 or month > 12 or day < 1 or day > 31 then return nil end
|
||||
-- Howard Hinnant days_from_civil,再减去东八区。
|
||||
local y = year - (month <= 2 and 1 or 0)
|
||||
local era = math.floor((y >= 0 and y or y - 399) / 400)
|
||||
local yoe = y - era * 400
|
||||
local doy = math.floor((153 * (month + (month > 2 and -3 or 9)) + 2) / 5) + day - 1
|
||||
local doe = yoe * 365 + math.floor(yoe / 4) - math.floor(yoe / 100) + doy
|
||||
local days = era * 146097 + doe - 719468
|
||||
return days * 86400 + hour * 3600 + minute * 60 + second - 8 * 3600
|
||||
end
|
||||
|
||||
--- 书架行里的阅读位置。没有 readCid 就是没读过。
|
||||
---@param row table|nil
|
||||
---@return { uid: string, title: string|nil }|nil
|
||||
function Mapper.readChapter(row)
|
||||
if type(row) ~= "table" then return nil end
|
||||
local uid = row.readCid
|
||||
if uid == nil or tostring(uid) == "" or tonumber(uid) == 0 then return nil end
|
||||
local title = row.readCname
|
||||
return { uid = tostring(uid), title = type(title) == "string" and title or nil }
|
||||
end
|
||||
|
||||
--- 目录页 vs[].cs[] → 目录。卷名不是章;VIP 章(sS=0)也进目录,打开时再看是否已购买。
|
||||
--- updated 是章节更新时间的 unix 秒,进度上传要带上,空字符串会把阅读状态写坏。
|
||||
---@param data table|nil
|
||||
---@return BookChapter[]
|
||||
function Mapper.toc(data)
|
||||
local volumes = data and data.vs
|
||||
local toc = {}
|
||||
for _idx, volume in ipairs(type(volumes) == "table" and volumes or {}) do
|
||||
for _ch, row in ipairs(type(volume.cs) == "table" and volume.cs or {}) do
|
||||
if row.id then
|
||||
toc[#toc + 1] = {
|
||||
idx = #toc + 1,
|
||||
uid = tostring(row.id),
|
||||
title = row.cN,
|
||||
words = tonumber(row.cnt),
|
||||
updated = Mapper.chapterTime(row.uT),
|
||||
vip = tonumber(row.sS) == 0,
|
||||
}
|
||||
end
|
||||
end
|
||||
end
|
||||
return toc
|
||||
end
|
||||
|
||||
--- 未购买的 VIP 只有预览。免费章 isBuy 也是 0,锁章只看 vipStatus。
|
||||
---@param info table|nil
|
||||
---@return boolean
|
||||
function Mapper.locked(info)
|
||||
return type(info) == "table" and tonumber(info.vipStatus) == 1 and tonumber(info.isBuy) ~= 1
|
||||
end
|
||||
|
||||
--- 已购 VIP 的正文是 Fock 密文(官方前端 fEnS=1)。
|
||||
---@param info table|nil
|
||||
---@return boolean
|
||||
function Mapper.fockEncrypted(info)
|
||||
return type(info) == "table" and (tonumber(info.fEnS) or 0) ~= 0
|
||||
end
|
||||
|
||||
--- 已购 VIP 的正文还套了一层字体映射(官方前端 cES=2)。
|
||||
--- TTF 画回真字,`<y class="sy-1">` 还要按 CSS 镜像;正文尾部另有一份诱饵副本。
|
||||
---@param info table|nil
|
||||
---@return boolean
|
||||
function Mapper.fontProtected(info)
|
||||
return type(info) == "table" and tonumber(info.cES) == 2
|
||||
end
|
||||
|
||||
--- 章节 HTML → 纯文本。起点用 <p> 分段,且不保证闭合。
|
||||
---@param html string|nil
|
||||
---@return string|nil
|
||||
function Mapper.chapterText(html)
|
||||
if type(html) ~= "string" or html == "" then return nil end
|
||||
local text = Text.xmlDecode((html
|
||||
:gsub("<[Pp][^>]*>", "\n")
|
||||
:gsub("</[Pp]>", "\n")
|
||||
:gsub("<[Bb][Rr]%s*/?>", "\n")
|
||||
:gsub("<[^>]*>", "")))
|
||||
return Text.trim(text) ~= "" and text or nil
|
||||
end
|
||||
|
||||
return Mapper
|
||||
@@ -0,0 +1,131 @@
|
||||
--[[--
|
||||
起点手机号短信登录窗口。取消只终止本窗口的候选会话,不影响已保存账号。
|
||||
|
||||
@module moonsource_qidian.phone_login
|
||||
--]]
|
||||
|
||||
local Text = require("utils.text")
|
||||
local _ = require("l10n").get("moonsource_qidian")
|
||||
---@class QidianPhoneLogin
|
||||
---@field session QidianLogin
|
||||
---@field on_cookie fun(cookie: string)
|
||||
---@field dialog BookThemeInput
|
||||
---@field verification QidianVerification|nil
|
||||
---@field phone string|nil
|
||||
---@field retry_at integer|nil
|
||||
---@field agreed boolean|nil
|
||||
---@field busy boolean|nil
|
||||
---@field closed boolean|nil
|
||||
local PhoneLogin = {}
|
||||
PhoneLogin.__index = PhoneLogin
|
||||
|
||||
function PhoneLogin.new(on_cookie)
|
||||
return setmetatable({ session = require("moonsource_qidian.login").new(), on_cookie = on_cookie }, PhoneLogin)
|
||||
end
|
||||
|
||||
function PhoneLogin:cancel()
|
||||
self.closed, self.busy = true, false
|
||||
if self.verification then self.verification:cancel() end
|
||||
self.session:cancel()
|
||||
self.phone = nil
|
||||
end
|
||||
|
||||
function PhoneLogin:toast(message)
|
||||
require("ui.themes.widgets.toast"):new{ text = message, timeout = 3 }:show()
|
||||
end
|
||||
|
||||
function PhoneLogin:available()
|
||||
if self.closed then return false end
|
||||
if self.busy then self:toast(_("正在处理,请稍候")); return false end
|
||||
if not require("ui/network/manager"):isConnected() then
|
||||
self:toast(_("网络不可用,请先连接 Wi-Fi")); return false
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
function PhoneLogin:_send(country, phone, proof)
|
||||
self.busy = true
|
||||
self.session:sendCodeAsync(country, phone, proof, function(data, err) self:_sent(country, phone, data, err) end)
|
||||
end
|
||||
|
||||
function PhoneLogin:_sent(country, phone, data, err)
|
||||
if self.closed then return end
|
||||
self.busy = false
|
||||
if not data then self:toast(err or _("请求失败")); return end
|
||||
if tonumber(data.nextAction) == 0 then
|
||||
self.phone, self.retry_at = country .. phone, os.time() + 60
|
||||
self:toast(_("验证码已发送")); return
|
||||
end
|
||||
self.busy = true
|
||||
local verification = require("moonsource_qidian.verify").new(self.session, data, function(proof, done)
|
||||
self.session:sendCodeAsync(country, phone, proof, done)
|
||||
end, function(result, reason)
|
||||
self.verification = nil
|
||||
self:_sent(country, phone, result, reason)
|
||||
end)
|
||||
if not verification.done then self.verification = verification end
|
||||
end
|
||||
|
||||
function PhoneLogin:send(country, phone)
|
||||
if not self:available() then return end
|
||||
country, phone = Text.trim(country), Text.trim(phone)
|
||||
if not country:match("^%+%d+$") or #country > 5 or not phone:match("^%d+$") or #phone < 6 or #phone > 15 then
|
||||
self:toast(_("请输入有效的手机号和国际区号")); return
|
||||
end
|
||||
if self.retry_at and os.time() < self.retry_at then self:toast(_("请稍后再获取验证码")); return end
|
||||
if not self.agreed then
|
||||
require("ui.themes.widgets.confirm"):new{
|
||||
text = _("获取验证码前请阅读并同意阅文用户服务协议和隐私政策")
|
||||
.. "\nhttps://passport.yuewen.com/terms_of_service.html"
|
||||
.. "\nhttps://passport.yuewen.com/privacy_policy.html",
|
||||
ok_text = _("同意并获取验证码"),
|
||||
ok_callback = function() self.agreed = true; self:send(country, phone) end,
|
||||
}:show()
|
||||
return
|
||||
end
|
||||
self:toast(_("正在获取验证码…"))
|
||||
if self.session.initialized then self:_send(country, phone); return end
|
||||
self.busy = true
|
||||
self.session:beginAsync(function(data, err)
|
||||
if self.closed then return end
|
||||
self.busy = false
|
||||
if not data then self:toast(err or _("登录失败")); return end
|
||||
self:_send(country, phone)
|
||||
end)
|
||||
end
|
||||
|
||||
function PhoneLogin:verify(country, phone, code)
|
||||
if not self:available() then return end
|
||||
country, phone, code = Text.trim(country), Text.trim(phone), Text.trim(code)
|
||||
if country .. phone ~= self.phone or not code:match("^%d+$") then
|
||||
self:toast(_("请先获取该手机号的验证码,再填写验证码登录")); return
|
||||
end
|
||||
self.busy = true
|
||||
self:toast(_("正在登录…"))
|
||||
self.session:verifyAsync(phone, code, function(cookie, err)
|
||||
if self.closed then return end
|
||||
self.busy = false
|
||||
if not cookie then self:toast(err or _("登录失败")); return end
|
||||
self:cancel()
|
||||
self.dialog:close()
|
||||
self.on_cookie(cookie)
|
||||
end)
|
||||
end
|
||||
|
||||
function PhoneLogin:start()
|
||||
self.dialog = require("ui.themes.widgets.input"):new{
|
||||
title = _("起点手机号验证码登录"),
|
||||
fields = {
|
||||
{ label = _("国际区号"), text = "+86", hint = "+86" },
|
||||
{ label = _("手机号"), input_type = "number" },
|
||||
{ label = _("验证码"), input_type = "number" },
|
||||
},
|
||||
keep_open = true, ok_text = _("登录"),
|
||||
actions = { { text = _("获取验证码"), callback = function(country, phone) self:send(country, phone) end } },
|
||||
callback = function(country, phone, code) self:verify(country, phone, code) end,
|
||||
cancel_callback = function() self:cancel() end,
|
||||
}
|
||||
self.dialog:show()
|
||||
end
|
||||
|
||||
return PhoneLogin
|
||||
@@ -0,0 +1,151 @@
|
||||
--[[--
|
||||
起点段评:本章每段评论数、某段的评论页、把段落定位到章节 HTML。
|
||||
|
||||
走手机站接口(m.qidian.com/webcommon/chapterreview/*),匿名可读,见 `Client.reviewSummaryAsync`:
|
||||
- reviewsummary4m:本章每段评论数;paragraphId 从 1 数,对应章节正文第 n 个 <p>(起点正文每个 <p> 都非空),-1 是章末总评。
|
||||
- reviewlist4m:某段评论,page 从 1 起。
|
||||
章节 HTML 的段落是非空行逐个包成 <p>(Text.textToBody),所以第 n 个 <p> 就是 paragraphId = n。
|
||||
|
||||
@module koplugin.book.moonsource_qidian.reviews
|
||||
--]]
|
||||
|
||||
local Client = require("moonsource_qidian.client")
|
||||
local ReviewLocate = require("book.review_locate")
|
||||
local Text = require("utils.text")
|
||||
local _ = require("l10n").get("moonsource_qidian")
|
||||
local T = require("ffi/util").template
|
||||
|
||||
local Reviews = {}
|
||||
|
||||
--- 整书帖子预览,与段评/章评分开;官网只给前三条,不虚构后续页。
|
||||
---@param data table
|
||||
---@return table|nil, string|nil
|
||||
function Reviews.bookPage(data)
|
||||
local total = tonumber(data.bookCirclePostCount)
|
||||
if type(data.bookCirclePostList) ~= "table" or not total then
|
||||
return nil, _("起点书友圈响应无效")
|
||||
end
|
||||
local items = {}
|
||||
for _idx, row in ipairs(data.bookCirclePostList) do
|
||||
if type(row) ~= "table" or type(row.title) ~= "string" or type(row.circleReviewDesc) ~= "string"
|
||||
or (row.userName ~= nil and type(row.userName) ~= "string") then
|
||||
return nil, _("起点书友圈响应无效")
|
||||
end
|
||||
items[#items + 1] = { author = row.userName or "",
|
||||
text = Text.stripHtml(row.title) .. "\n" .. Text.stripHtml(row.circleReviewDesc) }
|
||||
end
|
||||
return { items = items, total = total, title = T(_("书友圈预览(%1/%2)"), #items, total) }
|
||||
end
|
||||
|
||||
---@class QidianReviewHotspot
|
||||
---@field range string 段落序号(第几个 <p>)
|
||||
---@field text string
|
||||
---@field total integer 本段评论数
|
||||
|
||||
---- 统计回包 → 有评论的段落与章末(-1);调用方按粒度分开定位。
|
||||
---@param data table
|
||||
---@return QidianReviewHotspot[]
|
||||
function Reviews.hotspots(data)
|
||||
local out = {}
|
||||
for _idx, row in ipairs(data.list or {}) do
|
||||
local pid, total = tonumber(row.paragraphId), tonumber(row.textCount) or 0
|
||||
if pid and (pid > 0 or pid == -1) and total > 0 then
|
||||
out[#out + 1] = { range = tostring(pid), text = "", total = total }
|
||||
end
|
||||
end
|
||||
table.sort(out, function(a, b) return tonumber(a.range) < tonumber(b.range) end)
|
||||
return out
|
||||
end
|
||||
|
||||
--- 表情是「[fn=47]」这样的占位码,没有图可画,去掉。
|
||||
---@param row table
|
||||
---@return WechatReview
|
||||
local function reviewItem(row)
|
||||
local body = tostring(row.content or ""):gsub("%[fn=%d+%]", "")
|
||||
local images = {}
|
||||
if tonumber(row.hasImage) == 1 and type(row.imagePre) == "string" and row.imagePre ~= "" then
|
||||
images[1] = { url = row.imagePre, width = 0, height = 0 }
|
||||
end
|
||||
return {
|
||||
id = tostring(row.reviewId or ""),
|
||||
author = tostring(row.nickName or ""),
|
||||
content = Text.trim(body),
|
||||
likes = tonumber(row.likeCount) or 0,
|
||||
replies = tonumber(row.rootReviewReplyCount) or 0,
|
||||
images = images,
|
||||
time = tonumber(row.createTimestamp) or math.floor((tonumber(row.createTime) or 0) / 1000),
|
||||
reply_to = row.quoteNickName,
|
||||
}
|
||||
end
|
||||
|
||||
---@param row table
|
||||
---@return WechatReview
|
||||
function Reviews.item(row)
|
||||
local item = reviewItem(row)
|
||||
if type(row.replyList) == "table" then
|
||||
local preview = {}
|
||||
for _idx, reply in ipairs(row.replyList) do
|
||||
if type(reply) == "table" and tonumber(reply.status) ~= 0 then
|
||||
preview[#preview + 1] = reviewItem(reply)
|
||||
end
|
||||
end
|
||||
if #preview > 0 then
|
||||
item.reply_preview = preview
|
||||
item.replies = math.max(item.replies, #preview)
|
||||
end
|
||||
end
|
||||
return item
|
||||
end
|
||||
|
||||
--- 评论回包 → 一页。max_idx 存「已取到第几页」(首页请求带 0),避免依赖每页条数。
|
||||
---@param data table
|
||||
---@param page integer
|
||||
---@return WechatReviewPage|nil, string|nil
|
||||
function Reviews.page(data, page)
|
||||
if type(data.list) ~= "table" then return nil, _("起点段评响应缺少评论列表") end
|
||||
local items = {}
|
||||
for _idx, row in ipairs(data.list) do
|
||||
if type(row) == "table" and tonumber(row.status) ~= 0 then items[#items + 1] = Reviews.item(row) end
|
||||
end
|
||||
local total = tonumber(data.total) or #items
|
||||
return { items = items, total = total, max_idx = page,
|
||||
more = #data.list > 0 and data.isEnd ~= true and tonumber(data.isEnd) ~= 1
|
||||
and tonumber(data.size) ~= 0 and (page > 1 or #data.list < total) }
|
||||
end
|
||||
|
||||
--- 本章有评论的段落;这本书没开段评(enableReview ≠ 1)当没有。
|
||||
---@param book_id string
|
||||
---@param chapter_id string
|
||||
---@param cb fun(hotspots: QidianReviewHotspot[]|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
function Reviews.hotspotsAsync(book_id, chapter_id, cb)
|
||||
return Client.reviewSummaryAsync(book_id, chapter_id, function(data, err)
|
||||
if not data then cb(nil, err); return end
|
||||
cb(tonumber(data.enableReview) == 1 and Reviews.hotspots(data) or {})
|
||||
end)
|
||||
end
|
||||
|
||||
--- 某段的一页评论;max_idx 是已取页数(首页 0)。
|
||||
---@param book_id string
|
||||
---@param chapter_id string
|
||||
---@param paragraph_id integer
|
||||
---@param max_idx integer
|
||||
---@param cb fun(page: WechatReviewPage|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
function Reviews.pageAsync(book_id, chapter_id, paragraph_id, max_idx, cb)
|
||||
local page = max_idx + 1
|
||||
return Client.reviewListAsync(book_id, chapter_id, paragraph_id, page, function(data, err)
|
||||
if not data then cb(nil, err); return end
|
||||
cb(Reviews.page(data, page))
|
||||
end)
|
||||
end
|
||||
|
||||
--- 把有评论的段落定位到章节 HTML。
|
||||
---@param hotspots QidianReviewHotspot[]
|
||||
---@param html string
|
||||
---@return table[]
|
||||
function Reviews.locate(hotspots, html)
|
||||
return ReviewLocate.locate(ReviewLocate.paragraphs(html), hotspots, html)
|
||||
end
|
||||
|
||||
return Reviews
|
||||
@@ -0,0 +1,108 @@
|
||||
--[[--
|
||||
起点源设置:登录。
|
||||
|
||||
优先在设备上展示阅文二维码,用起点或 QQ阅读 App 扫码;保留浏览器扩展与手动 Cookie 导入。
|
||||
拿到登录态先拉书架页校验,通过才保存。Cookie 里的 _csrfToken 与请求参数同值。
|
||||
|
||||
@module koplugin.book.moonsource_qidian.setting
|
||||
--]]
|
||||
|
||||
local _ = require("l10n").get("moonsource_qidian")
|
||||
local CookieLogin = require("source.cookie_login")
|
||||
|
||||
local SOURCE_ID = "ext.qidian"
|
||||
local Setting = {}
|
||||
|
||||
---@return boolean
|
||||
local function loggedIn()
|
||||
return require("moonsource_qidian.client").cookie() ~= nil
|
||||
end
|
||||
|
||||
--- 同账号续期不动同步标记;换号保留本地记录并准备上行。
|
||||
local function commit(cookie, account, cb, current)
|
||||
if not account or type(account.id) ~= "string" or not account.id:match("^%d+$") then
|
||||
cb(false, _("起点账号标识缺失")); return
|
||||
end
|
||||
return CookieLogin.commitAccount(SOURCE_ID, cookie, account.id, cb, current)
|
||||
end
|
||||
|
||||
---@type CookieLoginSpec
|
||||
local SPEC = {
|
||||
id = SOURCE_ID,
|
||||
title = _("起点账号"),
|
||||
cookie_title = _("起点登录 Cookie"),
|
||||
cookie_hint = _("按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"),
|
||||
logout_text = _("确定退出起点账号?"),
|
||||
loggedIn = loggedIn,
|
||||
checkAsync = require("moonsource_qidian.client").loginCheckAsync,
|
||||
commit = commit,
|
||||
clear = function(cfg) cfg.cookie, cfg.account_id = nil, nil end,
|
||||
}
|
||||
|
||||
---@return string, boolean
|
||||
function Setting.rowStatus()
|
||||
local on = loggedIn()
|
||||
return on and _("已登录") or _("未登录 · 点此登录"), on
|
||||
end
|
||||
|
||||
Setting.parseCookie = CookieLogin.parse
|
||||
|
||||
--- 浏览器扩展交来的 payload.cookies → Cookie 请求头;只收起点站点的 Cookie。
|
||||
---@param payload table
|
||||
---@return string
|
||||
function Setting.fromPayload(payload)
|
||||
return CookieLogin.fromPayload(payload, "qidian.com")
|
||||
end
|
||||
|
||||
--- 浏览器扩展登录(features/cookie)。
|
||||
Setting.browser = {
|
||||
domain = "m.qidian.com",
|
||||
scope = "cookie",
|
||||
-- 扩展要求 login/check 与 domain 同主机。未登录时书架页自己 302 到 passport,登录完回到本站再采集。
|
||||
login = "https://m.qidian.com/bookshelf/my/",
|
||||
check = "https://m.qidian.com/bookshelf/my/",
|
||||
icon = "https://imgservices-1252317822.image.myqcloud.com/coco/s03102023/b7b10602.w663ve.ico",
|
||||
isAuthorized = function() return CookieLogin.authorized(SPEC) end,
|
||||
apply = function(payload, cb) return CookieLogin.save(SPEC, Setting.fromPayload(payload), cb) end,
|
||||
}
|
||||
|
||||
local function startQR()
|
||||
require("ui/network/manager"):runWhenConnected(function()
|
||||
require("moonsource_qidian.yuewen_qr"):new({
|
||||
app_id = "13", area_id = "31", return_url = "https://m.qidian.com/",
|
||||
ticket = "1",
|
||||
referer = "https://passport.qidian.com/mobile/login",
|
||||
title = _("起点扫码登录"), caption = _("用 QQ阅读或起点 App 扫一扫"),
|
||||
}, function(cookie)
|
||||
-- 不要造假 _csrfToken:loginCheck 会把书架页 Set-Cookie(真 csrf 等)合并后再保存。
|
||||
CookieLogin.verify(SPEC, cookie)
|
||||
end):start()
|
||||
end)
|
||||
end
|
||||
|
||||
---@return table[]
|
||||
function Setting.rows(plugin)
|
||||
local rows = {
|
||||
CookieLogin.accountRow(SPEC, { callback = startQR, off_text = _("未登录 · 点此扫码") }),
|
||||
function(iw)
|
||||
return require("ui.themes.widgets.row").widget{
|
||||
width = iw, chevron = true, kind = "nav", icon = "sms",
|
||||
title = _("手机号验证码登录"),
|
||||
callback = function()
|
||||
require("moonsource_qidian.phone_login").new(function(cookie) CookieLogin.verify(SPEC, cookie) end):start()
|
||||
end,
|
||||
}
|
||||
end,
|
||||
CookieLogin.browserRow(),
|
||||
CookieLogin.pasteRow(SPEC),
|
||||
require("source.review_setting").row(SOURCE_ID, plugin),
|
||||
require("source.category_setting").row(SOURCE_ID, plugin),
|
||||
}
|
||||
if loggedIn() then rows[#rows + 1] = CookieLogin.logoutRow(SPEC) end
|
||||
return rows
|
||||
end
|
||||
|
||||
--- 登录失效提示的「重新登录」直达入口(desktop.sync.promptLogin)。
|
||||
Setting.login = startQR
|
||||
|
||||
return Setting
|
||||
@@ -0,0 +1,393 @@
|
||||
--[[--
|
||||
起点中文网数据源。
|
||||
|
||||
详情 / 目录 / 章节走手机站页面(client.lua)。扫码、短信与浏览器 Cookie 经统一校验保存(setting.lua);
|
||||
登录后书架双向同步(source.shelf):拉取、本地加入上行、本地删除上行。
|
||||
进度只到章:开书从书架行的 readCid 拉,关书经 updReadStatus 推。笔记与统计仅本地记录。
|
||||
VIP 章未购买时打开一页临时提示,目录标注已购 / 未购(打开过才知道)。
|
||||
|
||||
@module moonsource_qidian
|
||||
--]]
|
||||
|
||||
local Browse = require("source.browse")
|
||||
local Client = require("moonsource_qidian.client")
|
||||
local Mapper = require("moonsource_qidian.mapper")
|
||||
local ReviewCache = require("book.review_cache")
|
||||
local Shelf = require("source.shelf")
|
||||
local SourceBase = require("source.base")
|
||||
local Toc = require("source.toc")
|
||||
local _ = require("l10n").get("moonsource_qidian")
|
||||
|
||||
local Qidian = {}
|
||||
|
||||
-- 章节页不小,预取与整本缓存逐章间隔请求。
|
||||
local FETCH_INTERVAL = 1
|
||||
|
||||
---@return BookSourceMeta
|
||||
function Qidian.meta()
|
||||
return require("moonsource_qidian.loadmeta")()
|
||||
end
|
||||
|
||||
---@class QidianSource : SourceBase
|
||||
---@field category_info table[]|nil 官网男频分类目录
|
||||
local Source = setmetatable({ shelf_add = true }, { __index = SourceBase })
|
||||
Source.__index = Source
|
||||
|
||||
---@return QidianSource
|
||||
function Qidian.new()
|
||||
local meta = Qidian.meta()
|
||||
return setmetatable({ id = meta.id, name = meta.name, type = meta.type }, Source)
|
||||
end
|
||||
|
||||
---@return boolean
|
||||
function Source:configured()
|
||||
return Client.cookie() ~= nil
|
||||
end
|
||||
|
||||
--- 书架行没有简介。本地没有简介或封面的书逐本补拉详情,拉不到就退回书架行。
|
||||
---@param rows table[]
|
||||
---@param cb fun(rows: table[])
|
||||
---@return { cancel: fun() }
|
||||
local function fillDetails(rows, cb)
|
||||
local BookDB = require("book.books_db")
|
||||
local cancelled, job, index = false, nil, 0
|
||||
local function nextRow()
|
||||
if cancelled then return end
|
||||
index = index + 1
|
||||
local row = rows[index]
|
||||
if not row then cb(rows); return end
|
||||
row.local_book = BookDB.get(Qidian.meta().id, tostring(row.bid))
|
||||
local book = row.local_book
|
||||
local intro = book and book.intro
|
||||
local cover = book and book.cover
|
||||
if intro and intro ~= "" and cover and cover ~= "" then nextRow(); return end
|
||||
job = Client.detailAsync(row.bid, function(info, err)
|
||||
if cancelled then return end
|
||||
if info then
|
||||
row.info = info
|
||||
else
|
||||
require("utils.log").warn("book qidian detail failed", row.bid, err)
|
||||
end
|
||||
nextRow()
|
||||
end)
|
||||
end
|
||||
nextRow()
|
||||
return { cancel = function()
|
||||
cancelled = true
|
||||
if job then job.cancel() end
|
||||
end }
|
||||
end
|
||||
|
||||
--- 书架远端:Shelf.syncAsync 要的三个冒号方法。
|
||||
local Remote = {}
|
||||
|
||||
function Remote:shelfSyncAsync(cb)
|
||||
local cancelled, job, fill = false, nil, nil
|
||||
job = Client.shelfAsync(Client.cookie(), function(rows, err)
|
||||
if cancelled then return end
|
||||
if not rows then cb(nil, err); return end
|
||||
fill = fillDetails(rows, cb)
|
||||
end)
|
||||
return { cancel = function()
|
||||
cancelled = true
|
||||
job.cancel()
|
||||
if fill then fill.cancel() end
|
||||
end }
|
||||
end
|
||||
|
||||
function Remote:addToShelfAsync(stable_id, cb)
|
||||
return Client.addAsync(stable_id, cb)
|
||||
end
|
||||
|
||||
function Remote:removeFromShelfAsync(stable_id, cb)
|
||||
return Client.removeAsync(stable_id, cb)
|
||||
end
|
||||
|
||||
function Source:syncBooksAsync(opts, cb)
|
||||
if not self:configured() then return SourceBase.skipped(cb, "qidian not logged in") end
|
||||
return Shelf.syncAsync(self.id, Remote, Mapper.shelfList, opts, cb)
|
||||
end
|
||||
|
||||
--- 书架行的 readCid 才是用户看到的进度。getReadStatus 在查询章等于已读章时会把章号省掉。
|
||||
function Source:getProgressAsync(identity, cb)
|
||||
if not self:configured() then return SourceBase.defer(cb, nil, _("未登录起点")) end
|
||||
local cancelled, job = false, nil
|
||||
job = Client.shelfAsync(Client.cookie(), function(rows, err)
|
||||
if cancelled then return end
|
||||
if not rows then cb(nil, err); return end
|
||||
local row
|
||||
for _idx, item in ipairs(rows) do
|
||||
if tostring(item.bid) == tostring(identity.stable_id) then row = item; break end
|
||||
end
|
||||
local read = Mapper.readChapter(row)
|
||||
if not read then cb(nil, nil, { empty = true }); return end
|
||||
job = self:loadTocAsync(identity, function(toc, reason)
|
||||
if cancelled then return end
|
||||
if not toc or #toc == 0 then cb(nil, reason or _("起点目录为空")); return end
|
||||
local idx = Toc.index(self.id, identity.stable_id, read.uid)
|
||||
if not idx then cb(nil, nil, { empty = true }); return end
|
||||
cb({
|
||||
chapter_idx = idx,
|
||||
chapter_title = read.title,
|
||||
fraction = (idx - 1) / #toc,
|
||||
extra = { chapter_uid = read.uid, chapter_idx = idx },
|
||||
})
|
||||
end)
|
||||
end)
|
||||
return { cancel = function()
|
||||
cancelled = true
|
||||
if job and job.cancel then job.cancel() end
|
||||
end }
|
||||
end
|
||||
|
||||
function Source:putProgressAsync(identity, pos, cb)
|
||||
if not self:configured() then return SourceBase.defer(cb, nil, _("未登录起点")) end
|
||||
local cancelled, job = false, nil
|
||||
local function send(chapter)
|
||||
if not chapter.updated then
|
||||
cb(nil, _("起点章节时间缺失"))
|
||||
return
|
||||
end
|
||||
job = Client.updateReadAsync(identity.stable_id, chapter.uid, chapter.title, chapter.vip, chapter.updated,
|
||||
function(ok, err)
|
||||
if cancelled then return end
|
||||
cb(ok and true or nil, err)
|
||||
end)
|
||||
end
|
||||
job = self:loadTocAsync(identity, function(toc, err)
|
||||
if cancelled then return end
|
||||
if not toc then cb(nil, err); return end
|
||||
local idx = tonumber(pos.chapter_idx) or tonumber(identity.chapter_idx)
|
||||
local chapter = idx and toc[idx]
|
||||
if not chapter or not chapter.uid then
|
||||
cb(nil, _("缺少起点章节位置"))
|
||||
return
|
||||
end
|
||||
if chapter.updated then send(chapter); return end
|
||||
-- 旧目录缓存没有章节更新时间。不带时间上传会把阅读状态写坏,先补拉目录。
|
||||
job = Client.catalogAsync(identity.stable_id, function(data, reason)
|
||||
if cancelled then return end
|
||||
local fresh = data and Mapper.toc(data)
|
||||
if fresh and #fresh > 0 then Toc.put(self.id, identity.stable_id, fresh) end
|
||||
local hit
|
||||
for _ch, item in ipairs(fresh or {}) do
|
||||
if item.uid == chapter.uid then hit = item; break end
|
||||
end
|
||||
if not hit then cb(nil, reason or _("缺少起点章节位置")); return end
|
||||
if not hit.updated then cb(nil, _("起点章节时间缺失")); return end
|
||||
send(hit)
|
||||
end)
|
||||
end)
|
||||
return { cancel = function()
|
||||
cancelled = true
|
||||
if job and job.cancel then job.cancel() end
|
||||
end }
|
||||
end
|
||||
|
||||
--- 书城搜索:回包形状同 listStoreAsync。
|
||||
---@param keyword string
|
||||
---@param cb fun(res: { data: Book[] }|nil, err: string|nil)
|
||||
---@return { cancel: fun() }|nil
|
||||
function Source:searchAsync(keyword, cb)
|
||||
return Browse.pages(function(page, done)
|
||||
return Client.searchAsync(keyword, function(data, err)
|
||||
if not data then done(nil, err); return end
|
||||
local info = data.bookInfo
|
||||
done(Mapper.search(data), nil, info.isLast ~= 1 and info.isLast ~= true)
|
||||
end, page)
|
||||
end, 200, {}, cb)
|
||||
end
|
||||
|
||||
local RANKS = {
|
||||
{ key = "yuepiao", title = _("月票榜") },
|
||||
{ key = "hotsales", title = _("畅销榜") },
|
||||
{ key = "readindex", title = _("阅读指数榜") },
|
||||
{ key = "newfans", title = _("新人榜") },
|
||||
{ key = "update", title = _("更新榜") },
|
||||
{ key = "newbook", title = _("新书榜") },
|
||||
{ key = "newauthor", title = _("新作者榜") },
|
||||
}
|
||||
local CATS = {
|
||||
{ id = "-1", title = _("全站") }, { id = "21", title = _("玄幻") }, { id = "1", title = _("奇幻") },
|
||||
{ id = "2", title = _("武侠") }, { id = "22", title = _("仙侠") }, { id = "4", title = _("都市") },
|
||||
{ id = "15", title = _("现实") }, { id = "6", title = _("军事") }, { id = "5", title = _("历史") },
|
||||
{ id = "7", title = _("游戏") }, { id = "8", title = _("体育") }, { id = "9", title = _("科幻") },
|
||||
{ id = "10", title = _("悬疑灵异") }, { id = "20109", title = _("诸天无限") }, { id = "12", title = _("轻小说") },
|
||||
}
|
||||
|
||||
--- 默认分类书库;兼容「榜单键:分类号」旧节点,分类和榜单均聚合后续页。
|
||||
---@param opts { node?: string, limit?: integer }
|
||||
---@param cb fun(res: { data: Book[], groups: StoreChipGroup[] }|nil, err: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
function Source:browseAsync(opts, cb)
|
||||
if not opts.node or opts.node:sub(1, 9) == "category?" then
|
||||
return require("moonsource_qidian.browse").run(self, opts, cb)
|
||||
end
|
||||
local key, cat = (opts.node or RANKS[1].key .. ":-1"):match("^(%w+):(-?%d+)$")
|
||||
if not key then return SourceBase.defer(cb, nil, _("起点分类条件无效")) end
|
||||
local ranks, cats = {}, {}
|
||||
for _idx, rank in ipairs(RANKS) do ranks[#ranks + 1] = { id = rank.key .. ":" .. cat, title = rank.title } end
|
||||
for _idx, row in ipairs(CATS) do cats[#cats + 1] = { id = key .. ":" .. row.id, title = row.title } end
|
||||
local node = key .. ":" .. cat
|
||||
table.insert(ranks, 1, { id = "category?catId=21&gender=male", title = _("分类书库") })
|
||||
local groups = { Browse.group(ranks, node), Browse.group(cats, node) }
|
||||
return Browse.pages(function(page, done)
|
||||
return Client.rankPageAsync(key, cat, page, function(data, err)
|
||||
if not data then done(nil, err); return end
|
||||
done(Mapper.rank(data), nil, data.isLast ~= 1 and data.isLast ~= true)
|
||||
end)
|
||||
end, opts.limit or 60, groups, cb)
|
||||
end
|
||||
|
||||
function Source:getDetailAsync(identity, cb)
|
||||
return SourceBase.defer(cb, identity.book or require("book.books_db").get(self.id, identity.stable_id))
|
||||
end
|
||||
|
||||
---@param identity BookIdentity
|
||||
---@param cb fun(page: table|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
function Source:bookReviewsAsync(identity, cb)
|
||||
if not require("ui/network/manager"):isConnected() then
|
||||
return SourceBase.defer(cb, nil, _("网络不可用,请先连接 Wi-Fi"))
|
||||
end
|
||||
return Client.bookCircleAsync(identity.stable_id, function(data, err)
|
||||
if not data then cb(nil, err); return end
|
||||
cb(require("moonsource_qidian.reviews").bookPage(data))
|
||||
end)
|
||||
end
|
||||
|
||||
--- 强制拉目录并写回;失败由调用方继续用旧缓存。
|
||||
---@param identity BookIdentity
|
||||
---@param cb fun(toc: BookChapter[]|nil, err: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
local function fetchTocAsync(self, identity, cb)
|
||||
local cancelled, job = false, nil
|
||||
job = Client.catalogAsync(identity.stable_id, function(data, err)
|
||||
if cancelled then return end
|
||||
local toc = data and Mapper.toc(data)
|
||||
if not toc then cb(nil, err); return end
|
||||
if #toc == 0 then cb(nil, _("起点目录为空")); return end
|
||||
if not Toc.put(self.id, identity.stable_id, toc) then cb(nil, _("章节目录保存失败")); return end
|
||||
cb(toc)
|
||||
end)
|
||||
return { cancel = function()
|
||||
cancelled = true
|
||||
job.cancel()
|
||||
end }
|
||||
end
|
||||
|
||||
---@param identity BookIdentity
|
||||
---@param cb fun(toc: BookChapter[]|nil, err: string|nil)
|
||||
---@param force boolean|nil 真=跳过缓存强制拉
|
||||
---@return { cancel: fun() }
|
||||
function Source:loadTocAsync(identity, cb, force)
|
||||
if not force then
|
||||
local cached = Toc.read(self.id, identity.stable_id)
|
||||
if cached and #cached > 0 then
|
||||
return SourceBase.defer(cb, cached)
|
||||
end
|
||||
end
|
||||
return fetchTocAsync(self, identity, cb)
|
||||
end
|
||||
|
||||
Source.refreshTocAsync = fetchTocAsync
|
||||
|
||||
function Source:openBookAsync(identity, opts, cb)
|
||||
local Chapter = require("source.chapter")
|
||||
local open = opts and opts.chapter_idx and Chapter.openAsync or Chapter.openWithUi
|
||||
local locate = require("book.review_locate")
|
||||
local reviews = self:paragraphReviewsEnabled()
|
||||
return open(self, identity, identity.book, opts, {
|
||||
loadToc = function(ref, done) return self:loadTocAsync(ref, done) end,
|
||||
fetchContent = Chapter.vipFetcher(self, Client.contentAsync, true, reviews and locate.prepareChapterEnd or nil),
|
||||
reuse = reviews and locate.reuseChapterEnd or nil,
|
||||
}, cb)
|
||||
end
|
||||
|
||||
function Source:prefetchChaptersAsync(identity, toc, from_idx, count, cb)
|
||||
local Chapter = require("source.chapter")
|
||||
local locate = require("book.review_locate")
|
||||
local reviews = self:paragraphReviewsEnabled()
|
||||
return Chapter.prefetchAsync(identity, identity.book, toc, from_idx, count, {
|
||||
fetchContent = Chapter.vipFetcher(self, Client.contentAsync, false, reviews and locate.prepareChapterEnd or nil),
|
||||
reuse = reviews and locate.reuseChapterEnd or nil,
|
||||
interval_seconds = FETCH_INTERVAL,
|
||||
}, cb)
|
||||
end
|
||||
|
||||
function Source:cacheAllChaptersAsync(identity, on_progress, cb, range)
|
||||
local Chapter = require("source.chapter")
|
||||
local prepare = self:paragraphReviewsEnabled() and require("book.review_locate").prepareChapterEnd or nil
|
||||
return Chapter.cacheAllAsync(self, identity, Chapter.vipFetcher(self, Client.contentAsync, false, prepare), on_progress, cb,
|
||||
FETCH_INTERVAL, range)
|
||||
end
|
||||
|
||||
--- 阅读页是否显示他人段评(设置页开关,默认关)。
|
||||
---@return boolean
|
||||
function Source:paragraphReviewsEnabled()
|
||||
return require("source.review_setting").enabled(self.id)
|
||||
end
|
||||
|
||||
--- 本章有评论的段落(未定位)。
|
||||
---@param identity BookIdentity
|
||||
---@param cb fun(hotspots: QidianReviewHotspot[]|nil, err: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
local function hotspotsAsync(self, identity, cb)
|
||||
local withUid = require("source.with_chapter_uid")
|
||||
return ReviewCache.hotspotsAsync(identity, function(done)
|
||||
return withUid.run(self, identity, _("缺少起点章节位置"), function(uid, finish)
|
||||
return require("moonsource_qidian.reviews").hotspotsAsync(identity.stable_id, uid, finish)
|
||||
end, done)
|
||||
end, cb)
|
||||
end
|
||||
|
||||
function Source:paragraphHotspotsAsync(identity, cb)
|
||||
return hotspotsAsync(self, identity, function(list, err)
|
||||
if not list then cb(nil, err); return end
|
||||
local paragraphs = {}
|
||||
for _idx, spot in ipairs(list) do
|
||||
if tonumber(spot.range) > 0 then paragraphs[#paragraphs + 1] = spot end
|
||||
end
|
||||
cb(paragraphs)
|
||||
end)
|
||||
end
|
||||
|
||||
function Source:chapterReviewHotspotsAsync(identity, cb)
|
||||
return hotspotsAsync(self, identity, function(list, err)
|
||||
if not list then cb(nil, err); return end
|
||||
local ending = {}
|
||||
for _idx, spot in ipairs(list) do
|
||||
if spot.range == "-1" then
|
||||
ending[#ending + 1] = { range = spot.range, text = _("本章讨论"), total = spot.total,
|
||||
badge = tostring(spot.total), heading = _("章节评论"),
|
||||
anchor = require("book.review_locate").CHAPTER_ANCHOR }
|
||||
end
|
||||
end
|
||||
cb(ending)
|
||||
end)
|
||||
end
|
||||
|
||||
--- 段落按段序定位到章节 HTML(子进程里跑,不碰实例状态)。
|
||||
---@param hotspots QidianReviewHotspot[]
|
||||
---@param html string
|
||||
---@return table[]
|
||||
function Source:locateHotspots(hotspots, html)
|
||||
return require("moonsource_qidian.reviews").locate(hotspots, html)
|
||||
end
|
||||
|
||||
--- 某段的一页评论;range 是段落序号,max_idx 是已取页数(首页 0)。
|
||||
---@param identity BookIdentity
|
||||
---@param range string
|
||||
---@param max_idx integer
|
||||
---@param cb fun(page: WechatReviewPage|nil, err: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
function Source:paragraphReviewPageAsync(identity, range, max_idx, cb)
|
||||
local withUid = require("source.with_chapter_uid")
|
||||
return ReviewCache.pageAsync(identity, range, max_idx, function(done)
|
||||
return withUid.run(self, identity, _("缺少起点章节位置"), function(uid, finish)
|
||||
return require("moonsource_qidian.reviews").pageAsync(identity.stable_id, uid, tonumber(range), max_idx, finish)
|
||||
end, done)
|
||||
end, cb)
|
||||
end
|
||||
|
||||
return Qidian
|
||||
@@ -0,0 +1,144 @@
|
||||
--[[--
|
||||
起点图形 / 腾讯验证码桥。浏览器只提交验证码凭据,匿名会话、手机号、短信码留在设备。
|
||||
|
||||
@module moonsource_qidian.verify
|
||||
--]]
|
||||
|
||||
local Ext = require("utils.extension")
|
||||
local _ = require("l10n").get("moonsource_qidian")
|
||||
---@class QidianVerification
|
||||
---@field session QidianLogin
|
||||
---@field challenge table
|
||||
---@field submit fun(proof: string, cb: fun(data: table|nil, err: string|nil))
|
||||
---@field callback fun(data: table|nil, err: string|nil)
|
||||
---@field ticket string
|
||||
---@field expires integer
|
||||
---@field timeout function
|
||||
---@field dialog BookThemeQR|nil
|
||||
---@field done boolean|nil
|
||||
---@field pending boolean|nil
|
||||
local Verification = {}
|
||||
Verification.__index = Verification
|
||||
local sessions = {}
|
||||
|
||||
function Verification:finish(result, err)
|
||||
if self.done then return end
|
||||
self.done = true
|
||||
sessions[self.ticket] = nil
|
||||
require("ui/uimanager"):unschedule(self.timeout)
|
||||
local dialog = self.dialog
|
||||
self.dialog = nil
|
||||
if dialog then dialog:close() end
|
||||
self.callback(result, err)
|
||||
end
|
||||
|
||||
function Verification:cancel()
|
||||
if self.done then return end
|
||||
self.session:interrupt()
|
||||
self:finish(nil, _("验证已取消"))
|
||||
end
|
||||
|
||||
function Verification.new(session, challenge, submit, cb)
|
||||
local self = setmetatable({
|
||||
session = session, challenge = challenge, submit = submit, callback = cb,
|
||||
ticket = require("utils.random").hex(24), expires = os.time() + 300,
|
||||
}, Verification)
|
||||
self.timeout = require("ui.guard").wrap("qidian verification timeout", function()
|
||||
self.session:interrupt()
|
||||
self:finish(nil, _("验证已过期,请重新发起验证"))
|
||||
end)
|
||||
sessions[self.ticket] = self
|
||||
require("ui/uimanager"):scheduleIn(300, self.timeout)
|
||||
self.dialog = Ext.call("web.open_page", "/qidian_verify.html#" .. self.ticket,
|
||||
_("起点安全验证"), _("用同一 Wi-Fi 下的手机扫码完成安全验证;手机号、密码和短信码只在设备填写。"), {
|
||||
close_callback = function() self:cancel() end,
|
||||
})
|
||||
if not self.dialog then self:finish(nil, _("无法打开远程验证,请先连接 Wi-Fi 并启用远程管理功能")) end
|
||||
return self
|
||||
end
|
||||
|
||||
local function handle(method, action, params, cb)
|
||||
local function reply(status, body) cb(status, body, { "Cache-Control: no-store" }) end
|
||||
if method ~= "POST" then reply(405, { error = "Method Not Allowed" }); return end
|
||||
local self = type(params.ticket) == "string" and sessions[params.ticket]
|
||||
if not self or os.time() >= self.expires then
|
||||
reply(403, { error = _("验证已过期,请重新发起验证") }); return
|
||||
end
|
||||
if self.pending then reply(409, { error = _("正在提交验证…") }); return end
|
||||
if action == "config" or action == "refresh" then
|
||||
local function config(challenge, err)
|
||||
if self.done or os.time() >= self.expires then reply(403, { error = _("验证已过期,请重新发起验证") }); return end
|
||||
if not challenge then reply(400, { error = err }); return end
|
||||
local mode = tonumber(challenge.nextAction) == 11 and "tencent" or "image"
|
||||
local function ready(image, reason)
|
||||
self.pending = false
|
||||
if self.done then reply(403, { error = _("验证已取消") }); return end
|
||||
if mode == "image" and not image then reply(400, { error = reason }); return end
|
||||
reply(200, {
|
||||
mode = mode, image = image,
|
||||
appid = challenge.imgSrc:match("[?&]aid=(%d+)") or "1600000770",
|
||||
title = _("起点安全验证"), instruction = _("请完成下方安全验证"),
|
||||
pending = _("正在提交验证…"), success = _("验证已提交,请回到设备查看结果。"),
|
||||
failure = _("验证失败,请重新验证"), retry = _("刷新验证码"), submit = _("提交"),
|
||||
})
|
||||
end
|
||||
if mode == "tencent" then
|
||||
if not challenge.imgSrc:find("TCaptcha.js", 1, true) then
|
||||
self.pending = false
|
||||
reply(400, { error = _("起点登录需要未支持的验证") }); return
|
||||
end
|
||||
ready(nil)
|
||||
else
|
||||
self.pending = true
|
||||
self.session:imageAsync(challenge.imgSrc, ready)
|
||||
end
|
||||
end
|
||||
if action == "refresh" then
|
||||
self.pending = true
|
||||
self.session:beginAsync(function(data, err)
|
||||
self.pending = false
|
||||
if not data or type(data.imgSrc) ~= "string" or data.imgSrc == "" then
|
||||
config(nil, err or _("起点验证码刷新失败")); return
|
||||
end
|
||||
data.nextAction = data.imgSrc:find("TCaptcha.js", 1, true) and 11 or 8
|
||||
self.challenge = data
|
||||
config(data)
|
||||
end)
|
||||
else config(self.challenge) end
|
||||
return
|
||||
end
|
||||
if action ~= "verify" then reply(404, { error = "Not Found" }); return end
|
||||
local proof
|
||||
if tonumber(self.challenge.nextAction) == 11 then
|
||||
if type(params.captcha_ticket) ~= "string" or params.captcha_ticket == "" or #params.captcha_ticket > 4096
|
||||
or params.captcha_ticket:match("^trerror_") or type(params.randstr) ~= "string"
|
||||
or params.randstr == "" or #params.randstr > 256 then
|
||||
reply(400, { error = _("验证凭据无效") }); return
|
||||
end
|
||||
proof = params.randstr .. ";" .. params.captcha_ticket
|
||||
else
|
||||
if type(params.code) ~= "string" or params.code == "" or #params.code > 32 then
|
||||
reply(400, { error = _("请输入验证码") }); return
|
||||
end
|
||||
proof = params.code
|
||||
end
|
||||
self.pending = true
|
||||
self.submit(proof, function(data, err)
|
||||
if self.done then reply(403, { error = _("验证已取消") }); return end
|
||||
if os.time() >= self.expires then
|
||||
self:cancel()
|
||||
reply(403, { error = _("验证已过期,请重新发起验证") }); return
|
||||
end
|
||||
if data and tonumber(data.nextAction) == 0 then reply(200, { ok = true })
|
||||
else reply(400, { error = err or _("验证失败,请重新验证") }) end
|
||||
self:finish(data, err)
|
||||
end)
|
||||
end
|
||||
|
||||
Ext.add("web.routes", {
|
||||
name = "qidian_verify", dir = debug.getinfo(1, "S").source:sub(2):match("(.*/)") .. "web",
|
||||
assets = { "qidian_verify.html", "qidian_verify.js" },
|
||||
public = { config = true, refresh = true, verify = true }, handle = handle,
|
||||
})
|
||||
|
||||
return Verification
|
||||
@@ -0,0 +1,25 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<meta name="referrer" content="no-referrer">
|
||||
<title>月读</title>
|
||||
<link rel="stylesheet" href="/style.css">
|
||||
<style>
|
||||
main{max-width:520px;margin:10vh auto;padding:24px}
|
||||
.panel{padding:24px}#captcha{min-height:180px;margin:24px 0}
|
||||
#image{max-width:100%}#code{width:100%;margin:12px 0}
|
||||
#status{overflow-wrap:anywhere;white-space:pre-line}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main><section class="panel">
|
||||
<h1 id="title">月读</h1><p id="instruction"></p>
|
||||
<div id="captcha"></div>
|
||||
<form id="image-form" hidden><img id="image" alt=""><input id="code" autocomplete="off"><button id="submit"></button></form>
|
||||
<p id="status" role="status" aria-live="polite"></p><button id="retry" type="button"></button>
|
||||
</section></main>
|
||||
<script src="/qidian_verify.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,91 @@
|
||||
(async function () {
|
||||
'use strict';
|
||||
const ticket = location.hash.slice(1);
|
||||
const status = document.getElementById('status');
|
||||
const retry = document.getElementById('retry');
|
||||
let messages, captcha, loading = false, submitting = false, done = false;
|
||||
async function request(action, fields = {}) {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), 90000);
|
||||
try {
|
||||
const response = await fetch('/api/qidian_verify/' + action, {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ...fields, ticket }), signal: controller.signal,
|
||||
});
|
||||
const result = await response.json();
|
||||
if (!response.ok) throw new Error(result.error || response.statusText);
|
||||
return result;
|
||||
} finally { clearTimeout(timer); }
|
||||
}
|
||||
async function submit(fields) {
|
||||
if (submitting || done) return;
|
||||
submitting = true;
|
||||
status.textContent = messages.pending;
|
||||
try {
|
||||
await request('verify', fields);
|
||||
done = true;
|
||||
status.textContent = messages.success;
|
||||
document.getElementById('captcha').hidden = true;
|
||||
document.getElementById('image-form').hidden = true;
|
||||
retry.hidden = true;
|
||||
} catch (error) { status.textContent = error.message; }
|
||||
finally { submitting = false; }
|
||||
}
|
||||
function captchaResult(result) {
|
||||
if (!result || result.ret !== 0 || result.errorCode || typeof result.ticket !== 'string'
|
||||
|| !result.ticket || result.ticket.startsWith('trerror_') || typeof result.randstr !== 'string'
|
||||
|| !result.randstr) {
|
||||
status.textContent = messages.failure;
|
||||
return;
|
||||
}
|
||||
return submit({ captcha_ticket: result.ticket, randstr: result.randstr });
|
||||
}
|
||||
function loadScript() {
|
||||
if (typeof window.TencentCaptcha === 'function') return Promise.resolve();
|
||||
return new Promise((resolve, reject) => {
|
||||
const script = document.createElement('script');
|
||||
const timer = setTimeout(() => finish(false), 20000);
|
||||
function finish(ok) {
|
||||
clearTimeout(timer);
|
||||
script.onload = script.onerror = null;
|
||||
if (ok) resolve();
|
||||
else { script.remove(); reject(new Error(messages.failure)); }
|
||||
}
|
||||
script.src = 'https://turing.captcha.qcloud.com/TCaptcha.js';
|
||||
script.onload = () => finish(typeof window.TencentCaptcha === 'function');
|
||||
script.onerror = () => finish(false);
|
||||
document.head.appendChild(script);
|
||||
});
|
||||
}
|
||||
async function load(action) {
|
||||
if (loading || submitting || done) return;
|
||||
loading = true;
|
||||
try {
|
||||
messages = await request(action);
|
||||
document.title = document.getElementById('title').textContent = messages.title;
|
||||
document.getElementById('instruction').textContent = messages.instruction;
|
||||
retry.textContent = messages.retry;
|
||||
document.getElementById('submit').textContent = messages.submit;
|
||||
status.textContent = '';
|
||||
if (captcha) { captcha.destroy(); captcha = null; }
|
||||
const container = document.getElementById('captcha');
|
||||
container.innerHTML = '';
|
||||
container.hidden = messages.mode !== 'tencent';
|
||||
document.getElementById('image-form').hidden = messages.mode !== 'image';
|
||||
document.getElementById('code').value = '';
|
||||
if (messages.mode === 'image') document.getElementById('image').src = messages.image;
|
||||
else {
|
||||
await loadScript();
|
||||
captcha = new window.TencentCaptcha(container, messages.appid, captchaResult, { type: 'embed' });
|
||||
captcha.show();
|
||||
}
|
||||
} catch (error) { status.textContent = error.message; }
|
||||
finally { loading = false; }
|
||||
}
|
||||
document.getElementById('image-form').onsubmit = event => {
|
||||
event.preventDefault();
|
||||
return submit({ code: document.getElementById('code').value });
|
||||
};
|
||||
retry.onclick = () => load('refresh');
|
||||
await load('config');
|
||||
})();
|
||||
@@ -0,0 +1,174 @@
|
||||
--[[--
|
||||
阅文系(起点 / QQ阅读 / 潇湘)Fock 章节解密的公共宿主。
|
||||
|
||||
三家网页端用同一段反盗版 wasm(经 wasm2js 成 asm.js)解密正文,只是各自一个构建:导出名、回调码、栈基址、
|
||||
宿主探测字符串不同。`tools/gen_fock.js` 把每个构建转译成 `source/<id>/fock_wasm.lua`,本模块提供它们共用的
|
||||
内存、导入函数与调用顺序(ctors + main,再 set_uid → set_key → decrypt,结果经导入 b 的回调码交回:
|
||||
三个 int:状态、明文指针、明文长度),源只在 `YuewenFockBuild` 表里填自己那份差异。
|
||||
|
||||
解密要 16MB 内存且纯 Lua 解释执行,在主进程做会拖慢 UI、抬高 KOReader 内存峰值(设备上可被系统杀掉重启),
|
||||
`Fock.jobAsync` 把它放进 fork 子进程,主进程只收结果;转译出的巨型函数会让 ARM 上的 LuaJIT 编译器段错误,
|
||||
`decrypt` 期间关掉 JIT,完事开回来(之后的字形比对要靠它)。
|
||||
|
||||
@module moonsource_qidian.yuewen_fock
|
||||
--]]--
|
||||
|
||||
local ffi = require("ffi")
|
||||
local Job = require("workers.job")
|
||||
local Text = require("utils.text")
|
||||
|
||||
---@class YuewenFockBuild
|
||||
---@field wasm string 转译产物模块名(`source.<id>.fock_wasm`)
|
||||
---@field callback integer 导入 b 交回解密结果的回调码
|
||||
---@field stack integer set_stack 的栈基址
|
||||
---@field exports { ctors: string, main: string, set_uid: string, set_key: string, decrypt: string, stack_save: string, stack_restore: string, alloc: string, malloc: string } 导出名
|
||||
---@field probe fun(code: integer): integer 导入 b 收到非回调码(反调试 / 定时器探测)时的返回值
|
||||
---@field imports fun(env: YuewenFockEnv): table<string, function> 构建特有的导入(宿主字符串探测 c / e / f)
|
||||
|
||||
---@class YuewenFockEnv
|
||||
---@field mem ffi.cdata* 线性内存
|
||||
---@field cstr fun(ptr: integer): string 读内存里的 C 字符串
|
||||
---@field malloc_str fun(s: string): integer 用导出 malloc 放一个 C 字符串,返回指针
|
||||
|
||||
local Fock = {}
|
||||
|
||||
local MEM_SIZE = 16 * 1024 * 1024
|
||||
|
||||
local factories = {}
|
||||
|
||||
--- `Fock.decrypt` 的本体,不碰 JIT 开关。
|
||||
---@param build YuewenFockBuild
|
||||
---@return string|nil text
|
||||
---@return string|nil err
|
||||
local function run(build, content, chapter_id, keypool, version, uid)
|
||||
local factory = factories[build.wasm]
|
||||
if not factory then
|
||||
factory = require(build.wasm)
|
||||
factories[build.wasm] = factory
|
||||
end
|
||||
local names = build.exports
|
||||
local mem = ffi.new("uint8_t[?]", MEM_SIZE)
|
||||
local i32 = ffi.cast("int32_t*", mem)
|
||||
local result, exp
|
||||
|
||||
local function cstr(ptr)
|
||||
local stop = ptr
|
||||
while mem[stop] ~= 0 do stop = stop + 1 end
|
||||
return ffi.string(mem + ptr, stop - ptr)
|
||||
end
|
||||
local function malloc_str(s)
|
||||
local ptr = exp[names.malloc](#s + 1)
|
||||
ffi.copy(mem + ptr, s, #s)
|
||||
mem[ptr + #s] = 0
|
||||
return ptr
|
||||
end
|
||||
|
||||
local imp = build.imports({ mem = mem, cstr = cstr, malloc_str = malloc_str })
|
||||
imp.abort = function() error("fock abort") end
|
||||
imp.d = function(ptr)
|
||||
local now = os.time()
|
||||
if ptr ~= 0 then i32[ptr / 4] = now end
|
||||
return now
|
||||
end
|
||||
imp.b = function(code, _sig, argptr)
|
||||
if code == build.callback then
|
||||
local args = argptr / 4
|
||||
result = { i32[args], i32[args + 1], i32[args + 2] }
|
||||
return 0
|
||||
end
|
||||
return build.probe(code)
|
||||
end
|
||||
|
||||
local data, set_stack
|
||||
exp, data, set_stack = factory({ mem = mem, imp = imp })
|
||||
for _idx, seg in ipairs(data) do
|
||||
local bytes = Text.base64Decode(seg[2])
|
||||
ffi.copy(mem + seg[1], bytes, #bytes)
|
||||
end
|
||||
set_stack(build.stack)
|
||||
|
||||
local function with_stack(fn)
|
||||
local sp = exp[names.stack_save]()
|
||||
local ok, err = pcall(fn)
|
||||
exp[names.stack_restore](sp)
|
||||
if not ok then error(err, 0) end
|
||||
end
|
||||
local function put_bytes(s)
|
||||
local ptr = exp[names.alloc](#s)
|
||||
ffi.copy(mem + ptr, s, #s)
|
||||
return ptr
|
||||
end
|
||||
local function put_string(s)
|
||||
local ptr = exp[names.alloc](#s + 1)
|
||||
ffi.copy(mem + ptr, s, #s)
|
||||
mem[ptr + #s] = 0
|
||||
return ptr
|
||||
end
|
||||
|
||||
local ok, err = pcall(function()
|
||||
exp[names.ctors]()
|
||||
exp[names.main](0, 0)
|
||||
with_stack(function()
|
||||
exp[names.set_uid](put_bytes(uid), #uid)
|
||||
end)
|
||||
local pool = Text.base64Decode(keypool)
|
||||
with_stack(function()
|
||||
exp[names.set_key](put_bytes(pool), #pool, put_string(version))
|
||||
end)
|
||||
local cipher = Text.base64Decode(content)
|
||||
local cid = tostring(chapter_id)
|
||||
with_stack(function()
|
||||
exp[names.decrypt](put_bytes(cipher), #cipher, put_bytes(cid), #cid)
|
||||
end)
|
||||
end)
|
||||
if not ok then return nil, tostring(err) end
|
||||
if not result then return nil, "no result" end
|
||||
if result[1] ~= 0 then return nil, "code " .. result[1] end
|
||||
return ffi.string(mem + result[2], result[3])
|
||||
end
|
||||
|
||||
---@param build YuewenFockBuild
|
||||
---@param content string base64 密文
|
||||
---@param chapter_id string|number
|
||||
---@param keypool string base64 密钥池(fkp 里 onkeyfocus 的第一个参数)
|
||||
---@param version string
|
||||
---@param uid string 用户标识(ywguid / fuid)
|
||||
---@return string|nil text
|
||||
---@return string|nil err
|
||||
function Fock.decrypt(build, content, chapter_id, keypool, version, uid)
|
||||
local jit_was_on = jit.status()
|
||||
jit.off()
|
||||
local text, err = run(build, content, chapter_id, keypool, version, uid)
|
||||
if jit_was_on then jit.on() end
|
||||
return text, err
|
||||
end
|
||||
|
||||
--- 在子进程里跑 worker(解密 / 字体还原),结果 `{ text, err }` 经 cb(text, err) 交回主进程。
|
||||
---@param name string 任务名(日志)
|
||||
---@param worker fun(temp_paths: string[]): { text: string|nil, err: string|nil }
|
||||
---@param cb fun(text: string|nil, err: string|nil)
|
||||
---@return BookJob
|
||||
function Fock.jobAsync(name, worker, cb)
|
||||
local Paths = require("utils.paths")
|
||||
local temp_paths = { Paths.tmpname(".font"), Paths.tmpname(".font") }
|
||||
local job
|
||||
local function cleanup()
|
||||
-- SIGKILL 后仍可能在内核里完成创建文件,等子进程退出再收尾。
|
||||
if job and job.pid and not require("ffi/util").isSubProcessDone(job.pid) then
|
||||
require("ui/uimanager"):scheduleIn(job.poll, cleanup)
|
||||
return
|
||||
end
|
||||
for _idx, path in ipairs(temp_paths) do os.remove(path) end
|
||||
end
|
||||
job = Job.run(function() return worker(temp_paths) end, {
|
||||
name = name,
|
||||
kind = "light",
|
||||
timeout = 600,
|
||||
on_done = function(res) cleanup(); cb(res.text, res.err) end,
|
||||
on_failed = function(err) cleanup(); cb(nil, tostring(err)) end,
|
||||
on_cancelled = cleanup,
|
||||
})
|
||||
return job
|
||||
end
|
||||
|
||||
return Fock
|
||||
@@ -0,0 +1,201 @@
|
||||
--[[--
|
||||
阅文系 VIP 章节的乱序字体还原(QQ阅读 / 起点共用)。
|
||||
|
||||
Fock 解出的 HTML 里,常用字码位被换成别的字,靠随章下发的 fixedFont 画回真字;
|
||||
扩展 A 区的生僻码位再靠 randomFont + CSS 排序/伪元素还原。这里把
|
||||
`utils.glyph` 的字形识别和 `moonsource_qidian.yuewen_fonts.scramble` 的 HTML 解析拼起来。
|
||||
|
||||
字体是随章下发的,写临时文件给 FreeType 读;参考字签名会落盘缓存。
|
||||
|
||||
@module moonsource_qidian.yuewen_fonts
|
||||
--]]--
|
||||
|
||||
local Text = require("utils.text")
|
||||
|
||||
local FontRestore = {}
|
||||
|
||||
local RARE_LIMIT, FIXED_LIMIT = 6763, 3755
|
||||
|
||||
--- 下载回来的字节是不是字体文件(TTF / OTF / TTC / WOFF 魔数)。CDN 的 HTML 错误页也会 200 回来,
|
||||
--- 写进缓存会被当字体复用,一章章都解不出来。
|
||||
---@param bytes string|nil
|
||||
---@return boolean
|
||||
function FontRestore.looksLikeFont(bytes)
|
||||
if type(bytes) ~= "string" or #bytes < 4 then return false end
|
||||
local head = bytes:sub(1, 4)
|
||||
return head == "\0\1\0\0" or head == "OTTO" or head == "true" or head == "ttcf" or head == "wOFF"
|
||||
end
|
||||
|
||||
local function writeTemp(bytes, path)
|
||||
local file = assert(io.open(path, "wb"))
|
||||
local ok, err = file:write(bytes)
|
||||
local closed, close_err = file:close()
|
||||
assert(ok, err)
|
||||
assert(closed, close_err)
|
||||
end
|
||||
|
||||
local function randomFontBytes(font)
|
||||
local parts = {}
|
||||
for idx, byte in ipairs(font and font.data or {}) do parts[idx] = string.char(byte) end
|
||||
return table.concat(parts)
|
||||
end
|
||||
|
||||
--- 乱序码位 / 互换字形 → 真字。
|
||||
---@param random_font table|nil fontResponse.randomFont({data={...}})
|
||||
---@param fixed_font string fixedFontTtf/woff2 下载下来的字节
|
||||
---@param rare integer[] 扩展 A 区码位
|
||||
---@param han integer[] 常用汉字码位
|
||||
---@param opts table { threshold=number, temp_paths=string[]|nil }
|
||||
---@return table rare_map
|
||||
---@return table han_map
|
||||
local function recognize(random_font, fixed_font, rare, han, opts)
|
||||
local rare_bytes = randomFontBytes(random_font)
|
||||
local paths, labels, tasks = {}, {}, {}
|
||||
local function cleanup()
|
||||
for _idx, path in ipairs(paths) do os.remove(path) end
|
||||
end
|
||||
if #rare > 0 and #rare_bytes > 0 then
|
||||
paths[#paths + 1] = opts.temp_paths and opts.temp_paths[1] or require("utils.paths").tmpname(".font")
|
||||
writeTemp(rare_bytes, paths[#paths])
|
||||
labels[#labels + 1] = "rare"
|
||||
tasks[#tasks + 1] = {
|
||||
font_path = paths[#paths], codes = rare, limit = RARE_LIMIT, threshold = opts and opts.threshold,
|
||||
}
|
||||
end
|
||||
if #han > 0 and fixed_font and #fixed_font > 0 then
|
||||
paths[#paths + 1] = opts.temp_paths and opts.temp_paths[2] or require("utils.paths").tmpname(".font")
|
||||
writeTemp(fixed_font, paths[#paths])
|
||||
labels[#labels + 1] = "han"
|
||||
tasks[#tasks + 1] = {
|
||||
font_path = paths[#paths], codes = han, limit = FIXED_LIMIT, threshold = opts and opts.threshold,
|
||||
}
|
||||
end
|
||||
if #tasks == 0 then return {}, {} end
|
||||
|
||||
local ref = require("fontlist").fontdir .. "/noto/NotoSansCJKsc-Regular.otf"
|
||||
local ref_file, ref_err = io.open(ref, "rb")
|
||||
if not ref_file then cleanup(); error(ref_err, 0) end
|
||||
local ref_size = ref_file:seek("end")
|
||||
ref_file:close()
|
||||
-- 签名只取决于参考字体和算法参数;参考字体换了(大小变)自动重算。
|
||||
-- 兼容旧版缓存名(qqreader_glyph_v1_ / glyph_v1_),避免重新渲染 6763 个参考字。
|
||||
local cache_dir = require("utils.paths").cacheDir()
|
||||
local cache = cache_dir .. "/yuewen_glyph_v1_" .. ref_size .. ".bin"
|
||||
for _idx, legacy in ipairs({ "yuewen_glyph_v1_", "qqreader_glyph_v1_", "glyph_v1_" }) do
|
||||
local path = cache_dir .. "/" .. legacy .. ref_size .. ".bin"
|
||||
local f = io.open(path, "rb")
|
||||
if f then
|
||||
f:close()
|
||||
cache = path
|
||||
break
|
||||
end
|
||||
end
|
||||
local ok, maps = pcall(require("utils.glyph").recognize, ref, cache, tasks)
|
||||
cleanup()
|
||||
if not ok then error(maps, 0) end
|
||||
local rare_map, han_map = {}, {}
|
||||
for idx, label in ipairs(labels) do
|
||||
if label == "rare" then rare_map = maps[idx] else han_map = maps[idx] end
|
||||
end
|
||||
return rare_map, han_map
|
||||
end
|
||||
|
||||
local function utf8len(text)
|
||||
return #Text.chars(text)
|
||||
end
|
||||
|
||||
local DECOY_SIMILARITY = 0.8
|
||||
|
||||
local chars = Text.chars
|
||||
|
||||
--- 起点 cES=2 的正文会把同一章再追加一份改了几个字的诱饵副本。
|
||||
--- 前后两半段落字数一一对应、且逐字位置上 ≥80% 相同才丢后一半,避免把真实的对称段落误删。
|
||||
---@param paragraphs string[]
|
||||
---@return string[]
|
||||
local function dropDecoyHalf(paragraphs)
|
||||
local n = #paragraphs
|
||||
if n < 4 or n % 2 ~= 0 then return paragraphs end
|
||||
local half = n / 2
|
||||
local same, total = 0, 0
|
||||
for i = 1, half do
|
||||
local a, b = chars(paragraphs[i]), chars(paragraphs[i + half])
|
||||
if #a ~= #b then return paragraphs end
|
||||
for k = 1, #a do
|
||||
if a[k] == b[k] then same = same + 1 end
|
||||
end
|
||||
total = total + #a
|
||||
end
|
||||
if total == 0 or same / total < DECOY_SIMILARITY then return paragraphs end
|
||||
for i = n, half + 1, -1 do paragraphs[i] = nil end
|
||||
return paragraphs
|
||||
end
|
||||
|
||||
local fixConfusions
|
||||
|
||||
--- 解出的 HTML 段落还原成纯文本。
|
||||
---@param plain string Fock 解出的正文
|
||||
---@param font table { css=string, randomFont=table|nil }
|
||||
---@param fixed_font string|nil fixedFont 下载下来的字节;没有字体加密的章为 nil
|
||||
---@param opts table|nil { dedupe=boolean, confusions=boolean, threshold=number, temp_paths=string[]|nil }
|
||||
---@return string
|
||||
function FontRestore.restore(plain, font, fixed_font, opts)
|
||||
opts = opts or {}
|
||||
local Scramble = require("moonsource_qidian.yuewen_fonts.scramble")
|
||||
local paragraphs = Scramble.paragraphs(plain, font.css or "")
|
||||
if #paragraphs == 0 then return plain end
|
||||
if opts.dedupe then paragraphs = dropDecoyHalf(paragraphs) end
|
||||
local rare, han = Scramble.codes(paragraphs)
|
||||
local rare_map, han_map = {}, {}
|
||||
if #rare + #han > 0 then
|
||||
rare_map, han_map = recognize(font.randomFont, fixed_font, rare, han, opts)
|
||||
end
|
||||
local text = Scramble.text(paragraphs, rare_map, han_map)
|
||||
if opts.confusions then text = fixConfusions(text) end
|
||||
return text
|
||||
end
|
||||
|
||||
FontRestore.dropDecoyHalf = dropDecoyHalf
|
||||
|
||||
-- 起点 fixedFont 里 于/干、责/贵 两组字形太近,16x16 相关度会把“关于/终于/负责”
|
||||
-- 认成“关干/终干/负贵”。只修这些固定搭配;“对干部/在干活”这类保留干。
|
||||
local YU_PREFIX = {
|
||||
["关"] = true, ["终"] = true, ["对"] = true, ["等"] = true, ["至"] = true,
|
||||
["由"] = true, ["属"] = true, ["便"] = true, ["利"] = true, ["善"] = true,
|
||||
["敢"] = true, ["勇"] = true, ["难"] = true, ["易"] = true, ["在"] = true,
|
||||
["位"] = true, ["鉴"] = true,
|
||||
}
|
||||
local YU_KEEP_NEXT = {
|
||||
["部"] = true, ["活"] = true, ["事"] = true, ["劲"] = true, ["什"] = true, ["嘛"] = true, ["啥"] = true,
|
||||
["吗"] = true, ["吧"] = true, ["净"] = true, ["脆"] = true, ["燥"] = true, ["旱"] = true, ["扰"] = true,
|
||||
["预"] = true, ["练"] = true, ["掉"] = true, ["架"] = true, ["涸"] = true,
|
||||
}
|
||||
local ZE_PREFIX = { ["职"] = true, ["担"] = true, ["负"] = true, ["责"] = true, ["贵"] = true }
|
||||
-- 少数整词在 fixedFont 里稳定认错(“泮”几乎只出现在“泮池”,不会误伤正文)。
|
||||
local TEXT_FIXES = {
|
||||
["同泮"] = "同伴",
|
||||
["泮随"] = "伴随",
|
||||
["聚干"] = "聚于",
|
||||
}
|
||||
|
||||
--- 修正两类固定形近字;只在起点字体层启用。
|
||||
--- Lua 的字符类是字节级,不能直接拿“部/活”做 [^...],这里按 UTF-8 单字扫描。
|
||||
---@param text string
|
||||
---@return string
|
||||
fixConfusions = function(text)
|
||||
local list = Text.chars(text)
|
||||
for i = 2, #list do
|
||||
local ch, prev, nxt = list[i], list[i - 1], list[i + 1]
|
||||
if ch == "干" and YU_PREFIX[prev] and not (nxt and YU_KEEP_NEXT[nxt]) then
|
||||
list[i] = "于"
|
||||
elseif ch == "贵" and (ZE_PREFIX[prev] or nxt == "任") then
|
||||
list[i] = "责"
|
||||
end
|
||||
end
|
||||
local fixed = table.concat(list)
|
||||
for from, to in pairs(TEXT_FIXES) do fixed = fixed:gsub(from, to) end
|
||||
return fixed
|
||||
end
|
||||
|
||||
FontRestore.fixConfusions = fixConfusions
|
||||
|
||||
return FontRestore
|
||||
@@ -0,0 +1,162 @@
|
||||
--[[--
|
||||
QQ阅读正文乱序还原:Fock 解出的是带反爬样式的 HTML,真正的字序和字形要靠随章下发的 CSS 才能还原。
|
||||
|
||||
- 有 `pN` 类的段落,子元素 `<yXX>` 按 `yXX{order:n}` 重排(网页是 flex 容器),每个元素再按
|
||||
`.pN yXX::first-letter{font-size:0}`(藏掉原字)与 `::before` / `::after` 的 `content`(字面量或 `attr(x)`)还原;
|
||||
- `<y class="sy-0">` 是 `font-size:0` 的占位,丢弃;`sy-1` 只是镜像显示,文字照留;
|
||||
- 其余码位落在 CJK 扩展 A 的字,是 randomFont 画出来的真字,由 `glyph.lua` 认出,这里只负责替换。
|
||||
|
||||
@module moonsource_qidian.yuewen_fonts.scramble
|
||||
--]]--
|
||||
|
||||
local Glyph = require("utils.glyph")
|
||||
|
||||
local Scramble = {}
|
||||
|
||||
local CHAR = require("utils.text").UTF8_CHAR
|
||||
|
||||
local UNKNOWN = "□"
|
||||
local LOW, HIGH = 0x3400, 0x4DBF
|
||||
|
||||
local function expand(css)
|
||||
return (css:gsub("TS%-1", "transform:scaleX(-1)"):gsub("::B", "::before"):gsub("::A", "::after")
|
||||
:gsub("{O:", "{order:"):gsub("{C:", "{content:"):gsub("'''", "'\\''"))
|
||||
end
|
||||
|
||||
--- content 值:'x' / "x" 字面量或 attr(name)。
|
||||
local function contentOf(body, attrs)
|
||||
local value = body:match("content:%s*(.-)%s*;?%s*$")
|
||||
if not value then return nil end
|
||||
local name = value:match("^attr%(([%w_-]+)%)$")
|
||||
if name then return attrs[name] or "" end
|
||||
return value:match("^'(.*)'$") or value:match('^"(.*)"$') or ""
|
||||
end
|
||||
|
||||
--- 解析 CSS:order[tag] 与 rules[class .. " " .. tag][self|first-letter|before|after] = body。
|
||||
local function parse(css)
|
||||
local order, rules = {}, {}
|
||||
for sel, body in expand(css):gmatch("([^{}]+){([^}]*)}") do
|
||||
sel = sel:match("^%s*(.-)%s*$")
|
||||
local tag, n = sel:match("^(y[%w_-]*)$"), body:match("^order:(%d+)")
|
||||
if tag and n then
|
||||
order[tag] = tonumber(n)
|
||||
else
|
||||
local key, pseudo = sel:match("^%.(p%d+ y[%w_-]*)::([%a-]+)$")
|
||||
if not key then key, pseudo = sel:match("^%.(p%d+ y[%w_-]*)$"), "self" end
|
||||
if key then
|
||||
rules[key] = rules[key] or {}
|
||||
rules[key][pseudo] = body
|
||||
end
|
||||
end
|
||||
end
|
||||
return order, rules
|
||||
end
|
||||
|
||||
local function attributes(raw)
|
||||
local attrs = {}
|
||||
for name, value in raw:gmatch('([%w_-]+)="([^"]*)"') do attrs[name] = value end
|
||||
return attrs
|
||||
end
|
||||
|
||||
local function dropFirst(text)
|
||||
return (text:gsub("^" .. CHAR, "", 1))
|
||||
end
|
||||
|
||||
local function unescape(text)
|
||||
return (text:gsub("<", "<"):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_qidian.yuewen_qr
|
||||
--]]
|
||||
|
||||
require("l10n").apply()
|
||||
local JSON = require("json")
|
||||
local Request = require("http.request")
|
||||
local Text = require("utils.text")
|
||||
local logger = require("utils.log")
|
||||
local _ = require("gettext")
|
||||
|
||||
local QRLogin = {}
|
||||
QRLogin.__index = QRLogin
|
||||
|
||||
local BASE = "https://ptlogin.yuewen.com"
|
||||
local POLL_INTERVAL = 3
|
||||
local POLL_MAX = 40
|
||||
local DEADLINE = 180
|
||||
local MAX_HOPS = 5
|
||||
local UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
.. "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
|
||||
|
||||
local KEEP = { ywguid = true, ywkey = true, ywopenid = true }
|
||||
|
||||
---@param value any
|
||||
---@return string|nil
|
||||
local function text(value)
|
||||
if type(value) == "string" and value ~= "" then return value end
|
||||
if type(value) == "number" then return tostring(value) end
|
||||
end
|
||||
|
||||
---@return table
|
||||
function QRLogin:baseParams()
|
||||
return {
|
||||
appId = self.spec.app_id,
|
||||
areaId = self.spec.area_id,
|
||||
format = "json",
|
||||
returnurl = self.spec.return_url,
|
||||
target = "top",
|
||||
ticket = self.spec.ticket or "0",
|
||||
autotime = "14",
|
||||
auto = "0",
|
||||
}
|
||||
end
|
||||
|
||||
--- 二维码内容。和官方图里的 URL 同一组参数,顺序无所谓。
|
||||
---@param session_key string
|
||||
---@return string
|
||||
function QRLogin:scanUrl(session_key)
|
||||
return BASE .. "/mobile/scanlogin?" .. Text.formEncode({
|
||||
sessionkey = session_key,
|
||||
appid = self.spec.app_id,
|
||||
areaid = self.spec.area_id,
|
||||
bookId = "0",
|
||||
chapterId = "0",
|
||||
})
|
||||
end
|
||||
|
||||
---@param jar table
|
||||
---@return string
|
||||
local function cookieHeader(jar)
|
||||
local keys = {}
|
||||
for key, value in pairs(jar) do
|
||||
if KEEP[key] and value ~= "" then keys[#keys + 1] = key end
|
||||
end
|
||||
table.sort(keys)
|
||||
local parts = {}
|
||||
for i, key in ipairs(keys) do parts[i] = key .. "=" .. jar[key] end
|
||||
return table.concat(parts, "; ")
|
||||
end
|
||||
|
||||
---@param jar table
|
||||
---@param set_cookie string|table|nil
|
||||
local function takeCookies(jar, set_cookie)
|
||||
if type(set_cookie) == "table" then
|
||||
for _key, value in pairs(set_cookie) do takeCookies(jar, value) end
|
||||
return
|
||||
end
|
||||
if type(set_cookie) ~= "string" or set_cookie == "" then return end
|
||||
for name, value in set_cookie:gmatch("([%w_]+)=([^;,]*)") do
|
||||
name = name:lower()
|
||||
value = value:match("^(.-)%s*$")
|
||||
if KEEP[name] and value ~= "" then jar[name] = value end
|
||||
end
|
||||
end
|
||||
|
||||
---@param data table|nil
|
||||
---@param jar table
|
||||
local function takeJson(data, jar)
|
||||
if type(data) ~= "table" then return end
|
||||
local value = data.ywGuid or data.ywguid
|
||||
local guid = type(value) == "number" and string.format("%.0f", value) or text(value)
|
||||
local key = text(data.ywKey or data.ywkey)
|
||||
local openid = text(data.ywOpenId or data.ywopenid)
|
||||
if guid then jar.ywguid = guid end
|
||||
if key then jar.ywkey = key end
|
||||
if openid then jar.ywopenid = openid end
|
||||
if type(data.data) == "table" then takeJson(data.data, jar) end
|
||||
end
|
||||
|
||||
---@param jar table
|
||||
---@return boolean
|
||||
local function ready(jar)
|
||||
return jar.ywguid ~= nil and jar.ywguid ~= "" and jar.ywkey ~= nil and jar.ywkey ~= ""
|
||||
end
|
||||
|
||||
---@class YuewenQRSpec
|
||||
---@field app_id string
|
||||
---@field area_id string
|
||||
---@field return_url string
|
||||
---@field referer string
|
||||
---@field title string
|
||||
---@field caption string
|
||||
---@field ticket string|nil 非 0 时必须兑换本站 Web 会话
|
||||
|
||||
---@param spec YuewenQRSpec
|
||||
---@param on_cookie fun(cookie: string)
|
||||
function QRLogin.new(_class, spec, on_cookie)
|
||||
local self = setmetatable({}, QRLogin)
|
||||
self.spec = spec
|
||||
self.on_cookie = on_cookie
|
||||
self.generation = 0
|
||||
self.jar = {}
|
||||
self.dialog = nil
|
||||
self.retry_dialog = nil
|
||||
self.busy = nil
|
||||
self.job = nil
|
||||
self.started = 0
|
||||
self.polls = 0
|
||||
self.session = nil
|
||||
self.login_completed = false
|
||||
self.scanned_notified = false
|
||||
return self
|
||||
end
|
||||
|
||||
function QRLogin:toast(text_msg)
|
||||
require("ui.themes.widgets.toast"):new{ text = tostring(text_msg), timeout = 2 }:show()
|
||||
end
|
||||
|
||||
function QRLogin:closeBusy()
|
||||
if self.busy then
|
||||
self.busy:close()
|
||||
self.busy = nil
|
||||
end
|
||||
end
|
||||
|
||||
function QRLogin:showBusy(text_msg)
|
||||
self:closeBusy()
|
||||
self.busy = require("ui.themes.widgets.progress_dialog"):new{
|
||||
title = self.spec.title, text = text_msg, dismissable = false,
|
||||
}
|
||||
self.busy:show()
|
||||
end
|
||||
|
||||
function QRLogin:_close_dialog()
|
||||
if self.dialog then
|
||||
local dialog = self.dialog
|
||||
self.dialog = nil
|
||||
dialog:close()
|
||||
end
|
||||
end
|
||||
|
||||
function QRLogin:_close_retry()
|
||||
if self.retry_dialog then
|
||||
local dialog = self.retry_dialog
|
||||
self.retry_dialog = nil
|
||||
dialog:close()
|
||||
end
|
||||
end
|
||||
|
||||
function QRLogin:_cancel_job()
|
||||
if self.job and self.job.cancel then self.job.cancel() end
|
||||
self.job = nil
|
||||
end
|
||||
|
||||
function QRLogin:cancel()
|
||||
self.generation = self.generation + 1
|
||||
self.login_completed = false
|
||||
self:_cancel_job()
|
||||
self:_close_dialog()
|
||||
self:_close_retry()
|
||||
self:closeBusy()
|
||||
self.jar = {}
|
||||
self.session = nil
|
||||
self.polls = 0
|
||||
self.scanned_notified = false
|
||||
end
|
||||
|
||||
---@param url string
|
||||
---@param cb fun(res: table|nil, err: string|nil)
|
||||
function QRLogin:_get(url, cb)
|
||||
local headers = {
|
||||
["User-Agent"] = UA,
|
||||
Accept = "application/json, text/javascript, */*",
|
||||
Referer = self.spec.referer,
|
||||
}
|
||||
local host = url:match("^https://([^/?#]+)")
|
||||
if host == self.spec.return_url:match("^https://([^/?#]+)") then
|
||||
local cookie = cookieHeader(self.jar)
|
||||
if cookie ~= "" then headers.Cookie = cookie end
|
||||
end
|
||||
local pending, gen = true, self.generation
|
||||
local job = Request.request({
|
||||
url = url,
|
||||
method = "GET",
|
||||
headers = headers,
|
||||
timeout = require("http.timeout").net(0.5),
|
||||
allow_redirects = false,
|
||||
}, function(res, err)
|
||||
pending = false
|
||||
if gen ~= self.generation then return end
|
||||
self.job = nil
|
||||
if err or not res then
|
||||
cb(nil, err and tostring(err) or _("请求失败"))
|
||||
return
|
||||
end
|
||||
local code = tonumber(res.code)
|
||||
if not code or code < 200 or code >= 400 then
|
||||
cb(nil, "HTTP " .. tostring(res.code))
|
||||
return
|
||||
end
|
||||
cb(res)
|
||||
end)
|
||||
if pending then self.job = job end
|
||||
end
|
||||
|
||||
---@param res table|nil
|
||||
---@return table|nil
|
||||
local function decode(res)
|
||||
local body = res and res.body
|
||||
if type(body) ~= "string" or body == "" then return nil end
|
||||
local ok, wire = pcall(JSON.decode, body)
|
||||
if not ok or type(wire) ~= "table" then return nil end
|
||||
return wire
|
||||
end
|
||||
|
||||
function QRLogin:_expired()
|
||||
return self.polls >= POLL_MAX or os.time() - self.started > DEADLINE
|
||||
end
|
||||
|
||||
---@param gen integer
|
||||
---@param session string
|
||||
function QRLogin:_later(gen, session)
|
||||
require("ui/uimanager"):scheduleIn(POLL_INTERVAL, function()
|
||||
self:_poll(gen, session)
|
||||
end)
|
||||
end
|
||||
|
||||
---@param gen integer
|
||||
function QRLogin:_show(gen, session)
|
||||
if gen ~= self.generation then return end
|
||||
self:closeBusy()
|
||||
self.session = session
|
||||
self.polls = 0
|
||||
local dialog
|
||||
dialog = require("ui.themes.widgets.qr"):new{
|
||||
title = self.spec.title,
|
||||
text = self:scanUrl(session),
|
||||
caption = self.spec.caption,
|
||||
close_callback = function()
|
||||
if self.dialog == dialog then self.dialog = nil end
|
||||
if gen == self.generation and not self.login_completed then
|
||||
self:cancel()
|
||||
self:toast(_("已取消登录"))
|
||||
end
|
||||
end,
|
||||
}
|
||||
self.dialog = dialog
|
||||
dialog:show()
|
||||
logger.info("[YuewenQR] 二维码已显示")
|
||||
self:_later(gen, session)
|
||||
end
|
||||
|
||||
function QRLogin:start()
|
||||
self:cancel()
|
||||
local gen = self.generation
|
||||
self.started = os.time()
|
||||
self.jar = {}
|
||||
self:showBusy(_("获取二维码中..."))
|
||||
local params = self:baseParams()
|
||||
self:_get(BASE .. "/login/qrcode?" .. Text.formEncode(params), function(res, err)
|
||||
if gen ~= self.generation then return end
|
||||
local wire = decode(res)
|
||||
local session = wire and type(wire.data) == "table" and text(wire.data.sessionKey)
|
||||
if not session or tonumber(wire.code) ~= 0 then
|
||||
self:closeBusy()
|
||||
logger.warn("[YuewenQR] 获取二维码失败:", err or (wire and wire.message))
|
||||
self:show_retry(_("获取二维码失败"))
|
||||
return
|
||||
end
|
||||
self:_show(gen, session)
|
||||
end)
|
||||
end
|
||||
|
||||
---@param gen integer
|
||||
---@param jar table
|
||||
function QRLogin:_done(gen, jar)
|
||||
if gen ~= self.generation or self.login_completed then return end
|
||||
if not ready(jar) then
|
||||
self:show_retry(_("登录失败:未获取到登录态"))
|
||||
return
|
||||
end
|
||||
self.login_completed = true
|
||||
self.generation = self.generation + 1
|
||||
self:_cancel_job()
|
||||
self:_close_dialog()
|
||||
self:_close_retry()
|
||||
self:closeBusy()
|
||||
local cookie = cookieHeader(jar)
|
||||
logger.info("[YuewenQR] 登录态已拿到")
|
||||
if self.on_cookie then self.on_cookie(cookie) end
|
||||
end
|
||||
|
||||
---@param gen integer
|
||||
---@param url string
|
||||
---@param hop integer
|
||||
function QRLogin:_follow(gen, url, hop)
|
||||
if gen ~= self.generation then return end
|
||||
local host = type(url) == "string" and url:match("^https://([^/?#]+)")
|
||||
local target = self.spec.return_url:match("^https://([^/?#]+)")
|
||||
if not host or (host ~= target and host ~= "ptlogin.yuewen.com"
|
||||
and host ~= "passport.yuewen.com" and host ~= "passport.qidian.com"
|
||||
and host ~= "login.book.qq.com") or hop > MAX_HOPS then
|
||||
self:show_retry(_("登录失败:未获取到登录态"))
|
||||
return
|
||||
end
|
||||
self:showBusy(_("正在完成登录..."))
|
||||
self:_get(url, function(res, err)
|
||||
if gen ~= self.generation then return end
|
||||
if not res then
|
||||
logger.warn("[YuewenQR] 跟跳失败:", err)
|
||||
self:show_retry(_("登录失败:未获取到登录态"))
|
||||
return
|
||||
end
|
||||
for _idx, value in ipairs(Request.headerAll(res, "Set-Cookie")) do takeCookies(self.jar, value) end
|
||||
local location = Text.absoluteUrl(url, Request.header(res, "Location"))
|
||||
if tonumber(res.code) >= 300 then
|
||||
if not location then
|
||||
self:show_retry(_("登录失败:未获取到登录态")); return
|
||||
end
|
||||
self:_follow(gen, location, hop + 1)
|
||||
return
|
||||
end
|
||||
-- ticket=1 仍要求落到本站 host;本站实际上常常不 Set-Cookie ywkey(只有 abPolicies),
|
||||
-- 不能把「见到 ywkey Set-Cookie」当成兑换成功条件,否则扫码永远失败。
|
||||
if ready(self.jar) and (self.spec.ticket ~= "1" or host == target) then
|
||||
self:_done(gen, self.jar)
|
||||
return
|
||||
end
|
||||
if not location then
|
||||
self:show_retry(_("登录失败:未获取到登录态"))
|
||||
return
|
||||
end
|
||||
self:_follow(gen, location, hop + 1)
|
||||
end)
|
||||
end
|
||||
|
||||
---@param gen integer
|
||||
---@param session string
|
||||
---@param wire table
|
||||
---@param res table
|
||||
function QRLogin:_on_poll(gen, session, wire, res)
|
||||
for _idx, value in ipairs(Request.headerAll(res, "Set-Cookie")) do takeCookies(self.jar, value) end
|
||||
local data = type(wire.data) == "table" and wire.data or {}
|
||||
takeJson(data, self.jar)
|
||||
takeJson(wire, self.jar)
|
||||
local status = tonumber(wire.scanStatus)
|
||||
local code = tonumber(wire.code)
|
||||
if code == -11033 then
|
||||
self:show_retry(text(wire.message) or _("登录失败"))
|
||||
return
|
||||
end
|
||||
if status == 5 and code == 0 then
|
||||
local ticket = text(data.ticket) or text(wire.ticket)
|
||||
local jump = text(data["302url"]) or text(wire["302url"])
|
||||
-- 起点 ticket=1:裸 302url(https://m.qidian.com/ 无 ticket)没用,改成本站 ticket 兑换。
|
||||
-- 若 302url 走 ptlogin 中转,照跟——那才是会带上完整跳转链的路径。
|
||||
if self.spec.ticket == "1" then
|
||||
local target = self.spec.return_url:match("^https://([^/?#]+)")
|
||||
local jump_host = jump and jump:match("^https://([^/?#]+)")
|
||||
local bare_home = jump_host == target and not jump:find("ticket=", 1, true)
|
||||
if ticket and (not jump or bare_home) then
|
||||
jump = self.spec.return_url .. (self.spec.return_url:find("?", 1, true) and "&" or "?")
|
||||
.. Text.formEncode({
|
||||
ticket = ticket,
|
||||
ywguid = self.jar.ywguid or "",
|
||||
ywOpenId = self.jar.ywopenid or "",
|
||||
})
|
||||
elseif not jump then
|
||||
self:show_retry(_("登录失败:未获取到登录态"))
|
||||
return
|
||||
end
|
||||
self:_follow(gen, jump, 1)
|
||||
return
|
||||
end
|
||||
if jump then
|
||||
self:_follow(gen, jump, 1)
|
||||
return
|
||||
end
|
||||
if ready(self.jar) then
|
||||
self:_done(gen, self.jar)
|
||||
return
|
||||
end
|
||||
self:show_retry(_("登录失败:未获取到登录态"))
|
||||
return
|
||||
end
|
||||
if status == 3 then
|
||||
logger.info("[YuewenQR] 手机取消,刷新二维码")
|
||||
self.generation = self.generation + 1
|
||||
self:_close_dialog()
|
||||
self:start()
|
||||
return
|
||||
end
|
||||
if status == 4 or self:_expired() then
|
||||
self:show_retry(_("二维码已过期"))
|
||||
return
|
||||
end
|
||||
if status == 1 and not self.scanned_notified then
|
||||
self.scanned_notified = true
|
||||
self.polls = 0
|
||||
self.started = os.time()
|
||||
self:toast(_("已扫码,请在手机上确认"))
|
||||
end
|
||||
self:_later(gen, session)
|
||||
end
|
||||
|
||||
---@param gen integer
|
||||
---@param session string
|
||||
function QRLogin:_poll(gen, session)
|
||||
if gen ~= self.generation or session ~= self.session then return end
|
||||
if self:_expired() then
|
||||
self:show_retry(_("二维码已过期"))
|
||||
return
|
||||
end
|
||||
self.polls = self.polls + 1
|
||||
local params = self:baseParams()
|
||||
params.qrcode = session
|
||||
self:_get(BASE .. "/login/qrcodelogin?" .. Text.formEncode(params), function(res, err)
|
||||
if gen ~= self.generation or session ~= self.session then return end
|
||||
local wire = decode(res)
|
||||
if not wire then
|
||||
if self.polls == 1 or self.polls % 5 == 0 then
|
||||
logger.warn("[YuewenQR] 轮询失败:", err)
|
||||
end
|
||||
if self:_expired() then
|
||||
self:show_retry(_("二维码已过期"))
|
||||
return
|
||||
end
|
||||
self:_later(gen, session)
|
||||
return
|
||||
end
|
||||
self:_on_poll(gen, session, wire, res)
|
||||
end)
|
||||
end
|
||||
|
||||
function QRLogin:show_retry(msg)
|
||||
self.generation = self.generation + 1
|
||||
self:_cancel_job()
|
||||
self:_close_dialog()
|
||||
self:_close_retry()
|
||||
self:closeBusy()
|
||||
local dialog
|
||||
dialog = require("ui.themes.widgets.confirm"):new{
|
||||
text = tostring(msg),
|
||||
ok_text = _("重新获取"),
|
||||
ok_callback = function()
|
||||
if self.retry_dialog == dialog then self.retry_dialog = nil end
|
||||
self:start()
|
||||
end,
|
||||
cancel_callback = function()
|
||||
if self.retry_dialog == dialog then self.retry_dialog = nil end
|
||||
self:cancel()
|
||||
end,
|
||||
}
|
||||
self.retry_dialog = dialog
|
||||
dialog:show()
|
||||
end
|
||||
|
||||
return QRLogin
|
||||
@@ -0,0 +1,115 @@
|
||||
--[[-- 起点分类:动态菜单、男 / 女频筛选、去重分页、错误与取消。 @module tests.moonsource_qidian.browse_spec --]]
|
||||
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local requests, pages, failure, delayed, late, cancelled = {}, {}, nil, false, nil, nil
|
||||
local metadata = {
|
||||
orderBy = { items = { { text = "人气", value = "" }, { text = "时间", value = "4" } } },
|
||||
filters = {
|
||||
{ key = "subCatId", title = "子分类", items = { { text = "全部", value = "" }, { text = "东方玄幻", value = 8 } } },
|
||||
{ key = "isvip", title = "资费", items = { { text = "全部", value = "" }, { text = "VIP", value = 1 } } },
|
||||
{ key = "isfinish", title = "状态", items = { { text = "全部", value = "" }, { text = "完本", value = 1 } } },
|
||||
},
|
||||
}
|
||||
package.preload["moonsource_qidian.client"] = function()
|
||||
return {
|
||||
categoryAsync = function(cat, cb)
|
||||
requests[#requests + 1] = cat or "index"
|
||||
cb(cat and metadata or { info = { { catId = 21, catName = "玄幻" }, { catId = 22, catName = "仙侠" } } })
|
||||
return { cancel = function() cancelled = "metadata" end }
|
||||
end,
|
||||
categoryListAsync = function(params, cb)
|
||||
requests[#requests + 1] = params
|
||||
local function done()
|
||||
if failure == params.pageNum then cb(nil, "offline")
|
||||
else cb({ records = pages[params.pageNum] or {}, pageNum = params.pageNum,
|
||||
isLast = params.pageNum >= #pages and 1 or 0, pageMax = 50 }) end
|
||||
end
|
||||
if delayed then late = done else done() end
|
||||
return { cancel = function() cancelled = "page" end }
|
||||
end,
|
||||
}
|
||||
end
|
||||
local Library = require("moonsource_qidian.browse")
|
||||
local function row(id) return { bid = id, bName = "书" .. id } end
|
||||
local function reset()
|
||||
requests, failure, delayed, late, cancelled = {}, nil, false, nil, nil
|
||||
pages = { { row(1), row(2) }, { row(2), row(3) }, { row(4), row(5) } }
|
||||
end
|
||||
|
||||
do
|
||||
reset()
|
||||
local source, result = {}, nil
|
||||
Library.run(source, { limit = 5 }, function(value) result = value end)
|
||||
Assert.len(result.data, 5, "合并后续页并按稳定身份去重")
|
||||
Assert.eq(result.data[3].stable_id, "3")
|
||||
Assert.eq(requests[1], "index")
|
||||
Assert.eq(requests[2], "21")
|
||||
Assert.eq(requests[5].pageNum, 3)
|
||||
Assert.len(source.category_info, 2, "动态分类归源实例所有")
|
||||
Assert.len(result.groups, 6, "资费、状态各自成组,不再把选中标记写进标题")
|
||||
Assert.eq(result.groups[4].title, "子分类")
|
||||
Assert.eq(result.groups[5].title, "资费")
|
||||
Assert.eq(result.groups[6].title, "状态")
|
||||
Assert.eq(result.groups[5].chips[2].title, "VIP")
|
||||
Assert.eq(result.groups[1].chips[3].id, "yuepiao:-1", "分类页仍可进入原榜单")
|
||||
Assert.matches(result.groups[2].chips[2].id, "catId=22")
|
||||
end
|
||||
|
||||
do
|
||||
reset()
|
||||
local result
|
||||
Library.run({}, { node = "category?catId=80&gender=female&isvip=1&isfinish=1&orderBy=4", limit = 2 },
|
||||
function(value) result = value end)
|
||||
Assert.eq(requests[3].gender, "female")
|
||||
Assert.eq(requests[3].catId, "80")
|
||||
Assert.eq(requests[3].isvip, "1")
|
||||
Assert.eq(requests[3].isfinish, "1")
|
||||
Assert.eq(requests[3].orderBy, "4")
|
||||
Assert.eq(result.groups[2].chips[1].title, "古代言情")
|
||||
Assert.matches(result.groups[1].chips[1].id, "catId=21")
|
||||
Assert.matches(result.groups[1].chips[1].id, "isvip=1", "跨频道保留兼容条件")
|
||||
Assert.eq(result.groups[5].chips[2].title, "VIP")
|
||||
Assert.eq(result.groups[5].active, result.groups[5].chips[2].id, "资费用 group.active 标选中")
|
||||
Assert.eq(result.groups[6].chips[2].title, "完本")
|
||||
Assert.eq(result.groups[6].active, result.groups[6].chips[2].id)
|
||||
end
|
||||
|
||||
do
|
||||
reset()
|
||||
failure = 2
|
||||
local result, err
|
||||
Library.run({}, { limit = 5 }, function(value, reason) result, err = value, reason end)
|
||||
Assert.is_nil(result, "中间页失败不能伪装成完整列表")
|
||||
Assert.eq(err, "offline")
|
||||
end
|
||||
|
||||
do
|
||||
reset()
|
||||
pages = { { row(1) }, { row(1) }, { row(2) } }
|
||||
local result, err
|
||||
Library.run({}, { limit = 5 }, function(value, reason) result, err = value, reason end)
|
||||
Assert.is_nil(result, "源重复整页不能无限循环")
|
||||
Assert.is_true(err ~= nil)
|
||||
end
|
||||
|
||||
do
|
||||
reset()
|
||||
delayed = true
|
||||
local called = false
|
||||
local job = Library.run({}, { limit = 5 }, function() called = true end)
|
||||
job.cancel()
|
||||
Assert.eq(cancelled, "page", "同步目录回调不能覆盖在飞分页的句柄")
|
||||
late()
|
||||
Assert.is_false(called)
|
||||
Assert.len(requests, 3)
|
||||
end
|
||||
|
||||
do
|
||||
reset()
|
||||
pages = { {} }
|
||||
local result
|
||||
Library.run({}, { limit = 60 }, function(value) result = value end)
|
||||
Assert.len(result.data, 0)
|
||||
Assert.len(requests, 3)
|
||||
end
|
||||
@@ -0,0 +1,39 @@
|
||||
--[[-- 起点升级离线缓存不删章节,启用章评时原地追加入口。 @module tests.moonsource_qidian.cache_spec --]]
|
||||
local Assert = require("support.assert")
|
||||
local Config = require("support.config")
|
||||
Config.setupNativePath()
|
||||
local lfs = require("libs/libkoreader-lfs")
|
||||
local Paths = require("utils.paths")
|
||||
local source = require("moonsource_qidian.source").new()
|
||||
local dir = Config.dir() .. "/qidian-cache-preserve"
|
||||
lfs.mkdir(dir)
|
||||
local path = dir .. "/1.html"
|
||||
local file = assert(io.open(path, "wb"))
|
||||
file:write("<html><body><p>离线可读正文</p></body></html>")
|
||||
file:close()
|
||||
local work_dir = Paths.bookWorkDir
|
||||
Paths.bookWorkDir = function() return dir end
|
||||
source.paragraphReviewsEnabled = function() return true end
|
||||
package.loaded["source.chapter"] = nil
|
||||
package.preload["source.chapter"] = function()
|
||||
return {
|
||||
vipFetcher = function() return function() error("缓存命中不应拉正文") end end,
|
||||
openAsync = function(_source, _identity, _book, _opts, ops, cb)
|
||||
Assert.is_true(ops.reuse(path))
|
||||
cb(path)
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
end
|
||||
local opened
|
||||
source:openBookAsync({ source_id = "ext.qidian", stable_id = "fixture" }, { chapter_idx = 1 },
|
||||
function(value) opened = value end)
|
||||
Assert.eq(opened, path)
|
||||
file = assert(io.open(path, "rb"))
|
||||
local html = file:read("*a")
|
||||
file:close()
|
||||
Assert.matches(html, "<p>离线可读正文</p>")
|
||||
Assert.matches(html, 'id="moon%-chapter%-reviews"')
|
||||
Paths.bookWorkDir = work_dir
|
||||
os.remove(path)
|
||||
lfs.rmdir(dir)
|
||||
@@ -0,0 +1,119 @@
|
||||
--[[-- 起点短信候选会话:图形 / 短信 key、官方兑换、取消与同步回调。 @module tests.moonsource_qidian.login_spec --]]
|
||||
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local JSON = require("support.json_stub")
|
||||
local Text = require("utils.text")
|
||||
package.preload["json"] = function() return JSON end
|
||||
local responses, requests, cancelled, late = {}, {}, {}, nil
|
||||
package.preload["http.request"] = function()
|
||||
return {
|
||||
request = function(opts, cb)
|
||||
requests[#requests + 1] = opts
|
||||
local index, res = #requests, table.remove(responses, 1)
|
||||
if res.defer then late = function() cb(res, res.err) end else cb(res, res.err) end
|
||||
return { cancel = function() cancelled[#cancelled + 1] = index end }
|
||||
end,
|
||||
header = function(res, key) return (res.headers or {})[key] end,
|
||||
headerAll = function(res, key)
|
||||
local value = (res.headers or {})[key]
|
||||
return type(value) == "table" and value or (value and { value } or {})
|
||||
end,
|
||||
}
|
||||
end
|
||||
local Login = require("moonsource_qidian.login")
|
||||
local function wire(data)
|
||||
return { code = 200, body = JSON.encode({ code = 0, data = data }) }
|
||||
end
|
||||
local function params(index)
|
||||
local result = {}
|
||||
for key, value in requests[index].url:match("%?(.*)"):gmatch("([^&=]+)=([^&]*)") do
|
||||
result[key] = Text.urlDecode(value)
|
||||
end
|
||||
return result
|
||||
end
|
||||
local function reset() responses, requests, cancelled, late = {}, {}, {}, nil end
|
||||
|
||||
do
|
||||
reset()
|
||||
local init = wire({ sessionKey = "image-key", imgSrc = "https://ptlogin.yuewen.com/image" })
|
||||
init.headers = { ["Set-Cookie"] = { "al=anonymous; Path=/", "session=anonymous-session; Path=/" } }
|
||||
responses = { init, wire({ nextAction = 0, sessionKey = "sms-key" }),
|
||||
wire({ nextAction = 0, ticket = "ticket", ywGuid = "raw-guid", ywKey = "raw-key" }),
|
||||
{ code = 302, headers = { Location = "/done", ["Set-Cookie"] = { "ywguid=321; Path=/", "ywkey=site-key; Path=/" } } },
|
||||
{ code = 200, body = "OK" } }
|
||||
local session, cookie = Login.new()
|
||||
session:beginAsync(function(data) Assert.is_true(data ~= nil) end)
|
||||
session:sendCodeAsync("+86", "13800000000", "image-code", function(data) Assert.eq(data.nextAction, 0) end)
|
||||
session:verifyAsync("13800000000", "123456", function(value) cookie = value end)
|
||||
Assert.eq(params(2).sessionKey, "image-key")
|
||||
Assert.eq(params(2).validateCode, "image-code")
|
||||
Assert.eq(params(2).inputUserId, "+8613800000000")
|
||||
Assert.eq(params(2).phoneIsAbroad, "0")
|
||||
Assert.eq(params(2).auto, "anonymous")
|
||||
Assert.eq(params(3).sessionKey, "sms-key")
|
||||
Assert.eq(params(3).inputUserId, "13800000000", "官方短信提交不带国际区号")
|
||||
Assert.matches(cookie, "ywguid=321")
|
||||
Assert.matches(cookie, "ywkey=site%-key")
|
||||
Assert.is_nil(cookie:find("_csrfToken", 1, true), "短信登录也不造假 csrf,交给 loginCheck 合并")
|
||||
Assert.is_nil(cookie:find("anonymous", 1, true), "匿名登录域 Cookie 不保存为书源凭据")
|
||||
Assert.is_nil(requests[1].headers.Cookie:find("ywkey", 1, true), "候选会话不读已保存账号")
|
||||
Assert.eq(requests[3].allow_redirects, false)
|
||||
end
|
||||
|
||||
do
|
||||
reset()
|
||||
responses = { wire({ nextAction = 11, sessionKey = "captcha-key",
|
||||
imgSrc = "https://turing.captcha.qcloud.com/TCaptcha.js?aid=1600000770" }),
|
||||
wire({ nextAction = 0, sessionKey = "sms" }) }
|
||||
local session = Login.new()
|
||||
session:sendCodeAsync("+852", "12345678", nil, function(data) Assert.eq(data.nextAction, 11) end)
|
||||
session:sendCodeAsync("+852", "12345678", "random;proof", function(data) Assert.eq(data.nextAction, 0) end)
|
||||
Assert.eq(params(2).sessionKey, "captcha-key")
|
||||
Assert.eq(params(2).validateCode, "random;proof")
|
||||
Assert.eq(params(1).phoneIsAbroad, "1")
|
||||
Assert.eq(session.sms_key, "sms")
|
||||
end
|
||||
|
||||
do
|
||||
reset()
|
||||
responses = { { code = 200, body = "not json" }, wire({ nextAction = 99 }) }
|
||||
local session, err = Login.new()
|
||||
session:beginAsync(function(value, reason) Assert.is_nil(value); err = reason end)
|
||||
Assert.matches(err, "响应无效")
|
||||
session:sendCodeAsync("+86", "13800000000", nil, function(value, reason) Assert.is_nil(value); err = reason end)
|
||||
Assert.matches(err, "未支持")
|
||||
end
|
||||
|
||||
do
|
||||
reset()
|
||||
responses = { wire({ nextAction = 0, ticket = "ticket", ywGuid = "123", ywKey = "raw" }),
|
||||
{ code = 302, headers = { Location = "/done" } }, { code = 200, body = "OK", defer = true } }
|
||||
local session, called = Login.new(), false
|
||||
session.sms_key = "sms"
|
||||
session:verifyAsync("13800000000", "123456", function() called = true end)
|
||||
session:cancel()
|
||||
Assert.eq(cancelled[1], 3, "同步首段回调不能覆盖后续兑换的取消句柄")
|
||||
late()
|
||||
Assert.is_false(called)
|
||||
Assert.is_nil(session.sms_key)
|
||||
Assert.is_nil(next(session.webjar))
|
||||
end
|
||||
|
||||
do
|
||||
reset()
|
||||
responses = { wire({ nextAction = 0, ["302url"] = "https://qidian.com.evil.example/x", ywGuid = "1", ywKey = "k" }) }
|
||||
local session, err = Login.new()
|
||||
session.sms_key = "sms"
|
||||
session:verifyAsync("13800000000", "123456", function(value, reason) Assert.is_nil(value); err = reason end)
|
||||
Assert.matches(err, "跳转地址无效")
|
||||
Assert.len(requests, 1)
|
||||
end
|
||||
|
||||
do
|
||||
reset()
|
||||
responses = { { code = 200, body = "\137PNG\r\n\26\nimage" } }
|
||||
local image
|
||||
Login.new():imageAsync("/image", function(value) image = value end)
|
||||
Assert.matches(image, "^data:image/png;base64,")
|
||||
end
|
||||
@@ -0,0 +1,64 @@
|
||||
--[[-- 起点短信窗口:同意协议、断网、冷却、绑定手机号与取消。 @module tests.moonsource_qidian.phone_login_spec --]]
|
||||
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local Theme = require("support.theme_stubs")
|
||||
Theme.install()
|
||||
local connected, begins, sends, verifies, cancelled, deferred, late = true, 0, 0, 0, 0, false, nil
|
||||
package.preload["ui/network/manager"] = function() return { isConnected = function() return connected end } end
|
||||
package.preload["moonsource_qidian.login"] = function()
|
||||
return { new = function() return {
|
||||
beginAsync = function(self, cb) begins = begins + 1; self.initialized = true; cb({}) end,
|
||||
sendCodeAsync = function(_self, country, phone, proof, cb)
|
||||
sends = sends + 1
|
||||
Assert.eq(country, "+86"); Assert.eq(phone, "13800000000"); Assert.is_nil(proof)
|
||||
cb({ nextAction = 0 })
|
||||
end,
|
||||
verifyAsync = function(_self, phone, code, cb)
|
||||
verifies = verifies + 1
|
||||
Assert.eq(phone, "13800000000"); Assert.eq(code, "123456")
|
||||
if deferred then late = function() cb("candidate") end else cb("candidate") end
|
||||
end,
|
||||
cancel = function() cancelled = cancelled + 1 end,
|
||||
} end }
|
||||
end
|
||||
local Phone = require("moonsource_qidian.phone_login")
|
||||
local cookie
|
||||
local phone = Phone.new(function(value) cookie = value end)
|
||||
phone:start()
|
||||
Assert.eq(Theme.last("input").title, "起点手机号验证码登录")
|
||||
Assert.is_true(Theme.last("input").keep_open)
|
||||
|
||||
connected = false
|
||||
phone:send("+86", "13800000000")
|
||||
Assert.eq(sends, 0)
|
||||
Assert.matches(Theme.last("toast").text, "网络不可用")
|
||||
connected = true
|
||||
phone:send("+86", "invalid")
|
||||
Assert.eq(sends, 0)
|
||||
phone:send("+86", "13800000000")
|
||||
Assert.eq(begins, 0, "同意协议前不初始化或发送短信")
|
||||
Theme.last("confirm").ok_callback()
|
||||
Assert.eq(begins, 1)
|
||||
Assert.eq(sends, 1)
|
||||
phone:send("+86", "13800000000")
|
||||
Assert.eq(sends, 1, "冷却期不重复发短信")
|
||||
phone:verify("+86", "13900000000", "123456")
|
||||
Assert.eq(verifies, 0, "不能把验证码用于另一个手机号")
|
||||
phone:verify("+86", "13800000000", "abc")
|
||||
Assert.eq(verifies, 0)
|
||||
phone:verify("+86", "13800000000", "123456")
|
||||
Assert.eq(cookie, "candidate")
|
||||
Assert.is_true(Theme.last("input").closed)
|
||||
Assert.eq(cancelled, 1)
|
||||
|
||||
phone = Phone.new(function() Assert.is_true(false, "取消后不得保存迟到候选") end)
|
||||
phone:start()
|
||||
phone.agreed = true
|
||||
phone:send("+86", "13800000000")
|
||||
deferred = true
|
||||
phone:verify("+86", "13800000000", "123456")
|
||||
phone:cancel()
|
||||
late()
|
||||
Assert.eq(cancelled, 2)
|
||||
Assert.is_nil(phone.phone)
|
||||
@@ -0,0 +1,193 @@
|
||||
--[[--
|
||||
起点正文流程:cES=2 先下字体再解密,cES=0/fEnS=0 直接出文本。
|
||||
|
||||
@module tests.source.qidian_content_spec
|
||||
--]]
|
||||
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local JSONStub = require("support.json_stub")
|
||||
local Text = require("utils.text")
|
||||
|
||||
package.preload["json"] = function()
|
||||
return { decode = JSONStub.decode, encode = JSONStub.encode }
|
||||
end
|
||||
|
||||
local cfg = { cookie = "ywguid=123; ywkey=k" }
|
||||
package.preload["utils.settings"] = function()
|
||||
return { getSource = function() return cfg end }
|
||||
end
|
||||
|
||||
local replies, deferred, requested_cookie = {}, nil, nil
|
||||
package.preload["http.request"] = function()
|
||||
return {
|
||||
get = function(url, opts, cb)
|
||||
requested_cookie = opts.headers and opts.headers.Cookie
|
||||
local reply = table.remove(replies, 1)
|
||||
if reply and reply.defer then deferred = function() cb(reply.body, reply.err, reply.res) end
|
||||
else cb(reply and reply.body, reply and reply.err, reply and reply.res) end
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
end
|
||||
|
||||
local FONT_BYTES = "\0\1\0\0FONTBYTES"
|
||||
local fock_calls = {}
|
||||
package.preload["moonsource_qidian.fock"] = function()
|
||||
return {
|
||||
chapterAsync = function(info, font, chapter_id, keypool, version, uid, cb)
|
||||
fock_calls[#fock_calls + 1] = {
|
||||
kind = "chapter", font = font, chapter_id = chapter_id,
|
||||
keypool = keypool, version = version, uid = uid,
|
||||
}
|
||||
cb("RESTORED")
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
restoreAsync = function(html, info, font, cb)
|
||||
fock_calls[#fock_calls + 1] = { kind = "restore", font = font, html = html }
|
||||
cb("RESTORED")
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
decryptAsync = function(content, chapter_id, keypool, version, uid, cb)
|
||||
fock_calls[#fock_calls + 1] = { kind = "decrypt", uid = uid }
|
||||
cb("<p>甲</p>")
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
end
|
||||
|
||||
package.loaded["moonsource_qidian.client"] = nil
|
||||
package.loaded["moonsource_qidian.mapper"] = nil
|
||||
local Client = require("moonsource_qidian.client")
|
||||
|
||||
local function page(info, user)
|
||||
return '<script id="vite-plugin-ssr_pageContext" type="application/json">'
|
||||
.. JSONStub.encode({ pageContext = { pageProps = { pageData = { chapterInfo = info, user = user } } } }) .. "</script>"
|
||||
end
|
||||
|
||||
local function fkp()
|
||||
return Text.base64Encode('window.onkeyfocus("KEYPOOL", 1635757421)')
|
||||
end
|
||||
|
||||
local function info(extra)
|
||||
local out = {
|
||||
chapterName = "第一章", chapterId = 9, vipStatus = 1, isBuy = 1,
|
||||
content = "CIPHER", fkp = fkp(), cES = 0, fEnS = 0,
|
||||
}
|
||||
for k, v in pairs(extra or {}) do out[k] = v end
|
||||
return out
|
||||
end
|
||||
|
||||
do
|
||||
-- 扫码 Cookie 的 GUID 不一定是章节响应的解码身份;用响应确认的 GUID。
|
||||
local html = page(info({ fEnS = 1 })):gsub('"pageData":{', '"pageData":{"user":{"guid":1234567890123456},')
|
||||
replies = { { body = html } }
|
||||
fock_calls = {}
|
||||
local text
|
||||
Client.contentAsync("1", "2", function(value) text = value end)
|
||||
Assert.is_true(text ~= nil)
|
||||
Assert.eq(fock_calls[1].uid, "1234567890123456", "LuaJIT tostring 会把长整数变成科学计数法")
|
||||
end
|
||||
|
||||
do
|
||||
-- 请求发出后换账号,旧响应仍绑定原请求,不重新读新 Cookie。
|
||||
cfg.cookie = "ywguid=123; ywkey=old"
|
||||
replies = { { defer = true, body = page(info({ fEnS = 1 })) } }
|
||||
fock_calls = {}
|
||||
Client.contentAsync("1", "2", function() end)
|
||||
Assert.eq(requested_cookie, cfg.cookie)
|
||||
cfg.cookie = "ywguid=999; ywkey=new"
|
||||
deferred()
|
||||
Assert.eq(fock_calls[1].uid, "123")
|
||||
cfg.cookie = "ywguid=123; ywkey=k"
|
||||
end
|
||||
|
||||
do
|
||||
replies = { { defer = true, body = page(info({ fEnS = 1 })) } }
|
||||
fock_calls = {}
|
||||
local called = false
|
||||
local job = Client.contentAsync("1", "2", function() called = true end)
|
||||
job.cancel()
|
||||
deferred()
|
||||
Assert.is_false(called, "取消后不交付迟到正文")
|
||||
Assert.len(fock_calls, 0)
|
||||
end
|
||||
|
||||
do
|
||||
-- 免费 / 普通章:不走 Fock,也不下字体。
|
||||
replies = { { body = page(info({ content = "<p>甲</p>" })) } }
|
||||
fock_calls = {}
|
||||
local text
|
||||
Client.contentAsync("1", "2", function(v) text = v end)
|
||||
Assert.eq(text, "\n甲\n")
|
||||
Assert.len(fock_calls, 0)
|
||||
end
|
||||
|
||||
do
|
||||
-- Fock + cES=2:先拉 fixedFontTtf,再把字节交给解密 + 字体还原。
|
||||
replies = {
|
||||
{ body = page(info({ fEnS = 1, cES = 2, fixedFontTtf = "https://font/fixed.ttf", randomFont = "{}", css = "" })) },
|
||||
{ body = FONT_BYTES },
|
||||
}
|
||||
fock_calls = {}
|
||||
local text
|
||||
Client.contentAsync("1", "2", function(v) text = v end)
|
||||
Assert.eq(text, "RESTORED")
|
||||
Assert.len(fock_calls, 1)
|
||||
Assert.eq(fock_calls[1].kind, "chapter")
|
||||
Assert.eq(fock_calls[1].font, FONT_BYTES)
|
||||
Assert.eq(fock_calls[1].uid, "123")
|
||||
Assert.eq(fock_calls[1].keypool, "KEYPOOL")
|
||||
Assert.eq(fock_calls[1].version, "1635757421")
|
||||
end
|
||||
|
||||
do
|
||||
-- 只有字体层(fEnS=0):直接还原 HTML,不做 Fock。
|
||||
replies = {
|
||||
{ body = page(info({ fEnS = 0, cES = 2, fixedFontTtf = "https://font/fixed.ttf", randomFont = "{}", css = "" })) },
|
||||
{ body = FONT_BYTES },
|
||||
}
|
||||
fock_calls = {}
|
||||
local text
|
||||
Client.contentAsync("1", "2", function(v) text = v end)
|
||||
Assert.eq(text, "RESTORED")
|
||||
Assert.len(fock_calls, 1)
|
||||
Assert.eq(fock_calls[1].kind, "restore")
|
||||
Assert.eq(fock_calls[1].font, FONT_BYTES)
|
||||
end
|
||||
|
||||
do
|
||||
-- 未识别的 cES 明确报错,不能把密文当正文。
|
||||
replies = { { body = page(info({ fEnS = 0, cES = 1 })) } }
|
||||
fock_calls = {}
|
||||
local text, err
|
||||
Client.contentAsync("1", "2", function(v, e) text, err = v, e end)
|
||||
Assert.is_nil(text)
|
||||
Assert.is_true(err ~= nil and err:find("不受支持", 1, true) ~= nil)
|
||||
Assert.len(fock_calls, 0)
|
||||
end
|
||||
|
||||
do
|
||||
-- CDN 返回 HTML 错误页而不是字体:按下载失败处理。
|
||||
replies = {
|
||||
{ body = page(info({ fEnS = 1, cES = 2, fixedFontTtf = "https://font/fixed.ttf", randomFont = "{}", css = "" })) },
|
||||
{ body = "<html>403</html>" },
|
||||
}
|
||||
fock_calls = {}
|
||||
local text, err
|
||||
Client.contentAsync("1", "2", function(v, e) text, err = v, e end)
|
||||
Assert.is_nil(text)
|
||||
Assert.is_true(err ~= nil and err:find("字体下载失败", 1, true) ~= nil)
|
||||
Assert.len(fock_calls, 0)
|
||||
end
|
||||
|
||||
do
|
||||
-- cES=2 但没有字体地址:明确报错,不把错字当正文。
|
||||
replies = { { body = page(info({ fEnS = 1, cES = 2, randomFont = "{}", css = "" })) } }
|
||||
fock_calls = {}
|
||||
local text, err
|
||||
Client.contentAsync("1", "2", function(v, e) text, err = v, e end)
|
||||
Assert.is_nil(text)
|
||||
Assert.is_true(err ~= nil and err:find("字体", 1, true) ~= nil)
|
||||
Assert.len(fock_calls, 0)
|
||||
end
|
||||
@@ -0,0 +1,120 @@
|
||||
--[[--
|
||||
起点 VIP 章节解密(Fock 转译版)离线用例。
|
||||
|
||||
@module tests.source.qidian_fock_spec
|
||||
--]]
|
||||
---@diagnostic disable: undefined-field
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local Sample = require("support.qidian_fock_sample")
|
||||
local Fock = require("moonsource_qidian.fock")
|
||||
|
||||
local plain, err = Fock.decrypt(Sample.content, Sample.chapter_id, Sample.keypool, Sample.version, Sample.uid)
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(#plain, 13654)
|
||||
Assert.eq(plain:sub(1, 3), "<p>")
|
||||
Assert.matches(plain, "光王街")
|
||||
|
||||
-- 子进程任务:worker 结果经 on_done 交回
|
||||
local Job = require("workers.job")
|
||||
local real_run = Job.run
|
||||
Job.run = function(worker, opts) opts.on_done(worker(function() end)); return {} end
|
||||
local async_text
|
||||
Fock.decryptAsync(Sample.content, Sample.chapter_id, Sample.keypool, Sample.version, Sample.uid,
|
||||
function(text) async_text = text end)
|
||||
Job.run = real_run
|
||||
Assert.eq(async_text, plain)
|
||||
|
||||
-- 共用宿主 moonsource_qidian.yuewen_fock:decrypt 期间关 JIT、完事恢复原状;jobAsync 子进程抛错经 cb(nil, err) 交回
|
||||
do
|
||||
local Shared = require("moonsource_qidian.yuewen_fock")
|
||||
local Text = require("utils.text")
|
||||
local was_on = jit.status()
|
||||
local seen_off
|
||||
local decode = Text.base64Decode
|
||||
Text.base64Decode = function(...)
|
||||
seen_off = not jit.status()
|
||||
return decode(...)
|
||||
end
|
||||
|
||||
-- 字体路径由主进程持有:取消只清自己的文件,失败 / 成功也清理,退出前不抢删。
|
||||
do
|
||||
local Shared = require("moonsource_qidian.yuewen_fock")
|
||||
local lfs = require("libs/libkoreader-lfs")
|
||||
local pending = {}
|
||||
Job.run = function(worker, opts)
|
||||
local job = { poll = 0.5 }
|
||||
pending[#pending + 1] = { worker = worker, opts = opts, job = job }
|
||||
return job
|
||||
end
|
||||
local files = {}
|
||||
local function worker(paths)
|
||||
files[#files + 1] = paths
|
||||
for index, path in ipairs(paths) do
|
||||
local file = assert(io.open(path, "wb"))
|
||||
assert(file:write("font-" .. index))
|
||||
assert(file:close())
|
||||
end
|
||||
return { text = "restored" }
|
||||
end
|
||||
local text, err
|
||||
local function done(value, reason) text, err = value, reason end
|
||||
Shared.jobAsync("font_cancel", worker, done)
|
||||
Shared.jobAsync("font_failed", worker, done)
|
||||
pending[1].worker()
|
||||
pending[2].worker()
|
||||
pending[1].opts.on_cancelled(pending[1].job)
|
||||
Assert.is_nil(text)
|
||||
for _idx, path in ipairs(files[1]) do Assert.is_nil(lfs.attributes(path)) end
|
||||
for _idx, path in ipairs(files[2]) do Assert.eq(lfs.attributes(path, "mode"), "file") end
|
||||
pending[2].opts.on_failed("timeout")
|
||||
Assert.is_nil(text)
|
||||
Assert.eq(err, "timeout")
|
||||
for _idx, path in ipairs(files[2]) do Assert.is_nil(lfs.attributes(path)) end
|
||||
|
||||
Shared.jobAsync("font_done", worker, done)
|
||||
pending[3].opts.on_done(pending[3].worker())
|
||||
Assert.eq(text, "restored")
|
||||
Assert.is_nil(err)
|
||||
for _idx, path in ipairs(files[3]) do Assert.is_nil(lfs.attributes(path)) end
|
||||
|
||||
Shared.jobAsync("font_exiting", worker, done)
|
||||
pending[4].worker()
|
||||
pending[4].job.pid = 123
|
||||
local ffiUtil = require("ffi/util")
|
||||
local UIManager = require("ui/uimanager")
|
||||
local real_done, real_schedule = ffiUtil.isSubProcessDone, UIManager.scheduleIn
|
||||
local exited, tick = false, nil
|
||||
ffiUtil.isSubProcessDone = function() return exited end
|
||||
UIManager.scheduleIn = function(_self, _delay, fn) tick = fn end
|
||||
pending[4].opts.on_cancelled(pending[4].job)
|
||||
for _idx, path in ipairs(files[4]) do Assert.eq(lfs.attributes(path, "mode"), "file") end
|
||||
Assert.eq(type(tick), "function")
|
||||
exited = true
|
||||
tick()
|
||||
for _idx, path in ipairs(files[4]) do Assert.is_nil(lfs.attributes(path)) end
|
||||
ffiUtil.isSubProcessDone, UIManager.scheduleIn = real_done, real_schedule
|
||||
Job.run = real_run
|
||||
end
|
||||
local text = Fock.decrypt(Sample.content, Sample.chapter_id, Sample.keypool, Sample.version, Sample.uid)
|
||||
Text.base64Decode = decode
|
||||
Assert.eq(#text, 13654)
|
||||
Assert.is_true(seen_off, "解密期间 JIT 关着")
|
||||
Assert.eq(jit.status(), was_on, "解密完 JIT 开关恢复")
|
||||
|
||||
local Job = require("workers.job")
|
||||
local real_run = Job.run
|
||||
Job.run = function(worker, opts)
|
||||
local ok, res = pcall(worker)
|
||||
if ok then opts.on_done(res) else opts.on_failed(res) end
|
||||
return {}
|
||||
end
|
||||
local got_text, got_err
|
||||
Shared.jobAsync("t", function() return { text = "ok" } end, function(t, e) got_text, got_err = t, e end)
|
||||
Assert.eq(got_text, "ok")
|
||||
Assert.is_nil(got_err)
|
||||
Shared.jobAsync("t", function() error("boom", 0) end, function(t, e) got_text, got_err = t, e end)
|
||||
Assert.is_nil(got_text)
|
||||
Assert.eq(got_err, "boom")
|
||||
Job.run = real_run
|
||||
end
|
||||
@@ -0,0 +1,92 @@
|
||||
--[[--
|
||||
起点 cES=2 字体层:字段判定、诱饵副本裁剪、无字体时的兜底。
|
||||
|
||||
@module tests.source.qidian_font_spec
|
||||
--]]
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local FontRestore = require("moonsource_qidian.yuewen_fonts")
|
||||
local Mapper = require("moonsource_qidian.mapper")
|
||||
|
||||
-- Fock 与字体层是两个独立标记,不能再用 cES 非 0 一把抓。
|
||||
Assert.is_true(Mapper.fockEncrypted({ fEnS = "1" }))
|
||||
Assert.is_false(Mapper.fockEncrypted({ fEnS = "0", cES = "2" }))
|
||||
Assert.is_true(Mapper.fontProtected({ cES = "2" }))
|
||||
Assert.is_false(Mapper.fontProtected({ cES = "1" }))
|
||||
|
||||
-- 起点把同一章再追加一份同长度的诱饵副本;长度一一对应时丢掉后半。
|
||||
local duplicate = { "甲甲乙乙", "乙乙乙乙乙", "甲甲乙乙", "乙乙乙乙丁" }
|
||||
local trimmed = FontRestore.dropDecoyHalf(duplicate)
|
||||
Assert.eq(#trimmed, 2)
|
||||
Assert.eq(trimmed[1], "甲甲乙乙")
|
||||
Assert.eq(trimmed[2], "乙乙乙乙乙")
|
||||
|
||||
local uneven = { "甲甲", "乙乙乙", "丙丙", "丁丁" }
|
||||
Assert.eq(#FontRestore.dropDecoyHalf(uneven), 4)
|
||||
|
||||
local odd = { "甲甲", "乙乙乙", "丙丙" }
|
||||
Assert.eq(#FontRestore.dropDecoyHalf(odd), 3)
|
||||
|
||||
-- 没有 fixedFont 时不进入 FreeType;仍应按 CSS 解析段落并裁剪诱饵。
|
||||
local html = "<p> 甲甲</p><p> 乙乙乙</p><p> 甲甲</p><p> 乙乙乙</p>"
|
||||
local text = FontRestore.restore(html, { css = "", randomFont = { data = {} } }, nil, { dedupe = true })
|
||||
Assert.eq(text, " 甲甲\n 乙乙乙")
|
||||
|
||||
-- 于/干、责/贵 只修固定搭配;“干部/干活/干事/干劲”保留。
|
||||
Assert.eq(FontRestore.fixConfusions("关干《链法总纲》终干敲定了"),
|
||||
"关于《链法总纲》终于敲定了")
|
||||
Assert.eq(FontRestore.fixConfusions("对干宗门,对干部,在干活,等干事"),
|
||||
"对于宗门,对干部,在干活,等干事")
|
||||
Assert.eq(FontRestore.fixConfusions("职贵、担贵、负贵、贵任"),
|
||||
"职责、担责、负责、责任")
|
||||
Assert.eq(FontRestore.fixConfusions("同泮支援,泮随着,汇聚干此"),
|
||||
"同伴支援,伴随着,汇聚于此")
|
||||
|
||||
-- restore 内部也要能调用到 fixConfusions(不能是未赋值的全局)。
|
||||
local text2 = FontRestore.restore("<p>关干《链法总纲》</p>", { css = "", randomFont = { data = {} } }, nil,
|
||||
{ confusions = true })
|
||||
Assert.eq(text2, "关于《链法总纲》")
|
||||
|
||||
-- 前后半字数相同但内容不同的真实对称段落不能被当诱饵删掉。
|
||||
Assert.eq(#FontRestore.dropDecoyHalf({ "春风来", "夏雨至", "秋叶落", "冬雪飘" }), 4)
|
||||
|
||||
-- 常见搭配里的“干”不能被改成“于”。
|
||||
Assert.eq(FontRestore.fixConfusions("在干什么,对干净的"), "在干什么,对干净的")
|
||||
|
||||
-- 识别使用主进程交下来的两条路径,正常 / glyph 抛错都及时删除。
|
||||
do
|
||||
local Paths = require("utils.paths")
|
||||
local lfs = require("libs/libkoreader-lfs")
|
||||
local dir = Paths.tmpDir() .. "/font_restore_spec"
|
||||
assert(Paths.ensureDir(dir .. "/noto"))
|
||||
local ref = dir .. "/noto/NotoSansCJKsc-Regular.otf"
|
||||
local file = assert(io.open(ref, "wb"))
|
||||
assert(file:write("reference"))
|
||||
assert(file:close())
|
||||
local old_fontlist, old_glyph = package.loaded["fontlist"], package.loaded["utils.glyph"]
|
||||
package.loaded["fontlist"] = { fontdir = dir }
|
||||
local paths = { Paths.tmpname(".font"), Paths.tmpname(".font") }
|
||||
local fixed = "\0\1\0\0fixed"
|
||||
package.loaded["utils.glyph"] = {
|
||||
recognize = function(_ref, _cache, tasks)
|
||||
Assert.eq(tasks[1].font_path, paths[1])
|
||||
Assert.eq(tasks[2].font_path, paths[2])
|
||||
local font = assert(io.open(tasks[2].font_path, "rb"))
|
||||
Assert.eq(font:read("*a"), fixed)
|
||||
font:close()
|
||||
return { { [0x4909] = "乙" }, { [0x7532] = "丙" } }
|
||||
end,
|
||||
}
|
||||
local font = { css = "", randomFont = { data = { 0, 1, 0, 0 } } }
|
||||
Assert.eq(FontRestore.restore("<p>甲䤉</p>", font, fixed, { temp_paths = paths }), "丙乙")
|
||||
for _idx, path in ipairs(paths) do Assert.is_nil(lfs.attributes(path)) end
|
||||
package.loaded["utils.glyph"].recognize = function() error("glyph failed", 0) end
|
||||
Assert.errors(function()
|
||||
FontRestore.restore("<p>甲䤉</p>", font, fixed, { temp_paths = paths })
|
||||
end, "glyph failed")
|
||||
for _idx, path in ipairs(paths) do Assert.is_nil(lfs.attributes(path)) end
|
||||
package.loaded["fontlist"], package.loaded["utils.glyph"] = old_fontlist, old_glyph
|
||||
os.remove(ref)
|
||||
lfs.rmdir(dir .. "/noto")
|
||||
lfs.rmdir(dir)
|
||||
end
|
||||
@@ -0,0 +1,351 @@
|
||||
--[[--
|
||||
起点书架分页、目录 / 正文映射与 Cookie 解析离线用例。
|
||||
|
||||
@module tests.source.qidian_spec
|
||||
--]]
|
||||
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local JSONStub = require("support.json_stub")
|
||||
|
||||
package.preload["json"] = function()
|
||||
return { decode = JSONStub.decode, encode = JSONStub.encode }
|
||||
end
|
||||
|
||||
local cfg = {}
|
||||
package.preload["utils.settings"] = function()
|
||||
return { getSource = function() return cfg end }
|
||||
end
|
||||
|
||||
local expired
|
||||
package.preload["source.auth"] = function()
|
||||
return { expire = function(_, msg) expired = msg; return msg end, ok = function() end }
|
||||
end
|
||||
|
||||
local requests, replies = {}, {}
|
||||
package.preload["http.request"] = function()
|
||||
return {
|
||||
get = function(url, opts, cb)
|
||||
requests[#requests + 1] = { url = url, opts = opts }
|
||||
local reply = table.remove(replies, 1)
|
||||
cb(reply.body, reply.err, reply.res)
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
post = function(url, body, opts, cb)
|
||||
requests[#requests + 1] = { url = url, body = body, opts = opts }
|
||||
local reply = table.remove(replies, 1)
|
||||
cb(reply.body, reply.err, reply.res)
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
headerAll = function(res, key)
|
||||
if not res or not res.headers then return {} end
|
||||
local value = res.headers[key]
|
||||
return type(value) == "table" and value or (value and { value } or {})
|
||||
end,
|
||||
}
|
||||
end
|
||||
|
||||
package.loaded["moonsource_qidian.client"] = nil
|
||||
package.loaded["moonsource_qidian.mapper"] = nil
|
||||
package.loaded["moonsource_qidian.setting"] = nil
|
||||
local Client = require("moonsource_qidian.client")
|
||||
local Mapper = require("moonsource_qidian.mapper")
|
||||
local Setting = require("moonsource_qidian.setting")
|
||||
|
||||
local function page(data)
|
||||
return '<script id="vite-plugin-ssr_pageContext" type="application/json">'
|
||||
.. JSONStub.encode({ pageContext = { pageProps = { pageData = data } } }) .. "</script>"
|
||||
end
|
||||
|
||||
do
|
||||
local data = Mapper.pageData(page({ bookInfo = { bookId = 9 } }))
|
||||
Assert.eq(data.bookInfo.bookId, 9)
|
||||
Assert.is_nil(Mapper.pageData("<html>登录</html>"))
|
||||
end
|
||||
|
||||
do
|
||||
local book = Mapper.book({
|
||||
bookId = 101, bookName = "诡秘", authorName = "乌贼", chanName = "玄幻",
|
||||
wordsCnt = 100, desc = " 甲<br>乙",
|
||||
})
|
||||
Assert.eq(book.stable_id, "101")
|
||||
Assert.eq(book.cover, "https://bookcover.yuewen.com/qdbimg/349573/101/180")
|
||||
Assert.eq(book.meta.words, 100)
|
||||
Assert.eq(book.intro, " 甲\n乙")
|
||||
end
|
||||
|
||||
do
|
||||
local books = Mapper.shelfList({
|
||||
{ bid = 1, bName = "短", info = { bookId = 1, bookName = "全名", authorName = "甲", wordsCnt = 3 } },
|
||||
{ bid = 2, bName = "截断", local_book = { stable_id = "2", title = "本地", cover = "" } },
|
||||
{ bid = 3, bName = "兜底", bAuth = "乙" },
|
||||
})
|
||||
Assert.eq(books[1].title, "全名")
|
||||
Assert.eq(books[2].cover, "https://bookcover.yuewen.com/qdbimg/349573/2/180")
|
||||
Assert.eq(books[3].title, "兜底")
|
||||
Assert.eq(books[3].authors, "乙")
|
||||
end
|
||||
|
||||
-- 分类开关:关 = 题材;开 = 自定义分组(互斥,不混合)。
|
||||
do
|
||||
cfg.category_as_group = false
|
||||
local off = Mapper.shelfList({
|
||||
{ bid = 1, cateName = "玄幻", _group_name = "追更", info = { bookId = 1, bookName = "甲", chanName = "玄幻" } },
|
||||
{ bid = 2, cateName = "都市", info = { bookId = 2, bookName = "乙", chanName = "都市" } },
|
||||
})
|
||||
Assert.eq(off[1].category, "玄幻", "关:进组仍用题材")
|
||||
Assert.eq(off[2].category, "都市", "关:没进组用题材")
|
||||
cfg.category_as_group = true
|
||||
local on = Mapper.shelfList({
|
||||
{ bid = 1, cateName = "玄幻", _group_name = "追更", info = { bookId = 1, bookName = "甲", chanName = "玄幻" } },
|
||||
{ bid = 2, cateName = "都市", info = { bookId = 2, bookName = "乙", chanName = "都市" } },
|
||||
})
|
||||
Assert.eq(on[1].category, "追更", "开:进组用分组名")
|
||||
Assert.is_nil(on[2].category, "开:没进组不写题材")
|
||||
cfg.category_as_group = false
|
||||
end
|
||||
|
||||
do
|
||||
local toc = Mapper.toc({ vs = {
|
||||
{ vN = "卷一", cs = { { id = 11, cN = "第一章", cnt = 10, sS = 1, uT = "2022-10-07 10:22:55" } } },
|
||||
{ vN = "卷二", cs = { { id = 22, cN = "VIP", cnt = 20, sS = 0, uT = "bad" } } },
|
||||
} })
|
||||
Assert.len(toc, 2)
|
||||
Assert.eq(toc[1].uid, "11")
|
||||
Assert.eq(toc[1].updated, 1665109375)
|
||||
Assert.is_false(toc[1].vip)
|
||||
Assert.eq(toc[2].idx, 2)
|
||||
Assert.eq(toc[2].title, "VIP")
|
||||
Assert.is_nil(toc[2].updated)
|
||||
Assert.is_true(toc[2].vip)
|
||||
Assert.eq(Mapper.chapterTime("2022-10-07 10:22"), 1665109320)
|
||||
Assert.is_nil(Mapper.chapterTime("2022-10-07"))
|
||||
local read = Mapper.readChapter({ readCid = 730944635, readCname = "第一章" })
|
||||
Assert.eq(read.uid, "730944635")
|
||||
Assert.eq(read.title, "第一章")
|
||||
Assert.is_nil(Mapper.readChapter({ readCid = 0 }))
|
||||
Assert.is_nil(Mapper.readChapter({}))
|
||||
end
|
||||
|
||||
do
|
||||
Assert.eq(Mapper.chapterText("<p> 甲<p> 乙&丙"), "\n 甲\n 乙&丙")
|
||||
Assert.is_nil(Mapper.chapterText(""))
|
||||
Assert.is_false(Mapper.locked({ vipStatus = 0, isBuy = 0, content = "<p>甲" }))
|
||||
Assert.is_true(Mapper.locked({ vipStatus = 1, isBuy = 0 }))
|
||||
Assert.is_false(Mapper.locked({ vipStatus = 1, isBuy = 1 }))
|
||||
end
|
||||
|
||||
do
|
||||
Assert.eq(Setting.parseCookie("_csrfToken=t; ywkey=k; bad name=1"), "_csrfToken=t; ywkey=k")
|
||||
Assert.eq(Client.csrf("_csrfToken=t; ywkey=k"), "t")
|
||||
Assert.is_nil(Client.csrf("ywkey=k"))
|
||||
Assert.eq(Setting.browser.domain, "m.qidian.com")
|
||||
Assert.eq(Setting.browser.login:match("^https://([^/]+)"), Setting.browser.domain)
|
||||
Assert.eq(Setting.browser.check:match("^https://([^/]+)"), Setting.browser.domain)
|
||||
Assert.eq(Setting.fromPayload({ cookies = {
|
||||
{ domain = ".qidian.com", name = "_csrfToken", value = "t" },
|
||||
{ domain = "m.qidian.com", name = "ywkey", value = "k" },
|
||||
{ domain = "evil.com", name = "x", value = "y" },
|
||||
} }), "_csrfToken=t; ywkey=k")
|
||||
end
|
||||
|
||||
-- 默认分组翻完再拉其它分组,请求带 _csrfToken。
|
||||
do
|
||||
cfg.cookie = "ywkey=k; _csrfToken=tok"
|
||||
requests, replies = {}, {
|
||||
{ body = '{"code":0,"data":{"list":[{"bid":1,"bName":"甲"}],"groups":[{"groupId":-100,"bookCount":1},{"groupId":2,"bookCount":1}],"page":{"isLast":1}}}' },
|
||||
{ body = '{"code":0,"data":{"list":[{"bid":1,"bName":"甲"},{"bid":2,"bName":"乙"}],"page":{"isLast":1}}}' },
|
||||
}
|
||||
local rows, err
|
||||
Client.shelfAsync(cfg.cookie, function(v, e) rows, err = v, e end)
|
||||
Assert.is_nil(err)
|
||||
Assert.len(rows, 2)
|
||||
Assert.eq(rows[2].bid, 2)
|
||||
Assert.len(requests, 2)
|
||||
Assert.matches(requests[1].url, "gid=%-100")
|
||||
Assert.matches(requests[1].url, "_csrfToken=tok")
|
||||
Assert.matches(requests[2].url, "gid=2")
|
||||
end
|
||||
|
||||
-- 书架页 302:已保存的 Cookie 标失效。
|
||||
do
|
||||
expired = nil
|
||||
requests, replies = {}, { { body = nil, err = "HTTP 302", res = { code = 302 } } }
|
||||
local ok, err
|
||||
Client.loginCheckAsync(cfg.cookie, function(v, e) ok, err = v, e end)
|
||||
Assert.is_nil(ok)
|
||||
Assert.matches(err, "QQ阅读或起点 App 扫码")
|
||||
Assert.eq(expired, err)
|
||||
end
|
||||
|
||||
-- 扫码只有 ywguid/ywkey:书架页 Set-Cookie 合并成真 csrf 后再回传 account.cookie。
|
||||
do
|
||||
requests, replies = {}, {
|
||||
{
|
||||
body = page({ user = { isLogin = true, guid = 12345 } }),
|
||||
res = {
|
||||
code = 200,
|
||||
headers = {
|
||||
["Set-Cookie"] = {
|
||||
"_csrfToken=real-csrf; Path=/",
|
||||
"newstatisticUUID=uuid-1; Path=/",
|
||||
"fu=1; Path=/",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
local ok, err, account
|
||||
Client.loginCheckAsync("ywguid=12345; ywkey=site-key", function(v, e, a) ok, err, account = v, e, a end)
|
||||
Assert.is_true(ok)
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(account.id, "12345")
|
||||
Assert.matches(account.cookie, "_csrfToken=real%-csrf")
|
||||
Assert.matches(account.cookie, "ywguid=12345")
|
||||
Assert.matches(account.cookie, "ywkey=site%-key")
|
||||
Assert.matches(account.cookie, "newstatisticUUID=uuid%-1")
|
||||
end
|
||||
|
||||
-- 登录态在,但书架页没给 csrf:拒绝落盘,免得 VIP 正文一直空。
|
||||
do
|
||||
requests, replies = {}, {
|
||||
{ body = page({ user = { isLogin = true, guid = 9 } }), res = { code = 200, headers = {} } },
|
||||
}
|
||||
local ok, err, account
|
||||
Client.loginCheckAsync("ywguid=9; ywkey=k", function(v, e, a) ok, err, account = v, e, a end)
|
||||
Assert.is_nil(ok)
|
||||
Assert.matches(err, "缺少登录凭证")
|
||||
Assert.is_nil(account)
|
||||
end
|
||||
|
||||
-- 书架响应明确删除 csrf:不能保留旧值继续判成功、回传过期凭据。
|
||||
do
|
||||
requests, replies = {}, {
|
||||
{ body = page({ user = { isLogin = true, guid = 9 } }),
|
||||
res = { code = 200, headers = { ["Set-Cookie"] = "_csrfToken=; Max-Age=0; Path=/" } } },
|
||||
}
|
||||
local ok, err, account
|
||||
Client.loginCheckAsync("ywguid=9; ywkey=k; _csrfToken=old", function(v, e, a) ok, err, account = v, e, a end)
|
||||
Assert.is_nil(ok)
|
||||
Assert.matches(err, "缺少登录凭证")
|
||||
Assert.is_nil(account)
|
||||
end
|
||||
|
||||
-- 非 csrf Cookie 删除、覆盖仍保留可用登录态。
|
||||
do
|
||||
requests, replies = {}, {
|
||||
{ body = page({ user = { isLogin = true, guid = 9 } }),
|
||||
res = { code = 200, headers = { ["Set-Cookie"] = {
|
||||
"old=; Max-Age=0", "_csrfToken=new; Path=/",
|
||||
} } } },
|
||||
}
|
||||
local ok, account
|
||||
Client.loginCheckAsync("ywguid=9; ywkey=k; _csrfToken=old; old=gone", function(v, _err, a) ok, account = v, a end)
|
||||
Assert.is_true(ok)
|
||||
Assert.eq(account.cookie, "_csrfToken=new; ywguid=9; ywkey=k")
|
||||
end
|
||||
|
||||
-- 加入书架走 POST,书号在表单里。
|
||||
do
|
||||
requests, replies = {}, { { body = '{"code":0,"data":{"9":{"code":0,"message":"操作成功"}}}' } }
|
||||
local ok
|
||||
Client.addAsync("9", function(v) ok = v end)
|
||||
Assert.is_true(ok)
|
||||
Assert.matches(requests[1].url, "/webcommon/bookshelf/addbooks%?")
|
||||
Assert.eq(requests[1].body, "bookId=9")
|
||||
end
|
||||
|
||||
-- 进度上传带章节更新时间的 unix 秒。空时间不发请求,避免把阅读状态写坏。
|
||||
do
|
||||
local Stubs = require("support.stubs")
|
||||
cfg.cookie = "ywkey=k; _csrfToken=tok"
|
||||
requests, replies = {}, {}
|
||||
local ok, err
|
||||
Client.updateReadAsync("9", "11", "c1", false, "", function(v, e) ok, err = v, e end)
|
||||
Stubs.flush()
|
||||
Assert.is_nil(ok)
|
||||
Assert.eq(err, "起点章节时间缺失")
|
||||
Assert.len(requests, 0)
|
||||
|
||||
requests, replies = {}, { { body = '{"code":0}' } }
|
||||
Client.updateReadAsync("9", "11", "c1", true, 1665109375, function(v, e) ok, err = v, e end)
|
||||
Assert.is_true(ok)
|
||||
Assert.matches(requests[1].url, "/webcommon/chapter/updReadStatus%?")
|
||||
Assert.matches(requests[1].body, "chapterUpdateTime=1665109375")
|
||||
Assert.matches(requests[1].body, "isVip=1")
|
||||
Assert.matches(requests[1].body, "chapterId=11")
|
||||
|
||||
requests, replies, expired = {}, { { body = '{"code":1403,"msg":"登录失效"}' } }, nil
|
||||
Client.updateReadAsync("9", "11", "c1", 0, "1665109375", function(v, e) ok, err = v, e end)
|
||||
Assert.is_nil(ok)
|
||||
Assert.matches(err, "QQ阅读或起点 App 扫码")
|
||||
Assert.eq(expired, err)
|
||||
end
|
||||
|
||||
do
|
||||
requests, replies = {}, { { body = page({ records = { { bid = 7, bName = "甲", bAuth = "乙", cat = "玄幻" } } }) } }
|
||||
local got
|
||||
Client.rankAsync("/rank/yuepiao/catid21/", function(v) got = v end)
|
||||
Assert.matches(requests[1].url, "/rank/yuepiao/catid21/$")
|
||||
local books = Mapper.rank(got)
|
||||
Assert.eq(books[1].stable_id, "7")
|
||||
Assert.eq(books[1].authors, "乙")
|
||||
|
||||
replies = { { body = "<html>nope</html>" } }
|
||||
local err
|
||||
Client.rankAsync("/rank/x/", function(v, e) got, err = v, e end)
|
||||
Assert.is_nil(got)
|
||||
Assert.is_true(err ~= nil)
|
||||
end
|
||||
|
||||
do
|
||||
local books = Mapper.search({ bookInfo = { records = {
|
||||
{ bid = 7, bName = "甲", bAuth = "乙...", cat = "玄幻", desc = "简<br>介" },
|
||||
{ bid = 8, bName = "丙", bAuth = "丁" },
|
||||
} } })
|
||||
Assert.len(books, 2)
|
||||
Assert.eq(books[1].stable_id, "7")
|
||||
Assert.is_nil(books[1].authors)
|
||||
Assert.eq(books[1].intro, "简\n介")
|
||||
Assert.eq(books[2].authors, "丁")
|
||||
|
||||
requests, replies = {}, { { body = JSONStub.encode({ code = 0, data = { bookInfo = { records = {} } } }) } }
|
||||
local got
|
||||
Client.searchAsync("斗罗", function(v) got = v end)
|
||||
Assert.matches(requests[1].url, "/webcommon/search/list%?")
|
||||
Assert.matches(requests[1].url, "kw=%%E6%%96%%97%%E7%%BD%%97")
|
||||
Assert.is_true(got.bookInfo ~= nil)
|
||||
end
|
||||
|
||||
do
|
||||
requests, replies = {}, { { body = JSONStub.encode({ code = 0, data = { records = {}, isLast = 0 } }) } }
|
||||
local got
|
||||
Client.rankPageAsync("readindex", "21", 2, function(data) got = data end)
|
||||
Assert.matches(requests[1].url, "/webcommon/rank/readIndexlist%?")
|
||||
Assert.matches(requests[1].url, "pageNum=2")
|
||||
Assert.matches(requests[1].url, "catId=21")
|
||||
Assert.matches(requests[1].url, "gender=male")
|
||||
Assert.is_false((requests[1].opts.headers.Cookie or ""):find("ywguid", 1, true) ~= nil)
|
||||
Assert.len(got.records, 0)
|
||||
|
||||
replies = { { body = JSONStub.encode({ code = 0, data = {} }) } }
|
||||
local err
|
||||
Client.rankPageAsync("yuepiao", "-1", 1, function(data, reason) got, err = data, reason end)
|
||||
Assert.is_nil(got)
|
||||
Assert.eq(err, "起点榜单响应无效")
|
||||
end
|
||||
|
||||
do
|
||||
requests, replies = {}, { { body = page({ bookCirclePost = {
|
||||
bookCirclePostCount = 8, bookCirclePostList = {},
|
||||
} }) } }
|
||||
local got, err
|
||||
Client.bookCircleAsync("7", function(data, reason) got, err = data, reason end)
|
||||
Assert.matches(requests[1].url, "/readersCircle/7/$")
|
||||
Assert.is_true(requests[1].opts.headers.Cookie == nil, "公共整书讨论不发送账号 Cookie")
|
||||
Assert.eq(got.bookCirclePostCount, 8)
|
||||
replies = { { body = page({}) } }
|
||||
Client.bookCircleAsync("7", function(data, reason) got, err = data, reason end)
|
||||
Assert.is_nil(got)
|
||||
Assert.eq(err, "起点书友圈响应无效")
|
||||
end
|
||||
@@ -0,0 +1,35 @@
|
||||
--[[-- 起点旧榜单节点的聚合分页与失败。 @module tests.moonsource_qidian.rank_spec --]]
|
||||
local Assert = require("support.assert")
|
||||
local pages, fail = {}, false
|
||||
package.preload["moonsource_qidian.client"] = function()
|
||||
return {
|
||||
rankPageAsync = function(key, cat, page, cb)
|
||||
pages[#pages + 1] = { key = key, cat = cat, page = page }
|
||||
if fail and page == 2 then cb(nil, "offline")
|
||||
else
|
||||
local rows = {}
|
||||
for i = 1, 20 do rows[i] = { bid = (page - 1) * 20 + i, bName = "测试" .. i } end
|
||||
cb({ records = rows, isLast = 0 })
|
||||
end
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
end
|
||||
local source = require("moonsource_qidian.source").new()
|
||||
local result, err
|
||||
source:browseAsync({ node = "yuepiao:-1", limit = 60 }, function(value, reason) result, err = value, reason end)
|
||||
Assert.is_nil(err)
|
||||
Assert.len(result.data, 60)
|
||||
Assert.eq(result.data[60].stable_id, "60")
|
||||
Assert.len(pages, 3)
|
||||
Assert.eq(pages[3].page, 3)
|
||||
Assert.eq(pages[1].cat, "-1")
|
||||
Assert.eq(result.groups[1].chips[1].title, "分类书库")
|
||||
|
||||
fail, pages = true, {}
|
||||
source:browseAsync({ node = "readindex:21", limit = 60 }, function(value, reason) result, err = value, reason end)
|
||||
Assert.is_nil(result, "后续页失败不能把榜单第一页报成完整结果")
|
||||
Assert.eq(err, "offline")
|
||||
Assert.len(pages, 2)
|
||||
Assert.eq(pages[1].key, "readindex")
|
||||
Assert.eq(pages[1].cat, "21")
|
||||
@@ -0,0 +1,129 @@
|
||||
--[[--
|
||||
起点段评:统计 → 热点、评论页 → 展示项(页码翻页)、段落按段序定位到章节 HTML。
|
||||
|
||||
@module tests.moonsource_qidian.reviews_spec
|
||||
--]]
|
||||
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
|
||||
|
||||
local Assert = require("support.assert")
|
||||
|
||||
local asked
|
||||
package.preload["moonsource_qidian.client"] = function()
|
||||
return {
|
||||
reviewSummaryAsync = function(book, chapter, cb)
|
||||
asked = { book = book, chapter = chapter }
|
||||
cb({ enableReview = package.enabled and 1 or 0, list = {
|
||||
{ paragraphId = -1, textCount = 99 },
|
||||
{ paragraphId = 3, textCount = 7 },
|
||||
{ paragraphId = 1, textCount = 4942 },
|
||||
{ paragraphId = 2, textCount = 0 },
|
||||
} })
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
reviewListAsync = function(book, chapter, pid, page, cb)
|
||||
asked = { book = book, chapter = chapter, pid = pid, page = page }
|
||||
cb({ total = 25, list = { { reviewId = "9", nickName = "甲", content = "好[fn=47]看", likeCount = 6,
|
||||
createTimestamp = 1725596312, hasImage = 1, imagePre = "https://x/y.jpg", status = 1 } } })
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
end
|
||||
package.loaded["moonsource_qidian.reviews"] = nil
|
||||
local Reviews = require("moonsource_qidian.reviews")
|
||||
|
||||
-- 统计:保留章末总评,0 评论不标,按段序排;没开段评的书当没有
|
||||
do
|
||||
package.enabled = true
|
||||
local hot
|
||||
Reviews.hotspotsAsync("1", "2", function(list) hot = list end)
|
||||
Assert.eq(asked.chapter, "2")
|
||||
Assert.len(hot, 3)
|
||||
Assert.eq(hot[1].range, "-1")
|
||||
Assert.eq(hot[2].range, "1")
|
||||
Assert.eq(hot[3].range, "3")
|
||||
Assert.eq(hot[3].total, 7)
|
||||
|
||||
package.enabled = false
|
||||
Reviews.hotspotsAsync("1", "2", function(list) hot = list end)
|
||||
Assert.len(hot, 0)
|
||||
end
|
||||
|
||||
-- 评论页:max_idx 是已取页数,请求页码 = max_idx + 1;表情码去掉;配图带上
|
||||
do
|
||||
local page
|
||||
Reviews.pageAsync("1", "2", 3, 0, function(p) page = p end)
|
||||
Assert.eq(asked.page, 1)
|
||||
Assert.eq(asked.pid, 3)
|
||||
Assert.eq(page.max_idx, 1)
|
||||
Assert.eq(page.total, 25)
|
||||
Assert.is_true(page.more)
|
||||
Assert.eq(page.items[1].content, "好看")
|
||||
Assert.eq(page.items[1].author, "甲")
|
||||
Assert.eq(page.items[1].time, 1725596312)
|
||||
Assert.eq(page.items[1].images[1].url, "https://x/y.jpg")
|
||||
|
||||
Assert.is_false(Reviews.page({ total = 1, list = { { reviewId = "1", content = "a" } } }, 1).more)
|
||||
Assert.is_false(Reviews.page({ total = 5, list = {} }, 2).more)
|
||||
Assert.is_nil((Reviews.page({}, 1)))
|
||||
Assert.is_false(Reviews.page({ total = 25, isEnd = 1, list = { { reviewId = "1" } } }, 2).more)
|
||||
Assert.is_true(Reviews.page({ total = 25, isEnd = 0, list = { { reviewId = "1" } } }, 3).more,
|
||||
"不等长的页不能用页码乘本页条数猜末页")
|
||||
local primary = Reviews.item({ content = "原评", rootReviewReplyCount = 65,
|
||||
replyList = {
|
||||
{ reviewId = "r1", nickName = "乙", content = "回复[fn=3]", createTime = "1725596312000",
|
||||
quoteNickName = "丙", rootReviewReplyCount = 4,
|
||||
replyList = { { content = "不递归生成三级列表" } } },
|
||||
{ reviewId = "r2", nickName = "丁", content = "另一条", likeCount = 2 },
|
||||
} })
|
||||
Assert.eq(primary.content, "原评", "不能把内嵌的两条回复预览拼进主评论")
|
||||
Assert.eq(primary.replies, 65)
|
||||
Assert.len(primary.reply_preview, 2)
|
||||
Assert.eq(primary.reply_preview[1].id, "r1")
|
||||
Assert.eq(primary.reply_preview[1].content, "回复")
|
||||
Assert.eq(primary.reply_preview[1].author, "乙")
|
||||
Assert.eq(primary.reply_preview[1].reply_to, "丙")
|
||||
Assert.eq(primary.reply_preview[1].time, 1725596312)
|
||||
Assert.is_nil(primary.reply_preview[1].reply_preview, "二级预览不继续生成三级列表")
|
||||
Assert.eq(primary.reply_preview[2].likes, 2)
|
||||
Assert.is_nil(Reviews.item({ rootReviewReplyCount = 65, replyList = {} }).reply_preview)
|
||||
Assert.is_nil(Reviews.item({ rootReviewReplyCount = 65 }).reply_preview)
|
||||
Assert.eq(Reviews.item({ replyList = { { content = "已有回复" } } }).replies, 1,
|
||||
"未给总数时至少显示实际预览数")
|
||||
end
|
||||
|
||||
-- 定位:第 n 个非空 <p> 即 paragraphId = n,xpointer 覆盖整段
|
||||
do
|
||||
local html = '<h1>标题</h1><p>开头一段话。</p>\n<p>第二段里有一句被很多人评论的话。</p>'
|
||||
local spots = Reviews.locate({
|
||||
{ range = "2", text = "", total = 4 },
|
||||
{ range = "9", text = "", total = 1 },
|
||||
}, html)
|
||||
Assert.len(spots, 1)
|
||||
Assert.eq(spots[1].range, "2")
|
||||
Assert.eq(spots[1].badge, "4")
|
||||
Assert.eq(spots[1].text, "第二段里有一句被很多人评论的话。")
|
||||
end
|
||||
|
||||
do
|
||||
local page, err = Reviews.bookPage({
|
||||
bookCirclePostCount = 9, bookCirclePostList = {
|
||||
{ title = "帖子标题", circleReviewDesc = "<p>正文 & 预览</p>", userName = "测试作者" },
|
||||
},
|
||||
})
|
||||
Assert.is_nil(err)
|
||||
Assert.len(page.items, 1)
|
||||
Assert.eq(page.items[1].text, "帖子标题\n正文 & 预览")
|
||||
Assert.eq(page.items[1].author, "测试作者")
|
||||
Assert.eq(page.total, 9)
|
||||
Assert.eq(page.title, "书友圈预览(1/9)")
|
||||
Assert.is_nil(page.pages, "不捏造官网未提供的整书帖子分页")
|
||||
page, err = Reviews.bookPage({ bookCirclePostCount = 0, bookCirclePostList = {} })
|
||||
Assert.is_nil(err)
|
||||
Assert.len(page.items, 0)
|
||||
page, err = Reviews.bookPage({ bookCirclePostCount = 9,
|
||||
bookCirclePostList = { { title = "坏帖" } } })
|
||||
Assert.is_nil(page)
|
||||
Assert.eq(err, "起点书友圈响应无效")
|
||||
end
|
||||
|
||||
return true
|
||||
@@ -0,0 +1,95 @@
|
||||
--[[-- 起点账号:续期不动同步标记;换号保留记录,不询问、不查询旧账号。 @module tests.moonsource_qidian.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 Auth = require("source.auth")
|
||||
local beginLogin = Auth.beginLogin
|
||||
local cfg, checks, cleared, closed = {}, 0, 0, 0
|
||||
local clear_ok, delayed, late = true, false, nil
|
||||
package.preload["utils.settings"] = function()
|
||||
return { getSource = function() return cfg end, saveSource = function() end }
|
||||
end
|
||||
package.preload["moonsource_qidian.client"] = function()
|
||||
return {
|
||||
cookie = function() return cfg.cookie end,
|
||||
loginCheckAsync = function(cookie, cb)
|
||||
checks = checks + 1
|
||||
Assert.is_true(cookie ~= "old", "换号不能查询旧凭据")
|
||||
local function done()
|
||||
cb(cookie ~= "bad", cookie == "bad" and "expired" or nil,
|
||||
{ id = cookie == "same" and "111" or "222" })
|
||||
end
|
||||
if delayed then late = done else done() end
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
end
|
||||
package.loaded["source.auth"] = nil
|
||||
package.preload["source.auth"] = function()
|
||||
return { beginLogin = beginLogin, changeAccount = Auth.changeAccount,
|
||||
ok = function() end, expired = function() return false 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["book.books_db"] = function()
|
||||
return { prepareAccountSync = function(id, shelf_add)
|
||||
Assert.eq(id, "ext.qidian", "只准备当前源")
|
||||
Assert.is_true(shelf_add)
|
||||
Assert.not_nil(cfg.cookie, "成功准备同步之后才替换凭据")
|
||||
cleared = cleared + 1
|
||||
return clear_ok
|
||||
end }
|
||||
end
|
||||
package.preload["reader.session"] = function()
|
||||
return { current = function() return {
|
||||
identity = { source_id = "ext.qidian" }, ui = { onClose = function() closed = closed + 1 end },
|
||||
} end }
|
||||
end
|
||||
local CookieLogin = require("source.cookie_login")
|
||||
CookieLogin.fromPayload = function(payload) return payload.cookie end
|
||||
local Setting = require("moonsource_qidian.setting")
|
||||
local function apply(cookie)
|
||||
local ok, err
|
||||
local job = Setting.browser.apply({ cookie = cookie }, function(value, reason) ok, err = value, reason end)
|
||||
return ok, err, job
|
||||
end
|
||||
|
||||
cfg = { cookie = "old", account_id = "111" }
|
||||
Assert.is_true(apply("same"))
|
||||
Assert.eq(cleared, 0, "同账号续期保留本地")
|
||||
cfg = { cookie = "old", account_id = "111" }
|
||||
Assert.is_true(apply("new"))
|
||||
Assert.eq(cfg.cookie, "new")
|
||||
Assert.eq(cfg.account_id, "222")
|
||||
Assert.eq(cleared, 1)
|
||||
Assert.eq(closed, 1)
|
||||
Assert.is_nil(Theme.last("confirm"), "换号不弹确认")
|
||||
cfg = { cookie = "old" }
|
||||
local before = checks
|
||||
Assert.is_true(apply("same"))
|
||||
Assert.eq(checks, before + 1, "旧配置缺身份时不多查一次")
|
||||
Assert.eq(cleared, 2)
|
||||
cfg = { cookie = "new", account_id = "111" }
|
||||
Assert.is_true(apply("new"))
|
||||
Assert.eq(cleared, 3, "账号身份变了,即使 Cookie 字符串相同也准备同步")
|
||||
cfg, clear_ok = { cookie = "old", account_id = "111" }, false
|
||||
local ok, err = apply("new")
|
||||
Assert.is_false(ok)
|
||||
Assert.eq(err, "准备本地同步失败")
|
||||
Assert.eq(cfg.cookie, "old", "准备失败仍保留旧凭据")
|
||||
clear_ok = true
|
||||
cfg = { cookie = "old", account_id = "111" }
|
||||
ok, err = apply("bad")
|
||||
Assert.is_false(ok)
|
||||
Assert.eq(err, "expired")
|
||||
Assert.eq(cfg.cookie, "old", "无效新凭据不清旧账号")
|
||||
delayed = true
|
||||
local called = false
|
||||
local job = Setting.browser.apply({ cookie = "same" }, function() called = true end)
|
||||
job.cancel()
|
||||
late()
|
||||
Assert.is_false(called, "取消后的校验回包不提交")
|
||||
Assert.eq(cfg.cookie, "old")
|
||||
@@ -0,0 +1,96 @@
|
||||
--[[--
|
||||
起点书架分组:拉书架时记住自定义分组(默认分组 -100 不算,一本书多个组取第一个),
|
||||
开「分组代替分类」时进组书的分类用分组名、没进组不写分类;移出分组后本地旧行也要落回题材。
|
||||
|
||||
@module tests.moonsource_qidian.shelf_spec
|
||||
--]]
|
||||
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
|
||||
|
||||
local Assert = require("support.assert")
|
||||
|
||||
package.loaded["json"] = nil
|
||||
package.preload["json"] = function()
|
||||
local stub = require("support.json_stub")
|
||||
return { decode = stub.decode, encode = stub.encode }
|
||||
end
|
||||
package.preload["moonsource_qidian.fock"] = function() return {} end
|
||||
|
||||
local PAGES = {
|
||||
["-100"] = '{"code":0,"data":{"count":3,"page":{"isLast":1},'
|
||||
.. '"groups":[{"groupId":-100,"groupName":"默认分组","bookCount":3},'
|
||||
.. '{"groupId":7,"groupName":"追更","bookCount":2}],'
|
||||
.. '"list":[{"bid":1,"bName":"甲","cateName":"玄幻"},{"bid":2,"bName":"乙","cateName":"都市"}]}}',
|
||||
["7"] = '{"code":0,"data":{"count":2,"page":{"isLast":1},'
|
||||
.. '"groups":[{"groupId":7,"groupName":"追更","bookCount":2}],'
|
||||
.. '"list":[{"bid":2,"bName":"乙","cateName":"都市"},{"bid":3,"bName":"丙","cateName":"科幻"}]}}',
|
||||
}
|
||||
package.loaded["http.request"] = nil
|
||||
package.preload["http.request"] = function()
|
||||
return {
|
||||
get = function(url, _opts, cb)
|
||||
local gid = url:match("gid=([^&]+)")
|
||||
cb(PAGES[gid] or PAGES["-100"])
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
end
|
||||
local cfg = { category_as_group = true }
|
||||
package.loaded["utils.settings"] = nil
|
||||
package.preload["utils.settings"] = function()
|
||||
return { getSource = function() return cfg end }
|
||||
end
|
||||
package.loaded["moonsource_qidian.client"] = nil
|
||||
package.loaded["moonsource_qidian.mapper"] = nil
|
||||
local Client = require("moonsource_qidian.client")
|
||||
local Mapper = require("moonsource_qidian.mapper")
|
||||
|
||||
do -- 逐组拉取后按 bookId 记组:乙在默认组先出现,进了「追更」仍要记上
|
||||
local rows
|
||||
Client.shelfAsync("_csrfToken=tok; other=1", function(r, err)
|
||||
rows = r
|
||||
Assert.is_nil(err)
|
||||
end)
|
||||
Assert.len(rows, 3)
|
||||
Assert.is_nil(rows[1]._group_name, "只在默认组的书不算分组")
|
||||
Assert.eq(rows[2]._group_name, "追更")
|
||||
Assert.eq(rows[3]._group_name, "追更")
|
||||
|
||||
local books = Mapper.shelfList(rows)
|
||||
Assert.is_nil(books[1].category, "开:没进组不写题材")
|
||||
Assert.eq(books[2].category, "追更")
|
||||
Assert.eq(books[3].category, "追更")
|
||||
end
|
||||
|
||||
do -- 移出分组:本地旧行分类是旧分组名,书架行题材要把它刷新回来
|
||||
local books = Mapper.shelfList({
|
||||
{ bid = 9, bName = "丁", cateName = "历史",
|
||||
local_book = { stable_id = "9", title = "丁", category = "追更", cover = "c" } },
|
||||
{ bid = 10, bName = "戊", cateName = "游戏", _group_name = "在读",
|
||||
local_book = { stable_id = "10", title = "戊", category = "历史", cover = "c" } },
|
||||
})
|
||||
Assert.is_nil(books[1].category, "开:移出分组后不再沿用旧分组名")
|
||||
Assert.is_true(books[1].category_authoritative, "移出分组要能清掉库里的旧分类")
|
||||
Assert.eq(books[2].category, "在读", "进了组用分组名覆盖本地旧分类")
|
||||
end
|
||||
|
||||
do -- 分页没有页数上限:超过 50 页照样翻到末页
|
||||
local n = 0
|
||||
local list = {}
|
||||
for i = 1, 20 do list[#list + 1] = ('{"bid":%d,"bName":"书","cateName":"玄幻"}'):format(i) end
|
||||
package.loaded["http.request"] = nil
|
||||
package.preload["http.request"] = function()
|
||||
return { get = function(_url, _opts, cb)
|
||||
n = n + 1
|
||||
cb('{"code":0,"data":{"count":9999,"page":{"isLast":' .. (n > 60 and "1" or "0")
|
||||
.. '},"groups":[],"list":[' .. table.concat(list, ",") .. "]}}")
|
||||
return { cancel = function() end }
|
||||
end }
|
||||
end
|
||||
package.loaded["moonsource_qidian.client"] = nil
|
||||
local Deep = require("moonsource_qidian.client")
|
||||
local rows, err
|
||||
Deep.shelfAsync("_csrfToken=tok", function(r, e) rows, err = r, e end)
|
||||
Assert.is_nil(err)
|
||||
Assert.len(rows, 20)
|
||||
Assert.eq(n, 61)
|
||||
end
|
||||
@@ -0,0 +1,69 @@
|
||||
--[[-- 起点验证码桥:仅 proof、时效、取消和候选会话存活。 @module tests.moonsource_qidian.verify_spec --]]
|
||||
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local Ext = require("utils.extension")
|
||||
local seq, interrupted = 0, 0
|
||||
package.preload["utils.random"] = function() return { hex = function() seq = seq + 1; return "ticket" .. seq end } end
|
||||
package.preload["ui/uimanager"] = function() return { scheduleIn = function() end, unschedule = function() end } end
|
||||
package.preload["ui.guard"] = function() return { wrap = function(_label, fn) return fn end } end
|
||||
Ext.add("web.open_page", function(path, _title, _text, opts)
|
||||
Assert.matches(path, "^/qidian_verify%.html#ticket")
|
||||
return { close = function() opts.close_callback() end }
|
||||
end)
|
||||
local Verification = require("moonsource_qidian.verify")
|
||||
local route
|
||||
for _idx, item in ipairs(Ext.list("web.routes")) do if item.name == "qidian_verify" then route = item end end
|
||||
local session = {
|
||||
interrupt = function() interrupted = interrupted + 1 end,
|
||||
imageAsync = function(_self, _url, cb) cb("data:image/png;base64,example") end,
|
||||
}
|
||||
local challenge = { nextAction = 11, imgSrc = "https://turing.captcha.qcloud.com/TCaptcha.js?aid=1600000770" }
|
||||
local submitted, finished, late = nil, false, nil
|
||||
local verification = Verification.new(session, challenge, function(proof, cb)
|
||||
submitted, late = proof, cb
|
||||
end, function(data) finished = data ~= nil end)
|
||||
local function request(action, fields, method)
|
||||
fields = fields or {}
|
||||
fields.ticket = fields.ticket or verification.ticket
|
||||
local status, data, headers
|
||||
route.handle(method or "POST", action, fields, function(code, body, extra) status, data, headers = code, body, extra end)
|
||||
return status, data, headers
|
||||
end
|
||||
|
||||
Assert.eq((request("config", nil, "GET")), 405)
|
||||
local status, data, headers = request("config")
|
||||
Assert.eq(status, 200)
|
||||
Assert.eq(data.appid, "1600000770")
|
||||
Assert.eq(headers[1], "Cache-Control: no-store")
|
||||
Assert.is_nil(data.phone)
|
||||
Assert.is_nil(data.cookie)
|
||||
Assert.eq((request("verify", { captcha_ticket = "trerror_invalid", randstr = "random" })), 400)
|
||||
Assert.is_nil(submitted)
|
||||
request("verify", { captcha_ticket = "proof", randstr = "random" })
|
||||
Assert.eq(submitted, "random;proof", "顺序与官方 randstr + 分号 + ticket 一致")
|
||||
Assert.eq((request("verify", { captcha_ticket = "proof", randstr = "random" })), 409)
|
||||
late({ nextAction = 0 })
|
||||
Assert.is_true(finished)
|
||||
Assert.eq(interrupted, 0, "成功后候选会话必须继续用于短信提交")
|
||||
Assert.eq((request("config")), 403, "验证票据用完即撤销")
|
||||
|
||||
verification = Verification.new(session, challenge, function(_proof, cb) late = cb end, function() end)
|
||||
request("verify", { captcha_ticket = "proof", randstr = "random" })
|
||||
verification:cancel()
|
||||
late({ nextAction = 0 })
|
||||
Assert.eq(interrupted, 1)
|
||||
Assert.eq((request("config")), 403)
|
||||
|
||||
verification = Verification.new(session, { nextAction = 8, imgSrc = "/image" },
|
||||
function(proof, cb) Assert.eq(proof, "abcd"); cb({ nextAction = 0 }) end, function() end)
|
||||
status, data = request("config")
|
||||
Assert.eq(status, 200)
|
||||
Assert.eq(data.mode, "image")
|
||||
Assert.matches(data.image, "^data:image/png;")
|
||||
Assert.eq((request("verify", { code = "abcd" })), 200)
|
||||
|
||||
verification = Verification.new(session, challenge, function() end, function() end)
|
||||
verification.expires = os.time() - 1
|
||||
Assert.eq((request("verify", { captcha_ticket = "proof", randstr = "random" })), 403)
|
||||
verification:cancel()
|
||||
@@ -0,0 +1,69 @@
|
||||
'use strict';
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const vm = require('node:vm');
|
||||
const source = fs.readFileSync(process.argv[2] + '/moonsource-qidian.koplugin/moonsource_qidian/web/qidian_verify.js', 'utf8');
|
||||
|
||||
async function page(options = {}) {
|
||||
const nodes = Object.fromEntries(['title', 'instruction', 'status', 'retry', 'captcha', 'image-form', 'image', 'code', 'submit']
|
||||
.map(id => [id, { textContent: '', hidden: false, value: '' }]));
|
||||
const requests = [];
|
||||
let callback;
|
||||
const messages = { mode: options.image ? 'image' : 'tencent', image: 'data:image/png;base64,fixture',
|
||||
appid: '1600000770', title: 'Qidian', instruction: 'Verify', pending: 'Pending',
|
||||
success: 'Done', failure: 'Failed', retry: 'Refresh', submit: 'Submit' };
|
||||
const context = {
|
||||
AbortController, setTimeout, clearTimeout, location: { hash: '#fixture' }, window: {},
|
||||
document: {
|
||||
get cookie() { throw new Error('Must not read browser credentials'); },
|
||||
getElementById: id => nodes[id],
|
||||
createElement: () => ({ remove() {} }),
|
||||
head: { appendChild(script) {
|
||||
context.window.TencentCaptcha = function(element, appid, cb, opts) {
|
||||
assert.equal(element, nodes.captcha);
|
||||
assert.equal(appid, '1600000770');
|
||||
assert.equal(opts.type, 'embed');
|
||||
callback = cb;
|
||||
this.destroy = this.show = () => {};
|
||||
if (options.auto) cb({ ret: 0, ticket: 'proof', randstr: 'random' });
|
||||
};
|
||||
script.onload();
|
||||
} },
|
||||
},
|
||||
fetch: async (url, opts) => {
|
||||
requests.push({ url, body: JSON.parse(opts.body) });
|
||||
const config = !url.endsWith('/verify');
|
||||
return { ok: config || !options.rejected, json: async () =>
|
||||
config ? messages : options.rejected ? { error: 'Rejected' } : { ok: true } };
|
||||
},
|
||||
};
|
||||
await vm.runInNewContext(source, context);
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
return { nodes, requests, get callback() { return callback; } };
|
||||
}
|
||||
|
||||
(async () => {
|
||||
let p = await page();
|
||||
await p.callback({ ret: 2 });
|
||||
await p.callback({ ret: 0, ticket: 'trerror_fixture', randstr: 'random' });
|
||||
await p.callback({ ret: 0, ticket: 'proof', randstr: 'random', errorCode: 1 });
|
||||
assert.equal(p.requests.length, 1, 'Invalid challenges never submit proof');
|
||||
await p.callback({ ret: 0, ticket: 'proof', randstr: 'random' });
|
||||
assert.deepEqual(p.requests[1].body, { ticket: 'fixture', captcha_ticket: 'proof', randstr: 'random' });
|
||||
assert.equal(p.nodes.status.textContent, 'Done');
|
||||
await p.callback({ ret: 0, ticket: 'late', randstr: 'random' });
|
||||
assert.equal(p.requests.length, 2, 'Completed proof cannot be replayed');
|
||||
p = await page({ auto: true });
|
||||
assert.equal(p.requests.length, 2, 'Synchronous SDK completion is not lost while loading');
|
||||
p = await page({ rejected: true });
|
||||
await p.callback({ ret: 0, ticket: 'proof', randstr: 'random' });
|
||||
assert.equal(p.nodes.status.textContent, 'Rejected');
|
||||
await p.nodes.retry.onclick();
|
||||
assert.equal(p.requests[2].url, '/api/qidian_verify/refresh');
|
||||
p = await page({ image: true });
|
||||
assert.equal(p.nodes.image.src, 'data:image/png;base64,fixture');
|
||||
p.nodes.code.value = 'abcd';
|
||||
await p.nodes['image-form'].onsubmit({ preventDefault() {} });
|
||||
assert.deepEqual(p.requests[1].body, { ticket: 'fixture', code: 'abcd' });
|
||||
console.log('qidian web: OK');
|
||||
})().catch(error => { console.error(error); process.exitCode = 1; });
|
||||
@@ -0,0 +1,8 @@
|
||||
--[[-- 起点验证码网页回归,使用已有 Node。 @module tests.moonsource_qidian.web_spec --]]
|
||||
local Assert = require("support.assert")
|
||||
local here = debug.getinfo(1, "S").source:match("^@(.+)/[^/]+$") or "."
|
||||
local root = here .. "/../.."
|
||||
local pipe = assert(io.popen('node "' .. here .. '/web_spec.js" "' .. root .. '" 2>&1'))
|
||||
local output = pipe:read("*a")
|
||||
pipe:close()
|
||||
Assert.is_true(output:find("qidian web: OK", 1, true) ~= nil, output)
|
||||
@@ -0,0 +1,102 @@
|
||||
--[[--
|
||||
阅文三源的设备扫码入口:各用自己的应用参数,先校验再保存。
|
||||
起点真 csrf 由 loginCheck 合并书架 Set-Cookie,扫码回调不再造假。
|
||||
|
||||
@module tests.moonsource_qidian.yuewen_qr_setting_spec
|
||||
--]]
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local beginLogin = require("source.auth").beginLogin
|
||||
local Themed = require("support.theme_stubs")
|
||||
Themed.install()
|
||||
package.preload["ui.themes.widgets.row"] = function()
|
||||
return { widget = function(spec) return spec end }
|
||||
end
|
||||
package.preload["ui/network/manager"] = function()
|
||||
return { runWhenConnected = function(_self, fn) fn() end }
|
||||
end
|
||||
package.preload["source.review_setting"] = function()
|
||||
return { row = function() return function() return {} end end }
|
||||
end
|
||||
package.preload["source.category_setting"] = package.preload["source.review_setting"]
|
||||
local configs, saved_id, authorized, reloads = {}, nil, nil, 0
|
||||
package.preload["utils.settings"] = function()
|
||||
return {
|
||||
getSource = function(id) configs[id] = configs[id] or {}; return configs[id] end,
|
||||
saveSource = function(id) saved_id = id end,
|
||||
}
|
||||
end
|
||||
package.loaded["source.auth"] = nil
|
||||
package.preload["source.auth"] = function()
|
||||
return { beginLogin = beginLogin, ok = function(id) authorized = id end, expired = function() return false end }
|
||||
end
|
||||
package.preload["source.registry"] = function()
|
||||
return { reload = function() reloads = reloads + 1 end }
|
||||
end
|
||||
local options, on_cookie, started, checked, reject
|
||||
for _idx, name in ipairs({ "qqreader", "qidian", "xiaoxiang" }) do
|
||||
package.preload["moonsource_" .. name .. ".yuewen_qr"] = function()
|
||||
return { new = function(_self, spec, cb)
|
||||
options, on_cookie = spec, cb
|
||||
return { start = function() started = true end }
|
||||
end }
|
||||
end
|
||||
end
|
||||
for _idx, name in ipairs({ "qqreader", "qidian", "xiaoxiang" }) do
|
||||
local id = "ext." .. name
|
||||
package.preload["moonsource_" .. name .. ".client"] = function()
|
||||
return {
|
||||
cookie = function() return configs[id] and configs[id].cookie end,
|
||||
loginCheckAsync = function(cookie, cb)
|
||||
checked = cookie
|
||||
cb(not reject, reject and "rejected" or nil, { id = "123" })
|
||||
end,
|
||||
userAsync = function(cookie, cb)
|
||||
checked = cookie
|
||||
cb(not reject and { id = "123" } or nil, reject and "rejected" or nil)
|
||||
end,
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
for _idx, source in ipairs({
|
||||
{ id = "ext.qqreader", app_id = "1450000220", area_id = "1" },
|
||||
{ id = "ext.qidian", app_id = "13", area_id = "31" },
|
||||
{ id = "ext.xiaoxiang", app_id = "57", area_id = "5" },
|
||||
}) do
|
||||
local Setting = require("moonsource_" .. source.id:sub(5) .. ".setting")
|
||||
started, checked, saved_id, authorized = nil, nil, nil, nil
|
||||
local rows = Setting.rows()
|
||||
rows[1](400).callback()
|
||||
Assert.is_true(started, "账号行直接启动设备扫码")
|
||||
Assert.eq(options.app_id, source.app_id)
|
||||
Assert.eq(options.area_id, source.area_id)
|
||||
Assert.is_nil(saved_id, "仅获取二维码不能保存登录态")
|
||||
reject = true
|
||||
on_cookie("ywguid=guid; ywkey=bad")
|
||||
Assert.is_nil(saved_id, "各源的账号校验失败时不保存")
|
||||
Assert.is_nil(authorized)
|
||||
Assert.eq(Themed.last("toast").text, "rejected")
|
||||
Assert.is_true(Themed.last("progress_dialog").closed)
|
||||
reject = false
|
||||
on_cookie("ywguid=guid; ywkey=key")
|
||||
Assert.eq(saved_id, source.id)
|
||||
Assert.eq(authorized, source.id)
|
||||
Assert.eq(configs[source.id].cookie, checked)
|
||||
Assert.eq(checked, "ywguid=guid; ywkey=key")
|
||||
Assert.eq(Themed.last("toast").text, "登录成功")
|
||||
started = nil
|
||||
Setting.login()
|
||||
Assert.is_true(started, "登录失效的直达入口也走设备扫码")
|
||||
if source.id ~= "ext.qqreader" then
|
||||
local paste
|
||||
for _idx, factory in ipairs(Setting.rows()) do
|
||||
local row = factory(400)
|
||||
if row.title == "粘贴 Cookie" then paste = row; break end
|
||||
end
|
||||
Assert.not_nil(paste)
|
||||
paste.callback()
|
||||
Assert.eq(Themed.last("input").title, source.id == "ext.qidian" and "起点登录 Cookie" or "潇湘登录 Cookie")
|
||||
end
|
||||
end
|
||||
Assert.eq(reloads, 3)
|
||||
@@ -0,0 +1,335 @@
|
||||
--[[--
|
||||
moonsource_qidian.yuewen_qr:取码 → 轮询 → ywguid/ywkey 或跟跳 Set-Cookie。
|
||||
过期、关窗、手机取消刷新不把迟到的登录态交给 on_cookie。
|
||||
浏览器扩展绑定仍指向 book.qq.com。
|
||||
@module tests.moonsource_qidian.yuewen_qr_spec
|
||||
--]]
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local Stubs = require("support.stubs")
|
||||
|
||||
package.preload["json"] = function()
|
||||
return { decode = require("support.json_stub").decode, encode = function() return "{}" end }
|
||||
end
|
||||
|
||||
package.preload["http.timeout"] = function()
|
||||
return { net = function() return 15 end }
|
||||
end
|
||||
|
||||
local script, requested = {}, {}
|
||||
local function respond(prefix, res) script[#script + 1] = { prefix = prefix, res = res } end
|
||||
package.preload["http.request"] = function()
|
||||
return {
|
||||
request = function(opts, cb)
|
||||
requested[#requested + 1] = opts
|
||||
for i, item in ipairs(script) do
|
||||
if opts.url:sub(1, #item.prefix) == item.prefix then
|
||||
table.remove(script, i)
|
||||
require("ui/uimanager"):nextTick(function()
|
||||
if item.res.hook then item.res.hook() end
|
||||
cb(item.res)
|
||||
end)
|
||||
return { cancel = function() end }
|
||||
end
|
||||
end
|
||||
require("ui/uimanager"):nextTick(function() cb(nil, "no script") end)
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
header = function(res, name) return res and res.headers and res.headers[name] end,
|
||||
headerAll = function(res, name)
|
||||
local value = res and res.headers and res.headers[name]
|
||||
return type(value) == "table" and value or (value and { value } or {})
|
||||
end,
|
||||
}
|
||||
end
|
||||
|
||||
local shown = {}
|
||||
local function widget(kind)
|
||||
return function()
|
||||
return { new = function(_, o)
|
||||
o.kind = kind
|
||||
function o:show() shown[#shown + 1] = self end
|
||||
function o:close()
|
||||
self.closed = true
|
||||
if self.close_callback then self.close_callback() end
|
||||
end
|
||||
return o
|
||||
end }
|
||||
end
|
||||
end
|
||||
package.preload["ui.themes.widgets.qr"] = widget("qr")
|
||||
package.preload["ui.themes.widgets.confirm"] = widget("confirm")
|
||||
package.preload["ui.themes.widgets.toast"] = widget("toast")
|
||||
package.preload["ui.themes.widgets.progress_dialog"] = widget("busy")
|
||||
|
||||
local QRLogin = require("moonsource_qidian.yuewen_qr")
|
||||
local SPEC = {
|
||||
app_id = "1450000220", area_id = "1", return_url = "https://book.qq.com/",
|
||||
referer = "https://login.book.qq.com/login.html",
|
||||
title = "QQ阅读扫码登录", caption = "用 QQ阅读或起点 App 扫一扫",
|
||||
}
|
||||
|
||||
local QR_PREFIX = "https://ptlogin.yuewen.com/login/qrcode?"
|
||||
local POLL_PREFIX = "https://ptlogin.yuewen.com/login/qrcodelogin?"
|
||||
|
||||
local function reset()
|
||||
script, requested, shown = {}, {}, {}
|
||||
end
|
||||
|
||||
local function find(kind)
|
||||
for i = #shown, 1, -1 do if shown[i].kind == kind then return shown[i] end end
|
||||
end
|
||||
|
||||
local function toastCount(text)
|
||||
local n = 0
|
||||
for i = 1, #shown do
|
||||
if shown[i].kind == "toast" and shown[i].text == text then n = n + 1 end
|
||||
end
|
||||
return n
|
||||
end
|
||||
|
||||
local function qrcode(session)
|
||||
return { code = 200, body = '{"code":0,"data":{"sessionKey":"' .. session .. '"}}' }
|
||||
end
|
||||
|
||||
local function poll(body, extra)
|
||||
local res = { code = 200, body = body }
|
||||
if extra then
|
||||
for k, v in pairs(extra) do res[k] = v end
|
||||
end
|
||||
return res
|
||||
end
|
||||
|
||||
do -- 扫码 URL 与官方同一组参数,顺序由 formEncode 排定
|
||||
Assert.eq(QRLogin:new(SPEC, function() end):scanUrl("sk/1"),
|
||||
"https://ptlogin.yuewen.com/mobile/scanlogin?appid=1450000220&areaid=1"
|
||||
.. "&bookId=0&chapterId=0&sessionkey=sk%2F1")
|
||||
end
|
||||
|
||||
do -- 等待是字符串 "0",成功后 JSON 里的 ywGuid/ywKey 排成 Cookie
|
||||
reset()
|
||||
respond(QR_PREFIX, qrcode("sk1"))
|
||||
respond(POLL_PREFIX, poll('{"code":-11019,"scanStatus":"0"}'))
|
||||
respond(POLL_PREFIX, poll('{"code":0,"scanStatus":"5","data":{"ywGuid":"g1","ywKey":"k1","ywOpenId":"o1"}}'))
|
||||
local got
|
||||
QRLogin:new(SPEC, function(cookie) got = cookie end):start()
|
||||
Stubs.flush()
|
||||
Assert.eq(find("qr").text,
|
||||
"https://ptlogin.yuewen.com/mobile/scanlogin?appid=1450000220&areaid=1"
|
||||
.. "&bookId=0&chapterId=0&sessionkey=sk1")
|
||||
Assert.eq(find("qr").caption, "用 QQ阅读或起点 App 扫一扫")
|
||||
Assert.eq(got, "ywguid=g1; ywkey=k1; ywopenid=o1")
|
||||
Assert.is_true(find("qr").closed)
|
||||
Assert.eq(toastCount("已取消登录"), 0)
|
||||
Assert.is_true(requested[1].allow_redirects == false)
|
||||
Assert.is_true(requested[2].url:find("qrcode=sk1", 1, true) ~= nil)
|
||||
Assert.len(script, 0)
|
||||
end
|
||||
|
||||
do -- 数字 GUID 要完整十进制;LuaJIT tostring 的科学计数法会毁掉 Fock 身份
|
||||
reset()
|
||||
respond(QR_PREFIX, qrcode("long-guid"))
|
||||
respond(POLL_PREFIX, poll('{"code":0,"scanStatus":5,"data":{"ywGuid":1234567890123456,"ywKey":"key"}}'))
|
||||
local got
|
||||
QRLogin:new(SPEC, function(cookie) got = cookie end):start()
|
||||
Stubs.flush()
|
||||
Assert.eq(got, "ywguid=1234567890123456; ywkey=key")
|
||||
end
|
||||
|
||||
do -- 已扫码只提示一次,确认后仍把登录态交出去
|
||||
reset()
|
||||
respond(QR_PREFIX, qrcode("sk1"))
|
||||
respond(POLL_PREFIX, poll('{"code":0,"scanStatus":"1"}'))
|
||||
respond(POLL_PREFIX, poll('{"code":0,"scanStatus":1}'))
|
||||
respond(POLL_PREFIX, poll('{"code":0,"scanStatus":"5","ywGuid":"g2","ywKey":"k2"}'))
|
||||
local got
|
||||
QRLogin:new(SPEC, function(cookie) got = cookie end):start()
|
||||
Stubs.flush()
|
||||
Assert.eq(got, "ywguid=g2; ywkey=k2")
|
||||
Assert.eq(toastCount("已扫码,请在手机上确认"), 1)
|
||||
end
|
||||
|
||||
do -- 过期:重试框,不交登录态
|
||||
reset()
|
||||
respond(QR_PREFIX, qrcode("sk1"))
|
||||
respond(POLL_PREFIX, poll('{"code":0,"scanStatus":"4"}'))
|
||||
local got
|
||||
QRLogin:new(SPEC, function(cookie) got = cookie end):start()
|
||||
Stubs.flush()
|
||||
Assert.is_nil(got)
|
||||
Assert.eq(find("confirm").text, "二维码已过期")
|
||||
Assert.eq(find("confirm").ok_text, "重新获取")
|
||||
Assert.eq(#requested, 2)
|
||||
end
|
||||
|
||||
do -- 用户关掉二维码:迟到的成功不交登录态,也不再轮询
|
||||
reset()
|
||||
respond(QR_PREFIX, qrcode("sk1"))
|
||||
respond(POLL_PREFIX, poll('{"code":0,"scanStatus":"5","data":{"ywGuid":"late","ywKey":"no"}}', {
|
||||
hook = function() find("qr"):close() end,
|
||||
}))
|
||||
local got
|
||||
QRLogin:new(SPEC, function(cookie) got = cookie end):start()
|
||||
Stubs.flush()
|
||||
Assert.is_nil(got)
|
||||
Assert.eq(#requested, 2, "关闭后不再轮询")
|
||||
Assert.eq(toastCount("已取消登录"), 1)
|
||||
end
|
||||
|
||||
do -- 只有 302url:跟跳收 Set-Cookie,相对 Location 拼回原 host;属性不当 cookie
|
||||
reset()
|
||||
respond(QR_PREFIX, qrcode("sk1"))
|
||||
respond(POLL_PREFIX, poll('{"code":0,"scanStatus":"5","data":{"302url":"https://ptlogin.yuewen.com/jump"}}'))
|
||||
respond("https://ptlogin.yuewen.com/jump", {
|
||||
code = 302, headers = { Location = "/done", ["Set-Cookie"] = "ywguid=g3; Path=/; HttpOnly" },
|
||||
})
|
||||
respond("https://ptlogin.yuewen.com/done", {
|
||||
code = 200, headers = { ["Set-Cookie"] = "ywkey=k3; Path=/, ywopenid=o3; Secure" },
|
||||
})
|
||||
local got
|
||||
QRLogin:new(SPEC, function(cookie) got = cookie end):start()
|
||||
Stubs.flush()
|
||||
Assert.eq(got, "ywguid=g3; ywkey=k3; ywopenid=o3")
|
||||
Assert.is_nil(got and got:find("Path", 1, true))
|
||||
Assert.len(script, 0)
|
||||
end
|
||||
|
||||
do -- 非 https 跳转不跟,不交登录态
|
||||
reset()
|
||||
respond(QR_PREFIX, qrcode("sk1"))
|
||||
respond(POLL_PREFIX, poll('{"code":0,"scanStatus":"5","data":{"302url":"http://evil.example/x"}}'))
|
||||
local got
|
||||
QRLogin:new(SPEC, function(cookie) got = cookie end):start()
|
||||
Stubs.flush()
|
||||
Assert.is_nil(got)
|
||||
Assert.eq(find("confirm").text, "登录失败:未获取到登录态")
|
||||
Assert.eq(#requested, 2)
|
||||
end
|
||||
|
||||
do -- 已拿到临时凭据仍须走 302url,不能把跨站身份当本站会话保存
|
||||
reset()
|
||||
respond(QR_PREFIX, qrcode("exchange"))
|
||||
respond(POLL_PREFIX, poll('{"code":0,"scanStatus":5,"data":{"ywGuid":"temporary","ywKey":"old",'
|
||||
.. '"302url":"https://ptlogin.yuewen.com/exchange"}}'))
|
||||
respond("https://ptlogin.yuewen.com/exchange", {
|
||||
code = 302, headers = { Location = "https://m.qidian.com/finish",
|
||||
["Set-Cookie"] = { "ywguid=intermediate; Path=/", "ywkey=intermediate; Path=/" } },
|
||||
})
|
||||
respond("https://m.qidian.com/finish", {
|
||||
code = 200, headers = { ["Set-Cookie"] = { "ywguid=321; Path=/", "ywkey=web; Path=/" } },
|
||||
})
|
||||
local spec = { app_id = "13", area_id = "31", return_url = "https://m.qidian.com/", ticket = "1" }
|
||||
local got
|
||||
QRLogin:new(spec, function(cookie) got = cookie end):start()
|
||||
Stubs.flush()
|
||||
Assert.eq(got, "ywguid=321; ywkey=web")
|
||||
Assert.len(requested, 4)
|
||||
Assert.is_nil(requested[3].headers.Cookie, "第三方扫码域不带书源 Cookie")
|
||||
Assert.matches(requested[1].url, "ticket=1")
|
||||
end
|
||||
|
||||
do -- 官网 ticket 路径必须兑换,本站回包替换扫码 JSON 中的身份
|
||||
reset()
|
||||
respond(QR_PREFIX, qrcode("ticket"))
|
||||
respond(POLL_PREFIX, poll('{"code":0,"scanStatus":5,"data":{"ticket":"one-use","ywGuid":"temporary","ywKey":"old"}}'))
|
||||
respond("https://m.qidian.com/?ticket=", {
|
||||
code = 200, headers = { ["Set-Cookie"] = { "ywguid=456; Path=/", "ywkey=web; Path=/" } },
|
||||
})
|
||||
local spec = { app_id = "13", area_id = "31", return_url = "https://m.qidian.com/", ticket = "1" }
|
||||
local got
|
||||
QRLogin:new(spec, function(cookie) got = cookie end):start()
|
||||
Stubs.flush()
|
||||
Assert.eq(got, "ywguid=456; ywkey=web")
|
||||
Assert.len(requested, 3)
|
||||
end
|
||||
|
||||
do -- ticket=1 时忽略裸 302url,强制带 ticket 兑换;否则会吃到空壳首页却「登录成功」
|
||||
reset()
|
||||
respond(QR_PREFIX, qrcode("bare-home"))
|
||||
respond(POLL_PREFIX, poll(
|
||||
'{"code":0,"scanStatus":5,"data":{"ticket":"t1","ywGuid":"temporary","ywKey":"old",'
|
||||
.. '"302url":"https://m.qidian.com/"}}'))
|
||||
respond("https://m.qidian.com/?ticket=", {
|
||||
code = 200, headers = { ["Set-Cookie"] = { "ywguid=789; Path=/", "ywkey=web; Path=/" } },
|
||||
})
|
||||
local spec = { app_id = "13", area_id = "31", return_url = "https://m.qidian.com/", ticket = "1" }
|
||||
local got
|
||||
QRLogin:new(spec, function(cookie) got = cookie end):start()
|
||||
Stubs.flush()
|
||||
Assert.eq(got, "ywguid=789; ywkey=web")
|
||||
Assert.matches(requested[3].url, "ticket=t1")
|
||||
Assert.is_nil(requested[3].url:match("^https://m%.qidian%.com/?$"))
|
||||
end
|
||||
|
||||
do -- 本站常常不 Set-Cookie ywkey(只有 abPolicies);ticket 落到本站且 JSON 身份齐全就算完成
|
||||
reset()
|
||||
respond(QR_PREFIX, qrcode("no-set-cookie"))
|
||||
respond(POLL_PREFIX, poll(
|
||||
'{"code":0,"scanStatus":5,"data":{"ticket":"t2","ywGuid":"temporary","ywKey":"old"}}'))
|
||||
respond("https://m.qidian.com/?ticket=", {
|
||||
code = 200, body = "<html>shell</html>",
|
||||
headers = { ["Set-Cookie"] = "abPolicies=%7B%7D; Path=/" },
|
||||
})
|
||||
local spec = { app_id = "13", area_id = "31", return_url = "https://m.qidian.com/", ticket = "1" }
|
||||
local got
|
||||
QRLogin:new(spec, function(cookie) got = cookie end):start()
|
||||
Stubs.flush()
|
||||
Assert.eq(got, "ywguid=temporary; ywkey=old")
|
||||
end
|
||||
|
||||
do -- 即使临时凭据完整,也不跟陌生 HTTPS 地址
|
||||
reset()
|
||||
respond(QR_PREFIX, qrcode("foreign"))
|
||||
respond(POLL_PREFIX, poll('{"code":0,"scanStatus":5,"data":{"ywGuid":"g","ywKey":"k",'
|
||||
.. '"302url":"https://qidian.com.evil.example/steal"}}'))
|
||||
local got
|
||||
QRLogin:new(SPEC, function(cookie) got = cookie end):start()
|
||||
Stubs.flush()
|
||||
Assert.is_nil(got)
|
||||
Assert.len(requested, 2)
|
||||
end
|
||||
|
||||
do -- 手机取消:关掉旧码不提示已取消,再要一张新码
|
||||
reset()
|
||||
respond(QR_PREFIX, qrcode("old"))
|
||||
respond(POLL_PREFIX, poll('{"code":0,"scanStatus":"3"}'))
|
||||
respond(QR_PREFIX, qrcode("new"))
|
||||
respond(POLL_PREFIX, poll('{"code":0,"scanStatus":"5","data":{"ywGuid":"g4","ywKey":"k4"}}'))
|
||||
local got
|
||||
QRLogin:new(SPEC, function(cookie) got = cookie end):start()
|
||||
Stubs.flush()
|
||||
Assert.eq(got, "ywguid=g4; ywkey=k4")
|
||||
Assert.eq(toastCount("已取消登录"), 0)
|
||||
Assert.eq(requested[1].url:sub(1, #QR_PREFIX), QR_PREFIX)
|
||||
Assert.eq(requested[3].url:sub(1, #QR_PREFIX), QR_PREFIX)
|
||||
Assert.is_true(requested[4].url:find("qrcode=new", 1, true) ~= nil)
|
||||
Assert.len(script, 0)
|
||||
end
|
||||
|
||||
for _idx, spec in ipairs({
|
||||
{ app_id = "13", area_id = "31", return_url = "https://m.qidian.com/",
|
||||
referer = "https://passport.qidian.com/mobile/login", title = "起点扫码登录", caption = SPEC.caption },
|
||||
{ app_id = "57", area_id = "5", return_url = "https://www.xxsypro.com/",
|
||||
referer = "https://passport.yuewen.com/yuewen.html", title = "潇湘扫码登录", caption = SPEC.caption },
|
||||
}) do
|
||||
reset()
|
||||
respond(QR_PREFIX, qrcode("source-session"))
|
||||
respond(POLL_PREFIX, poll('{"code":0,"scanStatus":5,"data":{"ywGuid":"source-guid","ywKey":"source-key"}}'))
|
||||
local got
|
||||
QRLogin:new(spec, function(cookie) got = cookie end):start()
|
||||
Stubs.flush()
|
||||
Assert.eq(find("qr").title, spec.title)
|
||||
Assert.matches(find("qr").text, "appid=" .. spec.app_id .. "&areaid=" .. spec.area_id)
|
||||
Assert.matches(requested[1].url, "appId=" .. spec.app_id .. "&areaId=" .. spec.area_id)
|
||||
Assert.matches(requested[2].url, "appId=" .. spec.app_id .. "&areaId=" .. spec.area_id)
|
||||
Assert.eq(requested[1].headers.Referer, spec.referer)
|
||||
Assert.eq(got, "ywguid=source-guid; ywkey=source-key")
|
||||
end
|
||||
|
||||
do -- 浏览器扩展绑定不改到 passport
|
||||
local Setting = require("moonsource_qqreader.setting")
|
||||
Assert.eq(Setting.browser.domain, "book.qq.com")
|
||||
Assert.eq(Setting.browser.login, "https://book.qq.com/book-shelf")
|
||||
Assert.eq(Setting.browser.check, "https://book.qq.com/book-shelf")
|
||||
Assert.eq(type(Setting.login), "function")
|
||||
end
|
||||
@@ -0,0 +1,13 @@
|
||||
--[[--
|
||||
起点已购 VIP 章节的真实密文样本(只有密文,明文不入库)。uid 是样本账号的 ywguid。
|
||||
|
||||
@module tests.support.qidian_fock_sample
|
||||
--]]
|
||||
|
||||
return {
|
||||
content = "QOdN5HBhkkC9/l/IRm0/lSCaOTaNaS/ARorq455Le/+m1mAGa/LUZcu6zIFRiJ7CbeVNRPxins4URdZ4Hc9Rlcwvo+qwxkdPz11mbiAP6givnifuNU+W5OgalHm1/Ww20ldVnoibut1VUEI3JfsEvy8VB6MODPq5Hy1qUsecqKhIMGMwLwp9GjU+Zaqa9ukrMmw/59m6Hh02sLM2Ncnwnlw/HlP8vCWoZuW/BS8OdYjuGn8LaG5/tAf8zS+faeOzpD6K3w6cFQ8i5CMPaMNWVrDyE+VexkQpbyEqScSbc7um8zpAk9wEoT2aE+eztirRpk8NQZEvC7Cf9Do9Gzix8zFcAudcSwmyYzwJkhGZxla1BqEM1mK0Fg6kWAMp0r3MI0Nt92INlp4feH0RinXUz0OTrtoEoinUMnyUPgYiN0BJxvWc5tep6Zng2C+Uz/NcDQytKpF/heioZV7MIyTSD1EEfqflJHlG+TPBNhsKWxukJK36u/azFbgZr45wlfUw0L+KnmdhCXqf+Y7YTytMfWnWxhXIAitzR0y4hpFS+35E1GJREY9Y84dN2AkOwedx0XrGeZLWBoAgcORJwf1Rvq+CpoS+FkoZXBH8FUKOybI/juG4Z9XrUxd/p95OV2BlpefeljTBfrr+X+y1AJiVN1njaVjfLaxAGwqTnimh73S/XtabkluwNx+WlbUNnoYvljs4VgbIhMqcaYOtCBt8XknbzE0dH1tyIWeeoK42jQ9zlLXiBf7KEiXbPiGxoTTK3LYv8kjMTQDIuA7Bq4HsFqbc17qE4d4L8jMdTHywjkP0sC8Ij8S6G+rFQR9rIP1T0vRcMSrZlJv1o5OhfXEs4IYC+X1r85HPah0zwNRF5i69BfU/DEPxzk+kr7oRn+W6+OWdyRk97Z429ykY9IWt8xqgCT9YGrk9INZURSLfeNhj+nzRpT3Z7OjjStlSNvl1/qnalqus3ZDZYd08KMEV3akweIGjBgrq/MeCcD9v8lfHuAjj3ntXnLlDmc/bT8pcMJII7C8ldVxyYIYDI5G1mFUEPFaw7d7yhM03R6t73lbCGqIZgBat2l5RT+q54/GA5YNc49Au17kqSHeCI61OXMAAtKF7JYfHMjGQDbRdyPfZssbLzV9Ga6wq+7IfE7lEtO5Ym4ZIbSVgyM9eu7WuQHNQ6pikZQ9HB9kxRdwx4ZJu8fZRhRfTm3/jBooo1/C+DmnSndoLwgBEaSVU5q3BmQJy5on44F789nHjDf5ZIvwlTeGZdnaxPFYqd+m0jofOTP9Xg0NWT2sShr6C8MnKSMvRijs058E1ceNeKoY33sk4ImvBJHfYkUDst0lZYBeiV+RgILNXKHe61bZ9gPNs+EsfnCz73xafbeK990Y6HiiSfmwJpmHF8C5p16M5C7aNFik+NnPJsPiCXFozNySPMoVah36eK54hyp9Kx7dvp974DRdr+V9w3swUqfBFEV2pUJxw01bSyot5smnqXCYqwrm187Kcr2FAZamszIW25ER+hy1dNljso+jA3XXD9rjv8HHJV/oIhTYf7CVPXSAFVocNJQMZjJn5TlIvx7RiDak3lj9Rbzil1wgDB/1Dh4HDUKPXO3Z6WFi4STsS6NC23KHLygztJXcQDYCM1WTNiG3EL+nbd+sp7oyMd4aVrPNpVz+eAcRxfIXBbVSMpLayqrspydIZ94LkeLxa2ZZoDJuEvD7V2bn6a09ZkKEHCW6D6qaSK8TuxhoM9iK/fYTbEr1fnq0QNvmO/ZBg7CDHTqzelTZWSOJ+nRiqQYaypcVWfRWowXwdUgh+2CrouXMFPUXgZoc3K7qWPtXcH91Nl+LDPNhrbwBJ2lV+/OTFGF3liIxf6kwyiSo6cmjrKarKmBjm3BNtWmMLa/PsxQEUSKZHA72iduoXR8IM88cQNdAdvXhfJ5B21onIgLaD7njhKh1n5i1ePRhZhrt360bz0tqTZwA3kgCCl+BeInURwL+gVHBiALJF7RM2W6RouzU/SeoChIY7VgJeigiI3ZMQEx/ZZRG4S+6jz3S6Nl7b5IXEskOjTBDylTXCaSn130hO4kQud7n+dNxQD4Mr3xjCHT/brdoYjyKRo+hBk35z9m8uxCxUE6ElIqbSmmvvS2PGRqnFS9S3LGxWH17LgLHoMgX99T7mQmbyGWcXBQXnEUeHayDo/PqAecLD/CEAKpk/vLc71Xx6e8XgO6t468y7KdVpESV9s/of1rfu9F2ixRsvarZ9HHFPe1s8P0urplWecV8JlOqWlUJSTuP5NNUn9mm9TDfj9hBMX59BVl7e9GAUWCekpJzC70Fp5AFaM4wFbxttZGQcl9ZlbinAtB9kPwh/RvvU/ws4QcipAljp/8r1SnIheI+ODR+uOunILDfKZCcat6hwYo04fuSVyVet5wUphSstdwwmsMUZ0eCb5wYf12aVBLZQw/ueImLV6uCuOrcCEBpQ4E4opPrF6rmLuasgRhAjvDqbi9HIUFPyZKDoOOtNNEdZwi5aYm+Y4UXrjn7LnMW+kH8DKDR2IVCccW33OWoWY72lg5lH8dn9wkVeNHu+t0Dly6eWZYea3D82RwRilJg6ltc22gHs6gKumecFbVudsOadpjeoHg4Ve1Id9EesWo4i/hAX6CLgeO+sQ+zgeeq5KJt+AGs48Bw7h1xREmZhfHR3GWLmi1jQBllK3Alc91RK9g4b8GB6lE2FFYydsStD50S4tHKTiKsMgcT2xtEcpvsiLMLx4iLhp0V80F3OHw6WiZxym1YVgqDeiC34de5qtff6zbcLoKENyS5EiZc2jVpRGGmI7eGR5FrdsG998KHK402e8Y4j9qfGnI1uQ+ZFArwdUkLmPqLKCQwHTs+U9Esy+/akIm7ViVxlKgvpe8XdqX1P+ZpEDDbi+5sUoDpMsgWzk0Fjum2vdNr6VEBolEkyKKXZOzgJ4PLkY4U+WaCNof9wuG2S8jfAScPL2o86PHBtLBud7x+/uVtADScbgToxeuKZSLAhZ71Th6eH4H1G+sQqHFvKMRFpFtxoDMAYQ9tBZCO45cJIgs98E6jM9jV9+MYtnYv5C7q23VN5J6tT31IlAzTID4Efe3Fvl8jlnzPh3x/qaxZ43uFi4BjpEP5ST6siTjZdExlNyxbxFriF9Qm1NSmlh44TN0l2WzIq7MIRqeAD7qdpZ+FqFkyEu1oV+aFNi7s7z8ZWsYUoj743Xcg9X6c4lM0U86Z45ZfDDSrrMbpwYfSmv9vR0v6p2fSN5/z7MX6HbJThgr3qel/SXU5LfkYPG1BO1TsrHtn1LCKLDAYks3hWkbofed76ZRWy5Y37WKKUV5Khs9HK1mr2t1+/Unt1Vt4Xz3qS40m/qHS0zH7qSnMqSG0Ya58rB8Qt/YcmP8XByyLpPtO9WRWK6cTNi9bRlRFBH9hRBXydJ+DjpUJkXvft4FxjhtQDiJpnH1nZZH/MF4GctUUuy7ALmyouhwstZQIQrxkJgdAfuDlv81ooZW3FaUZeKCK0nfs7BRkk2lyJN4aNXly0hVuOOVSLsiuCIJiC+eHET1Ed6Pjv+1a9uzXv5utB9wr4a/uJDW/LpkMvg1C6x5WvdKY88VNeBOcq3IuPFWchQwsAqogqUzkK3BZUagTXqRKk8IKAFONGTCQzmqOSykLZQYKBt7aPJtptLNfIDdkbVw/ImCj4NkAUwroiT5jXphYDvtA5Evrx+/2zPjbKLIHg2S5Yc3MWdIkbjX/YXs4C/2yFLK1kFTjXd5NL8KIHAML5FSaCWbM4/2hFW5u5HVmjVbW8hiIRtiJ+WuvwAaHNupZcwCZtYyCPKdsimVRSkwwchZ8Y7J4az6pSCCVNee3hpICDf1m3RQ5UmDep+sYumnS6hANpeMroIiT/0h5dZj+/+5F1uHeb/lAKEK9dm9HGOipfH6CTqER7mQdUC3TOYE7ZJFR7kA3EtcrUJZhEy/npJ3hGWlHXwinbwuEiASYdfeXDVd63aV+A3v0K+6Cxq9FYGDw9FkA0Ni0lkRKLNCYvxHOrEYdbMbH56IDqkon4i1jpJegO1fpSgHFcAKEYVlLnlSuDE5IEr88Cne9oez9gQFwaCmBA64NdHK5nlLmQ1ZmhIUAtNXs8coCf0Hs59IGNtYXN2XYPA4HwtDx78vIbv4Iif2Iji5M0DuoSYJVZfos/rVkP8jfvdVYK3s0h4MhlKwFhK8hkeMWShz6Zl5cRCVN5XOyToVIJWIxixk6YhmHpznIofeGLsLKpQVaaKds8PzIBWLdmAqEe6wSSJxwrd6FKJd5a8BhyMc0NXPm5bTBSWRuZfWgG/D6XygGot7OmuwfwfUM3aUloteaiNOYl8l5auY8E5ETJsUjQT+lJkErKl7K6Cb4FYkTsvscMTAXIz4yfcmAg7ezvc+HGY9ooo6sxMsi6Y1jJKXtNmk0zUVMdl0F4ZPAKCig8rp5IwMVq8mEfntUSkA1RIOdtk5BtO+HsTMO9CVmt5ay2zSSkXz/sT81IQs9iRLQuo8AXbVzRmjszRo0yGTIteoNrl6UfCU1wSVZnnXrggSnpD0ok0kOoX5uVNT9XvG9+akVxD6bT7oUZ+0b0w3dvEd9O/mBtlkjbgd7xpP6sT5+BTztUesX6ehD5/gemeVg6Ra/PGiEmv76dbnoYAC998mP9qQZ5C3/e2ZMis5uiYFVxNr12eQ82ML/9NQn7dGiKHR4p5HQByTI27hRUVGRNiePzV5apfok994jPSJ8VMcfOQS67M5qO2yRy7uPr9OtEcqMjvAluQZoyGa8XcDaPYkvPjOfETRqvZU+N7tv2Jx1ogfIvNbd9JIHvzSrEB4rluqD5BjdNoOMJtkrnm/Vkd+TB2Pjl0wCecd/54aCuq/vA866AcqNeppBpq0eVVFpD7XX1sdhihlI1dayBI7znd8O+6LkDwSfo0/4/UrzEp51f2iT3UdQy2CUbxshuSwZvNJWDdnLTZsREX4Bk9kdd8iw9x2z53V+WFyrdLine truncated
|
||||
chapter_id = "919458235",
|
||||
keypool = "Kbs29rbPW7ovIu6TZlGonTp7q8otJyw18iho6Sk0EwX43/Twr7ofO3m15ypGgpNGooA4C6GCTB2y+bBSOxY/8Zwtyx7ry34qaxDeHQfTn+5e+mlxaUQ4zWnmuuhOt7lCtFlftvtYv0sKykS8dMM9DPY/zUljbxQiDDM7AGzo/gP64dMPDozys2SzeJ/z3JEEUX2lcdLh/Ohh0J3VbCBwT/ccX5Al7Pa/JO8LjERMyaE=",
|
||||
version = "1635757421",
|
||||
uid = "900055953280",
|
||||
}
|
||||
@@ -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