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

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

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

No files matched your search

+23
View File
@@ -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/);离线缺图不保证字形可见 |
| 评论写操作 | 不支持 | 不发评、不点赞、不删评 |
| 账号切换 | 不支持直接隔离 | 没有稳定账号隔离;须先退出清理旧数据,未同步记录会丢失 |
+5
View File
@@ -0,0 +1,5 @@
local _ = require("gettext")
return {
fullname = _("月读书源:番茄小说"),
description = _("给月读增加「番茄小说」书源。需要同时安装月读,与平台官方无关。"),
}
+9
View File
@@ -0,0 +1,9 @@
--[[--
KOReader 只认带 main.lua 的插件目录;书源本身不需要任何插件钩子,月读读取旁边的 moon_source.lua。
--]]
local WidgetContainer = require("ui/widget/container/widgetcontainer")
return WidgetContainer:extend{
name = "moonsource_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