✨ 初始提交:月读第三方书源插件集合
每个书源一个独立插件目录,含微信读书公众号订阅、书架导入等完整功能。 Co-authored-by: Copilot <[email protected]>
This commit is contained in:
commit
9190db9019
38 files changed
+5783
No files matched your search
@@ -0,0 +1,23 @@
|
||||
# 番茄小说
|
||||
|
||||
| 能力 | 是否支持 | 备注 |
|
||||
| --- | --- | --- |
|
||||
| 扫码登录 | 已实现,未实测 | 番茄小说 App/抖音扫码;手机确认未实测 |
|
||||
| 设备密码与手动 Cookie 登录 | 不支持 | 未提供入口 |
|
||||
| 书架拉取 | 支持 | 包含分组 |
|
||||
| 书架新增与移出 | 已实现,未实测 | 本地先生效,联网后上行;未验证真实增删及回读 |
|
||||
| 搜索 | 部分支持 | 匿名 App 搜索,仅第一页 |
|
||||
| 发现与榜单 | 部分支持 | 男/女频阅读榜、新书榜和动态分类,仅首屏 10 本 |
|
||||
| 完整分类书城 | 不支持 | 未接完整书库、筛选和后续页 |
|
||||
| 详情与目录 | 支持 | 官网详情、完整目录及缓存刷新 |
|
||||
| 文字正文 | 支持 | App 协议下载和解密;受限内容未实测 |
|
||||
| 漫画阅读 | 已实现,未实测 | 下载为 CBZ |
|
||||
| 章节与全本缓存 | 支持 | 已缓存文字章节可离线重开;整本下载未实测 |
|
||||
| 阅读进度同步 | 部分支持 | 仅章节位置,无精确章内位置;真实远端写入未实测 |
|
||||
| 笔记与统计同步 | 不支持 | 仅本地保存 |
|
||||
| 整书书评与章评 | 不支持 | 未接入可验证的独立接口,不代表 App 没有这些功能 |
|
||||
| 段评 | 支持 | 按正文段落定位,支持分页和离线缓存 |
|
||||
| 评论回复 | 支持 | 支持分页;回复页不单独缓存 |
|
||||
| 评论表情 | 部分支持 | 已知标记使用非官方表情映射;图片来自 [Twemoji 16](https://github.com/jdecked/twemoji),版权归 Twitter, Inc. 及贡献者,[CC-BY 4.0](https://creativecommons.org/licenses/by/4.0/);离线缺图不保证字形可见 |
|
||||
| 评论写操作 | 不支持 | 不发评、不点赞、不删评 |
|
||||
| 账号切换 | 不支持直接隔离 | 没有稳定账号隔离;须先退出清理旧数据,未同步记录会丢失 |
|
||||
@@ -0,0 +1,5 @@
|
||||
local _ = require("gettext")
|
||||
return {
|
||||
fullname = _("月读书源:番茄小说"),
|
||||
description = _("给月读增加「番茄小说」书源。需要同时安装月读,与平台官方无关。"),
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
--[[--
|
||||
KOReader 只认带 main.lua 的插件目录;书源本身不需要任何插件钩子,月读读取旁边的 moon_source.lua。
|
||||
--]]
|
||||
local WidgetContainer = require("ui/widget/container/widgetcontainer")
|
||||
|
||||
return WidgetContainer:extend{
|
||||
name = "moonsource_fanqie",
|
||||
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_fanqie.source").meta() end,
|
||||
new = function() return require("moonsource_fanqie.source").new() end,
|
||||
setting = lazy("moonsource_fanqie.setting"),
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
--[[--
|
||||
书源元信息:id / 名称 / 类型,加上启用页展示用的说明与能力清单。`init.lua` 的 `meta()` 直接返回本表。
|
||||
|
||||
@module moonsource_fanqie._meta
|
||||
--]]
|
||||
|
||||
local _ = require("l10n").get("moonsource_fanqie")
|
||||
|
||||
return {
|
||||
id = "ext.fanqie",
|
||||
name = _("番茄小说"),
|
||||
type = "chapter",
|
||||
description = _("番茄小说书架与在线阅读"),
|
||||
abilities = { _("搜索与发现"), _("书架同步"), _("进度同步"), _("他人段评"), _("扫码登录") },
|
||||
}
|
||||
@@ -0,0 +1,553 @@
|
||||
--[[--
|
||||
番茄小说 HTTP 客户端:只走 http.request。
|
||||
|
||||
@module koplugin.book.moonsource_fanqie.client
|
||||
--]]
|
||||
|
||||
local Cookie = require("moonsource_fanqie.cookie")
|
||||
local FanQie = require("moonsource_fanqie.fanqie")
|
||||
local JSON = require("json")
|
||||
local Request = require("http.request")
|
||||
local Text = require("utils.text")
|
||||
local logger = require("utils.log")
|
||||
local _ = require("l10n").get("moonsource_fanqie")
|
||||
local T = require("ffi/util").template
|
||||
|
||||
local Client = {}
|
||||
Client.__index = Client
|
||||
|
||||
---@class FanqieClient
|
||||
---@field rankAsync fun(self: FanqieClient, path: string, cb: function): CancelHandle|nil
|
||||
---@field settings FanqieSettings
|
||||
---@field fetchReadProgressAsync fun(self: FanqieClient, cb: function): CancelHandle|nil
|
||||
---@field updateReadProgressAsync fun(self: FanqieClient, book_id: string, item_id: string, index: number, progress: number, cb: function): CancelHandle|nil
|
||||
---@field fetchChapterDirectoryAsync fun(self: FanqieClient, book_id: string, cb: function): CancelHandle|nil
|
||||
---@field fetchBookDetailAsync fun(self: FanqieClient, book_id: string, cb: function): CancelHandle
|
||||
---@field fetchShelfDetailAsync fun(self: FanqieClient, force_refresh: boolean|nil, cb: function): CancelHandle|nil
|
||||
---@field searchAsync fun(self: FanqieClient, keyword: string, cb: function): { cancel: fun() }
|
||||
---@field shelfActionAsync fun(self: FanqieClient, action: "add"|"delete", book_id: string, cb: function): { cancel: fun() }
|
||||
---@field officialGetContentAsync fun(self: FanqieClient, book_id: string, item_id: string, cb: function): CancelHandle|nil
|
||||
|
||||
local TIMEOUT_RATIO = 0.5 -- × 「网络超时」,缺省 15 秒
|
||||
local SHELF_CACHE_TTL = 5 * 60
|
||||
-- 书架逐本拉详情的并发上限:一次全发会被风控。
|
||||
local DETAIL_LIMIT = 4
|
||||
local SHELF_CACHE = {}
|
||||
|
||||
local AUTH_ERROR_CODES = {
|
||||
[-2012] = true,
|
||||
[-2041] = true,
|
||||
[101108] = true, -- 无用户信息
|
||||
[101119] = true, -- BOOKSHELF_GET_ERROR:无有效 sessionid
|
||||
}
|
||||
|
||||
---@param data table|nil
|
||||
---@param fallback string
|
||||
---@return string
|
||||
local function businessError(data, fallback)
|
||||
if type(data) ~= "table" then
|
||||
return fallback
|
||||
end
|
||||
local err_code = data.errCode or data.errcode or data.code
|
||||
local err_message = data.errMsg or data.errmsg or data.message or data.msg
|
||||
local parts = { fallback }
|
||||
if err_code ~= nil then
|
||||
parts[#parts + 1] = "code=" .. tostring(err_code)
|
||||
end
|
||||
if err_message ~= nil and tostring(err_message) ~= "" then
|
||||
parts[#parts + 1] = "message="
|
||||
.. tostring(err_message):gsub("[%c]+", " "):sub(1, 200)
|
||||
end
|
||||
if AUTH_ERROR_CODES[tonumber(err_code)]
|
||||
or (err_message and tostring(err_message):find("登录", 1, true))
|
||||
then
|
||||
parts[#parts + 1] = "请重新扫码登录"
|
||||
end
|
||||
return table.concat(parts, ", ")
|
||||
end
|
||||
|
||||
---@param text string|nil
|
||||
---@return table|nil, string|nil
|
||||
local function decodeJson(text)
|
||||
if type(text) ~= "string" or text == "" then
|
||||
return nil, _("响应为空")
|
||||
end
|
||||
local ok, data = pcall(JSON.decode, text)
|
||||
if not ok or type(data) ~= "table" then
|
||||
return nil, _("响应无效")
|
||||
end
|
||||
return data
|
||||
end
|
||||
|
||||
---@param settings table
|
||||
---@return FanqieClient
|
||||
function Client:new(settings)
|
||||
return setmetatable({ settings = settings }, self)
|
||||
end
|
||||
|
||||
---@param self FanqieClient
|
||||
---@param res table|nil
|
||||
local function absorbCookies(self, res)
|
||||
local set_cookie = Request.header(res, "Set-Cookie")
|
||||
if not set_cookie then return end
|
||||
local cookies = self.settings:get("cookies", {})
|
||||
local before = Cookie.to_header(cookies)
|
||||
local merged = Cookie.merge_set_cookie(cookies, set_cookie)
|
||||
-- 书架详情一次并发几十个请求,值没变就不每次落盘。
|
||||
if Cookie.to_header(merged) == before then return end
|
||||
self.settings:set("cookies", merged)
|
||||
self.settings:flush()
|
||||
end
|
||||
|
||||
---@param code number|nil
|
||||
---@param body string|nil
|
||||
---@param res table|nil
|
||||
---@return boolean
|
||||
local function isAuthError(code, body, res)
|
||||
if code == 401 or code == 403 then return true end
|
||||
body = tostring(body or "")
|
||||
local content_type = tostring(Request.header(res, "Content-Type") or "")
|
||||
local looks_json = content_type:lower():find("json", 1, true)
|
||||
or body:match("^%s*{") ~= nil
|
||||
if not looks_json or #body > 65536 then return false end
|
||||
local data = decodeJson(body)
|
||||
if type(data) ~= "table" then return false end
|
||||
local err_code = data.errCode or data.errcode or data.code
|
||||
if AUTH_ERROR_CODES[tonumber(err_code)] then return true end
|
||||
local msg = tostring(data.errMsg or data.errmsg or data.message or data.msg or "")
|
||||
if msg:find("登录", 1, true) then return true end
|
||||
-- 英文错误码(与京东同类):LOGIN / NOT.LOGIN / unauthorized
|
||||
local upper = msg:upper()
|
||||
return upper:find("NOT.LOGIN", 1, true) ~= nil
|
||||
or upper:find("NOT_LOGIN", 1, true) ~= nil
|
||||
or upper:find("UNAUTHORIZED", 1, true) ~= nil
|
||||
or (upper:find("LOGIN", 1, true) ~= nil and upper:find("FAIL", 1, true) ~= nil)
|
||||
end
|
||||
|
||||
---@param method string
|
||||
---@param url string
|
||||
---@param code number|nil
|
||||
---@param body string|nil
|
||||
---@param res table|nil
|
||||
---@return string
|
||||
local function httpError(method, url, code, body, res)
|
||||
local parts = {
|
||||
method .. " " .. tostring(url),
|
||||
"HTTP " .. tostring(code),
|
||||
}
|
||||
if isAuthError(code, body, res) then
|
||||
parts[#parts + 1] = "auth_expired=true"
|
||||
end
|
||||
local data = decodeJson(body)
|
||||
if type(data) == "table" then
|
||||
local err_code = data.errCode or data.errcode or data.code
|
||||
local err_message = data.errMsg or data.errmsg or data.message or data.msg
|
||||
if err_code ~= nil then
|
||||
parts[#parts + 1] = "error_code=" .. tostring(err_code)
|
||||
end
|
||||
if err_message ~= nil then
|
||||
parts[#parts + 1] = "error_message="
|
||||
.. tostring(err_message):gsub("[%c]+", " "):sub(1, 200)
|
||||
end
|
||||
end
|
||||
return table.concat(parts, ", ")
|
||||
end
|
||||
|
||||
--- 给用户看的 HTTP 错误:诊断串(httpError)只进日志,这里只留服务端
|
||||
--- msg,没有就只报状态码,免得整条 URL 被 toast 出来。
|
||||
---@param code number|nil
|
||||
---@param body string|nil
|
||||
---@return string
|
||||
local function userHttpError(code, body)
|
||||
local data = decodeJson(body)
|
||||
if type(data) == "table" then
|
||||
local err_message = data.errMsg or data.errmsg or data.message or data.msg
|
||||
if err_message ~= nil and tostring(err_message) ~= "" then
|
||||
return tostring(err_message):gsub("[%c]+", " "):sub(1, 200)
|
||||
end
|
||||
end
|
||||
return T(_("请求失败 (HTTP %1)"), tostring(code))
|
||||
end
|
||||
|
||||
---@param self FanqieClient
|
||||
---@return table
|
||||
local function sessionHeaders(self, extra)
|
||||
local cookies = self.settings:get("cookies", {})
|
||||
local headers = {
|
||||
["User-Agent"] = FanQie.USER_AGENT,
|
||||
["Accept"] = "application/json, text/plain, */*",
|
||||
["Accept-Encoding"] = "identity",
|
||||
["Referer"] = FanQie.BASE_URL .. "/",
|
||||
}
|
||||
local cookie_header = Cookie.to_header(cookies)
|
||||
if cookie_header ~= "" then
|
||||
headers["Cookie"] = cookie_header
|
||||
end
|
||||
for k, v in pairs(extra or {}) do
|
||||
headers[k] = v
|
||||
end
|
||||
return headers
|
||||
end
|
||||
|
||||
--- 带会话 Cookie 的 JSON 请求(跟随重定向);回包 Set-Cookie 并入会话。
|
||||
--- 传输失败、非 2xx 与非 JSON 都归一成 cb(nil, err)。
|
||||
---@param self FanqieClient
|
||||
---@param method string
|
||||
---@param url string
|
||||
---@param extra_headers table|nil
|
||||
---@param body string|nil
|
||||
---@param cb fun(data: table|nil, err: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
local function jsonAsync(self, method, url, extra_headers, body, cb)
|
||||
return Request.request({
|
||||
url = url,
|
||||
method = method,
|
||||
body = body,
|
||||
headers = sessionHeaders(self, extra_headers),
|
||||
timeout = require("http.timeout").net(TIMEOUT_RATIO),
|
||||
allow_redirects = true,
|
||||
}, function(res, err)
|
||||
if err or not res then
|
||||
cb(nil, err and tostring(err))
|
||||
return
|
||||
end
|
||||
absorbCookies(self, res)
|
||||
local code = tonumber(res.code)
|
||||
-- 番茄扫码登录的 Cookie 没有续期接口:会话失效直接标记,由上层引导重新扫码。
|
||||
local Auth = require("source.auth")
|
||||
if isAuthError(code, res.body, res) then
|
||||
-- 技术细节只打日志;弹窗给人看的中文由 Auth → Sync.promptLogin。
|
||||
logger.warn("fanqie auth expired", httpError(method, url, code, res.body, res))
|
||||
cb(nil, Auth.expire("ext.fanqie", _("点这个提示上的「重新登录」。二维码出来以后,打开手机上的番茄小说 App 或抖音,用扫一扫对准屏幕上的二维码,在手机上点确认。")))
|
||||
return
|
||||
end
|
||||
if not Request.ok(code) then
|
||||
logger.warn("fanqie http error", httpError(method, url, code, res.body, res))
|
||||
cb(nil, userHttpError(code, res.body))
|
||||
return
|
||||
end
|
||||
Auth.ok("ext.fanqie")
|
||||
cb(decodeJson(res.body))
|
||||
end)
|
||||
end
|
||||
|
||||
---@param cb fun(data: table|nil, err: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
function Client:fetchReadProgressAsync(cb)
|
||||
return jsonAsync(self, "GET", FanQie.BASE_URL .. "/api/reader/book/progress", nil, nil, cb)
|
||||
end
|
||||
|
||||
---@param book_id string
|
||||
---@param item_id string
|
||||
---@param index number
|
||||
---@param progress number
|
||||
---@param cb fun(data: table|nil, err: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
function Client:updateReadProgressAsync(book_id, item_id, index, progress, cb)
|
||||
return jsonAsync(self, "POST", FanQie.BASE_URL .. "/api/reader/book/update_progress", {
|
||||
["Content-Type"] = "application/json;charset=UTF-8",
|
||||
["Origin"] = FanQie.BASE_URL,
|
||||
}, JSON.encode({
|
||||
book_id = book_id,
|
||||
item_id = item_id,
|
||||
read_progress = progress or 0,
|
||||
index = index,
|
||||
read_timestamp = tostring(math.floor(os.time())),
|
||||
genre_type = 0,
|
||||
}), cb)
|
||||
end
|
||||
|
||||
---@param book_id string
|
||||
---@param cb fun(data: table|nil, err: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
function Client:fetchChapterDirectoryAsync(book_id, cb)
|
||||
local url = FanQie.BASE_URL .. "/api/reader/directory/detail?bookId=" .. Text.urlEncode(book_id)
|
||||
return jsonAsync(self, "GET", url, nil, nil, function(data, err)
|
||||
if not data then
|
||||
cb(nil, err or "官方 API 获取目录失败")
|
||||
return
|
||||
end
|
||||
if tonumber(data.code) ~= 0 or type(data.data) ~= "table" then
|
||||
cb(nil, "官方 API 获取目录失败: code="
|
||||
.. tostring(data.code) .. " message=" .. tostring(data.message or ""))
|
||||
return
|
||||
end
|
||||
cb(data)
|
||||
end)
|
||||
end
|
||||
|
||||
local function bookDetail(book_id, data)
|
||||
local author = data.author
|
||||
if not author or author == "" then author = data.authorName end
|
||||
return {
|
||||
book_id = book_id,
|
||||
book_name = data.bookName,
|
||||
author_name = author or "",
|
||||
abstract = data.abstract or "",
|
||||
thumb_url = FanQie.mobileCover(data.thumbUri),
|
||||
}
|
||||
end
|
||||
|
||||
---@param book_id string
|
||||
---@param cb fun(detail: table|nil, err: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
function Client:fetchBookDetailAsync(book_id, cb)
|
||||
return jsonAsync(self, "GET", FanQie.book_info_url(book_id), nil, nil, function(info, err)
|
||||
if not info then cb(nil, err); return end
|
||||
if (info.code ~= nil and tonumber(info.code) ~= 0)
|
||||
or type(info.data) ~= "table" or not info.data.bookName or info.data.bookName == ""
|
||||
then
|
||||
cb(nil, businessError(info, "番茄书籍详情请求失败"))
|
||||
return
|
||||
end
|
||||
cb(bookDetail(book_id, info.data))
|
||||
end)
|
||||
end
|
||||
|
||||
---@param force_refresh boolean|nil
|
||||
---@param cb fun(data: table|nil, err: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
function Client:fetchShelfDetailAsync(force_refresh, cb)
|
||||
local now = os.time()
|
||||
local cookies = self.settings:get("cookies", {})
|
||||
local cache_key = next(cookies) and Cookie.to_header(cookies) or "default"
|
||||
local cached = SHELF_CACHE[cache_key]
|
||||
if not force_refresh and cached and (now - cached.timestamp) < SHELF_CACHE_TTL then
|
||||
require("ui/uimanager"):nextTick(function() cb(cached.data) end)
|
||||
return { cancel = function() end }
|
||||
end
|
||||
|
||||
local cancelled = false
|
||||
local shelf_job
|
||||
local detail_jobs = {}
|
||||
local handle = {
|
||||
cancel = function()
|
||||
cancelled = true
|
||||
if shelf_job and shelf_job.cancel then shelf_job.cancel() end
|
||||
for _job_key, j in pairs(detail_jobs) do
|
||||
if j and j.cancel then j.cancel() end
|
||||
end
|
||||
end,
|
||||
}
|
||||
|
||||
local shelf_url = FanQie.BASE_URL .. "/reading/bookapi/bookshelf/info/v:version/?" .. Text.formEncode({
|
||||
aid = 1967,
|
||||
iid = 0,
|
||||
version_code = 57700,
|
||||
update_version_code = 57700,
|
||||
})
|
||||
shelf_job = jsonAsync(self, "GET", shelf_url, nil, nil, function(shelf_info, err)
|
||||
if cancelled then return end
|
||||
if type(shelf_info) ~= "table"
|
||||
or (shelf_info.code ~= nil and tonumber(shelf_info.code) ~= 0)
|
||||
or type(shelf_info.data) ~= "table"
|
||||
then
|
||||
cb(nil, err or businessError(shelf_info, "番茄书架请求失败"))
|
||||
return
|
||||
end
|
||||
local book_shelf_info = shelf_info.data.book_shelf_info
|
||||
or shelf_info.data.bookShelfInfo
|
||||
or shelf_info.data
|
||||
-- 自定义分组:bookId→分组名(无 group_name 的书不算分组)。
|
||||
-- last_operate_time / add_shelf_time 是手机上的最后打开和加入书架时间,挂到详情行给排序用。
|
||||
local shelf_book_ids, group_by_id, operate_by_id, added_by_id = {}, {}, {}, {}
|
||||
for _idx, item in ipairs(type(book_shelf_info) == "table" and book_shelf_info or {}) do
|
||||
if item.book_id then
|
||||
local book_id = tostring(item.book_id)
|
||||
shelf_book_ids[#shelf_book_ids + 1] = book_id
|
||||
local name = item.group_name
|
||||
if type(name) == "string" and name ~= "" then
|
||||
group_by_id[book_id] = group_by_id[book_id] or name
|
||||
end
|
||||
if operate_by_id[book_id] == nil and item.last_operate_time ~= nil then
|
||||
operate_by_id[book_id] = item.last_operate_time
|
||||
end
|
||||
if added_by_id[book_id] == nil and item.add_shelf_time ~= nil then
|
||||
added_by_id[book_id] = item.add_shelf_time
|
||||
end
|
||||
end
|
||||
end
|
||||
if #shelf_book_ids == 0 then
|
||||
local empty = { code = 0, data = { detail_list = {} } }
|
||||
SHELF_CACHE[cache_key] = { timestamp = os.time(), data = empty }
|
||||
cb(empty)
|
||||
return
|
||||
end
|
||||
|
||||
-- web multidetail 无作者;手机端 multi-detail 现已空响应。
|
||||
-- 用 /api/book/info 拿书名/作者,封面走手机 CDN(thumb_uri 稳定、不签名过期)。
|
||||
-- 接口答了但无详情(网页端查无此书,App 里仍在书架上):走书架 multidetail 取书名,
|
||||
-- 再失败才用书号占位保留在书架;请求本身失败则整次失败:剔掉会把书从本地书架藏起来。
|
||||
local by_id, next_idx, active, failed = {}, 0, 0, nil
|
||||
local function finish()
|
||||
if failed then
|
||||
cb(nil, failed)
|
||||
return
|
||||
end
|
||||
local detail_list = {}
|
||||
for _idx, book_id in ipairs(shelf_book_ids) do
|
||||
local row = by_id[book_id]
|
||||
if row then
|
||||
row._group_name = group_by_id[book_id]
|
||||
row.last_operate_time = operate_by_id[book_id]
|
||||
row.add_shelf_time = added_by_id[book_id]
|
||||
detail_list[#detail_list + 1] = row
|
||||
end
|
||||
end
|
||||
local result = { code = 0, data = { detail_list = detail_list } }
|
||||
SHELF_CACHE[cache_key] = { timestamp = os.time(), data = result }
|
||||
cb(result)
|
||||
end
|
||||
|
||||
local pump
|
||||
local function settle()
|
||||
active = active - 1
|
||||
if cancelled then return end
|
||||
if active == 0 and (failed or next_idx >= #shelf_book_ids) then
|
||||
finish()
|
||||
else
|
||||
pump()
|
||||
end
|
||||
end
|
||||
-- 网页端 book/info 查无此书时,改用书架 multidetail 取书名封面(只返回在架的书,正好)。
|
||||
local function fallbackDetail(book_id)
|
||||
local body = JSON.encode({ books = { { book_id = book_id, item_id = "0" } } })
|
||||
detail_jobs[book_id] = jsonAsync(self, "POST", FanQie.BASE_URL .. "/api/bookshelf/multidetail", {
|
||||
["Content-Type"] = "application/json;charset=UTF-8",
|
||||
["Origin"] = FanQie.BASE_URL,
|
||||
}, body, function(wire)
|
||||
detail_jobs[book_id] = nil
|
||||
if cancelled then return end
|
||||
local list = type(wire) == "table" and type(wire.data) == "table" and wire.data.detail_list
|
||||
local d = type(list) == "table" and list[1] or {}
|
||||
by_id[book_id] = {
|
||||
book_id = book_id,
|
||||
book_name = d.book_name or ("番茄书籍 " .. book_id),
|
||||
author_name = "",
|
||||
abstract = d.abstract or "",
|
||||
thumb_url = FanQie.mobileCover(d.thumb_url),
|
||||
}
|
||||
settle()
|
||||
end)
|
||||
end
|
||||
local function onInfo(book_id, info, info_err)
|
||||
detail_jobs[book_id] = nil
|
||||
if cancelled then return end
|
||||
if not info then
|
||||
failed = failed or info_err or "番茄书籍详情请求失败"
|
||||
elseif type(info.data) == "table" and (info.code == nil or tonumber(info.code) == 0) then
|
||||
by_id[book_id] = bookDetail(book_id, info.data)
|
||||
else
|
||||
logger.warn("fanqie book info", book_id, businessError(info, "invalid"))
|
||||
fallbackDetail(book_id)
|
||||
return
|
||||
end
|
||||
settle()
|
||||
end
|
||||
pump = function()
|
||||
while not failed and active < DETAIL_LIMIT and next_idx < #shelf_book_ids do
|
||||
next_idx = next_idx + 1
|
||||
local book_id = shelf_book_ids[next_idx]
|
||||
active = active + 1
|
||||
detail_jobs[book_id] = jsonAsync(self, "GET", FanQie.book_info_url(book_id), nil, nil,
|
||||
function(info, info_err) onInfo(book_id, info, info_err) end)
|
||||
end
|
||||
end
|
||||
pump()
|
||||
end)
|
||||
return handle
|
||||
end
|
||||
|
||||
--- 免登录搜索,只取第一页(接口的 has_more / offset 此处不用)。
|
||||
---@param keyword string
|
||||
---@param cb fun(data: table|nil, err: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
function Client:searchAsync(keyword, cb)
|
||||
return Request.request({
|
||||
url = FanQie.searchUrl(keyword),
|
||||
method = "GET",
|
||||
headers = { ["User-Agent"] = FanQie.APP_UA, ["Accept"] = "application/json, text/plain, */*" },
|
||||
timeout = require("http.timeout").net(TIMEOUT_RATIO),
|
||||
}, function(res, err)
|
||||
if err or not res then
|
||||
cb(nil, err and tostring(err))
|
||||
return
|
||||
end
|
||||
if not Request.ok(tonumber(res.code)) then
|
||||
logger.warn("fanqie http error", httpError("GET", FanQie.searchUrl(keyword), tonumber(res.code), res.body, res))
|
||||
cb(nil, userHttpError(tonumber(res.code), res.body))
|
||||
return
|
||||
end
|
||||
local data, derr = decodeJson(res.body)
|
||||
if not data then
|
||||
cb(nil, derr)
|
||||
elseif tonumber(data.code) ~= 0 then
|
||||
cb(nil, businessError(data, "番茄搜索失败"))
|
||||
else
|
||||
cb(data)
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
--- 网页榜单一页(服务端渲染,页面内嵌 __INITIAL_STATE__;分页接口要 a_bogus 签名,这里只取首屏 10 本)。
|
||||
--- path 形如 "1_2_1141"(频道_榜单_分类,分类可省)。
|
||||
---@param path string
|
||||
---@param cb fun(html: string|nil, err: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
function Client:rankAsync(path, cb)
|
||||
local url = FanQie.BASE_URL .. "/rank/" .. path
|
||||
return Request.request({
|
||||
url = url,
|
||||
method = "GET",
|
||||
headers = { ["User-Agent"] = FanQie.WEB_UA, ["Accept"] = "text/html" },
|
||||
timeout = require("http.timeout").net(TIMEOUT_RATIO),
|
||||
}, function(res, err)
|
||||
if err or not res then
|
||||
cb(nil, err and tostring(err))
|
||||
elseif not Request.ok(tonumber(res.code)) then
|
||||
logger.warn("fanqie http error", httpError("GET", url, tonumber(res.code), res.body, res))
|
||||
cb(nil, userHttpError(tonumber(res.code), res.body))
|
||||
else
|
||||
cb(res.body)
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
--- 加入 / 移出书架。成功后丢掉书架短缓存,紧接着的重新拉取才看得到变化。
|
||||
---@param action "add"|"delete"
|
||||
---@param book_id string
|
||||
---@param cb fun(data: table|nil, err: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
function Client:shelfActionAsync(action, book_id, cb)
|
||||
local item = { book_id = tostring(book_id) }
|
||||
local body = { identify_data = { item } }
|
||||
if action == "add" then
|
||||
item.asterisked = false
|
||||
item.modify_time = os.time() * 1000
|
||||
item.book_type = 0
|
||||
body.add_book_source = 0
|
||||
end
|
||||
return jsonAsync(self, "POST", FanQie.shelfActionUrl(action), {
|
||||
["Content-Type"] = "application/json;charset=UTF-8",
|
||||
["Origin"] = FanQie.BASE_URL,
|
||||
}, JSON.encode(body), function(data, err)
|
||||
if not data then
|
||||
cb(nil, err)
|
||||
elseif tonumber(data.code) ~= 0 then
|
||||
cb(nil, businessError(data, "番茄书架操作失败"))
|
||||
else
|
||||
SHELF_CACHE = {}
|
||||
cb(data)
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
---@param book_id string
|
||||
---@param item_id string
|
||||
---@param cb fun(data: table|nil, err: string|nil)
|
||||
---@return CancelHandle|nil
|
||||
function Client:officialGetContentAsync(book_id, item_id, cb)
|
||||
return require("moonsource_fanqie.reading").fetchAsync(self.settings, book_id, item_id, cb)
|
||||
end
|
||||
|
||||
return Client
|
||||
@@ -0,0 +1,97 @@
|
||||
--[[--
|
||||
番茄漫画章节(book_type=1):正文不是 HTML,而是 {"picInfos":[{"picUrl":…}],"encrypt":true,"encrypt_key":"<hex>"};
|
||||
每张图就是一页,CDN 给的是 AES-256-GCM 密文 [12B IV][密文][16B 标签]。
|
||||
|
||||
@module koplugin.book.moonsource_fanqie.comic
|
||||
--]]
|
||||
|
||||
local Aes = require("crypto.aes")
|
||||
local Gcm = require("crypto.gcm")
|
||||
local Cbz = require("source.cbz")
|
||||
local Image = require("utils.image")
|
||||
local Paths = require("utils.paths")
|
||||
local _ = require("l10n").get("moonsource_fanqie")
|
||||
|
||||
local Comic = {}
|
||||
|
||||
--- 章节正文是漫画 JSON 则返回页图地址列表与解密密钥(未加密为 nil);否则返回 nil。
|
||||
---@param raw string
|
||||
---@return string[]|nil urls, string|nil key
|
||||
function Comic.parse(raw)
|
||||
local s = raw:match("^%s*(.-)%s*$")
|
||||
if s:sub(1, 1) ~= "{" then return nil end
|
||||
local ok, data = pcall(require("json").decode, s)
|
||||
if not ok or type(data) ~= "table" or type(data.picInfos) ~= "table" then return nil end
|
||||
local urls = {}
|
||||
for _idx, pic in ipairs(data.picInfos) do
|
||||
if type(pic.picUrl) == "string" then urls[#urls + 1] = pic.picUrl end
|
||||
end
|
||||
if #urls == 0 then return nil end
|
||||
local key = data.encrypt == true and type(data.encrypt_key) == "string" and Aes.from_hex(data.encrypt_key) or nil
|
||||
return urls, key
|
||||
end
|
||||
|
||||
---@param data string 下载到的页图
|
||||
---@param key string|nil
|
||||
---@return string|nil
|
||||
function Comic.decrypt(data, key)
|
||||
if not key then return data end
|
||||
if #data <= 28 then return nil end
|
||||
return Gcm.ctr(key, data:sub(1, 12), data:sub(13, -17))
|
||||
end
|
||||
|
||||
--- 逐页下载、解密、打成 CBZ;页图先落在同名目录,打包成功后由 Cbz 删掉。
|
||||
---@param urls string[]
|
||||
---@param key string|nil
|
||||
---@param archive_path string
|
||||
---@param cb fun(path: string|nil, err: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
function Comic.materializeAsync(urls, key, archive_path, cb)
|
||||
local dir = archive_path:gsub("%.cbz$", "")
|
||||
local ok, dir_err = Paths.ensureDir(dir)
|
||||
local state, paths, current = { cancelled = false }, {}, 1
|
||||
local function nextPage()
|
||||
if state.cancelled then return end
|
||||
local url = urls[current]
|
||||
if not url then
|
||||
Cbz.build(paths, archive_path, state, function(path, err)
|
||||
require("libs/libkoreader-lfs").rmdir(dir)
|
||||
cb(path, err)
|
||||
end)
|
||||
return
|
||||
end
|
||||
state.active = require("http.request").request({
|
||||
url = url,
|
||||
method = "GET",
|
||||
timeout = require("http.timeout").net(3),
|
||||
allow_redirects = true,
|
||||
}, function(res)
|
||||
state.active = nil
|
||||
if state.cancelled then return end
|
||||
local data = res and res.code == 200 and res.body and Comic.decrypt(res.body, key)
|
||||
local ext = data and Image.ext(data)
|
||||
if not ext then cb(nil, _("漫画图片下载失败")); return end
|
||||
local path = string.format("%s/%04d%s", dir, current, ext)
|
||||
local file, err = io.open(path, "wb")
|
||||
if not file then cb(nil, err); return end
|
||||
file:write(data --[[@as string]])
|
||||
file:close()
|
||||
paths[current] = path
|
||||
current = current + 1
|
||||
nextPage()
|
||||
end)
|
||||
end
|
||||
if not ok then
|
||||
require("ui/uimanager"):nextTick(function() cb(nil, dir_err) end)
|
||||
else
|
||||
nextPage()
|
||||
end
|
||||
return { cancel = function()
|
||||
state.cancelled = true
|
||||
if state.active then state.active.cancel() end
|
||||
if state.writer then state.writer:close() end
|
||||
os.remove(archive_path .. ".part")
|
||||
end }
|
||||
end
|
||||
|
||||
return Comic
|
||||
@@ -0,0 +1,253 @@
|
||||
--[[--
|
||||
番茄正文:PUA 字体解码 + 目录归一化。章缓存走 source.chapter。
|
||||
|
||||
@module koplugin.book.moonsource_fanqie.content
|
||||
--]]
|
||||
|
||||
local Text = require("utils.text")
|
||||
local Content = {}
|
||||
|
||||
local PUA_CODE = { { 58344, 58715 }, { 58345, 58716 } }
|
||||
local PUA_CHARSET = {
|
||||
{ "D","在","主","特","家","军","然","表","场","4","要","只","v","和","?","6","别","还","g","现","儿","岁","?","?","此","象","月","3","出","战","工","相","o","男","直","失","世","F","都","平","文","什","V","O","将","真","T","那","当","?","会","立","些","u","是","十","张","学","气","大","爱","两","命","全","后","东","性","通","被","1","它","乐","接","而","感","车","山","公","了","常","以","何","可","话","先","p","i","叫","轻","M","士","w","着","变","尔","快","l","个","说","少","色","里","安","花","远","7","难","师","放","t","报","认","面","道","S","?","克","地","度","I","好","机","U","民","写","把","万","同","水","新","没","书","电","吃","像","斯","5","为","y","白","几","日","教","看","但","第","加","候","作","上","拉","住","有","法","r","事","应","位","利","你","声","身","国","问","马","女","他","Y","比","父","x","A","H","N","s","X","边","美","对","所","金","活","回","意","到","z","从","j","知","又","内","因","点","Q","三","定","8","R","b","正","或","夫","向","德","听","更","?","得","告","并","本","q","过","记","L","让","打","f","人","就","者","去","原","满","体","做","经","K","走","如","孩","c","G","给","使","物","?","最","笑","部","?","员","等","受","k","行","一","条","果","动","光","门","头","见","往","自","解","成","处","天","能","于","名","其","发","总","母","的","死","手","入","路","进","心","来","h","时","力","多","开","已","许","d","至","由","很","界","n","小","与","Z","想","代","么","分","生","口","再","妈","望","次","西","风","种","带","J","?","实","情","才","这","?","E","我","神","格","长","觉","间","年","眼","无","不","亲","关","结","0","友","信","下","却","重","己","老","2","音","字","m","呢","明","之","前","高","P","B","目","太","e","9","起","稜","她","也","W","用","方","子","英","每","理","便","四","数","期","中","C","外","样","a","海","们","任" },
|
||||
{ "s","?","作","口","在","他","能","并","B","士","4","U","克","才","正","们","字","声","高","全","尔","活","者","动","其","主","报","多","望","放","h","w","次","年","?","中","3","特","于","十","入","要","男","同","G","面","分","方","K","什","再","教","本","己","结","1","等","世","N","?","说","g","u","期","Z","外","美","M","行","给","9","文","将","两","许","张","友","0","英","应","向","像","此","白","安","少","何","打","气","常","定","间","花","见","孩","它","直","风","数","使","道","第","水","已","女","山","解","d","P","的","通","关","性","叫","儿","L","妈","问","回","神","来","S","","四","望","前","国","些","O","v","l","A","心","平","自","无","军","光","代","是","好","却","c","得","种","就","意","先","立","z","子","过","Y","j","表","","么","所","接","了","名","金","受","J","满","眼","没","部","那","m","每","车","度","可","R","斯","经","现","门","明","V","如","走","命","y","6","E","战","很","上","f","月","西","7","长","夫","想","话","变","海","机","x","到","W","一","成","生","信","笑","但","父","开","内","东","马","日","小","而","后","带","以","三","几","为","认","X","死","员","目","位","之","学","远","人","音","呢","我","q","乐","象","重","对","个","被","别","F","也","书","稜","D","写","还","因","家","发","时","i","或","住","德","当","o","l","比","觉","然","吃","去","公","a","老","亲","情","体","太","b","万","C","电","理","?","失","力","更","拉","物","着","原","她","工","实","色","感","记","看","出","相","路","大","你","候","2","和","?","与","p","样","新","只","便","最","不","进","T","r","做","格","母","总","爱","身","师","轻","知","往","加","从","?","天","e","H","?","听","场","由","快","边","让","把","任","8","条","头","事","至","起","点","真","手","这","难","都","界","用","法","n","处","下","又","Q","告","地","5","k","t","岁","有","会","果","利","民" }
|
||||
}
|
||||
|
||||
local function utf8_codepoint(str, i)
|
||||
local b1 = str:byte(i)
|
||||
if not b1 then return nil, i end
|
||||
if b1 < 0x80 then
|
||||
return b1, i + 1
|
||||
elseif b1 >= 0xC2 and b1 <= 0xDF then
|
||||
local b2 = str:byte(i + 1)
|
||||
if not b2 then return nil, i end
|
||||
return (b1 - 0xC0) * 0x40 + (b2 - 0x80), i + 2
|
||||
elseif b1 >= 0xE0 and b1 <= 0xEF then
|
||||
local b2 = str:byte(i + 1)
|
||||
local b3 = str:byte(i + 2)
|
||||
if not b2 or not b3 then return nil, i end
|
||||
return (b1 - 0xE0) * 0x1000 + (b2 - 0x80) * 0x40 + (b3 - 0x80), i + 3
|
||||
elseif b1 >= 0xF0 and b1 <= 0xF4 then
|
||||
local b2 = str:byte(i + 1)
|
||||
local b3 = str:byte(i + 2)
|
||||
local b4 = str:byte(i + 3)
|
||||
if not b2 or not b3 or not b4 then return nil, i end
|
||||
return (b1 - 0xF0) * 0x40000 + (b2 - 0x80) * 0x1000 + (b3 - 0x80) * 0x40 + (b4 - 0x80), i + 4
|
||||
end
|
||||
return nil, i
|
||||
end
|
||||
|
||||
function Content.decode_pua_content(content)
|
||||
if not content then return "" end
|
||||
local result = {}
|
||||
local i = 1
|
||||
while i <= #content do
|
||||
local code, next_i = utf8_codepoint(content, i)
|
||||
if not code then
|
||||
table.insert(result, content:sub(i, i))
|
||||
i = i + 1
|
||||
else
|
||||
local decoded = false
|
||||
for mode = 1, 2 do
|
||||
local range = PUA_CODE[mode]
|
||||
if code >= range[1] and code <= range[2] then
|
||||
local bias = code - range[1]
|
||||
local charset = PUA_CHARSET[mode]
|
||||
if bias + 1 <= #charset and charset[bias + 1] ~= "?" then
|
||||
table.insert(result, charset[bias + 1])
|
||||
decoded = true
|
||||
end
|
||||
break
|
||||
end
|
||||
end
|
||||
if not decoded then
|
||||
table.insert(result, content:sub(i, next_i - 1))
|
||||
end
|
||||
i = next_i
|
||||
end
|
||||
end
|
||||
return table.concat(result)
|
||||
end
|
||||
|
||||
|
||||
--- 官方目录 /api/reader/directory/detail 的 data → 平铺章节行。
|
||||
--- ID 一律是字符串(19 位,超出 double 精度,数字形态无法还原)。
|
||||
--- 优先 chapterListWithVolume(二维:卷 → 章),其次 chapterList,最后只有 allItemIds 时按序号起标题。
|
||||
--- 有卷名的卷给章写 depth=2 和 volume(卷名本身不占 idx,避免打乱章节文件序号);无卷名时 depth=1。
|
||||
--- 章上的官方子节点收成 anchors,不另开一行。
|
||||
---@param payload table|nil 完整回包
|
||||
---@return table[]
|
||||
function Content.normalize_chapters(payload)
|
||||
local records = type(payload) == "table" and payload.data
|
||||
if type(records) ~= "table" then
|
||||
return {}
|
||||
end
|
||||
|
||||
local function trim(value)
|
||||
if type(value) ~= "string" then return nil end
|
||||
value = Text.trim(value)
|
||||
if value == "" then return nil end
|
||||
return value
|
||||
end
|
||||
|
||||
local function volume_title(volume)
|
||||
if type(volume) ~= "table" then return nil end
|
||||
return trim(volume.volumeName or volume.volume_name or volume.volumeTitle
|
||||
or volume.volume_title or volume.name or volume.title)
|
||||
end
|
||||
|
||||
local function volume_chapters(volume)
|
||||
if type(volume) ~= "table" then return nil end
|
||||
if volume[1] ~= nil then return volume end
|
||||
local list = volume.chapterList or volume.chapter_list or volume.itemList or volume.item_list
|
||||
return type(list) == "table" and list or nil
|
||||
end
|
||||
|
||||
---@param ch table
|
||||
---@param depth integer
|
||||
---@return table[]
|
||||
local function official_anchors(ch, depth)
|
||||
local anchors = {}
|
||||
for _idx, key in ipairs({
|
||||
"children", "childList", "child_list", "catalogList", "catalog_list",
|
||||
"subItemList", "sub_item_list", "anchorList", "anchor_list",
|
||||
"tocList", "toc_list", "subChapterList", "sub_chapter_list",
|
||||
}) do
|
||||
local list = ch[key]
|
||||
if type(list) == "table" then
|
||||
for _row_idx, row in ipairs(list) do
|
||||
if type(row) == "table" then
|
||||
local title = trim(row.title or row.name or row.chapterName or row.chapter_name)
|
||||
local id = row.anchor or row.id or row.itemId or row.item_id
|
||||
if id ~= nil then id = tostring(id) end
|
||||
if title or (id and id ~= "") then
|
||||
anchors[#anchors + 1] = {
|
||||
title = title or ("#" .. #anchors + 1),
|
||||
depth = depth,
|
||||
id = id,
|
||||
}
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return anchors
|
||||
end
|
||||
|
||||
local function add_chapter(out, ch, depth, volume)
|
||||
if type(ch) ~= "table" or ch.itemId == nil then return end
|
||||
ch.depth = depth
|
||||
if volume then ch.volume = volume end
|
||||
local anchors = official_anchors(ch, depth + 1)
|
||||
if #anchors > 0 then ch.anchors = anchors end
|
||||
out[#out + 1] = ch
|
||||
end
|
||||
|
||||
local out = {}
|
||||
for _idx, volume in ipairs(records.chapterListWithVolume or {}) do
|
||||
local chapters = volume_chapters(volume)
|
||||
local name = volume_title(volume)
|
||||
local depth = name and 2 or 1
|
||||
for _ch_idx, ch in ipairs(type(chapters) == "table" and chapters or {}) do
|
||||
add_chapter(out, ch, depth, name)
|
||||
end
|
||||
end
|
||||
if #out > 0 then
|
||||
return out
|
||||
end
|
||||
if type(records.chapterList) == "table" then
|
||||
for _idx, ch in ipairs(records.chapterList) do
|
||||
add_chapter(out, ch, 1)
|
||||
end
|
||||
return out
|
||||
end
|
||||
for i, item_id in ipairs(records.allItemIds or {}) do
|
||||
out[#out + 1] = { itemId = tostring(item_id), title = "第" .. i .. "章", depth = 1 }
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
function Content.readable_chapters(chapters)
|
||||
local out = {}
|
||||
for _idx, chapter in ipairs(chapters or {}) do
|
||||
if tostring(chapter.title or "") ~= "封面" then
|
||||
out[#out + 1] = chapter
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
--- 从章节 HTML 收集 id="toc_N" 章内锚点,按文档顺序。
|
||||
--- 有可见标题用原标题;否则回退为 "#N"(与目录空标题章的 "#idx" 一致)。
|
||||
---@param html string|nil
|
||||
---@param depth integer|nil
|
||||
---@return BookChapterAnchor[]
|
||||
function Content.html_anchors(html, depth)
|
||||
if type(html) ~= "string" or html == "" then return {} end
|
||||
depth = math.max(1, math.floor(tonumber(depth) or 2))
|
||||
local Text = require("utils.text")
|
||||
local out, seen = {}, {}
|
||||
local pos = 1
|
||||
while true do
|
||||
local start_at, end_at, _quote, number = html:find('id=(["\'])toc_(%d+)%1', pos)
|
||||
if not start_at then break end
|
||||
pos = end_at + 1
|
||||
local id = "toc_" .. number
|
||||
if not seen[id] then
|
||||
seen[id] = true
|
||||
local open = start_at
|
||||
while open > 1 and html:sub(open, open) ~= "<" do
|
||||
open = open - 1
|
||||
end
|
||||
local title = ""
|
||||
if html:sub(open, open) == "<" then
|
||||
local gt = html:find(">", open, true)
|
||||
if gt and html:sub(gt - 1, gt) ~= "/>" then
|
||||
local tag = html:match("^<%s*([%w:-]+)", open)
|
||||
if tag then
|
||||
local close = html:find("</" .. tag .. ">", gt + 1, true)
|
||||
if close then
|
||||
title = Text.stripHtml(html:sub(gt + 1, close - 1)) or ""
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
title = title:match("^%s*(.-)%s*$") or ""
|
||||
if title == "" then title = "#" .. number end
|
||||
out[#out + 1] = { title = title, depth = depth, id = id }
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
--- 把incoming锚点并入 chapter.anchors:按 id 去重,已有真实标题不被回退标题覆盖。
|
||||
---@param chapter table
|
||||
---@param incoming BookChapterAnchor[]|nil
|
||||
---@return boolean changed
|
||||
function Content.merge_anchors(chapter, incoming)
|
||||
if type(chapter) ~= "table" or type(incoming) ~= "table" or #incoming == 0 then
|
||||
return false
|
||||
end
|
||||
local existing = chapter.anchors or {}
|
||||
local by_id = {}
|
||||
for _idx, anchor in ipairs(existing) do
|
||||
if anchor.id then by_id[tostring(anchor.id)] = anchor end
|
||||
end
|
||||
local changed = false
|
||||
for _idx, anchor in ipairs(incoming) do
|
||||
local id = anchor.id and tostring(anchor.id) or nil
|
||||
local prev = id and by_id[id]
|
||||
if not prev then
|
||||
existing[#existing + 1] = anchor
|
||||
if id then by_id[id] = anchor end
|
||||
changed = true
|
||||
elseif (not prev.title or prev.title == "") and anchor.title and anchor.title ~= "" then
|
||||
prev.title = anchor.title
|
||||
changed = true
|
||||
end
|
||||
end
|
||||
if changed then chapter.anchors = existing end
|
||||
return changed
|
||||
end
|
||||
|
||||
return Content
|
||||
@@ -0,0 +1,62 @@
|
||||
--[[--
|
||||
番茄 Cookie jar:只保留扫码/会话真正用到的两件事。
|
||||
|
||||
@module koplugin.book.moonsource_fanqie.cookie
|
||||
--]]
|
||||
|
||||
local Cookie = {}
|
||||
|
||||
-- Set-Cookie 标准属性(小写匹配),不得当 cookie 名持久化。
|
||||
local SET_COOKIE_ATTRS = {
|
||||
["path"] = true, ["domain"] = true, ["expires"] = true, ["max-age"] = true,
|
||||
["secure"] = true, ["httponly"] = true, ["samesite"] = true,
|
||||
["priority"] = true, ["partitioned"] = true, ["comment"] = true,
|
||||
["version"] = true, ["discard"] = true,
|
||||
}
|
||||
|
||||
---@param cookies table|nil
|
||||
---@return string
|
||||
function Cookie.to_header(cookies)
|
||||
local parts = {}
|
||||
for key, value in pairs(cookies or {}) do
|
||||
parts[#parts + 1] = key .. "=" .. value
|
||||
end
|
||||
table.sort(parts)
|
||||
return table.concat(parts, "; ")
|
||||
end
|
||||
|
||||
--- 合并 Set-Cookie 进 jar。兼容 string / 多值 table。
|
||||
--- Expires 值含逗号,不能直接按逗号切条。
|
||||
---@param cookies table|nil
|
||||
---@param set_cookie string|table|nil
|
||||
---@return table
|
||||
function Cookie.merge_set_cookie(cookies, set_cookie)
|
||||
if not set_cookie or set_cookie == "" then
|
||||
return cookies or {}
|
||||
end
|
||||
cookies = cookies or {}
|
||||
if type(set_cookie) == "table" then
|
||||
for _key, value in pairs(set_cookie) do
|
||||
Cookie.merge_set_cookie(cookies, value)
|
||||
end
|
||||
return cookies
|
||||
end
|
||||
local sc = tostring(set_cookie)
|
||||
local PLACEHOLDER = "\x01"
|
||||
sc = sc:gsub("([Ee][Xx][Pp][Ii][Rr][Ee][Ss]=[^,;]-)%,", "%1" .. PLACEHOLDER)
|
||||
for seg in sc:gmatch("[^,\r\n]+") do
|
||||
seg = seg:gsub("^%s+", ""):gsub("%s+$", "")
|
||||
seg = seg:gsub(PLACEHOLDER, ",")
|
||||
if seg ~= "" then
|
||||
local cookie_name, cookie_value = seg:match("^([^=%s;]+)=([^;]*)")
|
||||
if cookie_name and cookie_value then
|
||||
if not SET_COOKIE_ATTRS[cookie_name:lower()] then
|
||||
cookies[cookie_name] = cookie_value
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return cookies
|
||||
end
|
||||
|
||||
return Cookie
|
||||
@@ -0,0 +1,59 @@
|
||||
--[[--
|
||||
番茄协议常量与 URL。
|
||||
|
||||
@module koplugin.book.moonsource_fanqie.fanqie
|
||||
--]]
|
||||
|
||||
local Text = require("utils.text")
|
||||
|
||||
local FanQie = {}
|
||||
|
||||
FanQie.USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
|
||||
FanQie.BASE_URL = "https://fanqienovel.com"
|
||||
-- 手机端封面 CDN:相对 thumb_uri 可长期访问;web 签名 thumb_url 会过期。
|
||||
FanQie.MOBILE_COVER_CDN = "https://p6-novel.byteimg.com"
|
||||
|
||||
-- 免登录搜索:免签名、免 Cookie,只要 aid / offset / q;App UA 才不被拒。
|
||||
FanQie.APP_UA = "com.dragon.read/6.5.3.32 (Linux; U; Android 13; zh_CN; VDE-AL10; Build/TP1A.220624.014;tt-ok/3.10.0.2)"
|
||||
|
||||
FanQie.WEB_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
|
||||
|
||||
---@param keyword string
|
||||
---@return string
|
||||
function FanQie.searchUrl(keyword)
|
||||
return "https://novel.snssdk.com/api/novel/channel/homepage/search/search/v1/?aid=1967&offset=0&q="
|
||||
.. Text.urlEncode(keyword)
|
||||
end
|
||||
|
||||
---@param action "add"|"delete"
|
||||
---@return string
|
||||
function FanQie.shelfActionUrl(action)
|
||||
return FanQie.BASE_URL .. "/reading/bookapi/bookshelf/" .. action
|
||||
.. "/v:version?aid=1967&iid=0&version_code=57700&update_version_code=57700"
|
||||
end
|
||||
|
||||
---@param book_id string
|
||||
---@return string
|
||||
function FanQie.book_info_url(book_id)
|
||||
return FanQie.BASE_URL .. "/api/book/info?bookId=" .. Text.urlEncode(tostring(book_id))
|
||||
end
|
||||
|
||||
--- 把 thumb_uri / 签名 URL 收成手机端稳定封面。
|
||||
---@param thumb string|nil
|
||||
---@return string|nil
|
||||
function FanQie.mobileCover(thumb)
|
||||
if type(thumb) ~= "string" or thumb == "" then
|
||||
return nil
|
||||
end
|
||||
local path = thumb:match("(novel%-pic/[^~%?#]+)")
|
||||
or thumb:match("(novel%-static/[^~%?#]+)")
|
||||
if not path then
|
||||
if thumb:match("^https?://") then
|
||||
return thumb
|
||||
end
|
||||
path = thumb
|
||||
end
|
||||
return FanQie.MOBILE_COVER_CDN .. "/" .. path .. "~tplv-shrink:320:0.image"
|
||||
end
|
||||
|
||||
return FanQie
|
||||
@@ -0,0 +1,33 @@
|
||||
return {
|
||||
["扫码登录"] = "Sign in with QR code",
|
||||
["点这个提示上的「重新登录」。二维码出来以后,打开手机上的番茄小说 App 或抖音,用扫一扫对准屏幕上的二维码,在手机上点确认。"] = "Tap Sign in again on this message. When the QR code appears, open the Fanqie Novel app or Douyin on your phone, scan the code, and confirm on the phone.",
|
||||
["确定退出番茄账号?"] = "Sign out of Fanqie?",
|
||||
["未登录 · 点此扫码"] = "Not signed in · tap to scan",
|
||||
["漫画图片下载失败"] = "Failed to download comic image",
|
||||
["章节目录保存失败"] = "Failed to save chapter list",
|
||||
["请求失败 (HTTP %1)"] = "Request failed (HTTP %1)",
|
||||
["完成登录失败:"] = "Finish sign-in failed:",
|
||||
["番茄账号与登录"] = "Fanqie account & sign-in",
|
||||
["番茄请求失败"] = "Fanqie request failed",
|
||||
["番茄书架响应不完整,保留本地书架"] = "Fanqie shelf response incomplete; local shelf kept",
|
||||
["番茄目录为空"] = "Fanqie table of contents is empty",
|
||||
["番茄段评响应缺少段落统计"] = "Fanqie paragraph comment response is missing paragraph counts",
|
||||
["番茄段评响应包含无效段落统计"] = "Fanqie paragraph comment response contains invalid paragraph counts",
|
||||
["番茄段评列表为空"] = "Fanqie returned an empty paragraph comment list despite a nonzero total",
|
||||
["缺少番茄章节位置"] = "Missing Fanqie chapter position",
|
||||
["番茄进度上传失败"] = "Fanqie progress upload failed",
|
||||
["番茄正文需要注册设备,当前网络拦了 log.snssdk.com"] = "Fanqie chapter download needs a device registration; this network blocked log.snssdk.com",
|
||||
["番茄设备注册失败,请放行 log.snssdk.com"] = "Fanqie device registration failed; allow log.snssdk.com",
|
||||
["登录失败:未获取到 sessionid"] = "Sign-in failed: no sessionid",
|
||||
["获取二维码失败:"] = "Failed to get QR code:",
|
||||
["还没登录番茄小说。打开「设置 → 书库 → 账号 → 番茄小说 → 番茄账号与登录」,用番茄小说 App 或抖音扫屏幕上的二维码。"] = "Fanqie Novel is not signed in. Open Settings → Library → Account → Fanqie Novel → Fanqie account & sign-in, then scan the code with the Fanqie Novel app or Douyin.",
|
||||
["番茄扫码登录"] = "Fanqie QR login",
|
||||
["女频"] = "Female",
|
||||
["新书榜"] = "New Books",
|
||||
["男频"] = "Male",
|
||||
["阅读榜"] = "Reading chart",
|
||||
["书架同步"] = "Shelf sync",
|
||||
["搜索与发现"] = "Search and discover",
|
||||
["番茄小说书架与在线阅读"] = "Fanqie shelf and online reading",
|
||||
["进度同步"] = "Progress sync",
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
return {
|
||||
["扫码登录"] = "掃碼登入",
|
||||
["点这个提示上的「重新登录」。二维码出来以后,打开手机上的番茄小说 App 或抖音,用扫一扫对准屏幕上的二维码,在手机上点确认。"] = "點這個提示上的「重新登入」。二維碼出來以後,打開手機上的番茄小說 App 或抖音,用掃一掃對準螢幕上的二維碼,在手機上點確認。",
|
||||
["确定退出番茄账号?"] = "確定登出番茄帳號?",
|
||||
["未登录 · 点此扫码"] = "未登入 · 點此掃碼",
|
||||
["漫画图片下载失败"] = "漫畫圖片下載失敗",
|
||||
["章节目录保存失败"] = "章節目錄儲存失敗",
|
||||
["请求失败 (HTTP %1)"] = "請求失敗 (HTTP %1)",
|
||||
["完成登录失败:"] = "完成登入失敗:",
|
||||
["番茄账号与登录"] = "番茄帳號與登入",
|
||||
["番茄请求失败"] = "番茄請求失敗",
|
||||
["番茄书架响应不完整,保留本地书架"] = "番茄書架回應不完整,保留本地書架",
|
||||
["番茄目录为空"] = "番茄目錄為空",
|
||||
["番茄段评响应缺少段落统计"] = "番茄段評回應缺少段落統計",
|
||||
["番茄段评响应包含无效段落统计"] = "番茄段評回應包含無效段落統計",
|
||||
["番茄段评列表为空"] = "番茄段評列表為空",
|
||||
["缺少番茄章节位置"] = "缺少番茄章節位置",
|
||||
["番茄进度上传失败"] = "番茄進度上傳失敗",
|
||||
["番茄正文需要注册设备,当前网络拦了 log.snssdk.com"] = "番茄正文需要註冊裝置,目前網路攔了 log.snssdk.com",
|
||||
["番茄设备注册失败,请放行 log.snssdk.com"] = "番茄裝置註冊失敗,請放行 log.snssdk.com",
|
||||
["登录失败:未获取到 sessionid"] = "登入失敗:未取得 sessionid",
|
||||
["获取二维码失败:"] = "取得二維碼失敗:",
|
||||
["还没登录番茄小说。打开「设置 → 书库 → 账号 → 番茄小说 → 番茄账号与登录」,用番茄小说 App 或抖音扫屏幕上的二维码。"] = "還沒登入番茄小說。打開「設定 → 書庫 → 帳號 → 番茄小說 → 番茄帳號與登入」,用番茄小說 App 或抖音掃螢幕上的二維碼。",
|
||||
["番茄扫码登录"] = "番茄掃碼登入",
|
||||
["女频"] = "女頻",
|
||||
["新书榜"] = "新書榜",
|
||||
["男频"] = "男頻",
|
||||
["阅读榜"] = "閱讀榜",
|
||||
["书架同步"] = "書架同步",
|
||||
["搜索与发现"] = "搜尋與發現",
|
||||
["番茄小说书架与在线阅读"] = "番茄小說書架與線上閱讀",
|
||||
["进度同步"] = "進度同步",
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
return function()
|
||||
local copy = {}
|
||||
for k, v in pairs(require("moonsource_fanqie._meta")) do copy[k] = v end
|
||||
return copy
|
||||
end
|
||||
@@ -0,0 +1,417 @@
|
||||
--[[--
|
||||
番茄小说扫码登录。
|
||||
|
||||
流程:
|
||||
1. GET 登录页预热 cookie (passport_csrf_token)
|
||||
2. GET /passport/web/get_qrcode/ 获取二维码 token + qrcode_index_url
|
||||
3. 轮询 GET /passport/web/check_qrconnect/?token=... 直到 jar 出现 sessionid
|
||||
|
||||
网络只走 http.request;cookie jar 本地维护,登录成功后才写 settings。
|
||||
allow_redirects=false,手动跟跳以保留中间 Set-Cookie。
|
||||
|
||||
@module koplugin.book.moonsource_fanqie.qrlogin
|
||||
--]]
|
||||
|
||||
local UIManager = require("ui/uimanager")
|
||||
local Confirm = require("ui.themes.widgets.confirm")
|
||||
local QR = require("ui.themes.widgets.qr")
|
||||
local Toast = require("ui.themes.widgets.toast")
|
||||
local Request = require("http.request")
|
||||
|
||||
local Cookie = require("moonsource_fanqie.cookie")
|
||||
local Text = require("utils.text")
|
||||
local logger = require("utils.log")
|
||||
local JSON = require("json")
|
||||
local _ = require("l10n").get("moonsource_fanqie")
|
||||
|
||||
local QRLogin = {}
|
||||
QRLogin.__index = QRLogin
|
||||
|
||||
local LOGIN_PAGE = "https://fanqienovel.com/main/writer/login"
|
||||
local GET_QRCODE_URL = "https://fanqienovel.com/passport/web/get_qrcode/"
|
||||
local CHECK_QR_URL = "https://fanqienovel.com/passport/web/check_qrconnect/"
|
||||
local FANQIE_LOGIN_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
.. "(KHTML, like Gecko) Chrome/151.0.0.0 Safari/537.36 Edg/151.0.0.0"
|
||||
|
||||
local POLL_INTERVAL = 2
|
||||
local QR_TIMEOUT = 300
|
||||
|
||||
local COMMON_PARAMS = {
|
||||
passport_jssdk_version = "3.0.16",
|
||||
passport_jssdk_type = "normal",
|
||||
aid = "2503",
|
||||
language = "zh",
|
||||
account_sdk_source = "web",
|
||||
}
|
||||
|
||||
local function extract_csrf(jar)
|
||||
if not jar then return "" end
|
||||
return jar["passport_csrf_token"] or ""
|
||||
end
|
||||
|
||||
local function absolute_url(base, location)
|
||||
if not location or location == "" then return nil end
|
||||
if location:match("^https?://") then return location end
|
||||
local scheme, host = tostring(base or ""):match("^(https?)://([^/]+)")
|
||||
if not scheme then return location end
|
||||
if location:sub(1, 1) == "/" then
|
||||
return scheme .. "://" .. host .. location
|
||||
end
|
||||
local prefix = tostring(base):match("^(https?://.*/)") or (scheme .. "://" .. host .. "/")
|
||||
return prefix .. location
|
||||
end
|
||||
|
||||
---@param settings FanqieSettings
|
||||
---@param plugin table 提供 showBusy/closeBusy
|
||||
function QRLogin.new(_class, settings, plugin)
|
||||
local self = setmetatable({}, QRLogin)
|
||||
self.settings = settings
|
||||
self.plugin = plugin
|
||||
self.generation = 0
|
||||
self.jar = {}
|
||||
self.dialog = nil
|
||||
self.retry_dialog = nil
|
||||
self.started = 0
|
||||
self.poll_failures = 0
|
||||
self.login_completed = false
|
||||
self._job = nil
|
||||
return self
|
||||
end
|
||||
|
||||
--- 关掉并清空 self[field] 指向的弹窗。
|
||||
---@param field "dialog"|"retry_dialog"
|
||||
function QRLogin:_close(field)
|
||||
local d = self[field]
|
||||
self[field] = nil
|
||||
if d then d: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_dialog")
|
||||
self.jar = {}
|
||||
self.started = 0
|
||||
self.poll_failures = 0
|
||||
self.plugin:closeBusy()
|
||||
end
|
||||
|
||||
--- 底层 GET:allow_redirects=false;2xx/3xx 都算成功。
|
||||
---@param url string
|
||||
---@param jar table|nil
|
||||
---@param csrf string|nil
|
||||
---@param cb fun(res: table|nil, err: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
function QRLogin:_http_get(url, jar, csrf, cb)
|
||||
local headers = {
|
||||
["User-Agent"] = FANQIE_LOGIN_UA,
|
||||
["Accept"] = "application/json, text/javascript, text/html, */*",
|
||||
["Accept-Language"] = "zh-CN,zh;q=0.9",
|
||||
["Referer"] = LOGIN_PAGE,
|
||||
["sec-fetch-dest"] = "empty",
|
||||
["sec-fetch-mode"] = "cors",
|
||||
["sec-fetch-site"] = "same-origin",
|
||||
}
|
||||
if jar and next(jar) ~= nil then
|
||||
headers["Cookie"] = Cookie.to_header(jar)
|
||||
end
|
||||
if csrf and csrf ~= "" then
|
||||
headers["x-tt-passport-csrf-token"] = csrf
|
||||
end
|
||||
return Request.request({
|
||||
url = url,
|
||||
method = "GET",
|
||||
headers = headers,
|
||||
timeout = require("http.timeout").net(0.5),
|
||||
allow_redirects = false,
|
||||
}, function(res, err)
|
||||
if err then
|
||||
cb(nil, tostring(err))
|
||||
return
|
||||
end
|
||||
local code = tonumber(res and res.code)
|
||||
if not code then
|
||||
cb(nil, "HTTP 无响应码")
|
||||
return
|
||||
end
|
||||
if code < 200 or code >= 400 then
|
||||
cb(nil, "HTTP " .. tostring(code))
|
||||
return
|
||||
end
|
||||
cb(res)
|
||||
end)
|
||||
end
|
||||
|
||||
function QRLogin:start()
|
||||
self:cancel()
|
||||
local gen = self.generation
|
||||
self.started = os.time()
|
||||
self.plugin:showBusy(_("获取二维码中..."))
|
||||
logger.info("[FanQieQR] 开始获取二维码")
|
||||
|
||||
self._job = self:_http_get(LOGIN_PAGE, nil, nil, function(login_res, login_err)
|
||||
if gen ~= self.generation then return end
|
||||
if not login_res then
|
||||
self.plugin:closeBusy()
|
||||
logger.warn("[FanQieQR] 预热失败:", login_err)
|
||||
self:show_retry(_("获取二维码失败:") .. "\n" .. tostring(login_err))
|
||||
return
|
||||
end
|
||||
local jar = Cookie.merge_set_cookie({}, Request.header(login_res, "Set-Cookie"))
|
||||
local csrf = extract_csrf(jar)
|
||||
|
||||
local params = {}
|
||||
for k, v in pairs(COMMON_PARAMS) do params[k] = v end
|
||||
params["need_logo"] = "true"
|
||||
params["next"] = LOGIN_PAGE
|
||||
local qr_url = GET_QRCODE_URL .. "?" .. Text.formEncode(params)
|
||||
|
||||
self._job = self:_http_get(qr_url, jar, csrf, function(qr_res, qr_err)
|
||||
self.plugin:closeBusy()
|
||||
if gen ~= self.generation then return end
|
||||
if not qr_res then
|
||||
logger.warn("[FanQieQR] 获取二维码失败:", qr_err)
|
||||
self:show_retry(_("获取二维码失败:") .. "\n" .. tostring(qr_err))
|
||||
return
|
||||
end
|
||||
jar = Cookie.merge_set_cookie(jar, Request.header(qr_res, "Set-Cookie"))
|
||||
csrf = extract_csrf(jar)
|
||||
|
||||
local ok, data = pcall(JSON.decode, qr_res.body or "")
|
||||
if not ok or type(data) ~= "table" then
|
||||
self:show_retry(_("获取二维码失败:") .. "\n二维码响应非 JSON")
|
||||
return
|
||||
end
|
||||
if data.message ~= "success" then
|
||||
self:show_retry(_("获取二维码失败:") .. "\n接口返回: " .. tostring(data.message))
|
||||
return
|
||||
end
|
||||
local d = data.data or {}
|
||||
local token = d.token or ""
|
||||
local qr_index_url = d.qrcode_index_url or ""
|
||||
if token == "" or qr_index_url == "" then
|
||||
self:show_retry(_("获取二维码失败:") .. "\n二维码数据不完整")
|
||||
return
|
||||
end
|
||||
|
||||
self.jar = jar
|
||||
local dialog
|
||||
dialog = QR:new{
|
||||
title = _("番茄扫码登录"),
|
||||
text = qr_index_url,
|
||||
close_callback = function()
|
||||
if self.dialog == dialog then self.dialog = nil end
|
||||
if gen == self.generation and not self.login_completed then
|
||||
self:cancel()
|
||||
Toast:new{ text = _("已取消登录") }:show()
|
||||
end
|
||||
end,
|
||||
}
|
||||
self.dialog = dialog
|
||||
dialog:show()
|
||||
logger.info("[FanQieQR] 二维码已显示,开始轮询 token=", tostring(token):sub(1, 12))
|
||||
self:_schedule(gen, token, csrf, tonumber(d.expire_time) or 0)
|
||||
end)
|
||||
end)
|
||||
end
|
||||
|
||||
function QRLogin:_schedule(gen, token, csrf, expire_time)
|
||||
if gen ~= self.generation then return end
|
||||
if os.time() - self.started > QR_TIMEOUT then
|
||||
self:show_retry(_("二维码已过期"))
|
||||
return
|
||||
end
|
||||
if expire_time and expire_time > 0 and os.time() > expire_time then
|
||||
self:show_retry(_("二维码已过期"))
|
||||
return
|
||||
end
|
||||
|
||||
local params = {}
|
||||
for k, v in pairs(COMMON_PARAMS) do params[k] = v end
|
||||
params["token"] = token
|
||||
params["next"] = "/"
|
||||
local url = CHECK_QR_URL .. "?" .. Text.formEncode(params)
|
||||
local function poll_again()
|
||||
UIManager:scheduleIn(POLL_INTERVAL, function()
|
||||
self:_schedule(gen, token, csrf, expire_time)
|
||||
end)
|
||||
end
|
||||
|
||||
-- 禁用自动重定向:302 + Set-Cookie(sessionid) 必须自己吃。
|
||||
self._job = self:_http_get(url, self.jar, csrf, function(res, err)
|
||||
if gen ~= self.generation then return end
|
||||
if not res then
|
||||
self.poll_failures = (self.poll_failures or 0) + 1
|
||||
if self.poll_failures == 1 or self.poll_failures % 5 == 0 then
|
||||
logger.warn("[FanQieQR] 轮询失败 #" .. self.poll_failures .. ":", err)
|
||||
end
|
||||
poll_again()
|
||||
return
|
||||
end
|
||||
self.poll_failures = 0
|
||||
|
||||
local raw_set_cookie = Request.header(res, "Set-Cookie") or ""
|
||||
local new_jar = Cookie.merge_set_cookie(self.jar, raw_set_cookie)
|
||||
self.jar = new_jar
|
||||
local has_sessionid = new_jar.sessionid and new_jar.sessionid ~= ""
|
||||
|
||||
logger.dbg("[FanQieQR] 轮询 Set-Cookie(前300): " .. tostring(raw_set_cookie):sub(1, 300))
|
||||
logger.dbg("[FanQieQR] has_sessionid=" .. tostring(has_sessionid))
|
||||
|
||||
if has_sessionid then
|
||||
self:_finish_login_success(gen)
|
||||
return
|
||||
end
|
||||
|
||||
local data
|
||||
local text = res.body
|
||||
if text and #text > 0 then
|
||||
local ok, parsed = pcall(JSON.decode, text)
|
||||
if ok and type(parsed) == "table" then
|
||||
data = parsed
|
||||
end
|
||||
end
|
||||
|
||||
if not data then
|
||||
local location = Request.header(res, "Location") or ""
|
||||
logger.dbg("[FanQieQR] 非JSON响应, location=" .. tostring(location):sub(1, 100))
|
||||
poll_again()
|
||||
return
|
||||
end
|
||||
|
||||
local d = data.data or {}
|
||||
local status = d.status or ""
|
||||
if status == "success" or status == "confirmed" then
|
||||
logger.info("[FanQieQR] 确认状态 data=" .. tostring(text):sub(1, 500))
|
||||
logger.info("[FanQieQR] 用户已确认 status=" .. status)
|
||||
if d.redirect_url and d.redirect_url ~= "" then
|
||||
self:_finish_with_redirect(gen, d.redirect_url, csrf)
|
||||
else
|
||||
-- 无 redirect 时不要假装成功:登录态以 sessionid 为准,继续轮询等 Set-Cookie。
|
||||
logger.warn("[FanQieQR] " .. status .. " 但无 redirect_url / sessionid,继续轮询")
|
||||
poll_again()
|
||||
end
|
||||
elseif status == "expired" then
|
||||
self:show_retry(_("二维码已过期"))
|
||||
else
|
||||
if status == "scanned" or status == "confirming" or status == "confirm" then
|
||||
logger.info("[FanQieQR] 用户已扫码/确认中 status=", status)
|
||||
else
|
||||
logger.dbg("[FanQieQR] 轮询中 status=", status)
|
||||
end
|
||||
poll_again()
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
function QRLogin:_finish_with_redirect(gen, redirect_url, csrf)
|
||||
if gen ~= self.generation then return end
|
||||
self.plugin:showBusy(_("正在完成登录..."))
|
||||
logger.info("[FanQieQR] 访问 redirect_url:", tostring(redirect_url):sub(1, 80))
|
||||
|
||||
local max_redirects = 5
|
||||
local hop = 0
|
||||
local url = redirect_url
|
||||
|
||||
local function step()
|
||||
if gen ~= self.generation then return end
|
||||
hop = hop + 1
|
||||
if hop > max_redirects + 1 then
|
||||
self.plugin:closeBusy()
|
||||
self:show_retry(_("完成登录失败:") .. "\n重定向次数超限,未获取到 sessionid")
|
||||
return
|
||||
end
|
||||
self._job = self:_http_get(url, self.jar, csrf, function(res, err)
|
||||
if gen ~= self.generation then return end
|
||||
if not res then
|
||||
self.plugin:closeBusy()
|
||||
logger.warn("[FanQieQR] 访问 redirect_url 失败:", err)
|
||||
self:show_retry(_("完成登录失败:") .. "\n" .. tostring(err))
|
||||
return
|
||||
end
|
||||
self.jar = Cookie.merge_set_cookie(self.jar, Request.header(res, "Set-Cookie"))
|
||||
if self.jar.sessionid and self.jar.sessionid ~= "" then
|
||||
logger.info("[FanQieQR] 第" .. hop .. "跳获取到 sessionid")
|
||||
self.plugin:closeBusy()
|
||||
self:_finish_login_success(gen)
|
||||
return
|
||||
end
|
||||
local location = absolute_url(url, Request.header(res, "Location"))
|
||||
if not location then
|
||||
self.plugin:closeBusy()
|
||||
local keys = {}
|
||||
for k in pairs(self.jar) do keys[#keys + 1] = k end
|
||||
logger.warn("[FanQieQR] redirect 后仍无 sessionid, jar keys=" .. table.concat(keys, ","))
|
||||
self:show_retry(_("登录失败:未获取到 sessionid"))
|
||||
return
|
||||
end
|
||||
logger.dbg("[FanQieQR] 重定向第" .. hop .. "跳 -> " .. tostring(location):sub(1, 80))
|
||||
url = location
|
||||
step()
|
||||
end)
|
||||
end
|
||||
step()
|
||||
end
|
||||
|
||||
function QRLogin:_finish_login_success(gen)
|
||||
if gen ~= self.generation then return end
|
||||
if not (self.jar.sessionid and self.jar.sessionid ~= "") then
|
||||
logger.warn("[FanQieQR] 完成登录时 jar 无 sessionid")
|
||||
self:show_retry(_("登录失败:未获取到 sessionid"))
|
||||
return
|
||||
end
|
||||
local jar = {}
|
||||
for k, v in pairs(self.jar) do jar[k] = v end
|
||||
self.login_completed = true
|
||||
self.generation = self.generation + 1
|
||||
self:_cancel_job()
|
||||
self:_close("dialog")
|
||||
local keys = {}
|
||||
for k in pairs(jar) do keys[#keys + 1] = k end
|
||||
table.sort(keys)
|
||||
logger.info("[FanQieQR] 登录成功,扫码获取到 " .. #keys .. " 个 cookie: " .. table.concat(keys, ", "))
|
||||
if not require("source.logout").replaceLibrary("ext.fanqie", function()
|
||||
self.settings:set("cookies", jar)
|
||||
self.settings:flush()
|
||||
end) then
|
||||
Toast:new{ text = _("准备本地同步失败") }:show()
|
||||
return
|
||||
end
|
||||
self.jar = jar
|
||||
Toast:new{ text = _("登录成功") }:show()
|
||||
if type(self.plugin.onLoginSuccess) == "function" then
|
||||
self.plugin:onLoginSuccess()
|
||||
end
|
||||
end
|
||||
|
||||
function QRLogin:show_retry(msg)
|
||||
self.generation = self.generation + 1
|
||||
self:_cancel_job()
|
||||
self:_close("dialog")
|
||||
local dialog
|
||||
dialog = Confirm:new{
|
||||
text = tostring(msg),
|
||||
ok_text = _("重新获取"),
|
||||
ok_callback = function()
|
||||
if self.retry_dialog == dialog then self.retry_dialog = nil end
|
||||
self:start()
|
||||
end,
|
||||
cancel_callback = function()
|
||||
if self.retry_dialog == dialog then self.retry_dialog = nil end
|
||||
self:cancel()
|
||||
end,
|
||||
}
|
||||
self.retry_dialog = dialog
|
||||
dialog:show()
|
||||
end
|
||||
|
||||
return QRLogin
|
||||
@@ -0,0 +1,42 @@
|
||||
--[[--
|
||||
番茄网页榜单:解析榜单页内嵌的 __INITIAL_STATE__。书名 / 简介是 PUA 混淆字体,解码表同正文。
|
||||
|
||||
@module koplugin.book.moonsource_fanqie.rank
|
||||
--]]
|
||||
|
||||
local Content = require("moonsource_fanqie.content")
|
||||
local FanQie = require("moonsource_fanqie.fanqie")
|
||||
local JSON = require("json")
|
||||
|
||||
local Rank = {}
|
||||
|
||||
--- 榜单页 HTML → 榜单状态(book_list、rankCategoryTypeList)。脚本是 `(function(){ window.__INITIAL_STATE__={...}; })()`,
|
||||
--- 里面有裸 `undefined`,不是合法 JSON。
|
||||
---@param html string
|
||||
---@return table|nil rank
|
||||
function Rank.state(html)
|
||||
local script = html:match("__INITIAL_STATE__=(.-)</script>")
|
||||
local body = script and script:gsub("([:,%[])undefined", "%1null"):match("^(.*})%s*;%s*}%s*%)%s*%(%s*%)%s*$")
|
||||
local ok, state = pcall(JSON.decode, body or "")
|
||||
return ok and type(state) == "table" and state.rank or nil
|
||||
end
|
||||
|
||||
---@param rank table Rank.state 的结果
|
||||
---@param source_id string
|
||||
---@return Book[]
|
||||
function Rank.books(rank, source_id)
|
||||
local books = {}
|
||||
for _idx, row in ipairs(rank.book_list or {}) do
|
||||
books[#books + 1] = {
|
||||
source_id = source_id,
|
||||
stable_id = tostring(row.bookId),
|
||||
title = Content.decode_pua_content(row.bookName),
|
||||
authors = row.author or "",
|
||||
intro = Content.decode_pua_content(row.abstract),
|
||||
cover = FanQie.mobileCover(row.thumbUri),
|
||||
}
|
||||
end
|
||||
return books
|
||||
end
|
||||
|
||||
return Rank
|
||||
@@ -0,0 +1,207 @@
|
||||
--[[--
|
||||
番茄 App reading API 拉正文:registerkey → batch_full → 解密。
|
||||
协议来自 fanqie-re;网络走 http.request。
|
||||
|
||||
@module koplugin.book.moonsource_fanqie.reading
|
||||
--]]
|
||||
|
||||
local Crypto = require("moonsource_fanqie.reading.crypto")
|
||||
local Device = require("moonsource_fanqie.reading.device")
|
||||
local Sign = require("moonsource_fanqie.reading.sign")
|
||||
local JSON = require("json")
|
||||
local Request = require("http.request")
|
||||
local logger = require("utils.log")
|
||||
|
||||
local Reading = {}
|
||||
|
||||
local HOST = Crypto.HOST
|
||||
local TIMEOUT_RATIO = 2 / 3 -- × 「网络超时」,缺省 20 秒
|
||||
|
||||
---@param text string|nil
|
||||
---@return table|nil, string|nil
|
||||
local function decodeJson(text)
|
||||
if type(text) ~= "string" or text == "" then
|
||||
return nil, "空响应"
|
||||
end
|
||||
local ok, data = pcall(JSON.decode, text)
|
||||
if not ok or type(data) ~= "table" then
|
||||
return nil, "响应无效"
|
||||
end
|
||||
return data
|
||||
end
|
||||
|
||||
--- 带设备签名的 reading API 请求:build_body 非 nil 时以 JSON POST。
|
||||
--- 传输失败、非 2xx、空响应、非 JSON、业务 code≠0 或 data 非表都归一成 cb(nil, err)。
|
||||
---@param device table Device.ensureAsync 给出的设备身份
|
||||
---@param name string 接口名,用作错误文案前缀
|
||||
---@param path string
|
||||
---@param build_query fun(device: table, ts_ms: number): table
|
||||
---@param build_body (fun(device: table): string)|nil
|
||||
---@param cb fun(data: table|nil, err: string|nil) data 为完整回包
|
||||
---@return CancelHandle
|
||||
local function signedAsync(device, name, path, build_query, build_body, cb)
|
||||
local ts_ms = os.time() * 1000 + (math.random(0, 999))
|
||||
local qs = Crypto.encode_query(build_query(device, ts_ms))
|
||||
local headers = Crypto.build_unsigned_headers(device, ts_ms)
|
||||
if build_body then
|
||||
headers["Content-Type"] = "application/json"
|
||||
end
|
||||
for k, v in pairs(Sign.sign_headers(qs, device.device_id, {
|
||||
khronos = math.floor(ts_ms / 1000),
|
||||
version_name = device.version_name,
|
||||
device_type = device.device_type,
|
||||
os_version = device.os_version,
|
||||
})) do
|
||||
headers[k] = v
|
||||
end
|
||||
headers["X-Ss-Req-Ticket"] = tostring(ts_ms)
|
||||
local body = build_body and build_body(device)
|
||||
return Request.request({
|
||||
url = "https://" .. HOST .. path .. "?" .. qs,
|
||||
method = body and "POST" or "GET",
|
||||
headers = headers,
|
||||
body = body,
|
||||
timeout = require("http.timeout").net(TIMEOUT_RATIO),
|
||||
allow_redirects = true,
|
||||
}, function(res, err)
|
||||
if err or not res then
|
||||
cb(nil, err or name .. " 请求失败")
|
||||
return
|
||||
end
|
||||
local code = tonumber(res.code)
|
||||
if not Request.ok(code) then
|
||||
cb(nil, name .. " HTTP " .. tostring(code))
|
||||
return
|
||||
end
|
||||
local body_text = res.body or ""
|
||||
if body_text == "" then
|
||||
cb(nil, name .. " 空响应(设备身份可能被风控)")
|
||||
return
|
||||
end
|
||||
local data, decode_err = decodeJson(body_text)
|
||||
if not data then
|
||||
cb(nil, decode_err or name .. " 响应无效")
|
||||
return
|
||||
end
|
||||
if tonumber(data.code) ~= 0 or type(data.data) ~= "table" then
|
||||
cb(nil, name .. " 失败: " .. tostring(data.message or data.msg or data.code))
|
||||
return
|
||||
end
|
||||
cb(data)
|
||||
end)
|
||||
end
|
||||
|
||||
Reading.signedAsync = signedAsync
|
||||
|
||||
---@param device table
|
||||
---@param cb fun(v1_key: string|nil, err: string|nil)
|
||||
---@return CancelHandle
|
||||
local function registerKeyAsync(device, cb)
|
||||
return signedAsync(device, "registerkey", Crypto.REGISTERKEY_PATH, Crypto.build_common_query, function(device)
|
||||
return JSON.encode({
|
||||
content = Crypto.build_register_content(device.device_id, 0),
|
||||
keyver = 1,
|
||||
})
|
||||
end, function(data, err)
|
||||
if not data then
|
||||
cb(nil, err)
|
||||
return
|
||||
end
|
||||
if not data.data.key then
|
||||
cb(nil, "registerkey 失败: " .. tostring(data.message or data.msg or data.code))
|
||||
return
|
||||
end
|
||||
local ok, v1 = pcall(Crypto.decrypt_server_key, data.data.key)
|
||||
if not ok or not v1 then
|
||||
logger.warn("fanqie decrypt v1_key failed", v1)
|
||||
cb(nil, "解密 v1_key 失败")
|
||||
return
|
||||
end
|
||||
cb(v1)
|
||||
end)
|
||||
end
|
||||
|
||||
---@param device table
|
||||
---@param book_id string
|
||||
---@param item_id string
|
||||
---@param v1_key string
|
||||
---@param cb fun(row: table|nil, err: string|nil)
|
||||
---@return CancelHandle
|
||||
local function batchFullAsync(device, book_id, item_id, v1_key, cb)
|
||||
local function query(dev, ts_ms)
|
||||
return Crypto.build_batch_full_query(dev, book_id, { item_id }, ts_ms)
|
||||
end
|
||||
return signedAsync(device, "batch_full", Crypto.BATCH_FULL_PATH, query, nil, function(data, err)
|
||||
if not data then
|
||||
cb(nil, err)
|
||||
return
|
||||
end
|
||||
local item = data.data[item_id] or data.data[tostring(item_id)]
|
||||
if type(item) == "table" and item[1] then
|
||||
item = item[1]
|
||||
end
|
||||
if type(item) ~= "table" then
|
||||
cb(nil, "batch_full 无章节数据")
|
||||
return
|
||||
end
|
||||
local ok, text = pcall(Crypto.decode_chapter_item, item, v1_key)
|
||||
if not ok then
|
||||
logger.warn("fanqie chapter decrypt failed", text)
|
||||
cb(nil, "章节解密失败: " .. tostring(text))
|
||||
return
|
||||
end
|
||||
if type(text) ~= "string" or not text:match("%S") then
|
||||
cb(nil, "章节正文为空")
|
||||
return
|
||||
end
|
||||
cb({
|
||||
content = text,
|
||||
title = tostring(item.title or ""),
|
||||
author = tostring(item.author or item.authorName or ""),
|
||||
source = "reading_batch_full",
|
||||
})
|
||||
end)
|
||||
end
|
||||
|
||||
--- 拉取单章全文(App reading 协议)。
|
||||
---@param settings FanqieSettings
|
||||
---@param book_id string
|
||||
---@param item_id string
|
||||
---@param cb fun(data: table|nil, err: string|nil)
|
||||
---@return CancelHandle
|
||||
function Reading.fetchAsync(settings, book_id, item_id, cb)
|
||||
book_id, item_id = tostring(book_id or ""), tostring(item_id or "")
|
||||
if not book_id:match("^%d+$") or not item_id:match("^%d+$") then
|
||||
return require("source.base").defer(cb, nil, "章节 ID 无效")
|
||||
end
|
||||
local cancelled = false
|
||||
local job
|
||||
local handle = {
|
||||
cancel = function()
|
||||
cancelled = true
|
||||
if job and job.cancel then job.cancel() end
|
||||
end,
|
||||
}
|
||||
job = Device.ensureAsync(settings, function(device, device_err)
|
||||
if cancelled then return end
|
||||
if not device then
|
||||
cb(nil, device_err or "设备身份注册失败")
|
||||
return
|
||||
end
|
||||
job = registerKeyAsync(device, function(v1_key, err)
|
||||
if cancelled then return end
|
||||
if not v1_key then
|
||||
cb(nil, err or "registerkey 失败")
|
||||
return
|
||||
end
|
||||
logger.dbg("fanqie reading v1_key ok")
|
||||
job = batchFullAsync(device, book_id, item_id, v1_key, function(row, batch_err)
|
||||
if cancelled then return end
|
||||
cb(row, batch_err)
|
||||
end)
|
||||
end)
|
||||
end)
|
||||
return handle
|
||||
end
|
||||
|
||||
return Reading
|
||||
@@ -0,0 +1,240 @@
|
||||
--[[--
|
||||
番茄 reading API:registerkey / batch_full 请求构建与正文解密。
|
||||
移植自 fanqie-re/fanqie_crypto.py + fanqie_request.encode_query。
|
||||
|
||||
@module koplugin.book.moonsource_fanqie.reading.crypto
|
||||
--]]
|
||||
|
||||
local Aes = require("crypto.aes")
|
||||
local Text = require("utils.text")
|
||||
|
||||
local Crypto = {}
|
||||
|
||||
local HARDCODED_KEY = Aes.from_hex("ac25c67ddd8f38c1b37a2348828e222e")
|
||||
local AID = 1967
|
||||
|
||||
local function le64(n)
|
||||
-- device_id 常是 19 位十进制串,超过 2^53,转成 Lua 数字会丢低位;串按 uint64 精确累加。
|
||||
if type(n) == "string" and n:match("^%d+$") then
|
||||
local ffi = require("ffi")
|
||||
local v = ffi.new("uint64_t", 0)
|
||||
for d in n:gmatch("%d") do v = v * 10 + tonumber(d) end
|
||||
local out = {}
|
||||
for i = 1, 8 do
|
||||
out[i] = string.char(tonumber(v % 256))
|
||||
v = v / 256
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
n = tonumber(n) or 0
|
||||
local out = {}
|
||||
for i = 1, 8 do
|
||||
out[i] = string.char(n % 256)
|
||||
n = math.floor(n / 256)
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
Crypto.urandom = require("utils.random").bytes
|
||||
|
||||
local function uuid_iv()
|
||||
return (Aes.to_hex(Crypto.urandom(16)):sub(1, 16))
|
||||
end
|
||||
|
||||
---@param device_id string|number
|
||||
---@param user_id string|number|nil
|
||||
---@param iv_text string|nil 16 ASCII chars
|
||||
---@return string base64 content
|
||||
function Crypto.build_register_content(device_id, user_id, iv_text)
|
||||
local payload = le64(device_id) .. le64(user_id or 0)
|
||||
iv_text = iv_text or uuid_iv()
|
||||
assert(#iv_text == 16)
|
||||
local iv = iv_text
|
||||
local ct = Aes.cbc_encrypt(payload, HARDCODED_KEY, iv, true)
|
||||
return Text.base64Encode(iv .. ct)
|
||||
end
|
||||
|
||||
---@param encrypted_key_b64 string
|
||||
---@return string v1_key uppercase hex
|
||||
function Crypto.decrypt_server_key(encrypted_key_b64)
|
||||
local raw = Text.base64Decode(encrypted_key_b64)
|
||||
if #raw < 17 then error("encrypted key too short") end
|
||||
local pt = Aes.cbc_decrypt(raw:sub(17), HARDCODED_KEY, raw:sub(1, 16), true)
|
||||
return Aes.to_hex(pt):upper()
|
||||
end
|
||||
|
||||
---@param encrypted_content_b64 string
|
||||
---@param v1_key_hex string
|
||||
---@return string binary
|
||||
function Crypto.decrypt_content(encrypted_content_b64, v1_key_hex)
|
||||
local raw = Text.base64Decode(encrypted_content_b64)
|
||||
if #raw < 17 then error("encrypted content too short") end
|
||||
local key = Aes.from_hex(v1_key_hex:lower())
|
||||
return Aes.cbc_decrypt(raw:sub(17), key, raw:sub(1, 16), true)
|
||||
end
|
||||
|
||||
--- 尽量解压 gzip/zlib;失败则原样返回。
|
||||
---@param data string
|
||||
---@param compress_status number|nil
|
||||
---@return string
|
||||
function Crypto.maybe_decompress(data, compress_status)
|
||||
if not data or data == "" then return data end
|
||||
local is_gzip = data:byte(1) == 0x1f and data:byte(2) == 0x8b
|
||||
local is_zlib = data:byte(1) == 0x78
|
||||
local need = (tonumber(compress_status) or 0) > 0 or is_gzip or is_zlib
|
||||
if not need then return data end
|
||||
|
||||
--- 截断的载荷也要尽量给出前面解出的部分。
|
||||
local function inflate(blob, window_bits)
|
||||
return require("utils.inflate").all(blob, window_bits, true)
|
||||
end
|
||||
|
||||
if is_gzip then
|
||||
return inflate(data, 15 + 16) or inflate(data, 15 + 32) or data
|
||||
end
|
||||
if is_zlib then
|
||||
return inflate(data, 15) or data
|
||||
end
|
||||
-- raw deflate
|
||||
return inflate(data, -15) or data
|
||||
end
|
||||
|
||||
---@param item table
|
||||
---@param v1_key string
|
||||
---@return string
|
||||
function Crypto.decode_chapter_item(item, v1_key)
|
||||
local content_str = item.content or item.origin_content or ""
|
||||
if content_str == "" or content_str == "Invalid" then
|
||||
return ""
|
||||
end
|
||||
local crypt_status = tonumber(item.crypt_status) or 0
|
||||
local compress_status = tonumber(item.compress_status) or 0
|
||||
local raw
|
||||
if crypt_status == 0 and v1_key and v1_key ~= "" then
|
||||
raw = Crypto.decrypt_content(content_str, v1_key)
|
||||
else
|
||||
raw = content_str
|
||||
end
|
||||
return Crypto.maybe_decompress(raw, compress_status)
|
||||
end
|
||||
|
||||
---@param device table
|
||||
---@param ts_ms number|nil
|
||||
---@return table
|
||||
function Crypto.build_common_query(device, ts_ms)
|
||||
if type(ts_ms) ~= "number" then
|
||||
ts_ms = os.time() * 1000
|
||||
end
|
||||
return {
|
||||
iid = tostring(device.install_id),
|
||||
device_id = tostring(device.device_id),
|
||||
ac = "wifi",
|
||||
channel = device.channel or "43536163a",
|
||||
aid = tostring(AID),
|
||||
app_name = "novelapp",
|
||||
version_code = tostring(device.version_code or "73733"),
|
||||
version_name = tostring(device.version_name or "7.3.7.33"),
|
||||
device_platform = "android",
|
||||
os = "android",
|
||||
ssmix = "a",
|
||||
device_type = device.device_type or "P30",
|
||||
device_brand = device.device_brand or "Huawei",
|
||||
language = device.language or "zh",
|
||||
os_api = tostring(device.os_api or "30"),
|
||||
os_version = tostring(device.os_version or "12"),
|
||||
manifest_version_code = tostring(device.version_code or "73733"),
|
||||
resolution = device.resolution or "1280*720",
|
||||
dpi = tostring(device.dpi or "240"),
|
||||
update_version_code = tostring(device.version_code or "73733"),
|
||||
_rticket = tostring(ts_ms),
|
||||
host_abi = device.host_abi or "armeabi-v7a",
|
||||
cdid = device.cdid or "",
|
||||
openudid = device.openudid or "",
|
||||
}
|
||||
end
|
||||
|
||||
---@param device table
|
||||
---@param book_id string
|
||||
---@param item_ids string[]
|
||||
---@param ts_ms number|nil
|
||||
---@return table
|
||||
function Crypto.build_batch_full_query(device, book_id, item_ids, ts_ms)
|
||||
local q = Crypto.build_common_query(device, ts_ms)
|
||||
q.item_ids = table.concat(item_ids, ",")
|
||||
q.key_register_ts = "0"
|
||||
q.book_id = tostring(book_id)
|
||||
q.req_type = "1"
|
||||
return q
|
||||
end
|
||||
|
||||
--- ByteDance query:item_ids 逗号、* / + 不 percent-encode。
|
||||
---@param params table
|
||||
---@return string
|
||||
function Crypto.encode_query(params)
|
||||
local order = {
|
||||
"iid", "device_id", "ac", "channel", "aid", "app_name", "version_code",
|
||||
"version_name", "device_platform", "os", "ssmix", "device_type", "device_brand",
|
||||
"language", "os_api", "os_version", "manifest_version_code", "resolution",
|
||||
"dpi", "update_version_code", "_rticket", "host_abi", "cdid", "openudid",
|
||||
"item_ids", "key_register_ts", "book_id", "req_type",
|
||||
}
|
||||
local seen = {}
|
||||
local parts = {}
|
||||
local function add(k, v)
|
||||
if v == nil or seen[k] then return end
|
||||
seen[k] = true
|
||||
local vs = tostring(v)
|
||||
local ek = Text.urlEncode(tostring(k))
|
||||
local ev
|
||||
if k == "item_ids" then
|
||||
ev = (Text.urlEncode(vs):gsub("%%2C", ","))
|
||||
else
|
||||
ev = Text.urlEncode(vs)
|
||||
ev = ev:gsub("%%2A", "*"):gsub("%%2B", "+")
|
||||
end
|
||||
parts[#parts + 1] = ek .. "=" .. ev
|
||||
end
|
||||
for _idx, k in ipairs(order) do
|
||||
if params[k] ~= nil then add(k, params[k]) end
|
||||
end
|
||||
for k, v in pairs(params) do
|
||||
add(k, v)
|
||||
end
|
||||
return table.concat(parts, "&")
|
||||
end
|
||||
|
||||
---@param device table
|
||||
---@param ts_ms number|nil
|
||||
---@return table
|
||||
function Crypto.build_unsigned_headers(device, ts_ms)
|
||||
ts_ms = ts_ms or (os.time() * 1000)
|
||||
local vc = device.version_code or "73733"
|
||||
local rom = tostring(device.rom_version or "S643.217451.03386707"):match("^[^%+]+") or ""
|
||||
local ua = string.format(
|
||||
"com.dragon.read.oversea.gp/%s (Linux; U; Android %s; zh_CN; %s; Build/%s;tt-ok/3.12.13.4-tiktok)",
|
||||
vc, device.os_version or "12", device.device_type or "P30", rom)
|
||||
local rnd = require("utils.random").hex(4)
|
||||
return {
|
||||
["User-Agent"] = ua,
|
||||
["Accept"] = "application/json; charset=utf-8,application/x-protobuf",
|
||||
["Accept-Encoding"] = "identity",
|
||||
["sdk-version"] = "2",
|
||||
["passport-sdk-version"] = "50564",
|
||||
["lc"] = "101",
|
||||
["x-tt-store-region"] = "cn-zj",
|
||||
["x-tt-store-region-src"] = "did",
|
||||
["x-vc-bdturing-sdk-version"] = "3.7.2.cn",
|
||||
["x-xs-from-web"] = "0",
|
||||
["X-Ss-Req-Ticket"] = tostring(ts_ms),
|
||||
["x-reading-request"] = tostring(ts_ms) .. "-" .. rnd,
|
||||
["Cookie"] = "store-region=cn-zj; store-region-src=did; install_id="
|
||||
.. tostring(device.install_id),
|
||||
}
|
||||
end
|
||||
|
||||
Crypto.HARDCODED_KEY_HEX = "ac25c67ddd8f38c1b37a2348828e222e"
|
||||
Crypto.HOST = "api5-normal-sinfonlinec.fqnovel.com"
|
||||
Crypto.BATCH_FULL_PATH = "/reading/reader/batch_full/v"
|
||||
Crypto.REGISTERKEY_PATH = "/reading/crypt/registerkey"
|
||||
|
||||
return Crypto
|
||||
@@ -0,0 +1,274 @@
|
||||
--[[--
|
||||
番茄阅读设备身份:本机生成画像,经 device_register 换取 device_id/install_id。
|
||||
禁止复用别人的 did;每台 KOReader 安装各自持久化一份。
|
||||
|
||||
@module koplugin.book.moonsource_fanqie.reading.device
|
||||
--]]
|
||||
|
||||
local JSON = require("json")
|
||||
local Request = require("http.request")
|
||||
local Aes = require("crypto.aes")
|
||||
local logger = require("utils.log")
|
||||
local bit = require("bit")
|
||||
local _ = require("l10n").get("moonsource_fanqie")
|
||||
|
||||
local Device = {}
|
||||
|
||||
local REGISTER_HOST = "log.snssdk.com"
|
||||
local REGISTER_PATH = "/service/2/device_register/"
|
||||
local TIMEOUT_RATIO = 2 / 3 -- × 「网络超时」,缺省 20 秒
|
||||
|
||||
-- 画像模板(不含服务端签发的 id)。
|
||||
local PROFILE_TEMPLATE = {
|
||||
channel = "43536163a",
|
||||
version_code = "73733",
|
||||
version_name = "7.3.7.33",
|
||||
device_type = "P30",
|
||||
device_brand = "HUAWEI",
|
||||
language = "zh",
|
||||
os_api = "31",
|
||||
os_version = "12",
|
||||
resolution = "1280*720",
|
||||
dpi = "240",
|
||||
host_abi = "arm64-v8a",
|
||||
rom_version = "S643.217451.03386707",
|
||||
}
|
||||
|
||||
local urandom = require("moonsource_fanqie.reading.crypto").urandom
|
||||
|
||||
local function uuid4()
|
||||
local raw = urandom(16)
|
||||
local b = { raw:byte(1, 16) }
|
||||
b[7] = bit.bor(bit.band(b[7], 0x0f), 0x40)
|
||||
b[9] = bit.bor(bit.band(b[9], 0x3f), 0x80)
|
||||
return string.format(
|
||||
"%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
|
||||
b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8],
|
||||
b[9], b[10], b[11], b[12], b[13], b[14], b[15], b[16])
|
||||
end
|
||||
|
||||
---@return table 本地画像(含 cdid/openudid,尚无 device_id)
|
||||
function Device.newLocalProfile()
|
||||
local out = {}
|
||||
for k, v in pairs(PROFILE_TEMPLATE) do
|
||||
out[k] = v
|
||||
end
|
||||
out.cdid = uuid4()
|
||||
out.openudid = Aes.to_hex(urandom(8))
|
||||
out.clientudid = uuid4()
|
||||
return out
|
||||
end
|
||||
|
||||
---@param src table|nil
|
||||
---@return table|nil
|
||||
function Device.normalize(src)
|
||||
if type(src) ~= "table" then return nil end
|
||||
local profile = type(src.device_profile) == "table" and src.device_profile or src
|
||||
local device_id = tostring(src.device_id or "")
|
||||
local install_id = tostring(src.install_id or "")
|
||||
if device_id == "" or install_id == "" then
|
||||
return nil
|
||||
end
|
||||
local out = Device.newLocalProfile()
|
||||
for k in pairs(PROFILE_TEMPLATE) do
|
||||
if profile[k] ~= nil and tostring(profile[k]) ~= "" then
|
||||
out[k] = tostring(profile[k])
|
||||
end
|
||||
end
|
||||
if profile.cdid and profile.cdid ~= "" then out.cdid = tostring(profile.cdid) end
|
||||
if profile.openudid and profile.openudid ~= "" then out.openudid = tostring(profile.openudid) end
|
||||
if profile.clientudid and profile.clientudid ~= "" then
|
||||
out.clientudid = tostring(profile.clientudid)
|
||||
elseif src.clientudid and src.clientudid ~= "" then
|
||||
out.clientudid = tostring(src.clientudid)
|
||||
end
|
||||
out.device_id = device_id
|
||||
out.install_id = install_id
|
||||
out.version_code = tostring(out.version_code or PROFILE_TEMPLATE.version_code)
|
||||
out.version_name = tostring(out.version_name or PROFILE_TEMPLATE.version_name)
|
||||
return out
|
||||
end
|
||||
|
||||
---@param settings FanqieSettings
|
||||
---@param device table
|
||||
local function persist(settings, device)
|
||||
settings:set("reading_device", {
|
||||
install_id = device.install_id,
|
||||
device_id = device.device_id,
|
||||
clientudid = device.clientudid,
|
||||
device_profile = {
|
||||
channel = device.channel,
|
||||
version_code = device.version_code,
|
||||
version_name = device.version_name,
|
||||
device_type = device.device_type,
|
||||
device_brand = device.device_brand,
|
||||
language = device.language,
|
||||
os_api = device.os_api,
|
||||
os_version = device.os_version,
|
||||
resolution = device.resolution,
|
||||
dpi = device.dpi,
|
||||
host_abi = device.host_abi,
|
||||
cdid = device.cdid,
|
||||
openudid = device.openudid,
|
||||
rom_version = device.rom_version,
|
||||
},
|
||||
})
|
||||
settings:flush()
|
||||
end
|
||||
|
||||
---@param profile table
|
||||
---@return string url, string body, table headers
|
||||
local function buildRegisterRequest(profile)
|
||||
local now = os.time() * 1000 + math.random(0, 999)
|
||||
local openudid = profile.openudid
|
||||
local cdid = profile.cdid
|
||||
local qs = table.concat({
|
||||
"ac=wifi",
|
||||
"channel=" .. tostring(profile.channel),
|
||||
"aid=1967",
|
||||
"app_name=novelapp",
|
||||
"version_code=" .. tostring(profile.version_code),
|
||||
"version_name=" .. tostring(profile.version_name),
|
||||
"device_platform=android",
|
||||
"ssmix=a",
|
||||
"device_type=" .. tostring(profile.device_type),
|
||||
"device_brand=" .. tostring(profile.device_brand),
|
||||
"language=" .. tostring(profile.language),
|
||||
"os_api=" .. tostring(profile.os_api),
|
||||
"os_version=" .. tostring(profile.os_version),
|
||||
"openudid=" .. tostring(openudid),
|
||||
"manifest_version_code=" .. tostring(profile.version_code),
|
||||
"resolution=" .. tostring(profile.resolution),
|
||||
"dpi=" .. tostring(profile.dpi),
|
||||
"update_version_code=" .. tostring(profile.version_code),
|
||||
"_rticket=" .. tostring(now),
|
||||
"cdid=" .. tostring(cdid),
|
||||
}, "&")
|
||||
local body = {
|
||||
magic_tag = "ss_app_log",
|
||||
header = {
|
||||
display_name = "番茄小说",
|
||||
update_version_code = tonumber(profile.version_code) or 73733,
|
||||
manifest_version_code = tonumber(profile.version_code) or 73733,
|
||||
aid = 1967,
|
||||
channel = profile.channel,
|
||||
package = "com.dragon.read",
|
||||
app_version = profile.version_name,
|
||||
version_code = tonumber(profile.version_code) or 73733,
|
||||
sdk_version = "3.7.2.cn",
|
||||
os = "Android",
|
||||
os_version = profile.os_version,
|
||||
os_api = tonumber(profile.os_api) or 31,
|
||||
device_model = profile.device_type,
|
||||
device_brand = profile.device_brand,
|
||||
device_manufacturer = profile.device_brand,
|
||||
cpu_abi = profile.host_abi,
|
||||
density_dpi = tonumber(profile.dpi) or 240,
|
||||
resolution = (tostring(profile.resolution or "")):gsub("%*", "x"),
|
||||
language = profile.language,
|
||||
timezone = 8,
|
||||
access = "wifi",
|
||||
not_request_sender = 0,
|
||||
rom_version = profile.rom_version,
|
||||
cdid = cdid,
|
||||
openudid = openudid,
|
||||
clientudid = profile.clientudid or uuid4(),
|
||||
region = "CN",
|
||||
tz_name = "Asia/Shanghai",
|
||||
tz_offset = 28800,
|
||||
sim_region = "cn",
|
||||
req_id = uuid4(),
|
||||
apk_first_install_time = now - 86400000,
|
||||
is_system_app = 0,
|
||||
sdk_flavor = "china",
|
||||
},
|
||||
_gen_time = now,
|
||||
}
|
||||
local ua = string.format(
|
||||
"com.dragon.read/%s (Linux; U; Android %s; zh_CN; %s; Build/%s;tt-ok/3.12.13.4-tiktok)",
|
||||
profile.version_code, profile.os_version, profile.device_type,
|
||||
tostring(profile.rom_version):match("^[^%+]+") or "S643")
|
||||
return "https://" .. REGISTER_HOST .. REGISTER_PATH .. "?" .. qs,
|
||||
JSON.encode(body),
|
||||
{
|
||||
["Content-Type"] = "application/json; charset=utf-8",
|
||||
["User-Agent"] = ua,
|
||||
["Accept-Encoding"] = "identity",
|
||||
}
|
||||
end
|
||||
|
||||
--- 向 log.snssdk.com 注册,拿到本机专属 device_id/install_id。
|
||||
---@param settings FanqieSettings
|
||||
---@param cb fun(device: table|nil, err: string|nil)
|
||||
---@return CancelHandle
|
||||
function Device.registerAsync(settings, cb)
|
||||
local profile = Device.newLocalProfile()
|
||||
local url, body, headers = buildRegisterRequest(profile)
|
||||
return Request.request({
|
||||
url = url,
|
||||
method = "POST",
|
||||
headers = headers,
|
||||
body = body,
|
||||
timeout = require("http.timeout").net(TIMEOUT_RATIO),
|
||||
allow_redirects = true,
|
||||
}, function(res, err)
|
||||
-- turbo 超时仍返回 res 表,错误在 err;只看 res 会变成「HTTP nil」。
|
||||
if err or not res then
|
||||
local text = tostring(err or "")
|
||||
if text:find("refused", 1, true) or text:find("Could not connect", 1, true) then
|
||||
cb(nil, _("番茄正文需要注册设备,当前网络拦了 log.snssdk.com"))
|
||||
return
|
||||
end
|
||||
cb(nil, err or _("番茄设备注册失败,请放行 log.snssdk.com"))
|
||||
return
|
||||
end
|
||||
local code = tonumber(res.code)
|
||||
if not Request.ok(code) then
|
||||
cb(nil, "device_register HTTP " .. tostring(code))
|
||||
return
|
||||
end
|
||||
local text = res.body or ""
|
||||
if text == "" then
|
||||
cb(nil, "device_register 空响应")
|
||||
return
|
||||
end
|
||||
local ok, data = pcall(JSON.decode, text)
|
||||
if not ok or type(data) ~= "table" then
|
||||
cb(nil, "device_register 响应无效")
|
||||
return
|
||||
end
|
||||
local device_id = tostring(data.device_id_str or data.device_id or "")
|
||||
local install_id = tostring(data.install_id_str or data.install_id or "")
|
||||
if device_id == "" or install_id == "" then
|
||||
cb(nil, "device_register 未返回 device_id")
|
||||
return
|
||||
end
|
||||
profile.device_id = device_id
|
||||
profile.install_id = install_id
|
||||
persist(settings, profile)
|
||||
logger.info("fanqie device_register ok", "did=" .. device_id, "iid=" .. install_id)
|
||||
cb(profile)
|
||||
end)
|
||||
end
|
||||
|
||||
--- 已有身份下一帧返回;否则异步注册。
|
||||
--- 命中也必须异步:调用方在回调里换上后续请求的句柄,同步回调后再返回的句柄会把它覆盖掉。
|
||||
---@param settings FanqieSettings
|
||||
---@param cb fun(device: table|nil, err: string|nil)
|
||||
---@return CancelHandle
|
||||
function Device.ensureAsync(settings, cb)
|
||||
local cached = Device.get(settings)
|
||||
if cached then
|
||||
return require("source.base").defer(cb, cached)
|
||||
end
|
||||
return Device.registerAsync(settings, cb)
|
||||
end
|
||||
|
||||
--- 同步取已落盘身份;没有则返回 nil(调用方应走 ensureAsync)。
|
||||
---@param settings FanqieSettings
|
||||
---@return table|nil
|
||||
function Device.get(settings)
|
||||
return Device.normalize(settings:get("reading_device", nil))
|
||||
end
|
||||
|
||||
return Device
|
||||
@@ -0,0 +1,341 @@
|
||||
--[[--
|
||||
番茄四神签名:X-Khronos / X-Ladon / X-Helios / X-Argus。
|
||||
移植自 fanqie-re/fanqie_sign.py。
|
||||
|
||||
@module koplugin.book.moonsource_fanqie.reading.sign
|
||||
--]]
|
||||
|
||||
-- LuaJIT bit 的注解是 32 位 integer;这里传入的是 uint64 cdata 常量。
|
||||
---@diagnostic disable: param-type-mismatch
|
||||
|
||||
local Aes = require("crypto.aes")
|
||||
local Sm3 = require("crypto.sm3")
|
||||
local Text = require("utils.text")
|
||||
local md5 = require("ffi/sha2").md5
|
||||
local ffi = require("ffi")
|
||||
local bit = require("bit")
|
||||
|
||||
local Sign = {}
|
||||
|
||||
local AID = 1967
|
||||
local LADON_AID = 3019
|
||||
local LICENSE_ID = 1611921764
|
||||
local SDK_VERSION_STR = "v04.04.05-ov-android"
|
||||
local SDK_VERSION = 134744640
|
||||
|
||||
local SIGN_KEY = Aes.from_hex(
|
||||
"ac1adaae95a7af94a5114ab3b3a97dd80050aa0a39314c40528caec95256c28c")
|
||||
local INNER_SALT = string.char(0xf2, 0x81, 0x61, 0x6f)
|
||||
-- Z 常量:LuaJIT 字符串 cast 不可靠,拆成高低 32 位拼。
|
||||
local SIMON_Z = bit.bor(
|
||||
ffi.cast("uint64_t", 0x046D678B),
|
||||
bit.lshift(ffi.cast("uint64_t", 0x3DC94C3A), 32))
|
||||
|
||||
local function u64(n)
|
||||
if type(n) == "cdata" then return n end
|
||||
if type(n) == "string" then return ffi.cast("uint64_t", n) end
|
||||
return ffi.cast("uint64_t", n)
|
||||
end
|
||||
|
||||
local function u64_to_le(v)
|
||||
local p = ffi.new("uint64_t[1]", v)
|
||||
return ffi.string(p, 8)
|
||||
end
|
||||
|
||||
local function le_to_u64(s)
|
||||
local p = ffi.new("uint64_t[1]")
|
||||
ffi.copy(p, s, 8)
|
||||
return p[0]
|
||||
end
|
||||
|
||||
local function ror64(v, n)
|
||||
n = bit.band(n, 63)
|
||||
v = u64(v)
|
||||
if n == 0 then return v end
|
||||
return bit.bor(bit.rshift(v, n), bit.lshift(v, 64 - n))
|
||||
end
|
||||
|
||||
local function rol64(v, n)
|
||||
n = bit.band(n, 63)
|
||||
v = u64(v)
|
||||
if n == 0 then return v end
|
||||
return bit.bor(bit.lshift(v, n), bit.rshift(v, 64 - n))
|
||||
end
|
||||
|
||||
local urandom = require("moonsource_fanqie.reading.crypto").urandom
|
||||
|
||||
local function pkcs7_pad(data, block)
|
||||
return Aes.pkcs7_pad(data, block or 16)
|
||||
end
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- protobuf
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
local function varint(v)
|
||||
-- 无符号 32-bit:LuaJIT bit.* 对高位当有符号,不能直接 rshift。
|
||||
if type(v) ~= "number" then v = tonumber(v) or 0 end
|
||||
v = v % 0x100000000
|
||||
if v < 0 then v = v + 0x100000000 end
|
||||
local out = {}
|
||||
while v >= 0x80 do
|
||||
out[#out + 1] = string.char(bit.bor(bit.band(math.floor(v), 0x7f), 0x80))
|
||||
v = math.floor(v / 128)
|
||||
end
|
||||
out[#out + 1] = string.char(v)
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
local function pb_field(idx, wire, payload)
|
||||
return varint(bit.bor(bit.lshift(idx, 3), wire)) .. payload
|
||||
end
|
||||
|
||||
local function pb_varint(idx, val)
|
||||
return pb_field(idx, 0, varint(val))
|
||||
end
|
||||
|
||||
local function pb_bytes(idx, data)
|
||||
return pb_field(idx, 2, varint(#data) .. data)
|
||||
end
|
||||
|
||||
local function pb_str(idx, s)
|
||||
return pb_bytes(idx, s)
|
||||
end
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Ladon / Helios
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
local function encrypt_ladon_block(hash_table, block)
|
||||
local data0 = le_to_u64(block:sub(1, 8))
|
||||
local data1 = le_to_u64(block:sub(9, 16))
|
||||
for i = 0, 0x21 do
|
||||
local h = le_to_u64(hash_table:sub(i * 8 + 1, i * 8 + 8))
|
||||
data1 = bit.bxor(h, data0 + ror64(data1, 8))
|
||||
data0 = bit.bxor(data1, ror64(data0, 0x3d))
|
||||
end
|
||||
return u64_to_le(data0) .. u64_to_le(data1)
|
||||
end
|
||||
|
||||
local function build_ladon_hash_table(md5hex_ascii)
|
||||
local table_buf = md5hex_ascii:sub(1, 32) .. string.rep("\0", 272 + 16 - 32)
|
||||
local temp = {
|
||||
le_to_u64(table_buf:sub(1, 8)),
|
||||
le_to_u64(table_buf:sub(9, 16)),
|
||||
le_to_u64(table_buf:sub(17, 24)),
|
||||
le_to_u64(table_buf:sub(25, 32)),
|
||||
}
|
||||
local buffer_b0 = temp[1]
|
||||
local buffer_b8 = temp[2]
|
||||
-- drop first two; keep as queue
|
||||
local queue = { temp[3], temp[4] }
|
||||
local bytes = { table_buf:byte(1, #table_buf) }
|
||||
for i = 0, 0x21 do
|
||||
local x9 = buffer_b0
|
||||
local x8 = ror64(buffer_b8, 8)
|
||||
x8 = x8 + x9
|
||||
x8 = bit.bxor(x8, u64(i))
|
||||
queue[#queue + 1] = x8
|
||||
x8 = bit.bxor(x8, ror64(x9, 61))
|
||||
local le = u64_to_le(x8)
|
||||
for j = 1, 8 do
|
||||
bytes[(i + 1) * 8 + j] = le:byte(j)
|
||||
end
|
||||
buffer_b0 = x8
|
||||
buffer_b8 = table.remove(queue, 1)
|
||||
end
|
||||
local out = {}
|
||||
for i = 1, 272 + 16 do
|
||||
out[i] = string.char(bytes[i] or 0)
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
---@param khronos number
|
||||
---@param random4 string|nil 4 bytes
|
||||
---@return string base64
|
||||
function Sign.encrypt_ladon(khronos, random4)
|
||||
local data = string.format("%d-%d-%d", khronos, LICENSE_ID, LADON_AID)
|
||||
random4 = random4 or urandom(4)
|
||||
assert(#random4 == 4)
|
||||
local keygen = random4 .. tostring(AID)
|
||||
local table_ = build_ladon_hash_table(md5(keygen))
|
||||
local padded = pkcs7_pad(data, 16)
|
||||
local enc = {}
|
||||
for i = 1, #padded, 16 do
|
||||
enc[#enc + 1] = encrypt_ladon_block(table_, padded:sub(i, i + 15))
|
||||
end
|
||||
return Text.base64Encode(random4 .. table.concat(enc))
|
||||
end
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Argus
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
local function derive_inner_key()
|
||||
return Sm3.hash(SIGN_KEY .. INNER_SALT .. SIGN_KEY)
|
||||
end
|
||||
|
||||
local function simon_key_expansion(key4)
|
||||
local key = {}
|
||||
for i = 1, 4 do key[i] = key4[i] end
|
||||
for i = 5, 72 do
|
||||
local tmp = bit.bxor(ror64(key[i - 1], 3), key[i - 3])
|
||||
tmp = bit.bxor(tmp, ror64(tmp, 1))
|
||||
-- key 下标从 1 起:Lua 的 i=5 对应参考实现的第 4 个轮密钥,z 序列位为 (i-5)%62。
|
||||
local bit_i = bit.band(bit.rshift(SIMON_Z, (i - 5) % 62), u64(1))
|
||||
local not_prev = bit.bnot(key[i - 4])
|
||||
key[i] = bit.bxor(bit.bxor(bit.bxor(not_prev, tmp), bit_i), u64(3))
|
||||
end
|
||||
return key
|
||||
end
|
||||
|
||||
local function simon_encrypt_block(block, round_keys)
|
||||
local x_i = le_to_u64(block:sub(1, 8))
|
||||
local x_i1 = le_to_u64(block:sub(9, 16))
|
||||
for i = 1, 72 do
|
||||
local rk = round_keys[i]
|
||||
local tmp = x_i1
|
||||
local f = bit.band(rol64(x_i1, 1), rol64(x_i1, 8))
|
||||
x_i1 = bit.bxor(bit.bxor(bit.bxor(x_i, f), rol64(x_i1, 2)), rk)
|
||||
x_i = tmp
|
||||
end
|
||||
return u64_to_le(x_i) .. u64_to_le(x_i1)
|
||||
end
|
||||
|
||||
local function simon_encrypt(data, key32)
|
||||
assert(#data % 16 == 0 and #key32 == 32)
|
||||
local key4 = {
|
||||
le_to_u64(key32:sub(1, 8)),
|
||||
le_to_u64(key32:sub(9, 16)),
|
||||
le_to_u64(key32:sub(17, 24)),
|
||||
le_to_u64(key32:sub(25, 32)),
|
||||
}
|
||||
local rks = simon_key_expansion(key4)
|
||||
local out = {}
|
||||
for i = 1, #data, 16 do
|
||||
out[#out + 1] = simon_encrypt_block(data:sub(i, i + 15), rks)
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
local function get_bodyhash(stub_hex)
|
||||
local raw
|
||||
if stub_hex and stub_hex ~= "" then
|
||||
local ok, decoded = pcall(Aes.from_hex, stub_hex)
|
||||
raw = ok and decoded or string.rep("\0", 16)
|
||||
else
|
||||
raw = string.rep("\0", 16)
|
||||
end
|
||||
return Sm3.hash(raw):sub(1, 6)
|
||||
end
|
||||
|
||||
local function get_queryhash(query)
|
||||
if query and query ~= "" then
|
||||
return Sm3.hash(query):sub(1, 6)
|
||||
end
|
||||
return Sm3.hash(string.rep("\0", 16)):sub(1, 6)
|
||||
end
|
||||
|
||||
local function encrypt_enc_pb(data, length)
|
||||
local d = { data:byte(1, #data) }
|
||||
local xor_array = { unpack(d, 1, 8) }
|
||||
for i = 9, length do
|
||||
d[i] = bit.bxor(d[i], xor_array[((i - 1) % 8) + 1])
|
||||
end
|
||||
local rev = {}
|
||||
for i = length, 1, -1 do
|
||||
rev[#rev + 1] = string.char(d[i])
|
||||
end
|
||||
return table.concat(rev)
|
||||
end
|
||||
|
||||
local function u32_shl(v, n)
|
||||
-- bit.lshift 对 >2^30 的值会按有符号 32 位溢出;用乘法保 uint32。
|
||||
v = bit.band(v, 0xffffffff)
|
||||
for _step = 1, n do
|
||||
v = bit.band(v * 2, 0xffffffff)
|
||||
end
|
||||
return v
|
||||
end
|
||||
|
||||
---@param query string
|
||||
---@param timestamp number unix seconds (khronos)
|
||||
---@param device_id string
|
||||
---@param opts table|nil
|
||||
---@return string base64
|
||||
function Sign.encrypt_argus(query, timestamp, device_id, opts)
|
||||
opts = opts or {}
|
||||
local version_name = opts.version_name or "7.3.7.33"
|
||||
local aid = opts.aid or AID
|
||||
local device_type = opts.device_type or "P30"
|
||||
local os_version = opts.os_version or "12"
|
||||
local rand_val = opts.rand_val
|
||||
if not rand_val then
|
||||
local r = urandom(4)
|
||||
rand_val = bit.band(
|
||||
bit.bor(bit.lshift(r:byte(1), 24), bit.lshift(r:byte(2), 16),
|
||||
bit.lshift(r:byte(3), 8), r:byte(4)),
|
||||
0x7fffffff)
|
||||
end
|
||||
|
||||
local pb = table.concat({
|
||||
pb_varint(1, u32_shl(0x20200929, 1)),
|
||||
pb_varint(2, 2),
|
||||
pb_varint(3, rand_val),
|
||||
pb_str(4, tostring(aid)),
|
||||
pb_str(5, tostring(device_id)),
|
||||
pb_str(6, tostring(LICENSE_ID)),
|
||||
pb_str(7, version_name),
|
||||
pb_str(8, SDK_VERSION_STR),
|
||||
pb_varint(9, SDK_VERSION),
|
||||
pb_bytes(10, string.rep("\0", 8)),
|
||||
pb_varint(11, 0),
|
||||
pb_varint(12, u32_shl(timestamp, 1)),
|
||||
pb_bytes(13, get_bodyhash(opts.body_stub)),
|
||||
pb_bytes(14, get_queryhash(query)),
|
||||
pb_varint(20, 738),
|
||||
pb_bytes(23, table.concat({
|
||||
pb_str(1, device_type),
|
||||
pb_str(2, os_version),
|
||||
pb_str(3, "googleplay"),
|
||||
pb_varint(4, 0x48000000),
|
||||
})),
|
||||
})
|
||||
|
||||
local padded = pkcs7_pad(pb, 16)
|
||||
local enc_pb = simon_encrypt(padded, derive_inner_key())
|
||||
local prefix = string.char(0xf2, 0xf7, 0xfc, 0xff, 0xf2, 0xf7, 0xfc, 0xff)
|
||||
local inner = encrypt_enc_pb(prefix .. enc_pb, #enc_pb + 8)
|
||||
local head = string.char(0xa6, 0x6e, 0xad, 0x9f, 0x77, 0x01, 0xd0, 0x0c, 0x18)
|
||||
local buf = head .. inner .. "ao"
|
||||
local aes_key = Aes.from_hex(md5(SIGN_KEY:sub(1, 16)))
|
||||
local aes_iv = Aes.from_hex(md5(SIGN_KEY:sub(17, 32)))
|
||||
local encrypted = Aes.cbc_encrypt(buf, aes_key, aes_iv, true)
|
||||
return Text.base64Encode(string.char(0xf2, 0x81) .. encrypted)
|
||||
end
|
||||
|
||||
---@param query_string string
|
||||
---@param device_id string
|
||||
---@param opts table|nil
|
||||
---@return table headers
|
||||
function Sign.sign_headers(query_string, device_id, opts)
|
||||
opts = opts or {}
|
||||
local khronos = opts.khronos or os.time()
|
||||
return {
|
||||
["X-Khronos"] = tostring(khronos),
|
||||
["X-Ladon"] = Sign.encrypt_ladon(khronos, opts.ladon_random4),
|
||||
-- X-Helios 与 X-Ladon 同一算法,只是随机数独立。
|
||||
["X-Helios"] = opts.helios or Sign.encrypt_ladon(khronos, opts.helios_random4),
|
||||
["X-Argus"] = Sign.encrypt_argus(query_string, khronos, device_id, {
|
||||
version_name = opts.version_name,
|
||||
device_type = opts.device_type,
|
||||
os_version = opts.os_version,
|
||||
rand_val = opts.rand_val,
|
||||
}),
|
||||
}
|
||||
end
|
||||
|
||||
Sign.derive_inner_key = derive_inner_key
|
||||
|
||||
return Sign
|
||||
@@ -0,0 +1,324 @@
|
||||
--[[--
|
||||
番茄段评(App commentapi):本章各段评论数、某段的评论页、把段落定位到章节 HTML。
|
||||
|
||||
协议要点(与正文同一套设备签名,见 reading.lua):
|
||||
- 统计 ``idea/list`` 只能 GET 无 body;列表 ``comment/list`` 是 POST,body 里 comment_source=2、
|
||||
group_type=15,翻页游标是 body 里的字符串偏移(首屏空串)。
|
||||
- 回复 ``reply/list/{comment_id}`` 同样是 POST,comment_source 必须是 5;条数在评论的 stat.reply_count。
|
||||
- 签名不合规时服务端回 200 空响应,signedAsync 已把空响应归为失败,不会当成「没有段评」。
|
||||
- 章节正文段落形如 ``<p ...><blk p_idx="N">正文</blk></p>``,统计的键就是 blk 的 p_idx。
|
||||
|
||||
@module koplugin.book.moonsource_fanqie.reviews
|
||||
--]]
|
||||
|
||||
local Crypto = require("moonsource_fanqie.reading.crypto")
|
||||
local Device = require("moonsource_fanqie.reading.device")
|
||||
local Reading = require("moonsource_fanqie.reading")
|
||||
local Text = require("utils.text")
|
||||
local _ = require("l10n").get("moonsource_fanqie")
|
||||
|
||||
local Reviews = {}
|
||||
local EMOTICONS = {
|
||||
["[笑]"] = "1f604", ["[微笑]"] = "1f642", ["[大笑]"] = "1f606",
|
||||
["[偷笑]"] = "1f601", ["[笑哭]"] = "1f602", ["[奸笑]"] = "1f60f",
|
||||
["[捂脸]"] = "1f926", ["[哭]"] = "1f622", ["[思考]"] = "1f914",
|
||||
["[什么]"] = "2753", ["[害羞]"] = "1f633", ["[赞]"] = "1f44d",
|
||||
["[怒]"] = "1f621", ["[吃瓜]"] = "1f349", ["[盯]"] = "1f440",
|
||||
["[恐惧]"] = "1f631", ["[撇嘴]"] = "1f615", ["[酷]"] = "1f60e",
|
||||
["[爱慕]"] = "1f60d", ["[你细品]"] = "1f928", ["[尬笑]"] = "1f605",
|
||||
["[震惊]"] = "1f632", ["[快哭了]"] = "1f625", ["[送心]"] = "1f496",
|
||||
["[委屈]"] = "1f97a", ["[做鬼脸]"] = "1f61c", ["[舔屏]"] = "1f924",
|
||||
["[飞吻]"] = "1f618", ["[OK]"] = "1f44c", ["[翻白眼]"] = "1f644",
|
||||
["[惊呆]"] = "1f62e", ["[抓狂]"] = "1f62b", ["[吐]"] = "1f92e",
|
||||
}
|
||||
|
||||
--- 只映射已知表情;书中术语(如 [因果])与未知标记保留原文,不猜图片地址。
|
||||
---@param text string
|
||||
---@return table|nil
|
||||
local function inlineImages(text)
|
||||
local images = {}
|
||||
for token in text:gmatch("%b[]") do
|
||||
local hex = EMOTICONS[token]
|
||||
if hex then
|
||||
images[token] = { url = require("ui.themes.widgets.text.emoji").BASE .. hex .. ".png" }
|
||||
end
|
||||
end
|
||||
return next(images) and images or nil
|
||||
end
|
||||
|
||||
local STATS_PATH = "/novel/commentapi/idea/list/%s/v1/"
|
||||
local LIST_PATH = "/novel/commentapi/comment/list/%s/v1/"
|
||||
-- 回复哪条只由 URL 里的 comment_id 决定;body 的 comment_source 必须是 5,列表是 2。
|
||||
local REPLY_PATH = "/novel/commentapi/reply/list/%s/v1/"
|
||||
local PAGE_SIZE = 20
|
||||
-- 段评气泡跟在段末:只用段尾这么多个字定位(要唯一),气泡画在最后一行右侧。
|
||||
|
||||
---@class FanqieReviewHotspot
|
||||
---@field range string 段落序号(blk p_idx)
|
||||
---@field text string
|
||||
---@field total integer 本段评论数
|
||||
|
||||
local function query(device, ts_ms)
|
||||
local q = Crypto.build_common_query(device, ts_ms)
|
||||
q.compliance_status = "0"
|
||||
return q
|
||||
end
|
||||
|
||||
--- 先确保设备身份,再发一次签名请求。
|
||||
---@return CancelHandle
|
||||
local function call(settings, name, path, build_body, cb)
|
||||
local job, cancelled, ready = nil, false, false
|
||||
local registration = Device.ensureAsync(settings, function(device, err)
|
||||
ready = true
|
||||
if cancelled then return end
|
||||
if not device then
|
||||
cb(nil, err)
|
||||
return
|
||||
end
|
||||
job = Reading.signedAsync(device, name, path, query, build_body, function(wire, reason)
|
||||
if not cancelled then cb(wire, reason) end
|
||||
end)
|
||||
end)
|
||||
if not ready then job = registration end
|
||||
return { cancel = function()
|
||||
cancelled = true
|
||||
if job then job.cancel() end
|
||||
end }
|
||||
end
|
||||
|
||||
--- 本章有评论的段落。
|
||||
---@param settings FanqieSettings
|
||||
---@param item_id string
|
||||
---@param cb fun(hotspots: FanqieReviewHotspot[]|nil, err: string|nil)
|
||||
---@return CancelHandle
|
||||
function Reviews.hotspotsAsync(settings, item_id, cb)
|
||||
return call(settings, "comment_stats", STATS_PATH:format(item_id), nil, function(wire, err)
|
||||
if not wire then
|
||||
cb(nil, err)
|
||||
return
|
||||
end
|
||||
local raw = wire.data.data
|
||||
if type(raw) ~= "table" then
|
||||
cb(nil, _("番茄段评响应缺少段落统计"))
|
||||
return
|
||||
end
|
||||
local out = {}
|
||||
for key, info in pairs(raw) do
|
||||
local pid, total = tonumber(key), type(info) == "table" and tonumber(info.count)
|
||||
if not pid or not total or total < 0 then
|
||||
cb(nil, _("番茄段评响应包含无效段落统计"))
|
||||
return
|
||||
end
|
||||
if total > 0 then
|
||||
out[#out + 1] = { range = tostring(pid), text = "", total = total }
|
||||
end
|
||||
end
|
||||
table.sort(out, function(a, b) return tonumber(a.range) < tonumber(b.range) end)
|
||||
cb(out)
|
||||
end)
|
||||
end
|
||||
|
||||
--- 设备解不了 HEIC(用户上传图):改成同一张图的 800 宽 webp 缩略图(该地址不带签名)。
|
||||
--- 路径不是用户图的(表情等)原样返回。
|
||||
---@param url string
|
||||
---@return string
|
||||
local function displayUrl(url)
|
||||
if not url:find("~tplv%-[%w%-]+jpeg%.heic") then return url end
|
||||
local head = url:gsub("%?.*$", ""):match("^https?://[^/]+(/[^~]+)~tplv")
|
||||
if head and (head:match("^/tos%-cn%-i%-[%w]+/[^/]+$") or head:match("^/img/novel%-static/[^/]+$")) then
|
||||
return "https://p3-novel.byteimg.com" .. head .. "~tplv-1yzifmftcy-expand:800:0:0.webp"
|
||||
end
|
||||
return url
|
||||
end
|
||||
|
||||
--- 评论里的图:`image_data_list.image_data` 是图数组(兼容直接是数组 / 单个对象)。
|
||||
---@param content table
|
||||
---@return { url: string, width: integer, height: integer }[]
|
||||
local function images(content)
|
||||
local list = content.image_data_list
|
||||
if type(list) ~= "table" then return {} end
|
||||
local raw = list.image_data or list
|
||||
if raw.web_url then raw = { raw } end
|
||||
local out = {}
|
||||
for _idx, img in ipairs(raw) do
|
||||
local url = img.web_url or img.dynamic_url or img.expand_web_url
|
||||
if type(url) == "string" and url ~= "" then
|
||||
out[#out + 1] = { url = displayUrl(url), width = tonumber(img.width) or 0, height = tonumber(img.height) or 0 }
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
---@param entry table commentapi 评论条目
|
||||
---@return WechatReview
|
||||
local function item(entry)
|
||||
local c = type(entry.comment) == "table" and entry.comment or entry
|
||||
local common = type(c.common) == "table" and c.common or {}
|
||||
local user = type(common.user_info) == "table" and common.user_info or {}
|
||||
local base = type(user.base_info) == "table" and user.base_info or user
|
||||
local content = type(common.content) == "table" and common.content or {}
|
||||
local stat = type(c.stat) == "table" and c.stat or {}
|
||||
local created = tonumber(common.create_timestamp or common.create_time) or 0
|
||||
local text = tostring(content.text or common.text or "")
|
||||
return {
|
||||
id = tostring(c.comment_id or ""),
|
||||
author = tostring(base.user_name or common.user_name or ""),
|
||||
content = text,
|
||||
inline_images = inlineImages(text),
|
||||
likes = tonumber(stat.digg_count) or 0,
|
||||
replies = tonumber(stat.reply_count) or 0,
|
||||
images = images(content),
|
||||
time = created > 1e11 and math.floor(created / 1000) or created,
|
||||
}
|
||||
end
|
||||
|
||||
--- 回复条目。公共块字段名是 Common(也见过小写);楼中楼用 reply_to_user_info,不再开下一页。
|
||||
---@param entry table
|
||||
---@return WechatReview
|
||||
local function replyItem(entry)
|
||||
local common = type(entry.Common) == "table" and entry.Common
|
||||
or (type(entry.common) == "table" and entry.common or {})
|
||||
local user = type(common.user_info) == "table" and common.user_info or {}
|
||||
local base = type(user.base_info) == "table" and user.base_info or user
|
||||
local content = type(common.content) == "table" and common.content or {}
|
||||
local stat = type(entry.stat) == "table" and entry.stat or {}
|
||||
local to_info = type(entry.reply_to_user_info) == "table" and entry.reply_to_user_info or {}
|
||||
local to_base = type(to_info.base_info) == "table" and to_info.base_info or to_info
|
||||
local created = tonumber(common.create_timestamp or common.create_time) or 0
|
||||
local reply_to = to_base.user_name
|
||||
local text = tostring(content.text or "")
|
||||
return {
|
||||
id = tostring(entry.reply_id or ""),
|
||||
author = tostring(base.user_name or ""),
|
||||
content = text,
|
||||
inline_images = inlineImages(text),
|
||||
likes = tonumber(stat.digg_count) or 0,
|
||||
replies = 0,
|
||||
reply_to = type(reply_to) == "string" and reply_to ~= "" and reply_to or nil,
|
||||
images = images(content),
|
||||
time = created > 1e11 and math.floor(created / 1000) or created,
|
||||
}
|
||||
end
|
||||
|
||||
--- 某段的一页评论;max_idx 即游标偏移(首页 0)。
|
||||
---@param settings FanqieSettings
|
||||
---@param book_id string
|
||||
---@param item_id string
|
||||
---@param para_index integer
|
||||
---@param max_idx integer
|
||||
---@param cb fun(page: WechatReviewPage|nil, err: string|nil)
|
||||
---@return CancelHandle
|
||||
function Reviews.pageAsync(settings, book_id, item_id, para_index, max_idx, cb)
|
||||
local JSON = require("json")
|
||||
return call(settings, "comment_list", LIST_PATH:format(item_id), function()
|
||||
return JSON.encode({
|
||||
chapter_id = item_id,
|
||||
comment_source = 2,
|
||||
comment_type = 1,
|
||||
group_type = 15,
|
||||
count = PAGE_SIZE,
|
||||
sort = 0,
|
||||
cursor = max_idx > 0 and tostring(max_idx) or "",
|
||||
business_param = { book_id = book_id, item_version = "0", para_index = para_index },
|
||||
})
|
||||
end, function(wire, err)
|
||||
if not wire then
|
||||
cb(nil, err)
|
||||
return
|
||||
end
|
||||
local list = wire.data.data_list
|
||||
if type(list) ~= "table" then
|
||||
-- code 为 0 却没有 data_list:被限流 / 风控,不能当成「0 条」。
|
||||
cb(nil, "番茄段评响应缺少 data_list")
|
||||
return
|
||||
end
|
||||
local info = type(wire.data.common_list_info) == "table" and wire.data.common_list_info or {}
|
||||
if #list == 0 and max_idx == 0 and (tonumber(info.total) or 0) > 0 then
|
||||
cb(nil, _("番茄段评列表为空"))
|
||||
return
|
||||
end
|
||||
local items = {}
|
||||
for _idx, entry in ipairs(list) do
|
||||
if type(entry) == "table" then items[#items + 1] = item(entry) end
|
||||
end
|
||||
local cursor = tonumber(info.cursor)
|
||||
cb({
|
||||
items = items,
|
||||
total = tonumber(info.total) or #items,
|
||||
max_idx = cursor or max_idx,
|
||||
more = info.has_more == true and cursor ~= nil and cursor > max_idx and #items > 0,
|
||||
})
|
||||
end)
|
||||
end
|
||||
|
||||
--- 某条段评的一页回复。max_idx 即游标(首页 0 → 空串)。
|
||||
--- 空列表且 total>0 是风控的空成功,不当成「没有回复」。
|
||||
---@param settings FanqieSettings
|
||||
---@param comment_id string
|
||||
---@param max_idx integer|string
|
||||
---@param cb fun(page: WechatReviewPage|nil, err: string|nil)
|
||||
---@return CancelHandle
|
||||
function Reviews.repliesAsync(settings, comment_id, max_idx, cb)
|
||||
local JSON = require("json")
|
||||
local prev = (max_idx == 0 or max_idx == "") and "" or tostring(max_idx)
|
||||
return call(settings, "reply_list", REPLY_PATH:format(tostring(comment_id)), function()
|
||||
return JSON.encode({
|
||||
comment_id = tostring(comment_id),
|
||||
comment_source = 5,
|
||||
comment_type = 1,
|
||||
group_type = 15,
|
||||
count = PAGE_SIZE,
|
||||
cursor = prev,
|
||||
})
|
||||
end, function(wire, err)
|
||||
if not wire then
|
||||
cb(nil, err)
|
||||
return
|
||||
end
|
||||
local data = type(wire.data) == "table" and wire.data or {}
|
||||
local list = data.reply_list
|
||||
if type(list) ~= "table" then
|
||||
cb(nil, "番茄段评回复响应缺少 reply_list")
|
||||
return
|
||||
end
|
||||
local info = type(data.comment_list_info) == "table" and data.comment_list_info or {}
|
||||
if #list == 0 and (tonumber(info.total) or 0) > 0 then
|
||||
cb(nil, "番茄段评回复列表为空")
|
||||
return
|
||||
end
|
||||
local items = {}
|
||||
for _idx, entry in ipairs(list) do
|
||||
if type(entry) == "table" then items[#items + 1] = replyItem(entry) end
|
||||
end
|
||||
local cursor = info.cursor
|
||||
local next_cursor = cursor == nil and prev or tostring(cursor)
|
||||
cb({
|
||||
items = items,
|
||||
total = tonumber(info.total) or #items,
|
||||
max_idx = next_cursor,
|
||||
more = info.has_more == true and next_cursor ~= "" and next_cursor ~= prev and #items > 0,
|
||||
})
|
||||
end)
|
||||
end
|
||||
|
||||
--- 章节 HTML 里每段的纯文本,键为 blk p_idx。
|
||||
---@param html string
|
||||
---@return table<string, string>
|
||||
local function paragraphs(html)
|
||||
local out = {}
|
||||
for seg in html:gmatch("<p%s[^>]*>.-</p>") do
|
||||
local pid = seg:match('<blk[^>]-p_idx="(%d+)"')
|
||||
if pid then out[pid] = Text.trim((Text.stripHtml(seg):gsub('\n', ''))) end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
--- 把有评论的段落定位到章节 HTML。
|
||||
---@param hotspots FanqieReviewHotspot[]
|
||||
---@param html string
|
||||
---@return table[]
|
||||
function Reviews.locate(hotspots, html)
|
||||
return require("book.review_locate").locate(paragraphs(html), hotspots, html)
|
||||
end
|
||||
|
||||
return Reviews
|
||||
@@ -0,0 +1,80 @@
|
||||
--[[--
|
||||
番茄源设置入口。
|
||||
|
||||
@module koplugin.book.moonsource_fanqie.setting
|
||||
--]]
|
||||
|
||||
local _ = require("l10n").get("moonsource_fanqie")
|
||||
|
||||
local SOURCE_ID = "ext.fanqie"
|
||||
local M = {}
|
||||
|
||||
function M.rowTitle()
|
||||
return _("番茄账号与登录")
|
||||
end
|
||||
|
||||
function M.rowStatus()
|
||||
local ok = require("moonsource_fanqie.settings"):new():is_cookie_configured()
|
||||
return ok and _("已登录") or _("未登录 · 点此扫码"), ok
|
||||
end
|
||||
|
||||
function M.open()
|
||||
local settings = require("moonsource_fanqie.settings"):new()
|
||||
local owner = {}
|
||||
function owner:closeBusy()
|
||||
if self.busy then self.busy:close(); self.busy = nil end
|
||||
end
|
||||
function owner:showBusy(text)
|
||||
self:closeBusy()
|
||||
self.busy = require("ui.themes.widgets.progress_dialog"):new{
|
||||
title = _("番茄扫码登录"), text = text, dismissable = false,
|
||||
}
|
||||
self.busy:show()
|
||||
end
|
||||
function owner:onLoginSuccess()
|
||||
require("source.auth").ok(SOURCE_ID)
|
||||
require("source.registry").reload()
|
||||
end
|
||||
require("ui/network/manager"):runWhenConnected(function()
|
||||
require("moonsource_fanqie.qrlogin"):new(settings, owner):start()
|
||||
end)
|
||||
end
|
||||
|
||||
--- 设置页行:账号(扫码)与阅读选项。
|
||||
---@param plugin table|nil
|
||||
---@return table[]
|
||||
function M.rows(plugin)
|
||||
local Row = require("ui.themes.widgets.row")
|
||||
local rows = {
|
||||
function(iw)
|
||||
local status, status_on = M.rowStatus()
|
||||
return Row.widget({ width = iw, chevron = true, kind = "nav", icon = "account_circle",
|
||||
title = M.rowTitle(), status = status, status_on = status_on,
|
||||
callback = function() M.open() end })
|
||||
end,
|
||||
function(iw)
|
||||
local settings = require("moonsource_fanqie.settings"):new()
|
||||
local on = settings:get("show_paragraph_reviews", false) == true
|
||||
return Row.widget({ width = iw, chevron = false, kind = "toggle", icon = "forum",
|
||||
title = _("显示段评"), subtitle = _("阅读时给有他人段评的段落末尾画线,点按查看;需联网"),
|
||||
status = on and _("开") or _("关"), status_on = on,
|
||||
callback = function()
|
||||
settings:set("show_paragraph_reviews", not on)
|
||||
settings:flush()
|
||||
if plugin and plugin.desktop then plugin.desktop:updateView() end
|
||||
end })
|
||||
end,
|
||||
require("source.category_setting").row("ext.fanqie", plugin),
|
||||
}
|
||||
local _status, logged_in = M.rowStatus()
|
||||
if logged_in then
|
||||
rows[#rows + 1] = require("source.logout").row("ext.fanqie", _("确定退出番茄账号?"), function()
|
||||
local settings = require("moonsource_fanqie.settings"):new()
|
||||
settings:set("cookies", nil)
|
||||
settings:flush()
|
||||
end)
|
||||
end
|
||||
return rows
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,50 @@
|
||||
--[[--
|
||||
番茄源配置:落在 utils.settings.getSource("ext.fanqie")。
|
||||
|
||||
@module koplugin.book.moonsource_fanqie.settings
|
||||
--]]
|
||||
|
||||
local SOURCE_ID = "ext.fanqie"
|
||||
|
||||
---@class FanqieSettings
|
||||
---@field cfg table
|
||||
---@field get fun(self: FanqieSettings, key: string, default: any): any
|
||||
---@field set fun(self: FanqieSettings, key: string, value: any)
|
||||
---@field flush fun(self: FanqieSettings)
|
||||
---@field is_cookie_configured fun(self: FanqieSettings): boolean
|
||||
|
||||
local Settings = {}
|
||||
Settings.__index = Settings
|
||||
|
||||
---@return FanqieSettings
|
||||
function Settings:new()
|
||||
local cfg = require("utils.settings").getSource(SOURCE_ID)
|
||||
return setmetatable({ cfg = cfg }, self)
|
||||
end
|
||||
|
||||
---@param key string
|
||||
function Settings:get(key, default)
|
||||
local value = self.cfg[key]
|
||||
if value == nil then return default end
|
||||
return value
|
||||
end
|
||||
|
||||
---@param key string
|
||||
function Settings:set(key, value)
|
||||
self.cfg[key] = value
|
||||
end
|
||||
|
||||
function Settings:flush()
|
||||
require("utils.settings").saveSource(SOURCE_ID, self.cfg)
|
||||
end
|
||||
|
||||
---@return boolean
|
||||
function Settings:is_cookie_configured()
|
||||
-- 书架接口要 HttpOnly 会话 cookie;只有 novel_web_id 等可见 cookie 会返回 101119。
|
||||
local cookies = self.cfg.cookies
|
||||
return type(cookies) == "table"
|
||||
and type(cookies.sessionid) == "string"
|
||||
and cookies.sessionid ~= ""
|
||||
end
|
||||
|
||||
return Settings
|
||||
@@ -0,0 +1,558 @@
|
||||
--[[--
|
||||
番茄小说官方数据源。
|
||||
|
||||
正文走 App reading API:registerkey → batch_full → 解密(reading/)。书架双向(加架 / 移出架经番茄网页接口,Shelf.syncAsync 编排),搜索走免登录端点,进度双向,无笔记、统计。
|
||||
封面用 fanqie.lua 的 mobileCover 稳定路径(网页签名 thumb_url 会过期)。19 位设备 id 按 uint64 精确编码;Cookie 没变不重写设置。
|
||||
|
||||
@module moonsource_fanqie
|
||||
--]]
|
||||
|
||||
local Base = require("source.base")
|
||||
local Browse = require("source.browse")
|
||||
local Assets = require("source.assets")
|
||||
local Cbz = require("source.cbz")
|
||||
local Comic = require("moonsource_fanqie.comic")
|
||||
local Paths = require("utils.paths")
|
||||
local ReviewCache = require("book.review_cache")
|
||||
local _ = require("l10n").get("moonsource_fanqie")
|
||||
local T = require("ffi/util").template
|
||||
|
||||
local M = {}
|
||||
|
||||
---@class FanqieSource : SourceBase
|
||||
---@field settings FanqieSettings
|
||||
---@field client FanqieClient
|
||||
|
||||
-- 书架双向(shelfActionAsync add/delete);换账号要重推本地成员。
|
||||
local Source = setmetatable({ shelf_add = true }, { __index = Base })
|
||||
Source.__index = Source
|
||||
|
||||
function M.meta()
|
||||
return require("moonsource_fanqie.loadmeta")()
|
||||
end
|
||||
|
||||
function M.new()
|
||||
local Settings = require("moonsource_fanqie.settings")
|
||||
local Client = require("moonsource_fanqie.client")
|
||||
local settings = Settings:new()
|
||||
local meta = M.meta()
|
||||
return setmetatable({
|
||||
id = meta.id,
|
||||
name = meta.name,
|
||||
type = meta.type,
|
||||
settings = settings,
|
||||
client = Client:new(settings),
|
||||
}, Source)
|
||||
end
|
||||
|
||||
function Source:configured()
|
||||
return self.settings:is_cookie_configured()
|
||||
end
|
||||
|
||||
---@class FanqieAsyncHandle : CancelHandle
|
||||
---@field job CancelHandle|nil
|
||||
---@field cancelled boolean
|
||||
|
||||
---@return FanqieAsyncHandle
|
||||
local function handle()
|
||||
---@type FanqieAsyncHandle
|
||||
local h
|
||||
h = {
|
||||
job = nil,
|
||||
cancelled = false,
|
||||
cancel = function()
|
||||
h.cancelled = true
|
||||
if h.job and h.job.cancel then
|
||||
h.job.cancel()
|
||||
end
|
||||
end,
|
||||
}
|
||||
return h
|
||||
end
|
||||
|
||||
---@return string
|
||||
local function errMsg(err)
|
||||
if type(err) == "table" then
|
||||
return tostring(err.message or err.err or _("番茄请求失败"))
|
||||
end
|
||||
return tostring(err or _("番茄请求失败"))
|
||||
end
|
||||
|
||||
--- 秒;毫秒值折成秒。无效为 nil。
|
||||
---@param value any
|
||||
---@return integer|nil
|
||||
local function shelfTime(value)
|
||||
local n = tonumber(value) or 0
|
||||
if n > 1e11 then n = n / 1000 end
|
||||
if n > 0 then return math.floor(n) end
|
||||
end
|
||||
|
||||
--- 分类口径见 source.category_setting:开 = 只用自定义分组,关 = 不写分类(番茄书架不带题材)。
|
||||
--- 书架行带最后打开时间(last_operate_time)和加入时间(add_shelf_time)。
|
||||
local function shelfBook(row)
|
||||
local book = {
|
||||
source_id = "ext.fanqie",
|
||||
stable_id = tostring(row.book_id),
|
||||
title = row.book_name,
|
||||
authors = row.author_name,
|
||||
intro = require("utils.text").stripHtml(row.abstract),
|
||||
cover = row.thumb_url,
|
||||
read_at = shelfTime(row.last_operate_time),
|
||||
inserted_at = shelfTime(row.add_shelf_time),
|
||||
}
|
||||
book.category = require("source.category_setting").apply("ext.fanqie", nil, row._group_name)
|
||||
return book
|
||||
end
|
||||
|
||||
---@param wire table fetchShelfDetailAsync 的回包
|
||||
---@return Book[]
|
||||
local function shelfBooks(wire)
|
||||
local books = {}
|
||||
for _idx, row in ipairs(wire.data.detail_list) do
|
||||
local book = shelfBook(row)
|
||||
-- 书架快照就是分类口径:没进组要清掉旧分类。详情更新不带这个标记。
|
||||
book.category_authoritative = true
|
||||
books[#books + 1] = book
|
||||
end
|
||||
return books
|
||||
end
|
||||
|
||||
--- 书架远端:Shelf.syncAsync 要的三个冒号方法。
|
||||
---@param self FanqieSource
|
||||
---@param force boolean|nil
|
||||
local function shelfRemote(self, force)
|
||||
local remote = {}
|
||||
function remote.shelfSyncAsync(_remote, cb)
|
||||
return self.client:fetchShelfDetailAsync(force, function(wire, err)
|
||||
if not wire then
|
||||
cb(nil, errMsg(err))
|
||||
elseif type(wire.data) ~= "table" or type(wire.data.detail_list) ~= "table" then
|
||||
cb(nil, _("番茄书架响应不完整,保留本地书架"))
|
||||
else
|
||||
require("utils.paths").ensureLayout("ext.fanqie")
|
||||
cb(wire)
|
||||
end
|
||||
end)
|
||||
end
|
||||
function remote.addToShelfAsync(_remote, stable_id, cb)
|
||||
return self.client:shelfActionAsync("add", stable_id, cb)
|
||||
end
|
||||
function remote.removeFromShelfAsync(_remote, stable_id, cb)
|
||||
return self.client:shelfActionAsync("delete", stable_id, cb)
|
||||
end
|
||||
return remote
|
||||
end
|
||||
|
||||
---@param opts { force?: boolean, dirty_only?: boolean, on_progress?: fun(text: string|nil, done: integer|nil, total: integer|nil) }|nil
|
||||
---@param cb fun(result: SyncResult|nil, err: any)
|
||||
---@return CancelHandle|nil
|
||||
---@param self FanqieSource
|
||||
function Source:syncBooksAsync(opts, cb)
|
||||
opts = opts or {}
|
||||
if not self:configured() then
|
||||
if opts.dirty_only then return Base.skipped(cb, "fanqie not logged in") end
|
||||
return Base.defer(cb, nil, _("还没登录番茄小说。打开「设置 → 书库 → 账号 → 番茄小说 → 番茄账号与登录」,用番茄小说 App 或抖音扫屏幕上的二维码。"))
|
||||
end
|
||||
-- 加入时间来自书架 add_shelf_time,否则整架一次同步的 inserted_at 相同,「最近添加」只能按书号排。
|
||||
opts.inserted_at_from_row = true
|
||||
return require("source.shelf").syncAsync(self.id, shelfRemote(self, opts.force), shelfBooks, opts, cb)
|
||||
end
|
||||
|
||||
--- 书城搜索:免登录端点,字段比书架少(没有字数 / 最新章)。
|
||||
---@param keyword string
|
||||
---@param cb fun(res: { data: Book[] }|nil, err: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
function Source:searchAsync(keyword, cb)
|
||||
return self.client:searchAsync(keyword, function(wire, err)
|
||||
if not wire then
|
||||
cb(nil, errMsg(err))
|
||||
return
|
||||
end
|
||||
local FanQie = require("moonsource_fanqie.fanqie")
|
||||
local books = {}
|
||||
local list = type(wire.data) == "table" and wire.data.ret_data
|
||||
for _idx, row in ipairs(type(list) == "table" and list or {}) do
|
||||
if row.book_id then
|
||||
books[#books + 1] = {
|
||||
source_id = self.id,
|
||||
stable_id = tostring(row.book_id),
|
||||
title = row.title,
|
||||
authors = row.author or "",
|
||||
category = row.category,
|
||||
intro = row.abstract,
|
||||
cover = FanQie.mobileCover(row.thumb_url) or FanQie.mobileCover(row.audio_thumb_uri),
|
||||
}
|
||||
end
|
||||
end
|
||||
cb({ data = books })
|
||||
end)
|
||||
end
|
||||
|
||||
--- 书城浏览:网页榜单,榜单(阅读榜 / 新书榜)× 频道(男 / 女)× 分类;节点是「频道:榜单:分类」,缺省男频阅读榜首个分类。
|
||||
--- 页面只带前 10 本(分页接口要签名),分类列表取自页面本身。
|
||||
---@param opts { node?: string }
|
||||
---@param cb fun(res: { data: Book[], groups: StoreChipGroup[] }|nil, err: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
function Source:browseAsync(opts, cb)
|
||||
local gender, kind, category = (opts.node or "1:2:"):match("^(%d):(%d):(%d*)$")
|
||||
return self.client:rankAsync(gender .. "_" .. kind .. (category ~= "" and "_" .. category or ""), function(html, err)
|
||||
local rank = html and require("moonsource_fanqie.rank").state(html)
|
||||
if not rank then
|
||||
cb(nil, err and errMsg(err) or _("加载失败"))
|
||||
return
|
||||
end
|
||||
local cats, first = {}, nil
|
||||
for _idx, cat in ipairs(rank.rankCategoryTypeList[gender == "1" and "male" or "female"] or {}) do
|
||||
first = first or cat.id
|
||||
cats[#cats + 1] = { id = gender .. ":" .. kind .. ":" .. cat.id, title = cat.name }
|
||||
end
|
||||
local node = gender .. ":" .. kind .. ":" .. (category ~= "" and category or first or "")
|
||||
cb({
|
||||
data = require("moonsource_fanqie.rank").books(rank, self.id),
|
||||
groups = {
|
||||
Browse.group({ { id = gender .. ":2:", title = _("阅读榜") }, { id = gender .. ":1:", title = _("新书榜") } },
|
||||
gender .. ":" .. kind .. ":"),
|
||||
Browse.group({ { id = "1:" .. kind .. ":", title = _("男频") }, { id = "0:" .. kind .. ":", title = _("女频") } },
|
||||
gender .. ":" .. kind .. ":"),
|
||||
Browse.group(cats, node),
|
||||
},
|
||||
})
|
||||
end)
|
||||
end
|
||||
|
||||
function Source:getDetailAsync(identity, cb)
|
||||
local h = handle()
|
||||
h.job = self.client:fetchBookDetailAsync(identity.stable_id, function(row, err)
|
||||
if h.cancelled then return end
|
||||
if not row then cb(nil, errMsg(err)); return end
|
||||
local BookDB = require("book.books_db")
|
||||
local book = shelfBook(row)
|
||||
local existing = BookDB.get(self.id, identity.stable_id)
|
||||
if existing then book.deleted = existing.deleted end
|
||||
if not BookDB.upsertRemote(book) then
|
||||
cb(nil, _("书籍信息保存失败"))
|
||||
return
|
||||
end
|
||||
cb(BookDB.get(self.id, identity.stable_id))
|
||||
end)
|
||||
return h
|
||||
end
|
||||
|
||||
--- 刷新目录时按 uid 并入已缓存的章内锚点。TocDB.put 只保留同 uid 的 words/paid,不会带回 extra。
|
||||
---@param previous BookChapter[]|nil
|
||||
---@param toc BookChapter[]
|
||||
local function mergeCachedAnchors(previous, toc)
|
||||
if not previous or #previous == 0 then return end
|
||||
local Content = require("moonsource_fanqie.content")
|
||||
local by_uid = {}
|
||||
for _idx, chapter in ipairs(previous) do
|
||||
if chapter.uid then
|
||||
by_uid[tostring(chapter.uid)] = chapter
|
||||
end
|
||||
end
|
||||
for _idx, chapter in ipairs(toc) do
|
||||
local old = chapter.uid and by_uid[tostring(chapter.uid)]
|
||||
if old then
|
||||
Content.merge_anchors(chapter, old.anchors)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--- 正文刚下完时,把章内锚点写进已缓存目录(失败不影响开章)。
|
||||
---@param identity BookIdentity
|
||||
---@param chapter BookChapter
|
||||
---@param html string
|
||||
local function persistAnchorsFromHtml(identity, chapter, html)
|
||||
local Toc = require("source.toc")
|
||||
local Content = require("moonsource_fanqie.content")
|
||||
local source_id = identity.source_id or "ext.fanqie"
|
||||
local list = Toc.read(source_id, identity.stable_id)
|
||||
if not list then return end
|
||||
local target
|
||||
for _idx, item in ipairs(list) do
|
||||
if item.uid == tostring(chapter.uid) or item.idx == chapter.idx then
|
||||
target = item
|
||||
break
|
||||
end
|
||||
end
|
||||
if not target then return end
|
||||
if Content.merge_anchors(target, Content.html_anchors(html, (target.depth or 1) + 1)) then
|
||||
Toc.put(source_id, identity.stable_id, list)
|
||||
end
|
||||
end
|
||||
|
||||
--- 强制拉目录并写回;失败由调用方继续用旧缓存。
|
||||
---@param identity BookIdentity
|
||||
---@param cb fun(toc: BookChapter[]|nil, err: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
function Source:refreshTocAsync(identity, cb)
|
||||
local Toc = require("source.toc")
|
||||
local Content = require("moonsource_fanqie.content")
|
||||
local h = handle()
|
||||
h.job = self.client:fetchChapterDirectoryAsync(identity.stable_id, function(wire, err)
|
||||
if h.cancelled then return end
|
||||
if not wire then
|
||||
cb(nil, errMsg(err))
|
||||
return
|
||||
end
|
||||
local rows = Content.readable_chapters(Content.normalize_chapters(wire))
|
||||
local toc = {}
|
||||
for _idx, row in ipairs(rows) do
|
||||
local w = tonumber(row.wordCount or row.word_count or row.words or row.chapterWordCount)
|
||||
toc[#toc + 1] = {
|
||||
idx = #toc + 1, uid = tostring(row.itemId), title = row.title,
|
||||
words = w and w > 0 and w or nil,
|
||||
depth = row.depth,
|
||||
volume = row.volume,
|
||||
anchors = row.anchors,
|
||||
}
|
||||
end
|
||||
if #toc == 0 then
|
||||
cb(nil, _("番茄目录为空"))
|
||||
return
|
||||
end
|
||||
mergeCachedAnchors(Toc.read(self.id, identity.stable_id), toc)
|
||||
if not Toc.put(self.id, identity.stable_id, toc) then
|
||||
cb(nil, _("章节目录保存失败"))
|
||||
return
|
||||
end
|
||||
cb(toc)
|
||||
end)
|
||||
return h
|
||||
end
|
||||
|
||||
function Source:loadTocAsync(identity, cb)
|
||||
local Toc = require("source.toc")
|
||||
local cached = Toc.read(self.id, identity.stable_id)
|
||||
if cached and #cached > 0 then
|
||||
return Base.defer(cb, cached)
|
||||
end
|
||||
return self:refreshTocAsync(identity, cb)
|
||||
end
|
||||
|
||||
local function comicPath(identity, chapter)
|
||||
return Paths.bookWorkDir(identity.stable_id, identity.source_id) .. "/" .. chapter.uid .. ".cbz"
|
||||
end
|
||||
|
||||
---@param url string
|
||||
---@param cb fun(data: string|nil, err: any)
|
||||
---@return { cancel: fun() }|nil
|
||||
local function downloadImage(url, cb)
|
||||
return require("http.request").get(url, {
|
||||
accept = "image/avif,image/webp,image/apng,image/*,*/*;q=0.8",
|
||||
headers = { ["Referer"] = "https://fanqienovel.com/" },
|
||||
timeout = require("http.timeout").net(3),
|
||||
allow_redirects = true,
|
||||
}, function(raw, err)
|
||||
if raw and raw ~= "" then cb(raw) else cb(nil, err) end
|
||||
end)
|
||||
end
|
||||
|
||||
local function fetch(self, identity, chapter, cb)
|
||||
local Content = require("moonsource_fanqie.content")
|
||||
Paths.ensureBookWork(identity.stable_id, identity.source_id)
|
||||
-- 已打好的漫画章节不再联网(也免去正文接口风控)
|
||||
local archive = comicPath(identity, chapter)
|
||||
if Cbz.ready(archive) then
|
||||
return Base.defer(cb, { file = archive })
|
||||
end
|
||||
local h = handle()
|
||||
h.job = self.client:officialGetContentAsync(identity.stable_id, chapter.uid, function(result, err)
|
||||
if h.cancelled then return end
|
||||
if not result then
|
||||
cb(nil, errMsg(err))
|
||||
return
|
||||
end
|
||||
local title = result.title ~= "" and result.title or chapter.title
|
||||
local urls, key = Comic.parse(result.content)
|
||||
if not urls then
|
||||
-- 正文里的远程插图落到书籍工作目录;下不下来的图保留原地址,不拖垮整章。
|
||||
h.job = Assets.localizeAsync(Content.decode_pua_content(result.content),
|
||||
Paths.bookWorkDir(identity.stable_id, identity.source_id) .. "/images", downloadImage,
|
||||
function(html)
|
||||
if h.cancelled then return end
|
||||
persistAnchorsFromHtml(identity, chapter, html)
|
||||
cb({ title = title, html = html })
|
||||
end)
|
||||
return
|
||||
end
|
||||
h.job = Comic.materializeAsync(urls, key, comicPath(identity, chapter), function(path, err_msg)
|
||||
if h.cancelled then return end
|
||||
if path then cb({ title = title, file = path }) else cb(nil, err_msg) end
|
||||
end)
|
||||
end)
|
||||
return h
|
||||
end
|
||||
|
||||
-- 番茄正文接口有设备风控,预取与整本下载都按这个间隔逐章请求。
|
||||
local FETCH_INTERVAL = 6
|
||||
|
||||
---@return ChapterFetchContent
|
||||
local function contentFetcher(self)
|
||||
return function(ref, ch, done) return fetch(self, ref, ch, done) end
|
||||
end
|
||||
|
||||
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 = contentFetcher(self),
|
||||
}, cb)
|
||||
end
|
||||
|
||||
function Source:prefetchChaptersAsync(identity, toc, from_idx, count, cb)
|
||||
return require("source.chapter").prefetchAsync(identity, identity.book, toc, from_idx, count, {
|
||||
fetchContent = contentFetcher(self),
|
||||
interval_seconds = FETCH_INTERVAL,
|
||||
}, cb)
|
||||
end
|
||||
|
||||
--- 缓存整本章节正文;已落盘章节由公共实现自动跳过。
|
||||
---@param identity BookIdentity
|
||||
---@param on_progress fun(done: integer, total: integer)|nil
|
||||
---@param cb fun(ok: boolean, cached: integer, err: string|nil, total: integer, failed: integer)
|
||||
---@return { cancel: fun() }
|
||||
function Source:cacheAllChaptersAsync(identity, on_progress, cb, range)
|
||||
return require("source.chapter").cacheAllAsync(self, identity, contentFetcher(self), on_progress, cb,
|
||||
FETCH_INTERVAL, range)
|
||||
end
|
||||
|
||||
function Source:getProgressAsync(identity, cb)
|
||||
local Toc = require("source.toc")
|
||||
local h = handle()
|
||||
h.job = self.client:fetchReadProgressAsync(function(wire, err)
|
||||
if h.cancelled then return end
|
||||
if not wire then
|
||||
cb(nil, errMsg(err))
|
||||
return
|
||||
end
|
||||
local row
|
||||
for _idx, item in ipairs(wire.data or {}) do
|
||||
if tostring(item.book_id) == identity.stable_id then
|
||||
row = item
|
||||
break
|
||||
end
|
||||
end
|
||||
if not row or not row.item_id then
|
||||
cb(nil, nil, { empty = true })
|
||||
return
|
||||
end
|
||||
h.job = self:loadTocAsync(identity, function(toc, reason)
|
||||
if h.cancelled then return end
|
||||
if not toc then
|
||||
cb(nil, reason)
|
||||
return
|
||||
end
|
||||
local idx = Toc.index(self.id, identity.stable_id, row.item_id)
|
||||
if not idx then
|
||||
cb(nil, nil, { empty = true })
|
||||
return
|
||||
end
|
||||
-- 官方网页只写章节:read_progress 为 0 或章节 order,并不是章内万分比。
|
||||
cb({
|
||||
chapter_idx = idx,
|
||||
fraction = (idx - 1) / #toc,
|
||||
extra = { chapter_uid = tostring(row.item_id), chapter_idx = idx },
|
||||
})
|
||||
end)
|
||||
end)
|
||||
return h
|
||||
end
|
||||
|
||||
function Source:putProgressAsync(identity, pos, cb)
|
||||
local h = handle()
|
||||
h.job = self:loadTocAsync(identity, function(toc, err)
|
||||
if h.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
|
||||
h.job = self.client:updateReadProgressAsync(
|
||||
identity.stable_id, chapter.uid, idx - 1,
|
||||
0,
|
||||
function(wire, reason)
|
||||
if h.cancelled then return end
|
||||
if not wire or tonumber(wire.code or 0) ~= 0 then
|
||||
cb(nil, reason and errMsg(reason) or _("番茄进度上传失败"))
|
||||
return
|
||||
end
|
||||
cb(true)
|
||||
end)
|
||||
end)
|
||||
return h
|
||||
end
|
||||
|
||||
--- 阅读页是否显示他人段评(设置页开关,默认关)。
|
||||
---@return boolean
|
||||
function Source:paragraphReviewsEnabled()
|
||||
return self.settings:get("show_paragraph_reviews", false) == true
|
||||
end
|
||||
|
||||
--- 章节序号 → 番茄 item_id,目录来自缓存或在线拉取。
|
||||
local function withChapterUid(self, identity, cb, start)
|
||||
local h = handle()
|
||||
h.job = self:loadTocAsync(identity, function(toc, err)
|
||||
if h.cancelled then return end
|
||||
local chapter = toc and toc[tonumber(identity.chapter_idx)]
|
||||
if not chapter then
|
||||
cb(nil, err or _("缺少番茄章节位置"))
|
||||
return
|
||||
end
|
||||
h.job = start(chapter.uid, cb)
|
||||
end)
|
||||
return h
|
||||
end
|
||||
|
||||
--- 本章有评论的段落(未定位)。
|
||||
---@param identity BookIdentity
|
||||
---@param cb fun(hotspots: FanqieReviewHotspot[]|nil, err: string|nil)
|
||||
---@return CancelHandle
|
||||
function Source:paragraphHotspotsAsync(identity, cb)
|
||||
return ReviewCache.hotspotsAsync(identity, function(done)
|
||||
return withChapterUid(self, identity, done, function(uid, finish)
|
||||
return require("moonsource_fanqie.reviews").hotspotsAsync(self.settings, uid, finish)
|
||||
end)
|
||||
end, cb)
|
||||
end
|
||||
|
||||
--- 段落按段末文字定位到章节 HTML(子进程里跑,不碰实例状态)。
|
||||
---@param hotspots FanqieReviewHotspot[]
|
||||
---@param html string
|
||||
---@return table[]
|
||||
function Source:locateHotspots(hotspots, html)
|
||||
return require("moonsource_fanqie.reviews").locate(hotspots, html)
|
||||
end
|
||||
|
||||
--- 某段的一页评论;range 是段落序号,max_idx 是游标偏移(首页 0)。
|
||||
---@param identity BookIdentity
|
||||
---@param range string
|
||||
---@param max_idx integer
|
||||
---@param cb fun(page: WechatReviewPage|nil, err: string|nil)
|
||||
---@return CancelHandle
|
||||
function Source:paragraphReviewPageAsync(identity, range, max_idx, cb)
|
||||
return ReviewCache.pageAsync(identity, range, max_idx, function(done)
|
||||
return withChapterUid(self, identity, done, function(uid, finish)
|
||||
return require("moonsource_fanqie.reviews").pageAsync(
|
||||
self.settings, identity.stable_id, uid, tonumber(range), max_idx, finish)
|
||||
end)
|
||||
end, cb)
|
||||
end
|
||||
|
||||
--- 某条段评的一页回复。不走段评缓存。
|
||||
---@param _identity BookIdentity
|
||||
---@param review_id string
|
||||
---@param max_idx integer|string
|
||||
---@param cb fun(page: WechatReviewPage|nil, err: string|nil)
|
||||
---@return CancelHandle
|
||||
function Source:paragraphReviewRepliesAsync(_identity, review_id, max_idx, cb)
|
||||
return require("moonsource_fanqie.reviews").repliesAsync(self.settings, review_id, max_idx, cb)
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,293 @@
|
||||
--[[--
|
||||
番茄书架详情:网页端查无此书的用书号占位保留;详情请求本身失败则整次失败(保留本地书架);
|
||||
并发有上限;book_shelf_info 上的 group_name 挂到详情行。
|
||||
|
||||
@module tests.moonsource_fanqie.client_spec
|
||||
--]]
|
||||
|
||||
local Assert = require("support.assert")
|
||||
|
||||
package.loaded["json"] = nil
|
||||
package.preload["json"] = function()
|
||||
local stub = require("support.json_stub")
|
||||
return { decode = stub.decode, encode = stub.encode }
|
||||
end
|
||||
|
||||
local SHELF_IDS = { "1", "2", "3" }
|
||||
-- book_id → group_name;空表 = 书架项不带分组字段(和没建文件夹的账号一致)。
|
||||
local SHELF_GROUPS = {}
|
||||
local SHELF_OPERATE, SHELF_ADDED = {}, {}
|
||||
local fail_ids = {}
|
||||
local gone_ids = {}
|
||||
local requests = 0
|
||||
-- 异步桩:详情请求先挂起,由 drain 逐个回包,才量得出并发。
|
||||
local held = {}
|
||||
local no_multi = false
|
||||
local in_flight, peak = 0, 0
|
||||
package.loaded["http.request"] = nil
|
||||
package.preload["http.request"] = function()
|
||||
return {
|
||||
header = function() return nil end,
|
||||
ok = function(code) return code >= 200 and code < 300 end,
|
||||
request = function(opts, cb)
|
||||
requests = requests + 1
|
||||
if opts.url:find("/bookshelf/info/", 1, true) then
|
||||
local list = {}
|
||||
for _idx, id in ipairs(SHELF_IDS) do
|
||||
local item = '{"book_id":"' .. id .. '"'
|
||||
if SHELF_GROUPS[id] then
|
||||
item = item .. ',"group_id":"7","group_name":"' .. SHELF_GROUPS[id] .. '"'
|
||||
end
|
||||
if SHELF_OPERATE[id] then
|
||||
item = item .. ',"last_operate_time":' .. SHELF_OPERATE[id]
|
||||
end
|
||||
if SHELF_ADDED[id] then
|
||||
item = item .. ',"add_shelf_time":' .. SHELF_ADDED[id]
|
||||
end
|
||||
list[#list + 1] = item .. "}"
|
||||
end
|
||||
cb({ code = 200, body = '{"code":0,"data":{"book_shelf_info":[' .. table.concat(list, ",") .. ']}}' })
|
||||
return { cancel = function() end }
|
||||
end
|
||||
if opts.url:find("/multidetail", 1, true) then
|
||||
local bid = opts.body:match('"book_id":"(%d+)"')
|
||||
cb({ code = 200, body = no_multi and '{"code":0,"data":{"detail_list":[]}}'
|
||||
or '{"code":0,"data":{"detail_list":[{"book_id":"' .. bid .. '","book_name":"架上' .. bid .. '"}]}}' })
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local id = opts.url:match("bookId=(%d+)")
|
||||
in_flight = in_flight + 1
|
||||
if in_flight > peak then peak = in_flight end
|
||||
held[#held + 1] = function()
|
||||
in_flight = in_flight - 1
|
||||
if fail_ids[id] then
|
||||
cb(nil, "timeout")
|
||||
elseif gone_ids[id] then
|
||||
cb({ code = 200, body = '{"code":-1,"message":"book not found"}' })
|
||||
else
|
||||
local metadata = id == "1"
|
||||
and ',"author":"年轻熊","abstract":"真正的书籍简介","description":"作者签名"'
|
||||
or ',"author":"","authorName":"兼容作者","abstract":"另一份简介","description":"仍是作者签名"'
|
||||
cb({ code = 200, body = '{"code":0,"data":{"bookName":"书' .. id .. '","thumbUri":"x"' .. metadata .. '}}' })
|
||||
end
|
||||
end
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
end
|
||||
local function drain()
|
||||
while #held > 0 do table.remove(held, 1)() end
|
||||
end
|
||||
package.preload["ui/uimanager"] = function()
|
||||
return { nextTick = function(_, f) f() end }
|
||||
end
|
||||
package.loaded["ui/uimanager"] = nil
|
||||
|
||||
package.loaded["moonsource_fanqie.client"] = nil
|
||||
local Client = require("moonsource_fanqie.client")
|
||||
local settings = {
|
||||
get = function(_, _key, default) return default end,
|
||||
set = function() end,
|
||||
flush = function() end,
|
||||
}
|
||||
local client = Client:new(settings)
|
||||
|
||||
-- 一本超时:整次失败,不能把这本书从本地书架藏起来;失败结果不进缓存。
|
||||
fail_ids["2"] = true
|
||||
local data, err
|
||||
client:fetchShelfDetailAsync(false, function(d, e) data, err = d, e end)
|
||||
drain()
|
||||
Assert.is_nil(data)
|
||||
Assert.eq(err, "timeout")
|
||||
|
||||
-- 一本查无此书:占位保留,其余照常返回,不报错。
|
||||
fail_ids["2"] = nil
|
||||
gone_ids["3"] = true
|
||||
requests = 0
|
||||
client:fetchShelfDetailAsync(false, function(d, e) data, err = d, e end)
|
||||
drain()
|
||||
Assert.eq(requests, 5, "上次失败没进缓存,这次必须重新请求")
|
||||
Assert.is_nil(err)
|
||||
Assert.len(data.data.detail_list, 3)
|
||||
Assert.eq(data.data.detail_list[1].book_name, "书1")
|
||||
Assert.eq(data.data.detail_list[2].book_id, "2")
|
||||
Assert.eq(data.data.detail_list[1].author_name, "年轻熊", "第三方版权书只返回 author")
|
||||
Assert.eq(data.data.detail_list[1].abstract, "真正的书籍简介", "description 是作者签名,不能当书简介")
|
||||
Assert.eq(data.data.detail_list[2].author_name, "兼容作者")
|
||||
Assert.eq(data.data.detail_list[2].abstract, "另一份简介")
|
||||
Assert.eq(data.data.detail_list[3].book_name, "架上3", "网页查无此书时用书架 multidetail 取书名")
|
||||
|
||||
-- 结果进缓存:再拉直接命中,不再发请求。
|
||||
requests = 0
|
||||
client:fetchShelfDetailAsync(false, function(d) data = d end)
|
||||
Assert.eq(requests, 0)
|
||||
Assert.len(data.data.detail_list, 3)
|
||||
|
||||
-- 强制刷新绕过缓存:恢复后按书架顺序拿全。
|
||||
gone_ids["3"] = nil
|
||||
client:fetchShelfDetailAsync(true, function(d, e) data, err = d, e end)
|
||||
drain()
|
||||
Assert.is_nil(err)
|
||||
Assert.len(data.data.detail_list, 3)
|
||||
Assert.eq(data.data.detail_list[3].book_id, "3")
|
||||
|
||||
-- 全部查无此书且 multidetail 也没有:全部书号占位,不报错。
|
||||
gone_ids = { ["1"] = true, ["2"] = true, ["3"] = true }
|
||||
no_multi = true
|
||||
client:fetchShelfDetailAsync(true, function(d, e) data, err = d, e end)
|
||||
drain()
|
||||
Assert.is_nil(err)
|
||||
Assert.len(data.data.detail_list, 3)
|
||||
Assert.eq(data.data.detail_list[1].book_name, "番茄书籍 1")
|
||||
no_multi = false
|
||||
|
||||
-- 大书架:详情请求并发不超过 4,全部拿到后按书架顺序返回。
|
||||
gone_ids = {}
|
||||
SHELF_IDS = {}
|
||||
for i = 1, 10 do SHELF_IDS[i] = tostring(100 + i) end
|
||||
peak = 0
|
||||
client:fetchShelfDetailAsync(true, function(d, e) data, err = d, e end)
|
||||
Assert.eq(in_flight, 4)
|
||||
drain()
|
||||
Assert.eq(peak, 4)
|
||||
Assert.is_nil(err)
|
||||
Assert.len(data.data.detail_list, 10)
|
||||
Assert.eq(data.data.detail_list[10].book_id, "110")
|
||||
|
||||
do -- 书架分组:book_shelf_info 上的 group_name 挂到详情行(没进组的不写)
|
||||
SHELF_IDS = { "1", "2", "3" }
|
||||
SHELF_GROUPS = { ["1"] = "追更", ["3"] = "追更" }
|
||||
gone_ids = {}
|
||||
client:fetchShelfDetailAsync(true, function(d, e) data, err = d, e end)
|
||||
drain()
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(data.data.detail_list[1]._group_name, "追更")
|
||||
Assert.is_nil(data.data.detail_list[2]._group_name, "没进组不算分组")
|
||||
Assert.eq(data.data.detail_list[3]._group_name, "追更")
|
||||
SHELF_GROUPS = {}
|
||||
SHELF_OPERATE = { ["1"] = 1793017940, ["2"] = 1788754903 }
|
||||
SHELF_ADDED = { ["1"] = 1789912130 }
|
||||
client:fetchShelfDetailAsync(true, function(d, e) data, err = d, e end)
|
||||
drain()
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(data.data.detail_list[1].last_operate_time, 1793017940)
|
||||
Assert.eq(data.data.detail_list[1].add_shelf_time, 1789912130)
|
||||
Assert.eq(data.data.detail_list[2].last_operate_time, 1788754903)
|
||||
Assert.is_nil(data.data.detail_list[2].add_shelf_time, "没给加入时间就不写")
|
||||
SHELF_OPERATE, SHELF_ADDED = {}, {}
|
||||
end
|
||||
|
||||
do
|
||||
client:fetchBookDetailAsync("1", function(d, e) data, err = d, e end)
|
||||
drain()
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(data.author_name, "年轻熊")
|
||||
Assert.eq(data.abstract, "真正的书籍简介")
|
||||
fail_ids["1"] = true
|
||||
client:fetchBookDetailAsync("1", function(d, e) data, err = d, e end)
|
||||
drain()
|
||||
Assert.is_nil(data)
|
||||
Assert.eq(err, "timeout")
|
||||
fail_ids["1"] = nil
|
||||
gone_ids["1"] = true
|
||||
client:fetchBookDetailAsync("1", function(d, e) data, err = d, e end)
|
||||
drain()
|
||||
Assert.is_nil(data)
|
||||
Assert.matches(err, "book not found")
|
||||
gone_ids["1"] = nil
|
||||
end
|
||||
|
||||
do -- Set-Cookie 值没变不落盘;变了才 flush 一次
|
||||
local set_cookie = "ttwid=a; Path=/"
|
||||
package.loaded["http.request"] = {
|
||||
header = function(_res, name) if name == "Set-Cookie" then return set_cookie end end,
|
||||
ok = function(code) return code >= 200 and code < 300 end,
|
||||
request = function(_opts, cb)
|
||||
cb({ code = 200, body = '{"code":0,"data":{}}' })
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
package.loaded["moonsource_fanqie.client"] = nil
|
||||
local C = require("moonsource_fanqie.client")
|
||||
local store, flushes = {}, 0
|
||||
local s = {
|
||||
get = function(_, key, default) return store[key] or default end,
|
||||
set = function(_, key, value) store[key] = value end,
|
||||
flush = function() flushes = flushes + 1 end,
|
||||
}
|
||||
local c = C:new(s)
|
||||
c:fetchReadProgressAsync(function() end)
|
||||
c:fetchReadProgressAsync(function() end)
|
||||
Assert.eq(flushes, 1, "同值 Set-Cookie 不重复写设置")
|
||||
set_cookie = "ttwid=b; Path=/"
|
||||
c:fetchReadProgressAsync(function() end)
|
||||
Assert.eq(flushes, 2)
|
||||
Assert.eq(store.cookies.ttwid, "b")
|
||||
package.loaded["http.request"] = nil
|
||||
package.loaded["moonsource_fanqie.client"] = nil
|
||||
end
|
||||
|
||||
do -- 搜索免登录(不带 Cookie、App UA);书架加 / 删走网页接口并校验业务码
|
||||
local seen, reply, reply_code
|
||||
package.loaded["http.request"] = {
|
||||
header = function() return nil end,
|
||||
ok = function(code) return code >= 200 and code < 300 end,
|
||||
request = function(opts, cb)
|
||||
seen = opts
|
||||
cb({ code = reply_code or 200, body = reply })
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
package.loaded["moonsource_fanqie.client"] = nil
|
||||
local C = require("moonsource_fanqie.client")
|
||||
local c = C:new({ get = function(_, _key, default) return default end, set = function() end, flush = function() end })
|
||||
local d, e
|
||||
reply = '{"code":0,"data":{"ret_data":[]}}'
|
||||
c:searchAsync("斗 破", function(r, err) d, e = r, err end)
|
||||
Assert.matches(seen.url, "q=%%E6%%96%%97")
|
||||
Assert.matches(seen.headers["User-Agent"], "com%.dragon%.read")
|
||||
Assert.is_nil(seen.headers["Cookie"])
|
||||
Assert.not_nil(d)
|
||||
reply = '{"code":1,"message":"bad"}'
|
||||
c:searchAsync("x", function(r, err) d, e = r, err end)
|
||||
Assert.is_nil(d)
|
||||
Assert.matches(e, "番茄搜索失败")
|
||||
|
||||
reply = '{"code":0}'
|
||||
c:shelfActionAsync("add", "42", function(r, err) d, e = r, err end)
|
||||
Assert.matches(seen.url, "/bookshelf/add/")
|
||||
Assert.matches(seen.body, '"book_id":"42"')
|
||||
Assert.matches(seen.body, "add_book_source")
|
||||
Assert.not_nil(d)
|
||||
c:shelfActionAsync("delete", "42", function(r, err) d, e = r, err end)
|
||||
Assert.matches(seen.url, "/bookshelf/delete/")
|
||||
Assert.is_nil(seen.body:find("add_book_source", 1, true))
|
||||
reply = '{"code":101108,"message":"无用户信息"}'
|
||||
local Auth = require("source.auth")
|
||||
Auth.reset()
|
||||
c:shelfActionAsync("delete", "42", function(r, err) d, e = r, err end)
|
||||
Assert.is_nil(d)
|
||||
Assert.matches(e, "重新登录")
|
||||
Assert.is_true(Auth.expired("ext.fanqie"))
|
||||
Auth.reset()
|
||||
|
||||
-- HTTP 错误给用户只留短句:诊断串(URL/状态码拼接)只进日志;
|
||||
-- 非 JSON 回包(风控 HTML 页)同样只报「响应无效」。
|
||||
reply_code = 500
|
||||
reply = "<html><title>blocked</title></html>"
|
||||
c:searchAsync("x", function(r, err) d, e = r, err end)
|
||||
Assert.is_nil(d)
|
||||
Assert.eq(e, "请求失败 (HTTP 500)")
|
||||
reply = '{"code":500,"message":"服务繁忙"}'
|
||||
c:searchAsync("x", function(r, err) d, e = r, err end)
|
||||
Assert.eq(e, "服务繁忙")
|
||||
reply_code = 200
|
||||
reply = "<html>not json</html>"
|
||||
c:searchAsync("x", function(r, err) d, e = r, err end)
|
||||
Assert.is_nil(d)
|
||||
Assert.eq(e, "响应无效")
|
||||
package.loaded["http.request"] = nil
|
||||
package.loaded["moonsource_fanqie.client"] = nil
|
||||
end
|
||||
|
||||
return true
|
||||
@@ -0,0 +1,36 @@
|
||||
--[[--
|
||||
番茄漫画章节:JSON 页清单 → 页图地址,页图 AES-GCM 解密(只解 CTR 流)。
|
||||
|
||||
@module tests.moonsource_fanqie.comic_spec
|
||||
--]]
|
||||
|
||||
local Assert = require("support.assert")
|
||||
package.preload["json"] = function()
|
||||
local J = require("support.json_stub")
|
||||
return { encode = J.encode, decode = J.decode }
|
||||
end
|
||||
package.loaded["json"] = nil
|
||||
|
||||
local Aes = require("crypto.aes")
|
||||
local Comic = require("moonsource_fanqie.comic")
|
||||
|
||||
local key_hex = string.rep("00", 32)
|
||||
local urls, key = Comic.parse('{"picInfos":[{"picUrl":"https://x/a.jpg?a=1&b=2"},{"picUrl":"https://x/b.jpg"}],'
|
||||
.. '"encrypt":true,"encrypt_key":"' .. key_hex .. '"}')
|
||||
Assert.len(urls, 2)
|
||||
Assert.eq(urls[1], "https://x/a.jpg?a=1&b=2")
|
||||
Assert.eq(urls[2], "https://x/b.jpg")
|
||||
Assert.eq(key, string.rep("\0", 32))
|
||||
|
||||
local _, plain_key = Comic.parse('{"picInfos":[{"picUrl":"https://x/a.jpg"}]}')
|
||||
Assert.is_nil(plain_key)
|
||||
|
||||
Assert.is_nil(Comic.parse("<p>正文</p>"))
|
||||
Assert.is_nil(Comic.parse('{"picInfos":[]}'))
|
||||
|
||||
-- NIST GCM 测试向量 2:全零 128 位密钥与 IV,明文 16 个零字节
|
||||
local iv = string.rep("\0", 12)
|
||||
local sealed = iv .. Aes.from_hex("0388dace60b6a392f328c2b971b2fe78" .. "ab6e47d42cec13bdf53a67b21257bddf")
|
||||
Assert.eq(Comic.decrypt(sealed, string.rep("\0", 16)), string.rep("\0", 16))
|
||||
Assert.eq(Comic.decrypt("raw", nil), "raw")
|
||||
Assert.is_nil(Comic.decrypt("short", string.rep("\0", 16)))
|
||||
@@ -0,0 +1,121 @@
|
||||
--[[--
|
||||
番茄 PUA 解码:真实章节片段必须解成可读中文。
|
||||
|
||||
@module tests.moonsource_fanqie.content_spec
|
||||
--]]
|
||||
|
||||
local Assert = require("support.assert")
|
||||
|
||||
package.loaded["moonsource_fanqie.content"] = nil
|
||||
local Content = require("moonsource_fanqie.content")
|
||||
|
||||
-- /api/reader/full 第1章首段原始字节(含 PUA)
|
||||
local sample = "\227\128\144\238\144\178\232\176\162\230\130\168\238\146\168\229\135\187\238\147\184\238\147\186\233\152\133\232\175\187\239\188\140\238\147\175\238\146\142\238\147\179\238\147\131\238\148\170\238\145\138\238\144\182\239\188\140\231\174\128\228\187\139\238\145\141\238\144\142\238\146\128\227\128\145"
|
||||
local decoded = Content.decode_pua_content(sample)
|
||||
Assert.eq(decoded, "【感谢您点击进来阅读,其他的就不说了,简介里都有】")
|
||||
|
||||
-- 官方目录:分卷二维数组优先,平铺且跳过没有 itemId 的行
|
||||
local by_volume = Content.normalize_chapters({ data = {
|
||||
chapterListWithVolume = {
|
||||
{ { itemId = "1", title = "封面" }, { itemId = "2", title = "第1章" } },
|
||||
{ { title = "无 id" }, { itemId = "3", title = "第2章" } },
|
||||
},
|
||||
chapterList = { { itemId = "x" } },
|
||||
} })
|
||||
Assert.len(by_volume, 3)
|
||||
Assert.eq(by_volume[3].itemId, "3")
|
||||
Assert.eq(by_volume[1].depth, 1, "无卷名时不编造卷标题,章仍为第 1 层")
|
||||
Assert.eq(by_volume[3].depth, 1)
|
||||
Assert.len(Content.readable_chapters(by_volume), 2)
|
||||
|
||||
-- 没有分卷时用 chapterList
|
||||
local flat = Content.normalize_chapters({ data = { chapterListWithVolume = {}, chapterList = { { itemId = "9" } } } })
|
||||
Assert.eq(flat[1].itemId, "9")
|
||||
Assert.eq(flat[1].depth, 1)
|
||||
|
||||
-- 只有 allItemIds:按序号起标题
|
||||
local ids = Content.normalize_chapters({ data = { allItemIds = { "7", "8" } } })
|
||||
Assert.eq(ids[2].itemId, "8")
|
||||
Assert.eq(ids[2].title, "第2章")
|
||||
Assert.eq(ids[2].depth, 1)
|
||||
|
||||
-- 回包缺 data:空目录
|
||||
Assert.len(Content.normalize_chapters({ code = 0 }), 0)
|
||||
Assert.len(Content.normalize_chapters(nil), 0)
|
||||
|
||||
-- normalize 保留上游字数字段(有则估全书页码)
|
||||
do
|
||||
local rows = Content.normalize_chapters({ data = { chapterList = {
|
||||
{ itemId = "1", title = "A", wordCount = 1200 },
|
||||
{ itemId = "2", title = "B", word_count = 800 },
|
||||
} } })
|
||||
Assert.eq(tonumber(rows[1].wordCount), 1200)
|
||||
Assert.eq(tonumber(rows[2].word_count), 800)
|
||||
end
|
||||
|
||||
|
||||
-- 有卷名:章 depth=2 并带 volume,不额外占 idx
|
||||
do
|
||||
local rows = Content.normalize_chapters({ data = {
|
||||
chapterListWithVolume = {
|
||||
{ volumeName = "第一卷", chapterList = { { itemId = "1", title = "第1章" }, { itemId = "2", title = "第2章" } } },
|
||||
{ volume_name = "第二卷", { itemId = "3", title = "第3章" } },
|
||||
},
|
||||
} })
|
||||
Assert.len(rows, 3)
|
||||
Assert.eq(rows[1].depth, 2)
|
||||
Assert.eq(rows[1].volume, "第一卷")
|
||||
Assert.eq(rows[2].volume, "第一卷")
|
||||
Assert.eq(rows[3].itemId, "3")
|
||||
Assert.eq(rows[3].depth, 2)
|
||||
Assert.eq(rows[3].volume, "第二卷")
|
||||
end
|
||||
|
||||
-- 官方子节点收成 anchors,不另开一章
|
||||
do
|
||||
local rows = Content.normalize_chapters({ data = { chapterList = {
|
||||
{ itemId = "10", title = "正文", children = {
|
||||
{ title = "第一节", anchor = "toc_1" },
|
||||
{ title = "第二节", id = "toc_2" },
|
||||
} },
|
||||
} } })
|
||||
Assert.len(rows, 1)
|
||||
Assert.len(rows[1].anchors, 2)
|
||||
Assert.eq(rows[1].anchors[1].title, "第一节")
|
||||
Assert.eq(rows[1].anchors[1].id, "toc_1")
|
||||
Assert.eq(rows[1].anchors[1].depth, 2)
|
||||
Assert.eq(rows[1].anchors[2].id, "toc_2")
|
||||
end
|
||||
|
||||
-- HTML toc_*:有可见标题用原文,纯图片锚点回退 #N
|
||||
do
|
||||
local html = [[<h1>正文</h1>
|
||||
<h2 id="toc_1">第一节 相遇</h2><p>文字</p>
|
||||
<p class="picture" id="toc_2"><img src="a.jpg"/></p>
|
||||
<p id="toc_11"><img src="b.jpg"/></p>
|
||||
<p id="toc_2">重复 id 忽略</p>]]
|
||||
local anchors = Content.html_anchors(html, 2)
|
||||
Assert.len(anchors, 3)
|
||||
Assert.eq(anchors[1].id, "toc_1")
|
||||
Assert.eq(anchors[1].title, "第一节 相遇")
|
||||
Assert.eq(anchors[1].depth, 2)
|
||||
Assert.eq(anchors[2].id, "toc_2")
|
||||
Assert.eq(anchors[2].title, "#2")
|
||||
Assert.eq(anchors[3].id, "toc_11")
|
||||
Assert.eq(anchors[3].title, "#11")
|
||||
Assert.len(Content.html_anchors(""), 0)
|
||||
Assert.len(Content.html_anchors(nil), 0)
|
||||
end
|
||||
|
||||
-- merge_anchors:按 id 去重,已有标题不被回退覆盖
|
||||
do
|
||||
local chapter = { idx = 3, title = "正文", anchors = { { title = "官方第一节", depth = 2, id = "toc_1" } } }
|
||||
Assert.is_true(Content.merge_anchors(chapter, {
|
||||
{ title = "#1", depth = 2, id = "toc_1" },
|
||||
{ title = "#2", depth = 2, id = "toc_2" },
|
||||
}))
|
||||
Assert.len(chapter.anchors, 2)
|
||||
Assert.eq(chapter.anchors[1].title, "官方第一节")
|
||||
Assert.eq(chapter.anchors[2].id, "toc_2")
|
||||
Assert.is_false(Content.merge_anchors(chapter, { { title = "#2", depth = 2, id = "toc_2" } }))
|
||||
end
|
||||
@@ -0,0 +1,476 @@
|
||||
--[[--
|
||||
source.fanqie 门面离线用例。
|
||||
|
||||
@module tests.source.fanqie_spec
|
||||
--]]
|
||||
---@diagnostic disable: undefined-field, missing-fields, redundant-parameter, missing-parameter, inject-field, assign-type-mismatch, param-type-mismatch, cast-type-mismatch, return-type-mismatch, cast-local-type
|
||||
|
||||
local Assert = require("support.assert")
|
||||
|
||||
local queue = {}
|
||||
package.preload["ui/uimanager"] = function()
|
||||
return {
|
||||
nextTick = function(_, f) queue[#queue + 1] = f end,
|
||||
}
|
||||
end
|
||||
local function drain()
|
||||
while #queue > 0 do table.remove(queue, 1)() end
|
||||
end
|
||||
|
||||
package.loaded["source.base"] = nil
|
||||
local progress_wire = { data = {} }
|
||||
local put_args, put_wire = nil, { code = 0 }
|
||||
local shelf_actions, pending_adds = {}, {}
|
||||
local detail_error
|
||||
local detail_writable = true
|
||||
local search_wire = { code = 0, data = { ret_data = {
|
||||
{ book_id = "111", title = "搜到的书", author = "某人", abstract = "简介", category = "玄幻",
|
||||
thumb_url = "https://p6-tt.bytecdn.cn/novel-pic/abc~tplv-shrink:640:0.image" },
|
||||
{ title = "没有书号" },
|
||||
} } }
|
||||
local source_cfg = {}
|
||||
package.preload["utils.settings"] = function()
|
||||
return {
|
||||
getSource = function() return source_cfg end,
|
||||
saveSource = function(_, values)
|
||||
if values and values ~= source_cfg then
|
||||
for k in pairs(source_cfg) do source_cfg[k] = nil end
|
||||
for k, v in pairs(values) do source_cfg[k] = v end
|
||||
end
|
||||
end,
|
||||
}
|
||||
end
|
||||
package.preload["moonsource_fanqie.settings"] = function()
|
||||
return {
|
||||
new = function()
|
||||
return {
|
||||
is_cookie_configured = function() return true end,
|
||||
get = function(_, key, default)
|
||||
local v = source_cfg[key]
|
||||
if v == nil then return default end
|
||||
return v
|
||||
end,
|
||||
set = function(_, key, value) source_cfg[key] = value end,
|
||||
flush = function() end,
|
||||
}
|
||||
end,
|
||||
}
|
||||
end
|
||||
package.preload["moonsource_fanqie.client"] = function()
|
||||
return {
|
||||
new = function()
|
||||
return {
|
||||
fetchBookDetailAsync = function(_self, book_id, cb)
|
||||
require("ui/uimanager"):nextTick(function()
|
||||
if detail_error then cb(nil, detail_error); return end
|
||||
cb({
|
||||
book_id = book_id, book_name = "详情书名",
|
||||
author_name = "详情作者", abstract = "<p>详情简介</p>",
|
||||
thumb_url = "https://p6-novel.byteimg.com/novel-pic/x~tplv-shrink:320:0.image",
|
||||
})
|
||||
end)
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
fetchShelfDetailAsync = function(_, _force, cb)
|
||||
require("ui/uimanager"):nextTick(function()
|
||||
cb({
|
||||
data = {
|
||||
detail_list = {
|
||||
{
|
||||
book_id = "1234567890123456789",
|
||||
book_name = "测试",
|
||||
author_name = "作者",
|
||||
thumb_url = "https://p6-novel.byteimg.com/novel-pic/x~tplv-shrink:320:0.image",
|
||||
abstract = "简介",
|
||||
_group_name = "追更",
|
||||
last_operate_time = 1793017940,
|
||||
add_shelf_time = 1789912130,
|
||||
},
|
||||
{
|
||||
book_id = "9876543210987654321",
|
||||
book_name = "未分组书",
|
||||
author_name = "作者乙",
|
||||
thumb_url = "https://p6-novel.byteimg.com/novel-pic/y~tplv-shrink:320:0.image",
|
||||
abstract = "简介乙",
|
||||
last_operate_time = 1788754903,
|
||||
add_shelf_time = 1788754903000,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
end)
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
fetchChapterDirectoryAsync = function(_, _id, cb)
|
||||
require("ui/uimanager"):nextTick(function()
|
||||
cb({
|
||||
data = {
|
||||
chapterList = {
|
||||
{ itemId = "9876543210987654321", title = "第一章" },
|
||||
},
|
||||
},
|
||||
})
|
||||
end)
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
officialGetContentAsync = function(_, _bid, _iid, cb)
|
||||
require("ui/uimanager"):nextTick(function()
|
||||
cb({ title = "第一章", content = "<p>测试正文</p>" })
|
||||
end)
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
shelfActionAsync = function(_, action, book_id, cb)
|
||||
shelf_actions[#shelf_actions + 1] = action .. ":" .. book_id
|
||||
require("ui/uimanager"):nextTick(function() cb({ code = 0 }) end)
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
searchAsync = function(_, _keyword, cb)
|
||||
require("ui/uimanager"):nextTick(function() cb(search_wire) end)
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
fetchReadProgressAsync = function(_, cb)
|
||||
require("ui/uimanager"):nextTick(function()
|
||||
cb(progress_wire)
|
||||
end)
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
updateReadProgressAsync = function(_, book_id, item_id, index, progress, cb)
|
||||
put_args = { book_id = book_id, item_id = item_id, index = index, progress = progress }
|
||||
require("ui/uimanager"):nextTick(function()
|
||||
cb(put_wire)
|
||||
end)
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
end,
|
||||
}
|
||||
end
|
||||
package.preload["libs/libkoreader-lfs"] = function()
|
||||
return { attributes = function() return nil end }
|
||||
end
|
||||
package.preload["utils.paths"] = function()
|
||||
return {
|
||||
imageDir = function() return "missing" end,
|
||||
coverPath = function() return "missing/cover.jpg" end,
|
||||
ensureLayout = function() end,
|
||||
bookWorkDir = function() return "work" end,
|
||||
ensureBookWork = function() end,
|
||||
}
|
||||
end
|
||||
|
||||
local stored
|
||||
package.preload["book.books_db"] = function()
|
||||
return {
|
||||
reconcile = function(id, books)
|
||||
Assert.eq(id, "ext.fanqie")
|
||||
stored = books
|
||||
return true, 0
|
||||
end,
|
||||
pendingDeleteIds = function() return {} end,
|
||||
pendingShelfAddIds = function() return pending_adds end,
|
||||
markSynced = function() return true end,
|
||||
upsertRemote = function(book)
|
||||
if not detail_writable then return false end
|
||||
stored = { book }
|
||||
return true
|
||||
end,
|
||||
get = function(_source_id, stable_id)
|
||||
return stored and stored[1] and stored[1].stable_id == stable_id and stored[1] or nil
|
||||
end,
|
||||
}
|
||||
end
|
||||
|
||||
local toc
|
||||
local toc_writable = true
|
||||
package.preload["source.toc"] = function()
|
||||
return {
|
||||
read = function() return toc end,
|
||||
index = function(_source_id, _stable_id, uid)
|
||||
for _idx, ch in ipairs(toc or {}) do
|
||||
if ch.uid == uid then return ch.idx end
|
||||
end
|
||||
end,
|
||||
put = function(_, _, v)
|
||||
if not toc_writable then return false end
|
||||
toc = v
|
||||
return true
|
||||
end,
|
||||
}
|
||||
end
|
||||
package.preload["source.chapter"] = function()
|
||||
return {
|
||||
openAsync = function(_, id, book, opts, ops, cb)
|
||||
ops.loadToc(id, function(chapters)
|
||||
Assert.eq(chapters[1].uid, "9876543210987654321")
|
||||
cb("ready.html")
|
||||
end)
|
||||
end,
|
||||
openWithUi = function()
|
||||
error("chapter transition must not open a progress dialog")
|
||||
end,
|
||||
prefetchAsync = function(_, _, _, _, count, ops, cb)
|
||||
Assert.eq(count, 3)
|
||||
Assert.eq(ops.interval_seconds, 6)
|
||||
cb()
|
||||
end,
|
||||
cacheAllAsync = function(source, identity, fetchContent, on_progress, cb, interval)
|
||||
Assert.eq(source.id, "ext.fanqie")
|
||||
Assert.eq(interval, 6)
|
||||
on_progress(1, 1)
|
||||
fetchContent(identity, { idx = 1, uid = "9876543210987654321", title = "第一章" }, function(payload)
|
||||
Assert.eq(payload.html, "<p>测试正文</p>")
|
||||
cb(true, 1, nil, 1, 0)
|
||||
end)
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
end
|
||||
|
||||
package.loaded["moonsource_fanqie.source"] = nil
|
||||
local src = require("moonsource_fanqie.source").new()
|
||||
local settings = src.settings
|
||||
Assert.is_true(src:configured())
|
||||
Assert.eq(src.settings, settings)
|
||||
|
||||
local count = 0
|
||||
src:syncBooksAsync({}, function(r, e)
|
||||
Assert.not_nil(r)
|
||||
Assert.is_nil(e)
|
||||
count = r.pulled
|
||||
end)
|
||||
drain()
|
||||
Assert.eq(count, 2)
|
||||
Assert.eq(stored[1].stable_id, "1234567890123456789")
|
||||
Assert.eq(stored[1].authors, "作者")
|
||||
Assert.eq(stored[1].title, "测试")
|
||||
Assert.eq(stored[1].category, "追更", "默认开:进组书分类用分组名")
|
||||
Assert.is_true(stored[1].category_authoritative, "书架快照声明分类口径")
|
||||
Assert.eq(stored[1].read_at, 1793017940, "最后打开时间进最近阅读")
|
||||
Assert.eq(stored[1].inserted_at, 1789912130, "加入书架时间进最近添加")
|
||||
Assert.matches(stored[1].cover, "p6%-novel%.byteimg%.com")
|
||||
Assert.eq(stored[2].stable_id, "9876543210987654321")
|
||||
Assert.is_nil(stored[2].category, "没进组不写分类")
|
||||
Assert.is_true(stored[2].category_authoritative)
|
||||
Assert.eq(stored[2].read_at, 1788754903)
|
||||
Assert.eq(stored[2].inserted_at, 1788754903, "毫秒加入时间折成秒")
|
||||
|
||||
-- 关掉「使用自定义分组代替分类」后再同步:番茄书架不带题材,分类清空。
|
||||
do
|
||||
source_cfg.category_as_group = false
|
||||
local again = 0
|
||||
src:syncBooksAsync({ force = true }, function(r, e)
|
||||
Assert.not_nil(r)
|
||||
Assert.is_nil(e)
|
||||
again = r.pulled
|
||||
end)
|
||||
drain()
|
||||
Assert.eq(again, 2)
|
||||
Assert.is_nil(stored[1].category, "关:进组也不写分组名")
|
||||
Assert.is_nil(stored[2].category, "关:没进组不写分类")
|
||||
source_cfg.category_as_group = nil
|
||||
end
|
||||
|
||||
local ref = { source_id = "ext.fanqie", stable_id = "1234567890123456789" }
|
||||
src:openBookAsync(ref, { chapter_idx = 1 }, function(path)
|
||||
Assert.eq(path, "ready.html")
|
||||
count = count + 1
|
||||
end)
|
||||
drain()
|
||||
Assert.eq(count, 3)
|
||||
|
||||
local cancelled = src:syncBooksAsync({}, function()
|
||||
error("cancelled callback delivered")
|
||||
end)
|
||||
cancelled.cancel()
|
||||
drain()
|
||||
|
||||
src:prefetchChaptersAsync(ref, {}, 1, 3, function()
|
||||
count = count + 1
|
||||
end)
|
||||
Assert.eq(count, 4)
|
||||
|
||||
-- 整本下载:走公共 cacheAllAsync,正文用番茄接口,间隔与预取一致(风控)
|
||||
do
|
||||
local progressed, ok, cached
|
||||
src:cacheAllChaptersAsync(ref, function(done, total) progressed = { done, total } end,
|
||||
function(success, n) ok, cached = success, n end)
|
||||
drain()
|
||||
Assert.eq(progressed[1], 1)
|
||||
Assert.is_true(ok)
|
||||
Assert.eq(cached, 1)
|
||||
end
|
||||
|
||||
-- 漫画章节归档已就绪:不联网直接回文件;返回的句柄取消后回调不再投递(之前句柄丢了,取消是空操作)
|
||||
do
|
||||
local Chapter = package.loaded["source.chapter"]
|
||||
local real_cache_all = Chapter.cacheAllAsync
|
||||
local fetchContent
|
||||
Chapter.cacheAllAsync = function(_source, _identity, fetcher) fetchContent = fetcher; return { cancel = function() end } end
|
||||
src:cacheAllChaptersAsync(ref, function() end, function() end)
|
||||
Chapter.cacheAllAsync = real_cache_all
|
||||
local Cbz = package.loaded["source.cbz"]
|
||||
local real_ready = Cbz.ready
|
||||
Cbz.ready = function(path) return path == "work/777.cbz" end
|
||||
local chapter = { idx = 1, uid = "777", title = "漫画一" }
|
||||
local got
|
||||
fetchContent(ref, chapter, function(payload) got = payload end)
|
||||
drain()
|
||||
Assert.eq(got.file, "work/777.cbz")
|
||||
got = nil
|
||||
local handle = fetchContent(ref, chapter, function(payload) got = payload end)
|
||||
handle.cancel()
|
||||
drain()
|
||||
Assert.is_nil(got, "取消后不能再回调")
|
||||
Cbz.ready = real_ready
|
||||
end
|
||||
|
||||
do
|
||||
toc = nil
|
||||
toc_writable = false
|
||||
local chapters, err
|
||||
src:loadTocAsync(ref, function(value, reason)
|
||||
chapters, err = value, reason
|
||||
end)
|
||||
drain()
|
||||
Assert.is_nil(chapters)
|
||||
Assert.eq(err, "章节目录保存失败")
|
||||
Assert.is_nil(toc)
|
||||
|
||||
toc_writable = true
|
||||
src:loadTocAsync(ref, function(value) chapters = value end)
|
||||
drain()
|
||||
Assert.eq(chapters[1].uid, "9876543210987654321")
|
||||
Assert.eq(chapters[1].depth, 1)
|
||||
local called = false
|
||||
local cached = src:loadTocAsync(ref, function() called = true end)
|
||||
cached:cancel()
|
||||
drain()
|
||||
Assert.is_false(called)
|
||||
end
|
||||
|
||||
do
|
||||
local result
|
||||
src:syncBooksAsync({ dirty_only = true }, function(r) result = r end)
|
||||
Assert.is_nil(result)
|
||||
drain()
|
||||
Assert.eq(result.pushed, 0)
|
||||
Assert.len(shelf_actions, 0)
|
||||
|
||||
-- 本地新加架的书经网页接口上行
|
||||
pending_adds = { "555" }
|
||||
src:syncBooksAsync({ dirty_only = true }, function(r) result = r end)
|
||||
drain()
|
||||
Assert.eq(result.pushed, 1)
|
||||
Assert.eq(shelf_actions[1], "add:555")
|
||||
pending_adds = {}
|
||||
end
|
||||
|
||||
-- 书城搜索:只留有书号的行,封面归一到手机 CDN
|
||||
do
|
||||
local res
|
||||
src:searchAsync("关键字", function(r) res = r end)
|
||||
drain()
|
||||
Assert.len(res.data, 1)
|
||||
Assert.eq(res.data[1].stable_id, "111")
|
||||
Assert.eq(res.data[1].authors, "某人")
|
||||
Assert.eq(res.data[1].category, "玄幻")
|
||||
Assert.matches(res.data[1].cover, "p6%-novel%.byteimg%.com")
|
||||
end
|
||||
|
||||
-- 封面走基类:查书库 cover(同步书架时写入的手机 CDN 地址)
|
||||
Assert.matches(src:coverRequest(ref).url, "p6%-novel%.byteimg%.com")
|
||||
|
||||
-- 官方网页进度只有章节;read_progress 不是章内比例。
|
||||
toc = {
|
||||
{ idx = 1, uid = "a" }, { idx = 2, uid = "b" }, { idx = 3, uid = "c" }, { idx = 4, uid = "d" },
|
||||
}
|
||||
do
|
||||
progress_wire = { code = 0, data = {
|
||||
{ book_id = "other", item_id = "a" },
|
||||
{ book_id = ref.stable_id, item_id = "c", read_progress = 5000 },
|
||||
} }
|
||||
local pos, err
|
||||
src:getProgressAsync(ref, function(p, e) pos, err = p, e end)
|
||||
drain()
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(pos.chapter_idx, 3)
|
||||
Assert.is_nil(pos.chapter_fraction, "不能把章节 order 当成万分比")
|
||||
Assert.eq(pos.fraction, 0.5)
|
||||
Assert.eq(pos.extra.chapter_uid, "c")
|
||||
|
||||
-- 章节不在目录 / 云端没这本书:空进度,不是错误
|
||||
progress_wire.data[2].item_id = "gone"
|
||||
local meta
|
||||
src:getProgressAsync(ref, function(p, e, m) pos, err, meta = p, e, m end)
|
||||
drain()
|
||||
Assert.is_nil(pos)
|
||||
Assert.is_nil(err)
|
||||
Assert.is_true(meta.empty)
|
||||
progress_wire = { code = 0, data = {} }
|
||||
meta = nil
|
||||
src:getProgressAsync(ref, function(p, e, m) pos, err, meta = p, e, m end)
|
||||
drain()
|
||||
Assert.is_true(meta.empty)
|
||||
end
|
||||
|
||||
-- 进度上传:章节序号 → uid + 0 起 index,不伪造网页不支持的章内位置。
|
||||
do
|
||||
local ok, err
|
||||
src:putProgressAsync(ref, { chapter_idx = 2, chapter_fraction = 1.5 }, function(r, e) ok, err = r, e end)
|
||||
drain()
|
||||
Assert.is_true(ok)
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(put_args.book_id, ref.stable_id)
|
||||
Assert.eq(put_args.item_id, "b")
|
||||
Assert.eq(put_args.index, 1)
|
||||
Assert.eq(put_args.progress, 0)
|
||||
|
||||
-- 没有章节位置:不发请求,直接报错
|
||||
put_args = nil
|
||||
src:putProgressAsync(ref, { fraction = 0.3 }, function(r, e) ok, err = r, e end)
|
||||
drain()
|
||||
Assert.is_nil(ok)
|
||||
Assert.eq(err, "缺少番茄章节位置")
|
||||
Assert.is_nil(put_args)
|
||||
|
||||
-- 业务码非 0:上传失败
|
||||
put_wire = { code = 1001 }
|
||||
src:putProgressAsync(ref, { chapter_idx = 1 }, function(r, e) ok, err = r, e end)
|
||||
drain()
|
||||
Assert.is_nil(ok)
|
||||
Assert.eq(err, "番茄进度上传失败")
|
||||
end
|
||||
|
||||
do
|
||||
local detail, err
|
||||
stored[1].deleted = 1
|
||||
src:getDetailAsync({ source_id = src.id, stable_id = ref.stable_id, book = { intro = "" } },
|
||||
function(book, reason) detail, err = book, reason end)
|
||||
Assert.is_nil(detail, "详情不能同步返回旧的本地行")
|
||||
drain()
|
||||
Assert.is_nil(err)
|
||||
Assert.eq(detail.authors, "详情作者")
|
||||
Assert.eq(detail.intro, "详情简介")
|
||||
Assert.eq(detail.deleted, 1, "补详情不能复活墓碑")
|
||||
|
||||
detail_error = "network failed"
|
||||
src:getDetailAsync(ref, function(book, reason) detail, err = book, reason end)
|
||||
drain()
|
||||
Assert.is_nil(detail)
|
||||
Assert.eq(err, "network failed")
|
||||
Assert.eq(stored[1].intro, "详情简介")
|
||||
detail_error = nil
|
||||
|
||||
detail_writable = false
|
||||
src:getDetailAsync(ref, function(book, reason) detail, err = book, reason end)
|
||||
drain()
|
||||
Assert.is_nil(detail)
|
||||
Assert.eq(err, "书籍信息保存失败")
|
||||
detail_writable = true
|
||||
|
||||
local previous = stored[1]
|
||||
local job = src:getDetailAsync(ref, function() error("cancelled detail callback delivered") end)
|
||||
job:cancel()
|
||||
drain()
|
||||
Assert.eq(stored[1], previous, "关闭详情后到达的回包不能写库")
|
||||
end
|
||||
@@ -0,0 +1,13 @@
|
||||
--[[--
|
||||
番茄正文入口:client 直调 reading API。
|
||||
|
||||
@module tests.moonsource_fanqie.official_spec
|
||||
--]]
|
||||
|
||||
local Assert = require("support.assert")
|
||||
|
||||
package.loaded["moonsource_fanqie.official"] = nil
|
||||
package.loaded["moonsource_fanqie.reading"] = nil
|
||||
local Reading = require("moonsource_fanqie.reading")
|
||||
|
||||
Assert.eq(type(Reading.fetchAsync), "function")
|
||||
@@ -0,0 +1,123 @@
|
||||
--[[--
|
||||
moonsource_fanqie.qrlogin:预热 → 取码 → 轮询 → 跟跳拿 sessionid → 落盘;过期与取消不落盘。
|
||||
@module tests.moonsource_fanqie.qrlogin_spec
|
||||
--]]
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local Stubs = require("support.stubs")
|
||||
require("source.logout").replaceLibrary = function(id, commit)
|
||||
Assert.eq(id, "ext.fanqie")
|
||||
commit()
|
||||
return true
|
||||
end
|
||||
|
||||
package.preload["json"] = function()
|
||||
return { decode = require("support.json_stub").decode, encode = function() return "{}" end }
|
||||
end
|
||||
|
||||
-- 按 URL 前缀排队的罐头响应
|
||||
local script, requested = {}, {}
|
||||
local function respond(prefix, res) script[#script + 1] = { prefix = prefix, res = res } end
|
||||
package.preload["http.request"] = function()
|
||||
return {
|
||||
request = function(opts, cb)
|
||||
requested[#requested + 1] = opts
|
||||
for i, item in ipairs(script) do
|
||||
if opts.url:sub(1, #item.prefix) == item.prefix then
|
||||
table.remove(script, i)
|
||||
require("ui/uimanager"):nextTick(function()
|
||||
if item.res.hook then item.res.hook() end
|
||||
cb(item.res)
|
||||
end)
|
||||
return { cancel = function() end }
|
||||
end
|
||||
end
|
||||
require("ui/uimanager"):nextTick(function() cb(nil, "no script") end)
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
header = function(res, name) return res and res.headers and res.headers[name] end,
|
||||
}
|
||||
end
|
||||
|
||||
local shown = {}
|
||||
local function widget(kind)
|
||||
return function()
|
||||
return { new = function(_, o)
|
||||
o.kind = kind
|
||||
function o:show() shown[#shown + 1] = self end
|
||||
function o:close() self.closed = true; if self.close_callback then self.close_callback() end end
|
||||
return o
|
||||
end }
|
||||
end
|
||||
end
|
||||
package.preload["ui.themes.widgets.qr"] = widget("qr")
|
||||
package.preload["ui.themes.widgets.confirm"] = widget("confirm")
|
||||
package.preload["ui.themes.widgets.toast"] = widget("toast")
|
||||
|
||||
local QRLogin = require("moonsource_fanqie.qrlogin")
|
||||
|
||||
local function newLogin()
|
||||
local saved = {}
|
||||
local settings = { set = function(_, k, v) saved[k] = v end, flush = function() saved.flushed = true end }
|
||||
local plugin = { showBusy = function() end, closeBusy = function() end,
|
||||
onLoginSuccess = function() saved.success = true end }
|
||||
return QRLogin:new(settings, plugin), saved
|
||||
end
|
||||
|
||||
local function find(kind)
|
||||
for i = #shown, 1, -1 do if shown[i].kind == kind then return shown[i] end end
|
||||
end
|
||||
|
||||
local QR_OK = { code = 200, headers = { ["Set-Cookie"] = "ttwid=t; Path=/" },
|
||||
body = '{"message":"success","data":{"token":"tok","qrcode_index_url":"https://qr/x"}}' }
|
||||
|
||||
do -- 成功:确认后 redirect_url 第二跳下发 sessionid(相对 Location 拼回原 host)
|
||||
script, requested, shown = {}, {}, {}
|
||||
respond("https://fanqienovel.com/main/writer/login",
|
||||
{ code = 200, headers = { ["Set-Cookie"] = "passport_csrf_token=c1; Path=/; HttpOnly" } })
|
||||
respond("https://fanqienovel.com/passport/web/get_qrcode/", QR_OK)
|
||||
respond("https://fanqienovel.com/passport/web/check_qrconnect/",
|
||||
{ code = 200, body = '{"data":{"status":"scanned"}}' })
|
||||
respond("https://fanqienovel.com/passport/web/check_qrconnect/",
|
||||
{ code = 200, body = '{"data":{"status":"confirmed","redirect_url":"https://sso.fanqie/a"}}' })
|
||||
respond("https://sso.fanqie/a", { code = 302, headers = { Location = "/b" } })
|
||||
respond("https://sso.fanqie/b", { code = 200, headers = { ["Set-Cookie"] = "sessionid=S; Path=/; Secure" } })
|
||||
local login, saved = newLogin()
|
||||
login:start()
|
||||
Stubs.flush()
|
||||
Assert.eq(find("qr").text, "https://qr/x")
|
||||
Assert.eq(saved.cookies.sessionid, "S")
|
||||
Assert.eq(saved.cookies.passport_csrf_token, "c1")
|
||||
Assert.is_nil(saved.cookies.Path, "Set-Cookie 属性不当 cookie 存")
|
||||
Assert.is_true(saved.success)
|
||||
Assert.is_true(find("qr").closed)
|
||||
-- 轮询带上 csrf 头
|
||||
Assert.eq(requested[3].headers["x-tt-passport-csrf-token"], "c1")
|
||||
Assert.len(script, 0)
|
||||
end
|
||||
|
||||
do -- 过期:弹重试框,不落盘
|
||||
script, requested, shown = {}, {}, {}
|
||||
respond("https://fanqienovel.com/main/writer/login", { code = 200, headers = {} })
|
||||
respond("https://fanqienovel.com/passport/web/get_qrcode/", QR_OK)
|
||||
respond("https://fanqienovel.com/passport/web/check_qrconnect/",
|
||||
{ code = 200, body = '{"data":{"status":"expired"}}' })
|
||||
local login, saved = newLogin()
|
||||
login:start()
|
||||
Stubs.flush()
|
||||
Assert.is_nil(saved.cookies)
|
||||
Assert.eq(find("confirm").ok_text ~= nil, true)
|
||||
end
|
||||
|
||||
do -- 用户关掉二维码(轮询在途时):迟到的 sessionid 不落盘,也不再轮询
|
||||
script, requested, shown = {}, {}, {}
|
||||
respond("https://fanqienovel.com/main/writer/login", { code = 200, headers = {} })
|
||||
respond("https://fanqienovel.com/passport/web/get_qrcode/", QR_OK)
|
||||
respond("https://fanqienovel.com/passport/web/check_qrconnect/",
|
||||
{ code = 200, headers = { ["Set-Cookie"] = "sessionid=LATE" }, hook = function() find("qr"):close() end })
|
||||
local login, saved = newLogin()
|
||||
login:start()
|
||||
Stubs.flush()
|
||||
Assert.is_nil(saved.cookies)
|
||||
Assert.eq(#requested, 3, "关闭后不再轮询")
|
||||
end
|
||||
@@ -0,0 +1,32 @@
|
||||
--[[--
|
||||
番茄网页榜单解析离线用例:内嵌状态(含裸 undefined)、PUA 书名解码、封面。
|
||||
|
||||
@module tests.moonsource_fanqie.rank_spec
|
||||
--]]
|
||||
---@diagnostic disable: undefined-field, missing-fields, redundant-parameter, missing-parameter, inject-field, assign-type-mismatch, param-type-mismatch, cast-type-mismatch, return-type-mismatch, cast-local-type
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local JSONStub = require("support.json_stub")
|
||||
|
||||
package.preload["json"] = function()
|
||||
return { decode = JSONStub.decode, encode = JSONStub.encode }
|
||||
end
|
||||
package.loaded["moonsource_fanqie.rank"] = nil
|
||||
local Rank = require("moonsource_fanqie.rank")
|
||||
|
||||
local html = '<script>(function(){window.__INITIAL_STATE__={"rank":{"book_list":[{"bookId":"7654593151348247614",'
|
||||
.. '"bookName":"\u{E4C2}\u{E3E9}诡异","author":"糕","abstract":"\u{E3E9}简介","pos_category_id":undefined,'
|
||||
.. '"thumbUri":"https://p3-reading-sign.fqnovelpic.com/novel-pic/abc~tplv-resize:225:0.image?x=1"}],'
|
||||
.. '"rankCategoryTypeList":{"male":[{"id":"1141","name":"西方奇幻"}],"female":[]}}};\n})()\n</script><script>x</script>'
|
||||
|
||||
do
|
||||
local rank = Rank.state(html)
|
||||
Assert.eq(rank.rankCategoryTypeList.male[1].name, "西方奇幻")
|
||||
local books = Rank.books(rank, "ext.fanqie")
|
||||
Assert.len(books, 1)
|
||||
Assert.eq(books[1].stable_id, "7654593151348247614")
|
||||
Assert.matches(books[1].title, "在诡异$")
|
||||
Assert.eq(books[1].intro, "在简介")
|
||||
Assert.matches(books[1].cover, "novel%-pic/abc")
|
||||
Assert.is_nil(Rank.state("<html>人机验证</html>"))
|
||||
end
|
||||
@@ -0,0 +1,58 @@
|
||||
--[[--
|
||||
番茄 reading crypto 向量(离线)。
|
||||
|
||||
@module tests.moonsource_fanqie.reading_crypto_spec
|
||||
--]]
|
||||
|
||||
local Assert = require("support.assert")
|
||||
|
||||
-- 设备上 z_stream / inflate 可能已被其他模块以不同签名声明,解压不能因此失效。
|
||||
pcall(require("ffi").cdef, [[
|
||||
typedef struct z_stream_s { void *p; } z_stream;
|
||||
int inflate(z_stream *, int);
|
||||
]])
|
||||
|
||||
package.loaded["moonsource_fanqie.reading.crypto"] = nil
|
||||
package.loaded["crypto.aes"] = nil
|
||||
|
||||
local Aes = require("crypto.aes")
|
||||
local Crypto = require("moonsource_fanqie.reading.crypto")
|
||||
|
||||
local key = Aes.from_hex(Crypto.HARDCODED_KEY_HEX)
|
||||
local iv = "1234567890123456"
|
||||
local pt = Aes.from_hex("2b5dbca76c4902000000000000000000")
|
||||
local ct = Aes.cbc_encrypt(pt, key, iv, true)
|
||||
Assert.eq(Aes.to_hex(ct), "64fd9775e48333728345235490bca65492c8c2ccd7832564732fb54839593fe2")
|
||||
|
||||
local content = Crypto.build_register_content(643680972856619, 0, "1234567890123456")
|
||||
Assert.eq(content, "MTIzNDU2Nzg5MDEyMzQ1NmT9l3XkgzNyg0UjVJC8plSSyMLM14MlZHMvtUg5WT/i")
|
||||
|
||||
-- 19 位 device_id 串超过 2^53:小端 8 字节必须逐位精确
|
||||
do
|
||||
local b64 = Crypto.build_register_content("7342475219212192830", 0, "1234567890123456")
|
||||
local raw = require("utils.text").base64Decode(b64)
|
||||
local plain_id = Aes.cbc_decrypt(raw:sub(17), key, raw:sub(1, 16), true)
|
||||
Assert.eq(Aes.to_hex(plain_id:sub(1, 8)), "3e4c404d4fb6e565")
|
||||
Assert.eq(Crypto.build_register_content("643680972856619", 0, "1234567890123456"), content)
|
||||
end
|
||||
|
||||
-- decrypt_server_key roundtrip
|
||||
local session = Aes.from_hex("00112233445566778899aabbccddeeff")
|
||||
local iv2 = "0123456789abcdef"
|
||||
local blob = require("utils.text").base64Encode(iv2 .. Aes.cbc_encrypt(session, key, iv2, true))
|
||||
Assert.eq(Crypto.decrypt_server_key(blob), "00112233445566778899AABBCCDDEEFF")
|
||||
|
||||
local q = Crypto.build_batch_full_query({
|
||||
install_id = "1", device_id = "2", version_code = "73733", version_name = "7.3.7.33",
|
||||
}, "7342475219212192830", { "7463695105224884760" }, 1000)
|
||||
local qs = Crypto.encode_query(q)
|
||||
Assert.matches(qs, "item_ids=7463695105224884760")
|
||||
Assert.is_true(not qs:find("%%2C", 1, true))
|
||||
Assert.matches(qs, "book_id=7342475219212192830")
|
||||
|
||||
local plain = string.rep("番茄正文", 20)
|
||||
Assert.eq(Crypto.maybe_decompress(Aes.from_hex(
|
||||
"1f8b08000000000002ff7b3e75d58b9e96676b173f9bd6fe7c04b00161f60cc9f0000000"), 1), plain)
|
||||
Assert.eq(Crypto.maybe_decompress(Aes.from_hex(
|
||||
"789c7b3e75d58b9e96676b173f9bd6fe7c04b001a6cea6cd"), 1), plain)
|
||||
Assert.eq(Crypto.maybe_decompress("plain", 0), "plain")
|
||||
@@ -0,0 +1,213 @@
|
||||
--[[--
|
||||
番茄设备身份:本地画像唯一 + device_register 落盘(HTTP 打桩)。
|
||||
|
||||
@module tests.moonsource_fanqie.reading_device_spec
|
||||
--]]
|
||||
---@diagnostic disable: undefined-field, missing-fields, redundant-parameter, missing-parameter, inject-field, assign-type-mismatch, param-type-mismatch, cast-type-mismatch, return-type-mismatch, cast-local-type
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local Stubs = require("support.stubs")
|
||||
|
||||
local state = {
|
||||
cfg = {},
|
||||
saved = nil,
|
||||
request_impl = nil,
|
||||
}
|
||||
|
||||
package.preload["utils.settings"] = function()
|
||||
return {
|
||||
getSource = function() return state.cfg end,
|
||||
saveSource = function(_, value)
|
||||
state.saved = value
|
||||
state.cfg = value
|
||||
end,
|
||||
}
|
||||
end
|
||||
|
||||
package.preload["http.request"] = function()
|
||||
return {
|
||||
ok = function(code)
|
||||
local n = tonumber(code)
|
||||
return n ~= nil and n >= 200 and n < 300
|
||||
end,
|
||||
header = function() return nil end,
|
||||
request = function(opts, cb)
|
||||
return state.request_impl(opts, cb)
|
||||
end,
|
||||
}
|
||||
end
|
||||
|
||||
package.preload["json"] = function()
|
||||
return {
|
||||
encode = function(t)
|
||||
-- 足够 register body 冒烟:只要发出去
|
||||
Assert.eq(type(t), "table")
|
||||
Assert.eq(t.magic_tag, "ss_app_log")
|
||||
return '{"magic_tag":"ss_app_log"}'
|
||||
end,
|
||||
decode = function(s)
|
||||
if type(s) ~= "string" or s == "" then error("empty") end
|
||||
-- 极简:只解析我们罐装的响应
|
||||
local did = s:match('"device_id_str"%s*:%s*"(%d+)"')
|
||||
or s:match('"device_id"%s*:%s*(%d+)')
|
||||
local iid = s:match('"install_id_str"%s*:%s*"(%d+)"')
|
||||
or s:match('"install_id"%s*:%s*(%d+)')
|
||||
if not did or not iid then error("bad json") end
|
||||
return {
|
||||
device_id = tonumber(did),
|
||||
install_id = tonumber(iid),
|
||||
device_id_str = did,
|
||||
install_id_str = iid,
|
||||
new_user = 1,
|
||||
}
|
||||
end,
|
||||
}
|
||||
end
|
||||
|
||||
for _, name in ipairs({
|
||||
"utils.settings", "http.request", "json",
|
||||
"moonsource_fanqie.reading.device", "moonsource_fanqie.settings",
|
||||
}) do
|
||||
package.loaded[name] = nil
|
||||
end
|
||||
|
||||
local Device = require("moonsource_fanqie.reading.device")
|
||||
local Settings = require("moonsource_fanqie.settings")
|
||||
|
||||
-- normalize:缺 id 一律拒绝(禁止半残共享身份)
|
||||
Assert.is_nil(Device.normalize(nil))
|
||||
Assert.is_nil(Device.normalize({}))
|
||||
Assert.is_nil(Device.normalize({ device_id = "1" }))
|
||||
Assert.is_nil(Device.normalize({ install_id = "1" }))
|
||||
|
||||
-- 本地画像每次唯一
|
||||
local a = Device.newLocalProfile()
|
||||
local b = Device.newLocalProfile()
|
||||
Assert.is_true(a.cdid ~= b.cdid)
|
||||
Assert.is_true(a.openudid ~= b.openudid)
|
||||
Assert.eq(#a.openudid, 16)
|
||||
Assert.matches(a.cdid, "^%x%x%x%x%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%x%x%x%x%x%x%x%x$")
|
||||
Assert.is_nil(a.device_id)
|
||||
Assert.is_nil(a.install_id)
|
||||
|
||||
local ok = Device.normalize({
|
||||
device_id = "123",
|
||||
install_id = "456",
|
||||
device_profile = { device_type = "Pixel", cdid = a.cdid, openudid = a.openudid },
|
||||
})
|
||||
Assert.eq(ok.device_id, "123")
|
||||
Assert.eq(ok.install_id, "456")
|
||||
Assert.eq(ok.device_type, "Pixel")
|
||||
Assert.eq(ok.cdid, a.cdid)
|
||||
Assert.is_nil(Device.DEFAULT)
|
||||
|
||||
-- registerAsync:打桩 HTTP,校验 URL / 落盘
|
||||
state.cfg = {}
|
||||
state.saved = nil
|
||||
local settings = Settings:new()
|
||||
local seen_url
|
||||
state.request_impl = function(opts, cb)
|
||||
seen_url = opts.url
|
||||
Assert.eq(opts.method, "POST")
|
||||
Assert.matches(opts.url, "log%.snssdk%.com/service/2/device_register/")
|
||||
Assert.matches(opts.url, "aid=1967")
|
||||
Assert.matches(opts.url, "app_name=novelapp")
|
||||
Assert.eq(opts.headers["Content-Type"], "application/json; charset=utf-8")
|
||||
require("ui/uimanager"):nextTick(function()
|
||||
cb({
|
||||
code = 200,
|
||||
body = '{"device_id_str":"516130687997515","install_id_str":"516130688001611","new_user":1}',
|
||||
})
|
||||
end)
|
||||
return { cancel = function() end }
|
||||
end
|
||||
|
||||
local got, reg_err
|
||||
Device.registerAsync(settings, function(device, err)
|
||||
got, reg_err = device, err
|
||||
end)
|
||||
Stubs.flush()
|
||||
Assert.is_nil(reg_err)
|
||||
Assert.eq(got.device_id, "516130687997515")
|
||||
Assert.eq(got.install_id, "516130688001611")
|
||||
Assert.is_true(type(got.cdid) == "string" and got.cdid ~= "")
|
||||
Assert.matches(seen_url, "openudid=")
|
||||
Assert.eq(state.saved.reading_device.device_id, "516130687997515")
|
||||
Assert.eq(state.saved.reading_device.install_id, "516130688001611")
|
||||
|
||||
-- ensureAsync:已有身份不再请求网络
|
||||
local net_hits = 0
|
||||
state.request_impl = function(_, cb)
|
||||
net_hits = net_hits + 1
|
||||
cb(nil, "should not call")
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local cached, cache_err
|
||||
Device.ensureAsync(settings, function(device, err)
|
||||
cached, cache_err = device, err
|
||||
end)
|
||||
Stubs.flush()
|
||||
Assert.is_nil(cache_err)
|
||||
Assert.eq(cached.device_id, "516130687997515")
|
||||
Assert.eq(net_hits, 0)
|
||||
|
||||
-- ensureAsync:无身份则注册
|
||||
state.cfg = {}
|
||||
state.saved = nil
|
||||
settings = Settings:new()
|
||||
state.request_impl = function(_, cb)
|
||||
require("ui/uimanager"):nextTick(function()
|
||||
cb({
|
||||
code = 200,
|
||||
body = '{"device_id":999001,"install_id":999002,"new_user":1}',
|
||||
})
|
||||
end)
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local ensured
|
||||
Device.ensureAsync(settings, function(device, err)
|
||||
ensured, cache_err = device, err
|
||||
end)
|
||||
Stubs.flush()
|
||||
Assert.is_nil(cache_err)
|
||||
Assert.eq(ensured.device_id, "999001")
|
||||
Assert.eq(ensured.install_id, "999002")
|
||||
|
||||
-- 传输错误:res 表还在,但 err 才是超时原因,不能报成 HTTP nil
|
||||
state.cfg = {}
|
||||
state.saved = nil
|
||||
settings = Settings:new()
|
||||
state.request_impl = function(_, cb)
|
||||
require("ui/uimanager"):nextTick(function()
|
||||
cb({ error = { code = -6, message = "Request timed out after 20 secs" } },
|
||||
"Request timed out after 20 secs")
|
||||
end)
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local timed
|
||||
Device.registerAsync(settings, function(device, err)
|
||||
timed = err
|
||||
Assert.is_nil(device)
|
||||
end)
|
||||
Stubs.flush()
|
||||
Assert.eq(timed, "Request timed out after 20 secs")
|
||||
Assert.is_nil(state.saved)
|
||||
|
||||
-- Kindle 出网拦 log.snssdk.com:英文原句换成能看懂的中文
|
||||
state.cfg = {}
|
||||
state.saved = nil
|
||||
settings = Settings:new()
|
||||
state.request_impl = function(_, cb)
|
||||
require("ui/uimanager"):nextTick(function()
|
||||
cb(nil, "Could not connect: connection refused")
|
||||
end)
|
||||
return { cancel = function() end }
|
||||
end
|
||||
local blocked
|
||||
Device.registerAsync(settings, function(device, err)
|
||||
blocked = err
|
||||
Assert.is_nil(device)
|
||||
end)
|
||||
Stubs.flush()
|
||||
Assert.eq(blocked, "番茄正文需要注册设备,当前网络拦了 log.snssdk.com")
|
||||
Assert.is_nil(state.saved)
|
||||
@@ -0,0 +1,256 @@
|
||||
--[[--
|
||||
番茄 reading.fetchAsync:ensure 设备 → registerkey → batch_full(全打桩)。
|
||||
|
||||
@module tests.moonsource_fanqie.reading_fetch_spec
|
||||
--]]
|
||||
---@diagnostic disable: undefined-field, missing-fields, redundant-parameter, missing-parameter, inject-field, assign-type-mismatch, param-type-mismatch, cast-type-mismatch, return-type-mismatch, cast-local-type
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local Stubs = require("support.stubs")
|
||||
|
||||
local state = {
|
||||
cfg = {
|
||||
reading_device = {
|
||||
device_id = "516130687997515",
|
||||
install_id = "516130688001611",
|
||||
device_profile = {
|
||||
channel = "43536163a",
|
||||
version_code = "73733",
|
||||
version_name = "7.3.7.33",
|
||||
device_type = "P30",
|
||||
device_brand = "HUAWEI",
|
||||
language = "zh",
|
||||
os_api = "31",
|
||||
os_version = "12",
|
||||
resolution = "1280*720",
|
||||
dpi = "240",
|
||||
host_abi = "arm64-v8a",
|
||||
cdid = "8550abb6-a07b-4b77-9edd-6710f414828b",
|
||||
openudid = "733b78130c0d0098",
|
||||
rom_version = "S643.217451.03386707",
|
||||
},
|
||||
},
|
||||
},
|
||||
urls = {},
|
||||
}
|
||||
|
||||
package.preload["utils.settings"] = function()
|
||||
return {
|
||||
getSource = function() return state.cfg end,
|
||||
saveSource = function(_, value) state.cfg = value end,
|
||||
}
|
||||
end
|
||||
|
||||
-- registerkey / batch_full 都要编解码 JSON
|
||||
package.preload["json"] = function()
|
||||
local J = require("support.json_stub")
|
||||
return { encode = J.encode, decode = J.decode }
|
||||
end
|
||||
package.loaded["json"] = nil
|
||||
|
||||
-- 用真实 crypto 解一把已知向量,给 fetch 罐装响应
|
||||
package.loaded["crypto.aes"] = nil
|
||||
package.loaded["moonsource_fanqie.reading.crypto"] = nil
|
||||
local Aes = require("crypto.aes")
|
||||
local Crypto = require("moonsource_fanqie.reading.crypto")
|
||||
local Text = require("utils.text")
|
||||
|
||||
-- 构造假 v1_key 与假章节密文
|
||||
local v1_bin = Aes.from_hex("00112233445566778899aabbccddeeff")
|
||||
local v1_hex = Aes.to_hex(v1_bin):upper()
|
||||
local iv = "0123456789abcdef"
|
||||
local plain = "<?xml version=\"1.0\"?><html><body>第776章 养女如母 测试正文内容足够长</body></html>"
|
||||
-- compress_status=0:不解压
|
||||
local enc = Aes.cbc_encrypt(plain, v1_bin, iv, true)
|
||||
local content_b64 = Text.base64Encode(iv .. enc)
|
||||
local key_blob = Text.base64Encode(iv .. Aes.cbc_encrypt(v1_bin, Aes.from_hex(Crypto.HARDCODED_KEY_HEX), iv, true))
|
||||
|
||||
package.preload["http.request"] = function()
|
||||
return {
|
||||
ok = function(code)
|
||||
local n = tonumber(code)
|
||||
return n ~= nil and n >= 200 and n < 300
|
||||
end,
|
||||
header = function() return nil end,
|
||||
request = function(opts, cb)
|
||||
state.urls[#state.urls + 1] = opts.url
|
||||
require("ui/uimanager"):nextTick(function()
|
||||
if opts.url:find("/reading/crypt/registerkey", 1, true) then
|
||||
Assert.eq(opts.method, "POST")
|
||||
Assert.is_true(opts.headers["X-Argus"] ~= nil)
|
||||
Assert.is_true(opts.headers["X-Ladon"] ~= nil)
|
||||
cb({
|
||||
code = 200,
|
||||
body = '{"code":0,"data":{"key":"' .. key_blob .. '","keyver":1},"message":"ok"}',
|
||||
})
|
||||
return
|
||||
end
|
||||
if opts.url:find("/reading/reader/batch_full", 1, true) then
|
||||
Assert.eq(opts.method, "GET")
|
||||
Assert.matches(opts.url, "item_ids=7463695105224884760")
|
||||
Assert.matches(opts.url, "book_id=7342475219212192830")
|
||||
Assert.is_true(not opts.url:find("%%2C", 1, true))
|
||||
cb({
|
||||
code = 200,
|
||||
body = '{"code":0,"data":{"7463695105224884760":{'
|
||||
.. '"title":"第776章 养女如母",'
|
||||
.. '"crypt_status":0,"compress_status":0,'
|
||||
.. '"content":"' .. content_b64 .. '"}}}',
|
||||
})
|
||||
return
|
||||
end
|
||||
cb(nil, "unexpected url " .. tostring(opts.url))
|
||||
end)
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
end
|
||||
|
||||
for _, name in ipairs({
|
||||
"http.request", "utils.settings", "json",
|
||||
"moonsource_fanqie.reading",
|
||||
"moonsource_fanqie.reading.device", "moonsource_fanqie.settings",
|
||||
"moonsource_fanqie.reading.sign",
|
||||
}) do
|
||||
package.loaded[name] = nil
|
||||
end
|
||||
|
||||
local Reading = require("moonsource_fanqie.reading")
|
||||
local Settings = require("moonsource_fanqie.settings")
|
||||
|
||||
local row, fetch_err
|
||||
Reading.fetchAsync(Settings:new(), "7342475219212192830", "7463695105224884760", function(data, err)
|
||||
row, fetch_err = data, err
|
||||
end)
|
||||
Stubs.flush()
|
||||
|
||||
Assert.is_nil(fetch_err)
|
||||
Assert.eq(row.title, "第776章 养女如母")
|
||||
Assert.eq(row.source, "reading_batch_full")
|
||||
Assert.matches(row.content, "养女如母")
|
||||
Assert.eq(#state.urls, 2)
|
||||
Assert.matches(state.urls[1], "registerkey")
|
||||
Assert.matches(state.urls[2], "batch_full")
|
||||
|
||||
-- 无设备身份时先走 device_register
|
||||
state.cfg = {}
|
||||
state.urls = {}
|
||||
package.loaded["moonsource_fanqie.reading"] = nil
|
||||
package.loaded["moonsource_fanqie.reading.device"] = nil
|
||||
package.loaded["moonsource_fanqie.settings"] = nil
|
||||
|
||||
local register_hits = 0
|
||||
package.preload["http.request"] = function()
|
||||
return {
|
||||
ok = function(code)
|
||||
local n = tonumber(code)
|
||||
return n ~= nil and n >= 200 and n < 300
|
||||
end,
|
||||
header = function() return nil end,
|
||||
request = function(opts, cb)
|
||||
state.urls[#state.urls + 1] = opts.url
|
||||
require("ui/uimanager"):nextTick(function()
|
||||
if opts.url:find("device_register", 1, true) then
|
||||
register_hits = register_hits + 1
|
||||
cb({
|
||||
code = 200,
|
||||
body = '{"device_id_str":"111","install_id_str":"222","new_user":1}',
|
||||
})
|
||||
return
|
||||
end
|
||||
if opts.url:find("registerkey", 1, true) then
|
||||
cb({
|
||||
code = 200,
|
||||
body = '{"code":0,"data":{"key":"' .. key_blob .. '","keyver":1}}',
|
||||
})
|
||||
return
|
||||
end
|
||||
if opts.url:find("batch_full", 1, true) then
|
||||
cb({
|
||||
code = 200,
|
||||
body = '{"code":0,"data":{"1":{"title":"T","crypt_status":0,"compress_status":0,"content":"'
|
||||
.. content_b64 .. '"}}}',
|
||||
})
|
||||
return
|
||||
end
|
||||
cb(nil, "bad url")
|
||||
end)
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
end
|
||||
package.loaded["http.request"] = nil
|
||||
|
||||
Reading = require("moonsource_fanqie.reading")
|
||||
Settings = require("moonsource_fanqie.settings")
|
||||
row, fetch_err = nil, nil
|
||||
Reading.fetchAsync(Settings:new(), "99", "1", function(data, err)
|
||||
row, fetch_err = data, err
|
||||
end)
|
||||
Stubs.flush()
|
||||
Assert.is_nil(fetch_err)
|
||||
Assert.eq(register_hits, 1)
|
||||
Assert.eq(row.title, "T")
|
||||
Assert.eq(state.cfg.reading_device.device_id, "111")
|
||||
|
||||
-- registerkey 超时:res 非 nil,err 必须原样回到打开流程
|
||||
state.urls = {}
|
||||
package.preload["http.request"] = function()
|
||||
return {
|
||||
ok = function(code)
|
||||
local n = tonumber(code)
|
||||
return n ~= nil and n >= 200 and n < 300
|
||||
end,
|
||||
header = function() return nil end,
|
||||
request = function(opts, cb)
|
||||
state.urls[#state.urls + 1] = opts.url
|
||||
require("ui/uimanager"):nextTick(function()
|
||||
cb({ error = { code = -6 } }, "Request timed out after 20 secs")
|
||||
end)
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
end
|
||||
package.loaded["http.request"] = nil
|
||||
package.loaded["moonsource_fanqie.reading"] = nil
|
||||
package.loaded["moonsource_fanqie.reading.device"] = nil
|
||||
package.loaded["moonsource_fanqie.settings"] = nil
|
||||
Reading = require("moonsource_fanqie.reading")
|
||||
Settings = require("moonsource_fanqie.settings")
|
||||
row, fetch_err = nil, nil
|
||||
Reading.fetchAsync(Settings:new(), "99", "1", function(data, err)
|
||||
row, fetch_err = data, err
|
||||
end)
|
||||
Stubs.flush()
|
||||
Assert.is_nil(row)
|
||||
Assert.eq(fetch_err, "Request timed out after 20 secs")
|
||||
Assert.eq(#state.urls, 1)
|
||||
Assert.matches(state.urls[1], "registerkey")
|
||||
|
||||
-- 设备已缓存时取消:句柄必须落到在飞的 registerkey 上,而不是 ensureAsync 的空句柄
|
||||
local held_cancels = 0
|
||||
package.preload["http.request"] = function()
|
||||
return {
|
||||
ok = function() return true end,
|
||||
header = function() return nil end,
|
||||
request = function()
|
||||
return { cancel = function() held_cancels = held_cancels + 1 end }
|
||||
end,
|
||||
}
|
||||
end
|
||||
package.loaded["http.request"] = nil
|
||||
package.loaded["moonsource_fanqie.reading"] = nil
|
||||
Reading = require("moonsource_fanqie.reading")
|
||||
local delivered = false
|
||||
local handle = Reading.fetchAsync(Settings:new(), "99", "1", function() delivered = true end)
|
||||
Stubs.flush()
|
||||
handle.cancel()
|
||||
Assert.eq(held_cancels, 1)
|
||||
Assert.is_false(delivered)
|
||||
|
||||
-- 非法 ID:下一帧回错误,不在 fetchAsync 返回前同步回调
|
||||
local id_err
|
||||
Reading.fetchAsync(Settings:new(), "abc", "1", function(_data, err) id_err = err end)
|
||||
Assert.is_nil(id_err)
|
||||
Stubs.flush()
|
||||
Assert.eq(id_err, "章节 ID 无效")
|
||||
@@ -0,0 +1,31 @@
|
||||
--[[--
|
||||
番茄 reading 签名向量(离线)。
|
||||
|
||||
@module tests.moonsource_fanqie.reading_sign_spec
|
||||
--]]
|
||||
|
||||
local Assert = require("support.assert")
|
||||
|
||||
package.loaded["moonsource_fanqie.reading.sign"] = nil
|
||||
package.loaded["crypto.aes"] = nil
|
||||
package.loaded["crypto.sm3"] = nil
|
||||
|
||||
local Aes = require("crypto.aes")
|
||||
local Sm3 = require("crypto.sm3")
|
||||
local Sign = require("moonsource_fanqie.reading.sign")
|
||||
|
||||
Assert.eq(Sm3.hex(""), "1ab21d8355cfa17f8e61194831e81a8f22bec8c728fefb747ed035eb5082aa2b")
|
||||
Assert.eq(Sm3.hex("abc"), "66c7f0f462eeedd9d1f2d46bdc10e4e24167c4875cf2f7a2297da02b8f4ba8e0")
|
||||
Assert.eq(Aes.to_hex(Sign.derive_inner_key()):sub(1, 32), "fc78e0a9657a0c748ce51559903ccf03")
|
||||
|
||||
local ladon = Sign.encrypt_ladon(1789957197, Aes.from_hex("1b98ce68"))
|
||||
Assert.eq(ladon, "G5jOaLRVvJuv4+NwKK5O28l5Otk8CtR/oS5UUASQ16HNqKIl")
|
||||
|
||||
local helios = Sign.encrypt_ladon(1789957197, Aes.from_hex("9af455f3"))
|
||||
Assert.eq(helios, "mvRV81hWfK8mji4oDqkBUaKNIcydz7kADrxZKHO7vEnxeFQ/")
|
||||
|
||||
local argus = Sign.encrypt_argus(
|
||||
"aid=1967&device_id=1", 1789949275, "3405654380789289", { rand_val = 1 })
|
||||
local raw = require("utils.text").base64Decode(argus)
|
||||
Assert.eq(raw:sub(1, 2), string.char(0xf2, 0x81))
|
||||
Assert.eq(#raw, 194)
|
||||
@@ -0,0 +1,227 @@
|
||||
--[[--
|
||||
番茄段评:统计 → 热点、评论页 → 展示项(游标翻页)、段落定位到章节 HTML。
|
||||
|
||||
@module tests.moonsource_fanqie.reviews_spec
|
||||
--]]
|
||||
---@diagnostic disable: undefined-field, missing-fields, redundant-parameter, missing-parameter, inject-field, assign-type-mismatch, param-type-mismatch, cast-type-mismatch, return-type-mismatch, cast-local-type
|
||||
|
||||
local Assert = require("support.assert")
|
||||
|
||||
package.preload["json"] = function()
|
||||
local J = require("support.json_stub")
|
||||
return { encode = J.encode, decode = J.decode }
|
||||
end
|
||||
package.loaded["json"] = nil
|
||||
|
||||
local calls, reply, reply_err = {}, nil, nil
|
||||
package.preload["moonsource_fanqie.reading.device"] = function()
|
||||
return { ensureAsync = function(_, cb) cb({ device_id = "1", install_id = "2" }) return { cancel = function() end } end }
|
||||
end
|
||||
package.preload["moonsource_fanqie.reading"] = function()
|
||||
return {
|
||||
signedAsync = function(_device, name, path, build_query, build_body, cb)
|
||||
calls[#calls + 1] = { name = name, path = path, query = build_query({}, 1), body = build_body and build_body() }
|
||||
cb(reply, reply_err)
|
||||
return { cancel = function() end }
|
||||
end,
|
||||
}
|
||||
end
|
||||
package.preload["moonsource_fanqie.reading.crypto"] = function()
|
||||
return { build_common_query = function() return { aid = "1967" } end }
|
||||
end
|
||||
package.loaded["moonsource_fanqie.reviews"] = nil
|
||||
local Reviews = require("moonsource_fanqie.reviews")
|
||||
|
||||
-- 统计:只留评论数 > 0 的段,按段序排
|
||||
do
|
||||
reply = { data = { data = { ["12"] = { count = 5 }, ["3"] = { count = 2 }, ["7"] = { count = 0 } } } }
|
||||
local hotspots
|
||||
Reviews.hotspotsAsync({}, "900", function(list) hotspots = list end)
|
||||
Assert.eq(calls[1].path, "/novel/commentapi/idea/list/900/v1/")
|
||||
Assert.eq(calls[1].query.compliance_status, "0")
|
||||
Assert.is_nil(calls[1].body)
|
||||
Assert.len(hotspots, 2)
|
||||
Assert.eq(hotspots[1].range, "3")
|
||||
Assert.eq(hotspots[2].total, 5)
|
||||
|
||||
reply, reply_err = nil, "comment_stats 空响应"
|
||||
local err
|
||||
Reviews.hotspotsAsync({}, "900", function(list, e) Assert.is_nil(list) err = e end)
|
||||
Assert.eq(err, "comment_stats 空响应")
|
||||
reply_err = nil
|
||||
|
||||
for _idx, data in ipairs({ {}, { data = { ["1"] = {} } } }) do
|
||||
reply = { data = data }
|
||||
Reviews.hotspotsAsync({}, "900", function(list, e) Assert.is_nil(list); err = e end)
|
||||
Assert.matches(err, "统计", "坏响应不能覆盖缓存成空热点")
|
||||
end
|
||||
end
|
||||
|
||||
-- 评论页:POST body 带段序与游标;毫秒时间归一成秒;has_more 且游标前进才算还有
|
||||
do
|
||||
reply = { data = {
|
||||
data_list = { { comment = {
|
||||
comment_id = "c1",
|
||||
common = { user_info = { base_info = { user_name = "书友" } }, content = { text = "好看", image_data_list = { image_data = {
|
||||
{ web_url = "https://p3-novel.byteimg.com/tos-cn-i-abc/xyz~tplv-q:300:0.awebp?sig=1" },
|
||||
{ web_url = "https://p3-novel.byteimg.com/tos-cn-i-abc/up123~tplv-q-jpeg.heic?sig=2" },
|
||||
} } },
|
||||
create_timestamp = 1700000000000 },
|
||||
stat = { digg_count = 9, reply_count = 4 },
|
||||
} } },
|
||||
common_list_info = { cursor = "20", has_more = true, total = 33 },
|
||||
} }
|
||||
local page
|
||||
Reviews.pageAsync({}, "111", "900", 12, 0, function(p) page = p end)
|
||||
local call = calls[#calls]
|
||||
Assert.eq(call.path, "/novel/commentapi/comment/list/900/v1/")
|
||||
Assert.matches(call.body, '"para_index":12')
|
||||
Assert.matches(call.body, '"cursor":""')
|
||||
Assert.eq(page.items[1].author, "书友")
|
||||
Assert.eq(page.items[1].content, "好看")
|
||||
Assert.eq(page.items[1].likes, 9)
|
||||
Assert.eq(page.items[1].replies, 4)
|
||||
Assert.len(page.items[1].images, 2)
|
||||
Assert.matches(page.items[1].images[1].url, "awebp%?sig=1")
|
||||
Assert.eq(page.items[1].images[2].url,
|
||||
"https://p3-novel.byteimg.com/tos-cn-i-abc/up123~tplv-1yzifmftcy-expand:800:0:0.webp")
|
||||
Assert.eq(page.items[1].time, 1700000000)
|
||||
Assert.eq(page.total, 33)
|
||||
Assert.eq(page.max_idx, 20)
|
||||
Assert.is_true(page.more)
|
||||
|
||||
Reviews.pageAsync({}, "111", "900", 12, 20, function(p) page = p end)
|
||||
Assert.matches(calls[#calls].body, '"cursor":"20"')
|
||||
|
||||
-- 游标没前进:停,免得无限翻
|
||||
Reviews.pageAsync({}, "111", "900", 12, 20, function(p) page = p end)
|
||||
Assert.is_false(page.more)
|
||||
|
||||
-- code 为 0 却没有 data_list:风控,报错而不是「0 条」
|
||||
reply = { data = { common_list_info = {} } }
|
||||
local err
|
||||
Reviews.pageAsync({}, "111", "900", 12, 0, function(p, e) Assert.is_nil(p) err = e end)
|
||||
Assert.matches(err, "data_list")
|
||||
|
||||
reply = { data = { data_list = {}, common_list_info = { total = 3 } } }
|
||||
Reviews.pageAsync({}, "111", "900", 12, 0, function(p, e) Assert.is_nil(p); err = e end)
|
||||
Assert.matches(err, "为空", "风控空成功不删除已有热点")
|
||||
reply.data.common_list_info.total = 0
|
||||
Reviews.pageAsync({}, "111", "900", 12, 0, function(p) page = p end)
|
||||
Assert.len(page.items, 0, "真正空列表正常返回")
|
||||
Assert.is_false(page.more)
|
||||
|
||||
reply = { data = { data_list = { { comment = { common = {
|
||||
content = { text = "甲[笑]乙[哭][笑][因果]😀" },
|
||||
} } } }, common_list_info = { total = 1 } } }
|
||||
Reviews.pageAsync({}, "111", "900", 12, 0, function(p) page = p end)
|
||||
Assert.eq(page.items[1].content, "甲[笑]乙[哭][笑][因果]😀", "原文供引用、复制与缓存,不做破坏性替换")
|
||||
Assert.matches(page.items[1].inline_images["[笑]"].url, "/1f604%.png$")
|
||||
Assert.matches(page.items[1].inline_images["[哭]"].url, "/1f622%.png$")
|
||||
Assert.is_nil(page.items[1].inline_images["[因果]"], "书中术语不是表情")
|
||||
end
|
||||
|
||||
-- 回复:comment_source 必须是 5;楼中楼记被回复者;空列表且 total>0 不当成功
|
||||
do
|
||||
reply = { data = {
|
||||
reply_list = { {
|
||||
reply_id = "rp1",
|
||||
reply_to_user_info = { base_info = { user_name = "楼主" } },
|
||||
Common = { user_info = { base_info = { user_name = "路人" } },
|
||||
content = { text = "确实[吃瓜]" }, create_timestamp = 1700000000 },
|
||||
stat = { digg_count = 2, reply_count = 9 },
|
||||
} },
|
||||
comment_list_info = { cursor = "20", has_more = true, total = 6 },
|
||||
} }
|
||||
local page
|
||||
Reviews.repliesAsync({}, "c1", 0, function(p) page = p end)
|
||||
local call = calls[#calls]
|
||||
Assert.eq(call.name, "reply_list")
|
||||
Assert.eq(call.path, "/novel/commentapi/reply/list/c1/v1/")
|
||||
Assert.matches(call.body, '"comment_source":5')
|
||||
Assert.matches(call.body, '"cursor":""')
|
||||
Assert.eq(page.items[1].author, "路人")
|
||||
Assert.eq(page.items[1].content, "确实[吃瓜]")
|
||||
Assert.matches(page.items[1].inline_images["[吃瓜]"].url, "/1f349%.png$", "回复与主评论共用表情映射")
|
||||
Assert.eq(page.items[1].reply_to, "楼主")
|
||||
Assert.eq(page.items[1].replies, 0, "回复页不再往下开")
|
||||
Assert.eq(page.items[1].likes, 2)
|
||||
Assert.eq(page.total, 6)
|
||||
Assert.eq(page.max_idx, "20")
|
||||
Assert.is_true(page.more)
|
||||
|
||||
Reviews.repliesAsync({}, "c1", "20", function(p) page = p end)
|
||||
Assert.matches(calls[#calls].body, '"cursor":"20"')
|
||||
Assert.is_false(page.more, "游标停住就不再翻")
|
||||
|
||||
reply = { data = { reply_list = {}, comment_list_info = { total = 3, has_more = false, cursor = "" } } }
|
||||
local err
|
||||
Reviews.repliesAsync({}, "c1", 0, function(p, e) Assert.is_nil(p) err = e end)
|
||||
Assert.matches(err, "为空")
|
||||
|
||||
reply = { data = {} }
|
||||
Reviews.repliesAsync({}, "c1", 0, function(p, e) Assert.is_nil(p) err = e end)
|
||||
Assert.matches(err, "reply_list")
|
||||
end
|
||||
|
||||
do -- 同步设备桩不能把正在请求的句柄覆盖掉;关闭后忽略迟到回包。
|
||||
local Device = require("moonsource_fanqie.reading.device")
|
||||
local Reading = require("moonsource_fanqie.reading")
|
||||
local ensure, signed = Device.ensureAsync, Reading.signedAsync
|
||||
local pending_device, pending_response
|
||||
local registration_cancelled, request_cancelled, received = false, false, false
|
||||
local signed_calls = 0
|
||||
Reading.signedAsync = function(_device, _name, _path, _query, _body, cb)
|
||||
signed_calls = signed_calls + 1
|
||||
pending_response = cb
|
||||
return { cancel = function() request_cancelled = true end }
|
||||
end
|
||||
local job = Reviews.hotspotsAsync({}, "900", function() received = true end)
|
||||
job.cancel()
|
||||
Assert.is_true(request_cancelled, "同步注册回调后取消实际段评请求")
|
||||
pending_response({ data = { data = {} } })
|
||||
Assert.is_false(received, "窗口关闭后不接受迟到响应")
|
||||
|
||||
Device.ensureAsync = function(_settings, cb)
|
||||
pending_device = cb
|
||||
return { cancel = function() registration_cancelled = true end }
|
||||
end
|
||||
request_cancelled = false
|
||||
job = Reviews.hotspotsAsync({}, "900", function() received = true end)
|
||||
job.cancel()
|
||||
Assert.is_true(registration_cancelled)
|
||||
pending_device({})
|
||||
Assert.is_false(request_cancelled)
|
||||
Assert.eq(signed_calls, 1, "取消注册后迟到回调不得启动段评请求")
|
||||
Assert.is_false(received)
|
||||
|
||||
job = Reviews.hotspotsAsync({}, "900", function() received = true end)
|
||||
pending_device({})
|
||||
Assert.eq(signed_calls, 2, "异步注册正常进入段评请求")
|
||||
job.cancel()
|
||||
Assert.is_true(request_cancelled, "异步注册完成后取消当前请求")
|
||||
pending_response({ data = { data = {} } })
|
||||
Assert.is_false(received)
|
||||
Device.ensureAsync, Reading.signedAsync = ensure, signed
|
||||
end
|
||||
|
||||
-- 定位:按段序找 blk p_idx 对应段落,xpointer 覆盖整段;整段原文作引用
|
||||
do
|
||||
local html = '<html><body>'
|
||||
.. '<p idx="0" p_idx="40000"><blk p_idx="0">开头一段话。</blk></p>'
|
||||
.. '<p idx="1" p_idx="40001"><blk p_idx="1">第二段里有一句被很多人评论的话。</blk></p>'
|
||||
.. '</body></html>'
|
||||
local spots = Reviews.locate({
|
||||
{ range = "1", text = "", total = 4 },
|
||||
{ range = "9", text = "", total = 1 },
|
||||
}, html)
|
||||
Assert.len(spots, 1)
|
||||
Assert.eq(spots[1].range, "1")
|
||||
Assert.eq(spots[1].total, 4)
|
||||
Assert.eq(spots[1].badge, "4")
|
||||
Assert.eq(spots[1].text, "第二段里有一句被很多人评论的话。")
|
||||
Assert.matches(spots[1].pos0, "%.%d+$")
|
||||
Assert.matches(spots[1].pos1, "%.%d+$")
|
||||
end
|
||||
|
||||
return true
|
||||
@@ -0,0 +1,30 @@
|
||||
--[[--
|
||||
番茄设置页:扫码入口与段评开关,不含 Cookie / 浏览器登录。
|
||||
|
||||
@module tests.moonsource_fanqie.setting_spec
|
||||
--]]
|
||||
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
|
||||
|
||||
local Assert = require("support.assert")
|
||||
package.loaded["ui.themes.widgets.row"] = { widget = function(spec) return spec end }
|
||||
|
||||
local cfg = {}
|
||||
package.loaded["utils.settings"] = {
|
||||
getSource = function() return cfg end,
|
||||
saveSource = function(_id, value) if value then cfg = value end end,
|
||||
}
|
||||
package.loaded["source.category_setting"] = {
|
||||
row = function() return function(iw) return { title = "分类", width = iw } end end,
|
||||
}
|
||||
|
||||
package.loaded["moonsource_fanqie.setting"] = nil
|
||||
local Setting = require("moonsource_fanqie.setting")
|
||||
|
||||
Assert.is_nil(Setting.browser)
|
||||
local rows = Setting.rows()
|
||||
Assert.eq(rows[1](400).title, "番茄账号与登录")
|
||||
Assert.eq(rows[2](400).title, "显示段评")
|
||||
for _idx, factory in ipairs(rows) do
|
||||
local row = factory(400)
|
||||
Assert.is_true(row.title ~= "浏览器登录" and row.title ~= "粘贴 Cookie")
|
||||
end
|
||||
@@ -0,0 +1,27 @@
|
||||
--[[--
|
||||
番茄 settings:登录判定必须以 sessionid 为准。
|
||||
|
||||
@module tests.moonsource_fanqie.settings_spec
|
||||
--]]
|
||||
|
||||
local Assert = require("support.assert")
|
||||
|
||||
local cfg = {}
|
||||
package.preload["utils.settings"] = function()
|
||||
return {
|
||||
getSource = function() return cfg end,
|
||||
saveSource = function(_, value) cfg = value end,
|
||||
}
|
||||
end
|
||||
|
||||
package.loaded["moonsource_fanqie.settings"] = nil
|
||||
local Settings = require("moonsource_fanqie.settings")
|
||||
|
||||
cfg = { cookies = { novel_web_id = "1", s_v_web_id = "2" } }
|
||||
Assert.is_true(not Settings:new():is_cookie_configured())
|
||||
|
||||
cfg = { cookies = { sessionid = "" } }
|
||||
Assert.is_true(not Settings:new():is_cookie_configured())
|
||||
|
||||
cfg = { cookies = { sessionid = "abc", novel_web_id = "1" } }
|
||||
Assert.is_true(Settings:new():is_cookie_configured())
|
||||
@@ -0,0 +1,152 @@
|
||||
--[[--
|
||||
番茄目录:读缓存和刷新都不再扫章节 HTML;锚点只在新下正文时写入,刷新时按 uid 保留。
|
||||
|
||||
@module tests.moonsource_fanqie.toc_spec
|
||||
--]]
|
||||
---@diagnostic disable: undefined-field, missing-fields, redundant-parameter, missing-parameter, inject-field, assign-type-mismatch, param-type-mismatch, cast-type-mismatch, return-type-mismatch, cast-local-type
|
||||
|
||||
local Assert = require("support.assert")
|
||||
local Stubs = require("support.stubs")
|
||||
local Paths = require("utils.paths")
|
||||
local Toc = require("source.toc")
|
||||
|
||||
local html_reads = 0
|
||||
local open = io.open
|
||||
io.open = function(path, mode, ...)
|
||||
if type(path) == "string" and path:match("/%d+%.html$") and (mode == nil or tostring(mode):match("^r")) then
|
||||
html_reads = html_reads + 1
|
||||
end
|
||||
return open(path, mode, ...)
|
||||
end
|
||||
|
||||
local directory, content
|
||||
local src = require("moonsource_fanqie.source").new()
|
||||
src.client.fetchChapterDirectoryAsync = function(_self, _id, cb)
|
||||
require("ui/uimanager"):nextTick(function() cb(directory) end)
|
||||
return { cancel = function() end }
|
||||
end
|
||||
src.client.officialGetContentAsync = function(_self, _bid, _iid, cb)
|
||||
require("ui/uimanager"):nextTick(function() cb(content) end)
|
||||
return { cancel = function() end }
|
||||
end
|
||||
|
||||
local identity = { source_id = "ext.fanqie", stable_id = "fanqie-toc-anchors" }
|
||||
local poison = '<h2 id="toc_99">不该扫到</h2><p>旧正文</p>'
|
||||
|
||||
local function writeChapterHtml(idx, html)
|
||||
Paths.ensureBookWork(identity.stable_id, identity.source_id)
|
||||
local file = assert(open(Paths.chapterPath(identity.stable_id, idx, identity.source_id), "w"))
|
||||
file:write(html)
|
||||
file:close()
|
||||
end
|
||||
|
||||
local function loadToc()
|
||||
local toc, err
|
||||
src:loadTocAsync(identity, function(value, reason) toc, err = value, reason end)
|
||||
Stubs.flush()
|
||||
return toc, err
|
||||
end
|
||||
|
||||
local function refreshToc()
|
||||
local toc, err
|
||||
src:refreshTocAsync(identity, function(value, reason) toc, err = value, reason end)
|
||||
Stubs.flush()
|
||||
return toc, err
|
||||
end
|
||||
|
||||
local function fetchContent(chapter)
|
||||
local Chapter = require("source.chapter")
|
||||
local ops
|
||||
local orig = Chapter.openAsync
|
||||
Chapter.openAsync = function(_source, _identity, _book, _opts, options, cb)
|
||||
ops = options
|
||||
if cb then cb("ok") end
|
||||
return { cancel = function() end }
|
||||
end
|
||||
src:openBookAsync(identity, { chapter_idx = 1 }, function() end)
|
||||
Chapter.openAsync = orig
|
||||
local payload, err
|
||||
ops.fetchContent(identity, chapter, function(value, reason) payload, err = value, reason end)
|
||||
Stubs.flush()
|
||||
return payload, err
|
||||
end
|
||||
|
||||
Toc.drop(identity.source_id, identity.stable_id)
|
||||
writeChapterHtml(1, poison)
|
||||
writeChapterHtml(2, poison)
|
||||
|
||||
-- 有缓存时 loadToc 直接返回,不读章节 HTML,也不为回填锚点写库。
|
||||
Assert.is_true(Toc.put(identity.source_id, identity.stable_id, {
|
||||
{ idx = 1, uid = "10", title = "正文", depth = 1 },
|
||||
{ idx = 2, uid = "20", title = "第二章", depth = 1 },
|
||||
}))
|
||||
html_reads = 0
|
||||
local puts = 0
|
||||
local orig_put = Toc.put
|
||||
Toc.put = function(...)
|
||||
puts = puts + 1
|
||||
return orig_put(...)
|
||||
end
|
||||
local cached, load_err = loadToc()
|
||||
Toc.put = orig_put
|
||||
Assert.is_nil(load_err)
|
||||
Assert.eq(cached[1].uid, "10")
|
||||
Assert.is_nil(cached[1].anchors, "读缓存不能靠扫 HTML 补锚点")
|
||||
Assert.is_nil(cached[2].anchors)
|
||||
Assert.eq(html_reads, 0, "有缓存时不能打开章节 HTML")
|
||||
Assert.eq(puts, 0, "读缓存目录不必 Toc.put")
|
||||
|
||||
-- 刷新保留库里已有的 HTML 锚点,同时收下官方锚点,且不扫 HTML。
|
||||
Assert.is_true(orig_put(identity.source_id, identity.stable_id, {
|
||||
{
|
||||
idx = 1, uid = "10", title = "正文", depth = 1,
|
||||
anchors = {
|
||||
{ title = "已缓存第一节", depth = 2, id = "toc_1" },
|
||||
{ title = "HTML锚点", depth = 2, id = "toc_8" },
|
||||
},
|
||||
},
|
||||
{ idx = 2, uid = "20", title = "第二章", depth = 1, anchors = { { title = "旧章锚点", depth = 2, id = "toc_9" } } },
|
||||
}))
|
||||
directory = { data = { chapterList = {
|
||||
{ itemId = "10", title = "正文", children = {
|
||||
{ title = "官方第一节", anchor = "toc_1" },
|
||||
{ title = "官方第二节", id = "toc_2" },
|
||||
} },
|
||||
{ itemId = "20", title = "第二章" },
|
||||
{ itemId = "30", title = "第三章" },
|
||||
} } }
|
||||
html_reads = 0
|
||||
local refreshed, refresh_err = refreshToc()
|
||||
Assert.is_nil(refresh_err)
|
||||
Assert.eq(html_reads, 0, "刷新目录不能打开章节 HTML")
|
||||
Assert.len(refreshed, 3)
|
||||
Assert.eq(refreshed[1].anchors[1].title, "官方第一节", "同 id 保留官方标题")
|
||||
Assert.eq(refreshed[1].anchors[2].id, "toc_2")
|
||||
Assert.eq(refreshed[1].anchors[3].id, "toc_8", "库里已有的 HTML 锚点不能被刷新冲掉")
|
||||
Assert.eq(refreshed[1].anchors[3].title, "HTML锚点")
|
||||
Assert.len(refreshed[1].anchors, 3)
|
||||
Assert.eq(refreshed[2].anchors[1].id, "toc_9")
|
||||
Assert.eq(refreshed[2].anchors[1].title, "旧章锚点")
|
||||
Assert.is_nil(refreshed[3].anchors, "新章没有旧锚点")
|
||||
local stored = Toc.read(identity.source_id, identity.stable_id)
|
||||
Assert.eq(stored[1].anchors[1].title, "官方第一节")
|
||||
Assert.eq(stored[1].anchors[3].id, "toc_8")
|
||||
Assert.eq(stored[2].anchors[1].id, "toc_9")
|
||||
|
||||
-- 拉正文后 persistAnchorsFromHtml 仍按章把锚点写进目录。
|
||||
content = { title = "第二章", content = '<h2 id="toc_3">新下的节</h2><p>新正文</p><h2 id="toc_4"></h2>' }
|
||||
html_reads = 0
|
||||
local payload, fetch_err = fetchContent({ idx = 2, uid = "20", title = "第二章", depth = 1 })
|
||||
Assert.is_nil(fetch_err)
|
||||
Assert.matches(payload.html, "新下的节")
|
||||
local after = Toc.read(identity.source_id, identity.stable_id)
|
||||
Assert.eq(after[2].anchors[1].id, "toc_9", "按章写入不能丢掉已有锚点")
|
||||
Assert.eq(after[2].anchors[2].id, "toc_3")
|
||||
Assert.eq(after[2].anchors[2].title, "新下的节")
|
||||
Assert.eq(after[2].anchors[3].id, "toc_4")
|
||||
Assert.eq(after[2].anchors[3].title, "#4")
|
||||
Assert.eq(after[1].anchors[3].id, "toc_8", "只写本章,不动其它章")
|
||||
Assert.eq(html_reads, 0, "按章写入走内存 HTML,不必再读落盘文件")
|
||||
|
||||
Toc.drop(identity.source_id, identity.stable_id)
|
||||
io.open = open
|
||||
Reference in new issue
Block a user