Files
moonsource-legadorule/moonsource-legadorule.koplugin/moonsource_legadorule/remote.lua
T

210 lines
9.1 KiB
Lua
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
--[[--
远程管理网页(/legado_sources.html)的接口:导入、检查有效性、启停、删除书源,以及书架换源。
导入内容(文件、粘贴、在线地址)可以是单个书源 JSON、书源数组 JSON,或每行一个书源的合集文件。
@module moonsource_legadorule.remote
--]]
local Sources = require("moonsource_legadorule.sources")
local Remote = {}
local MAX_BODY = 64 * 1024 * 1024
Remote.UPLOAD_LIMIT = MAX_BODY
--- 请求体一律 UTF-8;在线文件不一定标了编码,按 Charset 转一次。
local function fetch(url, cb)
if not url:match("^https?://") then cb(nil, "只支持 http / https 地址"); return end
local Request = require("http.request")
Request.get(url, { timeout = 60, allow_redirects = true, cache_ttl = 0 }, function(body, err, res)
if not body then cb(nil, err and tostring(err) or "请求失败"); return end
local text = require("utils.charset").toUtf8(body, res and Request.header(res, "content-type")) or body
cb(text)
end)
end
local function summary(s)
return { key = s.key, name = s.name, url = s.url, enabled = s.enabled and true or false,
reason = s.reason, ms = s.ms, checked = s.checked }
end
local function listing(params)
local page = math.max(1, math.floor(tonumber(params.page) or 1))
local size = math.min(200, math.max(1, math.floor(tonumber(params.size) or 50)))
local status = params.status == "on" and "on" or params.status == "off" and "off" or nil
local list, total = Sources.page(params.q and tostring(params.q) or nil, status, page, size)
local sources = {}
for _idx, s in ipairs(list) do sources[#sources + 1] = summary(s) end
return { sources = sources, total = total, counts = Sources.counts() }
end
---@param text string
---@return table|nil result, string|nil err
local function importText(text)
local rules, skipped = Sources.parse(text)
if #rules == 0 then return nil, "没有找到有效的书源(需要含 bookSourceUrl 的 JSON)" end
local added, disabled = Sources.add(rules)
return { total = #rules, added = added, skipped = skipped, disabled = disabled }
end
---------------------------------------------------------------- 有效性检查
local CHECK_KEYWORD = "我的"
local CHECK_CONCURRENCY = 6
--- 秒(带小数),用于计响应时间。
local function now()
local ok, socket = pcall(require, "socket")
return ok and socket.gettime and socket.gettime() or os.time()
end
local errMessage = function(err) return require("moonsource_legadorule.unsupported").message(err) end
--- done(nil) 表示通过,done(reason) 表示该环节失败。
local function walk(parser, done)
local function fail(stage, err) done(stage .. ":" .. (err and errMessage(err) or "无结果")) end
parser:search(CHECK_KEYWORD, 1, function(books, err)
local first = type(books) == "table" and books[1]
if not first then return fail("搜索", err or "搜索无结果") end
parser:detail(first.bookUrl or "", first, function(book, derr)
if not book then return fail("详情", derr) end
parser:chapters(book, function(chapters, cerr)
if type(chapters) ~= "table" then return fail("目录", cerr) end
local chapter
for _idx, ch in ipairs(chapters) do
if not ch.isVolume then chapter = ch; break end
end
if not chapter then return fail("目录", "章节列表为空") end
parser:content(chapter, book, nil, function(res, xerr)
if not res then return fail("正文", xerr) end
if res.text == nil or res.text == "" then return fail("正文", "章节内容为空") end
done(nil)
end)
end)
end)
end)
end
local check = { running = false, total = 0, done = 0, disabled = 0 }
--- 走一遍完整读书流程:搜索 → 详情 → 目录 → 第一章正文,每步都成功才算有效,
--- 任何一步报错、超时或结果为空都禁用,原因带上失败的环节。
--- 后台逐批进行,进度由 check_status 读取;同时只跑一轮。
local function startCheck(keys)
if check.running then return false end
local entries = {}
if keys and #keys > 0 then
local want = {}
for _idx, k in ipairs(keys) do want[k] = true end
for _idx, e in ipairs(Sources.all()) do if want[e.key] then entries[#entries + 1] = e end end
else
entries = Sources.all()
end
check = { running = true, total = #entries, done = 0, disabled = 0, invalid = {} }
local state, nextIdx, active = check, 0, 0
local function finish()
if state.done < state.total then return end
state.running = false
end
local function launch()
while active < CHECK_CONCURRENCY and nextIdx < #entries do
nextIdx = nextIdx + 1
local entry = entries[nextIdx]
active = active + 1
local settled = false
local started = now()
local function settle(ok, why)
if settled then return end
settled = true
Sources.setCheck(entry.key, math.floor((now() - started) * 1000), (not ok) and (why or "搜索失败") or nil)
if not ok then
state.disabled = state.disabled + 1
state.invalid[#state.invalid + 1] = entry.key
end
active = active - 1
state.done = state.done + 1
launch()
finish()
end
local made, parser = pcall(function()
return require("moonsource_legadorule.parser").new(Sources.rule(entry))
end)
if not made then
settle(false, "书源规则无法解析")
else
local ran, err = pcall(walk, parser, function(why) settle(why == nil, why) end)
if not ran then settle(false, errMessage(err)) end
end
end
end
if #entries == 0 then check.running = false else launch() end
return true
end
local function readFile(path)
local f = io.open(path, "rb")
if not f then return nil end
local data = f:read("*a")
f:close()
return data
end
--- 书源全量列表 / 导入 / 检查 / 启停 / 删除。
---@param method string
---@param action string
---@param params table
---@param cb fun(status: integer, body: table)
function Remote.handle(method, action, params, cb)
require("utils.awake").poke()
if method == "GET" and action == "list" then
cb(200, listing(params))
elseif method == "POST" and action == "import" then
-- 原始文件体落在临时文件里(路径在 params.temp);粘贴的文本由网页同样当文件体发来
local path = params.temp
local text = path and readFile(path)
if path then os.remove(path) end
if not text then cb(400, { error = "没有收到内容" }); return end
local result, err = importText(text)
if result then cb(200, result) else cb(422, { error = err }) end
elseif method == "POST" and action == "import_url" then
-- 单次导入在线地址,不留订阅
fetch(tostring(params.url or ""), function(text, err)
if not text then cb(502, { error = err }); return end
local result, perr = importText(text)
if result then cb(200, result) else cb(422, { error = perr }) end
end)
elseif method == "POST" and action == "check" then
cb(200, { started = startCheck(params.keys) })
elseif method == "GET" and action == "check_status" then
cb(200, { running = check.running, total = check.total, done = check.done, disabled = check.disabled })
elseif method == "GET" and action == "switch_books" then
cb(200, { books = require("moonsource_legadorule.switch").books() })
elseif method == "POST" and action == "switch_search" then
local Switch = require("moonsource_legadorule.switch")
local book = { stable_id = tostring(params.stable_id or ""), title = tostring(params.title or ""),
authors = tostring(params.authors or "") }
if book.stable_id == "" or book.title == "" then cb(400, { error = "缺少书籍信息" }); return end
cb(200, { started = Switch.start(book) })
elseif method == "POST" and action == "switch_cancel" then
require("moonsource_legadorule.switch").cancel()
cb(200, {})
elseif method == "GET" and action == "switch_status" then
cb(200, require("moonsource_legadorule.switch").status())
elseif method == "POST" and action == "switch_apply" then
local ok, err = require("moonsource_legadorule.switch").apply(tostring(params.stable_id or ""), params.target)
if ok then cb(200, {}) else cb(422, { error = err }) end
elseif method == "POST" and action == "enable" then
Sources.setEnabledMany(params.keys or {}, params.enabled and true or false)
cb(200, {})
elseif method == "POST" and action == "delete" then
cb(200, { removed = Sources.removeMany(params.keys or {}) })
else
cb(404, { error = "unknown action" })
end
end
return Remote