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

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

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

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
# 潇湘书院
| 能力 | 是否支持 | 备注 |
| --- | --- | --- |
| 扫码登录 | 已实现,未实测 | 阅文二维码,使用 QQ阅读或起点 App;最终账号登录未完成实测 |
| 浏览器登录与 Cookie 导入 | 已实现,未实测 | 保留扩展回传和手动粘贴入口 |
| 设备密码与验证码登录 | 不支持 | 可在官网完成登录后导入 Cookie |
| 书架拉取 | 支持 | 仅根书架图书,不枚举其他文件夹或资源类型 |
| 书架新增与移出 | 已实现,未实测 | 本地先生效,同步上行后回读确认;失败保留脏行或墓碑 |
| 搜索 | 支持 | 聚合后续页,默认最多 60 本 |
| 分类书城 | 支持 | 动态分类、标签、排序、资费、状态、更新时段和字数筛选 |
| 榜单 | 部分支持 | 潇湘票、畅销、完结、阅读、收藏;旧移动榜单仅单页 |
| 详情与分卷目录 | 支持 | 保留章节顺序和长整数 ID |
| 免费正文 | 支持 | 可匿名读取 |
| 已购正文 | 已实现,未实测 | 按官网权限解码;未购预览不作为正文缓存 |
| 章节与全本缓存 | 支持 | 支持预取和后台缓存;整本下载未完成实测 |
| 离线阅读 | 支持 | 已缓存章节可续读、关书重开 |
| 阅读进度同步 | 部分支持 | 仅章节位置,无章内比例;远端写入未实测 |
| 笔记与统计同步 | 不支持 | 仅本地保存 |
| 书评、章评、段评与回复 | 不支持 | 当前 Web 协议未找到可验证接口,不代表 App 没有评论 |
| 账号切换 | 部分支持 | 同账号可续期;换号须确认清理旧本地数据,未同步记录会丢失 |
+5
View File
@@ -0,0 +1,5 @@
local _ = require("gettext")
return {
fullname = _("月读书源:潇湘书院"),
description = _("给月读增加「潇湘书院」书源。需要同时安装月读,与平台官方无关。"),
}
+9
View File
@@ -0,0 +1,9 @@
--[[--
KOReader 只认带 main.lua 的插件目录;书源本身不需要任何插件钩子,月读读取旁边的 moon_source.lua。
--]]
local WidgetContainer = require("ui/widget/container/widgetcontainer")
return WidgetContainer:extend{
name = "moonsource_xiaoxiang",
is_doc_only = false,
}
@@ -0,0 +1,15 @@
--[[--
月读第三方书源描述:潇湘书院。契约见月读 examples/moonsource-demo.koplugin/moon_source.lua。
--]]
local function lazy(module)
return setmetatable({}, { __index = function(_, key) return require(module)[key] end })
end
return {
api = 1,
provides = { source = true },
meta = function() return require("moonsource_xiaoxiang.source").meta() end,
new = function() return require("moonsource_xiaoxiang.source").new() end,
setting = lazy("moonsource_xiaoxiang.setting"),
}
@@ -0,0 +1,15 @@
--[[--
书源元信息:id / 名称 / 类型,加上启用页展示用的说明与能力清单。`init.lua` 的 `meta()` 直接返回本表。
@module moonsource_xiaoxiang._meta
--]]
local _ = require("l10n").get("moonsource_xiaoxiang")
return {
id = "ext.xiaoxiang",
name = _("潇湘书院"),
type = "chapter",
description = _("潇湘书院书架与在线阅读"),
abilities = { _("搜索与发现"), _("书架同步"), _("进度同步") },
}
@@ -0,0 +1,119 @@
--[[--
潇湘官网分类库:动态分类与标签,筛选编码沿用官网,顺序聚合分页。
@module moonsource_xiaoxiang.browse
--]]
local Browse = require("source.browse")
local Client = require("moonsource_xiaoxiang.client")
local Mapper = require("moonsource_xiaoxiang.mapper")
local JSON_NULL = require("json").decode("null")
local _ = require("l10n").get("moonsource_xiaoxiang")
local Library = {}
local KEYS = { "state", "charge", "update", "words", "order", "category", "tag" }
local DEFAULT = { state = -1, charge = -1, update = -1, words = -1, order = 10, category = 0, tag = -1 }
local FILTERS = {
{ key = "order", title = _("排序"), items = { { 6, _("综合热度") }, { 10, _("最畅销") }, { 3, _("收藏最多") } } },
{ key = "state", title = _("状态"), items = { { -1, _("全部") }, { 0, _("连载") }, { 1, _("完结") } } },
{ key = "charge", title = _("价格"), items = { { -1, _("全部") }, { 0, _("免费") }, { 2, _("付费") } } },
{ key = "update", title = _("更新"), items = {
{ -1, _("全部") }, { 0, _("3天以内") }, { 1, _("7天以内") }, { 2, _("15天以内") }, { 3, _("一个月以内") },
} },
{ key = "words", title = _("字数"), items = {
{ -1, _("全部") }, { 11, _("20万以内") }, { 12, _("20-30万") }, { 3, _("30-50万") },
{ 24, _("50-100万") }, { 25, _("100-200万") }, { 26, _("200万以上") },
} },
}
local function node(params, key, value)
local values = {}
for index, name in ipairs(KEYS) do
values[index] = tostring(name == key and value
or (key == "category" and name == "tag" and -1 or params[name]))
end
return "cate:" .. table.concat(values, ":")
end
local function group(params, key, title, items)
local chips = {}
for _idx, item in ipairs(items) do chips[#chips + 1] = { id = node(params, key, item[1]), title = item[2] } end
local result = Browse.group(chips, node(params))
result.title = title
return result
end
function Library.run(opts, cb)
opts = opts or {}
local params = {}
for key, value in pairs(DEFAULT) do params[key] = value end
local valid = true
if opts.node then
local values = { opts.node:match("^cate:(%-?%d+):(%-?%d+):(%-?%d+):(%-?%d+):(%-?%d+):(%-?%d+):(%-?%d+)$") }
valid = #values == #KEYS
if valid then for index, key in ipairs(KEYS) do params[key] = tonumber(values[index]) end end
end
for _idx, filter in ipairs(FILTERS) do
local found = false
for _item, item in ipairs(filter.items) do if params[filter.key] == item[1] then found = true end end
valid = valid and found
end
if not valid then return require("source.base").defer(cb, nil, _("潇湘分类条件无效")) end
local cancelled, job, pending = false, nil, true
local initial = Client.libraryAsync(params, 1, function(wire, err)
pending = false
if cancelled then return end
local data = wire and wire.data
if type(data) ~= "table" or type(data.categoryList) ~= "table" then cb(nil, err or _("响应无效")); return end
local categories, tags, selected = {}, { { -1, _("全部") } }, nil
for _idx, category in ipairs(data.categoryList) do
if type(category) ~= "table" or not tonumber(category.id) or type(category.name) ~= "string" then
cb(nil, _("响应无效")); return
end
categories[#categories + 1] = { tonumber(category.id), _(category.name) }
if tonumber(category.id) == params.category then selected = category end
end
if not selected or type(selected.labelClassList) ~= "table" then cb(nil, _("响应无效")); return end
local seen, found = {}, params.tag == -1
for _idx, class in ipairs(selected.labelClassList) do
if type(class) ~= "table" then cb(nil, _("响应无效")); return end
local items = class.tagInfoList
if items == JSON_NULL then items = nil end
if items ~= nil and type(items) ~= "table" then
cb(nil, _("响应无效")); return
end
for _tag, tag in ipairs(items or {}) do
if type(tag) ~= "table" or not tonumber(tag.tagId) or type(tag.tagName) ~= "string" then
cb(nil, _("响应无效")); return
end
local id = tonumber(tag.tagId)
if id == params.tag then found = true end
if not seen[id] then tags[#tags + 1], seen[id] = { id, _(tag.tagName) }, true end
end
end
if not found then cb(nil, _("潇湘分类条件无效")); return end
local groups = { group(params, "category", _("分类"), categories) }
groups[1].chips[#groups[1].chips + 1] = { id = "rank", title = _("排行榜") }
if #tags > 1 then groups[#groups + 1] = group(params, "tag", _("标签"), tags) end
for _idx, filter in ipairs(FILTERS) do groups[#groups + 1] = group(params, filter.key, filter.title, filter.items) end
job = Browse.pages(function(index, done)
local function receive(result, reason)
local page_data = result and result.data
if type(page_data) ~= "table" or not tonumber(page_data.total) then
done(nil, reason or _("响应无效")); return
end
local books, failure = Mapper.books(page_data.bookList)
done(books, failure, index * 20 < tonumber(page_data.total))
end
if index == 1 then receive(wire); return end
return Client.libraryAsync(params, index, receive)
end, opts.limit or 60, groups, cb)
end)
if pending then job = initial end
return { cancel = function()
cancelled = true
if job then job.cancel() end
end }
end
return Library
@@ -0,0 +1,440 @@
--[[--
潇湘书院 HTTP 客户端(仅异步)。
搜索、分类走新站 JSON;详情走电脑官网 SSR,目录、旧榜单走移动官网(m.xxsy.net,匿名可读)。
账号、正文、书架、进度走新站 www.xxsypro.com 的 JSON 接口(阅文通行证,与起点同一套账号体系):请求带登录 Cookie
(ywGuid / ywKey 等)和同值的 csrfToken(Cookie 与 `_csrfToken` 查询参数),回包 code 0 为成功。
匿名也能调,但书架是访客书架、没买的 VIP 章只回 130 字预览(auth=false),所以带登录态的操作先用 /user/auth/personal 确认 isLogin=1。
书 / 章 id 是 17 位整数,超出 double 精度,解码前先加引号。目录页上千章、1MB+,解析放子进程。
@module koplugin.book.moonsource_xiaoxiang.client
--]]
local Job = require("workers.job")
local logger = require("utils.log")
local Mapper = require("moonsource_xiaoxiang.mapper")
local Request = require("http.request")
local Text = require("utils.text")
local _ = require("l10n").get("moonsource_xiaoxiang")
local Client = {}
--- 已保存的登录 Cookie。
---@return string|nil
function Client.cookie()
local cookie = require("utils.settings").getSource("ext.xiaoxiang").cookie
return type(cookie) == "string" and cookie ~= "" and cookie or nil
end
local UA = "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) "
.. "Version/16.0 Mobile/15E148 Safari/604.1"
---@param url string
---@param cb fun(html: string|nil, err: string|nil)
---@return HttpJob
local function page(url, cb)
return Request.get(url, {
headers = { ["User-Agent"] = UA },
timeout = require("http.timeout").net(1),
}, function(raw, err)
if not raw then cb(nil, err and tostring(err) or _("请求失败")); return end
cb(raw)
end)
end
local SOURCE_ID = "ext.xiaoxiang"
local API = "https://www.xxsypro.com/api"
--- 请求头里的 Cookie:没有 csrfToken 就补一个,网页端要求 Cookie 与 `_csrfToken` 同值。
---@param cookie string|nil
---@return string cookie
---@return string csrf
local function withCsrf(cookie)
local csrf = cookie and cookie:match("csrfToken=([^;%s]+)")
if csrf then return cookie, csrf end
csrf = "moon"
return (cookie and cookie .. "; " or "") .. "csrfToken=" .. csrf, csrf
end
--- 回包 JSON 解码(17 位 id 先加引号);code 非 0 取 msg 当错误。
---@param raw string|nil
---@param err any
---@param cb fun(wire: table|nil, err: string|nil)
local function decode(raw, err, cb)
if not raw then cb(nil, err and tostring(err) or _("请求失败")); return end
local wire, reason = Mapper.decode(raw)
if not wire then cb(nil, reason); return end
if wire.code ~= 0 then cb(nil, wire.msg and tostring(wire.msg) or _("响应无效")); return end
cb(wire)
end
--- 新站 JSON 接口;body 为 nil 发 GET,否则 POST(body 是已编码的 JSON 串)。
---@param path string
---@param query string 不含 _csrfToken
---@param body string|nil
---@param cookie string|nil
---@param cb fun(wire: table|nil, err: string|nil)
---@return HttpJob
local function call(path, query, body, cookie, cb)
local cookie_header, csrf = withCsrf(cookie)
local url = API .. path .. "?" .. (query ~= "" and query .. "&" or "") .. "_csrfToken=" .. Text.urlEncode(csrf)
local opts = {
accept = "application/json",
headers = { Referer = "https://www.xxsypro.com/", ["User-Agent"] = UA },
jar = require("http.cookie_jar").session(SOURCE_ID, cookie_header),
timeout = require("http.timeout").net(0.5),
cache_ttl = 0,
}
if body then
opts.content_type = "application/json"
return Request.post(url, body, opts, function(raw, err) decode(raw, err, cb) end)
end
return Request.get(url, opts, function(raw, err) decode(raw, err, cb) end)
end
--- 账号信息:isLogin=1 才是真登录(失效的 Cookie 仍 code 0,只是 isLogin=0)。cookie 显式传入,登录入口先校验再保存。
---@param cookie string
---@param cb fun(info: table|nil, err: string|nil, kind: "auth"|nil)
---@return HttpJob
function Client.userAsync(cookie, cb)
local cancelled = false
local job = call("/user/auth/personal", "", nil, cookie, function(wire, err)
if cancelled then return end
local data = wire and wire.data
if not wire then cb(nil, err); return end
if type(data) ~= "table" then cb(nil, _("响应无效")); return end
if tonumber(data.isLogin) == 0 then cb(nil, _("未登录潇湘"), "auth"); return end
if tonumber(data.isLogin) ~= 1 then cb(nil, _("响应无效")); return end
local guid = type(data.user) == "table" and data.user.guid
local id = type(guid) == "number" and guid % 1 == 0 and string.format("%.0f", guid) or guid
if type(id) ~= "string" or not id:match("^%d+$") or id:match("^0+$") then
cb(nil, _("潇湘账号标识缺失")); return
end
cb({ isLogin = 1, id = id })
end)
return { cancel = function()
cancelled = true
if job then job:cancel() end
end }
end
--- 同一 Cookie 校验通过后多久内不再问个人接口:每章翻页都报进度,次次先打一遍个人接口是双倍请求。
Client.AUTH_TTL = 10 * 60
---@type { cookie: string|nil, at: integer } 最近一次通过校验的 Cookie 与时刻
local verified = { cookie = nil, at = 0 }
--- 带登录态的调用:先确认 isLogin=1(AUTH_TTL 内同一 Cookie 只确认一次),失效就标记登出,免得访客书架被当成真实书架。
---@param path string
---@param query string
---@param body string|nil
---@param cb fun(wire: table|nil, err: string|nil)
---@return { cancel: fun() }
local function authed(path, query, body, cb)
local cookie = Client.cookie()
if not cookie then return require("source.base").defer(cb, nil, _("未登录潇湘")) end
local cancelled, job = false, nil
local function done(wire, err)
if cancelled then return end
if Client.cookie() ~= cookie then cb(nil, _("账号已变化,请重新登录")); return end
cb(wire, err)
end
if cookie and cookie == verified.cookie and os.time() - verified.at < Client.AUTH_TTL then
job = call(path, query, body, cookie, done)
else
local pending = true
local check = Client.userAsync(cookie, function(info, err, kind)
pending = false
if cancelled then return end
if Client.cookie() ~= cookie then done(nil); return end
if not info then
if kind == "auth" then
verified.cookie = nil
err = require("source.auth").expire(SOURCE_ID,
_("潇湘登录已失效,请点「重新登录」,用 QQ阅读或起点 App 扫码。也可在账号设置里粘贴 Cookie。"))
end
done(nil, err)
return
end
verified.cookie, verified.at = cookie, os.time()
require("source.auth").ok(SOURCE_ID)
job = call(path, query, body, cookie, done)
end)
if pending then job = check end
end
return { cancel = function()
cancelled = true
if job then job:cancel() end
end }
end
--- 书架(只收根目录的书,resType 1),翻页收齐。
---@param cb fun(rows: table[]|nil, err: string|nil)
---@return { cancel: fun() }
function Client.shelfAsync(cb)
---@type table[], boolean, CancelHandle|nil
local rows, cancelled, job = {}, false, nil
local cookie = Client.cookie()
local function more(page)
local pending = true
local request = authed("/bookshelf/pc/page", "pageIndex=" .. page .. "&pageSize=20", nil, function(wire, err)
pending = false
if cancelled then return end
if Client.cookie() ~= cookie then cb(nil, _("账号已变化,请重新登录")); return end
local data = wire and wire.data
if type(data) ~= "table" or type(data.data) ~= "table" or not tonumber(data.pageCount) then
cb(nil, err or _("响应无效")); return
end
for _idx, row in ipairs(data.data) do
if type(row) ~= "table" then cb(nil, _("响应无效")); return end
if tonumber(row.restype) == 1 and tonumber(row.groupId) == -100 then
if type(row.bookid) ~= "string" or not row.bookid:match("^%d+$") then
cb(nil, _("响应无效")); return
end
rows[#rows + 1] = row
end
end
if page < (tonumber(data.pageCount) or 0) then
more(page + 1)
return
end
cb(rows)
end)
if pending then job = request end
end
more(1)
return { cancel = function()
cancelled = true
if job then job:cancel() end
end }
end
---@param book_id string
---@return string
local function shelfBody(book_id, extra)
return '{"groupInfo":[{"groupId":-100,"books":[{"bookId":"' .. book_id .. '","resType":1' .. extra .. "}]}]}"
end
--- 成功码不够:回读根书架,确认成员或章节确实收敛后才让调用方清脏行。
local function confirmShelf(path, query, body, book_id, expected, cb)
local cancelled, job, pending = false, nil, true
local initial = authed(path, query, body, function(wire, err)
pending = false
if cancelled then return end
if not wire then cb(nil, err); return end
job = Client.shelfAsync(function(rows, reason)
if cancelled then return end
if not rows then cb(nil, reason); return end
local matched
for _idx, row in ipairs(rows) do if tostring(row.bookid) == book_id then matched = row end end
local confirmed = expected == false and not matched
or expected == true and matched ~= nil
or type(expected) == "string" and matched and tostring(matched.ccid) == expected
if not confirmed then cb(nil, _("潇湘远端状态未更新,请稍后重试")); return end
cb(wire)
end)
end)
if pending then job = initial end
return { cancel = function()
cancelled = true
if job then job:cancel() end
end }
end
---@param book_id string
---@param cb fun(wire: table|nil, err: string|nil)
---@return { cancel: fun() }
function Client.shelfAddAsync(book_id, cb)
return confirmShelf("/bookshelf/add", "",
shelfBody(book_id, ',"ccid":"0","offset":0,"updatetime":' .. os.time() * 1000), book_id, true, cb)
end
---@param book_id string
---@param cb fun(wire: table|nil, err: string|nil)
---@return { cancel: fun() }
function Client.shelfRemoveAsync(book_id, cb)
return confirmShelf("/bookshelf/delete", "", shelfBody(book_id, ""), book_id, false, cb)
end
--- 记「读到这一章」:书架行的 ccid 就是它。
---@param book_id string
---@param chapter_id string
---@param cb fun(wire: table|nil, err: string|nil)
---@return { cancel: fun() }
function Client.progressAsync(book_id, chapter_id, cb)
return confirmShelf("/bookshelf/readingProcess/add", "bookId=" .. book_id, '{"books":[{"resType":1,"bookId":"' .. book_id
.. '","updatetime":' .. os.time() * 1000 .. ',"ccid":"' .. chapter_id .. '","offset":0}]}', book_id, chapter_id, cb)
end
---@param keyword string
---@param cb fun(books: Book[]|nil, err: string|nil)
---@return { cancel: fun() }
function Client.searchAsync(keyword, cb)
return require("source.browse").pages(function(index, done)
return call("/xxsy/bookstore/web/search", "key=" .. Text.urlEncode(keyword)
.. "&start=" .. (index - 1) * 20 .. "&n=20", nil, nil, function(wire, err)
local data = wire and type(wire.data) == "table" and wire.data.searchData
if type(data) ~= "table" or not tonumber(data.total) then done(nil, err or _("响应无效")); return end
local books, reason = Mapper.books(data.cardList)
done(books, reason, index * 20 < tonumber(data.total))
end)
end, 60, {}, function(result, err)
cb(result and result.data, err)
end)
end
function Client.libraryAsync(params, index, cb)
local tag = params.tag
local filters = { tag, params.state, params.charge, params.update, params.words, params.order }
return call("/xxsy/bookstore/library/v1/web/search",
"action=" .. (tag == -1 and "category" or "tag") .. "&categoryid=" .. params.category
.. "&actionTag=" .. Text.urlEncode(table.concat(filters, ","))
.. "&start=" .. (index - 1) * 20 .. "&n=20", nil, nil, cb)
end
function Client.detailAsync(book_id, cb)
return page("https://www.xxsypro.com/book/" .. book_id, function(html, err)
if not html then cb(nil, err); return end
local book, reason = Mapper.detail(html)
if book and book.stable_id ~= book_id then cb(nil, _("响应无效")); return end
cb(book, reason)
end)
end
--- 榜单页(一页 20 本);name 是手机站 /rank/<name>。
---@param name string
---@param cb fun(books: Book[]|nil, err: string|nil)
---@param title string|nil SSR 栏目名,旧调用不传时仍解析 HTML
---@return HttpJob
function Client.rankAsync(name, cb, title)
return page("https://m.xxsy.net/rank/" .. name, function(html, err)
if not html then cb(nil, err); return end
cb(Mapper.rank(html, title))
end)
end
--- 取页面并在子进程里按 parse 解析;parse 返回 nil 以外的值都算成功。
---@param url string
---@param name string
---@param parse fun(html: string): any, string|nil
---@param cb fun(value: any, err: string|nil, kind: string|nil)
---@return { cancel: fun() }
local function parsed(url, name, parse, cb)
---@type boolean, CancelHandle|nil
local cancelled, job = false, nil
local pending = true
local request = page(url, function(html, err)
pending = false
if cancelled then return end
if not html then cb(nil, err); return end
job = Job.run(function()
local value, reason = parse(html)
return { value = value, err = reason }
end, {
name = name,
kind = "light",
timeout = 60,
on_done = function(res)
if cancelled then return end
cb(res.value, res.err)
end,
on_failed = function(reason) if not cancelled then cb(nil, tostring(reason)) end end,
on_cancelled = function() end,
})
end)
if pending then job = request end
return { cancel = function()
cancelled = true
if job then job:cancel() end
end }
end
---@param book_id string
---@param cb fun(toc: BookChapter[]|nil, err: string|nil)
---@return { cancel: fun() }
function Client.chaptersAsync(book_id, cb)
return parsed("https://m.xxsy.net/books/" .. book_id .. ".html", "xiaoxiang_toc", Mapper.toc, cb)
end
--- 一章正文(纯文本,段落以换行分隔)。免费章匿名可读;没买的 VIP 章只回预览(auth=false),报 "unpaid"。
---@param book_id string
---@param chapter_id string
---@param cb fun(text: string|nil, err: string|nil, kind: "unpaid"|nil)
---@return table handle { cancel }
function Client.contentAsync(book_id, chapter_id, cb)
local current, cancelled = nil, false
local cookie = Client.cookie()
local function done(text, err, kind)
if cancelled then return end
if Client.cookie() ~= cookie then cb(nil, _("账号已变化,请重新登录")); return end
cb(text, err, kind)
end
-- 已购 VIP 章是 Fock 加密 + 乱序字体:fkp 是 `window.onkeyfocus("<密钥池>", <版本>)` 的 base64(只取参数不执行),用户密钥是 Cookie 的 ywGuid
local function decrypt(chapter)
local keypool, version = Text.base64Decode(tostring(chapter.fkp or ""))
:match('onkeyfocus%("([^"]+)",%s*(%d+)%)')
local uid = (cookie or ""):lower():match("ywguid=(%d+)")
local font = type(chapter.fontResponse) == "table" and chapter.fontResponse or {}
if not (keypool and version and uid and type(chapter.chapterContent) == "string") then
logger.warn("xiaoxiang decrypt inputs missing: keypool", keypool ~= nil, "version", version ~= nil,
"uid", uid ~= nil, "content", type(chapter.chapterContent))
done(nil, _("潇湘章节解密失败")); return
end
local function run(fixed_font)
local pending = true
local job = require("moonsource_xiaoxiang.fock").chapterAsync(chapter, fixed_font, chapter_id, keypool, version,
uid, function(text, derr)
pending = false
if cancelled then return end
current = nil
if not text then
logger.warn("xiaoxiang fock decrypt failed:", derr)
done(nil, _("潇湘章节解密失败")); return
end
done(text)
end)
if pending then current = job end
end
if chapter.font ~= true then run(nil); return end
if type(font.fixedFontTtf) ~= "string" then
logger.warn("xiaoxiang decrypt: fixedFontTtf missing")
done(nil, _("潇湘章节解密失败")); return
end
local pending = true
local request = Request.get(font.fixedFontTtf, { timeout = require("http.timeout").net(1) }, function(ttf, ferr)
pending = false
if cancelled then return end
if Client.cookie() ~= cookie then done(nil); return end
if not ttf then done(nil, ferr and tostring(ferr) or _("请求失败")); return end
if not require("moonsource_xiaoxiang.yuewen_fonts").looksLikeFont(ttf) then
logger.warn("xiaoxiang font download invalid:", #ttf, tostring(ttf:sub(1, 16)))
done(nil, _("潇湘章节解密失败")); return
end
run(ttf)
end)
if pending then current = request end
end
local pending = true
local request = call("/book/auth/download/v2/chapters", "",
'{"cbid":"' .. book_id .. '","ccids":["' .. chapter_id .. '"]}', cookie, function(wire, err)
pending = false
if cancelled then return end
if Client.cookie() ~= cookie then done(nil); return end
if not wire then done(nil, err); return end
local contents = type(wire.data) == "table" and wire.data.chapterContents
local chapter = type(contents) == "table" and contents[1]
if type(chapter) ~= "table" or tostring(chapter.ccid) ~= chapter_id then
done(nil, _("响应无效")); return
end
local text, kind, chapter = Mapper.content(wire)
if text then done(text); return end
if kind == "encrypted" then decrypt(chapter); return end
done(nil, (not kind) and _("潇湘章节内容为空") or nil, kind --[[@as "unpaid"|nil]])
end)
if pending then current = request end
return { cancel = function()
cancelled = true
if current then current:cancel() end
end }
end
return Client
@@ -0,0 +1,59 @@
--[[--
潇湘 VIP 章节正文解密(Fock):阅文 wasm 的潇湘构建参数 + 子进程编排,宿主在 `moonsource_xiaoxiang.yuewen_fock`。
网页端用它解密 `chapterContents[].chapterContent`。
@module moonsource_xiaoxiang.fock
--]]--
local Shared = require("moonsource_xiaoxiang.yuewen_fock")
local Fock = {}
local HOST = {
["location.hostname"] = "www.xxsypro.com",
["location.protocol"] = "https:",
}
---@type YuewenFockBuild
local BUILD = {
wasm = "moonsource_xiaoxiang.fock_wasm",
callback = 22353,
stack = 5274656,
exports = { ctors = "g", main = "l", set_uid = "h", set_key = "i", decrypt = "j",
stack_save = "m", stack_restore = "n", alloc = "o", malloc = "p" },
-- 其余是反调试 / 定时器探测:返回 -1(那几个会返回 indexOf 结果)或 0
probe = function(code) return code % 709 == 151 and -1 or 0 end,
imports = function(env)
return {
f = function() return 0 end,
c = function(a, b) return env.malloc_str(HOST[env.cstr(a) .. "." .. env.cstr(b)] or "undefined") end,
e = function() return env.malloc_str("undefined") end,
}
end,
}
---@param content string base64 密文
---@param chapter_id string|number
---@param keypool string base64 密钥池(fkp 里 onkeyfocus 的第一个参数)
---@param version string
---@param uid string 用户 ywGuid
---@return string|nil text
---@return string|nil err
function Fock.decrypt(content, chapter_id, keypool, version, uid)
return Shared.decrypt(BUILD, content, chapter_id, keypool, version, uid)
end
--- 在子进程里解密并还原乱序字体,回调拿正文纯文本或错误。
---@param info table chapterContents 的一项(chapterContent、fontResponse)
---@param fixed_font string|nil fontResponse.fixedFontTtf 下载下来的字节;没有字体加密的章为 nil
---@return BookJob
function Fock.chapterAsync(info, fixed_font, chapter_id, keypool, version, uid, cb)
return Shared.jobAsync("xiaoxiang_fock", function(temp_paths)
local plain, err = Fock.decrypt(info.chapterContent, chapter_id, keypool, version, uid)
if not plain then return { err = err } end
local font = type(info.fontResponse) == "table" and info.fontResponse or {}
return { text = require("moonsource_xiaoxiang.yuewen_fonts").restore(plain, font, fixed_font, { temp_paths = temp_paths }) }
end, cb)
end
return Fock
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,52 @@
return {
["综合热度"] = "Overall popularity",
["最畅销"] = "Best sellers",
["收藏最多"] = "Most favorites",
["分类库"] = "Library categories",
["3天以内"] = "Within 3 days",
["7天以内"] = "Within 7 days",
["15天以内"] = "Within 15 days",
["一个月以内"] = "Within a month",
["20万以内"] = "Under 200k words",
["20-30万"] = "200-300k words",
["30-50万"] = "300-500k words",
["50-100万"] = "500k-1m words",
["100-200万"] = "1-2m words",
["潇湘分类条件无效"] = "Invalid Xiaoxiang library filters.",
["潇湘账号标识缺失"] = "Missing Xiaoxiang account ID.",
["潇湘远端状态未更新,请稍后重试"] = "The remote Xiaoxiang state has not updated. Please retry later.",
["切换潇湘账号会清除这台设备上潇湘的书架、阅读进度、笔记和缓存,包括尚未同步的记录。不会删除远端书架。确定继续?"] = "Switching Xiaoxiang accounts clears this device's Xiaoxiang shelf, progress, notes and cache, including unsynced records. Your remote shelf will not be deleted. Continue?",
["完结"] = "Completed",
["排行榜"] = "Rankings",
["切换账号"] = "Switch account",
["无法确认旧账号,请先退出旧账号再登录"] = "Cannot identify the previous account. Sign out before signing in again.",
["200万以上"] = "Over 2 million words",
["连载"] = "Ongoing",
["字数"] = "Word count",
["价格"] = "Price",
["免费"] = "Free",
["付费"] = "Paid",
["潇湘扫码登录"] = "Xiaoxiang QR sign-in",
["潇湘登录已失效,请点「重新登录」,用 QQ阅读或起点 App 扫码。也可在账号设置里粘贴 Cookie。"] = "Xiaoxiang sign-in has expired. Tap Sign in again and scan with QQReader or Qidian. You can also paste a Cookie in account settings.",
["未登录 · 点此扫码"] = "Not signed in · tap to scan",
["章节目录保存失败"] = "Failed to save chapter list",
["按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"] = "Press F12, open Network, refresh, and copy the entire Cookie request header",
["用 QQ阅读或起点 App 扫一扫"] = "Scan with the QQ Reader or Qidian app",
["畅销榜"] = "Bestsellers",
["阅读榜"] = "Reading chart",
["潇湘目录为空"] = "Xiaoxiang table of contents is empty",
["潇湘章节内容为空"] = "Xiaoxiang chapter is empty",
["潇湘章节解密失败"] = "Xiaoxiang chapter decryption failed",
["潇湘账号"] = "Xiaoxiang account",
["潇湘登录 Cookie"] = "Xiaoxiang login cookie",
["确定退出潇湘账号?"] = "Sign out of Xiaoxiang?",
["潇湘票榜"] = "Xiaoxiang Ticket Chart",
["完结榜"] = "Completed",
["收藏榜"] = "Favorites",
["未登录潇湘"] = "Not signed in to Xiaoxiang",
["缺少潇湘章节位置"] = "Missing Xiaoxiang chapter position",
["书架同步"] = "Shelf sync",
["搜索与发现"] = "Search and discover",
["潇湘书院书架与在线阅读"] = "Xiaoxiang shelf and online reading",
["进度同步"] = "Progress sync",
}
@@ -0,0 +1,52 @@
return {
["综合热度"] = "綜合熱度",
["最畅销"] = "最暢銷",
["收藏最多"] = "收藏最多",
["分类库"] = "分類庫",
["3天以内"] = "3天以內",
["7天以内"] = "7天以內",
["15天以内"] = "15天以內",
["一个月以内"] = "一個月以內",
["20万以内"] = "20萬以內",
["20-30万"] = "20–30萬",
["30-50万"] = "30–50萬",
["50-100万"] = "50–100萬",
["100-200万"] = "100–200萬",
["潇湘分类条件无效"] = "瀟湘分類條件無效",
["潇湘账号标识缺失"] = "瀟湘帳號識別碼缺失",
["潇湘远端状态未更新,请稍后重试"] = "瀟湘遠端狀態尚未更新,請稍後重試",
["切换潇湘账号会清除这台设备上潇湘的书架、阅读进度、笔记和缓存,包括尚未同步的记录。不会删除远端书架。确定继续?"] = "切換瀟湘帳號會清除這台裝置上瀟湘的書架、閱讀進度、筆記和快取,包括尚未同步的記錄。不會刪除遠端書架。確定繼續?",
["完结"] = "完結",
["排行榜"] = "排行榜",
["切换账号"] = "切換帳號",
["无法确认旧账号,请先退出旧账号再登录"] = "無法確認舊帳號,請先登出舊帳號再登入",
["200万以上"] = "200 萬字以上",
["连载"] = "連載",
["字数"] = "字數",
["价格"] = "價格",
["免费"] = "免費",
["付费"] = "付費",
["潇湘扫码登录"] = "瀟湘掃碼登入",
["潇湘登录已失效,请点「重新登录」,用 QQ阅读或起点 App 扫码。也可在账号设置里粘贴 Cookie。"] = "瀟湘登入已失效,請點「重新登入」,用 QQ閱讀或起點 App 掃碼。也可在帳號設定裡貼上 Cookie。",
["未登录 · 点此扫码"] = "未登入 · 點此掃碼",
["章节目录保存失败"] = "章節目錄儲存失敗",
["按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"] = "按鍵盤 F12,點「網路」,重新整理網頁,複製請求標頭裡的整段 Cookie",
["用 QQ阅读或起点 App 扫一扫"] = "用 QQ閱讀或起點 App 掃一掃",
["畅销榜"] = "暢銷榜",
["阅读榜"] = "閱讀榜",
["潇湘目录为空"] = "瀟湘目錄為空",
["潇湘章节内容为空"] = "瀟湘章節內容為空",
["潇湘章节解密失败"] = "瀟湘章節解密失敗",
["潇湘账号"] = "潇湘帳號",
["潇湘登录 Cookie"] = "潇湘登入 Cookie",
["确定退出潇湘账号?"] = "確定登出潇湘帳號?",
["潇湘票榜"] = "潇湘票榜",
["完结榜"] = "完結榜",
["收藏榜"] = "收藏榜",
["未登录潇湘"] = "未登入瀟湘",
["缺少潇湘章节位置"] = "缺少瀟湘章節位置",
["书架同步"] = "書架同步",
["搜索与发现"] = "搜尋與發現",
["潇湘书院书架与在线阅读"] = "瀟湘書院書架與線上閱讀",
["进度同步"] = "進度同步",
}
@@ -0,0 +1,5 @@
return function()
local copy = {}
for k, v in pairs(require("moonsource_xiaoxiang._meta")) do copy[k] = v end
return copy
end
@@ -0,0 +1,195 @@
--[[--
潇湘书院数据映射(纯函数):新站 JSON、官网 SSR 与旧榜单 HTML → 领域对象。
@module koplugin.book.moonsource_xiaoxiang.mapper
--]]
local JSON = require("json")
local Text = require("utils.text")
local _ = require("l10n").get("moonsource_xiaoxiang")
local Mapper = {}
local SOURCE_ID = "ext.xiaoxiang"
--- 新站 JSON 的整数身份不能经过 Lua number;不匹配小数、指数或字符串里的转义引号。
function Mapper.decode(raw)
local encoded = raw:gsub('("[%w_]+"%s*:%s*)(%d+)([,}%]%s])', function(key, value, tail)
return key .. (#value >= 16 and ('"' .. value .. '"') or value) .. tail
end)
local ok, data = pcall(JSON.decode, encoded)
if not ok or type(data) ~= "table" then return nil, _("响应无效") end
return data
end
--- 电脑与移动官网共用的 SSR 容器,只取公开页面数据。
function Mapper.state(html)
local raw = html:match('<script[^>]-id="vite%-plugin%-ssr_pageContext"[^>]*>(.-)</script>')
if not raw then return nil, _("响应无效") end
local data = Mapper.decode(raw)
local context = data and data.pageContext
local props = type(context) == "table" and context.pageProps
local page_data = type(props) == "table" and props.pageData
if type(page_data) ~= "table" then return nil, _("响应无效") end
return page_data
end
--- 分类库、搜索与详情的公开字段有两套命名,身份始终保留字符串。
function Mapper.books(rows)
if type(rows) ~= "table" then return nil, _("响应无效") end
local books = {}
for _idx, row in ipairs(rows) do
if type(row) ~= "table" then return nil, _("响应无效") end
local id, title = row.cbId or row.cbid, row.bookName or row.title
if type(id) ~= "string" or not id:match("^%d+$") or type(title) ~= "string" then
return nil, _("响应无效")
end
books[#books + 1] = {
source_id = SOURCE_ID, stable_id = id, title = Text.trim(title),
authors = Text.trim(row.authorName or row.author or ""),
category = row.cate2Name or row.catel2name or row.categoryShortName,
intro = Text.trim(row.intro or ""), words = tonumber(row.totalWords),
cover = "https://bookcover.yuewen.com/qdbimg/349573/c_" .. id .. "/180",
}
end
return books
end
function Mapper.detail(html)
local data, err = Mapper.state(html)
if not data then return nil, err end
local detail = data.detailData or data.bookInfo or data
local books, reason = Mapper.books({ detail })
return books and books[1], reason
end
--- 手机站榜单 SSR 中按栏目名选当前榜单;兼容旧 HTML。
---@param html string
---@param title string|nil
---@return Book[]|nil
---@return string|nil
function Mapper.rank(html, title)
if title and html:find('id="vite-plugin-ssr_pageContext"', 1, true) then
local data, err = Mapper.state(html)
if not data then return nil, err end
for _idx, section in ipairs(data) do
if type(section) ~= "table" then return nil, _("响应无效") end
local info = section.columnInfo
if type(info) == "table" and info.name == title then return Mapper.books(section.bookList) end
end
return nil, _("响应无效")
end
local out = {}
for id, item in html:gmatch('<a href="/book/(%d+)"[^>]*data%-bookid=.-(<div class="common%-img".-)</a>') do
local title = item:match('class="book%-title"[^>]*>([^<]*)<')
if title then
local module = item:match('class="book%-module"[^>]*>(.-)</p>') or ""
local cover = item:match('<img src="([^"]*)"')
out[#out + 1] = {
source_id = SOURCE_ID,
stable_id = id,
title = Text.xmlDecode(title),
authors = Text.trim(Text.xmlDecode(module:match("^([^<]*)") or "")),
intro = Text.trim(Text.xmlDecode(item:match('class="book%-profile"[^>]*>([^<]*)<') or "")),
cover = cover and (cover:gsub("^//", "https://")),
}
end
end
if #out == 0 then return nil, _("响应无效") end
return out
end
--- 目录缓存格式版本。
Mapper.TOC_VERSION = 1
--- 手机站目录页 → 目录。页面内嵌 SSR JSON,`"chapters":[` 之后是扁平对象:type 0 是卷,type 1 是章(price > 0 为 VIP)。
---@param html string
---@return BookChapter[]|nil
---@return string|nil
function Mapper.toc(html)
local toc = {}
local rows
if html:find('id="vite-plugin-ssr_pageContext"', 1, true) then
local data, err = Mapper.state(html)
if not data then return nil, err end
rows = data.chapters or data.chapterListData
else
local raw = html:match('"chapters":%s*(%b[])')
rows = raw and Mapper.decode('{"rows":' .. raw .. "}")
rows = rows and rows.rows
end
if type(rows) ~= "table" then return nil, _("响应无效") end
for _idx, row in ipairs(rows) do
if type(row) ~= "table" or (row.type ~= 0 and row.type ~= 1) then return nil, _("响应无效") end
if row.type == 1 then
if type(row.ccid) ~= "string" or not row.ccid:match("^%d+$") or type(row.title) ~= "string" then
return nil, _("响应无效")
end
toc[#toc + 1] = {
idx = #toc + 1,
uid = row.ccid,
title = row.title,
vip = (tonumber(row.price) or 0) > 0 or nil,
}
end
end
if toc[1] then toc[1].toc_version = Mapper.TOC_VERSION end
return toc
end
--- 章节接口回包 → 正文纯文本。没买的 VIP 章(价格 > 0 且 auth 不为真)只有 130 字预览,返回 nil, "unpaid"。
--- 正文段落以 \r\n 分隔、每段前有全角缩进。
---@param wire table
---@return string|nil text
---@return "unpaid"|"encrypted"|nil kind
---@return table|nil encrypted
function Mapper.content(wire)
local chapters = type(wire.data) == "table" and wire.data.chapterContents
local chapter = chapters and chapters[1]
if type(chapter) ~= "table" then return nil end
local price = tonumber(chapter.chapterPrice)
if not price then return nil end
if price > 0 and chapter.auth ~= true then return nil, "unpaid" end
if chapter.encrypt == true then return nil, "encrypted", chapter end
if type(chapter.chapterContent) ~= "string" then return nil end
local lines = {}
for line in chapter.chapterContent:gmatch("[^\r\n]+") do
line = Text.trim(line)
while line:sub(1, 3) == "\227\128\128" do line = Text.trim(line:sub(4)) end
if line ~= "" then lines[#lines + 1] = line end
end
if #lines == 0 then return nil end
return table.concat(lines, "\n")
end
--- 书架行 → Book[]。封面按书 id 拼(书架接口不给)。
---@param rows table[]
---@return Book[]
function Mapper.shelfList(rows)
local out = {}
for _idx, row in ipairs(rows) do
local id = tostring(row.bookid)
out[#out + 1] = {
source_id = SOURCE_ID,
stable_id = id,
title = Text.trim(row.title or ""),
authors = Text.trim(row.author or ""),
cover = "https://bookcover.yuewen.com/qdbimg/349573/c_" .. id .. "/180",
}
end
return out
end
--- 书架行 → 书 id → 最近读到的章 id(ccid 为 "0" 表示没读过)。
---@param rows table[]
---@return table<string, string>
function Mapper.progress(rows)
local out = {}
for _idx, row in ipairs(rows) do
local ccid = tostring(row.ccid or "0")
if ccid ~= "0" then out[tostring(row.bookid)] = ccid end
end
return out
end
return Mapper
@@ -0,0 +1,92 @@
--[[--
潇湘源设置:登录。
潇湘新站 www.xxsypro.com 使用阅文通行证:设备上展示 App 扫码,保留浏览器扩展与手动 Cookie 导入。
拿到 Cookie 先用 personal 接口的 data.isLogin 校验,通过才保存。
@module koplugin.book.moonsource_xiaoxiang.setting
--]]
local _ = require("l10n").get("moonsource_xiaoxiang")
local CookieLogin = require("source.cookie_login")
local SOURCE_ID = "ext.xiaoxiang"
local Setting = {}
---@return boolean
local function loggedIn()
return require("moonsource_xiaoxiang.client").cookie() ~= nil
end
local function commit(cookie, account, cb, current)
if not account or type(account.id) ~= "string" or not account.id:match("^%d+$") then
cb(false, _("潇湘账号标识缺失")); return
end
return CookieLogin.commitAccount(SOURCE_ID, cookie, account.id, cb, current)
end
---@type CookieLoginSpec
local SPEC = {
id = SOURCE_ID,
title = _("潇湘账号"),
cookie_title = _("潇湘登录 Cookie"),
cookie_hint = _("按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"),
logout_text = _("确定退出潇湘账号?"),
loggedIn = loggedIn,
checkAsync = function(cookie, cb)
local Client = require("moonsource_xiaoxiang.client")
local previous = Client.cookie()
return Client.userAsync(cookie, function(info, err)
if Client.cookie() ~= previous then cb(false, _("账号已变化,请重新登录")); return end
cb(info ~= nil, err, info)
end)
end,
commit = commit,
clear = function(cfg) cfg.cookie, cfg.account_id = nil, nil end,
}
---@return string, boolean
function Setting.rowStatus()
local on = loggedIn()
return on and _("已登录") or _("未登录 · 点此登录"), on
end
Setting.parseCookie = CookieLogin.parse
--- 浏览器扩展登录(features/cookie)。personal 接口一律 code 0,靠 data.isLogin 判登录。
Setting.browser = {
domain = "www.xxsypro.com",
scope = "cookie",
login = "https://www.xxsypro.com/",
check = "https://www.xxsypro.com/api/user/auth/personal",
check_json = { path = "data.isLogin", ok = { 1 } },
icon = "https://www.xxsypro.com/favicon.ico",
isAuthorized = function() return CookieLogin.authorized(SPEC) end,
apply = function(payload, cb) return CookieLogin.save(SPEC, CookieLogin.fromPayload(payload, "xxsypro.com"), cb) end,
}
local function startQR()
require("ui/network/manager"):runWhenConnected(function()
require("moonsource_xiaoxiang.yuewen_qr"):new({
app_id = "57", area_id = "5", return_url = "https://www.xxsypro.com/",
referer = "https://passport.yuewen.com/yuewen.html",
title = _("潇湘扫码登录"), caption = _("用 QQ阅读或起点 App 扫一扫"),
}, function(cookie) CookieLogin.verify(SPEC, cookie) end):start()
end)
end
---@return table[]
function Setting.rows()
local rows = {
CookieLogin.accountRow(SPEC, { callback = startQR, off_text = _("未登录 · 点此扫码") }),
CookieLogin.browserRow(),
CookieLogin.pasteRow(SPEC),
}
if loggedIn() then rows[#rows + 1] = CookieLogin.logoutRow(SPEC) end
return rows
end
--- 登录失效提示的「重新登录」直达入口(desktop.sync.promptLogin)。
Setting.login = startQR
return Setting
@@ -0,0 +1,219 @@
--[[--
潇湘书院数据源。
分类、搜索、账号、正文、书架、进度走新站 JSON;详情、目录、旧榜单走电脑/移动官网 SSR(client.lua)。
登录态是新站 Cookie(阅文通行证):App 扫码、浏览器扩展授权,或粘贴 Cookie(setting.lua)。
书架双向同步(Shelf.syncAsync),进度按章:读书架行的 ccid,写 readingProcess/add。没买的 VIP 章开章给临时提示页,目录标「未购」。
@module moonsource_xiaoxiang
--]]
local Client = require("moonsource_xiaoxiang.client")
local Mapper = require("moonsource_xiaoxiang.mapper")
local SourceBase = require("source.base")
local Browse = require("source.browse")
local Shelf = require("source.shelf")
local Toc = require("source.toc")
local _ = require("l10n").get("moonsource_xiaoxiang")
local Xiaoxiang = {}
-- 接口按 IP 限流,预取与整本缓存逐章间隔请求。
local FETCH_INTERVAL = 1
---@return BookSourceMeta
function Xiaoxiang.meta()
return require("moonsource_xiaoxiang.loadmeta")()
end
---@class XiaoxiangSource : SourceBase
local Source = setmetatable({ shelf_add = true }, { __index = SourceBase })
Source.__index = Source
---@return XiaoxiangSource
function Xiaoxiang.new()
local meta = Xiaoxiang.meta()
return setmetatable({ id = meta.id, name = meta.name, type = meta.type }, Source)
end
--- 搜索 / 目录 / 榜单匿名可用,书架、进度和已购 VIP 章要登录 Cookie。
---@return boolean
function Source:configured()
return Client.cookie() ~= nil
end
--- 书架远端:Shelf.syncAsync 要的三个冒号方法。
local Remote = {}
function Remote:shelfSyncAsync(cb) return Client.shelfAsync(cb) end
function Remote:addToShelfAsync(stable_id, cb) return Client.shelfAddAsync(stable_id, cb) end
function Remote:removeFromShelfAsync(stable_id, cb) return Client.shelfRemoveAsync(stable_id, cb) end
function Source:syncBooksAsync(opts, cb)
if not self:configured() then return SourceBase.skipped(cb, "xiaoxiang not logged in") end
return Shelf.syncAsync(self.id, Remote, Mapper.shelfList, opts, cb)
end
--- 进度只到章:读书架行里这本书最近读到的章(ccid)。
function Source:getProgressAsync(identity, cb)
if not self:configured() then return SourceBase.defer(cb, nil, _("未登录潇湘")) end
local cookie = Client.cookie()
local cancelled, job = false, nil
local pending = true
local initial = Client.shelfAsync(function(rows, err)
pending = false
if cancelled then return end
if Client.cookie() ~= cookie then cb(nil, _("账号已变化,请重新登录")); return end
if not rows then cb(nil, err); return end
local uid = Mapper.progress(rows)[tostring(identity.stable_id)]
if not uid then cb(nil, nil, { empty = true }); return end
job = self:loadTocAsync(identity, function(toc, reason)
if cancelled then return end
if Client.cookie() ~= cookie then cb(nil, _("账号已变化,请重新登录")); return end
if not toc or #toc == 0 then cb(nil, reason or _("潇湘目录为空")); return end
local idx = Toc.index(self.id, identity.stable_id, uid)
if not idx then cb(nil, nil, { empty = true }); return end
cb({
chapter_idx = idx,
chapter_title = toc[idx].title,
fraction = (idx - 1) / #toc,
extra = { chapter_uid = uid, chapter_idx = idx },
})
end)
end)
if pending then job = initial end
return { cancel = function()
cancelled = true
if job and job.cancel then job.cancel() end
end }
end
function Source:putProgressAsync(identity, pos, cb)
if not self:configured() then return SourceBase.defer(cb, nil, _("未登录潇湘")) end
local cookie = Client.cookie()
local cancelled, job = false, nil
local pending = true
local initial = self:loadTocAsync(identity, function(toc, err)
pending = false
if cancelled then return end
if Client.cookie() ~= cookie then cb(nil, _("账号已变化,请重新登录")); return end
if not toc then cb(nil, err); return end
local idx = tonumber(pos.chapter_idx) or tonumber(identity.chapter_idx)
local chapter = idx and toc[idx]
if not chapter then cb(nil, _("缺少潇湘章节位置")); return end
job = Client.progressAsync(identity.stable_id, chapter.uid, function(wire, perr)
if not cancelled then cb(wire and true, perr) end
end)
end)
if pending then job = initial end
return { cancel = function()
cancelled = true
if job and job.cancel then job.cancel() end
end }
end
---@param keyword string
---@param cb fun(res: { data: Book[] }|nil, err: string|nil)
---@return { cancel: fun() }|nil
function Source:searchAsync(keyword, cb)
return Client.searchAsync(keyword, function(books, err)
if not books then
cb(nil, err)
return
end
cb({ data = books })
end)
end
-- 手机站 /rank/<id> 的榜单,顺序同网页。
local RANKS = {
{ id = "xxyuepiao", title = "潇湘票榜" },
{ id = "bestsales", title = "畅销榜" },
{ id = "finish", title = "完结榜" },
{ id = "reading", title = "阅读榜" },
{ id = "collections", title = "收藏榜" },
}
---@param opts { node?: string, limit?: integer }
---@param cb fun(res: { data: Book[], groups: StoreChipGroup[] }|nil, err: string|nil)
---@return { cancel: fun() }
function Source:browseAsync(opts, cb)
opts = opts or {}
local legacy = opts.node == "rank"
for _idx, row in ipairs(RANKS) do if row.id == opts.node then legacy = true end end
if not legacy then return require("moonsource_xiaoxiang.browse").run(opts, cb) end
local rank = RANKS[1]
for _idx, row in ipairs(RANKS) do
if row.id == opts.node then rank = row end
end
local chips = {}
for _idx, row in ipairs(RANKS) do chips[#chips + 1] = { id = row.id, title = _(row.title) } end
local groups = { Browse.group(chips, rank.id) }
groups[1].title = _("排行榜")
groups[1].chips[#groups[1].chips + 1] = { id = "cate:-1:-1:-1:-1:10:0:-1", title = _("分类库") }
return Client.rankAsync(rank.id, function(books, err)
if not books then cb(nil, err); return end
if opts.limit then for index = #books, opts.limit + 1, -1 do books[index] = nil end end
cb({ data = books, groups = groups })
end, rank.title)
end
function Source:getDetailAsync(identity, cb)
return Client.detailAsync(identity.stable_id, cb)
end
--- 强制拉目录并写回;失败由调用方继续用旧缓存。
---@param identity BookIdentity
---@param cb fun(toc: BookChapter[]|nil, err: string|nil)
---@return { cancel: fun() }|nil
local function fetchTocAsync(self, identity, cb)
return Client.chaptersAsync(identity.stable_id, function(toc, err)
if not toc then cb(nil, err); return end
if #toc == 0 then cb(nil, _("潇湘目录为空")); return end
if not Toc.put(self.id, identity.stable_id, toc) then cb(nil, _("章节目录保存失败")); return end
cb(toc)
end)
end
---@param identity BookIdentity
---@param cb fun(toc: BookChapter[]|nil, err: string|nil)
---@param force boolean|nil 真=跳过缓存强制拉
---@return { cancel: fun() }|nil
function Source:loadTocAsync(identity, cb, force)
if not force then
local cached = Toc.read(self.id, identity.stable_id)
if cached and #cached > 0 and cached[1].toc_version == Mapper.TOC_VERSION then
return SourceBase.defer(cb, cached)
end
end
return fetchTocAsync(self, identity, cb)
end
Source.refreshTocAsync = fetchTocAsync
function Source:openBookAsync(identity, opts, cb)
local Chapter = require("source.chapter")
local open = opts and opts.chapter_idx and Chapter.openAsync or Chapter.openWithUi
return open(self, identity, identity.book, opts, {
loadToc = function(ref, done) return self:loadTocAsync(ref, done) end,
fetchContent = Chapter.vipFetcher(self, Client.contentAsync, true),
}, cb)
end
function Source:prefetchChaptersAsync(identity, toc, from_idx, count, cb)
local Chapter = require("source.chapter")
return Chapter.prefetchAsync(identity, identity.book, toc, from_idx, count, {
fetchContent = Chapter.vipFetcher(self, Client.contentAsync, false),
interval_seconds = FETCH_INTERVAL,
}, cb)
end
function Source:cacheAllChaptersAsync(identity, on_progress, cb, range)
local Chapter = require("source.chapter")
return Chapter.cacheAllAsync(self, identity, Chapter.vipFetcher(self, Client.contentAsync, false), on_progress, cb,
FETCH_INTERVAL, range)
end
return Xiaoxiang
@@ -0,0 +1,174 @@
--[[--
阅文系(起点 / QQ阅读 / 潇湘)Fock 章节解密的公共宿主。
三家网页端用同一段反盗版 wasm(经 wasm2js 成 asm.js)解密正文,只是各自一个构建:导出名、回调码、栈基址、
宿主探测字符串不同。`tools/gen_fock.js` 把每个构建转译成 `source/<id>/fock_wasm.lua`,本模块提供它们共用的
内存、导入函数与调用顺序(ctors + main,再 set_uid → set_key → decrypt,结果经导入 b 的回调码交回:
三个 int:状态、明文指针、明文长度),源只在 `YuewenFockBuild` 表里填自己那份差异。
解密要 16MB 内存且纯 Lua 解释执行,在主进程做会拖慢 UI、抬高 KOReader 内存峰值(设备上可被系统杀掉重启),
`Fock.jobAsync` 把它放进 fork 子进程,主进程只收结果;转译出的巨型函数会让 ARM 上的 LuaJIT 编译器段错误,
`decrypt` 期间关掉 JIT,完事开回来(之后的字形比对要靠它)。
@module moonsource_xiaoxiang.yuewen_fock
--]]--
local ffi = require("ffi")
local Job = require("workers.job")
local Text = require("utils.text")
---@class YuewenFockBuild
---@field wasm string 转译产物模块名(`source.<id>.fock_wasm`)
---@field callback integer 导入 b 交回解密结果的回调码
---@field stack integer set_stack 的栈基址
---@field exports { ctors: string, main: string, set_uid: string, set_key: string, decrypt: string, stack_save: string, stack_restore: string, alloc: string, malloc: string } 导出名
---@field probe fun(code: integer): integer 导入 b 收到非回调码(反调试 / 定时器探测)时的返回值
---@field imports fun(env: YuewenFockEnv): table<string, function> 构建特有的导入(宿主字符串探测 c / e / f)
---@class YuewenFockEnv
---@field mem ffi.cdata* 线性内存
---@field cstr fun(ptr: integer): string 读内存里的 C 字符串
---@field malloc_str fun(s: string): integer 用导出 malloc 放一个 C 字符串,返回指针
local Fock = {}
local MEM_SIZE = 16 * 1024 * 1024
local factories = {}
--- `Fock.decrypt` 的本体,不碰 JIT 开关。
---@param build YuewenFockBuild
---@return string|nil text
---@return string|nil err
local function run(build, content, chapter_id, keypool, version, uid)
local factory = factories[build.wasm]
if not factory then
factory = require(build.wasm)
factories[build.wasm] = factory
end
local names = build.exports
local mem = ffi.new("uint8_t[?]", MEM_SIZE)
local i32 = ffi.cast("int32_t*", mem)
local result, exp
local function cstr(ptr)
local stop = ptr
while mem[stop] ~= 0 do stop = stop + 1 end
return ffi.string(mem + ptr, stop - ptr)
end
local function malloc_str(s)
local ptr = exp[names.malloc](#s + 1)
ffi.copy(mem + ptr, s, #s)
mem[ptr + #s] = 0
return ptr
end
local imp = build.imports({ mem = mem, cstr = cstr, malloc_str = malloc_str })
imp.abort = function() error("fock abort") end
imp.d = function(ptr)
local now = os.time()
if ptr ~= 0 then i32[ptr / 4] = now end
return now
end
imp.b = function(code, _sig, argptr)
if code == build.callback then
local args = argptr / 4
result = { i32[args], i32[args + 1], i32[args + 2] }
return 0
end
return build.probe(code)
end
local data, set_stack
exp, data, set_stack = factory({ mem = mem, imp = imp })
for _idx, seg in ipairs(data) do
local bytes = Text.base64Decode(seg[2])
ffi.copy(mem + seg[1], bytes, #bytes)
end
set_stack(build.stack)
local function with_stack(fn)
local sp = exp[names.stack_save]()
local ok, err = pcall(fn)
exp[names.stack_restore](sp)
if not ok then error(err, 0) end
end
local function put_bytes(s)
local ptr = exp[names.alloc](#s)
ffi.copy(mem + ptr, s, #s)
return ptr
end
local function put_string(s)
local ptr = exp[names.alloc](#s + 1)
ffi.copy(mem + ptr, s, #s)
mem[ptr + #s] = 0
return ptr
end
local ok, err = pcall(function()
exp[names.ctors]()
exp[names.main](0, 0)
with_stack(function()
exp[names.set_uid](put_bytes(uid), #uid)
end)
local pool = Text.base64Decode(keypool)
with_stack(function()
exp[names.set_key](put_bytes(pool), #pool, put_string(version))
end)
local cipher = Text.base64Decode(content)
local cid = tostring(chapter_id)
with_stack(function()
exp[names.decrypt](put_bytes(cipher), #cipher, put_bytes(cid), #cid)
end)
end)
if not ok then return nil, tostring(err) end
if not result then return nil, "no result" end
if result[1] ~= 0 then return nil, "code " .. result[1] end
return ffi.string(mem + result[2], result[3])
end
---@param build YuewenFockBuild
---@param content string base64 密文
---@param chapter_id string|number
---@param keypool string base64 密钥池(fkp 里 onkeyfocus 的第一个参数)
---@param version string
---@param uid string 用户标识(ywguid / fuid)
---@return string|nil text
---@return string|nil err
function Fock.decrypt(build, content, chapter_id, keypool, version, uid)
local jit_was_on = jit.status()
jit.off()
local text, err = run(build, content, chapter_id, keypool, version, uid)
if jit_was_on then jit.on() end
return text, err
end
--- 在子进程里跑 worker(解密 / 字体还原),结果 `{ text, err }` 经 cb(text, err) 交回主进程。
---@param name string 任务名(日志)
---@param worker fun(temp_paths: string[]): { text: string|nil, err: string|nil }
---@param cb fun(text: string|nil, err: string|nil)
---@return BookJob
function Fock.jobAsync(name, worker, cb)
local Paths = require("utils.paths")
local temp_paths = { Paths.tmpname(".font"), Paths.tmpname(".font") }
local job
local function cleanup()
-- SIGKILL 后仍可能在内核里完成创建文件,等子进程退出再收尾。
if job and job.pid and not require("ffi/util").isSubProcessDone(job.pid) then
require("ui/uimanager"):scheduleIn(job.poll, cleanup)
return
end
for _idx, path in ipairs(temp_paths) do os.remove(path) end
end
job = Job.run(function() return worker(temp_paths) end, {
name = name,
kind = "light",
timeout = 600,
on_done = function(res) cleanup(); cb(res.text, res.err) end,
on_failed = function(err) cleanup(); cb(nil, tostring(err)) end,
on_cancelled = cleanup,
})
return job
end
return Fock
@@ -0,0 +1,201 @@
--[[--
阅文系 VIP 章节的乱序字体还原(QQ阅读 / 起点共用)。
Fock 解出的 HTML 里,常用字码位被换成别的字,靠随章下发的 fixedFont 画回真字;
扩展 A 区的生僻码位再靠 randomFont + CSS 排序/伪元素还原。这里把
`utils.glyph` 的字形识别和 `moonsource_xiaoxiang.yuewen_fonts.scramble` 的 HTML 解析拼起来。
字体是随章下发的,写临时文件给 FreeType 读;参考字签名会落盘缓存。
@module moonsource_xiaoxiang.yuewen_fonts
--]]--
local Text = require("utils.text")
local FontRestore = {}
local RARE_LIMIT, FIXED_LIMIT = 6763, 3755
--- 下载回来的字节是不是字体文件(TTF / OTF / TTC / WOFF 魔数)。CDN 的 HTML 错误页也会 200 回来,
--- 写进缓存会被当字体复用,一章章都解不出来。
---@param bytes string|nil
---@return boolean
function FontRestore.looksLikeFont(bytes)
if type(bytes) ~= "string" or #bytes < 4 then return false end
local head = bytes:sub(1, 4)
return head == "\0\1\0\0" or head == "OTTO" or head == "true" or head == "ttcf" or head == "wOFF"
end
local function writeTemp(bytes, path)
local file = assert(io.open(path, "wb"))
local ok, err = file:write(bytes)
local closed, close_err = file:close()
assert(ok, err)
assert(closed, close_err)
end
local function randomFontBytes(font)
local parts = {}
for idx, byte in ipairs(font and font.data or {}) do parts[idx] = string.char(byte) end
return table.concat(parts)
end
--- 乱序码位 / 互换字形 → 真字。
---@param random_font table|nil fontResponse.randomFont({data={...}})
---@param fixed_font string fixedFontTtf/woff2 下载下来的字节
---@param rare integer[] 扩展 A 区码位
---@param han integer[] 常用汉字码位
---@param opts table { threshold=number, temp_paths=string[]|nil }
---@return table rare_map
---@return table han_map
local function recognize(random_font, fixed_font, rare, han, opts)
local rare_bytes = randomFontBytes(random_font)
local paths, labels, tasks = {}, {}, {}
local function cleanup()
for _idx, path in ipairs(paths) do os.remove(path) end
end
if #rare > 0 and #rare_bytes > 0 then
paths[#paths + 1] = opts.temp_paths and opts.temp_paths[1] or require("utils.paths").tmpname(".font")
writeTemp(rare_bytes, paths[#paths])
labels[#labels + 1] = "rare"
tasks[#tasks + 1] = {
font_path = paths[#paths], codes = rare, limit = RARE_LIMIT, threshold = opts and opts.threshold,
}
end
if #han > 0 and fixed_font and #fixed_font > 0 then
paths[#paths + 1] = opts.temp_paths and opts.temp_paths[2] or require("utils.paths").tmpname(".font")
writeTemp(fixed_font, paths[#paths])
labels[#labels + 1] = "han"
tasks[#tasks + 1] = {
font_path = paths[#paths], codes = han, limit = FIXED_LIMIT, threshold = opts and opts.threshold,
}
end
if #tasks == 0 then return {}, {} end
local ref = require("fontlist").fontdir .. "/noto/NotoSansCJKsc-Regular.otf"
local ref_file, ref_err = io.open(ref, "rb")
if not ref_file then cleanup(); error(ref_err, 0) end
local ref_size = ref_file:seek("end")
ref_file:close()
-- 签名只取决于参考字体和算法参数;参考字体换了(大小变)自动重算。
-- 兼容旧版缓存名(qqreader_glyph_v1_ / glyph_v1_),避免重新渲染 6763 个参考字。
local cache_dir = require("utils.paths").cacheDir()
local cache = cache_dir .. "/yuewen_glyph_v1_" .. ref_size .. ".bin"
for _idx, legacy in ipairs({ "yuewen_glyph_v1_", "qqreader_glyph_v1_", "glyph_v1_" }) do
local path = cache_dir .. "/" .. legacy .. ref_size .. ".bin"
local f = io.open(path, "rb")
if f then
f:close()
cache = path
break
end
end
local ok, maps = pcall(require("utils.glyph").recognize, ref, cache, tasks)
cleanup()
if not ok then error(maps, 0) end
local rare_map, han_map = {}, {}
for idx, label in ipairs(labels) do
if label == "rare" then rare_map = maps[idx] else han_map = maps[idx] end
end
return rare_map, han_map
end
local function utf8len(text)
return #Text.chars(text)
end
local DECOY_SIMILARITY = 0.8
local chars = Text.chars
--- 起点 cES=2 的正文会把同一章再追加一份改了几个字的诱饵副本。
--- 前后两半段落字数一一对应、且逐字位置上 ≥80% 相同才丢后一半,避免把真实的对称段落误删。
---@param paragraphs string[]
---@return string[]
local function dropDecoyHalf(paragraphs)
local n = #paragraphs
if n < 4 or n % 2 ~= 0 then return paragraphs end
local half = n / 2
local same, total = 0, 0
for i = 1, half do
local a, b = chars(paragraphs[i]), chars(paragraphs[i + half])
if #a ~= #b then return paragraphs end
for k = 1, #a do
if a[k] == b[k] then same = same + 1 end
end
total = total + #a
end
if total == 0 or same / total < DECOY_SIMILARITY then return paragraphs end
for i = n, half + 1, -1 do paragraphs[i] = nil end
return paragraphs
end
local fixConfusions
--- 解出的 HTML 段落还原成纯文本。
---@param plain string Fock 解出的正文
---@param font table { css=string, randomFont=table|nil }
---@param fixed_font string|nil fixedFont 下载下来的字节;没有字体加密的章为 nil
---@param opts table|nil { dedupe=boolean, confusions=boolean, threshold=number, temp_paths=string[]|nil }
---@return string
function FontRestore.restore(plain, font, fixed_font, opts)
opts = opts or {}
local Scramble = require("moonsource_xiaoxiang.yuewen_fonts.scramble")
local paragraphs = Scramble.paragraphs(plain, font.css or "")
if #paragraphs == 0 then return plain end
if opts.dedupe then paragraphs = dropDecoyHalf(paragraphs) end
local rare, han = Scramble.codes(paragraphs)
local rare_map, han_map = {}, {}
if #rare + #han > 0 then
rare_map, han_map = recognize(font.randomFont, fixed_font, rare, han, opts)
end
local text = Scramble.text(paragraphs, rare_map, han_map)
if opts.confusions then text = fixConfusions(text) end
return text
end
FontRestore.dropDecoyHalf = dropDecoyHalf
-- 起点 fixedFont 里 于/干、责/贵 两组字形太近,16x16 相关度会把“关于/终于/负责”
-- 认成“关干/终干/负贵”。只修这些固定搭配;“对干部/在干活”这类保留干。
local YU_PREFIX = {
["关"] = true, ["终"] = true, ["对"] = true, ["等"] = true, ["至"] = true,
["由"] = true, ["属"] = true, ["便"] = true, ["利"] = true, ["善"] = true,
["敢"] = true, ["勇"] = true, ["难"] = true, ["易"] = true, ["在"] = true,
["位"] = true, ["鉴"] = true,
}
local YU_KEEP_NEXT = {
["部"] = true, ["活"] = true, ["事"] = true, ["劲"] = true, ["什"] = true, ["嘛"] = true, ["啥"] = true,
["吗"] = true, ["吧"] = true, ["净"] = true, ["脆"] = true, ["燥"] = true, ["旱"] = true, ["扰"] = true,
["预"] = true, ["练"] = true, ["掉"] = true, ["架"] = true, ["涸"] = true,
}
local ZE_PREFIX = { ["职"] = true, ["担"] = true, ["负"] = true, ["责"] = true, ["贵"] = true }
-- 少数整词在 fixedFont 里稳定认错(“泮”几乎只出现在“泮池”,不会误伤正文)。
local TEXT_FIXES = {
["同泮"] = "同伴",
["泮随"] = "伴随",
["聚干"] = "聚于",
}
--- 修正两类固定形近字;只在起点字体层启用。
--- Lua 的字符类是字节级,不能直接拿“部/活”做 [^...],这里按 UTF-8 单字扫描。
---@param text string
---@return string
fixConfusions = function(text)
local list = Text.chars(text)
for i = 2, #list do
local ch, prev, nxt = list[i], list[i - 1], list[i + 1]
if ch == "干" and YU_PREFIX[prev] and not (nxt and YU_KEEP_NEXT[nxt]) then
list[i] = "于"
elseif ch == "贵" and (ZE_PREFIX[prev] or nxt == "任") then
list[i] = "责"
end
end
local fixed = table.concat(list)
for from, to in pairs(TEXT_FIXES) do fixed = fixed:gsub(from, to) end
return fixed
end
FontRestore.fixConfusions = fixConfusions
return FontRestore
@@ -0,0 +1,162 @@
--[[--
QQ阅读正文乱序还原:Fock 解出的是带反爬样式的 HTML,真正的字序和字形要靠随章下发的 CSS 才能还原。
- 有 `pN` 类的段落,子元素 `<yXX>` 按 `yXX{order:n}` 重排(网页是 flex 容器),每个元素再按
`.pN yXX::first-letter{font-size:0}`(藏掉原字)与 `::before` / `::after` 的 `content`(字面量或 `attr(x)`)还原;
- `<y class="sy-0">` 是 `font-size:0` 的占位,丢弃;`sy-1` 只是镜像显示,文字照留;
- 其余码位落在 CJK 扩展 A 的字,是 randomFont 画出来的真字,由 `glyph.lua` 认出,这里只负责替换。
@module moonsource_xiaoxiang.yuewen_fonts.scramble
--]]--
local Glyph = require("utils.glyph")
local Scramble = {}
local CHAR = require("utils.text").UTF8_CHAR
local UNKNOWN = "□"
local LOW, HIGH = 0x3400, 0x4DBF
local function expand(css)
return (css:gsub("TS%-1", "transform:scaleX(-1)"):gsub("::B", "::before"):gsub("::A", "::after")
:gsub("{O:", "{order:"):gsub("{C:", "{content:"):gsub("'''", "'\\''"))
end
--- content 值:'x' / "x" 字面量或 attr(name)。
local function contentOf(body, attrs)
local value = body:match("content:%s*(.-)%s*;?%s*$")
if not value then return nil end
local name = value:match("^attr%(([%w_-]+)%)$")
if name then return attrs[name] or "" end
return value:match("^'(.*)'$") or value:match('^"(.*)"$') or ""
end
--- 解析 CSS:order[tag] 与 rules[class .. " " .. tag][self|first-letter|before|after] = body。
local function parse(css)
local order, rules = {}, {}
for sel, body in expand(css):gmatch("([^{}]+){([^}]*)}") do
sel = sel:match("^%s*(.-)%s*$")
local tag, n = sel:match("^(y[%w_-]*)$"), body:match("^order:(%d+)")
if tag and n then
order[tag] = tonumber(n)
else
local key, pseudo = sel:match("^%.(p%d+ y[%w_-]*)::([%a-]+)$")
if not key then key, pseudo = sel:match("^%.(p%d+ y[%w_-]*)$"), "self" end
if key then
rules[key] = rules[key] or {}
rules[key][pseudo] = body
end
end
end
return order, rules
end
local function attributes(raw)
local attrs = {}
for name, value in raw:gmatch('([%w_-]+)="([^"]*)"') do attrs[name] = value end
return attrs
end
local function dropFirst(text)
return (text:gsub("^" .. CHAR, "", 1))
end
local function unescape(text)
return (text:gsub("&lt;", "<"):gsub("&gt;", ">"):gsub("&quot;", '"'):gsub("&#39;", "'"):gsub("&amp;", "&"))
end
local function scrambled(cls, children, order, rules)
for idx, child in ipairs(children) do child.idx = idx end
table.sort(children, function(a, b)
local oa, ob = order[a.tag] or math.huge, order[b.tag] or math.huge
if oa ~= ob then return oa < ob end
return a.idx < b.idx
end)
local out = {}
for _idx, child in ipairs(children) do
local rule = rules[cls .. " " .. child.tag] or {}
local attrs = attributes(child.attrs)
local text = child.text
if rule["first-letter"] and rule["first-letter"]:find("font%-size:%s*0") then text = dropFirst(text) end
out[#out + 1] = (rule.before and contentOf(rule.before, attrs) or "") .. text
.. (rule.after and contentOf(rule.after, attrs) or "")
end
return table.concat(out)
end
--- 还原一章的段落文本(字形码位还没替换)。
---@param html string Fock 明文
---@param css string 章节下发的 CSS
---@return string[] paragraphs
function Scramble.paragraphs(html, css)
local order, rules = parse(css)
local paragraphs = {}
for open, body in html:gmatch("<p([^>]*)>(.-)</p>") do
local cls = open:match('class="(p%d+)"')
local text
if cls then
local children = {}
for tag, attrs, inner in body:gmatch("<(y[%w_-]*)([^>]*)>(.-)</%1>") do
children[#children + 1] = { tag = tag, attrs = attrs, text = unescape(inner) }
end
text = scrambled(cls, children, order, rules)
else
text = body:gsub('<y class="sy%-0">.-</y>', ""):gsub("<[^>]+>", "")
text = unescape(text)
end
if text ~= "" then paragraphs[#paragraphs + 1] = text end
end
return paragraphs
end
local function isRare(code)
return (code >= LOW and code <= HIGH) or code == 0xF900
end
local function isHan(code)
return code >= 0x4E00 and code <= 0x9FA5
end
--- 文本里要查字体的码位(去重):rare 走 randomFont,han 走 fixedFont(该字体没有的码位原样保留)。
---@param paragraphs string[]
---@return integer[] rare
---@return integer[] han
function Scramble.codes(paragraphs)
local seen, rare, han = {}, {}, {}
for _idx, text in ipairs(paragraphs) do
for ch in text:gmatch(CHAR) do
local code = Glyph.codepoint(ch)
if not seen[code] then
seen[code] = true
if isRare(code) then rare[#rare + 1] = code elseif isHan(code) then han[#han + 1] = code end
end
end
end
table.sort(rare)
table.sort(han)
return rare, han
end
--- 把码位换成真字,认不出的写 □;返回全文(段落以换行连接)。
---@param paragraphs string[]
---@param rare_map table<integer, string|false> randomFont 的识别结果
---@param han_map table<integer, string|false> fixedFont 的识别结果
---@return string
function Scramble.text(paragraphs, rare_map, han_map)
local out = {}
for idx, text in ipairs(paragraphs) do
out[idx] = (text:gsub(CHAR, function(ch)
local code = Glyph.codepoint(ch)
local real
if isRare(code) then real = rare_map[code] or false
elseif isHan(code) then real = han_map[code]
else return nil end
if real == nil then return nil end
return real or UNKNOWN
end))
end
return table.concat(out, "\n")
end
return Scramble
@@ -0,0 +1,486 @@
--[[--
阅文 App 扫码登录(QQ阅读、起点、潇湘共用)。
阅文自己的码,用 QQ阅读或起点 App 扫,不是手机 QQ。
GET /login/qrcode 拿 sessionKey,二维码内容是固定的 scanlogin URL。
轮询 /login/qrcodelogin。scanStatus 5 时取 ywguid / ywkey;只有 302url 时跟跳收 Set-Cookie。
拿到 Cookie 交给 on_cookie,由设置页走现有账号校验再保存。
@module koplugin.book.moonsource_xiaoxiang.yuewen_qr
--]]
require("l10n").apply()
local JSON = require("json")
local Request = require("http.request")
local Text = require("utils.text")
local logger = require("utils.log")
local _ = require("gettext")
local QRLogin = {}
QRLogin.__index = QRLogin
local BASE = "https://ptlogin.yuewen.com"
local POLL_INTERVAL = 3
local POLL_MAX = 40
local DEADLINE = 180
local MAX_HOPS = 5
local UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
.. "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
local KEEP = { ywguid = true, ywkey = true, ywopenid = true }
---@param value any
---@return string|nil
local function text(value)
if type(value) == "string" and value ~= "" then return value end
if type(value) == "number" then return tostring(value) end
end
---@return table
function QRLogin:baseParams()
return {
appId = self.spec.app_id,
areaId = self.spec.area_id,
format = "json",
returnurl = self.spec.return_url,
target = "top",
ticket = self.spec.ticket or "0",
autotime = "14",
auto = "0",
}
end
--- 二维码内容。和官方图里的 URL 同一组参数,顺序无所谓。
---@param session_key string
---@return string
function QRLogin:scanUrl(session_key)
return BASE .. "/mobile/scanlogin?" .. Text.formEncode({
sessionkey = session_key,
appid = self.spec.app_id,
areaid = self.spec.area_id,
bookId = "0",
chapterId = "0",
})
end
---@param jar table
---@return string
local function cookieHeader(jar)
local keys = {}
for key, value in pairs(jar) do
if KEEP[key] and value ~= "" then keys[#keys + 1] = key end
end
table.sort(keys)
local parts = {}
for i, key in ipairs(keys) do parts[i] = key .. "=" .. jar[key] end
return table.concat(parts, "; ")
end
---@param jar table
---@param set_cookie string|table|nil
local function takeCookies(jar, set_cookie)
if type(set_cookie) == "table" then
for _key, value in pairs(set_cookie) do takeCookies(jar, value) end
return
end
if type(set_cookie) ~= "string" or set_cookie == "" then return end
for name, value in set_cookie:gmatch("([%w_]+)=([^;,]*)") do
name = name:lower()
value = value:match("^(.-)%s*$")
if KEEP[name] and value ~= "" then jar[name] = value end
end
end
---@param data table|nil
---@param jar table
local function takeJson(data, jar)
if type(data) ~= "table" then return end
local value = data.ywGuid or data.ywguid
local guid = type(value) == "number" and string.format("%.0f", value) or text(value)
local key = text(data.ywKey or data.ywkey)
local openid = text(data.ywOpenId or data.ywopenid)
if guid then jar.ywguid = guid end
if key then jar.ywkey = key end
if openid then jar.ywopenid = openid end
if type(data.data) == "table" then takeJson(data.data, jar) end
end
---@param jar table
---@return boolean
local function ready(jar)
return jar.ywguid ~= nil and jar.ywguid ~= "" and jar.ywkey ~= nil and jar.ywkey ~= ""
end
---@class YuewenQRSpec
---@field app_id string
---@field area_id string
---@field return_url string
---@field referer string
---@field title string
---@field caption string
---@field ticket string|nil 非 0 时必须兑换本站 Web 会话
---@param spec YuewenQRSpec
---@param on_cookie fun(cookie: string)
function QRLogin.new(_class, spec, on_cookie)
local self = setmetatable({}, QRLogin)
self.spec = spec
self.on_cookie = on_cookie
self.generation = 0
self.jar = {}
self.dialog = nil
self.retry_dialog = nil
self.busy = nil
self.job = nil
self.started = 0
self.polls = 0
self.session = nil
self.login_completed = false
self.scanned_notified = false
return self
end
function QRLogin:toast(text_msg)
require("ui.themes.widgets.toast"):new{ text = tostring(text_msg), timeout = 2 }:show()
end
function QRLogin:closeBusy()
if self.busy then
self.busy:close()
self.busy = nil
end
end
function QRLogin:showBusy(text_msg)
self:closeBusy()
self.busy = require("ui.themes.widgets.progress_dialog"):new{
title = self.spec.title, text = text_msg, dismissable = false,
}
self.busy:show()
end
function QRLogin:_close_dialog()
if self.dialog then
local dialog = self.dialog
self.dialog = nil
dialog:close()
end
end
function QRLogin:_close_retry()
if self.retry_dialog then
local dialog = self.retry_dialog
self.retry_dialog = nil
dialog:close()
end
end
function QRLogin:_cancel_job()
if self.job and self.job.cancel then self.job.cancel() end
self.job = nil
end
function QRLogin:cancel()
self.generation = self.generation + 1
self.login_completed = false
self:_cancel_job()
self:_close_dialog()
self:_close_retry()
self:closeBusy()
self.jar = {}
self.session = nil
self.polls = 0
self.scanned_notified = false
end
---@param url string
---@param cb fun(res: table|nil, err: string|nil)
function QRLogin:_get(url, cb)
local headers = {
["User-Agent"] = UA,
Accept = "application/json, text/javascript, */*",
Referer = self.spec.referer,
}
local host = url:match("^https://([^/?#]+)")
if host == self.spec.return_url:match("^https://([^/?#]+)") then
local cookie = cookieHeader(self.jar)
if cookie ~= "" then headers.Cookie = cookie end
end
local pending, gen = true, self.generation
local job = Request.request({
url = url,
method = "GET",
headers = headers,
timeout = require("http.timeout").net(0.5),
allow_redirects = false,
}, function(res, err)
pending = false
if gen ~= self.generation then return end
self.job = nil
if err or not res then
cb(nil, err and tostring(err) or _("请求失败"))
return
end
local code = tonumber(res.code)
if not code or code < 200 or code >= 400 then
cb(nil, "HTTP " .. tostring(res.code))
return
end
cb(res)
end)
if pending then self.job = job end
end
---@param res table|nil
---@return table|nil
local function decode(res)
local body = res and res.body
if type(body) ~= "string" or body == "" then return nil end
local ok, wire = pcall(JSON.decode, body)
if not ok or type(wire) ~= "table" then return nil end
return wire
end
function QRLogin:_expired()
return self.polls >= POLL_MAX or os.time() - self.started > DEADLINE
end
---@param gen integer
---@param session string
function QRLogin:_later(gen, session)
require("ui/uimanager"):scheduleIn(POLL_INTERVAL, function()
self:_poll(gen, session)
end)
end
---@param gen integer
function QRLogin:_show(gen, session)
if gen ~= self.generation then return end
self:closeBusy()
self.session = session
self.polls = 0
local dialog
dialog = require("ui.themes.widgets.qr"):new{
title = self.spec.title,
text = self:scanUrl(session),
caption = self.spec.caption,
close_callback = function()
if self.dialog == dialog then self.dialog = nil end
if gen == self.generation and not self.login_completed then
self:cancel()
self:toast(_("已取消登录"))
end
end,
}
self.dialog = dialog
dialog:show()
logger.info("[YuewenQR] 二维码已显示")
self:_later(gen, session)
end
function QRLogin:start()
self:cancel()
local gen = self.generation
self.started = os.time()
self.jar = {}
self:showBusy(_("获取二维码中..."))
local params = self:baseParams()
self:_get(BASE .. "/login/qrcode?" .. Text.formEncode(params), function(res, err)
if gen ~= self.generation then return end
local wire = decode(res)
local session = wire and type(wire.data) == "table" and text(wire.data.sessionKey)
if not session or tonumber(wire.code) ~= 0 then
self:closeBusy()
logger.warn("[YuewenQR] 获取二维码失败:", err or (wire and wire.message))
self:show_retry(_("获取二维码失败"))
return
end
self:_show(gen, session)
end)
end
---@param gen integer
---@param jar table
function QRLogin:_done(gen, jar)
if gen ~= self.generation or self.login_completed then return end
if not ready(jar) then
self:show_retry(_("登录失败:未获取到登录态"))
return
end
self.login_completed = true
self.generation = self.generation + 1
self:_cancel_job()
self:_close_dialog()
self:_close_retry()
self:closeBusy()
local cookie = cookieHeader(jar)
logger.info("[YuewenQR] 登录态已拿到")
if self.on_cookie then self.on_cookie(cookie) end
end
---@param gen integer
---@param url string
---@param hop integer
function QRLogin:_follow(gen, url, hop)
if gen ~= self.generation then return end
local host = type(url) == "string" and url:match("^https://([^/?#]+)")
local target = self.spec.return_url:match("^https://([^/?#]+)")
if not host or (host ~= target and host ~= "ptlogin.yuewen.com"
and host ~= "passport.yuewen.com" and host ~= "passport.qidian.com"
and host ~= "login.book.qq.com") or hop > MAX_HOPS then
self:show_retry(_("登录失败:未获取到登录态"))
return
end
self:showBusy(_("正在完成登录..."))
self:_get(url, function(res, err)
if gen ~= self.generation then return end
if not res then
logger.warn("[YuewenQR] 跟跳失败:", err)
self:show_retry(_("登录失败:未获取到登录态"))
return
end
for _idx, value in ipairs(Request.headerAll(res, "Set-Cookie")) do takeCookies(self.jar, value) end
local location = Text.absoluteUrl(url, Request.header(res, "Location"))
if tonumber(res.code) >= 300 then
if not location then
self:show_retry(_("登录失败:未获取到登录态")); return
end
self:_follow(gen, location, hop + 1)
return
end
-- ticket=1 仍要求落到本站 host;本站实际上常常不 Set-Cookie ywkey(只有 abPolicies),
-- 不能把「见到 ywkey Set-Cookie」当成兑换成功条件,否则扫码永远失败。
if ready(self.jar) and (self.spec.ticket ~= "1" or host == target) then
self:_done(gen, self.jar)
return
end
if not location then
self:show_retry(_("登录失败:未获取到登录态"))
return
end
self:_follow(gen, location, hop + 1)
end)
end
---@param gen integer
---@param session string
---@param wire table
---@param res table
function QRLogin:_on_poll(gen, session, wire, res)
for _idx, value in ipairs(Request.headerAll(res, "Set-Cookie")) do takeCookies(self.jar, value) end
local data = type(wire.data) == "table" and wire.data or {}
takeJson(data, self.jar)
takeJson(wire, self.jar)
local status = tonumber(wire.scanStatus)
local code = tonumber(wire.code)
if code == -11033 then
self:show_retry(text(wire.message) or _("登录失败"))
return
end
if status == 5 and code == 0 then
local ticket = text(data.ticket) or text(wire.ticket)
local jump = text(data["302url"]) or text(wire["302url"])
-- 起点 ticket=1:裸 302url(https://m.qidian.com/ 无 ticket)没用,改成本站 ticket 兑换。
-- 若 302url 走 ptlogin 中转,照跟——那才是会带上完整跳转链的路径。
if self.spec.ticket == "1" then
local target = self.spec.return_url:match("^https://([^/?#]+)")
local jump_host = jump and jump:match("^https://([^/?#]+)")
local bare_home = jump_host == target and not jump:find("ticket=", 1, true)
if ticket and (not jump or bare_home) then
jump = self.spec.return_url .. (self.spec.return_url:find("?", 1, true) and "&" or "?")
.. Text.formEncode({
ticket = ticket,
ywguid = self.jar.ywguid or "",
ywOpenId = self.jar.ywopenid or "",
})
elseif not jump then
self:show_retry(_("登录失败:未获取到登录态"))
return
end
self:_follow(gen, jump, 1)
return
end
if jump then
self:_follow(gen, jump, 1)
return
end
if ready(self.jar) then
self:_done(gen, self.jar)
return
end
self:show_retry(_("登录失败:未获取到登录态"))
return
end
if status == 3 then
logger.info("[YuewenQR] 手机取消,刷新二维码")
self.generation = self.generation + 1
self:_close_dialog()
self:start()
return
end
if status == 4 or self:_expired() then
self:show_retry(_("二维码已过期"))
return
end
if status == 1 and not self.scanned_notified then
self.scanned_notified = true
self.polls = 0
self.started = os.time()
self:toast(_("已扫码,请在手机上确认"))
end
self:_later(gen, session)
end
---@param gen integer
---@param session string
function QRLogin:_poll(gen, session)
if gen ~= self.generation or session ~= self.session then return end
if self:_expired() then
self:show_retry(_("二维码已过期"))
return
end
self.polls = self.polls + 1
local params = self:baseParams()
params.qrcode = session
self:_get(BASE .. "/login/qrcodelogin?" .. Text.formEncode(params), function(res, err)
if gen ~= self.generation or session ~= self.session then return end
local wire = decode(res)
if not wire then
if self.polls == 1 or self.polls % 5 == 0 then
logger.warn("[YuewenQR] 轮询失败:", err)
end
if self:_expired() then
self:show_retry(_("二维码已过期"))
return
end
self:_later(gen, session)
return
end
self:_on_poll(gen, session, wire, res)
end)
end
function QRLogin:show_retry(msg)
self.generation = self.generation + 1
self:_cancel_job()
self:_close_dialog()
self:_close_retry()
self:closeBusy()
local dialog
dialog = require("ui.themes.widgets.confirm"):new{
text = tostring(msg),
ok_text = _("重新获取"),
ok_callback = function()
if self.retry_dialog == dialog then self.retry_dialog = nil end
self:start()
end,
cancel_callback = function()
if self.retry_dialog == dialog then self.retry_dialog = nil end
self:cancel()
end,
}
self.retry_dialog = dialog
dialog:show()
end
return QRLogin