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

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

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

No files matched your search

+23
View File
@@ -0,0 +1,23 @@
# 长佩文学
| 能力 | 是否支持 | 备注 |
| --- | --- | --- |
| App 扫码登录 | 支持 | 扫描官网二维码,确认后校验账号再保存 |
| 浏览器登录与 Cookie 导入 | 已实现,未实测 | 支持手动粘贴和浏览器扩展回传 |
| 设备密码、短信与登录验证码 | 不支持 | 其他登录方式在官网完成后导入 Cookie |
| 书架拉取 | 部分支持 | 读取根目录,不枚举分组内成员 |
| 书架新增与移出 | 已实现,未实测 | 本地先生效,后续同步;远端失败保留脏行或墓碑 |
| 搜索与分类书城 | 支持 | 动态频道、分类及排序、资费、状态、字数筛选,默认聚合 60 本 |
| 榜单 | 支持 | 保留原有榜单入口 |
| 详情与完整目录 | 支持 | 保留小说和章节身份 |
| 免费与已购正文 | 部分支持 | 需有效登录及阅读权限;已购正文未完成实测 |
| 阅读安全验证 | 支持 | 当前进程复用服务端下发的会话 Cookie,扫码后重取并校验正文;后台预取不弹窗。网络/IP 变化、重启、会话过期或服务端再次风控时可能重验,不能保证每个网络只验证一次 |
| 章节与全本缓存 | 支持 | 权限不足的提示不计入正文缓存;缓存流程未完成真实登录实测 |
| 离线阅读 | 支持 | 已缓存章节、目录和章评可用 |
| 阅读进度同步 | 部分支持 | 仅章节位置;读章及预取可能改变官网历史,关书再收敛 |
| 笔记与统计同步 | 不支持 | 仅本地保存 |
| 整书评论 | 部分支持 | 首页预览可能汇总章评,保留对应章节名 |
| 章评 | 支持 | 真正按章绑定,章末入口、分页和离线缓存 |
| 段评 | 不支持 | 当前 Web 协议未找到可验证的段落定位接口 |
| 评论回复与写操作 | 不支持 | 可展示回复数,未接回复分页、发评、点赞或删评 |
| 账号切换 | 部分支持 | 同账号可续期;换号须确认清理旧本地数据,未同步记录会丢失 |
+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_changpei",
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_changpei.source").meta() end,
new = function() return require("moonsource_changpei.source").new() end,
setting = lazy("moonsource_changpei.setting"),
}
@@ -0,0 +1,15 @@
--[[--
书源元信息:id / 名称 / 类型,加上启用页展示用的说明与能力清单。`init.lua` 的 `meta()` 直接返回本表。
@module moonsource_changpei._meta
--]]
local _ = require("l10n").get("moonsource_changpei")
return {
id = "ext.changpei",
name = _("长佩文学"),
type = "chapter",
description = _("长佩文学书架与在线阅读"),
abilities = { _("搜索与发现"), _("书架同步"), _("进度同步"), _("书评"), _("章节评论") },
}
@@ -0,0 +1,135 @@
--[[--
长佩官网分类库;旧「榜单号:子榜值」节点继续可用。
@module moonsource_changpei.browse
--]]
local Browse = require("source.browse")
local Client = require("moonsource_changpei.client")
local Mapper = require("moonsource_changpei.mapper")
local SourceBase = require("source.base")
local _ = require("l10n").get("moonsource_changpei")
local Library = {}
local KEYS = { "channel", "category", "process", "sell", "number", "field" }
local DEFAULT = { channel = 0, category = 0, process = 0, sell = 2, number = 0, field = 8 }
local FILTERS = {
{ key = "field", title = _("排序"), items = {
{ 8, _("综合") }, { 4, _("最新") }, { 7, _("热门") }, { 1, _("人气") },
{ 2, _("收藏") }, { 3, _("字数") },
} },
{ key = "process", title = _("状态"), items = { { 0, _("全部") }, { 1, _("连载") }, { 2, _("完结") } } },
{ key = "sell", title = _("价格"), items = { { 2, _("全部") }, { 0, _("免费") }, { 1, _("付费") } } },
{ key = "number", title = _("字数"), items = {
{ 0, _("全部") }, { 1, _("7万以下") }, { 2, _("7-15万") }, { 3, _("15-25万") },
{ 4, _("25-40万") }, { 5, _("40-60万") }, { 6, _("60万以上") },
} },
}
local function node(params, key, value)
local parts = {}
local changing_channel = key == "channel" and tonumber(value) ~= params.channel
for idx, name in ipairs(KEYS) do
parts[idx] = tostring(name == key and value or (changing_channel and name == "category" and 0 or params[name]))
end
return "cate:" .. table.concat(parts, ":")
end
local function types(wire)
local list = type(wire.data) == "table" and wire.data.list
if type(list) ~= "table" then return nil end
for _idx, row in ipairs(list) do
if type(row) ~= "table" or not tonumber(row.id) or type(row.type_name) ~= "string" then return nil end
end
return list
end
local function select(params, key, list)
if params[key] == 0 then return end
for _idx, row in ipairs(list) do
if tonumber(row.id) == params[key] then return end
end
params[key] = 0
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 out = Browse.group(chips, node(params))
out.title = title
return out
end
function Library.run(opts, cb)
opts = opts or {}
local params = {}
for key, value in pairs(DEFAULT) do params[key] = value end
if opts.node then
local channel, category, process, sell, number, field =
opts.node:match("^cate:(%d+):(%d+):(%d+):(%d+):(%d+):(%d+)$")
if not channel then return SourceBase.defer(cb, nil, _("长佩分类条件无效")) end
params = { channel = tonumber(channel), category = tonumber(category), process = tonumber(process),
sell = tonumber(sell), number = tonumber(number), field = tonumber(field) }
for _idx, filter in ipairs(FILTERS) do
local valid = false
for _item, item in ipairs(filter.items) do
if params[filter.key] == item[1] then valid = true end
end
if not valid then return SourceBase.defer(cb, nil, _("长佩分类条件无效")) end
end
end
local cancelled, job, pending = false, nil, true
local initial = Client.typesAsync(nil, function(wire, err)
pending = false
if cancelled then return end
local channels = wire and types(wire)
if not channels then cb(nil, err or _("响应无效")); return end
select(params, "channel", channels)
if params.channel == 0 then params.category = 0 end
local function load(categories, reason)
if cancelled then return end
if not categories then cb(nil, reason or _("响应无效")); return end
select(params, "category", categories)
local channel_items, category_items = { { 0, _("全部") } }, { { 0, _("全部") } }
for _idx, row in ipairs(channels) do channel_items[#channel_items + 1] = { row.id, _(row.type_name) } end
for _idx, row in ipairs(categories) do category_items[#category_items + 1] = { row.id, _(row.type_name) } end
local groups = { group(params, "channel", _("频道"), channel_items) }
groups[1].chips[#groups[1].chips + 1] = { id = "rank", title = _("排行榜") }
if params.channel ~= 0 then groups[#groups + 1] = group(params, "category", _("分类"), category_items) end
for _idx, filter in ipairs(FILTERS) do
groups[#groups + 1] = group(params, filter.key, filter.title, filter.items)
end
local query = { field = params.field,
tid = params.category ~= 0 and params.category or (params.channel ~= 0 and params.channel or nil),
process = params.process ~= 0 and params.process or nil,
sell = params.sell ~= 2 and params.sell or nil,
number = params.number ~= 0 and params.number or nil }
job = Browse.pages(function(page, done)
return Client.libraryAsync(query, page, function(result, failure)
if not result then done(nil, failure); return end
local data = result.data
if type(data) ~= "table" or type(data.list) ~= "table" or not tonumber(data.count) then
done(nil, _("响应无效")); return
end
done(Mapper.search(result), nil, page * 10 < tonumber(data.count))
end)
end, opts.limit or 60, groups, cb)
end
if params.channel == 0 then load({}); return end
local loading = true
local categories = Client.typesAsync(params.channel, function(result, failure)
loading = false
load(result and types(result), failure)
end)
if loading then job = categories end
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,499 @@
--[[--
长佩文学网 HTTP 客户端(仅异步)。
走官网网页的 JSON 接口(www.gongzicp.com/webapi),请求头照网页端:`Client: pc` + 桌面浏览器 UA。
正文是 AES 密文,解密放子进程。data.check > 1 表示需要人机验证,不表示登录失效;
用户开章时经远程管理完成验证,成功后使用同一会话重取正文;
后台预取只返回错误,不弹窗、不缓存待验证正文。
登录态是网页 Cookie(setting.lua:扫码 / 浏览器授权 / 粘贴),Cookie 失效回包 code 9996;没买的 VIP 章不出正文。
@module koplugin.book.moonsource_changpei.client
--]]
local Job = require("workers.job")
local JSON = require("json")
local Mapper = require("moonsource_changpei.mapper")
local Request = require("http.request")
local Text = require("utils.text")
local _ = require("l10n").get("moonsource_changpei")
local Client = {}
local SOURCE_ID = "ext.changpei"
local LOGIN_REQUIRED = 9996
Client.VERIFY_REQUIRED = _("长佩需要滑块验证,请打开章节并扫码完成验证,无需重新登录。")
--- 网页重新登录,再用扩展抓 Cookie;不装扩展就按设置路径粘贴。
---@return string
local function changpeiRelogin()
return require("source.cookie_login").relogin(
_("长佩文学"), "https://www.gongzicp.com/login/signin", _("长佩文学 → 粘贴 Cookie"))
end
local API = "https://www.gongzicp.com/webapi"
Client.USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) "
.. "Chrome/126.0.0.0 Safari/537.36"
local HEADERS = {
["Client"] = "pc",
["Referer"] = "https://www.gongzicp.com/",
["User-Agent"] = Client.USER_AGENT,
}
--- 已保存的登录 Cookie。
---@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
-- 凭据身份不含 moon_token / moon_refresh(请求头 token 与续期凭据,续期会变,不该让会话重置)。
---@param cookie string|nil
---@return CookieJar|nil
local function jarFor(cookie)
if not cookie then return nil end
local login = cookie:gsub(";?%s*moon_token=[^;%s]+", ""):gsub(";?%s*moon_refresh=[^;%s]+", "")
return require("http.cookie_jar").session(SOURCE_ID, login)
end
---@param cookie string|nil
---@return table<string, string>
local function headers(cookie)
local out = {}
local token = cookie and cookie:match("moon_token=([^;%s]+)")
-- 扫码登录拿到的是网页端 sessionStorage 里的 token(请求头 token),不是 Cookie;借 Cookie 串带着存
if token then out["token"] = token end
for key, value in pairs(HEADERS) do out[key] = value end
return out
end
--- 登录 token 过期:用 refresh_token(扫码登录存的 moon_refresh,或浏览器 Cookie 里的 ukey)换新 token,
--- 写回已保存的 Cookie。没有 refresh_token 或服务端拒绝返回 false。
---@param cb fun(ok: boolean, err: string|nil)
function Client.renewAsync(cb)
local cookie = Client.cookie()
local jar = jarFor(cookie)
local refresh = cookie and (cookie:match("moon_refresh=([^;%s]+)") or jar:get("ukey"))
local imei = cookie and cookie:match("_c_n_=([^;%s]+)")
if not refresh or not imei then cb(false); return end
local cancelled = false
local QRLogin = require("moonsource_changpei.qrlogin")
local head = headers(cookie)
head["Content-Type"] = "application/grpc-web+proto"
head["X-Grpc-Web"] = "1"
head["version"] = "1"
head["imei"] = imei
head["_c_n_"] = imei
local job = Request.post("https://www.gongzicp.com/cp.UserExternal/get_token", QRLogin.frame(refresh, 5), {
headers = head,
jar = jar,
content_type = "application/grpc-web+proto",
timeout = require("http.timeout").net(0.5),
}, function(body, err, res)
if cancelled then return end
if cookie ~= Client.cookie() then cb(false, _("账号已变化,请重新登录")); return end
if not body then cb(false, err and tostring(err) or _("请求失败")); return end
-- get_token 回包:token(3)。grpc-status 非 0 = refresh_token 也失效
local token = body and (tonumber(Request.header(res, "grpc-status")) or 0) == 0 and QRLogin.decode(body)[3]
if type(token) ~= "string" or token == "" then cb(false); return end
local settings = require("utils.settings")
local cfg = settings.getSource(SOURCE_ID)
local saved = cfg.cookie:gsub(";?%s*moon_token=[^;%s]+", "")
cfg.cookie = saved .. "; moon_token=" .. token
settings.saveSource(SOURCE_ID, cfg)
cb(true)
end)
return { cancel = function() cancelled = true; job:cancel() end }
end
--- cookie 显式传入:登录入口要先校验再保存,校验用的新 Cookie 失效不能污染已保存的登录态。
---@param cookie string|nil
---@param cb fun(wire: table|nil, err: string|nil)
---@param retry function|nil
---@return fun(raw: string|nil, err: any)
local function reply(cookie, cb, retry)
return 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
if wire.code ~= 200 then
local msg = wire.msg or _("响应无效")
if wire.code == LOGIN_REQUIRED and cookie and cookie == Client.cookie() then
-- 只有 PHPSESSID 的 Cookie 登录是服务端会话,闲置(休眠)一阵就丢,没有续期凭据
if not (cookie:match("moon_refresh=") or cookie:match("ukey=")) then
msg = _("这个登录是网页 Cookie,放一会儿就会失效,而且不能自动续上。请改用扫码登录:打开「设置 → 书库 → 账号 → 长佩文学 → 长佩账号」,用长佩 App 对准屏幕上的二维码扫一下,再在手机上点确认。提示上如果有「重新登录」,点它,选「用长佩 App 扫码」,是同一件事。")
else
msg = changpeiRelogin()
end
if retry then
-- token 过期:用 refresh_token 换新的再重发一次;换不到才算登录失效
return Client.renewAsync(function(renewed, reason)
if renewed then retry()
elseif reason then cb(nil, reason)
elseif cookie == Client.cookie() then cb(nil, require("source.auth").expire(SOURCE_ID, msg))
else cb(nil, _("账号已变化,请重新登录")) end
end)
end
msg = require("source.auth").expire(SOURCE_ID, msg)
end
cb(nil, msg)
return
end
if cookie and cookie == Client.cookie() then require("source.auth").ok(SOURCE_ID) end
cb(wire)
end
end
local function get(path, query, cookie, cb, renewed, cache_ttl)
local cancelled, job, pending = false, nil, true
local managed = cookie ~= nil and cookie == Client.cookie()
local retry
if cookie and not renewed then
retry = function()
if not cancelled then job = get(path, query, Client.cookie(), cb, true, cache_ttl) end
end
end
local respond = reply(cookie, cb, retry)
local initial = Request.get(API .. path .. "?" .. query, {
accept = "application/json",
headers = headers(cookie),
jar = jarFor(cookie),
timeout = require("http.timeout").net(0.5),
cache_ttl = cache_ttl or 0,
}, function(raw, err)
pending = false
if cancelled then return end
if managed and cookie ~= Client.cookie() then cb(nil, _("账号已变化,请重新登录")); return end
local previous = job
local renewing = respond(raw, err)
if renewing and job == previous then job = renewing end
end)
if pending then job = initial end
return { cancel = function()
cancelled = true
if job then job:cancel() end
end }
end
-- 网页端非 GET 请求的签名:md5(固定前缀 .. 按键名排序的 &k=v .. &服务器时间),params 的值是已渲染的字符串。
local SIGN_PREFIX = "SIa7xu0LRrbu$En3*I1T3EiO^40cN49D"
---@param params table<string, string>
---@param timestamp string
---@return string
local function sign(params, timestamp)
local keys = {}
for key in pairs(params) do keys[#keys + 1] = key end
table.sort(keys)
local parts = { SIGN_PREFIX }
for _idx, key in ipairs(keys) do parts[#parts + 1] = "&" .. key .. "=" .. params[key] end
parts[#parts + 1] = "&" .. timestamp
return require("ffi/sha2").md5(table.concat(parts)) --[[@as string]]
end
--- 带签名的 JSON POST:先取服务器时间(本机时钟不可信)再发。
---@param path string
---@param params table<string, string>
---@param body string
---@param cb fun(wire: table|nil, err: string|nil)
---@return { cancel: fun() }
local function post(path, params, body, cb, renewed)
local cookie = Client.cookie()
local cancelled, job, pending = false, nil, true
local retry
if cookie and not renewed then
retry = function()
if not cancelled then job = post(path, params, body, cb, true) end
end
end
local initial = get("/system/init", "", nil, function(init, err)
pending = false
if cancelled then return end
if cookie ~= Client.cookie() then cb(nil, _("账号已变化,请重新登录")); return end
local timestamp = (init and type(init.data) == "table" and init.data.timestamp) --[[@as string|number|nil]]
if not timestamp then cb(nil, err or _("响应无效")); return end
---@cast timestamp string|number
timestamp = tostring(timestamp)
local head = headers(cookie)
head["Timestamp"] = timestamp
head["Rand-Str"] = sign(params, timestamp)
local posting = true
local respond = reply(cookie, cb, retry)
local posted = Request.post(API .. path, body, {
accept = "application/json",
headers = head,
jar = jarFor(cookie),
content_type = "application/json",
timeout = require("http.timeout").net(0.5),
}, function(raw, reason)
posting = false
if cancelled then return end
if cookie ~= Client.cookie() then cb(nil, _("账号已变化,请重新登录")); return end
local previous = job
local renewing = respond(raw, reason)
if renewing and job == previous then job = renewing end
end)
if posting then job = posted end
end)
if pending then job = initial end
return { cancel = function()
cancelled = true
if job then job:cancel() end
end }
end
---@param keyword string
---@param cb fun(wire: table|nil, err: string|nil)
---@return HttpJob
function Client.searchAsync(keyword, cb)
return get("/search/novels", "page=1&k=" .. Text.urlEncode(keyword), nil, cb, true)
end
---@param novel_id string
---@param cb fun(wire: table|nil, err: string|nil)
---@return HttpJob
function Client.chaptersAsync(novel_id, cb)
return get("/novel/chapterGetList", "nid=" .. novel_id, Client.cookie(), cb)
end
---@param cb fun(wire: table|nil, err: string|nil)
---@return HttpJob
function Client.rankNavAsync(cb)
return get("/novel/rankingNav", "", nil, cb, true)
end
---@param rid integer
---@param tid integer
---@param page integer
---@param cb fun(wire: table|nil, err: string|nil)
---@return HttpJob
function Client.rankAsync(rid, tid, page, cb)
return get("/novel/rankingGetList", ("tid=0&rid=%d&date=%d&page=%d"):format(rid, tid, page), nil, cb, true)
end
function Client.typesAsync(id, cb)
return get("/novel/typeGetList", id and ("id=" .. id) or "", nil, cb, true)
end
function Client.libraryAsync(params, page, cb)
local query = { "page=" .. page, "size=10", "field=" .. params.field, "order=0" }
for _idx, key in ipairs({ "tid", "process", "sell", "number" }) do
if params[key] ~= nil then query[#query + 1] = key .. "=" .. params[key] end
end
return get("/novel/novelGetList", table.concat(query, "&"), nil, cb, true)
end
function Client.detailAsync(novel_id, cb)
return get("/novel/novelInfo", "id=" .. novel_id, nil, cb, true)
end
function Client.commentsAsync(module, id, page, cb)
return get("/comment/getList", "module=" .. module .. "&cid=" .. id .. "&gift=0&page=" .. page, nil, cb, true)
end
--- 网页书架(根目录,不含分组里的书),逐页取到空页为止。
---@param cb fun(rows: table[]|nil, err: string|nil)
---@return { cancel: fun() }
function Client.shelfAsync(cb)
local rows, cancelled, job = {}, false, nil
local function page(n)
local pending = true
local initial = get("/usercoll/getList", "filter=0&sort_key=1&sort_flag=2&did=0&page=" .. n, Client.cookie(),
function(wire, err)
pending = false
if cancelled then return end
if not wire then cb(nil, err); return end
local list = type(wire.data) == "table" and wire.data.list
if type(list) ~= "table" then cb(nil, _("响应无效")); return end
for _idx, row in ipairs(list) do
if row.type == "novel" then rows[#rows + 1] = row end
end
if #list == 0 then cb(rows) else page(n + 1) end
end)
if pending then job = initial end
end
page(1)
return { cancel = function()
cancelled = true
if job then job:cancel() end
end }
end
--- 网页端加 / 移出书架同一个接口:status 1 加入,0 移出。
local function collect(stable_id, status, cb)
local nid = ("%d"):format(tonumber(stable_id))
return post("/usercoll/collHandle", { module = "novel", cid = nid, status = tostring(status) },
'{"module":"novel","cid":' .. nid .. ',"status":' .. status .. "}", cb)
end
---@param stable_id string
---@param cb fun(wire: table|nil, err: string|nil)
---@return { cancel: fun() }
function Client.shelfAddAsync(stable_id, cb) return collect(stable_id, 1, cb) end
---@param stable_id string
---@param cb fun(wire: table|nil, err: string|nil)
---@return { cancel: fun() }
function Client.shelfRemoveAsync(stable_id, cb) return collect(stable_id, 0, cb) end
--- 由设备使用自己的登录态提交浏览器完成的滑块凭据。
---@param token string
---@param cb fun(ok: boolean, err: string|nil)
---@return { cancel: fun() }
function Client.readCheckAsync(token, cb)
return post("/novel/readCheck", { token = token }, JSON.encode({ token = token }), function(wire, err)
local data = wire and wire.data
local ok = type(data) == "table" and data.code == 200
cb(ok, not ok and (err or (type(data) == "table" and data.msg) or _("验证失败,请重新滑动验证")) or nil)
end)
end
--- 阅读历史:服务端按 novel_id 记最近读到的章(latest_read_cid)。
---@param cb fun(wire: table|nil, err: string|nil)
---@return HttpJob
function Client.historyAsync(cb)
return get("/usernovel/getHistory", "", Client.cookie(), cb)
end
--- 已对齐历史就不再取章;否则取章后回读确认,减少重复触发阅读风控。
---@param chapter_id string
---@param cb fun(ok: boolean|nil, err: string|nil)
---@return HttpJob
function Client.markReadAsync(chapter_id, cb)
local cancelled, job, pending = false, nil, true
---@return boolean|nil
local function confirm(history, err)
if cancelled then return end
if not history then cb(nil, err); return end
for _id, uid in pairs(Mapper.history(history)) do
if uid == tostring(chapter_id) then cb(true); return true end
end
return false
end
local initial = Client.historyAsync(function(history, err)
pending = false
if confirm(history, err) ~= false then return end
local loading = true
local content = get("/novel/chapterGetInfo", "cid=" .. chapter_id .. "&server=0", Client.cookie(), function(wire, reason)
loading = false
if cancelled then return end
if not wire then cb(nil, reason); return end
if type(wire.data) ~= "table" or type(wire.data.chapterInfo) ~= "table" then
cb(nil, _("响应无效")); return
end
if (tonumber(wire.data.check) or 0) > 1 then cb(nil, Client.VERIFY_REQUIRED); return end
job = Client.historyAsync(function(updated, message)
if confirm(updated, message) == false then cb(nil, _("长佩阅读进度未确认")) end
end)
end)
if loading then job = content end
end)
if pending then job = initial end
return { cancel = function()
cancelled = true
if job then job:cancel() end
end }
end
--- 校验 cookie:返回账号信息(nickname 等),失效回调错误。
---@param cookie string
---@param cb fun(info: table|nil, err: string|nil)
---@return HttpJob
function Client.userAsync(cookie, cb)
return get("/user/getUserInfo", "", cookie, function(wire, err)
if not wire then cb(nil, err); return end
local info = type(wire.data) == "table" and wire.data.info
local uid = type(info) == "table" and tonumber(info.show_uid)
if not uid or uid <= 0 then
cb(nil, _("长佩账号标识缺失")); return
end
cb({ uid = uid })
end, true)
end
local LOGIN_HINT = _("还没登录长佩。打开「设置 → 书库 → 账号 → 长佩文学 → 长佩账号」,用长佩 App 扫二维码。也可以点「粘贴 Cookie」,把网页里的 Cookie 贴进去。")
--- 取章并解密;on_done 收到 Mapper.content 的打包结果。
---@param chapter_id string
---@param on_done fun(res: { text: string|nil, err: string|nil, kind: "unpaid"|"verify"|nil })
---@param on_failed fun(reason: string)
---@return { cancel: fun() }
local function fetchContent(chapter_id, on_done, on_failed)
local cancelled, job, pending = false, nil, true
local initial = get("/novel/chapterGetInfo", "cid=" .. chapter_id .. "&server=0", Client.cookie(), function(wire, err)
pending = false
if cancelled then return end
if not wire then on_failed(err or _("请求失败")); return end
job = Job.run(function()
local text, reason, kind = Mapper.content(wire)
return { text = text, err = reason, kind = kind }
end, {
name = "changpei_content",
kind = "light",
timeout = 60,
on_done = function(res) if not cancelled then on_done(res) end end,
on_failed = function(reason) if not cancelled then on_failed(tostring(reason)) end end,
on_cancelled = function() end,
})
end)
if pending then job = initial end
return { cancel = function()
cancelled = true
if job then job:cancel() end
end }
end
--- 一章正文(纯文本,段落以换行分隔)。后台预取用:待验证不回正文,避免把未验证章写进缓存。
---@param _novel_id string
---@param chapter_id string
---@param cb fun(text: string|nil, err: string|nil, kind: "unpaid"|"verify"|nil)
---@return { cancel: fun() }
function Client.contentAsync(_novel_id, chapter_id, cb)
return fetchContent(chapter_id, function(res)
if res.kind == "verify" then
if not Client.cookie() then cb(nil, LOGIN_HINT); return end
cb(nil, Client.VERIFY_REQUIRED, "verify")
return
end
if res.text then cb(res.text); return end
cb(nil, res.err or _("长佩章节内容为空"), res.kind)
end, function(reason) cb(nil, reason) end)
end
--- 只有用户开章才等扫码验证;验后重取,拒绝继续使用验证前的正文。
---@param _novel_id string
---@param chapter_id string
---@param cb fun(text: string|nil, err: string|nil, kind: "unpaid"|"verify"|nil)
---@return { cancel: fun() }
function Client.openContentAsync(_novel_id, chapter_id, cb)
local cancelled, job = false, nil
local function accept(res)
if res.kind == "verify" then
cb(nil, Client.VERIFY_REQUIRED, "verify")
return
end
if res.text then cb(res.text); return end
cb(nil, res.err or _("长佩章节内容为空"), res.kind)
end
local function fail(reason) cb(nil, reason) end
job = fetchContent(chapter_id, function(res)
if cancelled then return end
if res.kind ~= "verify" then accept(res); return end
if not Client.cookie() then cb(nil, LOGIN_HINT); return end
local verifying = true
local verification = require("moonsource_changpei.verify").new(function(ok, verify_err)
verifying = false
if cancelled then return end
if not ok then cb(nil, verify_err); return end
job = fetchContent(chapter_id, function(again)
if not cancelled then accept(again) end
end, function(reason) if not cancelled then fail(reason) end end)
end)
if verifying then job = verification end
end, function(reason) if not cancelled then fail(reason) end end)
return { cancel = function()
cancelled = true
if job then job:cancel() end
end }
end
return Client
@@ -0,0 +1,65 @@
return {
["综合"] = "Overall",
["长佩分类条件无效"] = "Invalid Changpei library filters.",
["长佩账号标识缺失"] = "Missing Changpei account ID.",
["长佩阅读进度未确认"] = "Changpei reading progress could not be confirmed.",
["长佩章节解密失败"] = "Failed to decrypt the Changpei chapter.",
["书评预览"] = "Book comment previews",
["切换长佩账号会清除这台设备上长佩的书架、阅读进度、笔记和缓存,包括尚未同步的记录。不会删除远端书架。确定继续?"] = "Switching Changpei accounts clears this device's Changpei shelf, progress, notes and cache, including unsynced records. Your remote shelf will not be deleted. Continue?",
["在章末显示本章讨论,不是段落评论"] = "Show this chapter's discussion at the end, not paragraph comments.",
["7万以下"] = "Under 70k words",
["7-15万"] = "70–150k words",
["15-25万"] = "150–250k words",
["25-40万"] = "250–400k words",
["40-60万"] = "400–600k words",
["60万以上"] = "Over 600k words",
["完结"] = "Completed",
["排行榜"] = "Rankings",
["分类书库"] = "Category library",
["切换账号"] = "Switch account",
["无法确认旧账号,请先退出旧账号再登录"] = "Cannot identify the previous account. Sign out before signing in again.",
["本章讨论"] = "Chapter discussion",
["人气"] = "Popularity",
["连载"] = "Ongoing",
["滑块加载失败,请检查网络后刷新网页"] = "Could not load the slider. Check your connection and refresh the page.",
["频道"] = "Channel",
["字数"] = "Word count",
["章节评论"] = "Chapter comments",
["价格"] = "Price",
["免费"] = "Free",
["付费"] = "Paid",
["用同一 Wi-Fi 下的手机扫码,在网页完成滑块验证后自动继续阅读。无需重新登录或安装浏览器扩展。"] = "Scan with a phone on the same Wi-Fi and complete the slider on the web page to continue reading automatically. No sign-in or browser extension needed.",
["验证已过期,请重新发起验证"] = "Verification expired. Please start again",
["验证成功,已在设备上继续打开章节。"] = "Verified. Opening the chapter on your device.",
["这个登录是网页 Cookie,放一会儿就会失效,而且不能自动续上。请改用扫码登录:打开「设置 → 书库 → 账号 → 长佩文学 → 长佩账号」,用长佩 App 对准屏幕上的二维码扫一下,再在手机上点确认。提示上如果有「重新登录」,点它,选「用长佩 App 扫码」,是同一件事。"] = "This sign-in is a web cookie. It dies after a while and cannot be renewed. Use QR sign-in instead: open Settings → Library → Account → Changpei → Changpei account, scan the code with the Changpei app, and confirm on the phone. If this message has Sign in again, tap it and choose Scan with the Changpei app. That is the same thing.",
["章节目录保存失败"] = "Failed to save chapter list",
["按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"] = "Press F12, open Network, refresh, and copy the entire Cookie request header",
["长佩文学 → 粘贴 Cookie"] = "Changpei → Paste Cookie",
["长佩目录为空"] = "Changpei table of contents is empty",
["长佩章节内容为空"] = "Changpei chapter is empty",
["长佩需要滑块验证,请打开章节并扫码完成验证,无需重新登录。"] = "Changpei requires slider verification. Open a chapter and scan the code to verify; no need to sign in again.",
["长佩滑块验证"] = "Changpei slider verification",
["无法打开远程验证,请先连接 Wi-Fi 并启用远程管理功能"] = "Cannot open remote verification. Connect to Wi-Fi and enable Remote management first.",
["验证已取消"] = "Verification cancelled",
["验证失败,请重新滑动验证"] = "Verification failed. Try the slider again.",
["验证凭据无效"] = "Invalid verification proof",
["请按住滑块,拖动到最右边"] = "Hold the slider and drag it all the way to the right",
["正在提交验证…"] = "Submitting verification…",
["还没登录长佩。打开「设置 → 书库 → 账号 → 长佩文学 → 长佩账号」,用长佩 App 扫二维码。也可以点「粘贴 Cookie」,把网页里的 Cookie 贴进去。"] = "Changpei is not signed in. Open Settings → Library → Account → Changpei → Changpei account and scan the code with the Changpei app. Or tap Paste Cookie and paste the cookie from the website.",
["长佩账号"] = "Changpei account",
["确定退出长佩账号?"] = "Sign out of Changpei?",
["长佩登录 Cookie"] = "Changpei login cookie",
["用长佩 App 扫一扫"] = "Scan with the Changpei app",
["长佩扫码登录"] = "Changpei QR sign-in",
["已在手机上拒绝登录"] = "Sign-in rejected on the phone",
["未登录长佩"] = "Not signed in to Changpei",
["缺少长佩章节位置"] = "Changpei chapter position missing",
["长佩榜单为空"] = "Changpei rankings are empty",
["重试"] = "Retry",
["书架同步"] = "Shelf sync",
["搜索与发现"] = "Search and discover",
["进度同步"] = "Progress sync",
["长佩文学书架与在线阅读"] = "Changpei shelf and online reading",
["重新登录长佩"] = "Sign in to Changpei again",
["用长佩 App 扫码"] = "Scan with the Changpei app",
}
@@ -0,0 +1,65 @@
return {
["综合"] = "綜合",
["长佩分类条件无效"] = "長佩分類條件無效",
["长佩账号标识缺失"] = "長佩帳號識別碼缺失",
["长佩阅读进度未确认"] = "長佩閱讀進度未確認",
["长佩章节解密失败"] = "長佩章節解密失敗",
["书评预览"] = "書評預覽",
["切换长佩账号会清除这台设备上长佩的书架、阅读进度、笔记和缓存,包括尚未同步的记录。不会删除远端书架。确定继续?"] = "切換長佩帳號會清除這台裝置上長佩的書架、閱讀進度、筆記和快取,包括尚未同步的記錄。不會刪除遠端書架。確定繼續?",
["在章末显示本章讨论,不是段落评论"] = "在章末顯示本章討論,不是段落評論",
["7万以下"] = "7萬以下",
["7-15万"] = "7–15萬",
["15-25万"] = "15–25萬",
["25-40万"] = "25–40萬",
["40-60万"] = "40–60萬",
["60万以上"] = "60萬以上",
["完结"] = "完結",
["排行榜"] = "排行榜",
["分类书库"] = "分類書庫",
["切换账号"] = "切換帳號",
["无法确认旧账号,请先退出旧账号再登录"] = "無法確認舊帳號,請先登出舊帳號再登入",
["本章讨论"] = "本章討論",
["人气"] = "人氣",
["连载"] = "連載",
["滑块加载失败,请检查网络后刷新网页"] = "滑塊載入失敗,請檢查網路後重新整理網頁",
["频道"] = "頻道",
["字数"] = "字數",
["章节评论"] = "章節評論",
["价格"] = "價格",
["免费"] = "免費",
["付费"] = "付費",
["用同一 Wi-Fi 下的手机扫码,在网页完成滑块验证后自动继续阅读。无需重新登录或安装浏览器扩展。"] = "用同一 Wi-Fi 下的手機掃碼,在網頁完成滑塊驗證後自動繼續閱讀。無需重新登入或安裝瀏覽器擴充功能。",
["验证已过期,请重新发起验证"] = "驗證已過期,請重新發起驗證",
["验证成功,已在设备上继续打开章节。"] = "驗證成功,已在裝置上繼續打開章節。",
["这个登录是网页 Cookie,放一会儿就会失效,而且不能自动续上。请改用扫码登录:打开「设置 → 书库 → 账号 → 长佩文学 → 长佩账号」,用长佩 App 对准屏幕上的二维码扫一下,再在手机上点确认。提示上如果有「重新登录」,点它,选「用长佩 App 扫码」,是同一件事。"] = "這個登入是網頁 Cookie,放一會兒就會失效,而且不能自動續上。請改用掃碼登入:打開「設定 → 書庫 → 帳號 → 長佩文學 → 長佩帳號」,用長佩 App 對準螢幕上的二維碼掃一下,再在手機上點確認。提示上如果有「重新登入」,點它,選「用長佩 App 掃碼」,是同一件事。",
["章节目录保存失败"] = "章節目錄儲存失敗",
["按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"] = "按鍵盤 F12,點「網路」,重新整理網頁,複製請求標頭裡的整段 Cookie",
["长佩文学 → 粘贴 Cookie"] = "長佩文學 → 貼上 Cookie",
["长佩目录为空"] = "長佩目錄為空",
["长佩章节内容为空"] = "長佩章節內容為空",
["长佩需要滑块验证,请打开章节并扫码完成验证,无需重新登录。"] = "長佩需要滑塊驗證,請打開章節並掃碼完成驗證,無需重新登入。",
["长佩滑块验证"] = "長佩滑塊驗證",
["无法打开远程验证,请先连接 Wi-Fi 并启用远程管理功能"] = "無法打開遠端驗證,請先連接 Wi-Fi 並啟用遠端管理功能",
["验证已取消"] = "驗證已取消",
["验证失败,请重新滑动验证"] = "驗證失敗,請重新滑動驗證",
["验证凭据无效"] = "驗證憑據無效",
["请按住滑块,拖动到最右边"] = "請按住滑塊,拖動到最右邊",
["正在提交验证…"] = "正在提交驗證…",
["还没登录长佩。打开「设置 → 书库 → 账号 → 长佩文学 → 长佩账号」,用长佩 App 扫二维码。也可以点「粘贴 Cookie」,把网页里的 Cookie 贴进去。"] = "還沒登入長佩。打開「設定 → 書庫 → 帳號 → 長佩文學 → 長佩帳號」,用長佩 App 掃二維碼。也可以點「貼上 Cookie」,把網頁裡的 Cookie 貼進去。",
["长佩账号"] = "長佩帳號",
["确定退出长佩账号?"] = "確定登出長佩帳號?",
["长佩登录 Cookie"] = "長佩登入 Cookie",
["用长佩 App 扫一扫"] = "用長佩 App 掃一掃",
["长佩扫码登录"] = "長佩掃碼登入",
["已在手机上拒绝登录"] = "已在手機上拒絕登入",
["未登录长佩"] = "未登入長佩",
["缺少长佩章节位置"] = "缺少長佩章節位置",
["长佩榜单为空"] = "長佩榜單為空",
["重试"] = "重試",
["书架同步"] = "書架同步",
["搜索与发现"] = "搜尋與發現",
["进度同步"] = "進度同步",
["长佩文学书架与在线阅读"] = "長佩文學書架與線上閱讀",
["重新登录长佩"] = "重新登入長佩",
["用长佩 App 扫码"] = "用長佩 App 掃碼",
}
@@ -0,0 +1,5 @@
return function()
local copy = {}
for k, v in pairs(require("moonsource_changpei._meta")) do copy[k] = v end
return copy
end
@@ -0,0 +1,208 @@
--[[--
长佩文学网数据映射(纯函数):网页 JSON 接口 → 领域对象。
@module koplugin.book.moonsource_changpei.mapper
--]]
local Aes = require("crypto.aes")
local Text = require("utils.text")
local _ = require("l10n").get("moonsource_changpei")
local Mapper = {}
local SOURCE_ID = "ext.changpei"
-- 网页端正文 AES-128-CBC 的固定密钥与 IV(出自官网 h5 脚本)。
local KEY = "u0LRrbu$Enm84koA"
local IV = "$h$b3!iGzsYnnshj"
--- 封面链接的 ?x-oss-process 只是缩略样式,去掉就是原图。
---@param url string|nil
---@return string|nil
local function cover(url)
if type(url) ~= "string" or url == "" or url:find("nocover", 1, true) then return nil end
return (url:gsub("%?.*$", ""))
end
---@param wire table
---@return Book[]
function Mapper.search(wire)
local out = {}
local list = type(wire.data) == "table" and wire.data.list or {}
for _idx, row in ipairs(list) do
if row.novel_id then
local process = tonumber(row.novel_process or row.process)
out[#out + 1] = {
source_id = SOURCE_ID,
stable_id = tostring(row.novel_id),
title = Text.trim(row.novel_name),
authors = Text.trim(row.novel_author),
category = row.novel_type ~= "" and row.novel_type or nil,
intro = Text.trim(row.novel_info or row.novel_desc or ""),
cover = cover(row.novel_cover),
meta = {
words = tonumber(row.novel_wordnumber),
status = process == 1 and "连载" or process == 2 and "完结" or nil,
},
}
end
end
return out
end
---@param wire table
---@return Book|nil, string|nil
function Mapper.detail(wire)
local row = wire.data
if type(row) ~= "table" or not row.novel_id or type(row.novel_name) ~= "string" then
return nil, _("响应无效")
end
local book = Mapper.search({ data = { list = { row } } })[1]
book.authors = row.author_nickname
book.category = type(row.type_names) == "table" and table.concat(row.type_names, " · ") or row.type_names
return book
end
--- 网页 count 在有评论时也可能是 0,以实际页长判断是否还有下一页。
---@param wire table
---@param module string
---@param id string
---@param page integer
---@return table|nil, string|nil
function Mapper.comments(wire, module, id, page)
local data = wire.data
if type(data) ~= "table" or type(data.list) ~= "table" then return nil, _("响应无效") end
local items = {}
for _idx, row in ipairs(data.list) do
if type(row) ~= "table" then return nil, _("响应无效") end
local belongs = module == "chapter" and row.replay_module == "novel_chapter"
and tostring(row.replay_cid) == tostring(id)
or module == "novel" and (
row.replay_module == "novel" and tostring(row.replay_cid) == tostring(id)
or row.replay_module == "novel_chapter" and tostring(row.novel_id) == tostring(id))
if not belongs or not row.replay_id or type(row.replay_content) ~= "string" then
return nil, _("响应无效")
end
items[#items + 1] = {
id = tostring(row.replay_id), author = row.replay_nickname or "",
content = row.replay_content, text = row.replay_content, time = row.replay_time or "",
reply_to = module == "novel" and row.replay_module == "novel_chapter" and row.novel_chapter_name or nil,
replies = tonumber(row.child_comment_number) or 0,
}
end
local count = tonumber(data.count)
local total = math.max(count or 0, (page - 1) * 10 + #items)
return { items = items, total = total, max_idx = page,
more = #items == 10 and (not count or count == 0 or page * 10 < count) }
end
--- rankingNav → 榜单列表 { rid, name, types = { { value, name } } };带 url 的是跳转活动页的入口、没有子榜的不收。
---@param wire table
---@return table[]
function Mapper.ranks(wire)
local out = {}
for _idx, row in ipairs(type(wire.data) == "table" and wire.data or {}) do
if not row.url and type(row.type) == "table" and #row.type > 0 then
out[#out + 1] = { rid = row.rank_id, name = row.name, types = row.type }
end
end
return out
end
--- usercoll/getList 的书行 → 书架。
---@param rows table[]
---@return Book[]
function Mapper.shelfList(rows)
local out = {}
for _idx, row in ipairs(rows) do
out[#out + 1] = {
source_id = SOURCE_ID,
stable_id = tostring(row.id),
title = Text.trim(row.name),
authors = Text.trim(row.author),
cover = cover(row.cover),
}
end
return out
end
--- getHistory(按日期分组的 list)→ novel_id → 最近读到的章 id。
---@param wire table
---@return table<string, string>
function Mapper.history(wire)
local out = {}
local groups = type(wire.data) == "table" and wire.data.list or {}
for _idx, group in ipairs(groups) do
for _row, row in ipairs(group.list or {}) do
local cid = tonumber(row.latest_read_cid)
if row.novel_id and cid and cid > 0 and not out[tostring(row.novel_id)] then
out[tostring(row.novel_id)] = tostring(cid)
end
end
end
return out
end
--- 目录缓存格式版本。
Mapper.TOC_VERSION = 1
--- chapterGetList → 目录。只收 type = "item"(还有分页占位 "more");price > 0 的是 VIP 章。
---@param wire table
---@return BookChapter[]|nil, string|nil
function Mapper.toc(wire)
local toc = {}
local list = type(wire.data) == "table" and wire.data.list
if type(list) ~= "table" then return nil, _("响应无效") end
for _idx, row in ipairs(list) do
if row.type == "item" then
toc[#toc + 1] = {
idx = #toc + 1,
uid = tostring(row.id),
title = row.name,
vip = (tonumber(row.price) or 0) > 0 or nil,
paid = (tonumber(row.price) or 0) > 0 and (row.is_sub == true or tonumber(row.is_sub) == 1
or tonumber(row.whole_book_is_bought) == 1 or tonumber(row.is_free_limit) == 1),
}
end
end
if toc[1] then toc[1].toc_version = Mapper.TOC_VERSION end
return toc
end
--- chapterGetInfo → 正文纯文本;没买的 VIP 章返回 nil, "unpaid"。
--- data.check > 1 时不解密、不给正文,交给开章入口验证后重取。
---@param wire table
---@return string|nil text
---@return string|nil err
---@return "unpaid"|"verify"|nil kind
function Mapper.content(wire)
local info = type(wire.data) == "table" and wire.data.chapterInfo
if type(info) ~= "table" then return nil, wire.msg end
local check = tonumber(wire.data.check) or 0
if check > 1 then return nil, nil, "verify" end
-- isSub 在接口里是 "0" / "1" 字符串("0" 在 Lua 里是真值)
local locked = (tonumber(info.chapterPrice) or 0) > 0 and not (info.isSub == true or tonumber(info.isSub) == 1)
local text
if type(info.content) == "string" and info.content ~= "" then
local plain = Aes.cbc_decrypt(Text.base64Decode(info.content), KEY, IV)
if plain and Text.isValidUtf8(plain) and not plain:find("[%z\1-\8\11\12\14-\31\127]") then
local lines = {}
for line in (plain .. "\n"):gmatch("(.-)\r?\n") do
line = Text.trim(line)
if line ~= "" then lines[#lines + 1] = line end
end
if #lines > 0 then text = table.concat(lines, "\n") end
elseif not locked then
return nil, _("长佩章节解密失败")
end
end
if text then return text end
if locked then return nil, nil, "unpaid" end
if type(info.content) ~= "string" or info.content == "" then
return nil, _("长佩章节内容为空")
end
return nil, _("长佩章节解密失败")
end
return Mapper
@@ -0,0 +1,285 @@
--[[--
长佩扫码登录。
官网登录页的扫码走 gRPC-web(POST /cp.UserExternal/<方法>,请求头 version / imei 必带,否则回「系统繁忙」):
get_qrcode_token(scene="Login") → { token, uid },二维码内容是固定的 transfer/login/middleware URL,用长佩 App 扫;
qrcode_polling(token) → { status, login_res, token },status 1 待扫 / 2 已扫待确认 / 3 拒绝 / 4 通过 / 5 失效,
二维码过期时 grpc-status 非 0。登录态挂在服务端会话(PHPSESSID)上:先请求 webapi 拿到 PHPSESSID,
轮询带着它,通过后这个会话即已登录。设备号 `_c_n_` 是网页端随机生成的 MD5(同时作 imei 请求头),这里照做。
Cookie 交给 on_cookie,由设置页走账号校验再保存。
@module koplugin.book.moonsource_changpei.qrlogin
--]]
local Request = require("http.request")
local _ = require("l10n").get("moonsource_changpei")
local QRLogin = {}
QRLogin.__index = QRLogin
local ORIGIN = "https://www.gongzicp.com"
local POLL_INTERVAL = 2
local DEADLINE = 180
local STATUS_WAITING_AUTH, STATUS_REJECT, STATUS_APPROVED = 2, 3, 4
---- 一帧 gRPC-web:0x00 + 4 字节长度 + protobuf 字符串字段。
---@param value string
---@param field? integer
---@return string
function QRLogin.frame(value, field)
local length, bytes = #value, {}
repeat
local byte = length % 128
length = math.floor(length / 128)
bytes[#bytes + 1] = string.char(byte + (length > 0 and 128 or 0))
until length == 0
local msg = string.char((field or 1) * 8 + 2) .. table.concat(bytes) .. value
local n = #msg
return string.char(0, math.floor(n / 16777216) % 256, math.floor(n / 65536) % 256,
math.floor(n / 256) % 256, n % 256) .. msg
end
--- 解一帧里的顶层 protobuf 字段:varint → 数字,其余 → 字符串;同号取首个。
---@param body string
---@return table<integer, number|string>
function QRLogin.decode(body)
if #body < 5 or body:byte(1) ~= 0 then return {} end
local length = body:byte(2) * 16777216 + body:byte(3) * 65536 + body:byte(4) * 256 + body:byte(5)
if length > #body - 5 then return {} end
return QRLogin.fields(body:sub(6, 5 + length))
end
--- 解一段裸 protobuf(不带 gRPC 帧头)。
---@param data string
---@return table<integer, number|string>
function QRLogin.fields(data)
local out, pos = {}, 1
local function varint()
local value, shift = 0, 1
while pos <= #data do
local byte = data:byte(pos)
pos = pos + 1
value = value + (byte % 128) * shift
if byte < 128 then return value end
shift = shift * 128
end
return value
end
while pos <= #data do
local tag = varint()
local field, wire = math.floor(tag / 8), tag % 8
local value
if wire == 0 then
value = varint()
elseif wire == 2 then
local len = varint()
value = data:sub(pos, pos + len - 1)
pos = pos + len
else
break
end
if out[field] == nil then out[field] = value end
end
return out
end
--- 回包 Set-Cookie 里的 name=value 收进 jar。
---@param jar table<string, string>
---@param res table
local function takeCookies(jar, res)
for _idx, line in ipairs(Request.headerAll(res, "Set-Cookie")) do
local name, value = line:match("^%s*([^=;%s]+)=([^;]*)")
if name and value ~= "" and value ~= "deleted" then jar[name] = value end
end
end
---@param jar table<string, string>
---@return string
local function cookieHeader(jar)
local names = {}
for name in pairs(jar) do names[#names + 1] = name end
table.sort(names)
for i, name in ipairs(names) do names[i] = name .. "=" .. jar[name] end
return table.concat(names, "; ")
end
---@param on_cookie fun(cookie: string)
function QRLogin.new(_class, on_cookie)
return setmetatable({ on_cookie = on_cookie, generation = 0, jar = {} }, QRLogin)
end
function QRLogin:toast(text)
require("ui.themes.widgets.toast"):new{ text = text, timeout = 2 }:show()
end
---@param method string
---@param value string
---@param cb fun(fields: table|nil, res: table|nil, err: string|nil)
function QRLogin:_call(method, value, cb)
local gen, pending = self.generation, true
local headers = {
["Content-Type"] = "application/grpc-web+proto",
["X-Grpc-Web"] = "1",
["Client"] = "pc",
["version"] = "1",
["imei"] = self.jar._c_n_,
["Referer"] = ORIGIN .. "/",
["User-Agent"] = require("moonsource_changpei.client").USER_AGENT,
}
local cookie = cookieHeader(self.jar)
if cookie ~= "" then headers["Cookie"] = cookie end
local job = Request.post(ORIGIN .. "/cp.UserExternal/" .. method, QRLogin.frame(value), {
headers = headers,
content_type = "application/grpc-web+proto",
-- 官网待扫码响应会挂起约 30 秒,不能套用普通请求的 15 秒超时。
timeout = method == "qrcode_polling" and DEADLINE or require("http.timeout").net(0.5),
}, function(body, err, res)
pending = false
if gen ~= self.generation then return end
self.job = nil
if not body then cb(nil, res, err and tostring(err) or _("请求失败")); return end
takeCookies(self.jar, res)
local status = tonumber(Request.header(res, "grpc-status")) or 0
if status ~= 0 then cb(nil, res, "grpc " .. status); return end
cb(QRLogin.decode(body), res)
end)
if pending then self.job = job end
end
function QRLogin:_closeDialog()
local dialog = self.dialog
self.dialog = nil
if dialog then dialog:close() end
end
function QRLogin:cancel()
self.generation = self.generation + 1
if self.job then self.job.cancel(); self.job = nil end
self:_closeDialog()
end
function QRLogin:_retry(text)
self:cancel()
require("ui.themes.widgets.confirm"):new{
text = text,
ok_text = _("重新获取"),
ok_callback = function() self:start() end,
}:show()
end
---@param gen integer
---@param token string
---@param started integer
function QRLogin:_poll(gen, token, started)
if os.time() - started >= DEADLINE then self:_retry(_("二维码已过期")); return end
self:_call("qrcode_polling", token, function(fields, _res, err)
if gen ~= self.generation then return end
if not fields then
-- grpc-status 非 0:二维码失效;网络错误同样重新获取,比无声地一直轮询好
self:_retry(err and err:match("^grpc ") and _("二维码已过期") or err or _("请求失败"))
return
end
local status = fields[1]
if status == STATUS_APPROVED then
if self.saved_cookie ~= require("moonsource_changpei.client").cookie() then
self:cancel()
self:toast(_("账号已变化,请重新登录"))
return
end
local cookie = self.jar.PHPSESSID and cookieHeader(self.jar)
-- login_res(2).web_data(4).token(1):网页端后续请求靠它认人;refresh_token(2) 在 token 失效时换新的
local login = type(fields[2]) == "string" and QRLogin.fields(fields[2]) or {}
local web = type(login[4]) == "string" and QRLogin.fields(login[4] --[[@as string]]) or {}
require("utils.log").info("changpei qr approved", "login_status", login[1], "token", web[1] and #web[1] or 0,
"refresh", type(web[2]) == "string" and #web[2] or 0)
if cookie and type(web[1]) == "string" and web[1] ~= "" then
cookie = cookie .. "; moon_token=" .. web[1]
if type(web[2]) == "string" and web[2] ~= "" then cookie = cookie .. "; moon_refresh=" .. web[2] end
end
self:cancel()
if not cookie then self:toast(_("登录失败:未获取到登录态")); return end
self.on_cookie(cookie)
elseif status == STATUS_REJECT then
self:_retry(_("已在手机上拒绝登录"))
elseif status == 5 or os.time() - started >= DEADLINE then
self:_retry(_("二维码已过期"))
elseif status ~= 1 and status ~= STATUS_WAITING_AUTH then
self:_retry(_("响应无效"))
else
if status == STATUS_WAITING_AUTH and not self.scanned then
self.scanned = true
self:toast(_("已扫码,请在手机上确认"))
end
require("ui/uimanager"):scheduleIn(POLL_INTERVAL, function()
if gen == self.generation then self:_poll(gen, token, started) end
end)
end
end)
end
function QRLogin:start()
self:cancel()
self.saved_cookie = require("moonsource_changpei.client").cookie()
local gen = self.generation
local device = require("utils.random").hex(16)
self.jar, self.scanned = { _c_n_ = device, _c_n_n_ = device }, false
self:_session(function(ok)
if gen ~= self.generation then return end
if not ok then
self:toast(_("获取二维码失败"))
return
end
self:_call("get_qrcode_token", "Login", function(fields)
if gen ~= self.generation then return end
self:_show(gen, fields)
end)
end)
end
--- webapi 的任何接口都会下发 PHPSESSID。
---@param cb fun(ok: boolean)
function QRLogin:_session(cb)
local client = require("moonsource_changpei.client")
local gen, pending = self.generation, true
local job = Request.get(ORIGIN .. "/webapi/system/init", {
headers = { ["Client"] = "pc", ["User-Agent"] = client.USER_AGENT, ["Cookie"] = cookieHeader(self.jar) },
timeout = require("http.timeout").net(0.5),
}, function(_body, _err, res)
pending = false
if gen ~= self.generation then return end
self.job = nil
if res then takeCookies(self.jar, res) end
cb(self.jar.PHPSESSID ~= nil)
end)
if pending then self.job = job end
end
---@param gen integer
---@param fields table|nil
function QRLogin:_show(gen, fields)
local token, uid = fields and fields[1], fields and fields[2]
if type(token) ~= "string" or token == "" then
self:toast(_("获取二维码失败"))
return
end
local dialog
dialog = require("ui.themes.widgets.qr"):new{
title = _("长佩扫码登录"),
text = ORIGIN .. "/transfer/login/middleware?token=" .. token .. "&uid=" .. tostring(uid or 0)
.. "&pageType=app_qr_code_login",
caption = _("用长佩 App 扫一扫"),
close_callback = function()
if self.dialog == dialog then
self.dialog = nil
self:cancel()
self:toast(_("已取消登录"))
end
end,
}
self.dialog = dialog
dialog:show()
self:_poll(gen, token, os.time())
end
return QRLogin
@@ -0,0 +1,103 @@
--[[--
长佩源设置:登录。
长佩网页的登录态是 Cookie(PHPSESSID 等,含 HttpOnly)。没有登录态时服务端要求人机验证、不给正文。
登录三条路:扫码(长佩 App 扫,qrlogin.lua)、浏览器扩展授权(check 靠 JSON code 判定)、或在电脑浏览器登录后把请求里的 Cookie 请求头粘贴进来。
拿到 Cookie 先拉一次账号信息校验,通过才保存。
@module koplugin.book.moonsource_changpei.setting
--]]
local _ = require("l10n").get("moonsource_changpei")
local CookieLogin = require("source.cookie_login")
local SOURCE_ID = "ext.changpei"
local Setting = {}
---@return boolean
local function loggedIn()
return require("moonsource_changpei.client").cookie() ~= nil
end
local function commit(cookie, account, cb, current)
if not account or not tonumber(account.uid) or tonumber(account.uid) <= 0 then
cb(false, _("长佩账号标识缺失")); return
end
return CookieLogin.commitAccount(SOURCE_ID, cookie, tostring(account.uid), 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_changpei.client")
local previous = Client.cookie()
return Client.userAsync(cookie, function(info, err)
if previous ~= Client.cookie() 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)。getUserInfo 一律 HTTP 200,靠 JSON code 判登录(未登录 9996)。
Setting.browser = {
domain = "www.gongzicp.com",
scope = "cookie",
login = "https://www.gongzicp.com/login/signin",
check = "https://www.gongzicp.com/webapi/user/getUserInfo",
check_json = { path = "code", ok = { 200 } },
icon = "https://www.gongzicp.com/favicon.ico",
isAuthorized = function() return CookieLogin.authorized(SPEC) end,
apply = function(payload, cb) return CookieLogin.save(SPEC, CookieLogin.fromPayload(payload, "gongzicp.com"), cb) end,
}
local function startQR()
require("ui/network/manager"):runWhenConnected(function()
require("moonsource_changpei.qrlogin"):new(function(cookie) CookieLogin.verify(SPEC, cookie) end):start()
end)
end
---@return table[]
function Setting.rows()
local rows = {
CookieLogin.accountRow(SPEC, { callback = startQR }),
CookieLogin.browserRow(),
CookieLogin.pasteRow(SPEC),
}
if loggedIn() then rows[#rows + 1] = CookieLogin.logoutRow(SPEC) end
rows[#rows + 1] = function(iw)
local ReviewSetting = require("source.review_setting")
local enabled = ReviewSetting.enabled(SOURCE_ID)
return require("ui.themes.widgets.row").widget({
width = iw, kind = "toggle", icon = "forum", title = _("章节评论"),
subtitle = _("在章末显示本章讨论,不是段落评论"), chevron = false,
status = enabled and _("开") or _("关"), status_on = enabled,
callback = function() ReviewSetting.set(SOURCE_ID, not enabled) end,
})
end
return rows
end
--- 登录失效提示的「重新登录」直达账号页里的扫码行。
local function chooseLogin()
startQR()
end
Setting.login = chooseLogin
return Setting
@@ -0,0 +1,306 @@
--[[--
长佩文学网数据源。
网页 JSON 接口(client.lua):搜索、分类与榜单、详情、目录、正文、书评与章评;登录 Cookie(setting.lua)后已购 VIP 章可读,书架双向同步
(source.shelf,网页书架接口,分组里的书不同步),进度只到章(读阅读历史,写靠取一次当前章)。没有笔记和统计。
没买的 VIP 章开章给临时提示页,目录标「未购」。
@module moonsource_changpei
--]]
local Browse = require("source.browse")
local Client = require("moonsource_changpei.client")
local Mapper = require("moonsource_changpei.mapper")
local Shelf = require("source.shelf")
local SourceBase = require("source.base")
local Toc = require("source.toc")
local _ = require("l10n").get("moonsource_changpei")
local Changpei = {}
-- 接口按 IP 限流,预取与整本缓存逐章间隔请求。
local FETCH_INTERVAL = 1
---@return BookSourceMeta
function Changpei.meta()
return require("moonsource_changpei.loadmeta")()
end
---@class ChangpeiSource : SourceBase
local Source = setmetatable({ shelf_add = true }, { __index = SourceBase })
Source.__index = Source
---@return ChangpeiSource
function Changpei.new()
local meta = Changpei.meta()
return setmetatable({ id = meta.id, name = meta.name, type = meta.type }, Source)
end
--- 搜索 / 目录匿名可用,但读正文和书架、进度都要登录 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, "changpei not logged in") end
return Shelf.syncAsync(self.id, Remote, Mapper.shelfList, opts, cb)
end
--- 进度只到章:读阅读历史里这本书最近读到的章。
function Source:getProgressAsync(identity, cb)
if not self:configured() then return SourceBase.defer(cb, nil, _("未登录长佩")) end
local cancelled, job, pending = false, nil, true
local initial = Client.historyAsync(function(wire, err)
pending = false
if cancelled then return end
if not wire then cb(nil, err); return end
if type(wire.data) ~= "table" or type(wire.data.list) ~= "table" then
cb(nil, _("响应无效")); return
end
local uid = Mapper.history(wire)[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 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 cancelled, job, pending = false, nil, true
local initial = self:loadTocAsync(identity, function(toc, err)
pending = false
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 then cb(nil, _("缺少长佩章节位置")); return end
job = Client.markReadAsync(chapter.uid, function(ok, reason)
if not cancelled then cb(ok, reason) 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(wire, err)
if not wire then
cb(nil, err)
return
end
if type(wire.data) ~= "table" or type(wire.data.list) ~= "table" then
cb(nil, _("响应无效")); return
end
cb({ data = Mapper.search(wire) })
end)
end
--- 书城浏览:榜单 / 子榜两行 chip,节点是「榜单号:子榜值」,缺省第一个榜单的第一个子榜。榜单每页 10 本。
---@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 {}
if not opts.node or opts.node:sub(1, 5) == "cate:" then
return require("moonsource_changpei.browse").run(opts, cb)
end
local handle = {}
local pending = true
local initial = Client.rankNavAsync(function(nav, err)
pending = false
if handle.cancelled then return end
if not nav then cb(nil, err); return end
local ranks = Mapper.ranks(nav)
if #ranks == 0 then cb(nil, _("长佩榜单为空")); return end
local rid, tid = (opts.node or ""):match("^(%d+):(%d+)$")
local rank = ranks[1]
for _idx, row in ipairs(ranks) do
if tostring(row.rid) == rid then rank = row end
end
tid = tonumber(tid)
local sub = rank.types[1].value
for _idx, row in ipairs(rank.types) do
if row.value == tid then sub = tid end
end
local rank_chips, sub_chips = {}, {}
rank_chips[1] = { id = "cate:0:0:0:2:0:8", title = _("分类书库") }
for _idx, row in ipairs(ranks) do
rank_chips[#rank_chips + 1] = { id = row.rid .. ":" .. row.types[1].value, title = row.name }
end
for _idx, row in ipairs(rank.types) do
sub_chips[#sub_chips + 1] = { id = rank.rid .. ":" .. row.value, title = row.name }
end
local groups = {
Browse.group(rank_chips, rank.rid .. ":" .. rank.types[1].value),
Browse.group(sub_chips, rank.rid .. ":" .. sub),
}
local total = 0
handle.inner = Browse.pages(function(page, done)
return Client.rankAsync(rank.rid, sub, page, function(wire, reason)
if not wire then done(nil, reason); return end
if type(wire.data) ~= "table" or type(wire.data.list) ~= "table" or not tonumber(wire.data.count) then
done(nil, _("响应无效")); return
end
total = tonumber(wire.data and wire.data.count) or 0
done(Mapper.search(wire), nil, page * 10 < total)
end)
end, opts.limit or 20, groups, cb)
end)
if pending then handle.inner = initial end
return { cancel = function()
handle.cancelled = true
if handle.inner then handle.inner.cancel() end
end }
end
function Source:getDetailAsync(identity, cb)
if not require("ui/network/manager"):isConnected() then
return SourceBase.defer(cb, identity.book or require("book.books_db").get(self.id, identity.stable_id))
end
return Client.detailAsync(identity.stable_id, function(wire, err)
if not wire then cb(nil, err); return end
local book, reason = Mapper.detail(wire)
if not book then cb(nil, reason); return end
cb(require("book.store").rememberDetail(book))
end)
end
function Source:bookReviewsAsync(identity, cb)
local ref = { source_id = self.id, stable_id = identity.stable_id }
return require("book.review_cache").pageAsync(ref, "book", 0, function(done)
return Client.commentsAsync("novel", identity.stable_id, 1, function(wire, err)
if not wire then done(nil, err); return end
local page, reason = Mapper.comments(wire, "novel", identity.stable_id, 1)
if page then page.title = page.more and _("书评预览") or _("书评") end
done(page, reason)
end)
end, cb)
end
function Source:paragraphReviewsEnabled()
return require("source.review_setting").enabled(self.id)
end
function Source:paragraphReviewPageAsync(identity, range, max_idx, cb)
if range ~= "chapter" then return SourceBase.defer(cb, nil, _("缺少长佩章节位置")) end
return require("book.review_cache").pageAsync(identity, range, max_idx, function(done)
return require("source.with_chapter_uid").run(self, identity, _("缺少长佩章节位置"), function(uid, finish)
local page = tonumber(max_idx) + 1
return Client.commentsAsync("chapter", uid, page, function(wire, err)
if not wire then finish(nil, err); return end
finish(Mapper.comments(wire, "chapter", uid, page))
end)
end, done)
end, cb)
end
function Source:chapterReviewHotspotsAsync(identity, cb)
return require("book.review_cache").hotspotsAsync(identity, function(done)
return self:paragraphReviewPageAsync(identity, "chapter", 0, function(page, err)
if not page then done(nil, err); return end
local spots = {}
if #page.items > 0 then
spots[1] = { range = "chapter", text = _("本章讨论"), total = page.total,
badge = tostring(page.total) .. (page.more and "+" or ""), heading = _("章节评论"),
anchor = require("book.review_locate").CHAPTER_ANCHOR }
end
done(spots)
end)
end, 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(wire, err)
if not wire then cb(nil, err); return end
local toc, reason = Mapper.toc(wire)
if not toc then cb(nil, reason); 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
or not require("ui/network/manager"):isConnected()) 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 locate = require("book.review_locate")
local reviews = self:paragraphReviewsEnabled()
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.openContentAsync, 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 Changpei
@@ -0,0 +1,117 @@
--[[--
长佩滑块验证:一次开章拥有一个会话,票据仅能提交验证,不能访问远程管理的其它接口。
五分钟后、关窗或取消开书即销毁;Cookie 留在设备,不发送到网页。
@module koplugin.book.moonsource_changpei.verify
--]]
local Ext = require("utils.extension")
local Random = require("utils.random")
local Client = require("moonsource_changpei.client")
local _ = require("l10n").get("moonsource_changpei")
---@class ChangpeiVerification
---@field ticket string
---@field cookie string|nil
---@field callback fun(ok: boolean, err: string|nil)
---@field expires integer
---@field dialog BookThemeQR|nil
---@field pending table|nil
---@field timeout function
---@field done boolean|nil
local Verification = {}
Verification.__index = Verification
---@type table<string, ChangpeiVerification>
local sessions = {}
function Verification:cancel()
if self.done then return end
self.done = true
sessions[self.ticket] = nil
require("ui/uimanager"):unschedule(self.timeout)
if self.pending and self.pending.job then self.pending.job:cancel() end
if self.dialog then self.dialog:close() end
end
function Verification:finish(ok, err)
if self.done then return end
self:cancel()
self.callback(ok, err)
end
---@param cb fun(ok: boolean, err: string|nil)
---@return ChangpeiVerification
function Verification.new(cb)
local self = setmetatable({
ticket = Random.hex(24), cookie = Client.cookie(), callback = cb, expires = os.time() + 300,
}, Verification)
self.timeout = require("ui.guard").wrap("source verification timeout", function()
self:finish(false, _("验证已过期,请重新发起验证"))
end)
sessions[self.ticket] = self
require("ui/uimanager"):scheduleIn(300, self.timeout)
self.dialog = Ext.call("web.open_page", "/changpei_verify.html#" .. self.ticket,
_("长佩滑块验证"), _("用同一 Wi-Fi 下的手机扫码,在网页完成滑块验证后自动继续阅读。无需重新登录或安装浏览器扩展。"), {
close_callback = function() self:finish(false, _("验证已取消")) end,
})
if not self.dialog then
self:finish(false, _("无法打开远程验证,请先连接 Wi-Fi 并启用远程管理功能"))
end
return self
end
---@param method string
---@param action string
---@param params table
---@param cb fun(status: integer, body: table, headers: string[]|nil)
local function handle(method, action, params, cb)
local function reply(status, body)
cb(status, body, { "Cache-Control: no-store" })
end
if method ~= "POST" then return reply(405, { error = "Method Not Allowed" }) end
if action ~= "config" and action ~= "verify" then return reply(404, { error = "Not Found" }) end
local session = type(params.ticket) == "string" and sessions[params.ticket]
if not session or os.time() >= session.expires or session.cookie ~= Client.cookie() then
return reply(403, { error = _("验证已过期,请重新发起验证") })
end
if action == "config" then
return reply(200, {
title = _("长佩滑块验证"), instruction = _("请按住滑块,拖动到最右边"),
pending = _("正在提交验证…"),
success = _("验证成功,已在设备上继续打开章节。"),
failure = _("验证失败,请重新滑动验证"),
load_error = _("滑块加载失败,请检查网络后刷新网页"),
retry = _("重试"),
})
end
if type(params.token) ~= "string" or params.token == "" or #params.token > 16384 then
return reply(400, { error = _("验证凭据无效") })
end
if session.pending then return reply(409, { error = _("正在提交验证…") }) end
local operation = {}
session.pending = operation
operation.job = Client.readCheckAsync(params.token, function(ok, message)
if session.done then return reply(403, { error = _("验证已过期,请重新发起验证") }) end
if session.pending ~= operation then return end
if os.time() >= session.expires or session.cookie ~= Client.cookie() then
session:finish(false, _("验证已过期,请重新发起验证"))
return reply(403, { error = _("验证已过期,请重新发起验证") })
end
session.pending = nil
if not ok then return reply(400, { error = message or _("验证失败,请重新滑动验证") }) end
reply(200, { ok = true })
session:finish(true)
end)
end
local dir = debug.getinfo(1, "S").source:sub(2):match("(.*/)")
Ext.add("web.routes", {
name = "changpei_verify", dir = dir .. "web",
assets = { "changpei_verify.html", "changpei_verify.js" },
public = { config = 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:12vh auto;padding:24px}
.panel{padding:24px}#captcha-element{min-height:48px;margin:24px 0}
#status{overflow-wrap:anywhere}button[hidden]{display:none}
</style>
</head>
<body>
<main><section class="panel">
<h1 id="title">月读</h1>
<p id="instruction"></p>
<div id="captcha-element"></div><div id="captcha-button"></div>
<p id="status" role="status" aria-live="polite"></p>
<button id="retry" type="button" hidden></button>
</section></main>
<script src="/changpei_verify.js"></script>
</body>
</html>
@@ -0,0 +1,77 @@
(async function () {
'use strict';
const ticket = location.hash.slice(1);
const status = document.getElementById('status');
const retry = document.getElementById('retry');
let messages, captcha;
async function request(action, body) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 45000);
try {
const response = await fetch('/api/changpei_verify/' + action, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ...body, ticket }),
signal: controller.signal,
});
const result = await response.json();
if (!response.ok) throw new Error(result.error || response.statusText);
return result;
} finally {
clearTimeout(timer);
}
}
function failed(error) {
status.textContent = error.message || messages.failure;
retry.hidden = false;
}
retry.onclick = () => {
retry.hidden = true;
status.textContent = '';
if (captcha) captcha.refresh();
else loadCaptcha().catch(failed);
};
async function verify(token) {
status.textContent = messages.pending;
try {
await request('verify', { token });
status.textContent = messages.success;
document.getElementById('captcha-element').hidden = true;
retry.hidden = true;
} catch (error) {
failed(error);
}
}
async function loadCaptcha() {
if (!window.initAliyunCaptcha) {
window.AliyunCaptchaConfig = { region: 'cn', prefix: 'euphyd' };
await new Promise((resolve, reject) => {
const script = document.createElement('script');
const timer = setTimeout(() => reject(new Error(messages.load_error)), 20000);
script.src = 'https://o.alicdn.com/captcha-frontend/aliyunCaptcha/AliyunCaptcha.js';
script.onload = () => { clearTimeout(timer); resolve(); };
script.onerror = () => { clearTimeout(timer); reject(new Error(messages.load_error)); };
document.head.appendChild(script);
});
}
window.initAliyunCaptcha({
SceneId: '1p2ezg9e', mode: 'embed',
element: '#captcha-element', button: '#captcha-button',
slideStyle: { width: Math.min(320, document.getElementById('captcha-element').clientWidth), height: 40 },
getInstance: instance => { captcha = instance; },
success: verify,
fail: () => failed(new Error(messages.failure)),
onError: error => failed(new Error(error.msg || messages.load_error)),
});
}
try {
messages = await request('config', {});
document.title = document.getElementById('title').textContent = messages.title;
document.getElementById('instruction').textContent = messages.instruction;
retry.textContent = messages.retry;
await loadCaptcha();
} catch (error) {
if (messages) failed(error);
else status.textContent = error.message;
}
})();