✨ (manage): 书源存数据库,远程管理网页支持导入、分页、有效性检查与启停

This commit is contained in:
garfield committed 2026-12-04 00:33:36 +08:00
1 parent 3a7cb92270
commit f0d737e68a
9 files changed
+1519

No files matched your search

@@ -0,0 +1,29 @@
--[[--
把书源管理网页(/legado_sources.html)挂进月读远程管理(web.routes)。由 moon_source.lua 加载时 require 一次;
接口实现在 remote.lua,用到时才加载。
@module moonsource_legadorule.extras
--]]
local Ext = require("utils.extension")
local PREFIX = "moonsource_legadorule."
local here = debug.getinfo(1, "S").source:match("^@(.+)/[^/]+$") or "."
Ext.add("web.routes", {
name = "legado_sources",
dir = here .. "/web",
assets = { "legado_sources.html", "legado_sources.js", "legado_sources.css" },
page = {
href = "/legado_sources.html", title = "Legado 书源", title_long = "Legado 书源管理", tile = "tile-green",
desc = "导入、检查有效性、启停与删除 Legado 书源(单个、数组或合集,本地或在线)。",
icon = "M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h10v2H4v-2z",
},
l10n = PREFIX .. "l10n.web",
upload = { import = 64 * 1024 * 1024 },
handle = function(method, action, params, cb)
require(PREFIX .. "remote").handle(method, action, params, cb)
end,
})
return {}
@@ -0,0 +1,79 @@
-- 书源管理网页文案(经 web.routes 的 l10n 合入远程管理 /api/i18n)。
return {
["Legado 书源"] = "Legado sources",
["Legado 书源管理"] = "Legado source manager",
["Legado 书源管理 - 远程管理"] = "Legado source manager - Remote",
["粘贴书源 JSON…"] = "Paste source JSON…",
["书源"] = "Sources",
["搜索名称或地址"] = "Search name or URL",
["已启用"] = "Enabled",
["已禁用"] = "Disabled",
["正在处理…"] = "Working…",
["请先粘贴书源 JSON"] = "Paste source JSON first",
["请先填写书源地址"] = "Enter a source URL first",
["共 %1 个书源,新增 %2 个"] = "%1 sources, %2 new",
["共 %1 个书源"] = "%1 sources",
[",跳过无效项 %1 个"] = ", %1 invalid skipped",
["完成"] = "Done",
["书源操作"] = "Source actions",
["搜索书源"] = "Search sources",
["状态"] = "Status",
["添加书源"] = "Add sources",
["批量操作"] = "Bulk actions",
["启用"] = "Enable",
["禁用"] = "Disable",
["删除"] = "Delete",
["取消选择"] = "Clear selection",
["书源列表"] = "Source list",
["全选"] = "Select all",
["正在加载…"] = "Loading…",
["取消"] = "Cancel",
["确定"] = "OK",
["添加方式"] = "Add method",
["粘贴 JSON"] = "Paste JSON",
["单个、数组或每行一个"] = "Single, array or one per line",
["本地文件"] = "Local file",
["地址"] = "URL",
["文件"] = "File",
["添加"] = "Add",
["操作失败:%1"] = "Failed: %1",
["全部书源"] = "All sources",
["选择 %1"] = "Select %1",
["没有符合条件的书源"] = "No matching sources",
["还没有书源,点右上角「添加书源」"] = "No sources yet. Click “Add sources”.",
["显示更多(还有 %1 个)"] = "Show more (%1 left)",
["已选 %1 项"] = "%1 selected",
["删除书源?"] = "Delete sources?",
["将删除 %1 个书源。"] = "%1 sources will be deleted.",
["已删除"] = "Deleted",
["请先选择文件"] = "Choose a file first",
["导入、检查有效性、启停与删除 Legado 书源(单个、数组或合集,本地或在线)。"] = "Import, check, enable/disable and delete Legado sources (single, array or collection; local or online).",
["检查有效性"] = "Check validity",
["检查所选"] = "Check selected",
["在线地址"] = "Online URL",
["单个 JSON、数组或合集,只下载一次"] = "Single JSON, array or collection; downloaded once",
["书源 JSON"] = "Source JSON",
[",%1 个需要 JS/WebView 已禁用"] = ", %1 disabled (need JS/WebView)",
["原因:%1"] = "Reason: %1",
["还没有书源"] = "No sources yet",
["检查已在进行中"] = "A check is already running",
["正在检查书源 %1 / %2,已禁用 %3 个…"] = "Checking sources %1 / %2, %3 disabled…",
["检查完成:共 %1 个,禁用了 %2 个无效书源"] = "Check done: %1 checked, %2 invalid sources disabled",
["第 %1 / %2 页,共 %3 个"] = "Page %1 / %2, %3 total",
["上一页"] = "Previous",
["下一页"] = "Next",
["书架换源"] = "Switch source for a book",
["书的进度和阅读时间不变,只改从哪个书源读取。来源已失效的书排在前面。"] = "Progress and reading time stay the same; only the source changes. Books whose source is invalid come first.",
["返回书架"] = "Back to shelf",
["关闭"] = "Close",
["书架里还没有这个书源的书"] = "No books from this source on the shelf",
[" · 已换源"] = " · switched",
["换源:%1"] = "Switch source: %1",
["正在搜索…"] = "Searching…",
["其他书源里没有找到这本书"] = "Not found in other sources",
["正在 %1 个书源里搜索《%2》… %3"] = "Searching %1 sources for “%2”… %3",
["已有搜索在后台进行"] = "A search is already running in the background",
["换源"] = "Switch source",
["《%1》改从「%2」读取?进度和阅读时间不变,目录会重新获取。"] = "Read “%1” from “%2”? Progress and reading time stay; the TOC will be reloaded.",
["已换到 %1"] = "Switched to %1",
}
@@ -0,0 +1,79 @@
-- 書源管理網頁文案(繁體)。
return {
["Legado 书源"] = "Legado 書源",
["Legado 书源管理"] = "Legado 書源管理",
["Legado 书源管理 - 远程管理"] = "Legado 書源管理 - 遠程管理",
["粘贴书源 JSON…"] = "粘貼書源 JSON…",
["书源"] = "書源",
["搜索名称或地址"] = "搜索名称或地址",
["已启用"] = "已啟用",
["已禁用"] = "已禁用",
["正在处理…"] = "正在處理…",
["请先粘贴书源 JSON"] = "請先粘貼書源 JSON",
["请先填写书源地址"] = "請先填寫書源地址",
["共 %1 个书源,新增 %2 个"] = "共 %1 個書源,新增 %2 個",
["共 %1 个书源"] = "共 %1 個書源",
[",跳过无效项 %1 个"] = ",跳過无效項 %1 個",
["完成"] = "完成",
["书源操作"] = "書源操作",
["搜索书源"] = "搜索書源",
["状态"] = "狀態",
["添加书源"] = "添加書源",
["批量操作"] = "批量操作",
["启用"] = "啟用",
["禁用"] = "禁用",
["删除"] = "刪除",
["取消选择"] = "取消選择",
["书源列表"] = "書源列表",
["全选"] = "全選",
["正在加载…"] = "正在加載…",
["取消"] = "取消",
["确定"] = "確定",
["添加方式"] = "添加方式",
["粘贴 JSON"] = "粘貼 JSON",
["单个、数组或每行一个"] = "單個、數組或每行一個",
["本地文件"] = "本地文件",
["地址"] = "地址",
["文件"] = "文件",
["添加"] = "添加",
["操作失败:%1"] = "操作失败:%1",
["全部书源"] = "全部書源",
["选择 %1"] = "選择 %1",
["没有符合条件的书源"] = "沒有符合條件的書源",
["还没有书源,点右上角「添加书源」"] = "還沒有書源,点右上角「添加書源」",
["显示更多(还有 %1 个)"] = "顯示更多(還有 %1 個)",
["已选 %1 项"] = "已選 %1 項",
["删除书源?"] = "刪除書源?",
["将删除 %1 个书源。"] = "將刪除 %1 個書源。",
["已删除"] = "已刪除",
["请先选择文件"] = "請先選择文件",
["导入、检查有效性、启停与删除 Legado 书源(单个、数组或合集,本地或在线)。"] = "導入、檢查有效性、啟停與刪除 Legado 書源(單個、數組或合集,本地或在線)。",
["检查有效性"] = "檢查有效性",
["检查所选"] = "檢查所選",
["在线地址"] = "在線地址",
["单个 JSON、数组或合集,只下载一次"] = "單個 JSON、數組或合集,只下載一次",
["书源 JSON"] = "書源 JSON",
[",%1 个需要 JS/WebView 已禁用"] = ",%1 個需要 JS/WebView 已禁用",
["原因:%1"] = "原因:%1",
["还没有书源"] = "還沒有書源",
["检查已在进行中"] = "檢查已在進行中",
["正在检查书源 %1 / %2,已禁用 %3 个…"] = "正在檢查書源 %1 / %2,已禁用 %3 個…",
["检查完成:共 %1 个,禁用了 %2 个无效书源"] = "檢查完成:共 %1 個,禁用了 %2 個無效書源",
["第 %1 / %2 页,共 %3 个"] = "第 %1 / %2 頁,共 %3 個",
["上一页"] = "上一頁",
["下一页"] = "下一頁",
["书架换源"] = "書架換源",
["书的进度和阅读时间不变,只改从哪个书源读取。来源已失效的书排在前面。"] = "書的進度和閱讀時間不變,只改從哪個書源讀取。來源已失效的書排在前面。",
["返回书架"] = "返回書架",
["关闭"] = "關閉",
["书架里还没有这个书源的书"] = "書架裡還沒有這個書源的書",
[" · 已换源"] = " · 已換源",
["换源:%1"] = "換源:%1",
["正在搜索…"] = "正在搜索…",
["其他书源里没有找到这本书"] = "其他書源裡沒有找到這本書",
["正在 %1 个书源里搜索《%2》… %3"] = "正在 %1 個書源裡搜索《%2》… %3",
["已有搜索在后台进行"] = "已有搜索在後台進行",
["换源"] = "換源",
["《%1》改从「%2」读取?进度和阅读时间不变,目录会重新获取。"] = "《%1》改從「%2」讀取?進度和閱讀時間不變,目錄會重新獲取。",
["已换到 %1"] = "已換到 %1",
}
@@ -0,0 +1,209 @@
--[[--
远程管理网页(/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
@@ -0,0 +1,319 @@
--[[--
已导入的 Legado 书源:解析导入文本、存库、读取、启停、换源映射,以及发现页入口(exploreUrl)解析。
书源存在月读的 book.sqlite3:legadorule_sources(规则 JSON 原文,用到时才读出解码);
书源身份是 bookSourceUrl 的短哈希,seq 是导入顺序。
@module moonsource_legadorule.sources
--]]
local DB = require("utils.db")
local Json = require("moonsource_legadorule.json")
local Unsupported = require("moonsource_legadorule.unsupported")
local Sources = {}
---@param url string bookSourceUrl
---@return string 8 位十六进制
function Sources.key(url)
local bit = require("bit")
local h = 5381
for i = 1, #url do h = bit.band(h * 33 + url:byte(i), 0x7fffffff) end
local g = 2166136261
for i = 1, #url do g = bit.band(bit.bxor(g, url:byte(i)) * 16777619, 0x7fffffff) end
return string.format("%04x%04x", bit.band(h, 0xffff), bit.band(g, 0xffff))
end
--- 导入文本:一个书源对象、书源数组,或每行一个对象。返回有效书源数组与被跳过的数量。
---@param text string
---@return table[] rules
---@return integer skipped
function Sources.parse(text)
text = text:gsub("^\239\187\191", "")
local rules, skipped = {}, 0
local function take(v)
if Json.isObject(v) and type(v.bookSourceUrl) == "string" and v.bookSourceUrl ~= "" then
rules[#rules + 1] = v
else
skipped = skipped + 1
end
end
local v = Json.decode(text)
if Json.isArray(v) then
for _idx, item in ipairs(v) do take(item) end
elseif v ~= nil then
take(v)
else
for line in text:gmatch("[^\r\n]+") do
local item = Json.decode(line)
if item ~= nil then take(item) else skipped = skipped + 1 end
end
end
return rules, skipped
end
DB.schema("legadorule_sources", function()
if DB.exec([[
CREATE TABLE IF NOT EXISTS legadorule_sources (
key TEXT PRIMARY KEY, url TEXT NOT NULL, name TEXT NOT NULL,
enabled INTEGER NOT NULL DEFAULT 1, json TEXT NOT NULL,
seq INTEGER NOT NULL,
reason TEXT, ms INTEGER, checked INTEGER
);
DROP TABLE IF EXISTS legadorule_subs;
]]) == nil then return false end
-- 早期建的表没有检查结果列:补上
local info, n = DB.query("PRAGMA table_info(legadorule_sources);")
local have = {}
for i = 1, n or 0 do have[info[2][i]] = true end
for _idx, col in ipairs({ { "reason", "TEXT" }, { "ms", "INTEGER" }, { "checked", "INTEGER" } }) do
if not have[col[1]] then
DB.exec("ALTER TABLE legadorule_sources ADD COLUMN " .. col[1] .. " " .. col[2] .. ";")
end
end
return true
end)
DB.schema("legadorule_alias", function()
return DB.exec([[
CREATE TABLE IF NOT EXISTS legadorule_alias (
stable_id TEXT PRIMARY KEY, key TEXT NOT NULL, book_url TEXT NOT NULL
);
]]) ~= nil
end)
local LIST = "SELECT key, url, name, enabled, reason, ms, checked FROM legadorule_sources"
local function entries(where, ...)
local result, n = DB.query(LIST .. (where or "") .. ";", ...)
local out = {}
for i = 1, n or 0 do
out[i] = { key = result[1][i], url = result[2][i], name = result[3][i],
enabled = tonumber(result[4][i]) == 1,
reason = result[5][i], ms = tonumber(result[6][i]), checked = tonumber(result[7][i]) }
end
return out
end
local function nextSeq(tbl)
return (tonumber(DB.rowexec("SELECT COALESCE(MAX(seq),0) FROM " .. tbl .. ";")) or 0) + 1
end
local function inList(keys)
local marks = {}
for i = 1, #keys do marks[i] = "?" end
return "(" .. table.concat(marks, ",") .. ")"
end
--- 全部已导入书源(不含规则原文):{ key, name, url, enabled, reason, ms(上次检查响应毫秒), checked(检查时间) },按导入顺序。
function Sources.all()
return entries(" ORDER BY seq ASC")
end
--- 分页查询:q 匹配名称或地址(不分大小写),status 为 "on" / "off" / nil。返回当页书源与符合条件的总数。
---@param q string|nil
---@param status string|nil
---@param page integer 从 1 起
---@param size integer
---@return table[] list
---@return integer total
function Sources.page(q, status, page, size)
local where, args = {}, {}
if q and q ~= "" then
local like = "%" .. q:gsub("[\\%%_]", "\\%0") .. "%"
where[#where + 1] = "(name LIKE ? ESCAPE '\\' OR url LIKE ? ESCAPE '\\')"
args[#args + 1] = like
args[#args + 1] = like
end
if status == "on" then where[#where + 1] = "enabled=1"
elseif status == "off" then where[#where + 1] = "enabled=0" end
local cond = #where > 0 and (" WHERE " .. table.concat(where, " AND ")) or ""
local total = tonumber(DB.rowexec("SELECT COUNT(*) FROM legadorule_sources" .. cond .. ";", unpack(args))) or 0
args[#args + 1] = size
args[#args + 1] = (page - 1) * size
return entries(cond .. " ORDER BY seq ASC LIMIT ? OFFSET ?", unpack(args)), total
end
---@return { all: integer, on: integer, off: integer }
function Sources.counts()
local all = tonumber(DB.rowexec("SELECT COUNT(*) FROM legadorule_sources;")) or 0
local on = Sources.enabledCount()
return { all = all, on = on, off = all - on }
end
function Sources.enabled()
return entries(" WHERE enabled=1 ORDER BY seq ASC")
end
---@return integer
function Sources.enabledCount()
return tonumber(DB.rowexec("SELECT COUNT(*) FROM legadorule_sources WHERE enabled=1;")) or 0
end
function Sources.find(key)
return entries(" WHERE key=?", key)[1]
end
local decoded = {}
--- 书源内容变更计数:解析器缓存据此失效。
Sources.version = 0
local function changed(key)
Sources.version = Sources.version + 1
if key then decoded[key] = nil else decoded = {} end
end
--- 取书源规则表(从库里读规则原文,解码一次)。
function Sources.rule(entry)
local rule = decoded[entry.key]
if not rule then
local text = DB.rowexec("SELECT json FROM legadorule_sources WHERE key=?;", entry.key)
rule = text and Json.decode(text)
decoded[entry.key] = rule
end
return rule
end
--- 读书必经的规则里是否含 JS / WebView 片段(静态判断,仅抓明显的 <js>、@js:、webView 选项)。
---@param rule table
---@return boolean ok
---@return string|nil reason
function Sources.supported(rule)
local parts = { tostring(rule.searchUrl or "") }
for _idx, f in ipairs({ "ruleSearch", "ruleBookInfo", "ruleToc", "ruleContent" }) do
if rule[f] ~= nil then parts[#parts + 1] = Json.encode(rule[f]) end
end
local text = table.concat(parts, "\n")
if Unsupported.isJsSnippet(text) or text:lower():find('webview"?%s*[:=]%s*"?true', 1) then
return false, Unsupported.MESSAGE
end
return true
end
--- 导入(同 bookSourceUrl 覆盖,保留原启停状态);含 JS / WebView 的书源导入即禁用。返回新增数量与被禁用数量。
function Sources.add(rules)
local added, disabled = 0, 0
DB.transaction(function()
local seq = nextSeq("legadorule_sources")
for _idx, rule in ipairs(rules) do
local key = Sources.key(rule.bookSourceUrl)
local name = tostring(rule.bookSourceName or rule.bookSourceUrl)
local text = Json.encode(rule)
changed(key)
local ok, why = Sources.supported(rule)
if not ok then disabled = disabled + 1 end
local exists = DB.rowexec("SELECT 1 FROM legadorule_sources WHERE key=?;", key)
if exists then
DB.exec("UPDATE legadorule_sources SET url=?, name=?, json=?, enabled=CASE WHEN ? THEN enabled ELSE 0 END, reason=?, ms=NULL, checked=NULL WHERE key=?;",
rule.bookSourceUrl, name, text, ok and 1 or 0, why, key)
else
DB.exec("INSERT INTO legadorule_sources(key,url,name,enabled,json,seq,reason) VALUES(?,?,?,?,?,?,?);",
key, rule.bookSourceUrl, name, ok and 1 or 0, text, seq, why)
seq = seq + 1
added = added + 1
end
end
return true
end)
return added, disabled
end
function Sources.setEnabled(key, enabled)
Sources.setEnabledMany({ key }, enabled)
end
---@param keys string[]
---@param enabled boolean
function Sources.setEnabledMany(keys, enabled)
if #keys == 0 then return end
DB.transaction(function()
for i = 1, #keys, 500 do
local chunk = { unpack(keys, i, math.min(i + 499, #keys)) }
DB.exec("UPDATE legadorule_sources SET enabled=?" .. (enabled and ", reason=NULL" or "") ..
" WHERE key IN " .. inList(chunk) .. ";",
enabled and 1 or 0, unpack(chunk))
end
return true
end)
end
--- 记录一次检查:响应毫秒与结果;无效(reason 非空)时同时禁用。
---@param key string
---@param ms integer|nil
---@param reason string|nil 无效原因,有效传 nil
function Sources.setCheck(key, ms, reason)
if reason then reason = reason:sub(1, 200) end
DB.exec("UPDATE legadorule_sources SET ms=?, reason=?, checked=?, enabled=CASE WHEN ? THEN 0 ELSE enabled END WHERE key=?;",
ms, reason, os.time(), reason and 1 or 0, key)
end
function Sources.remove(key)
Sources.removeMany({ key })
end
---@param keys string[]
---@return integer removed
function Sources.removeMany(keys)
local removed = 0
DB.transaction(function()
for i = 1, #keys, 500 do
local chunk = { unpack(keys, i, math.min(i + 499, #keys)) }
DB.exec("DELETE FROM legadorule_sources WHERE key IN " .. inList(chunk) .. ";", unpack(chunk))
removed = removed + (tonumber(DB.rowexec("SELECT changes();")) or 0)
for _idx, k in ipairs(chunk) do changed(k) end
end
return true
end)
return removed
end
--- 换源:书架里的书身份(stable_id)不变,改成从另一个书源的书地址读取。
---@param stable_id string
---@param key string 新书源 key
---@param bookUrl string 新书源里的书地址
function Sources.setAlias(stable_id, key, bookUrl)
DB.exec("INSERT OR REPLACE INTO legadorule_alias(stable_id,key,book_url) VALUES(?,?,?);", stable_id, key, bookUrl)
end
--- 该身份换过源则返回新的 key 与书地址。
---@param stable_id string
---@return string|nil key, string|nil bookUrl
function Sources.alias(stable_id)
local key, url = DB.rowexec("SELECT key, book_url FROM legadorule_alias WHERE stable_id=?;", stable_id)
return key, url
end
--- 发现入口:`标题::地址` 每行一条,或 [{title,url}] JSON。含 JS 的条目跳过。
---@param rule table
---@return { title: string, url: string }[]
function Sources.explore(rule)
local raw = rule.exploreUrl
local out = {}
local function add(title, url)
if type(title) == "string" and type(url) == "string" and url ~= "" and not Unsupported.isJsSnippet(url) then
out[#out + 1] = { title = title ~= "" and title or url, url = url }
end
end
if Json.isArray(raw) then
for _idx, item in ipairs(raw) do
if Json.isObject(item) then add(item.title, item.url) end
end
elseif type(raw) == "string" then
local text = raw:gsub("^%s+", "")
if Unsupported.isJsSnippet(text) then return out end
local arr = text:sub(1, 1) == "[" and Json.decode(text)
if Json.isArray(arr) then
for _idx, item in ipairs(arr) do
if Json.isObject(item) then add(item.title, item.url) end
end
else
for line in (text:gsub("&&", "\n") .. "\n"):gmatch("(.-)\r?\n") do
local title, url = line:match("^(.-)::(.+)$")
if title then add(title:gsub("^%s+", ""):gsub("%s+$", ""), url:gsub("^%s+", ""):gsub("%s+$", "")) end
end
end
end
return out
end
return Sources
@@ -0,0 +1,73 @@
/* Legado 书源管理页样式;外壳与订阅页相同,沿用 /style.css 与订阅页的 sub-* 类(订阅页的样式在 /subscribe.css,这里补齐本页用到的部分)。 */
.sub-toolbar { flex-wrap: wrap; gap: 8px }
.sub-toolbar select { min-height: 32px; font-size: 13px }
.sub-search input { width: min(280px, 46vw); min-height: 32px; font-size: 13px }
.sub-toolbar .file-action.primary { border-color: var(--accent); background: var(--accent); color: var(--on-accent) }
.sub-batch { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; padding: 6px 12px; border-bottom: 1px solid var(--row-rule); background: var(--accent-soft) }
.sub-batch[hidden], .ls-progress[hidden] { display: none }
.sub-groups button { display: flex; align-items: center; gap: 6px }
.sub-groups button[data-all]::before { background: var(--accent) }
.sub-groups button .g-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis }
.sub-groups button .g-count { color: var(--dim); font-size: 12px; font-weight: 400 }
.sub-groups button .g-err { color: var(--danger); font-size: 12px }
.ls-subbar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 8px 14px; border-bottom: 1px solid var(--row-rule) }
.ls-subinfo { flex: 1 1 auto; min-width: 0; overflow: hidden; color: var(--dim); font-size: 13px; text-overflow: ellipsis; white-space: nowrap }
.sub-list { table-layout: auto }
.sub-list td { vertical-align: middle }
.sub-list th { font-weight: 500; text-align: left; color: var(--dim); font-size: 12px }
.sub-list td.sel, .sub-list th.sel { width: 36px; padding: 0 0 0 12px }
.sub-list td.ico { width: 34px; padding-right: 0 }
.sub-icon { display: grid; place-items: center; width: 30px; height: 30px; border-radius: 8px; background: #5079aa; color: #fff; font-size: 12px; font-weight: 600 }
.sub-list tr.off .sub-icon { background: #9aa3ad }
.sub-list td.n { max-width: 0; width: 100% }
.sub-list .f-title { display: block; overflow: hidden; color: var(--fg); font-weight: 500; text-overflow: ellipsis; white-space: nowrap }
.sub-list tr.off .f-title { color: var(--dim); text-decoration: line-through }
.sub-list .f-url { display: block; overflow: hidden; color: var(--dim); font-size: 12px; text-overflow: ellipsis; white-space: nowrap }
.sub-list .f-err { display: block; color: var(--danger); font-size: 12px }
.sub-badge { display: inline-block; padding: 1px 8px; border: 1px solid var(--pill-border); border-radius: 10px; background: var(--pill-bg); color: var(--dim); font-size: 11px; white-space: nowrap }
.sub-badge.on { border-color: var(--accent); color: var(--accent) }
.sub-list td.meta { width: 1%; white-space: nowrap }
.sub-list td.ops { width: 1%; white-space: nowrap }
.sub-list td.ops button { min-height: 28px; padding: 0 10px; font-size: 12px }
.sub-list td.empty { padding: 48px 14px; text-align: center; color: var(--dim) }
.sub-list tbody tr.selected td { background: var(--accent-soft) }
.sub-list td.more { text-align: center }
.sub-dialog { width: min(560px, 100%); max-height: calc(100vh - 32px); overflow: auto }
.sub-dialog .field { margin: 10px 0 }
.sub-dialog .field label { display: block; margin-bottom: 4px; color: var(--dim); font-size: 13px }
.sub-dialog .field input, .sub-dialog .field textarea { width: 100%; margin: 0; box-sizing: border-box }
.sub-kinds { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin: 6px 0 4px }
.sub-kinds .opt { display: flex; gap: 8px; align-items: flex-start; padding: 10px; border: 1px solid var(--rule); border-radius: var(--radius); cursor: pointer }
.sub-kinds .opt:has(input:checked) { border-color: var(--accent); background: var(--accent-soft) }
.sub-kinds strong { display: block; font-size: 14px; font-weight: 500 }
.sub-kinds small { color: var(--dim); font-size: 12px }
.sub-toasts { position: fixed; right: 16px; bottom: 16px; z-index: 60; display: grid; gap: 8px; max-width: min(360px, calc(100vw - 32px)) }
.sub-toast { padding: 10px 14px; border-radius: var(--radius); background: var(--bar); color: var(--bar-fg); box-shadow: var(--shadow-dialog); font-size: 13px }
.sub-toast.err { background: var(--danger) }
@media (max-width: 720px) {
.sub-search input { width: 100% }
.sub-toolbar .fa-left { flex: 1 1 100% }
.sub-groups { display: flex; gap: 6px; overflow-x: auto }
.sub-kinds { grid-template-columns: 1fr }
.sub-list th { display: none }
}
@media (prefers-color-scheme: dark) {
.f-ms { margin-left: 6px; font-size: 11px; color: var(--dim) }
.f-reason { display: block; margin-top: 2px; font-size: 12px; color: var(--danger, #c0392b); word-break: break-all }
.ls-pager { display: flex; align-items: center; justify-content: center; gap: 12px; padding: 12px 0 }
.ls-pginfo { font-size: 13px; color: var(--dim) }
.ls-progress { display: flex; align-items: center; gap: 12px; padding: 8px 14px; border-bottom: 1px solid var(--row-rule); font-size: 13px; color: var(--dim) }
.ls-track { flex: 1; height: 6px; border-radius: 3px; background: var(--pill-bg); overflow: hidden }
.ls-fill { height: 100%; width: 0; background: var(--accent); transition: width .3s }
.sw-hint { margin: 0 0 8px; font-size: 13px; color: var(--dim) }
.sw-list { list-style: none; margin: 8px 0; padding: 0; max-height: 52vh; overflow: auto; border: 1px solid var(--rule); border-radius: var(--radius) }
.sw-list li { display: flex; align-items: center; gap: 10px; padding: 9px 12px; border-bottom: 1px solid var(--row-rule); cursor: pointer }
.sw-list li:last-child { border-bottom: 0 }
.sw-list li:hover { background: var(--accent-soft) }
.sw-list li.empty { cursor: default; color: var(--dim); justify-content: center }
.sw-list .sw-t { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap }
.sw-list .sw-m { font-size: 12px; color: var(--dim); white-space: nowrap }
.sw-list .sw-bad { color: var(--danger, #c0392b) }
.sw-list .sw-best { color: var(--accent) }
@@ -0,0 +1,116 @@
<!DOCTYPE html>
<!-- Legado 书源管理页(moonsource_legadorule 经 web.routes 开放;外壳沿用订阅页;逻辑在 /legado_sources.js,接口 /api/legado_sources/*) -->
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>Legado 书源管理 - 远程管理</title>
<link rel="icon" href="/favicon.ico?v=2" sizes="16x16 32x32 48x48">
<link rel="apple-touch-icon" href="/apple-touch-icon.png?v=2">
<meta name="theme-color" content="#263a52">
<link rel="stylesheet" href="/style.css">
<link rel="stylesheet" href="/legado_sources.css">
<script>try{var t=localStorage.getItem('moon-theme');if(t==='light'||t==='dark')document.documentElement.setAttribute('data-theme',t);var l=localStorage.getItem('moon-lang');if(l&&!/^zh_CN/.test(l))document.documentElement.classList.add('i18n-wait')}catch(e){}</script>
</head>
<body class="file-page ls-page">
<header class="appbar"><div class="appbar-inner">
<a class="appbar-brand" href="/"><img src="/logo.jpg" alt="" width="28" height="28"><span>月读远程管理</span></a>
<nav class="appbar-nav" aria-label="页面导航"><a href="/"><svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor" aria-hidden="true"><path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/></svg><span>首页</span></a><a href="/file.html"><svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor" aria-hidden="true"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg><span>文件</span></a><a href="/input.html"><svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor" aria-hidden="true"><path d="M20 5H4c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm-9 3h2v2h-2V8zm0 3h2v2h-2v-2zM8 8h2v2H8V8zm0 3h2v2H8v-2zm-1 2H5v-2h2v2zm0-3H5V8h2v2zm9 7H8v-2h8v2zm0-4h-2v-2h2v2zm0-3h-2V8h2v2zm3 3h-2v-2h2v2zm0-3h-2V8h2v2z"/></svg><span>输入</span></a><a href="/clipboard.html"><svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor" aria-hidden="true"><path d="M19 3h-4.18C14.4 1.84 13.3 1 12 1S9.6 1.84 9.18 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm5 14H7v-2h10v2zm0-4H7v-2h10v2zm0-4H7V7h10v2z"/></svg><span>剪贴板</span></a><a href="/settings.html"><svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor" aria-hidden="true"><path d="M19.14 12.94c.04-.31.06-.63.06-.94s-.02-.63-.06-.94l2.03-1.58a.49.49 0 0 0 .12-.61l-1.92-3.32a.49.49 0 0 0-.59-.22l-2.39.96a7.03 7.03 0 0 0-1.62-.94l-.36-2.54a.48.48 0 0 0-.48-.41h-3.84a.47.47 0 0 0-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96a.48.48 0 0 0-.59.22L2.74 8.87a.47.47 0 0 0 .12.61l2.03 1.58c-.04.31-.06.63-.06.94s.02.63.06.94l-2.03 1.58a.49.49 0 0 0-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32a.48.48 0 0 0-.12-.61l-2.01-1.58zM12 15.6a3.6 3.6 0 1 1 0-7.2 3.6 3.6 0 0 1 0 7.2z"/></svg><span>配置</span></a><a href="/update.html"><svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor" aria-hidden="true"><path d="M5 20h14v-2H5v2zm0-10h4v6h6v-6h4l-7-7-7 7z"/></svg><span>更新</span></a></nav>
<button type="button" id="theme-toggle" class="icon-btn" aria-label="切换主题" title="主题:跟随系统"><svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor" aria-hidden="true"><path d="M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20zm0 18V4a8 8 0 0 1 0 16z"/></svg></button>
</div></header>
<main class="file-main">
<div class="tab-strip sub-strip">
<div class="file-action-toolbar sub-toolbar" role="toolbar" aria-label="书源操作">
<div class="fa-group fa-left">
<label class="sub-search"><span class="visually-hidden">搜索书源</span><input id="q" type="search" placeholder="搜索名称或地址" autocomplete="off"></label>
</div>
<div class="fa-group fa-right">
<button type="button" id="check-all" class="file-action">检查有效性</button>
<button type="button" id="switch" class="file-action">书架换源</button>
<button type="button" id="add" class="file-action primary">添加书源</button>
</div>
</div>
</div>
<div id="batch" class="sub-batch" role="toolbar" aria-label="批量操作" hidden>
<span id="batch-count" class="count-badge"></span>
<button type="button" id="b-check" class="file-action">检查所选</button>
<button type="button" id="b-on" class="file-action">启用</button>
<button type="button" id="b-off" class="file-action">禁用</button>
<button type="button" id="b-delete" class="file-action danger-text">删除</button>
<button type="button" id="b-clear" class="file-action">取消选择</button>
</div>
<div id="progress" class="ls-progress" role="status" hidden><span id="pr-text"></span><div class="ls-track" role="progressbar" aria-valuemin="0" aria-valuemax="100"><div id="pr-fill" class="ls-fill"></div></div></div>
<div class="explorer-shell">
<aside class="explorer-sidebar sub-sidebar" aria-label="状态">
<div class="sidebar-title">状态</div>
<div id="groups" class="quick-list sub-groups"></div>
<div class="sidebar-credit">月读 · Ankio · <a href="https://ankio.net" target="_blank" rel="noopener noreferrer">ankio.net</a></div>
</aside>
<section class="explorer-content" aria-labelledby="list-title">
<h1 id="list-title" class="visually-hidden">书源列表</h1>
<div class="table-wrap" id="listwrap">
<table class="sub-list">
<thead><tr><th class="sel"><input type="checkbox" id="pick-all" aria-label="全选"></th><th></th><th>书源</th><th>状态</th><th></th></tr></thead>
<tbody id="list"><tr><td class="empty" colspan="5">正在加载…</td></tr></tbody>
</table>
</div>
<div id="pager" class="ls-pager" hidden>
<button type="button" id="pg-prev" class="file-action">上一页</button>
<span id="pg-info" class="ls-pginfo"></span>
<button type="button" id="pg-next" class="file-action">下一页</button>
</div>
</section>
</div>
</main>
<div id="toasts" class="sub-toasts" aria-live="polite"></div>
<div id="ov" class="overlay" hidden>
<div id="dlg" class="dialog" role="dialog" aria-modal="true" aria-labelledby="dt">
<h2 id="dt"></h2>
<p id="dm"></p>
<div class="btns">
<button type="button" id="dc">取消</button>
<button type="button" id="dk" class="primary">确定</button>
</div>
</div>
</div>
<div id="add-dlg" class="overlay up-overlay" hidden>
<form id="add-form" class="dialog sub-dialog" role="dialog" aria-modal="true" aria-labelledby="ad-title">
<h2 id="ad-title">添加书源</h2>
<div id="ad-kinds" class="sub-kinds" role="radiogroup" aria-label="添加方式">
<label class="opt"><input type="radio" name="kind" value="once" checked><span><strong>在线地址</strong><small>单个 JSON、数组或合集,只下载一次</small></span></label>
<label class="opt"><input type="radio" name="kind" value="text"><span><strong>粘贴 JSON</strong><small>单个、数组或每行一个</small></span></label>
<label class="opt"><input type="radio" name="kind" value="file"><span><strong>本地文件</strong><small>.json / .jsonl / .txt</small></span></label>
</div>
<div class="field" id="ad-url-row"><label for="ad-url">地址</label><input id="ad-url" type="url" placeholder="https://" spellcheck="false"></div>
<div class="field" id="ad-text-row" hidden><label for="ad-text">书源 JSON</label><textarea id="ad-text" rows="8" spellcheck="false" placeholder="粘贴书源 JSON…"></textarea></div>
<div class="field" id="ad-file-row" hidden><label for="ad-file">文件</label><input id="ad-file" type="file" accept=".json,.jsonl,.txt,application/json"></div>
<div id="ad-state" class="state" role="status"></div>
<div class="btns">
<button type="button" id="ad-cancel">取消</button>
<button type="submit" id="ad-ok" class="primary">添加</button>
</div>
</form>
</div>
<div id="sw-dlg" class="overlay up-overlay" hidden>
<div class="dialog sub-dialog" role="dialog" aria-modal="true" aria-labelledby="sw-title">
<h2 id="sw-title">书架换源</h2>
<p id="sw-hint" class="sw-hint">书的进度和阅读时间不变,只改从哪个书源读取。来源已失效的书排在前面。</p>
<div id="sw-progress" class="ls-progress" role="status" hidden><span id="sw-text"></span><div class="ls-track"><div id="sw-fill" class="ls-fill"></div></div></div>
<ul id="sw-list" class="sw-list"></ul>
<div class="btns">
<button type="button" id="sw-back" hidden>返回书架</button>
<button type="button" id="sw-close">关闭</button>
</div>
</div>
</div>
<script src="/js.js"></script>
<script src="/legado_sources.js"></script>
</body>
</html>
@@ -0,0 +1,439 @@
/* Legado 书源管理:外壳与订阅页一致。状态侧栏(全部 / 已启用 / 已禁用)+ 书源分页列表 + 批量操作 + 添加对话框。接口 /api/legado_sources/*。 */
(function () {
var API = '/api/legado_sources/';
var SIZE = 50;
var ALL = 'all', ON = 'on', OFF = 'off';
var data = { sources: [], total: 0, counts: { all: 0, on: 0, off: 0 } };
var cur = ALL;
var page = 1;
var sel = {};
var searchTimer = null;
var busy = false;
function post(action, body) {
return jfetch(API + action, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body || {}),
});
}
/* 原文当请求体上传,不受 JSON 大小限制 */
function postRaw(action, text) {
return jfetch(API + action, {
method: 'POST',
headers: { 'Content-Type': 'application/octet-stream' },
body: text,
});
}
function errText(e) { return (e && e.message) || String(e); }
function mk(tag, cls, text) {
var n = document.createElement(tag);
if (cls) n.className = cls;
if (text != null) n.textContent = text;
return n;
}
function toast(text, kind) {
var n = mk('div', 'sub-toast' + (kind ? ' ' + kind : ''), text);
el('toasts').appendChild(n);
setTimeout(function () { n.remove(); }, kind === 'err' ? 6000 : 3000);
}
function fail(e) { toast(t('操作失败:%1', errText(e)), 'err'); }
/* 确认框:沿用月读网页的 overlay / dialog */
function confirmBox(title, msg, okText, danger, cancelText) {
return new Promise(function (resolve) {
var ov = el('ov');
el('dt').textContent = title;
el('dm').textContent = msg || '';
el('dk').textContent = okText || t('确定');
el('dc').textContent = cancelText || t('取消');
el('dk').className = danger ? 'danger' : 'primary';
function done(v) { ov.hidden = true; ov.className = 'overlay'; resolve(v); }
el('dc').onclick = function () { done(false); };
el('dk').onclick = function () { done(true); };
ov.hidden = false;
ov.className = 'overlay on';
});
}
/* 串行执行一个后台动作,期间不接受新的动作 */
function run(job, okText) {
if (busy) return Promise.resolve();
busy = true;
return job().then(function (r) {
toast(okText || describe(r));
return load();
}).catch(fail).then(function () { busy = false; });
}
/* 书源按页从服务端取,搜索与状态筛选也在服务端做 */
function load() {
var qs = 'page=' + page + '&size=' + SIZE + '&status=' + (cur === ALL ? '' : cur) +
'&q=' + encodeURIComponent(el('q').value.trim());
return jfetch(API + 'list?' + qs, { cache: 'no-store' }).then(function (d) {
/* 空 Lua 表编码成 {} 而不是 [],统一成数组 */
d.sources = Array.isArray(d.sources) ? d.sources : [];
data = d;
var pages = Math.max(1, Math.ceil(d.total / SIZE));
if (page > pages) { page = pages; return load(); }
render();
}).catch(function (e) {
el('list').textContent = '';
var tr = mk('tr'), td = mk('td', 'empty', t('读取失败:%1', errText(e)));
td.colSpan = 5;
tr.appendChild(td);
el('list').appendChild(tr);
});
}
function describe(r) {
if (!r || r.total == null) return t('完成');
var s = r.added != null ? t('共 %1 个书源,新增 %2 个', r.total, r.added) : t('共 %1 个书源', r.total);
if (r.skipped) s += t(',跳过无效项 %1 个', r.skipped);
if (r.disabled) s += t(',%1 个需要 JS/WebView 已禁用', r.disabled);
return s;
}
// ── 状态侧栏 ──
function groupButton(key, name, count) {
var b = mk('button');
b.type = 'button';
if (key === ALL) b.setAttribute('data-all', '');
b.className = cur === key ? 'active' : '';
b.appendChild(mk('span', 'g-name', name));
b.appendChild(mk('span', 'g-count', String(count)));
b.onclick = function () { cur = key; page = 1; sel = {}; load(); };
return b;
}
function renderGroups() {
var box = el('groups');
box.textContent = '';
box.appendChild(groupButton(ALL, t('全部书源'), data.counts.all));
box.appendChild(groupButton(ON, t('已启用'), data.counts.on));
box.appendChild(groupButton(OFF, t('已禁用'), data.counts.off));
}
// ── 列表 ──
function row(s) {
var tr = mk('tr', (s.enabled ? '' : 'off') + (sel[s.key] ? ' selected' : ''));
var tdSel = mk('td', 'sel'), cb = mk('input');
cb.type = 'checkbox';
cb.checked = !!sel[s.key];
cb.setAttribute('aria-label', t('选择 %1', s.name));
cb.onchange = function () {
if (cb.checked) sel[s.key] = true; else delete sel[s.key];
tr.className = (s.enabled ? '' : 'off') + (cb.checked ? ' selected' : '');
renderBatch();
};
tdSel.appendChild(cb);
tr.appendChild(tdSel);
var tdIco = mk('td', 'ico'), ico = mk('span', 'sub-icon', (s.name || '?').charAt(0).toUpperCase());
ico.setAttribute('translate', 'no');
tdIco.appendChild(ico);
tr.appendChild(tdIco);
var tdN = mk('td', 'n');
var title = mk('span', 'f-title', s.name);
title.setAttribute('translate', 'no');
var url = mk('span', 'f-url', s.url);
url.setAttribute('translate', 'no');
tdN.appendChild(title);
tdN.appendChild(url);
if (s.reason) tdN.appendChild(mk('span', 'f-reason', t('原因:%1', s.reason)));
tr.appendChild(tdN);
var tdK = mk('td', 'meta');
tdK.appendChild(mk('span', 'sub-badge' + (s.enabled ? ' on' : ''), s.enabled ? t('已启用') : t('已禁用')));
if (s.ms != null) tdK.appendChild(mk('span', 'f-ms', ' ' + (s.ms >= 1000 ? (s.ms / 1000).toFixed(1) + ' s' : s.ms + ' ms')));
tr.appendChild(tdK);
var ops = mk('td', 'ops');
var bTog = mk('button', 'btn-outline', s.enabled ? t('禁用') : t('启用'));
bTog.type = 'button';
bTog.onclick = function () {
run(function () { return post('enable', { keys: [s.key], enabled: !s.enabled }); }, t('完成'));
};
var bDel = mk('button', 'btn-outline danger-text', t('删除'));
bDel.type = 'button';
bDel.onclick = function () { removeKeys([s.key]); };
ops.appendChild(bTog);
ops.appendChild(bDel);
tr.appendChild(ops);
return tr;
}
function renderList() {
var body = el('list');
body.textContent = '';
if (!data.sources.length) {
var tr = mk('tr'), td = mk('td', 'empty', data.counts.all ? t('没有符合条件的书源') : t('还没有书源,点右上角「添加书源」'));
td.colSpan = 5;
tr.appendChild(td);
body.appendChild(tr);
}
data.sources.forEach(function (s) { body.appendChild(row(s)); });
el('pick-all').checked = data.sources.length > 0 && data.sources.every(function (s) { return sel[s.key]; });
renderPager();
renderBatch();
}
function renderPager() {
var pages = Math.max(1, Math.ceil(data.total / SIZE));
var box = el('pager');
box.hidden = data.total <= SIZE;
el('pg-info').textContent = t('第 %1 / %2 页,共 %3 个', page, pages, data.total);
el('pg-prev').disabled = page <= 1;
el('pg-next').disabled = page >= pages;
}
function selectedKeys() { return Object.keys(sel); }
function renderBatch() {
var n = selectedKeys().length;
el('batch').hidden = !n;
el('batch-count').textContent = t('已选 %1 项', n);
}
function render() {
renderGroups();
renderList();
}
function removeKeys(keys) {
confirmBox(t('删除书源?'), t('将删除 %1 个书源。', keys.length), t('删除'), true).then(function (ok) {
if (!ok) return;
run(function () { return post('delete', { keys: keys }); }, t('已删除'));
});
}
// ── 添加对话框 ──
function kindValue() {
var r = document.querySelector('#ad-kinds input:checked');
return r ? r.value : 'once';
}
function syncKind() {
var k = kindValue();
el('ad-url-row').hidden = k !== 'once';
el('ad-text-row').hidden = k !== 'text';
el('ad-file-row').hidden = k !== 'file';
}
function openAdd() {
el('ad-url').value = '';
el('ad-text').value = '';
el('ad-file').value = '';
setState(el('ad-state'), '');
syncKind();
var ov = el('add-dlg');
ov.hidden = false;
ov.className = 'overlay up-overlay on';
el('ad-url').focus();
}
function closeAdd() {
var ov = el('add-dlg');
ov.hidden = true;
ov.className = 'overlay up-overlay';
}
function submitAdd(e) {
e.preventDefault();
if (busy) return;
var k = kindValue(), job;
if (k === 'once') {
var url = el('ad-url').value.trim();
if (!url) { setState(el('ad-state'), t('请先填写书源地址'), 'err'); return; }
job = function () { return post('import_url', { url: url }); };
} else if (k === 'text') {
var text = el('ad-text').value.trim();
if (!text) { setState(el('ad-state'), t('请先粘贴书源 JSON'), 'err'); return; }
job = function () { return postRaw('import', text); };
} else {
var f = el('ad-file').files[0];
if (!f) { setState(el('ad-state'), t('请先选择文件'), 'err'); return; }
job = function () { return f.text().then(function (x) { return postRaw('import', x); }); };
}
busy = true;
el('ad-ok').disabled = true;
setState(el('ad-state'), t('正在处理…'));
job().then(function (r) {
closeAdd();
toast(describe(r));
return load();
}).catch(function (err) {
setState(el('ad-state'), errText(err), 'err');
return load();
}).then(function () {
busy = false;
el('ad-ok').disabled = false;
});
}
// ── 有效性检查:后台逐个试搜索,打不开或搜不到书的直接禁用 ──
var polling = false;
function showProgress(text, done, total) {
el('progress').hidden = !text;
el('pr-text').textContent = text || '';
el('pr-fill').style.width = (total ? Math.round(done * 100 / total) : 0) + '%';
}
function pollCheck() {
if (polling) return;
polling = true;
(function tick() {
jfetch(API + 'check_status', { cache: 'no-store' }).then(function (r) {
if (r.running) {
showProgress(t('正在检查书源 %1 / %2,已禁用 %3 个…', r.done, r.total, r.disabled), r.done, r.total);
setTimeout(tick, 1500);
return;
}
polling = false;
showProgress('');
if (r.total) toast(t('检查完成:共 %1 个,禁用了 %2 个无效书源', r.total, r.disabled));
return load();
}).catch(function (e) { polling = false; showProgress(''); fail(e); });
})();
}
function startCheck(keys) {
if (!data.counts.all) { toast(t('还没有书源')); return; }
post('check', { keys: keys }).then(function (r) {
if (!r.started) toast(t('检查已在进行中'));
pollCheck();
}).catch(fail);
}
// ── 书架换源:选书 → 后台在其他书源里搜同名书 → 选一个改读 ──
var sw = { book: null, timer: null };
function swList(rows, empty) {
var ul = el('sw-list');
ul.textContent = '';
if (!rows.length) ul.appendChild(mk('li', 'empty', empty));
return ul;
}
function swProgress(text, done, total) {
el('sw-progress').hidden = !text;
el('sw-text').textContent = text || '';
el('sw-fill').style.width = (total ? Math.round(done * 100 / total) : 0) + '%';
}
function swClose() {
clearTimeout(sw.timer);
sw.book = null;
var ov = el('sw-dlg');
ov.hidden = true;
ov.className = 'overlay up-overlay';
}
function swShelf() {
clearTimeout(sw.timer);
sw.book = null;
el('sw-back').hidden = true;
el('sw-title').textContent = t('书架换源');
swProgress('');
jfetch(API + 'switch_books', { cache: 'no-store' }).then(function (d) {
var books = Array.isArray(d.books) ? d.books : [];
var ul = swList(books, t('书架里还没有这个书源的书'));
books.forEach(function (b) {
var li = mk('li');
var title = mk('span', 'sw-t' + (b.broken ? ' sw-bad' : ''), (b.broken ? '✗ ' : '') + b.title);
title.setAttribute('translate', 'no');
li.appendChild(title);
var meta = (b.authors ? b.authors + ' · ' : '') + (b.source_name || '') + (b.switched ? t(' · 已换源') : '');
li.appendChild(mk('span', 'sw-m', meta));
li.onclick = function () { swSearch(b); };
ul.appendChild(li);
});
}).catch(fail);
}
function swResults(r) {
var rows = Array.isArray(r.results) ? r.results : [];
var ul = swList(rows, r.running ? t('正在搜索…') : t('其他书源里没有找到这本书'));
rows.forEach(function (row) {
var li = mk('li');
var title = mk('span', 'sw-t' + (row.score > 0 ? ' sw-best' : ''), row.title);
title.setAttribute('translate', 'no');
li.appendChild(title);
li.appendChild(mk('span', 'sw-m', (row.authors ? row.authors + ' · ' : '') + row.source_name));
li.onclick = function () { swApply(row); };
ul.appendChild(li);
});
}
function swPoll() {
clearTimeout(sw.timer);
jfetch(API + 'switch_status', { cache: 'no-store' }).then(function (r) {
if (!sw.book) return;
swResults(r);
if (r.running) {
swProgress(t('正在 %1 个书源里搜索《%2》… %3', r.total, r.title, r.done + ' / ' + r.total), r.done, r.total);
sw.timer = setTimeout(swPoll, 1000);
} else {
swProgress('');
}
}).catch(fail);
}
function swSearch(b) {
sw.book = b;
el('sw-back').hidden = false;
el('sw-title').textContent = t('换源:%1', b.title);
swList([], t('正在搜索…'));
post('switch_search', { stable_id: b.stable_id, title: b.title, authors: b.authors }).then(function (r) {
if (!r.started) toast(t('已有搜索在后台进行'));
swPoll();
}).catch(fail);
}
function swApply(row) {
if (!sw.book) return;
var b = sw.book;
confirmBox(t('换源'), t('《%1》改从「%2」读取?进度和阅读时间不变,目录会重新获取。', b.title, row.source_name), t('确定')).then(function (ok) {
if (!ok) return;
post('switch_cancel', {}).then(function () {
return post('switch_apply', { stable_id: b.stable_id, target: row.stable_id });
}).then(function () {
toast(t('已换到 %1', row.source_name));
swShelf();
}).catch(fail);
});
}
function openSwitch() {
var ov = el('sw-dlg');
ov.hidden = false;
ov.className = 'overlay up-overlay on';
/* 后台还有搜索在跑(上次没等完就关了)时直接接上 */
jfetch(API + 'switch_status', { cache: 'no-store' }).then(function (r) {
if (r.running && r.stable_id) {
sw.book = { stable_id: r.stable_id, title: r.title, authors: '' };
el('sw-back').hidden = false;
el('sw-title').textContent = t('换源:%1', r.title);
swPoll();
} else {
swShelf();
}
}).catch(fail);
}
function boot() {
el('switch').onclick = openSwitch;
el('sw-close').onclick = swClose;
el('sw-back').onclick = function () { post('switch_cancel', {}).then(swShelf, swShelf); };
el('sw-dlg').onclick = function (e) { if (e.target === el('sw-dlg')) swClose(); };
el('add').onclick = openAdd;
el('ad-cancel').onclick = closeAdd;
el('add-dlg').onclick = function (e) { if (e.target === el('add-dlg')) closeAdd(); };
el('add-form').onsubmit = submitAdd;
Array.prototype.forEach.call(document.querySelectorAll('#ad-kinds input'), function (r) { r.onchange = syncKind; });
el('check-all').onclick = function () { startCheck([]); };
el('b-check').onclick = function () { startCheck(selectedKeys()); };
el('b-on').onclick = function () {
run(function () { return post('enable', { keys: selectedKeys(), enabled: true }); }, t('完成'));
};
el('b-off').onclick = function () {
run(function () { return post('enable', { keys: selectedKeys(), enabled: false }); }, t('完成'));
};
el('b-delete').onclick = function () { removeKeys(selectedKeys()); };
el('b-clear').onclick = function () { sel = {}; renderList(); };
el('q').oninput = function () {
clearTimeout(searchTimer);
searchTimer = setTimeout(function () { page = 1; load(); }, 300);
};
el('pg-prev').onclick = function () { page--; load(); };
el('pg-next').onclick = function () { page++; load(); };
el('pick-all').onchange = function () {
var on = el('pick-all').checked;
data.sources.forEach(function (s) { if (on) sel[s.key] = true; else delete sel[s.key]; });
renderList();
};
load().then(pollCheck);
}
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot); else boot();
})();
+176
View File
@@ -0,0 +1,176 @@
--[[--
moonsource_legadorule.remote 离线用例:导入三种格式、在线单次导入、导入即禁用不支持的书源、有效性检查、启停删除,设置与 http 走桩。
@module tests.legadorule.remote_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, redundant-parameter, missing-parameter, inject-field, assign-type-mismatch, param-type-mismatch
local Assert = require("support.assert")
package.preload["utils.awake"] = function() return { poke = function() end } end
package.preload["utils.charset"] = function() return { toUtf8 = function(b) return b end } end
local pages = {}
package.preload["http.request"] = function()
return {
header = function() return nil end,
get = function(url, _o, cb)
if pages[url] then cb(pages[url], nil, { code = 200 }) else cb(nil, "HTTP 404", { code = 404 }) end
return { cancel = function() end }
end,
}
end
local Remote = require("moonsource_legadorule.remote")
local function call(method, action, params)
local status, body
Remote.handle(method, action, params or {}, function(s, b) status, body = s, b end)
return status, body
end
local function tmp(text)
local path = os.tmpname()
local f = io.open(path, "wb")
f:write(text)
f:close()
return path
end
-- 测试沙箱的库跨次运行保留:先清空
do
local _, r = call("GET", "list")
local keys = {}
for _idx, src in ipairs(r.sources) do keys[#keys + 1] = src.key end
call("POST", "delete", { keys = keys })
end
local one = '{"bookSourceUrl":"http://a.com","bookSourceName":"A"}'
local lines = '{"bookSourceUrl":"http://b.com","bookSourceName":"B"}\n{"bookSourceUrl":"http://c.com","bookSourceName":"C"}\n'
local array = '[{"bookSourceUrl":"http://d.com"},{"bookSourceUrl":"http://e.com"},{"x":1}]'
do
local s, r = call("POST", "import", { temp = tmp(one) })
Assert.eq(s, 200); Assert.eq(r.added, 1)
s, r = call("POST", "import", { temp = tmp(lines) })
Assert.eq(r.total, 2)
s, r = call("POST", "import", { temp = tmp(array) })
Assert.eq(r.total, 2); Assert.eq(r.skipped, 1)
s, r = call("POST", "import", { temp = tmp("hello") })
Assert.eq(s, 422)
s, r = call("GET", "list")
Assert.len(r.sources, 5)
end
do
pages["http://x.com/all.json"] = lines
local s, r = call("POST", "import_url", { url = "http://x.com/all.json" })
Assert.eq(s, 200); Assert.eq(r.total, 2)
s = call("POST", "import_url", { url = "http://x.com/missing.json" })
Assert.eq(s, 502)
end
do
-- 含 JS 的书源导入即禁用并记原因
local js = '{"bookSourceUrl":"http://js.com","searchUrl":"@js:java.get(1)"}'
local s, r = call("POST", "import", { temp = tmp(js) })
Assert.eq(r.disabled, 1)
local _, l = call("GET", "list")
local found
for _idx, src in ipairs(l.sources) do if src.url == "http://js.com" then found = src end end
Assert.is_false(found.enabled)
Assert.not_nil(found.reason)
-- 手动启用后原因清除
call("POST", "enable", { keys = { found.key }, enabled = true })
_, l = call("GET", "list")
for _idx, src in ipairs(l.sources) do if src.url == "http://js.com" then Assert.is_nil(src.reason) end end
call("POST", "delete", { keys = { found.key } })
end
do
-- 检查:有效的保持启用并记响应时间;搜不了的禁用并记原因
pages["http://v.com/s?q=%E6%88%91%E7%9A%84"] = '{"list":[{"n":"书","u":"/b/1"}]}'
pages["http://v.com/b/1"] = '{"ch":[{"t":"第一章","u":"/c/1"}]}'
pages["http://v.com/c/1"] = '{"text":"正文内容"}'
local good = '{"bookSourceUrl":"http://v.com","searchUrl":"http://v.com/s?q={{key}}","ruleSearch":{"bookList":"$.list","name":"$.n","bookUrl":"$.u"},"ruleToc":{"chapterList":"$.ch","chapterName":"$.t","chapterUrl":"$.u"},"ruleContent":{"content":"$.text"}}'
call("POST", "import", { temp = tmp(good) })
-- 搜索能用但正文坏了的书源也要禁用
pages["http://w.com/s?q=%E6%88%91%E7%9A%84"] = '{"list":[{"n":"书","u":"/b/1"}]}'
pages["http://w.com/b/1"] = '{"ch":[{"t":"第一章","u":"/c/1"}]}'
call("POST", "import", { temp = tmp((good:gsub("v%.com", "w.com"))) })
local s, r = call("POST", "check", {})
Assert.eq(s, 200); Assert.is_true(r.started)
local _, st = call("GET", "check_status")
Assert.is_false(st.running)
Assert.eq(st.total, 7)
Assert.eq(st.disabled, 6)
local _, l = call("GET", "list")
for _idx, src in ipairs(l.sources) do
Assert.not_nil(src.ms)
if src.url == "http://v.com" then
Assert.is_true(src.enabled, tostring(src.reason)); Assert.is_nil(src.reason)
else
Assert.is_false(src.enabled); Assert.not_nil(src.reason)
end
end
end
do
-- 书架换源:后台在其他启用书源里搜同名书,选定后只改映射
pages["http://v.com/s?q=%E4%B9%A6"] = '{"list":[{"n":"书","u":"/b/7"}]}'
local Sources = require("moonsource_legadorule.sources")
local Mapper = require("moonsource_legadorule.mapper")
local wkey = Sources.key("http://w.com")
local oldId = Mapper.stableId(wkey, "http://w.com/b/1")
local s, r = call("POST", "switch_search", { stable_id = oldId, title = "书", authors = "" })
Assert.eq(s, 200); Assert.is_true(r.started)
local _, st = call("GET", "switch_status")
Assert.is_false(st.running)
Assert.eq(st.total, 1); Assert.eq(st.done, 1)
Assert.eq(#st.results, 1)
Assert.eq(st.results[1].title, "书")
Assert.eq(st.results[1].score, 1)
local s2 = call("POST", "switch_apply", { stable_id = oldId, target = st.results[1].stable_id })
Assert.eq(s2, 200)
local key, url = Sources.alias(oldId)
Assert.eq(key, Sources.key("http://v.com")); Assert.eq(url, "http://v.com/b/7")
Assert.eq(call("POST", "switch_apply", { stable_id = oldId, target = "bad" }), 422)
end
do
local _, r = call("GET", "list")
local key = r.sources[1].key
call("POST", "enable", { keys = { key }, enabled = false })
_, r = call("GET", "list")
Assert.is_false(r.sources[1].enabled)
local s, d = call("POST", "delete", { keys = { key } })
Assert.eq(d.removed, 1)
end
do
-- 分页、搜索与状态筛选在服务端
local _, r = call("GET", "list", { page = "1", size = "2" })
Assert.len(r.sources, 2)
Assert.eq(r.total, r.counts.all)
local second
_, second = call("GET", "list", { page = "2", size = "2" })
Assert.len(second.sources, 2)
Assert.is_true(second.sources[1].key ~= r.sources[1].key)
_, r = call("GET", "list", { q = "V.COM" })
Assert.eq(r.total, 1)
_, r = call("GET", "list", { status = "on" })
Assert.eq(r.total, r.counts.on)
end
do
-- 换源映射:身份不变,读取指向新书源
local Sources = require("moonsource_legadorule.sources")
require("utils.db").exec("DELETE FROM legadorule_alias;")
Assert.is_nil(Sources.alias("old|http://x/1"))
Sources.setAlias("old|http://x/1", "abcd1234", "http://y/9")
local key, url = Sources.alias("old|http://x/1")
Assert.eq(key, "abcd1234"); Assert.eq(url, "http://y/9")
Sources.setAlias("old|http://x/1", "ffff0000", "http://z/1")
Assert.eq((Sources.alias("old|http://x/1")), "ffff0000")
end
print(" ok")