500 lines
21 KiB
Lua
500 lines
21 KiB
Lua
--[[--
|
||
长佩文学网 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 = "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
|